From 6186a6e2597d4ef3bb67bbac48876accaf0e5a6d Mon Sep 17 00:00:00 2001 From: Robbin Janssen Date: Fri, 4 Mar 2022 13:43:36 +0000 Subject: [PATCH 01/13] Add category.collapse option --- README.md | 9 +++++++++ lib/releases.js | 28 +++++++++++++++++++++++----- lib/schema.js | 1 + 3 files changed, 33 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index d21e83809..6a0615ed1 100644 --- a/README.md +++ b/README.md @@ -249,6 +249,15 @@ Pull requests with the label "feature" or "fix" will now be grouped together: Adding such labels to your PRs can be automated by using the embedded Autolabeler functionality (see below), [PR Labeler](https://github.com/TimonVS/pr-labeler-action) or [Probot Auto Labeler](https://github.com/probot/autolabeler). +Optionally you can add a `collapse` boolean to your category item, if the category has more than 3 pull requests then it will show all pull requests collapsed for that category. Append the `collapse` boolean to your category as following: + +```yml +categories: + - title: '⬆️ Dependencies' + label: 'dependencies' + collapse: true +``` + ## Exclude Pull Requests With the `exclude-labels` option you can exclude pull requests from the release notes using labels. For example, append the following to your `.github/release-drafter.yml` file: diff --git a/lib/releases.js b/lib/releases.js index 2881311cc..39f81aba2 100644 --- a/lib/releases.js +++ b/lib/releases.js @@ -238,15 +238,33 @@ const generateChangeLog = (mergedPullRequests, config) => { } categorizedPullRequests.map((category, index) => { - if (category.pullRequests.length > 0) { + if (category.pullRequests.length === 0) { + return category + } + + const categoryTitle = template(config['category-template'], { + $TITLE: category.title, + }) + const pullRequestString = pullRequestToString(category.pullRequests) + + if ( + !category.collapse || + (category.collapse && category.pullRequests.length < 4) + ) { + changeLog.push(categoryTitle, '\n\n', pullRequestString) + } else { changeLog.push( - template(config['category-template'], { $TITLE: category.title }), + categoryTitle, + '
', + '\n', + `${category.pullRequests.length} changes`, '\n\n', - pullRequestToString(category.pullRequests) + pullRequestString, + '
' ) - - if (index + 1 !== categorizedPullRequests.length) changeLog.push('\n\n') } + + if (index + 1 !== categorizedPullRequests.length) changeLog.push('\n\n') }) return changeLog.join('').trim() diff --git a/lib/schema.js b/lib/schema.js index 521ba1b1a..3da260282 100644 --- a/lib/schema.js +++ b/lib/schema.js @@ -111,6 +111,7 @@ const schema = (context) => { Joi.object() .keys({ title: Joi.string().required(), + collapse: Joi.boolean().default(false), label: Joi.string(), labels: Joi.array().items(Joi.string()).single().default([]), }) From 00416c53bed61dfdaf8b0903744c4b0e5cbef33e Mon Sep 17 00:00:00 2001 From: Robbin Janssen Date: Fri, 4 Mar 2022 13:48:08 +0000 Subject: [PATCH 02/13] Update build files --- dist/index.js | 21045 ++++++++++++++++++++++++------------------------ schema.json | 4 + 2 files changed, 10558 insertions(+), 10491 deletions(-) diff --git a/dist/index.js b/dist/index.js index 6e5a773ba..36ea21fe7 100644 --- a/dist/index.js +++ b/dist/index.js @@ -31859,5008 +31859,3877 @@ module['exports'] = colors; /***/ }), -/***/ 61904: -/***/ ((module, exports, __nccwpck_require__) => { +/***/ 89296: +/***/ (function(module) { -/** - * Module dependencies. - */ +/* global define */ +(function (root, factory) { + /* istanbul ignore next */ + if (typeof define === 'function' && define.amd) { + define([], factory); + } else if (true) { + module.exports = factory(); + } else {} +})(this, function () { + var semver = + /^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i; -const EventEmitter = (__nccwpck_require__(82361).EventEmitter); -const spawn = (__nccwpck_require__(32081).spawn); -const path = __nccwpck_require__(71017); -const fs = __nccwpck_require__(57147); + function indexOrEnd(str, q) { + return str.indexOf(q) === -1 ? str.length : str.indexOf(q); + } -// @ts-check + function split(v) { + var c = v.replace(/^v/, '').replace(/\+.*$/, ''); + var patchIndex = indexOrEnd(c, '-'); + var arr = c.substring(0, patchIndex).split('.'); + arr.push(c.substring(patchIndex + 1)); + return arr; + } -class Option { - /** - * Initialize a new `Option` with the given `flags` and `description`. - * - * @param {string} flags - * @param {string} description - * @api public - */ + function tryParse(v) { + var n = parseInt(v, 10); + return isNaN(n) ? v : n; + } - constructor(flags, description) { - this.flags = flags; - this.required = flags.includes('<'); // A value must be supplied when the option is specified. - this.optional = flags.includes('['); // A value is optional when the option is specified. - // variadic test ignores et al which might be used to describe custom splitting of single argument - this.variadic = /\w\.\.\.[>\]]$/.test(flags); // The option can take multiple values. - this.mandatory = false; // The option must have a value after parsing, which usually means it must be specified on command line. - const optionFlags = _parseOptionFlags(flags); - this.short = optionFlags.shortFlag; - this.long = optionFlags.longFlag; - this.negate = false; - if (this.long) { - this.negate = this.long.startsWith('--no-'); + function validateAndParse(v) { + if (typeof v !== 'string') { + throw new TypeError('Invalid argument expected string'); } - this.description = description || ''; - this.defaultValue = undefined; + var match = v.match(semver); + if (!match) { + throw new Error( + "Invalid argument not valid semver ('" + v + "' received)" + ); + } + match.shift(); + return match; } - /** - * Return option name. - * - * @return {string} - * @api private - */ + function forceType(a, b) { + return typeof a !== typeof b ? [String(a), String(b)] : [a, b]; + } - name() { - if (this.long) { - return this.long.replace(/^--/, ''); + function compareStrings(a, b) { + var [ap, bp] = forceType(tryParse(a), tryParse(b)); + if (ap > bp) return 1; + if (ap < bp) return -1; + return 0; + } + + function compareSegments(a, b) { + for (var i = 0; i < Math.max(a.length, b.length); i++) { + var r = compareStrings(a[i] || 0, b[i] || 0); + if (r !== 0) return r; } - return this.short.replace(/^-/, ''); - }; + return 0; + } - /** - * Return option name, in a camelcase format that can be used - * as a object attribute key. - * - * @return {string} - * @api private - */ + function compareVersions(v1, v2) { + [v1, v2].forEach(validateAndParse); - attributeName() { - return camelcase(this.name().replace(/^no-/, '')); - }; + var s1 = split(v1); + var s2 = split(v2); - /** - * Check if `arg` matches the short or long flag. - * - * @param {string} arg - * @return {boolean} - * @api private - */ + for (var i = 0; i < Math.max(s1.length - 1, s2.length - 1); i++) { + var n1 = parseInt(s1[i] || 0, 10); + var n2 = parseInt(s2[i] || 0, 10); - is(arg) { - return this.short === arg || this.long === arg; - }; -} + if (n1 > n2) return 1; + if (n2 > n1) return -1; + } -/** - * CommanderError class - * @class - */ -class CommanderError extends Error { - /** - * Constructs the CommanderError class - * @param {number} exitCode suggested exit code which could be used with process.exit - * @param {string} code an id string representing the error - * @param {string} message human-readable description of the error - * @constructor - */ - constructor(exitCode, code, message) { - super(message); - // properly capture stack trace in Node.js - Error.captureStackTrace(this, this.constructor); - this.name = this.constructor.name; - this.code = code; - this.exitCode = exitCode; - this.nestedError = undefined; - } -} + var sp1 = s1[s1.length - 1]; + var sp2 = s2[s2.length - 1]; -class Command extends EventEmitter { - /** - * Initialize a new `Command`. - * - * @param {string} [name] - * @api public - */ + if (sp1 && sp2) { + var p1 = sp1.split('.').map(tryParse); + var p2 = sp2.split('.').map(tryParse); - constructor(name) { - super(); - this.commands = []; - this.options = []; - this.parent = null; - this._allowUnknownOption = false; - this._args = []; - this.rawArgs = null; - this._scriptPath = null; - this._name = name || ''; - this._optionValues = {}; - this._storeOptionsAsProperties = true; // backwards compatible by default - this._storeOptionsAsPropertiesCalled = false; - this._passCommandToAction = true; // backwards compatible by default - this._actionResults = []; - this._actionHandler = null; - this._executableHandler = false; - this._executableFile = null; // custom name for executable - this._defaultCommandName = null; - this._exitCallback = null; - this._aliases = []; - this._combineFlagAndOptionalValue = true; + for (i = 0; i < Math.max(p1.length, p2.length); i++) { + if ( + p1[i] === undefined || + (typeof p2[i] === 'string' && typeof p1[i] === 'number') + ) + return -1; + if ( + p2[i] === undefined || + (typeof p1[i] === 'string' && typeof p2[i] === 'number') + ) + return 1; - this._hidden = false; - this._hasHelpOption = true; - this._helpFlags = '-h, --help'; - this._helpDescription = 'display help for command'; - this._helpShortFlag = '-h'; - this._helpLongFlag = '--help'; - this._hasImplicitHelpCommand = undefined; // Deliberately undefined, not decided whether true or false - this._helpCommandName = 'help'; - this._helpCommandnameAndArgs = 'help [command]'; - this._helpCommandDescription = 'display help for command'; + if (p1[i] > p2[i]) return 1; + if (p2[i] > p1[i]) return -1; + } + } else if (sp1 || sp2) { + return sp1 ? -1 : 1; + } + + return 0; } - /** - * Define a command. - * - * There are two styles of command: pay attention to where to put the description. - * - * Examples: - * - * // Command implemented using action handler (description is supplied separately to `.command`) - * program - * .command('clone [destination]') - * .description('clone a repository into a newly created directory') - * .action((source, destination) => { - * console.log('clone command called'); - * }); - * - * // Command implemented using separate executable file (description is second parameter to `.command`) - * program - * .command('start ', 'start named service') - * .command('stop [service]', 'stop named service, or all if no name supplied'); - * - * @param {string} nameAndArgs - command name and arguments, args are `` or `[optional]` and last may also be `variadic...` - * @param {Object|string} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable) - * @param {Object} [execOpts] - configuration options (for executable) - * @return {Command} returns new command for action handler, or `this` for executable command - * @api public - */ + var allowedOperators = ['>', '>=', '=', '<', '<=']; - command(nameAndArgs, actionOptsOrExecDesc, execOpts) { - let desc = actionOptsOrExecDesc; - let opts = execOpts; - if (typeof desc === 'object' && desc !== null) { - opts = desc; - desc = null; - } - opts = opts || {}; - const args = nameAndArgs.split(/ +/); - const cmd = this.createCommand(args.shift()); + var operatorResMap = { + '>': [1], + '>=': [0, 1], + '=': [0], + '<=': [-1, 0], + '<': [-1], + }; - if (desc) { - cmd.description(desc); - cmd._executableHandler = true; + function validateOperator(op) { + if (typeof op !== 'string') { + throw new TypeError( + 'Invalid operator type, expected string but got ' + typeof op + ); } - if (opts.isDefault) this._defaultCommandName = cmd._name; - - cmd._hidden = !!(opts.noHelp || opts.hidden); - cmd._hasHelpOption = this._hasHelpOption; - cmd._helpFlags = this._helpFlags; - cmd._helpDescription = this._helpDescription; - cmd._helpShortFlag = this._helpShortFlag; - cmd._helpLongFlag = this._helpLongFlag; - cmd._helpCommandName = this._helpCommandName; - cmd._helpCommandnameAndArgs = this._helpCommandnameAndArgs; - cmd._helpCommandDescription = this._helpCommandDescription; - cmd._exitCallback = this._exitCallback; - cmd._storeOptionsAsProperties = this._storeOptionsAsProperties; - cmd._passCommandToAction = this._passCommandToAction; - cmd._combineFlagAndOptionalValue = this._combineFlagAndOptionalValue; - - cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor - this.commands.push(cmd); - cmd._parseExpectedArgs(args); - cmd.parent = this; + if (allowedOperators.indexOf(op) === -1) { + throw new TypeError( + 'Invalid operator, expected one of ' + allowedOperators.join('|') + ); + } + } - if (desc) return this; - return cmd; + compareVersions.validate = function (version) { + return typeof version === 'string' && semver.test(version); }; - /** - * Factory routine to create a new unattached command. - * - * See .command() for creating an attached subcommand, which uses this routine to - * create the command. You can override createCommand to customise subcommands. - * - * @param {string} [name] - * @return {Command} new command - * @api public - */ + compareVersions.compare = function (v1, v2, operator) { + // Validate operator + validateOperator(operator); - createCommand(name) { - return new Command(name); + // since result of compareVersions can only be -1 or 0 or 1 + // a simple map can be used to replace switch + var res = compareVersions(v1, v2); + return operatorResMap[operator].indexOf(res) > -1; }; - /** - * Add a prepared subcommand. - * - * See .command() for creating an attached subcommand which inherits settings from its parent. - * - * @param {Command} cmd - new subcommand - * @param {Object} [opts] - configuration options - * @return {Command} `this` command for chaining - * @api public - */ + compareVersions.satisfies = function (v, r) { + // if no range operator then "=" + var match = r.match(/^([<>=~^]+)/); + var op = match ? match[1] : '='; - addCommand(cmd, opts) { - if (!cmd._name) throw new Error('Command passed to .addCommand() must have a name'); + // if gt/lt/eq then operator compare + if (op !== '^' && op !== '~') return compareVersions.compare(v, r, op); - // To keep things simple, block automatic name generation for deeply nested executables. - // Fail fast and detect when adding rather than later when parsing. - function checkExplicitNames(commandArray) { - commandArray.forEach((cmd) => { - if (cmd._executableHandler && !cmd._executableFile) { - throw new Error(`Must specify executableFile for deeply nested executable: ${cmd.name()}`); - } - checkExplicitNames(cmd.commands); - }); + // else range of either "~" or "^" is assumed + var [v1, v2, v3] = validateAndParse(v); + var [m1, m2, m3] = validateAndParse(r); + if (compareStrings(v1, m1) !== 0) return false; + if (op === '^') { + return compareSegments([v2, v3], [m2, m3]) >= 0; } - checkExplicitNames(cmd.commands); - - opts = opts || {}; - if (opts.isDefault) this._defaultCommandName = cmd._name; - if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation - - this.commands.push(cmd); - cmd.parent = this; - return this; + if (compareStrings(v2, m2) !== 0) return false; + return compareStrings(v3, m3) >= 0; }; - /** - * Define argument syntax for the command. - * - * @api public - */ + return compareVersions; +}); - arguments(desc) { - return this._parseExpectedArgs(desc.split(/ +/)); - }; - /** - * Override default decision whether to add implicit help command. - * - * addHelpCommand() // force on - * addHelpCommand(false); // force off - * addHelpCommand('help [cmd]', 'display help for [cmd]'); // force on with custom details - * - * @return {Command} `this` command for chaining - * @api public - */ +/***/ }), - addHelpCommand(enableOrNameAndArgs, description) { - if (enableOrNameAndArgs === false) { - this._hasImplicitHelpCommand = false; - } else { - this._hasImplicitHelpCommand = true; - if (typeof enableOrNameAndArgs === 'string') { - this._helpCommandName = enableOrNameAndArgs.split(' ')[0]; - this._helpCommandnameAndArgs = enableOrNameAndArgs; - } - this._helpCommandDescription = description || this._helpCommandDescription; - } - return this; - }; +/***/ 53921: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /** - * @return {boolean} - * @api private - */ +"use strict"; +/*! + * content-disposition + * Copyright(c) 2014-2017 Douglas Christopher Wilson + * MIT Licensed + */ - _lazyHasImplicitHelpCommand() { - if (this._hasImplicitHelpCommand === undefined) { - this._hasImplicitHelpCommand = this.commands.length && !this._actionHandler && !this._findCommand('help'); - } - return this._hasImplicitHelpCommand; - }; - /** - * Parse expected `args`. - * - * For example `["[type]"]` becomes `[{ required: false, name: 'type' }]`. - * - * @param {Array} args - * @return {Command} `this` command for chaining - * @api private - */ - _parseExpectedArgs(args) { - if (!args.length) return; - args.forEach((arg) => { - const argDetails = { - required: false, - name: '', - variadic: false - }; +/** + * Module exports. + * @public + */ - switch (arg[0]) { - case '<': - argDetails.required = true; - argDetails.name = arg.slice(1, -1); - break; - case '[': - argDetails.name = arg.slice(1, -1); - break; - } +module.exports = contentDisposition +module.exports.parse = parse - if (argDetails.name.length > 3 && argDetails.name.slice(-3) === '...') { - argDetails.variadic = true; - argDetails.name = argDetails.name.slice(0, -3); - } - if (argDetails.name) { - this._args.push(argDetails); - } - }); - this._args.forEach((arg, i) => { - if (arg.variadic && i < this._args.length - 1) { - throw new Error(`only the last argument can be variadic '${arg.name}'`); - } - }); - return this; - }; +/** + * Module dependencies. + * @private + */ - /** - * Register callback to use as replacement for calling process.exit. - * - * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing - * @return {Command} `this` command for chaining - * @api public - */ +var basename = (__nccwpck_require__(71017).basename) +var Buffer = (__nccwpck_require__(38558).Buffer) - exitOverride(fn) { - if (fn) { - this._exitCallback = fn; - } else { - this._exitCallback = (err) => { - if (err.code !== 'commander.executeSubCommandAsync') { - throw err; - } else { - // Async callback from spawn events, not useful to throw. - } - }; - } - return this; - }; +/** + * RegExp to match non attr-char, *after* encodeURIComponent (i.e. not including "%") + * @private + */ - /** - * Call process.exit, and _exitCallback if defined. - * - * @param {number} exitCode exit code for using with process.exit - * @param {string} code an id string representing the error - * @param {string} message human-readable description of the error - * @return never - * @api private - */ +var ENCODE_URL_ATTR_CHAR_REGEXP = /[\x00-\x20"'()*,/:;<=>?@[\\\]{}\x7f]/g // eslint-disable-line no-control-regex - _exit(exitCode, code, message) { - if (this._exitCallback) { - this._exitCallback(new CommanderError(exitCode, code, message)); - // Expecting this line is not reached. - } - process.exit(exitCode); - }; +/** + * RegExp to match percent encoding escape. + * @private + */ - /** - * Register callback `fn` for the command. - * - * Examples: - * - * program - * .command('help') - * .description('display verbose help') - * .action(function() { - * // output help here - * }); - * - * @param {Function} fn - * @return {Command} `this` command for chaining - * @api public - */ +var HEX_ESCAPE_REGEXP = /%[0-9A-Fa-f]{2}/ +var HEX_ESCAPE_REPLACE_REGEXP = /%([0-9A-Fa-f]{2})/g - action(fn) { - const listener = (args) => { - // The .action callback takes an extra parameter which is the command or options. - const expectedArgsCount = this._args.length; - const actionArgs = args.slice(0, expectedArgsCount); - if (this._passCommandToAction) { - actionArgs[expectedArgsCount] = this; - } else { - actionArgs[expectedArgsCount] = this.opts(); - } - // Add the extra arguments so available too. - if (args.length > expectedArgsCount) { - actionArgs.push(args.slice(expectedArgsCount)); - } +/** + * RegExp to match non-latin1 characters. + * @private + */ - const actionResult = fn.apply(this, actionArgs); - // Remember result in case it is async. Assume parseAsync getting called on root. - let rootCommand = this; - while (rootCommand.parent) { - rootCommand = rootCommand.parent; - } - rootCommand._actionResults.push(actionResult); - }; - this._actionHandler = listener; - return this; - }; +var NON_LATIN1_REGEXP = /[^\x20-\x7e\xa0-\xff]/g - /** - * Internal routine to check whether there is a clash storing option value with a Command property. - * - * @param {Option} option - * @api private - */ +/** + * RegExp to match quoted-pair in RFC 2616 + * + * quoted-pair = "\" CHAR + * CHAR = + * @private + */ - _checkForOptionNameClash(option) { - if (!this._storeOptionsAsProperties || this._storeOptionsAsPropertiesCalled) { - // Storing options safely, or user has been explicit and up to them. - return; - } - // User may override help, and hard to tell if worth warning. - if (option.name() === 'help') { - return; - } +var QESC_REGEXP = /\\([\u0000-\u007f])/g // eslint-disable-line no-control-regex - const commandProperty = this._getOptionValue(option.attributeName()); - if (commandProperty === undefined) { - // no clash - return; - } +/** + * RegExp to match chars that must be quoted-pair in RFC 2616 + * @private + */ - let foundClash = true; - if (option.negate) { - // It is ok if define foo before --no-foo. - const positiveLongFlag = option.long.replace(/^--no-/, '--'); - foundClash = !this._findOption(positiveLongFlag); - } else if (option.long) { - const negativeLongFlag = option.long.replace(/^--/, '--no-'); - foundClash = !this._findOption(negativeLongFlag); - } +var QUOTE_REGEXP = /([\\"])/g - if (foundClash) { - throw new Error(`option '${option.name()}' clashes with existing property '${option.attributeName()}' on Command -- call storeOptionsAsProperties(false) to store option values safely, -- or call storeOptionsAsProperties(true) to suppress this check, -- or change option name +/** + * RegExp for various RFC 2616 grammar + * + * parameter = token "=" ( token | quoted-string ) + * token = 1* + * separators = "(" | ")" | "<" | ">" | "@" + * | "," | ";" | ":" | "\" | <"> + * | "/" | "[" | "]" | "?" | "=" + * | "{" | "}" | SP | HT + * quoted-string = ( <"> *(qdtext | quoted-pair ) <"> ) + * qdtext = > + * quoted-pair = "\" CHAR + * CHAR = + * TEXT = + * LWS = [CRLF] 1*( SP | HT ) + * CRLF = CR LF + * CR = + * LF = + * SP = + * HT = + * CTL = + * OCTET = + * @private + */ -Read more on https://git.io/JJc0W`); - } - }; +var PARAM_REGEXP = /;[\x09\x20]*([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*=[\x09\x20]*("(?:[\x20!\x23-\x5b\x5d-\x7e\x80-\xff]|\\[\x20-\x7e])*"|[!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*/g // eslint-disable-line no-control-regex +var TEXT_REGEXP = /^[\x20-\x7e\x80-\xff]+$/ +var TOKEN_REGEXP = /^[!#$%&'*+.0-9A-Z^_`a-z|~-]+$/ - /** - * Internal implementation shared by .option() and .requiredOption() - * - * @param {Object} config - * @param {string} flags - * @param {string} description - * @param {Function|*} [fn] - custom option processing function or default value - * @param {*} [defaultValue] - * @return {Command} `this` command for chaining - * @api private - */ +/** + * RegExp for various RFC 5987 grammar + * + * ext-value = charset "'" [ language ] "'" value-chars + * charset = "UTF-8" / "ISO-8859-1" / mime-charset + * mime-charset = 1*mime-charsetc + * mime-charsetc = ALPHA / DIGIT + * / "!" / "#" / "$" / "%" / "&" + * / "+" / "-" / "^" / "_" / "`" + * / "{" / "}" / "~" + * language = ( 2*3ALPHA [ extlang ] ) + * / 4ALPHA + * / 5*8ALPHA + * extlang = *3( "-" 3ALPHA ) + * value-chars = *( pct-encoded / attr-char ) + * pct-encoded = "%" HEXDIG HEXDIG + * attr-char = ALPHA / DIGIT + * / "!" / "#" / "$" / "&" / "+" / "-" / "." + * / "^" / "_" / "`" / "|" / "~" + * @private + */ - _optionEx(config, flags, description, fn, defaultValue) { - const option = new Option(flags, description); - const oname = option.name(); - const name = option.attributeName(); - option.mandatory = !!config.mandatory; +var EXT_VALUE_REGEXP = /^([A-Za-z0-9!#$%&+\-^_`{}~]+)'(?:[A-Za-z]{2,3}(?:-[A-Za-z]{3}){0,3}|[A-Za-z]{4,8}|)'((?:%[0-9A-Fa-f]{2}|[A-Za-z0-9!#$&+.^_`|~-])+)$/ - this._checkForOptionNameClash(option); +/** + * RegExp for various RFC 6266 grammar + * + * disposition-type = "inline" | "attachment" | disp-ext-type + * disp-ext-type = token + * disposition-parm = filename-parm | disp-ext-parm + * filename-parm = "filename" "=" value + * | "filename*" "=" ext-value + * disp-ext-parm = token "=" value + * | ext-token "=" ext-value + * ext-token = + * @private + */ - // default as 3rd arg - if (typeof fn !== 'function') { - if (fn instanceof RegExp) { - // This is a bit simplistic (especially no error messages), and probably better handled by caller using custom option processing. - // No longer documented in README, but still present for backwards compatibility. - const regex = fn; - fn = (val, def) => { - const m = regex.exec(val); - return m ? m[0] : def; - }; - } else { - defaultValue = fn; - fn = null; - } - } +var DISPOSITION_TYPE_REGEXP = /^([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*(?:$|;)/ // eslint-disable-line no-control-regex - // preassign default value for --no-*, [optional], , or plain flag if boolean value - if (option.negate || option.optional || option.required || typeof defaultValue === 'boolean') { - // when --no-foo we make sure default is true, unless a --foo option is already defined - if (option.negate) { - const positiveLongFlag = option.long.replace(/^--no-/, '--'); - defaultValue = this._findOption(positiveLongFlag) ? this._getOptionValue(name) : true; - } - // preassign only if we have a default - if (defaultValue !== undefined) { - this._setOptionValue(name, defaultValue); - option.defaultValue = defaultValue; - } - } +/** + * Create an attachment Content-Disposition header. + * + * @param {string} [filename] + * @param {object} [options] + * @param {string} [options.type=attachment] + * @param {string|boolean} [options.fallback=true] + * @return {string} + * @public + */ - // register the option - this.options.push(option); +function contentDisposition (filename, options) { + var opts = options || {} - // when it's passed assign the value - // and conditionally invoke the callback - this.on('option:' + oname, (val) => { - const oldValue = this._getOptionValue(name); + // get type + var type = opts.type || 'attachment' - // custom processing - if (val !== null && fn) { - val = fn(val, oldValue === undefined ? defaultValue : oldValue); - } else if (val !== null && option.variadic) { - if (oldValue === defaultValue || !Array.isArray(oldValue)) { - val = [val]; - } else { - val = oldValue.concat(val); - } - } + // get parameters + var params = createparams(filename, opts.fallback) - // unassigned or boolean value - if (typeof oldValue === 'boolean' || typeof oldValue === 'undefined') { - // if no value, negate false, and we have a default, then use it! - if (val == null) { - this._setOptionValue(name, option.negate - ? false - : defaultValue || true); - } else { - this._setOptionValue(name, val); - } - } else if (val !== null) { - // reassign - this._setOptionValue(name, option.negate ? false : val); - } - }); + // format into string + return format(new ContentDisposition(type, params)) +} - return this; - }; +/** + * Create parameters object from filename and fallback. + * + * @param {string} [filename] + * @param {string|boolean} [fallback=true] + * @return {object} + * @private + */ - /** - * Define option with `flags`, `description` and optional - * coercion `fn`. - * - * The `flags` string should contain both the short and long flags, - * separated by comma, a pipe or space. The following are all valid - * all will output this way when `--help` is used. - * - * "-p, --pepper" - * "-p|--pepper" - * "-p --pepper" - * - * Examples: - * - * // simple boolean defaulting to undefined - * program.option('-p, --pepper', 'add pepper'); - * - * program.pepper - * // => undefined - * - * --pepper - * program.pepper - * // => true - * - * // simple boolean defaulting to true (unless non-negated option is also defined) - * program.option('-C, --no-cheese', 'remove cheese'); - * - * program.cheese - * // => true - * - * --no-cheese - * program.cheese - * // => false - * - * // required argument - * program.option('-C, --chdir ', 'change the working directory'); - * - * --chdir /tmp - * program.chdir - * // => "/tmp" - * - * // optional argument - * program.option('-c, --cheese [type]', 'add cheese [marble]'); - * - * @param {string} flags - * @param {string} description - * @param {Function|*} [fn] - custom option processing function or default value - * @param {*} [defaultValue] - * @return {Command} `this` command for chaining - * @api public - */ +function createparams (filename, fallback) { + if (filename === undefined) { + return + } - option(flags, description, fn, defaultValue) { - return this._optionEx({}, flags, description, fn, defaultValue); - }; + var params = {} - /** - * Add a required option which must have a value after parsing. This usually means - * the option must be specified on the command line. (Otherwise the same as .option().) - * - * The `flags` string should contain both the short and long flags, separated by comma, a pipe or space. - * - * @param {string} flags - * @param {string} description - * @param {Function|*} [fn] - custom option processing function or default value - * @param {*} [defaultValue] - * @return {Command} `this` command for chaining - * @api public - */ + if (typeof filename !== 'string') { + throw new TypeError('filename must be a string') + } - requiredOption(flags, description, fn, defaultValue) { - return this._optionEx({ mandatory: true }, flags, description, fn, defaultValue); - }; + // fallback defaults to true + if (fallback === undefined) { + fallback = true + } - /** - * Alter parsing of short flags with optional values. - * - * Examples: - * - * // for `.option('-f,--flag [value]'): - * .combineFlagAndOptionalValue(true) // `-f80` is treated like `--flag=80`, this is the default behaviour - * .combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b` - * - * @param {Boolean} [arg] - if `true` or omitted, an optional value can be specified directly after the flag. - * @api public - */ - combineFlagAndOptionalValue(arg) { - this._combineFlagAndOptionalValue = (arg === undefined) || arg; - return this; - }; + if (typeof fallback !== 'string' && typeof fallback !== 'boolean') { + throw new TypeError('fallback must be a string or boolean') + } - /** - * Allow unknown options on the command line. - * - * @param {Boolean} [arg] - if `true` or omitted, no error will be thrown - * for unknown options. - * @api public - */ - allowUnknownOption(arg) { - this._allowUnknownOption = (arg === undefined) || arg; - return this; - }; + if (typeof fallback === 'string' && NON_LATIN1_REGEXP.test(fallback)) { + throw new TypeError('fallback must be ISO-8859-1 string') + } - /** - * Whether to store option values as properties on command object, - * or store separately (specify false). In both cases the option values can be accessed using .opts(). - * - * @param {boolean} value - * @return {Command} `this` command for chaining - * @api public - */ + // restrict to file base name + var name = basename(filename) - storeOptionsAsProperties(value) { - this._storeOptionsAsPropertiesCalled = true; - this._storeOptionsAsProperties = (value === undefined) || value; - if (this.options.length) { - throw new Error('call .storeOptionsAsProperties() before adding options'); - } - return this; - }; + // determine if name is suitable for quoted string + var isQuotedString = TEXT_REGEXP.test(name) - /** - * Whether to pass command to action handler, - * or just the options (specify false). - * - * @param {boolean} value - * @return {Command} `this` command for chaining - * @api public - */ + // generate fallback name + var fallbackName = typeof fallback !== 'string' + ? fallback && getlatin1(name) + : basename(fallback) + var hasFallback = typeof fallbackName === 'string' && fallbackName !== name - passCommandToAction(value) { - this._passCommandToAction = (value === undefined) || value; - return this; - }; + // set extended filename parameter + if (hasFallback || !isQuotedString || HEX_ESCAPE_REGEXP.test(name)) { + params['filename*'] = name + } - /** - * Store option value - * - * @param {string} key - * @param {Object} value - * @api private - */ + // set filename parameter + if (isQuotedString || hasFallback) { + params.filename = hasFallback + ? fallbackName + : name + } - _setOptionValue(key, value) { - if (this._storeOptionsAsProperties) { - this[key] = value; - } else { - this._optionValues[key] = value; - } - }; + return params +} - /** - * Retrieve option value - * - * @param {string} key - * @return {Object} value - * @api private - */ +/** + * Format object to Content-Disposition header. + * + * @param {object} obj + * @param {string} obj.type + * @param {object} [obj.parameters] + * @return {string} + * @private + */ - _getOptionValue(key) { - if (this._storeOptionsAsProperties) { - return this[key]; - } - return this._optionValues[key]; - }; +function format (obj) { + var parameters = obj.parameters + var type = obj.type - /** - * Parse `argv`, setting options and invoking commands when defined. - * - * The default expectation is that the arguments are from node and have the application as argv[0] - * and the script being run in argv[1], with user parameters after that. - * - * Examples: - * - * program.parse(process.argv); - * program.parse(); // implicitly use process.argv and auto-detect node vs electron conventions - * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0] - * - * @param {string[]} [argv] - optional, defaults to process.argv - * @param {Object} [parseOptions] - optionally specify style of options with from: node/user/electron - * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron' - * @return {Command} `this` command for chaining - * @api public - */ + if (!type || typeof type !== 'string' || !TOKEN_REGEXP.test(type)) { + throw new TypeError('invalid type') + } - parse(argv, parseOptions) { - if (argv !== undefined && !Array.isArray(argv)) { - throw new Error('first parameter to parse must be array or undefined'); - } - parseOptions = parseOptions || {}; + // start with normalized type + var string = String(type).toLowerCase() - // Default to using process.argv - if (argv === undefined) { - argv = process.argv; - // @ts-ignore - if (process.versions && process.versions.electron) { - parseOptions.from = 'electron'; - } - } - this.rawArgs = argv.slice(); + // append parameters + if (parameters && typeof parameters === 'object') { + var param + var params = Object.keys(parameters).sort() - // make it a little easier for callers by supporting various argv conventions - let userArgs; - switch (parseOptions.from) { - case undefined: - case 'node': - this._scriptPath = argv[1]; - userArgs = argv.slice(2); - break; - case 'electron': - // @ts-ignore - if (process.defaultApp) { - this._scriptPath = argv[1]; - userArgs = argv.slice(2); - } else { - userArgs = argv.slice(1); - } - break; - case 'user': - userArgs = argv.slice(0); - break; - default: - throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`); - } - if (!this._scriptPath && process.mainModule) { - this._scriptPath = process.mainModule.filename; - } + for (var i = 0; i < params.length; i++) { + param = params[i] - // Guess name, used in usage in help. - this._name = this._name || (this._scriptPath && path.basename(this._scriptPath, path.extname(this._scriptPath))); + var val = param.substr(-1) === '*' + ? ustring(parameters[param]) + : qstring(parameters[param]) - // Let's go! - this._parseCommand([], userArgs); + string += '; ' + param + '=' + val + } + } - return this; - }; + return string +} - /** - * Parse `argv`, setting options and invoking commands when defined. - * - * Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise. - * - * The default expectation is that the arguments are from node and have the application as argv[0] - * and the script being run in argv[1], with user parameters after that. - * - * Examples: - * - * program.parseAsync(process.argv); - * program.parseAsync(); // implicitly use process.argv and auto-detect node vs electron conventions - * program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0] - * - * @param {string[]} [argv] - * @param {Object} [parseOptions] - * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron' - * @return {Promise} - * @api public - */ +/** + * Decode a RFC 5987 field value (gracefully). + * + * @param {string} str + * @return {string} + * @private + */ - parseAsync(argv, parseOptions) { - this.parse(argv, parseOptions); - return Promise.all(this._actionResults).then(() => this); - }; +function decodefield (str) { + var match = EXT_VALUE_REGEXP.exec(str) - /** - * Execute a sub-command executable. - * - * @api private - */ + if (!match) { + throw new TypeError('invalid extended field value') + } - _executeSubCommand(subcommand, args) { - args = args.slice(); - let launchWithNode = false; // Use node for source targets so do not need to get permissions correct, and on Windows. - const sourceExt = ['.js', '.ts', '.tsx', '.mjs']; + var charset = match[1].toLowerCase() + var encoded = match[2] + var value - // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command. - this._checkForMissingMandatoryOptions(); + // to binary string + var binary = encoded.replace(HEX_ESCAPE_REPLACE_REGEXP, pdecode) - // Want the entry script as the reference for command name and directory for searching for other files. - let scriptPath = this._scriptPath; - // Fallback in case not set, due to how Command created or called. - if (!scriptPath && process.mainModule) { - scriptPath = process.mainModule.filename; - } + switch (charset) { + case 'iso-8859-1': + value = getlatin1(binary) + break + case 'utf-8': + value = Buffer.from(binary, 'binary').toString('utf8') + break + default: + throw new TypeError('unsupported charset in extended field') + } - let baseDir; - try { - const resolvedLink = fs.realpathSync(scriptPath); - baseDir = path.dirname(resolvedLink); - } catch (e) { - baseDir = '.'; // dummy, probably not going to find executable! - } + return value +} - // name of the subcommand, like `pm-install` - let bin = path.basename(scriptPath, path.extname(scriptPath)) + '-' + subcommand._name; - if (subcommand._executableFile) { - bin = subcommand._executableFile; - } +/** + * Get ISO-8859-1 version of string. + * + * @param {string} val + * @return {string} + * @private + */ - const localBin = path.join(baseDir, bin); - if (fs.existsSync(localBin)) { - // prefer local `./` to bin in the $PATH - bin = localBin; - } else { - // Look for source files. - sourceExt.forEach((ext) => { - if (fs.existsSync(`${localBin}${ext}`)) { - bin = `${localBin}${ext}`; - } - }); - } - launchWithNode = sourceExt.includes(path.extname(bin)); +function getlatin1 (val) { + // simple Unicode -> ISO-8859-1 transformation + return String(val).replace(NON_LATIN1_REGEXP, '?') +} - let proc; - if (process.platform !== 'win32') { - if (launchWithNode) { - args.unshift(bin); - // add executable arguments to spawn - args = incrementNodeInspectorPort(process.execArgv).concat(args); +/** + * Parse Content-Disposition header string. + * + * @param {string} string + * @return {object} + * @public + */ - proc = spawn(process.argv[0], args, { stdio: 'inherit' }); - } else { - proc = spawn(bin, args, { stdio: 'inherit' }); - } - } else { - args.unshift(bin); - // add executable arguments to spawn - args = incrementNodeInspectorPort(process.execArgv).concat(args); - proc = spawn(process.execPath, args, { stdio: 'inherit' }); - } +function parse (string) { + if (!string || typeof string !== 'string') { + throw new TypeError('argument string is required') + } - const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP']; - signals.forEach((signal) => { - // @ts-ignore - process.on(signal, () => { - if (proc.killed === false && proc.exitCode === null) { - proc.kill(signal); - } - }); - }); + var match = DISPOSITION_TYPE_REGEXP.exec(string) - // By default terminate process when spawned process terminates. - // Suppressing the exit if exitCallback defined is a bit messy and of limited use, but does allow process to stay running! - const exitCallback = this._exitCallback; - if (!exitCallback) { - proc.on('close', process.exit.bind(process)); - } else { - proc.on('close', () => { - exitCallback(new CommanderError(process.exitCode || 0, 'commander.executeSubCommandAsync', '(close)')); - }); - } - proc.on('error', (err) => { - // @ts-ignore - if (err.code === 'ENOENT') { - const executableMissing = `'${bin}' does not exist - - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead - - if the default executable name is not suitable, use the executableFile option to supply a custom name`; - throw new Error(executableMissing); - // @ts-ignore - } else if (err.code === 'EACCES') { - throw new Error(`'${bin}' not executable`); - } - if (!exitCallback) { - process.exit(1); - } else { - const wrappedError = new CommanderError(1, 'commander.executeSubCommandAsync', '(error)'); - wrappedError.nestedError = err; - exitCallback(wrappedError); - } - }); + if (!match) { + throw new TypeError('invalid type format') + } - // Store the reference to the child process - this.runningCommand = proc; - }; + // normalize type + var index = match[0].length + var type = match[1].toLowerCase() - /** - * @api private - */ - _dispatchSubcommand(commandName, operands, unknown) { - const subCommand = this._findCommand(commandName); - if (!subCommand) this._helpAndError(); + var key + var names = [] + var params = {} + var value - if (subCommand._executableHandler) { - this._executeSubCommand(subCommand, operands.concat(unknown)); - } else { - subCommand._parseCommand(operands, unknown); + // calculate index to start at + index = PARAM_REGEXP.lastIndex = match[0].substr(-1) === ';' + ? index - 1 + : index + + // match parameters + while ((match = PARAM_REGEXP.exec(string))) { + if (match.index !== index) { + throw new TypeError('invalid parameter format') } - }; - /** - * Process arguments in context of this command. - * - * @api private - */ + index += match[0].length + key = match[1].toLowerCase() + value = match[2] - _parseCommand(operands, unknown) { - const parsed = this.parseOptions(unknown); - operands = operands.concat(parsed.operands); - unknown = parsed.unknown; - this.args = operands.concat(unknown); + if (names.indexOf(key) !== -1) { + throw new TypeError('invalid duplicate parameter') + } - if (operands && this._findCommand(operands[0])) { - this._dispatchSubcommand(operands[0], operands.slice(1), unknown); - } else if (this._lazyHasImplicitHelpCommand() && operands[0] === this._helpCommandName) { - if (operands.length === 1) { - this.help(); - } else { - this._dispatchSubcommand(operands[1], [], [this._helpLongFlag]); - } - } else if (this._defaultCommandName) { - outputHelpIfRequested(this, unknown); // Run the help for default command from parent rather than passing to default command - this._dispatchSubcommand(this._defaultCommandName, operands, unknown); - } else { - if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) { - // probably missing subcommand and no handler, user needs help - this._helpAndError(); - } + names.push(key) - outputHelpIfRequested(this, parsed.unknown); - this._checkForMissingMandatoryOptions(); - if (parsed.unknown.length > 0) { - this.unknownOption(parsed.unknown[0]); - } + if (key.indexOf('*') + 1 === key.length) { + // decode extended value + key = key.slice(0, -1) + value = decodefield(value) - if (this._actionHandler) { - const args = this.args.slice(); - this._args.forEach((arg, i) => { - if (arg.required && args[i] == null) { - this.missingArgument(arg.name); - } else if (arg.variadic) { - args[i] = args.splice(i); - } - }); + // overwrite existing value + params[key] = value + continue + } - this._actionHandler(args); - this.emit('command:' + this.name(), operands, unknown); - } else if (operands.length) { - if (this._findCommand('*')) { - this._dispatchSubcommand('*', operands, unknown); - } else if (this.listenerCount('command:*')) { - this.emit('command:*', operands, unknown); - } else if (this.commands.length) { - this.unknownCommand(); - } - } else if (this.commands.length) { - // This command has subcommands and nothing hooked up at this level, so display help. - this._helpAndError(); - } else { - // fall through for caller to handle after calling .parse() - } + if (typeof params[key] === 'string') { + continue } - }; - /** - * Find matching command. - * - * @api private - */ - _findCommand(name) { - if (!name) return undefined; - return this.commands.find(cmd => cmd._name === name || cmd._aliases.includes(name)); - }; + if (value[0] === '"') { + // remove quotes and escapes + value = value + .substr(1, value.length - 2) + .replace(QESC_REGEXP, '$1') + } - /** - * Return an option matching `arg` if any. - * - * @param {string} arg - * @return {Option} - * @api private - */ + params[key] = value + } - _findOption(arg) { - return this.options.find(option => option.is(arg)); - }; + if (index !== -1 && index !== string.length) { + throw new TypeError('invalid parameter format') + } - /** - * Display an error message if a mandatory option does not have a value. - * Lazy calling after checking for help flags from leaf subcommand. - * - * @api private - */ + return new ContentDisposition(type, params) +} - _checkForMissingMandatoryOptions() { - // Walk up hierarchy so can call in subcommand after checking for displaying help. - for (let cmd = this; cmd; cmd = cmd.parent) { - cmd.options.forEach((anOption) => { - if (anOption.mandatory && (cmd._getOptionValue(anOption.attributeName()) === undefined)) { - cmd.missingMandatoryOptionValue(anOption); - } - }); - } - }; +/** + * Percent decode a single character. + * + * @param {string} str + * @param {string} hex + * @return {string} + * @private + */ - /** - * Parse options from `argv` removing known options, - * and return argv split into operands and unknown arguments. - * - * Examples: - * - * argv => operands, unknown - * --known kkk op => [op], [] - * op --known kkk => [op], [] - * sub --unknown uuu op => [sub], [--unknown uuu op] - * sub -- --unknown uuu op => [sub --unknown uuu op], [] - * - * @param {String[]} argv - * @return {{operands: String[], unknown: String[]}} - * @api public - */ +function pdecode (str, hex) { + return String.fromCharCode(parseInt(hex, 16)) +} - parseOptions(argv) { - const operands = []; // operands, not options or values - const unknown = []; // first unknown option and remaining unknown args - let dest = operands; - const args = argv.slice(); +/** + * Percent encode a single character. + * + * @param {string} char + * @return {string} + * @private + */ - function maybeOption(arg) { - return arg.length > 1 && arg[0] === '-'; - } +function pencode (char) { + return '%' + String(char) + .charCodeAt(0) + .toString(16) + .toUpperCase() +} - // parse options - let activeVariadicOption = null; - while (args.length) { - const arg = args.shift(); +/** + * Quote a string for HTTP. + * + * @param {string} val + * @return {string} + * @private + */ - // literal - if (arg === '--') { - if (dest === unknown) dest.push(arg); - dest.push(...args); - break; - } +function qstring (val) { + var str = String(val) - if (activeVariadicOption && !maybeOption(arg)) { - this.emit(`option:${activeVariadicOption.name()}`, arg); - continue; - } - activeVariadicOption = null; + return '"' + str.replace(QUOTE_REGEXP, '\\$1') + '"' +} - if (maybeOption(arg)) { - const option = this._findOption(arg); - // recognised option, call listener to assign value with possible custom processing - if (option) { - if (option.required) { - const value = args.shift(); - if (value === undefined) this.optionMissingArgument(option); - this.emit(`option:${option.name()}`, value); - } else if (option.optional) { - let value = null; - // historical behaviour is optional value is following arg unless an option - if (args.length > 0 && !maybeOption(args[0])) { - value = args.shift(); - } - this.emit(`option:${option.name()}`, value); - } else { // boolean flag - this.emit(`option:${option.name()}`); - } - activeVariadicOption = option.variadic ? option : null; - continue; - } - } +/** + * Encode a Unicode string for HTTP (RFC 5987). + * + * @param {string} val + * @return {string} + * @private + */ - // Look for combo options following single dash, eat first one if known. - if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') { - const option = this._findOption(`-${arg[1]}`); - if (option) { - if (option.required || (option.optional && this._combineFlagAndOptionalValue)) { - // option with value following in same argument - this.emit(`option:${option.name()}`, arg.slice(2)); - } else { - // boolean option, emit and put back remainder of arg for further processing - this.emit(`option:${option.name()}`); - args.unshift(`-${arg.slice(2)}`); - } - continue; - } - } +function ustring (val) { + var str = String(val) - // Look for known long flag with value, like --foo=bar - if (/^--[^=]+=/.test(arg)) { - const index = arg.indexOf('='); - const option = this._findOption(arg.slice(0, index)); - if (option && (option.required || option.optional)) { - this.emit(`option:${option.name()}`, arg.slice(index + 1)); - continue; - } - } + // percent encode as UTF-8 + var encoded = encodeURIComponent(str) + .replace(ENCODE_URL_ATTR_CHAR_REGEXP, pencode) - // looks like an option but unknown, unknowns from here - if (arg.length > 1 && arg[0] === '-') { - dest = unknown; - } + return 'UTF-8\'\'' + encoded +} - // add arg - dest.push(arg); - } +/** + * Class for parsed Content-Disposition header for v8 optimization + * + * @public + * @param {string} type + * @param {object} parameters + * @constructor + */ - return { operands, unknown }; - }; +function ContentDisposition (type, parameters) { + this.type = type + this.parameters = parameters +} - /** - * Return an object containing options as key-value pairs - * - * @return {Object} - * @api public - */ - opts() { - if (this._storeOptionsAsProperties) { - // Preserve original behaviour so backwards compatible when still using properties - const result = {}; - const len = this.options.length; - for (let i = 0; i < len; i++) { - const key = this.options[i].attributeName(); - result[key] = key === this._versionOptionName ? this._version : this[key]; - } - return result; - } +/***/ }), - return this._optionValues; - }; +/***/ 38558: +/***/ ((module, exports, __nccwpck_require__) => { - /** - * Argument `name` is missing. - * - * @param {string} name - * @api private - */ +/*! safe-buffer. MIT License. Feross Aboukhadijeh */ +/* eslint-disable node/no-deprecated-api */ +var buffer = __nccwpck_require__(14300) +var Buffer = buffer.Buffer - missingArgument(name) { - const message = `error: missing required argument '${name}'`; - console.error(message); - this._exit(1, 'commander.missingArgument', message); - }; +// alternative to using Object.keys for old browsers +function copyProps (src, dst) { + for (var key in src) { + dst[key] = src[key] + } +} +if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer +} else { + // Copy properties from require('buffer') + copyProps(buffer, exports) + exports.Buffer = SafeBuffer +} - /** - * `Option` is missing an argument, but received `flag` or nothing. - * - * @param {Option} option - * @param {string} [flag] - * @api private - */ +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) +} - optionMissingArgument(option, flag) { - let message; - if (flag) { - message = `error: option '${option.flags}' argument missing, got '${flag}'`; +SafeBuffer.prototype = Object.create(Buffer.prototype) + +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer) + +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') + } + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + var buf = Buffer(size) + if (fill !== undefined) { + if (typeof encoding === 'string') { + buf.fill(fill, encoding) } else { - message = `error: option '${option.flags}' argument missing`; + buf.fill(fill) } - console.error(message); - this._exit(1, 'commander.optionMissingArgument', message); - }; - - /** - * `Option` does not have a value, and is a mandatory option. - * - * @param {Option} option - * @api private - */ + } else { + buf.fill(0) + } + return buf +} - missingMandatoryOptionValue(option) { - const message = `error: required option '${option.flags}' not specified`; - console.error(message); - this._exit(1, 'commander.missingMandatoryOptionValue', message); - }; +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) +} - /** - * Unknown option `flag`. - * - * @param {string} flag - * @api private - */ +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) +} - unknownOption(flag) { - if (this._allowUnknownOption) return; - const message = `error: unknown option '${flag}'`; - console.error(message); - this._exit(1, 'commander.unknownOption', message); - }; - /** - * Unknown command. - * - * @api private - */ +/***/ }), - unknownCommand() { - const partCommands = [this.name()]; - for (let parentCmd = this.parent; parentCmd; parentCmd = parentCmd.parent) { - partCommands.unshift(parentCmd.name()); - } - const fullCommand = partCommands.join(' '); - const message = `error: unknown command '${this.args[0]}'.` + - (this._hasHelpOption ? ` See '${fullCommand} ${this._helpLongFlag}'.` : ''); - console.error(message); - this._exit(1, 'commander.unknownCommand', message); - }; +/***/ 99915: +/***/ ((__unused_webpack_module, exports) => { - /** - * Set the program version to `str`. - * - * This method auto-registers the "-V, --version" flag - * which will print the version number when passed. - * - * You can optionally supply the flags and description to override the defaults. - * - * @param {string} str - * @param {string} [flags] - * @param {string} [description] - * @return {this | string} `this` command for chaining, or version string if no arguments - * @api public - */ +"use strict"; +/*! + * content-type + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ - version(str, flags, description) { - if (str === undefined) return this._version; - this._version = str; - flags = flags || '-V, --version'; - description = description || 'output the version number'; - const versionOption = new Option(flags, description); - this._versionOptionName = versionOption.attributeName(); - this.options.push(versionOption); - this.on('option:' + versionOption.name(), () => { - process.stdout.write(str + '\n'); - this._exit(0, 'commander.version', str); - }); - return this; - }; - /** - * Set the description to `str`. - * - * @param {string} str - * @param {Object} [argsDescription] - * @return {string|Command} - * @api public - */ - description(str, argsDescription) { - if (str === undefined && argsDescription === undefined) return this._description; - this._description = str; - this._argsDescription = argsDescription; - return this; - }; +/** + * RegExp to match *( ";" parameter ) in RFC 7231 sec 3.1.1.1 + * + * parameter = token "=" ( token / quoted-string ) + * token = 1*tchar + * tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" + * / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" + * / DIGIT / ALPHA + * ; any VCHAR, except delimiters + * quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE + * qdtext = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text + * obs-text = %x80-FF + * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) + */ +var PARAM_REGEXP = /; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g +var TEXT_REGEXP = /^[\u000b\u0020-\u007e\u0080-\u00ff]+$/ +var TOKEN_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/ - /** - * Set an alias for the command. - * - * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help. - * - * @param {string} [alias] - * @return {string|Command} - * @api public - */ +/** + * RegExp to match quoted-pair in RFC 7230 sec 3.2.6 + * + * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) + * obs-text = %x80-FF + */ +var QESC_REGEXP = /\\([\u000b\u0020-\u00ff])/g - alias(alias) { - if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility +/** + * RegExp to match chars that must be quoted-pair in RFC 7230 sec 3.2.6 + */ +var QUOTE_REGEXP = /([\\"])/g - let command = this; - if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) { - // assume adding alias for last added executable subcommand, rather than this - command = this.commands[this.commands.length - 1]; - } +/** + * RegExp to match type in RFC 7231 sec 3.1.1.1 + * + * media-type = type "/" subtype + * type = token + * subtype = token + */ +var TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/ - if (alias === command._name) throw new Error('Command alias can\'t be the same as its name'); +/** + * Module exports. + * @public + */ - command._aliases.push(alias); - return this; - }; +exports.format = format +exports.parse = parse - /** - * Set aliases for the command. - * - * Only the first alias is shown in the auto-generated help. - * - * @param {string[]} [aliases] - * @return {string[]|Command} - * @api public - */ +/** + * Format object to media type. + * + * @param {object} obj + * @return {string} + * @public + */ - aliases(aliases) { - // Getter for the array of aliases is the main reason for having aliases() in addition to alias(). - if (aliases === undefined) return this._aliases; +function format (obj) { + if (!obj || typeof obj !== 'object') { + throw new TypeError('argument obj is required') + } - aliases.forEach((alias) => this.alias(alias)); - return this; - }; + var parameters = obj.parameters + var type = obj.type - /** - * Set / get the command usage `str`. - * - * @param {string} [str] - * @return {String|Command} - * @api public - */ + if (!type || !TYPE_REGEXP.test(type)) { + throw new TypeError('invalid type') + } - usage(str) { - if (str === undefined) { - if (this._usage) return this._usage; + var string = type - const args = this._args.map((arg) => { - return humanReadableArgName(arg); - }); - return [].concat( - (this.options.length || this._hasHelpOption ? '[options]' : []), - (this.commands.length ? '[command]' : []), - (this._args.length ? args : []) - ).join(' '); - } + // append parameters + if (parameters && typeof parameters === 'object') { + var param + var params = Object.keys(parameters).sort() - this._usage = str; - return this; - }; + for (var i = 0; i < params.length; i++) { + param = params[i] - /** - * Get or set the name of the command - * - * @param {string} [str] - * @return {String|Command} - * @api public - */ + if (!TOKEN_REGEXP.test(param)) { + throw new TypeError('invalid parameter name') + } - name(str) { - if (str === undefined) return this._name; - this._name = str; - return this; - }; + string += '; ' + param + '=' + qstring(parameters[param]) + } + } - /** - * Return prepared commands. - * - * @return {Array} - * @api private - */ + return string +} - prepareCommands() { - const commandDetails = this.commands.filter((cmd) => { - return !cmd._hidden; - }).map((cmd) => { - const args = cmd._args.map((arg) => { - return humanReadableArgName(arg); - }).join(' '); +/** + * Parse media type to object. + * + * @param {string|object} string + * @return {Object} + * @public + */ - return [ - cmd._name + - (cmd._aliases[0] ? '|' + cmd._aliases[0] : '') + - (cmd.options.length ? ' [options]' : '') + - (args ? ' ' + args : ''), - cmd._description - ]; - }); +function parse (string) { + if (!string) { + throw new TypeError('argument string is required') + } - if (this._lazyHasImplicitHelpCommand()) { - commandDetails.push([this._helpCommandnameAndArgs, this._helpCommandDescription]); - } - return commandDetails; - }; + // support req/res-like objects as argument + var header = typeof string === 'object' + ? getcontenttype(string) + : string - /** - * Return the largest command length. - * - * @return {number} - * @api private - */ + if (typeof header !== 'string') { + throw new TypeError('argument string is required to be a string') + } - largestCommandLength() { - const commands = this.prepareCommands(); - return commands.reduce((max, command) => { - return Math.max(max, command[0].length); - }, 0); - }; + var index = header.indexOf(';') + var type = index !== -1 + ? header.substr(0, index).trim() + : header.trim() - /** - * Return the largest option length. - * - * @return {number} - * @api private - */ + if (!TYPE_REGEXP.test(type)) { + throw new TypeError('invalid media type') + } - largestOptionLength() { - const options = [].slice.call(this.options); - options.push({ - flags: this._helpFlags - }); + var obj = new ContentType(type.toLowerCase()) - return options.reduce((max, option) => { - return Math.max(max, option.flags.length); - }, 0); - }; + // parse parameters + if (index !== -1) { + var key + var match + var value - /** - * Return the largest arg length. - * - * @return {number} - * @api private - */ + PARAM_REGEXP.lastIndex = index - largestArgLength() { - return this._args.reduce((max, arg) => { - return Math.max(max, arg.name.length); - }, 0); - }; + while ((match = PARAM_REGEXP.exec(header))) { + if (match.index !== index) { + throw new TypeError('invalid parameter format') + } - /** - * Return the pad width. - * - * @return {number} - * @api private - */ + index += match[0].length + key = match[1].toLowerCase() + value = match[2] - padWidth() { - let width = this.largestOptionLength(); - if (this._argsDescription && this._args.length) { - if (this.largestArgLength() > width) { - width = this.largestArgLength(); + if (value[0] === '"') { + // remove quotes and escapes + value = value + .substr(1, value.length - 2) + .replace(QESC_REGEXP, '$1') } + + obj.parameters[key] = value } - if (this.commands && this.commands.length) { - if (this.largestCommandLength() > width) { - width = this.largestCommandLength(); - } + if (index !== header.length) { + throw new TypeError('invalid parameter format') } + } - return width; - }; + return obj +} - /** - * Return help for options. - * - * @return {string} - * @api private - */ +/** + * Get content-type from req/res objects. + * + * @param {object} + * @return {Object} + * @private + */ - optionHelp() { - const width = this.padWidth(); - const columns = process.stdout.columns || 80; - const descriptionWidth = columns - width - 4; - function padOptionDetails(flags, description) { - return pad(flags, width) + ' ' + optionalWrap(description, descriptionWidth, width + 2); - }; +function getcontenttype (obj) { + var header - // Explicit options (including version) - const help = this.options.map((option) => { - const fullDesc = option.description + - ((!option.negate && option.defaultValue !== undefined) ? ' (default: ' + JSON.stringify(option.defaultValue) + ')' : ''); - return padOptionDetails(option.flags, fullDesc); - }); + if (typeof obj.getHeader === 'function') { + // res-like + header = obj.getHeader('content-type') + } else if (typeof obj.headers === 'object') { + // req-like + header = obj.headers && obj.headers['content-type'] + } - // Implicit help - const showShortHelpFlag = this._hasHelpOption && this._helpShortFlag && !this._findOption(this._helpShortFlag); - const showLongHelpFlag = this._hasHelpOption && !this._findOption(this._helpLongFlag); - if (showShortHelpFlag || showLongHelpFlag) { - let helpFlags = this._helpFlags; - if (!showShortHelpFlag) { - helpFlags = this._helpLongFlag; - } else if (!showLongHelpFlag) { - helpFlags = this._helpShortFlag; - } - help.push(padOptionDetails(helpFlags, this._helpDescription)); - } + if (typeof header !== 'string') { + throw new TypeError('content-type header is missing from object') + } - return help.join('\n'); - }; + return header +} - /** - * Return command help documentation. - * - * @return {string} - * @api private - */ +/** + * Quote a string if necessary. + * + * @param {string} val + * @return {string} + * @private + */ - commandHelp() { - if (!this.commands.length && !this._lazyHasImplicitHelpCommand()) return ''; +function qstring (val) { + var str = String(val) - const commands = this.prepareCommands(); - const width = this.padWidth(); + // no need to quote tokens + if (TOKEN_REGEXP.test(str)) { + return str + } - const columns = process.stdout.columns || 80; - const descriptionWidth = columns - width - 4; + if (str.length > 0 && !TEXT_REGEXP.test(str)) { + throw new TypeError('invalid parameter value') + } - return [ - 'Commands:', - commands.map((cmd) => { - const desc = cmd[1] ? ' ' + cmd[1] : ''; - return (desc ? pad(cmd[0], width) : cmd[0]) + optionalWrap(desc, descriptionWidth, width + 2); - }).join('\n').replace(/^/gm, ' '), - '' - ].join('\n'); - }; + return '"' + str.replace(QUOTE_REGEXP, '\\$1') + '"' +} - /** - * Return program help documentation. - * - * @return {string} - * @api public - */ +/** + * Class to represent a content type. + * @private + */ +function ContentType (type) { + this.parameters = Object.create(null) + this.type = type +} - helpInformation() { - let desc = []; - if (this._description) { - desc = [ - this._description, - '' - ]; - const argsDescription = this._argsDescription; - if (argsDescription && this._args.length) { - const width = this.padWidth(); - const columns = process.stdout.columns || 80; - const descriptionWidth = columns - width - 5; - desc.push('Arguments:'); - this._args.forEach((arg) => { - desc.push(' ' + pad(arg.name, width) + ' ' + wrap(argsDescription[arg.name] || '', descriptionWidth, width + 4)); - }); - desc.push(''); - } - } +/***/ }), - let cmdName = this._name; - if (this._aliases[0]) { - cmdName = cmdName + '|' + this._aliases[0]; - } - let parentCmdNames = ''; - for (let parentCmd = this.parent; parentCmd; parentCmd = parentCmd.parent) { - parentCmdNames = parentCmd.name() + ' ' + parentCmdNames; - } - const usage = [ - 'Usage: ' + parentCmdNames + cmdName + ' ' + this.usage(), - '' - ]; +/***/ 61579: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - let cmds = []; - const commandHelp = this.commandHelp(); - if (commandHelp) cmds = [commandHelp]; +/** + * Module dependencies. + */ - let options = []; - if (this._hasHelpOption || this.options.length > 0) { - options = [ - 'Options:', - '' + this.optionHelp().replace(/^/gm, ' '), - '' - ]; - } +var crypto = __nccwpck_require__(6113); - return usage - .concat(desc) - .concat(options) - .concat(cmds) - .join('\n'); - }; +/** + * Sign the given `val` with `secret`. + * + * @param {String} val + * @param {String} secret + * @return {String} + * @api private + */ - /** - * Output help information for this command. - * - * When listener(s) are available for the helpLongFlag - * those callbacks are invoked. - * - * @api public - */ +exports.sign = function(val, secret){ + if ('string' != typeof val) throw new TypeError("Cookie value must be provided as a string."); + if ('string' != typeof secret) throw new TypeError("Secret string must be provided."); + return val + '.' + crypto + .createHmac('sha256', secret) + .update(val) + .digest('base64') + .replace(/\=+$/, ''); +}; - outputHelp(cb) { - if (!cb) { - cb = (passthru) => { - return passthru; - }; - } - const cbOutput = cb(this.helpInformation()); - if (typeof cbOutput !== 'string' && !Buffer.isBuffer(cbOutput)) { - throw new Error('outputHelp callback must return a string or a Buffer'); - } - process.stdout.write(cbOutput); - this.emit(this._helpLongFlag); - }; +/** + * Unsign and decode the given `val` with `secret`, + * returning `false` if the signature is invalid. + * + * @param {String} val + * @param {String} secret + * @return {String|Boolean} + * @api private + */ - /** - * You can pass in flags and a description to override the help - * flags and help description for your command. Pass in false to - * disable the built-in help option. - * - * @param {string | boolean} [flags] - * @param {string} [description] - * @return {Command} `this` command for chaining - * @api public - */ +exports.unsign = function(val, secret){ + if ('string' != typeof val) throw new TypeError("Signed cookie string must be provided."); + if ('string' != typeof secret) throw new TypeError("Secret string must be provided."); + var str = val.slice(0, val.lastIndexOf('.')) + , mac = exports.sign(str, secret); + + return sha1(mac) == sha1(val) ? str : false; +}; - helpOption(flags, description) { - if (typeof flags === 'boolean') { - this._hasHelpOption = flags; - return this; - } - this._helpFlags = flags || this._helpFlags; - this._helpDescription = description || this._helpDescription; +/** + * Private + */ - const helpFlags = _parseOptionFlags(this._helpFlags); - this._helpShortFlag = helpFlags.shortFlag; - this._helpLongFlag = helpFlags.longFlag; +function sha1(str){ + return crypto.createHash('sha1').update(str).digest('hex'); +} - return this; - }; - /** - * Output help information and exit. - * - * @param {Function} [cb] - * @api public - */ +/***/ }), - help(cb) { - this.outputHelp(cb); - // exitCode: preserving original behaviour which was calling process.exit() - // message: do not have all displayed text available so only passing placeholder. - this._exit(process.exitCode || 0, 'commander.help', '(outputHelp)'); - }; +/***/ 93658: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; +/*! + * cookie + * Copyright(c) 2012-2014 Roman Shtylman + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ - /** - * Output help information and exit. Display for error situations. - * - * @api private - */ - _helpAndError() { - this.outputHelp(); - // message: do not have all displayed text available so only passing placeholder. - this._exit(1, 'commander.help', '(outputHelp)'); - }; -}; /** - * Expose the root command. + * Module exports. + * @public */ -exports = module.exports = new Command(); -exports.program = exports; // More explicit access to global command. +exports.parse = parse; +exports.serialize = serialize; /** - * Expose classes + * Module variables. + * @private */ -exports.Command = Command; -exports.Option = Option; -exports.CommanderError = CommanderError; +var decode = decodeURIComponent; +var encode = encodeURIComponent; +var pairSplitRegExp = /; */; /** - * Camel-case the given `flag` + * RegExp to match field-content in RFC 7230 sec 3.2 * - * @param {string} flag - * @return {string} - * @api private + * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] + * field-vchar = VCHAR / obs-text + * obs-text = %x80-FF */ -function camelcase(flag) { - return flag.split('-').reduce((str, word) => { - return str + word[0].toUpperCase() + word.slice(1); - }); -} +var fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/; /** - * Pad `str` to `width`. + * Parse a cookie header. + * + * Parse the given cookie header string into an object + * The object has the various cookies as keys(names) => values * * @param {string} str - * @param {number} width - * @return {string} - * @api private + * @param {object} [options] + * @return {object} + * @public */ -function pad(str, width) { - const len = Math.max(0, width - str.length); - return str + Array(len + 1).join(' '); -} +function parse(str, options) { + if (typeof str !== 'string') { + throw new TypeError('argument str must be a string'); + } -/** - * Wraps the given string with line breaks at the specified width while breaking - * words and indenting every but the first line on the left. - * - * @param {string} str - * @param {number} width - * @param {number} indent - * @return {string} - * @api private - */ -function wrap(str, width, indent) { - const regex = new RegExp('.{1,' + (width - 1) + '}([\\s\u200B]|$)|[^\\s\u200B]+?([\\s\u200B]|$)', 'g'); - const lines = str.match(regex) || []; - return lines.map((line, i) => { - if (line.slice(-1) === '\n') { - line = line.slice(0, line.length - 1); - } - return ((i > 0 && indent) ? Array(indent + 1).join(' ') : '') + line.trimRight(); - }).join('\n'); -} + var obj = {} + var opt = options || {}; + var pairs = str.split(pairSplitRegExp); + var dec = opt.decode || decode; -/** - * Optionally wrap the given str to a max width of width characters per line - * while indenting with indent spaces. Do not wrap if insufficient width or - * string is manually formatted. - * - * @param {string} str - * @param {number} width - * @param {number} indent - * @return {string} - * @api private - */ -function optionalWrap(str, width, indent) { - // Detect manually wrapped and indented strings by searching for line breaks - // followed by multiple spaces/tabs. - if (str.match(/[\n]\s+/)) return str; - // Do not wrap to narrow columns (or can end up with a word per line). - const minWidth = 40; - if (width < minWidth) return str; + for (var i = 0; i < pairs.length; i++) { + var pair = pairs[i]; + var eq_idx = pair.indexOf('='); - return wrap(str, width, indent); -} + // skip things that don't look like key=value + if (eq_idx < 0) { + continue; + } -/** - * Output help information if help flags specified - * - * @param {Command} cmd - command to output help for - * @param {Array} args - array of options to search for help flags - * @api private - */ + var key = pair.substr(0, eq_idx).trim() + var val = pair.substr(++eq_idx, pair.length).trim(); -function outputHelpIfRequested(cmd, args) { - const helpOption = cmd._hasHelpOption && args.find(arg => arg === cmd._helpLongFlag || arg === cmd._helpShortFlag); - if (helpOption) { - cmd.outputHelp(); - // (Do not have all displayed text available so only passing placeholder.) - cmd._exit(0, 'commander.helpDisplayed', '(outputHelp)'); + // quoted values + if ('"' == val[0]) { + val = val.slice(1, -1); + } + + // only assign once + if (undefined == obj[key]) { + obj[key] = tryDecode(val, dec); + } } + + return obj; } /** - * Takes an argument and returns its human readable equivalent for help usage. + * Serialize data into a cookie header. * - * @param {Object} arg + * Serialize the a name value pair into a cookie string suitable for + * http headers. An optional options object specified cookie parameters. + * + * serialize('foo', 'bar', { httpOnly: true }) + * => "foo=bar; httpOnly" + * + * @param {string} name + * @param {string} val + * @param {object} [options] * @return {string} - * @api private + * @public */ -function humanReadableArgName(arg) { - const nameOutput = arg.name + (arg.variadic === true ? '...' : ''); +function serialize(name, val, options) { + var opt = options || {}; + var enc = opt.encode || encode; - return arg.required - ? '<' + nameOutput + '>' - : '[' + nameOutput + ']'; -} + if (typeof enc !== 'function') { + throw new TypeError('option encode is invalid'); + } -/** - * Parse the short and long flag out of something like '-m,--mixed ' - * - * @api private - */ + if (!fieldContentRegExp.test(name)) { + throw new TypeError('argument name is invalid'); + } -function _parseOptionFlags(flags) { - let shortFlag; - let longFlag; - // Use original very loose parsing to maintain backwards compatibility for now, - // which allowed for example unintended `-sw, --short-word` [sic]. - const flagParts = flags.split(/[ |,]+/); - if (flagParts.length > 1 && !/^[[<]/.test(flagParts[1])) shortFlag = flagParts.shift(); - longFlag = flagParts.shift(); - // Add support for lone short flag without significantly changing parsing! - if (!shortFlag && /^-[^-]$/.test(longFlag)) { - shortFlag = longFlag; - longFlag = undefined; + var value = enc(val); + + if (value && !fieldContentRegExp.test(value)) { + throw new TypeError('argument val is invalid'); } - return { shortFlag, longFlag }; -} -/** - * Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command). - * - * @param {string[]} args - array of arguments from node.execArgv - * @returns {string[]} - * @api private - */ + var str = name + '=' + value; -function incrementNodeInspectorPort(args) { - // Testing for these options: - // --inspect[=[host:]port] - // --inspect-brk[=[host:]port] - // --inspect-port=[host:]port - return args.map((arg) => { - if (!arg.startsWith('--inspect')) { - return arg; - } - let debugOption; - let debugHost = '127.0.0.1'; - let debugPort = '9229'; - let match; - if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) { - // e.g. --inspect - debugOption = match[1]; - } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) { - debugOption = match[1]; - if (/^\d+$/.test(match[3])) { - // e.g. --inspect=1234 - debugPort = match[3]; - } else { - // e.g. --inspect=localhost - debugHost = match[3]; - } - } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) { - // e.g. --inspect=localhost:1234 - debugOption = match[1]; - debugHost = match[3]; - debugPort = match[4]; + if (null != opt.maxAge) { + var maxAge = opt.maxAge - 0; + + if (isNaN(maxAge) || !isFinite(maxAge)) { + throw new TypeError('option maxAge is invalid') } - if (debugOption && debugPort !== '0') { - return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`; + str += '; Max-Age=' + Math.floor(maxAge); + } + + if (opt.domain) { + if (!fieldContentRegExp.test(opt.domain)) { + throw new TypeError('option domain is invalid'); } - return arg; - }); -} + str += '; Domain=' + opt.domain; + } -/***/ }), + if (opt.path) { + if (!fieldContentRegExp.test(opt.path)) { + throw new TypeError('option path is invalid'); + } -/***/ 89296: -/***/ (function(module) { + str += '; Path=' + opt.path; + } -/* global define */ -(function (root, factory) { - /* istanbul ignore next */ - if (typeof define === 'function' && define.amd) { - define([], factory); - } else if (true) { - module.exports = factory(); - } else {} -})(this, function () { - var semver = - /^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i; + if (opt.expires) { + if (typeof opt.expires.toUTCString !== 'function') { + throw new TypeError('option expires is invalid'); + } - function indexOrEnd(str, q) { - return str.indexOf(q) === -1 ? str.length : str.indexOf(q); + str += '; Expires=' + opt.expires.toUTCString(); } - function split(v) { - var c = v.replace(/^v/, '').replace(/\+.*$/, ''); - var patchIndex = indexOrEnd(c, '-'); - var arr = c.substring(0, patchIndex).split('.'); - arr.push(c.substring(patchIndex + 1)); - return arr; + if (opt.httpOnly) { + str += '; HttpOnly'; } - function tryParse(v) { - var n = parseInt(v, 10); - return isNaN(n) ? v : n; - } - - function validateAndParse(v) { - if (typeof v !== 'string') { - throw new TypeError('Invalid argument expected string'); - } - var match = v.match(semver); - if (!match) { - throw new Error( - "Invalid argument not valid semver ('" + v + "' received)" - ); - } - match.shift(); - return match; - } - - function forceType(a, b) { - return typeof a !== typeof b ? [String(a), String(b)] : [a, b]; - } - - function compareStrings(a, b) { - var [ap, bp] = forceType(tryParse(a), tryParse(b)); - if (ap > bp) return 1; - if (ap < bp) return -1; - return 0; - } - - function compareSegments(a, b) { - for (var i = 0; i < Math.max(a.length, b.length); i++) { - var r = compareStrings(a[i] || 0, b[i] || 0); - if (r !== 0) return r; - } - return 0; + if (opt.secure) { + str += '; Secure'; } - function compareVersions(v1, v2) { - [v1, v2].forEach(validateAndParse); - - var s1 = split(v1); - var s2 = split(v2); - - for (var i = 0; i < Math.max(s1.length - 1, s2.length - 1); i++) { - var n1 = parseInt(s1[i] || 0, 10); - var n2 = parseInt(s2[i] || 0, 10); - - if (n1 > n2) return 1; - if (n2 > n1) return -1; - } - - var sp1 = s1[s1.length - 1]; - var sp2 = s2[s2.length - 1]; - - if (sp1 && sp2) { - var p1 = sp1.split('.').map(tryParse); - var p2 = sp2.split('.').map(tryParse); - - for (i = 0; i < Math.max(p1.length, p2.length); i++) { - if ( - p1[i] === undefined || - (typeof p2[i] === 'string' && typeof p1[i] === 'number') - ) - return -1; - if ( - p2[i] === undefined || - (typeof p1[i] === 'string' && typeof p2[i] === 'number') - ) - return 1; + if (opt.sameSite) { + var sameSite = typeof opt.sameSite === 'string' + ? opt.sameSite.toLowerCase() : opt.sameSite; - if (p1[i] > p2[i]) return 1; - if (p2[i] > p1[i]) return -1; - } - } else if (sp1 || sp2) { - return sp1 ? -1 : 1; + switch (sameSite) { + case true: + str += '; SameSite=Strict'; + break; + case 'lax': + str += '; SameSite=Lax'; + break; + case 'strict': + str += '; SameSite=Strict'; + break; + case 'none': + str += '; SameSite=None'; + break; + default: + throw new TypeError('option sameSite is invalid'); } - - return 0; } - var allowedOperators = ['>', '>=', '=', '<', '<=']; + return str; +} - var operatorResMap = { - '>': [1], - '>=': [0, 1], - '=': [0], - '<=': [-1, 0], - '<': [-1], - }; +/** + * Try decoding a string using a decoding function. + * + * @param {string} str + * @param {function} decode + * @private + */ - function validateOperator(op) { - if (typeof op !== 'string') { - throw new TypeError( - 'Invalid operator type, expected string but got ' + typeof op - ); - } - if (allowedOperators.indexOf(op) === -1) { - throw new TypeError( - 'Invalid operator, expected one of ' + allowedOperators.join('|') - ); - } +function tryDecode(str, decode) { + try { + return decode(str); + } catch (e) { + return str; } - - compareVersions.validate = function (version) { - return typeof version === 'string' && semver.test(version); - }; - - compareVersions.compare = function (v1, v2, operator) { - // Validate operator - validateOperator(operator); - - // since result of compareVersions can only be -1 or 0 or 1 - // a simple map can be used to replace switch - var res = compareVersions(v1, v2); - return operatorResMap[operator].indexOf(res) > -1; - }; - - compareVersions.satisfies = function (v, r) { - // if no range operator then "=" - var match = r.match(/^([<>=~^]+)/); - var op = match ? match[1] : '='; - - // if gt/lt/eq then operator compare - if (op !== '^' && op !== '~') return compareVersions.compare(v, r, op); - - // else range of either "~" or "^" is assumed - var [v1, v2, v3] = validateAndParse(v); - var [m1, m2, m3] = validateAndParse(r); - if (compareStrings(v1, m1) !== 0) return false; - if (op === '^') { - return compareSegments([v2, v3], [m2, m3]) >= 0; - } - if (compareStrings(v2, m2) !== 0) return false; - return compareStrings(v3, m3) >= 0; - }; - - return compareVersions; -}); +} /***/ }), -/***/ 53921: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 51512: +/***/ ((module, exports) => { "use strict"; -/*! - * content-disposition - * Copyright(c) 2014-2017 Douglas Christopher Wilson - * MIT Licensed - */ - +function _typeof(obj){"@babel/helpers - typeof";if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj}}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj}}return _typeof(obj)}(function(global){var _arguments=arguments;var dateFormat=function(){var token=/d{1,4}|D{3,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|W{1,2}|[LlopSZN]|"[^"]*"|'[^']*'/g;var timezone=/\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g;var timezoneClip=/[^-+\dA-Z]/g;return function(date,mask,utc,gmt){if(_arguments.length===1&&kindOf(date)==="string"&&!/\d/.test(date)){mask=date;date=undefined}date=date||date===0?date:new Date;if(!(date instanceof Date)){date=new Date(date)}if(isNaN(date)){throw TypeError("Invalid date")}mask=String(dateFormat.masks[mask]||mask||dateFormat.masks["default"]);var maskSlice=mask.slice(0,4);if(maskSlice==="UTC:"||maskSlice==="GMT:"){mask=mask.slice(4);utc=true;if(maskSlice==="GMT:"){gmt=true}}var _=function _(){return utc?"getUTC":"get"};var _d=function d(){return date[_()+"Date"]()};var D=function D(){return date[_()+"Day"]()};var _m=function m(){return date[_()+"Month"]()};var y=function y(){return date[_()+"FullYear"]()};var _H=function H(){return date[_()+"Hours"]()};var _M=function M(){return date[_()+"Minutes"]()};var _s=function s(){return date[_()+"Seconds"]()};var _L=function L(){return date[_()+"Milliseconds"]()};var _o=function o(){return utc?0:date.getTimezoneOffset()};var _W=function W(){return getWeek(date)};var _N=function N(){return getDayOfWeek(date)};var flags={d:function d(){return _d()},dd:function dd(){return pad(_d())},ddd:function ddd(){return dateFormat.i18n.dayNames[D()]},DDD:function DDD(){return getDayName({y:y(),m:_m(),d:_d(),_:_(),dayName:dateFormat.i18n.dayNames[D()],short:true})},dddd:function dddd(){return dateFormat.i18n.dayNames[D()+7]},DDDD:function DDDD(){return getDayName({y:y(),m:_m(),d:_d(),_:_(),dayName:dateFormat.i18n.dayNames[D()+7]})},m:function m(){return _m()+1},mm:function mm(){return pad(_m()+1)},mmm:function mmm(){return dateFormat.i18n.monthNames[_m()]},mmmm:function mmmm(){return dateFormat.i18n.monthNames[_m()+12]},yy:function yy(){return String(y()).slice(2)},yyyy:function yyyy(){return pad(y(),4)},h:function h(){return _H()%12||12},hh:function hh(){return pad(_H()%12||12)},H:function H(){return _H()},HH:function HH(){return pad(_H())},M:function M(){return _M()},MM:function MM(){return pad(_M())},s:function s(){return _s()},ss:function ss(){return pad(_s())},l:function l(){return pad(_L(),3)},L:function L(){return pad(Math.floor(_L()/10))},t:function t(){return _H()<12?dateFormat.i18n.timeNames[0]:dateFormat.i18n.timeNames[1]},tt:function tt(){return _H()<12?dateFormat.i18n.timeNames[2]:dateFormat.i18n.timeNames[3]},T:function T(){return _H()<12?dateFormat.i18n.timeNames[4]:dateFormat.i18n.timeNames[5]},TT:function TT(){return _H()<12?dateFormat.i18n.timeNames[6]:dateFormat.i18n.timeNames[7]},Z:function Z(){return gmt?"GMT":utc?"UTC":(String(date).match(timezone)||[""]).pop().replace(timezoneClip,"").replace(/GMT\+0000/g,"UTC")},o:function o(){return(_o()>0?"-":"+")+pad(Math.floor(Math.abs(_o())/60)*100+Math.abs(_o())%60,4)},p:function p(){return(_o()>0?"-":"+")+pad(Math.floor(Math.abs(_o())/60),2)+":"+pad(Math.floor(Math.abs(_o())%60),2)},S:function S(){return["th","st","nd","rd"][_d()%10>3?0:(_d()%100-_d()%10!=10)*_d()%10]},W:function W(){return _W()},WW:function WW(){return pad(_W())},N:function N(){return _N()}};return mask.replace(token,function(match){if(match in flags){return flags[match]()}return match.slice(1,match.length-1)})}}();dateFormat.masks={default:"ddd mmm dd yyyy HH:MM:ss",shortDate:"m/d/yy",paddedShortDate:"mm/dd/yyyy",mediumDate:"mmm d, yyyy",longDate:"mmmm d, yyyy",fullDate:"dddd, mmmm d, yyyy",shortTime:"h:MM TT",mediumTime:"h:MM:ss TT",longTime:"h:MM:ss TT Z",isoDate:"yyyy-mm-dd",isoTime:"HH:MM:ss",isoDateTime:"yyyy-mm-dd'T'HH:MM:sso",isoUtcDateTime:"UTC:yyyy-mm-dd'T'HH:MM:ss'Z'",expiresHeaderFormat:"ddd, dd mmm yyyy HH:MM:ss Z"};dateFormat.i18n={dayNames:["Sun","Mon","Tue","Wed","Thu","Fri","Sat","Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],monthNames:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec","January","February","March","April","May","June","July","August","September","October","November","December"],timeNames:["a","p","am","pm","A","P","AM","PM"]};var pad=function pad(val,len){val=String(val);len=len||2;while(val.length { -module.exports = contentDisposition -module.exports.parse = parse +/* eslint-env browser */ /** - * Module dependencies. - * @private + * This is the web browser implementation of `debug()`. */ -var basename = (__nccwpck_require__(71017).basename) -var Buffer = (__nccwpck_require__(21867).Buffer) +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = localstorage(); +exports.destroy = (() => { + let warned = false; + + return () => { + if (!warned) { + warned = true; + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } + }; +})(); /** - * RegExp to match non attr-char, *after* encodeURIComponent (i.e. not including "%") - * @private + * Colors. */ -var ENCODE_URL_ATTR_CHAR_REGEXP = /[\x00-\x20"'()*,/:;<=>?@[\\\]{}\x7f]/g // eslint-disable-line no-control-regex +exports.colors = [ + '#0000CC', + '#0000FF', + '#0033CC', + '#0033FF', + '#0066CC', + '#0066FF', + '#0099CC', + '#0099FF', + '#00CC00', + '#00CC33', + '#00CC66', + '#00CC99', + '#00CCCC', + '#00CCFF', + '#3300CC', + '#3300FF', + '#3333CC', + '#3333FF', + '#3366CC', + '#3366FF', + '#3399CC', + '#3399FF', + '#33CC00', + '#33CC33', + '#33CC66', + '#33CC99', + '#33CCCC', + '#33CCFF', + '#6600CC', + '#6600FF', + '#6633CC', + '#6633FF', + '#66CC00', + '#66CC33', + '#9900CC', + '#9900FF', + '#9933CC', + '#9933FF', + '#99CC00', + '#99CC33', + '#CC0000', + '#CC0033', + '#CC0066', + '#CC0099', + '#CC00CC', + '#CC00FF', + '#CC3300', + '#CC3333', + '#CC3366', + '#CC3399', + '#CC33CC', + '#CC33FF', + '#CC6600', + '#CC6633', + '#CC9900', + '#CC9933', + '#CCCC00', + '#CCCC33', + '#FF0000', + '#FF0033', + '#FF0066', + '#FF0099', + '#FF00CC', + '#FF00FF', + '#FF3300', + '#FF3333', + '#FF3366', + '#FF3399', + '#FF33CC', + '#FF33FF', + '#FF6600', + '#FF6633', + '#FF9900', + '#FF9933', + '#FFCC00', + '#FFCC33' +]; /** - * RegExp to match percent encoding escape. - * @private + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. + * + * TODO: add a `localStorage` variable to explicitly enable/disable colors */ -var HEX_ESCAPE_REGEXP = /%[0-9A-Fa-f]{2}/ -var HEX_ESCAPE_REPLACE_REGEXP = /%([0-9A-Fa-f]{2})/g +// eslint-disable-next-line complexity +function useColors() { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { + return true; + } -/** - * RegExp to match non-latin1 characters. - * @private - */ + // Internet Explorer and Edge do not support colors. + if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; + } -var NON_LATIN1_REGEXP = /[^\x20-\x7e\xa0-\xff]/g + // Is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || + // Is firebug? http://stackoverflow.com/a/398120/376773 + (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || + // Is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || + // Double check webkit in userAgent just in case we are in a worker + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); +} /** - * RegExp to match quoted-pair in RFC 2616 + * Colorize log arguments if enabled. * - * quoted-pair = "\" CHAR - * CHAR = - * @private + * @api public */ -var QESC_REGEXP = /\\([\u0000-\u007f])/g // eslint-disable-line no-control-regex +function formatArgs(args) { + args[0] = (this.useColors ? '%c' : '') + + this.namespace + + (this.useColors ? ' %c' : ' ') + + args[0] + + (this.useColors ? '%c ' : ' ') + + '+' + module.exports.humanize(this.diff); -/** - * RegExp to match chars that must be quoted-pair in RFC 2616 - * @private - */ + if (!this.useColors) { + return; + } -var QUOTE_REGEXP = /([\\"])/g + const c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit'); -/** - * RegExp for various RFC 2616 grammar - * - * parameter = token "=" ( token | quoted-string ) - * token = 1* - * separators = "(" | ")" | "<" | ">" | "@" - * | "," | ";" | ":" | "\" | <"> - * | "/" | "[" | "]" | "?" | "=" - * | "{" | "}" | SP | HT - * quoted-string = ( <"> *(qdtext | quoted-pair ) <"> ) - * qdtext = > - * quoted-pair = "\" CHAR - * CHAR = - * TEXT = - * LWS = [CRLF] 1*( SP | HT ) - * CRLF = CR LF - * CR = - * LF = - * SP = - * HT = - * CTL = - * OCTET = - * @private - */ + // The final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + let index = 0; + let lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, match => { + if (match === '%%') { + return; + } + index++; + if (match === '%c') { + // We only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); -var PARAM_REGEXP = /;[\x09\x20]*([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*=[\x09\x20]*("(?:[\x20!\x23-\x5b\x5d-\x7e\x80-\xff]|\\[\x20-\x7e])*"|[!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*/g // eslint-disable-line no-control-regex -var TEXT_REGEXP = /^[\x20-\x7e\x80-\xff]+$/ -var TOKEN_REGEXP = /^[!#$%&'*+.0-9A-Z^_`a-z|~-]+$/ + args.splice(lastC, 0, c); +} /** - * RegExp for various RFC 5987 grammar + * Invokes `console.debug()` when available. + * No-op when `console.debug` is not a "function". + * If `console.debug` is not available, falls back + * to `console.log`. * - * ext-value = charset "'" [ language ] "'" value-chars - * charset = "UTF-8" / "ISO-8859-1" / mime-charset - * mime-charset = 1*mime-charsetc - * mime-charsetc = ALPHA / DIGIT - * / "!" / "#" / "$" / "%" / "&" - * / "+" / "-" / "^" / "_" / "`" - * / "{" / "}" / "~" - * language = ( 2*3ALPHA [ extlang ] ) - * / 4ALPHA - * / 5*8ALPHA - * extlang = *3( "-" 3ALPHA ) - * value-chars = *( pct-encoded / attr-char ) - * pct-encoded = "%" HEXDIG HEXDIG - * attr-char = ALPHA / DIGIT - * / "!" / "#" / "$" / "&" / "+" / "-" / "." - * / "^" / "_" / "`" / "|" / "~" - * @private + * @api public */ - -var EXT_VALUE_REGEXP = /^([A-Za-z0-9!#$%&+\-^_`{}~]+)'(?:[A-Za-z]{2,3}(?:-[A-Za-z]{3}){0,3}|[A-Za-z]{4,8}|)'((?:%[0-9A-Fa-f]{2}|[A-Za-z0-9!#$&+.^_`|~-])+)$/ +exports.log = console.debug || console.log || (() => {}); /** - * RegExp for various RFC 6266 grammar + * Save `namespaces`. * - * disposition-type = "inline" | "attachment" | disp-ext-type - * disp-ext-type = token - * disposition-parm = filename-parm | disp-ext-parm - * filename-parm = "filename" "=" value - * | "filename*" "=" ext-value - * disp-ext-parm = token "=" value - * | ext-token "=" ext-value - * ext-token = - * @private + * @param {String} namespaces + * @api private */ - -var DISPOSITION_TYPE_REGEXP = /^([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*(?:$|;)/ // eslint-disable-line no-control-regex +function save(namespaces) { + try { + if (namespaces) { + exports.storage.setItem('debug', namespaces); + } else { + exports.storage.removeItem('debug'); + } + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } +} /** - * Create an attachment Content-Disposition header. + * Load `namespaces`. * - * @param {string} [filename] - * @param {object} [options] - * @param {string} [options.type=attachment] - * @param {string|boolean} [options.fallback=true] - * @return {string} - * @public + * @return {String} returns the previously persisted debug modes + * @api private */ +function load() { + let r; + try { + r = exports.storage.getItem('debug'); + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } -function contentDisposition (filename, options) { - var opts = options || {} - - // get type - var type = opts.type || 'attachment' - - // get parameters - var params = createparams(filename, opts.fallback) + // If debug isn't set in LS, and we're in Electron, try to load $DEBUG + if (!r && typeof process !== 'undefined' && 'env' in process) { + r = process.env.DEBUG; + } - // format into string - return format(new ContentDisposition(type, params)) + return r; } /** - * Create parameters object from filename and fallback. + * Localstorage attempts to return the localstorage. * - * @param {string} [filename] - * @param {string|boolean} [fallback=true] - * @return {object} - * @private + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. + * + * @return {LocalStorage} + * @api private */ -function createparams (filename, fallback) { - if (filename === undefined) { - return - } +function localstorage() { + try { + // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context + // The Browser also has localStorage in the global context. + return localStorage; + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } +} - var params = {} +module.exports = __nccwpck_require__(46243)(exports); - if (typeof filename !== 'string') { - throw new TypeError('filename must be a string') - } +const {formatters} = module.exports; - // fallback defaults to true - if (fallback === undefined) { - fallback = true - } - - if (typeof fallback !== 'string' && typeof fallback !== 'boolean') { - throw new TypeError('fallback must be a string or boolean') - } - - if (typeof fallback === 'string' && NON_LATIN1_REGEXP.test(fallback)) { - throw new TypeError('fallback must be ISO-8859-1 string') - } - - // restrict to file base name - var name = basename(filename) +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ - // determine if name is suitable for quoted string - var isQuotedString = TEXT_REGEXP.test(name) +formatters.j = function (v) { + try { + return JSON.stringify(v); + } catch (error) { + return '[UnexpectedJSONParseError]: ' + error.message; + } +}; - // generate fallback name - var fallbackName = typeof fallback !== 'string' - ? fallback && getlatin1(name) - : basename(fallback) - var hasFallback = typeof fallbackName === 'string' && fallbackName !== name - // set extended filename parameter - if (hasFallback || !isQuotedString || HEX_ESCAPE_REGEXP.test(name)) { - params['filename*'] = name - } +/***/ }), - // set filename parameter - if (isQuotedString || hasFallback) { - params.filename = hasFallback - ? fallbackName - : name - } +/***/ 46243: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return params -} /** - * Format object to Content-Disposition header. - * - * @param {object} obj - * @param {string} obj.type - * @param {object} [obj.parameters] - * @return {string} - * @private + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. */ -function format (obj) { - var parameters = obj.parameters - var type = obj.type - - if (!type || typeof type !== 'string' || !TOKEN_REGEXP.test(type)) { - throw new TypeError('invalid type') - } +function setup(env) { + createDebug.debug = createDebug; + createDebug.default = createDebug; + createDebug.coerce = coerce; + createDebug.disable = disable; + createDebug.enable = enable; + createDebug.enabled = enabled; + createDebug.humanize = __nccwpck_require__(80900); + createDebug.destroy = destroy; - // start with normalized type - var string = String(type).toLowerCase() + Object.keys(env).forEach(key => { + createDebug[key] = env[key]; + }); - // append parameters - if (parameters && typeof parameters === 'object') { - var param - var params = Object.keys(parameters).sort() + /** + * The currently active debug mode names, and names to skip. + */ - for (var i = 0; i < params.length; i++) { - param = params[i] + createDebug.names = []; + createDebug.skips = []; - var val = param.substr(-1) === '*' - ? ustring(parameters[param]) - : qstring(parameters[param]) + /** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + */ + createDebug.formatters = {}; - string += '; ' + param + '=' + val - } - } + /** + * Selects a color for a debug namespace + * @param {String} namespace The namespace string for the debug instance to be colored + * @return {Number|String} An ANSI color code for the given namespace + * @api private + */ + function selectColor(namespace) { + let hash = 0; - return string -} + for (let i = 0; i < namespace.length; i++) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } -/** - * Decode a RFC 5987 field value (gracefully). - * - * @param {string} str - * @return {string} - * @private - */ + return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; + } + createDebug.selectColor = selectColor; -function decodefield (str) { - var match = EXT_VALUE_REGEXP.exec(str) + /** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + function createDebug(namespace) { + let prevTime; + let enableOverride = null; + let namespacesCache; + let enabledCache; - if (!match) { - throw new TypeError('invalid extended field value') - } + function debug(...args) { + // Disabled? + if (!debug.enabled) { + return; + } - var charset = match[1].toLowerCase() - var encoded = match[2] - var value + const self = debug; - // to binary string - var binary = encoded.replace(HEX_ESCAPE_REPLACE_REGEXP, pdecode) + // Set `diff` timestamp + const curr = Number(new Date()); + const ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; - switch (charset) { - case 'iso-8859-1': - value = getlatin1(binary) - break - case 'utf-8': - value = Buffer.from(binary, 'binary').toString('utf8') - break - default: - throw new TypeError('unsupported charset in extended field') - } + args[0] = createDebug.coerce(args[0]); - return value -} + if (typeof args[0] !== 'string') { + // Anything else let's inspect with %O + args.unshift('%O'); + } -/** - * Get ISO-8859-1 version of string. - * - * @param {string} val - * @return {string} - * @private - */ + // Apply any `formatters` transformations + let index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { + // If we encounter an escaped % then don't increase the array index + if (match === '%%') { + return '%'; + } + index++; + const formatter = createDebug.formatters[format]; + if (typeof formatter === 'function') { + const val = args[index]; + match = formatter.call(self, val); -function getlatin1 (val) { - // simple Unicode -> ISO-8859-1 transformation - return String(val).replace(NON_LATIN1_REGEXP, '?') -} + // Now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); -/** - * Parse Content-Disposition header string. - * - * @param {string} string - * @return {object} - * @public - */ + // Apply env-specific formatting (colors, etc.) + createDebug.formatArgs.call(self, args); -function parse (string) { - if (!string || typeof string !== 'string') { - throw new TypeError('argument string is required') - } + const logFn = self.log || createDebug.log; + logFn.apply(self, args); + } - var match = DISPOSITION_TYPE_REGEXP.exec(string) + debug.namespace = namespace; + debug.useColors = createDebug.useColors(); + debug.color = createDebug.selectColor(namespace); + debug.extend = extend; + debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. - if (!match) { - throw new TypeError('invalid type format') - } + Object.defineProperty(debug, 'enabled', { + enumerable: true, + configurable: false, + get: () => { + if (enableOverride !== null) { + return enableOverride; + } + if (namespacesCache !== createDebug.namespaces) { + namespacesCache = createDebug.namespaces; + enabledCache = createDebug.enabled(namespace); + } - // normalize type - var index = match[0].length - var type = match[1].toLowerCase() + return enabledCache; + }, + set: v => { + enableOverride = v; + } + }); - var key - var names = [] - var params = {} - var value + // Env-specific initialization logic for debug instances + if (typeof createDebug.init === 'function') { + createDebug.init(debug); + } - // calculate index to start at - index = PARAM_REGEXP.lastIndex = match[0].substr(-1) === ';' - ? index - 1 - : index + return debug; + } - // match parameters - while ((match = PARAM_REGEXP.exec(string))) { - if (match.index !== index) { - throw new TypeError('invalid parameter format') - } + function extend(namespace, delimiter) { + const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); + newDebug.log = this.log; + return newDebug; + } - index += match[0].length - key = match[1].toLowerCase() - value = match[2] + /** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ + function enable(namespaces) { + createDebug.save(namespaces); + createDebug.namespaces = namespaces; - if (names.indexOf(key) !== -1) { - throw new TypeError('invalid duplicate parameter') - } + createDebug.names = []; + createDebug.skips = []; - names.push(key) + let i; + const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + const len = split.length; - if (key.indexOf('*') + 1 === key.length) { - // decode extended value - key = key.slice(0, -1) - value = decodefield(value) + for (i = 0; i < len; i++) { + if (!split[i]) { + // ignore empty strings + continue; + } - // overwrite existing value - params[key] = value - continue - } + namespaces = split[i].replace(/\*/g, '.*?'); - if (typeof params[key] === 'string') { - continue - } + if (namespaces[0] === '-') { + createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); + } else { + createDebug.names.push(new RegExp('^' + namespaces + '$')); + } + } + } - if (value[0] === '"') { - // remove quotes and escapes - value = value - .substr(1, value.length - 2) - .replace(QESC_REGEXP, '$1') - } + /** + * Disable debug output. + * + * @return {String} namespaces + * @api public + */ + function disable() { + const namespaces = [ + ...createDebug.names.map(toNamespace), + ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) + ].join(','); + createDebug.enable(''); + return namespaces; + } - params[key] = value - } + /** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + function enabled(name) { + if (name[name.length - 1] === '*') { + return true; + } - if (index !== -1 && index !== string.length) { - throw new TypeError('invalid parameter format') - } + let i; + let len; - return new ContentDisposition(type, params) -} + for (i = 0, len = createDebug.skips.length; i < len; i++) { + if (createDebug.skips[i].test(name)) { + return false; + } + } -/** - * Percent decode a single character. - * - * @param {string} str - * @param {string} hex - * @return {string} - * @private - */ + for (i = 0, len = createDebug.names.length; i < len; i++) { + if (createDebug.names[i].test(name)) { + return true; + } + } -function pdecode (str, hex) { - return String.fromCharCode(parseInt(hex, 16)) -} + return false; + } -/** - * Percent encode a single character. - * - * @param {string} char - * @return {string} - * @private - */ + /** + * Convert regexp to namespace + * + * @param {RegExp} regxep + * @return {String} namespace + * @api private + */ + function toNamespace(regexp) { + return regexp.toString() + .substring(2, regexp.toString().length - 2) + .replace(/\.\*\?$/, '*'); + } -function pencode (char) { - return '%' + String(char) - .charCodeAt(0) - .toString(16) - .toUpperCase() -} + /** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + function coerce(val) { + if (val instanceof Error) { + return val.stack || val.message; + } + return val; + } -/** - * Quote a string for HTTP. - * - * @param {string} val - * @return {string} - * @private - */ + /** + * XXX DO NOT USE. This is a temporary stub function. + * XXX It WILL be removed in the next major release. + */ + function destroy() { + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } -function qstring (val) { - var str = String(val) + createDebug.enable(createDebug.load()); - return '"' + str.replace(QUOTE_REGEXP, '\\$1') + '"' + return createDebug; } -/** - * Encode a Unicode string for HTTP (RFC 5987). - * - * @param {string} val - * @return {string} - * @private - */ +module.exports = setup; -function ustring (val) { - var str = String(val) - // percent encode as UTF-8 - var encoded = encodeURIComponent(str) - .replace(ENCODE_URL_ATTR_CHAR_REGEXP, pencode) +/***/ }), - return 'UTF-8\'\'' + encoded -} +/***/ 38237: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { /** - * Class for parsed Content-Disposition header for v8 optimization - * - * @public - * @param {string} type - * @param {object} parameters - * @constructor + * Detect Electron renderer / nwjs process, which is node, but we should + * treat as a browser. */ -function ContentDisposition (type, parameters) { - this.type = type - this.parameters = parameters +if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { + module.exports = __nccwpck_require__(28222); +} else { + module.exports = __nccwpck_require__(35332); } /***/ }), -/***/ 99915: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; -/*! - * content-type - * Copyright(c) 2015 Douglas Christopher Wilson - * MIT Licensed - */ - - +/***/ 35332: +/***/ ((module, exports, __nccwpck_require__) => { /** - * RegExp to match *( ";" parameter ) in RFC 7231 sec 3.1.1.1 - * - * parameter = token "=" ( token / quoted-string ) - * token = 1*tchar - * tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" - * / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" - * / DIGIT / ALPHA - * ; any VCHAR, except delimiters - * quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE - * qdtext = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text - * obs-text = %x80-FF - * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) + * Module dependencies. */ -var PARAM_REGEXP = /; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g -var TEXT_REGEXP = /^[\u000b\u0020-\u007e\u0080-\u00ff]+$/ -var TOKEN_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/ -/** - * RegExp to match quoted-pair in RFC 7230 sec 3.2.6 - * - * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) - * obs-text = %x80-FF - */ -var QESC_REGEXP = /\\([\u000b\u0020-\u00ff])/g +const tty = __nccwpck_require__(76224); +const util = __nccwpck_require__(73837); /** - * RegExp to match chars that must be quoted-pair in RFC 7230 sec 3.2.6 - */ -var QUOTE_REGEXP = /([\\"])/g - -/** - * RegExp to match type in RFC 7231 sec 3.1.1.1 - * - * media-type = type "/" subtype - * type = token - * subtype = token - */ -var TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/ - -/** - * Module exports. - * @public + * This is the Node.js implementation of `debug()`. */ -exports.format = format -exports.parse = parse +exports.init = init; +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.destroy = util.deprecate( + () => {}, + 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' +); /** - * Format object to media type. - * - * @param {object} obj - * @return {string} - * @public + * Colors. */ -function format (obj) { - if (!obj || typeof obj !== 'object') { - throw new TypeError('argument obj is required') - } - - var parameters = obj.parameters - var type = obj.type - - if (!type || !TYPE_REGEXP.test(type)) { - throw new TypeError('invalid type') - } - - var string = type - - // append parameters - if (parameters && typeof parameters === 'object') { - var param - var params = Object.keys(parameters).sort() - - for (var i = 0; i < params.length; i++) { - param = params[i] - - if (!TOKEN_REGEXP.test(param)) { - throw new TypeError('invalid parameter name') - } +exports.colors = [6, 2, 3, 4, 5, 1]; - string += '; ' + param + '=' + qstring(parameters[param]) - } - } +try { + // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) + // eslint-disable-next-line import/no-extraneous-dependencies + const supportsColor = __nccwpck_require__(59318); - return string + if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { + exports.colors = [ + 20, + 21, + 26, + 27, + 32, + 33, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 56, + 57, + 62, + 63, + 68, + 69, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 92, + 93, + 98, + 99, + 112, + 113, + 128, + 129, + 134, + 135, + 148, + 149, + 160, + 161, + 162, + 163, + 164, + 165, + 166, + 167, + 168, + 169, + 170, + 171, + 172, + 173, + 178, + 179, + 184, + 185, + 196, + 197, + 198, + 199, + 200, + 201, + 202, + 203, + 204, + 205, + 206, + 207, + 208, + 209, + 214, + 215, + 220, + 221 + ]; + } +} catch (error) { + // Swallow - we only care if `supports-color` is available; it doesn't have to be. } /** - * Parse media type to object. + * Build up the default `inspectOpts` object from the environment variables. * - * @param {string|object} string - * @return {Object} - * @public + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js */ -function parse (string) { - if (!string) { - throw new TypeError('argument string is required') - } - - // support req/res-like objects as argument - var header = typeof string === 'object' - ? getcontenttype(string) - : string - - if (typeof header !== 'string') { - throw new TypeError('argument string is required to be a string') - } - - var index = header.indexOf(';') - var type = index !== -1 - ? header.substr(0, index).trim() - : header.trim() - - if (!TYPE_REGEXP.test(type)) { - throw new TypeError('invalid media type') - } - - var obj = new ContentType(type.toLowerCase()) - - // parse parameters - if (index !== -1) { - var key - var match - var value - - PARAM_REGEXP.lastIndex = index - - while ((match = PARAM_REGEXP.exec(header))) { - if (match.index !== index) { - throw new TypeError('invalid parameter format') - } - - index += match[0].length - key = match[1].toLowerCase() - value = match[2] - - if (value[0] === '"') { - // remove quotes and escapes - value = value - .substr(1, value.length - 2) - .replace(QESC_REGEXP, '$1') - } - - obj.parameters[key] = value - } +exports.inspectOpts = Object.keys(process.env).filter(key => { + return /^debug_/i.test(key); +}).reduce((obj, key) => { + // Camel-case + const prop = key + .substring(6) + .toLowerCase() + .replace(/_([a-z])/g, (_, k) => { + return k.toUpperCase(); + }); - if (index !== header.length) { - throw new TypeError('invalid parameter format') - } - } + // Coerce string value into JS value + let val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) { + val = true; + } else if (/^(no|off|false|disabled)$/i.test(val)) { + val = false; + } else if (val === 'null') { + val = null; + } else { + val = Number(val); + } - return obj -} + obj[prop] = val; + return obj; +}, {}); /** - * Get content-type from req/res objects. - * - * @param {object} - * @return {Object} - * @private + * Is stdout a TTY? Colored output is enabled when `true`. */ -function getcontenttype (obj) { - var header - - if (typeof obj.getHeader === 'function') { - // res-like - header = obj.getHeader('content-type') - } else if (typeof obj.headers === 'object') { - // req-like - header = obj.headers && obj.headers['content-type'] - } - - if (typeof header !== 'string') { - throw new TypeError('content-type header is missing from object') - } - - return header +function useColors() { + return 'colors' in exports.inspectOpts ? + Boolean(exports.inspectOpts.colors) : + tty.isatty(process.stderr.fd); } /** - * Quote a string if necessary. + * Adds ANSI color escape codes if enabled. * - * @param {string} val - * @return {string} - * @private + * @api public */ -function qstring (val) { - var str = String(val) - - // no need to quote tokens - if (TOKEN_REGEXP.test(str)) { - return str - } +function formatArgs(args) { + const {namespace: name, useColors} = this; - if (str.length > 0 && !TEXT_REGEXP.test(str)) { - throw new TypeError('invalid parameter value') - } + if (useColors) { + const c = this.color; + const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); + const prefix = ` ${colorCode};1m${name} \u001B[0m`; - return '"' + str.replace(QUOTE_REGEXP, '\\$1') + '"' + args[0] = prefix + args[0].split('\n').join('\n' + prefix); + args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); + } else { + args[0] = getDate() + name + ' ' + args[0]; + } } -/** - * Class to represent a content type. - * @private - */ -function ContentType (type) { - this.parameters = Object.create(null) - this.type = type +function getDate() { + if (exports.inspectOpts.hideDate) { + return ''; + } + return new Date().toISOString() + ' '; } - -/***/ }), - -/***/ 61579: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - /** - * Module dependencies. + * Invokes `util.format()` with the specified arguments and writes to stderr. */ -var crypto = __nccwpck_require__(6113); +function log(...args) { + return process.stderr.write(util.format(...args) + '\n'); +} /** - * Sign the given `val` with `secret`. + * Save `namespaces`. * - * @param {String} val - * @param {String} secret - * @return {String} + * @param {String} namespaces * @api private */ - -exports.sign = function(val, secret){ - if ('string' != typeof val) throw new TypeError("Cookie value must be provided as a string."); - if ('string' != typeof secret) throw new TypeError("Secret string must be provided."); - return val + '.' + crypto - .createHmac('sha256', secret) - .update(val) - .digest('base64') - .replace(/\=+$/, ''); -}; +function save(namespaces) { + if (namespaces) { + process.env.DEBUG = namespaces; + } else { + // If you set a process.env field to null or undefined, it gets cast to the + // string 'null' or 'undefined'. Just delete instead. + delete process.env.DEBUG; + } +} /** - * Unsign and decode the given `val` with `secret`, - * returning `false` if the signature is invalid. + * Load `namespaces`. * - * @param {String} val - * @param {String} secret - * @return {String|Boolean} + * @return {String} returns the previously persisted debug modes * @api private */ -exports.unsign = function(val, secret){ - if ('string' != typeof val) throw new TypeError("Signed cookie string must be provided."); - if ('string' != typeof secret) throw new TypeError("Secret string must be provided."); - var str = val.slice(0, val.lastIndexOf('.')) - , mac = exports.sign(str, secret); - - return sha1(mac) == sha1(val) ? str : false; -}; +function load() { + return process.env.DEBUG; +} /** - * Private + * Init logic for `debug` instances. + * + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. */ -function sha1(str){ - return crypto.createHash('sha1').update(str).digest('hex'); -} - - -/***/ }), - -/***/ 93658: -/***/ ((__unused_webpack_module, exports) => { +function init(debug) { + debug.inspectOpts = {}; -"use strict"; -/*! - * cookie - * Copyright(c) 2012-2014 Roman Shtylman - * Copyright(c) 2015 Douglas Christopher Wilson - * MIT Licensed - */ + const keys = Object.keys(exports.inspectOpts); + for (let i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } +} +module.exports = __nccwpck_require__(46243)(exports); +const {formatters} = module.exports; /** - * Module exports. - * @public + * Map %o to `util.inspect()`, all on a single line. */ -exports.parse = parse; -exports.serialize = serialize; +formatters.o = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts) + .split('\n') + .map(str => str.trim()) + .join(' '); +}; /** - * Module variables. - * @private + * Map %O to `util.inspect()`, allowing multiple lines if needed. */ -var decode = decodeURIComponent; -var encode = encodeURIComponent; -var pairSplitRegExp = /; */; +formatters.O = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); +}; -/** - * RegExp to match field-content in RFC 7230 sec 3.2 - * - * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] - * field-vchar = VCHAR / obs-text - * obs-text = %x80-FF - */ -var fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/; +/***/ }), -/** - * Parse a cookie header. - * - * Parse the given cookie header string into an object - * The object has the various cookies as keys(names) => values - * - * @param {string} str - * @param {object} [options] - * @return {object} - * @public - */ +/***/ 56323: +/***/ ((module) => { -function parse(str, options) { - if (typeof str !== 'string') { - throw new TypeError('argument str must be a string'); - } +"use strict"; - var obj = {} - var opt = options || {}; - var pairs = str.split(pairSplitRegExp); - var dec = opt.decode || decode; - for (var i = 0; i < pairs.length; i++) { - var pair = pairs[i]; - var eq_idx = pair.indexOf('='); +var isMergeableObject = function isMergeableObject(value) { + return isNonNullObject(value) + && !isSpecial(value) +}; - // skip things that don't look like key=value - if (eq_idx < 0) { - continue; - } +function isNonNullObject(value) { + return !!value && typeof value === 'object' +} - var key = pair.substr(0, eq_idx).trim() - var val = pair.substr(++eq_idx, pair.length).trim(); +function isSpecial(value) { + var stringValue = Object.prototype.toString.call(value); - // quoted values - if ('"' == val[0]) { - val = val.slice(1, -1); - } + return stringValue === '[object RegExp]' + || stringValue === '[object Date]' + || isReactElement(value) +} - // only assign once - if (undefined == obj[key]) { - obj[key] = tryDecode(val, dec); - } - } +// see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25 +var canUseSymbol = typeof Symbol === 'function' && Symbol.for; +var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7; - return obj; +function isReactElement(value) { + return value.$$typeof === REACT_ELEMENT_TYPE } -/** - * Serialize data into a cookie header. - * - * Serialize the a name value pair into a cookie string suitable for - * http headers. An optional options object specified cookie parameters. - * - * serialize('foo', 'bar', { httpOnly: true }) - * => "foo=bar; httpOnly" - * - * @param {string} name - * @param {string} val - * @param {object} [options] - * @return {string} - * @public - */ +function emptyTarget(val) { + return Array.isArray(val) ? [] : {} +} -function serialize(name, val, options) { - var opt = options || {}; - var enc = opt.encode || encode; +function cloneUnlessOtherwiseSpecified(value, options) { + return (options.clone !== false && options.isMergeableObject(value)) + ? deepmerge(emptyTarget(value), value, options) + : value +} - if (typeof enc !== 'function') { - throw new TypeError('option encode is invalid'); - } +function defaultArrayMerge(target, source, options) { + return target.concat(source).map(function(element) { + return cloneUnlessOtherwiseSpecified(element, options) + }) +} - if (!fieldContentRegExp.test(name)) { - throw new TypeError('argument name is invalid'); - } +function getMergeFunction(key, options) { + if (!options.customMerge) { + return deepmerge + } + var customMerge = options.customMerge(key); + return typeof customMerge === 'function' ? customMerge : deepmerge +} - var value = enc(val); +function getEnumerableOwnPropertySymbols(target) { + return Object.getOwnPropertySymbols + ? Object.getOwnPropertySymbols(target).filter(function(symbol) { + return target.propertyIsEnumerable(symbol) + }) + : [] +} - if (value && !fieldContentRegExp.test(value)) { - throw new TypeError('argument val is invalid'); - } +function getKeys(target) { + return Object.keys(target).concat(getEnumerableOwnPropertySymbols(target)) +} - var str = name + '=' + value; +function propertyIsOnObject(object, property) { + try { + return property in object + } catch(_) { + return false + } +} - if (null != opt.maxAge) { - var maxAge = opt.maxAge - 0; +// Protects from prototype poisoning and unexpected merging up the prototype chain. +function propertyIsUnsafe(target, key) { + return propertyIsOnObject(target, key) // Properties are safe to merge if they don't exist in the target yet, + && !(Object.hasOwnProperty.call(target, key) // unsafe if they exist up the prototype chain, + && Object.propertyIsEnumerable.call(target, key)) // and also unsafe if they're nonenumerable. +} - if (isNaN(maxAge) || !isFinite(maxAge)) { - throw new TypeError('option maxAge is invalid') - } +function mergeObject(target, source, options) { + var destination = {}; + if (options.isMergeableObject(target)) { + getKeys(target).forEach(function(key) { + destination[key] = cloneUnlessOtherwiseSpecified(target[key], options); + }); + } + getKeys(source).forEach(function(key) { + if (propertyIsUnsafe(target, key)) { + return + } - str += '; Max-Age=' + Math.floor(maxAge); - } + if (propertyIsOnObject(target, key) && options.isMergeableObject(source[key])) { + destination[key] = getMergeFunction(key, options)(target[key], source[key], options); + } else { + destination[key] = cloneUnlessOtherwiseSpecified(source[key], options); + } + }); + return destination +} - if (opt.domain) { - if (!fieldContentRegExp.test(opt.domain)) { - throw new TypeError('option domain is invalid'); - } +function deepmerge(target, source, options) { + options = options || {}; + options.arrayMerge = options.arrayMerge || defaultArrayMerge; + options.isMergeableObject = options.isMergeableObject || isMergeableObject; + // cloneUnlessOtherwiseSpecified is added to `options` so that custom arrayMerge() + // implementations can use it. The caller may not replace it. + options.cloneUnlessOtherwiseSpecified = cloneUnlessOtherwiseSpecified; - str += '; Domain=' + opt.domain; - } + var sourceIsArray = Array.isArray(source); + var targetIsArray = Array.isArray(target); + var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray; - if (opt.path) { - if (!fieldContentRegExp.test(opt.path)) { - throw new TypeError('option path is invalid'); - } + if (!sourceAndTargetTypesMatch) { + return cloneUnlessOtherwiseSpecified(source, options) + } else if (sourceIsArray) { + return options.arrayMerge(target, source, options) + } else { + return mergeObject(target, source, options) + } +} - str += '; Path=' + opt.path; - } +deepmerge.all = function deepmergeAll(array, options) { + if (!Array.isArray(array)) { + throw new Error('first argument should be an array') + } - if (opt.expires) { - if (typeof opt.expires.toUTCString !== 'function') { - throw new TypeError('option expires is invalid'); - } + return array.reduce(function(prev, next) { + return deepmerge(prev, next, options) + }, {}) +}; - str += '; Expires=' + opt.expires.toUTCString(); - } +var deepmerge_1 = deepmerge; - if (opt.httpOnly) { - str += '; HttpOnly'; - } +module.exports = deepmerge_1; - if (opt.secure) { - str += '; Secure'; - } - if (opt.sameSite) { - var sameSite = typeof opt.sameSite === 'string' - ? opt.sameSite.toLowerCase() : opt.sameSite; +/***/ }), - switch (sameSite) { - case true: - str += '; SameSite=Strict'; - break; - case 'lax': - str += '; SameSite=Lax'; - break; - case 'strict': - str += '; SameSite=Strict'; - break; - case 'none': - str += '; SameSite=None'; - break; - default: - throw new TypeError('option sameSite is invalid'); - } - } +/***/ 42342: +/***/ ((module) => { + +"use strict"; - return str; -} /** - * Try decoding a string using a decoding function. - * - * @param {string} str - * @param {function} decode - * @private + * Custom implementation of a double ended queue. */ +function Denque(array, options) { + var options = options || {}; -function tryDecode(str, decode) { - try { - return decode(str); - } catch (e) { - return str; + this._head = 0; + this._tail = 0; + this._capacity = options.capacity; + this._capacityMask = 0x3; + this._list = new Array(4); + if (Array.isArray(array)) { + this._fromArray(array); } } - -/***/ }), - -/***/ 51512: -/***/ ((module, exports) => { - -"use strict"; -function _typeof(obj){"@babel/helpers - typeof";if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj}}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj}}return _typeof(obj)}(function(global){var _arguments=arguments;var dateFormat=function(){var token=/d{1,4}|D{3,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|W{1,2}|[LlopSZN]|"[^"]*"|'[^']*'/g;var timezone=/\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g;var timezoneClip=/[^-+\dA-Z]/g;return function(date,mask,utc,gmt){if(_arguments.length===1&&kindOf(date)==="string"&&!/\d/.test(date)){mask=date;date=undefined}date=date||date===0?date:new Date;if(!(date instanceof Date)){date=new Date(date)}if(isNaN(date)){throw TypeError("Invalid date")}mask=String(dateFormat.masks[mask]||mask||dateFormat.masks["default"]);var maskSlice=mask.slice(0,4);if(maskSlice==="UTC:"||maskSlice==="GMT:"){mask=mask.slice(4);utc=true;if(maskSlice==="GMT:"){gmt=true}}var _=function _(){return utc?"getUTC":"get"};var _d=function d(){return date[_()+"Date"]()};var D=function D(){return date[_()+"Day"]()};var _m=function m(){return date[_()+"Month"]()};var y=function y(){return date[_()+"FullYear"]()};var _H=function H(){return date[_()+"Hours"]()};var _M=function M(){return date[_()+"Minutes"]()};var _s=function s(){return date[_()+"Seconds"]()};var _L=function L(){return date[_()+"Milliseconds"]()};var _o=function o(){return utc?0:date.getTimezoneOffset()};var _W=function W(){return getWeek(date)};var _N=function N(){return getDayOfWeek(date)};var flags={d:function d(){return _d()},dd:function dd(){return pad(_d())},ddd:function ddd(){return dateFormat.i18n.dayNames[D()]},DDD:function DDD(){return getDayName({y:y(),m:_m(),d:_d(),_:_(),dayName:dateFormat.i18n.dayNames[D()],short:true})},dddd:function dddd(){return dateFormat.i18n.dayNames[D()+7]},DDDD:function DDDD(){return getDayName({y:y(),m:_m(),d:_d(),_:_(),dayName:dateFormat.i18n.dayNames[D()+7]})},m:function m(){return _m()+1},mm:function mm(){return pad(_m()+1)},mmm:function mmm(){return dateFormat.i18n.monthNames[_m()]},mmmm:function mmmm(){return dateFormat.i18n.monthNames[_m()+12]},yy:function yy(){return String(y()).slice(2)},yyyy:function yyyy(){return pad(y(),4)},h:function h(){return _H()%12||12},hh:function hh(){return pad(_H()%12||12)},H:function H(){return _H()},HH:function HH(){return pad(_H())},M:function M(){return _M()},MM:function MM(){return pad(_M())},s:function s(){return _s()},ss:function ss(){return pad(_s())},l:function l(){return pad(_L(),3)},L:function L(){return pad(Math.floor(_L()/10))},t:function t(){return _H()<12?dateFormat.i18n.timeNames[0]:dateFormat.i18n.timeNames[1]},tt:function tt(){return _H()<12?dateFormat.i18n.timeNames[2]:dateFormat.i18n.timeNames[3]},T:function T(){return _H()<12?dateFormat.i18n.timeNames[4]:dateFormat.i18n.timeNames[5]},TT:function TT(){return _H()<12?dateFormat.i18n.timeNames[6]:dateFormat.i18n.timeNames[7]},Z:function Z(){return gmt?"GMT":utc?"UTC":(String(date).match(timezone)||[""]).pop().replace(timezoneClip,"").replace(/GMT\+0000/g,"UTC")},o:function o(){return(_o()>0?"-":"+")+pad(Math.floor(Math.abs(_o())/60)*100+Math.abs(_o())%60,4)},p:function p(){return(_o()>0?"-":"+")+pad(Math.floor(Math.abs(_o())/60),2)+":"+pad(Math.floor(Math.abs(_o())%60),2)},S:function S(){return["th","st","nd","rd"][_d()%10>3?0:(_d()%100-_d()%10!=10)*_d()%10]},W:function W(){return _W()},WW:function WW(){return pad(_W())},N:function N(){return _N()}};return mask.replace(token,function(match){if(match in flags){return flags[match]()}return match.slice(1,match.length-1)})}}();dateFormat.masks={default:"ddd mmm dd yyyy HH:MM:ss",shortDate:"m/d/yy",paddedShortDate:"mm/dd/yyyy",mediumDate:"mmm d, yyyy",longDate:"mmmm d, yyyy",fullDate:"dddd, mmmm d, yyyy",shortTime:"h:MM TT",mediumTime:"h:MM:ss TT",longTime:"h:MM:ss TT Z",isoDate:"yyyy-mm-dd",isoTime:"HH:MM:ss",isoDateTime:"yyyy-mm-dd'T'HH:MM:sso",isoUtcDateTime:"UTC:yyyy-mm-dd'T'HH:MM:ss'Z'",expiresHeaderFormat:"ddd, dd mmm yyyy HH:MM:ss Z"};dateFormat.i18n={dayNames:["Sun","Mon","Tue","Wed","Thu","Fri","Sat","Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],monthNames:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec","January","February","March","April","May","June","July","August","September","October","November","December"],timeNames:["a","p","am","pm","A","P","AM","PM"]};var pad=function pad(val,len){val=String(val);len=len||2;while(val.length { - -/* eslint-env browser */ - /** - * This is the web browser implementation of `debug()`. + * ------------- + * PUBLIC API + * ------------- */ -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.storage = localstorage(); -exports.destroy = (() => { - let warned = false; - - return () => { - if (!warned) { - warned = true; - console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); - } - }; -})(); - /** - * Colors. + * Returns the item at the specified index from the list. + * 0 is the first element, 1 is the second, and so on... + * Elements at negative values are that many from the end: -1 is one before the end + * (the last element), -2 is two before the end (one before last), etc. + * @param index + * @returns {*} */ - -exports.colors = [ - '#0000CC', - '#0000FF', - '#0033CC', - '#0033FF', - '#0066CC', - '#0066FF', - '#0099CC', - '#0099FF', - '#00CC00', - '#00CC33', - '#00CC66', - '#00CC99', - '#00CCCC', - '#00CCFF', - '#3300CC', - '#3300FF', - '#3333CC', - '#3333FF', - '#3366CC', - '#3366FF', - '#3399CC', - '#3399FF', - '#33CC00', - '#33CC33', - '#33CC66', - '#33CC99', - '#33CCCC', - '#33CCFF', - '#6600CC', - '#6600FF', - '#6633CC', - '#6633FF', - '#66CC00', - '#66CC33', - '#9900CC', - '#9900FF', - '#9933CC', - '#9933FF', - '#99CC00', - '#99CC33', - '#CC0000', - '#CC0033', - '#CC0066', - '#CC0099', - '#CC00CC', - '#CC00FF', - '#CC3300', - '#CC3333', - '#CC3366', - '#CC3399', - '#CC33CC', - '#CC33FF', - '#CC6600', - '#CC6633', - '#CC9900', - '#CC9933', - '#CCCC00', - '#CCCC33', - '#FF0000', - '#FF0033', - '#FF0066', - '#FF0099', - '#FF00CC', - '#FF00FF', - '#FF3300', - '#FF3333', - '#FF3366', - '#FF3399', - '#FF33CC', - '#FF33FF', - '#FF6600', - '#FF6633', - '#FF9900', - '#FF9933', - '#FFCC00', - '#FFCC33' -]; +Denque.prototype.peekAt = function peekAt(index) { + var i = index; + // expect a number or return undefined + if ((i !== (i | 0))) { + return void 0; + } + var len = this.size(); + if (i >= len || i < -len) return undefined; + if (i < 0) i += len; + i = (this._head + i) & this._capacityMask; + return this._list[i]; +}; /** - * Currently only WebKit-based Web Inspectors, Firefox >= v31, - * and the Firebug extension (any Firefox version) are known - * to support "%c" CSS customizations. - * - * TODO: add a `localStorage` variable to explicitly enable/disable colors + * Alias for peekAt() + * @param i + * @returns {*} */ - -// eslint-disable-next-line complexity -function useColors() { - // NB: In an Electron preload script, document will be defined but not fully - // initialized. Since we know we're in Chrome, we'll just detect this case - // explicitly - if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { - return true; - } - - // Internet Explorer and Edge do not support colors. - if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { - return false; - } - - // Is webkit? http://stackoverflow.com/a/16459606/376773 - // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 - return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || - // Is firebug? http://stackoverflow.com/a/398120/376773 - (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || - // Is firefox >= v31? - // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || - // Double check webkit in userAgent just in case we are in a worker - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); -} +Denque.prototype.get = function get(i) { + return this.peekAt(i); +}; /** - * Colorize log arguments if enabled. - * - * @api public + * Returns the first item in the list without removing it. + * @returns {*} */ - -function formatArgs(args) { - args[0] = (this.useColors ? '%c' : '') + - this.namespace + - (this.useColors ? ' %c' : ' ') + - args[0] + - (this.useColors ? '%c ' : ' ') + - '+' + module.exports.humanize(this.diff); - - if (!this.useColors) { - return; - } - - const c = 'color: ' + this.color; - args.splice(1, 0, c, 'color: inherit'); - - // The final "%c" is somewhat tricky, because there could be other - // arguments passed either before or after the %c, so we need to - // figure out the correct index to insert the CSS into - let index = 0; - let lastC = 0; - args[0].replace(/%[a-zA-Z%]/g, match => { - if (match === '%%') { - return; - } - index++; - if (match === '%c') { - // We only are interested in the *last* %c - // (the user may have provided their own) - lastC = index; - } - }); - - args.splice(lastC, 0, c); -} +Denque.prototype.peek = function peek() { + if (this._head === this._tail) return undefined; + return this._list[this._head]; +}; /** - * Invokes `console.debug()` when available. - * No-op when `console.debug` is not a "function". - * If `console.debug` is not available, falls back - * to `console.log`. - * - * @api public + * Alias for peek() + * @returns {*} */ -exports.log = console.debug || console.log || (() => {}); +Denque.prototype.peekFront = function peekFront() { + return this.peek(); +}; /** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private + * Returns the item that is at the back of the queue without removing it. + * Uses peekAt(-1) */ -function save(namespaces) { - try { - if (namespaces) { - exports.storage.setItem('debug', namespaces); - } else { - exports.storage.removeItem('debug'); - } - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } -} +Denque.prototype.peekBack = function peekBack() { + return this.peekAt(-1); +}; /** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private + * Returns the current length of the queue + * @return {Number} */ -function load() { - let r; - try { - r = exports.storage.getItem('debug'); - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } - - // If debug isn't set in LS, and we're in Electron, try to load $DEBUG - if (!r && typeof process !== 'undefined' && 'env' in process) { - r = process.env.DEBUG; - } - - return r; -} +Object.defineProperty(Denque.prototype, 'length', { + get: function length() { + return this.size(); + } +}); /** - * Localstorage attempts to return the localstorage. - * - * This is necessary because safari throws - * when a user disables cookies/localstorage - * and you attempt to access it. - * - * @return {LocalStorage} - * @api private + * Return the number of items on the list, or 0 if empty. + * @returns {number} */ - -function localstorage() { - try { - // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context - // The Browser also has localStorage in the global context. - return localStorage; - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } -} - -module.exports = __nccwpck_require__(46243)(exports); - -const {formatters} = module.exports; +Denque.prototype.size = function size() { + if (this._head === this._tail) return 0; + if (this._head < this._tail) return this._tail - this._head; + else return this._capacityMask + 1 - (this._head - this._tail); +}; /** - * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + * Add an item at the beginning of the list. + * @param item */ - -formatters.j = function (v) { - try { - return JSON.stringify(v); - } catch (error) { - return '[UnexpectedJSONParseError]: ' + error.message; - } +Denque.prototype.unshift = function unshift(item) { + if (item === undefined) return this.size(); + var len = this._list.length; + this._head = (this._head - 1 + len) & this._capacityMask; + this._list[this._head] = item; + if (this._tail === this._head) this._growArray(); + if (this._capacity && this.size() > this._capacity) this.pop(); + if (this._head < this._tail) return this._tail - this._head; + else return this._capacityMask + 1 - (this._head - this._tail); }; - -/***/ }), - -/***/ 46243: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - /** - * This is the common logic for both the Node.js and web browser - * implementations of `debug()`. + * Remove and return the first item on the list, + * Returns undefined if the list is empty. + * @returns {*} */ +Denque.prototype.shift = function shift() { + var head = this._head; + if (head === this._tail) return undefined; + var item = this._list[head]; + this._list[head] = undefined; + this._head = (head + 1) & this._capacityMask; + if (head < 2 && this._tail > 10000 && this._tail <= this._list.length >>> 2) this._shrinkArray(); + return item; +}; -function setup(env) { - createDebug.debug = createDebug; - createDebug.default = createDebug; - createDebug.coerce = coerce; - createDebug.disable = disable; - createDebug.enable = enable; - createDebug.enabled = enabled; - createDebug.humanize = __nccwpck_require__(80900); - createDebug.destroy = destroy; +/** + * Add an item to the bottom of the list. + * @param item + */ +Denque.prototype.push = function push(item) { + if (item === undefined) return this.size(); + var tail = this._tail; + this._list[tail] = item; + this._tail = (tail + 1) & this._capacityMask; + if (this._tail === this._head) { + this._growArray(); + } + if (this._capacity && this.size() > this._capacity) { + this.shift(); + } + if (this._head < this._tail) return this._tail - this._head; + else return this._capacityMask + 1 - (this._head - this._tail); +}; - Object.keys(env).forEach(key => { - createDebug[key] = env[key]; - }); +/** + * Remove and return the last item on the list. + * Returns undefined if the list is empty. + * @returns {*} + */ +Denque.prototype.pop = function pop() { + var tail = this._tail; + if (tail === this._head) return undefined; + var len = this._list.length; + this._tail = (tail - 1 + len) & this._capacityMask; + var item = this._list[this._tail]; + this._list[this._tail] = undefined; + if (this._head < 2 && tail > 10000 && tail <= len >>> 2) this._shrinkArray(); + return item; +}; - /** - * The currently active debug mode names, and names to skip. - */ +/** + * Remove and return the item at the specified index from the list. + * Returns undefined if the list is empty. + * @param index + * @returns {*} + */ +Denque.prototype.removeOne = function removeOne(index) { + var i = index; + // expect a number or return undefined + if ((i !== (i | 0))) { + return void 0; + } + if (this._head === this._tail) return void 0; + var size = this.size(); + var len = this._list.length; + if (i >= size || i < -size) return void 0; + if (i < 0) i += size; + i = (this._head + i) & this._capacityMask; + var item = this._list[i]; + var k; + if (index < size / 2) { + for (k = index; k > 0; k--) { + this._list[i] = this._list[i = (i - 1 + len) & this._capacityMask]; + } + this._list[i] = void 0; + this._head = (this._head + 1 + len) & this._capacityMask; + } else { + for (k = size - 1 - index; k > 0; k--) { + this._list[i] = this._list[i = ( i + 1 + len) & this._capacityMask]; + } + this._list[i] = void 0; + this._tail = (this._tail - 1 + len) & this._capacityMask; + } + return item; +}; - createDebug.names = []; - createDebug.skips = []; +/** + * Remove number of items from the specified index from the list. + * Returns array of removed items. + * Returns undefined if the list is empty. + * @param index + * @param count + * @returns {array} + */ +Denque.prototype.remove = function remove(index, count) { + var i = index; + var removed; + var del_count = count; + // expect a number or return undefined + if ((i !== (i | 0))) { + return void 0; + } + if (this._head === this._tail) return void 0; + var size = this.size(); + var len = this._list.length; + if (i >= size || i < -size || count < 1) return void 0; + if (i < 0) i += size; + if (count === 1 || !count) { + removed = new Array(1); + removed[0] = this.removeOne(i); + return removed; + } + if (i === 0 && i + count >= size) { + removed = this.toArray(); + this.clear(); + return removed; + } + if (i + count > size) count = size - i; + var k; + removed = new Array(count); + for (k = 0; k < count; k++) { + removed[k] = this._list[(this._head + i + k) & this._capacityMask]; + } + i = (this._head + i) & this._capacityMask; + if (index + count === size) { + this._tail = (this._tail - count + len) & this._capacityMask; + for (k = count; k > 0; k--) { + this._list[i = (i + 1 + len) & this._capacityMask] = void 0; + } + return removed; + } + if (index === 0) { + this._head = (this._head + count + len) & this._capacityMask; + for (k = count - 1; k > 0; k--) { + this._list[i = (i + 1 + len) & this._capacityMask] = void 0; + } + return removed; + } + if (i < size / 2) { + this._head = (this._head + index + count + len) & this._capacityMask; + for (k = index; k > 0; k--) { + this.unshift(this._list[i = (i - 1 + len) & this._capacityMask]); + } + i = (this._head - 1 + len) & this._capacityMask; + while (del_count > 0) { + this._list[i = (i - 1 + len) & this._capacityMask] = void 0; + del_count--; + } + if (index < 0) this._tail = i; + } else { + this._tail = i; + i = (i + count + len) & this._capacityMask; + for (k = size - (count + index); k > 0; k--) { + this.push(this._list[i++]); + } + i = this._tail; + while (del_count > 0) { + this._list[i = (i + 1 + len) & this._capacityMask] = void 0; + del_count--; + } + } + if (this._head < 2 && this._tail > 10000 && this._tail <= len >>> 2) this._shrinkArray(); + return removed; +}; - /** - * Map of special "%n" handling functions, for the debug "format" argument. - * - * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". - */ - createDebug.formatters = {}; +/** + * Native splice implementation. + * Remove number of items from the specified index from the list and/or add new elements. + * Returns array of removed items or empty array if count == 0. + * Returns undefined if the list is empty. + * + * @param index + * @param count + * @param {...*} [elements] + * @returns {array} + */ +Denque.prototype.splice = function splice(index, count) { + var i = index; + // expect a number or return undefined + if ((i !== (i | 0))) { + return void 0; + } + var size = this.size(); + if (i < 0) i += size; + if (i > size) return void 0; + if (arguments.length > 2) { + var k; + var temp; + var removed; + var arg_len = arguments.length; + var len = this._list.length; + var arguments_index = 2; + if (!size || i < size / 2) { + temp = new Array(i); + for (k = 0; k < i; k++) { + temp[k] = this._list[(this._head + k) & this._capacityMask]; + } + if (count === 0) { + removed = []; + if (i > 0) { + this._head = (this._head + i + len) & this._capacityMask; + } + } else { + removed = this.remove(i, count); + this._head = (this._head + i + len) & this._capacityMask; + } + while (arg_len > arguments_index) { + this.unshift(arguments[--arg_len]); + } + for (k = i; k > 0; k--) { + this.unshift(temp[k - 1]); + } + } else { + temp = new Array(size - (i + count)); + var leng = temp.length; + for (k = 0; k < leng; k++) { + temp[k] = this._list[(this._head + i + count + k) & this._capacityMask]; + } + if (count === 0) { + removed = []; + if (i != size) { + this._tail = (this._head + i + len) & this._capacityMask; + } + } else { + removed = this.remove(i, count); + this._tail = (this._tail - leng + len) & this._capacityMask; + } + while (arguments_index < arg_len) { + this.push(arguments[arguments_index++]); + } + for (k = 0; k < leng; k++) { + this.push(temp[k]); + } + } + return removed; + } else { + return this.remove(i, count); + } +}; - /** - * Selects a color for a debug namespace - * @param {String} namespace The namespace string for the debug instance to be colored - * @return {Number|String} An ANSI color code for the given namespace - * @api private - */ - function selectColor(namespace) { - let hash = 0; +/** + * Soft clear - does not reset capacity. + */ +Denque.prototype.clear = function clear() { + this._head = 0; + this._tail = 0; +}; - for (let i = 0; i < namespace.length; i++) { - hash = ((hash << 5) - hash) + namespace.charCodeAt(i); - hash |= 0; // Convert to 32bit integer - } +/** + * Returns true or false whether the list is empty. + * @returns {boolean} + */ +Denque.prototype.isEmpty = function isEmpty() { + return this._head === this._tail; +}; - return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; - } - createDebug.selectColor = selectColor; +/** + * Returns an array of all queue items. + * @returns {Array} + */ +Denque.prototype.toArray = function toArray() { + return this._copyArray(false); +}; - /** - * Create a debugger with the given `namespace`. - * - * @param {String} namespace - * @return {Function} - * @api public - */ - function createDebug(namespace) { - let prevTime; - let enableOverride = null; - let namespacesCache; - let enabledCache; +/** + * ------------- + * INTERNALS + * ------------- + */ - function debug(...args) { - // Disabled? - if (!debug.enabled) { - return; - } +/** + * Fills the queue with items from an array + * For use in the constructor + * @param array + * @private + */ +Denque.prototype._fromArray = function _fromArray(array) { + for (var i = 0; i < array.length; i++) this.push(array[i]); +}; - const self = debug; +/** + * + * @param fullCopy + * @returns {Array} + * @private + */ +Denque.prototype._copyArray = function _copyArray(fullCopy) { + var newArray = []; + var list = this._list; + var len = list.length; + var i; + if (fullCopy || this._head > this._tail) { + for (i = this._head; i < len; i++) newArray.push(list[i]); + for (i = 0; i < this._tail; i++) newArray.push(list[i]); + } else { + for (i = this._head; i < this._tail; i++) newArray.push(list[i]); + } + return newArray; +}; - // Set `diff` timestamp - const curr = Number(new Date()); - const ms = curr - (prevTime || curr); - self.diff = ms; - self.prev = prevTime; - self.curr = curr; - prevTime = curr; +/** + * Grows the internal list array. + * @private + */ +Denque.prototype._growArray = function _growArray() { + if (this._head) { + // copy existing data, head to end, then beginning to tail. + this._list = this._copyArray(true); + this._head = 0; + } - args[0] = createDebug.coerce(args[0]); + // head is at 0 and array is now full, safe to extend + this._tail = this._list.length; - if (typeof args[0] !== 'string') { - // Anything else let's inspect with %O - args.unshift('%O'); - } + this._list.length <<= 1; + this._capacityMask = (this._capacityMask << 1) | 1; +}; - // Apply any `formatters` transformations - let index = 0; - args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { - // If we encounter an escaped % then don't increase the array index - if (match === '%%') { - return '%'; - } - index++; - const formatter = createDebug.formatters[format]; - if (typeof formatter === 'function') { - const val = args[index]; - match = formatter.call(self, val); +/** + * Shrinks the internal list array. + * @private + */ +Denque.prototype._shrinkArray = function _shrinkArray() { + this._list.length >>>= 1; + this._capacityMask >>>= 1; +}; - // Now we need to remove `args[index]` since it's inlined in the `format` - args.splice(index, 1); - index--; - } - return match; - }); - // Apply env-specific formatting (colors, etc.) - createDebug.formatArgs.call(self, args); +module.exports = Denque; - const logFn = self.log || createDebug.log; - logFn.apply(self, args); - } - debug.namespace = namespace; - debug.useColors = createDebug.useColors(); - debug.color = createDebug.selectColor(namespace); - debug.extend = extend; - debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. +/***/ }), - Object.defineProperty(debug, 'enabled', { - enumerable: true, - configurable: false, - get: () => { - if (enableOverride !== null) { - return enableOverride; - } - if (namespacesCache !== createDebug.namespaces) { - namespacesCache = createDebug.namespaces; - enabledCache = createDebug.enabled(namespace); - } +/***/ 18883: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return enabledCache; - }, - set: v => { - enableOverride = v; - } - }); +/*! + * depd + * Copyright(c) 2014-2017 Douglas Christopher Wilson + * MIT Licensed + */ - // Env-specific initialization logic for debug instances - if (typeof createDebug.init === 'function') { - createDebug.init(debug); - } +/** + * Module dependencies. + */ - return debug; - } +var callSiteToString = (__nccwpck_require__(69829).callSiteToString) +var eventListenerCount = (__nccwpck_require__(69829).eventListenerCount) +var relative = (__nccwpck_require__(71017).relative) - function extend(namespace, delimiter) { - const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); - newDebug.log = this.log; - return newDebug; - } +/** + * Module exports. + */ - /** - * Enables a debug mode by namespaces. This can include modes - * separated by a colon and wildcards. - * - * @param {String} namespaces - * @api public - */ - function enable(namespaces) { - createDebug.save(namespaces); - createDebug.namespaces = namespaces; +module.exports = depd - createDebug.names = []; - createDebug.skips = []; +/** + * Get the path to base files on. + */ - let i; - const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); - const len = split.length; +var basePath = process.cwd() - for (i = 0; i < len; i++) { - if (!split[i]) { - // ignore empty strings - continue; - } +/** + * Determine if namespace is contained in the string. + */ - namespaces = split[i].replace(/\*/g, '.*?'); +function containsNamespace (str, namespace) { + var vals = str.split(/[ ,]+/) + var ns = String(namespace).toLowerCase() - if (namespaces[0] === '-') { - createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); - } else { - createDebug.names.push(new RegExp('^' + namespaces + '$')); - } - } - } + for (var i = 0; i < vals.length; i++) { + var val = vals[i] - /** - * Disable debug output. - * - * @return {String} namespaces - * @api public - */ - function disable() { - const namespaces = [ - ...createDebug.names.map(toNamespace), - ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) - ].join(','); - createDebug.enable(''); - return namespaces; - } + // namespace contained + if (val && (val === '*' || val.toLowerCase() === ns)) { + return true + } + } - /** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ - function enabled(name) { - if (name[name.length - 1] === '*') { - return true; - } + return false +} - let i; - let len; +/** + * Convert a data descriptor to accessor descriptor. + */ - for (i = 0, len = createDebug.skips.length; i < len; i++) { - if (createDebug.skips[i].test(name)) { - return false; - } - } - - for (i = 0, len = createDebug.names.length; i < len; i++) { - if (createDebug.names[i].test(name)) { - return true; - } - } - - return false; - } +function convertDataDescriptorToAccessor (obj, prop, message) { + var descriptor = Object.getOwnPropertyDescriptor(obj, prop) + var value = descriptor.value - /** - * Convert regexp to namespace - * - * @param {RegExp} regxep - * @return {String} namespace - * @api private - */ - function toNamespace(regexp) { - return regexp.toString() - .substring(2, regexp.toString().length - 2) - .replace(/\.\*\?$/, '*'); - } + descriptor.get = function getter () { return value } - /** - * Coerce `val`. - * - * @param {Mixed} val - * @return {Mixed} - * @api private - */ - function coerce(val) { - if (val instanceof Error) { - return val.stack || val.message; - } - return val; - } + if (descriptor.writable) { + descriptor.set = function setter (val) { return (value = val) } + } - /** - * XXX DO NOT USE. This is a temporary stub function. - * XXX It WILL be removed in the next major release. - */ - function destroy() { - console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); - } + delete descriptor.value + delete descriptor.writable - createDebug.enable(createDebug.load()); + Object.defineProperty(obj, prop, descriptor) - return createDebug; + return descriptor } -module.exports = setup; +/** + * Create arguments string to keep arity. + */ +function createArgumentsString (arity) { + var str = '' -/***/ }), + for (var i = 0; i < arity; i++) { + str += ', arg' + i + } -/***/ 38237: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return str.substr(2) +} /** - * Detect Electron renderer / nwjs process, which is node, but we should - * treat as a browser. + * Create stack string from stack. */ -if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { - module.exports = __nccwpck_require__(28222); -} else { - module.exports = __nccwpck_require__(35332); -} +function createStackString (stack) { + var str = this.name + ': ' + this.namespace + if (this.message) { + str += ' deprecated ' + this.message + } -/***/ }), + for (var i = 0; i < stack.length; i++) { + str += '\n at ' + callSiteToString(stack[i]) + } -/***/ 35332: -/***/ ((module, exports, __nccwpck_require__) => { + return str +} /** - * Module dependencies. + * Create deprecate for namespace in caller. */ -const tty = __nccwpck_require__(76224); -const util = __nccwpck_require__(73837); - -/** - * This is the Node.js implementation of `debug()`. - */ +function depd (namespace) { + if (!namespace) { + throw new TypeError('argument namespace is required') + } -exports.init = init; -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.destroy = util.deprecate( - () => {}, - 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' -); + var stack = getStack() + var site = callSiteLocation(stack[1]) + var file = site[0] -/** - * Colors. - */ + function deprecate (message) { + // call to self as log + log.call(deprecate, message) + } -exports.colors = [6, 2, 3, 4, 5, 1]; + deprecate._file = file + deprecate._ignored = isignored(namespace) + deprecate._namespace = namespace + deprecate._traced = istraced(namespace) + deprecate._warned = Object.create(null) -try { - // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) - // eslint-disable-next-line import/no-extraneous-dependencies - const supportsColor = __nccwpck_require__(59318); + deprecate.function = wrapfunction + deprecate.property = wrapproperty - if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { - exports.colors = [ - 20, - 21, - 26, - 27, - 32, - 33, - 38, - 39, - 40, - 41, - 42, - 43, - 44, - 45, - 56, - 57, - 62, - 63, - 68, - 69, - 74, - 75, - 76, - 77, - 78, - 79, - 80, - 81, - 92, - 93, - 98, - 99, - 112, - 113, - 128, - 129, - 134, - 135, - 148, - 149, - 160, - 161, - 162, - 163, - 164, - 165, - 166, - 167, - 168, - 169, - 170, - 171, - 172, - 173, - 178, - 179, - 184, - 185, - 196, - 197, - 198, - 199, - 200, - 201, - 202, - 203, - 204, - 205, - 206, - 207, - 208, - 209, - 214, - 215, - 220, - 221 - ]; - } -} catch (error) { - // Swallow - we only care if `supports-color` is available; it doesn't have to be. + return deprecate } /** - * Build up the default `inspectOpts` object from the environment variables. - * - * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + * Determine if namespace is ignored. */ -exports.inspectOpts = Object.keys(process.env).filter(key => { - return /^debug_/i.test(key); -}).reduce((obj, key) => { - // Camel-case - const prop = key - .substring(6) - .toLowerCase() - .replace(/_([a-z])/g, (_, k) => { - return k.toUpperCase(); - }); +function isignored (namespace) { + /* istanbul ignore next: tested in a child processs */ + if (process.noDeprecation) { + // --no-deprecation support + return true + } - // Coerce string value into JS value - let val = process.env[key]; - if (/^(yes|on|true|enabled)$/i.test(val)) { - val = true; - } else if (/^(no|off|false|disabled)$/i.test(val)) { - val = false; - } else if (val === 'null') { - val = null; - } else { - val = Number(val); - } + var str = process.env.NO_DEPRECATION || '' - obj[prop] = val; - return obj; -}, {}); + // namespace ignored + return containsNamespace(str, namespace) +} /** - * Is stdout a TTY? Colored output is enabled when `true`. + * Determine if namespace is traced. */ -function useColors() { - return 'colors' in exports.inspectOpts ? - Boolean(exports.inspectOpts.colors) : - tty.isatty(process.stderr.fd); +function istraced (namespace) { + /* istanbul ignore next: tested in a child processs */ + if (process.traceDeprecation) { + // --trace-deprecation support + return true + } + + var str = process.env.TRACE_DEPRECATION || '' + + // namespace traced + return containsNamespace(str, namespace) } /** - * Adds ANSI color escape codes if enabled. - * - * @api public + * Display deprecation message. */ -function formatArgs(args) { - const {namespace: name, useColors} = this; +function log (message, site) { + var haslisteners = eventListenerCount(process, 'deprecation') !== 0 - if (useColors) { - const c = this.color; - const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); - const prefix = ` ${colorCode};1m${name} \u001B[0m`; + // abort early if no destination + if (!haslisteners && this._ignored) { + return + } - args[0] = prefix + args[0].split('\n').join('\n' + prefix); - args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); - } else { - args[0] = getDate() + name + ' ' + args[0]; - } -} + var caller + var callFile + var callSite + var depSite + var i = 0 + var seen = false + var stack = getStack() + var file = this._file -function getDate() { - if (exports.inspectOpts.hideDate) { - return ''; - } - return new Date().toISOString() + ' '; -} + if (site) { + // provided site + depSite = site + callSite = callSiteLocation(stack[1]) + callSite.name = depSite.name + file = callSite[0] + } else { + // get call site + i = 2 + depSite = callSiteLocation(stack[i]) + callSite = depSite + } -/** - * Invokes `util.format()` with the specified arguments and writes to stderr. - */ + // get caller of deprecated thing in relation to file + for (; i < stack.length; i++) { + caller = callSiteLocation(stack[i]) + callFile = caller[0] -function log(...args) { - return process.stderr.write(util.format(...args) + '\n'); -} + if (callFile === file) { + seen = true + } else if (callFile === this._file) { + file = this._file + } else if (seen) { + break + } + } -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ -function save(namespaces) { - if (namespaces) { - process.env.DEBUG = namespaces; - } else { - // If you set a process.env field to null or undefined, it gets cast to the - // string 'null' or 'undefined'. Just delete instead. - delete process.env.DEBUG; - } -} + var key = caller + ? depSite.join(':') + '__' + caller.join(':') + : undefined -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ + if (key !== undefined && key in this._warned) { + // already warned + return + } -function load() { - return process.env.DEBUG; + this._warned[key] = true + + // generate automatic message from call site + var msg = message + if (!msg) { + msg = callSite === depSite || !callSite.name + ? defaultMessage(depSite) + : defaultMessage(callSite) + } + + // emit deprecation if listeners exist + if (haslisteners) { + var err = DeprecationError(this._namespace, msg, stack.slice(i)) + process.emit('deprecation', err) + return + } + + // format and write message + var format = process.stderr.isTTY + ? formatColor + : formatPlain + var output = format.call(this, msg, caller, stack.slice(i)) + process.stderr.write(output + '\n', 'utf8') } /** - * Init logic for `debug` instances. - * - * Create a new `inspectOpts` object in case `useColors` is set - * differently for a particular `debug` instance. + * Get call site location as array. */ -function init(debug) { - debug.inspectOpts = {}; - - const keys = Object.keys(exports.inspectOpts); - for (let i = 0; i < keys.length; i++) { - debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; - } -} +function callSiteLocation (callSite) { + var file = callSite.getFileName() || '' + var line = callSite.getLineNumber() + var colm = callSite.getColumnNumber() -module.exports = __nccwpck_require__(46243)(exports); + if (callSite.isEval()) { + file = callSite.getEvalOrigin() + ', ' + file + } -const {formatters} = module.exports; + var site = [file, line, colm] -/** - * Map %o to `util.inspect()`, all on a single line. - */ + site.callSite = callSite + site.name = callSite.getFunctionName() -formatters.o = function (v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts) - .split('\n') - .map(str => str.trim()) - .join(' '); -}; + return site +} /** - * Map %O to `util.inspect()`, allowing multiple lines if needed. + * Generate a default message from the site. */ -formatters.O = function (v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts); -}; +function defaultMessage (site) { + var callSite = site.callSite + var funcName = site.name + // make useful anonymous name + if (!funcName) { + funcName = '' + } -/***/ }), + var context = callSite.getThis() + var typeName = context && callSite.getTypeName() -/***/ 56323: -/***/ ((module) => { + // ignore useless type name + if (typeName === 'Object') { + typeName = undefined + } -"use strict"; + // make useful type name + if (typeName === 'Function') { + typeName = context.name || typeName + } + return typeName && callSite.getMethodName() + ? typeName + '.' + funcName + : funcName +} -var isMergeableObject = function isMergeableObject(value) { - return isNonNullObject(value) - && !isSpecial(value) -}; +/** + * Format deprecation message without color. + */ -function isNonNullObject(value) { - return !!value && typeof value === 'object' -} +function formatPlain (msg, caller, stack) { + var timestamp = new Date().toUTCString() -function isSpecial(value) { - var stringValue = Object.prototype.toString.call(value); + var formatted = timestamp + + ' ' + this._namespace + + ' deprecated ' + msg - return stringValue === '[object RegExp]' - || stringValue === '[object Date]' - || isReactElement(value) -} + // add stack trace + if (this._traced) { + for (var i = 0; i < stack.length; i++) { + formatted += '\n at ' + callSiteToString(stack[i]) + } -// see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25 -var canUseSymbol = typeof Symbol === 'function' && Symbol.for; -var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7; + return formatted + } -function isReactElement(value) { - return value.$$typeof === REACT_ELEMENT_TYPE -} + if (caller) { + formatted += ' at ' + formatLocation(caller) + } -function emptyTarget(val) { - return Array.isArray(val) ? [] : {} + return formatted } -function cloneUnlessOtherwiseSpecified(value, options) { - return (options.clone !== false && options.isMergeableObject(value)) - ? deepmerge(emptyTarget(value), value, options) - : value -} +/** + * Format deprecation message with color. + */ -function defaultArrayMerge(target, source, options) { - return target.concat(source).map(function(element) { - return cloneUnlessOtherwiseSpecified(element, options) - }) -} +function formatColor (msg, caller, stack) { + var formatted = '\x1b[36;1m' + this._namespace + '\x1b[22;39m' + // bold cyan + ' \x1b[33;1mdeprecated\x1b[22;39m' + // bold yellow + ' \x1b[0m' + msg + '\x1b[39m' // reset -function getMergeFunction(key, options) { - if (!options.customMerge) { - return deepmerge - } - var customMerge = options.customMerge(key); - return typeof customMerge === 'function' ? customMerge : deepmerge -} + // add stack trace + if (this._traced) { + for (var i = 0; i < stack.length; i++) { + formatted += '\n \x1b[36mat ' + callSiteToString(stack[i]) + '\x1b[39m' // cyan + } -function getEnumerableOwnPropertySymbols(target) { - return Object.getOwnPropertySymbols - ? Object.getOwnPropertySymbols(target).filter(function(symbol) { - return target.propertyIsEnumerable(symbol) - }) - : [] -} + return formatted + } -function getKeys(target) { - return Object.keys(target).concat(getEnumerableOwnPropertySymbols(target)) + if (caller) { + formatted += ' \x1b[36m' + formatLocation(caller) + '\x1b[39m' // cyan + } + + return formatted } -function propertyIsOnObject(object, property) { - try { - return property in object - } catch(_) { - return false - } +/** + * Format call site location. + */ + +function formatLocation (callSite) { + return relative(basePath, callSite[0]) + + ':' + callSite[1] + + ':' + callSite[2] } -// Protects from prototype poisoning and unexpected merging up the prototype chain. -function propertyIsUnsafe(target, key) { - return propertyIsOnObject(target, key) // Properties are safe to merge if they don't exist in the target yet, - && !(Object.hasOwnProperty.call(target, key) // unsafe if they exist up the prototype chain, - && Object.propertyIsEnumerable.call(target, key)) // and also unsafe if they're nonenumerable. +/** + * Get the stack as array of call sites. + */ + +function getStack () { + var limit = Error.stackTraceLimit + var obj = {} + var prep = Error.prepareStackTrace + + Error.prepareStackTrace = prepareObjectStackTrace + Error.stackTraceLimit = Math.max(10, limit) + + // capture the stack + Error.captureStackTrace(obj) + + // slice this function off the top + var stack = obj.stack.slice(1) + + Error.prepareStackTrace = prep + Error.stackTraceLimit = limit + + return stack } -function mergeObject(target, source, options) { - var destination = {}; - if (options.isMergeableObject(target)) { - getKeys(target).forEach(function(key) { - destination[key] = cloneUnlessOtherwiseSpecified(target[key], options); - }); - } - getKeys(source).forEach(function(key) { - if (propertyIsUnsafe(target, key)) { - return - } +/** + * Capture call site stack from v8. + */ - if (propertyIsOnObject(target, key) && options.isMergeableObject(source[key])) { - destination[key] = getMergeFunction(key, options)(target[key], source[key], options); - } else { - destination[key] = cloneUnlessOtherwiseSpecified(source[key], options); - } - }); - return destination +function prepareObjectStackTrace (obj, stack) { + return stack } -function deepmerge(target, source, options) { - options = options || {}; - options.arrayMerge = options.arrayMerge || defaultArrayMerge; - options.isMergeableObject = options.isMergeableObject || isMergeableObject; - // cloneUnlessOtherwiseSpecified is added to `options` so that custom arrayMerge() - // implementations can use it. The caller may not replace it. - options.cloneUnlessOtherwiseSpecified = cloneUnlessOtherwiseSpecified; +/** + * Return a wrapped function in a deprecation message. + */ - var sourceIsArray = Array.isArray(source); - var targetIsArray = Array.isArray(target); - var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray; +function wrapfunction (fn, message) { + if (typeof fn !== 'function') { + throw new TypeError('argument fn must be a function') + } - if (!sourceAndTargetTypesMatch) { - return cloneUnlessOtherwiseSpecified(source, options) - } else if (sourceIsArray) { - return options.arrayMerge(target, source, options) - } else { - return mergeObject(target, source, options) - } + var args = createArgumentsString(fn.length) + var deprecate = this // eslint-disable-line no-unused-vars + var stack = getStack() + var site = callSiteLocation(stack[1]) + + site.name = fn.name + + // eslint-disable-next-line no-eval + var deprecatedfn = eval('(function (' + args + ') {\n' + + '"use strict"\n' + + 'log.call(deprecate, message, site)\n' + + 'return fn.apply(this, arguments)\n' + + '})') + + return deprecatedfn } -deepmerge.all = function deepmergeAll(array, options) { - if (!Array.isArray(array)) { - throw new Error('first argument should be an array') - } +/** + * Wrap property in a deprecation message. + */ - return array.reduce(function(prev, next) { - return deepmerge(prev, next, options) - }, {}) -}; +function wrapproperty (obj, prop, message) { + if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { + throw new TypeError('argument obj must be object') + } -var deepmerge_1 = deepmerge; + var descriptor = Object.getOwnPropertyDescriptor(obj, prop) -module.exports = deepmerge_1; + if (!descriptor) { + throw new TypeError('must call property on owner object') + } + if (!descriptor.configurable) { + throw new TypeError('property must be configurable') + } -/***/ }), + var deprecate = this + var stack = getStack() + var site = callSiteLocation(stack[1]) -/***/ 42342: -/***/ ((module) => { + // set site name + site.name = prop -"use strict"; + // convert data descriptor + if ('value' in descriptor) { + descriptor = convertDataDescriptorToAccessor(obj, prop, message) + } + var get = descriptor.get + var set = descriptor.set -/** - * Custom implementation of a double ended queue. - */ -function Denque(array, options) { - var options = options || {}; + // wrap getter + if (typeof get === 'function') { + descriptor.get = function getter () { + log.call(deprecate, message, site) + return get.apply(this, arguments) + } + } - this._head = 0; - this._tail = 0; - this._capacity = options.capacity; - this._capacityMask = 0x3; - this._list = new Array(4); - if (Array.isArray(array)) { - this._fromArray(array); + // wrap setter + if (typeof set === 'function') { + descriptor.set = function setter () { + log.call(deprecate, message, site) + return set.apply(this, arguments) + } } + + Object.defineProperty(obj, prop, descriptor) } /** - * ------------- - * PUBLIC API - * ------------- + * Create DeprecationError for deprecation */ -/** - * Returns the item at the specified index from the list. - * 0 is the first element, 1 is the second, and so on... - * Elements at negative values are that many from the end: -1 is one before the end - * (the last element), -2 is two before the end (one before last), etc. - * @param index - * @returns {*} - */ -Denque.prototype.peekAt = function peekAt(index) { - var i = index; - // expect a number or return undefined - if ((i !== (i | 0))) { - return void 0; - } - var len = this.size(); - if (i >= len || i < -len) return undefined; - if (i < 0) i += len; - i = (this._head + i) & this._capacityMask; - return this._list[i]; -}; +function DeprecationError (namespace, message, stack) { + var error = new Error() + var stackString -/** - * Alias for peekAt() - * @param i - * @returns {*} - */ -Denque.prototype.get = function get(i) { - return this.peekAt(i); -}; + Object.defineProperty(error, 'constructor', { + value: DeprecationError + }) -/** - * Returns the first item in the list without removing it. - * @returns {*} + Object.defineProperty(error, 'message', { + configurable: true, + enumerable: false, + value: message, + writable: true + }) + + Object.defineProperty(error, 'name', { + enumerable: false, + configurable: true, + value: 'DeprecationError', + writable: true + }) + + Object.defineProperty(error, 'namespace', { + configurable: true, + enumerable: false, + value: namespace, + writable: true + }) + + Object.defineProperty(error, 'stack', { + configurable: true, + enumerable: false, + get: function () { + if (stackString !== undefined) { + return stackString + } + + // prepare stack trace + return (stackString = createStackString.call(this, stack)) + }, + set: function setter (val) { + stackString = val + } + }) + + return error +} + + +/***/ }), + +/***/ 35554: +/***/ ((module) => { + +"use strict"; +/*! + * depd + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed */ -Denque.prototype.peek = function peek() { - if (this._head === this._tail) return undefined; - return this._list[this._head]; -}; + + /** - * Alias for peek() - * @returns {*} + * Module exports. */ -Denque.prototype.peekFront = function peekFront() { - return this.peek(); -}; + +module.exports = callSiteToString /** - * Returns the item that is at the back of the queue without removing it. - * Uses peekAt(-1) + * Format a CallSite file location to a string. */ -Denque.prototype.peekBack = function peekBack() { - return this.peekAt(-1); -}; + +function callSiteFileLocation (callSite) { + var fileName + var fileLocation = '' + + if (callSite.isNative()) { + fileLocation = 'native' + } else if (callSite.isEval()) { + fileName = callSite.getScriptNameOrSourceURL() + if (!fileName) { + fileLocation = callSite.getEvalOrigin() + } + } else { + fileName = callSite.getFileName() + } + + if (fileName) { + fileLocation += fileName + + var lineNumber = callSite.getLineNumber() + if (lineNumber != null) { + fileLocation += ':' + lineNumber + + var columnNumber = callSite.getColumnNumber() + if (columnNumber) { + fileLocation += ':' + columnNumber + } + } + } + + return fileLocation || 'unknown source' +} /** - * Returns the current length of the queue - * @return {Number} + * Format a CallSite to a string. */ -Object.defineProperty(Denque.prototype, 'length', { - get: function length() { - return this.size(); + +function callSiteToString (callSite) { + var addSuffix = true + var fileLocation = callSiteFileLocation(callSite) + var functionName = callSite.getFunctionName() + var isConstructor = callSite.isConstructor() + var isMethodCall = !(callSite.isToplevel() || isConstructor) + var line = '' + + if (isMethodCall) { + var methodName = callSite.getMethodName() + var typeName = getConstructorName(callSite) + + if (functionName) { + if (typeName && functionName.indexOf(typeName) !== 0) { + line += typeName + '.' + } + + line += functionName + + if (methodName && functionName.lastIndexOf('.' + methodName) !== functionName.length - methodName.length - 1) { + line += ' [as ' + methodName + ']' + } + } else { + line += typeName + '.' + (methodName || '') + } + } else if (isConstructor) { + line += 'new ' + (functionName || '') + } else if (functionName) { + line += functionName + } else { + addSuffix = false + line += fileLocation } -}); + + if (addSuffix) { + line += ' (' + fileLocation + ')' + } + + return line +} /** - * Return the number of items on the list, or 0 if empty. - * @returns {number} + * Get constructor name of reviver. */ -Denque.prototype.size = function size() { - if (this._head === this._tail) return 0; - if (this._head < this._tail) return this._tail - this._head; - else return this._capacityMask + 1 - (this._head - this._tail); -}; -/** - * Add an item at the beginning of the list. - * @param item +function getConstructorName (obj) { + var receiver = obj.receiver + return (receiver.constructor && receiver.constructor.name) || null +} + + +/***/ }), + +/***/ 12078: +/***/ ((module) => { + +"use strict"; +/*! + * depd + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed */ -Denque.prototype.unshift = function unshift(item) { - if (item === undefined) return this.size(); - var len = this._list.length; - this._head = (this._head - 1 + len) & this._capacityMask; - this._list[this._head] = item; - if (this._tail === this._head) this._growArray(); - if (this._capacity && this.size() > this._capacity) this.pop(); - if (this._head < this._tail) return this._tail - this._head; - else return this._capacityMask + 1 - (this._head - this._tail); -}; + + /** - * Remove and return the first item on the list, - * Returns undefined if the list is empty. - * @returns {*} + * Module exports. + * @public */ -Denque.prototype.shift = function shift() { - var head = this._head; - if (head === this._tail) return undefined; - var item = this._list[head]; - this._list[head] = undefined; - this._head = (head + 1) & this._capacityMask; - if (head < 2 && this._tail > 10000 && this._tail <= this._list.length >>> 2) this._shrinkArray(); - return item; -}; + +module.exports = eventListenerCount /** - * Add an item to the bottom of the list. - * @param item + * Get the count of listeners on an event emitter of a specific type. */ -Denque.prototype.push = function push(item) { - if (item === undefined) return this.size(); - var tail = this._tail; - this._list[tail] = item; - this._tail = (tail + 1) & this._capacityMask; - if (this._tail === this._head) { - this._growArray(); - } - if (this._capacity && this.size() > this._capacity) { - this.shift(); - } - if (this._head < this._tail) return this._tail - this._head; - else return this._capacityMask + 1 - (this._head - this._tail); -}; + +function eventListenerCount (emitter, type) { + return emitter.listeners(type).length +} + + +/***/ }), + +/***/ 69829: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; +/*! + * depd + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + + /** - * Remove and return the last item on the list. - * Returns undefined if the list is empty. - * @returns {*} + * Module dependencies. + * @private */ -Denque.prototype.pop = function pop() { - var tail = this._tail; - if (tail === this._head) return undefined; - var len = this._list.length; - this._tail = (tail - 1 + len) & this._capacityMask; - var item = this._list[this._tail]; - this._list[this._tail] = undefined; - if (this._head < 2 && tail > 10000 && tail <= len >>> 2) this._shrinkArray(); - return item; -}; + +var EventEmitter = (__nccwpck_require__(82361).EventEmitter) /** - * Remove and return the item at the specified index from the list. - * Returns undefined if the list is empty. - * @param index - * @returns {*} + * Module exports. + * @public */ -Denque.prototype.removeOne = function removeOne(index) { - var i = index; - // expect a number or return undefined - if ((i !== (i | 0))) { - return void 0; - } - if (this._head === this._tail) return void 0; - var size = this.size(); - var len = this._list.length; - if (i >= size || i < -size) return void 0; - if (i < 0) i += size; - i = (this._head + i) & this._capacityMask; - var item = this._list[i]; - var k; - if (index < size / 2) { - for (k = index; k > 0; k--) { - this._list[i] = this._list[i = (i - 1 + len) & this._capacityMask]; - } - this._list[i] = void 0; - this._head = (this._head + 1 + len) & this._capacityMask; - } else { - for (k = size - 1 - index; k > 0; k--) { - this._list[i] = this._list[i = ( i + 1 + len) & this._capacityMask]; - } - this._list[i] = void 0; - this._tail = (this._tail - 1 + len) & this._capacityMask; - } - return item; -}; -/** - * Remove number of items from the specified index from the list. - * Returns array of removed items. - * Returns undefined if the list is empty. - * @param index - * @param count - * @returns {array} - */ -Denque.prototype.remove = function remove(index, count) { - var i = index; - var removed; - var del_count = count; - // expect a number or return undefined - if ((i !== (i | 0))) { - return void 0; - } - if (this._head === this._tail) return void 0; - var size = this.size(); - var len = this._list.length; - if (i >= size || i < -size || count < 1) return void 0; - if (i < 0) i += size; - if (count === 1 || !count) { - removed = new Array(1); - removed[0] = this.removeOne(i); - return removed; - } - if (i === 0 && i + count >= size) { - removed = this.toArray(); - this.clear(); - return removed; - } - if (i + count > size) count = size - i; - var k; - removed = new Array(count); - for (k = 0; k < count; k++) { - removed[k] = this._list[(this._head + i + k) & this._capacityMask]; - } - i = (this._head + i) & this._capacityMask; - if (index + count === size) { - this._tail = (this._tail - count + len) & this._capacityMask; - for (k = count; k > 0; k--) { - this._list[i = (i + 1 + len) & this._capacityMask] = void 0; - } - return removed; - } - if (index === 0) { - this._head = (this._head + count + len) & this._capacityMask; - for (k = count - 1; k > 0; k--) { - this._list[i = (i + 1 + len) & this._capacityMask] = void 0; - } - return removed; - } - if (i < size / 2) { - this._head = (this._head + index + count + len) & this._capacityMask; - for (k = index; k > 0; k--) { - this.unshift(this._list[i = (i - 1 + len) & this._capacityMask]); - } - i = (this._head - 1 + len) & this._capacityMask; - while (del_count > 0) { - this._list[i = (i - 1 + len) & this._capacityMask] = void 0; - del_count--; - } - if (index < 0) this._tail = i; - } else { - this._tail = i; - i = (i + count + len) & this._capacityMask; - for (k = size - (count + index); k > 0; k--) { - this.push(this._list[i++]); - } - i = this._tail; - while (del_count > 0) { - this._list[i = (i + 1 + len) & this._capacityMask] = void 0; - del_count--; - } - } - if (this._head < 2 && this._tail > 10000 && this._tail <= len >>> 2) this._shrinkArray(); - return removed; -}; +lazyProperty(module.exports, 'callSiteToString', function callSiteToString () { + var limit = Error.stackTraceLimit + var obj = {} + var prep = Error.prepareStackTrace -/** - * Native splice implementation. - * Remove number of items from the specified index from the list and/or add new elements. - * Returns array of removed items or empty array if count == 0. - * Returns undefined if the list is empty. - * - * @param index - * @param count - * @param {...*} [elements] - * @returns {array} - */ -Denque.prototype.splice = function splice(index, count) { - var i = index; - // expect a number or return undefined - if ((i !== (i | 0))) { - return void 0; - } - var size = this.size(); - if (i < 0) i += size; - if (i > size) return void 0; - if (arguments.length > 2) { - var k; - var temp; - var removed; - var arg_len = arguments.length; - var len = this._list.length; - var arguments_index = 2; - if (!size || i < size / 2) { - temp = new Array(i); - for (k = 0; k < i; k++) { - temp[k] = this._list[(this._head + k) & this._capacityMask]; - } - if (count === 0) { - removed = []; - if (i > 0) { - this._head = (this._head + i + len) & this._capacityMask; - } - } else { - removed = this.remove(i, count); - this._head = (this._head + i + len) & this._capacityMask; - } - while (arg_len > arguments_index) { - this.unshift(arguments[--arg_len]); - } - for (k = i; k > 0; k--) { - this.unshift(temp[k - 1]); - } - } else { - temp = new Array(size - (i + count)); - var leng = temp.length; - for (k = 0; k < leng; k++) { - temp[k] = this._list[(this._head + i + count + k) & this._capacityMask]; - } - if (count === 0) { - removed = []; - if (i != size) { - this._tail = (this._head + i + len) & this._capacityMask; - } - } else { - removed = this.remove(i, count); - this._tail = (this._tail - leng + len) & this._capacityMask; - } - while (arguments_index < arg_len) { - this.push(arguments[arguments_index++]); - } - for (k = 0; k < leng; k++) { - this.push(temp[k]); - } - } - return removed; - } else { - return this.remove(i, count); + function prepareObjectStackTrace (obj, stack) { + return stack } -}; -/** - * Soft clear - does not reset capacity. - */ -Denque.prototype.clear = function clear() { - this._head = 0; - this._tail = 0; -}; + Error.prepareStackTrace = prepareObjectStackTrace + Error.stackTraceLimit = 2 -/** - * Returns true or false whether the list is empty. - * @returns {boolean} - */ -Denque.prototype.isEmpty = function isEmpty() { - return this._head === this._tail; -}; + // capture the stack + Error.captureStackTrace(obj) -/** - * Returns an array of all queue items. - * @returns {Array} - */ -Denque.prototype.toArray = function toArray() { - return this._copyArray(false); -}; + // slice the stack + var stack = obj.stack.slice() -/** - * ------------- - * INTERNALS - * ------------- - */ + Error.prepareStackTrace = prep + Error.stackTraceLimit = limit -/** - * Fills the queue with items from an array - * For use in the constructor - * @param array - * @private - */ -Denque.prototype._fromArray = function _fromArray(array) { - for (var i = 0; i < array.length; i++) this.push(array[i]); -}; + return stack[0].toString ? toString : __nccwpck_require__(35554) +}) + +lazyProperty(module.exports, 'eventListenerCount', function eventListenerCount () { + return EventEmitter.listenerCount || __nccwpck_require__(12078) +}) /** - * - * @param fullCopy - * @returns {Array} - * @private + * Define a lazy property. */ -Denque.prototype._copyArray = function _copyArray(fullCopy) { - var newArray = []; - var list = this._list; - var len = list.length; - var i; - if (fullCopy || this._head > this._tail) { - for (i = this._head; i < len; i++) newArray.push(list[i]); - for (i = 0; i < this._tail; i++) newArray.push(list[i]); - } else { - for (i = this._head; i < this._tail; i++) newArray.push(list[i]); + +function lazyProperty (obj, prop, getter) { + function get () { + var val = getter() + + Object.defineProperty(obj, prop, { + configurable: true, + enumerable: true, + value: val + }) + + return val } - return newArray; -}; + + Object.defineProperty(obj, prop, { + configurable: true, + enumerable: true, + get: get + }) +} /** - * Grows the internal list array. - * @private + * Call toString() on the obj */ -Denque.prototype._growArray = function _growArray() { - if (this._head) { - // copy existing data, head to end, then beginning to tail. - this._list = this._copyArray(true); - this._head = 0; - } - // head is at 0 and array is now full, safe to extend - this._tail = this._list.length; +function toString (obj) { + return obj.toString() +} - this._list.length <<= 1; - this._capacityMask = (this._capacityMask << 1) | 1; -}; -/** - * Shrinks the internal list array. - * @private - */ -Denque.prototype._shrinkArray = function _shrinkArray() { - this._list.length >>>= 1; - this._capacityMask >>>= 1; -}; +/***/ }), + +/***/ 58932: +/***/ ((__unused_webpack_module, exports) => { +"use strict"; -module.exports = Denque; + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +class Deprecation extends Error { + constructor(message) { + super(message); // Maintains proper stack trace (only available on V8) + + /* istanbul ignore next */ + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + + this.name = 'Deprecation'; + } + +} + +exports.Deprecation = Deprecation; /***/ }), -/***/ 18883: +/***/ 43225: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +"use strict"; /*! - * depd - * Copyright(c) 2014-2017 Douglas Christopher Wilson + * destroy + * Copyright(c) 2014 Jonathan Ong * MIT Licensed */ -/** - * Module dependencies. - */ -var callSiteToString = (__nccwpck_require__(69829).callSiteToString) -var eventListenerCount = (__nccwpck_require__(69829).eventListenerCount) -var relative = (__nccwpck_require__(71017).relative) /** - * Module exports. + * Module dependencies. + * @private */ -module.exports = depd +var ReadStream = (__nccwpck_require__(57147).ReadStream) +var Stream = __nccwpck_require__(12781) /** - * Get the path to base files on. + * Module exports. + * @public */ -var basePath = process.cwd() +module.exports = destroy /** - * Determine if namespace is contained in the string. + * Destroy a stream. + * + * @param {object} stream + * @public */ -function containsNamespace (str, namespace) { - var vals = str.split(/[ ,]+/) - var ns = String(namespace).toLowerCase() +function destroy(stream) { + if (stream instanceof ReadStream) { + return destroyReadStream(stream) + } - for (var i = 0; i < vals.length; i++) { - var val = vals[i] + if (!(stream instanceof Stream)) { + return stream + } - // namespace contained - if (val && (val === '*' || val.toLowerCase() === ns)) { - return true - } + if (typeof stream.destroy === 'function') { + stream.destroy() } - return false + return stream } /** - * Convert a data descriptor to accessor descriptor. + * Destroy a ReadStream. + * + * @param {object} stream + * @private */ -function convertDataDescriptorToAccessor (obj, prop, message) { - var descriptor = Object.getOwnPropertyDescriptor(obj, prop) - var value = descriptor.value - - descriptor.get = function getter () { return value } +function destroyReadStream(stream) { + stream.destroy() - if (descriptor.writable) { - descriptor.set = function setter (val) { return (value = val) } + if (typeof stream.close === 'function') { + // node.js core bug work-around + stream.on('open', onOpenClose) } - delete descriptor.value - delete descriptor.writable - - Object.defineProperty(obj, prop, descriptor) - - return descriptor + return stream } /** - * Create arguments string to keep arity. + * On open handler to close stream. + * @private */ -function createArgumentsString (arity) { - var str = '' - - for (var i = 0; i < arity; i++) { - str += ', arg' + i +function onOpenClose() { + if (typeof this.fd === 'number') { + // actually close down the fd + this.close() } - - return str.substr(2) } -/** - * Create stack string from stack. - */ -function createStackString (stack) { - var str = this.name + ': ' + this.namespace +/***/ }), - if (this.message) { - str += ' deprecated ' + this.message - } +/***/ 12437: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - for (var i = 0; i < stack.length; i++) { - str += '\n at ' + callSiteToString(stack[i]) - } +/* @flow */ +/*:: - return str +type DotenvParseOptions = { + debug?: boolean } -/** - * Create deprecate for namespace in caller. - */ - -function depd (namespace) { - if (!namespace) { - throw new TypeError('argument namespace is required') - } +// keys and values from src +type DotenvParseOutput = { [string]: string } - var stack = getStack() - var site = callSiteLocation(stack[1]) - var file = site[0] +type DotenvConfigOptions = { + path?: string, // path to .env file + encoding?: string, // encoding of .env file + debug?: string // turn on logging for debugging purposes +} - function deprecate (message) { - // call to self as log - log.call(deprecate, message) - } +type DotenvConfigOutput = { + parsed?: DotenvParseOutput, + error?: Error +} - deprecate._file = file - deprecate._ignored = isignored(namespace) - deprecate._namespace = namespace - deprecate._traced = istraced(namespace) - deprecate._warned = Object.create(null) +*/ - deprecate.function = wrapfunction - deprecate.property = wrapproperty +const fs = __nccwpck_require__(57147) +const path = __nccwpck_require__(71017) - return deprecate +function log (message /*: string */) { + console.log(`[dotenv][DEBUG] ${message}`) } -/** - * Determine if namespace is ignored. - */ +const NEWLINE = '\n' +const RE_INI_KEY_VAL = /^\s*([\w.-]+)\s*=\s*(.*)?\s*$/ +const RE_NEWLINES = /\\n/g +const NEWLINES_MATCH = /\n|\r|\r\n/ -function isignored (namespace) { - /* istanbul ignore next: tested in a child processs */ - if (process.noDeprecation) { - // --no-deprecation support - return true - } +// Parses src into an Object +function parse (src /*: string | Buffer */, options /*: ?DotenvParseOptions */) /*: DotenvParseOutput */ { + const debug = Boolean(options && options.debug) + const obj = {} - var str = process.env.NO_DEPRECATION || '' + // convert Buffers before splitting into lines and processing + src.toString().split(NEWLINES_MATCH).forEach(function (line, idx) { + // matching "KEY' and 'VAL' in 'KEY=VAL' + const keyValueArr = line.match(RE_INI_KEY_VAL) + // matched? + if (keyValueArr != null) { + const key = keyValueArr[1] + // default undefined or missing values to empty string + let val = (keyValueArr[2] || '') + const end = val.length - 1 + const isDoubleQuoted = val[0] === '"' && val[end] === '"' + const isSingleQuoted = val[0] === "'" && val[end] === "'" - // namespace ignored - return containsNamespace(str, namespace) -} + // if single or double quoted, remove quotes + if (isSingleQuoted || isDoubleQuoted) { + val = val.substring(1, end) -/** - * Determine if namespace is traced. - */ + // if double quoted, expand newlines + if (isDoubleQuoted) { + val = val.replace(RE_NEWLINES, NEWLINE) + } + } else { + // remove surrounding whitespace + val = val.trim() + } -function istraced (namespace) { - /* istanbul ignore next: tested in a child processs */ - if (process.traceDeprecation) { - // --trace-deprecation support - return true - } - - var str = process.env.TRACE_DEPRECATION || '' + obj[key] = val + } else if (debug) { + log(`did not match key and value when parsing line ${idx + 1}: ${line}`) + } + }) - // namespace traced - return containsNamespace(str, namespace) + return obj } -/** - * Display deprecation message. - */ - -function log (message, site) { - var haslisteners = eventListenerCount(process, 'deprecation') !== 0 - - // abort early if no destination - if (!haslisteners && this._ignored) { - return - } - - var caller - var callFile - var callSite - var depSite - var i = 0 - var seen = false - var stack = getStack() - var file = this._file - - if (site) { - // provided site - depSite = site - callSite = callSiteLocation(stack[1]) - callSite.name = depSite.name - file = callSite[0] - } else { - // get call site - i = 2 - depSite = callSiteLocation(stack[i]) - callSite = depSite - } - - // get caller of deprecated thing in relation to file - for (; i < stack.length; i++) { - caller = callSiteLocation(stack[i]) - callFile = caller[0] +// Populates process.env from .env file +function config (options /*: ?DotenvConfigOptions */) /*: DotenvConfigOutput */ { + let dotenvPath = path.resolve(process.cwd(), '.env') + let encoding /*: string */ = 'utf8' + let debug = false - if (callFile === file) { - seen = true - } else if (callFile === this._file) { - file = this._file - } else if (seen) { - break + if (options) { + if (options.path != null) { + dotenvPath = options.path + } + if (options.encoding != null) { + encoding = options.encoding + } + if (options.debug != null) { + debug = true } } - var key = caller - ? depSite.join(':') + '__' + caller.join(':') - : undefined - - if (key !== undefined && key in this._warned) { - // already warned - return - } - - this._warned[key] = true + try { + // specifying an encoding returns a string instead of a buffer + const parsed = parse(fs.readFileSync(dotenvPath, { encoding }), { debug }) - // generate automatic message from call site - var msg = message - if (!msg) { - msg = callSite === depSite || !callSite.name - ? defaultMessage(depSite) - : defaultMessage(callSite) - } + Object.keys(parsed).forEach(function (key) { + if (!Object.prototype.hasOwnProperty.call(process.env, key)) { + process.env[key] = parsed[key] + } else if (debug) { + log(`"${key}" is already defined in \`process.env\` and will not be overwritten`) + } + }) - // emit deprecation if listeners exist - if (haslisteners) { - var err = DeprecationError(this._namespace, msg, stack.slice(i)) - process.emit('deprecation', err) - return + return { parsed } + } catch (e) { + return { error: e } } - - // format and write message - var format = process.stderr.isTTY - ? formatColor - : formatPlain - var output = format.call(this, msg, caller, stack.slice(i)) - process.stderr.write(output + '\n', 'utf8') } -/** - * Get call site location as array. - */ - -function callSiteLocation (callSite) { - var file = callSite.getFileName() || '' - var line = callSite.getLineNumber() - var colm = callSite.getColumnNumber() +module.exports.config = config +module.exports.parse = parse - if (callSite.isEval()) { - file = callSite.getEvalOrigin() + ', ' + file - } - var site = [file, line, colm] +/***/ }), - site.callSite = callSite - site.name = callSite.getFunctionName() +/***/ 11728: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return site -} +"use strict"; -/** - * Generate a default message from the site. - */ -function defaultMessage (site) { - var callSite = site.callSite - var funcName = site.name +var Buffer = (__nccwpck_require__(21867).Buffer); - // make useful anonymous name - if (!funcName) { - funcName = '' - } +var getParamBytesForAlg = __nccwpck_require__(30528); - var context = callSite.getThis() - var typeName = context && callSite.getTypeName() +var MAX_OCTET = 0x80, + CLASS_UNIVERSAL = 0, + PRIMITIVE_BIT = 0x20, + TAG_SEQ = 0x10, + TAG_INT = 0x02, + ENCODED_TAG_SEQ = (TAG_SEQ | PRIMITIVE_BIT) | (CLASS_UNIVERSAL << 6), + ENCODED_TAG_INT = TAG_INT | (CLASS_UNIVERSAL << 6); - // ignore useless type name - if (typeName === 'Object') { - typeName = undefined - } +function base64Url(base64) { + return base64 + .replace(/=/g, '') + .replace(/\+/g, '-') + .replace(/\//g, '_'); +} - // make useful type name - if (typeName === 'Function') { - typeName = context.name || typeName - } +function signatureAsBuffer(signature) { + if (Buffer.isBuffer(signature)) { + return signature; + } else if ('string' === typeof signature) { + return Buffer.from(signature, 'base64'); + } - return typeName && callSite.getMethodName() - ? typeName + '.' + funcName - : funcName + throw new TypeError('ECDSA signature must be a Base64 string or a Buffer'); } -/** - * Format deprecation message without color. - */ +function derToJose(signature, alg) { + signature = signatureAsBuffer(signature); + var paramBytes = getParamBytesForAlg(alg); -function formatPlain (msg, caller, stack) { - var timestamp = new Date().toUTCString() + // the DER encoded param should at most be the param size, plus a padding + // zero, since due to being a signed integer + var maxEncodedParamLength = paramBytes + 1; - var formatted = timestamp + - ' ' + this._namespace + - ' deprecated ' + msg + var inputLength = signature.length; - // add stack trace - if (this._traced) { - for (var i = 0; i < stack.length; i++) { - formatted += '\n at ' + callSiteToString(stack[i]) - } + var offset = 0; + if (signature[offset++] !== ENCODED_TAG_SEQ) { + throw new Error('Could not find expected "seq"'); + } - return formatted - } + var seqLength = signature[offset++]; + if (seqLength === (MAX_OCTET | 1)) { + seqLength = signature[offset++]; + } - if (caller) { - formatted += ' at ' + formatLocation(caller) - } + if (inputLength - offset < seqLength) { + throw new Error('"seq" specified length of "' + seqLength + '", only "' + (inputLength - offset) + '" remaining'); + } - return formatted -} + if (signature[offset++] !== ENCODED_TAG_INT) { + throw new Error('Could not find expected "int" for "r"'); + } -/** - * Format deprecation message with color. - */ + var rLength = signature[offset++]; -function formatColor (msg, caller, stack) { - var formatted = '\x1b[36;1m' + this._namespace + '\x1b[22;39m' + // bold cyan - ' \x1b[33;1mdeprecated\x1b[22;39m' + // bold yellow - ' \x1b[0m' + msg + '\x1b[39m' // reset + if (inputLength - offset - 2 < rLength) { + throw new Error('"r" specified length of "' + rLength + '", only "' + (inputLength - offset - 2) + '" available'); + } - // add stack trace - if (this._traced) { - for (var i = 0; i < stack.length; i++) { - formatted += '\n \x1b[36mat ' + callSiteToString(stack[i]) + '\x1b[39m' // cyan - } + if (maxEncodedParamLength < rLength) { + throw new Error('"r" specified length of "' + rLength + '", max of "' + maxEncodedParamLength + '" is acceptable'); + } - return formatted - } + var rOffset = offset; + offset += rLength; - if (caller) { - formatted += ' \x1b[36m' + formatLocation(caller) + '\x1b[39m' // cyan - } + if (signature[offset++] !== ENCODED_TAG_INT) { + throw new Error('Could not find expected "int" for "s"'); + } - return formatted -} + var sLength = signature[offset++]; -/** - * Format call site location. - */ + if (inputLength - offset !== sLength) { + throw new Error('"s" specified length of "' + sLength + '", expected "' + (inputLength - offset) + '"'); + } -function formatLocation (callSite) { - return relative(basePath, callSite[0]) + - ':' + callSite[1] + - ':' + callSite[2] -} + if (maxEncodedParamLength < sLength) { + throw new Error('"s" specified length of "' + sLength + '", max of "' + maxEncodedParamLength + '" is acceptable'); + } -/** - * Get the stack as array of call sites. - */ + var sOffset = offset; + offset += sLength; -function getStack () { - var limit = Error.stackTraceLimit - var obj = {} - var prep = Error.prepareStackTrace + if (offset !== inputLength) { + throw new Error('Expected to consume entire buffer, but "' + (inputLength - offset) + '" bytes remain'); + } - Error.prepareStackTrace = prepareObjectStackTrace - Error.stackTraceLimit = Math.max(10, limit) + var rPadding = paramBytes - rLength, + sPadding = paramBytes - sLength; - // capture the stack - Error.captureStackTrace(obj) + var dst = Buffer.allocUnsafe(rPadding + rLength + sPadding + sLength); - // slice this function off the top - var stack = obj.stack.slice(1) + for (offset = 0; offset < rPadding; ++offset) { + dst[offset] = 0; + } + signature.copy(dst, offset, rOffset + Math.max(-rPadding, 0), rOffset + rLength); - Error.prepareStackTrace = prep - Error.stackTraceLimit = limit + offset = paramBytes; - return stack -} + for (var o = offset; offset < o + sPadding; ++offset) { + dst[offset] = 0; + } + signature.copy(dst, offset, sOffset + Math.max(-sPadding, 0), sOffset + sLength); -/** - * Capture call site stack from v8. - */ + dst = dst.toString('base64'); + dst = base64Url(dst); -function prepareObjectStackTrace (obj, stack) { - return stack + return dst; } -/** - * Return a wrapped function in a deprecation message. - */ - -function wrapfunction (fn, message) { - if (typeof fn !== 'function') { - throw new TypeError('argument fn must be a function') - } - - var args = createArgumentsString(fn.length) - var deprecate = this // eslint-disable-line no-unused-vars - var stack = getStack() - var site = callSiteLocation(stack[1]) - - site.name = fn.name +function countPadding(buf, start, stop) { + var padding = 0; + while (start + padding < stop && buf[start + padding] === 0) { + ++padding; + } - // eslint-disable-next-line no-eval - var deprecatedfn = eval('(function (' + args + ') {\n' + - '"use strict"\n' + - 'log.call(deprecate, message, site)\n' + - 'return fn.apply(this, arguments)\n' + - '})') + var needsSign = buf[start + padding] >= MAX_OCTET; + if (needsSign) { + --padding; + } - return deprecatedfn + return padding; } -/** - * Wrap property in a deprecation message. - */ - -function wrapproperty (obj, prop, message) { - if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { - throw new TypeError('argument obj must be object') - } - - var descriptor = Object.getOwnPropertyDescriptor(obj, prop) - - if (!descriptor) { - throw new TypeError('must call property on owner object') - } - - if (!descriptor.configurable) { - throw new TypeError('property must be configurable') - } +function joseToDer(signature, alg) { + signature = signatureAsBuffer(signature); + var paramBytes = getParamBytesForAlg(alg); - var deprecate = this - var stack = getStack() - var site = callSiteLocation(stack[1]) + var signatureBytes = signature.length; + if (signatureBytes !== paramBytes * 2) { + throw new TypeError('"' + alg + '" signatures must be "' + paramBytes * 2 + '" bytes, saw "' + signatureBytes + '"'); + } - // set site name - site.name = prop + var rPadding = countPadding(signature, 0, paramBytes); + var sPadding = countPadding(signature, paramBytes, signature.length); + var rLength = paramBytes - rPadding; + var sLength = paramBytes - sPadding; - // convert data descriptor - if ('value' in descriptor) { - descriptor = convertDataDescriptorToAccessor(obj, prop, message) - } + var rsBytes = 1 + 1 + rLength + 1 + 1 + sLength; - var get = descriptor.get - var set = descriptor.set + var shortLength = rsBytes < MAX_OCTET; - // wrap getter - if (typeof get === 'function') { - descriptor.get = function getter () { - log.call(deprecate, message, site) - return get.apply(this, arguments) - } - } + var dst = Buffer.allocUnsafe((shortLength ? 2 : 3) + rsBytes); - // wrap setter - if (typeof set === 'function') { - descriptor.set = function setter () { - log.call(deprecate, message, site) - return set.apply(this, arguments) - } - } + var offset = 0; + dst[offset++] = ENCODED_TAG_SEQ; + if (shortLength) { + // Bit 8 has value "0" + // bits 7-1 give the length. + dst[offset++] = rsBytes; + } else { + // Bit 8 of first octet has value "1" + // bits 7-1 give the number of additional length octets. + dst[offset++] = MAX_OCTET | 1; + // length, base 256 + dst[offset++] = rsBytes & 0xff; + } + dst[offset++] = ENCODED_TAG_INT; + dst[offset++] = rLength; + if (rPadding < 0) { + dst[offset++] = 0; + offset += signature.copy(dst, offset, 0, paramBytes); + } else { + offset += signature.copy(dst, offset, rPadding, paramBytes); + } + dst[offset++] = ENCODED_TAG_INT; + dst[offset++] = sLength; + if (sPadding < 0) { + dst[offset++] = 0; + signature.copy(dst, offset, paramBytes); + } else { + signature.copy(dst, offset, paramBytes + sPadding); + } - Object.defineProperty(obj, prop, descriptor) + return dst; } -/** - * Create DeprecationError for deprecation - */ +module.exports = { + derToJose: derToJose, + joseToDer: joseToDer +}; -function DeprecationError (namespace, message, stack) { - var error = new Error() - var stackString - Object.defineProperty(error, 'constructor', { - value: DeprecationError - }) +/***/ }), - Object.defineProperty(error, 'message', { - configurable: true, - enumerable: false, - value: message, - writable: true - }) +/***/ 30528: +/***/ ((module) => { - Object.defineProperty(error, 'name', { - enumerable: false, - configurable: true, - value: 'DeprecationError', - writable: true - }) +"use strict"; - Object.defineProperty(error, 'namespace', { - configurable: true, - enumerable: false, - value: namespace, - writable: true - }) - Object.defineProperty(error, 'stack', { - configurable: true, - enumerable: false, - get: function () { - if (stackString !== undefined) { - return stackString - } +function getParamSize(keySize) { + var result = ((keySize / 8) | 0) + (keySize % 8 === 0 ? 0 : 1); + return result; +} - // prepare stack trace - return (stackString = createStackString.call(this, stack)) - }, - set: function setter (val) { - stackString = val - } - }) +var paramBytesForAlg = { + ES256: getParamSize(256), + ES384: getParamSize(384), + ES512: getParamSize(521) +}; - return error +function getParamBytesForAlg(alg) { + var paramBytes = paramBytesForAlg[alg]; + if (paramBytes) { + return paramBytes; + } + + throw new Error('Unknown algorithm "' + alg + '"'); } +module.exports = getParamBytesForAlg; + /***/ }), -/***/ 35554: +/***/ 14401: /***/ ((module) => { "use strict"; /*! - * depd - * Copyright(c) 2014 Douglas Christopher Wilson + * ee-first + * Copyright(c) 2014 Jonathan Ong * MIT Licensed */ @@ -36868,110 +35737,116 @@ function DeprecationError (namespace, message, stack) { /** * Module exports. + * @public */ -module.exports = callSiteToString +module.exports = first /** - * Format a CallSite file location to a string. - */ - -function callSiteFileLocation (callSite) { - var fileName - var fileLocation = '' + * Get the first event in a set of event emitters and event pairs. + * + * @param {array} stuff + * @param {function} done + * @public + */ - if (callSite.isNative()) { - fileLocation = 'native' - } else if (callSite.isEval()) { - fileName = callSite.getScriptNameOrSourceURL() - if (!fileName) { - fileLocation = callSite.getEvalOrigin() +function first(stuff, done) { + if (!Array.isArray(stuff)) + throw new TypeError('arg must be an array of [ee, events...] arrays') + + var cleanups = [] + + for (var i = 0; i < stuff.length; i++) { + var arr = stuff[i] + + if (!Array.isArray(arr) || arr.length < 2) + throw new TypeError('each array member must be [ee, events...]') + + var ee = arr[0] + + for (var j = 1; j < arr.length; j++) { + var event = arr[j] + var fn = listener(event, callback) + + // listen to the event + ee.on(event, fn) + // push this listener to the list of cleanups + cleanups.push({ + ee: ee, + event: event, + fn: fn, + }) } - } else { - fileName = callSite.getFileName() } - if (fileName) { - fileLocation += fileName - - var lineNumber = callSite.getLineNumber() - if (lineNumber != null) { - fileLocation += ':' + lineNumber + function callback() { + cleanup() + done.apply(null, arguments) + } - var columnNumber = callSite.getColumnNumber() - if (columnNumber) { - fileLocation += ':' + columnNumber - } + function cleanup() { + var x + for (var i = 0; i < cleanups.length; i++) { + x = cleanups[i] + x.ee.removeListener(x.event, x.fn) } } - return fileLocation || 'unknown source' + function thunk(fn) { + done = fn + } + + thunk.cancel = cleanup + + return thunk } /** - * Format a CallSite to a string. + * Create the event listener. + * @private */ -function callSiteToString (callSite) { - var addSuffix = true - var fileLocation = callSiteFileLocation(callSite) - var functionName = callSite.getFunctionName() - var isConstructor = callSite.isConstructor() - var isMethodCall = !(callSite.isToplevel() || isConstructor) - var line = '' +function listener(event, done) { + return function onevent(arg1) { + var args = new Array(arguments.length) + var ee = this + var err = event === 'error' + ? arg1 + : null - if (isMethodCall) { - var methodName = callSite.getMethodName() - var typeName = getConstructorName(callSite) + // copy args to prevent arguments escaping scope + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i] + } - if (functionName) { - if (typeName && functionName.indexOf(typeName) !== 0) { - line += typeName + '.' - } + done(err, ee, event, args) + } +} - line += functionName - if (methodName && functionName.lastIndexOf('.' + methodName) !== functionName.length - methodName.length - 1) { - line += ' [as ' + methodName + ']' - } - } else { - line += typeName + '.' + (methodName || '') - } - } else if (isConstructor) { - line += 'new ' + (functionName || '') - } else if (functionName) { - line += functionName - } else { - addSuffix = false - line += fileLocation - } +/***/ }), - if (addSuffix) { - line += ' (' + fileLocation + ')' - } +/***/ 18212: +/***/ ((module) => { - return line -} +"use strict"; -/** - * Get constructor name of reviver. - */ -function getConstructorName (obj) { - var receiver = obj.receiver - return (receiver.constructor && receiver.constructor.name) || null -} +module.exports = function () { + // https://mths.be/emoji + return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|\uD83D\uDC68(?:\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68\uD83C\uDFFB|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C[\uDFFB-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)\uD83C\uDFFB|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB\uDFFC])|\uD83D\uDC69(?:\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB-\uDFFD])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83C\uDFF4\u200D\u2620)\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF4\uD83C\uDDF2|\uD83C\uDDF6\uD83C\uDDE6|[#\*0-9]\uFE0F\u20E3|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDBB\uDDD2-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g; +}; /***/ }), -/***/ 12078: +/***/ 16592: /***/ ((module) => { "use strict"; /*! - * depd - * Copyright(c) 2015 Douglas Christopher Wilson + * encodeurl + * Copyright(c) 2016 Douglas Christopher Wilson * MIT Licensed */ @@ -36982,1144 +35857,1299 @@ function getConstructorName (obj) { * @public */ -module.exports = eventListenerCount +module.exports = encodeUrl /** - * Get the count of listeners on an event emitter of a specific type. + * RegExp to match non-URL code points, *after* encoding (i.e. not including "%") + * and including invalid escape sequences. + * @private */ -function eventListenerCount (emitter, type) { - return emitter.listeners(type).length +var ENCODE_CHARS_REGEXP = /(?:[^\x21\x25\x26-\x3B\x3D\x3F-\x5B\x5D\x5F\x61-\x7A\x7E]|%(?:[^0-9A-Fa-f]|[0-9A-Fa-f][^0-9A-Fa-f]|$))+/g + +/** + * RegExp to match unmatched surrogate pair. + * @private + */ + +var UNMATCHED_SURROGATE_PAIR_REGEXP = /(^|[^\uD800-\uDBFF])[\uDC00-\uDFFF]|[\uD800-\uDBFF]([^\uDC00-\uDFFF]|$)/g + +/** + * String to replace unmatched surrogate pair with. + * @private + */ + +var UNMATCHED_SURROGATE_PAIR_REPLACE = '$1\uFFFD$2' + +/** + * Encode a URL to a percent-encoded form, excluding already-encoded sequences. + * + * This function will take an already-encoded URL and encode all the non-URL + * code points. This function will not encode the "%" character unless it is + * not part of a valid sequence (`%20` will be left as-is, but `%foo` will + * be encoded as `%25foo`). + * + * This encode is meant to be "safe" and does not throw errors. It will try as + * hard as it can to properly encode the given URL, including replacing any raw, + * unpaired surrogate pairs with the Unicode replacement character prior to + * encoding. + * + * @param {string} url + * @return {string} + * @public + */ + +function encodeUrl (url) { + return String(url) + .replace(UNMATCHED_SURROGATE_PAIR_REGEXP, UNMATCHED_SURROGATE_PAIR_REPLACE) + .replace(ENCODE_CHARS_REGEXP, encodeURI) } /***/ }), -/***/ 69829: +/***/ 23505: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -/*! - * depd - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ +var util = __nccwpck_require__(73837); +var isArrayish = __nccwpck_require__(7604); -/** - * Module dependencies. - * @private - */ +var errorEx = function errorEx(name, properties) { + if (!name || name.constructor !== String) { + properties = name || {}; + name = Error.name; + } -var EventEmitter = (__nccwpck_require__(82361).EventEmitter) + var errorExError = function ErrorEXError(message) { + if (!this) { + return new ErrorEXError(message); + } -/** - * Module exports. - * @public - */ + message = message instanceof Error + ? message.message + : (message || this.message); -lazyProperty(module.exports, 'callSiteToString', function callSiteToString () { - var limit = Error.stackTraceLimit - var obj = {} - var prep = Error.prepareStackTrace + Error.call(this, message); + Error.captureStackTrace(this, errorExError); - function prepareObjectStackTrace (obj, stack) { - return stack - } + this.name = name; - Error.prepareStackTrace = prepareObjectStackTrace - Error.stackTraceLimit = 2 + Object.defineProperty(this, 'message', { + configurable: true, + enumerable: false, + get: function () { + var newMessage = message.split(/\r?\n/g); - // capture the stack - Error.captureStackTrace(obj) + for (var key in properties) { + if (!properties.hasOwnProperty(key)) { + continue; + } - // slice the stack - var stack = obj.stack.slice() + var modifier = properties[key]; - Error.prepareStackTrace = prep - Error.stackTraceLimit = limit + if ('message' in modifier) { + newMessage = modifier.message(this[key], newMessage) || newMessage; + if (!isArrayish(newMessage)) { + newMessage = [newMessage]; + } + } + } - return stack[0].toString ? toString : __nccwpck_require__(35554) -}) + return newMessage.join('\n'); + }, + set: function (v) { + message = v; + } + }); -lazyProperty(module.exports, 'eventListenerCount', function eventListenerCount () { - return EventEmitter.listenerCount || __nccwpck_require__(12078) -}) + var overwrittenStack = null; -/** - * Define a lazy property. - */ + var stackDescriptor = Object.getOwnPropertyDescriptor(this, 'stack'); + var stackGetter = stackDescriptor.get; + var stackValue = stackDescriptor.value; + delete stackDescriptor.value; + delete stackDescriptor.writable; -function lazyProperty (obj, prop, getter) { - function get () { - var val = getter() + stackDescriptor.set = function (newstack) { + overwrittenStack = newstack; + }; - Object.defineProperty(obj, prop, { - configurable: true, - enumerable: true, - value: val - }) + stackDescriptor.get = function () { + var stack = (overwrittenStack || ((stackGetter) + ? stackGetter.call(this) + : stackValue)).split(/\r?\n+/g); - return val - } + // starting in Node 7, the stack builder caches the message. + // just replace it. + if (!overwrittenStack) { + stack[0] = this.name + ': ' + this.message; + } - Object.defineProperty(obj, prop, { - configurable: true, - enumerable: true, - get: get - }) -} + var lineCount = 1; + for (var key in properties) { + if (!properties.hasOwnProperty(key)) { + continue; + } -/** - * Call toString() on the obj - */ + var modifier = properties[key]; -function toString (obj) { - return obj.toString() -} + if ('line' in modifier) { + var line = modifier.line(this[key]); + if (line) { + stack.splice(lineCount++, 0, ' ' + line); + } + } + if ('stack' in modifier) { + modifier.stack(this[key], stack); + } + } -/***/ }), + return stack.join('\n'); + }; -/***/ 58932: -/***/ ((__unused_webpack_module, exports) => { + Object.defineProperty(this, 'stack', stackDescriptor); + }; -"use strict"; + if (Object.setPrototypeOf) { + Object.setPrototypeOf(errorExError.prototype, Error.prototype); + Object.setPrototypeOf(errorExError, Error); + } else { + util.inherits(errorExError, Error); + } + return errorExError; +}; -Object.defineProperty(exports, "__esModule", ({ value: true })); +errorEx.append = function (str, def) { + return { + message: function (v, message) { + v = v || def; -class Deprecation extends Error { - constructor(message) { - super(message); // Maintains proper stack trace (only available on V8) + if (v) { + message[0] += ' ' + str.replace('%s', v.toString()); + } - /* istanbul ignore next */ + return message; + } + }; +}; - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } +errorEx.line = function (str, def) { + return { + line: function (v) { + v = v || def; - this.name = 'Deprecation'; - } + if (v) { + return str.replace('%s', v.toString()); + } -} + return null; + } + }; +}; -exports.Deprecation = Deprecation; +module.exports = errorEx; /***/ }), -/***/ 43225: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 94070: +/***/ ((module) => { "use strict"; /*! - * destroy - * Copyright(c) 2014 Jonathan Ong + * escape-html + * Copyright(c) 2012-2013 TJ Holowaychuk + * Copyright(c) 2015 Andreas Lubbe + * Copyright(c) 2015 Tiancheng "Timothy" Gu * MIT Licensed */ /** - * Module dependencies. + * Module variables. * @private */ -var ReadStream = (__nccwpck_require__(57147).ReadStream) -var Stream = __nccwpck_require__(12781) +var matchHtmlRegExp = /["'&<>]/; /** * Module exports. * @public */ -module.exports = destroy +module.exports = escapeHtml; /** - * Destroy a stream. + * Escape special characters in the given string of html. * - * @param {object} stream + * @param {string} string The string to escape for inserting into HTML + * @return {string} * @public */ -function destroy(stream) { - if (stream instanceof ReadStream) { - return destroyReadStream(stream) - } +function escapeHtml(string) { + var str = '' + string; + var match = matchHtmlRegExp.exec(str); - if (!(stream instanceof Stream)) { - return stream + if (!match) { + return str; } - if (typeof stream.destroy === 'function') { - stream.destroy() + var escape; + var html = ''; + var index = 0; + var lastIndex = 0; + + for (index = match.index; index < str.length; index++) { + switch (str.charCodeAt(index)) { + case 34: // " + escape = '"'; + break; + case 38: // & + escape = '&'; + break; + case 39: // ' + escape = '''; + break; + case 60: // < + escape = '<'; + break; + case 62: // > + escape = '>'; + break; + default: + continue; + } + + if (lastIndex !== index) { + html += str.substring(lastIndex, index); + } + + lastIndex = index + 1; + html += escape; } - return stream + return lastIndex !== index + ? html + str.substring(lastIndex, index) + : html; } -/** - * Destroy a ReadStream. - * - * @param {object} stream - * @private - */ -function destroyReadStream(stream) { - stream.destroy() +/***/ }), - if (typeof stream.close === 'function') { - // node.js core bug work-around - stream.on('open', onOpenClose) - } +/***/ 98691: +/***/ ((module) => { - return stream -} +"use strict"; -/** - * On open handler to close stream. - * @private - */ -function onOpenClose() { - if (typeof this.fd === 'number') { - // actually close down the fd - this.close() - } -} +module.exports = string => { + if (typeof string !== 'string') { + throw new TypeError('Expected a string'); + } + + // Escape characters with special meaning either inside or outside character sets. + // Use a simple backslash escape when it’s always valid, and a \unnnn escape when the simpler form would be disallowed by Unicode patterns’ stricter grammar. + return string + .replace(/[|\\{}()[\]^$+*?.]/g, '\\$&') + .replace(/-/g, '\\x2d'); +}; /***/ }), -/***/ 12437: +/***/ 69972: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/* @flow */ -/*:: +"use strict"; +/*! + * etag + * Copyright(c) 2014-2016 Douglas Christopher Wilson + * MIT Licensed + */ -type DotenvParseOptions = { - debug?: boolean -} -// keys and values from src -type DotenvParseOutput = { [string]: string } -type DotenvConfigOptions = { - path?: string, // path to .env file - encoding?: string, // encoding of .env file - debug?: string // turn on logging for debugging purposes -} +/** + * Module exports. + * @public + */ -type DotenvConfigOutput = { - parsed?: DotenvParseOutput, - error?: Error -} +module.exports = etag -*/ - -const fs = __nccwpck_require__(57147) -const path = __nccwpck_require__(71017) +/** + * Module dependencies. + * @private + */ -function log (message /*: string */) { - console.log(`[dotenv][DEBUG] ${message}`) -} +var crypto = __nccwpck_require__(6113) +var Stats = (__nccwpck_require__(57147).Stats) -const NEWLINE = '\n' -const RE_INI_KEY_VAL = /^\s*([\w.-]+)\s*=\s*(.*)?\s*$/ -const RE_NEWLINES = /\\n/g -const NEWLINES_MATCH = /\n|\r|\r\n/ +/** + * Module variables. + * @private + */ -// Parses src into an Object -function parse (src /*: string | Buffer */, options /*: ?DotenvParseOptions */) /*: DotenvParseOutput */ { - const debug = Boolean(options && options.debug) - const obj = {} +var toString = Object.prototype.toString - // convert Buffers before splitting into lines and processing - src.toString().split(NEWLINES_MATCH).forEach(function (line, idx) { - // matching "KEY' and 'VAL' in 'KEY=VAL' - const keyValueArr = line.match(RE_INI_KEY_VAL) - // matched? - if (keyValueArr != null) { - const key = keyValueArr[1] - // default undefined or missing values to empty string - let val = (keyValueArr[2] || '') - const end = val.length - 1 - const isDoubleQuoted = val[0] === '"' && val[end] === '"' - const isSingleQuoted = val[0] === "'" && val[end] === "'" +/** + * Generate an entity tag. + * + * @param {Buffer|string} entity + * @return {string} + * @private + */ - // if single or double quoted, remove quotes - if (isSingleQuoted || isDoubleQuoted) { - val = val.substring(1, end) +function entitytag (entity) { + if (entity.length === 0) { + // fast-path empty + return '"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk"' + } - // if double quoted, expand newlines - if (isDoubleQuoted) { - val = val.replace(RE_NEWLINES, NEWLINE) - } - } else { - // remove surrounding whitespace - val = val.trim() - } + // compute hash of entity + var hash = crypto + .createHash('sha1') + .update(entity, 'utf8') + .digest('base64') + .substring(0, 27) - obj[key] = val - } else if (debug) { - log(`did not match key and value when parsing line ${idx + 1}: ${line}`) - } - }) + // compute length of entity + var len = typeof entity === 'string' + ? Buffer.byteLength(entity, 'utf8') + : entity.length - return obj + return '"' + len.toString(16) + '-' + hash + '"' } -// Populates process.env from .env file -function config (options /*: ?DotenvConfigOptions */) /*: DotenvConfigOutput */ { - let dotenvPath = path.resolve(process.cwd(), '.env') - let encoding /*: string */ = 'utf8' - let debug = false +/** + * Create a simple ETag. + * + * @param {string|Buffer|Stats} entity + * @param {object} [options] + * @param {boolean} [options.weak] + * @return {String} + * @public + */ - if (options) { - if (options.path != null) { - dotenvPath = options.path - } - if (options.encoding != null) { - encoding = options.encoding - } - if (options.debug != null) { - debug = true - } +function etag (entity, options) { + if (entity == null) { + throw new TypeError('argument entity is required') } - try { - // specifying an encoding returns a string instead of a buffer - const parsed = parse(fs.readFileSync(dotenvPath, { encoding }), { debug }) - - Object.keys(parsed).forEach(function (key) { - if (!Object.prototype.hasOwnProperty.call(process.env, key)) { - process.env[key] = parsed[key] - } else if (debug) { - log(`"${key}" is already defined in \`process.env\` and will not be overwritten`) - } - }) + // support fs.Stats object + var isStats = isstats(entity) + var weak = options && typeof options.weak === 'boolean' + ? options.weak + : isStats - return { parsed } - } catch (e) { - return { error: e } + // validate argument + if (!isStats && typeof entity !== 'string' && !Buffer.isBuffer(entity)) { + throw new TypeError('argument entity must be string, Buffer, or fs.Stats') } + + // generate entity tag + var tag = isStats + ? stattag(entity) + : entitytag(entity) + + return weak + ? 'W/' + tag + : tag } -module.exports.config = config -module.exports.parse = parse +/** + * Determine if object is a Stats object. + * + * @param {object} obj + * @return {boolean} + * @api private + */ +function isstats (obj) { + // genuine fs.Stats + if (typeof Stats === 'function' && obj instanceof Stats) { + return true + } -/***/ }), + // quack quack + return obj && typeof obj === 'object' && + 'ctime' in obj && toString.call(obj.ctime) === '[object Date]' && + 'mtime' in obj && toString.call(obj.mtime) === '[object Date]' && + 'ino' in obj && typeof obj.ino === 'number' && + 'size' in obj && typeof obj.size === 'number' +} -/***/ 11728: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/** + * Generate a tag for a stat. + * + * @param {object} stat + * @return {string} + * @private + */ -"use strict"; +function stattag (stat) { + var mtime = stat.mtime.getTime().toString(16) + var size = stat.size.toString(16) + return '"' + size + '-' + mtime + '"' +} -var Buffer = (__nccwpck_require__(21867).Buffer); -var getParamBytesForAlg = __nccwpck_require__(30528); +/***/ }), -var MAX_OCTET = 0x80, - CLASS_UNIVERSAL = 0, - PRIMITIVE_BIT = 0x20, - TAG_SEQ = 0x10, - TAG_INT = 0x02, - ENCODED_TAG_SEQ = (TAG_SEQ | PRIMITIVE_BIT) | (CLASS_UNIVERSAL << 6), - ENCODED_TAG_INT = TAG_INT | (CLASS_UNIVERSAL << 6); +/***/ 71204: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -function base64Url(base64) { - return base64 - .replace(/=/g, '') - .replace(/\+/g, '-') - .replace(/\//g, '_'); -} +"use strict"; +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ -function signatureAsBuffer(signature) { - if (Buffer.isBuffer(signature)) { - return signature; - } else if ('string' === typeof signature) { - return Buffer.from(signature, 'base64'); - } - throw new TypeError('ECDSA signature must be a Base64 string or a Buffer'); -} -function derToJose(signature, alg) { - signature = signatureAsBuffer(signature); - var paramBytes = getParamBytesForAlg(alg); +module.exports = __nccwpck_require__(22587); - // the DER encoded param should at most be the param size, plus a padding - // zero, since due to being a signed integer - var maxEncodedParamLength = paramBytes + 1; - var inputLength = signature.length; +/***/ }), - var offset = 0; - if (signature[offset++] !== ENCODED_TAG_SEQ) { - throw new Error('Could not find expected "seq"'); - } +/***/ 313: +/***/ ((module, exports, __nccwpck_require__) => { - var seqLength = signature[offset++]; - if (seqLength === (MAX_OCTET | 1)) { - seqLength = signature[offset++]; - } +"use strict"; +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ - if (inputLength - offset < seqLength) { - throw new Error('"seq" specified length of "' + seqLength + '", only "' + (inputLength - offset) + '" remaining'); - } - if (signature[offset++] !== ENCODED_TAG_INT) { - throw new Error('Could not find expected "int" for "r"'); - } - var rLength = signature[offset++]; +/** + * Module dependencies. + * @private + */ - if (inputLength - offset - 2 < rLength) { - throw new Error('"r" specified length of "' + rLength + '", only "' + (inputLength - offset - 2) + '" available'); - } +var finalhandler = __nccwpck_require__(30810); +var Router = __nccwpck_require__(24963); +var methods = __nccwpck_require__(58752); +var middleware = __nccwpck_require__(92636); +var query = __nccwpck_require__(79768); +var debug = __nccwpck_require__(52529)('express:application'); +var View = __nccwpck_require__(99209); +var http = __nccwpck_require__(13685); +var compileETag = (__nccwpck_require__(53561).compileETag); +var compileQueryParser = (__nccwpck_require__(53561).compileQueryParser); +var compileTrust = (__nccwpck_require__(53561).compileTrust); +var deprecate = __nccwpck_require__(18883)('express'); +var flatten = __nccwpck_require__(62003); +var merge = __nccwpck_require__(44429); +var resolve = (__nccwpck_require__(71017).resolve); +var setPrototypeOf = __nccwpck_require__(40414) +var slice = Array.prototype.slice; - if (maxEncodedParamLength < rLength) { - throw new Error('"r" specified length of "' + rLength + '", max of "' + maxEncodedParamLength + '" is acceptable'); - } +/** + * Application prototype. + */ - var rOffset = offset; - offset += rLength; +var app = exports = module.exports = {}; - if (signature[offset++] !== ENCODED_TAG_INT) { - throw new Error('Could not find expected "int" for "s"'); - } +/** + * Variable for trust proxy inheritance back-compat + * @private + */ - var sLength = signature[offset++]; +var trustProxyDefaultSymbol = '@@symbol:trust_proxy_default'; - if (inputLength - offset !== sLength) { - throw new Error('"s" specified length of "' + sLength + '", expected "' + (inputLength - offset) + '"'); - } +/** + * Initialize the server. + * + * - setup default configuration + * - setup default middleware + * - setup route reflection methods + * + * @private + */ - if (maxEncodedParamLength < sLength) { - throw new Error('"s" specified length of "' + sLength + '", max of "' + maxEncodedParamLength + '" is acceptable'); - } +app.init = function init() { + this.cache = {}; + this.engines = {}; + this.settings = {}; - var sOffset = offset; - offset += sLength; + this.defaultConfiguration(); +}; - if (offset !== inputLength) { - throw new Error('Expected to consume entire buffer, but "' + (inputLength - offset) + '" bytes remain'); - } +/** + * Initialize application configuration. + * @private + */ - var rPadding = paramBytes - rLength, - sPadding = paramBytes - sLength; +app.defaultConfiguration = function defaultConfiguration() { + var env = process.env.NODE_ENV || 'development'; - var dst = Buffer.allocUnsafe(rPadding + rLength + sPadding + sLength); + // default settings + this.enable('x-powered-by'); + this.set('etag', 'weak'); + this.set('env', env); + this.set('query parser', 'extended'); + this.set('subdomain offset', 2); + this.set('trust proxy', false); - for (offset = 0; offset < rPadding; ++offset) { - dst[offset] = 0; - } - signature.copy(dst, offset, rOffset + Math.max(-rPadding, 0), rOffset + rLength); + // trust proxy inherit back-compat + Object.defineProperty(this.settings, trustProxyDefaultSymbol, { + configurable: true, + value: true + }); - offset = paramBytes; + debug('booting in %s mode', env); - for (var o = offset; offset < o + sPadding; ++offset) { - dst[offset] = 0; - } - signature.copy(dst, offset, sOffset + Math.max(-sPadding, 0), sOffset + sLength); + this.on('mount', function onmount(parent) { + // inherit trust proxy + if (this.settings[trustProxyDefaultSymbol] === true + && typeof parent.settings['trust proxy fn'] === 'function') { + delete this.settings['trust proxy']; + delete this.settings['trust proxy fn']; + } - dst = dst.toString('base64'); - dst = base64Url(dst); + // inherit protos + setPrototypeOf(this.request, parent.request) + setPrototypeOf(this.response, parent.response) + setPrototypeOf(this.engines, parent.engines) + setPrototypeOf(this.settings, parent.settings) + }); - return dst; -} + // setup locals + this.locals = Object.create(null); -function countPadding(buf, start, stop) { - var padding = 0; - while (start + padding < stop && buf[start + padding] === 0) { - ++padding; - } + // top-most app is mounted at / + this.mountpath = '/'; - var needsSign = buf[start + padding] >= MAX_OCTET; - if (needsSign) { - --padding; - } + // default locals + this.locals.settings = this.settings; - return padding; -} + // default configuration + this.set('view', View); + this.set('views', resolve('views')); + this.set('jsonp callback name', 'callback'); -function joseToDer(signature, alg) { - signature = signatureAsBuffer(signature); - var paramBytes = getParamBytesForAlg(alg); + if (env === 'production') { + this.enable('view cache'); + } - var signatureBytes = signature.length; - if (signatureBytes !== paramBytes * 2) { - throw new TypeError('"' + alg + '" signatures must be "' + paramBytes * 2 + '" bytes, saw "' + signatureBytes + '"'); - } + Object.defineProperty(this, 'router', { + get: function() { + throw new Error('\'app.router\' is deprecated!\nPlease see the 3.x to 4.x migration guide for details on how to update your app.'); + } + }); +}; - var rPadding = countPadding(signature, 0, paramBytes); - var sPadding = countPadding(signature, paramBytes, signature.length); - var rLength = paramBytes - rPadding; - var sLength = paramBytes - sPadding; +/** + * lazily adds the base router if it has not yet been added. + * + * We cannot add the base router in the defaultConfiguration because + * it reads app settings which might be set after that has run. + * + * @private + */ +app.lazyrouter = function lazyrouter() { + if (!this._router) { + this._router = new Router({ + caseSensitive: this.enabled('case sensitive routing'), + strict: this.enabled('strict routing') + }); - var rsBytes = 1 + 1 + rLength + 1 + 1 + sLength; + this._router.use(query(this.get('query parser fn'))); + this._router.use(middleware.init(this)); + } +}; - var shortLength = rsBytes < MAX_OCTET; +/** + * Dispatch a req, res pair into the application. Starts pipeline processing. + * + * If no callback is provided, then default error handlers will respond + * in the event of an error bubbling through the stack. + * + * @private + */ - var dst = Buffer.allocUnsafe((shortLength ? 2 : 3) + rsBytes); +app.handle = function handle(req, res, callback) { + var router = this._router; - var offset = 0; - dst[offset++] = ENCODED_TAG_SEQ; - if (shortLength) { - // Bit 8 has value "0" - // bits 7-1 give the length. - dst[offset++] = rsBytes; - } else { - // Bit 8 of first octet has value "1" - // bits 7-1 give the number of additional length octets. - dst[offset++] = MAX_OCTET | 1; - // length, base 256 - dst[offset++] = rsBytes & 0xff; - } - dst[offset++] = ENCODED_TAG_INT; - dst[offset++] = rLength; - if (rPadding < 0) { - dst[offset++] = 0; - offset += signature.copy(dst, offset, 0, paramBytes); - } else { - offset += signature.copy(dst, offset, rPadding, paramBytes); - } - dst[offset++] = ENCODED_TAG_INT; - dst[offset++] = sLength; - if (sPadding < 0) { - dst[offset++] = 0; - signature.copy(dst, offset, paramBytes); - } else { - signature.copy(dst, offset, paramBytes + sPadding); - } + // final handler + var done = callback || finalhandler(req, res, { + env: this.get('env'), + onerror: logerror.bind(this) + }); - return dst; -} + // no routes + if (!router) { + debug('no routes defined on app'); + done(); + return; + } -module.exports = { - derToJose: derToJose, - joseToDer: joseToDer + router.handle(req, res, done); }; +/** + * Proxy `Router#use()` to add middleware to the app router. + * See Router#use() documentation for details. + * + * If the _fn_ parameter is an express app, then it will be + * mounted at the _route_ specified. + * + * @public + */ -/***/ }), +app.use = function use(fn) { + var offset = 0; + var path = '/'; -/***/ 30528: -/***/ ((module) => { + // default path to '/' + // disambiguate app.use([fn]) + if (typeof fn !== 'function') { + var arg = fn; -"use strict"; + while (Array.isArray(arg) && arg.length !== 0) { + arg = arg[0]; + } + // first arg is the path + if (typeof arg !== 'function') { + offset = 1; + path = fn; + } + } -function getParamSize(keySize) { - var result = ((keySize / 8) | 0) + (keySize % 8 === 0 ? 0 : 1); - return result; -} + var fns = flatten(slice.call(arguments, offset)); -var paramBytesForAlg = { - ES256: getParamSize(256), - ES384: getParamSize(384), - ES512: getParamSize(521) -}; - -function getParamBytesForAlg(alg) { - var paramBytes = paramBytesForAlg[alg]; - if (paramBytes) { - return paramBytes; - } - - throw new Error('Unknown algorithm "' + alg + '"'); -} - -module.exports = getParamBytesForAlg; + if (fns.length === 0) { + throw new TypeError('app.use() requires a middleware function') + } + // setup router + this.lazyrouter(); + var router = this._router; -/***/ }), + fns.forEach(function (fn) { + // non-express app + if (!fn || !fn.handle || !fn.set) { + return router.use(path, fn); + } -/***/ 14401: -/***/ ((module) => { + debug('.use app under %s', path); + fn.mountpath = path; + fn.parent = this; -"use strict"; -/*! - * ee-first - * Copyright(c) 2014 Jonathan Ong - * MIT Licensed - */ + // restore .app property on req and res + router.use(path, function mounted_app(req, res, next) { + var orig = req.app; + fn.handle(req, res, function (err) { + setPrototypeOf(req, orig.request) + setPrototypeOf(res, orig.response) + next(err); + }); + }); + // mounted an app + fn.emit('mount', this); + }, this); + return this; +}; /** - * Module exports. + * Proxy to the app `Router#route()` + * Returns a new `Route` instance for the _path_. + * + * Routes are isolated middleware stacks for specific paths. + * See the Route api docs for details. + * * @public */ -module.exports = first +app.route = function route(path) { + this.lazyrouter(); + return this._router.route(path); +}; /** - * Get the first event in a set of event emitters and event pairs. + * Register the given template engine callback `fn` + * as `ext`. * - * @param {array} stuff - * @param {function} done + * By default will `require()` the engine based on the + * file extension. For example if you try to render + * a "foo.ejs" file Express will invoke the following internally: + * + * app.engine('ejs', require('ejs').__express); + * + * For engines that do not provide `.__express` out of the box, + * or if you wish to "map" a different extension to the template engine + * you may use this method. For example mapping the EJS template engine to + * ".html" files: + * + * app.engine('html', require('ejs').renderFile); + * + * In this case EJS provides a `.renderFile()` method with + * the same signature that Express expects: `(path, options, callback)`, + * though note that it aliases this method as `ejs.__express` internally + * so if you're using ".ejs" extensions you don't need to do anything. + * + * Some template engines do not follow this convention, the + * [Consolidate.js](https://github.com/tj/consolidate.js) + * library was created to map all of node's popular template + * engines to follow this convention, thus allowing them to + * work seamlessly within Express. + * + * @param {String} ext + * @param {Function} fn + * @return {app} for chaining * @public */ -function first(stuff, done) { - if (!Array.isArray(stuff)) - throw new TypeError('arg must be an array of [ee, events...] arrays') - - var cleanups = [] - - for (var i = 0; i < stuff.length; i++) { - var arr = stuff[i] +app.engine = function engine(ext, fn) { + if (typeof fn !== 'function') { + throw new Error('callback function required'); + } - if (!Array.isArray(arr) || arr.length < 2) - throw new TypeError('each array member must be [ee, events...]') + // get file extension + var extension = ext[0] !== '.' + ? '.' + ext + : ext; - var ee = arr[0] + // store engine + this.engines[extension] = fn; - for (var j = 1; j < arr.length; j++) { - var event = arr[j] - var fn = listener(event, callback) + return this; +}; - // listen to the event - ee.on(event, fn) - // push this listener to the list of cleanups - cleanups.push({ - ee: ee, - event: event, - fn: fn, - }) - } - } +/** + * Proxy to `Router#param()` with one added api feature. The _name_ parameter + * can be an array of names. + * + * See the Router#param() docs for more details. + * + * @param {String|Array} name + * @param {Function} fn + * @return {app} for chaining + * @public + */ - function callback() { - cleanup() - done.apply(null, arguments) - } +app.param = function param(name, fn) { + this.lazyrouter(); - function cleanup() { - var x - for (var i = 0; i < cleanups.length; i++) { - x = cleanups[i] - x.ee.removeListener(x.event, x.fn) + if (Array.isArray(name)) { + for (var i = 0; i < name.length; i++) { + this.param(name[i], fn); } - } - function thunk(fn) { - done = fn + return this; } - thunk.cancel = cleanup + this._router.param(name, fn); - return thunk -} + return this; +}; /** - * Create the event listener. - * @private + * Assign `setting` to `val`, or return `setting`'s value. + * + * app.set('foo', 'bar'); + * app.set('foo'); + * // => "bar" + * + * Mounted servers inherit their parent server's settings. + * + * @param {String} setting + * @param {*} [val] + * @return {Server} for chaining + * @public */ -function listener(event, done) { - return function onevent(arg1) { - var args = new Array(arguments.length) - var ee = this - var err = event === 'error' - ? arg1 - : null - - // copy args to prevent arguments escaping scope - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i] - } - - done(err, ee, event, args) +app.set = function set(setting, val) { + if (arguments.length === 1) { + // app.get(setting) + return this.settings[setting]; } -} + debug('set "%s" to %o', setting, val); -/***/ }), + // set value + this.settings[setting] = val; -/***/ 18212: -/***/ ((module) => { + // trigger matched settings + switch (setting) { + case 'etag': + this.set('etag fn', compileETag(val)); + break; + case 'query parser': + this.set('query parser fn', compileQueryParser(val)); + break; + case 'trust proxy': + this.set('trust proxy fn', compileTrust(val)); -"use strict"; + // trust proxy inherit back-compat + Object.defineProperty(this.settings, trustProxyDefaultSymbol, { + configurable: true, + value: false + }); + break; + } -module.exports = function () { - // https://mths.be/emoji - return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|\uD83D\uDC68(?:\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68\uD83C\uDFFB|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C[\uDFFB-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)\uD83C\uDFFB|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB\uDFFC])|\uD83D\uDC69(?:\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB-\uDFFD])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83C\uDFF4\u200D\u2620)\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF4\uD83C\uDDF2|\uD83C\uDDF6\uD83C\uDDE6|[#\*0-9]\uFE0F\u20E3|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDBB\uDDD2-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g; + return this; }; +/** + * Return the app's absolute pathname + * based on the parent(s) that have + * mounted it. + * + * For example if the application was + * mounted as "/admin", which itself + * was mounted as "/blog" then the + * return value would be "/blog/admin". + * + * @return {String} + * @private + */ -/***/ }), - -/***/ 16592: -/***/ ((module) => { +app.path = function path() { + return this.parent + ? this.parent.path() + this.mountpath + : ''; +}; -"use strict"; -/*! - * encodeurl - * Copyright(c) 2016 Douglas Christopher Wilson - * MIT Licensed +/** + * Check if `setting` is enabled (truthy). + * + * app.enabled('foo') + * // => false + * + * app.enable('foo') + * app.enabled('foo') + * // => true + * + * @param {String} setting + * @return {Boolean} + * @public */ - +app.enabled = function enabled(setting) { + return Boolean(this.set(setting)); +}; /** - * Module exports. + * Check if `setting` is disabled. + * + * app.disabled('foo') + * // => true + * + * app.enable('foo') + * app.disabled('foo') + * // => false + * + * @param {String} setting + * @return {Boolean} * @public */ -module.exports = encodeUrl +app.disabled = function disabled(setting) { + return !this.set(setting); +}; /** - * RegExp to match non-URL code points, *after* encoding (i.e. not including "%") - * and including invalid escape sequences. - * @private + * Enable `setting`. + * + * @param {String} setting + * @return {app} for chaining + * @public */ -var ENCODE_CHARS_REGEXP = /(?:[^\x21\x25\x26-\x3B\x3D\x3F-\x5B\x5D\x5F\x61-\x7A\x7E]|%(?:[^0-9A-Fa-f]|[0-9A-Fa-f][^0-9A-Fa-f]|$))+/g +app.enable = function enable(setting) { + return this.set(setting, true); +}; /** - * RegExp to match unmatched surrogate pair. - * @private + * Disable `setting`. + * + * @param {String} setting + * @return {app} for chaining + * @public */ -var UNMATCHED_SURROGATE_PAIR_REGEXP = /(^|[^\uD800-\uDBFF])[\uDC00-\uDFFF]|[\uD800-\uDBFF]([^\uDC00-\uDFFF]|$)/g +app.disable = function disable(setting) { + return this.set(setting, false); +}; /** - * String to replace unmatched surrogate pair with. - * @private + * Delegate `.VERB(...)` calls to `router.VERB(...)`. */ -var UNMATCHED_SURROGATE_PAIR_REPLACE = '$1\uFFFD$2' +methods.forEach(function(method){ + app[method] = function(path){ + if (method === 'get' && arguments.length === 1) { + // app.get(setting) + return this.set(path); + } + + this.lazyrouter(); + + var route = this._router.route(path); + route[method].apply(route, slice.call(arguments, 1)); + return this; + }; +}); /** - * Encode a URL to a percent-encoded form, excluding already-encoded sequences. - * - * This function will take an already-encoded URL and encode all the non-URL - * code points. This function will not encode the "%" character unless it is - * not part of a valid sequence (`%20` will be left as-is, but `%foo` will - * be encoded as `%25foo`). - * - * This encode is meant to be "safe" and does not throw errors. It will try as - * hard as it can to properly encode the given URL, including replacing any raw, - * unpaired surrogate pairs with the Unicode replacement character prior to - * encoding. + * Special-cased "all" method, applying the given route `path`, + * middleware, and callback to _every_ HTTP method. * - * @param {string} url - * @return {string} + * @param {String} path + * @param {Function} ... + * @return {app} for chaining * @public */ -function encodeUrl (url) { - return String(url) - .replace(UNMATCHED_SURROGATE_PAIR_REGEXP, UNMATCHED_SURROGATE_PAIR_REPLACE) - .replace(ENCODE_CHARS_REGEXP, encodeURI) -} +app.all = function all(path) { + this.lazyrouter(); + var route = this._router.route(path); + var args = slice.call(arguments, 1); -/***/ }), + for (var i = 0; i < methods.length; i++) { + route[methods[i]].apply(route, args); + } -/***/ 23505: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return this; +}; -"use strict"; +// del -> delete alias +app.del = deprecate.function(app.delete, 'app.del: Use app.delete instead'); -var util = __nccwpck_require__(73837); -var isArrayish = __nccwpck_require__(7604); +/** + * Render the given view `name` name with `options` + * and a callback accepting an error and the + * rendered template string. + * + * Example: + * + * app.render('email', { name: 'Tobi' }, function(err, html){ + * // ... + * }) + * + * @param {String} name + * @param {Object|Function} options or fn + * @param {Function} callback + * @public + */ -var errorEx = function errorEx(name, properties) { - if (!name || name.constructor !== String) { - properties = name || {}; - name = Error.name; - } +app.render = function render(name, options, callback) { + var cache = this.cache; + var done = callback; + var engines = this.engines; + var opts = options; + var renderOptions = {}; + var view; - var errorExError = function ErrorEXError(message) { - if (!this) { - return new ErrorEXError(message); - } + // support callback function as second arg + if (typeof options === 'function') { + done = options; + opts = {}; + } - message = message instanceof Error - ? message.message - : (message || this.message); + // merge app.locals + merge(renderOptions, this.locals); - Error.call(this, message); - Error.captureStackTrace(this, errorExError); + // merge options._locals + if (opts._locals) { + merge(renderOptions, opts._locals); + } - this.name = name; + // merge options + merge(renderOptions, opts); - Object.defineProperty(this, 'message', { - configurable: true, - enumerable: false, - get: function () { - var newMessage = message.split(/\r?\n/g); + // set .cache unless explicitly provided + if (renderOptions.cache == null) { + renderOptions.cache = this.enabled('view cache'); + } - for (var key in properties) { - if (!properties.hasOwnProperty(key)) { - continue; - } + // primed cache + if (renderOptions.cache) { + view = cache[name]; + } - var modifier = properties[key]; + // view + if (!view) { + var View = this.get('view'); - if ('message' in modifier) { - newMessage = modifier.message(this[key], newMessage) || newMessage; - if (!isArrayish(newMessage)) { - newMessage = [newMessage]; - } - } - } + view = new View(name, { + defaultEngine: this.get('view engine'), + root: this.get('views'), + engines: engines + }); - return newMessage.join('\n'); - }, - set: function (v) { - message = v; - } - }); + if (!view.path) { + var dirs = Array.isArray(view.root) && view.root.length > 1 + ? 'directories "' + view.root.slice(0, -1).join('", "') + '" or "' + view.root[view.root.length - 1] + '"' + : 'directory "' + view.root + '"' + var err = new Error('Failed to lookup view "' + name + '" in views ' + dirs); + err.view = view; + return done(err); + } - var overwrittenStack = null; + // prime the cache + if (renderOptions.cache) { + cache[name] = view; + } + } - var stackDescriptor = Object.getOwnPropertyDescriptor(this, 'stack'); - var stackGetter = stackDescriptor.get; - var stackValue = stackDescriptor.value; - delete stackDescriptor.value; - delete stackDescriptor.writable; + // render + tryRender(view, renderOptions, done); +}; - stackDescriptor.set = function (newstack) { - overwrittenStack = newstack; - }; +/** + * Listen for connections. + * + * A node `http.Server` is returned, with this + * application (which is a `Function`) as its + * callback. If you wish to create both an HTTP + * and HTTPS server you may do so with the "http" + * and "https" modules as shown here: + * + * var http = require('http') + * , https = require('https') + * , express = require('express') + * , app = express(); + * + * http.createServer(app).listen(80); + * https.createServer({ ... }, app).listen(443); + * + * @return {http.Server} + * @public + */ - stackDescriptor.get = function () { - var stack = (overwrittenStack || ((stackGetter) - ? stackGetter.call(this) - : stackValue)).split(/\r?\n+/g); +app.listen = function listen() { + var server = http.createServer(this); + return server.listen.apply(server, arguments); +}; - // starting in Node 7, the stack builder caches the message. - // just replace it. - if (!overwrittenStack) { - stack[0] = this.name + ': ' + this.message; - } - - var lineCount = 1; - for (var key in properties) { - if (!properties.hasOwnProperty(key)) { - continue; - } - - var modifier = properties[key]; - - if ('line' in modifier) { - var line = modifier.line(this[key]); - if (line) { - stack.splice(lineCount++, 0, ' ' + line); - } - } - - if ('stack' in modifier) { - modifier.stack(this[key], stack); - } - } - - return stack.join('\n'); - }; - - Object.defineProperty(this, 'stack', stackDescriptor); - }; - - if (Object.setPrototypeOf) { - Object.setPrototypeOf(errorExError.prototype, Error.prototype); - Object.setPrototypeOf(errorExError, Error); - } else { - util.inherits(errorExError, Error); - } - - return errorExError; -}; - -errorEx.append = function (str, def) { - return { - message: function (v, message) { - v = v || def; - - if (v) { - message[0] += ' ' + str.replace('%s', v.toString()); - } - - return message; - } - }; -}; - -errorEx.line = function (str, def) { - return { - line: function (v) { - v = v || def; +/** + * Log error using console.error. + * + * @param {Error} err + * @private + */ - if (v) { - return str.replace('%s', v.toString()); - } +function logerror(err) { + /* istanbul ignore next */ + if (this.get('env') !== 'test') console.error(err.stack || err.toString()); +} - return null; - } - }; -}; +/** + * Try rendering a view. + * @private + */ -module.exports = errorEx; +function tryRender(view, options, callback) { + try { + view.render(options, callback); + } catch (err) { + callback(err); + } +} /***/ }), -/***/ 94070: -/***/ ((module) => { +/***/ 22587: +/***/ ((module, exports, __nccwpck_require__) => { "use strict"; /*! - * escape-html - * Copyright(c) 2012-2013 TJ Holowaychuk - * Copyright(c) 2015 Andreas Lubbe - * Copyright(c) 2015 Tiancheng "Timothy" Gu + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson * MIT Licensed */ /** - * Module variables. - * @private + * Module dependencies. */ -var matchHtmlRegExp = /["'&<>]/; +var bodyParser = __nccwpck_require__(97076) +var EventEmitter = (__nccwpck_require__(82361).EventEmitter); +var mixin = __nccwpck_require__(11149); +var proto = __nccwpck_require__(313); +var Route = __nccwpck_require__(23699); +var Router = __nccwpck_require__(24963); +var req = __nccwpck_require__(71260); +var res = __nccwpck_require__(64934); /** - * Module exports. - * @public + * Expose `createApplication()`. */ -module.exports = escapeHtml; +exports = module.exports = createApplication; /** - * Escape special characters in the given string of html. + * Create an express application. * - * @param {string} string The string to escape for inserting into HTML - * @return {string} - * @public + * @return {Function} + * @api public */ -function escapeHtml(string) { - var str = '' + string; - var match = matchHtmlRegExp.exec(str); - - if (!match) { - return str; - } - - var escape; - var html = ''; - var index = 0; - var lastIndex = 0; +function createApplication() { + var app = function(req, res, next) { + app.handle(req, res, next); + }; - for (index = match.index; index < str.length; index++) { - switch (str.charCodeAt(index)) { - case 34: // " - escape = '"'; - break; - case 38: // & - escape = '&'; - break; - case 39: // ' - escape = '''; - break; - case 60: // < - escape = '<'; - break; - case 62: // > - escape = '>'; - break; - default: - continue; - } + mixin(app, EventEmitter.prototype, false); + mixin(app, proto, false); - if (lastIndex !== index) { - html += str.substring(lastIndex, index); - } + // expose the prototype that will get set on requests + app.request = Object.create(req, { + app: { configurable: true, enumerable: true, writable: true, value: app } + }) - lastIndex = index + 1; - html += escape; - } + // expose the prototype that will get set on responses + app.response = Object.create(res, { + app: { configurable: true, enumerable: true, writable: true, value: app } + }) - return lastIndex !== index - ? html + str.substring(lastIndex, index) - : html; + app.init(); + return app; } - -/***/ }), - -/***/ 98691: -/***/ ((module) => { - -"use strict"; - - -module.exports = string => { - if (typeof string !== 'string') { - throw new TypeError('Expected a string'); - } - - // Escape characters with special meaning either inside or outside character sets. - // Use a simple backslash escape when it’s always valid, and a \unnnn escape when the simpler form would be disallowed by Unicode patterns’ stricter grammar. - return string - .replace(/[|\\{}()[\]^$+*?.]/g, '\\$&') - .replace(/-/g, '\\x2d'); -}; - - -/***/ }), - -/***/ 69972: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -/*! - * etag - * Copyright(c) 2014-2016 Douglas Christopher Wilson - * MIT Licensed - */ - - - /** - * Module exports. - * @public + * Expose the prototypes. */ -module.exports = etag +exports.application = proto; +exports.request = req; +exports.response = res; /** - * Module dependencies. - * @private + * Expose constructors. */ -var crypto = __nccwpck_require__(6113) -var Stats = (__nccwpck_require__(57147).Stats) +exports.Route = Route; +exports.Router = Router; /** - * Module variables. - * @private + * Expose middleware */ -var toString = Object.prototype.toString +exports.json = bodyParser.json +exports.query = __nccwpck_require__(79768); +exports.raw = bodyParser.raw +exports["static"] = __nccwpck_require__(13146); +exports.text = bodyParser.text +exports.urlencoded = bodyParser.urlencoded /** - * Generate an entity tag. - * - * @param {Buffer|string} entity - * @return {string} - * @private + * Replace removed middleware with an appropriate error message. */ -function entitytag (entity) { - if (entity.length === 0) { - // fast-path empty - return '"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk"' - } +var removedMiddlewares = [ + 'bodyParser', + 'compress', + 'cookieSession', + 'session', + 'logger', + 'cookieParser', + 'favicon', + 'responseTime', + 'errorHandler', + 'timeout', + 'methodOverride', + 'vhost', + 'csrf', + 'directory', + 'limit', + 'multipart', + 'staticCache' +] - // compute hash of entity - var hash = crypto - .createHash('sha1') - .update(entity, 'utf8') - .digest('base64') - .substring(0, 27) +removedMiddlewares.forEach(function (name) { + Object.defineProperty(exports, name, { + get: function () { + throw new Error('Most middleware (like ' + name + ') is no longer bundled with Express and must be installed separately. Please see https://github.com/senchalabs/connect#middleware.'); + }, + configurable: true + }); +}); - // compute length of entity - var len = typeof entity === 'string' - ? Buffer.byteLength(entity, 'utf8') - : entity.length - return '"' + len.toString(16) + '-' + hash + '"' -} +/***/ }), -/** - * Create a simple ETag. - * - * @param {string|Buffer|Stats} entity - * @param {object} [options] - * @param {boolean} [options.weak] - * @return {String} - * @public - */ +/***/ 92636: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -function etag (entity, options) { - if (entity == null) { - throw new TypeError('argument entity is required') - } +"use strict"; +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ - // support fs.Stats object - var isStats = isstats(entity) - var weak = options && typeof options.weak === 'boolean' - ? options.weak - : isStats - // validate argument - if (!isStats && typeof entity !== 'string' && !Buffer.isBuffer(entity)) { - throw new TypeError('argument entity must be string, Buffer, or fs.Stats') - } - // generate entity tag - var tag = isStats - ? stattag(entity) - : entitytag(entity) +/** + * Module dependencies. + * @private + */ - return weak - ? 'W/' + tag - : tag -} +var setPrototypeOf = __nccwpck_require__(40414) /** - * Determine if object is a Stats object. + * Initialization middleware, exposing the + * request and response to each other, as well + * as defaulting the X-Powered-By header field. * - * @param {object} obj - * @return {boolean} + * @param {Function} app + * @return {Function} * @api private */ -function isstats (obj) { - // genuine fs.Stats - if (typeof Stats === 'function' && obj instanceof Stats) { - return true - } +exports.init = function(app){ + return function expressInit(req, res, next){ + if (app.enabled('x-powered-by')) res.setHeader('X-Powered-By', 'Express'); + req.res = res; + res.req = req; + req.next = next; - // quack quack - return obj && typeof obj === 'object' && - 'ctime' in obj && toString.call(obj.ctime) === '[object Date]' && - 'mtime' in obj && toString.call(obj.mtime) === '[object Date]' && - 'ino' in obj && typeof obj.ino === 'number' && - 'size' in obj && typeof obj.size === 'number' -} + setPrototypeOf(req, app.request) + setPrototypeOf(res, app.response) -/** - * Generate a tag for a stat. - * - * @param {object} stat - * @return {string} - * @private - */ + res.locals = res.locals || Object.create(null); -function stattag (stat) { - var mtime = stat.mtime.getTime().toString(16) - var size = stat.size.toString(16) + next(); + }; +}; - return '"' + size + '-' + mtime + '"' -} /***/ }), -/***/ 71204: +/***/ 79768: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -38133,13 +37163,49 @@ function stattag (stat) { -module.exports = __nccwpck_require__(22587); +/** + * Module dependencies. + */ + +var merge = __nccwpck_require__(44429) +var parseUrl = __nccwpck_require__(89808); +var qs = __nccwpck_require__(22760); + +/** + * @param {Object} options + * @return {Function} + * @api public + */ + +module.exports = function query(options) { + var opts = merge({}, options) + var queryparse = qs.parse; + + if (typeof options === 'function') { + queryparse = options; + opts = undefined; + } + + if (opts !== undefined && opts.allowPrototypes === undefined) { + // back-compat for qs module + opts.allowPrototypes = true; + } + + return function query(req, res, next){ + if (!req.query) { + var val = parseUrl(req).query; + req.query = queryparse(val, opts); + } + + next(); + }; +}; /***/ }), -/***/ 313: -/***/ ((module, exports, __nccwpck_require__) => { +/***/ 71260: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /*! @@ -38157,647 +37223,527 @@ module.exports = __nccwpck_require__(22587); * @private */ -var finalhandler = __nccwpck_require__(30810); -var Router = __nccwpck_require__(24963); -var methods = __nccwpck_require__(58752); -var middleware = __nccwpck_require__(92636); -var query = __nccwpck_require__(79768); -var debug = __nccwpck_require__(52529)('express:application'); -var View = __nccwpck_require__(99209); -var http = __nccwpck_require__(13685); -var compileETag = (__nccwpck_require__(53561).compileETag); -var compileQueryParser = (__nccwpck_require__(53561).compileQueryParser); -var compileTrust = (__nccwpck_require__(53561).compileTrust); +var accepts = __nccwpck_require__(83633); var deprecate = __nccwpck_require__(18883)('express'); -var flatten = __nccwpck_require__(62003); -var merge = __nccwpck_require__(44429); -var resolve = (__nccwpck_require__(71017).resolve); -var setPrototypeOf = __nccwpck_require__(40414) -var slice = Array.prototype.slice; +var isIP = (__nccwpck_require__(41808).isIP); +var typeis = __nccwpck_require__(71159); +var http = __nccwpck_require__(13685); +var fresh = __nccwpck_require__(83136); +var parseRange = __nccwpck_require__(26435); +var parse = __nccwpck_require__(89808); +var proxyaddr = __nccwpck_require__(80140); /** - * Application prototype. + * Request prototype. + * @public */ -var app = exports = module.exports = {}; +var req = Object.create(http.IncomingMessage.prototype) /** - * Variable for trust proxy inheritance back-compat - * @private + * Module exports. + * @public */ -var trustProxyDefaultSymbol = '@@symbol:trust_proxy_default'; +module.exports = req /** - * Initialize the server. + * Return request header. * - * - setup default configuration - * - setup default middleware - * - setup route reflection methods + * The `Referrer` header field is special-cased, + * both `Referrer` and `Referer` are interchangeable. * - * @private + * Examples: + * + * req.get('Content-Type'); + * // => "text/plain" + * + * req.get('content-type'); + * // => "text/plain" + * + * req.get('Something'); + * // => undefined + * + * Aliased as `req.header()`. + * + * @param {String} name + * @return {String} + * @public */ -app.init = function init() { - this.cache = {}; - this.engines = {}; - this.settings = {}; +req.get = +req.header = function header(name) { + if (!name) { + throw new TypeError('name argument is required to req.get'); + } - this.defaultConfiguration(); + if (typeof name !== 'string') { + throw new TypeError('name must be a string to req.get'); + } + + var lc = name.toLowerCase(); + + switch (lc) { + case 'referer': + case 'referrer': + return this.headers.referrer + || this.headers.referer; + default: + return this.headers[lc]; + } }; /** - * Initialize application configuration. - * @private - */ - -app.defaultConfiguration = function defaultConfiguration() { - var env = process.env.NODE_ENV || 'development'; - - // default settings - this.enable('x-powered-by'); - this.set('etag', 'weak'); - this.set('env', env); - this.set('query parser', 'extended'); - this.set('subdomain offset', 2); - this.set('trust proxy', false); - - // trust proxy inherit back-compat - Object.defineProperty(this.settings, trustProxyDefaultSymbol, { - configurable: true, - value: true - }); - - debug('booting in %s mode', env); - - this.on('mount', function onmount(parent) { - // inherit trust proxy - if (this.settings[trustProxyDefaultSymbol] === true - && typeof parent.settings['trust proxy fn'] === 'function') { - delete this.settings['trust proxy']; - delete this.settings['trust proxy fn']; - } - - // inherit protos - setPrototypeOf(this.request, parent.request) - setPrototypeOf(this.response, parent.response) - setPrototypeOf(this.engines, parent.engines) - setPrototypeOf(this.settings, parent.settings) - }); - - // setup locals - this.locals = Object.create(null); - - // top-most app is mounted at / - this.mountpath = '/'; - - // default locals - this.locals.settings = this.settings; - - // default configuration - this.set('view', View); - this.set('views', resolve('views')); - this.set('jsonp callback name', 'callback'); - - if (env === 'production') { - this.enable('view cache'); - } - - Object.defineProperty(this, 'router', { - get: function() { - throw new Error('\'app.router\' is deprecated!\nPlease see the 3.x to 4.x migration guide for details on how to update your app.'); - } - }); -}; - -/** - * lazily adds the base router if it has not yet been added. + * To do: update docs. * - * We cannot add the base router in the defaultConfiguration because - * it reads app settings which might be set after that has run. + * Check if the given `type(s)` is acceptable, returning + * the best match when true, otherwise `undefined`, in which + * case you should respond with 406 "Not Acceptable". * - * @private + * The `type` value may be a single MIME type string + * such as "application/json", an extension name + * such as "json", a comma-delimited list such as "json, html, text/plain", + * an argument list such as `"json", "html", "text/plain"`, + * or an array `["json", "html", "text/plain"]`. When a list + * or array is given, the _best_ match, if any is returned. + * + * Examples: + * + * // Accept: text/html + * req.accepts('html'); + * // => "html" + * + * // Accept: text/*, application/json + * req.accepts('html'); + * // => "html" + * req.accepts('text/html'); + * // => "text/html" + * req.accepts('json, text'); + * // => "json" + * req.accepts('application/json'); + * // => "application/json" + * + * // Accept: text/*, application/json + * req.accepts('image/png'); + * req.accepts('png'); + * // => undefined + * + * // Accept: text/*;q=.5, application/json + * req.accepts(['html', 'json']); + * req.accepts('html', 'json'); + * req.accepts('html, json'); + * // => "json" + * + * @param {String|Array} type(s) + * @return {String|Array|Boolean} + * @public */ -app.lazyrouter = function lazyrouter() { - if (!this._router) { - this._router = new Router({ - caseSensitive: this.enabled('case sensitive routing'), - strict: this.enabled('strict routing') - }); - this._router.use(query(this.get('query parser fn'))); - this._router.use(middleware.init(this)); - } +req.accepts = function(){ + var accept = accepts(this); + return accept.types.apply(accept, arguments); }; /** - * Dispatch a req, res pair into the application. Starts pipeline processing. - * - * If no callback is provided, then default error handlers will respond - * in the event of an error bubbling through the stack. + * Check if the given `encoding`s are accepted. * - * @private + * @param {String} ...encoding + * @return {String|Array} + * @public */ -app.handle = function handle(req, res, callback) { - var router = this._router; - - // final handler - var done = callback || finalhandler(req, res, { - env: this.get('env'), - onerror: logerror.bind(this) - }); - - // no routes - if (!router) { - debug('no routes defined on app'); - done(); - return; - } - - router.handle(req, res, done); +req.acceptsEncodings = function(){ + var accept = accepts(this); + return accept.encodings.apply(accept, arguments); }; +req.acceptsEncoding = deprecate.function(req.acceptsEncodings, + 'req.acceptsEncoding: Use acceptsEncodings instead'); + /** - * Proxy `Router#use()` to add middleware to the app router. - * See Router#use() documentation for details. - * - * If the _fn_ parameter is an express app, then it will be - * mounted at the _route_ specified. + * Check if the given `charset`s are acceptable, + * otherwise you should respond with 406 "Not Acceptable". * + * @param {String} ...charset + * @return {String|Array} * @public */ -app.use = function use(fn) { - var offset = 0; - var path = '/'; - - // default path to '/' - // disambiguate app.use([fn]) - if (typeof fn !== 'function') { - var arg = fn; - - while (Array.isArray(arg) && arg.length !== 0) { - arg = arg[0]; - } - - // first arg is the path - if (typeof arg !== 'function') { - offset = 1; - path = fn; - } - } - - var fns = flatten(slice.call(arguments, offset)); - - if (fns.length === 0) { - throw new TypeError('app.use() requires a middleware function') - } - - // setup router - this.lazyrouter(); - var router = this._router; - - fns.forEach(function (fn) { - // non-express app - if (!fn || !fn.handle || !fn.set) { - return router.use(path, fn); - } - - debug('.use app under %s', path); - fn.mountpath = path; - fn.parent = this; - - // restore .app property on req and res - router.use(path, function mounted_app(req, res, next) { - var orig = req.app; - fn.handle(req, res, function (err) { - setPrototypeOf(req, orig.request) - setPrototypeOf(res, orig.response) - next(err); - }); - }); - - // mounted an app - fn.emit('mount', this); - }, this); - - return this; +req.acceptsCharsets = function(){ + var accept = accepts(this); + return accept.charsets.apply(accept, arguments); }; +req.acceptsCharset = deprecate.function(req.acceptsCharsets, + 'req.acceptsCharset: Use acceptsCharsets instead'); + /** - * Proxy to the app `Router#route()` - * Returns a new `Route` instance for the _path_. - * - * Routes are isolated middleware stacks for specific paths. - * See the Route api docs for details. + * Check if the given `lang`s are acceptable, + * otherwise you should respond with 406 "Not Acceptable". * + * @param {String} ...lang + * @return {String|Array} * @public */ -app.route = function route(path) { - this.lazyrouter(); - return this._router.route(path); +req.acceptsLanguages = function(){ + var accept = accepts(this); + return accept.languages.apply(accept, arguments); }; +req.acceptsLanguage = deprecate.function(req.acceptsLanguages, + 'req.acceptsLanguage: Use acceptsLanguages instead'); + /** - * Register the given template engine callback `fn` - * as `ext`. - * - * By default will `require()` the engine based on the - * file extension. For example if you try to render - * a "foo.ejs" file Express will invoke the following internally: - * - * app.engine('ejs', require('ejs').__express); + * Parse Range header field, capping to the given `size`. * - * For engines that do not provide `.__express` out of the box, - * or if you wish to "map" a different extension to the template engine - * you may use this method. For example mapping the EJS template engine to - * ".html" files: + * Unspecified ranges such as "0-" require knowledge of your resource length. In + * the case of a byte range this is of course the total number of bytes. If the + * Range header field is not given `undefined` is returned, `-1` when unsatisfiable, + * and `-2` when syntactically invalid. * - * app.engine('html', require('ejs').renderFile); + * When ranges are returned, the array has a "type" property which is the type of + * range that is required (most commonly, "bytes"). Each array element is an object + * with a "start" and "end" property for the portion of the range. * - * In this case EJS provides a `.renderFile()` method with - * the same signature that Express expects: `(path, options, callback)`, - * though note that it aliases this method as `ejs.__express` internally - * so if you're using ".ejs" extensions you don't need to do anything. + * The "combine" option can be set to `true` and overlapping & adjacent ranges + * will be combined into a single range. * - * Some template engines do not follow this convention, the - * [Consolidate.js](https://github.com/tj/consolidate.js) - * library was created to map all of node's popular template - * engines to follow this convention, thus allowing them to - * work seamlessly within Express. + * NOTE: remember that ranges are inclusive, so for example "Range: users=0-3" + * should respond with 4 users when available, not 3. * - * @param {String} ext - * @param {Function} fn - * @return {app} for chaining + * @param {number} size + * @param {object} [options] + * @param {boolean} [options.combine=false] + * @return {number|array} * @public */ -app.engine = function engine(ext, fn) { - if (typeof fn !== 'function') { - throw new Error('callback function required'); - } - - // get file extension - var extension = ext[0] !== '.' - ? '.' + ext - : ext; - - // store engine - this.engines[extension] = fn; - - return this; +req.range = function range(size, options) { + var range = this.get('Range'); + if (!range) return; + return parseRange(size, range, options); }; /** - * Proxy to `Router#param()` with one added api feature. The _name_ parameter - * can be an array of names. + * Return the value of param `name` when present or `defaultValue`. * - * See the Router#param() docs for more details. + * - Checks route placeholders, ex: _/user/:id_ + * - Checks body params, ex: id=12, {"id":12} + * - Checks query string params, ex: ?id=12 * - * @param {String|Array} name - * @param {Function} fn - * @return {app} for chaining + * To utilize request bodies, `req.body` + * should be an object. This can be done by using + * the `bodyParser()` middleware. + * + * @param {String} name + * @param {Mixed} [defaultValue] + * @return {String} * @public */ -app.param = function param(name, fn) { - this.lazyrouter(); - - if (Array.isArray(name)) { - for (var i = 0; i < name.length; i++) { - this.param(name[i], fn); - } +req.param = function param(name, defaultValue) { + var params = this.params || {}; + var body = this.body || {}; + var query = this.query || {}; - return this; - } + var args = arguments.length === 1 + ? 'name' + : 'name, default'; + deprecate('req.param(' + args + '): Use req.params, req.body, or req.query instead'); - this._router.param(name, fn); + if (null != params[name] && params.hasOwnProperty(name)) return params[name]; + if (null != body[name]) return body[name]; + if (null != query[name]) return query[name]; - return this; + return defaultValue; }; /** - * Assign `setting` to `val`, or return `setting`'s value. + * Check if the incoming request contains the "Content-Type" + * header field, and it contains the given mime `type`. * - * app.set('foo', 'bar'); - * app.set('foo'); - * // => "bar" + * Examples: * - * Mounted servers inherit their parent server's settings. + * // With Content-Type: text/html; charset=utf-8 + * req.is('html'); + * req.is('text/html'); + * req.is('text/*'); + * // => true * - * @param {String} setting - * @param {*} [val] - * @return {Server} for chaining + * // When Content-Type is application/json + * req.is('json'); + * req.is('application/json'); + * req.is('application/*'); + * // => true + * + * req.is('html'); + * // => false + * + * @param {String|Array} types... + * @return {String|false|null} * @public */ -app.set = function set(setting, val) { - if (arguments.length === 1) { - // app.get(setting) - return this.settings[setting]; - } - - debug('set "%s" to %o', setting, val); - - // set value - this.settings[setting] = val; - - // trigger matched settings - switch (setting) { - case 'etag': - this.set('etag fn', compileETag(val)); - break; - case 'query parser': - this.set('query parser fn', compileQueryParser(val)); - break; - case 'trust proxy': - this.set('trust proxy fn', compileTrust(val)); - - // trust proxy inherit back-compat - Object.defineProperty(this.settings, trustProxyDefaultSymbol, { - configurable: true, - value: false - }); +req.is = function is(types) { + var arr = types; - break; + // support flattened arguments + if (!Array.isArray(types)) { + arr = new Array(arguments.length); + for (var i = 0; i < arr.length; i++) { + arr[i] = arguments[i]; + } } - return this; + return typeis(this, arr); }; /** - * Return the app's absolute pathname - * based on the parent(s) that have - * mounted it. + * Return the protocol string "http" or "https" + * when requested with TLS. When the "trust proxy" + * setting trusts the socket address, the + * "X-Forwarded-Proto" header field will be trusted + * and used if present. * - * For example if the application was - * mounted as "/admin", which itself - * was mounted as "/blog" then the - * return value would be "/blog/admin". + * If you're running behind a reverse proxy that + * supplies https for you this may be enabled. * * @return {String} - * @private + * @public */ -app.path = function path() { - return this.parent - ? this.parent.path() + this.mountpath - : ''; -}; +defineGetter(req, 'protocol', function protocol(){ + var proto = this.connection.encrypted + ? 'https' + : 'http'; + var trust = this.app.get('trust proxy fn'); + + if (!trust(this.connection.remoteAddress, 0)) { + return proto; + } + + // Note: X-Forwarded-Proto is normally only ever a + // single value, but this is to be safe. + var header = this.get('X-Forwarded-Proto') || proto + var index = header.indexOf(',') + + return index !== -1 + ? header.substring(0, index).trim() + : header.trim() +}); /** - * Check if `setting` is enabled (truthy). - * - * app.enabled('foo') - * // => false + * Short-hand for: * - * app.enable('foo') - * app.enabled('foo') - * // => true + * req.protocol === 'https' * - * @param {String} setting * @return {Boolean} * @public */ -app.enabled = function enabled(setting) { - return Boolean(this.set(setting)); -}; +defineGetter(req, 'secure', function secure(){ + return this.protocol === 'https'; +}); /** - * Check if `setting` is disabled. - * - * app.disabled('foo') - * // => true + * Return the remote address from the trusted proxy. * - * app.enable('foo') - * app.disabled('foo') - * // => false + * The is the remote address on the socket unless + * "trust proxy" is set. * - * @param {String} setting - * @return {Boolean} + * @return {String} * @public */ -app.disabled = function disabled(setting) { - return !this.set(setting); -}; +defineGetter(req, 'ip', function ip(){ + var trust = this.app.get('trust proxy fn'); + return proxyaddr(this, trust); +}); /** - * Enable `setting`. + * When "trust proxy" is set, trusted proxy addresses + client. * - * @param {String} setting - * @return {app} for chaining + * For example if the value were "client, proxy1, proxy2" + * you would receive the array `["client", "proxy1", "proxy2"]` + * where "proxy2" is the furthest down-stream and "proxy1" and + * "proxy2" were trusted. + * + * @return {Array} * @public */ -app.enable = function enable(setting) { - return this.set(setting, true); -}; +defineGetter(req, 'ips', function ips() { + var trust = this.app.get('trust proxy fn'); + var addrs = proxyaddr.all(this, trust); + + // reverse the order (to farthest -> closest) + // and remove socket address + addrs.reverse().pop() + + return addrs +}); /** - * Disable `setting`. + * Return subdomains as an array. * - * @param {String} setting - * @return {app} for chaining + * Subdomains are the dot-separated parts of the host before the main domain of + * the app. By default, the domain of the app is assumed to be the last two + * parts of the host. This can be changed by setting "subdomain offset". + * + * For example, if the domain is "tobi.ferrets.example.com": + * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`. + * If "subdomain offset" is 3, req.subdomains is `["tobi"]`. + * + * @return {Array} * @public */ -app.disable = function disable(setting) { - return this.set(setting, false); -}; - -/** - * Delegate `.VERB(...)` calls to `router.VERB(...)`. - */ +defineGetter(req, 'subdomains', function subdomains() { + var hostname = this.hostname; -methods.forEach(function(method){ - app[method] = function(path){ - if (method === 'get' && arguments.length === 1) { - // app.get(setting) - return this.set(path); - } + if (!hostname) return []; - this.lazyrouter(); + var offset = this.app.get('subdomain offset'); + var subdomains = !isIP(hostname) + ? hostname.split('.').reverse() + : [hostname]; - var route = this._router.route(path); - route[method].apply(route, slice.call(arguments, 1)); - return this; - }; + return subdomains.slice(offset); }); /** - * Special-cased "all" method, applying the given route `path`, - * middleware, and callback to _every_ HTTP method. + * Short-hand for `url.parse(req.url).pathname`. * - * @param {String} path - * @param {Function} ... - * @return {app} for chaining + * @return {String} * @public */ -app.all = function all(path) { - this.lazyrouter(); - - var route = this._router.route(path); - var args = slice.call(arguments, 1); - - for (var i = 0; i < methods.length; i++) { - route[methods[i]].apply(route, args); - } - - return this; -}; - -// del -> delete alias - -app.del = deprecate.function(app.delete, 'app.del: Use app.delete instead'); +defineGetter(req, 'path', function path() { + return parse(this).pathname; +}); /** - * Render the given view `name` name with `options` - * and a callback accepting an error and the - * rendered template string. - * - * Example: + * Parse the "Host" header field to a hostname. * - * app.render('email', { name: 'Tobi' }, function(err, html){ - * // ... - * }) + * When the "trust proxy" setting trusts the socket + * address, the "X-Forwarded-Host" header field will + * be trusted. * - * @param {String} name - * @param {Object|Function} options or fn - * @param {Function} callback + * @return {String} * @public */ -app.render = function render(name, options, callback) { - var cache = this.cache; - var done = callback; - var engines = this.engines; - var opts = options; - var renderOptions = {}; - var view; +defineGetter(req, 'hostname', function hostname(){ + var trust = this.app.get('trust proxy fn'); + var host = this.get('X-Forwarded-Host'); - // support callback function as second arg - if (typeof options === 'function') { - done = options; - opts = {}; + if (!host || !trust(this.connection.remoteAddress, 0)) { + host = this.get('Host'); + } else if (host.indexOf(',') !== -1) { + // Note: X-Forwarded-Host is normally only ever a + // single value, but this is to be safe. + host = host.substring(0, host.indexOf(',')).trimRight() } - // merge app.locals - merge(renderOptions, this.locals); + if (!host) return; - // merge options._locals - if (opts._locals) { - merge(renderOptions, opts._locals); - } + // IPv6 literal support + var offset = host[0] === '[' + ? host.indexOf(']') + 1 + : 0; + var index = host.indexOf(':', offset); - // merge options - merge(renderOptions, opts); + return index !== -1 + ? host.substring(0, index) + : host; +}); - // set .cache unless explicitly provided - if (renderOptions.cache == null) { - renderOptions.cache = this.enabled('view cache'); - } +// TODO: change req.host to return host in next major - // primed cache - if (renderOptions.cache) { - view = cache[name]; - } +defineGetter(req, 'host', deprecate.function(function host(){ + return this.hostname; +}, 'req.host: Use req.hostname instead')); - // view - if (!view) { - var View = this.get('view'); +/** + * Check if the request is fresh, aka + * Last-Modified and/or the ETag + * still match. + * + * @return {Boolean} + * @public + */ - view = new View(name, { - defaultEngine: this.get('view engine'), - root: this.get('views'), - engines: engines - }); +defineGetter(req, 'fresh', function(){ + var method = this.method; + var res = this.res + var status = res.statusCode - if (!view.path) { - var dirs = Array.isArray(view.root) && view.root.length > 1 - ? 'directories "' + view.root.slice(0, -1).join('", "') + '" or "' + view.root[view.root.length - 1] + '"' - : 'directory "' + view.root + '"' - var err = new Error('Failed to lookup view "' + name + '" in views ' + dirs); - err.view = view; - return done(err); - } + // GET or HEAD for weak freshness validation only + if ('GET' !== method && 'HEAD' !== method) return false; - // prime the cache - if (renderOptions.cache) { - cache[name] = view; - } + // 2xx or 304 as per rfc2616 14.26 + if ((status >= 200 && status < 300) || 304 === status) { + return fresh(this.headers, { + 'etag': res.get('ETag'), + 'last-modified': res.get('Last-Modified') + }) } - // render - tryRender(view, renderOptions, done); -}; + return false; +}); /** - * Listen for connections. - * - * A node `http.Server` is returned, with this - * application (which is a `Function`) as its - * callback. If you wish to create both an HTTP - * and HTTPS server you may do so with the "http" - * and "https" modules as shown here: - * - * var http = require('http') - * , https = require('https') - * , express = require('express') - * , app = express(); - * - * http.createServer(app).listen(80); - * https.createServer({ ... }, app).listen(443); + * Check if the request is stale, aka + * "Last-Modified" and / or the "ETag" for the + * resource has changed. * - * @return {http.Server} + * @return {Boolean} * @public */ -app.listen = function listen() { - var server = http.createServer(this); - return server.listen.apply(server, arguments); -}; +defineGetter(req, 'stale', function stale(){ + return !this.fresh; +}); /** - * Log error using console.error. + * Check if the request was an _XMLHttpRequest_. * - * @param {Error} err - * @private + * @return {Boolean} + * @public */ -function logerror(err) { - /* istanbul ignore next */ - if (this.get('env') !== 'test') console.error(err.stack || err.toString()); -} +defineGetter(req, 'xhr', function xhr(){ + var val = this.get('X-Requested-With') || ''; + return val.toLowerCase() === 'xmlhttprequest'; +}); /** - * Try rendering a view. + * Helper function for creating a getter on an object. + * + * @param {Object} obj + * @param {String} name + * @param {Function} getter * @private */ - -function tryRender(view, options, callback) { - try { - view.render(options, callback); - } catch (err) { - callback(err); - } +function defineGetter(obj, name, getter) { + Object.defineProperty(obj, name, { + configurable: true, + enumerable: true, + get: getter + }); } /***/ }), -/***/ 22587: -/***/ ((module, exports, __nccwpck_require__) => { +/***/ 64934: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /*! * express * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2013 Roman Shtylman * Copyright(c) 2014-2015 Douglas Christopher Wilson * MIT Licensed */ @@ -38806,1909 +37752,1823 @@ function tryRender(view, options, callback) { /** * Module dependencies. + * @private */ -var bodyParser = __nccwpck_require__(97076) -var EventEmitter = (__nccwpck_require__(82361).EventEmitter); -var mixin = __nccwpck_require__(11149); -var proto = __nccwpck_require__(313); -var Route = __nccwpck_require__(23699); -var Router = __nccwpck_require__(24963); -var req = __nccwpck_require__(71260); -var res = __nccwpck_require__(64934); +var Buffer = (__nccwpck_require__(41894).Buffer) +var contentDisposition = __nccwpck_require__(53921); +var deprecate = __nccwpck_require__(18883)('express'); +var encodeUrl = __nccwpck_require__(16592); +var escapeHtml = __nccwpck_require__(94070); +var http = __nccwpck_require__(13685); +var isAbsolute = (__nccwpck_require__(53561).isAbsolute); +var onFinished = __nccwpck_require__(24694); +var path = __nccwpck_require__(71017); +var statuses = __nccwpck_require__(57415) +var merge = __nccwpck_require__(44429); +var sign = (__nccwpck_require__(61579).sign); +var normalizeType = (__nccwpck_require__(53561).normalizeType); +var normalizeTypes = (__nccwpck_require__(53561).normalizeTypes); +var setCharset = (__nccwpck_require__(53561).setCharset); +var cookie = __nccwpck_require__(93658); +var send = __nccwpck_require__(95287); +var extname = path.extname; +var mime = send.mime; +var resolve = path.resolve; +var vary = __nccwpck_require__(85931); /** - * Expose `createApplication()`. + * Response prototype. + * @public */ -exports = module.exports = createApplication; +var res = Object.create(http.ServerResponse.prototype) /** - * Create an express application. - * - * @return {Function} - * @api public + * Module exports. + * @public */ -function createApplication() { - var app = function(req, res, next) { - app.handle(req, res, next); - }; - - mixin(app, EventEmitter.prototype, false); - mixin(app, proto, false); - - // expose the prototype that will get set on requests - app.request = Object.create(req, { - app: { configurable: true, enumerable: true, writable: true, value: app } - }) - - // expose the prototype that will get set on responses - app.response = Object.create(res, { - app: { configurable: true, enumerable: true, writable: true, value: app } - }) - - app.init(); - return app; -} +module.exports = res /** - * Expose the prototypes. + * Module variables. + * @private */ -exports.application = proto; -exports.request = req; -exports.response = res; +var charsetRegExp = /;\s*charset\s*=/; /** - * Expose constructors. + * Set status `code`. + * + * @param {Number} code + * @return {ServerResponse} + * @public */ -exports.Route = Route; -exports.Router = Router; +res.status = function status(code) { + this.statusCode = code; + return this; +}; /** - * Expose middleware + * Set Link header field with the given `links`. + * + * Examples: + * + * res.links({ + * next: 'http://api.example.com/users?page=2', + * last: 'http://api.example.com/users?page=5' + * }); + * + * @param {Object} links + * @return {ServerResponse} + * @public */ -exports.json = bodyParser.json -exports.query = __nccwpck_require__(79768); -exports.raw = bodyParser.raw -exports["static"] = __nccwpck_require__(13146); -exports.text = bodyParser.text -exports.urlencoded = bodyParser.urlencoded +res.links = function(links){ + var link = this.get('Link') || ''; + if (link) link += ', '; + return this.set('Link', link + Object.keys(links).map(function(rel){ + return '<' + links[rel] + '>; rel="' + rel + '"'; + }).join(', ')); +}; /** - * Replace removed middleware with an appropriate error message. + * Send a response. + * + * Examples: + * + * res.send(Buffer.from('wahoo')); + * res.send({ some: 'json' }); + * res.send('

some html

'); + * + * @param {string|number|boolean|object|Buffer} body + * @public */ -var removedMiddlewares = [ - 'bodyParser', - 'compress', - 'cookieSession', - 'session', - 'logger', - 'cookieParser', - 'favicon', - 'responseTime', - 'errorHandler', - 'timeout', - 'methodOverride', - 'vhost', - 'csrf', - 'directory', - 'limit', - 'multipart', - 'staticCache' -] +res.send = function send(body) { + var chunk = body; + var encoding; + var req = this.req; + var type; -removedMiddlewares.forEach(function (name) { - Object.defineProperty(exports, name, { - get: function () { - throw new Error('Most middleware (like ' + name + ') is no longer bundled with Express and must be installed separately. Please see https://github.com/senchalabs/connect#middleware.'); - }, - configurable: true - }); -}); + // settings + var app = this.app; + // allow status / body + if (arguments.length === 2) { + // res.send(body, status) backwards compat + if (typeof arguments[0] !== 'number' && typeof arguments[1] === 'number') { + deprecate('res.send(body, status): Use res.status(status).send(body) instead'); + this.statusCode = arguments[1]; + } else { + deprecate('res.send(status, body): Use res.status(status).send(body) instead'); + this.statusCode = arguments[0]; + chunk = arguments[1]; + } + } -/***/ }), + // disambiguate res.send(status) and res.send(status, num) + if (typeof chunk === 'number' && arguments.length === 1) { + // res.send(status) will set status message as text string + if (!this.get('Content-Type')) { + this.type('txt'); + } -/***/ 92636: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + deprecate('res.send(status): Use res.sendStatus(status) instead'); + this.statusCode = chunk; + chunk = statuses[chunk] + } -"use strict"; -/*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2013 Roman Shtylman - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ + switch (typeof chunk) { + // string defaulting to html + case 'string': + if (!this.get('Content-Type')) { + this.type('html'); + } + break; + case 'boolean': + case 'number': + case 'object': + if (chunk === null) { + chunk = ''; + } else if (Buffer.isBuffer(chunk)) { + if (!this.get('Content-Type')) { + this.type('bin'); + } + } else { + return this.json(chunk); + } + break; + } + // write strings in utf-8 + if (typeof chunk === 'string') { + encoding = 'utf8'; + type = this.get('Content-Type'); + // reflect this in content-type + if (typeof type === 'string') { + this.set('Content-Type', setCharset(type, 'utf-8')); + } + } -/** - * Module dependencies. - * @private - */ + // determine if ETag should be generated + var etagFn = app.get('etag fn') + var generateETag = !this.get('ETag') && typeof etagFn === 'function' -var setPrototypeOf = __nccwpck_require__(40414) + // populate Content-Length + var len + if (chunk !== undefined) { + if (Buffer.isBuffer(chunk)) { + // get length of Buffer + len = chunk.length + } else if (!generateETag && chunk.length < 1000) { + // just calculate length when no ETag + small chunk + len = Buffer.byteLength(chunk, encoding) + } else { + // convert chunk to Buffer and calculate + chunk = Buffer.from(chunk, encoding) + encoding = undefined; + len = chunk.length + } -/** - * Initialization middleware, exposing the - * request and response to each other, as well - * as defaulting the X-Powered-By header field. - * - * @param {Function} app - * @return {Function} - * @api private - */ + this.set('Content-Length', len); + } -exports.init = function(app){ - return function expressInit(req, res, next){ - if (app.enabled('x-powered-by')) res.setHeader('X-Powered-By', 'Express'); - req.res = res; - res.req = req; - req.next = next; + // populate ETag + var etag; + if (generateETag && len !== undefined) { + if ((etag = etagFn(chunk, encoding))) { + this.set('ETag', etag); + } + } - setPrototypeOf(req, app.request) - setPrototypeOf(res, app.response) + // freshness + if (req.fresh) this.statusCode = 304; - res.locals = res.locals || Object.create(null); + // strip irrelevant headers + if (204 === this.statusCode || 304 === this.statusCode) { + this.removeHeader('Content-Type'); + this.removeHeader('Content-Length'); + this.removeHeader('Transfer-Encoding'); + chunk = ''; + } - next(); - }; -}; + if (req.method === 'HEAD') { + // skip body for HEAD + this.end(); + } else { + // respond + this.end(chunk, encoding); + } + return this; +}; +/** + * Send JSON response. + * + * Examples: + * + * res.json(null); + * res.json({ user: 'tj' }); + * + * @param {string|number|boolean|object} obj + * @public + */ -/***/ }), +res.json = function json(obj) { + var val = obj; -/***/ 79768: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // allow status / body + if (arguments.length === 2) { + // res.json(body, status) backwards compat + if (typeof arguments[1] === 'number') { + deprecate('res.json(obj, status): Use res.status(status).json(obj) instead'); + this.statusCode = arguments[1]; + } else { + deprecate('res.json(status, obj): Use res.status(status).json(obj) instead'); + this.statusCode = arguments[0]; + val = arguments[1]; + } + } -"use strict"; -/*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2013 Roman Shtylman - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ + // settings + var app = this.app; + var escape = app.get('json escape') + var replacer = app.get('json replacer'); + var spaces = app.get('json spaces'); + var body = stringify(val, replacer, spaces, escape) + // content-type + if (!this.get('Content-Type')) { + this.set('Content-Type', 'application/json'); + } + return this.send(body); +}; /** - * Module dependencies. + * Send JSON response with JSONP callback support. + * + * Examples: + * + * res.jsonp(null); + * res.jsonp({ user: 'tj' }); + * + * @param {string|number|boolean|object} obj + * @public */ -var merge = __nccwpck_require__(44429) -var parseUrl = __nccwpck_require__(89808); -var qs = __nccwpck_require__(22760); +res.jsonp = function jsonp(obj) { + var val = obj; -/** - * @param {Object} options - * @return {Function} - * @api public - */ + // allow status / body + if (arguments.length === 2) { + // res.jsonp(body, status) backwards compat + if (typeof arguments[1] === 'number') { + deprecate('res.jsonp(obj, status): Use res.status(status).jsonp(obj) instead'); + this.statusCode = arguments[1]; + } else { + deprecate('res.jsonp(status, obj): Use res.status(status).jsonp(obj) instead'); + this.statusCode = arguments[0]; + val = arguments[1]; + } + } -module.exports = function query(options) { - var opts = merge({}, options) - var queryparse = qs.parse; + // settings + var app = this.app; + var escape = app.get('json escape') + var replacer = app.get('json replacer'); + var spaces = app.get('json spaces'); + var body = stringify(val, replacer, spaces, escape) + var callback = this.req.query[app.get('jsonp callback name')]; - if (typeof options === 'function') { - queryparse = options; - opts = undefined; + // content-type + if (!this.get('Content-Type')) { + this.set('X-Content-Type-Options', 'nosniff'); + this.set('Content-Type', 'application/json'); } - if (opts !== undefined && opts.allowPrototypes === undefined) { - // back-compat for qs module - opts.allowPrototypes = true; + // fixup callback + if (Array.isArray(callback)) { + callback = callback[0]; } - return function query(req, res, next){ - if (!req.query) { - var val = parseUrl(req).query; - req.query = queryparse(val, opts); - } - - next(); - }; -}; - - -/***/ }), - -/***/ 71260: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -/*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2013 Roman Shtylman - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ + // jsonp + if (typeof callback === 'string' && callback.length !== 0) { + this.set('X-Content-Type-Options', 'nosniff'); + this.set('Content-Type', 'text/javascript'); + // restrict callback charset + callback = callback.replace(/[^\[\]\w$.]/g, ''); + if (body === undefined) { + // empty argument + body = '' + } else if (typeof body === 'string') { + // replace chars not allowed in JavaScript that are in JSON + body = body + .replace(/\u2028/g, '\\u2028') + .replace(/\u2029/g, '\\u2029') + } -/** - * Module dependencies. - * @private - */ + // the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse" + // the typeof check is just to reduce client error noise + body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');'; + } -var accepts = __nccwpck_require__(83633); -var deprecate = __nccwpck_require__(18883)('express'); -var isIP = (__nccwpck_require__(41808).isIP); -var typeis = __nccwpck_require__(71159); -var http = __nccwpck_require__(13685); -var fresh = __nccwpck_require__(83136); -var parseRange = __nccwpck_require__(26435); -var parse = __nccwpck_require__(89808); -var proxyaddr = __nccwpck_require__(80140); + return this.send(body); +}; /** - * Request prototype. + * Send given HTTP status code. + * + * Sets the response status to `statusCode` and the body of the + * response to the standard description from node's http.STATUS_CODES + * or the statusCode number if no description. + * + * Examples: + * + * res.sendStatus(200); + * + * @param {number} statusCode * @public */ -var req = Object.create(http.IncomingMessage.prototype) +res.sendStatus = function sendStatus(statusCode) { + var body = statuses[statusCode] || String(statusCode) -/** - * Module exports. - * @public - */ + this.statusCode = statusCode; + this.type('txt'); -module.exports = req + return this.send(body); +}; /** - * Return request header. + * Transfer the file at the given `path`. * - * The `Referrer` header field is special-cased, - * both `Referrer` and `Referer` are interchangeable. + * Automatically sets the _Content-Type_ response header field. + * The callback `callback(err)` is invoked when the transfer is complete + * or when an error occurs. Be sure to check `res.headersSent` + * if you wish to attempt responding, as the header and some data + * may have already been transferred. * - * Examples: + * Options: * - * req.get('Content-Type'); - * // => "text/plain" + * - `maxAge` defaulting to 0 (can be string converted by `ms`) + * - `root` root directory for relative filenames + * - `headers` object of headers to serve with file + * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them * - * req.get('content-type'); - * // => "text/plain" + * Other options are passed along to `send`. * - * req.get('Something'); - * // => undefined + * Examples: * - * Aliased as `req.header()`. + * The following example illustrates how `res.sendFile()` may + * be used as an alternative for the `static()` middleware for + * dynamic situations. The code backing `res.sendFile()` is actually + * the same code, so HTTP cache support etc is identical. + * + * app.get('/user/:uid/photos/:file', function(req, res){ + * var uid = req.params.uid + * , file = req.params.file; + * + * req.user.mayViewFilesFrom(uid, function(yes){ + * if (yes) { + * res.sendFile('/uploads/' + uid + '/' + file); + * } else { + * res.send(403, 'Sorry! you cant see that.'); + * } + * }); + * }); * - * @param {String} name - * @return {String} * @public */ -req.get = -req.header = function header(name) { - if (!name) { - throw new TypeError('name argument is required to req.get'); +res.sendFile = function sendFile(path, options, callback) { + var done = callback; + var req = this.req; + var res = this; + var next = req.next; + var opts = options || {}; + + if (!path) { + throw new TypeError('path argument is required to res.sendFile'); } - if (typeof name !== 'string') { - throw new TypeError('name must be a string to req.get'); + if (typeof path !== 'string') { + throw new TypeError('path must be a string to res.sendFile') } - var lc = name.toLowerCase(); + // support function as second arg + if (typeof options === 'function') { + done = options; + opts = {}; + } - switch (lc) { - case 'referer': - case 'referrer': - return this.headers.referrer - || this.headers.referer; - default: - return this.headers[lc]; + if (!opts.root && !isAbsolute(path)) { + throw new TypeError('path must be absolute or specify root to res.sendFile'); } + + // create file stream + var pathname = encodeURI(path); + var file = send(req, pathname, opts); + + // transfer + sendfile(res, file, opts, function (err) { + if (done) return done(err); + if (err && err.code === 'EISDIR') return next(); + + // next() all but write errors + if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') { + next(err); + } + }); }; /** - * To do: update docs. + * Transfer the file at the given `path`. * - * Check if the given `type(s)` is acceptable, returning - * the best match when true, otherwise `undefined`, in which - * case you should respond with 406 "Not Acceptable". + * Automatically sets the _Content-Type_ response header field. + * The callback `callback(err)` is invoked when the transfer is complete + * or when an error occurs. Be sure to check `res.headersSent` + * if you wish to attempt responding, as the header and some data + * may have already been transferred. * - * The `type` value may be a single MIME type string - * such as "application/json", an extension name - * such as "json", a comma-delimited list such as "json, html, text/plain", - * an argument list such as `"json", "html", "text/plain"`, - * or an array `["json", "html", "text/plain"]`. When a list - * or array is given, the _best_ match, if any is returned. + * Options: * - * Examples: + * - `maxAge` defaulting to 0 (can be string converted by `ms`) + * - `root` root directory for relative filenames + * - `headers` object of headers to serve with file + * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them * - * // Accept: text/html - * req.accepts('html'); - * // => "html" + * Other options are passed along to `send`. * - * // Accept: text/*, application/json - * req.accepts('html'); - * // => "html" - * req.accepts('text/html'); - * // => "text/html" - * req.accepts('json, text'); - * // => "json" - * req.accepts('application/json'); - * // => "application/json" + * Examples: * - * // Accept: text/*, application/json - * req.accepts('image/png'); - * req.accepts('png'); - * // => undefined + * The following example illustrates how `res.sendfile()` may + * be used as an alternative for the `static()` middleware for + * dynamic situations. The code backing `res.sendfile()` is actually + * the same code, so HTTP cache support etc is identical. * - * // Accept: text/*;q=.5, application/json - * req.accepts(['html', 'json']); - * req.accepts('html', 'json'); - * req.accepts('html, json'); - * // => "json" + * app.get('/user/:uid/photos/:file', function(req, res){ + * var uid = req.params.uid + * , file = req.params.file; * - * @param {String|Array} type(s) - * @return {String|Array|Boolean} - * @public - */ - -req.accepts = function(){ - var accept = accepts(this); - return accept.types.apply(accept, arguments); -}; - -/** - * Check if the given `encoding`s are accepted. + * req.user.mayViewFilesFrom(uid, function(yes){ + * if (yes) { + * res.sendfile('/uploads/' + uid + '/' + file); + * } else { + * res.send(403, 'Sorry! you cant see that.'); + * } + * }); + * }); * - * @param {String} ...encoding - * @return {String|Array} * @public */ -req.acceptsEncodings = function(){ - var accept = accepts(this); - return accept.encodings.apply(accept, arguments); -}; - -req.acceptsEncoding = deprecate.function(req.acceptsEncodings, - 'req.acceptsEncoding: Use acceptsEncodings instead'); - -/** - * Check if the given `charset`s are acceptable, - * otherwise you should respond with 406 "Not Acceptable". - * - * @param {String} ...charset - * @return {String|Array} - * @public - */ +res.sendfile = function (path, options, callback) { + var done = callback; + var req = this.req; + var res = this; + var next = req.next; + var opts = options || {}; -req.acceptsCharsets = function(){ - var accept = accepts(this); - return accept.charsets.apply(accept, arguments); -}; + // support function as second arg + if (typeof options === 'function') { + done = options; + opts = {}; + } -req.acceptsCharset = deprecate.function(req.acceptsCharsets, - 'req.acceptsCharset: Use acceptsCharsets instead'); + // create file stream + var file = send(req, path, opts); -/** - * Check if the given `lang`s are acceptable, - * otherwise you should respond with 406 "Not Acceptable". - * - * @param {String} ...lang - * @return {String|Array} - * @public - */ + // transfer + sendfile(res, file, opts, function (err) { + if (done) return done(err); + if (err && err.code === 'EISDIR') return next(); -req.acceptsLanguages = function(){ - var accept = accepts(this); - return accept.languages.apply(accept, arguments); + // next() all but write errors + if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') { + next(err); + } + }); }; -req.acceptsLanguage = deprecate.function(req.acceptsLanguages, - 'req.acceptsLanguage: Use acceptsLanguages instead'); +res.sendfile = deprecate.function(res.sendfile, + 'res.sendfile: Use res.sendFile instead'); /** - * Parse Range header field, capping to the given `size`. - * - * Unspecified ranges such as "0-" require knowledge of your resource length. In - * the case of a byte range this is of course the total number of bytes. If the - * Range header field is not given `undefined` is returned, `-1` when unsatisfiable, - * and `-2` when syntactically invalid. + * Transfer the file at the given `path` as an attachment. * - * When ranges are returned, the array has a "type" property which is the type of - * range that is required (most commonly, "bytes"). Each array element is an object - * with a "start" and "end" property for the portion of the range. + * Optionally providing an alternate attachment `filename`, + * and optional callback `callback(err)`. The callback is invoked + * when the data transfer is complete, or when an error has + * ocurred. Be sure to check `res.headersSent` if you plan to respond. * - * The "combine" option can be set to `true` and overlapping & adjacent ranges - * will be combined into a single range. + * Optionally providing an `options` object to use with `res.sendFile()`. + * This function will set the `Content-Disposition` header, overriding + * any `Content-Disposition` header passed as header options in order + * to set the attachment and filename. * - * NOTE: remember that ranges are inclusive, so for example "Range: users=0-3" - * should respond with 4 users when available, not 3. + * This method uses `res.sendFile()`. * - * @param {number} size - * @param {object} [options] - * @param {boolean} [options.combine=false] - * @return {number|array} * @public */ -req.range = function range(size, options) { - var range = this.get('Range'); - if (!range) return; - return parseRange(size, range, options); -}; +res.download = function download (path, filename, options, callback) { + var done = callback; + var name = filename; + var opts = options || null -/** - * Return the value of param `name` when present or `defaultValue`. - * - * - Checks route placeholders, ex: _/user/:id_ - * - Checks body params, ex: id=12, {"id":12} - * - Checks query string params, ex: ?id=12 - * - * To utilize request bodies, `req.body` - * should be an object. This can be done by using - * the `bodyParser()` middleware. - * - * @param {String} name - * @param {Mixed} [defaultValue] - * @return {String} - * @public - */ + // support function as second or third arg + if (typeof filename === 'function') { + done = filename; + name = null; + opts = null + } else if (typeof options === 'function') { + done = options + opts = null + } -req.param = function param(name, defaultValue) { - var params = this.params || {}; - var body = this.body || {}; - var query = this.query || {}; + // set Content-Disposition when file is sent + var headers = { + 'Content-Disposition': contentDisposition(name || path) + }; - var args = arguments.length === 1 - ? 'name' - : 'name, default'; - deprecate('req.param(' + args + '): Use req.params, req.body, or req.query instead'); + // merge user-provided headers + if (opts && opts.headers) { + var keys = Object.keys(opts.headers) + for (var i = 0; i < keys.length; i++) { + var key = keys[i] + if (key.toLowerCase() !== 'content-disposition') { + headers[key] = opts.headers[key] + } + } + } - if (null != params[name] && params.hasOwnProperty(name)) return params[name]; - if (null != body[name]) return body[name]; - if (null != query[name]) return query[name]; + // merge user-provided options + opts = Object.create(opts) + opts.headers = headers - return defaultValue; + // Resolve the full path for sendFile + var fullPath = resolve(path); + + // send file + return this.sendFile(fullPath, opts, done) }; /** - * Check if the incoming request contains the "Content-Type" - * header field, and it contains the given mime `type`. + * Set _Content-Type_ response header with `type` through `mime.lookup()` + * when it does not contain "/", or set the Content-Type to `type` otherwise. * * Examples: * - * // With Content-Type: text/html; charset=utf-8 - * req.is('html'); - * req.is('text/html'); - * req.is('text/*'); - * // => true - * - * // When Content-Type is application/json - * req.is('json'); - * req.is('application/json'); - * req.is('application/*'); - * // => true - * - * req.is('html'); - * // => false + * res.type('.html'); + * res.type('html'); + * res.type('json'); + * res.type('application/json'); + * res.type('png'); * - * @param {String|Array} types... - * @return {String|false|null} + * @param {String} type + * @return {ServerResponse} for chaining * @public */ -req.is = function is(types) { - var arr = types; - - // support flattened arguments - if (!Array.isArray(types)) { - arr = new Array(arguments.length); - for (var i = 0; i < arr.length; i++) { - arr[i] = arguments[i]; - } - } +res.contentType = +res.type = function contentType(type) { + var ct = type.indexOf('/') === -1 + ? mime.lookup(type) + : type; - return typeis(this, arr); + return this.set('Content-Type', ct); }; /** - * Return the protocol string "http" or "https" - * when requested with TLS. When the "trust proxy" - * setting trusts the socket address, the - * "X-Forwarded-Proto" header field will be trusted - * and used if present. + * Respond to the Acceptable formats using an `obj` + * of mime-type callbacks. * - * If you're running behind a reverse proxy that - * supplies https for you this may be enabled. + * This method uses `req.accepted`, an array of + * acceptable types ordered by their quality values. + * When "Accept" is not present the _first_ callback + * is invoked, otherwise the first match is used. When + * no match is performed the server responds with + * 406 "Not Acceptable". * - * @return {String} - * @public - */ - -defineGetter(req, 'protocol', function protocol(){ - var proto = this.connection.encrypted - ? 'https' - : 'http'; - var trust = this.app.get('trust proxy fn'); - - if (!trust(this.connection.remoteAddress, 0)) { - return proto; - } - - // Note: X-Forwarded-Proto is normally only ever a - // single value, but this is to be safe. - var header = this.get('X-Forwarded-Proto') || proto - var index = header.indexOf(',') - - return index !== -1 - ? header.substring(0, index).trim() - : header.trim() -}); - -/** - * Short-hand for: + * Content-Type is set for you, however if you choose + * you may alter this within the callback using `res.type()` + * or `res.set('Content-Type', ...)`. * - * req.protocol === 'https' + * res.format({ + * 'text/plain': function(){ + * res.send('hey'); + * }, * - * @return {Boolean} - * @public - */ - -defineGetter(req, 'secure', function secure(){ - return this.protocol === 'https'; -}); - -/** - * Return the remote address from the trusted proxy. + * 'text/html': function(){ + * res.send('

hey

'); + * }, * - * The is the remote address on the socket unless - * "trust proxy" is set. + * 'application/json': function () { + * res.send({ message: 'hey' }); + * } + * }); * - * @return {String} - * @public - */ - -defineGetter(req, 'ip', function ip(){ - var trust = this.app.get('trust proxy fn'); - return proxyaddr(this, trust); -}); - -/** - * When "trust proxy" is set, trusted proxy addresses + client. + * In addition to canonicalized MIME types you may + * also use extnames mapped to these types: * - * For example if the value were "client, proxy1, proxy2" - * you would receive the array `["client", "proxy1", "proxy2"]` - * where "proxy2" is the furthest down-stream and "proxy1" and - * "proxy2" were trusted. + * res.format({ + * text: function(){ + * res.send('hey'); + * }, * - * @return {Array} - * @public - */ - -defineGetter(req, 'ips', function ips() { - var trust = this.app.get('trust proxy fn'); - var addrs = proxyaddr.all(this, trust); - - // reverse the order (to farthest -> closest) - // and remove socket address - addrs.reverse().pop() - - return addrs -}); - -/** - * Return subdomains as an array. + * html: function(){ + * res.send('

hey

'); + * }, * - * Subdomains are the dot-separated parts of the host before the main domain of - * the app. By default, the domain of the app is assumed to be the last two - * parts of the host. This can be changed by setting "subdomain offset". + * json: function(){ + * res.send({ message: 'hey' }); + * } + * }); * - * For example, if the domain is "tobi.ferrets.example.com": - * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`. - * If "subdomain offset" is 3, req.subdomains is `["tobi"]`. + * By default Express passes an `Error` + * with a `.status` of 406 to `next(err)` + * if a match is not made. If you provide + * a `.default` callback it will be invoked + * instead. * - * @return {Array} + * @param {Object} obj + * @return {ServerResponse} for chaining * @public */ -defineGetter(req, 'subdomains', function subdomains() { - var hostname = this.hostname; +res.format = function(obj){ + var req = this.req; + var next = req.next; - if (!hostname) return []; + var fn = obj.default; + if (fn) delete obj.default; + var keys = Object.keys(obj); - var offset = this.app.get('subdomain offset'); - var subdomains = !isIP(hostname) - ? hostname.split('.').reverse() - : [hostname]; + var key = keys.length > 0 + ? req.accepts(keys) + : false; - return subdomains.slice(offset); -}); + this.vary("Accept"); -/** - * Short-hand for `url.parse(req.url).pathname`. - * - * @return {String} - * @public - */ + if (key) { + this.set('Content-Type', normalizeType(key).value); + obj[key](req, this, next); + } else if (fn) { + fn(); + } else { + var err = new Error('Not Acceptable'); + err.status = err.statusCode = 406; + err.types = normalizeTypes(keys).map(function(o){ return o.value }); + next(err); + } -defineGetter(req, 'path', function path() { - return parse(this).pathname; -}); + return this; +}; /** - * Parse the "Host" header field to a hostname. - * - * When the "trust proxy" setting trusts the socket - * address, the "X-Forwarded-Host" header field will - * be trusted. + * Set _Content-Disposition_ header to _attachment_ with optional `filename`. * - * @return {String} + * @param {String} filename + * @return {ServerResponse} * @public */ -defineGetter(req, 'hostname', function hostname(){ - var trust = this.app.get('trust proxy fn'); - var host = this.get('X-Forwarded-Host'); - - if (!host || !trust(this.connection.remoteAddress, 0)) { - host = this.get('Host'); - } else if (host.indexOf(',') !== -1) { - // Note: X-Forwarded-Host is normally only ever a - // single value, but this is to be safe. - host = host.substring(0, host.indexOf(',')).trimRight() +res.attachment = function attachment(filename) { + if (filename) { + this.type(extname(filename)); } - if (!host) return; - - // IPv6 literal support - var offset = host[0] === '[' - ? host.indexOf(']') + 1 - : 0; - var index = host.indexOf(':', offset); - - return index !== -1 - ? host.substring(0, index) - : host; -}); - -// TODO: change req.host to return host in next major + this.set('Content-Disposition', contentDisposition(filename)); -defineGetter(req, 'host', deprecate.function(function host(){ - return this.hostname; -}, 'req.host: Use req.hostname instead')); + return this; +}; /** - * Check if the request is fresh, aka - * Last-Modified and/or the ETag - * still match. + * Append additional header `field` with value `val`. * - * @return {Boolean} + * Example: + * + * res.append('Link', ['', '']); + * res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly'); + * res.append('Warning', '199 Miscellaneous warning'); + * + * @param {String} field + * @param {String|Array} val + * @return {ServerResponse} for chaining * @public */ -defineGetter(req, 'fresh', function(){ - var method = this.method; - var res = this.res - var status = res.statusCode - - // GET or HEAD for weak freshness validation only - if ('GET' !== method && 'HEAD' !== method) return false; +res.append = function append(field, val) { + var prev = this.get(field); + var value = val; - // 2xx or 304 as per rfc2616 14.26 - if ((status >= 200 && status < 300) || 304 === status) { - return fresh(this.headers, { - 'etag': res.get('ETag'), - 'last-modified': res.get('Last-Modified') - }) + if (prev) { + // concat the new and prev vals + value = Array.isArray(prev) ? prev.concat(val) + : Array.isArray(val) ? [prev].concat(val) + : [prev, val] } - return false; -}); + return this.set(field, value); +}; /** - * Check if the request is stale, aka - * "Last-Modified" and / or the "ETag" for the - * resource has changed. + * Set header `field` to `val`, or pass + * an object of header fields. * - * @return {Boolean} + * Examples: + * + * res.set('Foo', ['bar', 'baz']); + * res.set('Accept', 'application/json'); + * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' }); + * + * Aliased as `res.header()`. + * + * @param {String|Object} field + * @param {String|Array} val + * @return {ServerResponse} for chaining * @public */ -defineGetter(req, 'stale', function stale(){ - return !this.fresh; -}); +res.set = +res.header = function header(field, val) { + if (arguments.length === 2) { + var value = Array.isArray(val) + ? val.map(String) + : String(val); + + // add charset to content-type + if (field.toLowerCase() === 'content-type') { + if (Array.isArray(value)) { + throw new TypeError('Content-Type cannot be set to an Array'); + } + if (!charsetRegExp.test(value)) { + var charset = mime.charsets.lookup(value.split(';')[0]); + if (charset) value += '; charset=' + charset.toLowerCase(); + } + } + + this.setHeader(field, value); + } else { + for (var key in field) { + this.set(key, field[key]); + } + } + return this; +}; /** - * Check if the request was an _XMLHttpRequest_. + * Get value for header `field`. * - * @return {Boolean} + * @param {String} field + * @return {String} * @public */ -defineGetter(req, 'xhr', function xhr(){ - var val = this.get('X-Requested-With') || ''; - return val.toLowerCase() === 'xmlhttprequest'; -}); +res.get = function(field){ + return this.getHeader(field); +}; /** - * Helper function for creating a getter on an object. + * Clear cookie `name`. * - * @param {Object} obj * @param {String} name - * @param {Function} getter - * @private - */ -function defineGetter(obj, name, getter) { - Object.defineProperty(obj, name, { - configurable: true, - enumerable: true, - get: getter - }); -} - - -/***/ }), - -/***/ 64934: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -/*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed + * @param {Object} [options] + * @return {ServerResponse} for chaining + * @public */ +res.clearCookie = function clearCookie(name, options) { + var opts = merge({ expires: new Date(1), path: '/' }, options); + return this.cookie(name, '', opts); +}; /** - * Module dependencies. - * @private - */ - -var Buffer = (__nccwpck_require__(21867).Buffer) -var contentDisposition = __nccwpck_require__(53921); -var deprecate = __nccwpck_require__(18883)('express'); -var encodeUrl = __nccwpck_require__(16592); -var escapeHtml = __nccwpck_require__(94070); -var http = __nccwpck_require__(13685); -var isAbsolute = (__nccwpck_require__(53561).isAbsolute); -var onFinished = __nccwpck_require__(24694); -var path = __nccwpck_require__(71017); -var statuses = __nccwpck_require__(57415) -var merge = __nccwpck_require__(44429); -var sign = (__nccwpck_require__(61579).sign); -var normalizeType = (__nccwpck_require__(53561).normalizeType); -var normalizeTypes = (__nccwpck_require__(53561).normalizeTypes); -var setCharset = (__nccwpck_require__(53561).setCharset); -var cookie = __nccwpck_require__(93658); -var send = __nccwpck_require__(95287); -var extname = path.extname; -var mime = send.mime; -var resolve = path.resolve; -var vary = __nccwpck_require__(85931); - -/** - * Response prototype. + * Set cookie `name` to `value`, with the given `options`. + * + * Options: + * + * - `maxAge` max-age in milliseconds, converted to `expires` + * - `signed` sign the cookie + * - `path` defaults to "/" + * + * Examples: + * + * // "Remember Me" for 15 minutes + * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true }); + * + * // same as above + * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true }) + * + * @param {String} name + * @param {String|Object} value + * @param {Object} [options] + * @return {ServerResponse} for chaining * @public */ -var res = Object.create(http.ServerResponse.prototype) +res.cookie = function (name, value, options) { + var opts = merge({}, options); + var secret = this.req.secret; + var signed = opts.signed; -/** - * Module exports. - * @public - */ + if (signed && !secret) { + throw new Error('cookieParser("secret") required for signed cookies'); + } -module.exports = res + var val = typeof value === 'object' + ? 'j:' + JSON.stringify(value) + : String(value); -/** - * Module variables. - * @private - */ + if (signed) { + val = 's:' + sign(val, secret); + } -var charsetRegExp = /;\s*charset\s*=/; + if ('maxAge' in opts) { + opts.expires = new Date(Date.now() + opts.maxAge); + opts.maxAge /= 1000; + } -/** - * Set status `code`. - * - * @param {Number} code - * @return {ServerResponse} - * @public - */ + if (opts.path == null) { + opts.path = '/'; + } + + this.append('Set-Cookie', cookie.serialize(name, String(val), opts)); -res.status = function status(code) { - this.statusCode = code; return this; }; /** - * Set Link header field with the given `links`. + * Set the location header to `url`. + * + * The given `url` can also be "back", which redirects + * to the _Referrer_ or _Referer_ headers or "/". * * Examples: * - * res.links({ - * next: 'http://api.example.com/users?page=2', - * last: 'http://api.example.com/users?page=5' - * }); + * res.location('/foo/bar').; + * res.location('http://example.com'); + * res.location('../login'); * - * @param {Object} links - * @return {ServerResponse} + * @param {String} url + * @return {ServerResponse} for chaining * @public */ -res.links = function(links){ - var link = this.get('Link') || ''; - if (link) link += ', '; - return this.set('Link', link + Object.keys(links).map(function(rel){ - return '<' + links[rel] + '>; rel="' + rel + '"'; - }).join(', ')); +res.location = function location(url) { + var loc = url; + + // "back" is an alias for the referrer + if (url === 'back') { + loc = this.req.get('Referrer') || '/'; + } + + // set location + return this.set('Location', encodeUrl(loc)); }; /** - * Send a response. + * Redirect to the given `url` with optional response `status` + * defaulting to 302. + * + * The resulting `url` is determined by `res.location()`, so + * it will play nicely with mounted apps, relative paths, + * `"back"` etc. * * Examples: * - * res.send(Buffer.from('wahoo')); - * res.send({ some: 'json' }); - * res.send('

some html

'); + * res.redirect('/foo/bar'); + * res.redirect('http://example.com'); + * res.redirect(301, 'http://example.com'); + * res.redirect('../login'); // /blog/post/1 -> /blog/login * - * @param {string|number|boolean|object|Buffer} body * @public */ -res.send = function send(body) { - var chunk = body; - var encoding; - var req = this.req; - var type; - - // settings - var app = this.app; +res.redirect = function redirect(url) { + var address = url; + var body; + var status = 302; - // allow status / body + // allow status / url if (arguments.length === 2) { - // res.send(body, status) backwards compat - if (typeof arguments[0] !== 'number' && typeof arguments[1] === 'number') { - deprecate('res.send(body, status): Use res.status(status).send(body) instead'); - this.statusCode = arguments[1]; + if (typeof arguments[0] === 'number') { + status = arguments[0]; + address = arguments[1]; } else { - deprecate('res.send(status, body): Use res.status(status).send(body) instead'); - this.statusCode = arguments[0]; - chunk = arguments[1]; - } - } - - // disambiguate res.send(status) and res.send(status, num) - if (typeof chunk === 'number' && arguments.length === 1) { - // res.send(status) will set status message as text string - if (!this.get('Content-Type')) { - this.type('txt'); + deprecate('res.redirect(url, status): Use res.redirect(status, url) instead'); + status = arguments[1]; } - - deprecate('res.send(status): Use res.sendStatus(status) instead'); - this.statusCode = chunk; - chunk = statuses[chunk] - } - - switch (typeof chunk) { - // string defaulting to html - case 'string': - if (!this.get('Content-Type')) { - this.type('html'); - } - break; - case 'boolean': - case 'number': - case 'object': - if (chunk === null) { - chunk = ''; - } else if (Buffer.isBuffer(chunk)) { - if (!this.get('Content-Type')) { - this.type('bin'); - } - } else { - return this.json(chunk); - } - break; } - // write strings in utf-8 - if (typeof chunk === 'string') { - encoding = 'utf8'; - type = this.get('Content-Type'); + // Set location header + address = this.location(address).get('Location'); - // reflect this in content-type - if (typeof type === 'string') { - this.set('Content-Type', setCharset(type, 'utf-8')); - } - } + // Support text/{plain,html} by default + this.format({ + text: function(){ + body = statuses[status] + '. Redirecting to ' + address + }, - // determine if ETag should be generated - var etagFn = app.get('etag fn') - var generateETag = !this.get('ETag') && typeof etagFn === 'function' + html: function(){ + var u = escapeHtml(address); + body = '

' + statuses[status] + '. Redirecting to ' + u + '

' + }, - // populate Content-Length - var len - if (chunk !== undefined) { - if (Buffer.isBuffer(chunk)) { - // get length of Buffer - len = chunk.length - } else if (!generateETag && chunk.length < 1000) { - // just calculate length when no ETag + small chunk - len = Buffer.byteLength(chunk, encoding) - } else { - // convert chunk to Buffer and calculate - chunk = Buffer.from(chunk, encoding) - encoding = undefined; - len = chunk.length + default: function(){ + body = ''; } + }); - this.set('Content-Length', len); - } + // Respond + this.statusCode = status; + this.set('Content-Length', Buffer.byteLength(body)); - // populate ETag - var etag; - if (generateETag && len !== undefined) { - if ((etag = etagFn(chunk, encoding))) { - this.set('ETag', etag); - } + if (this.req.method === 'HEAD') { + this.end(); + } else { + this.end(body); } +}; - // freshness - if (req.fresh) this.statusCode = 304; +/** + * Add `field` to Vary. If already present in the Vary set, then + * this call is simply ignored. + * + * @param {Array|String} field + * @return {ServerResponse} for chaining + * @public + */ - // strip irrelevant headers - if (204 === this.statusCode || 304 === this.statusCode) { - this.removeHeader('Content-Type'); - this.removeHeader('Content-Length'); - this.removeHeader('Transfer-Encoding'); - chunk = ''; +res.vary = function(field){ + // checks for back-compat + if (!field || (Array.isArray(field) && !field.length)) { + deprecate('res.vary(): Provide a field name'); + return this; } - if (req.method === 'HEAD') { - // skip body for HEAD - this.end(); - } else { - // respond - this.end(chunk, encoding); - } + vary(this, field); return this; }; /** - * Send JSON response. + * Render `view` with the given `options` and optional callback `fn`. + * When a callback function is given a response will _not_ be made + * automatically, otherwise a response of _200_ and _text/html_ is given. * - * Examples: + * Options: * - * res.json(null); - * res.json({ user: 'tj' }); + * - `cache` boolean hinting to the engine it should cache + * - `filename` filename of the view being rendered * - * @param {string|number|boolean|object} obj * @public */ -res.json = function json(obj) { - var val = obj; +res.render = function render(view, options, callback) { + var app = this.req.app; + var done = callback; + var opts = options || {}; + var req = this.req; + var self = this; - // allow status / body - if (arguments.length === 2) { - // res.json(body, status) backwards compat - if (typeof arguments[1] === 'number') { - deprecate('res.json(obj, status): Use res.status(status).json(obj) instead'); - this.statusCode = arguments[1]; - } else { - deprecate('res.json(status, obj): Use res.status(status).json(obj) instead'); - this.statusCode = arguments[0]; - val = arguments[1]; - } + // support callback function as second arg + if (typeof options === 'function') { + done = options; + opts = {}; } - // settings - var app = this.app; - var escape = app.get('json escape') - var replacer = app.get('json replacer'); - var spaces = app.get('json spaces'); - var body = stringify(val, replacer, spaces, escape) + // merge res.locals + opts._locals = self.locals; - // content-type - if (!this.get('Content-Type')) { - this.set('Content-Type', 'application/json'); - } + // default callback to respond + done = done || function (err, str) { + if (err) return req.next(err); + self.send(str); + }; - return this.send(body); + // render + app.render(view, opts, done); }; -/** - * Send JSON response with JSONP callback support. - * - * Examples: - * - * res.jsonp(null); - * res.jsonp({ user: 'tj' }); - * - * @param {string|number|boolean|object} obj - * @public - */ +// pipe the send file stream +function sendfile(res, file, options, callback) { + var done = false; + var streaming; -res.jsonp = function jsonp(obj) { - var val = obj; + // request aborted + function onaborted() { + if (done) return; + done = true; - // allow status / body - if (arguments.length === 2) { - // res.jsonp(body, status) backwards compat - if (typeof arguments[1] === 'number') { - deprecate('res.jsonp(obj, status): Use res.status(status).jsonp(obj) instead'); - this.statusCode = arguments[1]; - } else { - deprecate('res.jsonp(status, obj): Use res.status(status).jsonp(obj) instead'); - this.statusCode = arguments[0]; - val = arguments[1]; - } + var err = new Error('Request aborted'); + err.code = 'ECONNABORTED'; + callback(err); } - // settings - var app = this.app; - var escape = app.get('json escape') - var replacer = app.get('json replacer'); - var spaces = app.get('json spaces'); - var body = stringify(val, replacer, spaces, escape) - var callback = this.req.query[app.get('jsonp callback name')]; + // directory + function ondirectory() { + if (done) return; + done = true; - // content-type - if (!this.get('Content-Type')) { - this.set('X-Content-Type-Options', 'nosniff'); - this.set('Content-Type', 'application/json'); + var err = new Error('EISDIR, read'); + err.code = 'EISDIR'; + callback(err); } - // fixup callback - if (Array.isArray(callback)) { - callback = callback[0]; + // errors + function onerror(err) { + if (done) return; + done = true; + callback(err); } - // jsonp - if (typeof callback === 'string' && callback.length !== 0) { - this.set('X-Content-Type-Options', 'nosniff'); - this.set('Content-Type', 'text/javascript'); + // ended + function onend() { + if (done) return; + done = true; + callback(); + } - // restrict callback charset - callback = callback.replace(/[^\[\]\w$.]/g, ''); + // file + function onfile() { + streaming = false; + } - if (body === undefined) { - // empty argument - body = '' - } else if (typeof body === 'string') { - // replace chars not allowed in JavaScript that are in JSON - body = body - .replace(/\u2028/g, '\\u2028') - .replace(/\u2029/g, '\\u2029') - } + // finished + function onfinish(err) { + if (err && err.code === 'ECONNRESET') return onaborted(); + if (err) return onerror(err); + if (done) return; - // the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse" - // the typeof check is just to reduce client error noise - body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');'; + setImmediate(function () { + if (streaming !== false && !done) { + onaborted(); + return; + } + + if (done) return; + done = true; + callback(); + }); } - return this.send(body); -}; + // streaming + function onstream() { + streaming = true; + } + + file.on('directory', ondirectory); + file.on('end', onend); + file.on('error', onerror); + file.on('file', onfile); + file.on('stream', onstream); + onFinished(res, onfinish); + + if (options.headers) { + // set headers on successful transfer + file.on('headers', function headers(res) { + var obj = options.headers; + var keys = Object.keys(obj); + + for (var i = 0; i < keys.length; i++) { + var k = keys[i]; + res.setHeader(k, obj[k]); + } + }); + } + + // pipe + file.pipe(res); +} /** - * Send given HTTP status code. - * - * Sets the response status to `statusCode` and the body of the - * response to the standard description from node's http.STATUS_CODES - * or the statusCode number if no description. - * - * Examples: - * - * res.sendStatus(200); + * Stringify JSON, like JSON.stringify, but v8 optimized, with the + * ability to escape characters that can trigger HTML sniffing. * - * @param {number} statusCode - * @public + * @param {*} value + * @param {function} replaces + * @param {number} spaces + * @param {boolean} escape + * @returns {string} + * @private */ -res.sendStatus = function sendStatus(statusCode) { - var body = statuses[statusCode] || String(statusCode) +function stringify (value, replacer, spaces, escape) { + // v8 checks arguments.length for optimizing simple call + // https://bugs.chromium.org/p/v8/issues/detail?id=4730 + var json = replacer || spaces + ? JSON.stringify(value, replacer, spaces) + : JSON.stringify(value); + + if (escape && typeof json === 'string') { + json = json.replace(/[<>&]/g, function (c) { + switch (c.charCodeAt(0)) { + case 0x3c: + return '\\u003c' + case 0x3e: + return '\\u003e' + case 0x26: + return '\\u0026' + /* istanbul ignore next: unreachable default */ + default: + return c + } + }) + } + + return json +} + + +/***/ }), + +/***/ 24963: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ - this.statusCode = statusCode; - this.type('txt'); - return this.send(body); -}; /** - * Transfer the file at the given `path`. - * - * Automatically sets the _Content-Type_ response header field. - * The callback `callback(err)` is invoked when the transfer is complete - * or when an error occurs. Be sure to check `res.headersSent` - * if you wish to attempt responding, as the header and some data - * may have already been transferred. - * - * Options: - * - * - `maxAge` defaulting to 0 (can be string converted by `ms`) - * - `root` root directory for relative filenames - * - `headers` object of headers to serve with file - * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them - * - * Other options are passed along to `send`. - * - * Examples: - * - * The following example illustrates how `res.sendFile()` may - * be used as an alternative for the `static()` middleware for - * dynamic situations. The code backing `res.sendFile()` is actually - * the same code, so HTTP cache support etc is identical. - * - * app.get('/user/:uid/photos/:file', function(req, res){ - * var uid = req.params.uid - * , file = req.params.file; - * - * req.user.mayViewFilesFrom(uid, function(yes){ - * if (yes) { - * res.sendFile('/uploads/' + uid + '/' + file); - * } else { - * res.send(403, 'Sorry! you cant see that.'); - * } - * }); - * }); - * - * @public + * Module dependencies. + * @private */ -res.sendFile = function sendFile(path, options, callback) { - var done = callback; - var req = this.req; - var res = this; - var next = req.next; - var opts = options || {}; +var Route = __nccwpck_require__(23699); +var Layer = __nccwpck_require__(25624); +var methods = __nccwpck_require__(58752); +var mixin = __nccwpck_require__(44429); +var debug = __nccwpck_require__(52529)('express:router'); +var deprecate = __nccwpck_require__(18883)('express'); +var flatten = __nccwpck_require__(62003); +var parseUrl = __nccwpck_require__(89808); +var setPrototypeOf = __nccwpck_require__(40414) - if (!path) { - throw new TypeError('path argument is required to res.sendFile'); - } +/** + * Module variables. + * @private + */ - if (typeof path !== 'string') { - throw new TypeError('path must be a string to res.sendFile') - } +var objectRegExp = /^\[object (\S+)\]$/; +var slice = Array.prototype.slice; +var toString = Object.prototype.toString; - // support function as second arg - if (typeof options === 'function') { - done = options; - opts = {}; - } +/** + * Initialize a new `Router` with the given `options`. + * + * @param {Object} [options] + * @return {Router} which is an callable function + * @public + */ - if (!opts.root && !isAbsolute(path)) { - throw new TypeError('path must be absolute or specify root to res.sendFile'); +var proto = module.exports = function(options) { + var opts = options || {}; + + function router(req, res, next) { + router.handle(req, res, next); } - // create file stream - var pathname = encodeURI(path); - var file = send(req, pathname, opts); + // mixin Router class functions + setPrototypeOf(router, proto) - // transfer - sendfile(res, file, opts, function (err) { - if (done) return done(err); - if (err && err.code === 'EISDIR') return next(); + router.params = {}; + router._params = []; + router.caseSensitive = opts.caseSensitive; + router.mergeParams = opts.mergeParams; + router.strict = opts.strict; + router.stack = []; - // next() all but write errors - if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') { - next(err); - } - }); + return router; }; /** - * Transfer the file at the given `path`. + * Map the given param placeholder `name`(s) to the given callback. * - * Automatically sets the _Content-Type_ response header field. - * The callback `callback(err)` is invoked when the transfer is complete - * or when an error occurs. Be sure to check `res.headersSent` - * if you wish to attempt responding, as the header and some data - * may have already been transferred. - * - * Options: - * - * - `maxAge` defaulting to 0 (can be string converted by `ms`) - * - `root` root directory for relative filenames - * - `headers` object of headers to serve with file - * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them - * - * Other options are passed along to `send`. - * - * Examples: + * Parameter mapping is used to provide pre-conditions to routes + * which use normalized placeholders. For example a _:user_id_ parameter + * could automatically load a user's information from the database without + * any additional code, * - * The following example illustrates how `res.sendfile()` may - * be used as an alternative for the `static()` middleware for - * dynamic situations. The code backing `res.sendfile()` is actually - * the same code, so HTTP cache support etc is identical. + * The callback uses the same signature as middleware, the only difference + * being that the value of the placeholder is passed, in this case the _id_ + * of the user. Once the `next()` function is invoked, just like middleware + * it will continue on to execute the route, or subsequent parameter functions. * - * app.get('/user/:uid/photos/:file', function(req, res){ - * var uid = req.params.uid - * , file = req.params.file; + * Just like in middleware, you must either respond to the request or call next + * to avoid stalling the request. * - * req.user.mayViewFilesFrom(uid, function(yes){ - * if (yes) { - * res.sendfile('/uploads/' + uid + '/' + file); - * } else { - * res.send(403, 'Sorry! you cant see that.'); - * } - * }); - * }); + * app.param('user_id', function(req, res, next, id){ + * User.find(id, function(err, user){ + * if (err) { + * return next(err); + * } else if (!user) { + * return next(new Error('failed to load user')); + * } + * req.user = user; + * next(); + * }); + * }); * + * @param {String} name + * @param {Function} fn + * @return {app} for chaining * @public */ -res.sendfile = function (path, options, callback) { - var done = callback; - var req = this.req; - var res = this; - var next = req.next; - var opts = options || {}; - - // support function as second arg - if (typeof options === 'function') { - done = options; - opts = {}; +proto.param = function param(name, fn) { + // param logic + if (typeof name === 'function') { + deprecate('router.param(fn): Refactor to use path params'); + this._params.push(name); + return; } - // create file stream - var file = send(req, path, opts); + // apply param functions + var params = this._params; + var len = params.length; + var ret; - // transfer - sendfile(res, file, opts, function (err) { - if (done) return done(err); - if (err && err.code === 'EISDIR') return next(); + if (name[0] === ':') { + deprecate('router.param(' + JSON.stringify(name) + ', fn): Use router.param(' + JSON.stringify(name.substr(1)) + ', fn) instead'); + name = name.substr(1); + } - // next() all but write errors - if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') { - next(err); + for (var i = 0; i < len; ++i) { + if (ret = params[i](name, fn)) { + fn = ret; } - }); -}; + } -res.sendfile = deprecate.function(res.sendfile, - 'res.sendfile: Use res.sendFile instead'); + // ensure we end up with a + // middleware function + if ('function' !== typeof fn) { + throw new Error('invalid param() call for ' + name + ', got ' + fn); + } + + (this.params[name] = this.params[name] || []).push(fn); + return this; +}; /** - * Transfer the file at the given `path` as an attachment. - * - * Optionally providing an alternate attachment `filename`, - * and optional callback `callback(err)`. The callback is invoked - * when the data transfer is complete, or when an error has - * ocurred. Be sure to check `res.headersSent` if you plan to respond. - * - * Optionally providing an `options` object to use with `res.sendFile()`. - * This function will set the `Content-Disposition` header, overriding - * any `Content-Disposition` header passed as header options in order - * to set the attachment and filename. - * - * This method uses `res.sendFile()`. - * - * @public + * Dispatch a req, res into the router. + * @private */ -res.download = function download (path, filename, options, callback) { - var done = callback; - var name = filename; - var opts = options || null +proto.handle = function handle(req, res, out) { + var self = this; - // support function as second or third arg - if (typeof filename === 'function') { - done = filename; - name = null; - opts = null - } else if (typeof options === 'function') { - done = options - opts = null + debug('dispatching %s %s', req.method, req.url); + + var idx = 0; + var protohost = getProtohost(req.url) || '' + var removed = ''; + var slashAdded = false; + var paramcalled = {}; + + // store options for OPTIONS request + // only used if OPTIONS request + var options = []; + + // middleware and routes + var stack = self.stack; + + // manage inter-router variables + var parentParams = req.params; + var parentUrl = req.baseUrl || ''; + var done = restore(out, req, 'baseUrl', 'next', 'params'); + + // setup next layer + req.next = next; + + // for options requests, respond with a default if nothing else responds + if (req.method === 'OPTIONS') { + done = wrap(done, function(old, err) { + if (err || options.length === 0) return old(err); + sendOptionsResponse(res, options, old); + }); } - // set Content-Disposition when file is sent - var headers = { - 'Content-Disposition': contentDisposition(name || path) - }; + // setup basic req values + req.baseUrl = parentUrl; + req.originalUrl = req.originalUrl || req.url; - // merge user-provided headers - if (opts && opts.headers) { - var keys = Object.keys(opts.headers) - for (var i = 0; i < keys.length; i++) { - var key = keys[i] - if (key.toLowerCase() !== 'content-disposition') { - headers[key] = opts.headers[key] - } + next(); + + function next(err) { + var layerError = err === 'route' + ? null + : err; + + // remove added slash + if (slashAdded) { + req.url = req.url.substr(1); + slashAdded = false; } - } - // merge user-provided options - opts = Object.create(opts) - opts.headers = headers + // restore altered req.url + if (removed.length !== 0) { + req.baseUrl = parentUrl; + req.url = protohost + removed + req.url.substr(protohost.length); + removed = ''; + } - // Resolve the full path for sendFile - var fullPath = resolve(path); + // signal to exit router + if (layerError === 'router') { + setImmediate(done, null) + return + } - // send file - return this.sendFile(fullPath, opts, done) -}; + // no more matching layers + if (idx >= stack.length) { + setImmediate(done, layerError); + return; + } -/** - * Set _Content-Type_ response header with `type` through `mime.lookup()` - * when it does not contain "/", or set the Content-Type to `type` otherwise. - * - * Examples: - * - * res.type('.html'); - * res.type('html'); - * res.type('json'); - * res.type('application/json'); - * res.type('png'); - * - * @param {String} type - * @return {ServerResponse} for chaining - * @public - */ + // get pathname of request + var path = getPathname(req); -res.contentType = -res.type = function contentType(type) { - var ct = type.indexOf('/') === -1 - ? mime.lookup(type) - : type; + if (path == null) { + return done(layerError); + } - return this.set('Content-Type', ct); -}; + // find next matching layer + var layer; + var match; + var route; -/** - * Respond to the Acceptable formats using an `obj` - * of mime-type callbacks. - * - * This method uses `req.accepted`, an array of - * acceptable types ordered by their quality values. - * When "Accept" is not present the _first_ callback - * is invoked, otherwise the first match is used. When - * no match is performed the server responds with - * 406 "Not Acceptable". - * - * Content-Type is set for you, however if you choose - * you may alter this within the callback using `res.type()` - * or `res.set('Content-Type', ...)`. - * - * res.format({ - * 'text/plain': function(){ - * res.send('hey'); - * }, - * - * 'text/html': function(){ - * res.send('

hey

'); - * }, - * - * 'application/json': function () { - * res.send({ message: 'hey' }); - * } - * }); - * - * In addition to canonicalized MIME types you may - * also use extnames mapped to these types: - * - * res.format({ - * text: function(){ - * res.send('hey'); - * }, - * - * html: function(){ - * res.send('

hey

'); - * }, - * - * json: function(){ - * res.send({ message: 'hey' }); - * } - * }); - * - * By default Express passes an `Error` - * with a `.status` of 406 to `next(err)` - * if a match is not made. If you provide - * a `.default` callback it will be invoked - * instead. - * - * @param {Object} obj - * @return {ServerResponse} for chaining - * @public - */ + while (match !== true && idx < stack.length) { + layer = stack[idx++]; + match = matchLayer(layer, path); + route = layer.route; -res.format = function(obj){ - var req = this.req; - var next = req.next; + if (typeof match !== 'boolean') { + // hold on to layerError + layerError = layerError || match; + } - var fn = obj.default; - if (fn) delete obj.default; - var keys = Object.keys(obj); + if (match !== true) { + continue; + } - var key = keys.length > 0 - ? req.accepts(keys) - : false; + if (!route) { + // process non-route handlers normally + continue; + } - this.vary("Accept"); + if (layerError) { + // routes do not match with a pending error + match = false; + continue; + } - if (key) { - this.set('Content-Type', normalizeType(key).value); - obj[key](req, this, next); - } else if (fn) { - fn(); - } else { - var err = new Error('Not Acceptable'); - err.status = err.statusCode = 406; - err.types = normalizeTypes(keys).map(function(o){ return o.value }); - next(err); - } + var method = req.method; + var has_method = route._handles_method(method); - return this; -}; + // build up automatic options response + if (!has_method && method === 'OPTIONS') { + appendMethods(options, route._options()); + } -/** - * Set _Content-Disposition_ header to _attachment_ with optional `filename`. - * - * @param {String} filename - * @return {ServerResponse} - * @public - */ + // don't even bother matching route + if (!has_method && method !== 'HEAD') { + match = false; + continue; + } + } -res.attachment = function attachment(filename) { - if (filename) { - this.type(extname(filename)); - } + // no match + if (match !== true) { + return done(layerError); + } - this.set('Content-Disposition', contentDisposition(filename)); + // store route for dispatch on change + if (route) { + req.route = route; + } - return this; -}; + // Capture one-time layer values + req.params = self.mergeParams + ? mergeParams(layer.params, parentParams) + : layer.params; + var layerPath = layer.path; -/** - * Append additional header `field` with value `val`. - * - * Example: - * - * res.append('Link', ['', '']); - * res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly'); - * res.append('Warning', '199 Miscellaneous warning'); - * - * @param {String} field - * @param {String|Array} val - * @return {ServerResponse} for chaining - * @public - */ + // this should be done for the layer + self.process_params(layer, paramcalled, req, res, function (err) { + if (err) { + return next(layerError || err); + } -res.append = function append(field, val) { - var prev = this.get(field); - var value = val; + if (route) { + return layer.handle_request(req, res, next); + } - if (prev) { - // concat the new and prev vals - value = Array.isArray(prev) ? prev.concat(val) - : Array.isArray(val) ? [prev].concat(val) - : [prev, val] + trim_prefix(layer, layerError, layerPath, path); + }); } - return this.set(field, value); -}; + function trim_prefix(layer, layerError, layerPath, path) { + if (layerPath.length !== 0) { + // Validate path is a prefix match + if (layerPath !== path.substr(0, layerPath.length)) { + next(layerError) + return + } -/** - * Set header `field` to `val`, or pass - * an object of header fields. - * - * Examples: - * - * res.set('Foo', ['bar', 'baz']); - * res.set('Accept', 'application/json'); - * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' }); - * - * Aliased as `res.header()`. - * - * @param {String|Object} field - * @param {String|Array} val - * @return {ServerResponse} for chaining - * @public - */ + // Validate path breaks on a path separator + var c = path[layerPath.length] + if (c && c !== '/' && c !== '.') return next(layerError) -res.set = -res.header = function header(field, val) { - if (arguments.length === 2) { - var value = Array.isArray(val) - ? val.map(String) - : String(val); + // Trim off the part of the url that matches the route + // middleware (.use stuff) needs to have the path stripped + debug('trim prefix (%s) from url %s', layerPath, req.url); + removed = layerPath; + req.url = protohost + req.url.substr(protohost.length + removed.length); - // add charset to content-type - if (field.toLowerCase() === 'content-type') { - if (Array.isArray(value)) { - throw new TypeError('Content-Type cannot be set to an Array'); - } - if (!charsetRegExp.test(value)) { - var charset = mime.charsets.lookup(value.split(';')[0]); - if (charset) value += '; charset=' + charset.toLowerCase(); + // Ensure leading slash + if (!protohost && req.url[0] !== '/') { + req.url = '/' + req.url; + slashAdded = true; } + + // Setup base URL (no trailing slash) + req.baseUrl = parentUrl + (removed[removed.length - 1] === '/' + ? removed.substring(0, removed.length - 1) + : removed); } - this.setHeader(field, value); - } else { - for (var key in field) { - this.set(key, field[key]); + debug('%s %s : %s', layer.name, layerPath, req.originalUrl); + + if (layerError) { + layer.handle_error(layerError, req, res, next); + } else { + layer.handle_request(req, res, next); } } - return this; }; /** - * Get value for header `field`. - * - * @param {String} field - * @return {String} - * @public + * Process any parameters for the layer. + * @private */ -res.get = function(field){ - return this.getHeader(field); -}; +proto.process_params = function process_params(layer, called, req, res, done) { + var params = this.params; -/** - * Clear cookie `name`. - * - * @param {String} name - * @param {Object} [options] - * @return {ServerResponse} for chaining - * @public - */ + // captured parameters from the layer, keys and values + var keys = layer.keys; -res.clearCookie = function clearCookie(name, options) { - var opts = merge({ expires: new Date(1), path: '/' }, options); + // fast track + if (!keys || keys.length === 0) { + return done(); + } - return this.cookie(name, '', opts); -}; + var i = 0; + var name; + var paramIndex = 0; + var key; + var paramVal; + var paramCallbacks; + var paramCalled; -/** - * Set cookie `name` to `value`, with the given `options`. - * - * Options: - * - * - `maxAge` max-age in milliseconds, converted to `expires` - * - `signed` sign the cookie - * - `path` defaults to "/" - * - * Examples: - * - * // "Remember Me" for 15 minutes - * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true }); - * - * // same as above - * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true }) - * - * @param {String} name - * @param {String|Object} value - * @param {Object} [options] - * @return {ServerResponse} for chaining - * @public - */ + // process params in order + // param callbacks can be async + function param(err) { + if (err) { + return done(err); + } -res.cookie = function (name, value, options) { - var opts = merge({}, options); - var secret = this.req.secret; - var signed = opts.signed; + if (i >= keys.length ) { + return done(); + } - if (signed && !secret) { - throw new Error('cookieParser("secret") required for signed cookies'); - } + paramIndex = 0; + key = keys[i++]; + name = key.name; + paramVal = req.params[name]; + paramCallbacks = params[name]; + paramCalled = called[name]; - var val = typeof value === 'object' - ? 'j:' + JSON.stringify(value) - : String(value); + if (paramVal === undefined || !paramCallbacks) { + return param(); + } - if (signed) { - val = 's:' + sign(val, secret); - } + // param previously called with same value or error occurred + if (paramCalled && (paramCalled.match === paramVal + || (paramCalled.error && paramCalled.error !== 'route'))) { + // restore value + req.params[name] = paramCalled.value; - if ('maxAge' in opts) { - opts.expires = new Date(Date.now() + opts.maxAge); - opts.maxAge /= 1000; - } + // next param + return param(paramCalled.error); + } - if (opts.path == null) { - opts.path = '/'; + called[name] = paramCalled = { + error: null, + match: paramVal, + value: paramVal + }; + + paramCallback(); } - this.append('Set-Cookie', cookie.serialize(name, String(val), opts)); + // single param callbacks + function paramCallback(err) { + var fn = paramCallbacks[paramIndex++]; - return this; -}; + // store updated value + paramCalled.value = req.params[key.name]; -/** - * Set the location header to `url`. - * - * The given `url` can also be "back", which redirects - * to the _Referrer_ or _Referer_ headers or "/". - * - * Examples: - * - * res.location('/foo/bar').; - * res.location('http://example.com'); - * res.location('../login'); - * - * @param {String} url - * @return {ServerResponse} for chaining - * @public - */ + if (err) { + // store error + paramCalled.error = err; + param(err); + return; + } -res.location = function location(url) { - var loc = url; + if (!fn) return param(); - // "back" is an alias for the referrer - if (url === 'back') { - loc = this.req.get('Referrer') || '/'; + try { + fn(req, res, paramCallback, paramVal, key.name); + } catch (e) { + paramCallback(e); + } } - // set location - return this.set('Location', encodeUrl(loc)); + param(); }; /** - * Redirect to the given `url` with optional response `status` - * defaulting to 302. - * - * The resulting `url` is determined by `res.location()`, so - * it will play nicely with mounted apps, relative paths, - * `"back"` etc. + * Use the given middleware function, with optional path, defaulting to "/". * - * Examples: + * Use (like `.all`) will run for any http METHOD, but it will not add + * handlers for those methods so OPTIONS requests will not consider `.use` + * functions even if they could respond. * - * res.redirect('/foo/bar'); - * res.redirect('http://example.com'); - * res.redirect(301, 'http://example.com'); - * res.redirect('../login'); // /blog/post/1 -> /blog/login + * The other difference is that _route_ path is stripped and not visible + * to the handler function. The main effect of this feature is that mounted + * handlers can operate without any code changes regardless of the "prefix" + * pathname. * * @public */ -res.redirect = function redirect(url) { - var address = url; - var body; - var status = 302; +proto.use = function use(fn) { + var offset = 0; + var path = '/'; - // allow status / url - if (arguments.length === 2) { - if (typeof arguments[0] === 'number') { - status = arguments[0]; - address = arguments[1]; - } else { - deprecate('res.redirect(url, status): Use res.redirect(status, url) instead'); - status = arguments[1]; + // default path to '/' + // disambiguate router.use([fn]) + if (typeof fn !== 'function') { + var arg = fn; + + while (Array.isArray(arg) && arg.length !== 0) { + arg = arg[0]; + } + + // first arg is the path + if (typeof arg !== 'function') { + offset = 1; + path = fn; } } - // Set location header - address = this.location(address).get('Location'); + var callbacks = flatten(slice.call(arguments, offset)); - // Support text/{plain,html} by default - this.format({ - text: function(){ - body = statuses[status] + '. Redirecting to ' + address - }, + if (callbacks.length === 0) { + throw new TypeError('Router.use() requires a middleware function') + } - html: function(){ - var u = escapeHtml(address); - body = '

' + statuses[status] + '. Redirecting to ' + u + '

' - }, + for (var i = 0; i < callbacks.length; i++) { + var fn = callbacks[i]; - default: function(){ - body = ''; + if (typeof fn !== 'function') { + throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn)) } - }); - // Respond - this.statusCode = status; - this.set('Content-Length', Buffer.byteLength(body)); + // add the middleware + debug('use %o %s', path, fn.name || '') - if (this.req.method === 'HEAD') { - this.end(); - } else { - this.end(body); - } -}; + var layer = new Layer(path, { + sensitive: this.caseSensitive, + strict: false, + end: false + }, fn); -/** - * Add `field` to Vary. If already present in the Vary set, then - * this call is simply ignored. - * - * @param {Array|String} field - * @return {ServerResponse} for chaining - * @public - */ + layer.route = undefined; -res.vary = function(field){ - // checks for back-compat - if (!field || (Array.isArray(field) && !field.length)) { - deprecate('res.vary(): Provide a field name'); - return this; + this.stack.push(layer); } - vary(this, field); - return this; }; /** - * Render `view` with the given `options` and optional callback `fn`. - * When a callback function is given a response will _not_ be made - * automatically, otherwise a response of _200_ and _text/html_ is given. + * Create a new Route for the given path. * - * Options: + * Each route contains a separate middleware stack and VERB handlers. * - * - `cache` boolean hinting to the engine it should cache - * - `filename` filename of the view being rendered + * See the Route api documentation for details on adding handlers + * and middleware to routes. * + * @param {String} path + * @return {Route} * @public */ -res.render = function render(view, options, callback) { - var app = this.req.app; - var done = callback; - var opts = options || {}; - var req = this.req; - var self = this; - - // support callback function as second arg - if (typeof options === 'function') { - done = options; - opts = {}; - } +proto.route = function route(path) { + var route = new Route(path); - // merge res.locals - opts._locals = self.locals; + var layer = new Layer(path, { + sensitive: this.caseSensitive, + strict: this.strict, + end: true + }, route.dispatch.bind(route)); - // default callback to respond - done = done || function (err, str) { - if (err) return req.next(err); - self.send(str); - }; + layer.route = route; - // render - app.render(view, opts, done); + this.stack.push(layer); + return route; }; -// pipe the send file stream -function sendfile(res, file, options, callback) { - var done = false; - var streaming; +// create Router#VERB functions +methods.concat('all').forEach(function(method){ + proto[method] = function(path){ + var route = this.route(path) + route[method].apply(route, slice.call(arguments, 1)); + return this; + }; +}); - // request aborted - function onaborted() { - if (done) return; - done = true; +// append methods to a list of methods +function appendMethods(list, addition) { + for (var i = 0; i < addition.length; i++) { + var method = addition[i]; + if (list.indexOf(method) === -1) { + list.push(method); + } + } +} - var err = new Error('Request aborted'); - err.code = 'ECONNABORTED'; - callback(err); +// get pathname of request +function getPathname(req) { + try { + return parseUrl(req).pathname; + } catch (err) { + return undefined; } +} - // directory - function ondirectory() { - if (done) return; - done = true; +// Get get protocol + host for a URL +function getProtohost(url) { + if (typeof url !== 'string' || url.length === 0 || url[0] === '/') { + return undefined + } - var err = new Error('EISDIR, read'); - err.code = 'EISDIR'; - callback(err); + var searchIndex = url.indexOf('?') + var pathLength = searchIndex !== -1 + ? searchIndex + : url.length + var fqdnIndex = url.substr(0, pathLength).indexOf('://') + + return fqdnIndex !== -1 + ? url.substr(0, url.indexOf('/', 3 + fqdnIndex)) + : undefined +} + +// get type for error message +function gettype(obj) { + var type = typeof obj; + + if (type !== 'object') { + return type; } - // errors - function onerror(err) { - if (done) return; - done = true; - callback(err); + // inspect [[Class]] for objects + return toString.call(obj) + .replace(objectRegExp, '$1'); +} + +/** + * Match path to a layer. + * + * @param {Layer} layer + * @param {string} path + * @private + */ + +function matchLayer(layer, path) { + try { + return layer.match(path); + } catch (err) { + return err; } +} - // ended - function onend() { - if (done) return; - done = true; - callback(); +// merge params with parent params +function mergeParams(params, parent) { + if (typeof parent !== 'object' || !parent) { + return params; } - // file - function onfile() { - streaming = false; + // make copy of parent for base + var obj = mixin({}, parent); + + // simple non-numeric merging + if (!(0 in params) || !(0 in parent)) { + return mixin(obj, params); } - // finished - function onfinish(err) { - if (err && err.code === 'ECONNRESET') return onaborted(); - if (err) return onerror(err); - if (done) return; + var i = 0; + var o = 0; - setImmediate(function () { - if (streaming !== false && !done) { - onaborted(); - return; - } + // determine numeric gaps + while (i in params) { + i++; + } - if (done) return; - done = true; - callback(); - }); + while (o in parent) { + o++; } - // streaming - function onstream() { - streaming = true; + // offset numeric indices in params before merge + for (i--; i >= 0; i--) { + params[i + o] = params[i]; + + // create holes for the merge when necessary + if (i < o) { + delete params[i]; + } } - file.on('directory', ondirectory); - file.on('end', onend); - file.on('error', onerror); - file.on('file', onfile); - file.on('stream', onstream); - onFinished(res, onfinish); + return mixin(obj, params); +} - if (options.headers) { - // set headers on successful transfer - file.on('headers', function headers(res) { - var obj = options.headers; - var keys = Object.keys(obj); +// restore obj props after function +function restore(fn, obj) { + var props = new Array(arguments.length - 2); + var vals = new Array(arguments.length - 2); - for (var i = 0; i < keys.length; i++) { - var k = keys[i]; - res.setHeader(k, obj[k]); - } - }); + for (var i = 0; i < props.length; i++) { + props[i] = arguments[i + 2]; + vals[i] = obj[props[i]]; } - // pipe - file.pipe(res); + return function () { + // restore vals + for (var i = 0; i < props.length; i++) { + obj[props[i]] = vals[i]; + } + + return fn.apply(this, arguments); + }; } -/** - * Stringify JSON, like JSON.stringify, but v8 optimized, with the - * ability to escape characters that can trigger HTML sniffing. - * - * @param {*} value - * @param {function} replaces - * @param {number} spaces - * @param {boolean} escape - * @returns {string} - * @private - */ +// send an OPTIONS response +function sendOptionsResponse(res, options, next) { + try { + var body = options.join(','); + res.set('Allow', body); + res.send(body); + } catch (err) { + next(err); + } +} -function stringify (value, replacer, spaces, escape) { - // v8 checks arguments.length for optimizing simple call - // https://bugs.chromium.org/p/v8/issues/detail?id=4730 - var json = replacer || spaces - ? JSON.stringify(value, replacer, spaces) - : JSON.stringify(value); +// wrap a function +function wrap(old, fn) { + return function proxy() { + var args = new Array(arguments.length + 1); - if (escape && typeof json === 'string') { - json = json.replace(/[<>&]/g, function (c) { - switch (c.charCodeAt(0)) { - case 0x3c: - return '\\u003c' - case 0x3e: - return '\\u003e' - case 0x26: - return '\\u0026' - /* istanbul ignore next: unreachable default */ - default: - return c - } - }) - } + args[0] = old; + for (var i = 0, len = arguments.length; i < len; i++) { + args[i + 1] = arguments[i]; + } - return json + fn.apply(this, args); + }; } /***/ }), -/***/ 24963: +/***/ 25624: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -40727,664 +39587,711 @@ function stringify (value, replacer, spaces, escape) { * @private */ -var Route = __nccwpck_require__(23699); -var Layer = __nccwpck_require__(25624); -var methods = __nccwpck_require__(58752); -var mixin = __nccwpck_require__(44429); -var debug = __nccwpck_require__(52529)('express:router'); -var deprecate = __nccwpck_require__(18883)('express'); -var flatten = __nccwpck_require__(62003); -var parseUrl = __nccwpck_require__(89808); -var setPrototypeOf = __nccwpck_require__(40414) - +var pathRegexp = __nccwpck_require__(37819); +var debug = __nccwpck_require__(52529)('express:router:layer'); + /** * Module variables. * @private */ -var objectRegExp = /^\[object (\S+)\]$/; -var slice = Array.prototype.slice; -var toString = Object.prototype.toString; +var hasOwnProperty = Object.prototype.hasOwnProperty; /** - * Initialize a new `Router` with the given `options`. - * - * @param {Object} [options] - * @return {Router} which is an callable function + * Module exports. * @public */ -var proto = module.exports = function(options) { - var opts = options || {}; +module.exports = Layer; - function router(req, res, next) { - router.handle(req, res, next); +function Layer(path, options, fn) { + if (!(this instanceof Layer)) { + return new Layer(path, options, fn); } - // mixin Router class functions - setPrototypeOf(router, proto) + debug('new %o', path) + var opts = options || {}; - router.params = {}; - router._params = []; - router.caseSensitive = opts.caseSensitive; - router.mergeParams = opts.mergeParams; - router.strict = opts.strict; - router.stack = []; + this.handle = fn; + this.name = fn.name || ''; + this.params = undefined; + this.path = undefined; + this.regexp = pathRegexp(path, this.keys = [], opts); - return router; -}; + // set fast path flags + this.regexp.fast_star = path === '*' + this.regexp.fast_slash = path === '/' && opts.end === false +} /** - * Map the given param placeholder `name`(s) to the given callback. - * - * Parameter mapping is used to provide pre-conditions to routes - * which use normalized placeholders. For example a _:user_id_ parameter - * could automatically load a user's information from the database without - * any additional code, - * - * The callback uses the same signature as middleware, the only difference - * being that the value of the placeholder is passed, in this case the _id_ - * of the user. Once the `next()` function is invoked, just like middleware - * it will continue on to execute the route, or subsequent parameter functions. - * - * Just like in middleware, you must either respond to the request or call next - * to avoid stalling the request. - * - * app.param('user_id', function(req, res, next, id){ - * User.find(id, function(err, user){ - * if (err) { - * return next(err); - * } else if (!user) { - * return next(new Error('failed to load user')); - * } - * req.user = user; - * next(); - * }); - * }); + * Handle the error for the layer. * - * @param {String} name - * @param {Function} fn - * @return {app} for chaining - * @public + * @param {Error} error + * @param {Request} req + * @param {Response} res + * @param {function} next + * @api private */ -proto.param = function param(name, fn) { - // param logic - if (typeof name === 'function') { - deprecate('router.param(fn): Refactor to use path params'); - this._params.push(name); - return; - } - - // apply param functions - var params = this._params; - var len = params.length; - var ret; +Layer.prototype.handle_error = function handle_error(error, req, res, next) { + var fn = this.handle; - if (name[0] === ':') { - deprecate('router.param(' + JSON.stringify(name) + ', fn): Use router.param(' + JSON.stringify(name.substr(1)) + ', fn) instead'); - name = name.substr(1); + if (fn.length !== 4) { + // not a standard error handler + return next(error); } - for (var i = 0; i < len; ++i) { - if (ret = params[i](name, fn)) { - fn = ret; - } + try { + fn(error, req, res, next); + } catch (err) { + next(err); } +}; - // ensure we end up with a - // middleware function - if ('function' !== typeof fn) { - throw new Error('invalid param() call for ' + name + ', got ' + fn); +/** + * Handle the request for the layer. + * + * @param {Request} req + * @param {Response} res + * @param {function} next + * @api private + */ + +Layer.prototype.handle_request = function handle(req, res, next) { + var fn = this.handle; + + if (fn.length > 3) { + // not a standard request handler + return next(); } - (this.params[name] = this.params[name] || []).push(fn); - return this; + try { + fn(req, res, next); + } catch (err) { + next(err); + } }; /** - * Dispatch a req, res into the router. - * @private + * Check if this route matches `path`, if so + * populate `.params`. + * + * @param {String} path + * @return {Boolean} + * @api private */ -proto.handle = function handle(req, res, out) { - var self = this; +Layer.prototype.match = function match(path) { + var match - debug('dispatching %s %s', req.method, req.url); + if (path != null) { + // fast path non-ending match for / (any path matches) + if (this.regexp.fast_slash) { + this.params = {} + this.path = '' + return true + } - var idx = 0; - var protohost = getProtohost(req.url) || '' - var removed = ''; - var slashAdded = false; - var paramcalled = {}; + // fast path for * (everything matched in a param) + if (this.regexp.fast_star) { + this.params = {'0': decode_param(path)} + this.path = path + return true + } - // store options for OPTIONS request - // only used if OPTIONS request - var options = []; + // match the path + match = this.regexp.exec(path) + } - // middleware and routes - var stack = self.stack; + if (!match) { + this.params = undefined; + this.path = undefined; + return false; + } - // manage inter-router variables - var parentParams = req.params; - var parentUrl = req.baseUrl || ''; - var done = restore(out, req, 'baseUrl', 'next', 'params'); + // store values + this.params = {}; + this.path = match[0] - // setup next layer - req.next = next; + var keys = this.keys; + var params = this.params; - // for options requests, respond with a default if nothing else responds - if (req.method === 'OPTIONS') { - done = wrap(done, function(old, err) { - if (err || options.length === 0) return old(err); - sendOptionsResponse(res, options, old); - }); - } + for (var i = 1; i < match.length; i++) { + var key = keys[i - 1]; + var prop = key.name; + var val = decode_param(match[i]) - // setup basic req values - req.baseUrl = parentUrl; - req.originalUrl = req.originalUrl || req.url; + if (val !== undefined || !(hasOwnProperty.call(params, prop))) { + params[prop] = val; + } + } - next(); + return true; +}; - function next(err) { - var layerError = err === 'route' - ? null - : err; +/** + * Decode param value. + * + * @param {string} val + * @return {string} + * @private + */ - // remove added slash - if (slashAdded) { - req.url = req.url.substr(1); - slashAdded = false; - } +function decode_param(val) { + if (typeof val !== 'string' || val.length === 0) { + return val; + } - // restore altered req.url - if (removed.length !== 0) { - req.baseUrl = parentUrl; - req.url = protohost + removed + req.url.substr(protohost.length); - removed = ''; + try { + return decodeURIComponent(val); + } catch (err) { + if (err instanceof URIError) { + err.message = 'Failed to decode param \'' + val + '\''; + err.status = err.statusCode = 400; } - // signal to exit router - if (layerError === 'router') { - setImmediate(done, null) - return - } + throw err; + } +} - // no more matching layers - if (idx >= stack.length) { - setImmediate(done, layerError); - return; - } - // get pathname of request - var path = getPathname(req); +/***/ }), - if (path == null) { - return done(layerError); - } +/***/ 23699: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // find next matching layer - var layer; - var match; - var route; +"use strict"; +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ - while (match !== true && idx < stack.length) { - layer = stack[idx++]; - match = matchLayer(layer, path); - route = layer.route; - if (typeof match !== 'boolean') { - // hold on to layerError - layerError = layerError || match; - } - if (match !== true) { - continue; - } +/** + * Module dependencies. + * @private + */ - if (!route) { - // process non-route handlers normally - continue; - } +var debug = __nccwpck_require__(52529)('express:router:route'); +var flatten = __nccwpck_require__(62003); +var Layer = __nccwpck_require__(25624); +var methods = __nccwpck_require__(58752); - if (layerError) { - // routes do not match with a pending error - match = false; - continue; - } +/** + * Module variables. + * @private + */ - var method = req.method; - var has_method = route._handles_method(method); +var slice = Array.prototype.slice; +var toString = Object.prototype.toString; - // build up automatic options response - if (!has_method && method === 'OPTIONS') { - appendMethods(options, route._options()); - } +/** + * Module exports. + * @public + */ - // don't even bother matching route - if (!has_method && method !== 'HEAD') { - match = false; - continue; - } - } +module.exports = Route; - // no match - if (match !== true) { - return done(layerError); - } +/** + * Initialize `Route` with the given `path`, + * + * @param {String} path + * @public + */ - // store route for dispatch on change - if (route) { - req.route = route; - } +function Route(path) { + this.path = path; + this.stack = []; - // Capture one-time layer values - req.params = self.mergeParams - ? mergeParams(layer.params, parentParams) - : layer.params; - var layerPath = layer.path; + debug('new %o', path) - // this should be done for the layer - self.process_params(layer, paramcalled, req, res, function (err) { - if (err) { - return next(layerError || err); - } + // route handlers for various http methods + this.methods = {}; +} - if (route) { - return layer.handle_request(req, res, next); - } +/** + * Determine if the route handles a given method. + * @private + */ - trim_prefix(layer, layerError, layerPath, path); - }); +Route.prototype._handles_method = function _handles_method(method) { + if (this.methods._all) { + return true; } - function trim_prefix(layer, layerError, layerPath, path) { - if (layerPath.length !== 0) { - // Validate path is a prefix match - if (layerPath !== path.substr(0, layerPath.length)) { - next(layerError) - return - } + var name = method.toLowerCase(); - // Validate path breaks on a path separator - var c = path[layerPath.length] - if (c && c !== '/' && c !== '.') return next(layerError) + if (name === 'head' && !this.methods['head']) { + name = 'get'; + } - // Trim off the part of the url that matches the route - // middleware (.use stuff) needs to have the path stripped - debug('trim prefix (%s) from url %s', layerPath, req.url); - removed = layerPath; - req.url = protohost + req.url.substr(protohost.length + removed.length); + return Boolean(this.methods[name]); +}; - // Ensure leading slash - if (!protohost && req.url[0] !== '/') { - req.url = '/' + req.url; - slashAdded = true; - } +/** + * @return {Array} supported HTTP methods + * @private + */ - // Setup base URL (no trailing slash) - req.baseUrl = parentUrl + (removed[removed.length - 1] === '/' - ? removed.substring(0, removed.length - 1) - : removed); - } +Route.prototype._options = function _options() { + var methods = Object.keys(this.methods); - debug('%s %s : %s', layer.name, layerPath, req.originalUrl); + // append automatic head + if (this.methods.get && !this.methods.head) { + methods.push('head'); + } - if (layerError) { - layer.handle_error(layerError, req, res, next); - } else { - layer.handle_request(req, res, next); - } + for (var i = 0; i < methods.length; i++) { + // make upper case + methods[i] = methods[i].toUpperCase(); } + + return methods; }; /** - * Process any parameters for the layer. + * dispatch req, res into this route * @private */ -proto.process_params = function process_params(layer, called, req, res, done) { - var params = this.params; - - // captured parameters from the layer, keys and values - var keys = layer.keys; - - // fast track - if (!keys || keys.length === 0) { +Route.prototype.dispatch = function dispatch(req, res, done) { + var idx = 0; + var stack = this.stack; + if (stack.length === 0) { return done(); } - var i = 0; - var name; - var paramIndex = 0; - var key; - var paramVal; - var paramCallbacks; - var paramCalled; + var method = req.method.toLowerCase(); + if (method === 'head' && !this.methods['head']) { + method = 'get'; + } - // process params in order - // param callbacks can be async - function param(err) { - if (err) { - return done(err); - } + req.route = this; - if (i >= keys.length ) { + next(); + + function next(err) { + // signal to exit route + if (err && err === 'route') { return done(); } - paramIndex = 0; - key = keys[i++]; - name = key.name; - paramVal = req.params[name]; - paramCallbacks = params[name]; - paramCalled = called[name]; - - if (paramVal === undefined || !paramCallbacks) { - return param(); + // signal to exit router + if (err && err === 'router') { + return done(err) } - // param previously called with same value or error occurred - if (paramCalled && (paramCalled.match === paramVal - || (paramCalled.error && paramCalled.error !== 'route'))) { - // restore value - req.params[name] = paramCalled.value; - - // next param - return param(paramCalled.error); + var layer = stack[idx++]; + if (!layer) { + return done(err); } - called[name] = paramCalled = { - error: null, - match: paramVal, - value: paramVal - }; - - paramCallback(); - } - - // single param callbacks - function paramCallback(err) { - var fn = paramCallbacks[paramIndex++]; - - // store updated value - paramCalled.value = req.params[key.name]; - - if (err) { - // store error - paramCalled.error = err; - param(err); - return; + if (layer.method && layer.method !== method) { + return next(err); } - if (!fn) return param(); - - try { - fn(req, res, paramCallback, paramVal, key.name); - } catch (e) { - paramCallback(e); + if (err) { + layer.handle_error(err, req, res, next); + } else { + layer.handle_request(req, res, next); } } - - param(); }; /** - * Use the given middleware function, with optional path, defaulting to "/". + * Add a handler for all HTTP verbs to this route. * - * Use (like `.all`) will run for any http METHOD, but it will not add - * handlers for those methods so OPTIONS requests will not consider `.use` - * functions even if they could respond. + * Behaves just like middleware and can respond or call `next` + * to continue processing. * - * The other difference is that _route_ path is stripped and not visible - * to the handler function. The main effect of this feature is that mounted - * handlers can operate without any code changes regardless of the "prefix" - * pathname. + * You can use multiple `.all` call to add multiple handlers. * - * @public + * function check_something(req, res, next){ + * next(); + * }; + * + * function validate_user(req, res, next){ + * next(); + * }; + * + * route + * .all(validate_user) + * .all(check_something) + * .get(function(req, res, next){ + * res.send('hello world'); + * }); + * + * @param {function} handler + * @return {Route} for chaining + * @api public */ -proto.use = function use(fn) { - var offset = 0; - var path = '/'; +Route.prototype.all = function all() { + var handles = flatten(slice.call(arguments)); - // default path to '/' - // disambiguate router.use([fn]) - if (typeof fn !== 'function') { - var arg = fn; + for (var i = 0; i < handles.length; i++) { + var handle = handles[i]; - while (Array.isArray(arg) && arg.length !== 0) { - arg = arg[0]; + if (typeof handle !== 'function') { + var type = toString.call(handle); + var msg = 'Route.all() requires a callback function but got a ' + type + throw new TypeError(msg); } - // first arg is the path - if (typeof arg !== 'function') { - offset = 1; - path = fn; - } + var layer = Layer('/', {}, handle); + layer.method = undefined; + + this.methods._all = true; + this.stack.push(layer); } - var callbacks = flatten(slice.call(arguments, offset)); + return this; +}; - if (callbacks.length === 0) { - throw new TypeError('Router.use() requires a middleware function') - } +methods.forEach(function(method){ + Route.prototype[method] = function(){ + var handles = flatten(slice.call(arguments)); - for (var i = 0; i < callbacks.length; i++) { - var fn = callbacks[i]; + for (var i = 0; i < handles.length; i++) { + var handle = handles[i]; - if (typeof fn !== 'function') { - throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn)) + if (typeof handle !== 'function') { + var type = toString.call(handle); + var msg = 'Route.' + method + '() requires a callback function but got a ' + type + throw new Error(msg); + } + + debug('%s %o', method, this.path) + + var layer = Layer('/', {}, handle); + layer.method = method; + + this.methods[method] = true; + this.stack.push(layer); } - // add the middleware - debug('use %o %s', path, fn.name || '') + return this; + }; +}); - var layer = new Layer(path, { - sensitive: this.caseSensitive, - strict: false, - end: false - }, fn); - layer.route = undefined; +/***/ }), + +/***/ 53561: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ - this.stack.push(layer); - } - return this; -}; /** - * Create a new Route for the given path. + * Module dependencies. + * @api private + */ + +var Buffer = (__nccwpck_require__(41894).Buffer) +var contentDisposition = __nccwpck_require__(53921); +var contentType = __nccwpck_require__(99915); +var deprecate = __nccwpck_require__(18883)('express'); +var flatten = __nccwpck_require__(62003); +var mime = (__nccwpck_require__(95287).mime); +var etag = __nccwpck_require__(69972); +var proxyaddr = __nccwpck_require__(80140); +var qs = __nccwpck_require__(22760); +var querystring = __nccwpck_require__(63477); + +/** + * Return strong ETag for `body`. * - * Each route contains a separate middleware stack and VERB handlers. + * @param {String|Buffer} body + * @param {String} [encoding] + * @return {String} + * @api private + */ + +exports.etag = createETagGenerator({ weak: false }) + +/** + * Return weak ETag for `body`. * - * See the Route api documentation for details on adding handlers - * and middleware to routes. + * @param {String|Buffer} body + * @param {String} [encoding] + * @return {String} + * @api private + */ + +exports.wetag = createETagGenerator({ weak: true }) + +/** + * Check if `path` looks absolute. * * @param {String} path - * @return {Route} - * @public + * @return {Boolean} + * @api private */ -proto.route = function route(path) { - var route = new Route(path); +exports.isAbsolute = function(path){ + if ('/' === path[0]) return true; + if (':' === path[1] && ('\\' === path[2] || '/' === path[2])) return true; // Windows device path + if ('\\\\' === path.substring(0, 2)) return true; // Microsoft Azure absolute path +}; - var layer = new Layer(path, { - sensitive: this.caseSensitive, - strict: this.strict, - end: true - }, route.dispatch.bind(route)); +/** + * Flatten the given `arr`. + * + * @param {Array} arr + * @return {Array} + * @api private + */ - layer.route = route; +exports.flatten = deprecate.function(flatten, + 'utils.flatten: use array-flatten npm module instead'); - this.stack.push(layer); - return route; +/** + * Normalize the given `type`, for example "html" becomes "text/html". + * + * @param {String} type + * @return {Object} + * @api private + */ + +exports.normalizeType = function(type){ + return ~type.indexOf('/') + ? acceptParams(type) + : { value: mime.lookup(type), params: {} }; }; -// create Router#VERB functions -methods.concat('all').forEach(function(method){ - proto[method] = function(path){ - var route = this.route(path) - route[method].apply(route, slice.call(arguments, 1)); - return this; - }; -}); +/** + * Normalize `types`, for example "html" becomes "text/html". + * + * @param {Array} types + * @return {Array} + * @api private + */ -// append methods to a list of methods -function appendMethods(list, addition) { - for (var i = 0; i < addition.length; i++) { - var method = addition[i]; - if (list.indexOf(method) === -1) { - list.push(method); - } - } -} +exports.normalizeTypes = function(types){ + var ret = []; -// get pathname of request -function getPathname(req) { - try { - return parseUrl(req).pathname; - } catch (err) { - return undefined; + for (var i = 0; i < types.length; ++i) { + ret.push(exports.normalizeType(types[i])); } -} -// Get get protocol + host for a URL -function getProtohost(url) { - if (typeof url !== 'string' || url.length === 0 || url[0] === '/') { - return undefined - } + return ret; +}; - var searchIndex = url.indexOf('?') - var pathLength = searchIndex !== -1 - ? searchIndex - : url.length - var fqdnIndex = url.substr(0, pathLength).indexOf('://') +/** + * Generate Content-Disposition header appropriate for the filename. + * non-ascii filenames are urlencoded and a filename* parameter is added + * + * @param {String} filename + * @return {String} + * @api private + */ - return fqdnIndex !== -1 - ? url.substr(0, url.indexOf('/', 3 + fqdnIndex)) - : undefined -} +exports.contentDisposition = deprecate.function(contentDisposition, + 'utils.contentDisposition: use content-disposition npm module instead'); -// get type for error message -function gettype(obj) { - var type = typeof obj; +/** + * Parse accept params `str` returning an + * object with `.value`, `.quality` and `.params`. + * also includes `.originalIndex` for stable sorting + * + * @param {String} str + * @return {Object} + * @api private + */ - if (type !== 'object') { - return type; +function acceptParams(str, index) { + var parts = str.split(/ *; */); + var ret = { value: parts[0], quality: 1, params: {}, originalIndex: index }; + + for (var i = 1; i < parts.length; ++i) { + var pms = parts[i].split(/ *= */); + if ('q' === pms[0]) { + ret.quality = parseFloat(pms[1]); + } else { + ret.params[pms[0]] = pms[1]; + } } - // inspect [[Class]] for objects - return toString.call(obj) - .replace(objectRegExp, '$1'); + return ret; } /** - * Match path to a layer. + * Compile "etag" value to function. * - * @param {Layer} layer - * @param {string} path - * @private + * @param {Boolean|String|Function} val + * @return {Function} + * @api private */ -function matchLayer(layer, path) { - try { - return layer.match(path); - } catch (err) { - return err; +exports.compileETag = function(val) { + var fn; + + if (typeof val === 'function') { + return val; } -} -// merge params with parent params -function mergeParams(params, parent) { - if (typeof parent !== 'object' || !parent) { - return params; + switch (val) { + case true: + case 'weak': + fn = exports.wetag; + break; + case false: + break; + case 'strong': + fn = exports.etag; + break; + default: + throw new TypeError('unknown value for etag function: ' + val); } - // make copy of parent for base - var obj = mixin({}, parent); + return fn; +} - // simple non-numeric merging - if (!(0 in params) || !(0 in parent)) { - return mixin(obj, params); - } +/** + * Compile "query parser" value to function. + * + * @param {String|Function} val + * @return {Function} + * @api private + */ - var i = 0; - var o = 0; +exports.compileQueryParser = function compileQueryParser(val) { + var fn; - // determine numeric gaps - while (i in params) { - i++; + if (typeof val === 'function') { + return val; } - while (o in parent) { - o++; + switch (val) { + case true: + case 'simple': + fn = querystring.parse; + break; + case false: + fn = newObject; + break; + case 'extended': + fn = parseExtendedQueryString; + break; + default: + throw new TypeError('unknown value for query parser function: ' + val); } - // offset numeric indices in params before merge - for (i--; i >= 0; i--) { - params[i + o] = params[i]; + return fn; +} - // create holes for the merge when necessary - if (i < o) { - delete params[i]; - } +/** + * Compile "proxy trust" value to function. + * + * @param {Boolean|String|Number|Array|Function} val + * @return {Function} + * @api private + */ + +exports.compileTrust = function(val) { + if (typeof val === 'function') return val; + + if (val === true) { + // Support plain true/false + return function(){ return true }; } - return mixin(obj, params); + if (typeof val === 'number') { + // Support trusting hop count + return function(a, i){ return i < val }; + } + + if (typeof val === 'string') { + // Support comma-separated values + val = val.split(/ *, */); + } + + return proxyaddr.compile(val || []); } -// restore obj props after function -function restore(fn, obj) { - var props = new Array(arguments.length - 2); - var vals = new Array(arguments.length - 2); +/** + * Set the charset in a given Content-Type string. + * + * @param {String} type + * @param {String} charset + * @return {String} + * @api private + */ - for (var i = 0; i < props.length; i++) { - props[i] = arguments[i + 2]; - vals[i] = obj[props[i]]; +exports.setCharset = function setCharset(type, charset) { + if (!type || !charset) { + return type; } - return function () { - // restore vals - for (var i = 0; i < props.length; i++) { - obj[props[i]] = vals[i]; - } + // parse type + var parsed = contentType.parse(type); - return fn.apply(this, arguments); - }; -} + // set charset + parsed.parameters.charset = charset; -// send an OPTIONS response -function sendOptionsResponse(res, options, next) { - try { - var body = options.join(','); - res.set('Allow', body); - res.send(body); - } catch (err) { - next(err); + // format type + return contentType.format(parsed); +}; + +/** + * Create an ETag generator function, generating ETags with + * the given options. + * + * @param {object} options + * @return {function} + * @private + */ + +function createETagGenerator (options) { + return function generateETag (body, encoding) { + var buf = !Buffer.isBuffer(body) + ? Buffer.from(body, encoding) + : body + + return etag(buf, options) } } -// wrap a function -function wrap(old, fn) { - return function proxy() { - var args = new Array(arguments.length + 1); +/** + * Parse an extended query string with qs. + * + * @return {Object} + * @private + */ - args[0] = old; - for (var i = 0, len = arguments.length; i < len; i++) { - args[i + 1] = arguments[i]; - } +function parseExtendedQueryString(str) { + return qs.parse(str, { + allowPrototypes: true + }); +} - fn.apply(this, args); - }; +/** + * Return new empty object. + * + * @return {Object} + * @api private + */ + +function newObject() { + return {}; } /***/ }), -/***/ 25624: +/***/ 99209: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -41403,1782 +40310,1553 @@ function wrap(old, fn) { * @private */ -var pathRegexp = __nccwpck_require__(37819); -var debug = __nccwpck_require__(52529)('express:router:layer'); +var debug = __nccwpck_require__(52529)('express:view'); +var path = __nccwpck_require__(71017); +var fs = __nccwpck_require__(57147); /** * Module variables. * @private */ -var hasOwnProperty = Object.prototype.hasOwnProperty; +var dirname = path.dirname; +var basename = path.basename; +var extname = path.extname; +var join = path.join; +var resolve = path.resolve; /** * Module exports. * @public */ -module.exports = Layer; - -function Layer(path, options, fn) { - if (!(this instanceof Layer)) { - return new Layer(path, options, fn); - } - - debug('new %o', path) - var opts = options || {}; - - this.handle = fn; - this.name = fn.name || ''; - this.params = undefined; - this.path = undefined; - this.regexp = pathRegexp(path, this.keys = [], opts); - - // set fast path flags - this.regexp.fast_star = path === '*' - this.regexp.fast_slash = path === '/' && opts.end === false -} +module.exports = View; /** - * Handle the error for the layer. + * Initialize a new `View` with the given `name`. * - * @param {Error} error - * @param {Request} req - * @param {Response} res - * @param {function} next - * @api private + * Options: + * + * - `defaultEngine` the default template engine name + * - `engines` template engine require() cache + * - `root` root path for view lookup + * + * @param {string} name + * @param {object} options + * @public */ -Layer.prototype.handle_error = function handle_error(error, req, res, next) { - var fn = this.handle; +function View(name, options) { + var opts = options || {}; - if (fn.length !== 4) { - // not a standard error handler - return next(error); + this.defaultEngine = opts.defaultEngine; + this.ext = extname(name); + this.name = name; + this.root = opts.root; + + if (!this.ext && !this.defaultEngine) { + throw new Error('No default engine was specified and no extension was provided.'); } - try { - fn(error, req, res, next); - } catch (err) { - next(err); + var fileName = name; + + if (!this.ext) { + // get extension from default engine name + this.ext = this.defaultEngine[0] !== '.' + ? '.' + this.defaultEngine + : this.defaultEngine; + + fileName += this.ext; } -}; + + if (!opts.engines[this.ext]) { + // load engine + var mod = this.ext.substr(1) + debug('require "%s"', mod) + + // default engine export + var fn = require(mod).__express + + if (typeof fn !== 'function') { + throw new Error('Module "' + mod + '" does not provide a view engine.') + } + + opts.engines[this.ext] = fn + } + + // store loaded engine + this.engine = opts.engines[this.ext]; + + // lookup path + this.path = this.lookup(fileName); +} /** - * Handle the request for the layer. + * Lookup view by the given `name` * - * @param {Request} req - * @param {Response} res - * @param {function} next - * @api private + * @param {string} name + * @private */ -Layer.prototype.handle_request = function handle(req, res, next) { - var fn = this.handle; +View.prototype.lookup = function lookup(name) { + var path; + var roots = [].concat(this.root); - if (fn.length > 3) { - // not a standard request handler - return next(); - } + debug('lookup "%s"', name); - try { - fn(req, res, next); - } catch (err) { - next(err); + for (var i = 0; i < roots.length && !path; i++) { + var root = roots[i]; + + // resolve the path + var loc = resolve(root, name); + var dir = dirname(loc); + var file = basename(loc); + + // resolve the file + path = this.resolve(dir, file); } + + return path; }; /** - * Check if this route matches `path`, if so - * populate `.params`. + * Render with the given options. * - * @param {String} path - * @return {Boolean} - * @api private + * @param {object} options + * @param {function} callback + * @private */ -Layer.prototype.match = function match(path) { - var match +View.prototype.render = function render(options, callback) { + debug('render "%s"', this.path); + this.engine(this.path, options, callback); +}; - if (path != null) { - // fast path non-ending match for / (any path matches) - if (this.regexp.fast_slash) { - this.params = {} - this.path = '' - return true - } +/** + * Resolve the file within the given directory. + * + * @param {string} dir + * @param {string} file + * @private + */ - // fast path for * (everything matched in a param) - if (this.regexp.fast_star) { - this.params = {'0': decode_param(path)} - this.path = path - return true - } +View.prototype.resolve = function resolve(dir, file) { + var ext = this.ext; - // match the path - match = this.regexp.exec(path) - } + // . + var path = join(dir, file); + var stat = tryStat(path); - if (!match) { - this.params = undefined; - this.path = undefined; - return false; + if (stat && stat.isFile()) { + return path; } - // store values - this.params = {}; - this.path = match[0] - - var keys = this.keys; - var params = this.params; - - for (var i = 1; i < match.length; i++) { - var key = keys[i - 1]; - var prop = key.name; - var val = decode_param(match[i]) + // /index. + path = join(dir, basename(file, ext), 'index' + ext); + stat = tryStat(path); - if (val !== undefined || !(hasOwnProperty.call(params, prop))) { - params[prop] = val; - } + if (stat && stat.isFile()) { + return path; } - - return true; }; /** - * Decode param value. + * Return a stat, maybe. * - * @param {string} val - * @return {string} + * @param {string} path + * @return {fs.Stats} * @private */ -function decode_param(val) { - if (typeof val !== 'string' || val.length === 0) { - return val; - } +function tryStat(path) { + debug('stat "%s"', path); try { - return decodeURIComponent(val); - } catch (err) { - if (err instanceof URIError) { - err.message = 'Failed to decode param \'' + val + '\''; - err.status = err.statusCode = 400; - } - - throw err; + return fs.statSync(path); + } catch (e) { + return undefined; } } /***/ }), -/***/ 23699: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 36654: +/***/ ((module, exports, __nccwpck_require__) => { -"use strict"; -/*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2013 Roman Shtylman - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed +/** + * This is the web browser implementation of `debug()`. + * + * Expose `debug()` as the module. */ - +exports = module.exports = __nccwpck_require__(86991); +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = 'undefined' != typeof chrome + && 'undefined' != typeof chrome.storage + ? chrome.storage.local + : localstorage(); /** - * Module dependencies. - * @private + * Colors. */ -var debug = __nccwpck_require__(52529)('express:router:route'); -var flatten = __nccwpck_require__(62003); -var Layer = __nccwpck_require__(25624); -var methods = __nccwpck_require__(58752); +exports.colors = [ + 'lightseagreen', + 'forestgreen', + 'goldenrod', + 'dodgerblue', + 'darkorchid', + 'crimson' +]; /** - * Module variables. - * @private + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. + * + * TODO: add a `localStorage` variable to explicitly enable/disable colors */ -var slice = Array.prototype.slice; -var toString = Object.prototype.toString; +function useColors() { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') { + return true; + } + + // is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || + // is firebug? http://stackoverflow.com/a/398120/376773 + (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || + // is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || + // double check webkit in userAgent just in case we are in a worker + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); +} /** - * Module exports. - * @public + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. */ -module.exports = Route; +exports.formatters.j = function(v) { + try { + return JSON.stringify(v); + } catch (err) { + return '[UnexpectedJSONParseError]: ' + err.message; + } +}; + /** - * Initialize `Route` with the given `path`, + * Colorize log arguments if enabled. * - * @param {String} path - * @public + * @api public */ -function Route(path) { - this.path = path; - this.stack = []; +function formatArgs(args) { + var useColors = this.useColors; - debug('new %o', path) + args[0] = (useColors ? '%c' : '') + + this.namespace + + (useColors ? ' %c' : ' ') + + args[0] + + (useColors ? '%c ' : ' ') + + '+' + exports.humanize(this.diff); - // route handlers for various http methods - this.methods = {}; + if (!useColors) return; + + var c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit') + + // the final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + var index = 0; + var lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, function(match) { + if ('%%' === match) return; + index++; + if ('%c' === match) { + // we only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); + + args.splice(lastC, 0, c); } /** - * Determine if the route handles a given method. - * @private + * Invokes `console.log()` when available. + * No-op when `console.log` is not a "function". + * + * @api public */ -Route.prototype._handles_method = function _handles_method(method) { - if (this.methods._all) { - return true; - } - - var name = method.toLowerCase(); +function log() { + // this hackery is required for IE8/9, where + // the `console.log` function doesn't have 'apply' + return 'object' === typeof console + && console.log + && Function.prototype.apply.call(console.log, console, arguments); +} - if (name === 'head' && !this.methods['head']) { - name = 'get'; - } +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ - return Boolean(this.methods[name]); -}; +function save(namespaces) { + try { + if (null == namespaces) { + exports.storage.removeItem('debug'); + } else { + exports.storage.debug = namespaces; + } + } catch(e) {} +} /** - * @return {Array} supported HTTP methods - * @private + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private */ -Route.prototype._options = function _options() { - var methods = Object.keys(this.methods); +function load() { + var r; + try { + r = exports.storage.debug; + } catch(e) {} - // append automatic head - if (this.methods.get && !this.methods.head) { - methods.push('head'); + // If debug isn't set in LS, and we're in Electron, try to load $DEBUG + if (!r && typeof process !== 'undefined' && 'env' in process) { + r = process.env.DEBUG; } - for (var i = 0; i < methods.length; i++) { - // make upper case - methods[i] = methods[i].toUpperCase(); - } + return r; +} - return methods; -}; +/** + * Enable namespaces listed in `localStorage.debug` initially. + */ + +exports.enable(load()); /** - * dispatch req, res into this route - * @private + * Localstorage attempts to return the localstorage. + * + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. + * + * @return {LocalStorage} + * @api private */ -Route.prototype.dispatch = function dispatch(req, res, done) { - var idx = 0; - var stack = this.stack; - if (stack.length === 0) { - return done(); - } +function localstorage() { + try { + return window.localStorage; + } catch (e) {} +} - var method = req.method.toLowerCase(); - if (method === 'head' && !this.methods['head']) { - method = 'get'; - } - req.route = this; +/***/ }), - next(); +/***/ 86991: +/***/ ((module, exports, __nccwpck_require__) => { - function next(err) { - // signal to exit route - if (err && err === 'route') { - return done(); - } - // signal to exit router - if (err && err === 'router') { - return done(err) - } +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + * + * Expose `debug()` as the module. + */ - var layer = stack[idx++]; - if (!layer) { - return done(err); - } +exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; +exports.coerce = coerce; +exports.disable = disable; +exports.enable = enable; +exports.enabled = enabled; +exports.humanize = __nccwpck_require__(27025); - if (layer.method && layer.method !== method) { - return next(err); - } +/** + * The currently active debug mode names, and names to skip. + */ - if (err) { - layer.handle_error(err, req, res, next); - } else { - layer.handle_request(req, res, next); - } - } -}; +exports.names = []; +exports.skips = []; /** - * Add a handler for all HTTP verbs to this route. - * - * Behaves just like middleware and can respond or call `next` - * to continue processing. - * - * You can use multiple `.all` call to add multiple handlers. - * - * function check_something(req, res, next){ - * next(); - * }; - * - * function validate_user(req, res, next){ - * next(); - * }; - * - * route - * .all(validate_user) - * .all(check_something) - * .get(function(req, res, next){ - * res.send('hello world'); - * }); + * Map of special "%n" handling functions, for the debug "format" argument. * - * @param {function} handler - * @return {Route} for chaining - * @api public + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". */ -Route.prototype.all = function all() { - var handles = flatten(slice.call(arguments)); +exports.formatters = {}; - for (var i = 0; i < handles.length; i++) { - var handle = handles[i]; +/** + * Previous log timestamp. + */ - if (typeof handle !== 'function') { - var type = toString.call(handle); - var msg = 'Route.all() requires a callback function but got a ' + type - throw new TypeError(msg); - } +var prevTime; - var layer = Layer('/', {}, handle); - layer.method = undefined; +/** + * Select a color. + * @param {String} namespace + * @return {Number} + * @api private + */ - this.methods._all = true; - this.stack.push(layer); - } +function selectColor(namespace) { + var hash = 0, i; - return this; -}; + for (i in namespace) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } -methods.forEach(function(method){ - Route.prototype[method] = function(){ - var handles = flatten(slice.call(arguments)); + return exports.colors[Math.abs(hash) % exports.colors.length]; +} - for (var i = 0; i < handles.length; i++) { - var handle = handles[i]; +/** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ - if (typeof handle !== 'function') { - var type = toString.call(handle); - var msg = 'Route.' + method + '() requires a callback function but got a ' + type - throw new Error(msg); - } +function createDebug(namespace) { - debug('%s %o', method, this.path) + function debug() { + // disabled? + if (!debug.enabled) return; - var layer = Layer('/', {}, handle); - layer.method = method; + var self = debug; - this.methods[method] = true; - this.stack.push(layer); + // set `diff` timestamp + var curr = +new Date(); + var ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; + + // turn the `arguments` into a proper Array + var args = new Array(arguments.length); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i]; } - return this; - }; -}); + args[0] = exports.coerce(args[0]); + if ('string' !== typeof args[0]) { + // anything else let's inspect with %O + args.unshift('%O'); + } -/***/ }), + // apply any `formatters` transformations + var index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) { + // if we encounter an escaped % then don't increase the array index + if (match === '%%') return match; + index++; + var formatter = exports.formatters[format]; + if ('function' === typeof formatter) { + var val = args[index]; + match = formatter.call(self, val); -/***/ 53561: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + // now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); -"use strict"; -/*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ + // apply env-specific formatting (colors, etc.) + exports.formatArgs.call(self, args); + var logFn = debug.log || exports.log || console.log.bind(console); + logFn.apply(self, args); + } + debug.namespace = namespace; + debug.enabled = exports.enabled(namespace); + debug.useColors = exports.useColors(); + debug.color = selectColor(namespace); -/** - * Module dependencies. - * @api private - */ + // env-specific initialization logic for debug instances + if ('function' === typeof exports.init) { + exports.init(debug); + } -var Buffer = (__nccwpck_require__(21867).Buffer) -var contentDisposition = __nccwpck_require__(53921); -var contentType = __nccwpck_require__(99915); -var deprecate = __nccwpck_require__(18883)('express'); -var flatten = __nccwpck_require__(62003); -var mime = (__nccwpck_require__(95287).mime); -var etag = __nccwpck_require__(69972); -var proxyaddr = __nccwpck_require__(80140); -var qs = __nccwpck_require__(22760); -var querystring = __nccwpck_require__(63477); + return debug; +} /** - * Return strong ETag for `body`. + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. * - * @param {String|Buffer} body - * @param {String} [encoding] - * @return {String} - * @api private + * @param {String} namespaces + * @api public */ -exports.etag = createETagGenerator({ weak: false }) +function enable(namespaces) { + exports.save(namespaces); + + exports.names = []; + exports.skips = []; + + var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + var len = split.length; + + for (var i = 0; i < len; i++) { + if (!split[i]) continue; // ignore empty strings + namespaces = split[i].replace(/\*/g, '.*?'); + if (namespaces[0] === '-') { + exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); + } else { + exports.names.push(new RegExp('^' + namespaces + '$')); + } + } +} /** - * Return weak ETag for `body`. + * Disable debug output. * - * @param {String|Buffer} body - * @param {String} [encoding] - * @return {String} - * @api private + * @api public */ -exports.wetag = createETagGenerator({ weak: true }) +function disable() { + exports.enable(''); +} /** - * Check if `path` looks absolute. + * Returns true if the given mode name is enabled, false otherwise. * - * @param {String} path + * @param {String} name * @return {Boolean} - * @api private + * @api public */ -exports.isAbsolute = function(path){ - if ('/' === path[0]) return true; - if (':' === path[1] && ('\\' === path[2] || '/' === path[2])) return true; // Windows device path - if ('\\\\' === path.substring(0, 2)) return true; // Microsoft Azure absolute path -}; +function enabled(name) { + var i, len; + for (i = 0, len = exports.skips.length; i < len; i++) { + if (exports.skips[i].test(name)) { + return false; + } + } + for (i = 0, len = exports.names.length; i < len; i++) { + if (exports.names[i].test(name)) { + return true; + } + } + return false; +} /** - * Flatten the given `arr`. + * Coerce `val`. * - * @param {Array} arr - * @return {Array} + * @param {Mixed} val + * @return {Mixed} * @api private */ -exports.flatten = deprecate.function(flatten, - 'utils.flatten: use array-flatten npm module instead'); +function coerce(val) { + if (val instanceof Error) return val.stack || val.message; + return val; +} -/** - * Normalize the given `type`, for example "html" becomes "text/html". - * - * @param {String} type - * @return {Object} - * @api private - */ -exports.normalizeType = function(type){ - return ~type.indexOf('/') - ? acceptParams(type) - : { value: mime.lookup(type), params: {} }; -}; +/***/ }), + +/***/ 52529: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { /** - * Normalize `types`, for example "html" becomes "text/html". - * - * @param {Array} types - * @return {Array} - * @api private + * Detect Electron renderer process, which is node, but we should + * treat as a browser. */ -exports.normalizeTypes = function(types){ - var ret = []; +if (typeof process !== 'undefined' && process.type === 'renderer') { + module.exports = __nccwpck_require__(36654); +} else { + module.exports = __nccwpck_require__(25696); +} - for (var i = 0; i < types.length; ++i) { - ret.push(exports.normalizeType(types[i])); - } - return ret; -}; +/***/ }), + +/***/ 25696: +/***/ ((module, exports, __nccwpck_require__) => { /** - * Generate Content-Disposition header appropriate for the filename. - * non-ascii filenames are urlencoded and a filename* parameter is added - * - * @param {String} filename - * @return {String} - * @api private + * Module dependencies. */ -exports.contentDisposition = deprecate.function(contentDisposition, - 'utils.contentDisposition: use content-disposition npm module instead'); +var tty = __nccwpck_require__(76224); +var util = __nccwpck_require__(73837); /** - * Parse accept params `str` returning an - * object with `.value`, `.quality` and `.params`. - * also includes `.originalIndex` for stable sorting + * This is the Node.js implementation of `debug()`. * - * @param {String} str - * @return {Object} - * @api private + * Expose `debug()` as the module. */ -function acceptParams(str, index) { - var parts = str.split(/ *; */); - var ret = { value: parts[0], quality: 1, params: {}, originalIndex: index }; - - for (var i = 1; i < parts.length; ++i) { - var pms = parts[i].split(/ *= */); - if ('q' === pms[0]) { - ret.quality = parseFloat(pms[1]); - } else { - ret.params[pms[0]] = pms[1]; - } - } - - return ret; -} +exports = module.exports = __nccwpck_require__(86991); +exports.init = init; +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; /** - * Compile "etag" value to function. - * - * @param {Boolean|String|Function} val - * @return {Function} - * @api private + * Colors. */ -exports.compileETag = function(val) { - var fn; - - if (typeof val === 'function') { - return val; - } - - switch (val) { - case true: - case 'weak': - fn = exports.wetag; - break; - case false: - break; - case 'strong': - fn = exports.etag; - break; - default: - throw new TypeError('unknown value for etag function: ' + val); - } - - return fn; -} +exports.colors = [6, 2, 3, 4, 5, 1]; /** - * Compile "query parser" value to function. + * Build up the default `inspectOpts` object from the environment variables. * - * @param {String|Function} val - * @return {Function} - * @api private + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js */ -exports.compileQueryParser = function compileQueryParser(val) { - var fn; - - if (typeof val === 'function') { - return val; - } +exports.inspectOpts = Object.keys(process.env).filter(function (key) { + return /^debug_/i.test(key); +}).reduce(function (obj, key) { + // camel-case + var prop = key + .substring(6) + .toLowerCase() + .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() }); - switch (val) { - case true: - case 'simple': - fn = querystring.parse; - break; - case false: - fn = newObject; - break; - case 'extended': - fn = parseExtendedQueryString; - break; - default: - throw new TypeError('unknown value for query parser function: ' + val); - } + // coerce string value into JS value + var val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) val = true; + else if (/^(no|off|false|disabled)$/i.test(val)) val = false; + else if (val === 'null') val = null; + else val = Number(val); - return fn; -} + obj[prop] = val; + return obj; +}, {}); /** - * Compile "proxy trust" value to function. + * The file descriptor to write the `debug()` calls to. + * Set the `DEBUG_FD` env variable to override with another value. i.e.: * - * @param {Boolean|String|Number|Array|Function} val - * @return {Function} - * @api private + * $ DEBUG_FD=3 node script.js 3>debug.log */ -exports.compileTrust = function(val) { - if (typeof val === 'function') return val; +var fd = parseInt(process.env.DEBUG_FD, 10) || 2; - if (val === true) { - // Support plain true/false - return function(){ return true }; - } +if (1 !== fd && 2 !== fd) { + util.deprecate(function(){}, 'except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)')() +} - if (typeof val === 'number') { - // Support trusting hop count - return function(a, i){ return i < val }; - } +var stream = 1 === fd ? process.stdout : + 2 === fd ? process.stderr : + createWritableStdioStream(fd); - if (typeof val === 'string') { - // Support comma-separated values - val = val.split(/ *, */); - } +/** + * Is stdout a TTY? Colored output is enabled when `true`. + */ - return proxyaddr.compile(val || []); +function useColors() { + return 'colors' in exports.inspectOpts + ? Boolean(exports.inspectOpts.colors) + : tty.isatty(fd); } /** - * Set the charset in a given Content-Type string. - * - * @param {String} type - * @param {String} charset - * @return {String} - * @api private + * Map %o to `util.inspect()`, all on a single line. */ -exports.setCharset = function setCharset(type, charset) { - if (!type || !charset) { - return type; - } - - // parse type - var parsed = contentType.parse(type); +exports.formatters.o = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts) + .split('\n').map(function(str) { + return str.trim() + }).join(' '); +}; - // set charset - parsed.parameters.charset = charset; +/** + * Map %o to `util.inspect()`, allowing multiple lines if needed. + */ - // format type - return contentType.format(parsed); +exports.formatters.O = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); }; /** - * Create an ETag generator function, generating ETags with - * the given options. + * Adds ANSI color escape codes if enabled. * - * @param {object} options - * @return {function} - * @private + * @api public */ -function createETagGenerator (options) { - return function generateETag (body, encoding) { - var buf = !Buffer.isBuffer(body) - ? Buffer.from(body, encoding) - : body +function formatArgs(args) { + var name = this.namespace; + var useColors = this.useColors; - return etag(buf, options) + if (useColors) { + var c = this.color; + var prefix = ' \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m'; + + args[0] = prefix + args[0].split('\n').join('\n' + prefix); + args.push('\u001b[3' + c + 'm+' + exports.humanize(this.diff) + '\u001b[0m'); + } else { + args[0] = new Date().toUTCString() + + ' ' + name + ' ' + args[0]; } } /** - * Parse an extended query string with qs. - * - * @return {Object} - * @private + * Invokes `util.format()` with the specified arguments and writes to `stream`. */ -function parseExtendedQueryString(str) { - return qs.parse(str, { - allowPrototypes: true - }); +function log() { + return stream.write(util.format.apply(util, arguments) + '\n'); } /** - * Return new empty object. + * Save `namespaces`. * - * @return {Object} + * @param {String} namespaces * @api private */ -function newObject() { - return {}; +function save(namespaces) { + if (null == namespaces) { + // If you set a process.env field to null or undefined, it gets cast to the + // string 'null' or 'undefined'. Just delete instead. + delete process.env.DEBUG; + } else { + process.env.DEBUG = namespaces; + } } - -/***/ }), - -/***/ 99209: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -/*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2013 Roman Shtylman - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ - - - /** - * Module dependencies. - * @private + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private */ -var debug = __nccwpck_require__(52529)('express:view'); -var path = __nccwpck_require__(71017); -var fs = __nccwpck_require__(57147); +function load() { + return process.env.DEBUG; +} /** - * Module variables. - * @private + * Copied from `node/src/node.js`. + * + * XXX: It's lame that node doesn't expose this API out-of-the-box. It also + * relies on the undocumented `tty_wrap.guessHandleType()` which is also lame. */ -var dirname = path.dirname; -var basename = path.basename; -var extname = path.extname; -var join = path.join; -var resolve = path.resolve; +function createWritableStdioStream (fd) { + var stream; + var tty_wrap = process.binding('tty_wrap'); -/** - * Module exports. - * @public - */ + // Note stream._type is used for test-module-load-list.js -module.exports = View; + switch (tty_wrap.guessHandleType(fd)) { + case 'TTY': + stream = new tty.WriteStream(fd); + stream._type = 'tty'; -/** - * Initialize a new `View` with the given `name`. - * - * Options: - * - * - `defaultEngine` the default template engine name - * - `engines` template engine require() cache - * - `root` root path for view lookup - * - * @param {string} name - * @param {object} options - * @public - */ - -function View(name, options) { - var opts = options || {}; + // Hack to have stream not keep the event loop alive. + // See https://github.com/joyent/node/issues/1726 + if (stream._handle && stream._handle.unref) { + stream._handle.unref(); + } + break; - this.defaultEngine = opts.defaultEngine; - this.ext = extname(name); - this.name = name; - this.root = opts.root; + case 'FILE': + var fs = __nccwpck_require__(57147); + stream = new fs.SyncWriteStream(fd, { autoClose: false }); + stream._type = 'fs'; + break; - if (!this.ext && !this.defaultEngine) { - throw new Error('No default engine was specified and no extension was provided.'); - } + case 'PIPE': + case 'TCP': + var net = __nccwpck_require__(41808); + stream = new net.Socket({ + fd: fd, + readable: false, + writable: true + }); - var fileName = name; + // FIXME Should probably have an option in net.Socket to create a + // stream from an existing fd which is writable only. But for now + // we'll just add this hack and set the `readable` member to false. + // Test: ./node test/fixtures/echo.js < /etc/passwd + stream.readable = false; + stream.read = null; + stream._type = 'pipe'; - if (!this.ext) { - // get extension from default engine name - this.ext = this.defaultEngine[0] !== '.' - ? '.' + this.defaultEngine - : this.defaultEngine; + // FIXME Hack to have stream not keep the event loop alive. + // See https://github.com/joyent/node/issues/1726 + if (stream._handle && stream._handle.unref) { + stream._handle.unref(); + } + break; - fileName += this.ext; + default: + // Probably an error on in uv_guess_handle() + throw new Error('Implement me. Unknown stream file type!'); } - if (!opts.engines[this.ext]) { - // load engine - var mod = this.ext.substr(1) - debug('require "%s"', mod) - - // default engine export - var fn = require(mod).__express - - if (typeof fn !== 'function') { - throw new Error('Module "' + mod + '" does not provide a view engine.') - } - - opts.engines[this.ext] = fn - } + // For supporting legacy API we put the FD here. + stream.fd = fd; - // store loaded engine - this.engine = opts.engines[this.ext]; + stream._isStdio = true; - // lookup path - this.path = this.lookup(fileName); + return stream; } /** - * Lookup view by the given `name` + * Init logic for `debug` instances. * - * @param {string} name - * @private + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. */ -View.prototype.lookup = function lookup(name) { - var path; - var roots = [].concat(this.root); +function init (debug) { + debug.inspectOpts = {}; - debug('lookup "%s"', name); + var keys = Object.keys(exports.inspectOpts); + for (var i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } +} - for (var i = 0; i < roots.length && !path; i++) { - var root = roots[i]; +/** + * Enable namespaces listed in `process.env.DEBUG` initially. + */ - // resolve the path - var loc = resolve(root, name); - var dir = dirname(loc); - var file = basename(loc); +exports.enable(load()); - // resolve the file - path = this.resolve(dir, file); - } - return path; -}; +/***/ }), + +/***/ 27025: +/***/ ((module) => { /** - * Render with the given options. - * - * @param {object} options - * @param {function} callback - * @private + * Helpers. */ -View.prototype.render = function render(options, callback) { - debug('render "%s"', this.path); - this.engine(this.path, options, callback); -}; +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var y = d * 365.25; /** - * Resolve the file within the given directory. + * Parse or format the given `val`. * - * @param {string} dir - * @param {string} file - * @private + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public */ -View.prototype.resolve = function resolve(dir, file) { - var ext = this.ext; - - // . - var path = join(dir, file); - var stat = tryStat(path); - - if (stat && stat.isFile()) { - return path; - } - - // /index. - path = join(dir, basename(file, ext), 'index' + ext); - stat = tryStat(path); - - if (stat && stat.isFile()) { - return path; +module.exports = function(val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isNaN(val) === false) { + return options.long ? fmtLong(val) : fmtShort(val); } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); }; /** - * Return a stat, maybe. + * Parse the given `str` and return milliseconds. * - * @param {string} path - * @return {fs.Stats} - * @private + * @param {String} str + * @return {Number} + * @api private */ -function tryStat(path) { - debug('stat "%s"', path); - - try { - return fs.statSync(path); - } catch (e) { - return undefined; +function parse(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; } } - -/***/ }), - -/***/ 36654: -/***/ ((module, exports, __nccwpck_require__) => { - /** - * This is the web browser implementation of `debug()`. + * Short format for `ms`. * - * Expose `debug()` as the module. - */ - -exports = module.exports = __nccwpck_require__(86991); -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.storage = 'undefined' != typeof chrome - && 'undefined' != typeof chrome.storage - ? chrome.storage.local - : localstorage(); - -/** - * Colors. + * @param {Number} ms + * @return {String} + * @api private */ -exports.colors = [ - 'lightseagreen', - 'forestgreen', - 'goldenrod', - 'dodgerblue', - 'darkorchid', - 'crimson' -]; +function fmtShort(ms) { + if (ms >= d) { + return Math.round(ms / d) + 'd'; + } + if (ms >= h) { + return Math.round(ms / h) + 'h'; + } + if (ms >= m) { + return Math.round(ms / m) + 'm'; + } + if (ms >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; +} /** - * Currently only WebKit-based Web Inspectors, Firefox >= v31, - * and the Firebug extension (any Firefox version) are known - * to support "%c" CSS customizations. + * Long format for `ms`. * - * TODO: add a `localStorage` variable to explicitly enable/disable colors + * @param {Number} ms + * @return {String} + * @api private */ -function useColors() { - // NB: In an Electron preload script, document will be defined but not fully - // initialized. Since we know we're in Chrome, we'll just detect this case - // explicitly - if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') { - return true; - } - - // is webkit? http://stackoverflow.com/a/16459606/376773 - // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 - return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || - // is firebug? http://stackoverflow.com/a/398120/376773 - (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || - // is firefox >= v31? - // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || - // double check webkit in userAgent just in case we are in a worker - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); +function fmtLong(ms) { + return plural(ms, d, 'day') || + plural(ms, h, 'hour') || + plural(ms, m, 'minute') || + plural(ms, s, 'second') || + ms + ' ms'; } /** - * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + * Pluralization helper. */ -exports.formatters.j = function(v) { - try { - return JSON.stringify(v); - } catch (err) { - return '[UnexpectedJSONParseError]: ' + err.message; +function plural(ms, n, name) { + if (ms < n) { + return; } -}; - - -/** - * Colorize log arguments if enabled. - * - * @api public - */ + if (ms < n * 1.5) { + return Math.floor(ms / n) + ' ' + name; + } + return Math.ceil(ms / n) + ' ' + name + 's'; +} -function formatArgs(args) { - var useColors = this.useColors; - args[0] = (useColors ? '%c' : '') - + this.namespace - + (useColors ? ' %c' : ' ') - + args[0] - + (useColors ? '%c ' : ' ') - + '+' + exports.humanize(this.diff); +/***/ }), - if (!useColors) return; +/***/ 41894: +/***/ ((module, exports, __nccwpck_require__) => { - var c = 'color: ' + this.color; - args.splice(1, 0, c, 'color: inherit') +/*! safe-buffer. MIT License. Feross Aboukhadijeh */ +/* eslint-disable node/no-deprecated-api */ +var buffer = __nccwpck_require__(14300) +var Buffer = buffer.Buffer - // the final "%c" is somewhat tricky, because there could be other - // arguments passed either before or after the %c, so we need to - // figure out the correct index to insert the CSS into - var index = 0; - var lastC = 0; - args[0].replace(/%[a-zA-Z%]/g, function(match) { - if ('%%' === match) return; - index++; - if ('%c' === match) { - // we only are interested in the *last* %c - // (the user may have provided their own) - lastC = index; - } - }); +// alternative to using Object.keys for old browsers +function copyProps (src, dst) { + for (var key in src) { + dst[key] = src[key] + } +} +if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer +} else { + // Copy properties from require('buffer') + copyProps(buffer, exports) + exports.Buffer = SafeBuffer +} - args.splice(lastC, 0, c); +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) } -/** - * Invokes `console.log()` when available. - * No-op when `console.log` is not a "function". - * - * @api public - */ +SafeBuffer.prototype = Object.create(Buffer.prototype) -function log() { - // this hackery is required for IE8/9, where - // the `console.log` function doesn't have 'apply' - return 'object' === typeof console - && console.log - && Function.prototype.apply.call(console.log, console, arguments); -} +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer) -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') + } + return Buffer(arg, encodingOrOffset, length) +} -function save(namespaces) { - try { - if (null == namespaces) { - exports.storage.removeItem('debug'); +SafeBuffer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + var buf = Buffer(size) + if (fill !== undefined) { + if (typeof encoding === 'string') { + buf.fill(fill, encoding) } else { - exports.storage.debug = namespaces; + buf.fill(fill) } - } catch(e) {} + } else { + buf.fill(0) + } + return buf } -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ - -function load() { - var r; - try { - r = exports.storage.debug; - } catch(e) {} - - // If debug isn't set in LS, and we're in Electron, try to load $DEBUG - if (!r && typeof process !== 'undefined' && 'env' in process) { - r = process.env.DEBUG; +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') } + return Buffer(size) +} - return r; +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) } -/** - * Enable namespaces listed in `localStorage.debug` initially. - */ -exports.enable(load()); +/***/ }), -/** - * Localstorage attempts to return the localstorage. - * - * This is necessary because safari throws - * when a user disables cookies/localstorage - * and you attempt to access it. - * - * @return {LocalStorage} - * @api private - */ +/***/ 24826: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -function localstorage() { - try { - return window.localStorage; - } catch (e) {} -} +"use strict"; -/***/ }), +const validator = __nccwpck_require__(74174) +const parse = __nccwpck_require__(96214) +const redactor = __nccwpck_require__(17333) +const restorer = __nccwpck_require__(98806) +const { groupRedact, nestedRedact } = __nccwpck_require__(54865) +const state = __nccwpck_require__(41012) +const rx = __nccwpck_require__(9158) +const validate = validator() +const noop = (o) => o +noop.restore = noop -/***/ 86991: -/***/ ((module, exports, __nccwpck_require__) => { +const DEFAULT_CENSOR = '[REDACTED]' +fastRedact.rx = rx +fastRedact.validator = validator +module.exports = fastRedact -/** - * This is the common logic for both the Node.js and web browser - * implementations of `debug()`. - * - * Expose `debug()` as the module. - */ - -exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; -exports.coerce = coerce; -exports.disable = disable; -exports.enable = enable; -exports.enabled = enabled; -exports.humanize = __nccwpck_require__(27025); - -/** - * The currently active debug mode names, and names to skip. - */ - -exports.names = []; -exports.skips = []; - -/** - * Map of special "%n" handling functions, for the debug "format" argument. - * - * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". - */ - -exports.formatters = {}; - -/** - * Previous log timestamp. - */ - -var prevTime; - -/** - * Select a color. - * @param {String} namespace - * @return {Number} - * @api private - */ - -function selectColor(namespace) { - var hash = 0, i; - - for (i in namespace) { - hash = ((hash << 5) - hash) + namespace.charCodeAt(i); - hash |= 0; // Convert to 32bit integer +function fastRedact (opts = {}) { + const paths = Array.from(new Set(opts.paths || [])) + const serialize = 'serialize' in opts ? ( + opts.serialize === false ? opts.serialize + : (typeof opts.serialize === 'function' ? opts.serialize : JSON.stringify) + ) : JSON.stringify + const remove = opts.remove + if (remove === true && serialize !== JSON.stringify) { + throw Error('fast-redact – remove option may only be set when serializer is JSON.stringify') } + const censor = remove === true + ? undefined + : 'censor' in opts ? opts.censor : DEFAULT_CENSOR - return exports.colors[Math.abs(hash) % exports.colors.length]; -} - -/** - * Create a debugger with the given `namespace`. - * - * @param {String} namespace - * @return {Function} - * @api public - */ - -function createDebug(namespace) { + const isCensorFct = typeof censor === 'function' + const censorFctTakesPath = isCensorFct && censor.length > 1 - function debug() { - // disabled? - if (!debug.enabled) return; + if (paths.length === 0) return serialize || noop - var self = debug; + validate({ paths, serialize, censor }) - // set `diff` timestamp - var curr = +new Date(); - var ms = curr - (prevTime || curr); - self.diff = ms; - self.prev = prevTime; - self.curr = curr; - prevTime = curr; + const { wildcards, wcLen, secret } = parse({ paths, censor }) - // turn the `arguments` into a proper Array - var args = new Array(arguments.length); - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i]; - } + const compileRestore = restorer({ secret, wcLen }) + const strict = 'strict' in opts ? opts.strict : true - args[0] = exports.coerce(args[0]); + return redactor({ secret, wcLen, serialize, strict, isCensorFct, censorFctTakesPath }, state({ + secret, + censor, + compileRestore, + serialize, + groupRedact, + nestedRedact, + wildcards, + wcLen + })) +} - if ('string' !== typeof args[0]) { - // anything else let's inspect with %O - args.unshift('%O'); - } - // apply any `formatters` transformations - var index = 0; - args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) { - // if we encounter an escaped % then don't increase the array index - if (match === '%%') return match; - index++; - var formatter = exports.formatters[format]; - if ('function' === typeof formatter) { - var val = args[index]; - match = formatter.call(self, val); +/***/ }), - // now we need to remove `args[index]` since it's inlined in the `format` - args.splice(index, 1); - index--; - } - return match; - }); +/***/ 54865: +/***/ ((module) => { - // apply env-specific formatting (colors, etc.) - exports.formatArgs.call(self, args); +"use strict"; - var logFn = debug.log || exports.log || console.log.bind(console); - logFn.apply(self, args); - } - debug.namespace = namespace; - debug.enabled = exports.enabled(namespace); - debug.useColors = exports.useColors(); - debug.color = selectColor(namespace); +module.exports = { + groupRedact, + groupRestore, + nestedRedact, + nestedRestore +} - // env-specific initialization logic for debug instances - if ('function' === typeof exports.init) { - exports.init(debug); +function groupRestore ({ keys, values, target }) { + if (target == null) return + const length = keys.length + for (var i = 0; i < length; i++) { + const k = keys[i] + target[k] = values[i] } - - return debug; } -/** - * Enables a debug mode by namespaces. This can include modes - * separated by a colon and wildcards. - * - * @param {String} namespaces - * @api public - */ - -function enable(namespaces) { - exports.save(namespaces); - - exports.names = []; - exports.skips = []; +function groupRedact (o, path, censor, isCensorFct, censorFctTakesPath) { + const target = get(o, path) + if (target == null) return { keys: null, values: null, target: null, flat: true } + const keys = Object.keys(target) + const keysLength = keys.length + const pathLength = path.length + const pathWithKey = censorFctTakesPath ? [...path] : undefined + const values = new Array(keysLength) - var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); - var len = split.length; + for (var i = 0; i < keysLength; i++) { + const key = keys[i] + values[i] = target[key] - for (var i = 0; i < len; i++) { - if (!split[i]) continue; // ignore empty strings - namespaces = split[i].replace(/\*/g, '.*?'); - if (namespaces[0] === '-') { - exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); + if (censorFctTakesPath) { + pathWithKey[pathLength] = key + target[key] = censor(target[key], pathWithKey) + } else if (isCensorFct) { + target[key] = censor(target[key]) } else { - exports.names.push(new RegExp('^' + namespaces + '$')); + target[key] = censor } } + return { keys, values, target, flat: true } } -/** - * Disable debug output. - * - * @api public - */ - -function disable() { - exports.enable(''); +function nestedRestore (arr) { + const length = arr.length + for (var i = 0; i < length; i++) { + const { key, target, value } = arr[i] + target[key] = value + } } -/** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ +function nestedRedact (store, o, path, ns, censor, isCensorFct, censorFctTakesPath) { + const target = get(o, path) + if (target == null) return + const keys = Object.keys(target) + const keysLength = keys.length + for (var i = 0; i < keysLength; i++) { + const key = keys[i] + const { value, parent, exists } = + specialSet(target, key, path, ns, censor, isCensorFct, censorFctTakesPath) -function enabled(name) { - var i, len; - for (i = 0, len = exports.skips.length; i < len; i++) { - if (exports.skips[i].test(name)) { - return false; + if (exists === true && parent !== null) { + store.push({ key: ns[ns.length - 1], target: parent, value }) } } - for (i = 0, len = exports.names.length; i < len; i++) { - if (exports.names[i].test(name)) { - return true; + return store +} + +function has (obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop) +} + +function specialSet (o, k, path, afterPath, censor, isCensorFct, censorFctTakesPath) { + const afterPathLen = afterPath.length + const lastPathIndex = afterPathLen - 1 + const originalKey = k + var i = -1 + var n + var nv + var ov + var oov = null + var exists = true + ov = n = o[k] + if (typeof n !== 'object') return { value: null, parent: null, exists } + while (n != null && ++i < afterPathLen) { + k = afterPath[i] + oov = ov + if (!(k in n)) { + exists = false + break } + ov = n[k] + nv = (i !== lastPathIndex) + ? ov + : (isCensorFct + ? (censorFctTakesPath ? censor(ov, [...path, originalKey, ...afterPath]) : censor(ov)) + : censor) + n[k] = (has(n, k) && nv === ov) || (nv === undefined && censor !== undefined) ? n[k] : nv + n = n[k] + if (typeof n !== 'object') break } - return false; + return { value: ov, parent: oov, exists } } -/** - * Coerce `val`. - * - * @param {Mixed} val - * @return {Mixed} - * @api private - */ - -function coerce(val) { - if (val instanceof Error) return val.stack || val.message; - return val; +function get (o, p) { + var i = -1 + var l = p.length + var n = o + while (n != null && ++i < l) { + n = n[p[i]] + } + return n } /***/ }), -/***/ 52529: +/***/ 96214: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * Detect Electron renderer process, which is node, but we should - * treat as a browser. - */ +"use strict"; -if (typeof process !== 'undefined' && process.type === 'renderer') { - module.exports = __nccwpck_require__(36654); -} else { - module.exports = __nccwpck_require__(25696); -} +const rx = __nccwpck_require__(9158) -/***/ }), +module.exports = parse -/***/ 25696: -/***/ ((module, exports, __nccwpck_require__) => { +function parse ({ paths }) { + const wildcards = [] + var wcLen = 0 + const secret = paths.reduce(function (o, strPath, ix) { + var path = strPath.match(rx).map((p) => p.replace(/'|"|`/g, '')) + const leadingBracket = strPath[0] === '[' + path = path.map((p) => { + if (p[0] === '[') return p.substr(1, p.length - 2) + else return p + }) + const star = path.indexOf('*') + if (star > -1) { + const before = path.slice(0, star) + const beforeStr = before.join('.') + const after = path.slice(star + 1, path.length) + if (after.indexOf('*') > -1) throw Error('fast-redact – Only one wildcard per path is supported') + const nested = after.length > 0 + wcLen++ + wildcards.push({ + before, + beforeStr, + after, + nested + }) + } else { + o[strPath] = { + path: path, + val: undefined, + precensored: false, + circle: '', + escPath: JSON.stringify(strPath), + leadingBracket: leadingBracket + } + } + return o + }, {}) -/** - * Module dependencies. - */ + return { wildcards, wcLen, secret } +} -var tty = __nccwpck_require__(76224); -var util = __nccwpck_require__(73837); -/** - * This is the Node.js implementation of `debug()`. - * - * Expose `debug()` as the module. - */ +/***/ }), -exports = module.exports = __nccwpck_require__(86991); -exports.init = init; -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; +/***/ 17333: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * Colors. - */ +"use strict"; -exports.colors = [6, 2, 3, 4, 5, 1]; -/** - * Build up the default `inspectOpts` object from the environment variables. - * - * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js - */ +const rx = __nccwpck_require__(9158) -exports.inspectOpts = Object.keys(process.env).filter(function (key) { - return /^debug_/i.test(key); -}).reduce(function (obj, key) { - // camel-case - var prop = key - .substring(6) - .toLowerCase() - .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() }); +module.exports = redactor - // coerce string value into JS value - var val = process.env[key]; - if (/^(yes|on|true|enabled)$/i.test(val)) val = true; - else if (/^(no|off|false|disabled)$/i.test(val)) val = false; - else if (val === 'null') val = null; - else val = Number(val); +function redactor ({ secret, serialize, wcLen, strict, isCensorFct, censorFctTakesPath }, state) { + /* eslint-disable-next-line */ + const redact = Function('o', ` + if (typeof o !== 'object' || o == null) { + ${strictImpl(strict, serialize)} + } + const { censor, secret } = this + ${redactTmpl(secret, isCensorFct, censorFctTakesPath)} + this.compileRestore() + ${dynamicRedactTmpl(wcLen > 0, isCensorFct, censorFctTakesPath)} + ${resultTmpl(serialize)} + `).bind(state) - obj[prop] = val; - return obj; -}, {}); + if (serialize === false) { + redact.restore = (o) => state.restore(o) + } -/** - * The file descriptor to write the `debug()` calls to. - * Set the `DEBUG_FD` env variable to override with another value. i.e.: - * - * $ DEBUG_FD=3 node script.js 3>debug.log - */ + return redact +} -var fd = parseInt(process.env.DEBUG_FD, 10) || 2; +function redactTmpl (secret, isCensorFct, censorFctTakesPath) { + return Object.keys(secret).map((path) => { + const { escPath, leadingBracket, path: arrPath } = secret[path] + const skip = leadingBracket ? 1 : 0 + const delim = leadingBracket ? '' : '.' + const hops = [] + var match + while ((match = rx.exec(path)) !== null) { + const [ , ix ] = match + const { index, input } = match + if (index > skip) hops.push(input.substring(0, index - (ix ? 0 : 1))) + } + var existence = hops.map((p) => `o${delim}${p}`).join(' && ') + if (existence.length === 0) existence += `o${delim}${path} != null` + else existence += ` && o${delim}${path} != null` -if (1 !== fd && 2 !== fd) { - util.deprecate(function(){}, 'except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)')() + const circularDetection = ` + switch (true) { + ${hops.reverse().map((p) => ` + case o${delim}${p} === censor: + secret[${escPath}].circle = ${JSON.stringify(p)} + break + `).join('\n')} + } + ` + + const censorArgs = censorFctTakesPath + ? `val, ${JSON.stringify(arrPath)}` + : `val` + + return ` + if (${existence}) { + const val = o${delim}${path} + if (val === censor) { + secret[${escPath}].precensored = true + } else { + secret[${escPath}].val = val + o${delim}${path} = ${isCensorFct ? `censor(${censorArgs})` : 'censor'} + ${circularDetection} + } + } + ` + }).join('\n') } -var stream = 1 === fd ? process.stdout : - 2 === fd ? process.stderr : - createWritableStdioStream(fd); +function dynamicRedactTmpl (hasWildcards, isCensorFct, censorFctTakesPath) { + return hasWildcards === true ? ` + { + const { wildcards, wcLen, groupRedact, nestedRedact } = this + for (var i = 0; i < wcLen; i++) { + const { before, beforeStr, after, nested } = wildcards[i] + if (nested === true) { + secret[beforeStr] = secret[beforeStr] || [] + nestedRedact(secret[beforeStr], o, before, after, censor, ${isCensorFct}, ${censorFctTakesPath}) + } else secret[beforeStr] = groupRedact(o, before, censor, ${isCensorFct}, ${censorFctTakesPath}) + } + } + ` : '' +} -/** - * Is stdout a TTY? Colored output is enabled when `true`. - */ +function resultTmpl (serialize) { + return serialize === false ? `return o` : ` + var s = this.serialize(o) + this.restore(o) + return s + ` +} -function useColors() { - return 'colors' in exports.inspectOpts - ? Boolean(exports.inspectOpts.colors) - : tty.isatty(fd); +function strictImpl (strict, serialize) { + return strict === true + ? `throw Error('fast-redact: primitives cannot be redacted')` + : serialize === false ? `return o` : `return this.serialize(o)` } -/** - * Map %o to `util.inspect()`, all on a single line. - */ -exports.formatters.o = function(v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts) - .split('\n').map(function(str) { - return str.trim() - }).join(' '); -}; +/***/ }), -/** - * Map %o to `util.inspect()`, allowing multiple lines if needed. - */ +/***/ 98806: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -exports.formatters.O = function(v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts); -}; - -/** - * Adds ANSI color escape codes if enabled. - * - * @api public - */ - -function formatArgs(args) { - var name = this.namespace; - var useColors = this.useColors; - - if (useColors) { - var c = this.color; - var prefix = ' \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m'; - - args[0] = prefix + args[0].split('\n').join('\n' + prefix); - args.push('\u001b[3' + c + 'm+' + exports.humanize(this.diff) + '\u001b[0m'); - } else { - args[0] = new Date().toUTCString() - + ' ' + name + ' ' + args[0]; - } -} +"use strict"; -/** - * Invokes `util.format()` with the specified arguments and writes to `stream`. - */ -function log() { - return stream.write(util.format.apply(util, arguments) + '\n'); -} +const { groupRestore, nestedRestore } = __nccwpck_require__(54865) -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ +module.exports = restorer -function save(namespaces) { - if (null == namespaces) { - // If you set a process.env field to null or undefined, it gets cast to the - // string 'null' or 'undefined'. Just delete instead. - delete process.env.DEBUG; - } else { - process.env.DEBUG = namespaces; +function restorer ({ secret, wcLen }) { + return function compileRestore () { + if (this.restore) return + const paths = Object.keys(secret) + const resetters = resetTmpl(secret, paths) + const hasWildcards = wcLen > 0 + const state = hasWildcards ? { secret, groupRestore, nestedRestore } : { secret } + /* eslint-disable-next-line */ + this.restore = Function( + 'o', + restoreTmpl(resetters, paths, hasWildcards) + ).bind(state) } } /** - * Load `namespaces`. + * Mutates the original object to be censored by restoring its original values + * prior to censoring. * - * @return {String} returns the previously persisted debug modes - * @api private - */ - -function load() { - return process.env.DEBUG; -} - -/** - * Copied from `node/src/node.js`. + * @param {object} secret Compiled object describing which target fields should + * be censored and the field states. + * @param {string[]} paths The list of paths to censor as provided at + * initialization time. * - * XXX: It's lame that node doesn't expose this API out-of-the-box. It also - * relies on the undocumented `tty_wrap.guessHandleType()` which is also lame. + * @returns {string} String of JavaScript to be used by `Function()`. The + * string compiles to the function that does the work in the description. */ - -function createWritableStdioStream (fd) { - var stream; - var tty_wrap = process.binding('tty_wrap'); - - // Note stream._type is used for test-module-load-list.js - - switch (tty_wrap.guessHandleType(fd)) { - case 'TTY': - stream = new tty.WriteStream(fd); - stream._type = 'tty'; - - // Hack to have stream not keep the event loop alive. - // See https://github.com/joyent/node/issues/1726 - if (stream._handle && stream._handle.unref) { - stream._handle.unref(); - } - break; - - case 'FILE': - var fs = __nccwpck_require__(57147); - stream = new fs.SyncWriteStream(fd, { autoClose: false }); - stream._type = 'fs'; - break; - - case 'PIPE': - case 'TCP': - var net = __nccwpck_require__(41808); - stream = new net.Socket({ - fd: fd, - readable: false, - writable: true - }); - - // FIXME Should probably have an option in net.Socket to create a - // stream from an existing fd which is writable only. But for now - // we'll just add this hack and set the `readable` member to false. - // Test: ./node test/fixtures/echo.js < /etc/passwd - stream.readable = false; - stream.read = null; - stream._type = 'pipe'; - - // FIXME Hack to have stream not keep the event loop alive. - // See https://github.com/joyent/node/issues/1726 - if (stream._handle && stream._handle.unref) { - stream._handle.unref(); +function resetTmpl (secret, paths) { + return paths.map((path) => { + const { circle, escPath, leadingBracket } = secret[path] + const delim = leadingBracket ? '' : '.' + const reset = circle + ? `o.${circle} = secret[${escPath}].val` + : `o${delim}${path} = secret[${escPath}].val` + const clear = `secret[${escPath}].val = undefined` + return ` + if (secret[${escPath}].val !== undefined) { + try { ${reset} } catch (e) {} + ${clear} } - break; - - default: - // Probably an error on in uv_guess_handle() - throw new Error('Implement me. Unknown stream file type!'); - } - - // For supporting legacy API we put the FD here. - stream.fd = fd; - - stream._isStdio = true; - - return stream; + ` + }).join('') } /** - * Init logic for `debug` instances. + * Creates the body of the restore function * - * Create a new `inspectOpts` object in case `useColors` is set - * differently for a particular `debug` instance. + * Restoration of the redacted object happens + * backwards, in reverse order of redactions, + * so that repeated redactions on the same object + * property can be eventually rolled back to the + * original value. + * + * This way dynamic redactions are restored first, + * starting from the last one working backwards and + * followed by the static ones. + * + * @returns {string} the body of the restore function */ +function restoreTmpl (resetters, paths, hasWildcards) { + const dynamicReset = hasWildcards === true ? ` + const keys = Object.keys(secret) + const len = keys.length + for (var i = len - 1; i >= ${paths.length}; i--) { + const k = keys[i] + const o = secret[k] + if (o.flat === true) this.groupRestore(o) + else this.nestedRestore(o) + secret[k] = null + } + ` : '' -function init (debug) { - debug.inspectOpts = {}; - - var keys = Object.keys(exports.inspectOpts); - for (var i = 0; i < keys.length; i++) { - debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; - } + return ` + const secret = this.secret + ${dynamicReset} + ${resetters} + return o + ` } -/** - * Enable namespaces listed in `process.env.DEBUG` initially. - */ - -exports.enable(load()); - /***/ }), -/***/ 27025: +/***/ 9158: /***/ ((module) => { -/** - * Helpers. - */ - -var s = 1000; -var m = s * 60; -var h = m * 60; -var d = h * 24; -var y = d * 365.25; - -/** - * Parse or format the given `val`. - * - * Options: - * - * - `long` verbose formatting [false] - * - * @param {String|Number} val - * @param {Object} [options] - * @throws {Error} throw an error if val is not a non-empty string or a number - * @return {String|Number} - * @api public - */ - -module.exports = function(val, options) { - options = options || {}; - var type = typeof val; - if (type === 'string' && val.length > 0) { - return parse(val); - } else if (type === 'number' && isNaN(val) === false) { - return options.long ? fmtLong(val) : fmtShort(val); - } - throw new Error( - 'val is not a non-empty string or a valid number. val=' + - JSON.stringify(val) - ); -}; - -/** - * Parse the given `str` and return milliseconds. - * - * @param {String} str - * @return {Number} - * @api private - */ - -function parse(str) { - str = String(str); - if (str.length > 100) { - return; - } - var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec( - str - ); - if (!match) { - return; - } - var n = parseFloat(match[1]); - var type = (match[2] || 'ms').toLowerCase(); - switch (type) { - case 'years': - case 'year': - case 'yrs': - case 'yr': - case 'y': - return n * y; - case 'days': - case 'day': - case 'd': - return n * d; - case 'hours': - case 'hour': - case 'hrs': - case 'hr': - case 'h': - return n * h; - case 'minutes': - case 'minute': - case 'mins': - case 'min': - case 'm': - return n * m; - case 'seconds': - case 'second': - case 'secs': - case 'sec': - case 's': - return n * s; - case 'milliseconds': - case 'millisecond': - case 'msecs': - case 'msec': - case 'ms': - return n; - default: - return undefined; - } -} - -/** - * Short format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ +"use strict"; -function fmtShort(ms) { - if (ms >= d) { - return Math.round(ms / d) + 'd'; - } - if (ms >= h) { - return Math.round(ms / h) + 'h'; - } - if (ms >= m) { - return Math.round(ms / m) + 'm'; - } - if (ms >= s) { - return Math.round(ms / s) + 's'; - } - return ms + 'ms'; -} -/** - * Long format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ +module.exports = /[^.[\]]+|\[((?:.)*?)\]/g -function fmtLong(ms) { - return plural(ms, d, 'day') || - plural(ms, h, 'hour') || - plural(ms, m, 'minute') || - plural(ms, s, 'second') || - ms + ' ms'; -} +/* +Regular expression explanation: -/** - * Pluralization helper. - */ +Alt 1: /[^.[\]]+/ - Match one or more characters that are *not* a dot (.) + opening square bracket ([) or closing square bracket (]) -function plural(ms, n, name) { - if (ms < n) { - return; - } - if (ms < n * 1.5) { - return Math.floor(ms / n) + ' ' + name; - } - return Math.ceil(ms / n) + ' ' + name + 's'; -} +Alt 2: /\[((?:.)*?)\]/ - If the char IS dot or square bracket, then create a capture + group (which will be capture group $1) that matches anything + within square brackets. Expansion is lazy so it will + stop matching as soon as the first closing bracket is met `]` + (rather than continuing to match until the final closing bracket). +*/ /***/ }), -/***/ 24826: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 41012: +/***/ ((module) => { "use strict"; -const validator = __nccwpck_require__(74174) -const parse = __nccwpck_require__(96214) -const redactor = __nccwpck_require__(17333) -const restorer = __nccwpck_require__(98806) -const { groupRedact, nestedRedact } = __nccwpck_require__(54865) -const state = __nccwpck_require__(41012) -const rx = __nccwpck_require__(9158) -const validate = validator() -const noop = (o) => o -noop.restore = noop - -const DEFAULT_CENSOR = '[REDACTED]' -fastRedact.rx = rx -fastRedact.validator = validator - -module.exports = fastRedact - -function fastRedact (opts = {}) { - const paths = Array.from(new Set(opts.paths || [])) - const serialize = 'serialize' in opts ? ( - opts.serialize === false ? opts.serialize - : (typeof opts.serialize === 'function' ? opts.serialize : JSON.stringify) - ) : JSON.stringify - const remove = opts.remove - if (remove === true && serialize !== JSON.stringify) { - throw Error('fast-redact – remove option may only be set when serializer is JSON.stringify') - } - const censor = remove === true - ? undefined - : 'censor' in opts ? opts.censor : DEFAULT_CENSOR - - const isCensorFct = typeof censor === 'function' - const censorFctTakesPath = isCensorFct && censor.length > 1 - - if (paths.length === 0) return serialize || noop - - validate({ paths, serialize, censor }) - - const { wildcards, wcLen, secret } = parse({ paths, censor }) - - const compileRestore = restorer({ secret, wcLen }) - const strict = 'strict' in opts ? opts.strict : true +module.exports = state - return redactor({ secret, wcLen, serialize, strict, isCensorFct, censorFctTakesPath }, state({ +function state (o) { + const { secret, censor, compileRestore, @@ -43187,502 +41865,80 @@ function fastRedact (opts = {}) { nestedRedact, wildcards, wcLen - })) + } = o + const builder = [{ secret, censor, compileRestore }] + if (serialize !== false) builder.push({ serialize }) + if (wcLen > 0) builder.push({ groupRedact, nestedRedact, wildcards, wcLen }) + return Object.assign(...builder) } /***/ }), -/***/ 54865: -/***/ ((module) => { +/***/ 74174: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -module.exports = { - groupRedact, - groupRestore, - nestedRedact, - nestedRestore -} +const { createContext, runInContext } = __nccwpck_require__(26144) -function groupRestore ({ keys, values, target }) { - if (target == null) return - const length = keys.length - for (var i = 0; i < length; i++) { - const k = keys[i] - target[k] = values[i] +module.exports = validator + +function validator (opts = {}) { + const { + ERR_PATHS_MUST_BE_STRINGS = () => 'fast-redact - Paths must be (non-empty) strings', + ERR_INVALID_PATH = (s) => `fast-redact – Invalid path (${s})` + } = opts + + return function validate ({ paths }) { + paths.forEach((s) => { + if (typeof s !== 'string') { + throw Error(ERR_PATHS_MUST_BE_STRINGS()) + } + try { + if (/〇/.test(s)) throw Error() + const proxy = new Proxy({}, { get: () => proxy, set: () => { throw Error() } }) + const expr = (s[0] === '[' ? '' : '.') + s.replace(/^\*/, '〇').replace(/\.\*/g, '.〇').replace(/\[\*\]/g, '[〇]') + if (/\n|\r|;/.test(expr)) throw Error() + if (/\/\*/.test(expr)) throw Error() + runInContext(` + (function () { + 'use strict' + o${expr} + if ([o${expr}].length !== 1) throw Error() + })() + `, createContext({ o: proxy, 〇: null }), { + codeGeneration: { strings: false, wasm: false } + }) + } catch (e) { + throw Error(ERR_INVALID_PATH(s)) + } + }) } } -function groupRedact (o, path, censor, isCensorFct, censorFctTakesPath) { - const target = get(o, path) - if (target == null) return { keys: null, values: null, target: null, flat: true } - const keys = Object.keys(target) - const keysLength = keys.length - const pathLength = path.length - const pathWithKey = censorFctTakesPath ? [...path] : undefined - const values = new Array(keysLength) - for (var i = 0; i < keysLength; i++) { - const key = keys[i] - values[i] = target[key] +/***/ }), - if (censorFctTakesPath) { - pathWithKey[pathLength] = key - target[key] = censor(target[key], pathWithKey) - } else if (isCensorFct) { - target[key] = censor(target[key]) - } else { - target[key] = censor - } - } - return { keys, values, target, flat: true } -} +/***/ 17676: +/***/ ((module) => { -function nestedRestore (arr) { - const length = arr.length - for (var i = 0; i < length; i++) { - const { key, target, value } = arr[i] - target[key] = value - } -} - -function nestedRedact (store, o, path, ns, censor, isCensorFct, censorFctTakesPath) { - const target = get(o, path) - if (target == null) return - const keys = Object.keys(target) - const keysLength = keys.length - for (var i = 0; i < keysLength; i++) { - const key = keys[i] - const { value, parent, exists } = - specialSet(target, key, path, ns, censor, isCensorFct, censorFctTakesPath) - - if (exists === true && parent !== null) { - store.push({ key: ns[ns.length - 1], target: parent, value }) - } - } - return store -} - -function has (obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop) -} - -function specialSet (o, k, path, afterPath, censor, isCensorFct, censorFctTakesPath) { - const afterPathLen = afterPath.length - const lastPathIndex = afterPathLen - 1 - const originalKey = k - var i = -1 - var n - var nv - var ov - var oov = null - var exists = true - ov = n = o[k] - if (typeof n !== 'object') return { value: null, parent: null, exists } - while (n != null && ++i < afterPathLen) { - k = afterPath[i] - oov = ov - if (!(k in n)) { - exists = false - break - } - ov = n[k] - nv = (i !== lastPathIndex) - ? ov - : (isCensorFct - ? (censorFctTakesPath ? censor(ov, [...path, originalKey, ...afterPath]) : censor(ov)) - : censor) - n[k] = (has(n, k) && nv === ov) || (nv === undefined && censor !== undefined) ? n[k] : nv - n = n[k] - if (typeof n !== 'object') break - } - return { value: ov, parent: oov, exists } -} - -function get (o, p) { - var i = -1 - var l = p.length - var n = o - while (n != null && ++i < l) { - n = n[p[i]] - } - return n -} - - -/***/ }), - -/***/ 96214: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const rx = __nccwpck_require__(9158) - -module.exports = parse - -function parse ({ paths }) { - const wildcards = [] - var wcLen = 0 - const secret = paths.reduce(function (o, strPath, ix) { - var path = strPath.match(rx).map((p) => p.replace(/'|"|`/g, '')) - const leadingBracket = strPath[0] === '[' - path = path.map((p) => { - if (p[0] === '[') return p.substr(1, p.length - 2) - else return p - }) - const star = path.indexOf('*') - if (star > -1) { - const before = path.slice(0, star) - const beforeStr = before.join('.') - const after = path.slice(star + 1, path.length) - if (after.indexOf('*') > -1) throw Error('fast-redact – Only one wildcard per path is supported') - const nested = after.length > 0 - wcLen++ - wildcards.push({ - before, - beforeStr, - after, - nested - }) - } else { - o[strPath] = { - path: path, - val: undefined, - precensored: false, - circle: '', - escPath: JSON.stringify(strPath), - leadingBracket: leadingBracket - } - } - return o - }, {}) - - return { wildcards, wcLen, secret } -} - - -/***/ }), - -/***/ 17333: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const rx = __nccwpck_require__(9158) - -module.exports = redactor - -function redactor ({ secret, serialize, wcLen, strict, isCensorFct, censorFctTakesPath }, state) { - /* eslint-disable-next-line */ - const redact = Function('o', ` - if (typeof o !== 'object' || o == null) { - ${strictImpl(strict, serialize)} - } - const { censor, secret } = this - ${redactTmpl(secret, isCensorFct, censorFctTakesPath)} - this.compileRestore() - ${dynamicRedactTmpl(wcLen > 0, isCensorFct, censorFctTakesPath)} - ${resultTmpl(serialize)} - `).bind(state) - - if (serialize === false) { - redact.restore = (o) => state.restore(o) - } - - return redact -} - -function redactTmpl (secret, isCensorFct, censorFctTakesPath) { - return Object.keys(secret).map((path) => { - const { escPath, leadingBracket, path: arrPath } = secret[path] - const skip = leadingBracket ? 1 : 0 - const delim = leadingBracket ? '' : '.' - const hops = [] - var match - while ((match = rx.exec(path)) !== null) { - const [ , ix ] = match - const { index, input } = match - if (index > skip) hops.push(input.substring(0, index - (ix ? 0 : 1))) - } - var existence = hops.map((p) => `o${delim}${p}`).join(' && ') - if (existence.length === 0) existence += `o${delim}${path} != null` - else existence += ` && o${delim}${path} != null` - - const circularDetection = ` - switch (true) { - ${hops.reverse().map((p) => ` - case o${delim}${p} === censor: - secret[${escPath}].circle = ${JSON.stringify(p)} - break - `).join('\n')} - } - ` - - const censorArgs = censorFctTakesPath - ? `val, ${JSON.stringify(arrPath)}` - : `val` - - return ` - if (${existence}) { - const val = o${delim}${path} - if (val === censor) { - secret[${escPath}].precensored = true - } else { - secret[${escPath}].val = val - o${delim}${path} = ${isCensorFct ? `censor(${censorArgs})` : 'censor'} - ${circularDetection} - } - } - ` - }).join('\n') -} - -function dynamicRedactTmpl (hasWildcards, isCensorFct, censorFctTakesPath) { - return hasWildcards === true ? ` - { - const { wildcards, wcLen, groupRedact, nestedRedact } = this - for (var i = 0; i < wcLen; i++) { - const { before, beforeStr, after, nested } = wildcards[i] - if (nested === true) { - secret[beforeStr] = secret[beforeStr] || [] - nestedRedact(secret[beforeStr], o, before, after, censor, ${isCensorFct}, ${censorFctTakesPath}) - } else secret[beforeStr] = groupRedact(o, before, censor, ${isCensorFct}, ${censorFctTakesPath}) - } - } - ` : '' -} - -function resultTmpl (serialize) { - return serialize === false ? `return o` : ` - var s = this.serialize(o) - this.restore(o) - return s - ` -} - -function strictImpl (strict, serialize) { - return strict === true - ? `throw Error('fast-redact: primitives cannot be redacted')` - : serialize === false ? `return o` : `return this.serialize(o)` -} - - -/***/ }), - -/***/ 98806: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const { groupRestore, nestedRestore } = __nccwpck_require__(54865) - -module.exports = restorer - -function restorer ({ secret, wcLen }) { - return function compileRestore () { - if (this.restore) return - const paths = Object.keys(secret) - const resetters = resetTmpl(secret, paths) - const hasWildcards = wcLen > 0 - const state = hasWildcards ? { secret, groupRestore, nestedRestore } : { secret } - /* eslint-disable-next-line */ - this.restore = Function( - 'o', - restoreTmpl(resetters, paths, hasWildcards) - ).bind(state) - } -} - -/** - * Mutates the original object to be censored by restoring its original values - * prior to censoring. - * - * @param {object} secret Compiled object describing which target fields should - * be censored and the field states. - * @param {string[]} paths The list of paths to censor as provided at - * initialization time. - * - * @returns {string} String of JavaScript to be used by `Function()`. The - * string compiles to the function that does the work in the description. - */ -function resetTmpl (secret, paths) { - return paths.map((path) => { - const { circle, escPath, leadingBracket } = secret[path] - const delim = leadingBracket ? '' : '.' - const reset = circle - ? `o.${circle} = secret[${escPath}].val` - : `o${delim}${path} = secret[${escPath}].val` - const clear = `secret[${escPath}].val = undefined` - return ` - if (secret[${escPath}].val !== undefined) { - try { ${reset} } catch (e) {} - ${clear} - } - ` - }).join('') -} - -/** - * Creates the body of the restore function - * - * Restoration of the redacted object happens - * backwards, in reverse order of redactions, - * so that repeated redactions on the same object - * property can be eventually rolled back to the - * original value. - * - * This way dynamic redactions are restored first, - * starting from the last one working backwards and - * followed by the static ones. - * - * @returns {string} the body of the restore function - */ -function restoreTmpl (resetters, paths, hasWildcards) { - const dynamicReset = hasWildcards === true ? ` - const keys = Object.keys(secret) - const len = keys.length - for (var i = len - 1; i >= ${paths.length}; i--) { - const k = keys[i] - const o = secret[k] - if (o.flat === true) this.groupRestore(o) - else this.nestedRestore(o) - secret[k] = null - } - ` : '' - - return ` - const secret = this.secret - ${dynamicReset} - ${resetters} - return o - ` -} - - -/***/ }), - -/***/ 9158: -/***/ ((module) => { - -"use strict"; - - -module.exports = /[^.[\]]+|\[((?:.)*?)\]/g - -/* -Regular expression explanation: - -Alt 1: /[^.[\]]+/ - Match one or more characters that are *not* a dot (.) - opening square bracket ([) or closing square bracket (]) - -Alt 2: /\[((?:.)*?)\]/ - If the char IS dot or square bracket, then create a capture - group (which will be capture group $1) that matches anything - within square brackets. Expansion is lazy so it will - stop matching as soon as the first closing bracket is met `]` - (rather than continuing to match until the final closing bracket). -*/ - - -/***/ }), - -/***/ 41012: -/***/ ((module) => { - -"use strict"; - - -module.exports = state - -function state (o) { - const { - secret, - censor, - compileRestore, - serialize, - groupRedact, - nestedRedact, - wildcards, - wcLen - } = o - const builder = [{ secret, censor, compileRestore }] - if (serialize !== false) builder.push({ serialize }) - if (wcLen > 0) builder.push({ groupRedact, nestedRedact, wildcards, wcLen }) - return Object.assign(...builder) -} - - -/***/ }), - -/***/ 74174: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const { createContext, runInContext } = __nccwpck_require__(26144) - -module.exports = validator - -function validator (opts = {}) { - const { - ERR_PATHS_MUST_BE_STRINGS = () => 'fast-redact - Paths must be (non-empty) strings', - ERR_INVALID_PATH = (s) => `fast-redact – Invalid path (${s})` - } = opts - - return function validate ({ paths }) { - paths.forEach((s) => { - if (typeof s !== 'string') { - throw Error(ERR_PATHS_MUST_BE_STRINGS()) - } - try { - if (/〇/.test(s)) throw Error() - const proxy = new Proxy({}, { get: () => proxy, set: () => { throw Error() } }) - const expr = (s[0] === '[' ? '' : '.') + s.replace(/^\*/, '〇').replace(/\.\*/g, '.〇').replace(/\[\*\]/g, '[〇]') - if (/\n|\r|;/.test(expr)) throw Error() - if (/\/\*/.test(expr)) throw Error() - runInContext(` - (function () { - 'use strict' - o${expr} - if ([o${expr}].length !== 1) throw Error() - })() - `, createContext({ o: proxy, 〇: null }), { - codeGeneration: { strings: false, wasm: false } - }) - } catch (e) { - throw Error(ERR_INVALID_PATH(s)) - } - }) - } -} - - -/***/ }), - -/***/ 17676: -/***/ ((module) => { - -module.exports = stringify -stringify.default = stringify -stringify.stable = deterministicStringify -stringify.stableStringify = deterministicStringify - -var LIMIT_REPLACE_NODE = '[...]' -var CIRCULAR_REPLACE_NODE = '[Circular]' - -var arr = [] -var replacerStack = [] - -function defaultOptions () { - return { - depthLimit: Number.MAX_SAFE_INTEGER, - edgesLimit: Number.MAX_SAFE_INTEGER +module.exports = stringify +stringify.default = stringify +stringify.stable = deterministicStringify +stringify.stableStringify = deterministicStringify + +var LIMIT_REPLACE_NODE = '[...]' +var CIRCULAR_REPLACE_NODE = '[Circular]' + +var arr = [] +var replacerStack = [] + +function defaultOptions () { + return { + depthLimit: Number.MAX_SAFE_INTEGER, + edgesLimit: Number.MAX_SAFE_INTEGER } } @@ -54631,7 +52887,7 @@ const util_1 = __nccwpck_require__(73837); const standard_as_callback_1 = __nccwpck_require__(91543); const redis_commands_1 = __nccwpck_require__(98020); const calculateSlot = __nccwpck_require__(48481); -const pMap = __nccwpck_require__(91855); +const pMap = __nccwpck_require__(12071); const PromiseContainer = __nccwpck_require__(71475); const commander_1 = __nccwpck_require__(33642); const utils_1 = __nccwpck_require__(94832); @@ -56784,6 +55040,86 @@ function noop() { } exports.noop = noop; +/***/ }), + +/***/ 12071: +/***/ ((module) => { + +"use strict"; + + +const pMap = (iterable, mapper, options) => new Promise((resolve, reject) => { + options = Object.assign({ + concurrency: Infinity + }, options); + + if (typeof mapper !== 'function') { + throw new TypeError('Mapper function is required'); + } + + const {concurrency} = options; + + if (!(typeof concurrency === 'number' && concurrency >= 1)) { + throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${concurrency}\` (${typeof concurrency})`); + } + + const ret = []; + const iterator = iterable[Symbol.iterator](); + let isRejected = false; + let isIterableDone = false; + let resolvingCount = 0; + let currentIndex = 0; + + const next = () => { + if (isRejected) { + return; + } + + const nextItem = iterator.next(); + const i = currentIndex; + currentIndex++; + + if (nextItem.done) { + isIterableDone = true; + + if (resolvingCount === 0) { + resolve(ret); + } + + return; + } + + resolvingCount++; + + Promise.resolve(nextItem.value) + .then(element => mapper(element, i)) + .then( + value => { + ret[i] = value; + resolvingCount--; + next(); + }, + error => { + isRejected = true; + reject(error); + } + ); + }; + + for (let i = 0; i < concurrency; i++) { + next(); + + if (isIterableDone) { + break; + } + } +}); + +module.exports = pMap; +// TODO: Remove this for the next major release +module.exports["default"] = pMap; + + /***/ }), /***/ 37263: @@ -57606,64 +55942,6 @@ module.exports = function isCore(x, nodeVersion) { }; -/***/ }), - -/***/ 64882: -/***/ ((module) => { - -"use strict"; -/* eslint-disable yoda */ - - -const isFullwidthCodePoint = codePoint => { - if (Number.isNaN(codePoint)) { - return false; - } - - // Code points are derived from: - // http://www.unix.org/Public/UNIDATA/EastAsianWidth.txt - if ( - codePoint >= 0x1100 && ( - codePoint <= 0x115F || // Hangul Jamo - codePoint === 0x2329 || // LEFT-POINTING ANGLE BRACKET - codePoint === 0x232A || // RIGHT-POINTING ANGLE BRACKET - // CJK Radicals Supplement .. Enclosed CJK Letters and Months - (0x2E80 <= codePoint && codePoint <= 0x3247 && codePoint !== 0x303F) || - // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A - (0x3250 <= codePoint && codePoint <= 0x4DBF) || - // CJK Unified Ideographs .. Yi Radicals - (0x4E00 <= codePoint && codePoint <= 0xA4C6) || - // Hangul Jamo Extended-A - (0xA960 <= codePoint && codePoint <= 0xA97C) || - // Hangul Syllables - (0xAC00 <= codePoint && codePoint <= 0xD7A3) || - // CJK Compatibility Ideographs - (0xF900 <= codePoint && codePoint <= 0xFAFF) || - // Vertical Forms - (0xFE10 <= codePoint && codePoint <= 0xFE19) || - // CJK Compatibility Forms .. Small Form Variants - (0xFE30 <= codePoint && codePoint <= 0xFE6B) || - // Halfwidth and Fullwidth Forms - (0xFF01 <= codePoint && codePoint <= 0xFF60) || - (0xFFE0 <= codePoint && codePoint <= 0xFFE6) || - // Kana Supplement - (0x1B000 <= codePoint && codePoint <= 0x1B001) || - // Enclosed Ideographic Supplement - (0x1F200 <= codePoint && codePoint <= 0x1F251) || - // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane - (0x20000 <= codePoint && codePoint <= 0x3FFFD) - ) - ) { - return true; - } - - return false; -}; - -module.exports = isFullwidthCodePoint; -module.exports["default"] = isFullwidthCodePoint; - - /***/ }), /***/ 63287: @@ -74566,7 +72844,7 @@ module.exports = semver.satisfies(process.version, '^6.12.0 || >=8.0.0'); /***/ 46098: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var ms = __nccwpck_require__(84098); +var ms = __nccwpck_require__(80900); module.exports = function (time, iat) { var timestamp = iat || Math.floor(Date.now() / 1000); @@ -74585,175 +72863,6 @@ module.exports = function (time, iat) { }; -/***/ }), - -/***/ 84098: -/***/ ((module) => { - -/** - * Helpers. - */ - -var s = 1000; -var m = s * 60; -var h = m * 60; -var d = h * 24; -var w = d * 7; -var y = d * 365.25; - -/** - * Parse or format the given `val`. - * - * Options: - * - * - `long` verbose formatting [false] - * - * @param {String|Number} val - * @param {Object} [options] - * @throws {Error} throw an error if val is not a non-empty string or a number - * @return {String|Number} - * @api public - */ - -module.exports = function (val, options) { - options = options || {}; - var type = typeof val; - if (type === 'string' && val.length > 0) { - return parse(val); - } else if (type === 'number' && isFinite(val)) { - return options.long ? fmtLong(val) : fmtShort(val); - } - throw new Error( - 'val is not a non-empty string or a valid number. val=' + - JSON.stringify(val) - ); -}; - -/** - * Parse the given `str` and return milliseconds. - * - * @param {String} str - * @return {Number} - * @api private - */ - -function parse(str) { - str = String(str); - if (str.length > 100) { - return; - } - var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( - str - ); - if (!match) { - return; - } - var n = parseFloat(match[1]); - var type = (match[2] || 'ms').toLowerCase(); - switch (type) { - case 'years': - case 'year': - case 'yrs': - case 'yr': - case 'y': - return n * y; - case 'weeks': - case 'week': - case 'w': - return n * w; - case 'days': - case 'day': - case 'd': - return n * d; - case 'hours': - case 'hour': - case 'hrs': - case 'hr': - case 'h': - return n * h; - case 'minutes': - case 'minute': - case 'mins': - case 'min': - case 'm': - return n * m; - case 'seconds': - case 'second': - case 'secs': - case 'sec': - case 's': - return n * s; - case 'milliseconds': - case 'millisecond': - case 'msecs': - case 'msec': - case 'ms': - return n; - default: - return undefined; - } -} - -/** - * Short format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ - -function fmtShort(ms) { - var msAbs = Math.abs(ms); - if (msAbs >= d) { - return Math.round(ms / d) + 'd'; - } - if (msAbs >= h) { - return Math.round(ms / h) + 'h'; - } - if (msAbs >= m) { - return Math.round(ms / m) + 'm'; - } - if (msAbs >= s) { - return Math.round(ms / s) + 's'; - } - return ms + 'ms'; -} - -/** - * Long format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ - -function fmtLong(ms) { - var msAbs = Math.abs(ms); - if (msAbs >= d) { - return plural(ms, msAbs, d, 'day'); - } - if (msAbs >= h) { - return plural(ms, msAbs, h, 'hour'); - } - if (msAbs >= m) { - return plural(ms, msAbs, m, 'minute'); - } - if (msAbs >= s) { - return plural(ms, msAbs, s, 'second'); - } - return ms + ' ms'; -} - -/** - * Pluralization helper. - */ - -function plural(ms, msAbs, n, name) { - var isPlural = msAbs >= n * 1.5; - return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); -} - - /***/ }), /***/ 27174: @@ -77277,7 +75386,7 @@ module.exports = VerifyStream; const path = __nccwpck_require__(71017); const fs = __nccwpck_require__(77758); -const stripBom = __nccwpck_require__(88551); +const stripBom = __nccwpck_require__(89383); const parseJson = __nccwpck_require__(81680); const pify = __nccwpck_require__(64810); @@ -77340,6 +75449,28 @@ module.exports = (input, reviver, filename) => { }; +/***/ }), + +/***/ 89383: +/***/ ((module) => { + +"use strict"; + +module.exports = x => { + if (typeof x !== 'string') { + throw new TypeError('Expected a string, got ' + typeof x); + } + + // Catches EFBBBF (UTF-8 BOM) because the buffer-to-string + // conversion translates it to FEFF (UTF-16 BOM) + if (x.charCodeAt(0) === 0xFEFF) { + return x.slice(1); + } + + return x; +}; + + /***/ }), /***/ 11289: @@ -104528,86 +102659,6 @@ module.exports = pLimit; module.exports["default"] = pLimit; -/***/ }), - -/***/ 91855: -/***/ ((module) => { - -"use strict"; - - -const pMap = (iterable, mapper, options) => new Promise((resolve, reject) => { - options = Object.assign({ - concurrency: Infinity - }, options); - - if (typeof mapper !== 'function') { - throw new TypeError('Mapper function is required'); - } - - const {concurrency} = options; - - if (!(typeof concurrency === 'number' && concurrency >= 1)) { - throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${concurrency}\` (${typeof concurrency})`); - } - - const ret = []; - const iterator = iterable[Symbol.iterator](); - let isRejected = false; - let isIterableDone = false; - let resolvingCount = 0; - let currentIndex = 0; - - const next = () => { - if (isRejected) { - return; - } - - const nextItem = iterator.next(); - const i = currentIndex; - currentIndex++; - - if (nextItem.done) { - isIterableDone = true; - - if (resolvingCount === 0) { - resolve(ret); - } - - return; - } - - resolvingCount++; - - Promise.resolve(nextItem.value) - .then(element => mapper(element, i)) - .then( - value => { - ret[i] = value; - resolvingCount--; - next(); - }, - error => { - isRejected = true; - reject(error); - } - ); - }; - - for (let i = 0; i < concurrency; i++) { - next(); - - if (isIterableDone) { - break; - } - } -}); - -module.exports = pMap; -// TODO: Remove this for the next major release -module.exports["default"] = pMap; - - /***/ }), /***/ 80746: @@ -107338,7 +105389,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.readCliOptions = void 0; -const commander_1 = __importDefault(__nccwpck_require__(61904)); +const commander_1 = __importDefault(__nccwpck_require__(18828)); const get_private_key_1 = __nccwpck_require__(97743); function readCliOptions(argv) { commander_1.default @@ -107678,958 +105729,2846 @@ exports.createProbot = createProbot; "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.aliasLog = void 0; -/** - * `probot.log()`, `app.log()` and `context.log()` are aliasing `.log.info()`. - * We will probably remove the aliasing in future. - */ -function aliasLog(log) { - function logInfo() { - // @ts-ignore - log.info(...arguments); - } - for (const key in log) { - // @ts-ignore - logInfo[key] = - typeof log[key] === "function" ? log[key].bind(log) : log[key]; - } - // @ts-ignore - return logInfo; -} -exports.aliasLog = aliasLog; -//# sourceMappingURL=alias-log.js.map +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.aliasLog = void 0; +/** + * `probot.log()`, `app.log()` and `context.log()` are aliasing `.log.info()`. + * We will probably remove the aliasing in future. + */ +function aliasLog(log) { + function logInfo() { + // @ts-ignore + log.info(...arguments); + } + for (const key in log) { + // @ts-ignore + logInfo[key] = + typeof log[key] === "function" ? log[key].bind(log) : log[key]; + } + // @ts-ignore + return logInfo; +} +exports.aliasLog = aliasLog; +//# sourceMappingURL=alias-log.js.map + +/***/ }), + +/***/ 25625: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getErrorHandler = void 0; +function getErrorHandler(log) { + return (error) => { + const errors = (error.name === "AggregateError" ? error : [error]); + const event = error.event; + for (const error of errors) { + const errMessage = (error.message || "").toLowerCase(); + if (errMessage.includes("x-hub-signature-256")) { + log.error(error, "Go to https://github.com/settings/apps/YOUR_APP and verify that the Webhook secret matches the value of the WEBHOOK_SECRET environment variable."); + continue; + } + if (errMessage.includes("pem") || errMessage.includes("json web token")) { + log.error(error, "Your private key (a .pem file or PRIVATE_KEY environment variable) or APP_ID is incorrect. Go to https://github.com/settings/apps/YOUR_APP, verify that APP_ID is set correctly, and generate a new PEM file if necessary."); + continue; + } + log + .child({ + name: "event", + id: event ? event.id : undefined, + }) + .error(error); + } + }; +} +exports.getErrorHandler = getErrorHandler; +//# sourceMappingURL=get-error-handler.js.map + +/***/ }), + +/***/ 75942: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getLog = void 0; +/** + * A logger backed by [pino](https://getpino.io/) + * + * The default log level is `info`, but you can change it passing a level + * string set to one of: `"trace"`, `"debug"`, `"info"`, `"warn"`, + * `"error"`, or `"fatal"`. + * + * ```js + * app.log.debug("…so is this"); + * app.log.trace("Now we're talking"); + * app.log.info("I thought you should know…"); + * app.log.warn("Woah there"); + * app.log.error("ETOOMANYLOGS"); + * app.log.fatal("Goodbye, cruel world!"); + * ``` + */ +const pino_1 = __importDefault(__nccwpck_require__(79608)); +const pino_2 = __nccwpck_require__(39662); +function getLog(options = {}) { + const { level, logMessageKey, ...getTransformStreamOptions } = options; + const pinoOptions = { + level: level || "info", + name: "probot", + messageKey: logMessageKey || "msg", + }; + const transform = pino_2.getTransformStream(getTransformStreamOptions); + // @ts-ignore TODO: check out what's wrong here + transform.pipe(pino_1.default.destination(1)); + const log = pino_1.default(pinoOptions, transform); + return log; +} +exports.getLog = getLog; +//# sourceMappingURL=get-log.js.map + +/***/ }), + +/***/ 78079: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.isProduction = void 0; +function isProduction() { + return process.env.NODE_ENV === "production"; +} +exports.isProduction = isProduction; +//# sourceMappingURL=is-production.js.map + +/***/ }), + +/***/ 32350: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.resolveAppFunction = void 0; +const resolve_1 = __nccwpck_require__(39283); +const defaultOptions = {}; +const resolveAppFunction = async (appFnId, opts) => { + opts = opts || defaultOptions; + // These are mostly to ease testing + const basedir = opts.basedir || process.cwd(); + const resolver = opts.resolver || resolve_1.sync; + const appFnPath = resolver(appFnId, { basedir }); + const mod = await Promise.resolve().then(() => __importStar(require(appFnPath))); + // Note: This needs "esModuleInterop" to be set to "true" in "tsconfig.json" + return mod.default; +}; +exports.resolveAppFunction = resolveAppFunction; +//# sourceMappingURL=resolve-app-function.js.map + +/***/ }), + +/***/ 32415: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.createWebhookProxy = void 0; +const createWebhookProxy = (opts) => { + try { + const SmeeClient = __nccwpck_require__(24807); + const smee = new SmeeClient({ + logger: opts.logger, + source: opts.url, + target: `http://localhost:${opts.port}${opts.path}`, + }); + return smee.start(); + } + catch (error) { + opts.logger.warn("Run `npm install --save-dev smee-client` to proxy webhooks to localhost."); + return; + } +}; +exports.createWebhookProxy = createWebhookProxy; +//# sourceMappingURL=webhook-proxy.js.map + +/***/ }), + +/***/ 58930: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.createProbot = exports.createNodeMiddleware = exports.Server = exports.Probot = exports.run = exports.ProbotOctokit = exports.Context = void 0; +const context_1 = __nccwpck_require__(94219); +Object.defineProperty(exports, "Context", ({ enumerable: true, get: function () { return context_1.Context; } })); +const probot_1 = __nccwpck_require__(87085); +Object.defineProperty(exports, "Probot", ({ enumerable: true, get: function () { return probot_1.Probot; } })); +const server_1 = __nccwpck_require__(93772); +Object.defineProperty(exports, "Server", ({ enumerable: true, get: function () { return server_1.Server; } })); +const probot_octokit_1 = __nccwpck_require__(45351); +Object.defineProperty(exports, "ProbotOctokit", ({ enumerable: true, get: function () { return probot_octokit_1.ProbotOctokit; } })); +const run_1 = __nccwpck_require__(75611); +Object.defineProperty(exports, "run", ({ enumerable: true, get: function () { return run_1.run; } })); +const create_node_middleware_1 = __nccwpck_require__(95960); +Object.defineProperty(exports, "createNodeMiddleware", ({ enumerable: true, get: function () { return create_node_middleware_1.createNodeMiddleware; } })); +const create_probot_1 = __nccwpck_require__(82598); +Object.defineProperty(exports, "createProbot", ({ enumerable: true, get: function () { return create_probot_1.createProbot; } })); +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 59159: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ManifestCreation = void 0; +const fs_1 = __importDefault(__nccwpck_require__(57147)); +const js_yaml_1 = __importDefault(__nccwpck_require__(695)); +const path_1 = __importDefault(__nccwpck_require__(71017)); +const update_dotenv_1 = __importDefault(__nccwpck_require__(51023)); +const probot_octokit_1 = __nccwpck_require__(45351); +class ManifestCreation { + get pkg() { + let pkg; + try { + pkg = require(path_1.default.join(process.cwd(), "package.json")); + } + catch (e) { + pkg = {}; + } + return pkg; + } + async createWebhookChannel() { + try { + // tslint:disable:no-var-requires + const SmeeClient = __nccwpck_require__(24807); + await this.updateEnv({ + WEBHOOK_PROXY_URL: await SmeeClient.createChannel(), + }); + } + catch (error) { + // Smee is not available, so we'll just move on + // tslint:disable:no-console + console.warn("Unable to connect to smee.io, try restarting your server."); + } + } + getManifest(pkg, baseUrl) { + let manifest = {}; + try { + const file = fs_1.default.readFileSync(path_1.default.join(process.cwd(), "app.yml"), "utf8"); + manifest = js_yaml_1.default.safeLoad(file); + } + catch (error) { + // App config does not exist, which is ok. + if (error.code !== "ENOENT") { + throw error; + } + } + const generatedManifest = JSON.stringify(Object.assign({ + description: manifest.description || pkg.description, + hook_attributes: { + url: process.env.WEBHOOK_PROXY_URL || `${baseUrl}/`, + }, + name: process.env.PROJECT_DOMAIN || manifest.name || pkg.name, + public: manifest.public || true, + redirect_url: `${baseUrl}/probot/setup`, + // TODO: add setup url + // setup_url:`${baseUrl}/probot/success`, + url: manifest.url || pkg.homepage || pkg.repository, + version: "v1", + }, manifest)); + return generatedManifest; + } + async createAppFromCode(code) { + const octokit = new probot_octokit_1.ProbotOctokit(); + const options = { + code, + mediaType: { + previews: ["fury"], // needed for GHES 2.20 and older + }, + ...(process.env.GHE_HOST && { + baseUrl: `${process.env.GHE_PROTOCOL || "https"}://${process.env.GHE_HOST}/api/v3`, + }), + }; + const response = await octokit.request("POST /app-manifests/:code/conversions", options); + const { id, client_id, client_secret, webhook_secret, pem } = response.data; + await this.updateEnv({ + APP_ID: id.toString(), + PRIVATE_KEY: `"${pem}"`, + WEBHOOK_SECRET: webhook_secret, + GITHUB_CLIENT_ID: client_id, + GITHUB_CLIENT_SECRET: client_secret, + }); + return response.data.html_url; + } + async updateEnv(env) { + // Needs to be public due to tests + return update_dotenv_1.default(env); + } + get createAppUrl() { + const githubHost = process.env.GHE_HOST || `github.com`; + return `${process.env.GHE_PROTOCOL || "https"}://${githubHost}${process.env.GH_ORG ? "/organizations/".concat(process.env.GH_ORG) : ""}/settings/apps/new`; + } +} +exports.ManifestCreation = ManifestCreation; +//# sourceMappingURL=manifest-creation.js.map + +/***/ }), + +/***/ 88916: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getAuthenticatedOctokit = void 0; +async function getAuthenticatedOctokit(state, installationId) { + const { log, octokit } = state; + if (!installationId) + return octokit; + return octokit.auth({ + type: "installation", + installationId, + factory: ({ octokit, octokitOptions, ...otherOptions }) => { + const pinoLog = log.child({ name: "github" }); + const options = { + ...octokitOptions, + log: { + fatal: pinoLog.fatal.bind(pinoLog), + error: pinoLog.error.bind(pinoLog), + warn: pinoLog.warn.bind(pinoLog), + info: pinoLog.info.bind(pinoLog), + debug: pinoLog.debug.bind(pinoLog), + trace: pinoLog.trace.bind(pinoLog), + }, + throttle: { + ...octokitOptions.throttle, + id: installationId, + }, + auth: { + ...octokitOptions.auth, + otherOptions, + installationId, + }, + }; + const Octokit = octokit.constructor; + return new Octokit(options); + }, + }); +} +exports.getAuthenticatedOctokit = getAuthenticatedOctokit; +//# sourceMappingURL=get-authenticated-octokit.js.map + +/***/ }), + +/***/ 2286: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getOctokitThrottleOptions = void 0; +const bottleneck_1 = __importDefault(__nccwpck_require__(27356)); +const ioredis_1 = __importDefault(__nccwpck_require__(45069)); +function getOctokitThrottleOptions(options) { + let { log, redisConfig } = options; + if (!redisConfig) + return; + const connection = new bottleneck_1.default.IORedisConnection({ + client: getRedisClient(options), + }); + connection.on("error", (error) => { + log.error(Object.assign(error, { source: "bottleneck" })); + }); + return { + Bottleneck: bottleneck_1.default, + connection, + }; +} +exports.getOctokitThrottleOptions = getOctokitThrottleOptions; +function getRedisClient({ log, redisConfig }) { + if (redisConfig) + return new ioredis_1.default(redisConfig); +} +//# sourceMappingURL=get-octokit-throttle-options.js.map + +/***/ }), + +/***/ 62543: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getProbotOctokitWithDefaults = void 0; +const get_octokit_throttle_options_1 = __nccwpck_require__(2286); +/** + * Returns an Octokit instance with default settings for authentication. If + * a `githubToken` is passed explicitly, the Octokit instance will be + * pre-authenticated with that token when instantiated. Otherwise Octokit's + * app authentication strategy is used, and `options.auth` options are merged + * deeply when instantiated. + * + * Besides the authentication, the Octokit's baseUrl is set as well when run + * against a GitHub Enterprise Server with a custom domain. + */ +function getProbotOctokitWithDefaults(options) { + const authOptions = options.githubToken + ? { + token: options.githubToken, + } + : { + cache: options.cache, + appId: options.appId, + privateKey: options.privateKey, + }; + const octokitThrottleOptions = get_octokit_throttle_options_1.getOctokitThrottleOptions({ + log: options.log, + redisConfig: options.redisConfig, + }); + let defaultOptions = { + auth: authOptions, + }; + if (options.baseUrl) { + defaultOptions.baseUrl = options.baseUrl; + } + if (octokitThrottleOptions) { + defaultOptions.throttle = octokitThrottleOptions; + } + return options.Octokit.defaults((instanceOptions) => { + const options = Object.assign({}, defaultOptions, instanceOptions, { + auth: instanceOptions.auth + ? Object.assign({}, defaultOptions.auth, instanceOptions.auth) + : defaultOptions.auth, + }); + if (instanceOptions.throttle) { + options.throttle = Object.assign({}, defaultOptions.throttle, instanceOptions.throttle); + } + return options; + }); +} +exports.getProbotOctokitWithDefaults = getProbotOctokitWithDefaults; +//# sourceMappingURL=get-probot-octokit-with-defaults.js.map + +/***/ }), + +/***/ 92974: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getWebhooks = void 0; +const webhooks_1 = __nccwpck_require__(18513); +const get_error_handler_1 = __nccwpck_require__(25625); +const octokit_webhooks_transform_1 = __nccwpck_require__(50645); +// import { Context } from "../context"; +function getWebhooks(state) { + // TODO: This should be webhooks = new Webhooks({...}) but fails with + // > The context of the event that was triggered, including the payload and + // helpers for extracting information can be passed to GitHub API calls + const webhooks = new webhooks_1.Webhooks({ + secret: state.webhooks.secret, + transform: octokit_webhooks_transform_1.webhookTransform.bind(null, state), + }); + webhooks.onError(get_error_handler_1.getErrorHandler(state.log)); + return webhooks; +} +exports.getWebhooks = getWebhooks; +//# sourceMappingURL=get-webhooks.js.map + +/***/ }), + +/***/ 87517: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.probotRequestLogging = void 0; +function probotRequestLogging(octokit) { + octokit.hook.error("request", (error, options) => { + if ("status" in error) { + const { method, url, request, ...params } = octokit.request.endpoint.parse(options); + const msg = `GitHub request: ${method} ${url} - ${error.status}`; + // @ts-expect-error log.debug is a pino log method and accepts a fields object + octokit.log.debug(params.body || {}, msg); + } + throw error; + }); + octokit.hook.after("request", (result, options) => { + const { method, url, request, ...params } = octokit.request.endpoint.parse(options); + const msg = `GitHub request: ${method} ${url} - ${result.status}`; + // @ts-ignore log.debug is a pino log method and accepts a fields object + octokit.log.debug(params.body || {}, msg); + }); +} +exports.probotRequestLogging = probotRequestLogging; +//# sourceMappingURL=octokit-plugin-probot-request-logging.js.map + +/***/ }), + +/***/ 50645: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.webhookTransform = void 0; +const context_1 = __nccwpck_require__(94219); +/** + * Probot's transform option, which extends the `event` object that is passed + * to webhook event handlers by `@octokit/webhooks` + * @see https://github.com/octokit/webhooks.js/#constructor + */ +async function webhookTransform(state, event) { + const log = state.log.child({ name: "event", id: event.id }); + const octokit = (await state.octokit.auth({ + type: "event-octokit", + event, + })); + return new context_1.Context(event, octokit, log); +} +exports.webhookTransform = webhookTransform; +//# sourceMappingURL=octokit-webhooks-transform.js.map + +/***/ }), + +/***/ 45351: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ProbotOctokit = void 0; +const core_1 = __nccwpck_require__(76762); +const plugin_enterprise_compatibility_1 = __nccwpck_require__(25823); +const plugin_paginate_rest_1 = __nccwpck_require__(64193); +const plugin_rest_endpoint_methods_1 = __nccwpck_require__(83044); +const plugin_retry_1 = __nccwpck_require__(86298); +const plugin_throttling_1 = __nccwpck_require__(9968); +const octokit_plugin_config_1 = __nccwpck_require__(59326); +const octokit_auth_probot_1 = __nccwpck_require__(80536); +const octokit_plugin_probot_request_logging_1 = __nccwpck_require__(87517); +const version_1 = __nccwpck_require__(23972); +const defaultOptions = { + authStrategy: octokit_auth_probot_1.createProbotAuth, + throttle: { + onAbuseLimit: (retryAfter, options, octokit) => { + octokit.log.warn(`Abuse limit hit with "${options.method} ${options.url}", retrying in ${retryAfter} seconds.`); + return true; + }, + onRateLimit: (retryAfter, options, octokit) => { + octokit.log.warn(`Rate limit hit with "${options.method} ${options.url}", retrying in ${retryAfter} seconds.`); + return true; + }, + }, + userAgent: `probot/${version_1.VERSION}`, +}; +exports.ProbotOctokit = core_1.Octokit.plugin(plugin_throttling_1.throttling, plugin_retry_1.retry, plugin_paginate_rest_1.paginateRest, plugin_rest_endpoint_methods_1.legacyRestEndpointMethods, plugin_enterprise_compatibility_1.enterpriseCompatibility, octokit_plugin_probot_request_logging_1.probotRequestLogging, octokit_plugin_config_1.config).defaults((instanceOptions) => { + // merge throttle options deeply + const options = Object.assign({}, defaultOptions, instanceOptions, { + throttle: instanceOptions.throttle + ? Object.assign({}, defaultOptions.throttle, instanceOptions.throttle) + : defaultOptions.throttle, + }); + return options; +}); +//# sourceMappingURL=probot-octokit.js.map + +/***/ }), + +/***/ 87085: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Probot = void 0; +const lru_cache_1 = __importDefault(__nccwpck_require__(7129)); +const alias_log_1 = __nccwpck_require__(95326); +const auth_1 = __nccwpck_require__(23831); +const get_log_1 = __nccwpck_require__(75942); +const get_probot_octokit_with_defaults_1 = __nccwpck_require__(62543); +const get_webhooks_1 = __nccwpck_require__(92974); +const probot_octokit_1 = __nccwpck_require__(45351); +const version_1 = __nccwpck_require__(23972); +class Probot { + constructor(options = {}) { + options.secret = options.secret || "development"; + let level = options.logLevel; + const logMessageKey = options.logMessageKey; + this.log = alias_log_1.aliasLog(options.log || get_log_1.getLog({ level, logMessageKey })); + // TODO: support redis backend for access token cache if `options.redisConfig` + const cache = new lru_cache_1.default({ + // cache max. 15000 tokens, that will use less than 10mb memory + max: 15000, + // Cache for 1 minute less than GitHub expiry + maxAge: 1000 * 60 * 59, + }); + const Octokit = get_probot_octokit_with_defaults_1.getProbotOctokitWithDefaults({ + githubToken: options.githubToken, + Octokit: options.Octokit || probot_octokit_1.ProbotOctokit, + appId: Number(options.appId), + privateKey: options.privateKey, + cache, + log: this.log, + redisConfig: options.redisConfig, + baseUrl: options.baseUrl, + }); + const octokit = new Octokit(); + this.state = { + cache, + githubToken: options.githubToken, + log: this.log, + Octokit, + octokit, + webhooks: { + secret: options.secret, + }, + appId: Number(options.appId), + privateKey: options.privateKey, + host: options.host, + port: options.port, + }; + this.auth = auth_1.auth.bind(null, this.state); + this.webhooks = get_webhooks_1.getWebhooks(this.state); + this.on = this.webhooks.on; + this.onAny = this.webhooks.onAny; + this.onError = this.webhooks.onError; + this.version = version_1.VERSION; + } + static defaults(defaults) { + const ProbotWithDefaults = class extends this { + constructor(...args) { + const options = args[0] || {}; + super(Object.assign({}, defaults, options)); + } + }; + return ProbotWithDefaults; + } + receive(event) { + this.log.debug({ event }, "Webhook received"); + return this.webhooks.receive(event); + } + async load(appFn) { + if (Array.isArray(appFn)) { + for (const fn of appFn) { + await this.load(fn); + } + return; + } + return appFn(this, {}); + } +} +exports.Probot = Probot; +Probot.version = version_1.VERSION; +//# sourceMappingURL=probot.js.map + +/***/ }), + +/***/ 75611: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.run = void 0; +const pkg_conf_1 = __importDefault(__nccwpck_require__(51235)); +const index_1 = __nccwpck_require__(58930); +const setup_1 = __nccwpck_require__(31078); +const get_log_1 = __nccwpck_require__(75942); +const read_cli_options_1 = __nccwpck_require__(4015); +const read_env_options_1 = __nccwpck_require__(92004); +const server_1 = __nccwpck_require__(93772); +const default_1 = __nccwpck_require__(35362); +const resolve_app_function_1 = __nccwpck_require__(32350); +const is_production_1 = __nccwpck_require__(78079); +/** + * + * @param appFnOrArgv set to either a probot application function: `(app) => { ... }` or to process.argv + */ +async function run(appFnOrArgv, additionalOptions) { + (__nccwpck_require__(12437).config)(); + const envOptions = read_env_options_1.readEnvOptions(additionalOptions === null || additionalOptions === void 0 ? void 0 : additionalOptions.env); + const cliOptions = Array.isArray(appFnOrArgv) + ? read_cli_options_1.readCliOptions(appFnOrArgv) + : {}; + const { + // log options + logLevel: level, logFormat, logLevelInString, logMessageKey, sentryDsn, + // server options + host, port, webhookPath, webhookProxy, + // probot options + appId, privateKey, redisConfig, secret, baseUrl, + // others + args, } = { ...envOptions, ...cliOptions }; + const logOptions = { + level, + logFormat, + logLevelInString, + logMessageKey, + sentryDsn, + }; + const log = get_log_1.getLog(logOptions); + const probotOptions = { + appId, + privateKey, + redisConfig, + secret, + baseUrl, + log: log.child({ name: "probot" }), + }; + const serverOptions = { + host, + port, + webhookPath, + webhookProxy, + log: log.child({ name: "server" }), + Probot: index_1.Probot.defaults(probotOptions), + }; + let server; + if (!appId || !privateKey) { + if (is_production_1.isProduction()) { + if (!appId) { + throw new Error("App ID is missing, and is required to run in production mode. " + + "To resolve, ensure the APP_ID environment variable is set."); + } + else if (!privateKey) { + throw new Error("Certificate is missing, and is required to run in production mode. " + + "To resolve, ensure either the PRIVATE_KEY or PRIVATE_KEY_PATH environment variable is set and contains a valid certificate"); + } + } + // Workaround for setup (#1512) + // When probot is started for the first time, it gets into a setup mode + // where `appId` and `privateKey` are not present. The setup mode gets + // these credentials. In order to not throw an error, we set the values + // to anything, as the Probot instance is not used in setup it makes no + // difference anyway. + server = new server_1.Server({ + ...serverOptions, + Probot: index_1.Probot.defaults({ + ...probotOptions, + appId: 1, + privateKey: "dummy value for setup, see #1512", + }), + }); + await server.load(setup_1.setupAppFactory(host, port)); + await server.start(); + return server; + } + if (Array.isArray(appFnOrArgv)) { + const pkg = await pkg_conf_1.default("probot"); + const combinedApps = async (app) => { + await server.load(default_1.defaultApp); + if (Array.isArray(pkg.apps)) { + for (const appPath of pkg.apps) { + const appFn = await resolve_app_function_1.resolveAppFunction(appPath); + await server.load(appFn); + } + } + const [appPath] = args; + const appFn = await resolve_app_function_1.resolveAppFunction(appPath); + await server.load(appFn); + }; + server = new server_1.Server(serverOptions); + await server.load(combinedApps); + await server.start(); + return server; + } + server = new server_1.Server(serverOptions); + await server.load(appFnOrArgv); + await server.start(); + return server; +} +exports.run = run; +//# sourceMappingURL=run.js.map + +/***/ }), + +/***/ 27530: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getLoggingMiddleware = void 0; +const pino_http_1 = __importDefault(__nccwpck_require__(31778)); +const uuid_1 = __nccwpck_require__(75840); +function getLoggingMiddleware(logger) { + return pino_http_1.default({ + logger: logger.child({ name: "http" }), + customSuccessMessage(res) { + const responseTime = Date.now() - res[pino_http_1.default.startTime]; + // @ts-ignore + return `${res.req.method} ${res.req.url} ${res.statusCode} - ${responseTime}ms`; + }, + customErrorMessage(err, res) { + const responseTime = Date.now() - res[pino_http_1.default.startTime]; + // @ts-ignore + return `${res.req.method} ${res.req.url} ${res.statusCode} - ${responseTime}ms`; + }, + genReqId: (req) => req.headers["x-request-id"] || + req.headers["x-github-delivery"] || + uuid_1.v4(), + }); +} +exports.getLoggingMiddleware = getLoggingMiddleware; +//# sourceMappingURL=logging-middleware.js.map + +/***/ }), + +/***/ 93772: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Server = void 0; +const express_1 = __importStar(__nccwpck_require__(71204)); +const path_1 = __nccwpck_require__(71017); +const webhooks_1 = __nccwpck_require__(18513); +const get_log_1 = __nccwpck_require__(75942); +const logging_middleware_1 = __nccwpck_require__(27530); +const webhook_proxy_1 = __nccwpck_require__(32415); +const version_1 = __nccwpck_require__(23972); +class Server { + constructor(options = {}) { + this.version = version_1.VERSION; + this.expressApp = express_1.default(); + this.log = options.log || get_log_1.getLog().child({ name: "server" }); + this.probotApp = new options.Probot(); + this.state = { + port: options.port, + host: options.host, + webhookPath: options.webhookPath || "/", + webhookProxy: options.webhookProxy, + }; + this.expressApp.use(logging_middleware_1.getLoggingMiddleware(this.log)); + this.expressApp.use("/probot/static/", express_1.default.static(__nccwpck_require__.ab + "static")); + this.expressApp.use(this.state.webhookPath, webhooks_1.createNodeMiddleware(this.probotApp.webhooks, { + path: "/", + })); + this.expressApp.set("view engine", "hbs"); + this.expressApp.set("views", __nccwpck_require__.ab + "views"); + this.expressApp.get("/ping", (req, res) => res.end("PONG")); + } + async load(appFn) { + await appFn(this.probotApp, { + getRouter: (path) => this.router(path), + }); + } + async start() { + this.log.info(`Running Probot v${this.version} (Node.js: ${process.version})`); + const port = this.state.port || 3000; + const { host, webhookPath, webhookProxy } = this.state; + const printableHost = host !== null && host !== void 0 ? host : "localhost"; + this.state.httpServer = (await new Promise((resolve, reject) => { + const server = this.expressApp.listen(port, ...(host ? [host] : []), () => { + if (webhookProxy) { + this.state.eventSource = webhook_proxy_1.createWebhookProxy({ + logger: this.log, + path: webhookPath, + port: port, + url: webhookProxy, + }); + } + this.log.info(`Listening on http://${printableHost}:${port}`); + resolve(server); + }); + server.on("error", (error) => { + if (error.code === "EADDRINUSE") { + error = Object.assign(error, { + message: `Port ${port} is already in use. You can define the PORT environment variable to use a different port.`, + }); + } + this.log.error(error); + reject(error); + }); + })); + return this.state.httpServer; + } + async stop() { + if (this.state.eventSource) + this.state.eventSource.close(); + if (!this.state.httpServer) + return; + const server = this.state.httpServer; + return new Promise((resolve) => server.close(resolve)); + } + router(path = "/") { + const newRouter = express_1.Router(); + this.expressApp.use(path, newRouter); + return newRouter; + } +} +exports.Server = Server; +Server.version = version_1.VERSION; +//# sourceMappingURL=server.js.map + +/***/ }), + +/***/ 23972: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.VERSION = void 0; +// The version is set automatically before publish to npm +exports.VERSION = "12.2.1"; +//# sourceMappingURL=version.js.map + +/***/ }), + +/***/ 18828: +/***/ ((module, exports, __nccwpck_require__) => { + +/** + * Module dependencies. + */ + +const EventEmitter = (__nccwpck_require__(82361).EventEmitter); +const spawn = (__nccwpck_require__(32081).spawn); +const path = __nccwpck_require__(71017); +const fs = __nccwpck_require__(57147); + +// @ts-check + +class Option { + /** + * Initialize a new `Option` with the given `flags` and `description`. + * + * @param {string} flags + * @param {string} description + * @api public + */ + + constructor(flags, description) { + this.flags = flags; + this.required = flags.includes('<'); // A value must be supplied when the option is specified. + this.optional = flags.includes('['); // A value is optional when the option is specified. + // variadic test ignores et al which might be used to describe custom splitting of single argument + this.variadic = /\w\.\.\.[>\]]$/.test(flags); // The option can take multiple values. + this.mandatory = false; // The option must have a value after parsing, which usually means it must be specified on command line. + const optionFlags = _parseOptionFlags(flags); + this.short = optionFlags.shortFlag; + this.long = optionFlags.longFlag; + this.negate = false; + if (this.long) { + this.negate = this.long.startsWith('--no-'); + } + this.description = description || ''; + this.defaultValue = undefined; + } + + /** + * Return option name. + * + * @return {string} + * @api private + */ + + name() { + if (this.long) { + return this.long.replace(/^--/, ''); + } + return this.short.replace(/^-/, ''); + }; + + /** + * Return option name, in a camelcase format that can be used + * as a object attribute key. + * + * @return {string} + * @api private + */ + + attributeName() { + return camelcase(this.name().replace(/^no-/, '')); + }; + + /** + * Check if `arg` matches the short or long flag. + * + * @param {string} arg + * @return {boolean} + * @api private + */ + + is(arg) { + return this.short === arg || this.long === arg; + }; +} + +/** + * CommanderError class + * @class + */ +class CommanderError extends Error { + /** + * Constructs the CommanderError class + * @param {number} exitCode suggested exit code which could be used with process.exit + * @param {string} code an id string representing the error + * @param {string} message human-readable description of the error + * @constructor + */ + constructor(exitCode, code, message) { + super(message); + // properly capture stack trace in Node.js + Error.captureStackTrace(this, this.constructor); + this.name = this.constructor.name; + this.code = code; + this.exitCode = exitCode; + this.nestedError = undefined; + } +} + +class Command extends EventEmitter { + /** + * Initialize a new `Command`. + * + * @param {string} [name] + * @api public + */ + + constructor(name) { + super(); + this.commands = []; + this.options = []; + this.parent = null; + this._allowUnknownOption = false; + this._args = []; + this.rawArgs = null; + this._scriptPath = null; + this._name = name || ''; + this._optionValues = {}; + this._storeOptionsAsProperties = true; // backwards compatible by default + this._storeOptionsAsPropertiesCalled = false; + this._passCommandToAction = true; // backwards compatible by default + this._actionResults = []; + this._actionHandler = null; + this._executableHandler = false; + this._executableFile = null; // custom name for executable + this._defaultCommandName = null; + this._exitCallback = null; + this._aliases = []; + this._combineFlagAndOptionalValue = true; + + this._hidden = false; + this._hasHelpOption = true; + this._helpFlags = '-h, --help'; + this._helpDescription = 'display help for command'; + this._helpShortFlag = '-h'; + this._helpLongFlag = '--help'; + this._hasImplicitHelpCommand = undefined; // Deliberately undefined, not decided whether true or false + this._helpCommandName = 'help'; + this._helpCommandnameAndArgs = 'help [command]'; + this._helpCommandDescription = 'display help for command'; + } + + /** + * Define a command. + * + * There are two styles of command: pay attention to where to put the description. + * + * Examples: + * + * // Command implemented using action handler (description is supplied separately to `.command`) + * program + * .command('clone [destination]') + * .description('clone a repository into a newly created directory') + * .action((source, destination) => { + * console.log('clone command called'); + * }); + * + * // Command implemented using separate executable file (description is second parameter to `.command`) + * program + * .command('start ', 'start named service') + * .command('stop [service]', 'stop named service, or all if no name supplied'); + * + * @param {string} nameAndArgs - command name and arguments, args are `` or `[optional]` and last may also be `variadic...` + * @param {Object|string} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable) + * @param {Object} [execOpts] - configuration options (for executable) + * @return {Command} returns new command for action handler, or `this` for executable command + * @api public + */ + + command(nameAndArgs, actionOptsOrExecDesc, execOpts) { + let desc = actionOptsOrExecDesc; + let opts = execOpts; + if (typeof desc === 'object' && desc !== null) { + opts = desc; + desc = null; + } + opts = opts || {}; + const args = nameAndArgs.split(/ +/); + const cmd = this.createCommand(args.shift()); + + if (desc) { + cmd.description(desc); + cmd._executableHandler = true; + } + if (opts.isDefault) this._defaultCommandName = cmd._name; + + cmd._hidden = !!(opts.noHelp || opts.hidden); + cmd._hasHelpOption = this._hasHelpOption; + cmd._helpFlags = this._helpFlags; + cmd._helpDescription = this._helpDescription; + cmd._helpShortFlag = this._helpShortFlag; + cmd._helpLongFlag = this._helpLongFlag; + cmd._helpCommandName = this._helpCommandName; + cmd._helpCommandnameAndArgs = this._helpCommandnameAndArgs; + cmd._helpCommandDescription = this._helpCommandDescription; + cmd._exitCallback = this._exitCallback; + cmd._storeOptionsAsProperties = this._storeOptionsAsProperties; + cmd._passCommandToAction = this._passCommandToAction; + cmd._combineFlagAndOptionalValue = this._combineFlagAndOptionalValue; + + cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor + this.commands.push(cmd); + cmd._parseExpectedArgs(args); + cmd.parent = this; + + if (desc) return this; + return cmd; + }; + + /** + * Factory routine to create a new unattached command. + * + * See .command() for creating an attached subcommand, which uses this routine to + * create the command. You can override createCommand to customise subcommands. + * + * @param {string} [name] + * @return {Command} new command + * @api public + */ + + createCommand(name) { + return new Command(name); + }; + + /** + * Add a prepared subcommand. + * + * See .command() for creating an attached subcommand which inherits settings from its parent. + * + * @param {Command} cmd - new subcommand + * @param {Object} [opts] - configuration options + * @return {Command} `this` command for chaining + * @api public + */ + + addCommand(cmd, opts) { + if (!cmd._name) throw new Error('Command passed to .addCommand() must have a name'); + + // To keep things simple, block automatic name generation for deeply nested executables. + // Fail fast and detect when adding rather than later when parsing. + function checkExplicitNames(commandArray) { + commandArray.forEach((cmd) => { + if (cmd._executableHandler && !cmd._executableFile) { + throw new Error(`Must specify executableFile for deeply nested executable: ${cmd.name()}`); + } + checkExplicitNames(cmd.commands); + }); + } + checkExplicitNames(cmd.commands); + + opts = opts || {}; + if (opts.isDefault) this._defaultCommandName = cmd._name; + if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation + + this.commands.push(cmd); + cmd.parent = this; + return this; + }; + + /** + * Define argument syntax for the command. + * + * @api public + */ + + arguments(desc) { + return this._parseExpectedArgs(desc.split(/ +/)); + }; + + /** + * Override default decision whether to add implicit help command. + * + * addHelpCommand() // force on + * addHelpCommand(false); // force off + * addHelpCommand('help [cmd]', 'display help for [cmd]'); // force on with custom details + * + * @return {Command} `this` command for chaining + * @api public + */ + + addHelpCommand(enableOrNameAndArgs, description) { + if (enableOrNameAndArgs === false) { + this._hasImplicitHelpCommand = false; + } else { + this._hasImplicitHelpCommand = true; + if (typeof enableOrNameAndArgs === 'string') { + this._helpCommandName = enableOrNameAndArgs.split(' ')[0]; + this._helpCommandnameAndArgs = enableOrNameAndArgs; + } + this._helpCommandDescription = description || this._helpCommandDescription; + } + return this; + }; + + /** + * @return {boolean} + * @api private + */ + + _lazyHasImplicitHelpCommand() { + if (this._hasImplicitHelpCommand === undefined) { + this._hasImplicitHelpCommand = this.commands.length && !this._actionHandler && !this._findCommand('help'); + } + return this._hasImplicitHelpCommand; + }; + + /** + * Parse expected `args`. + * + * For example `["[type]"]` becomes `[{ required: false, name: 'type' }]`. + * + * @param {Array} args + * @return {Command} `this` command for chaining + * @api private + */ + + _parseExpectedArgs(args) { + if (!args.length) return; + args.forEach((arg) => { + const argDetails = { + required: false, + name: '', + variadic: false + }; + + switch (arg[0]) { + case '<': + argDetails.required = true; + argDetails.name = arg.slice(1, -1); + break; + case '[': + argDetails.name = arg.slice(1, -1); + break; + } + + if (argDetails.name.length > 3 && argDetails.name.slice(-3) === '...') { + argDetails.variadic = true; + argDetails.name = argDetails.name.slice(0, -3); + } + if (argDetails.name) { + this._args.push(argDetails); + } + }); + this._args.forEach((arg, i) => { + if (arg.variadic && i < this._args.length - 1) { + throw new Error(`only the last argument can be variadic '${arg.name}'`); + } + }); + return this; + }; + + /** + * Register callback to use as replacement for calling process.exit. + * + * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing + * @return {Command} `this` command for chaining + * @api public + */ + + exitOverride(fn) { + if (fn) { + this._exitCallback = fn; + } else { + this._exitCallback = (err) => { + if (err.code !== 'commander.executeSubCommandAsync') { + throw err; + } else { + // Async callback from spawn events, not useful to throw. + } + }; + } + return this; + }; + + /** + * Call process.exit, and _exitCallback if defined. + * + * @param {number} exitCode exit code for using with process.exit + * @param {string} code an id string representing the error + * @param {string} message human-readable description of the error + * @return never + * @api private + */ + + _exit(exitCode, code, message) { + if (this._exitCallback) { + this._exitCallback(new CommanderError(exitCode, code, message)); + // Expecting this line is not reached. + } + process.exit(exitCode); + }; + + /** + * Register callback `fn` for the command. + * + * Examples: + * + * program + * .command('help') + * .description('display verbose help') + * .action(function() { + * // output help here + * }); + * + * @param {Function} fn + * @return {Command} `this` command for chaining + * @api public + */ + + action(fn) { + const listener = (args) => { + // The .action callback takes an extra parameter which is the command or options. + const expectedArgsCount = this._args.length; + const actionArgs = args.slice(0, expectedArgsCount); + if (this._passCommandToAction) { + actionArgs[expectedArgsCount] = this; + } else { + actionArgs[expectedArgsCount] = this.opts(); + } + // Add the extra arguments so available too. + if (args.length > expectedArgsCount) { + actionArgs.push(args.slice(expectedArgsCount)); + } + + const actionResult = fn.apply(this, actionArgs); + // Remember result in case it is async. Assume parseAsync getting called on root. + let rootCommand = this; + while (rootCommand.parent) { + rootCommand = rootCommand.parent; + } + rootCommand._actionResults.push(actionResult); + }; + this._actionHandler = listener; + return this; + }; + + /** + * Internal routine to check whether there is a clash storing option value with a Command property. + * + * @param {Option} option + * @api private + */ + + _checkForOptionNameClash(option) { + if (!this._storeOptionsAsProperties || this._storeOptionsAsPropertiesCalled) { + // Storing options safely, or user has been explicit and up to them. + return; + } + // User may override help, and hard to tell if worth warning. + if (option.name() === 'help') { + return; + } + + const commandProperty = this._getOptionValue(option.attributeName()); + if (commandProperty === undefined) { + // no clash + return; + } + + let foundClash = true; + if (option.negate) { + // It is ok if define foo before --no-foo. + const positiveLongFlag = option.long.replace(/^--no-/, '--'); + foundClash = !this._findOption(positiveLongFlag); + } else if (option.long) { + const negativeLongFlag = option.long.replace(/^--/, '--no-'); + foundClash = !this._findOption(negativeLongFlag); + } + + if (foundClash) { + throw new Error(`option '${option.name()}' clashes with existing property '${option.attributeName()}' on Command +- call storeOptionsAsProperties(false) to store option values safely, +- or call storeOptionsAsProperties(true) to suppress this check, +- or change option name + +Read more on https://git.io/JJc0W`); + } + }; + + /** + * Internal implementation shared by .option() and .requiredOption() + * + * @param {Object} config + * @param {string} flags + * @param {string} description + * @param {Function|*} [fn] - custom option processing function or default value + * @param {*} [defaultValue] + * @return {Command} `this` command for chaining + * @api private + */ + + _optionEx(config, flags, description, fn, defaultValue) { + const option = new Option(flags, description); + const oname = option.name(); + const name = option.attributeName(); + option.mandatory = !!config.mandatory; + + this._checkForOptionNameClash(option); + + // default as 3rd arg + if (typeof fn !== 'function') { + if (fn instanceof RegExp) { + // This is a bit simplistic (especially no error messages), and probably better handled by caller using custom option processing. + // No longer documented in README, but still present for backwards compatibility. + const regex = fn; + fn = (val, def) => { + const m = regex.exec(val); + return m ? m[0] : def; + }; + } else { + defaultValue = fn; + fn = null; + } + } + + // preassign default value for --no-*, [optional], , or plain flag if boolean value + if (option.negate || option.optional || option.required || typeof defaultValue === 'boolean') { + // when --no-foo we make sure default is true, unless a --foo option is already defined + if (option.negate) { + const positiveLongFlag = option.long.replace(/^--no-/, '--'); + defaultValue = this._findOption(positiveLongFlag) ? this._getOptionValue(name) : true; + } + // preassign only if we have a default + if (defaultValue !== undefined) { + this._setOptionValue(name, defaultValue); + option.defaultValue = defaultValue; + } + } + + // register the option + this.options.push(option); + + // when it's passed assign the value + // and conditionally invoke the callback + this.on('option:' + oname, (val) => { + const oldValue = this._getOptionValue(name); + + // custom processing + if (val !== null && fn) { + val = fn(val, oldValue === undefined ? defaultValue : oldValue); + } else if (val !== null && option.variadic) { + if (oldValue === defaultValue || !Array.isArray(oldValue)) { + val = [val]; + } else { + val = oldValue.concat(val); + } + } + + // unassigned or boolean value + if (typeof oldValue === 'boolean' || typeof oldValue === 'undefined') { + // if no value, negate false, and we have a default, then use it! + if (val == null) { + this._setOptionValue(name, option.negate + ? false + : defaultValue || true); + } else { + this._setOptionValue(name, val); + } + } else if (val !== null) { + // reassign + this._setOptionValue(name, option.negate ? false : val); + } + }); + + return this; + }; + + /** + * Define option with `flags`, `description` and optional + * coercion `fn`. + * + * The `flags` string should contain both the short and long flags, + * separated by comma, a pipe or space. The following are all valid + * all will output this way when `--help` is used. + * + * "-p, --pepper" + * "-p|--pepper" + * "-p --pepper" + * + * Examples: + * + * // simple boolean defaulting to undefined + * program.option('-p, --pepper', 'add pepper'); + * + * program.pepper + * // => undefined + * + * --pepper + * program.pepper + * // => true + * + * // simple boolean defaulting to true (unless non-negated option is also defined) + * program.option('-C, --no-cheese', 'remove cheese'); + * + * program.cheese + * // => true + * + * --no-cheese + * program.cheese + * // => false + * + * // required argument + * program.option('-C, --chdir ', 'change the working directory'); + * + * --chdir /tmp + * program.chdir + * // => "/tmp" + * + * // optional argument + * program.option('-c, --cheese [type]', 'add cheese [marble]'); + * + * @param {string} flags + * @param {string} description + * @param {Function|*} [fn] - custom option processing function or default value + * @param {*} [defaultValue] + * @return {Command} `this` command for chaining + * @api public + */ + + option(flags, description, fn, defaultValue) { + return this._optionEx({}, flags, description, fn, defaultValue); + }; + + /** + * Add a required option which must have a value after parsing. This usually means + * the option must be specified on the command line. (Otherwise the same as .option().) + * + * The `flags` string should contain both the short and long flags, separated by comma, a pipe or space. + * + * @param {string} flags + * @param {string} description + * @param {Function|*} [fn] - custom option processing function or default value + * @param {*} [defaultValue] + * @return {Command} `this` command for chaining + * @api public + */ + + requiredOption(flags, description, fn, defaultValue) { + return this._optionEx({ mandatory: true }, flags, description, fn, defaultValue); + }; + + /** + * Alter parsing of short flags with optional values. + * + * Examples: + * + * // for `.option('-f,--flag [value]'): + * .combineFlagAndOptionalValue(true) // `-f80` is treated like `--flag=80`, this is the default behaviour + * .combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b` + * + * @param {Boolean} [arg] - if `true` or omitted, an optional value can be specified directly after the flag. + * @api public + */ + combineFlagAndOptionalValue(arg) { + this._combineFlagAndOptionalValue = (arg === undefined) || arg; + return this; + }; + + /** + * Allow unknown options on the command line. + * + * @param {Boolean} [arg] - if `true` or omitted, no error will be thrown + * for unknown options. + * @api public + */ + allowUnknownOption(arg) { + this._allowUnknownOption = (arg === undefined) || arg; + return this; + }; + + /** + * Whether to store option values as properties on command object, + * or store separately (specify false). In both cases the option values can be accessed using .opts(). + * + * @param {boolean} value + * @return {Command} `this` command for chaining + * @api public + */ + + storeOptionsAsProperties(value) { + this._storeOptionsAsPropertiesCalled = true; + this._storeOptionsAsProperties = (value === undefined) || value; + if (this.options.length) { + throw new Error('call .storeOptionsAsProperties() before adding options'); + } + return this; + }; + + /** + * Whether to pass command to action handler, + * or just the options (specify false). + * + * @param {boolean} value + * @return {Command} `this` command for chaining + * @api public + */ + + passCommandToAction(value) { + this._passCommandToAction = (value === undefined) || value; + return this; + }; + + /** + * Store option value + * + * @param {string} key + * @param {Object} value + * @api private + */ + + _setOptionValue(key, value) { + if (this._storeOptionsAsProperties) { + this[key] = value; + } else { + this._optionValues[key] = value; + } + }; + + /** + * Retrieve option value + * + * @param {string} key + * @return {Object} value + * @api private + */ + + _getOptionValue(key) { + if (this._storeOptionsAsProperties) { + return this[key]; + } + return this._optionValues[key]; + }; + + /** + * Parse `argv`, setting options and invoking commands when defined. + * + * The default expectation is that the arguments are from node and have the application as argv[0] + * and the script being run in argv[1], with user parameters after that. + * + * Examples: + * + * program.parse(process.argv); + * program.parse(); // implicitly use process.argv and auto-detect node vs electron conventions + * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0] + * + * @param {string[]} [argv] - optional, defaults to process.argv + * @param {Object} [parseOptions] - optionally specify style of options with from: node/user/electron + * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron' + * @return {Command} `this` command for chaining + * @api public + */ + + parse(argv, parseOptions) { + if (argv !== undefined && !Array.isArray(argv)) { + throw new Error('first parameter to parse must be array or undefined'); + } + parseOptions = parseOptions || {}; + + // Default to using process.argv + if (argv === undefined) { + argv = process.argv; + // @ts-ignore + if (process.versions && process.versions.electron) { + parseOptions.from = 'electron'; + } + } + this.rawArgs = argv.slice(); + + // make it a little easier for callers by supporting various argv conventions + let userArgs; + switch (parseOptions.from) { + case undefined: + case 'node': + this._scriptPath = argv[1]; + userArgs = argv.slice(2); + break; + case 'electron': + // @ts-ignore + if (process.defaultApp) { + this._scriptPath = argv[1]; + userArgs = argv.slice(2); + } else { + userArgs = argv.slice(1); + } + break; + case 'user': + userArgs = argv.slice(0); + break; + default: + throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`); + } + if (!this._scriptPath && process.mainModule) { + this._scriptPath = process.mainModule.filename; + } + + // Guess name, used in usage in help. + this._name = this._name || (this._scriptPath && path.basename(this._scriptPath, path.extname(this._scriptPath))); + + // Let's go! + this._parseCommand([], userArgs); + + return this; + }; + + /** + * Parse `argv`, setting options and invoking commands when defined. + * + * Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise. + * + * The default expectation is that the arguments are from node and have the application as argv[0] + * and the script being run in argv[1], with user parameters after that. + * + * Examples: + * + * program.parseAsync(process.argv); + * program.parseAsync(); // implicitly use process.argv and auto-detect node vs electron conventions + * program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0] + * + * @param {string[]} [argv] + * @param {Object} [parseOptions] + * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron' + * @return {Promise} + * @api public + */ + + parseAsync(argv, parseOptions) { + this.parse(argv, parseOptions); + return Promise.all(this._actionResults).then(() => this); + }; + + /** + * Execute a sub-command executable. + * + * @api private + */ + + _executeSubCommand(subcommand, args) { + args = args.slice(); + let launchWithNode = false; // Use node for source targets so do not need to get permissions correct, and on Windows. + const sourceExt = ['.js', '.ts', '.tsx', '.mjs']; + + // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command. + this._checkForMissingMandatoryOptions(); + + // Want the entry script as the reference for command name and directory for searching for other files. + let scriptPath = this._scriptPath; + // Fallback in case not set, due to how Command created or called. + if (!scriptPath && process.mainModule) { + scriptPath = process.mainModule.filename; + } + + let baseDir; + try { + const resolvedLink = fs.realpathSync(scriptPath); + baseDir = path.dirname(resolvedLink); + } catch (e) { + baseDir = '.'; // dummy, probably not going to find executable! + } + + // name of the subcommand, like `pm-install` + let bin = path.basename(scriptPath, path.extname(scriptPath)) + '-' + subcommand._name; + if (subcommand._executableFile) { + bin = subcommand._executableFile; + } + + const localBin = path.join(baseDir, bin); + if (fs.existsSync(localBin)) { + // prefer local `./` to bin in the $PATH + bin = localBin; + } else { + // Look for source files. + sourceExt.forEach((ext) => { + if (fs.existsSync(`${localBin}${ext}`)) { + bin = `${localBin}${ext}`; + } + }); + } + launchWithNode = sourceExt.includes(path.extname(bin)); + + let proc; + if (process.platform !== 'win32') { + if (launchWithNode) { + args.unshift(bin); + // add executable arguments to spawn + args = incrementNodeInspectorPort(process.execArgv).concat(args); + + proc = spawn(process.argv[0], args, { stdio: 'inherit' }); + } else { + proc = spawn(bin, args, { stdio: 'inherit' }); + } + } else { + args.unshift(bin); + // add executable arguments to spawn + args = incrementNodeInspectorPort(process.execArgv).concat(args); + proc = spawn(process.execPath, args, { stdio: 'inherit' }); + } + + const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP']; + signals.forEach((signal) => { + // @ts-ignore + process.on(signal, () => { + if (proc.killed === false && proc.exitCode === null) { + proc.kill(signal); + } + }); + }); + + // By default terminate process when spawned process terminates. + // Suppressing the exit if exitCallback defined is a bit messy and of limited use, but does allow process to stay running! + const exitCallback = this._exitCallback; + if (!exitCallback) { + proc.on('close', process.exit.bind(process)); + } else { + proc.on('close', () => { + exitCallback(new CommanderError(process.exitCode || 0, 'commander.executeSubCommandAsync', '(close)')); + }); + } + proc.on('error', (err) => { + // @ts-ignore + if (err.code === 'ENOENT') { + const executableMissing = `'${bin}' does not exist + - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead + - if the default executable name is not suitable, use the executableFile option to supply a custom name`; + throw new Error(executableMissing); + // @ts-ignore + } else if (err.code === 'EACCES') { + throw new Error(`'${bin}' not executable`); + } + if (!exitCallback) { + process.exit(1); + } else { + const wrappedError = new CommanderError(1, 'commander.executeSubCommandAsync', '(error)'); + wrappedError.nestedError = err; + exitCallback(wrappedError); + } + }); + + // Store the reference to the child process + this.runningCommand = proc; + }; + + /** + * @api private + */ + _dispatchSubcommand(commandName, operands, unknown) { + const subCommand = this._findCommand(commandName); + if (!subCommand) this._helpAndError(); + + if (subCommand._executableHandler) { + this._executeSubCommand(subCommand, operands.concat(unknown)); + } else { + subCommand._parseCommand(operands, unknown); + } + }; + + /** + * Process arguments in context of this command. + * + * @api private + */ + + _parseCommand(operands, unknown) { + const parsed = this.parseOptions(unknown); + operands = operands.concat(parsed.operands); + unknown = parsed.unknown; + this.args = operands.concat(unknown); + + if (operands && this._findCommand(operands[0])) { + this._dispatchSubcommand(operands[0], operands.slice(1), unknown); + } else if (this._lazyHasImplicitHelpCommand() && operands[0] === this._helpCommandName) { + if (operands.length === 1) { + this.help(); + } else { + this._dispatchSubcommand(operands[1], [], [this._helpLongFlag]); + } + } else if (this._defaultCommandName) { + outputHelpIfRequested(this, unknown); // Run the help for default command from parent rather than passing to default command + this._dispatchSubcommand(this._defaultCommandName, operands, unknown); + } else { + if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) { + // probably missing subcommand and no handler, user needs help + this._helpAndError(); + } + + outputHelpIfRequested(this, parsed.unknown); + this._checkForMissingMandatoryOptions(); + if (parsed.unknown.length > 0) { + this.unknownOption(parsed.unknown[0]); + } + + if (this._actionHandler) { + const args = this.args.slice(); + this._args.forEach((arg, i) => { + if (arg.required && args[i] == null) { + this.missingArgument(arg.name); + } else if (arg.variadic) { + args[i] = args.splice(i); + } + }); + + this._actionHandler(args); + this.emit('command:' + this.name(), operands, unknown); + } else if (operands.length) { + if (this._findCommand('*')) { + this._dispatchSubcommand('*', operands, unknown); + } else if (this.listenerCount('command:*')) { + this.emit('command:*', operands, unknown); + } else if (this.commands.length) { + this.unknownCommand(); + } + } else if (this.commands.length) { + // This command has subcommands and nothing hooked up at this level, so display help. + this._helpAndError(); + } else { + // fall through for caller to handle after calling .parse() + } + } + }; + + /** + * Find matching command. + * + * @api private + */ + _findCommand(name) { + if (!name) return undefined; + return this.commands.find(cmd => cmd._name === name || cmd._aliases.includes(name)); + }; + + /** + * Return an option matching `arg` if any. + * + * @param {string} arg + * @return {Option} + * @api private + */ + + _findOption(arg) { + return this.options.find(option => option.is(arg)); + }; + + /** + * Display an error message if a mandatory option does not have a value. + * Lazy calling after checking for help flags from leaf subcommand. + * + * @api private + */ + + _checkForMissingMandatoryOptions() { + // Walk up hierarchy so can call in subcommand after checking for displaying help. + for (let cmd = this; cmd; cmd = cmd.parent) { + cmd.options.forEach((anOption) => { + if (anOption.mandatory && (cmd._getOptionValue(anOption.attributeName()) === undefined)) { + cmd.missingMandatoryOptionValue(anOption); + } + }); + } + }; + + /** + * Parse options from `argv` removing known options, + * and return argv split into operands and unknown arguments. + * + * Examples: + * + * argv => operands, unknown + * --known kkk op => [op], [] + * op --known kkk => [op], [] + * sub --unknown uuu op => [sub], [--unknown uuu op] + * sub -- --unknown uuu op => [sub --unknown uuu op], [] + * + * @param {String[]} argv + * @return {{operands: String[], unknown: String[]}} + * @api public + */ + + parseOptions(argv) { + const operands = []; // operands, not options or values + const unknown = []; // first unknown option and remaining unknown args + let dest = operands; + const args = argv.slice(); + + function maybeOption(arg) { + return arg.length > 1 && arg[0] === '-'; + } + + // parse options + let activeVariadicOption = null; + while (args.length) { + const arg = args.shift(); + + // literal + if (arg === '--') { + if (dest === unknown) dest.push(arg); + dest.push(...args); + break; + } + + if (activeVariadicOption && !maybeOption(arg)) { + this.emit(`option:${activeVariadicOption.name()}`, arg); + continue; + } + activeVariadicOption = null; + + if (maybeOption(arg)) { + const option = this._findOption(arg); + // recognised option, call listener to assign value with possible custom processing + if (option) { + if (option.required) { + const value = args.shift(); + if (value === undefined) this.optionMissingArgument(option); + this.emit(`option:${option.name()}`, value); + } else if (option.optional) { + let value = null; + // historical behaviour is optional value is following arg unless an option + if (args.length > 0 && !maybeOption(args[0])) { + value = args.shift(); + } + this.emit(`option:${option.name()}`, value); + } else { // boolean flag + this.emit(`option:${option.name()}`); + } + activeVariadicOption = option.variadic ? option : null; + continue; + } + } + + // Look for combo options following single dash, eat first one if known. + if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') { + const option = this._findOption(`-${arg[1]}`); + if (option) { + if (option.required || (option.optional && this._combineFlagAndOptionalValue)) { + // option with value following in same argument + this.emit(`option:${option.name()}`, arg.slice(2)); + } else { + // boolean option, emit and put back remainder of arg for further processing + this.emit(`option:${option.name()}`); + args.unshift(`-${arg.slice(2)}`); + } + continue; + } + } + + // Look for known long flag with value, like --foo=bar + if (/^--[^=]+=/.test(arg)) { + const index = arg.indexOf('='); + const option = this._findOption(arg.slice(0, index)); + if (option && (option.required || option.optional)) { + this.emit(`option:${option.name()}`, arg.slice(index + 1)); + continue; + } + } + + // looks like an option but unknown, unknowns from here + if (arg.length > 1 && arg[0] === '-') { + dest = unknown; + } + + // add arg + dest.push(arg); + } + + return { operands, unknown }; + }; + + /** + * Return an object containing options as key-value pairs + * + * @return {Object} + * @api public + */ + opts() { + if (this._storeOptionsAsProperties) { + // Preserve original behaviour so backwards compatible when still using properties + const result = {}; + const len = this.options.length; + + for (let i = 0; i < len; i++) { + const key = this.options[i].attributeName(); + result[key] = key === this._versionOptionName ? this._version : this[key]; + } + return result; + } + + return this._optionValues; + }; + + /** + * Argument `name` is missing. + * + * @param {string} name + * @api private + */ + + missingArgument(name) { + const message = `error: missing required argument '${name}'`; + console.error(message); + this._exit(1, 'commander.missingArgument', message); + }; + + /** + * `Option` is missing an argument, but received `flag` or nothing. + * + * @param {Option} option + * @param {string} [flag] + * @api private + */ + + optionMissingArgument(option, flag) { + let message; + if (flag) { + message = `error: option '${option.flags}' argument missing, got '${flag}'`; + } else { + message = `error: option '${option.flags}' argument missing`; + } + console.error(message); + this._exit(1, 'commander.optionMissingArgument', message); + }; + + /** + * `Option` does not have a value, and is a mandatory option. + * + * @param {Option} option + * @api private + */ + + missingMandatoryOptionValue(option) { + const message = `error: required option '${option.flags}' not specified`; + console.error(message); + this._exit(1, 'commander.missingMandatoryOptionValue', message); + }; + + /** + * Unknown option `flag`. + * + * @param {string} flag + * @api private + */ + + unknownOption(flag) { + if (this._allowUnknownOption) return; + const message = `error: unknown option '${flag}'`; + console.error(message); + this._exit(1, 'commander.unknownOption', message); + }; + + /** + * Unknown command. + * + * @api private + */ + + unknownCommand() { + const partCommands = [this.name()]; + for (let parentCmd = this.parent; parentCmd; parentCmd = parentCmd.parent) { + partCommands.unshift(parentCmd.name()); + } + const fullCommand = partCommands.join(' '); + const message = `error: unknown command '${this.args[0]}'.` + + (this._hasHelpOption ? ` See '${fullCommand} ${this._helpLongFlag}'.` : ''); + console.error(message); + this._exit(1, 'commander.unknownCommand', message); + }; + + /** + * Set the program version to `str`. + * + * This method auto-registers the "-V, --version" flag + * which will print the version number when passed. + * + * You can optionally supply the flags and description to override the defaults. + * + * @param {string} str + * @param {string} [flags] + * @param {string} [description] + * @return {this | string} `this` command for chaining, or version string if no arguments + * @api public + */ + + version(str, flags, description) { + if (str === undefined) return this._version; + this._version = str; + flags = flags || '-V, --version'; + description = description || 'output the version number'; + const versionOption = new Option(flags, description); + this._versionOptionName = versionOption.attributeName(); + this.options.push(versionOption); + this.on('option:' + versionOption.name(), () => { + process.stdout.write(str + '\n'); + this._exit(0, 'commander.version', str); + }); + return this; + }; -/***/ }), + /** + * Set the description to `str`. + * + * @param {string} str + * @param {Object} [argsDescription] + * @return {string|Command} + * @api public + */ -/***/ 25625: -/***/ ((__unused_webpack_module, exports) => { + description(str, argsDescription) { + if (str === undefined && argsDescription === undefined) return this._description; + this._description = str; + this._argsDescription = argsDescription; + return this; + }; -"use strict"; + /** + * Set an alias for the command. + * + * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help. + * + * @param {string} [alias] + * @return {string|Command} + * @api public + */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getErrorHandler = void 0; -function getErrorHandler(log) { - return (error) => { - const errors = (error.name === "AggregateError" ? error : [error]); - const event = error.event; - for (const error of errors) { - const errMessage = (error.message || "").toLowerCase(); - if (errMessage.includes("x-hub-signature-256")) { - log.error(error, "Go to https://github.com/settings/apps/YOUR_APP and verify that the Webhook secret matches the value of the WEBHOOK_SECRET environment variable."); - continue; - } - if (errMessage.includes("pem") || errMessage.includes("json web token")) { - log.error(error, "Your private key (a .pem file or PRIVATE_KEY environment variable) or APP_ID is incorrect. Go to https://github.com/settings/apps/YOUR_APP, verify that APP_ID is set correctly, and generate a new PEM file if necessary."); - continue; - } - log - .child({ - name: "event", - id: event ? event.id : undefined, - }) - .error(error); - } - }; -} -exports.getErrorHandler = getErrorHandler; -//# sourceMappingURL=get-error-handler.js.map + alias(alias) { + if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility -/***/ }), + let command = this; + if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) { + // assume adding alias for last added executable subcommand, rather than this + command = this.commands[this.commands.length - 1]; + } -/***/ 75942: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + if (alias === command._name) throw new Error('Command alias can\'t be the same as its name'); -"use strict"; + command._aliases.push(alias); + return this; + }; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getLog = void 0; -/** - * A logger backed by [pino](https://getpino.io/) - * - * The default log level is `info`, but you can change it passing a level - * string set to one of: `"trace"`, `"debug"`, `"info"`, `"warn"`, - * `"error"`, or `"fatal"`. - * - * ```js - * app.log.debug("…so is this"); - * app.log.trace("Now we're talking"); - * app.log.info("I thought you should know…"); - * app.log.warn("Woah there"); - * app.log.error("ETOOMANYLOGS"); - * app.log.fatal("Goodbye, cruel world!"); - * ``` - */ -const pino_1 = __importDefault(__nccwpck_require__(79608)); -const pino_2 = __nccwpck_require__(39662); -function getLog(options = {}) { - const { level, logMessageKey, ...getTransformStreamOptions } = options; - const pinoOptions = { - level: level || "info", - name: "probot", - messageKey: logMessageKey || "msg", - }; - const transform = pino_2.getTransformStream(getTransformStreamOptions); - // @ts-ignore TODO: check out what's wrong here - transform.pipe(pino_1.default.destination(1)); - const log = pino_1.default(pinoOptions, transform); - return log; -} -exports.getLog = getLog; -//# sourceMappingURL=get-log.js.map + /** + * Set aliases for the command. + * + * Only the first alias is shown in the auto-generated help. + * + * @param {string[]} [aliases] + * @return {string[]|Command} + * @api public + */ -/***/ }), + aliases(aliases) { + // Getter for the array of aliases is the main reason for having aliases() in addition to alias(). + if (aliases === undefined) return this._aliases; -/***/ 78079: -/***/ ((__unused_webpack_module, exports) => { + aliases.forEach((alias) => this.alias(alias)); + return this; + }; -"use strict"; + /** + * Set / get the command usage `str`. + * + * @param {string} [str] + * @return {String|Command} + * @api public + */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.isProduction = void 0; -function isProduction() { - return process.env.NODE_ENV === "production"; -} -exports.isProduction = isProduction; -//# sourceMappingURL=is-production.js.map + usage(str) { + if (str === undefined) { + if (this._usage) return this._usage; -/***/ }), + const args = this._args.map((arg) => { + return humanReadableArgName(arg); + }); + return [].concat( + (this.options.length || this._hasHelpOption ? '[options]' : []), + (this.commands.length ? '[command]' : []), + (this._args.length ? args : []) + ).join(' '); + } -/***/ 32350: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + this._usage = str; + return this; + }; -"use strict"; + /** + * Get or set the name of the command + * + * @param {string} [str] + * @return {String|Command} + * @api public + */ -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.resolveAppFunction = void 0; -const resolve_1 = __nccwpck_require__(39283); -const defaultOptions = {}; -const resolveAppFunction = async (appFnId, opts) => { - opts = opts || defaultOptions; - // These are mostly to ease testing - const basedir = opts.basedir || process.cwd(); - const resolver = opts.resolver || resolve_1.sync; - const appFnPath = resolver(appFnId, { basedir }); - const mod = await Promise.resolve().then(() => __importStar(require(appFnPath))); - // Note: This needs "esModuleInterop" to be set to "true" in "tsconfig.json" - return mod.default; -}; -exports.resolveAppFunction = resolveAppFunction; -//# sourceMappingURL=resolve-app-function.js.map + name(str) { + if (str === undefined) return this._name; + this._name = str; + return this; + }; -/***/ }), + /** + * Return prepared commands. + * + * @return {Array} + * @api private + */ -/***/ 32415: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + prepareCommands() { + const commandDetails = this.commands.filter((cmd) => { + return !cmd._hidden; + }).map((cmd) => { + const args = cmd._args.map((arg) => { + return humanReadableArgName(arg); + }).join(' '); -"use strict"; + return [ + cmd._name + + (cmd._aliases[0] ? '|' + cmd._aliases[0] : '') + + (cmd.options.length ? ' [options]' : '') + + (args ? ' ' + args : ''), + cmd._description + ]; + }); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.createWebhookProxy = void 0; -const createWebhookProxy = (opts) => { - try { - const SmeeClient = __nccwpck_require__(24807); - const smee = new SmeeClient({ - logger: opts.logger, - source: opts.url, - target: `http://localhost:${opts.port}${opts.path}`, - }); - return smee.start(); - } - catch (error) { - opts.logger.warn("Run `npm install --save-dev smee-client` to proxy webhooks to localhost."); - return; + if (this._lazyHasImplicitHelpCommand()) { + commandDetails.push([this._helpCommandnameAndArgs, this._helpCommandDescription]); } -}; -exports.createWebhookProxy = createWebhookProxy; -//# sourceMappingURL=webhook-proxy.js.map + return commandDetails; + }; -/***/ }), + /** + * Return the largest command length. + * + * @return {number} + * @api private + */ -/***/ 58930: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + largestCommandLength() { + const commands = this.prepareCommands(); + return commands.reduce((max, command) => { + return Math.max(max, command[0].length); + }, 0); + }; -"use strict"; + /** + * Return the largest option length. + * + * @return {number} + * @api private + */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.createProbot = exports.createNodeMiddleware = exports.Server = exports.Probot = exports.run = exports.ProbotOctokit = exports.Context = void 0; -const context_1 = __nccwpck_require__(94219); -Object.defineProperty(exports, "Context", ({ enumerable: true, get: function () { return context_1.Context; } })); -const probot_1 = __nccwpck_require__(87085); -Object.defineProperty(exports, "Probot", ({ enumerable: true, get: function () { return probot_1.Probot; } })); -const server_1 = __nccwpck_require__(93772); -Object.defineProperty(exports, "Server", ({ enumerable: true, get: function () { return server_1.Server; } })); -const probot_octokit_1 = __nccwpck_require__(45351); -Object.defineProperty(exports, "ProbotOctokit", ({ enumerable: true, get: function () { return probot_octokit_1.ProbotOctokit; } })); -const run_1 = __nccwpck_require__(75611); -Object.defineProperty(exports, "run", ({ enumerable: true, get: function () { return run_1.run; } })); -const create_node_middleware_1 = __nccwpck_require__(95960); -Object.defineProperty(exports, "createNodeMiddleware", ({ enumerable: true, get: function () { return create_node_middleware_1.createNodeMiddleware; } })); -const create_probot_1 = __nccwpck_require__(82598); -Object.defineProperty(exports, "createProbot", ({ enumerable: true, get: function () { return create_probot_1.createProbot; } })); -//# sourceMappingURL=index.js.map + largestOptionLength() { + const options = [].slice.call(this.options); + options.push({ + flags: this._helpFlags + }); -/***/ }), + return options.reduce((max, option) => { + return Math.max(max, option.flags.length); + }, 0); + }; -/***/ 59159: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + /** + * Return the largest arg length. + * + * @return {number} + * @api private + */ -"use strict"; + largestArgLength() { + return this._args.reduce((max, arg) => { + return Math.max(max, arg.name.length); + }, 0); + }; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ManifestCreation = void 0; -const fs_1 = __importDefault(__nccwpck_require__(57147)); -const js_yaml_1 = __importDefault(__nccwpck_require__(695)); -const path_1 = __importDefault(__nccwpck_require__(71017)); -const update_dotenv_1 = __importDefault(__nccwpck_require__(51023)); -const probot_octokit_1 = __nccwpck_require__(45351); -class ManifestCreation { - get pkg() { - let pkg; - try { - pkg = require(path_1.default.join(process.cwd(), "package.json")); - } - catch (e) { - pkg = {}; - } - return pkg; - } - async createWebhookChannel() { - try { - // tslint:disable:no-var-requires - const SmeeClient = __nccwpck_require__(24807); - await this.updateEnv({ - WEBHOOK_PROXY_URL: await SmeeClient.createChannel(), - }); - } - catch (error) { - // Smee is not available, so we'll just move on - // tslint:disable:no-console - console.warn("Unable to connect to smee.io, try restarting your server."); - } - } - getManifest(pkg, baseUrl) { - let manifest = {}; - try { - const file = fs_1.default.readFileSync(path_1.default.join(process.cwd(), "app.yml"), "utf8"); - manifest = js_yaml_1.default.safeLoad(file); - } - catch (error) { - // App config does not exist, which is ok. - if (error.code !== "ENOENT") { - throw error; - } - } - const generatedManifest = JSON.stringify(Object.assign({ - description: manifest.description || pkg.description, - hook_attributes: { - url: process.env.WEBHOOK_PROXY_URL || `${baseUrl}/`, - }, - name: process.env.PROJECT_DOMAIN || manifest.name || pkg.name, - public: manifest.public || true, - redirect_url: `${baseUrl}/probot/setup`, - // TODO: add setup url - // setup_url:`${baseUrl}/probot/success`, - url: manifest.url || pkg.homepage || pkg.repository, - version: "v1", - }, manifest)); - return generatedManifest; - } - async createAppFromCode(code) { - const octokit = new probot_octokit_1.ProbotOctokit(); - const options = { - code, - mediaType: { - previews: ["fury"], // needed for GHES 2.20 and older - }, - ...(process.env.GHE_HOST && { - baseUrl: `${process.env.GHE_PROTOCOL || "https"}://${process.env.GHE_HOST}/api/v3`, - }), - }; - const response = await octokit.request("POST /app-manifests/:code/conversions", options); - const { id, client_id, client_secret, webhook_secret, pem } = response.data; - await this.updateEnv({ - APP_ID: id.toString(), - PRIVATE_KEY: `"${pem}"`, - WEBHOOK_SECRET: webhook_secret, - GITHUB_CLIENT_ID: client_id, - GITHUB_CLIENT_SECRET: client_secret, - }); - return response.data.html_url; - } - async updateEnv(env) { - // Needs to be public due to tests - return update_dotenv_1.default(env); - } - get createAppUrl() { - const githubHost = process.env.GHE_HOST || `github.com`; - return `${process.env.GHE_PROTOCOL || "https"}://${githubHost}${process.env.GH_ORG ? "/organizations/".concat(process.env.GH_ORG) : ""}/settings/apps/new`; - } -} -exports.ManifestCreation = ManifestCreation; -//# sourceMappingURL=manifest-creation.js.map + /** + * Return the pad width. + * + * @return {number} + * @api private + */ -/***/ }), + padWidth() { + let width = this.largestOptionLength(); + if (this._argsDescription && this._args.length) { + if (this.largestArgLength() > width) { + width = this.largestArgLength(); + } + } -/***/ 88916: -/***/ ((__unused_webpack_module, exports) => { + if (this.commands && this.commands.length) { + if (this.largestCommandLength() > width) { + width = this.largestCommandLength(); + } + } -"use strict"; + return width; + }; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getAuthenticatedOctokit = void 0; -async function getAuthenticatedOctokit(state, installationId) { - const { log, octokit } = state; - if (!installationId) - return octokit; - return octokit.auth({ - type: "installation", - installationId, - factory: ({ octokit, octokitOptions, ...otherOptions }) => { - const pinoLog = log.child({ name: "github" }); - const options = { - ...octokitOptions, - log: { - fatal: pinoLog.fatal.bind(pinoLog), - error: pinoLog.error.bind(pinoLog), - warn: pinoLog.warn.bind(pinoLog), - info: pinoLog.info.bind(pinoLog), - debug: pinoLog.debug.bind(pinoLog), - trace: pinoLog.trace.bind(pinoLog), - }, - throttle: { - ...octokitOptions.throttle, - id: installationId, - }, - auth: { - ...octokitOptions.auth, - otherOptions, - installationId, - }, - }; - const Octokit = octokit.constructor; - return new Octokit(options); - }, + /** + * Return help for options. + * + * @return {string} + * @api private + */ + + optionHelp() { + const width = this.padWidth(); + const columns = process.stdout.columns || 80; + const descriptionWidth = columns - width - 4; + function padOptionDetails(flags, description) { + return pad(flags, width) + ' ' + optionalWrap(description, descriptionWidth, width + 2); + }; + + // Explicit options (including version) + const help = this.options.map((option) => { + const fullDesc = option.description + + ((!option.negate && option.defaultValue !== undefined) ? ' (default: ' + JSON.stringify(option.defaultValue) + ')' : ''); + return padOptionDetails(option.flags, fullDesc); }); -} -exports.getAuthenticatedOctokit = getAuthenticatedOctokit; -//# sourceMappingURL=get-authenticated-octokit.js.map -/***/ }), + // Implicit help + const showShortHelpFlag = this._hasHelpOption && this._helpShortFlag && !this._findOption(this._helpShortFlag); + const showLongHelpFlag = this._hasHelpOption && !this._findOption(this._helpLongFlag); + if (showShortHelpFlag || showLongHelpFlag) { + let helpFlags = this._helpFlags; + if (!showShortHelpFlag) { + helpFlags = this._helpLongFlag; + } else if (!showLongHelpFlag) { + helpFlags = this._helpShortFlag; + } + help.push(padOptionDetails(helpFlags, this._helpDescription)); + } -/***/ 2286: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + return help.join('\n'); + }; -"use strict"; + /** + * Return command help documentation. + * + * @return {string} + * @api private + */ -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getOctokitThrottleOptions = void 0; -const bottleneck_1 = __importDefault(__nccwpck_require__(27356)); -const ioredis_1 = __importDefault(__nccwpck_require__(45069)); -function getOctokitThrottleOptions(options) { - let { log, redisConfig } = options; - if (!redisConfig) - return; - const connection = new bottleneck_1.default.IORedisConnection({ - client: getRedisClient(options), - }); - connection.on("error", (error) => { - log.error(Object.assign(error, { source: "bottleneck" })); - }); - return { - Bottleneck: bottleneck_1.default, - connection, - }; -} -exports.getOctokitThrottleOptions = getOctokitThrottleOptions; -function getRedisClient({ log, redisConfig }) { - if (redisConfig) - return new ioredis_1.default(redisConfig); -} -//# sourceMappingURL=get-octokit-throttle-options.js.map + commandHelp() { + if (!this.commands.length && !this._lazyHasImplicitHelpCommand()) return ''; -/***/ }), + const commands = this.prepareCommands(); + const width = this.padWidth(); -/***/ 62543: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + const columns = process.stdout.columns || 80; + const descriptionWidth = columns - width - 4; -"use strict"; + return [ + 'Commands:', + commands.map((cmd) => { + const desc = cmd[1] ? ' ' + cmd[1] : ''; + return (desc ? pad(cmd[0], width) : cmd[0]) + optionalWrap(desc, descriptionWidth, width + 2); + }).join('\n').replace(/^/gm, ' '), + '' + ].join('\n'); + }; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getProbotOctokitWithDefaults = void 0; -const get_octokit_throttle_options_1 = __nccwpck_require__(2286); -/** - * Returns an Octokit instance with default settings for authentication. If - * a `githubToken` is passed explicitly, the Octokit instance will be - * pre-authenticated with that token when instantiated. Otherwise Octokit's - * app authentication strategy is used, and `options.auth` options are merged - * deeply when instantiated. - * - * Besides the authentication, the Octokit's baseUrl is set as well when run - * against a GitHub Enterprise Server with a custom domain. - */ -function getProbotOctokitWithDefaults(options) { - const authOptions = options.githubToken - ? { - token: options.githubToken, - } - : { - cache: options.cache, - appId: options.appId, - privateKey: options.privateKey, - }; - const octokitThrottleOptions = get_octokit_throttle_options_1.getOctokitThrottleOptions({ - log: options.log, - redisConfig: options.redisConfig, - }); - let defaultOptions = { - auth: authOptions, - }; - if (options.baseUrl) { - defaultOptions.baseUrl = options.baseUrl; + /** + * Return program help documentation. + * + * @return {string} + * @api public + */ + + helpInformation() { + let desc = []; + if (this._description) { + desc = [ + this._description, + '' + ]; + + const argsDescription = this._argsDescription; + if (argsDescription && this._args.length) { + const width = this.padWidth(); + const columns = process.stdout.columns || 80; + const descriptionWidth = columns - width - 5; + desc.push('Arguments:'); + this._args.forEach((arg) => { + desc.push(' ' + pad(arg.name, width) + ' ' + wrap(argsDescription[arg.name] || '', descriptionWidth, width + 4)); + }); + desc.push(''); + } } - if (octokitThrottleOptions) { - defaultOptions.throttle = octokitThrottleOptions; + + let cmdName = this._name; + if (this._aliases[0]) { + cmdName = cmdName + '|' + this._aliases[0]; } - return options.Octokit.defaults((instanceOptions) => { - const options = Object.assign({}, defaultOptions, instanceOptions, { - auth: instanceOptions.auth - ? Object.assign({}, defaultOptions.auth, instanceOptions.auth) - : defaultOptions.auth, - }); - if (instanceOptions.throttle) { - options.throttle = Object.assign({}, defaultOptions.throttle, instanceOptions.throttle); - } - return options; - }); -} -exports.getProbotOctokitWithDefaults = getProbotOctokitWithDefaults; -//# sourceMappingURL=get-probot-octokit-with-defaults.js.map + let parentCmdNames = ''; + for (let parentCmd = this.parent; parentCmd; parentCmd = parentCmd.parent) { + parentCmdNames = parentCmd.name() + ' ' + parentCmdNames; + } + const usage = [ + 'Usage: ' + parentCmdNames + cmdName + ' ' + this.usage(), + '' + ]; -/***/ }), + let cmds = []; + const commandHelp = this.commandHelp(); + if (commandHelp) cmds = [commandHelp]; -/***/ 92974: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + let options = []; + if (this._hasHelpOption || this.options.length > 0) { + options = [ + 'Options:', + '' + this.optionHelp().replace(/^/gm, ' '), + '' + ]; + } -"use strict"; + return usage + .concat(desc) + .concat(options) + .concat(cmds) + .join('\n'); + }; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getWebhooks = void 0; -const webhooks_1 = __nccwpck_require__(18513); -const get_error_handler_1 = __nccwpck_require__(25625); -const octokit_webhooks_transform_1 = __nccwpck_require__(50645); -// import { Context } from "../context"; -function getWebhooks(state) { - // TODO: This should be webhooks = new Webhooks({...}) but fails with - // > The context of the event that was triggered, including the payload and - // helpers for extracting information can be passed to GitHub API calls - const webhooks = new webhooks_1.Webhooks({ - secret: state.webhooks.secret, - transform: octokit_webhooks_transform_1.webhookTransform.bind(null, state), - }); - webhooks.onError(get_error_handler_1.getErrorHandler(state.log)); - return webhooks; -} -exports.getWebhooks = getWebhooks; -//# sourceMappingURL=get-webhooks.js.map + /** + * Output help information for this command. + * + * When listener(s) are available for the helpLongFlag + * those callbacks are invoked. + * + * @api public + */ -/***/ }), + outputHelp(cb) { + if (!cb) { + cb = (passthru) => { + return passthru; + }; + } + const cbOutput = cb(this.helpInformation()); + if (typeof cbOutput !== 'string' && !Buffer.isBuffer(cbOutput)) { + throw new Error('outputHelp callback must return a string or a Buffer'); + } + process.stdout.write(cbOutput); + this.emit(this._helpLongFlag); + }; -/***/ 87517: -/***/ ((__unused_webpack_module, exports) => { + /** + * You can pass in flags and a description to override the help + * flags and help description for your command. Pass in false to + * disable the built-in help option. + * + * @param {string | boolean} [flags] + * @param {string} [description] + * @return {Command} `this` command for chaining + * @api public + */ -"use strict"; + helpOption(flags, description) { + if (typeof flags === 'boolean') { + this._hasHelpOption = flags; + return this; + } + this._helpFlags = flags || this._helpFlags; + this._helpDescription = description || this._helpDescription; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.probotRequestLogging = void 0; -function probotRequestLogging(octokit) { - octokit.hook.error("request", (error, options) => { - if ("status" in error) { - const { method, url, request, ...params } = octokit.request.endpoint.parse(options); - const msg = `GitHub request: ${method} ${url} - ${error.status}`; - // @ts-expect-error log.debug is a pino log method and accepts a fields object - octokit.log.debug(params.body || {}, msg); - } - throw error; - }); - octokit.hook.after("request", (result, options) => { - const { method, url, request, ...params } = octokit.request.endpoint.parse(options); - const msg = `GitHub request: ${method} ${url} - ${result.status}`; - // @ts-ignore log.debug is a pino log method and accepts a fields object - octokit.log.debug(params.body || {}, msg); - }); -} -exports.probotRequestLogging = probotRequestLogging; -//# sourceMappingURL=octokit-plugin-probot-request-logging.js.map + const helpFlags = _parseOptionFlags(this._helpFlags); + this._helpShortFlag = helpFlags.shortFlag; + this._helpLongFlag = helpFlags.longFlag; -/***/ }), + return this; + }; -/***/ 50645: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + /** + * Output help information and exit. + * + * @param {Function} [cb] + * @api public + */ -"use strict"; + help(cb) { + this.outputHelp(cb); + // exitCode: preserving original behaviour which was calling process.exit() + // message: do not have all displayed text available so only passing placeholder. + this._exit(process.exitCode || 0, 'commander.help', '(outputHelp)'); + }; + + /** + * Output help information and exit. Display for error situations. + * + * @api private + */ + + _helpAndError() { + this.outputHelp(); + // message: do not have all displayed text available so only passing placeholder. + this._exit(1, 'commander.help', '(outputHelp)'); + }; +}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.webhookTransform = void 0; -const context_1 = __nccwpck_require__(94219); /** - * Probot's transform option, which extends the `event` object that is passed - * to webhook event handlers by `@octokit/webhooks` - * @see https://github.com/octokit/webhooks.js/#constructor + * Expose the root command. */ -async function webhookTransform(state, event) { - const log = state.log.child({ name: "event", id: event.id }); - const octokit = (await state.octokit.auth({ - type: "event-octokit", - event, - })); - return new context_1.Context(event, octokit, log); -} -exports.webhookTransform = webhookTransform; -//# sourceMappingURL=octokit-webhooks-transform.js.map -/***/ }), +exports = module.exports = new Command(); +exports.program = exports; // More explicit access to global command. -/***/ 45351: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/** + * Expose classes + */ -"use strict"; +exports.Command = Command; +exports.Option = Option; +exports.CommanderError = CommanderError; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ProbotOctokit = void 0; -const core_1 = __nccwpck_require__(76762); -const plugin_enterprise_compatibility_1 = __nccwpck_require__(25823); -const plugin_paginate_rest_1 = __nccwpck_require__(64193); -const plugin_rest_endpoint_methods_1 = __nccwpck_require__(83044); -const plugin_retry_1 = __nccwpck_require__(86298); -const plugin_throttling_1 = __nccwpck_require__(9968); -const octokit_plugin_config_1 = __nccwpck_require__(59326); -const octokit_auth_probot_1 = __nccwpck_require__(80536); -const octokit_plugin_probot_request_logging_1 = __nccwpck_require__(87517); -const version_1 = __nccwpck_require__(23972); -const defaultOptions = { - authStrategy: octokit_auth_probot_1.createProbotAuth, - throttle: { - onAbuseLimit: (retryAfter, options, octokit) => { - octokit.log.warn(`Abuse limit hit with "${options.method} ${options.url}", retrying in ${retryAfter} seconds.`); - return true; - }, - onRateLimit: (retryAfter, options, octokit) => { - octokit.log.warn(`Rate limit hit with "${options.method} ${options.url}", retrying in ${retryAfter} seconds.`); - return true; - }, - }, - userAgent: `probot/${version_1.VERSION}`, -}; -exports.ProbotOctokit = core_1.Octokit.plugin(plugin_throttling_1.throttling, plugin_retry_1.retry, plugin_paginate_rest_1.paginateRest, plugin_rest_endpoint_methods_1.legacyRestEndpointMethods, plugin_enterprise_compatibility_1.enterpriseCompatibility, octokit_plugin_probot_request_logging_1.probotRequestLogging, octokit_plugin_config_1.config).defaults((instanceOptions) => { - // merge throttle options deeply - const options = Object.assign({}, defaultOptions, instanceOptions, { - throttle: instanceOptions.throttle - ? Object.assign({}, defaultOptions.throttle, instanceOptions.throttle) - : defaultOptions.throttle, - }); - return options; -}); -//# sourceMappingURL=probot-octokit.js.map +/** + * Camel-case the given `flag` + * + * @param {string} flag + * @return {string} + * @api private + */ -/***/ }), +function camelcase(flag) { + return flag.split('-').reduce((str, word) => { + return str + word[0].toUpperCase() + word.slice(1); + }); +} -/***/ 87085: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/** + * Pad `str` to `width`. + * + * @param {string} str + * @param {number} width + * @return {string} + * @api private + */ -"use strict"; +function pad(str, width) { + const len = Math.max(0, width - str.length); + return str + Array(len + 1).join(' '); +} -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Probot = void 0; -const lru_cache_1 = __importDefault(__nccwpck_require__(7129)); -const alias_log_1 = __nccwpck_require__(95326); -const auth_1 = __nccwpck_require__(23831); -const get_log_1 = __nccwpck_require__(75942); -const get_probot_octokit_with_defaults_1 = __nccwpck_require__(62543); -const get_webhooks_1 = __nccwpck_require__(92974); -const probot_octokit_1 = __nccwpck_require__(45351); -const version_1 = __nccwpck_require__(23972); -class Probot { - constructor(options = {}) { - options.secret = options.secret || "development"; - let level = options.logLevel; - const logMessageKey = options.logMessageKey; - this.log = alias_log_1.aliasLog(options.log || get_log_1.getLog({ level, logMessageKey })); - // TODO: support redis backend for access token cache if `options.redisConfig` - const cache = new lru_cache_1.default({ - // cache max. 15000 tokens, that will use less than 10mb memory - max: 15000, - // Cache for 1 minute less than GitHub expiry - maxAge: 1000 * 60 * 59, - }); - const Octokit = get_probot_octokit_with_defaults_1.getProbotOctokitWithDefaults({ - githubToken: options.githubToken, - Octokit: options.Octokit || probot_octokit_1.ProbotOctokit, - appId: Number(options.appId), - privateKey: options.privateKey, - cache, - log: this.log, - redisConfig: options.redisConfig, - baseUrl: options.baseUrl, - }); - const octokit = new Octokit(); - this.state = { - cache, - githubToken: options.githubToken, - log: this.log, - Octokit, - octokit, - webhooks: { - secret: options.secret, - }, - appId: Number(options.appId), - privateKey: options.privateKey, - host: options.host, - port: options.port, - }; - this.auth = auth_1.auth.bind(null, this.state); - this.webhooks = get_webhooks_1.getWebhooks(this.state); - this.on = this.webhooks.on; - this.onAny = this.webhooks.onAny; - this.onError = this.webhooks.onError; - this.version = version_1.VERSION; - } - static defaults(defaults) { - const ProbotWithDefaults = class extends this { - constructor(...args) { - const options = args[0] || {}; - super(Object.assign({}, defaults, options)); - } - }; - return ProbotWithDefaults; - } - receive(event) { - this.log.debug({ event }, "Webhook received"); - return this.webhooks.receive(event); - } - async load(appFn) { - if (Array.isArray(appFn)) { - for (const fn of appFn) { - await this.load(fn); - } - return; - } - return appFn(this, {}); +/** + * Wraps the given string with line breaks at the specified width while breaking + * words and indenting every but the first line on the left. + * + * @param {string} str + * @param {number} width + * @param {number} indent + * @return {string} + * @api private + */ +function wrap(str, width, indent) { + const regex = new RegExp('.{1,' + (width - 1) + '}([\\s\u200B]|$)|[^\\s\u200B]+?([\\s\u200B]|$)', 'g'); + const lines = str.match(regex) || []; + return lines.map((line, i) => { + if (line.slice(-1) === '\n') { + line = line.slice(0, line.length - 1); } + return ((i > 0 && indent) ? Array(indent + 1).join(' ') : '') + line.trimRight(); + }).join('\n'); } -exports.Probot = Probot; -Probot.version = version_1.VERSION; -//# sourceMappingURL=probot.js.map -/***/ }), - -/***/ 75611: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/** + * Optionally wrap the given str to a max width of width characters per line + * while indenting with indent spaces. Do not wrap if insufficient width or + * string is manually formatted. + * + * @param {string} str + * @param {number} width + * @param {number} indent + * @return {string} + * @api private + */ +function optionalWrap(str, width, indent) { + // Detect manually wrapped and indented strings by searching for line breaks + // followed by multiple spaces/tabs. + if (str.match(/[\n]\s+/)) return str; + // Do not wrap to narrow columns (or can end up with a word per line). + const minWidth = 40; + if (width < minWidth) return str; -"use strict"; + return wrap(str, width, indent); +} -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.run = void 0; -const pkg_conf_1 = __importDefault(__nccwpck_require__(51235)); -const index_1 = __nccwpck_require__(58930); -const setup_1 = __nccwpck_require__(31078); -const get_log_1 = __nccwpck_require__(75942); -const read_cli_options_1 = __nccwpck_require__(4015); -const read_env_options_1 = __nccwpck_require__(92004); -const server_1 = __nccwpck_require__(93772); -const default_1 = __nccwpck_require__(35362); -const resolve_app_function_1 = __nccwpck_require__(32350); -const is_production_1 = __nccwpck_require__(78079); /** + * Output help information if help flags specified * - * @param appFnOrArgv set to either a probot application function: `(app) => { ... }` or to process.argv + * @param {Command} cmd - command to output help for + * @param {Array} args - array of options to search for help flags + * @api private */ -async function run(appFnOrArgv, additionalOptions) { - (__nccwpck_require__(12437).config)(); - const envOptions = read_env_options_1.readEnvOptions(additionalOptions === null || additionalOptions === void 0 ? void 0 : additionalOptions.env); - const cliOptions = Array.isArray(appFnOrArgv) - ? read_cli_options_1.readCliOptions(appFnOrArgv) - : {}; - const { - // log options - logLevel: level, logFormat, logLevelInString, logMessageKey, sentryDsn, - // server options - host, port, webhookPath, webhookProxy, - // probot options - appId, privateKey, redisConfig, secret, baseUrl, - // others - args, } = { ...envOptions, ...cliOptions }; - const logOptions = { - level, - logFormat, - logLevelInString, - logMessageKey, - sentryDsn, - }; - const log = get_log_1.getLog(logOptions); - const probotOptions = { - appId, - privateKey, - redisConfig, - secret, - baseUrl, - log: log.child({ name: "probot" }), - }; - const serverOptions = { - host, - port, - webhookPath, - webhookProxy, - log: log.child({ name: "server" }), - Probot: index_1.Probot.defaults(probotOptions), - }; - let server; - if (!appId || !privateKey) { - if (is_production_1.isProduction()) { - if (!appId) { - throw new Error("App ID is missing, and is required to run in production mode. " + - "To resolve, ensure the APP_ID environment variable is set."); - } - else if (!privateKey) { - throw new Error("Certificate is missing, and is required to run in production mode. " + - "To resolve, ensure either the PRIVATE_KEY or PRIVATE_KEY_PATH environment variable is set and contains a valid certificate"); - } - } - // Workaround for setup (#1512) - // When probot is started for the first time, it gets into a setup mode - // where `appId` and `privateKey` are not present. The setup mode gets - // these credentials. In order to not throw an error, we set the values - // to anything, as the Probot instance is not used in setup it makes no - // difference anyway. - server = new server_1.Server({ - ...serverOptions, - Probot: index_1.Probot.defaults({ - ...probotOptions, - appId: 1, - privateKey: "dummy value for setup, see #1512", - }), - }); - await server.load(setup_1.setupAppFactory(host, port)); - await server.start(); - return server; - } - if (Array.isArray(appFnOrArgv)) { - const pkg = await pkg_conf_1.default("probot"); - const combinedApps = async (app) => { - await server.load(default_1.defaultApp); - if (Array.isArray(pkg.apps)) { - for (const appPath of pkg.apps) { - const appFn = await resolve_app_function_1.resolveAppFunction(appPath); - await server.load(appFn); - } - } - const [appPath] = args; - const appFn = await resolve_app_function_1.resolveAppFunction(appPath); - await server.load(appFn); - }; - server = new server_1.Server(serverOptions); - await server.load(combinedApps); - await server.start(); - return server; - } - server = new server_1.Server(serverOptions); - await server.load(appFnOrArgv); - await server.start(); - return server; -} -exports.run = run; -//# sourceMappingURL=run.js.map -/***/ }), +function outputHelpIfRequested(cmd, args) { + const helpOption = cmd._hasHelpOption && args.find(arg => arg === cmd._helpLongFlag || arg === cmd._helpShortFlag); + if (helpOption) { + cmd.outputHelp(); + // (Do not have all displayed text available so only passing placeholder.) + cmd._exit(0, 'commander.helpDisplayed', '(outputHelp)'); + } +} -/***/ 27530: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/** + * Takes an argument and returns its human readable equivalent for help usage. + * + * @param {Object} arg + * @return {string} + * @api private + */ -"use strict"; +function humanReadableArgName(arg) { + const nameOutput = arg.name + (arg.variadic === true ? '...' : ''); -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getLoggingMiddleware = void 0; -const pino_http_1 = __importDefault(__nccwpck_require__(31778)); -const uuid_1 = __nccwpck_require__(75840); -function getLoggingMiddleware(logger) { - return pino_http_1.default({ - logger: logger.child({ name: "http" }), - customSuccessMessage(res) { - const responseTime = Date.now() - res[pino_http_1.default.startTime]; - // @ts-ignore - return `${res.req.method} ${res.req.url} ${res.statusCode} - ${responseTime}ms`; - }, - customErrorMessage(err, res) { - const responseTime = Date.now() - res[pino_http_1.default.startTime]; - // @ts-ignore - return `${res.req.method} ${res.req.url} ${res.statusCode} - ${responseTime}ms`; - }, - genReqId: (req) => req.headers["x-request-id"] || - req.headers["x-github-delivery"] || - uuid_1.v4(), - }); + return arg.required + ? '<' + nameOutput + '>' + : '[' + nameOutput + ']'; } -exports.getLoggingMiddleware = getLoggingMiddleware; -//# sourceMappingURL=logging-middleware.js.map -/***/ }), +/** + * Parse the short and long flag out of something like '-m,--mixed ' + * + * @api private + */ -/***/ 93772: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +function _parseOptionFlags(flags) { + let shortFlag; + let longFlag; + // Use original very loose parsing to maintain backwards compatibility for now, + // which allowed for example unintended `-sw, --short-word` [sic]. + const flagParts = flags.split(/[ |,]+/); + if (flagParts.length > 1 && !/^[[<]/.test(flagParts[1])) shortFlag = flagParts.shift(); + longFlag = flagParts.shift(); + // Add support for lone short flag without significantly changing parsing! + if (!shortFlag && /^-[^-]$/.test(longFlag)) { + shortFlag = longFlag; + longFlag = undefined; + } + return { shortFlag, longFlag }; +} -"use strict"; +/** + * Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command). + * + * @param {string[]} args - array of arguments from node.execArgv + * @returns {string[]} + * @api private + */ -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Server = void 0; -const express_1 = __importStar(__nccwpck_require__(71204)); -const path_1 = __nccwpck_require__(71017); -const webhooks_1 = __nccwpck_require__(18513); -const get_log_1 = __nccwpck_require__(75942); -const logging_middleware_1 = __nccwpck_require__(27530); -const webhook_proxy_1 = __nccwpck_require__(32415); -const version_1 = __nccwpck_require__(23972); -class Server { - constructor(options = {}) { - this.version = version_1.VERSION; - this.expressApp = express_1.default(); - this.log = options.log || get_log_1.getLog().child({ name: "server" }); - this.probotApp = new options.Probot(); - this.state = { - port: options.port, - host: options.host, - webhookPath: options.webhookPath || "/", - webhookProxy: options.webhookProxy, - }; - this.expressApp.use(logging_middleware_1.getLoggingMiddleware(this.log)); - this.expressApp.use("/probot/static/", express_1.default.static(__nccwpck_require__.ab + "static")); - this.expressApp.use(this.state.webhookPath, webhooks_1.createNodeMiddleware(this.probotApp.webhooks, { - path: "/", - })); - this.expressApp.set("view engine", "hbs"); - this.expressApp.set("views", __nccwpck_require__.ab + "views"); - this.expressApp.get("/ping", (req, res) => res.end("PONG")); - } - async load(appFn) { - await appFn(this.probotApp, { - getRouter: (path) => this.router(path), - }); - } - async start() { - this.log.info(`Running Probot v${this.version} (Node.js: ${process.version})`); - const port = this.state.port || 3000; - const { host, webhookPath, webhookProxy } = this.state; - const printableHost = host !== null && host !== void 0 ? host : "localhost"; - this.state.httpServer = (await new Promise((resolve, reject) => { - const server = this.expressApp.listen(port, ...(host ? [host] : []), () => { - if (webhookProxy) { - this.state.eventSource = webhook_proxy_1.createWebhookProxy({ - logger: this.log, - path: webhookPath, - port: port, - url: webhookProxy, - }); - } - this.log.info(`Listening on http://${printableHost}:${port}`); - resolve(server); - }); - server.on("error", (error) => { - if (error.code === "EADDRINUSE") { - error = Object.assign(error, { - message: `Port ${port} is already in use. You can define the PORT environment variable to use a different port.`, - }); - } - this.log.error(error); - reject(error); - }); - })); - return this.state.httpServer; +function incrementNodeInspectorPort(args) { + // Testing for these options: + // --inspect[=[host:]port] + // --inspect-brk[=[host:]port] + // --inspect-port=[host:]port + return args.map((arg) => { + if (!arg.startsWith('--inspect')) { + return arg; } - async stop() { - if (this.state.eventSource) - this.state.eventSource.close(); - if (!this.state.httpServer) - return; - const server = this.state.httpServer; - return new Promise((resolve) => server.close(resolve)); + let debugOption; + let debugHost = '127.0.0.1'; + let debugPort = '9229'; + let match; + if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) { + // e.g. --inspect + debugOption = match[1]; + } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) { + debugOption = match[1]; + if (/^\d+$/.test(match[3])) { + // e.g. --inspect=1234 + debugPort = match[3]; + } else { + // e.g. --inspect=localhost + debugHost = match[3]; + } + } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) { + // e.g. --inspect=localhost:1234 + debugOption = match[1]; + debugHost = match[3]; + debugPort = match[4]; } - router(path = "/") { - const newRouter = express_1.Router(); - this.expressApp.use(path, newRouter); - return newRouter; + + if (debugOption && debugPort !== '0') { + return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`; } + return arg; + }); } -exports.Server = Server; -Server.version = version_1.VERSION; -//# sourceMappingURL=server.js.map -/***/ }), - -/***/ 23972: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.VERSION = void 0; -// The version is set automatically before publish to npm -exports.VERSION = "12.2.1"; -//# sourceMappingURL=version.js.map /***/ }), @@ -119792,7 +119731,6 @@ function rfdcCircles (opts) { /***/ 21867: /***/ ((module, exports, __nccwpck_require__) => { -/*! safe-buffer. MIT License. Feross Aboukhadijeh */ /* eslint-disable node/no-deprecated-api */ var buffer = __nccwpck_require__(14300) var Buffer = buffer.Buffer @@ -119815,8 +119753,6 @@ function SafeBuffer (arg, encodingOrOffset, length) { return Buffer(arg, encodingOrOffset, length) } -SafeBuffer.prototype = Object.create(Buffer.prototype) - // Copy static methods from Buffer copyProps(Buffer, SafeBuffer) @@ -125194,7 +125130,7 @@ function status (code) { "use strict"; const stripAnsi = __nccwpck_require__(45591); -const isFullwidthCodePoint = __nccwpck_require__(64882); +const isFullwidthCodePoint = __nccwpck_require__(10205); const emojiRegex = __nccwpck_require__(18212); const stringWidth = string => { @@ -125241,6 +125177,64 @@ module.exports = stringWidth; module.exports["default"] = stringWidth; +/***/ }), + +/***/ 10205: +/***/ ((module) => { + +"use strict"; +/* eslint-disable yoda */ + + +const isFullwidthCodePoint = codePoint => { + if (Number.isNaN(codePoint)) { + return false; + } + + // Code points are derived from: + // http://www.unix.org/Public/UNIDATA/EastAsianWidth.txt + if ( + codePoint >= 0x1100 && ( + codePoint <= 0x115F || // Hangul Jamo + codePoint === 0x2329 || // LEFT-POINTING ANGLE BRACKET + codePoint === 0x232A || // RIGHT-POINTING ANGLE BRACKET + // CJK Radicals Supplement .. Enclosed CJK Letters and Months + (0x2E80 <= codePoint && codePoint <= 0x3247 && codePoint !== 0x303F) || + // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A + (0x3250 <= codePoint && codePoint <= 0x4DBF) || + // CJK Unified Ideographs .. Yi Radicals + (0x4E00 <= codePoint && codePoint <= 0xA4C6) || + // Hangul Jamo Extended-A + (0xA960 <= codePoint && codePoint <= 0xA97C) || + // Hangul Syllables + (0xAC00 <= codePoint && codePoint <= 0xD7A3) || + // CJK Compatibility Ideographs + (0xF900 <= codePoint && codePoint <= 0xFAFF) || + // Vertical Forms + (0xFE10 <= codePoint && codePoint <= 0xFE19) || + // CJK Compatibility Forms .. Small Form Variants + (0xFE30 <= codePoint && codePoint <= 0xFE6B) || + // Halfwidth and Fullwidth Forms + (0xFF01 <= codePoint && codePoint <= 0xFF60) || + (0xFFE0 <= codePoint && codePoint <= 0xFFE6) || + // Kana Supplement + (0x1B000 <= codePoint && codePoint <= 0x1B001) || + // Enclosed Ideographic Supplement + (0x1F200 <= codePoint && codePoint <= 0x1F251) || + // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane + (0x20000 <= codePoint && codePoint <= 0x3FFFD) + ) + ) { + return true; + } + + return false; +}; + +module.exports = isFullwidthCodePoint; +module.exports["default"] = isFullwidthCodePoint; + + /***/ }), /***/ 94841: @@ -125272,7 +125266,7 @@ module.exports["default"] = stringWidth; /**/ -var Buffer = (__nccwpck_require__(21867).Buffer); +var Buffer = (__nccwpck_require__(2279).Buffer); /**/ var isEncoding = Buffer.isEncoding || function (encoding) { @@ -125546,36 +125540,86 @@ function simpleEnd(buf) { /***/ }), -/***/ 45591: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 2279: +/***/ ((module, exports, __nccwpck_require__) => { -"use strict"; +/*! safe-buffer. MIT License. Feross Aboukhadijeh */ +/* eslint-disable node/no-deprecated-api */ +var buffer = __nccwpck_require__(14300) +var Buffer = buffer.Buffer -const ansiRegex = __nccwpck_require__(65063); +// alternative to using Object.keys for old browsers +function copyProps (src, dst) { + for (var key in src) { + dst[key] = src[key] + } +} +if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer +} else { + // Copy properties from require('buffer') + copyProps(buffer, exports) + exports.Buffer = SafeBuffer +} -module.exports = string => typeof string === 'string' ? string.replace(ansiRegex(), '') : string; +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.prototype = Object.create(Buffer.prototype) + +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer) + +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') + } + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + var buf = Buffer(size) + if (fill !== undefined) { + if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) + } + } else { + buf.fill(0) + } + return buf +} + +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) +} + +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) +} /***/ }), -/***/ 88551: -/***/ ((module) => { +/***/ 45591: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -module.exports = x => { - if (typeof x !== 'string') { - throw new TypeError('Expected a string, got ' + typeof x); - } - - // Catches EFBBBF (UTF-8 BOM) because the buffer-to-string - // conversion translates it to FEFF (UTF-16 BOM) - if (x.charCodeAt(0) === 0xFEFF) { - return x.slice(1); - } +const ansiRegex = __nccwpck_require__(65063); - return x; -}; +module.exports = string => typeof string === 'string' ? string.replace(ansiRegex(), '') : string; /***/ }), @@ -129348,15 +129392,33 @@ const generateChangeLog = (mergedPullRequests, config) => { } categorizedPullRequests.map((category, index) => { - if (category.pullRequests.length > 0) { + if (category.pullRequests.length === 0) { + return category + } + + const categoryTitle = template(config['category-template'], { + $TITLE: category.title, + }) + const pullRequestString = pullRequestToString(category.pullRequests) + + if ( + !category.collapse || + (category.collapse && category.pullRequests.length < 4) + ) { + changeLog.push(categoryTitle, '\n\n', pullRequestString) + } else { changeLog.push( - template(config['category-template'], { $TITLE: category.title }), + categoryTitle, + '
', + '\n', + `${category.pullRequests.length} changes`, '\n\n', - pullRequestToString(category.pullRequests) + pullRequestString, + '
' ) - - if (index + 1 !== categorizedPullRequests.length) changeLog.push('\n\n') } + + if (index + 1 !== categorizedPullRequests.length) changeLog.push('\n\n') }) return changeLog.join('').trim() @@ -129647,6 +129709,7 @@ const schema = (context) => { Joi.object() .keys({ title: Joi.string().required(), + collapse: Joi.boolean().default(false), label: Joi.string(), labels: Joi.array().items(Joi.string()).single().default([]), }) diff --git a/schema.json b/schema.json index 0a4e6239e..6ad221bc8 100644 --- a/schema.json +++ b/schema.json @@ -199,6 +199,10 @@ "title": { "type": "string" }, + "collapse": { + "default": false, + "type": "boolean" + }, "label": { "type": "string" }, From 040715f02b2f2eda3d52d26191f7966691c72c72 Mon Sep 17 00:00:00 2001 From: Robbin Janssen Date: Fri, 4 Mar 2022 14:01:17 +0000 Subject: [PATCH 03/13] Replace map with for loops --- dist/index.js | 17 +++++++++-------- lib/releases.js | 17 +++++++++-------- 2 files changed, 18 insertions(+), 16 deletions(-) diff --git a/dist/index.js b/dist/index.js index 36ea21fe7..fce30a9f9 100644 --- a/dist/index.js +++ b/dist/index.js @@ -129332,8 +129332,8 @@ const categorizePullRequests = (pullRequests, config) => { .filter(getFilterIncludedPullRequests(includeLabels)) .filter((pullRequest) => filterUncategorizedPullRequests(pullRequest)) - categorizedPullRequests.map((category) => { - filteredPullRequests.map((pullRequest) => { + for (const category of categorizedPullRequests) { + for (const pullRequest of filteredPullRequests) { // lets categorize some pull request based on labels // note that having the same label in multiple categories // then it is intended to "duplicate" the pull request into each category @@ -129341,8 +129341,8 @@ const categorizePullRequests = (pullRequests, config) => { if (labels.some((label) => category.labels.includes(label.name))) { category.pullRequests.push(pullRequest) } - }) - }) + } + } return [uncategorizedPullRequests, categorizedPullRequests] } @@ -129391,11 +129391,10 @@ const generateChangeLog = (mergedPullRequests, config) => { changeLog.push(pullRequestToString(uncategorizedPullRequests), '\n\n') } - categorizedPullRequests.map((category, index) => { + for (const [index, category] of categorizedPullRequests.entries()) { if (category.pullRequests.length === 0) { - return category + continue } - const categoryTitle = template(config['category-template'], { $TITLE: category.title, }) @@ -129409,17 +129408,19 @@ const generateChangeLog = (mergedPullRequests, config) => { } else { changeLog.push( categoryTitle, + '\n', '
', '\n', `${category.pullRequests.length} changes`, '\n\n', pullRequestString, + '\n', '
' ) } if (index + 1 !== categorizedPullRequests.length) changeLog.push('\n\n') - }) + } return changeLog.join('').trim() } diff --git a/lib/releases.js b/lib/releases.js index 39f81aba2..8429df7ab 100644 --- a/lib/releases.js +++ b/lib/releases.js @@ -178,8 +178,8 @@ const categorizePullRequests = (pullRequests, config) => { .filter(getFilterIncludedPullRequests(includeLabels)) .filter((pullRequest) => filterUncategorizedPullRequests(pullRequest)) - categorizedPullRequests.map((category) => { - filteredPullRequests.map((pullRequest) => { + for (const category of categorizedPullRequests) { + for (const pullRequest of filteredPullRequests) { // lets categorize some pull request based on labels // note that having the same label in multiple categories // then it is intended to "duplicate" the pull request into each category @@ -187,8 +187,8 @@ const categorizePullRequests = (pullRequests, config) => { if (labels.some((label) => category.labels.includes(label.name))) { category.pullRequests.push(pullRequest) } - }) - }) + } + } return [uncategorizedPullRequests, categorizedPullRequests] } @@ -237,11 +237,10 @@ const generateChangeLog = (mergedPullRequests, config) => { changeLog.push(pullRequestToString(uncategorizedPullRequests), '\n\n') } - categorizedPullRequests.map((category, index) => { + for (const [index, category] of categorizedPullRequests.entries()) { if (category.pullRequests.length === 0) { - return category + continue } - const categoryTitle = template(config['category-template'], { $TITLE: category.title, }) @@ -255,17 +254,19 @@ const generateChangeLog = (mergedPullRequests, config) => { } else { changeLog.push( categoryTitle, + '\n', '
', '\n', `${category.pullRequests.length} changes`, '\n\n', pullRequestString, + '\n', '
' ) } if (index + 1 !== categorizedPullRequests.length) changeLog.push('\n\n') - }) + } return changeLog.join('').trim() } From c1fffb71ecf4255df2df9c783d665554c7f58beb Mon Sep 17 00:00:00 2001 From: Robbin Janssen Date: Fri, 4 Mar 2022 14:18:59 +0000 Subject: [PATCH 04/13] Add test --- README.md | 3 ++- test/releases.test.js | 44 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 6a0615ed1..5dcdb13f1 100644 --- a/README.md +++ b/README.md @@ -254,8 +254,9 @@ Optionally you can add a `collapse` boolean to your category item, if the catego ```yml categories: - title: '⬆️ Dependencies' - label: 'dependencies' collapse: true + labels: + - 'dependencies' ``` ## Exclude Pull Requests diff --git a/test/releases.test.js b/test/releases.test.js index 4353607ea..7bf818c1c 100644 --- a/test/releases.test.js +++ b/test/releases.test.js @@ -187,5 +187,49 @@ describe('releases', () => { * Adds @nullable annotations to the 1\\\\*1+2\\\\*4 test in \\\\\`tests.java\\\\\` (#0) @Happypig375" `) }) + it('adds proper details/summary markdown when collapse is set to true and more then 3 PRs', () => { + const config = { + ...baseConfig, + categories: [{ title: 'Bugs', collapse: true, labels: 'bug' }], + } + const changelog = generateChangeLog(pullRequests, config) + expect(changelog).toMatchInlineSnapshot(` + "* B2 (#2) @ghost + * Rename __confgs\\\\confg.yml to __configs\\\\config.yml (#7) @ghost + * Adds @nullable annotations to the 1*1+2*4 test in \`tests.java\` (#0) @Happypig375 + + ## Bugs +
+ 5 changes + + * A1 (#1) @ghost + * Adds missing (#3) @jetersen + * \`#code_block\` (#4) @jetersen + * Fixes #4 (#5) @Happypig375 + * 2*2 should equal to 4*1 (#6) @jetersen +
" + `) + }) + it('does not add proper details/summary markdown when collapse is set to true and less then 3 PRs', () => { + const config = { + ...baseConfig, + categories: [{ title: 'Feature', collapse: true, labels: 'feature' }], + } + const changelog = generateChangeLog(pullRequests, config) + console.log(changelog) + expect(changelog).toMatchInlineSnapshot(` + "* A1 (#1) @ghost + * Adds missing (#3) @jetersen + * \`#code_block\` (#4) @jetersen + * Fixes #4 (#5) @Happypig375 + * 2*2 should equal to 4*1 (#6) @jetersen + * Rename __confgs\\\\confg.yml to __configs\\\\config.yml (#7) @ghost + + ## Feature + + * B2 (#2) @ghost + * Adds @nullable annotations to the 1*1+2*4 test in \`tests.java\` (#0) @Happypig375" + `) + }) }) }) From cd3fbb34724a09e3bda67e07fcfcdd4d374c2014 Mon Sep 17 00:00:00 2001 From: Robbin Janssen Date: Fri, 4 Mar 2022 14:20:46 +0000 Subject: [PATCH 05/13] Fix typo --- test/releases.test.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/releases.test.js b/test/releases.test.js index 7bf818c1c..65cbaf3c2 100644 --- a/test/releases.test.js +++ b/test/releases.test.js @@ -187,7 +187,7 @@ describe('releases', () => { * Adds @nullable annotations to the 1\\\\*1+2\\\\*4 test in \\\\\`tests.java\\\\\` (#0) @Happypig375" `) }) - it('adds proper details/summary markdown when collapse is set to true and more then 3 PRs', () => { + it('adds proper details/summary markdown when collapse is set to true and more than 3 PRs', () => { const config = { ...baseConfig, categories: [{ title: 'Bugs', collapse: true, labels: 'bug' }], @@ -210,7 +210,7 @@ describe('releases', () => { " `) }) - it('does not add proper details/summary markdown when collapse is set to true and less then 3 PRs', () => { + it('does not add proper details/summary markdown when collapse is set to true and less than 3 PRs', () => { const config = { ...baseConfig, categories: [{ title: 'Feature', collapse: true, labels: 'feature' }], From 24c25bf71e82903376432211dcd2591fceb064da Mon Sep 17 00:00:00 2001 From: Robbin Janssen Date: Fri, 4 Mar 2022 14:21:16 +0000 Subject: [PATCH 06/13] Remove debug --- test/releases.test.js | 1 - 1 file changed, 1 deletion(-) diff --git a/test/releases.test.js b/test/releases.test.js index 65cbaf3c2..17547ae0e 100644 --- a/test/releases.test.js +++ b/test/releases.test.js @@ -216,7 +216,6 @@ describe('releases', () => { categories: [{ title: 'Feature', collapse: true, labels: 'feature' }], } const changelog = generateChangeLog(pullRequests, config) - console.log(changelog) expect(changelog).toMatchInlineSnapshot(` "* A1 (#1) @ghost * Adds missing (#3) @jetersen From eefb21d56c064187971999b9dfc9501a519f58b1 Mon Sep 17 00:00:00 2001 From: Robbin Janssen Date: Fri, 4 Mar 2022 14:40:50 +0000 Subject: [PATCH 07/13] Add extra test --- .../config-with-categories-with-collapse.yml | 18 +++++++ test/index.test.js | 54 +++++++++++++++++++ 2 files changed, 72 insertions(+) create mode 100644 test/fixtures/config/config-with-categories-with-collapse.yml diff --git a/test/fixtures/config/config-with-categories-with-collapse.yml b/test/fixtures/config/config-with-categories-with-collapse.yml new file mode 100644 index 000000000..5202b999a --- /dev/null +++ b/test/fixtures/config/config-with-categories-with-collapse.yml @@ -0,0 +1,18 @@ +template: | + # What's Changed + + $CHANGES + +categories: + - title: 🚀 All the things! + collapse: true + labels: + - feature + - enhancement + - fix + - bugfix + - bug + - sentry + - skip-changelog + - title: 👻 Maintenance + label: chore diff --git a/test/index.test.js b/test/index.test.js index 78da5ca41..400c31d0b 100644 --- a/test/index.test.js +++ b/test/index.test.js @@ -1198,6 +1198,60 @@ describe('release-drafter', () => { expect.assertions(1) }) + + it('categorizes pull requests with a collapsed category', async () => { + getConfigMock('config-with-categories-with-collapse.yml') + + nock('https://api.github.com') + .get('/repos/toolmantim/release-drafter-test-project/releases') + .query(true) + .reply(200, [releasePayload]) + + nock('https://api.github.com') + .post('/graphql', (body) => + body.query.includes('query findCommitsWithAssociatedPullRequests') + ) + .reply(200, graphqlCommitsMergeCommit) + + nock('https://api.github.com') + .post( + '/repos/toolmantim/release-drafter-test-project/releases', + (body) => { + expect(body).toMatchInlineSnapshot(` + Object { + "body": "# What's Changed + + * Update dependencies (#4) @TimonVS + + ## 🚀 All the things! +
+ 4 changes + + * Add documentation (#5) @TimonVS + * Bug fixes (#3) @TimonVS + * Add big feature (#2) @TimonVS + * 👽 Add alien technology (#1) @TimonVS +
+ ", + "draft": true, + "name": "", + "prerelease": false, + "tag_name": "", + "target_commitish": "refs/heads/master", + } + `) + return true + } + ) + .reply(200, releasePayload) + + await probot.receive({ + name: 'push', + payload: pushPayload, + }) + + expect.assertions(1) + }) }) describe('with exclude-labels config', () => { From 80c188a35964f0758d7f08d68192d3e000c232cd Mon Sep 17 00:00:00 2001 From: Robbin Janssen Date: Fri, 4 Mar 2022 14:42:11 +0000 Subject: [PATCH 08/13] Use yarn --- dist/index.js | 124334 +++++++++++++++++++++++------------------------ 1 file changed, 62145 insertions(+), 62189 deletions(-) diff --git a/dist/index.js b/dist/index.js index fce30a9f9..2340c690e 100644 --- a/dist/index.js +++ b/dist/index.js @@ -31859,5352 +31859,6267 @@ module['exports'] = colors; /***/ }), -/***/ 89296: -/***/ (function(module) { +/***/ 61904: +/***/ ((module, exports, __nccwpck_require__) => { -/* global define */ -(function (root, factory) { - /* istanbul ignore next */ - if (typeof define === 'function' && define.amd) { - define([], factory); - } else if (true) { - module.exports = factory(); - } else {} -})(this, function () { - var semver = - /^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i; +/** + * Module dependencies. + */ - function indexOrEnd(str, q) { - return str.indexOf(q) === -1 ? str.length : str.indexOf(q); - } +const EventEmitter = (__nccwpck_require__(82361).EventEmitter); +const spawn = (__nccwpck_require__(32081).spawn); +const path = __nccwpck_require__(71017); +const fs = __nccwpck_require__(57147); - function split(v) { - var c = v.replace(/^v/, '').replace(/\+.*$/, ''); - var patchIndex = indexOrEnd(c, '-'); - var arr = c.substring(0, patchIndex).split('.'); - arr.push(c.substring(patchIndex + 1)); - return arr; - } +// @ts-check - function tryParse(v) { - var n = parseInt(v, 10); - return isNaN(n) ? v : n; - } +class Option { + /** + * Initialize a new `Option` with the given `flags` and `description`. + * + * @param {string} flags + * @param {string} description + * @api public + */ - function validateAndParse(v) { - if (typeof v !== 'string') { - throw new TypeError('Invalid argument expected string'); - } - var match = v.match(semver); - if (!match) { - throw new Error( - "Invalid argument not valid semver ('" + v + "' received)" - ); + constructor(flags, description) { + this.flags = flags; + this.required = flags.includes('<'); // A value must be supplied when the option is specified. + this.optional = flags.includes('['); // A value is optional when the option is specified. + // variadic test ignores et al which might be used to describe custom splitting of single argument + this.variadic = /\w\.\.\.[>\]]$/.test(flags); // The option can take multiple values. + this.mandatory = false; // The option must have a value after parsing, which usually means it must be specified on command line. + const optionFlags = _parseOptionFlags(flags); + this.short = optionFlags.shortFlag; + this.long = optionFlags.longFlag; + this.negate = false; + if (this.long) { + this.negate = this.long.startsWith('--no-'); } - match.shift(); - return match; - } - - function forceType(a, b) { - return typeof a !== typeof b ? [String(a), String(b)] : [a, b]; + this.description = description || ''; + this.defaultValue = undefined; } - function compareStrings(a, b) { - var [ap, bp] = forceType(tryParse(a), tryParse(b)); - if (ap > bp) return 1; - if (ap < bp) return -1; - return 0; - } + /** + * Return option name. + * + * @return {string} + * @api private + */ - function compareSegments(a, b) { - for (var i = 0; i < Math.max(a.length, b.length); i++) { - var r = compareStrings(a[i] || 0, b[i] || 0); - if (r !== 0) return r; + name() { + if (this.long) { + return this.long.replace(/^--/, ''); } - return 0; - } - - function compareVersions(v1, v2) { - [v1, v2].forEach(validateAndParse); + return this.short.replace(/^-/, ''); + }; - var s1 = split(v1); - var s2 = split(v2); + /** + * Return option name, in a camelcase format that can be used + * as a object attribute key. + * + * @return {string} + * @api private + */ - for (var i = 0; i < Math.max(s1.length - 1, s2.length - 1); i++) { - var n1 = parseInt(s1[i] || 0, 10); - var n2 = parseInt(s2[i] || 0, 10); + attributeName() { + return camelcase(this.name().replace(/^no-/, '')); + }; - if (n1 > n2) return 1; - if (n2 > n1) return -1; - } + /** + * Check if `arg` matches the short or long flag. + * + * @param {string} arg + * @return {boolean} + * @api private + */ - var sp1 = s1[s1.length - 1]; - var sp2 = s2[s2.length - 1]; + is(arg) { + return this.short === arg || this.long === arg; + }; +} - if (sp1 && sp2) { - var p1 = sp1.split('.').map(tryParse); - var p2 = sp2.split('.').map(tryParse); +/** + * CommanderError class + * @class + */ +class CommanderError extends Error { + /** + * Constructs the CommanderError class + * @param {number} exitCode suggested exit code which could be used with process.exit + * @param {string} code an id string representing the error + * @param {string} message human-readable description of the error + * @constructor + */ + constructor(exitCode, code, message) { + super(message); + // properly capture stack trace in Node.js + Error.captureStackTrace(this, this.constructor); + this.name = this.constructor.name; + this.code = code; + this.exitCode = exitCode; + this.nestedError = undefined; + } +} - for (i = 0; i < Math.max(p1.length, p2.length); i++) { - if ( - p1[i] === undefined || - (typeof p2[i] === 'string' && typeof p1[i] === 'number') - ) - return -1; - if ( - p2[i] === undefined || - (typeof p1[i] === 'string' && typeof p2[i] === 'number') - ) - return 1; +class Command extends EventEmitter { + /** + * Initialize a new `Command`. + * + * @param {string} [name] + * @api public + */ - if (p1[i] > p2[i]) return 1; - if (p2[i] > p1[i]) return -1; - } - } else if (sp1 || sp2) { - return sp1 ? -1 : 1; - } + constructor(name) { + super(); + this.commands = []; + this.options = []; + this.parent = null; + this._allowUnknownOption = false; + this._args = []; + this.rawArgs = null; + this._scriptPath = null; + this._name = name || ''; + this._optionValues = {}; + this._storeOptionsAsProperties = true; // backwards compatible by default + this._storeOptionsAsPropertiesCalled = false; + this._passCommandToAction = true; // backwards compatible by default + this._actionResults = []; + this._actionHandler = null; + this._executableHandler = false; + this._executableFile = null; // custom name for executable + this._defaultCommandName = null; + this._exitCallback = null; + this._aliases = []; + this._combineFlagAndOptionalValue = true; - return 0; + this._hidden = false; + this._hasHelpOption = true; + this._helpFlags = '-h, --help'; + this._helpDescription = 'display help for command'; + this._helpShortFlag = '-h'; + this._helpLongFlag = '--help'; + this._hasImplicitHelpCommand = undefined; // Deliberately undefined, not decided whether true or false + this._helpCommandName = 'help'; + this._helpCommandnameAndArgs = 'help [command]'; + this._helpCommandDescription = 'display help for command'; } - var allowedOperators = ['>', '>=', '=', '<', '<=']; - - var operatorResMap = { - '>': [1], - '>=': [0, 1], - '=': [0], - '<=': [-1, 0], - '<': [-1], - }; + /** + * Define a command. + * + * There are two styles of command: pay attention to where to put the description. + * + * Examples: + * + * // Command implemented using action handler (description is supplied separately to `.command`) + * program + * .command('clone [destination]') + * .description('clone a repository into a newly created directory') + * .action((source, destination) => { + * console.log('clone command called'); + * }); + * + * // Command implemented using separate executable file (description is second parameter to `.command`) + * program + * .command('start ', 'start named service') + * .command('stop [service]', 'stop named service, or all if no name supplied'); + * + * @param {string} nameAndArgs - command name and arguments, args are `` or `[optional]` and last may also be `variadic...` + * @param {Object|string} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable) + * @param {Object} [execOpts] - configuration options (for executable) + * @return {Command} returns new command for action handler, or `this` for executable command + * @api public + */ - function validateOperator(op) { - if (typeof op !== 'string') { - throw new TypeError( - 'Invalid operator type, expected string but got ' + typeof op - ); + command(nameAndArgs, actionOptsOrExecDesc, execOpts) { + let desc = actionOptsOrExecDesc; + let opts = execOpts; + if (typeof desc === 'object' && desc !== null) { + opts = desc; + desc = null; } - if (allowedOperators.indexOf(op) === -1) { - throw new TypeError( - 'Invalid operator, expected one of ' + allowedOperators.join('|') - ); + opts = opts || {}; + const args = nameAndArgs.split(/ +/); + const cmd = this.createCommand(args.shift()); + + if (desc) { + cmd.description(desc); + cmd._executableHandler = true; } - } + if (opts.isDefault) this._defaultCommandName = cmd._name; - compareVersions.validate = function (version) { - return typeof version === 'string' && semver.test(version); - }; + cmd._hidden = !!(opts.noHelp || opts.hidden); + cmd._hasHelpOption = this._hasHelpOption; + cmd._helpFlags = this._helpFlags; + cmd._helpDescription = this._helpDescription; + cmd._helpShortFlag = this._helpShortFlag; + cmd._helpLongFlag = this._helpLongFlag; + cmd._helpCommandName = this._helpCommandName; + cmd._helpCommandnameAndArgs = this._helpCommandnameAndArgs; + cmd._helpCommandDescription = this._helpCommandDescription; + cmd._exitCallback = this._exitCallback; + cmd._storeOptionsAsProperties = this._storeOptionsAsProperties; + cmd._passCommandToAction = this._passCommandToAction; + cmd._combineFlagAndOptionalValue = this._combineFlagAndOptionalValue; - compareVersions.compare = function (v1, v2, operator) { - // Validate operator - validateOperator(operator); + cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor + this.commands.push(cmd); + cmd._parseExpectedArgs(args); + cmd.parent = this; - // since result of compareVersions can only be -1 or 0 or 1 - // a simple map can be used to replace switch - var res = compareVersions(v1, v2); - return operatorResMap[operator].indexOf(res) > -1; + if (desc) return this; + return cmd; }; - compareVersions.satisfies = function (v, r) { - // if no range operator then "=" - var match = r.match(/^([<>=~^]+)/); - var op = match ? match[1] : '='; - - // if gt/lt/eq then operator compare - if (op !== '^' && op !== '~') return compareVersions.compare(v, r, op); + /** + * Factory routine to create a new unattached command. + * + * See .command() for creating an attached subcommand, which uses this routine to + * create the command. You can override createCommand to customise subcommands. + * + * @param {string} [name] + * @return {Command} new command + * @api public + */ - // else range of either "~" or "^" is assumed - var [v1, v2, v3] = validateAndParse(v); - var [m1, m2, m3] = validateAndParse(r); - if (compareStrings(v1, m1) !== 0) return false; - if (op === '^') { - return compareSegments([v2, v3], [m2, m3]) >= 0; - } - if (compareStrings(v2, m2) !== 0) return false; - return compareStrings(v3, m3) >= 0; + createCommand(name) { + return new Command(name); }; - return compareVersions; -}); - - -/***/ }), + /** + * Add a prepared subcommand. + * + * See .command() for creating an attached subcommand which inherits settings from its parent. + * + * @param {Command} cmd - new subcommand + * @param {Object} [opts] - configuration options + * @return {Command} `this` command for chaining + * @api public + */ -/***/ 53921: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + addCommand(cmd, opts) { + if (!cmd._name) throw new Error('Command passed to .addCommand() must have a name'); -"use strict"; -/*! - * content-disposition - * Copyright(c) 2014-2017 Douglas Christopher Wilson - * MIT Licensed - */ + // To keep things simple, block automatic name generation for deeply nested executables. + // Fail fast and detect when adding rather than later when parsing. + function checkExplicitNames(commandArray) { + commandArray.forEach((cmd) => { + if (cmd._executableHandler && !cmd._executableFile) { + throw new Error(`Must specify executableFile for deeply nested executable: ${cmd.name()}`); + } + checkExplicitNames(cmd.commands); + }); + } + checkExplicitNames(cmd.commands); + opts = opts || {}; + if (opts.isDefault) this._defaultCommandName = cmd._name; + if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation + this.commands.push(cmd); + cmd.parent = this; + return this; + }; -/** - * Module exports. - * @public - */ + /** + * Define argument syntax for the command. + * + * @api public + */ -module.exports = contentDisposition -module.exports.parse = parse + arguments(desc) { + return this._parseExpectedArgs(desc.split(/ +/)); + }; -/** - * Module dependencies. - * @private - */ + /** + * Override default decision whether to add implicit help command. + * + * addHelpCommand() // force on + * addHelpCommand(false); // force off + * addHelpCommand('help [cmd]', 'display help for [cmd]'); // force on with custom details + * + * @return {Command} `this` command for chaining + * @api public + */ -var basename = (__nccwpck_require__(71017).basename) -var Buffer = (__nccwpck_require__(38558).Buffer) + addHelpCommand(enableOrNameAndArgs, description) { + if (enableOrNameAndArgs === false) { + this._hasImplicitHelpCommand = false; + } else { + this._hasImplicitHelpCommand = true; + if (typeof enableOrNameAndArgs === 'string') { + this._helpCommandName = enableOrNameAndArgs.split(' ')[0]; + this._helpCommandnameAndArgs = enableOrNameAndArgs; + } + this._helpCommandDescription = description || this._helpCommandDescription; + } + return this; + }; -/** - * RegExp to match non attr-char, *after* encodeURIComponent (i.e. not including "%") - * @private - */ + /** + * @return {boolean} + * @api private + */ -var ENCODE_URL_ATTR_CHAR_REGEXP = /[\x00-\x20"'()*,/:;<=>?@[\\\]{}\x7f]/g // eslint-disable-line no-control-regex + _lazyHasImplicitHelpCommand() { + if (this._hasImplicitHelpCommand === undefined) { + this._hasImplicitHelpCommand = this.commands.length && !this._actionHandler && !this._findCommand('help'); + } + return this._hasImplicitHelpCommand; + }; -/** - * RegExp to match percent encoding escape. - * @private - */ + /** + * Parse expected `args`. + * + * For example `["[type]"]` becomes `[{ required: false, name: 'type' }]`. + * + * @param {Array} args + * @return {Command} `this` command for chaining + * @api private + */ -var HEX_ESCAPE_REGEXP = /%[0-9A-Fa-f]{2}/ -var HEX_ESCAPE_REPLACE_REGEXP = /%([0-9A-Fa-f]{2})/g + _parseExpectedArgs(args) { + if (!args.length) return; + args.forEach((arg) => { + const argDetails = { + required: false, + name: '', + variadic: false + }; -/** - * RegExp to match non-latin1 characters. - * @private - */ + switch (arg[0]) { + case '<': + argDetails.required = true; + argDetails.name = arg.slice(1, -1); + break; + case '[': + argDetails.name = arg.slice(1, -1); + break; + } -var NON_LATIN1_REGEXP = /[^\x20-\x7e\xa0-\xff]/g + if (argDetails.name.length > 3 && argDetails.name.slice(-3) === '...') { + argDetails.variadic = true; + argDetails.name = argDetails.name.slice(0, -3); + } + if (argDetails.name) { + this._args.push(argDetails); + } + }); + this._args.forEach((arg, i) => { + if (arg.variadic && i < this._args.length - 1) { + throw new Error(`only the last argument can be variadic '${arg.name}'`); + } + }); + return this; + }; -/** - * RegExp to match quoted-pair in RFC 2616 - * - * quoted-pair = "\" CHAR - * CHAR = - * @private - */ + /** + * Register callback to use as replacement for calling process.exit. + * + * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing + * @return {Command} `this` command for chaining + * @api public + */ -var QESC_REGEXP = /\\([\u0000-\u007f])/g // eslint-disable-line no-control-regex + exitOverride(fn) { + if (fn) { + this._exitCallback = fn; + } else { + this._exitCallback = (err) => { + if (err.code !== 'commander.executeSubCommandAsync') { + throw err; + } else { + // Async callback from spawn events, not useful to throw. + } + }; + } + return this; + }; -/** - * RegExp to match chars that must be quoted-pair in RFC 2616 - * @private - */ - -var QUOTE_REGEXP = /([\\"])/g - -/** - * RegExp for various RFC 2616 grammar - * - * parameter = token "=" ( token | quoted-string ) - * token = 1* - * separators = "(" | ")" | "<" | ">" | "@" - * | "," | ";" | ":" | "\" | <"> - * | "/" | "[" | "]" | "?" | "=" - * | "{" | "}" | SP | HT - * quoted-string = ( <"> *(qdtext | quoted-pair ) <"> ) - * qdtext = > - * quoted-pair = "\" CHAR - * CHAR = - * TEXT = - * LWS = [CRLF] 1*( SP | HT ) - * CRLF = CR LF - * CR = - * LF = - * SP = - * HT = - * CTL = - * OCTET = - * @private - */ - -var PARAM_REGEXP = /;[\x09\x20]*([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*=[\x09\x20]*("(?:[\x20!\x23-\x5b\x5d-\x7e\x80-\xff]|\\[\x20-\x7e])*"|[!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*/g // eslint-disable-line no-control-regex -var TEXT_REGEXP = /^[\x20-\x7e\x80-\xff]+$/ -var TOKEN_REGEXP = /^[!#$%&'*+.0-9A-Z^_`a-z|~-]+$/ - -/** - * RegExp for various RFC 5987 grammar - * - * ext-value = charset "'" [ language ] "'" value-chars - * charset = "UTF-8" / "ISO-8859-1" / mime-charset - * mime-charset = 1*mime-charsetc - * mime-charsetc = ALPHA / DIGIT - * / "!" / "#" / "$" / "%" / "&" - * / "+" / "-" / "^" / "_" / "`" - * / "{" / "}" / "~" - * language = ( 2*3ALPHA [ extlang ] ) - * / 4ALPHA - * / 5*8ALPHA - * extlang = *3( "-" 3ALPHA ) - * value-chars = *( pct-encoded / attr-char ) - * pct-encoded = "%" HEXDIG HEXDIG - * attr-char = ALPHA / DIGIT - * / "!" / "#" / "$" / "&" / "+" / "-" / "." - * / "^" / "_" / "`" / "|" / "~" - * @private - */ - -var EXT_VALUE_REGEXP = /^([A-Za-z0-9!#$%&+\-^_`{}~]+)'(?:[A-Za-z]{2,3}(?:-[A-Za-z]{3}){0,3}|[A-Za-z]{4,8}|)'((?:%[0-9A-Fa-f]{2}|[A-Za-z0-9!#$&+.^_`|~-])+)$/ + /** + * Call process.exit, and _exitCallback if defined. + * + * @param {number} exitCode exit code for using with process.exit + * @param {string} code an id string representing the error + * @param {string} message human-readable description of the error + * @return never + * @api private + */ -/** - * RegExp for various RFC 6266 grammar - * - * disposition-type = "inline" | "attachment" | disp-ext-type - * disp-ext-type = token - * disposition-parm = filename-parm | disp-ext-parm - * filename-parm = "filename" "=" value - * | "filename*" "=" ext-value - * disp-ext-parm = token "=" value - * | ext-token "=" ext-value - * ext-token = - * @private - */ + _exit(exitCode, code, message) { + if (this._exitCallback) { + this._exitCallback(new CommanderError(exitCode, code, message)); + // Expecting this line is not reached. + } + process.exit(exitCode); + }; -var DISPOSITION_TYPE_REGEXP = /^([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*(?:$|;)/ // eslint-disable-line no-control-regex + /** + * Register callback `fn` for the command. + * + * Examples: + * + * program + * .command('help') + * .description('display verbose help') + * .action(function() { + * // output help here + * }); + * + * @param {Function} fn + * @return {Command} `this` command for chaining + * @api public + */ -/** - * Create an attachment Content-Disposition header. - * - * @param {string} [filename] - * @param {object} [options] - * @param {string} [options.type=attachment] - * @param {string|boolean} [options.fallback=true] - * @return {string} - * @public - */ + action(fn) { + const listener = (args) => { + // The .action callback takes an extra parameter which is the command or options. + const expectedArgsCount = this._args.length; + const actionArgs = args.slice(0, expectedArgsCount); + if (this._passCommandToAction) { + actionArgs[expectedArgsCount] = this; + } else { + actionArgs[expectedArgsCount] = this.opts(); + } + // Add the extra arguments so available too. + if (args.length > expectedArgsCount) { + actionArgs.push(args.slice(expectedArgsCount)); + } -function contentDisposition (filename, options) { - var opts = options || {} + const actionResult = fn.apply(this, actionArgs); + // Remember result in case it is async. Assume parseAsync getting called on root. + let rootCommand = this; + while (rootCommand.parent) { + rootCommand = rootCommand.parent; + } + rootCommand._actionResults.push(actionResult); + }; + this._actionHandler = listener; + return this; + }; - // get type - var type = opts.type || 'attachment' + /** + * Internal routine to check whether there is a clash storing option value with a Command property. + * + * @param {Option} option + * @api private + */ - // get parameters - var params = createparams(filename, opts.fallback) + _checkForOptionNameClash(option) { + if (!this._storeOptionsAsProperties || this._storeOptionsAsPropertiesCalled) { + // Storing options safely, or user has been explicit and up to them. + return; + } + // User may override help, and hard to tell if worth warning. + if (option.name() === 'help') { + return; + } - // format into string - return format(new ContentDisposition(type, params)) -} + const commandProperty = this._getOptionValue(option.attributeName()); + if (commandProperty === undefined) { + // no clash + return; + } -/** - * Create parameters object from filename and fallback. - * - * @param {string} [filename] - * @param {string|boolean} [fallback=true] - * @return {object} - * @private - */ + let foundClash = true; + if (option.negate) { + // It is ok if define foo before --no-foo. + const positiveLongFlag = option.long.replace(/^--no-/, '--'); + foundClash = !this._findOption(positiveLongFlag); + } else if (option.long) { + const negativeLongFlag = option.long.replace(/^--/, '--no-'); + foundClash = !this._findOption(negativeLongFlag); + } -function createparams (filename, fallback) { - if (filename === undefined) { - return - } + if (foundClash) { + throw new Error(`option '${option.name()}' clashes with existing property '${option.attributeName()}' on Command +- call storeOptionsAsProperties(false) to store option values safely, +- or call storeOptionsAsProperties(true) to suppress this check, +- or change option name - var params = {} +Read more on https://git.io/JJc0W`); + } + }; - if (typeof filename !== 'string') { - throw new TypeError('filename must be a string') - } + /** + * Internal implementation shared by .option() and .requiredOption() + * + * @param {Object} config + * @param {string} flags + * @param {string} description + * @param {Function|*} [fn] - custom option processing function or default value + * @param {*} [defaultValue] + * @return {Command} `this` command for chaining + * @api private + */ - // fallback defaults to true - if (fallback === undefined) { - fallback = true - } + _optionEx(config, flags, description, fn, defaultValue) { + const option = new Option(flags, description); + const oname = option.name(); + const name = option.attributeName(); + option.mandatory = !!config.mandatory; - if (typeof fallback !== 'string' && typeof fallback !== 'boolean') { - throw new TypeError('fallback must be a string or boolean') - } + this._checkForOptionNameClash(option); - if (typeof fallback === 'string' && NON_LATIN1_REGEXP.test(fallback)) { - throw new TypeError('fallback must be ISO-8859-1 string') - } + // default as 3rd arg + if (typeof fn !== 'function') { + if (fn instanceof RegExp) { + // This is a bit simplistic (especially no error messages), and probably better handled by caller using custom option processing. + // No longer documented in README, but still present for backwards compatibility. + const regex = fn; + fn = (val, def) => { + const m = regex.exec(val); + return m ? m[0] : def; + }; + } else { + defaultValue = fn; + fn = null; + } + } - // restrict to file base name - var name = basename(filename) + // preassign default value for --no-*, [optional], , or plain flag if boolean value + if (option.negate || option.optional || option.required || typeof defaultValue === 'boolean') { + // when --no-foo we make sure default is true, unless a --foo option is already defined + if (option.negate) { + const positiveLongFlag = option.long.replace(/^--no-/, '--'); + defaultValue = this._findOption(positiveLongFlag) ? this._getOptionValue(name) : true; + } + // preassign only if we have a default + if (defaultValue !== undefined) { + this._setOptionValue(name, defaultValue); + option.defaultValue = defaultValue; + } + } - // determine if name is suitable for quoted string - var isQuotedString = TEXT_REGEXP.test(name) + // register the option + this.options.push(option); - // generate fallback name - var fallbackName = typeof fallback !== 'string' - ? fallback && getlatin1(name) - : basename(fallback) - var hasFallback = typeof fallbackName === 'string' && fallbackName !== name + // when it's passed assign the value + // and conditionally invoke the callback + this.on('option:' + oname, (val) => { + const oldValue = this._getOptionValue(name); - // set extended filename parameter - if (hasFallback || !isQuotedString || HEX_ESCAPE_REGEXP.test(name)) { - params['filename*'] = name - } + // custom processing + if (val !== null && fn) { + val = fn(val, oldValue === undefined ? defaultValue : oldValue); + } else if (val !== null && option.variadic) { + if (oldValue === defaultValue || !Array.isArray(oldValue)) { + val = [val]; + } else { + val = oldValue.concat(val); + } + } - // set filename parameter - if (isQuotedString || hasFallback) { - params.filename = hasFallback - ? fallbackName - : name - } + // unassigned or boolean value + if (typeof oldValue === 'boolean' || typeof oldValue === 'undefined') { + // if no value, negate false, and we have a default, then use it! + if (val == null) { + this._setOptionValue(name, option.negate + ? false + : defaultValue || true); + } else { + this._setOptionValue(name, val); + } + } else if (val !== null) { + // reassign + this._setOptionValue(name, option.negate ? false : val); + } + }); - return params -} + return this; + }; -/** - * Format object to Content-Disposition header. - * - * @param {object} obj - * @param {string} obj.type - * @param {object} [obj.parameters] - * @return {string} - * @private - */ + /** + * Define option with `flags`, `description` and optional + * coercion `fn`. + * + * The `flags` string should contain both the short and long flags, + * separated by comma, a pipe or space. The following are all valid + * all will output this way when `--help` is used. + * + * "-p, --pepper" + * "-p|--pepper" + * "-p --pepper" + * + * Examples: + * + * // simple boolean defaulting to undefined + * program.option('-p, --pepper', 'add pepper'); + * + * program.pepper + * // => undefined + * + * --pepper + * program.pepper + * // => true + * + * // simple boolean defaulting to true (unless non-negated option is also defined) + * program.option('-C, --no-cheese', 'remove cheese'); + * + * program.cheese + * // => true + * + * --no-cheese + * program.cheese + * // => false + * + * // required argument + * program.option('-C, --chdir ', 'change the working directory'); + * + * --chdir /tmp + * program.chdir + * // => "/tmp" + * + * // optional argument + * program.option('-c, --cheese [type]', 'add cheese [marble]'); + * + * @param {string} flags + * @param {string} description + * @param {Function|*} [fn] - custom option processing function or default value + * @param {*} [defaultValue] + * @return {Command} `this` command for chaining + * @api public + */ -function format (obj) { - var parameters = obj.parameters - var type = obj.type + option(flags, description, fn, defaultValue) { + return this._optionEx({}, flags, description, fn, defaultValue); + }; - if (!type || typeof type !== 'string' || !TOKEN_REGEXP.test(type)) { - throw new TypeError('invalid type') - } + /** + * Add a required option which must have a value after parsing. This usually means + * the option must be specified on the command line. (Otherwise the same as .option().) + * + * The `flags` string should contain both the short and long flags, separated by comma, a pipe or space. + * + * @param {string} flags + * @param {string} description + * @param {Function|*} [fn] - custom option processing function or default value + * @param {*} [defaultValue] + * @return {Command} `this` command for chaining + * @api public + */ - // start with normalized type - var string = String(type).toLowerCase() + requiredOption(flags, description, fn, defaultValue) { + return this._optionEx({ mandatory: true }, flags, description, fn, defaultValue); + }; - // append parameters - if (parameters && typeof parameters === 'object') { - var param - var params = Object.keys(parameters).sort() + /** + * Alter parsing of short flags with optional values. + * + * Examples: + * + * // for `.option('-f,--flag [value]'): + * .combineFlagAndOptionalValue(true) // `-f80` is treated like `--flag=80`, this is the default behaviour + * .combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b` + * + * @param {Boolean} [arg] - if `true` or omitted, an optional value can be specified directly after the flag. + * @api public + */ + combineFlagAndOptionalValue(arg) { + this._combineFlagAndOptionalValue = (arg === undefined) || arg; + return this; + }; - for (var i = 0; i < params.length; i++) { - param = params[i] + /** + * Allow unknown options on the command line. + * + * @param {Boolean} [arg] - if `true` or omitted, no error will be thrown + * for unknown options. + * @api public + */ + allowUnknownOption(arg) { + this._allowUnknownOption = (arg === undefined) || arg; + return this; + }; - var val = param.substr(-1) === '*' - ? ustring(parameters[param]) - : qstring(parameters[param]) + /** + * Whether to store option values as properties on command object, + * or store separately (specify false). In both cases the option values can be accessed using .opts(). + * + * @param {boolean} value + * @return {Command} `this` command for chaining + * @api public + */ - string += '; ' + param + '=' + val + storeOptionsAsProperties(value) { + this._storeOptionsAsPropertiesCalled = true; + this._storeOptionsAsProperties = (value === undefined) || value; + if (this.options.length) { + throw new Error('call .storeOptionsAsProperties() before adding options'); } - } + return this; + }; - return string -} + /** + * Whether to pass command to action handler, + * or just the options (specify false). + * + * @param {boolean} value + * @return {Command} `this` command for chaining + * @api public + */ -/** - * Decode a RFC 5987 field value (gracefully). - * - * @param {string} str - * @return {string} - * @private - */ + passCommandToAction(value) { + this._passCommandToAction = (value === undefined) || value; + return this; + }; -function decodefield (str) { - var match = EXT_VALUE_REGEXP.exec(str) + /** + * Store option value + * + * @param {string} key + * @param {Object} value + * @api private + */ - if (!match) { - throw new TypeError('invalid extended field value') - } + _setOptionValue(key, value) { + if (this._storeOptionsAsProperties) { + this[key] = value; + } else { + this._optionValues[key] = value; + } + }; - var charset = match[1].toLowerCase() - var encoded = match[2] - var value + /** + * Retrieve option value + * + * @param {string} key + * @return {Object} value + * @api private + */ - // to binary string - var binary = encoded.replace(HEX_ESCAPE_REPLACE_REGEXP, pdecode) + _getOptionValue(key) { + if (this._storeOptionsAsProperties) { + return this[key]; + } + return this._optionValues[key]; + }; - switch (charset) { - case 'iso-8859-1': - value = getlatin1(binary) - break - case 'utf-8': - value = Buffer.from(binary, 'binary').toString('utf8') - break - default: - throw new TypeError('unsupported charset in extended field') - } - - return value -} + /** + * Parse `argv`, setting options and invoking commands when defined. + * + * The default expectation is that the arguments are from node and have the application as argv[0] + * and the script being run in argv[1], with user parameters after that. + * + * Examples: + * + * program.parse(process.argv); + * program.parse(); // implicitly use process.argv and auto-detect node vs electron conventions + * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0] + * + * @param {string[]} [argv] - optional, defaults to process.argv + * @param {Object} [parseOptions] - optionally specify style of options with from: node/user/electron + * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron' + * @return {Command} `this` command for chaining + * @api public + */ -/** - * Get ISO-8859-1 version of string. - * - * @param {string} val - * @return {string} - * @private - */ + parse(argv, parseOptions) { + if (argv !== undefined && !Array.isArray(argv)) { + throw new Error('first parameter to parse must be array or undefined'); + } + parseOptions = parseOptions || {}; -function getlatin1 (val) { - // simple Unicode -> ISO-8859-1 transformation - return String(val).replace(NON_LATIN1_REGEXP, '?') -} + // Default to using process.argv + if (argv === undefined) { + argv = process.argv; + // @ts-ignore + if (process.versions && process.versions.electron) { + parseOptions.from = 'electron'; + } + } + this.rawArgs = argv.slice(); -/** - * Parse Content-Disposition header string. - * - * @param {string} string - * @return {object} - * @public - */ + // make it a little easier for callers by supporting various argv conventions + let userArgs; + switch (parseOptions.from) { + case undefined: + case 'node': + this._scriptPath = argv[1]; + userArgs = argv.slice(2); + break; + case 'electron': + // @ts-ignore + if (process.defaultApp) { + this._scriptPath = argv[1]; + userArgs = argv.slice(2); + } else { + userArgs = argv.slice(1); + } + break; + case 'user': + userArgs = argv.slice(0); + break; + default: + throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`); + } + if (!this._scriptPath && process.mainModule) { + this._scriptPath = process.mainModule.filename; + } -function parse (string) { - if (!string || typeof string !== 'string') { - throw new TypeError('argument string is required') - } + // Guess name, used in usage in help. + this._name = this._name || (this._scriptPath && path.basename(this._scriptPath, path.extname(this._scriptPath))); - var match = DISPOSITION_TYPE_REGEXP.exec(string) + // Let's go! + this._parseCommand([], userArgs); - if (!match) { - throw new TypeError('invalid type format') - } + return this; + }; - // normalize type - var index = match[0].length - var type = match[1].toLowerCase() + /** + * Parse `argv`, setting options and invoking commands when defined. + * + * Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise. + * + * The default expectation is that the arguments are from node and have the application as argv[0] + * and the script being run in argv[1], with user parameters after that. + * + * Examples: + * + * program.parseAsync(process.argv); + * program.parseAsync(); // implicitly use process.argv and auto-detect node vs electron conventions + * program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0] + * + * @param {string[]} [argv] + * @param {Object} [parseOptions] + * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron' + * @return {Promise} + * @api public + */ - var key - var names = [] - var params = {} - var value + parseAsync(argv, parseOptions) { + this.parse(argv, parseOptions); + return Promise.all(this._actionResults).then(() => this); + }; - // calculate index to start at - index = PARAM_REGEXP.lastIndex = match[0].substr(-1) === ';' - ? index - 1 - : index + /** + * Execute a sub-command executable. + * + * @api private + */ - // match parameters - while ((match = PARAM_REGEXP.exec(string))) { - if (match.index !== index) { - throw new TypeError('invalid parameter format') - } + _executeSubCommand(subcommand, args) { + args = args.slice(); + let launchWithNode = false; // Use node for source targets so do not need to get permissions correct, and on Windows. + const sourceExt = ['.js', '.ts', '.tsx', '.mjs']; - index += match[0].length - key = match[1].toLowerCase() - value = match[2] + // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command. + this._checkForMissingMandatoryOptions(); - if (names.indexOf(key) !== -1) { - throw new TypeError('invalid duplicate parameter') + // Want the entry script as the reference for command name and directory for searching for other files. + let scriptPath = this._scriptPath; + // Fallback in case not set, due to how Command created or called. + if (!scriptPath && process.mainModule) { + scriptPath = process.mainModule.filename; } - names.push(key) - - if (key.indexOf('*') + 1 === key.length) { - // decode extended value - key = key.slice(0, -1) - value = decodefield(value) - - // overwrite existing value - params[key] = value - continue + let baseDir; + try { + const resolvedLink = fs.realpathSync(scriptPath); + baseDir = path.dirname(resolvedLink); + } catch (e) { + baseDir = '.'; // dummy, probably not going to find executable! } - if (typeof params[key] === 'string') { - continue + // name of the subcommand, like `pm-install` + let bin = path.basename(scriptPath, path.extname(scriptPath)) + '-' + subcommand._name; + if (subcommand._executableFile) { + bin = subcommand._executableFile; } - if (value[0] === '"') { - // remove quotes and escapes - value = value - .substr(1, value.length - 2) - .replace(QESC_REGEXP, '$1') + const localBin = path.join(baseDir, bin); + if (fs.existsSync(localBin)) { + // prefer local `./` to bin in the $PATH + bin = localBin; + } else { + // Look for source files. + sourceExt.forEach((ext) => { + if (fs.existsSync(`${localBin}${ext}`)) { + bin = `${localBin}${ext}`; + } + }); } + launchWithNode = sourceExt.includes(path.extname(bin)); - params[key] = value - } - - if (index !== -1 && index !== string.length) { - throw new TypeError('invalid parameter format') - } + let proc; + if (process.platform !== 'win32') { + if (launchWithNode) { + args.unshift(bin); + // add executable arguments to spawn + args = incrementNodeInspectorPort(process.execArgv).concat(args); - return new ContentDisposition(type, params) -} + proc = spawn(process.argv[0], args, { stdio: 'inherit' }); + } else { + proc = spawn(bin, args, { stdio: 'inherit' }); + } + } else { + args.unshift(bin); + // add executable arguments to spawn + args = incrementNodeInspectorPort(process.execArgv).concat(args); + proc = spawn(process.execPath, args, { stdio: 'inherit' }); + } -/** - * Percent decode a single character. - * - * @param {string} str - * @param {string} hex - * @return {string} - * @private - */ + const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP']; + signals.forEach((signal) => { + // @ts-ignore + process.on(signal, () => { + if (proc.killed === false && proc.exitCode === null) { + proc.kill(signal); + } + }); + }); -function pdecode (str, hex) { - return String.fromCharCode(parseInt(hex, 16)) -} + // By default terminate process when spawned process terminates. + // Suppressing the exit if exitCallback defined is a bit messy and of limited use, but does allow process to stay running! + const exitCallback = this._exitCallback; + if (!exitCallback) { + proc.on('close', process.exit.bind(process)); + } else { + proc.on('close', () => { + exitCallback(new CommanderError(process.exitCode || 0, 'commander.executeSubCommandAsync', '(close)')); + }); + } + proc.on('error', (err) => { + // @ts-ignore + if (err.code === 'ENOENT') { + const executableMissing = `'${bin}' does not exist + - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead + - if the default executable name is not suitable, use the executableFile option to supply a custom name`; + throw new Error(executableMissing); + // @ts-ignore + } else if (err.code === 'EACCES') { + throw new Error(`'${bin}' not executable`); + } + if (!exitCallback) { + process.exit(1); + } else { + const wrappedError = new CommanderError(1, 'commander.executeSubCommandAsync', '(error)'); + wrappedError.nestedError = err; + exitCallback(wrappedError); + } + }); -/** - * Percent encode a single character. - * - * @param {string} char - * @return {string} - * @private - */ + // Store the reference to the child process + this.runningCommand = proc; + }; -function pencode (char) { - return '%' + String(char) - .charCodeAt(0) - .toString(16) - .toUpperCase() -} + /** + * @api private + */ + _dispatchSubcommand(commandName, operands, unknown) { + const subCommand = this._findCommand(commandName); + if (!subCommand) this._helpAndError(); -/** - * Quote a string for HTTP. - * - * @param {string} val - * @return {string} - * @private - */ + if (subCommand._executableHandler) { + this._executeSubCommand(subCommand, operands.concat(unknown)); + } else { + subCommand._parseCommand(operands, unknown); + } + }; -function qstring (val) { - var str = String(val) + /** + * Process arguments in context of this command. + * + * @api private + */ - return '"' + str.replace(QUOTE_REGEXP, '\\$1') + '"' -} + _parseCommand(operands, unknown) { + const parsed = this.parseOptions(unknown); + operands = operands.concat(parsed.operands); + unknown = parsed.unknown; + this.args = operands.concat(unknown); -/** - * Encode a Unicode string for HTTP (RFC 5987). - * - * @param {string} val - * @return {string} - * @private - */ + if (operands && this._findCommand(operands[0])) { + this._dispatchSubcommand(operands[0], operands.slice(1), unknown); + } else if (this._lazyHasImplicitHelpCommand() && operands[0] === this._helpCommandName) { + if (operands.length === 1) { + this.help(); + } else { + this._dispatchSubcommand(operands[1], [], [this._helpLongFlag]); + } + } else if (this._defaultCommandName) { + outputHelpIfRequested(this, unknown); // Run the help for default command from parent rather than passing to default command + this._dispatchSubcommand(this._defaultCommandName, operands, unknown); + } else { + if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) { + // probably missing subcommand and no handler, user needs help + this._helpAndError(); + } -function ustring (val) { - var str = String(val) + outputHelpIfRequested(this, parsed.unknown); + this._checkForMissingMandatoryOptions(); + if (parsed.unknown.length > 0) { + this.unknownOption(parsed.unknown[0]); + } - // percent encode as UTF-8 - var encoded = encodeURIComponent(str) - .replace(ENCODE_URL_ATTR_CHAR_REGEXP, pencode) + if (this._actionHandler) { + const args = this.args.slice(); + this._args.forEach((arg, i) => { + if (arg.required && args[i] == null) { + this.missingArgument(arg.name); + } else if (arg.variadic) { + args[i] = args.splice(i); + } + }); - return 'UTF-8\'\'' + encoded -} + this._actionHandler(args); + this.emit('command:' + this.name(), operands, unknown); + } else if (operands.length) { + if (this._findCommand('*')) { + this._dispatchSubcommand('*', operands, unknown); + } else if (this.listenerCount('command:*')) { + this.emit('command:*', operands, unknown); + } else if (this.commands.length) { + this.unknownCommand(); + } + } else if (this.commands.length) { + // This command has subcommands and nothing hooked up at this level, so display help. + this._helpAndError(); + } else { + // fall through for caller to handle after calling .parse() + } + } + }; -/** - * Class for parsed Content-Disposition header for v8 optimization - * - * @public - * @param {string} type - * @param {object} parameters - * @constructor - */ + /** + * Find matching command. + * + * @api private + */ + _findCommand(name) { + if (!name) return undefined; + return this.commands.find(cmd => cmd._name === name || cmd._aliases.includes(name)); + }; -function ContentDisposition (type, parameters) { - this.type = type - this.parameters = parameters -} + /** + * Return an option matching `arg` if any. + * + * @param {string} arg + * @return {Option} + * @api private + */ + _findOption(arg) { + return this.options.find(option => option.is(arg)); + }; -/***/ }), + /** + * Display an error message if a mandatory option does not have a value. + * Lazy calling after checking for help flags from leaf subcommand. + * + * @api private + */ -/***/ 38558: -/***/ ((module, exports, __nccwpck_require__) => { + _checkForMissingMandatoryOptions() { + // Walk up hierarchy so can call in subcommand after checking for displaying help. + for (let cmd = this; cmd; cmd = cmd.parent) { + cmd.options.forEach((anOption) => { + if (anOption.mandatory && (cmd._getOptionValue(anOption.attributeName()) === undefined)) { + cmd.missingMandatoryOptionValue(anOption); + } + }); + } + }; -/*! safe-buffer. MIT License. Feross Aboukhadijeh */ -/* eslint-disable node/no-deprecated-api */ -var buffer = __nccwpck_require__(14300) -var Buffer = buffer.Buffer + /** + * Parse options from `argv` removing known options, + * and return argv split into operands and unknown arguments. + * + * Examples: + * + * argv => operands, unknown + * --known kkk op => [op], [] + * op --known kkk => [op], [] + * sub --unknown uuu op => [sub], [--unknown uuu op] + * sub -- --unknown uuu op => [sub --unknown uuu op], [] + * + * @param {String[]} argv + * @return {{operands: String[], unknown: String[]}} + * @api public + */ -// alternative to using Object.keys for old browsers -function copyProps (src, dst) { - for (var key in src) { - dst[key] = src[key] - } -} -if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { - module.exports = buffer -} else { - // Copy properties from require('buffer') - copyProps(buffer, exports) - exports.Buffer = SafeBuffer -} + parseOptions(argv) { + const operands = []; // operands, not options or values + const unknown = []; // first unknown option and remaining unknown args + let dest = operands; + const args = argv.slice(); -function SafeBuffer (arg, encodingOrOffset, length) { - return Buffer(arg, encodingOrOffset, length) -} + function maybeOption(arg) { + return arg.length > 1 && arg[0] === '-'; + } -SafeBuffer.prototype = Object.create(Buffer.prototype) + // parse options + let activeVariadicOption = null; + while (args.length) { + const arg = args.shift(); -// Copy static methods from Buffer -copyProps(Buffer, SafeBuffer) + // literal + if (arg === '--') { + if (dest === unknown) dest.push(arg); + dest.push(...args); + break; + } -SafeBuffer.from = function (arg, encodingOrOffset, length) { - if (typeof arg === 'number') { - throw new TypeError('Argument must not be a number') - } - return Buffer(arg, encodingOrOffset, length) -} + if (activeVariadicOption && !maybeOption(arg)) { + this.emit(`option:${activeVariadicOption.name()}`, arg); + continue; + } + activeVariadicOption = null; -SafeBuffer.alloc = function (size, fill, encoding) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - var buf = Buffer(size) - if (fill !== undefined) { - if (typeof encoding === 'string') { - buf.fill(fill, encoding) - } else { - buf.fill(fill) - } - } else { - buf.fill(0) - } - return buf -} + if (maybeOption(arg)) { + const option = this._findOption(arg); + // recognised option, call listener to assign value with possible custom processing + if (option) { + if (option.required) { + const value = args.shift(); + if (value === undefined) this.optionMissingArgument(option); + this.emit(`option:${option.name()}`, value); + } else if (option.optional) { + let value = null; + // historical behaviour is optional value is following arg unless an option + if (args.length > 0 && !maybeOption(args[0])) { + value = args.shift(); + } + this.emit(`option:${option.name()}`, value); + } else { // boolean flag + this.emit(`option:${option.name()}`); + } + activeVariadicOption = option.variadic ? option : null; + continue; + } + } -SafeBuffer.allocUnsafe = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - return Buffer(size) -} + // Look for combo options following single dash, eat first one if known. + if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') { + const option = this._findOption(`-${arg[1]}`); + if (option) { + if (option.required || (option.optional && this._combineFlagAndOptionalValue)) { + // option with value following in same argument + this.emit(`option:${option.name()}`, arg.slice(2)); + } else { + // boolean option, emit and put back remainder of arg for further processing + this.emit(`option:${option.name()}`); + args.unshift(`-${arg.slice(2)}`); + } + continue; + } + } -SafeBuffer.allocUnsafeSlow = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - return buffer.SlowBuffer(size) -} + // Look for known long flag with value, like --foo=bar + if (/^--[^=]+=/.test(arg)) { + const index = arg.indexOf('='); + const option = this._findOption(arg.slice(0, index)); + if (option && (option.required || option.optional)) { + this.emit(`option:${option.name()}`, arg.slice(index + 1)); + continue; + } + } + // looks like an option but unknown, unknowns from here + if (arg.length > 1 && arg[0] === '-') { + dest = unknown; + } -/***/ }), + // add arg + dest.push(arg); + } -/***/ 99915: -/***/ ((__unused_webpack_module, exports) => { + return { operands, unknown }; + }; -"use strict"; -/*! - * content-type - * Copyright(c) 2015 Douglas Christopher Wilson - * MIT Licensed - */ + /** + * Return an object containing options as key-value pairs + * + * @return {Object} + * @api public + */ + opts() { + if (this._storeOptionsAsProperties) { + // Preserve original behaviour so backwards compatible when still using properties + const result = {}; + const len = this.options.length; + for (let i = 0; i < len; i++) { + const key = this.options[i].attributeName(); + result[key] = key === this._versionOptionName ? this._version : this[key]; + } + return result; + } + return this._optionValues; + }; -/** - * RegExp to match *( ";" parameter ) in RFC 7231 sec 3.1.1.1 - * - * parameter = token "=" ( token / quoted-string ) - * token = 1*tchar - * tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" - * / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" - * / DIGIT / ALPHA - * ; any VCHAR, except delimiters - * quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE - * qdtext = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text - * obs-text = %x80-FF - * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) - */ -var PARAM_REGEXP = /; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g -var TEXT_REGEXP = /^[\u000b\u0020-\u007e\u0080-\u00ff]+$/ -var TOKEN_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/ + /** + * Argument `name` is missing. + * + * @param {string} name + * @api private + */ -/** - * RegExp to match quoted-pair in RFC 7230 sec 3.2.6 - * - * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) - * obs-text = %x80-FF - */ -var QESC_REGEXP = /\\([\u000b\u0020-\u00ff])/g + missingArgument(name) { + const message = `error: missing required argument '${name}'`; + console.error(message); + this._exit(1, 'commander.missingArgument', message); + }; -/** - * RegExp to match chars that must be quoted-pair in RFC 7230 sec 3.2.6 - */ -var QUOTE_REGEXP = /([\\"])/g + /** + * `Option` is missing an argument, but received `flag` or nothing. + * + * @param {Option} option + * @param {string} [flag] + * @api private + */ -/** - * RegExp to match type in RFC 7231 sec 3.1.1.1 - * - * media-type = type "/" subtype - * type = token - * subtype = token - */ -var TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/ + optionMissingArgument(option, flag) { + let message; + if (flag) { + message = `error: option '${option.flags}' argument missing, got '${flag}'`; + } else { + message = `error: option '${option.flags}' argument missing`; + } + console.error(message); + this._exit(1, 'commander.optionMissingArgument', message); + }; -/** - * Module exports. - * @public - */ + /** + * `Option` does not have a value, and is a mandatory option. + * + * @param {Option} option + * @api private + */ -exports.format = format -exports.parse = parse + missingMandatoryOptionValue(option) { + const message = `error: required option '${option.flags}' not specified`; + console.error(message); + this._exit(1, 'commander.missingMandatoryOptionValue', message); + }; -/** - * Format object to media type. - * - * @param {object} obj - * @return {string} - * @public - */ + /** + * Unknown option `flag`. + * + * @param {string} flag + * @api private + */ -function format (obj) { - if (!obj || typeof obj !== 'object') { - throw new TypeError('argument obj is required') - } + unknownOption(flag) { + if (this._allowUnknownOption) return; + const message = `error: unknown option '${flag}'`; + console.error(message); + this._exit(1, 'commander.unknownOption', message); + }; - var parameters = obj.parameters - var type = obj.type + /** + * Unknown command. + * + * @api private + */ - if (!type || !TYPE_REGEXP.test(type)) { - throw new TypeError('invalid type') - } + unknownCommand() { + const partCommands = [this.name()]; + for (let parentCmd = this.parent; parentCmd; parentCmd = parentCmd.parent) { + partCommands.unshift(parentCmd.name()); + } + const fullCommand = partCommands.join(' '); + const message = `error: unknown command '${this.args[0]}'.` + + (this._hasHelpOption ? ` See '${fullCommand} ${this._helpLongFlag}'.` : ''); + console.error(message); + this._exit(1, 'commander.unknownCommand', message); + }; - var string = type + /** + * Set the program version to `str`. + * + * This method auto-registers the "-V, --version" flag + * which will print the version number when passed. + * + * You can optionally supply the flags and description to override the defaults. + * + * @param {string} str + * @param {string} [flags] + * @param {string} [description] + * @return {this | string} `this` command for chaining, or version string if no arguments + * @api public + */ - // append parameters - if (parameters && typeof parameters === 'object') { - var param - var params = Object.keys(parameters).sort() + version(str, flags, description) { + if (str === undefined) return this._version; + this._version = str; + flags = flags || '-V, --version'; + description = description || 'output the version number'; + const versionOption = new Option(flags, description); + this._versionOptionName = versionOption.attributeName(); + this.options.push(versionOption); + this.on('option:' + versionOption.name(), () => { + process.stdout.write(str + '\n'); + this._exit(0, 'commander.version', str); + }); + return this; + }; - for (var i = 0; i < params.length; i++) { - param = params[i] + /** + * Set the description to `str`. + * + * @param {string} str + * @param {Object} [argsDescription] + * @return {string|Command} + * @api public + */ - if (!TOKEN_REGEXP.test(param)) { - throw new TypeError('invalid parameter name') - } + description(str, argsDescription) { + if (str === undefined && argsDescription === undefined) return this._description; + this._description = str; + this._argsDescription = argsDescription; + return this; + }; - string += '; ' + param + '=' + qstring(parameters[param]) + /** + * Set an alias for the command. + * + * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help. + * + * @param {string} [alias] + * @return {string|Command} + * @api public + */ + + alias(alias) { + if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility + + let command = this; + if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) { + // assume adding alias for last added executable subcommand, rather than this + command = this.commands[this.commands.length - 1]; } - } - return string -} + if (alias === command._name) throw new Error('Command alias can\'t be the same as its name'); -/** - * Parse media type to object. - * - * @param {string|object} string - * @return {Object} - * @public - */ + command._aliases.push(alias); + return this; + }; -function parse (string) { - if (!string) { - throw new TypeError('argument string is required') - } + /** + * Set aliases for the command. + * + * Only the first alias is shown in the auto-generated help. + * + * @param {string[]} [aliases] + * @return {string[]|Command} + * @api public + */ - // support req/res-like objects as argument - var header = typeof string === 'object' - ? getcontenttype(string) - : string + aliases(aliases) { + // Getter for the array of aliases is the main reason for having aliases() in addition to alias(). + if (aliases === undefined) return this._aliases; - if (typeof header !== 'string') { - throw new TypeError('argument string is required to be a string') - } + aliases.forEach((alias) => this.alias(alias)); + return this; + }; - var index = header.indexOf(';') - var type = index !== -1 - ? header.substr(0, index).trim() - : header.trim() + /** + * Set / get the command usage `str`. + * + * @param {string} [str] + * @return {String|Command} + * @api public + */ - if (!TYPE_REGEXP.test(type)) { - throw new TypeError('invalid media type') - } + usage(str) { + if (str === undefined) { + if (this._usage) return this._usage; - var obj = new ContentType(type.toLowerCase()) + const args = this._args.map((arg) => { + return humanReadableArgName(arg); + }); + return [].concat( + (this.options.length || this._hasHelpOption ? '[options]' : []), + (this.commands.length ? '[command]' : []), + (this._args.length ? args : []) + ).join(' '); + } - // parse parameters - if (index !== -1) { - var key - var match - var value + this._usage = str; + return this; + }; - PARAM_REGEXP.lastIndex = index + /** + * Get or set the name of the command + * + * @param {string} [str] + * @return {String|Command} + * @api public + */ - while ((match = PARAM_REGEXP.exec(header))) { - if (match.index !== index) { - throw new TypeError('invalid parameter format') - } + name(str) { + if (str === undefined) return this._name; + this._name = str; + return this; + }; - index += match[0].length - key = match[1].toLowerCase() - value = match[2] + /** + * Return prepared commands. + * + * @return {Array} + * @api private + */ - if (value[0] === '"') { - // remove quotes and escapes - value = value - .substr(1, value.length - 2) - .replace(QESC_REGEXP, '$1') - } + prepareCommands() { + const commandDetails = this.commands.filter((cmd) => { + return !cmd._hidden; + }).map((cmd) => { + const args = cmd._args.map((arg) => { + return humanReadableArgName(arg); + }).join(' '); - obj.parameters[key] = value - } + return [ + cmd._name + + (cmd._aliases[0] ? '|' + cmd._aliases[0] : '') + + (cmd.options.length ? ' [options]' : '') + + (args ? ' ' + args : ''), + cmd._description + ]; + }); - if (index !== header.length) { - throw new TypeError('invalid parameter format') + if (this._lazyHasImplicitHelpCommand()) { + commandDetails.push([this._helpCommandnameAndArgs, this._helpCommandDescription]); } - } + return commandDetails; + }; - return obj -} + /** + * Return the largest command length. + * + * @return {number} + * @api private + */ -/** - * Get content-type from req/res objects. - * - * @param {object} - * @return {Object} - * @private - */ + largestCommandLength() { + const commands = this.prepareCommands(); + return commands.reduce((max, command) => { + return Math.max(max, command[0].length); + }, 0); + }; -function getcontenttype (obj) { - var header + /** + * Return the largest option length. + * + * @return {number} + * @api private + */ - if (typeof obj.getHeader === 'function') { - // res-like - header = obj.getHeader('content-type') - } else if (typeof obj.headers === 'object') { - // req-like - header = obj.headers && obj.headers['content-type'] - } + largestOptionLength() { + const options = [].slice.call(this.options); + options.push({ + flags: this._helpFlags + }); - if (typeof header !== 'string') { - throw new TypeError('content-type header is missing from object') - } + return options.reduce((max, option) => { + return Math.max(max, option.flags.length); + }, 0); + }; - return header -} + /** + * Return the largest arg length. + * + * @return {number} + * @api private + */ -/** - * Quote a string if necessary. - * - * @param {string} val - * @return {string} - * @private - */ + largestArgLength() { + return this._args.reduce((max, arg) => { + return Math.max(max, arg.name.length); + }, 0); + }; -function qstring (val) { - var str = String(val) + /** + * Return the pad width. + * + * @return {number} + * @api private + */ - // no need to quote tokens - if (TOKEN_REGEXP.test(str)) { - return str - } + padWidth() { + let width = this.largestOptionLength(); + if (this._argsDescription && this._args.length) { + if (this.largestArgLength() > width) { + width = this.largestArgLength(); + } + } - if (str.length > 0 && !TEXT_REGEXP.test(str)) { - throw new TypeError('invalid parameter value') - } + if (this.commands && this.commands.length) { + if (this.largestCommandLength() > width) { + width = this.largestCommandLength(); + } + } - return '"' + str.replace(QUOTE_REGEXP, '\\$1') + '"' -} + return width; + }; -/** - * Class to represent a content type. - * @private - */ -function ContentType (type) { - this.parameters = Object.create(null) - this.type = type -} + /** + * Return help for options. + * + * @return {string} + * @api private + */ + optionHelp() { + const width = this.padWidth(); + const columns = process.stdout.columns || 80; + const descriptionWidth = columns - width - 4; + function padOptionDetails(flags, description) { + return pad(flags, width) + ' ' + optionalWrap(description, descriptionWidth, width + 2); + }; -/***/ }), + // Explicit options (including version) + const help = this.options.map((option) => { + const fullDesc = option.description + + ((!option.negate && option.defaultValue !== undefined) ? ' (default: ' + JSON.stringify(option.defaultValue) + ')' : ''); + return padOptionDetails(option.flags, fullDesc); + }); -/***/ 61579: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + // Implicit help + const showShortHelpFlag = this._hasHelpOption && this._helpShortFlag && !this._findOption(this._helpShortFlag); + const showLongHelpFlag = this._hasHelpOption && !this._findOption(this._helpLongFlag); + if (showShortHelpFlag || showLongHelpFlag) { + let helpFlags = this._helpFlags; + if (!showShortHelpFlag) { + helpFlags = this._helpLongFlag; + } else if (!showLongHelpFlag) { + helpFlags = this._helpShortFlag; + } + help.push(padOptionDetails(helpFlags, this._helpDescription)); + } -/** - * Module dependencies. - */ + return help.join('\n'); + }; -var crypto = __nccwpck_require__(6113); + /** + * Return command help documentation. + * + * @return {string} + * @api private + */ -/** - * Sign the given `val` with `secret`. - * - * @param {String} val - * @param {String} secret - * @return {String} - * @api private - */ + commandHelp() { + if (!this.commands.length && !this._lazyHasImplicitHelpCommand()) return ''; -exports.sign = function(val, secret){ - if ('string' != typeof val) throw new TypeError("Cookie value must be provided as a string."); - if ('string' != typeof secret) throw new TypeError("Secret string must be provided."); - return val + '.' + crypto - .createHmac('sha256', secret) - .update(val) - .digest('base64') - .replace(/\=+$/, ''); -}; + const commands = this.prepareCommands(); + const width = this.padWidth(); -/** - * Unsign and decode the given `val` with `secret`, - * returning `false` if the signature is invalid. - * - * @param {String} val - * @param {String} secret - * @return {String|Boolean} - * @api private - */ + const columns = process.stdout.columns || 80; + const descriptionWidth = columns - width - 4; -exports.unsign = function(val, secret){ - if ('string' != typeof val) throw new TypeError("Signed cookie string must be provided."); - if ('string' != typeof secret) throw new TypeError("Secret string must be provided."); - var str = val.slice(0, val.lastIndexOf('.')) - , mac = exports.sign(str, secret); - - return sha1(mac) == sha1(val) ? str : false; -}; + return [ + 'Commands:', + commands.map((cmd) => { + const desc = cmd[1] ? ' ' + cmd[1] : ''; + return (desc ? pad(cmd[0], width) : cmd[0]) + optionalWrap(desc, descriptionWidth, width + 2); + }).join('\n').replace(/^/gm, ' '), + '' + ].join('\n'); + }; -/** - * Private - */ + /** + * Return program help documentation. + * + * @return {string} + * @api public + */ -function sha1(str){ - return crypto.createHash('sha1').update(str).digest('hex'); -} + helpInformation() { + let desc = []; + if (this._description) { + desc = [ + this._description, + '' + ]; + const argsDescription = this._argsDescription; + if (argsDescription && this._args.length) { + const width = this.padWidth(); + const columns = process.stdout.columns || 80; + const descriptionWidth = columns - width - 5; + desc.push('Arguments:'); + this._args.forEach((arg) => { + desc.push(' ' + pad(arg.name, width) + ' ' + wrap(argsDescription[arg.name] || '', descriptionWidth, width + 4)); + }); + desc.push(''); + } + } -/***/ }), + let cmdName = this._name; + if (this._aliases[0]) { + cmdName = cmdName + '|' + this._aliases[0]; + } + let parentCmdNames = ''; + for (let parentCmd = this.parent; parentCmd; parentCmd = parentCmd.parent) { + parentCmdNames = parentCmd.name() + ' ' + parentCmdNames; + } + const usage = [ + 'Usage: ' + parentCmdNames + cmdName + ' ' + this.usage(), + '' + ]; -/***/ 93658: -/***/ ((__unused_webpack_module, exports) => { + let cmds = []; + const commandHelp = this.commandHelp(); + if (commandHelp) cmds = [commandHelp]; -"use strict"; -/*! - * cookie - * Copyright(c) 2012-2014 Roman Shtylman - * Copyright(c) 2015 Douglas Christopher Wilson - * MIT Licensed - */ + let options = []; + if (this._hasHelpOption || this.options.length > 0) { + options = [ + 'Options:', + '' + this.optionHelp().replace(/^/gm, ' '), + '' + ]; + } + + return usage + .concat(desc) + .concat(options) + .concat(cmds) + .join('\n'); + }; + + /** + * Output help information for this command. + * + * When listener(s) are available for the helpLongFlag + * those callbacks are invoked. + * + * @api public + */ + + outputHelp(cb) { + if (!cb) { + cb = (passthru) => { + return passthru; + }; + } + const cbOutput = cb(this.helpInformation()); + if (typeof cbOutput !== 'string' && !Buffer.isBuffer(cbOutput)) { + throw new Error('outputHelp callback must return a string or a Buffer'); + } + process.stdout.write(cbOutput); + this.emit(this._helpLongFlag); + }; + + /** + * You can pass in flags and a description to override the help + * flags and help description for your command. Pass in false to + * disable the built-in help option. + * + * @param {string | boolean} [flags] + * @param {string} [description] + * @return {Command} `this` command for chaining + * @api public + */ + + helpOption(flags, description) { + if (typeof flags === 'boolean') { + this._hasHelpOption = flags; + return this; + } + this._helpFlags = flags || this._helpFlags; + this._helpDescription = description || this._helpDescription; + + const helpFlags = _parseOptionFlags(this._helpFlags); + this._helpShortFlag = helpFlags.shortFlag; + this._helpLongFlag = helpFlags.longFlag; + + return this; + }; + + /** + * Output help information and exit. + * + * @param {Function} [cb] + * @api public + */ + + help(cb) { + this.outputHelp(cb); + // exitCode: preserving original behaviour which was calling process.exit() + // message: do not have all displayed text available so only passing placeholder. + this._exit(process.exitCode || 0, 'commander.help', '(outputHelp)'); + }; + /** + * Output help information and exit. Display for error situations. + * + * @api private + */ + _helpAndError() { + this.outputHelp(); + // message: do not have all displayed text available so only passing placeholder. + this._exit(1, 'commander.help', '(outputHelp)'); + }; +}; /** - * Module exports. - * @public + * Expose the root command. */ -exports.parse = parse; -exports.serialize = serialize; +exports = module.exports = new Command(); +exports.program = exports; // More explicit access to global command. /** - * Module variables. - * @private + * Expose classes */ -var decode = decodeURIComponent; -var encode = encodeURIComponent; -var pairSplitRegExp = /; */; +exports.Command = Command; +exports.Option = Option; +exports.CommanderError = CommanderError; /** - * RegExp to match field-content in RFC 7230 sec 3.2 + * Camel-case the given `flag` * - * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] - * field-vchar = VCHAR / obs-text - * obs-text = %x80-FF + * @param {string} flag + * @return {string} + * @api private */ -var fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/; +function camelcase(flag) { + return flag.split('-').reduce((str, word) => { + return str + word[0].toUpperCase() + word.slice(1); + }); +} /** - * Parse a cookie header. - * - * Parse the given cookie header string into an object - * The object has the various cookies as keys(names) => values + * Pad `str` to `width`. * * @param {string} str - * @param {object} [options] - * @return {object} - * @public + * @param {number} width + * @return {string} + * @api private */ -function parse(str, options) { - if (typeof str !== 'string') { - throw new TypeError('argument str must be a string'); - } - - var obj = {} - var opt = options || {}; - var pairs = str.split(pairSplitRegExp); - var dec = opt.decode || decode; - - for (var i = 0; i < pairs.length; i++) { - var pair = pairs[i]; - var eq_idx = pair.indexOf('='); +function pad(str, width) { + const len = Math.max(0, width - str.length); + return str + Array(len + 1).join(' '); +} - // skip things that don't look like key=value - if (eq_idx < 0) { - continue; +/** + * Wraps the given string with line breaks at the specified width while breaking + * words and indenting every but the first line on the left. + * + * @param {string} str + * @param {number} width + * @param {number} indent + * @return {string} + * @api private + */ +function wrap(str, width, indent) { + const regex = new RegExp('.{1,' + (width - 1) + '}([\\s\u200B]|$)|[^\\s\u200B]+?([\\s\u200B]|$)', 'g'); + const lines = str.match(regex) || []; + return lines.map((line, i) => { + if (line.slice(-1) === '\n') { + line = line.slice(0, line.length - 1); } + return ((i > 0 && indent) ? Array(indent + 1).join(' ') : '') + line.trimRight(); + }).join('\n'); +} - var key = pair.substr(0, eq_idx).trim() - var val = pair.substr(++eq_idx, pair.length).trim(); +/** + * Optionally wrap the given str to a max width of width characters per line + * while indenting with indent spaces. Do not wrap if insufficient width or + * string is manually formatted. + * + * @param {string} str + * @param {number} width + * @param {number} indent + * @return {string} + * @api private + */ +function optionalWrap(str, width, indent) { + // Detect manually wrapped and indented strings by searching for line breaks + // followed by multiple spaces/tabs. + if (str.match(/[\n]\s+/)) return str; + // Do not wrap to narrow columns (or can end up with a word per line). + const minWidth = 40; + if (width < minWidth) return str; - // quoted values - if ('"' == val[0]) { - val = val.slice(1, -1); - } + return wrap(str, width, indent); +} - // only assign once - if (undefined == obj[key]) { - obj[key] = tryDecode(val, dec); - } - } +/** + * Output help information if help flags specified + * + * @param {Command} cmd - command to output help for + * @param {Array} args - array of options to search for help flags + * @api private + */ - return obj; +function outputHelpIfRequested(cmd, args) { + const helpOption = cmd._hasHelpOption && args.find(arg => arg === cmd._helpLongFlag || arg === cmd._helpShortFlag); + if (helpOption) { + cmd.outputHelp(); + // (Do not have all displayed text available so only passing placeholder.) + cmd._exit(0, 'commander.helpDisplayed', '(outputHelp)'); + } } /** - * Serialize data into a cookie header. - * - * Serialize the a name value pair into a cookie string suitable for - * http headers. An optional options object specified cookie parameters. - * - * serialize('foo', 'bar', { httpOnly: true }) - * => "foo=bar; httpOnly" + * Takes an argument and returns its human readable equivalent for help usage. * - * @param {string} name - * @param {string} val - * @param {object} [options] + * @param {Object} arg * @return {string} - * @public + * @api private */ -function serialize(name, val, options) { - var opt = options || {}; - var enc = opt.encode || encode; - - if (typeof enc !== 'function') { - throw new TypeError('option encode is invalid'); - } +function humanReadableArgName(arg) { + const nameOutput = arg.name + (arg.variadic === true ? '...' : ''); - if (!fieldContentRegExp.test(name)) { - throw new TypeError('argument name is invalid'); - } + return arg.required + ? '<' + nameOutput + '>' + : '[' + nameOutput + ']'; +} - var value = enc(val); +/** + * Parse the short and long flag out of something like '-m,--mixed ' + * + * @api private + */ - if (value && !fieldContentRegExp.test(value)) { - throw new TypeError('argument val is invalid'); +function _parseOptionFlags(flags) { + let shortFlag; + let longFlag; + // Use original very loose parsing to maintain backwards compatibility for now, + // which allowed for example unintended `-sw, --short-word` [sic]. + const flagParts = flags.split(/[ |,]+/); + if (flagParts.length > 1 && !/^[[<]/.test(flagParts[1])) shortFlag = flagParts.shift(); + longFlag = flagParts.shift(); + // Add support for lone short flag without significantly changing parsing! + if (!shortFlag && /^-[^-]$/.test(longFlag)) { + shortFlag = longFlag; + longFlag = undefined; } + return { shortFlag, longFlag }; +} - var str = name + '=' + value; - - if (null != opt.maxAge) { - var maxAge = opt.maxAge - 0; +/** + * Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command). + * + * @param {string[]} args - array of arguments from node.execArgv + * @returns {string[]} + * @api private + */ - if (isNaN(maxAge) || !isFinite(maxAge)) { - throw new TypeError('option maxAge is invalid') +function incrementNodeInspectorPort(args) { + // Testing for these options: + // --inspect[=[host:]port] + // --inspect-brk[=[host:]port] + // --inspect-port=[host:]port + return args.map((arg) => { + if (!arg.startsWith('--inspect')) { + return arg; } - - str += '; Max-Age=' + Math.floor(maxAge); - } - - if (opt.domain) { - if (!fieldContentRegExp.test(opt.domain)) { - throw new TypeError('option domain is invalid'); + let debugOption; + let debugHost = '127.0.0.1'; + let debugPort = '9229'; + let match; + if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) { + // e.g. --inspect + debugOption = match[1]; + } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) { + debugOption = match[1]; + if (/^\d+$/.test(match[3])) { + // e.g. --inspect=1234 + debugPort = match[3]; + } else { + // e.g. --inspect=localhost + debugHost = match[3]; + } + } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) { + // e.g. --inspect=localhost:1234 + debugOption = match[1]; + debugHost = match[3]; + debugPort = match[4]; } - str += '; Domain=' + opt.domain; - } - - if (opt.path) { - if (!fieldContentRegExp.test(opt.path)) { - throw new TypeError('option path is invalid'); + if (debugOption && debugPort !== '0') { + return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`; } + return arg; + }); +} - str += '; Path=' + opt.path; - } - - if (opt.expires) { - if (typeof opt.expires.toUTCString !== 'function') { - throw new TypeError('option expires is invalid'); - } - str += '; Expires=' + opt.expires.toUTCString(); - } +/***/ }), - if (opt.httpOnly) { - str += '; HttpOnly'; - } +/***/ 89296: +/***/ (function(module) { - if (opt.secure) { - str += '; Secure'; +/* global define */ +(function (root, factory) { + /* istanbul ignore next */ + if (typeof define === 'function' && define.amd) { + define([], factory); + } else if (true) { + module.exports = factory(); + } else {} +})(this, function () { + var semver = + /^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i; + + function indexOrEnd(str, q) { + return str.indexOf(q) === -1 ? str.length : str.indexOf(q); } - if (opt.sameSite) { - var sameSite = typeof opt.sameSite === 'string' - ? opt.sameSite.toLowerCase() : opt.sameSite; + function split(v) { + var c = v.replace(/^v/, '').replace(/\+.*$/, ''); + var patchIndex = indexOrEnd(c, '-'); + var arr = c.substring(0, patchIndex).split('.'); + arr.push(c.substring(patchIndex + 1)); + return arr; + } - switch (sameSite) { - case true: - str += '; SameSite=Strict'; - break; - case 'lax': - str += '; SameSite=Lax'; - break; - case 'strict': - str += '; SameSite=Strict'; - break; - case 'none': - str += '; SameSite=None'; - break; - default: - throw new TypeError('option sameSite is invalid'); + function tryParse(v) { + var n = parseInt(v, 10); + return isNaN(n) ? v : n; + } + + function validateAndParse(v) { + if (typeof v !== 'string') { + throw new TypeError('Invalid argument expected string'); + } + var match = v.match(semver); + if (!match) { + throw new Error( + "Invalid argument not valid semver ('" + v + "' received)" + ); } + match.shift(); + return match; } - return str; -} + function forceType(a, b) { + return typeof a !== typeof b ? [String(a), String(b)] : [a, b]; + } -/** - * Try decoding a string using a decoding function. - * - * @param {string} str - * @param {function} decode - * @private - */ + function compareStrings(a, b) { + var [ap, bp] = forceType(tryParse(a), tryParse(b)); + if (ap > bp) return 1; + if (ap < bp) return -1; + return 0; + } -function tryDecode(str, decode) { - try { - return decode(str); - } catch (e) { - return str; + function compareSegments(a, b) { + for (var i = 0; i < Math.max(a.length, b.length); i++) { + var r = compareStrings(a[i] || 0, b[i] || 0); + if (r !== 0) return r; + } + return 0; } -} + function compareVersions(v1, v2) { + [v1, v2].forEach(validateAndParse); -/***/ }), + var s1 = split(v1); + var s2 = split(v2); -/***/ 51512: -/***/ ((module, exports) => { + for (var i = 0; i < Math.max(s1.length - 1, s2.length - 1); i++) { + var n1 = parseInt(s1[i] || 0, 10); + var n2 = parseInt(s2[i] || 0, 10); -"use strict"; -function _typeof(obj){"@babel/helpers - typeof";if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj}}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj}}return _typeof(obj)}(function(global){var _arguments=arguments;var dateFormat=function(){var token=/d{1,4}|D{3,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|W{1,2}|[LlopSZN]|"[^"]*"|'[^']*'/g;var timezone=/\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g;var timezoneClip=/[^-+\dA-Z]/g;return function(date,mask,utc,gmt){if(_arguments.length===1&&kindOf(date)==="string"&&!/\d/.test(date)){mask=date;date=undefined}date=date||date===0?date:new Date;if(!(date instanceof Date)){date=new Date(date)}if(isNaN(date)){throw TypeError("Invalid date")}mask=String(dateFormat.masks[mask]||mask||dateFormat.masks["default"]);var maskSlice=mask.slice(0,4);if(maskSlice==="UTC:"||maskSlice==="GMT:"){mask=mask.slice(4);utc=true;if(maskSlice==="GMT:"){gmt=true}}var _=function _(){return utc?"getUTC":"get"};var _d=function d(){return date[_()+"Date"]()};var D=function D(){return date[_()+"Day"]()};var _m=function m(){return date[_()+"Month"]()};var y=function y(){return date[_()+"FullYear"]()};var _H=function H(){return date[_()+"Hours"]()};var _M=function M(){return date[_()+"Minutes"]()};var _s=function s(){return date[_()+"Seconds"]()};var _L=function L(){return date[_()+"Milliseconds"]()};var _o=function o(){return utc?0:date.getTimezoneOffset()};var _W=function W(){return getWeek(date)};var _N=function N(){return getDayOfWeek(date)};var flags={d:function d(){return _d()},dd:function dd(){return pad(_d())},ddd:function ddd(){return dateFormat.i18n.dayNames[D()]},DDD:function DDD(){return getDayName({y:y(),m:_m(),d:_d(),_:_(),dayName:dateFormat.i18n.dayNames[D()],short:true})},dddd:function dddd(){return dateFormat.i18n.dayNames[D()+7]},DDDD:function DDDD(){return getDayName({y:y(),m:_m(),d:_d(),_:_(),dayName:dateFormat.i18n.dayNames[D()+7]})},m:function m(){return _m()+1},mm:function mm(){return pad(_m()+1)},mmm:function mmm(){return dateFormat.i18n.monthNames[_m()]},mmmm:function mmmm(){return dateFormat.i18n.monthNames[_m()+12]},yy:function yy(){return String(y()).slice(2)},yyyy:function yyyy(){return pad(y(),4)},h:function h(){return _H()%12||12},hh:function hh(){return pad(_H()%12||12)},H:function H(){return _H()},HH:function HH(){return pad(_H())},M:function M(){return _M()},MM:function MM(){return pad(_M())},s:function s(){return _s()},ss:function ss(){return pad(_s())},l:function l(){return pad(_L(),3)},L:function L(){return pad(Math.floor(_L()/10))},t:function t(){return _H()<12?dateFormat.i18n.timeNames[0]:dateFormat.i18n.timeNames[1]},tt:function tt(){return _H()<12?dateFormat.i18n.timeNames[2]:dateFormat.i18n.timeNames[3]},T:function T(){return _H()<12?dateFormat.i18n.timeNames[4]:dateFormat.i18n.timeNames[5]},TT:function TT(){return _H()<12?dateFormat.i18n.timeNames[6]:dateFormat.i18n.timeNames[7]},Z:function Z(){return gmt?"GMT":utc?"UTC":(String(date).match(timezone)||[""]).pop().replace(timezoneClip,"").replace(/GMT\+0000/g,"UTC")},o:function o(){return(_o()>0?"-":"+")+pad(Math.floor(Math.abs(_o())/60)*100+Math.abs(_o())%60,4)},p:function p(){return(_o()>0?"-":"+")+pad(Math.floor(Math.abs(_o())/60),2)+":"+pad(Math.floor(Math.abs(_o())%60),2)},S:function S(){return["th","st","nd","rd"][_d()%10>3?0:(_d()%100-_d()%10!=10)*_d()%10]},W:function W(){return _W()},WW:function WW(){return pad(_W())},N:function N(){return _N()}};return mask.replace(token,function(match){if(match in flags){return flags[match]()}return match.slice(1,match.length-1)})}}();dateFormat.masks={default:"ddd mmm dd yyyy HH:MM:ss",shortDate:"m/d/yy",paddedShortDate:"mm/dd/yyyy",mediumDate:"mmm d, yyyy",longDate:"mmmm d, yyyy",fullDate:"dddd, mmmm d, yyyy",shortTime:"h:MM TT",mediumTime:"h:MM:ss TT",longTime:"h:MM:ss TT Z",isoDate:"yyyy-mm-dd",isoTime:"HH:MM:ss",isoDateTime:"yyyy-mm-dd'T'HH:MM:sso",isoUtcDateTime:"UTC:yyyy-mm-dd'T'HH:MM:ss'Z'",expiresHeaderFormat:"ddd, dd mmm yyyy HH:MM:ss Z"};dateFormat.i18n={dayNames:["Sun","Mon","Tue","Wed","Thu","Fri","Sat","Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],monthNames:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec","January","February","March","April","May","June","July","August","September","October","November","December"],timeNames:["a","p","am","pm","A","P","AM","PM"]};var pad=function pad(val,len){val=String(val);len=len||2;while(val.length n2) return 1; + if (n2 > n1) return -1; + } -/***/ }), + var sp1 = s1[s1.length - 1]; + var sp2 = s2[s2.length - 1]; -/***/ 28222: -/***/ ((module, exports, __nccwpck_require__) => { + if (sp1 && sp2) { + var p1 = sp1.split('.').map(tryParse); + var p2 = sp2.split('.').map(tryParse); -/* eslint-env browser */ + for (i = 0; i < Math.max(p1.length, p2.length); i++) { + if ( + p1[i] === undefined || + (typeof p2[i] === 'string' && typeof p1[i] === 'number') + ) + return -1; + if ( + p2[i] === undefined || + (typeof p1[i] === 'string' && typeof p2[i] === 'number') + ) + return 1; -/** - * This is the web browser implementation of `debug()`. - */ + if (p1[i] > p2[i]) return 1; + if (p2[i] > p1[i]) return -1; + } + } else if (sp1 || sp2) { + return sp1 ? -1 : 1; + } -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.storage = localstorage(); -exports.destroy = (() => { - let warned = false; + return 0; + } - return () => { - if (!warned) { - warned = true; - console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); - } - }; -})(); + var allowedOperators = ['>', '>=', '=', '<', '<=']; -/** - * Colors. - */ + var operatorResMap = { + '>': [1], + '>=': [0, 1], + '=': [0], + '<=': [-1, 0], + '<': [-1], + }; -exports.colors = [ - '#0000CC', - '#0000FF', - '#0033CC', - '#0033FF', - '#0066CC', - '#0066FF', - '#0099CC', - '#0099FF', - '#00CC00', - '#00CC33', - '#00CC66', - '#00CC99', - '#00CCCC', - '#00CCFF', - '#3300CC', - '#3300FF', - '#3333CC', - '#3333FF', - '#3366CC', - '#3366FF', - '#3399CC', - '#3399FF', - '#33CC00', - '#33CC33', - '#33CC66', - '#33CC99', - '#33CCCC', - '#33CCFF', - '#6600CC', - '#6600FF', - '#6633CC', - '#6633FF', - '#66CC00', - '#66CC33', - '#9900CC', - '#9900FF', - '#9933CC', - '#9933FF', - '#99CC00', - '#99CC33', - '#CC0000', - '#CC0033', - '#CC0066', - '#CC0099', - '#CC00CC', - '#CC00FF', - '#CC3300', - '#CC3333', - '#CC3366', - '#CC3399', - '#CC33CC', - '#CC33FF', - '#CC6600', - '#CC6633', - '#CC9900', - '#CC9933', - '#CCCC00', - '#CCCC33', - '#FF0000', - '#FF0033', - '#FF0066', - '#FF0099', - '#FF00CC', - '#FF00FF', - '#FF3300', - '#FF3333', - '#FF3366', - '#FF3399', - '#FF33CC', - '#FF33FF', - '#FF6600', - '#FF6633', - '#FF9900', - '#FF9933', - '#FFCC00', - '#FFCC33' -]; + function validateOperator(op) { + if (typeof op !== 'string') { + throw new TypeError( + 'Invalid operator type, expected string but got ' + typeof op + ); + } + if (allowedOperators.indexOf(op) === -1) { + throw new TypeError( + 'Invalid operator, expected one of ' + allowedOperators.join('|') + ); + } + } -/** - * Currently only WebKit-based Web Inspectors, Firefox >= v31, - * and the Firebug extension (any Firefox version) are known - * to support "%c" CSS customizations. - * - * TODO: add a `localStorage` variable to explicitly enable/disable colors - */ + compareVersions.validate = function (version) { + return typeof version === 'string' && semver.test(version); + }; -// eslint-disable-next-line complexity -function useColors() { - // NB: In an Electron preload script, document will be defined but not fully - // initialized. Since we know we're in Chrome, we'll just detect this case - // explicitly - if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { - return true; - } + compareVersions.compare = function (v1, v2, operator) { + // Validate operator + validateOperator(operator); - // Internet Explorer and Edge do not support colors. - if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { - return false; - } + // since result of compareVersions can only be -1 or 0 or 1 + // a simple map can be used to replace switch + var res = compareVersions(v1, v2); + return operatorResMap[operator].indexOf(res) > -1; + }; - // Is webkit? http://stackoverflow.com/a/16459606/376773 - // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 - return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || - // Is firebug? http://stackoverflow.com/a/398120/376773 - (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || - // Is firefox >= v31? - // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || - // Double check webkit in userAgent just in case we are in a worker - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); -} + compareVersions.satisfies = function (v, r) { + // if no range operator then "=" + var match = r.match(/^([<>=~^]+)/); + var op = match ? match[1] : '='; -/** - * Colorize log arguments if enabled. - * - * @api public - */ + // if gt/lt/eq then operator compare + if (op !== '^' && op !== '~') return compareVersions.compare(v, r, op); -function formatArgs(args) { - args[0] = (this.useColors ? '%c' : '') + - this.namespace + - (this.useColors ? ' %c' : ' ') + - args[0] + - (this.useColors ? '%c ' : ' ') + - '+' + module.exports.humanize(this.diff); + // else range of either "~" or "^" is assumed + var [v1, v2, v3] = validateAndParse(v); + var [m1, m2, m3] = validateAndParse(r); + if (compareStrings(v1, m1) !== 0) return false; + if (op === '^') { + return compareSegments([v2, v3], [m2, m3]) >= 0; + } + if (compareStrings(v2, m2) !== 0) return false; + return compareStrings(v3, m3) >= 0; + }; - if (!this.useColors) { - return; - } + return compareVersions; +}); - const c = 'color: ' + this.color; - args.splice(1, 0, c, 'color: inherit'); - // The final "%c" is somewhat tricky, because there could be other - // arguments passed either before or after the %c, so we need to - // figure out the correct index to insert the CSS into - let index = 0; - let lastC = 0; - args[0].replace(/%[a-zA-Z%]/g, match => { - if (match === '%%') { - return; - } - index++; - if (match === '%c') { - // We only are interested in the *last* %c - // (the user may have provided their own) - lastC = index; - } - }); +/***/ }), - args.splice(lastC, 0, c); -} +/***/ 53921: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * Invokes `console.debug()` when available. - * No-op when `console.debug` is not a "function". - * If `console.debug` is not available, falls back - * to `console.log`. - * - * @api public +"use strict"; +/*! + * content-disposition + * Copyright(c) 2014-2017 Douglas Christopher Wilson + * MIT Licensed */ -exports.log = console.debug || console.log || (() => {}); -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ -function save(namespaces) { - try { - if (namespaces) { - exports.storage.setItem('debug', namespaces); - } else { - exports.storage.removeItem('debug'); - } - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } -} + /** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private + * Module exports. + * @public */ -function load() { - let r; - try { - r = exports.storage.getItem('debug'); - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } - - // If debug isn't set in LS, and we're in Electron, try to load $DEBUG - if (!r && typeof process !== 'undefined' && 'env' in process) { - r = process.env.DEBUG; - } - return r; -} +module.exports = contentDisposition +module.exports.parse = parse /** - * Localstorage attempts to return the localstorage. - * - * This is necessary because safari throws - * when a user disables cookies/localstorage - * and you attempt to access it. - * - * @return {LocalStorage} - * @api private + * Module dependencies. + * @private */ -function localstorage() { - try { - // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context - // The Browser also has localStorage in the global context. - return localStorage; - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } -} +var basename = (__nccwpck_require__(71017).basename) +var Buffer = (__nccwpck_require__(21867).Buffer) -module.exports = __nccwpck_require__(46243)(exports); +/** + * RegExp to match non attr-char, *after* encodeURIComponent (i.e. not including "%") + * @private + */ -const {formatters} = module.exports; +var ENCODE_URL_ATTR_CHAR_REGEXP = /[\x00-\x20"'()*,/:;<=>?@[\\\]{}\x7f]/g // eslint-disable-line no-control-regex /** - * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + * RegExp to match percent encoding escape. + * @private */ -formatters.j = function (v) { - try { - return JSON.stringify(v); - } catch (error) { - return '[UnexpectedJSONParseError]: ' + error.message; - } -}; +var HEX_ESCAPE_REGEXP = /%[0-9A-Fa-f]{2}/ +var HEX_ESCAPE_REPLACE_REGEXP = /%([0-9A-Fa-f]{2})/g +/** + * RegExp to match non-latin1 characters. + * @private + */ -/***/ }), +var NON_LATIN1_REGEXP = /[^\x20-\x7e\xa0-\xff]/g -/***/ 46243: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/** + * RegExp to match quoted-pair in RFC 2616 + * + * quoted-pair = "\" CHAR + * CHAR = + * @private + */ +var QESC_REGEXP = /\\([\u0000-\u007f])/g // eslint-disable-line no-control-regex /** - * This is the common logic for both the Node.js and web browser - * implementations of `debug()`. + * RegExp to match chars that must be quoted-pair in RFC 2616 + * @private */ -function setup(env) { - createDebug.debug = createDebug; - createDebug.default = createDebug; - createDebug.coerce = coerce; - createDebug.disable = disable; - createDebug.enable = enable; - createDebug.enabled = enabled; - createDebug.humanize = __nccwpck_require__(80900); - createDebug.destroy = destroy; - - Object.keys(env).forEach(key => { - createDebug[key] = env[key]; - }); +var QUOTE_REGEXP = /([\\"])/g - /** - * The currently active debug mode names, and names to skip. - */ +/** + * RegExp for various RFC 2616 grammar + * + * parameter = token "=" ( token | quoted-string ) + * token = 1* + * separators = "(" | ")" | "<" | ">" | "@" + * | "," | ";" | ":" | "\" | <"> + * | "/" | "[" | "]" | "?" | "=" + * | "{" | "}" | SP | HT + * quoted-string = ( <"> *(qdtext | quoted-pair ) <"> ) + * qdtext = > + * quoted-pair = "\" CHAR + * CHAR = + * TEXT = + * LWS = [CRLF] 1*( SP | HT ) + * CRLF = CR LF + * CR = + * LF = + * SP = + * HT = + * CTL = + * OCTET = + * @private + */ - createDebug.names = []; - createDebug.skips = []; +var PARAM_REGEXP = /;[\x09\x20]*([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*=[\x09\x20]*("(?:[\x20!\x23-\x5b\x5d-\x7e\x80-\xff]|\\[\x20-\x7e])*"|[!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*/g // eslint-disable-line no-control-regex +var TEXT_REGEXP = /^[\x20-\x7e\x80-\xff]+$/ +var TOKEN_REGEXP = /^[!#$%&'*+.0-9A-Z^_`a-z|~-]+$/ - /** - * Map of special "%n" handling functions, for the debug "format" argument. - * - * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". - */ - createDebug.formatters = {}; - - /** - * Selects a color for a debug namespace - * @param {String} namespace The namespace string for the debug instance to be colored - * @return {Number|String} An ANSI color code for the given namespace - * @api private - */ - function selectColor(namespace) { - let hash = 0; +/** + * RegExp for various RFC 5987 grammar + * + * ext-value = charset "'" [ language ] "'" value-chars + * charset = "UTF-8" / "ISO-8859-1" / mime-charset + * mime-charset = 1*mime-charsetc + * mime-charsetc = ALPHA / DIGIT + * / "!" / "#" / "$" / "%" / "&" + * / "+" / "-" / "^" / "_" / "`" + * / "{" / "}" / "~" + * language = ( 2*3ALPHA [ extlang ] ) + * / 4ALPHA + * / 5*8ALPHA + * extlang = *3( "-" 3ALPHA ) + * value-chars = *( pct-encoded / attr-char ) + * pct-encoded = "%" HEXDIG HEXDIG + * attr-char = ALPHA / DIGIT + * / "!" / "#" / "$" / "&" / "+" / "-" / "." + * / "^" / "_" / "`" / "|" / "~" + * @private + */ - for (let i = 0; i < namespace.length; i++) { - hash = ((hash << 5) - hash) + namespace.charCodeAt(i); - hash |= 0; // Convert to 32bit integer - } +var EXT_VALUE_REGEXP = /^([A-Za-z0-9!#$%&+\-^_`{}~]+)'(?:[A-Za-z]{2,3}(?:-[A-Za-z]{3}){0,3}|[A-Za-z]{4,8}|)'((?:%[0-9A-Fa-f]{2}|[A-Za-z0-9!#$&+.^_`|~-])+)$/ - return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; - } - createDebug.selectColor = selectColor; +/** + * RegExp for various RFC 6266 grammar + * + * disposition-type = "inline" | "attachment" | disp-ext-type + * disp-ext-type = token + * disposition-parm = filename-parm | disp-ext-parm + * filename-parm = "filename" "=" value + * | "filename*" "=" ext-value + * disp-ext-parm = token "=" value + * | ext-token "=" ext-value + * ext-token = + * @private + */ - /** - * Create a debugger with the given `namespace`. - * - * @param {String} namespace - * @return {Function} - * @api public - */ - function createDebug(namespace) { - let prevTime; - let enableOverride = null; - let namespacesCache; - let enabledCache; +var DISPOSITION_TYPE_REGEXP = /^([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*(?:$|;)/ // eslint-disable-line no-control-regex - function debug(...args) { - // Disabled? - if (!debug.enabled) { - return; - } +/** + * Create an attachment Content-Disposition header. + * + * @param {string} [filename] + * @param {object} [options] + * @param {string} [options.type=attachment] + * @param {string|boolean} [options.fallback=true] + * @return {string} + * @public + */ - const self = debug; +function contentDisposition (filename, options) { + var opts = options || {} - // Set `diff` timestamp - const curr = Number(new Date()); - const ms = curr - (prevTime || curr); - self.diff = ms; - self.prev = prevTime; - self.curr = curr; - prevTime = curr; + // get type + var type = opts.type || 'attachment' - args[0] = createDebug.coerce(args[0]); + // get parameters + var params = createparams(filename, opts.fallback) - if (typeof args[0] !== 'string') { - // Anything else let's inspect with %O - args.unshift('%O'); - } + // format into string + return format(new ContentDisposition(type, params)) +} - // Apply any `formatters` transformations - let index = 0; - args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { - // If we encounter an escaped % then don't increase the array index - if (match === '%%') { - return '%'; - } - index++; - const formatter = createDebug.formatters[format]; - if (typeof formatter === 'function') { - const val = args[index]; - match = formatter.call(self, val); +/** + * Create parameters object from filename and fallback. + * + * @param {string} [filename] + * @param {string|boolean} [fallback=true] + * @return {object} + * @private + */ - // Now we need to remove `args[index]` since it's inlined in the `format` - args.splice(index, 1); - index--; - } - return match; - }); +function createparams (filename, fallback) { + if (filename === undefined) { + return + } - // Apply env-specific formatting (colors, etc.) - createDebug.formatArgs.call(self, args); + var params = {} - const logFn = self.log || createDebug.log; - logFn.apply(self, args); - } + if (typeof filename !== 'string') { + throw new TypeError('filename must be a string') + } - debug.namespace = namespace; - debug.useColors = createDebug.useColors(); - debug.color = createDebug.selectColor(namespace); - debug.extend = extend; - debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. + // fallback defaults to true + if (fallback === undefined) { + fallback = true + } - Object.defineProperty(debug, 'enabled', { - enumerable: true, - configurable: false, - get: () => { - if (enableOverride !== null) { - return enableOverride; - } - if (namespacesCache !== createDebug.namespaces) { - namespacesCache = createDebug.namespaces; - enabledCache = createDebug.enabled(namespace); - } + if (typeof fallback !== 'string' && typeof fallback !== 'boolean') { + throw new TypeError('fallback must be a string or boolean') + } - return enabledCache; - }, - set: v => { - enableOverride = v; - } - }); + if (typeof fallback === 'string' && NON_LATIN1_REGEXP.test(fallback)) { + throw new TypeError('fallback must be ISO-8859-1 string') + } - // Env-specific initialization logic for debug instances - if (typeof createDebug.init === 'function') { - createDebug.init(debug); - } + // restrict to file base name + var name = basename(filename) - return debug; - } + // determine if name is suitable for quoted string + var isQuotedString = TEXT_REGEXP.test(name) - function extend(namespace, delimiter) { - const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); - newDebug.log = this.log; - return newDebug; - } + // generate fallback name + var fallbackName = typeof fallback !== 'string' + ? fallback && getlatin1(name) + : basename(fallback) + var hasFallback = typeof fallbackName === 'string' && fallbackName !== name - /** - * Enables a debug mode by namespaces. This can include modes - * separated by a colon and wildcards. - * - * @param {String} namespaces - * @api public - */ - function enable(namespaces) { - createDebug.save(namespaces); - createDebug.namespaces = namespaces; + // set extended filename parameter + if (hasFallback || !isQuotedString || HEX_ESCAPE_REGEXP.test(name)) { + params['filename*'] = name + } - createDebug.names = []; - createDebug.skips = []; + // set filename parameter + if (isQuotedString || hasFallback) { + params.filename = hasFallback + ? fallbackName + : name + } - let i; - const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); - const len = split.length; + return params +} - for (i = 0; i < len; i++) { - if (!split[i]) { - // ignore empty strings - continue; - } +/** + * Format object to Content-Disposition header. + * + * @param {object} obj + * @param {string} obj.type + * @param {object} [obj.parameters] + * @return {string} + * @private + */ - namespaces = split[i].replace(/\*/g, '.*?'); +function format (obj) { + var parameters = obj.parameters + var type = obj.type - if (namespaces[0] === '-') { - createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); - } else { - createDebug.names.push(new RegExp('^' + namespaces + '$')); - } - } - } + if (!type || typeof type !== 'string' || !TOKEN_REGEXP.test(type)) { + throw new TypeError('invalid type') + } - /** - * Disable debug output. - * - * @return {String} namespaces - * @api public - */ - function disable() { - const namespaces = [ - ...createDebug.names.map(toNamespace), - ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) - ].join(','); - createDebug.enable(''); - return namespaces; - } + // start with normalized type + var string = String(type).toLowerCase() - /** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ - function enabled(name) { - if (name[name.length - 1] === '*') { - return true; - } + // append parameters + if (parameters && typeof parameters === 'object') { + var param + var params = Object.keys(parameters).sort() - let i; - let len; + for (var i = 0; i < params.length; i++) { + param = params[i] - for (i = 0, len = createDebug.skips.length; i < len; i++) { - if (createDebug.skips[i].test(name)) { - return false; - } - } + var val = param.substr(-1) === '*' + ? ustring(parameters[param]) + : qstring(parameters[param]) - for (i = 0, len = createDebug.names.length; i < len; i++) { - if (createDebug.names[i].test(name)) { - return true; - } - } + string += '; ' + param + '=' + val + } + } - return false; - } + return string +} - /** - * Convert regexp to namespace - * - * @param {RegExp} regxep - * @return {String} namespace - * @api private - */ - function toNamespace(regexp) { - return regexp.toString() - .substring(2, regexp.toString().length - 2) - .replace(/\.\*\?$/, '*'); - } +/** + * Decode a RFC 5987 field value (gracefully). + * + * @param {string} str + * @return {string} + * @private + */ - /** - * Coerce `val`. - * - * @param {Mixed} val - * @return {Mixed} - * @api private - */ - function coerce(val) { - if (val instanceof Error) { - return val.stack || val.message; - } - return val; - } +function decodefield (str) { + var match = EXT_VALUE_REGEXP.exec(str) - /** - * XXX DO NOT USE. This is a temporary stub function. - * XXX It WILL be removed in the next major release. - */ - function destroy() { - console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); - } + if (!match) { + throw new TypeError('invalid extended field value') + } - createDebug.enable(createDebug.load()); + var charset = match[1].toLowerCase() + var encoded = match[2] + var value - return createDebug; -} + // to binary string + var binary = encoded.replace(HEX_ESCAPE_REPLACE_REGEXP, pdecode) -module.exports = setup; + switch (charset) { + case 'iso-8859-1': + value = getlatin1(binary) + break + case 'utf-8': + value = Buffer.from(binary, 'binary').toString('utf8') + break + default: + throw new TypeError('unsupported charset in extended field') + } + return value +} -/***/ }), +/** + * Get ISO-8859-1 version of string. + * + * @param {string} val + * @return {string} + * @private + */ -/***/ 38237: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +function getlatin1 (val) { + // simple Unicode -> ISO-8859-1 transformation + return String(val).replace(NON_LATIN1_REGEXP, '?') +} /** - * Detect Electron renderer / nwjs process, which is node, but we should - * treat as a browser. + * Parse Content-Disposition header string. + * + * @param {string} string + * @return {object} + * @public */ -if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { - module.exports = __nccwpck_require__(28222); -} else { - module.exports = __nccwpck_require__(35332); -} +function parse (string) { + if (!string || typeof string !== 'string') { + throw new TypeError('argument string is required') + } + var match = DISPOSITION_TYPE_REGEXP.exec(string) -/***/ }), + if (!match) { + throw new TypeError('invalid type format') + } -/***/ 35332: -/***/ ((module, exports, __nccwpck_require__) => { + // normalize type + var index = match[0].length + var type = match[1].toLowerCase() + + var key + var names = [] + var params = {} + var value + + // calculate index to start at + index = PARAM_REGEXP.lastIndex = match[0].substr(-1) === ';' + ? index - 1 + : index + + // match parameters + while ((match = PARAM_REGEXP.exec(string))) { + if (match.index !== index) { + throw new TypeError('invalid parameter format') + } + + index += match[0].length + key = match[1].toLowerCase() + value = match[2] + + if (names.indexOf(key) !== -1) { + throw new TypeError('invalid duplicate parameter') + } + + names.push(key) + + if (key.indexOf('*') + 1 === key.length) { + // decode extended value + key = key.slice(0, -1) + value = decodefield(value) + + // overwrite existing value + params[key] = value + continue + } + + if (typeof params[key] === 'string') { + continue + } + + if (value[0] === '"') { + // remove quotes and escapes + value = value + .substr(1, value.length - 2) + .replace(QESC_REGEXP, '$1') + } + + params[key] = value + } + + if (index !== -1 && index !== string.length) { + throw new TypeError('invalid parameter format') + } + + return new ContentDisposition(type, params) +} /** - * Module dependencies. + * Percent decode a single character. + * + * @param {string} str + * @param {string} hex + * @return {string} + * @private */ -const tty = __nccwpck_require__(76224); -const util = __nccwpck_require__(73837); +function pdecode (str, hex) { + return String.fromCharCode(parseInt(hex, 16)) +} /** - * This is the Node.js implementation of `debug()`. + * Percent encode a single character. + * + * @param {string} char + * @return {string} + * @private */ -exports.init = init; -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.destroy = util.deprecate( - () => {}, - 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' -); +function pencode (char) { + return '%' + String(char) + .charCodeAt(0) + .toString(16) + .toUpperCase() +} /** - * Colors. + * Quote a string for HTTP. + * + * @param {string} val + * @return {string} + * @private */ -exports.colors = [6, 2, 3, 4, 5, 1]; - -try { - // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) - // eslint-disable-next-line import/no-extraneous-dependencies - const supportsColor = __nccwpck_require__(59318); +function qstring (val) { + var str = String(val) - if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { - exports.colors = [ - 20, - 21, - 26, - 27, - 32, - 33, - 38, - 39, - 40, - 41, - 42, - 43, - 44, - 45, - 56, - 57, - 62, - 63, - 68, - 69, - 74, - 75, - 76, - 77, - 78, - 79, - 80, - 81, - 92, - 93, - 98, - 99, - 112, - 113, - 128, - 129, - 134, - 135, - 148, - 149, - 160, - 161, - 162, - 163, - 164, - 165, - 166, - 167, - 168, - 169, - 170, - 171, - 172, - 173, - 178, - 179, - 184, - 185, - 196, - 197, - 198, - 199, - 200, - 201, - 202, - 203, - 204, - 205, - 206, - 207, - 208, - 209, - 214, - 215, - 220, - 221 - ]; - } -} catch (error) { - // Swallow - we only care if `supports-color` is available; it doesn't have to be. + return '"' + str.replace(QUOTE_REGEXP, '\\$1') + '"' } /** - * Build up the default `inspectOpts` object from the environment variables. + * Encode a Unicode string for HTTP (RFC 5987). * - * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + * @param {string} val + * @return {string} + * @private */ -exports.inspectOpts = Object.keys(process.env).filter(key => { - return /^debug_/i.test(key); -}).reduce((obj, key) => { - // Camel-case - const prop = key - .substring(6) - .toLowerCase() - .replace(/_([a-z])/g, (_, k) => { - return k.toUpperCase(); - }); - - // Coerce string value into JS value - let val = process.env[key]; - if (/^(yes|on|true|enabled)$/i.test(val)) { - val = true; - } else if (/^(no|off|false|disabled)$/i.test(val)) { - val = false; - } else if (val === 'null') { - val = null; - } else { - val = Number(val); - } - - obj[prop] = val; - return obj; -}, {}); +function ustring (val) { + var str = String(val) -/** - * Is stdout a TTY? Colored output is enabled when `true`. - */ + // percent encode as UTF-8 + var encoded = encodeURIComponent(str) + .replace(ENCODE_URL_ATTR_CHAR_REGEXP, pencode) -function useColors() { - return 'colors' in exports.inspectOpts ? - Boolean(exports.inspectOpts.colors) : - tty.isatty(process.stderr.fd); + return 'UTF-8\'\'' + encoded } /** - * Adds ANSI color escape codes if enabled. + * Class for parsed Content-Disposition header for v8 optimization * - * @api public + * @public + * @param {string} type + * @param {object} parameters + * @constructor */ -function formatArgs(args) { - const {namespace: name, useColors} = this; +function ContentDisposition (type, parameters) { + this.type = type + this.parameters = parameters +} - if (useColors) { - const c = this.color; - const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); - const prefix = ` ${colorCode};1m${name} \u001B[0m`; - args[0] = prefix + args[0].split('\n').join('\n' + prefix); - args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); - } else { - args[0] = getDate() + name + ' ' + args[0]; - } -} +/***/ }), -function getDate() { - if (exports.inspectOpts.hideDate) { - return ''; - } - return new Date().toISOString() + ' '; -} +/***/ 99915: +/***/ ((__unused_webpack_module, exports) => { -/** - * Invokes `util.format()` with the specified arguments and writes to stderr. +"use strict"; +/*! + * content-type + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed */ -function log(...args) { - return process.stderr.write(util.format(...args) + '\n'); -} + /** - * Save `namespaces`. + * RegExp to match *( ";" parameter ) in RFC 7231 sec 3.1.1.1 * - * @param {String} namespaces - * @api private + * parameter = token "=" ( token / quoted-string ) + * token = 1*tchar + * tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" + * / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" + * / DIGIT / ALPHA + * ; any VCHAR, except delimiters + * quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE + * qdtext = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text + * obs-text = %x80-FF + * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) */ -function save(namespaces) { - if (namespaces) { - process.env.DEBUG = namespaces; - } else { - // If you set a process.env field to null or undefined, it gets cast to the - // string 'null' or 'undefined'. Just delete instead. - delete process.env.DEBUG; - } -} +var PARAM_REGEXP = /; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g +var TEXT_REGEXP = /^[\u000b\u0020-\u007e\u0080-\u00ff]+$/ +var TOKEN_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/ /** - * Load `namespaces`. + * RegExp to match quoted-pair in RFC 7230 sec 3.2.6 * - * @return {String} returns the previously persisted debug modes - * @api private + * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) + * obs-text = %x80-FF */ +var QESC_REGEXP = /\\([\u000b\u0020-\u00ff])/g -function load() { - return process.env.DEBUG; -} +/** + * RegExp to match chars that must be quoted-pair in RFC 7230 sec 3.2.6 + */ +var QUOTE_REGEXP = /([\\"])/g /** - * Init logic for `debug` instances. + * RegExp to match type in RFC 7231 sec 3.1.1.1 * - * Create a new `inspectOpts` object in case `useColors` is set - * differently for a particular `debug` instance. + * media-type = type "/" subtype + * type = token + * subtype = token */ - -function init(debug) { - debug.inspectOpts = {}; - - const keys = Object.keys(exports.inspectOpts); - for (let i = 0; i < keys.length; i++) { - debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; - } -} - -module.exports = __nccwpck_require__(46243)(exports); - -const {formatters} = module.exports; +var TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/ /** - * Map %o to `util.inspect()`, all on a single line. + * Module exports. + * @public */ -formatters.o = function (v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts) - .split('\n') - .map(str => str.trim()) - .join(' '); -}; +exports.format = format +exports.parse = parse /** - * Map %O to `util.inspect()`, allowing multiple lines if needed. + * Format object to media type. + * + * @param {object} obj + * @return {string} + * @public */ -formatters.O = function (v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts); -}; - +function format (obj) { + if (!obj || typeof obj !== 'object') { + throw new TypeError('argument obj is required') + } -/***/ }), + var parameters = obj.parameters + var type = obj.type -/***/ 56323: -/***/ ((module) => { + if (!type || !TYPE_REGEXP.test(type)) { + throw new TypeError('invalid type') + } -"use strict"; + var string = type + // append parameters + if (parameters && typeof parameters === 'object') { + var param + var params = Object.keys(parameters).sort() -var isMergeableObject = function isMergeableObject(value) { - return isNonNullObject(value) - && !isSpecial(value) -}; + for (var i = 0; i < params.length; i++) { + param = params[i] -function isNonNullObject(value) { - return !!value && typeof value === 'object' -} + if (!TOKEN_REGEXP.test(param)) { + throw new TypeError('invalid parameter name') + } -function isSpecial(value) { - var stringValue = Object.prototype.toString.call(value); + string += '; ' + param + '=' + qstring(parameters[param]) + } + } - return stringValue === '[object RegExp]' - || stringValue === '[object Date]' - || isReactElement(value) + return string } -// see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25 -var canUseSymbol = typeof Symbol === 'function' && Symbol.for; -var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7; +/** + * Parse media type to object. + * + * @param {string|object} string + * @return {Object} + * @public + */ -function isReactElement(value) { - return value.$$typeof === REACT_ELEMENT_TYPE -} +function parse (string) { + if (!string) { + throw new TypeError('argument string is required') + } -function emptyTarget(val) { - return Array.isArray(val) ? [] : {} -} + // support req/res-like objects as argument + var header = typeof string === 'object' + ? getcontenttype(string) + : string -function cloneUnlessOtherwiseSpecified(value, options) { - return (options.clone !== false && options.isMergeableObject(value)) - ? deepmerge(emptyTarget(value), value, options) - : value -} + if (typeof header !== 'string') { + throw new TypeError('argument string is required to be a string') + } -function defaultArrayMerge(target, source, options) { - return target.concat(source).map(function(element) { - return cloneUnlessOtherwiseSpecified(element, options) - }) -} + var index = header.indexOf(';') + var type = index !== -1 + ? header.substr(0, index).trim() + : header.trim() -function getMergeFunction(key, options) { - if (!options.customMerge) { - return deepmerge - } - var customMerge = options.customMerge(key); - return typeof customMerge === 'function' ? customMerge : deepmerge -} + if (!TYPE_REGEXP.test(type)) { + throw new TypeError('invalid media type') + } -function getEnumerableOwnPropertySymbols(target) { - return Object.getOwnPropertySymbols - ? Object.getOwnPropertySymbols(target).filter(function(symbol) { - return target.propertyIsEnumerable(symbol) - }) - : [] -} + var obj = new ContentType(type.toLowerCase()) -function getKeys(target) { - return Object.keys(target).concat(getEnumerableOwnPropertySymbols(target)) -} + // parse parameters + if (index !== -1) { + var key + var match + var value -function propertyIsOnObject(object, property) { - try { - return property in object - } catch(_) { - return false - } -} + PARAM_REGEXP.lastIndex = index -// Protects from prototype poisoning and unexpected merging up the prototype chain. -function propertyIsUnsafe(target, key) { - return propertyIsOnObject(target, key) // Properties are safe to merge if they don't exist in the target yet, - && !(Object.hasOwnProperty.call(target, key) // unsafe if they exist up the prototype chain, - && Object.propertyIsEnumerable.call(target, key)) // and also unsafe if they're nonenumerable. -} + while ((match = PARAM_REGEXP.exec(header))) { + if (match.index !== index) { + throw new TypeError('invalid parameter format') + } -function mergeObject(target, source, options) { - var destination = {}; - if (options.isMergeableObject(target)) { - getKeys(target).forEach(function(key) { - destination[key] = cloneUnlessOtherwiseSpecified(target[key], options); - }); - } - getKeys(source).forEach(function(key) { - if (propertyIsUnsafe(target, key)) { - return - } + index += match[0].length + key = match[1].toLowerCase() + value = match[2] - if (propertyIsOnObject(target, key) && options.isMergeableObject(source[key])) { - destination[key] = getMergeFunction(key, options)(target[key], source[key], options); - } else { - destination[key] = cloneUnlessOtherwiseSpecified(source[key], options); - } - }); - return destination -} + if (value[0] === '"') { + // remove quotes and escapes + value = value + .substr(1, value.length - 2) + .replace(QESC_REGEXP, '$1') + } -function deepmerge(target, source, options) { - options = options || {}; - options.arrayMerge = options.arrayMerge || defaultArrayMerge; - options.isMergeableObject = options.isMergeableObject || isMergeableObject; - // cloneUnlessOtherwiseSpecified is added to `options` so that custom arrayMerge() - // implementations can use it. The caller may not replace it. - options.cloneUnlessOtherwiseSpecified = cloneUnlessOtherwiseSpecified; + obj.parameters[key] = value + } - var sourceIsArray = Array.isArray(source); - var targetIsArray = Array.isArray(target); - var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray; + if (index !== header.length) { + throw new TypeError('invalid parameter format') + } + } - if (!sourceAndTargetTypesMatch) { - return cloneUnlessOtherwiseSpecified(source, options) - } else if (sourceIsArray) { - return options.arrayMerge(target, source, options) - } else { - return mergeObject(target, source, options) - } + return obj } -deepmerge.all = function deepmergeAll(array, options) { - if (!Array.isArray(array)) { - throw new Error('first argument should be an array') - } +/** + * Get content-type from req/res objects. + * + * @param {object} + * @return {Object} + * @private + */ - return array.reduce(function(prev, next) { - return deepmerge(prev, next, options) - }, {}) -}; +function getcontenttype (obj) { + var header -var deepmerge_1 = deepmerge; + if (typeof obj.getHeader === 'function') { + // res-like + header = obj.getHeader('content-type') + } else if (typeof obj.headers === 'object') { + // req-like + header = obj.headers && obj.headers['content-type'] + } -module.exports = deepmerge_1; + if (typeof header !== 'string') { + throw new TypeError('content-type header is missing from object') + } + return header +} -/***/ }), +/** + * Quote a string if necessary. + * + * @param {string} val + * @return {string} + * @private + */ -/***/ 42342: -/***/ ((module) => { +function qstring (val) { + var str = String(val) -"use strict"; + // no need to quote tokens + if (TOKEN_REGEXP.test(str)) { + return str + } + + if (str.length > 0 && !TEXT_REGEXP.test(str)) { + throw new TypeError('invalid parameter value') + } + return '"' + str.replace(QUOTE_REGEXP, '\\$1') + '"' +} /** - * Custom implementation of a double ended queue. + * Class to represent a content type. + * @private */ -function Denque(array, options) { - var options = options || {}; - - this._head = 0; - this._tail = 0; - this._capacity = options.capacity; - this._capacityMask = 0x3; - this._list = new Array(4); - if (Array.isArray(array)) { - this._fromArray(array); - } +function ContentType (type) { + this.parameters = Object.create(null) + this.type = type } + +/***/ }), + +/***/ 61579: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + /** - * ------------- - * PUBLIC API - * ------------- + * Module dependencies. */ -/** - * Returns the item at the specified index from the list. - * 0 is the first element, 1 is the second, and so on... - * Elements at negative values are that many from the end: -1 is one before the end - * (the last element), -2 is two before the end (one before last), etc. - * @param index - * @returns {*} - */ -Denque.prototype.peekAt = function peekAt(index) { - var i = index; - // expect a number or return undefined - if ((i !== (i | 0))) { - return void 0; - } - var len = this.size(); - if (i >= len || i < -len) return undefined; - if (i < 0) i += len; - i = (this._head + i) & this._capacityMask; - return this._list[i]; -}; +var crypto = __nccwpck_require__(6113); /** - * Alias for peekAt() - * @param i - * @returns {*} + * Sign the given `val` with `secret`. + * + * @param {String} val + * @param {String} secret + * @return {String} + * @api private */ -Denque.prototype.get = function get(i) { - return this.peekAt(i); -}; -/** - * Returns the first item in the list without removing it. - * @returns {*} - */ -Denque.prototype.peek = function peek() { - if (this._head === this._tail) return undefined; - return this._list[this._head]; +exports.sign = function(val, secret){ + if ('string' != typeof val) throw new TypeError("Cookie value must be provided as a string."); + if ('string' != typeof secret) throw new TypeError("Secret string must be provided."); + return val + '.' + crypto + .createHmac('sha256', secret) + .update(val) + .digest('base64') + .replace(/\=+$/, ''); }; /** - * Alias for peek() - * @returns {*} + * Unsign and decode the given `val` with `secret`, + * returning `false` if the signature is invalid. + * + * @param {String} val + * @param {String} secret + * @return {String|Boolean} + * @api private */ -Denque.prototype.peekFront = function peekFront() { - return this.peek(); -}; -/** - * Returns the item that is at the back of the queue without removing it. - * Uses peekAt(-1) - */ -Denque.prototype.peekBack = function peekBack() { - return this.peekAt(-1); +exports.unsign = function(val, secret){ + if ('string' != typeof val) throw new TypeError("Signed cookie string must be provided."); + if ('string' != typeof secret) throw new TypeError("Secret string must be provided."); + var str = val.slice(0, val.lastIndexOf('.')) + , mac = exports.sign(str, secret); + + return sha1(mac) == sha1(val) ? str : false; }; /** - * Returns the current length of the queue - * @return {Number} + * Private */ -Object.defineProperty(Denque.prototype, 'length', { - get: function length() { - return this.size(); - } -}); -/** - * Return the number of items on the list, or 0 if empty. - * @returns {number} - */ -Denque.prototype.size = function size() { - if (this._head === this._tail) return 0; - if (this._head < this._tail) return this._tail - this._head; - else return this._capacityMask + 1 - (this._head - this._tail); -}; +function sha1(str){ + return crypto.createHash('sha1').update(str).digest('hex'); +} -/** - * Add an item at the beginning of the list. - * @param item + +/***/ }), + +/***/ 93658: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; +/*! + * cookie + * Copyright(c) 2012-2014 Roman Shtylman + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed */ -Denque.prototype.unshift = function unshift(item) { - if (item === undefined) return this.size(); - var len = this._list.length; - this._head = (this._head - 1 + len) & this._capacityMask; - this._list[this._head] = item; - if (this._tail === this._head) this._growArray(); - if (this._capacity && this.size() > this._capacity) this.pop(); - if (this._head < this._tail) return this._tail - this._head; - else return this._capacityMask + 1 - (this._head - this._tail); -}; + + /** - * Remove and return the first item on the list, - * Returns undefined if the list is empty. - * @returns {*} + * Module exports. + * @public */ -Denque.prototype.shift = function shift() { - var head = this._head; - if (head === this._tail) return undefined; - var item = this._list[head]; - this._list[head] = undefined; - this._head = (head + 1) & this._capacityMask; - if (head < 2 && this._tail > 10000 && this._tail <= this._list.length >>> 2) this._shrinkArray(); - return item; -}; + +exports.parse = parse; +exports.serialize = serialize; /** - * Add an item to the bottom of the list. - * @param item + * Module variables. + * @private */ -Denque.prototype.push = function push(item) { - if (item === undefined) return this.size(); - var tail = this._tail; - this._list[tail] = item; - this._tail = (tail + 1) & this._capacityMask; - if (this._tail === this._head) { - this._growArray(); - } - if (this._capacity && this.size() > this._capacity) { - this.shift(); - } - if (this._head < this._tail) return this._tail - this._head; - else return this._capacityMask + 1 - (this._head - this._tail); -}; + +var decode = decodeURIComponent; +var encode = encodeURIComponent; +var pairSplitRegExp = /; */; /** - * Remove and return the last item on the list. - * Returns undefined if the list is empty. - * @returns {*} + * RegExp to match field-content in RFC 7230 sec 3.2 + * + * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] + * field-vchar = VCHAR / obs-text + * obs-text = %x80-FF */ -Denque.prototype.pop = function pop() { - var tail = this._tail; - if (tail === this._head) return undefined; - var len = this._list.length; - this._tail = (tail - 1 + len) & this._capacityMask; - var item = this._list[this._tail]; - this._list[this._tail] = undefined; - if (this._head < 2 && tail > 10000 && tail <= len >>> 2) this._shrinkArray(); - return item; -}; + +var fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/; /** - * Remove and return the item at the specified index from the list. - * Returns undefined if the list is empty. - * @param index - * @returns {*} + * Parse a cookie header. + * + * Parse the given cookie header string into an object + * The object has the various cookies as keys(names) => values + * + * @param {string} str + * @param {object} [options] + * @return {object} + * @public */ -Denque.prototype.removeOne = function removeOne(index) { - var i = index; - // expect a number or return undefined - if ((i !== (i | 0))) { - return void 0; + +function parse(str, options) { + if (typeof str !== 'string') { + throw new TypeError('argument str must be a string'); } - if (this._head === this._tail) return void 0; - var size = this.size(); - var len = this._list.length; - if (i >= size || i < -size) return void 0; - if (i < 0) i += size; - i = (this._head + i) & this._capacityMask; - var item = this._list[i]; - var k; - if (index < size / 2) { - for (k = index; k > 0; k--) { - this._list[i] = this._list[i = (i - 1 + len) & this._capacityMask]; + + var obj = {} + var opt = options || {}; + var pairs = str.split(pairSplitRegExp); + var dec = opt.decode || decode; + + for (var i = 0; i < pairs.length; i++) { + var pair = pairs[i]; + var eq_idx = pair.indexOf('='); + + // skip things that don't look like key=value + if (eq_idx < 0) { + continue; } - this._list[i] = void 0; - this._head = (this._head + 1 + len) & this._capacityMask; - } else { - for (k = size - 1 - index; k > 0; k--) { - this._list[i] = this._list[i = ( i + 1 + len) & this._capacityMask]; + + var key = pair.substr(0, eq_idx).trim() + var val = pair.substr(++eq_idx, pair.length).trim(); + + // quoted values + if ('"' == val[0]) { + val = val.slice(1, -1); + } + + // only assign once + if (undefined == obj[key]) { + obj[key] = tryDecode(val, dec); } - this._list[i] = void 0; - this._tail = (this._tail - 1 + len) & this._capacityMask; } - return item; -}; + + return obj; +} /** - * Remove number of items from the specified index from the list. - * Returns array of removed items. - * Returns undefined if the list is empty. - * @param index - * @param count - * @returns {array} + * Serialize data into a cookie header. + * + * Serialize the a name value pair into a cookie string suitable for + * http headers. An optional options object specified cookie parameters. + * + * serialize('foo', 'bar', { httpOnly: true }) + * => "foo=bar; httpOnly" + * + * @param {string} name + * @param {string} val + * @param {object} [options] + * @return {string} + * @public */ -Denque.prototype.remove = function remove(index, count) { - var i = index; - var removed; - var del_count = count; - // expect a number or return undefined - if ((i !== (i | 0))) { - return void 0; - } - if (this._head === this._tail) return void 0; - var size = this.size(); - var len = this._list.length; - if (i >= size || i < -size || count < 1) return void 0; - if (i < 0) i += size; - if (count === 1 || !count) { - removed = new Array(1); - removed[0] = this.removeOne(i); - return removed; + +function serialize(name, val, options) { + var opt = options || {}; + var enc = opt.encode || encode; + + if (typeof enc !== 'function') { + throw new TypeError('option encode is invalid'); } - if (i === 0 && i + count >= size) { - removed = this.toArray(); - this.clear(); - return removed; + + if (!fieldContentRegExp.test(name)) { + throw new TypeError('argument name is invalid'); } - if (i + count > size) count = size - i; - var k; - removed = new Array(count); - for (k = 0; k < count; k++) { - removed[k] = this._list[(this._head + i + k) & this._capacityMask]; + + var value = enc(val); + + if (value && !fieldContentRegExp.test(value)) { + throw new TypeError('argument val is invalid'); } - i = (this._head + i) & this._capacityMask; - if (index + count === size) { - this._tail = (this._tail - count + len) & this._capacityMask; - for (k = count; k > 0; k--) { - this._list[i = (i + 1 + len) & this._capacityMask] = void 0; + + var str = name + '=' + value; + + if (null != opt.maxAge) { + var maxAge = opt.maxAge - 0; + + if (isNaN(maxAge) || !isFinite(maxAge)) { + throw new TypeError('option maxAge is invalid') } - return removed; + + str += '; Max-Age=' + Math.floor(maxAge); } - if (index === 0) { - this._head = (this._head + count + len) & this._capacityMask; - for (k = count - 1; k > 0; k--) { - this._list[i = (i + 1 + len) & this._capacityMask] = void 0; + + if (opt.domain) { + if (!fieldContentRegExp.test(opt.domain)) { + throw new TypeError('option domain is invalid'); } - return removed; + + str += '; Domain=' + opt.domain; } - if (i < size / 2) { - this._head = (this._head + index + count + len) & this._capacityMask; - for (k = index; k > 0; k--) { - this.unshift(this._list[i = (i - 1 + len) & this._capacityMask]); - } - i = (this._head - 1 + len) & this._capacityMask; - while (del_count > 0) { - this._list[i = (i - 1 + len) & this._capacityMask] = void 0; - del_count--; - } - if (index < 0) this._tail = i; - } else { - this._tail = i; - i = (i + count + len) & this._capacityMask; - for (k = size - (count + index); k > 0; k--) { - this.push(this._list[i++]); - } - i = this._tail; - while (del_count > 0) { - this._list[i = (i + 1 + len) & this._capacityMask] = void 0; - del_count--; + + if (opt.path) { + if (!fieldContentRegExp.test(opt.path)) { + throw new TypeError('option path is invalid'); } - } - if (this._head < 2 && this._tail > 10000 && this._tail <= len >>> 2) this._shrinkArray(); - return removed; -}; -/** - * Native splice implementation. - * Remove number of items from the specified index from the list and/or add new elements. - * Returns array of removed items or empty array if count == 0. - * Returns undefined if the list is empty. - * - * @param index - * @param count - * @param {...*} [elements] - * @returns {array} - */ -Denque.prototype.splice = function splice(index, count) { - var i = index; - // expect a number or return undefined - if ((i !== (i | 0))) { - return void 0; + str += '; Path=' + opt.path; } - var size = this.size(); - if (i < 0) i += size; - if (i > size) return void 0; - if (arguments.length > 2) { - var k; - var temp; - var removed; - var arg_len = arguments.length; - var len = this._list.length; - var arguments_index = 2; - if (!size || i < size / 2) { - temp = new Array(i); - for (k = 0; k < i; k++) { - temp[k] = this._list[(this._head + k) & this._capacityMask]; - } - if (count === 0) { - removed = []; - if (i > 0) { - this._head = (this._head + i + len) & this._capacityMask; - } - } else { - removed = this.remove(i, count); - this._head = (this._head + i + len) & this._capacityMask; - } - while (arg_len > arguments_index) { - this.unshift(arguments[--arg_len]); - } - for (k = i; k > 0; k--) { - this.unshift(temp[k - 1]); - } - } else { - temp = new Array(size - (i + count)); - var leng = temp.length; - for (k = 0; k < leng; k++) { - temp[k] = this._list[(this._head + i + count + k) & this._capacityMask]; - } - if (count === 0) { - removed = []; - if (i != size) { - this._tail = (this._head + i + len) & this._capacityMask; - } - } else { - removed = this.remove(i, count); - this._tail = (this._tail - leng + len) & this._capacityMask; - } - while (arguments_index < arg_len) { - this.push(arguments[arguments_index++]); - } - for (k = 0; k < leng; k++) { - this.push(temp[k]); - } + + if (opt.expires) { + if (typeof opt.expires.toUTCString !== 'function') { + throw new TypeError('option expires is invalid'); } - return removed; - } else { - return this.remove(i, count); + + str += '; Expires=' + opt.expires.toUTCString(); } -}; -/** - * Soft clear - does not reset capacity. - */ -Denque.prototype.clear = function clear() { - this._head = 0; - this._tail = 0; -}; + if (opt.httpOnly) { + str += '; HttpOnly'; + } -/** - * Returns true or false whether the list is empty. - * @returns {boolean} - */ -Denque.prototype.isEmpty = function isEmpty() { - return this._head === this._tail; -}; + if (opt.secure) { + str += '; Secure'; + } -/** - * Returns an array of all queue items. - * @returns {Array} - */ -Denque.prototype.toArray = function toArray() { - return this._copyArray(false); -}; + if (opt.sameSite) { + var sameSite = typeof opt.sameSite === 'string' + ? opt.sameSite.toLowerCase() : opt.sameSite; -/** - * ------------- - * INTERNALS - * ------------- - */ + switch (sameSite) { + case true: + str += '; SameSite=Strict'; + break; + case 'lax': + str += '; SameSite=Lax'; + break; + case 'strict': + str += '; SameSite=Strict'; + break; + case 'none': + str += '; SameSite=None'; + break; + default: + throw new TypeError('option sameSite is invalid'); + } + } -/** - * Fills the queue with items from an array - * For use in the constructor - * @param array - * @private - */ -Denque.prototype._fromArray = function _fromArray(array) { - for (var i = 0; i < array.length; i++) this.push(array[i]); -}; + return str; +} /** + * Try decoding a string using a decoding function. * - * @param fullCopy - * @returns {Array} + * @param {string} str + * @param {function} decode * @private */ -Denque.prototype._copyArray = function _copyArray(fullCopy) { - var newArray = []; - var list = this._list; - var len = list.length; - var i; - if (fullCopy || this._head > this._tail) { - for (i = this._head; i < len; i++) newArray.push(list[i]); - for (i = 0; i < this._tail; i++) newArray.push(list[i]); - } else { - for (i = this._head; i < this._tail; i++) newArray.push(list[i]); - } - return newArray; -}; -/** - * Grows the internal list array. - * @private - */ -Denque.prototype._growArray = function _growArray() { - if (this._head) { - // copy existing data, head to end, then beginning to tail. - this._list = this._copyArray(true); - this._head = 0; +function tryDecode(str, decode) { + try { + return decode(str); + } catch (e) { + return str; } +} - // head is at 0 and array is now full, safe to extend - this._tail = this._list.length; - - this._list.length <<= 1; - this._capacityMask = (this._capacityMask << 1) | 1; -}; - -/** - * Shrinks the internal list array. - * @private - */ -Denque.prototype._shrinkArray = function _shrinkArray() { - this._list.length >>>= 1; - this._capacityMask >>>= 1; -}; +/***/ }), -module.exports = Denque; +/***/ 51512: +/***/ ((module, exports) => { +"use strict"; +function _typeof(obj){"@babel/helpers - typeof";if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj}}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj}}return _typeof(obj)}(function(global){var _arguments=arguments;var dateFormat=function(){var token=/d{1,4}|D{3,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|W{1,2}|[LlopSZN]|"[^"]*"|'[^']*'/g;var timezone=/\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g;var timezoneClip=/[^-+\dA-Z]/g;return function(date,mask,utc,gmt){if(_arguments.length===1&&kindOf(date)==="string"&&!/\d/.test(date)){mask=date;date=undefined}date=date||date===0?date:new Date;if(!(date instanceof Date)){date=new Date(date)}if(isNaN(date)){throw TypeError("Invalid date")}mask=String(dateFormat.masks[mask]||mask||dateFormat.masks["default"]);var maskSlice=mask.slice(0,4);if(maskSlice==="UTC:"||maskSlice==="GMT:"){mask=mask.slice(4);utc=true;if(maskSlice==="GMT:"){gmt=true}}var _=function _(){return utc?"getUTC":"get"};var _d=function d(){return date[_()+"Date"]()};var D=function D(){return date[_()+"Day"]()};var _m=function m(){return date[_()+"Month"]()};var y=function y(){return date[_()+"FullYear"]()};var _H=function H(){return date[_()+"Hours"]()};var _M=function M(){return date[_()+"Minutes"]()};var _s=function s(){return date[_()+"Seconds"]()};var _L=function L(){return date[_()+"Milliseconds"]()};var _o=function o(){return utc?0:date.getTimezoneOffset()};var _W=function W(){return getWeek(date)};var _N=function N(){return getDayOfWeek(date)};var flags={d:function d(){return _d()},dd:function dd(){return pad(_d())},ddd:function ddd(){return dateFormat.i18n.dayNames[D()]},DDD:function DDD(){return getDayName({y:y(),m:_m(),d:_d(),_:_(),dayName:dateFormat.i18n.dayNames[D()],short:true})},dddd:function dddd(){return dateFormat.i18n.dayNames[D()+7]},DDDD:function DDDD(){return getDayName({y:y(),m:_m(),d:_d(),_:_(),dayName:dateFormat.i18n.dayNames[D()+7]})},m:function m(){return _m()+1},mm:function mm(){return pad(_m()+1)},mmm:function mmm(){return dateFormat.i18n.monthNames[_m()]},mmmm:function mmmm(){return dateFormat.i18n.monthNames[_m()+12]},yy:function yy(){return String(y()).slice(2)},yyyy:function yyyy(){return pad(y(),4)},h:function h(){return _H()%12||12},hh:function hh(){return pad(_H()%12||12)},H:function H(){return _H()},HH:function HH(){return pad(_H())},M:function M(){return _M()},MM:function MM(){return pad(_M())},s:function s(){return _s()},ss:function ss(){return pad(_s())},l:function l(){return pad(_L(),3)},L:function L(){return pad(Math.floor(_L()/10))},t:function t(){return _H()<12?dateFormat.i18n.timeNames[0]:dateFormat.i18n.timeNames[1]},tt:function tt(){return _H()<12?dateFormat.i18n.timeNames[2]:dateFormat.i18n.timeNames[3]},T:function T(){return _H()<12?dateFormat.i18n.timeNames[4]:dateFormat.i18n.timeNames[5]},TT:function TT(){return _H()<12?dateFormat.i18n.timeNames[6]:dateFormat.i18n.timeNames[7]},Z:function Z(){return gmt?"GMT":utc?"UTC":(String(date).match(timezone)||[""]).pop().replace(timezoneClip,"").replace(/GMT\+0000/g,"UTC")},o:function o(){return(_o()>0?"-":"+")+pad(Math.floor(Math.abs(_o())/60)*100+Math.abs(_o())%60,4)},p:function p(){return(_o()>0?"-":"+")+pad(Math.floor(Math.abs(_o())/60),2)+":"+pad(Math.floor(Math.abs(_o())%60),2)},S:function S(){return["th","st","nd","rd"][_d()%10>3?0:(_d()%100-_d()%10!=10)*_d()%10]},W:function W(){return _W()},WW:function WW(){return pad(_W())},N:function N(){return _N()}};return mask.replace(token,function(match){if(match in flags){return flags[match]()}return match.slice(1,match.length-1)})}}();dateFormat.masks={default:"ddd mmm dd yyyy HH:MM:ss",shortDate:"m/d/yy",paddedShortDate:"mm/dd/yyyy",mediumDate:"mmm d, yyyy",longDate:"mmmm d, yyyy",fullDate:"dddd, mmmm d, yyyy",shortTime:"h:MM TT",mediumTime:"h:MM:ss TT",longTime:"h:MM:ss TT Z",isoDate:"yyyy-mm-dd",isoTime:"HH:MM:ss",isoDateTime:"yyyy-mm-dd'T'HH:MM:sso",isoUtcDateTime:"UTC:yyyy-mm-dd'T'HH:MM:ss'Z'",expiresHeaderFormat:"ddd, dd mmm yyyy HH:MM:ss Z"};dateFormat.i18n={dayNames:["Sun","Mon","Tue","Wed","Thu","Fri","Sat","Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],monthNames:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec","January","February","March","April","May","June","July","August","September","October","November","December"],timeNames:["a","p","am","pm","A","P","AM","PM"]};var pad=function pad(val,len){val=String(val);len=len||2;while(val.length { +/***/ 28222: +/***/ ((module, exports, __nccwpck_require__) => { -/*! - * depd - * Copyright(c) 2014-2017 Douglas Christopher Wilson - * MIT Licensed - */ +/* eslint-env browser */ /** - * Module dependencies. + * This is the web browser implementation of `debug()`. */ -var callSiteToString = (__nccwpck_require__(69829).callSiteToString) -var eventListenerCount = (__nccwpck_require__(69829).eventListenerCount) -var relative = (__nccwpck_require__(71017).relative) - -/** - * Module exports. - */ +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = localstorage(); +exports.destroy = (() => { + let warned = false; -module.exports = depd + return () => { + if (!warned) { + warned = true; + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } + }; +})(); /** - * Get the path to base files on. + * Colors. */ -var basePath = process.cwd() +exports.colors = [ + '#0000CC', + '#0000FF', + '#0033CC', + '#0033FF', + '#0066CC', + '#0066FF', + '#0099CC', + '#0099FF', + '#00CC00', + '#00CC33', + '#00CC66', + '#00CC99', + '#00CCCC', + '#00CCFF', + '#3300CC', + '#3300FF', + '#3333CC', + '#3333FF', + '#3366CC', + '#3366FF', + '#3399CC', + '#3399FF', + '#33CC00', + '#33CC33', + '#33CC66', + '#33CC99', + '#33CCCC', + '#33CCFF', + '#6600CC', + '#6600FF', + '#6633CC', + '#6633FF', + '#66CC00', + '#66CC33', + '#9900CC', + '#9900FF', + '#9933CC', + '#9933FF', + '#99CC00', + '#99CC33', + '#CC0000', + '#CC0033', + '#CC0066', + '#CC0099', + '#CC00CC', + '#CC00FF', + '#CC3300', + '#CC3333', + '#CC3366', + '#CC3399', + '#CC33CC', + '#CC33FF', + '#CC6600', + '#CC6633', + '#CC9900', + '#CC9933', + '#CCCC00', + '#CCCC33', + '#FF0000', + '#FF0033', + '#FF0066', + '#FF0099', + '#FF00CC', + '#FF00FF', + '#FF3300', + '#FF3333', + '#FF3366', + '#FF3399', + '#FF33CC', + '#FF33FF', + '#FF6600', + '#FF6633', + '#FF9900', + '#FF9933', + '#FFCC00', + '#FFCC33' +]; /** - * Determine if namespace is contained in the string. + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. + * + * TODO: add a `localStorage` variable to explicitly enable/disable colors */ -function containsNamespace (str, namespace) { - var vals = str.split(/[ ,]+/) - var ns = String(namespace).toLowerCase() - - for (var i = 0; i < vals.length; i++) { - var val = vals[i] +// eslint-disable-next-line complexity +function useColors() { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { + return true; + } - // namespace contained - if (val && (val === '*' || val.toLowerCase() === ns)) { - return true - } - } + // Internet Explorer and Edge do not support colors. + if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; + } - return false + // Is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || + // Is firebug? http://stackoverflow.com/a/398120/376773 + (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || + // Is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || + // Double check webkit in userAgent just in case we are in a worker + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); } /** - * Convert a data descriptor to accessor descriptor. + * Colorize log arguments if enabled. + * + * @api public */ -function convertDataDescriptorToAccessor (obj, prop, message) { - var descriptor = Object.getOwnPropertyDescriptor(obj, prop) - var value = descriptor.value - - descriptor.get = function getter () { return value } +function formatArgs(args) { + args[0] = (this.useColors ? '%c' : '') + + this.namespace + + (this.useColors ? ' %c' : ' ') + + args[0] + + (this.useColors ? '%c ' : ' ') + + '+' + module.exports.humanize(this.diff); - if (descriptor.writable) { - descriptor.set = function setter (val) { return (value = val) } - } + if (!this.useColors) { + return; + } - delete descriptor.value - delete descriptor.writable + const c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit'); - Object.defineProperty(obj, prop, descriptor) + // The final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + let index = 0; + let lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, match => { + if (match === '%%') { + return; + } + index++; + if (match === '%c') { + // We only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); - return descriptor + args.splice(lastC, 0, c); } /** - * Create arguments string to keep arity. + * Invokes `console.debug()` when available. + * No-op when `console.debug` is not a "function". + * If `console.debug` is not available, falls back + * to `console.log`. + * + * @api public */ - -function createArgumentsString (arity) { - var str = '' - - for (var i = 0; i < arity; i++) { - str += ', arg' + i - } - - return str.substr(2) -} +exports.log = console.debug || console.log || (() => {}); /** - * Create stack string from stack. + * Save `namespaces`. + * + * @param {String} namespaces + * @api private */ - -function createStackString (stack) { - var str = this.name + ': ' + this.namespace - - if (this.message) { - str += ' deprecated ' + this.message - } - - for (var i = 0; i < stack.length; i++) { - str += '\n at ' + callSiteToString(stack[i]) - } - - return str +function save(namespaces) { + try { + if (namespaces) { + exports.storage.setItem('debug', namespaces); + } else { + exports.storage.removeItem('debug'); + } + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } } /** - * Create deprecate for namespace in caller. + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private */ +function load() { + let r; + try { + r = exports.storage.getItem('debug'); + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } -function depd (namespace) { - if (!namespace) { - throw new TypeError('argument namespace is required') - } - - var stack = getStack() - var site = callSiteLocation(stack[1]) - var file = site[0] - - function deprecate (message) { - // call to self as log - log.call(deprecate, message) - } - - deprecate._file = file - deprecate._ignored = isignored(namespace) - deprecate._namespace = namespace - deprecate._traced = istraced(namespace) - deprecate._warned = Object.create(null) - - deprecate.function = wrapfunction - deprecate.property = wrapproperty + // If debug isn't set in LS, and we're in Electron, try to load $DEBUG + if (!r && typeof process !== 'undefined' && 'env' in process) { + r = process.env.DEBUG; + } - return deprecate + return r; } /** - * Determine if namespace is ignored. + * Localstorage attempts to return the localstorage. + * + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. + * + * @return {LocalStorage} + * @api private */ -function isignored (namespace) { - /* istanbul ignore next: tested in a child processs */ - if (process.noDeprecation) { - // --no-deprecation support - return true - } +function localstorage() { + try { + // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context + // The Browser also has localStorage in the global context. + return localStorage; + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } +} - var str = process.env.NO_DEPRECATION || '' +module.exports = __nccwpck_require__(46243)(exports); - // namespace ignored - return containsNamespace(str, namespace) -} +const {formatters} = module.exports; /** - * Determine if namespace is traced. + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. */ -function istraced (namespace) { - /* istanbul ignore next: tested in a child processs */ - if (process.traceDeprecation) { - // --trace-deprecation support - return true - } +formatters.j = function (v) { + try { + return JSON.stringify(v); + } catch (error) { + return '[UnexpectedJSONParseError]: ' + error.message; + } +}; - var str = process.env.TRACE_DEPRECATION || '' - // namespace traced - return containsNamespace(str, namespace) -} +/***/ }), + +/***/ 46243: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + /** - * Display deprecation message. + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. */ -function log (message, site) { - var haslisteners = eventListenerCount(process, 'deprecation') !== 0 +function setup(env) { + createDebug.debug = createDebug; + createDebug.default = createDebug; + createDebug.coerce = coerce; + createDebug.disable = disable; + createDebug.enable = enable; + createDebug.enabled = enabled; + createDebug.humanize = __nccwpck_require__(80900); + createDebug.destroy = destroy; - // abort early if no destination - if (!haslisteners && this._ignored) { - return - } + Object.keys(env).forEach(key => { + createDebug[key] = env[key]; + }); - var caller - var callFile - var callSite - var depSite - var i = 0 - var seen = false - var stack = getStack() - var file = this._file + /** + * The currently active debug mode names, and names to skip. + */ - if (site) { - // provided site - depSite = site - callSite = callSiteLocation(stack[1]) - callSite.name = depSite.name - file = callSite[0] - } else { - // get call site - i = 2 - depSite = callSiteLocation(stack[i]) - callSite = depSite - } + createDebug.names = []; + createDebug.skips = []; - // get caller of deprecated thing in relation to file - for (; i < stack.length; i++) { - caller = callSiteLocation(stack[i]) - callFile = caller[0] + /** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + */ + createDebug.formatters = {}; - if (callFile === file) { - seen = true - } else if (callFile === this._file) { - file = this._file - } else if (seen) { - break - } - } + /** + * Selects a color for a debug namespace + * @param {String} namespace The namespace string for the debug instance to be colored + * @return {Number|String} An ANSI color code for the given namespace + * @api private + */ + function selectColor(namespace) { + let hash = 0; - var key = caller - ? depSite.join(':') + '__' + caller.join(':') - : undefined + for (let i = 0; i < namespace.length; i++) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } - if (key !== undefined && key in this._warned) { - // already warned - return - } + return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; + } + createDebug.selectColor = selectColor; - this._warned[key] = true + /** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + function createDebug(namespace) { + let prevTime; + let enableOverride = null; + let namespacesCache; + let enabledCache; - // generate automatic message from call site - var msg = message - if (!msg) { - msg = callSite === depSite || !callSite.name - ? defaultMessage(depSite) - : defaultMessage(callSite) - } + function debug(...args) { + // Disabled? + if (!debug.enabled) { + return; + } - // emit deprecation if listeners exist - if (haslisteners) { - var err = DeprecationError(this._namespace, msg, stack.slice(i)) - process.emit('deprecation', err) - return - } + const self = debug; - // format and write message - var format = process.stderr.isTTY - ? formatColor - : formatPlain - var output = format.call(this, msg, caller, stack.slice(i)) - process.stderr.write(output + '\n', 'utf8') -} - -/** - * Get call site location as array. - */ - -function callSiteLocation (callSite) { - var file = callSite.getFileName() || '' - var line = callSite.getLineNumber() - var colm = callSite.getColumnNumber() + // Set `diff` timestamp + const curr = Number(new Date()); + const ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; - if (callSite.isEval()) { - file = callSite.getEvalOrigin() + ', ' + file - } + args[0] = createDebug.coerce(args[0]); - var site = [file, line, colm] + if (typeof args[0] !== 'string') { + // Anything else let's inspect with %O + args.unshift('%O'); + } - site.callSite = callSite - site.name = callSite.getFunctionName() + // Apply any `formatters` transformations + let index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { + // If we encounter an escaped % then don't increase the array index + if (match === '%%') { + return '%'; + } + index++; + const formatter = createDebug.formatters[format]; + if (typeof formatter === 'function') { + const val = args[index]; + match = formatter.call(self, val); - return site -} + // Now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); -/** - * Generate a default message from the site. - */ + // Apply env-specific formatting (colors, etc.) + createDebug.formatArgs.call(self, args); -function defaultMessage (site) { - var callSite = site.callSite - var funcName = site.name + const logFn = self.log || createDebug.log; + logFn.apply(self, args); + } - // make useful anonymous name - if (!funcName) { - funcName = '' - } + debug.namespace = namespace; + debug.useColors = createDebug.useColors(); + debug.color = createDebug.selectColor(namespace); + debug.extend = extend; + debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. - var context = callSite.getThis() - var typeName = context && callSite.getTypeName() + Object.defineProperty(debug, 'enabled', { + enumerable: true, + configurable: false, + get: () => { + if (enableOverride !== null) { + return enableOverride; + } + if (namespacesCache !== createDebug.namespaces) { + namespacesCache = createDebug.namespaces; + enabledCache = createDebug.enabled(namespace); + } - // ignore useless type name - if (typeName === 'Object') { - typeName = undefined - } + return enabledCache; + }, + set: v => { + enableOverride = v; + } + }); - // make useful type name - if (typeName === 'Function') { - typeName = context.name || typeName - } + // Env-specific initialization logic for debug instances + if (typeof createDebug.init === 'function') { + createDebug.init(debug); + } - return typeName && callSite.getMethodName() - ? typeName + '.' + funcName - : funcName -} + return debug; + } -/** - * Format deprecation message without color. - */ + function extend(namespace, delimiter) { + const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); + newDebug.log = this.log; + return newDebug; + } -function formatPlain (msg, caller, stack) { - var timestamp = new Date().toUTCString() + /** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ + function enable(namespaces) { + createDebug.save(namespaces); + createDebug.namespaces = namespaces; - var formatted = timestamp + - ' ' + this._namespace + - ' deprecated ' + msg + createDebug.names = []; + createDebug.skips = []; - // add stack trace - if (this._traced) { - for (var i = 0; i < stack.length; i++) { - formatted += '\n at ' + callSiteToString(stack[i]) - } + let i; + const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + const len = split.length; - return formatted - } + for (i = 0; i < len; i++) { + if (!split[i]) { + // ignore empty strings + continue; + } - if (caller) { - formatted += ' at ' + formatLocation(caller) - } + namespaces = split[i].replace(/\*/g, '.*?'); - return formatted -} + if (namespaces[0] === '-') { + createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); + } else { + createDebug.names.push(new RegExp('^' + namespaces + '$')); + } + } + } -/** - * Format deprecation message with color. - */ + /** + * Disable debug output. + * + * @return {String} namespaces + * @api public + */ + function disable() { + const namespaces = [ + ...createDebug.names.map(toNamespace), + ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) + ].join(','); + createDebug.enable(''); + return namespaces; + } -function formatColor (msg, caller, stack) { - var formatted = '\x1b[36;1m' + this._namespace + '\x1b[22;39m' + // bold cyan - ' \x1b[33;1mdeprecated\x1b[22;39m' + // bold yellow - ' \x1b[0m' + msg + '\x1b[39m' // reset + /** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + function enabled(name) { + if (name[name.length - 1] === '*') { + return true; + } - // add stack trace - if (this._traced) { - for (var i = 0; i < stack.length; i++) { - formatted += '\n \x1b[36mat ' + callSiteToString(stack[i]) + '\x1b[39m' // cyan - } + let i; + let len; - return formatted - } + for (i = 0, len = createDebug.skips.length; i < len; i++) { + if (createDebug.skips[i].test(name)) { + return false; + } + } - if (caller) { - formatted += ' \x1b[36m' + formatLocation(caller) + '\x1b[39m' // cyan - } + for (i = 0, len = createDebug.names.length; i < len; i++) { + if (createDebug.names[i].test(name)) { + return true; + } + } - return formatted -} + return false; + } -/** - * Format call site location. - */ + /** + * Convert regexp to namespace + * + * @param {RegExp} regxep + * @return {String} namespace + * @api private + */ + function toNamespace(regexp) { + return regexp.toString() + .substring(2, regexp.toString().length - 2) + .replace(/\.\*\?$/, '*'); + } -function formatLocation (callSite) { - return relative(basePath, callSite[0]) + - ':' + callSite[1] + - ':' + callSite[2] -} + /** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + function coerce(val) { + if (val instanceof Error) { + return val.stack || val.message; + } + return val; + } -/** - * Get the stack as array of call sites. - */ + /** + * XXX DO NOT USE. This is a temporary stub function. + * XXX It WILL be removed in the next major release. + */ + function destroy() { + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } -function getStack () { - var limit = Error.stackTraceLimit - var obj = {} - var prep = Error.prepareStackTrace + createDebug.enable(createDebug.load()); - Error.prepareStackTrace = prepareObjectStackTrace - Error.stackTraceLimit = Math.max(10, limit) + return createDebug; +} - // capture the stack - Error.captureStackTrace(obj) +module.exports = setup; - // slice this function off the top - var stack = obj.stack.slice(1) - Error.prepareStackTrace = prep - Error.stackTraceLimit = limit +/***/ }), - return stack -} +/***/ 38237: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { /** - * Capture call site stack from v8. + * Detect Electron renderer / nwjs process, which is node, but we should + * treat as a browser. */ -function prepareObjectStackTrace (obj, stack) { - return stack +if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { + module.exports = __nccwpck_require__(28222); +} else { + module.exports = __nccwpck_require__(35332); } -/** - * Return a wrapped function in a deprecation message. - */ - -function wrapfunction (fn, message) { - if (typeof fn !== 'function') { - throw new TypeError('argument fn must be a function') - } - var args = createArgumentsString(fn.length) - var deprecate = this // eslint-disable-line no-unused-vars - var stack = getStack() - var site = callSiteLocation(stack[1]) +/***/ }), - site.name = fn.name +/***/ 35332: +/***/ ((module, exports, __nccwpck_require__) => { - // eslint-disable-next-line no-eval - var deprecatedfn = eval('(function (' + args + ') {\n' + - '"use strict"\n' + - 'log.call(deprecate, message, site)\n' + - 'return fn.apply(this, arguments)\n' + - '})') +/** + * Module dependencies. + */ - return deprecatedfn -} +const tty = __nccwpck_require__(76224); +const util = __nccwpck_require__(73837); /** - * Wrap property in a deprecation message. + * This is the Node.js implementation of `debug()`. */ -function wrapproperty (obj, prop, message) { - if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { - throw new TypeError('argument obj must be object') - } +exports.init = init; +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.destroy = util.deprecate( + () => {}, + 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' +); - var descriptor = Object.getOwnPropertyDescriptor(obj, prop) +/** + * Colors. + */ - if (!descriptor) { - throw new TypeError('must call property on owner object') - } +exports.colors = [6, 2, 3, 4, 5, 1]; - if (!descriptor.configurable) { - throw new TypeError('property must be configurable') - } +try { + // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) + // eslint-disable-next-line import/no-extraneous-dependencies + const supportsColor = __nccwpck_require__(59318); - var deprecate = this - var stack = getStack() - var site = callSiteLocation(stack[1]) + if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { + exports.colors = [ + 20, + 21, + 26, + 27, + 32, + 33, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 56, + 57, + 62, + 63, + 68, + 69, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 92, + 93, + 98, + 99, + 112, + 113, + 128, + 129, + 134, + 135, + 148, + 149, + 160, + 161, + 162, + 163, + 164, + 165, + 166, + 167, + 168, + 169, + 170, + 171, + 172, + 173, + 178, + 179, + 184, + 185, + 196, + 197, + 198, + 199, + 200, + 201, + 202, + 203, + 204, + 205, + 206, + 207, + 208, + 209, + 214, + 215, + 220, + 221 + ]; + } +} catch (error) { + // Swallow - we only care if `supports-color` is available; it doesn't have to be. +} - // set site name - site.name = prop +/** + * Build up the default `inspectOpts` object from the environment variables. + * + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + */ - // convert data descriptor - if ('value' in descriptor) { - descriptor = convertDataDescriptorToAccessor(obj, prop, message) - } +exports.inspectOpts = Object.keys(process.env).filter(key => { + return /^debug_/i.test(key); +}).reduce((obj, key) => { + // Camel-case + const prop = key + .substring(6) + .toLowerCase() + .replace(/_([a-z])/g, (_, k) => { + return k.toUpperCase(); + }); - var get = descriptor.get - var set = descriptor.set + // Coerce string value into JS value + let val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) { + val = true; + } else if (/^(no|off|false|disabled)$/i.test(val)) { + val = false; + } else if (val === 'null') { + val = null; + } else { + val = Number(val); + } - // wrap getter - if (typeof get === 'function') { - descriptor.get = function getter () { - log.call(deprecate, message, site) - return get.apply(this, arguments) - } - } + obj[prop] = val; + return obj; +}, {}); - // wrap setter - if (typeof set === 'function') { - descriptor.set = function setter () { - log.call(deprecate, message, site) - return set.apply(this, arguments) - } - } +/** + * Is stdout a TTY? Colored output is enabled when `true`. + */ - Object.defineProperty(obj, prop, descriptor) +function useColors() { + return 'colors' in exports.inspectOpts ? + Boolean(exports.inspectOpts.colors) : + tty.isatty(process.stderr.fd); } /** - * Create DeprecationError for deprecation + * Adds ANSI color escape codes if enabled. + * + * @api public */ -function DeprecationError (namespace, message, stack) { - var error = new Error() - var stackString - - Object.defineProperty(error, 'constructor', { - value: DeprecationError - }) +function formatArgs(args) { + const {namespace: name, useColors} = this; - Object.defineProperty(error, 'message', { - configurable: true, - enumerable: false, - value: message, - writable: true - }) - - Object.defineProperty(error, 'name', { - enumerable: false, - configurable: true, - value: 'DeprecationError', - writable: true - }) - - Object.defineProperty(error, 'namespace', { - configurable: true, - enumerable: false, - value: namespace, - writable: true - }) - - Object.defineProperty(error, 'stack', { - configurable: true, - enumerable: false, - get: function () { - if (stackString !== undefined) { - return stackString - } - - // prepare stack trace - return (stackString = createStackString.call(this, stack)) - }, - set: function setter (val) { - stackString = val - } - }) + if (useColors) { + const c = this.color; + const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); + const prefix = ` ${colorCode};1m${name} \u001B[0m`; - return error + args[0] = prefix + args[0].split('\n').join('\n' + prefix); + args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); + } else { + args[0] = getDate() + name + ' ' + args[0]; + } } - -/***/ }), - -/***/ 35554: -/***/ ((module) => { - -"use strict"; -/*! - * depd - * Copyright(c) 2014 Douglas Christopher Wilson - * MIT Licensed - */ - - +function getDate() { + if (exports.inspectOpts.hideDate) { + return ''; + } + return new Date().toISOString() + ' '; +} /** - * Module exports. + * Invokes `util.format()` with the specified arguments and writes to stderr. */ -module.exports = callSiteToString +function log(...args) { + return process.stderr.write(util.format(...args) + '\n'); +} /** - * Format a CallSite file location to a string. + * Save `namespaces`. + * + * @param {String} namespaces + * @api private */ - -function callSiteFileLocation (callSite) { - var fileName - var fileLocation = '' - - if (callSite.isNative()) { - fileLocation = 'native' - } else if (callSite.isEval()) { - fileName = callSite.getScriptNameOrSourceURL() - if (!fileName) { - fileLocation = callSite.getEvalOrigin() - } - } else { - fileName = callSite.getFileName() - } - - if (fileName) { - fileLocation += fileName - - var lineNumber = callSite.getLineNumber() - if (lineNumber != null) { - fileLocation += ':' + lineNumber - - var columnNumber = callSite.getColumnNumber() - if (columnNumber) { - fileLocation += ':' + columnNumber - } - } - } - - return fileLocation || 'unknown source' +function save(namespaces) { + if (namespaces) { + process.env.DEBUG = namespaces; + } else { + // If you set a process.env field to null or undefined, it gets cast to the + // string 'null' or 'undefined'. Just delete instead. + delete process.env.DEBUG; + } } /** - * Format a CallSite to a string. + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private */ -function callSiteToString (callSite) { - var addSuffix = true - var fileLocation = callSiteFileLocation(callSite) - var functionName = callSite.getFunctionName() - var isConstructor = callSite.isConstructor() - var isMethodCall = !(callSite.isToplevel() || isConstructor) - var line = '' - - if (isMethodCall) { - var methodName = callSite.getMethodName() - var typeName = getConstructorName(callSite) - - if (functionName) { - if (typeName && functionName.indexOf(typeName) !== 0) { - line += typeName + '.' - } - - line += functionName - - if (methodName && functionName.lastIndexOf('.' + methodName) !== functionName.length - methodName.length - 1) { - line += ' [as ' + methodName + ']' - } - } else { - line += typeName + '.' + (methodName || '') - } - } else if (isConstructor) { - line += 'new ' + (functionName || '') - } else if (functionName) { - line += functionName - } else { - addSuffix = false - line += fileLocation - } - - if (addSuffix) { - line += ' (' + fileLocation + ')' - } - - return line +function load() { + return process.env.DEBUG; } /** - * Get constructor name of reviver. + * Init logic for `debug` instances. + * + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. */ -function getConstructorName (obj) { - var receiver = obj.receiver - return (receiver.constructor && receiver.constructor.name) || null -} - - -/***/ }), - -/***/ 12078: -/***/ ((module) => { +function init(debug) { + debug.inspectOpts = {}; -"use strict"; -/*! - * depd - * Copyright(c) 2015 Douglas Christopher Wilson - * MIT Licensed - */ + const keys = Object.keys(exports.inspectOpts); + for (let i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } +} +module.exports = __nccwpck_require__(46243)(exports); +const {formatters} = module.exports; /** - * Module exports. - * @public + * Map %o to `util.inspect()`, all on a single line. */ -module.exports = eventListenerCount +formatters.o = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts) + .split('\n') + .map(str => str.trim()) + .join(' '); +}; /** - * Get the count of listeners on an event emitter of a specific type. + * Map %O to `util.inspect()`, allowing multiple lines if needed. */ -function eventListenerCount (emitter, type) { - return emitter.listeners(type).length -} +formatters.O = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); +}; /***/ }), -/***/ 69829: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 56323: +/***/ ((module) => { "use strict"; -/*! - * depd - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ - - - -/** - * Module dependencies. - * @private - */ - -var EventEmitter = (__nccwpck_require__(82361).EventEmitter) - -/** - * Module exports. - * @public - */ - -lazyProperty(module.exports, 'callSiteToString', function callSiteToString () { - var limit = Error.stackTraceLimit - var obj = {} - var prep = Error.prepareStackTrace - - function prepareObjectStackTrace (obj, stack) { - return stack - } - - Error.prepareStackTrace = prepareObjectStackTrace - Error.stackTraceLimit = 2 - // capture the stack - Error.captureStackTrace(obj) - // slice the stack - var stack = obj.stack.slice() +var isMergeableObject = function isMergeableObject(value) { + return isNonNullObject(value) + && !isSpecial(value) +}; - Error.prepareStackTrace = prep - Error.stackTraceLimit = limit +function isNonNullObject(value) { + return !!value && typeof value === 'object' +} - return stack[0].toString ? toString : __nccwpck_require__(35554) -}) +function isSpecial(value) { + var stringValue = Object.prototype.toString.call(value); -lazyProperty(module.exports, 'eventListenerCount', function eventListenerCount () { - return EventEmitter.listenerCount || __nccwpck_require__(12078) -}) + return stringValue === '[object RegExp]' + || stringValue === '[object Date]' + || isReactElement(value) +} -/** - * Define a lazy property. - */ +// see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25 +var canUseSymbol = typeof Symbol === 'function' && Symbol.for; +var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7; -function lazyProperty (obj, prop, getter) { - function get () { - var val = getter() +function isReactElement(value) { + return value.$$typeof === REACT_ELEMENT_TYPE +} - Object.defineProperty(obj, prop, { - configurable: true, - enumerable: true, - value: val - }) +function emptyTarget(val) { + return Array.isArray(val) ? [] : {} +} - return val - } +function cloneUnlessOtherwiseSpecified(value, options) { + return (options.clone !== false && options.isMergeableObject(value)) + ? deepmerge(emptyTarget(value), value, options) + : value +} - Object.defineProperty(obj, prop, { - configurable: true, - enumerable: true, - get: get - }) +function defaultArrayMerge(target, source, options) { + return target.concat(source).map(function(element) { + return cloneUnlessOtherwiseSpecified(element, options) + }) } -/** - * Call toString() on the obj - */ +function getMergeFunction(key, options) { + if (!options.customMerge) { + return deepmerge + } + var customMerge = options.customMerge(key); + return typeof customMerge === 'function' ? customMerge : deepmerge +} -function toString (obj) { - return obj.toString() +function getEnumerableOwnPropertySymbols(target) { + return Object.getOwnPropertySymbols + ? Object.getOwnPropertySymbols(target).filter(function(symbol) { + return target.propertyIsEnumerable(symbol) + }) + : [] } +function getKeys(target) { + return Object.keys(target).concat(getEnumerableOwnPropertySymbols(target)) +} -/***/ }), +function propertyIsOnObject(object, property) { + try { + return property in object + } catch(_) { + return false + } +} -/***/ 58932: -/***/ ((__unused_webpack_module, exports) => { +// Protects from prototype poisoning and unexpected merging up the prototype chain. +function propertyIsUnsafe(target, key) { + return propertyIsOnObject(target, key) // Properties are safe to merge if they don't exist in the target yet, + && !(Object.hasOwnProperty.call(target, key) // unsafe if they exist up the prototype chain, + && Object.propertyIsEnumerable.call(target, key)) // and also unsafe if they're nonenumerable. +} -"use strict"; +function mergeObject(target, source, options) { + var destination = {}; + if (options.isMergeableObject(target)) { + getKeys(target).forEach(function(key) { + destination[key] = cloneUnlessOtherwiseSpecified(target[key], options); + }); + } + getKeys(source).forEach(function(key) { + if (propertyIsUnsafe(target, key)) { + return + } + if (propertyIsOnObject(target, key) && options.isMergeableObject(source[key])) { + destination[key] = getMergeFunction(key, options)(target[key], source[key], options); + } else { + destination[key] = cloneUnlessOtherwiseSpecified(source[key], options); + } + }); + return destination +} -Object.defineProperty(exports, "__esModule", ({ value: true })); +function deepmerge(target, source, options) { + options = options || {}; + options.arrayMerge = options.arrayMerge || defaultArrayMerge; + options.isMergeableObject = options.isMergeableObject || isMergeableObject; + // cloneUnlessOtherwiseSpecified is added to `options` so that custom arrayMerge() + // implementations can use it. The caller may not replace it. + options.cloneUnlessOtherwiseSpecified = cloneUnlessOtherwiseSpecified; -class Deprecation extends Error { - constructor(message) { - super(message); // Maintains proper stack trace (only available on V8) + var sourceIsArray = Array.isArray(source); + var targetIsArray = Array.isArray(target); + var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray; - /* istanbul ignore next */ + if (!sourceAndTargetTypesMatch) { + return cloneUnlessOtherwiseSpecified(source, options) + } else if (sourceIsArray) { + return options.arrayMerge(target, source, options) + } else { + return mergeObject(target, source, options) + } +} - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } +deepmerge.all = function deepmergeAll(array, options) { + if (!Array.isArray(array)) { + throw new Error('first argument should be an array') + } - this.name = 'Deprecation'; - } + return array.reduce(function(prev, next) { + return deepmerge(prev, next, options) + }, {}) +}; -} +var deepmerge_1 = deepmerge; -exports.Deprecation = Deprecation; +module.exports = deepmerge_1; /***/ }), -/***/ 43225: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 42342: +/***/ ((module) => { "use strict"; -/*! - * destroy - * Copyright(c) 2014 Jonathan Ong - * MIT Licensed - */ - /** - * Module dependencies. - * @private + * Custom implementation of a double ended queue. */ +function Denque(array, options) { + var options = options || {}; -var ReadStream = (__nccwpck_require__(57147).ReadStream) -var Stream = __nccwpck_require__(12781) + this._head = 0; + this._tail = 0; + this._capacity = options.capacity; + this._capacityMask = 0x3; + this._list = new Array(4); + if (Array.isArray(array)) { + this._fromArray(array); + } +} /** - * Module exports. - * @public + * ------------- + * PUBLIC API + * ------------- */ -module.exports = destroy - /** - * Destroy a stream. - * - * @param {object} stream - * @public + * Returns the item at the specified index from the list. + * 0 is the first element, 1 is the second, and so on... + * Elements at negative values are that many from the end: -1 is one before the end + * (the last element), -2 is two before the end (one before last), etc. + * @param index + * @returns {*} */ - -function destroy(stream) { - if (stream instanceof ReadStream) { - return destroyReadStream(stream) - } - - if (!(stream instanceof Stream)) { - return stream - } - - if (typeof stream.destroy === 'function') { - stream.destroy() +Denque.prototype.peekAt = function peekAt(index) { + var i = index; + // expect a number or return undefined + if ((i !== (i | 0))) { + return void 0; } - - return stream -} + var len = this.size(); + if (i >= len || i < -len) return undefined; + if (i < 0) i += len; + i = (this._head + i) & this._capacityMask; + return this._list[i]; +}; /** - * Destroy a ReadStream. - * - * @param {object} stream - * @private + * Alias for peekAt() + * @param i + * @returns {*} */ +Denque.prototype.get = function get(i) { + return this.peekAt(i); +}; -function destroyReadStream(stream) { - stream.destroy() - - if (typeof stream.close === 'function') { - // node.js core bug work-around - stream.on('open', onOpenClose) - } +/** + * Returns the first item in the list without removing it. + * @returns {*} + */ +Denque.prototype.peek = function peek() { + if (this._head === this._tail) return undefined; + return this._list[this._head]; +}; - return stream -} +/** + * Alias for peek() + * @returns {*} + */ +Denque.prototype.peekFront = function peekFront() { + return this.peek(); +}; /** - * On open handler to close stream. - * @private + * Returns the item that is at the back of the queue without removing it. + * Uses peekAt(-1) */ +Denque.prototype.peekBack = function peekBack() { + return this.peekAt(-1); +}; -function onOpenClose() { - if (typeof this.fd === 'number') { - // actually close down the fd - this.close() +/** + * Returns the current length of the queue + * @return {Number} + */ +Object.defineProperty(Denque.prototype, 'length', { + get: function length() { + return this.size(); } -} +}); +/** + * Return the number of items on the list, or 0 if empty. + * @returns {number} + */ +Denque.prototype.size = function size() { + if (this._head === this._tail) return 0; + if (this._head < this._tail) return this._tail - this._head; + else return this._capacityMask + 1 - (this._head - this._tail); +}; -/***/ }), +/** + * Add an item at the beginning of the list. + * @param item + */ +Denque.prototype.unshift = function unshift(item) { + if (item === undefined) return this.size(); + var len = this._list.length; + this._head = (this._head - 1 + len) & this._capacityMask; + this._list[this._head] = item; + if (this._tail === this._head) this._growArray(); + if (this._capacity && this.size() > this._capacity) this.pop(); + if (this._head < this._tail) return this._tail - this._head; + else return this._capacityMask + 1 - (this._head - this._tail); +}; -/***/ 12437: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/** + * Remove and return the first item on the list, + * Returns undefined if the list is empty. + * @returns {*} + */ +Denque.prototype.shift = function shift() { + var head = this._head; + if (head === this._tail) return undefined; + var item = this._list[head]; + this._list[head] = undefined; + this._head = (head + 1) & this._capacityMask; + if (head < 2 && this._tail > 10000 && this._tail <= this._list.length >>> 2) this._shrinkArray(); + return item; +}; -/* @flow */ -/*:: +/** + * Add an item to the bottom of the list. + * @param item + */ +Denque.prototype.push = function push(item) { + if (item === undefined) return this.size(); + var tail = this._tail; + this._list[tail] = item; + this._tail = (tail + 1) & this._capacityMask; + if (this._tail === this._head) { + this._growArray(); + } + if (this._capacity && this.size() > this._capacity) { + this.shift(); + } + if (this._head < this._tail) return this._tail - this._head; + else return this._capacityMask + 1 - (this._head - this._tail); +}; -type DotenvParseOptions = { - debug?: boolean -} +/** + * Remove and return the last item on the list. + * Returns undefined if the list is empty. + * @returns {*} + */ +Denque.prototype.pop = function pop() { + var tail = this._tail; + if (tail === this._head) return undefined; + var len = this._list.length; + this._tail = (tail - 1 + len) & this._capacityMask; + var item = this._list[this._tail]; + this._list[this._tail] = undefined; + if (this._head < 2 && tail > 10000 && tail <= len >>> 2) this._shrinkArray(); + return item; +}; -// keys and values from src -type DotenvParseOutput = { [string]: string } +/** + * Remove and return the item at the specified index from the list. + * Returns undefined if the list is empty. + * @param index + * @returns {*} + */ +Denque.prototype.removeOne = function removeOne(index) { + var i = index; + // expect a number or return undefined + if ((i !== (i | 0))) { + return void 0; + } + if (this._head === this._tail) return void 0; + var size = this.size(); + var len = this._list.length; + if (i >= size || i < -size) return void 0; + if (i < 0) i += size; + i = (this._head + i) & this._capacityMask; + var item = this._list[i]; + var k; + if (index < size / 2) { + for (k = index; k > 0; k--) { + this._list[i] = this._list[i = (i - 1 + len) & this._capacityMask]; + } + this._list[i] = void 0; + this._head = (this._head + 1 + len) & this._capacityMask; + } else { + for (k = size - 1 - index; k > 0; k--) { + this._list[i] = this._list[i = ( i + 1 + len) & this._capacityMask]; + } + this._list[i] = void 0; + this._tail = (this._tail - 1 + len) & this._capacityMask; + } + return item; +}; -type DotenvConfigOptions = { - path?: string, // path to .env file - encoding?: string, // encoding of .env file - debug?: string // turn on logging for debugging purposes -} +/** + * Remove number of items from the specified index from the list. + * Returns array of removed items. + * Returns undefined if the list is empty. + * @param index + * @param count + * @returns {array} + */ +Denque.prototype.remove = function remove(index, count) { + var i = index; + var removed; + var del_count = count; + // expect a number or return undefined + if ((i !== (i | 0))) { + return void 0; + } + if (this._head === this._tail) return void 0; + var size = this.size(); + var len = this._list.length; + if (i >= size || i < -size || count < 1) return void 0; + if (i < 0) i += size; + if (count === 1 || !count) { + removed = new Array(1); + removed[0] = this.removeOne(i); + return removed; + } + if (i === 0 && i + count >= size) { + removed = this.toArray(); + this.clear(); + return removed; + } + if (i + count > size) count = size - i; + var k; + removed = new Array(count); + for (k = 0; k < count; k++) { + removed[k] = this._list[(this._head + i + k) & this._capacityMask]; + } + i = (this._head + i) & this._capacityMask; + if (index + count === size) { + this._tail = (this._tail - count + len) & this._capacityMask; + for (k = count; k > 0; k--) { + this._list[i = (i + 1 + len) & this._capacityMask] = void 0; + } + return removed; + } + if (index === 0) { + this._head = (this._head + count + len) & this._capacityMask; + for (k = count - 1; k > 0; k--) { + this._list[i = (i + 1 + len) & this._capacityMask] = void 0; + } + return removed; + } + if (i < size / 2) { + this._head = (this._head + index + count + len) & this._capacityMask; + for (k = index; k > 0; k--) { + this.unshift(this._list[i = (i - 1 + len) & this._capacityMask]); + } + i = (this._head - 1 + len) & this._capacityMask; + while (del_count > 0) { + this._list[i = (i - 1 + len) & this._capacityMask] = void 0; + del_count--; + } + if (index < 0) this._tail = i; + } else { + this._tail = i; + i = (i + count + len) & this._capacityMask; + for (k = size - (count + index); k > 0; k--) { + this.push(this._list[i++]); + } + i = this._tail; + while (del_count > 0) { + this._list[i = (i + 1 + len) & this._capacityMask] = void 0; + del_count--; + } + } + if (this._head < 2 && this._tail > 10000 && this._tail <= len >>> 2) this._shrinkArray(); + return removed; +}; -type DotenvConfigOutput = { - parsed?: DotenvParseOutput, - error?: Error -} +/** + * Native splice implementation. + * Remove number of items from the specified index from the list and/or add new elements. + * Returns array of removed items or empty array if count == 0. + * Returns undefined if the list is empty. + * + * @param index + * @param count + * @param {...*} [elements] + * @returns {array} + */ +Denque.prototype.splice = function splice(index, count) { + var i = index; + // expect a number or return undefined + if ((i !== (i | 0))) { + return void 0; + } + var size = this.size(); + if (i < 0) i += size; + if (i > size) return void 0; + if (arguments.length > 2) { + var k; + var temp; + var removed; + var arg_len = arguments.length; + var len = this._list.length; + var arguments_index = 2; + if (!size || i < size / 2) { + temp = new Array(i); + for (k = 0; k < i; k++) { + temp[k] = this._list[(this._head + k) & this._capacityMask]; + } + if (count === 0) { + removed = []; + if (i > 0) { + this._head = (this._head + i + len) & this._capacityMask; + } + } else { + removed = this.remove(i, count); + this._head = (this._head + i + len) & this._capacityMask; + } + while (arg_len > arguments_index) { + this.unshift(arguments[--arg_len]); + } + for (k = i; k > 0; k--) { + this.unshift(temp[k - 1]); + } + } else { + temp = new Array(size - (i + count)); + var leng = temp.length; + for (k = 0; k < leng; k++) { + temp[k] = this._list[(this._head + i + count + k) & this._capacityMask]; + } + if (count === 0) { + removed = []; + if (i != size) { + this._tail = (this._head + i + len) & this._capacityMask; + } + } else { + removed = this.remove(i, count); + this._tail = (this._tail - leng + len) & this._capacityMask; + } + while (arguments_index < arg_len) { + this.push(arguments[arguments_index++]); + } + for (k = 0; k < leng; k++) { + this.push(temp[k]); + } + } + return removed; + } else { + return this.remove(i, count); + } +}; -*/ +/** + * Soft clear - does not reset capacity. + */ +Denque.prototype.clear = function clear() { + this._head = 0; + this._tail = 0; +}; -const fs = __nccwpck_require__(57147) -const path = __nccwpck_require__(71017) +/** + * Returns true or false whether the list is empty. + * @returns {boolean} + */ +Denque.prototype.isEmpty = function isEmpty() { + return this._head === this._tail; +}; -function log (message /*: string */) { - console.log(`[dotenv][DEBUG] ${message}`) -} +/** + * Returns an array of all queue items. + * @returns {Array} + */ +Denque.prototype.toArray = function toArray() { + return this._copyArray(false); +}; -const NEWLINE = '\n' -const RE_INI_KEY_VAL = /^\s*([\w.-]+)\s*=\s*(.*)?\s*$/ -const RE_NEWLINES = /\\n/g -const NEWLINES_MATCH = /\n|\r|\r\n/ +/** + * ------------- + * INTERNALS + * ------------- + */ -// Parses src into an Object -function parse (src /*: string | Buffer */, options /*: ?DotenvParseOptions */) /*: DotenvParseOutput */ { - const debug = Boolean(options && options.debug) - const obj = {} +/** + * Fills the queue with items from an array + * For use in the constructor + * @param array + * @private + */ +Denque.prototype._fromArray = function _fromArray(array) { + for (var i = 0; i < array.length; i++) this.push(array[i]); +}; - // convert Buffers before splitting into lines and processing - src.toString().split(NEWLINES_MATCH).forEach(function (line, idx) { - // matching "KEY' and 'VAL' in 'KEY=VAL' - const keyValueArr = line.match(RE_INI_KEY_VAL) - // matched? - if (keyValueArr != null) { - const key = keyValueArr[1] - // default undefined or missing values to empty string - let val = (keyValueArr[2] || '') - const end = val.length - 1 - const isDoubleQuoted = val[0] === '"' && val[end] === '"' - const isSingleQuoted = val[0] === "'" && val[end] === "'" +/** + * + * @param fullCopy + * @returns {Array} + * @private + */ +Denque.prototype._copyArray = function _copyArray(fullCopy) { + var newArray = []; + var list = this._list; + var len = list.length; + var i; + if (fullCopy || this._head > this._tail) { + for (i = this._head; i < len; i++) newArray.push(list[i]); + for (i = 0; i < this._tail; i++) newArray.push(list[i]); + } else { + for (i = this._head; i < this._tail; i++) newArray.push(list[i]); + } + return newArray; +}; - // if single or double quoted, remove quotes - if (isSingleQuoted || isDoubleQuoted) { - val = val.substring(1, end) +/** + * Grows the internal list array. + * @private + */ +Denque.prototype._growArray = function _growArray() { + if (this._head) { + // copy existing data, head to end, then beginning to tail. + this._list = this._copyArray(true); + this._head = 0; + } - // if double quoted, expand newlines - if (isDoubleQuoted) { - val = val.replace(RE_NEWLINES, NEWLINE) - } - } else { - // remove surrounding whitespace - val = val.trim() - } + // head is at 0 and array is now full, safe to extend + this._tail = this._list.length; - obj[key] = val - } else if (debug) { - log(`did not match key and value when parsing line ${idx + 1}: ${line}`) - } - }) + this._list.length <<= 1; + this._capacityMask = (this._capacityMask << 1) | 1; +}; - return obj -} +/** + * Shrinks the internal list array. + * @private + */ +Denque.prototype._shrinkArray = function _shrinkArray() { + this._list.length >>>= 1; + this._capacityMask >>>= 1; +}; -// Populates process.env from .env file -function config (options /*: ?DotenvConfigOptions */) /*: DotenvConfigOutput */ { - let dotenvPath = path.resolve(process.cwd(), '.env') - let encoding /*: string */ = 'utf8' - let debug = false - if (options) { - if (options.path != null) { - dotenvPath = options.path - } - if (options.encoding != null) { - encoding = options.encoding - } - if (options.debug != null) { - debug = true - } - } +module.exports = Denque; - try { - // specifying an encoding returns a string instead of a buffer - const parsed = parse(fs.readFileSync(dotenvPath, { encoding }), { debug }) - Object.keys(parsed).forEach(function (key) { - if (!Object.prototype.hasOwnProperty.call(process.env, key)) { - process.env[key] = parsed[key] - } else if (debug) { - log(`"${key}" is already defined in \`process.env\` and will not be overwritten`) - } - }) +/***/ }), - return { parsed } - } catch (e) { - return { error: e } - } -} +/***/ 18883: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -module.exports.config = config -module.exports.parse = parse +/*! + * depd + * Copyright(c) 2014-2017 Douglas Christopher Wilson + * MIT Licensed + */ +/** + * Module dependencies. + */ -/***/ }), +var callSiteToString = (__nccwpck_require__(69829).callSiteToString) +var eventListenerCount = (__nccwpck_require__(69829).eventListenerCount) +var relative = (__nccwpck_require__(71017).relative) -/***/ 11728: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/** + * Module exports. + */ -"use strict"; +module.exports = depd +/** + * Get the path to base files on. + */ -var Buffer = (__nccwpck_require__(21867).Buffer); +var basePath = process.cwd() -var getParamBytesForAlg = __nccwpck_require__(30528); +/** + * Determine if namespace is contained in the string. + */ -var MAX_OCTET = 0x80, - CLASS_UNIVERSAL = 0, - PRIMITIVE_BIT = 0x20, - TAG_SEQ = 0x10, - TAG_INT = 0x02, - ENCODED_TAG_SEQ = (TAG_SEQ | PRIMITIVE_BIT) | (CLASS_UNIVERSAL << 6), - ENCODED_TAG_INT = TAG_INT | (CLASS_UNIVERSAL << 6); +function containsNamespace (str, namespace) { + var vals = str.split(/[ ,]+/) + var ns = String(namespace).toLowerCase() -function base64Url(base64) { - return base64 - .replace(/=/g, '') - .replace(/\+/g, '-') - .replace(/\//g, '_'); -} + for (var i = 0; i < vals.length; i++) { + var val = vals[i] -function signatureAsBuffer(signature) { - if (Buffer.isBuffer(signature)) { - return signature; - } else if ('string' === typeof signature) { - return Buffer.from(signature, 'base64'); - } + // namespace contained + if (val && (val === '*' || val.toLowerCase() === ns)) { + return true + } + } - throw new TypeError('ECDSA signature must be a Base64 string or a Buffer'); + return false } -function derToJose(signature, alg) { - signature = signatureAsBuffer(signature); - var paramBytes = getParamBytesForAlg(alg); +/** + * Convert a data descriptor to accessor descriptor. + */ - // the DER encoded param should at most be the param size, plus a padding - // zero, since due to being a signed integer - var maxEncodedParamLength = paramBytes + 1; - - var inputLength = signature.length; +function convertDataDescriptorToAccessor (obj, prop, message) { + var descriptor = Object.getOwnPropertyDescriptor(obj, prop) + var value = descriptor.value - var offset = 0; - if (signature[offset++] !== ENCODED_TAG_SEQ) { - throw new Error('Could not find expected "seq"'); - } + descriptor.get = function getter () { return value } - var seqLength = signature[offset++]; - if (seqLength === (MAX_OCTET | 1)) { - seqLength = signature[offset++]; - } + if (descriptor.writable) { + descriptor.set = function setter (val) { return (value = val) } + } - if (inputLength - offset < seqLength) { - throw new Error('"seq" specified length of "' + seqLength + '", only "' + (inputLength - offset) + '" remaining'); - } + delete descriptor.value + delete descriptor.writable - if (signature[offset++] !== ENCODED_TAG_INT) { - throw new Error('Could not find expected "int" for "r"'); - } + Object.defineProperty(obj, prop, descriptor) - var rLength = signature[offset++]; + return descriptor +} - if (inputLength - offset - 2 < rLength) { - throw new Error('"r" specified length of "' + rLength + '", only "' + (inputLength - offset - 2) + '" available'); - } +/** + * Create arguments string to keep arity. + */ - if (maxEncodedParamLength < rLength) { - throw new Error('"r" specified length of "' + rLength + '", max of "' + maxEncodedParamLength + '" is acceptable'); - } +function createArgumentsString (arity) { + var str = '' - var rOffset = offset; - offset += rLength; + for (var i = 0; i < arity; i++) { + str += ', arg' + i + } - if (signature[offset++] !== ENCODED_TAG_INT) { - throw new Error('Could not find expected "int" for "s"'); - } + return str.substr(2) +} - var sLength = signature[offset++]; +/** + * Create stack string from stack. + */ - if (inputLength - offset !== sLength) { - throw new Error('"s" specified length of "' + sLength + '", expected "' + (inputLength - offset) + '"'); - } +function createStackString (stack) { + var str = this.name + ': ' + this.namespace - if (maxEncodedParamLength < sLength) { - throw new Error('"s" specified length of "' + sLength + '", max of "' + maxEncodedParamLength + '" is acceptable'); - } + if (this.message) { + str += ' deprecated ' + this.message + } - var sOffset = offset; - offset += sLength; + for (var i = 0; i < stack.length; i++) { + str += '\n at ' + callSiteToString(stack[i]) + } - if (offset !== inputLength) { - throw new Error('Expected to consume entire buffer, but "' + (inputLength - offset) + '" bytes remain'); - } + return str +} - var rPadding = paramBytes - rLength, - sPadding = paramBytes - sLength; +/** + * Create deprecate for namespace in caller. + */ - var dst = Buffer.allocUnsafe(rPadding + rLength + sPadding + sLength); +function depd (namespace) { + if (!namespace) { + throw new TypeError('argument namespace is required') + } - for (offset = 0; offset < rPadding; ++offset) { - dst[offset] = 0; - } - signature.copy(dst, offset, rOffset + Math.max(-rPadding, 0), rOffset + rLength); + var stack = getStack() + var site = callSiteLocation(stack[1]) + var file = site[0] - offset = paramBytes; + function deprecate (message) { + // call to self as log + log.call(deprecate, message) + } - for (var o = offset; offset < o + sPadding; ++offset) { - dst[offset] = 0; - } - signature.copy(dst, offset, sOffset + Math.max(-sPadding, 0), sOffset + sLength); + deprecate._file = file + deprecate._ignored = isignored(namespace) + deprecate._namespace = namespace + deprecate._traced = istraced(namespace) + deprecate._warned = Object.create(null) - dst = dst.toString('base64'); - dst = base64Url(dst); + deprecate.function = wrapfunction + deprecate.property = wrapproperty - return dst; + return deprecate } -function countPadding(buf, start, stop) { - var padding = 0; - while (start + padding < stop && buf[start + padding] === 0) { - ++padding; - } +/** + * Determine if namespace is ignored. + */ - var needsSign = buf[start + padding] >= MAX_OCTET; - if (needsSign) { - --padding; - } +function isignored (namespace) { + /* istanbul ignore next: tested in a child processs */ + if (process.noDeprecation) { + // --no-deprecation support + return true + } - return padding; -} + var str = process.env.NO_DEPRECATION || '' -function joseToDer(signature, alg) { - signature = signatureAsBuffer(signature); - var paramBytes = getParamBytesForAlg(alg); + // namespace ignored + return containsNamespace(str, namespace) +} - var signatureBytes = signature.length; - if (signatureBytes !== paramBytes * 2) { - throw new TypeError('"' + alg + '" signatures must be "' + paramBytes * 2 + '" bytes, saw "' + signatureBytes + '"'); - } +/** + * Determine if namespace is traced. + */ - var rPadding = countPadding(signature, 0, paramBytes); - var sPadding = countPadding(signature, paramBytes, signature.length); - var rLength = paramBytes - rPadding; - var sLength = paramBytes - sPadding; +function istraced (namespace) { + /* istanbul ignore next: tested in a child processs */ + if (process.traceDeprecation) { + // --trace-deprecation support + return true + } - var rsBytes = 1 + 1 + rLength + 1 + 1 + sLength; + var str = process.env.TRACE_DEPRECATION || '' - var shortLength = rsBytes < MAX_OCTET; + // namespace traced + return containsNamespace(str, namespace) +} - var dst = Buffer.allocUnsafe((shortLength ? 2 : 3) + rsBytes); +/** + * Display deprecation message. + */ - var offset = 0; - dst[offset++] = ENCODED_TAG_SEQ; - if (shortLength) { - // Bit 8 has value "0" - // bits 7-1 give the length. - dst[offset++] = rsBytes; - } else { - // Bit 8 of first octet has value "1" - // bits 7-1 give the number of additional length octets. - dst[offset++] = MAX_OCTET | 1; - // length, base 256 - dst[offset++] = rsBytes & 0xff; - } - dst[offset++] = ENCODED_TAG_INT; - dst[offset++] = rLength; - if (rPadding < 0) { - dst[offset++] = 0; - offset += signature.copy(dst, offset, 0, paramBytes); - } else { - offset += signature.copy(dst, offset, rPadding, paramBytes); - } - dst[offset++] = ENCODED_TAG_INT; - dst[offset++] = sLength; - if (sPadding < 0) { - dst[offset++] = 0; - signature.copy(dst, offset, paramBytes); - } else { - signature.copy(dst, offset, paramBytes + sPadding); - } +function log (message, site) { + var haslisteners = eventListenerCount(process, 'deprecation') !== 0 - return dst; -} + // abort early if no destination + if (!haslisteners && this._ignored) { + return + } -module.exports = { - derToJose: derToJose, - joseToDer: joseToDer -}; + var caller + var callFile + var callSite + var depSite + var i = 0 + var seen = false + var stack = getStack() + var file = this._file + if (site) { + // provided site + depSite = site + callSite = callSiteLocation(stack[1]) + callSite.name = depSite.name + file = callSite[0] + } else { + // get call site + i = 2 + depSite = callSiteLocation(stack[i]) + callSite = depSite + } -/***/ }), + // get caller of deprecated thing in relation to file + for (; i < stack.length; i++) { + caller = callSiteLocation(stack[i]) + callFile = caller[0] -/***/ 30528: -/***/ ((module) => { + if (callFile === file) { + seen = true + } else if (callFile === this._file) { + file = this._file + } else if (seen) { + break + } + } -"use strict"; + var key = caller + ? depSite.join(':') + '__' + caller.join(':') + : undefined + if (key !== undefined && key in this._warned) { + // already warned + return + } -function getParamSize(keySize) { - var result = ((keySize / 8) | 0) + (keySize % 8 === 0 ? 0 : 1); - return result; -} + this._warned[key] = true -var paramBytesForAlg = { - ES256: getParamSize(256), - ES384: getParamSize(384), - ES512: getParamSize(521) -}; + // generate automatic message from call site + var msg = message + if (!msg) { + msg = callSite === depSite || !callSite.name + ? defaultMessage(depSite) + : defaultMessage(callSite) + } -function getParamBytesForAlg(alg) { - var paramBytes = paramBytesForAlg[alg]; - if (paramBytes) { - return paramBytes; - } + // emit deprecation if listeners exist + if (haslisteners) { + var err = DeprecationError(this._namespace, msg, stack.slice(i)) + process.emit('deprecation', err) + return + } - throw new Error('Unknown algorithm "' + alg + '"'); + // format and write message + var format = process.stderr.isTTY + ? formatColor + : formatPlain + var output = format.call(this, msg, caller, stack.slice(i)) + process.stderr.write(output + '\n', 'utf8') } -module.exports = getParamBytesForAlg; - +/** + * Get call site location as array. + */ -/***/ }), +function callSiteLocation (callSite) { + var file = callSite.getFileName() || '' + var line = callSite.getLineNumber() + var colm = callSite.getColumnNumber() -/***/ 14401: -/***/ ((module) => { + if (callSite.isEval()) { + file = callSite.getEvalOrigin() + ', ' + file + } -"use strict"; -/*! - * ee-first - * Copyright(c) 2014 Jonathan Ong - * MIT Licensed - */ + var site = [file, line, colm] + site.callSite = callSite + site.name = callSite.getFunctionName() + return site +} /** - * Module exports. - * @public + * Generate a default message from the site. */ -module.exports = first - -/** - * Get the first event in a set of event emitters and event pairs. - * - * @param {array} stuff - * @param {function} done - * @public - */ +function defaultMessage (site) { + var callSite = site.callSite + var funcName = site.name -function first(stuff, done) { - if (!Array.isArray(stuff)) - throw new TypeError('arg must be an array of [ee, events...] arrays') + // make useful anonymous name + if (!funcName) { + funcName = '' + } - var cleanups = [] + var context = callSite.getThis() + var typeName = context && callSite.getTypeName() - for (var i = 0; i < stuff.length; i++) { - var arr = stuff[i] + // ignore useless type name + if (typeName === 'Object') { + typeName = undefined + } - if (!Array.isArray(arr) || arr.length < 2) - throw new TypeError('each array member must be [ee, events...]') + // make useful type name + if (typeName === 'Function') { + typeName = context.name || typeName + } - var ee = arr[0] + return typeName && callSite.getMethodName() + ? typeName + '.' + funcName + : funcName +} - for (var j = 1; j < arr.length; j++) { - var event = arr[j] - var fn = listener(event, callback) +/** + * Format deprecation message without color. + */ - // listen to the event - ee.on(event, fn) - // push this listener to the list of cleanups - cleanups.push({ - ee: ee, - event: event, - fn: fn, - }) - } - } +function formatPlain (msg, caller, stack) { + var timestamp = new Date().toUTCString() - function callback() { - cleanup() - done.apply(null, arguments) - } + var formatted = timestamp + + ' ' + this._namespace + + ' deprecated ' + msg - function cleanup() { - var x - for (var i = 0; i < cleanups.length; i++) { - x = cleanups[i] - x.ee.removeListener(x.event, x.fn) + // add stack trace + if (this._traced) { + for (var i = 0; i < stack.length; i++) { + formatted += '\n at ' + callSiteToString(stack[i]) } - } - function thunk(fn) { - done = fn + return formatted } - thunk.cancel = cleanup + if (caller) { + formatted += ' at ' + formatLocation(caller) + } - return thunk + return formatted } /** - * Create the event listener. - * @private + * Format deprecation message with color. */ -function listener(event, done) { - return function onevent(arg1) { - var args = new Array(arguments.length) - var ee = this - var err = event === 'error' - ? arg1 - : null +function formatColor (msg, caller, stack) { + var formatted = '\x1b[36;1m' + this._namespace + '\x1b[22;39m' + // bold cyan + ' \x1b[33;1mdeprecated\x1b[22;39m' + // bold yellow + ' \x1b[0m' + msg + '\x1b[39m' // reset - // copy args to prevent arguments escaping scope - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i] + // add stack trace + if (this._traced) { + for (var i = 0; i < stack.length; i++) { + formatted += '\n \x1b[36mat ' + callSiteToString(stack[i]) + '\x1b[39m' // cyan } - done(err, ee, event, args) + return formatted } -} + if (caller) { + formatted += ' \x1b[36m' + formatLocation(caller) + '\x1b[39m' // cyan + } -/***/ }), - -/***/ 18212: -/***/ ((module) => { + return formatted +} -"use strict"; +/** + * Format call site location. + */ +function formatLocation (callSite) { + return relative(basePath, callSite[0]) + + ':' + callSite[1] + + ':' + callSite[2] +} -module.exports = function () { - // https://mths.be/emoji - return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|\uD83D\uDC68(?:\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68\uD83C\uDFFB|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C[\uDFFB-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)\uD83C\uDFFB|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB\uDFFC])|\uD83D\uDC69(?:\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB-\uDFFD])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83C\uDFF4\u200D\u2620)\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF4\uD83C\uDDF2|\uD83C\uDDF6\uD83C\uDDE6|[#\*0-9]\uFE0F\u20E3|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDBB\uDDD2-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g; -}; +/** + * Get the stack as array of call sites. + */ +function getStack () { + var limit = Error.stackTraceLimit + var obj = {} + var prep = Error.prepareStackTrace -/***/ }), + Error.prepareStackTrace = prepareObjectStackTrace + Error.stackTraceLimit = Math.max(10, limit) -/***/ 16592: -/***/ ((module) => { + // capture the stack + Error.captureStackTrace(obj) -"use strict"; -/*! - * encodeurl - * Copyright(c) 2016 Douglas Christopher Wilson - * MIT Licensed - */ + // slice this function off the top + var stack = obj.stack.slice(1) + Error.prepareStackTrace = prep + Error.stackTraceLimit = limit + return stack +} /** - * Module exports. - * @public + * Capture call site stack from v8. */ -module.exports = encodeUrl +function prepareObjectStackTrace (obj, stack) { + return stack +} /** - * RegExp to match non-URL code points, *after* encoding (i.e. not including "%") - * and including invalid escape sequences. - * @private + * Return a wrapped function in a deprecation message. */ -var ENCODE_CHARS_REGEXP = /(?:[^\x21\x25\x26-\x3B\x3D\x3F-\x5B\x5D\x5F\x61-\x7A\x7E]|%(?:[^0-9A-Fa-f]|[0-9A-Fa-f][^0-9A-Fa-f]|$))+/g +function wrapfunction (fn, message) { + if (typeof fn !== 'function') { + throw new TypeError('argument fn must be a function') + } -/** - * RegExp to match unmatched surrogate pair. - * @private - */ + var args = createArgumentsString(fn.length) + var deprecate = this // eslint-disable-line no-unused-vars + var stack = getStack() + var site = callSiteLocation(stack[1]) -var UNMATCHED_SURROGATE_PAIR_REGEXP = /(^|[^\uD800-\uDBFF])[\uDC00-\uDFFF]|[\uD800-\uDBFF]([^\uDC00-\uDFFF]|$)/g + site.name = fn.name -/** - * String to replace unmatched surrogate pair with. - * @private - */ + // eslint-disable-next-line no-eval + var deprecatedfn = eval('(function (' + args + ') {\n' + + '"use strict"\n' + + 'log.call(deprecate, message, site)\n' + + 'return fn.apply(this, arguments)\n' + + '})') -var UNMATCHED_SURROGATE_PAIR_REPLACE = '$1\uFFFD$2' + return deprecatedfn +} /** - * Encode a URL to a percent-encoded form, excluding already-encoded sequences. - * - * This function will take an already-encoded URL and encode all the non-URL - * code points. This function will not encode the "%" character unless it is - * not part of a valid sequence (`%20` will be left as-is, but `%foo` will - * be encoded as `%25foo`). - * - * This encode is meant to be "safe" and does not throw errors. It will try as - * hard as it can to properly encode the given URL, including replacing any raw, - * unpaired surrogate pairs with the Unicode replacement character prior to - * encoding. - * - * @param {string} url - * @return {string} - * @public + * Wrap property in a deprecation message. */ -function encodeUrl (url) { - return String(url) - .replace(UNMATCHED_SURROGATE_PAIR_REGEXP, UNMATCHED_SURROGATE_PAIR_REPLACE) - .replace(ENCODE_CHARS_REGEXP, encodeURI) -} +function wrapproperty (obj, prop, message) { + if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { + throw new TypeError('argument obj must be object') + } + var descriptor = Object.getOwnPropertyDescriptor(obj, prop) -/***/ }), + if (!descriptor) { + throw new TypeError('must call property on owner object') + } -/***/ 23505: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (!descriptor.configurable) { + throw new TypeError('property must be configurable') + } -"use strict"; + var deprecate = this + var stack = getStack() + var site = callSiteLocation(stack[1]) + // set site name + site.name = prop -var util = __nccwpck_require__(73837); -var isArrayish = __nccwpck_require__(7604); + // convert data descriptor + if ('value' in descriptor) { + descriptor = convertDataDescriptorToAccessor(obj, prop, message) + } -var errorEx = function errorEx(name, properties) { - if (!name || name.constructor !== String) { - properties = name || {}; - name = Error.name; - } + var get = descriptor.get + var set = descriptor.set - var errorExError = function ErrorEXError(message) { - if (!this) { - return new ErrorEXError(message); - } + // wrap getter + if (typeof get === 'function') { + descriptor.get = function getter () { + log.call(deprecate, message, site) + return get.apply(this, arguments) + } + } - message = message instanceof Error - ? message.message - : (message || this.message); + // wrap setter + if (typeof set === 'function') { + descriptor.set = function setter () { + log.call(deprecate, message, site) + return set.apply(this, arguments) + } + } - Error.call(this, message); - Error.captureStackTrace(this, errorExError); + Object.defineProperty(obj, prop, descriptor) +} - this.name = name; +/** + * Create DeprecationError for deprecation + */ - Object.defineProperty(this, 'message', { - configurable: true, - enumerable: false, - get: function () { - var newMessage = message.split(/\r?\n/g); +function DeprecationError (namespace, message, stack) { + var error = new Error() + var stackString - for (var key in properties) { - if (!properties.hasOwnProperty(key)) { - continue; - } + Object.defineProperty(error, 'constructor', { + value: DeprecationError + }) - var modifier = properties[key]; + Object.defineProperty(error, 'message', { + configurable: true, + enumerable: false, + value: message, + writable: true + }) - if ('message' in modifier) { - newMessage = modifier.message(this[key], newMessage) || newMessage; - if (!isArrayish(newMessage)) { - newMessage = [newMessage]; - } - } - } + Object.defineProperty(error, 'name', { + enumerable: false, + configurable: true, + value: 'DeprecationError', + writable: true + }) - return newMessage.join('\n'); - }, - set: function (v) { - message = v; - } - }); + Object.defineProperty(error, 'namespace', { + configurable: true, + enumerable: false, + value: namespace, + writable: true + }) - var overwrittenStack = null; + Object.defineProperty(error, 'stack', { + configurable: true, + enumerable: false, + get: function () { + if (stackString !== undefined) { + return stackString + } - var stackDescriptor = Object.getOwnPropertyDescriptor(this, 'stack'); - var stackGetter = stackDescriptor.get; - var stackValue = stackDescriptor.value; - delete stackDescriptor.value; - delete stackDescriptor.writable; + // prepare stack trace + return (stackString = createStackString.call(this, stack)) + }, + set: function setter (val) { + stackString = val + } + }) - stackDescriptor.set = function (newstack) { - overwrittenStack = newstack; - }; + return error +} - stackDescriptor.get = function () { - var stack = (overwrittenStack || ((stackGetter) - ? stackGetter.call(this) - : stackValue)).split(/\r?\n+/g); - // starting in Node 7, the stack builder caches the message. - // just replace it. - if (!overwrittenStack) { - stack[0] = this.name + ': ' + this.message; - } +/***/ }), - var lineCount = 1; - for (var key in properties) { - if (!properties.hasOwnProperty(key)) { - continue; - } +/***/ 35554: +/***/ ((module) => { - var modifier = properties[key]; +"use strict"; +/*! + * depd + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ - if ('line' in modifier) { - var line = modifier.line(this[key]); - if (line) { - stack.splice(lineCount++, 0, ' ' + line); - } - } - if ('stack' in modifier) { - modifier.stack(this[key], stack); - } - } - return stack.join('\n'); - }; +/** + * Module exports. + */ - Object.defineProperty(this, 'stack', stackDescriptor); - }; +module.exports = callSiteToString - if (Object.setPrototypeOf) { - Object.setPrototypeOf(errorExError.prototype, Error.prototype); - Object.setPrototypeOf(errorExError, Error); - } else { - util.inherits(errorExError, Error); - } +/** + * Format a CallSite file location to a string. + */ - return errorExError; -}; +function callSiteFileLocation (callSite) { + var fileName + var fileLocation = '' -errorEx.append = function (str, def) { - return { - message: function (v, message) { - v = v || def; + if (callSite.isNative()) { + fileLocation = 'native' + } else if (callSite.isEval()) { + fileName = callSite.getScriptNameOrSourceURL() + if (!fileName) { + fileLocation = callSite.getEvalOrigin() + } + } else { + fileName = callSite.getFileName() + } - if (v) { - message[0] += ' ' + str.replace('%s', v.toString()); - } + if (fileName) { + fileLocation += fileName - return message; - } - }; -}; + var lineNumber = callSite.getLineNumber() + if (lineNumber != null) { + fileLocation += ':' + lineNumber -errorEx.line = function (str, def) { - return { - line: function (v) { - v = v || def; + var columnNumber = callSite.getColumnNumber() + if (columnNumber) { + fileLocation += ':' + columnNumber + } + } + } - if (v) { - return str.replace('%s', v.toString()); - } + return fileLocation || 'unknown source' +} - return null; - } - }; -}; +/** + * Format a CallSite to a string. + */ -module.exports = errorEx; +function callSiteToString (callSite) { + var addSuffix = true + var fileLocation = callSiteFileLocation(callSite) + var functionName = callSite.getFunctionName() + var isConstructor = callSite.isConstructor() + var isMethodCall = !(callSite.isToplevel() || isConstructor) + var line = '' + + if (isMethodCall) { + var methodName = callSite.getMethodName() + var typeName = getConstructorName(callSite) + + if (functionName) { + if (typeName && functionName.indexOf(typeName) !== 0) { + line += typeName + '.' + } + + line += functionName + + if (methodName && functionName.lastIndexOf('.' + methodName) !== functionName.length - methodName.length - 1) { + line += ' [as ' + methodName + ']' + } + } else { + line += typeName + '.' + (methodName || '') + } + } else if (isConstructor) { + line += 'new ' + (functionName || '') + } else if (functionName) { + line += functionName + } else { + addSuffix = false + line += fileLocation + } + + if (addSuffix) { + line += ' (' + fileLocation + ')' + } + + return line +} + +/** + * Get constructor name of reviver. + */ + +function getConstructorName (obj) { + var receiver = obj.receiver + return (receiver.constructor && receiver.constructor.name) || null +} /***/ }), -/***/ 94070: +/***/ 12078: /***/ ((module) => { "use strict"; /*! - * escape-html - * Copyright(c) 2012-2013 TJ Holowaychuk - * Copyright(c) 2015 Andreas Lubbe - * Copyright(c) 2015 Tiancheng "Timothy" Gu + * depd + * Copyright(c) 2015 Douglas Christopher Wilson * MIT Licensed */ /** - * Module variables. - * @private + * Module exports. + * @public */ -var matchHtmlRegExp = /["'&<>]/; +module.exports = eventListenerCount /** - * Module exports. - * @public + * Get the count of listeners on an event emitter of a specific type. */ -module.exports = escapeHtml; +function eventListenerCount (emitter, type) { + return emitter.listeners(type).length +} + + +/***/ }), + +/***/ 69829: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; +/*! + * depd + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + + /** - * Escape special characters in the given string of html. - * - * @param {string} string The string to escape for inserting into HTML - * @return {string} + * Module dependencies. + * @private + */ + +var EventEmitter = (__nccwpck_require__(82361).EventEmitter) + +/** + * Module exports. * @public */ -function escapeHtml(string) { - var str = '' + string; - var match = matchHtmlRegExp.exec(str); +lazyProperty(module.exports, 'callSiteToString', function callSiteToString () { + var limit = Error.stackTraceLimit + var obj = {} + var prep = Error.prepareStackTrace - if (!match) { - return str; + function prepareObjectStackTrace (obj, stack) { + return stack } - var escape; - var html = ''; - var index = 0; - var lastIndex = 0; + Error.prepareStackTrace = prepareObjectStackTrace + Error.stackTraceLimit = 2 - for (index = match.index; index < str.length; index++) { - switch (str.charCodeAt(index)) { - case 34: // " - escape = '"'; - break; - case 38: // & - escape = '&'; - break; - case 39: // ' - escape = '''; - break; - case 60: // < - escape = '<'; - break; - case 62: // > - escape = '>'; - break; - default: - continue; - } + // capture the stack + Error.captureStackTrace(obj) - if (lastIndex !== index) { - html += str.substring(lastIndex, index); - } + // slice the stack + var stack = obj.stack.slice() - lastIndex = index + 1; - html += escape; + Error.prepareStackTrace = prep + Error.stackTraceLimit = limit + + return stack[0].toString ? toString : __nccwpck_require__(35554) +}) + +lazyProperty(module.exports, 'eventListenerCount', function eventListenerCount () { + return EventEmitter.listenerCount || __nccwpck_require__(12078) +}) + +/** + * Define a lazy property. + */ + +function lazyProperty (obj, prop, getter) { + function get () { + var val = getter() + + Object.defineProperty(obj, prop, { + configurable: true, + enumerable: true, + value: val + }) + + return val } - return lastIndex !== index - ? html + str.substring(lastIndex, index) - : html; + Object.defineProperty(obj, prop, { + configurable: true, + enumerable: true, + get: get + }) +} + +/** + * Call toString() on the obj + */ + +function toString (obj) { + return obj.toString() } /***/ }), -/***/ 98691: -/***/ ((module) => { +/***/ 58932: +/***/ ((__unused_webpack_module, exports) => { "use strict"; -module.exports = string => { - if (typeof string !== 'string') { - throw new TypeError('Expected a string'); - } +Object.defineProperty(exports, "__esModule", ({ value: true })); - // Escape characters with special meaning either inside or outside character sets. - // Use a simple backslash escape when it’s always valid, and a \unnnn escape when the simpler form would be disallowed by Unicode patterns’ stricter grammar. - return string - .replace(/[|\\{}()[\]^$+*?.]/g, '\\$&') - .replace(/-/g, '\\x2d'); -}; +class Deprecation extends Error { + constructor(message) { + super(message); // Maintains proper stack trace (only available on V8) + + /* istanbul ignore next */ + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + + this.name = 'Deprecation'; + } + +} + +exports.Deprecation = Deprecation; /***/ }), -/***/ 69972: +/***/ 43225: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /*! - * etag - * Copyright(c) 2014-2016 Douglas Christopher Wilson + * destroy + * Copyright(c) 2014 Jonathan Ong * MIT Licensed */ -/** - * Module exports. - * @public - */ - -module.exports = etag - /** * Module dependencies. * @private */ -var crypto = __nccwpck_require__(6113) -var Stats = (__nccwpck_require__(57147).Stats) +var ReadStream = (__nccwpck_require__(57147).ReadStream) +var Stream = __nccwpck_require__(12781) /** - * Module variables. - * @private + * Module exports. + * @public */ -var toString = Object.prototype.toString +module.exports = destroy /** - * Generate an entity tag. + * Destroy a stream. * - * @param {Buffer|string} entity - * @return {string} - * @private + * @param {object} stream + * @public */ -function entitytag (entity) { - if (entity.length === 0) { - // fast-path empty - return '"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk"' +function destroy(stream) { + if (stream instanceof ReadStream) { + return destroyReadStream(stream) } - // compute hash of entity - var hash = crypto - .createHash('sha1') - .update(entity, 'utf8') - .digest('base64') - .substring(0, 27) + if (!(stream instanceof Stream)) { + return stream + } - // compute length of entity - var len = typeof entity === 'string' - ? Buffer.byteLength(entity, 'utf8') - : entity.length + if (typeof stream.destroy === 'function') { + stream.destroy() + } - return '"' + len.toString(16) + '-' + hash + '"' + return stream } /** - * Create a simple ETag. + * Destroy a ReadStream. * - * @param {string|Buffer|Stats} entity - * @param {object} [options] - * @param {boolean} [options.weak] - * @return {String} - * @public + * @param {object} stream + * @private */ -function etag (entity, options) { - if (entity == null) { - throw new TypeError('argument entity is required') - } - - // support fs.Stats object - var isStats = isstats(entity) - var weak = options && typeof options.weak === 'boolean' - ? options.weak - : isStats +function destroyReadStream(stream) { + stream.destroy() - // validate argument - if (!isStats && typeof entity !== 'string' && !Buffer.isBuffer(entity)) { - throw new TypeError('argument entity must be string, Buffer, or fs.Stats') + if (typeof stream.close === 'function') { + // node.js core bug work-around + stream.on('open', onOpenClose) } - // generate entity tag - var tag = isStats - ? stattag(entity) - : entitytag(entity) - - return weak - ? 'W/' + tag - : tag + return stream } /** - * Determine if object is a Stats object. - * - * @param {object} obj - * @return {boolean} - * @api private + * On open handler to close stream. + * @private */ -function isstats (obj) { - // genuine fs.Stats - if (typeof Stats === 'function' && obj instanceof Stats) { - return true +function onOpenClose() { + if (typeof this.fd === 'number') { + // actually close down the fd + this.close() } - - // quack quack - return obj && typeof obj === 'object' && - 'ctime' in obj && toString.call(obj.ctime) === '[object Date]' && - 'mtime' in obj && toString.call(obj.mtime) === '[object Date]' && - 'ino' in obj && typeof obj.ino === 'number' && - 'size' in obj && typeof obj.size === 'number' } -/** - * Generate a tag for a stat. - * - * @param {object} stat - * @return {string} - * @private - */ -function stattag (stat) { - var mtime = stat.mtime.getTime().toString(16) - var size = stat.size.toString(16) +/***/ }), - return '"' + size + '-' + mtime + '"' +/***/ 12437: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +/* @flow */ +/*:: + +type DotenvParseOptions = { + debug?: boolean } +// keys and values from src +type DotenvParseOutput = { [string]: string } -/***/ }), +type DotenvConfigOptions = { + path?: string, // path to .env file + encoding?: string, // encoding of .env file + debug?: string // turn on logging for debugging purposes +} -/***/ 71204: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +type DotenvConfigOutput = { + parsed?: DotenvParseOutput, + error?: Error +} -"use strict"; -/*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2013 Roman Shtylman - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ +*/ +const fs = __nccwpck_require__(57147) +const path = __nccwpck_require__(71017) +function log (message /*: string */) { + console.log(`[dotenv][DEBUG] ${message}`) +} -module.exports = __nccwpck_require__(22587); +const NEWLINE = '\n' +const RE_INI_KEY_VAL = /^\s*([\w.-]+)\s*=\s*(.*)?\s*$/ +const RE_NEWLINES = /\\n/g +const NEWLINES_MATCH = /\n|\r|\r\n/ +// Parses src into an Object +function parse (src /*: string | Buffer */, options /*: ?DotenvParseOptions */) /*: DotenvParseOutput */ { + const debug = Boolean(options && options.debug) + const obj = {} -/***/ }), + // convert Buffers before splitting into lines and processing + src.toString().split(NEWLINES_MATCH).forEach(function (line, idx) { + // matching "KEY' and 'VAL' in 'KEY=VAL' + const keyValueArr = line.match(RE_INI_KEY_VAL) + // matched? + if (keyValueArr != null) { + const key = keyValueArr[1] + // default undefined or missing values to empty string + let val = (keyValueArr[2] || '') + const end = val.length - 1 + const isDoubleQuoted = val[0] === '"' && val[end] === '"' + const isSingleQuoted = val[0] === "'" && val[end] === "'" -/***/ 313: -/***/ ((module, exports, __nccwpck_require__) => { + // if single or double quoted, remove quotes + if (isSingleQuoted || isDoubleQuoted) { + val = val.substring(1, end) -"use strict"; -/*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2013 Roman Shtylman - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ + // if double quoted, expand newlines + if (isDoubleQuoted) { + val = val.replace(RE_NEWLINES, NEWLINE) + } + } else { + // remove surrounding whitespace + val = val.trim() + } + obj[key] = val + } else if (debug) { + log(`did not match key and value when parsing line ${idx + 1}: ${line}`) + } + }) + return obj +} -/** - * Module dependencies. - * @private - */ +// Populates process.env from .env file +function config (options /*: ?DotenvConfigOptions */) /*: DotenvConfigOutput */ { + let dotenvPath = path.resolve(process.cwd(), '.env') + let encoding /*: string */ = 'utf8' + let debug = false -var finalhandler = __nccwpck_require__(30810); -var Router = __nccwpck_require__(24963); -var methods = __nccwpck_require__(58752); -var middleware = __nccwpck_require__(92636); -var query = __nccwpck_require__(79768); -var debug = __nccwpck_require__(52529)('express:application'); -var View = __nccwpck_require__(99209); -var http = __nccwpck_require__(13685); -var compileETag = (__nccwpck_require__(53561).compileETag); -var compileQueryParser = (__nccwpck_require__(53561).compileQueryParser); -var compileTrust = (__nccwpck_require__(53561).compileTrust); -var deprecate = __nccwpck_require__(18883)('express'); -var flatten = __nccwpck_require__(62003); -var merge = __nccwpck_require__(44429); -var resolve = (__nccwpck_require__(71017).resolve); -var setPrototypeOf = __nccwpck_require__(40414) -var slice = Array.prototype.slice; + if (options) { + if (options.path != null) { + dotenvPath = options.path + } + if (options.encoding != null) { + encoding = options.encoding + } + if (options.debug != null) { + debug = true + } + } -/** - * Application prototype. - */ + try { + // specifying an encoding returns a string instead of a buffer + const parsed = parse(fs.readFileSync(dotenvPath, { encoding }), { debug }) -var app = exports = module.exports = {}; + Object.keys(parsed).forEach(function (key) { + if (!Object.prototype.hasOwnProperty.call(process.env, key)) { + process.env[key] = parsed[key] + } else if (debug) { + log(`"${key}" is already defined in \`process.env\` and will not be overwritten`) + } + }) -/** - * Variable for trust proxy inheritance back-compat - * @private - */ + return { parsed } + } catch (e) { + return { error: e } + } +} -var trustProxyDefaultSymbol = '@@symbol:trust_proxy_default'; +module.exports.config = config +module.exports.parse = parse -/** - * Initialize the server. - * - * - setup default configuration - * - setup default middleware - * - setup route reflection methods - * - * @private - */ -app.init = function init() { - this.cache = {}; - this.engines = {}; - this.settings = {}; +/***/ }), - this.defaultConfiguration(); -}; +/***/ 11728: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * Initialize application configuration. - * @private - */ +"use strict"; -app.defaultConfiguration = function defaultConfiguration() { - var env = process.env.NODE_ENV || 'development'; - // default settings - this.enable('x-powered-by'); - this.set('etag', 'weak'); - this.set('env', env); - this.set('query parser', 'extended'); - this.set('subdomain offset', 2); - this.set('trust proxy', false); +var Buffer = (__nccwpck_require__(21867).Buffer); - // trust proxy inherit back-compat - Object.defineProperty(this.settings, trustProxyDefaultSymbol, { - configurable: true, - value: true - }); +var getParamBytesForAlg = __nccwpck_require__(30528); - debug('booting in %s mode', env); +var MAX_OCTET = 0x80, + CLASS_UNIVERSAL = 0, + PRIMITIVE_BIT = 0x20, + TAG_SEQ = 0x10, + TAG_INT = 0x02, + ENCODED_TAG_SEQ = (TAG_SEQ | PRIMITIVE_BIT) | (CLASS_UNIVERSAL << 6), + ENCODED_TAG_INT = TAG_INT | (CLASS_UNIVERSAL << 6); - this.on('mount', function onmount(parent) { - // inherit trust proxy - if (this.settings[trustProxyDefaultSymbol] === true - && typeof parent.settings['trust proxy fn'] === 'function') { - delete this.settings['trust proxy']; - delete this.settings['trust proxy fn']; - } +function base64Url(base64) { + return base64 + .replace(/=/g, '') + .replace(/\+/g, '-') + .replace(/\//g, '_'); +} - // inherit protos - setPrototypeOf(this.request, parent.request) - setPrototypeOf(this.response, parent.response) - setPrototypeOf(this.engines, parent.engines) - setPrototypeOf(this.settings, parent.settings) - }); +function signatureAsBuffer(signature) { + if (Buffer.isBuffer(signature)) { + return signature; + } else if ('string' === typeof signature) { + return Buffer.from(signature, 'base64'); + } - // setup locals - this.locals = Object.create(null); + throw new TypeError('ECDSA signature must be a Base64 string or a Buffer'); +} - // top-most app is mounted at / - this.mountpath = '/'; +function derToJose(signature, alg) { + signature = signatureAsBuffer(signature); + var paramBytes = getParamBytesForAlg(alg); - // default locals - this.locals.settings = this.settings; + // the DER encoded param should at most be the param size, plus a padding + // zero, since due to being a signed integer + var maxEncodedParamLength = paramBytes + 1; - // default configuration - this.set('view', View); - this.set('views', resolve('views')); - this.set('jsonp callback name', 'callback'); + var inputLength = signature.length; - if (env === 'production') { - this.enable('view cache'); - } + var offset = 0; + if (signature[offset++] !== ENCODED_TAG_SEQ) { + throw new Error('Could not find expected "seq"'); + } - Object.defineProperty(this, 'router', { - get: function() { - throw new Error('\'app.router\' is deprecated!\nPlease see the 3.x to 4.x migration guide for details on how to update your app.'); - } - }); -}; + var seqLength = signature[offset++]; + if (seqLength === (MAX_OCTET | 1)) { + seqLength = signature[offset++]; + } -/** - * lazily adds the base router if it has not yet been added. - * - * We cannot add the base router in the defaultConfiguration because - * it reads app settings which might be set after that has run. - * - * @private - */ -app.lazyrouter = function lazyrouter() { - if (!this._router) { - this._router = new Router({ - caseSensitive: this.enabled('case sensitive routing'), - strict: this.enabled('strict routing') - }); + if (inputLength - offset < seqLength) { + throw new Error('"seq" specified length of "' + seqLength + '", only "' + (inputLength - offset) + '" remaining'); + } - this._router.use(query(this.get('query parser fn'))); - this._router.use(middleware.init(this)); - } -}; + if (signature[offset++] !== ENCODED_TAG_INT) { + throw new Error('Could not find expected "int" for "r"'); + } -/** - * Dispatch a req, res pair into the application. Starts pipeline processing. - * - * If no callback is provided, then default error handlers will respond - * in the event of an error bubbling through the stack. - * - * @private - */ + var rLength = signature[offset++]; -app.handle = function handle(req, res, callback) { - var router = this._router; + if (inputLength - offset - 2 < rLength) { + throw new Error('"r" specified length of "' + rLength + '", only "' + (inputLength - offset - 2) + '" available'); + } - // final handler - var done = callback || finalhandler(req, res, { - env: this.get('env'), - onerror: logerror.bind(this) - }); + if (maxEncodedParamLength < rLength) { + throw new Error('"r" specified length of "' + rLength + '", max of "' + maxEncodedParamLength + '" is acceptable'); + } - // no routes - if (!router) { - debug('no routes defined on app'); - done(); - return; - } + var rOffset = offset; + offset += rLength; - router.handle(req, res, done); -}; + if (signature[offset++] !== ENCODED_TAG_INT) { + throw new Error('Could not find expected "int" for "s"'); + } -/** - * Proxy `Router#use()` to add middleware to the app router. - * See Router#use() documentation for details. - * - * If the _fn_ parameter is an express app, then it will be - * mounted at the _route_ specified. - * - * @public - */ + var sLength = signature[offset++]; -app.use = function use(fn) { - var offset = 0; - var path = '/'; + if (inputLength - offset !== sLength) { + throw new Error('"s" specified length of "' + sLength + '", expected "' + (inputLength - offset) + '"'); + } - // default path to '/' - // disambiguate app.use([fn]) - if (typeof fn !== 'function') { - var arg = fn; + if (maxEncodedParamLength < sLength) { + throw new Error('"s" specified length of "' + sLength + '", max of "' + maxEncodedParamLength + '" is acceptable'); + } - while (Array.isArray(arg) && arg.length !== 0) { - arg = arg[0]; - } + var sOffset = offset; + offset += sLength; - // first arg is the path - if (typeof arg !== 'function') { - offset = 1; - path = fn; - } - } + if (offset !== inputLength) { + throw new Error('Expected to consume entire buffer, but "' + (inputLength - offset) + '" bytes remain'); + } - var fns = flatten(slice.call(arguments, offset)); + var rPadding = paramBytes - rLength, + sPadding = paramBytes - sLength; - if (fns.length === 0) { - throw new TypeError('app.use() requires a middleware function') - } + var dst = Buffer.allocUnsafe(rPadding + rLength + sPadding + sLength); - // setup router - this.lazyrouter(); - var router = this._router; + for (offset = 0; offset < rPadding; ++offset) { + dst[offset] = 0; + } + signature.copy(dst, offset, rOffset + Math.max(-rPadding, 0), rOffset + rLength); - fns.forEach(function (fn) { - // non-express app - if (!fn || !fn.handle || !fn.set) { - return router.use(path, fn); - } + offset = paramBytes; - debug('.use app under %s', path); - fn.mountpath = path; - fn.parent = this; + for (var o = offset; offset < o + sPadding; ++offset) { + dst[offset] = 0; + } + signature.copy(dst, offset, sOffset + Math.max(-sPadding, 0), sOffset + sLength); - // restore .app property on req and res - router.use(path, function mounted_app(req, res, next) { - var orig = req.app; - fn.handle(req, res, function (err) { - setPrototypeOf(req, orig.request) - setPrototypeOf(res, orig.response) - next(err); - }); - }); + dst = dst.toString('base64'); + dst = base64Url(dst); - // mounted an app - fn.emit('mount', this); - }, this); + return dst; +} - return this; -}; +function countPadding(buf, start, stop) { + var padding = 0; + while (start + padding < stop && buf[start + padding] === 0) { + ++padding; + } -/** - * Proxy to the app `Router#route()` - * Returns a new `Route` instance for the _path_. - * - * Routes are isolated middleware stacks for specific paths. - * See the Route api docs for details. - * - * @public - */ + var needsSign = buf[start + padding] >= MAX_OCTET; + if (needsSign) { + --padding; + } -app.route = function route(path) { - this.lazyrouter(); - return this._router.route(path); -}; + return padding; +} -/** - * Register the given template engine callback `fn` - * as `ext`. - * - * By default will `require()` the engine based on the - * file extension. For example if you try to render - * a "foo.ejs" file Express will invoke the following internally: - * - * app.engine('ejs', require('ejs').__express); - * - * For engines that do not provide `.__express` out of the box, - * or if you wish to "map" a different extension to the template engine - * you may use this method. For example mapping the EJS template engine to - * ".html" files: - * - * app.engine('html', require('ejs').renderFile); - * - * In this case EJS provides a `.renderFile()` method with - * the same signature that Express expects: `(path, options, callback)`, - * though note that it aliases this method as `ejs.__express` internally - * so if you're using ".ejs" extensions you don't need to do anything. - * - * Some template engines do not follow this convention, the - * [Consolidate.js](https://github.com/tj/consolidate.js) - * library was created to map all of node's popular template - * engines to follow this convention, thus allowing them to - * work seamlessly within Express. - * - * @param {String} ext - * @param {Function} fn - * @return {app} for chaining - * @public - */ - -app.engine = function engine(ext, fn) { - if (typeof fn !== 'function') { - throw new Error('callback function required'); - } - - // get file extension - var extension = ext[0] !== '.' - ? '.' + ext - : ext; +function joseToDer(signature, alg) { + signature = signatureAsBuffer(signature); + var paramBytes = getParamBytesForAlg(alg); - // store engine - this.engines[extension] = fn; + var signatureBytes = signature.length; + if (signatureBytes !== paramBytes * 2) { + throw new TypeError('"' + alg + '" signatures must be "' + paramBytes * 2 + '" bytes, saw "' + signatureBytes + '"'); + } - return this; -}; + var rPadding = countPadding(signature, 0, paramBytes); + var sPadding = countPadding(signature, paramBytes, signature.length); + var rLength = paramBytes - rPadding; + var sLength = paramBytes - sPadding; -/** - * Proxy to `Router#param()` with one added api feature. The _name_ parameter - * can be an array of names. - * - * See the Router#param() docs for more details. - * - * @param {String|Array} name - * @param {Function} fn - * @return {app} for chaining - * @public - */ + var rsBytes = 1 + 1 + rLength + 1 + 1 + sLength; -app.param = function param(name, fn) { - this.lazyrouter(); + var shortLength = rsBytes < MAX_OCTET; - if (Array.isArray(name)) { - for (var i = 0; i < name.length; i++) { - this.param(name[i], fn); - } + var dst = Buffer.allocUnsafe((shortLength ? 2 : 3) + rsBytes); - return this; - } + var offset = 0; + dst[offset++] = ENCODED_TAG_SEQ; + if (shortLength) { + // Bit 8 has value "0" + // bits 7-1 give the length. + dst[offset++] = rsBytes; + } else { + // Bit 8 of first octet has value "1" + // bits 7-1 give the number of additional length octets. + dst[offset++] = MAX_OCTET | 1; + // length, base 256 + dst[offset++] = rsBytes & 0xff; + } + dst[offset++] = ENCODED_TAG_INT; + dst[offset++] = rLength; + if (rPadding < 0) { + dst[offset++] = 0; + offset += signature.copy(dst, offset, 0, paramBytes); + } else { + offset += signature.copy(dst, offset, rPadding, paramBytes); + } + dst[offset++] = ENCODED_TAG_INT; + dst[offset++] = sLength; + if (sPadding < 0) { + dst[offset++] = 0; + signature.copy(dst, offset, paramBytes); + } else { + signature.copy(dst, offset, paramBytes + sPadding); + } - this._router.param(name, fn); + return dst; +} - return this; +module.exports = { + derToJose: derToJose, + joseToDer: joseToDer }; -/** - * Assign `setting` to `val`, or return `setting`'s value. - * - * app.set('foo', 'bar'); - * app.set('foo'); - * // => "bar" - * - * Mounted servers inherit their parent server's settings. - * - * @param {String} setting - * @param {*} [val] - * @return {Server} for chaining - * @public - */ - -app.set = function set(setting, val) { - if (arguments.length === 1) { - // app.get(setting) - return this.settings[setting]; - } - debug('set "%s" to %o', setting, val); +/***/ }), - // set value - this.settings[setting] = val; +/***/ 30528: +/***/ ((module) => { - // trigger matched settings - switch (setting) { - case 'etag': - this.set('etag fn', compileETag(val)); - break; - case 'query parser': - this.set('query parser fn', compileQueryParser(val)); - break; - case 'trust proxy': - this.set('trust proxy fn', compileTrust(val)); +"use strict"; - // trust proxy inherit back-compat - Object.defineProperty(this.settings, trustProxyDefaultSymbol, { - configurable: true, - value: false - }); - break; - } +function getParamSize(keySize) { + var result = ((keySize / 8) | 0) + (keySize % 8 === 0 ? 0 : 1); + return result; +} - return this; +var paramBytesForAlg = { + ES256: getParamSize(256), + ES384: getParamSize(384), + ES512: getParamSize(521) }; -/** - * Return the app's absolute pathname - * based on the parent(s) that have - * mounted it. - * - * For example if the application was - * mounted as "/admin", which itself - * was mounted as "/blog" then the - * return value would be "/blog/admin". - * - * @return {String} - * @private - */ +function getParamBytesForAlg(alg) { + var paramBytes = paramBytesForAlg[alg]; + if (paramBytes) { + return paramBytes; + } -app.path = function path() { - return this.parent - ? this.parent.path() + this.mountpath - : ''; -}; + throw new Error('Unknown algorithm "' + alg + '"'); +} -/** - * Check if `setting` is enabled (truthy). - * - * app.enabled('foo') - * // => false - * - * app.enable('foo') - * app.enabled('foo') - * // => true - * - * @param {String} setting - * @return {Boolean} - * @public - */ +module.exports = getParamBytesForAlg; -app.enabled = function enabled(setting) { - return Boolean(this.set(setting)); -}; -/** - * Check if `setting` is disabled. - * - * app.disabled('foo') - * // => true - * - * app.enable('foo') - * app.disabled('foo') - * // => false - * - * @param {String} setting - * @return {Boolean} - * @public +/***/ }), + +/***/ 14401: +/***/ ((module) => { + +"use strict"; +/*! + * ee-first + * Copyright(c) 2014 Jonathan Ong + * MIT Licensed */ -app.disabled = function disabled(setting) { - return !this.set(setting); -}; + /** - * Enable `setting`. - * - * @param {String} setting - * @return {app} for chaining + * Module exports. * @public */ -app.enable = function enable(setting) { - return this.set(setting, true); -}; +module.exports = first /** - * Disable `setting`. + * Get the first event in a set of event emitters and event pairs. * - * @param {String} setting - * @return {app} for chaining + * @param {array} stuff + * @param {function} done * @public */ -app.disable = function disable(setting) { - return this.set(setting, false); -}; +function first(stuff, done) { + if (!Array.isArray(stuff)) + throw new TypeError('arg must be an array of [ee, events...] arrays') -/** - * Delegate `.VERB(...)` calls to `router.VERB(...)`. - */ + var cleanups = [] -methods.forEach(function(method){ - app[method] = function(path){ - if (method === 'get' && arguments.length === 1) { - // app.get(setting) - return this.set(path); - } + for (var i = 0; i < stuff.length; i++) { + var arr = stuff[i] - this.lazyrouter(); + if (!Array.isArray(arr) || arr.length < 2) + throw new TypeError('each array member must be [ee, events...]') - var route = this._router.route(path); - route[method].apply(route, slice.call(arguments, 1)); - return this; - }; -}); + var ee = arr[0] -/** - * Special-cased "all" method, applying the given route `path`, - * middleware, and callback to _every_ HTTP method. - * - * @param {String} path - * @param {Function} ... - * @return {app} for chaining - * @public - */ + for (var j = 1; j < arr.length; j++) { + var event = arr[j] + var fn = listener(event, callback) -app.all = function all(path) { - this.lazyrouter(); + // listen to the event + ee.on(event, fn) + // push this listener to the list of cleanups + cleanups.push({ + ee: ee, + event: event, + fn: fn, + }) + } + } - var route = this._router.route(path); - var args = slice.call(arguments, 1); + function callback() { + cleanup() + done.apply(null, arguments) + } - for (var i = 0; i < methods.length; i++) { - route[methods[i]].apply(route, args); + function cleanup() { + var x + for (var i = 0; i < cleanups.length; i++) { + x = cleanups[i] + x.ee.removeListener(x.event, x.fn) + } } - return this; -}; + function thunk(fn) { + done = fn + } -// del -> delete alias + thunk.cancel = cleanup -app.del = deprecate.function(app.delete, 'app.del: Use app.delete instead'); + return thunk +} /** - * Render the given view `name` name with `options` - * and a callback accepting an error and the - * rendered template string. - * - * Example: - * - * app.render('email', { name: 'Tobi' }, function(err, html){ - * // ... - * }) - * - * @param {String} name - * @param {Object|Function} options or fn - * @param {Function} callback - * @public + * Create the event listener. + * @private */ -app.render = function render(name, options, callback) { - var cache = this.cache; - var done = callback; - var engines = this.engines; - var opts = options; - var renderOptions = {}; - var view; +function listener(event, done) { + return function onevent(arg1) { + var args = new Array(arguments.length) + var ee = this + var err = event === 'error' + ? arg1 + : null - // support callback function as second arg - if (typeof options === 'function') { - done = options; - opts = {}; + // copy args to prevent arguments escaping scope + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i] + } + + done(err, ee, event, args) } +} - // merge app.locals - merge(renderOptions, this.locals); - // merge options._locals - if (opts._locals) { - merge(renderOptions, opts._locals); - } +/***/ }), - // merge options - merge(renderOptions, opts); +/***/ 18212: +/***/ ((module) => { - // set .cache unless explicitly provided - if (renderOptions.cache == null) { - renderOptions.cache = this.enabled('view cache'); - } +"use strict"; - // primed cache - if (renderOptions.cache) { - view = cache[name]; - } - // view - if (!view) { - var View = this.get('view'); +module.exports = function () { + // https://mths.be/emoji + return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|\uD83D\uDC68(?:\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68\uD83C\uDFFB|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C[\uDFFB-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)\uD83C\uDFFB|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB\uDFFC])|\uD83D\uDC69(?:\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB-\uDFFD])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83C\uDFF4\u200D\u2620)\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF4\uD83C\uDDF2|\uD83C\uDDF6\uD83C\uDDE6|[#\*0-9]\uFE0F\u20E3|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDBB\uDDD2-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g; +}; - view = new View(name, { - defaultEngine: this.get('view engine'), - root: this.get('views'), - engines: engines - }); - if (!view.path) { - var dirs = Array.isArray(view.root) && view.root.length > 1 - ? 'directories "' + view.root.slice(0, -1).join('", "') + '" or "' + view.root[view.root.length - 1] + '"' - : 'directory "' + view.root + '"' - var err = new Error('Failed to lookup view "' + name + '" in views ' + dirs); - err.view = view; - return done(err); - } +/***/ }), + +/***/ 16592: +/***/ ((module) => { + +"use strict"; +/*! + * encodeurl + * Copyright(c) 2016 Douglas Christopher Wilson + * MIT Licensed + */ - // prime the cache - if (renderOptions.cache) { - cache[name] = view; - } - } - // render - tryRender(view, renderOptions, done); -}; /** - * Listen for connections. - * - * A node `http.Server` is returned, with this - * application (which is a `Function`) as its - * callback. If you wish to create both an HTTP - * and HTTPS server you may do so with the "http" - * and "https" modules as shown here: - * - * var http = require('http') - * , https = require('https') - * , express = require('express') - * , app = express(); - * - * http.createServer(app).listen(80); - * https.createServer({ ... }, app).listen(443); - * - * @return {http.Server} + * Module exports. * @public */ -app.listen = function listen() { - var server = http.createServer(this); - return server.listen.apply(server, arguments); -}; +module.exports = encodeUrl /** - * Log error using console.error. - * - * @param {Error} err + * RegExp to match non-URL code points, *after* encoding (i.e. not including "%") + * and including invalid escape sequences. * @private */ -function logerror(err) { - /* istanbul ignore next */ - if (this.get('env') !== 'test') console.error(err.stack || err.toString()); -} +var ENCODE_CHARS_REGEXP = /(?:[^\x21\x25\x26-\x3B\x3D\x3F-\x5B\x5D\x5F\x61-\x7A\x7E]|%(?:[^0-9A-Fa-f]|[0-9A-Fa-f][^0-9A-Fa-f]|$))+/g /** - * Try rendering a view. + * RegExp to match unmatched surrogate pair. * @private */ -function tryRender(view, options, callback) { - try { - view.render(options, callback); - } catch (err) { - callback(err); - } +var UNMATCHED_SURROGATE_PAIR_REGEXP = /(^|[^\uD800-\uDBFF])[\uDC00-\uDFFF]|[\uD800-\uDBFF]([^\uDC00-\uDFFF]|$)/g + +/** + * String to replace unmatched surrogate pair with. + * @private + */ + +var UNMATCHED_SURROGATE_PAIR_REPLACE = '$1\uFFFD$2' + +/** + * Encode a URL to a percent-encoded form, excluding already-encoded sequences. + * + * This function will take an already-encoded URL and encode all the non-URL + * code points. This function will not encode the "%" character unless it is + * not part of a valid sequence (`%20` will be left as-is, but `%foo` will + * be encoded as `%25foo`). + * + * This encode is meant to be "safe" and does not throw errors. It will try as + * hard as it can to properly encode the given URL, including replacing any raw, + * unpaired surrogate pairs with the Unicode replacement character prior to + * encoding. + * + * @param {string} url + * @return {string} + * @public + */ + +function encodeUrl (url) { + return String(url) + .replace(UNMATCHED_SURROGATE_PAIR_REGEXP, UNMATCHED_SURROGATE_PAIR_REPLACE) + .replace(ENCODE_CHARS_REGEXP, encodeURI) } /***/ }), -/***/ 22587: -/***/ ((module, exports, __nccwpck_require__) => { +/***/ 23505: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -/*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2013 Roman Shtylman - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ +var util = __nccwpck_require__(73837); +var isArrayish = __nccwpck_require__(7604); -/** - * Module dependencies. - */ +var errorEx = function errorEx(name, properties) { + if (!name || name.constructor !== String) { + properties = name || {}; + name = Error.name; + } -var bodyParser = __nccwpck_require__(97076) -var EventEmitter = (__nccwpck_require__(82361).EventEmitter); -var mixin = __nccwpck_require__(11149); -var proto = __nccwpck_require__(313); -var Route = __nccwpck_require__(23699); -var Router = __nccwpck_require__(24963); -var req = __nccwpck_require__(71260); -var res = __nccwpck_require__(64934); + var errorExError = function ErrorEXError(message) { + if (!this) { + return new ErrorEXError(message); + } -/** - * Expose `createApplication()`. - */ + message = message instanceof Error + ? message.message + : (message || this.message); -exports = module.exports = createApplication; + Error.call(this, message); + Error.captureStackTrace(this, errorExError); -/** - * Create an express application. - * - * @return {Function} - * @api public - */ + this.name = name; -function createApplication() { - var app = function(req, res, next) { - app.handle(req, res, next); - }; + Object.defineProperty(this, 'message', { + configurable: true, + enumerable: false, + get: function () { + var newMessage = message.split(/\r?\n/g); - mixin(app, EventEmitter.prototype, false); - mixin(app, proto, false); + for (var key in properties) { + if (!properties.hasOwnProperty(key)) { + continue; + } - // expose the prototype that will get set on requests - app.request = Object.create(req, { - app: { configurable: true, enumerable: true, writable: true, value: app } - }) + var modifier = properties[key]; - // expose the prototype that will get set on responses - app.response = Object.create(res, { - app: { configurable: true, enumerable: true, writable: true, value: app } - }) + if ('message' in modifier) { + newMessage = modifier.message(this[key], newMessage) || newMessage; + if (!isArrayish(newMessage)) { + newMessage = [newMessage]; + } + } + } - app.init(); - return app; -} + return newMessage.join('\n'); + }, + set: function (v) { + message = v; + } + }); -/** - * Expose the prototypes. - */ + var overwrittenStack = null; -exports.application = proto; -exports.request = req; -exports.response = res; + var stackDescriptor = Object.getOwnPropertyDescriptor(this, 'stack'); + var stackGetter = stackDescriptor.get; + var stackValue = stackDescriptor.value; + delete stackDescriptor.value; + delete stackDescriptor.writable; -/** - * Expose constructors. - */ + stackDescriptor.set = function (newstack) { + overwrittenStack = newstack; + }; -exports.Route = Route; -exports.Router = Router; + stackDescriptor.get = function () { + var stack = (overwrittenStack || ((stackGetter) + ? stackGetter.call(this) + : stackValue)).split(/\r?\n+/g); -/** - * Expose middleware - */ + // starting in Node 7, the stack builder caches the message. + // just replace it. + if (!overwrittenStack) { + stack[0] = this.name + ': ' + this.message; + } -exports.json = bodyParser.json -exports.query = __nccwpck_require__(79768); -exports.raw = bodyParser.raw -exports["static"] = __nccwpck_require__(13146); -exports.text = bodyParser.text -exports.urlencoded = bodyParser.urlencoded + var lineCount = 1; + for (var key in properties) { + if (!properties.hasOwnProperty(key)) { + continue; + } -/** - * Replace removed middleware with an appropriate error message. - */ + var modifier = properties[key]; -var removedMiddlewares = [ - 'bodyParser', - 'compress', - 'cookieSession', - 'session', - 'logger', - 'cookieParser', - 'favicon', - 'responseTime', - 'errorHandler', - 'timeout', - 'methodOverride', - 'vhost', - 'csrf', - 'directory', - 'limit', - 'multipart', - 'staticCache' -] + if ('line' in modifier) { + var line = modifier.line(this[key]); + if (line) { + stack.splice(lineCount++, 0, ' ' + line); + } + } -removedMiddlewares.forEach(function (name) { - Object.defineProperty(exports, name, { - get: function () { - throw new Error('Most middleware (like ' + name + ') is no longer bundled with Express and must be installed separately. Please see https://github.com/senchalabs/connect#middleware.'); - }, - configurable: true - }); -}); + if ('stack' in modifier) { + modifier.stack(this[key], stack); + } + } + + return stack.join('\n'); + }; + + Object.defineProperty(this, 'stack', stackDescriptor); + }; + + if (Object.setPrototypeOf) { + Object.setPrototypeOf(errorExError.prototype, Error.prototype); + Object.setPrototypeOf(errorExError, Error); + } else { + util.inherits(errorExError, Error); + } + + return errorExError; +}; + +errorEx.append = function (str, def) { + return { + message: function (v, message) { + v = v || def; + + if (v) { + message[0] += ' ' + str.replace('%s', v.toString()); + } + + return message; + } + }; +}; + +errorEx.line = function (str, def) { + return { + line: function (v) { + v = v || def; + + if (v) { + return str.replace('%s', v.toString()); + } + + return null; + } + }; +}; + +module.exports = errorEx; /***/ }), -/***/ 92636: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 94070: +/***/ ((module) => { "use strict"; /*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2013 Roman Shtylman - * Copyright(c) 2014-2015 Douglas Christopher Wilson + * escape-html + * Copyright(c) 2012-2013 TJ Holowaychuk + * Copyright(c) 2015 Andreas Lubbe + * Copyright(c) 2015 Tiancheng "Timothy" Gu * MIT Licensed */ /** - * Module dependencies. + * Module variables. * @private */ -var setPrototypeOf = __nccwpck_require__(40414) +var matchHtmlRegExp = /["'&<>]/; /** - * Initialization middleware, exposing the - * request and response to each other, as well - * as defaulting the X-Powered-By header field. + * Module exports. + * @public + */ + +module.exports = escapeHtml; + +/** + * Escape special characters in the given string of html. * - * @param {Function} app - * @return {Function} - * @api private + * @param {string} string The string to escape for inserting into HTML + * @return {string} + * @public */ -exports.init = function(app){ - return function expressInit(req, res, next){ - if (app.enabled('x-powered-by')) res.setHeader('X-Powered-By', 'Express'); - req.res = res; - res.req = req; - req.next = next; +function escapeHtml(string) { + var str = '' + string; + var match = matchHtmlRegExp.exec(str); - setPrototypeOf(req, app.request) - setPrototypeOf(res, app.response) + if (!match) { + return str; + } - res.locals = res.locals || Object.create(null); + var escape; + var html = ''; + var index = 0; + var lastIndex = 0; - next(); - }; -}; + for (index = match.index; index < str.length; index++) { + switch (str.charCodeAt(index)) { + case 34: // " + escape = '"'; + break; + case 38: // & + escape = '&'; + break; + case 39: // ' + escape = '''; + break; + case 60: // < + escape = '<'; + break; + case 62: // > + escape = '>'; + break; + default: + continue; + } + + if (lastIndex !== index) { + html += str.substring(lastIndex, index); + } + + lastIndex = index + 1; + html += escape; + } + return lastIndex !== index + ? html + str.substring(lastIndex, index) + : html; +} /***/ }), -/***/ 79768: +/***/ 98691: +/***/ ((module) => { + +"use strict"; + + +module.exports = string => { + if (typeof string !== 'string') { + throw new TypeError('Expected a string'); + } + + // Escape characters with special meaning either inside or outside character sets. + // Use a simple backslash escape when it’s always valid, and a \unnnn escape when the simpler form would be disallowed by Unicode patterns’ stricter grammar. + return string + .replace(/[|\\{}()[\]^$+*?.]/g, '\\$&') + .replace(/-/g, '\\x2d'); +}; + + +/***/ }), + +/***/ 69972: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2013 Roman Shtylman - * Copyright(c) 2014-2015 Douglas Christopher Wilson + * etag + * Copyright(c) 2014-2016 Douglas Christopher Wilson * MIT Licensed */ +/** + * Module exports. + * @public + */ + +module.exports = etag + /** * Module dependencies. + * @private */ -var merge = __nccwpck_require__(44429) -var parseUrl = __nccwpck_require__(89808); -var qs = __nccwpck_require__(22760); +var crypto = __nccwpck_require__(6113) +var Stats = (__nccwpck_require__(57147).Stats) /** - * @param {Object} options - * @return {Function} - * @api public + * Module variables. + * @private */ -module.exports = function query(options) { - var opts = merge({}, options) - var queryparse = qs.parse; +var toString = Object.prototype.toString - if (typeof options === 'function') { - queryparse = options; - opts = undefined; +/** + * Generate an entity tag. + * + * @param {Buffer|string} entity + * @return {string} + * @private + */ + +function entitytag (entity) { + if (entity.length === 0) { + // fast-path empty + return '"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk"' } - if (opts !== undefined && opts.allowPrototypes === undefined) { - // back-compat for qs module - opts.allowPrototypes = true; + // compute hash of entity + var hash = crypto + .createHash('sha1') + .update(entity, 'utf8') + .digest('base64') + .substring(0, 27) + + // compute length of entity + var len = typeof entity === 'string' + ? Buffer.byteLength(entity, 'utf8') + : entity.length + + return '"' + len.toString(16) + '-' + hash + '"' +} + +/** + * Create a simple ETag. + * + * @param {string|Buffer|Stats} entity + * @param {object} [options] + * @param {boolean} [options.weak] + * @return {String} + * @public + */ + +function etag (entity, options) { + if (entity == null) { + throw new TypeError('argument entity is required') } - return function query(req, res, next){ - if (!req.query) { - var val = parseUrl(req).query; - req.query = queryparse(val, opts); - } + // support fs.Stats object + var isStats = isstats(entity) + var weak = options && typeof options.weak === 'boolean' + ? options.weak + : isStats - next(); - }; -}; + // validate argument + if (!isStats && typeof entity !== 'string' && !Buffer.isBuffer(entity)) { + throw new TypeError('argument entity must be string, Buffer, or fs.Stats') + } + + // generate entity tag + var tag = isStats + ? stattag(entity) + : entitytag(entity) + + return weak + ? 'W/' + tag + : tag +} + +/** + * Determine if object is a Stats object. + * + * @param {object} obj + * @return {boolean} + * @api private + */ + +function isstats (obj) { + // genuine fs.Stats + if (typeof Stats === 'function' && obj instanceof Stats) { + return true + } + + // quack quack + return obj && typeof obj === 'object' && + 'ctime' in obj && toString.call(obj.ctime) === '[object Date]' && + 'mtime' in obj && toString.call(obj.mtime) === '[object Date]' && + 'ino' in obj && typeof obj.ino === 'number' && + 'size' in obj && typeof obj.size === 'number' +} + +/** + * Generate a tag for a stat. + * + * @param {object} stat + * @return {string} + * @private + */ + +function stattag (stat) { + var mtime = stat.mtime.getTime().toString(16) + var size = stat.size.toString(16) + + return '"' + size + '-' + mtime + '"' +} /***/ }), -/***/ 71260: +/***/ 71204: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -37218,532 +38133,671 @@ module.exports = function query(options) { +module.exports = __nccwpck_require__(22587); + + +/***/ }), + +/***/ 313: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + + + /** * Module dependencies. * @private */ -var accepts = __nccwpck_require__(83633); -var deprecate = __nccwpck_require__(18883)('express'); -var isIP = (__nccwpck_require__(41808).isIP); -var typeis = __nccwpck_require__(71159); +var finalhandler = __nccwpck_require__(30810); +var Router = __nccwpck_require__(24963); +var methods = __nccwpck_require__(58752); +var middleware = __nccwpck_require__(92636); +var query = __nccwpck_require__(79768); +var debug = __nccwpck_require__(52529)('express:application'); +var View = __nccwpck_require__(99209); var http = __nccwpck_require__(13685); -var fresh = __nccwpck_require__(83136); -var parseRange = __nccwpck_require__(26435); -var parse = __nccwpck_require__(89808); -var proxyaddr = __nccwpck_require__(80140); +var compileETag = (__nccwpck_require__(53561).compileETag); +var compileQueryParser = (__nccwpck_require__(53561).compileQueryParser); +var compileTrust = (__nccwpck_require__(53561).compileTrust); +var deprecate = __nccwpck_require__(18883)('express'); +var flatten = __nccwpck_require__(62003); +var merge = __nccwpck_require__(44429); +var resolve = (__nccwpck_require__(71017).resolve); +var setPrototypeOf = __nccwpck_require__(40414) +var slice = Array.prototype.slice; /** - * Request prototype. - * @public + * Application prototype. */ -var req = Object.create(http.IncomingMessage.prototype) +var app = exports = module.exports = {}; /** - * Module exports. - * @public + * Variable for trust proxy inheritance back-compat + * @private */ -module.exports = req +var trustProxyDefaultSymbol = '@@symbol:trust_proxy_default'; /** - * Return request header. + * Initialize the server. * - * The `Referrer` header field is special-cased, - * both `Referrer` and `Referer` are interchangeable. - * - * Examples: - * - * req.get('Content-Type'); - * // => "text/plain" - * - * req.get('content-type'); - * // => "text/plain" - * - * req.get('Something'); - * // => undefined - * - * Aliased as `req.header()`. + * - setup default configuration + * - setup default middleware + * - setup route reflection methods * - * @param {String} name - * @return {String} - * @public + * @private */ -req.get = -req.header = function header(name) { - if (!name) { - throw new TypeError('name argument is required to req.get'); - } +app.init = function init() { + this.cache = {}; + this.engines = {}; + this.settings = {}; - if (typeof name !== 'string') { - throw new TypeError('name must be a string to req.get'); - } + this.defaultConfiguration(); +}; - var lc = name.toLowerCase(); +/** + * Initialize application configuration. + * @private + */ - switch (lc) { - case 'referer': - case 'referrer': - return this.headers.referrer - || this.headers.referer; - default: - return this.headers[lc]; +app.defaultConfiguration = function defaultConfiguration() { + var env = process.env.NODE_ENV || 'development'; + + // default settings + this.enable('x-powered-by'); + this.set('etag', 'weak'); + this.set('env', env); + this.set('query parser', 'extended'); + this.set('subdomain offset', 2); + this.set('trust proxy', false); + + // trust proxy inherit back-compat + Object.defineProperty(this.settings, trustProxyDefaultSymbol, { + configurable: true, + value: true + }); + + debug('booting in %s mode', env); + + this.on('mount', function onmount(parent) { + // inherit trust proxy + if (this.settings[trustProxyDefaultSymbol] === true + && typeof parent.settings['trust proxy fn'] === 'function') { + delete this.settings['trust proxy']; + delete this.settings['trust proxy fn']; + } + + // inherit protos + setPrototypeOf(this.request, parent.request) + setPrototypeOf(this.response, parent.response) + setPrototypeOf(this.engines, parent.engines) + setPrototypeOf(this.settings, parent.settings) + }); + + // setup locals + this.locals = Object.create(null); + + // top-most app is mounted at / + this.mountpath = '/'; + + // default locals + this.locals.settings = this.settings; + + // default configuration + this.set('view', View); + this.set('views', resolve('views')); + this.set('jsonp callback name', 'callback'); + + if (env === 'production') { + this.enable('view cache'); } + + Object.defineProperty(this, 'router', { + get: function() { + throw new Error('\'app.router\' is deprecated!\nPlease see the 3.x to 4.x migration guide for details on how to update your app.'); + } + }); }; /** - * To do: update docs. - * - * Check if the given `type(s)` is acceptable, returning - * the best match when true, otherwise `undefined`, in which - * case you should respond with 406 "Not Acceptable". - * - * The `type` value may be a single MIME type string - * such as "application/json", an extension name - * such as "json", a comma-delimited list such as "json, html, text/plain", - * an argument list such as `"json", "html", "text/plain"`, - * or an array `["json", "html", "text/plain"]`. When a list - * or array is given, the _best_ match, if any is returned. - * - * Examples: - * - * // Accept: text/html - * req.accepts('html'); - * // => "html" - * - * // Accept: text/*, application/json - * req.accepts('html'); - * // => "html" - * req.accepts('text/html'); - * // => "text/html" - * req.accepts('json, text'); - * // => "json" - * req.accepts('application/json'); - * // => "application/json" - * - * // Accept: text/*, application/json - * req.accepts('image/png'); - * req.accepts('png'); - * // => undefined + * lazily adds the base router if it has not yet been added. * - * // Accept: text/*;q=.5, application/json - * req.accepts(['html', 'json']); - * req.accepts('html', 'json'); - * req.accepts('html, json'); - * // => "json" + * We cannot add the base router in the defaultConfiguration because + * it reads app settings which might be set after that has run. * - * @param {String|Array} type(s) - * @return {String|Array|Boolean} - * @public + * @private */ +app.lazyrouter = function lazyrouter() { + if (!this._router) { + this._router = new Router({ + caseSensitive: this.enabled('case sensitive routing'), + strict: this.enabled('strict routing') + }); -req.accepts = function(){ - var accept = accepts(this); - return accept.types.apply(accept, arguments); + this._router.use(query(this.get('query parser fn'))); + this._router.use(middleware.init(this)); + } }; /** - * Check if the given `encoding`s are accepted. + * Dispatch a req, res pair into the application. Starts pipeline processing. * - * @param {String} ...encoding - * @return {String|Array} - * @public + * If no callback is provided, then default error handlers will respond + * in the event of an error bubbling through the stack. + * + * @private */ -req.acceptsEncodings = function(){ - var accept = accepts(this); - return accept.encodings.apply(accept, arguments); -}; +app.handle = function handle(req, res, callback) { + var router = this._router; -req.acceptsEncoding = deprecate.function(req.acceptsEncodings, - 'req.acceptsEncoding: Use acceptsEncodings instead'); + // final handler + var done = callback || finalhandler(req, res, { + env: this.get('env'), + onerror: logerror.bind(this) + }); -/** - * Check if the given `charset`s are acceptable, - * otherwise you should respond with 406 "Not Acceptable". - * - * @param {String} ...charset - * @return {String|Array} - * @public - */ + // no routes + if (!router) { + debug('no routes defined on app'); + done(); + return; + } -req.acceptsCharsets = function(){ - var accept = accepts(this); - return accept.charsets.apply(accept, arguments); + router.handle(req, res, done); }; -req.acceptsCharset = deprecate.function(req.acceptsCharsets, - 'req.acceptsCharset: Use acceptsCharsets instead'); - /** - * Check if the given `lang`s are acceptable, - * otherwise you should respond with 406 "Not Acceptable". + * Proxy `Router#use()` to add middleware to the app router. + * See Router#use() documentation for details. + * + * If the _fn_ parameter is an express app, then it will be + * mounted at the _route_ specified. * - * @param {String} ...lang - * @return {String|Array} * @public */ -req.acceptsLanguages = function(){ - var accept = accepts(this); - return accept.languages.apply(accept, arguments); -}; +app.use = function use(fn) { + var offset = 0; + var path = '/'; -req.acceptsLanguage = deprecate.function(req.acceptsLanguages, - 'req.acceptsLanguage: Use acceptsLanguages instead'); + // default path to '/' + // disambiguate app.use([fn]) + if (typeof fn !== 'function') { + var arg = fn; + + while (Array.isArray(arg) && arg.length !== 0) { + arg = arg[0]; + } + + // first arg is the path + if (typeof arg !== 'function') { + offset = 1; + path = fn; + } + } + + var fns = flatten(slice.call(arguments, offset)); + + if (fns.length === 0) { + throw new TypeError('app.use() requires a middleware function') + } + + // setup router + this.lazyrouter(); + var router = this._router; + + fns.forEach(function (fn) { + // non-express app + if (!fn || !fn.handle || !fn.set) { + return router.use(path, fn); + } + + debug('.use app under %s', path); + fn.mountpath = path; + fn.parent = this; + + // restore .app property on req and res + router.use(path, function mounted_app(req, res, next) { + var orig = req.app; + fn.handle(req, res, function (err) { + setPrototypeOf(req, orig.request) + setPrototypeOf(res, orig.response) + next(err); + }); + }); + + // mounted an app + fn.emit('mount', this); + }, this); + + return this; +}; /** - * Parse Range header field, capping to the given `size`. - * - * Unspecified ranges such as "0-" require knowledge of your resource length. In - * the case of a byte range this is of course the total number of bytes. If the - * Range header field is not given `undefined` is returned, `-1` when unsatisfiable, - * and `-2` when syntactically invalid. - * - * When ranges are returned, the array has a "type" property which is the type of - * range that is required (most commonly, "bytes"). Each array element is an object - * with a "start" and "end" property for the portion of the range. - * - * The "combine" option can be set to `true` and overlapping & adjacent ranges - * will be combined into a single range. + * Proxy to the app `Router#route()` + * Returns a new `Route` instance for the _path_. * - * NOTE: remember that ranges are inclusive, so for example "Range: users=0-3" - * should respond with 4 users when available, not 3. + * Routes are isolated middleware stacks for specific paths. + * See the Route api docs for details. * - * @param {number} size - * @param {object} [options] - * @param {boolean} [options.combine=false] - * @return {number|array} * @public */ -req.range = function range(size, options) { - var range = this.get('Range'); - if (!range) return; - return parseRange(size, range, options); +app.route = function route(path) { + this.lazyrouter(); + return this._router.route(path); }; /** - * Return the value of param `name` when present or `defaultValue`. + * Register the given template engine callback `fn` + * as `ext`. * - * - Checks route placeholders, ex: _/user/:id_ - * - Checks body params, ex: id=12, {"id":12} - * - Checks query string params, ex: ?id=12 + * By default will `require()` the engine based on the + * file extension. For example if you try to render + * a "foo.ejs" file Express will invoke the following internally: * - * To utilize request bodies, `req.body` - * should be an object. This can be done by using - * the `bodyParser()` middleware. + * app.engine('ejs', require('ejs').__express); * - * @param {String} name - * @param {Mixed} [defaultValue] - * @return {String} + * For engines that do not provide `.__express` out of the box, + * or if you wish to "map" a different extension to the template engine + * you may use this method. For example mapping the EJS template engine to + * ".html" files: + * + * app.engine('html', require('ejs').renderFile); + * + * In this case EJS provides a `.renderFile()` method with + * the same signature that Express expects: `(path, options, callback)`, + * though note that it aliases this method as `ejs.__express` internally + * so if you're using ".ejs" extensions you don't need to do anything. + * + * Some template engines do not follow this convention, the + * [Consolidate.js](https://github.com/tj/consolidate.js) + * library was created to map all of node's popular template + * engines to follow this convention, thus allowing them to + * work seamlessly within Express. + * + * @param {String} ext + * @param {Function} fn + * @return {app} for chaining * @public */ -req.param = function param(name, defaultValue) { - var params = this.params || {}; - var body = this.body || {}; - var query = this.query || {}; +app.engine = function engine(ext, fn) { + if (typeof fn !== 'function') { + throw new Error('callback function required'); + } - var args = arguments.length === 1 - ? 'name' - : 'name, default'; - deprecate('req.param(' + args + '): Use req.params, req.body, or req.query instead'); + // get file extension + var extension = ext[0] !== '.' + ? '.' + ext + : ext; - if (null != params[name] && params.hasOwnProperty(name)) return params[name]; - if (null != body[name]) return body[name]; - if (null != query[name]) return query[name]; + // store engine + this.engines[extension] = fn; - return defaultValue; + return this; }; /** - * Check if the incoming request contains the "Content-Type" - * header field, and it contains the given mime `type`. - * - * Examples: - * - * // With Content-Type: text/html; charset=utf-8 - * req.is('html'); - * req.is('text/html'); - * req.is('text/*'); - * // => true - * - * // When Content-Type is application/json - * req.is('json'); - * req.is('application/json'); - * req.is('application/*'); - * // => true + * Proxy to `Router#param()` with one added api feature. The _name_ parameter + * can be an array of names. * - * req.is('html'); - * // => false + * See the Router#param() docs for more details. * - * @param {String|Array} types... - * @return {String|false|null} + * @param {String|Array} name + * @param {Function} fn + * @return {app} for chaining * @public */ -req.is = function is(types) { - var arr = types; +app.param = function param(name, fn) { + this.lazyrouter(); - // support flattened arguments - if (!Array.isArray(types)) { - arr = new Array(arguments.length); - for (var i = 0; i < arr.length; i++) { - arr[i] = arguments[i]; + if (Array.isArray(name)) { + for (var i = 0; i < name.length; i++) { + this.param(name[i], fn); } + + return this; } - return typeis(this, arr); + this._router.param(name, fn); + + return this; }; /** - * Return the protocol string "http" or "https" - * when requested with TLS. When the "trust proxy" - * setting trusts the socket address, the - * "X-Forwarded-Proto" header field will be trusted - * and used if present. + * Assign `setting` to `val`, or return `setting`'s value. * - * If you're running behind a reverse proxy that - * supplies https for you this may be enabled. + * app.set('foo', 'bar'); + * app.set('foo'); + * // => "bar" * - * @return {String} + * Mounted servers inherit their parent server's settings. + * + * @param {String} setting + * @param {*} [val] + * @return {Server} for chaining * @public */ -defineGetter(req, 'protocol', function protocol(){ - var proto = this.connection.encrypted - ? 'https' - : 'http'; - var trust = this.app.get('trust proxy fn'); - - if (!trust(this.connection.remoteAddress, 0)) { - return proto; +app.set = function set(setting, val) { + if (arguments.length === 1) { + // app.get(setting) + return this.settings[setting]; } - // Note: X-Forwarded-Proto is normally only ever a - // single value, but this is to be safe. - var header = this.get('X-Forwarded-Proto') || proto - var index = header.indexOf(',') + debug('set "%s" to %o', setting, val); - return index !== -1 - ? header.substring(0, index).trim() - : header.trim() -}); + // set value + this.settings[setting] = val; + + // trigger matched settings + switch (setting) { + case 'etag': + this.set('etag fn', compileETag(val)); + break; + case 'query parser': + this.set('query parser fn', compileQueryParser(val)); + break; + case 'trust proxy': + this.set('trust proxy fn', compileTrust(val)); + + // trust proxy inherit back-compat + Object.defineProperty(this.settings, trustProxyDefaultSymbol, { + configurable: true, + value: false + }); + + break; + } + + return this; +}; /** - * Short-hand for: + * Return the app's absolute pathname + * based on the parent(s) that have + * mounted it. * - * req.protocol === 'https' + * For example if the application was + * mounted as "/admin", which itself + * was mounted as "/blog" then the + * return value would be "/blog/admin". * - * @return {Boolean} - * @public + * @return {String} + * @private */ -defineGetter(req, 'secure', function secure(){ - return this.protocol === 'https'; -}); +app.path = function path() { + return this.parent + ? this.parent.path() + this.mountpath + : ''; +}; /** - * Return the remote address from the trusted proxy. + * Check if `setting` is enabled (truthy). * - * The is the remote address on the socket unless - * "trust proxy" is set. + * app.enabled('foo') + * // => false * - * @return {String} + * app.enable('foo') + * app.enabled('foo') + * // => true + * + * @param {String} setting + * @return {Boolean} * @public */ -defineGetter(req, 'ip', function ip(){ - var trust = this.app.get('trust proxy fn'); - return proxyaddr(this, trust); -}); +app.enabled = function enabled(setting) { + return Boolean(this.set(setting)); +}; /** - * When "trust proxy" is set, trusted proxy addresses + client. + * Check if `setting` is disabled. * - * For example if the value were "client, proxy1, proxy2" - * you would receive the array `["client", "proxy1", "proxy2"]` - * where "proxy2" is the furthest down-stream and "proxy1" and - * "proxy2" were trusted. + * app.disabled('foo') + * // => true * - * @return {Array} + * app.enable('foo') + * app.disabled('foo') + * // => false + * + * @param {String} setting + * @return {Boolean} * @public */ -defineGetter(req, 'ips', function ips() { - var trust = this.app.get('trust proxy fn'); - var addrs = proxyaddr.all(this, trust); +app.disabled = function disabled(setting) { + return !this.set(setting); +}; - // reverse the order (to farthest -> closest) - // and remove socket address - addrs.reverse().pop() +/** + * Enable `setting`. + * + * @param {String} setting + * @return {app} for chaining + * @public + */ - return addrs -}); +app.enable = function enable(setting) { + return this.set(setting, true); +}; /** - * Return subdomains as an array. - * - * Subdomains are the dot-separated parts of the host before the main domain of - * the app. By default, the domain of the app is assumed to be the last two - * parts of the host. This can be changed by setting "subdomain offset". - * - * For example, if the domain is "tobi.ferrets.example.com": - * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`. - * If "subdomain offset" is 3, req.subdomains is `["tobi"]`. + * Disable `setting`. * - * @return {Array} + * @param {String} setting + * @return {app} for chaining * @public */ -defineGetter(req, 'subdomains', function subdomains() { - var hostname = this.hostname; +app.disable = function disable(setting) { + return this.set(setting, false); +}; - if (!hostname) return []; +/** + * Delegate `.VERB(...)` calls to `router.VERB(...)`. + */ - var offset = this.app.get('subdomain offset'); - var subdomains = !isIP(hostname) - ? hostname.split('.').reverse() - : [hostname]; +methods.forEach(function(method){ + app[method] = function(path){ + if (method === 'get' && arguments.length === 1) { + // app.get(setting) + return this.set(path); + } - return subdomains.slice(offset); + this.lazyrouter(); + + var route = this._router.route(path); + route[method].apply(route, slice.call(arguments, 1)); + return this; + }; }); /** - * Short-hand for `url.parse(req.url).pathname`. + * Special-cased "all" method, applying the given route `path`, + * middleware, and callback to _every_ HTTP method. * - * @return {String} + * @param {String} path + * @param {Function} ... + * @return {app} for chaining * @public */ -defineGetter(req, 'path', function path() { - return parse(this).pathname; -}); +app.all = function all(path) { + this.lazyrouter(); + + var route = this._router.route(path); + var args = slice.call(arguments, 1); + + for (var i = 0; i < methods.length; i++) { + route[methods[i]].apply(route, args); + } + + return this; +}; + +// del -> delete alias + +app.del = deprecate.function(app.delete, 'app.del: Use app.delete instead'); /** - * Parse the "Host" header field to a hostname. + * Render the given view `name` name with `options` + * and a callback accepting an error and the + * rendered template string. * - * When the "trust proxy" setting trusts the socket - * address, the "X-Forwarded-Host" header field will - * be trusted. + * Example: * - * @return {String} + * app.render('email', { name: 'Tobi' }, function(err, html){ + * // ... + * }) + * + * @param {String} name + * @param {Object|Function} options or fn + * @param {Function} callback * @public */ -defineGetter(req, 'hostname', function hostname(){ - var trust = this.app.get('trust proxy fn'); - var host = this.get('X-Forwarded-Host'); +app.render = function render(name, options, callback) { + var cache = this.cache; + var done = callback; + var engines = this.engines; + var opts = options; + var renderOptions = {}; + var view; - if (!host || !trust(this.connection.remoteAddress, 0)) { - host = this.get('Host'); - } else if (host.indexOf(',') !== -1) { - // Note: X-Forwarded-Host is normally only ever a - // single value, but this is to be safe. - host = host.substring(0, host.indexOf(',')).trimRight() + // support callback function as second arg + if (typeof options === 'function') { + done = options; + opts = {}; } - if (!host) return; + // merge app.locals + merge(renderOptions, this.locals); - // IPv6 literal support - var offset = host[0] === '[' - ? host.indexOf(']') + 1 - : 0; - var index = host.indexOf(':', offset); + // merge options._locals + if (opts._locals) { + merge(renderOptions, opts._locals); + } - return index !== -1 - ? host.substring(0, index) - : host; -}); + // merge options + merge(renderOptions, opts); -// TODO: change req.host to return host in next major + // set .cache unless explicitly provided + if (renderOptions.cache == null) { + renderOptions.cache = this.enabled('view cache'); + } -defineGetter(req, 'host', deprecate.function(function host(){ - return this.hostname; -}, 'req.host: Use req.hostname instead')); + // primed cache + if (renderOptions.cache) { + view = cache[name]; + } -/** - * Check if the request is fresh, aka - * Last-Modified and/or the ETag - * still match. - * - * @return {Boolean} - * @public - */ + // view + if (!view) { + var View = this.get('view'); -defineGetter(req, 'fresh', function(){ - var method = this.method; - var res = this.res - var status = res.statusCode + view = new View(name, { + defaultEngine: this.get('view engine'), + root: this.get('views'), + engines: engines + }); - // GET or HEAD for weak freshness validation only - if ('GET' !== method && 'HEAD' !== method) return false; + if (!view.path) { + var dirs = Array.isArray(view.root) && view.root.length > 1 + ? 'directories "' + view.root.slice(0, -1).join('", "') + '" or "' + view.root[view.root.length - 1] + '"' + : 'directory "' + view.root + '"' + var err = new Error('Failed to lookup view "' + name + '" in views ' + dirs); + err.view = view; + return done(err); + } - // 2xx or 304 as per rfc2616 14.26 - if ((status >= 200 && status < 300) || 304 === status) { - return fresh(this.headers, { - 'etag': res.get('ETag'), - 'last-modified': res.get('Last-Modified') - }) + // prime the cache + if (renderOptions.cache) { + cache[name] = view; + } } - return false; -}); + // render + tryRender(view, renderOptions, done); +}; /** - * Check if the request is stale, aka - * "Last-Modified" and / or the "ETag" for the - * resource has changed. + * Listen for connections. * - * @return {Boolean} + * A node `http.Server` is returned, with this + * application (which is a `Function`) as its + * callback. If you wish to create both an HTTP + * and HTTPS server you may do so with the "http" + * and "https" modules as shown here: + * + * var http = require('http') + * , https = require('https') + * , express = require('express') + * , app = express(); + * + * http.createServer(app).listen(80); + * https.createServer({ ... }, app).listen(443); + * + * @return {http.Server} * @public */ -defineGetter(req, 'stale', function stale(){ - return !this.fresh; -}); +app.listen = function listen() { + var server = http.createServer(this); + return server.listen.apply(server, arguments); +}; /** - * Check if the request was an _XMLHttpRequest_. + * Log error using console.error. * - * @return {Boolean} - * @public + * @param {Error} err + * @private */ -defineGetter(req, 'xhr', function xhr(){ - var val = this.get('X-Requested-With') || ''; - return val.toLowerCase() === 'xmlhttprequest'; -}); +function logerror(err) { + /* istanbul ignore next */ + if (this.get('env') !== 'test') console.error(err.stack || err.toString()); +} /** - * Helper function for creating a getter on an object. - * - * @param {Object} obj - * @param {String} name - * @param {Function} getter + * Try rendering a view. * @private */ -function defineGetter(obj, name, getter) { - Object.defineProperty(obj, name, { - configurable: true, - enumerable: true, - get: getter - }); + +function tryRender(view, options, callback) { + try { + view.render(options, callback); + } catch (err) { + callback(err); + } } /***/ }), -/***/ 64934: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 22587: +/***/ ((module, exports, __nccwpck_require__) => { "use strict"; /*! * express * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman * Copyright(c) 2014-2015 Douglas Christopher Wilson * MIT Licensed */ @@ -37752,1154 +38806,760 @@ function defineGetter(obj, name, getter) { /** * Module dependencies. - * @private */ -var Buffer = (__nccwpck_require__(41894).Buffer) -var contentDisposition = __nccwpck_require__(53921); -var deprecate = __nccwpck_require__(18883)('express'); -var encodeUrl = __nccwpck_require__(16592); -var escapeHtml = __nccwpck_require__(94070); -var http = __nccwpck_require__(13685); -var isAbsolute = (__nccwpck_require__(53561).isAbsolute); -var onFinished = __nccwpck_require__(24694); -var path = __nccwpck_require__(71017); -var statuses = __nccwpck_require__(57415) -var merge = __nccwpck_require__(44429); -var sign = (__nccwpck_require__(61579).sign); -var normalizeType = (__nccwpck_require__(53561).normalizeType); -var normalizeTypes = (__nccwpck_require__(53561).normalizeTypes); -var setCharset = (__nccwpck_require__(53561).setCharset); -var cookie = __nccwpck_require__(93658); -var send = __nccwpck_require__(95287); -var extname = path.extname; -var mime = send.mime; -var resolve = path.resolve; -var vary = __nccwpck_require__(85931); +var bodyParser = __nccwpck_require__(97076) +var EventEmitter = (__nccwpck_require__(82361).EventEmitter); +var mixin = __nccwpck_require__(11149); +var proto = __nccwpck_require__(313); +var Route = __nccwpck_require__(23699); +var Router = __nccwpck_require__(24963); +var req = __nccwpck_require__(71260); +var res = __nccwpck_require__(64934); /** - * Response prototype. - * @public + * Expose `createApplication()`. */ -var res = Object.create(http.ServerResponse.prototype) +exports = module.exports = createApplication; /** - * Module exports. - * @public + * Create an express application. + * + * @return {Function} + * @api public */ -module.exports = res +function createApplication() { + var app = function(req, res, next) { + app.handle(req, res, next); + }; + + mixin(app, EventEmitter.prototype, false); + mixin(app, proto, false); + + // expose the prototype that will get set on requests + app.request = Object.create(req, { + app: { configurable: true, enumerable: true, writable: true, value: app } + }) + + // expose the prototype that will get set on responses + app.response = Object.create(res, { + app: { configurable: true, enumerable: true, writable: true, value: app } + }) + + app.init(); + return app; +} /** - * Module variables. - * @private + * Expose the prototypes. */ -var charsetRegExp = /;\s*charset\s*=/; +exports.application = proto; +exports.request = req; +exports.response = res; /** - * Set status `code`. - * - * @param {Number} code - * @return {ServerResponse} - * @public + * Expose constructors. */ -res.status = function status(code) { - this.statusCode = code; - return this; -}; +exports.Route = Route; +exports.Router = Router; /** - * Set Link header field with the given `links`. - * - * Examples: - * - * res.links({ - * next: 'http://api.example.com/users?page=2', - * last: 'http://api.example.com/users?page=5' - * }); - * - * @param {Object} links - * @return {ServerResponse} - * @public + * Expose middleware */ -res.links = function(links){ - var link = this.get('Link') || ''; - if (link) link += ', '; - return this.set('Link', link + Object.keys(links).map(function(rel){ - return '<' + links[rel] + '>; rel="' + rel + '"'; - }).join(', ')); -}; +exports.json = bodyParser.json +exports.query = __nccwpck_require__(79768); +exports.raw = bodyParser.raw +exports["static"] = __nccwpck_require__(13146); +exports.text = bodyParser.text +exports.urlencoded = bodyParser.urlencoded /** - * Send a response. - * - * Examples: - * - * res.send(Buffer.from('wahoo')); - * res.send({ some: 'json' }); - * res.send('

some html

'); - * - * @param {string|number|boolean|object|Buffer} body - * @public + * Replace removed middleware with an appropriate error message. */ -res.send = function send(body) { - var chunk = body; - var encoding; - var req = this.req; - var type; +var removedMiddlewares = [ + 'bodyParser', + 'compress', + 'cookieSession', + 'session', + 'logger', + 'cookieParser', + 'favicon', + 'responseTime', + 'errorHandler', + 'timeout', + 'methodOverride', + 'vhost', + 'csrf', + 'directory', + 'limit', + 'multipart', + 'staticCache' +] - // settings - var app = this.app; +removedMiddlewares.forEach(function (name) { + Object.defineProperty(exports, name, { + get: function () { + throw new Error('Most middleware (like ' + name + ') is no longer bundled with Express and must be installed separately. Please see https://github.com/senchalabs/connect#middleware.'); + }, + configurable: true + }); +}); - // allow status / body - if (arguments.length === 2) { - // res.send(body, status) backwards compat - if (typeof arguments[0] !== 'number' && typeof arguments[1] === 'number') { - deprecate('res.send(body, status): Use res.status(status).send(body) instead'); - this.statusCode = arguments[1]; - } else { - deprecate('res.send(status, body): Use res.status(status).send(body) instead'); - this.statusCode = arguments[0]; - chunk = arguments[1]; - } - } - // disambiguate res.send(status) and res.send(status, num) - if (typeof chunk === 'number' && arguments.length === 1) { - // res.send(status) will set status message as text string - if (!this.get('Content-Type')) { - this.type('txt'); - } +/***/ }), - deprecate('res.send(status): Use res.sendStatus(status) instead'); - this.statusCode = chunk; - chunk = statuses[chunk] - } +/***/ 92636: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - switch (typeof chunk) { - // string defaulting to html - case 'string': - if (!this.get('Content-Type')) { - this.type('html'); - } - break; - case 'boolean': - case 'number': - case 'object': - if (chunk === null) { - chunk = ''; - } else if (Buffer.isBuffer(chunk)) { - if (!this.get('Content-Type')) { - this.type('bin'); - } - } else { - return this.json(chunk); - } - break; - } +"use strict"; +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ - // write strings in utf-8 - if (typeof chunk === 'string') { - encoding = 'utf8'; - type = this.get('Content-Type'); - // reflect this in content-type - if (typeof type === 'string') { - this.set('Content-Type', setCharset(type, 'utf-8')); - } - } - // determine if ETag should be generated - var etagFn = app.get('etag fn') - var generateETag = !this.get('ETag') && typeof etagFn === 'function' +/** + * Module dependencies. + * @private + */ - // populate Content-Length - var len - if (chunk !== undefined) { - if (Buffer.isBuffer(chunk)) { - // get length of Buffer - len = chunk.length - } else if (!generateETag && chunk.length < 1000) { - // just calculate length when no ETag + small chunk - len = Buffer.byteLength(chunk, encoding) - } else { - // convert chunk to Buffer and calculate - chunk = Buffer.from(chunk, encoding) - encoding = undefined; - len = chunk.length - } - - this.set('Content-Length', len); - } +var setPrototypeOf = __nccwpck_require__(40414) - // populate ETag - var etag; - if (generateETag && len !== undefined) { - if ((etag = etagFn(chunk, encoding))) { - this.set('ETag', etag); - } - } +/** + * Initialization middleware, exposing the + * request and response to each other, as well + * as defaulting the X-Powered-By header field. + * + * @param {Function} app + * @return {Function} + * @api private + */ - // freshness - if (req.fresh) this.statusCode = 304; +exports.init = function(app){ + return function expressInit(req, res, next){ + if (app.enabled('x-powered-by')) res.setHeader('X-Powered-By', 'Express'); + req.res = res; + res.req = req; + req.next = next; - // strip irrelevant headers - if (204 === this.statusCode || 304 === this.statusCode) { - this.removeHeader('Content-Type'); - this.removeHeader('Content-Length'); - this.removeHeader('Transfer-Encoding'); - chunk = ''; - } + setPrototypeOf(req, app.request) + setPrototypeOf(res, app.response) - if (req.method === 'HEAD') { - // skip body for HEAD - this.end(); - } else { - // respond - this.end(chunk, encoding); - } + res.locals = res.locals || Object.create(null); - return this; + next(); + }; }; -/** - * Send JSON response. - * - * Examples: - * - * res.json(null); - * res.json({ user: 'tj' }); - * - * @param {string|number|boolean|object} obj - * @public - */ -res.json = function json(obj) { - var val = obj; - // allow status / body - if (arguments.length === 2) { - // res.json(body, status) backwards compat - if (typeof arguments[1] === 'number') { - deprecate('res.json(obj, status): Use res.status(status).json(obj) instead'); - this.statusCode = arguments[1]; - } else { - deprecate('res.json(status, obj): Use res.status(status).json(obj) instead'); - this.statusCode = arguments[0]; - val = arguments[1]; - } - } +/***/ }), - // settings - var app = this.app; - var escape = app.get('json escape') - var replacer = app.get('json replacer'); - var spaces = app.get('json spaces'); - var body = stringify(val, replacer, spaces, escape) +/***/ 79768: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ - // content-type - if (!this.get('Content-Type')) { - this.set('Content-Type', 'application/json'); - } - return this.send(body); -}; /** - * Send JSON response with JSONP callback support. - * - * Examples: - * - * res.jsonp(null); - * res.jsonp({ user: 'tj' }); - * - * @param {string|number|boolean|object} obj - * @public + * Module dependencies. */ -res.jsonp = function jsonp(obj) { - var val = obj; +var merge = __nccwpck_require__(44429) +var parseUrl = __nccwpck_require__(89808); +var qs = __nccwpck_require__(22760); - // allow status / body - if (arguments.length === 2) { - // res.jsonp(body, status) backwards compat - if (typeof arguments[1] === 'number') { - deprecate('res.jsonp(obj, status): Use res.status(status).jsonp(obj) instead'); - this.statusCode = arguments[1]; - } else { - deprecate('res.jsonp(status, obj): Use res.status(status).jsonp(obj) instead'); - this.statusCode = arguments[0]; - val = arguments[1]; - } - } +/** + * @param {Object} options + * @return {Function} + * @api public + */ - // settings - var app = this.app; - var escape = app.get('json escape') - var replacer = app.get('json replacer'); - var spaces = app.get('json spaces'); - var body = stringify(val, replacer, spaces, escape) - var callback = this.req.query[app.get('jsonp callback name')]; +module.exports = function query(options) { + var opts = merge({}, options) + var queryparse = qs.parse; - // content-type - if (!this.get('Content-Type')) { - this.set('X-Content-Type-Options', 'nosniff'); - this.set('Content-Type', 'application/json'); + if (typeof options === 'function') { + queryparse = options; + opts = undefined; } - // fixup callback - if (Array.isArray(callback)) { - callback = callback[0]; + if (opts !== undefined && opts.allowPrototypes === undefined) { + // back-compat for qs module + opts.allowPrototypes = true; } - // jsonp - if (typeof callback === 'string' && callback.length !== 0) { - this.set('X-Content-Type-Options', 'nosniff'); - this.set('Content-Type', 'text/javascript'); + return function query(req, res, next){ + if (!req.query) { + var val = parseUrl(req).query; + req.query = queryparse(val, opts); + } - // restrict callback charset - callback = callback.replace(/[^\[\]\w$.]/g, ''); + next(); + }; +}; - if (body === undefined) { - // empty argument - body = '' - } else if (typeof body === 'string') { - // replace chars not allowed in JavaScript that are in JSON - body = body - .replace(/\u2028/g, '\\u2028') - .replace(/\u2029/g, '\\u2029') - } - // the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse" - // the typeof check is just to reduce client error noise - body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');'; - } +/***/ }), + +/***/ 71260: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + - return this.send(body); -}; /** - * Send given HTTP status code. - * - * Sets the response status to `statusCode` and the body of the - * response to the standard description from node's http.STATUS_CODES - * or the statusCode number if no description. - * - * Examples: - * - * res.sendStatus(200); - * - * @param {number} statusCode + * Module dependencies. + * @private + */ + +var accepts = __nccwpck_require__(83633); +var deprecate = __nccwpck_require__(18883)('express'); +var isIP = (__nccwpck_require__(41808).isIP); +var typeis = __nccwpck_require__(71159); +var http = __nccwpck_require__(13685); +var fresh = __nccwpck_require__(83136); +var parseRange = __nccwpck_require__(26435); +var parse = __nccwpck_require__(89808); +var proxyaddr = __nccwpck_require__(80140); + +/** + * Request prototype. * @public */ -res.sendStatus = function sendStatus(statusCode) { - var body = statuses[statusCode] || String(statusCode) +var req = Object.create(http.IncomingMessage.prototype) - this.statusCode = statusCode; - this.type('txt'); +/** + * Module exports. + * @public + */ - return this.send(body); -}; +module.exports = req /** - * Transfer the file at the given `path`. - * - * Automatically sets the _Content-Type_ response header field. - * The callback `callback(err)` is invoked when the transfer is complete - * or when an error occurs. Be sure to check `res.headersSent` - * if you wish to attempt responding, as the header and some data - * may have already been transferred. - * - * Options: - * - * - `maxAge` defaulting to 0 (can be string converted by `ms`) - * - `root` root directory for relative filenames - * - `headers` object of headers to serve with file - * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them + * Return request header. * - * Other options are passed along to `send`. + * The `Referrer` header field is special-cased, + * both `Referrer` and `Referer` are interchangeable. * * Examples: * - * The following example illustrates how `res.sendFile()` may - * be used as an alternative for the `static()` middleware for - * dynamic situations. The code backing `res.sendFile()` is actually - * the same code, so HTTP cache support etc is identical. + * req.get('Content-Type'); + * // => "text/plain" * - * app.get('/user/:uid/photos/:file', function(req, res){ - * var uid = req.params.uid - * , file = req.params.file; + * req.get('content-type'); + * // => "text/plain" * - * req.user.mayViewFilesFrom(uid, function(yes){ - * if (yes) { - * res.sendFile('/uploads/' + uid + '/' + file); - * } else { - * res.send(403, 'Sorry! you cant see that.'); - * } - * }); - * }); + * req.get('Something'); + * // => undefined + * + * Aliased as `req.header()`. * + * @param {String} name + * @return {String} * @public */ -res.sendFile = function sendFile(path, options, callback) { - var done = callback; - var req = this.req; - var res = this; - var next = req.next; - var opts = options || {}; - - if (!path) { - throw new TypeError('path argument is required to res.sendFile'); +req.get = +req.header = function header(name) { + if (!name) { + throw new TypeError('name argument is required to req.get'); } - if (typeof path !== 'string') { - throw new TypeError('path must be a string to res.sendFile') + if (typeof name !== 'string') { + throw new TypeError('name must be a string to req.get'); } - // support function as second arg - if (typeof options === 'function') { - done = options; - opts = {}; - } + var lc = name.toLowerCase(); - if (!opts.root && !isAbsolute(path)) { - throw new TypeError('path must be absolute or specify root to res.sendFile'); + switch (lc) { + case 'referer': + case 'referrer': + return this.headers.referrer + || this.headers.referer; + default: + return this.headers[lc]; } - - // create file stream - var pathname = encodeURI(path); - var file = send(req, pathname, opts); - - // transfer - sendfile(res, file, opts, function (err) { - if (done) return done(err); - if (err && err.code === 'EISDIR') return next(); - - // next() all but write errors - if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') { - next(err); - } - }); }; /** - * Transfer the file at the given `path`. - * - * Automatically sets the _Content-Type_ response header field. - * The callback `callback(err)` is invoked when the transfer is complete - * or when an error occurs. Be sure to check `res.headersSent` - * if you wish to attempt responding, as the header and some data - * may have already been transferred. - * - * Options: + * To do: update docs. * - * - `maxAge` defaulting to 0 (can be string converted by `ms`) - * - `root` root directory for relative filenames - * - `headers` object of headers to serve with file - * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them + * Check if the given `type(s)` is acceptable, returning + * the best match when true, otherwise `undefined`, in which + * case you should respond with 406 "Not Acceptable". * - * Other options are passed along to `send`. + * The `type` value may be a single MIME type string + * such as "application/json", an extension name + * such as "json", a comma-delimited list such as "json, html, text/plain", + * an argument list such as `"json", "html", "text/plain"`, + * or an array `["json", "html", "text/plain"]`. When a list + * or array is given, the _best_ match, if any is returned. * * Examples: * - * The following example illustrates how `res.sendfile()` may - * be used as an alternative for the `static()` middleware for - * dynamic situations. The code backing `res.sendfile()` is actually - * the same code, so HTTP cache support etc is identical. + * // Accept: text/html + * req.accepts('html'); + * // => "html" * - * app.get('/user/:uid/photos/:file', function(req, res){ - * var uid = req.params.uid - * , file = req.params.file; + * // Accept: text/*, application/json + * req.accepts('html'); + * // => "html" + * req.accepts('text/html'); + * // => "text/html" + * req.accepts('json, text'); + * // => "json" + * req.accepts('application/json'); + * // => "application/json" * - * req.user.mayViewFilesFrom(uid, function(yes){ - * if (yes) { - * res.sendfile('/uploads/' + uid + '/' + file); - * } else { - * res.send(403, 'Sorry! you cant see that.'); - * } - * }); - * }); + * // Accept: text/*, application/json + * req.accepts('image/png'); + * req.accepts('png'); + * // => undefined + * + * // Accept: text/*;q=.5, application/json + * req.accepts(['html', 'json']); + * req.accepts('html', 'json'); + * req.accepts('html, json'); + * // => "json" * + * @param {String|Array} type(s) + * @return {String|Array|Boolean} * @public */ -res.sendfile = function (path, options, callback) { - var done = callback; - var req = this.req; - var res = this; - var next = req.next; - var opts = options || {}; - - // support function as second arg - if (typeof options === 'function') { - done = options; - opts = {}; - } - - // create file stream - var file = send(req, path, opts); - - // transfer - sendfile(res, file, opts, function (err) { - if (done) return done(err); - if (err && err.code === 'EISDIR') return next(); - - // next() all but write errors - if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') { - next(err); - } - }); +req.accepts = function(){ + var accept = accepts(this); + return accept.types.apply(accept, arguments); }; -res.sendfile = deprecate.function(res.sendfile, - 'res.sendfile: Use res.sendFile instead'); - /** - * Transfer the file at the given `path` as an attachment. - * - * Optionally providing an alternate attachment `filename`, - * and optional callback `callback(err)`. The callback is invoked - * when the data transfer is complete, or when an error has - * ocurred. Be sure to check `res.headersSent` if you plan to respond. - * - * Optionally providing an `options` object to use with `res.sendFile()`. - * This function will set the `Content-Disposition` header, overriding - * any `Content-Disposition` header passed as header options in order - * to set the attachment and filename. - * - * This method uses `res.sendFile()`. + * Check if the given `encoding`s are accepted. * + * @param {String} ...encoding + * @return {String|Array} * @public */ -res.download = function download (path, filename, options, callback) { - var done = callback; - var name = filename; - var opts = options || null +req.acceptsEncodings = function(){ + var accept = accepts(this); + return accept.encodings.apply(accept, arguments); +}; - // support function as second or third arg - if (typeof filename === 'function') { - done = filename; - name = null; - opts = null - } else if (typeof options === 'function') { - done = options - opts = null - } +req.acceptsEncoding = deprecate.function(req.acceptsEncodings, + 'req.acceptsEncoding: Use acceptsEncodings instead'); - // set Content-Disposition when file is sent - var headers = { - 'Content-Disposition': contentDisposition(name || path) - }; +/** + * Check if the given `charset`s are acceptable, + * otherwise you should respond with 406 "Not Acceptable". + * + * @param {String} ...charset + * @return {String|Array} + * @public + */ - // merge user-provided headers - if (opts && opts.headers) { - var keys = Object.keys(opts.headers) - for (var i = 0; i < keys.length; i++) { - var key = keys[i] - if (key.toLowerCase() !== 'content-disposition') { - headers[key] = opts.headers[key] - } - } - } +req.acceptsCharsets = function(){ + var accept = accepts(this); + return accept.charsets.apply(accept, arguments); +}; - // merge user-provided options - opts = Object.create(opts) - opts.headers = headers +req.acceptsCharset = deprecate.function(req.acceptsCharsets, + 'req.acceptsCharset: Use acceptsCharsets instead'); - // Resolve the full path for sendFile - var fullPath = resolve(path); +/** + * Check if the given `lang`s are acceptable, + * otherwise you should respond with 406 "Not Acceptable". + * + * @param {String} ...lang + * @return {String|Array} + * @public + */ - // send file - return this.sendFile(fullPath, opts, done) +req.acceptsLanguages = function(){ + var accept = accepts(this); + return accept.languages.apply(accept, arguments); }; +req.acceptsLanguage = deprecate.function(req.acceptsLanguages, + 'req.acceptsLanguage: Use acceptsLanguages instead'); + /** - * Set _Content-Type_ response header with `type` through `mime.lookup()` - * when it does not contain "/", or set the Content-Type to `type` otherwise. + * Parse Range header field, capping to the given `size`. * - * Examples: + * Unspecified ranges such as "0-" require knowledge of your resource length. In + * the case of a byte range this is of course the total number of bytes. If the + * Range header field is not given `undefined` is returned, `-1` when unsatisfiable, + * and `-2` when syntactically invalid. * - * res.type('.html'); - * res.type('html'); - * res.type('json'); - * res.type('application/json'); - * res.type('png'); + * When ranges are returned, the array has a "type" property which is the type of + * range that is required (most commonly, "bytes"). Each array element is an object + * with a "start" and "end" property for the portion of the range. * - * @param {String} type - * @return {ServerResponse} for chaining + * The "combine" option can be set to `true` and overlapping & adjacent ranges + * will be combined into a single range. + * + * NOTE: remember that ranges are inclusive, so for example "Range: users=0-3" + * should respond with 4 users when available, not 3. + * + * @param {number} size + * @param {object} [options] + * @param {boolean} [options.combine=false] + * @return {number|array} * @public */ -res.contentType = -res.type = function contentType(type) { - var ct = type.indexOf('/') === -1 - ? mime.lookup(type) - : type; - - return this.set('Content-Type', ct); +req.range = function range(size, options) { + var range = this.get('Range'); + if (!range) return; + return parseRange(size, range, options); }; /** - * Respond to the Acceptable formats using an `obj` - * of mime-type callbacks. - * - * This method uses `req.accepted`, an array of - * acceptable types ordered by their quality values. - * When "Accept" is not present the _first_ callback - * is invoked, otherwise the first match is used. When - * no match is performed the server responds with - * 406 "Not Acceptable". - * - * Content-Type is set for you, however if you choose - * you may alter this within the callback using `res.type()` - * or `res.set('Content-Type', ...)`. - * - * res.format({ - * 'text/plain': function(){ - * res.send('hey'); - * }, - * - * 'text/html': function(){ - * res.send('

hey

'); - * }, - * - * 'application/json': function () { - * res.send({ message: 'hey' }); - * } - * }); - * - * In addition to canonicalized MIME types you may - * also use extnames mapped to these types: - * - * res.format({ - * text: function(){ - * res.send('hey'); - * }, - * - * html: function(){ - * res.send('

hey

'); - * }, + * Return the value of param `name` when present or `defaultValue`. * - * json: function(){ - * res.send({ message: 'hey' }); - * } - * }); + * - Checks route placeholders, ex: _/user/:id_ + * - Checks body params, ex: id=12, {"id":12} + * - Checks query string params, ex: ?id=12 * - * By default Express passes an `Error` - * with a `.status` of 406 to `next(err)` - * if a match is not made. If you provide - * a `.default` callback it will be invoked - * instead. + * To utilize request bodies, `req.body` + * should be an object. This can be done by using + * the `bodyParser()` middleware. * - * @param {Object} obj - * @return {ServerResponse} for chaining + * @param {String} name + * @param {Mixed} [defaultValue] + * @return {String} * @public */ -res.format = function(obj){ - var req = this.req; - var next = req.next; - - var fn = obj.default; - if (fn) delete obj.default; - var keys = Object.keys(obj); - - var key = keys.length > 0 - ? req.accepts(keys) - : false; +req.param = function param(name, defaultValue) { + var params = this.params || {}; + var body = this.body || {}; + var query = this.query || {}; - this.vary("Accept"); + var args = arguments.length === 1 + ? 'name' + : 'name, default'; + deprecate('req.param(' + args + '): Use req.params, req.body, or req.query instead'); - if (key) { - this.set('Content-Type', normalizeType(key).value); - obj[key](req, this, next); - } else if (fn) { - fn(); - } else { - var err = new Error('Not Acceptable'); - err.status = err.statusCode = 406; - err.types = normalizeTypes(keys).map(function(o){ return o.value }); - next(err); - } + if (null != params[name] && params.hasOwnProperty(name)) return params[name]; + if (null != body[name]) return body[name]; + if (null != query[name]) return query[name]; - return this; + return defaultValue; }; /** - * Set _Content-Disposition_ header to _attachment_ with optional `filename`. + * Check if the incoming request contains the "Content-Type" + * header field, and it contains the given mime `type`. * - * @param {String} filename - * @return {ServerResponse} + * Examples: + * + * // With Content-Type: text/html; charset=utf-8 + * req.is('html'); + * req.is('text/html'); + * req.is('text/*'); + * // => true + * + * // When Content-Type is application/json + * req.is('json'); + * req.is('application/json'); + * req.is('application/*'); + * // => true + * + * req.is('html'); + * // => false + * + * @param {String|Array} types... + * @return {String|false|null} * @public */ -res.attachment = function attachment(filename) { - if (filename) { - this.type(extname(filename)); - } +req.is = function is(types) { + var arr = types; - this.set('Content-Disposition', contentDisposition(filename)); + // support flattened arguments + if (!Array.isArray(types)) { + arr = new Array(arguments.length); + for (var i = 0; i < arr.length; i++) { + arr[i] = arguments[i]; + } + } - return this; + return typeis(this, arr); }; /** - * Append additional header `field` with value `val`. - * - * Example: + * Return the protocol string "http" or "https" + * when requested with TLS. When the "trust proxy" + * setting trusts the socket address, the + * "X-Forwarded-Proto" header field will be trusted + * and used if present. * - * res.append('Link', ['', '']); - * res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly'); - * res.append('Warning', '199 Miscellaneous warning'); + * If you're running behind a reverse proxy that + * supplies https for you this may be enabled. * - * @param {String} field - * @param {String|Array} val - * @return {ServerResponse} for chaining + * @return {String} * @public */ -res.append = function append(field, val) { - var prev = this.get(field); - var value = val; +defineGetter(req, 'protocol', function protocol(){ + var proto = this.connection.encrypted + ? 'https' + : 'http'; + var trust = this.app.get('trust proxy fn'); - if (prev) { - // concat the new and prev vals - value = Array.isArray(prev) ? prev.concat(val) - : Array.isArray(val) ? [prev].concat(val) - : [prev, val] + if (!trust(this.connection.remoteAddress, 0)) { + return proto; } - return this.set(field, value); -}; + // Note: X-Forwarded-Proto is normally only ever a + // single value, but this is to be safe. + var header = this.get('X-Forwarded-Proto') || proto + var index = header.indexOf(',') + + return index !== -1 + ? header.substring(0, index).trim() + : header.trim() +}); /** - * Set header `field` to `val`, or pass - * an object of header fields. - * - * Examples: - * - * res.set('Foo', ['bar', 'baz']); - * res.set('Accept', 'application/json'); - * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' }); + * Short-hand for: * - * Aliased as `res.header()`. + * req.protocol === 'https' * - * @param {String|Object} field - * @param {String|Array} val - * @return {ServerResponse} for chaining + * @return {Boolean} * @public */ -res.set = -res.header = function header(field, val) { - if (arguments.length === 2) { - var value = Array.isArray(val) - ? val.map(String) - : String(val); - - // add charset to content-type - if (field.toLowerCase() === 'content-type') { - if (Array.isArray(value)) { - throw new TypeError('Content-Type cannot be set to an Array'); - } - if (!charsetRegExp.test(value)) { - var charset = mime.charsets.lookup(value.split(';')[0]); - if (charset) value += '; charset=' + charset.toLowerCase(); - } - } - - this.setHeader(field, value); - } else { - for (var key in field) { - this.set(key, field[key]); - } - } - return this; -}; +defineGetter(req, 'secure', function secure(){ + return this.protocol === 'https'; +}); /** - * Get value for header `field`. + * Return the remote address from the trusted proxy. + * + * The is the remote address on the socket unless + * "trust proxy" is set. * - * @param {String} field * @return {String} * @public */ -res.get = function(field){ - return this.getHeader(field); -}; +defineGetter(req, 'ip', function ip(){ + var trust = this.app.get('trust proxy fn'); + return proxyaddr(this, trust); +}); /** - * Clear cookie `name`. + * When "trust proxy" is set, trusted proxy addresses + client. * - * @param {String} name - * @param {Object} [options] - * @return {ServerResponse} for chaining + * For example if the value were "client, proxy1, proxy2" + * you would receive the array `["client", "proxy1", "proxy2"]` + * where "proxy2" is the furthest down-stream and "proxy1" and + * "proxy2" were trusted. + * + * @return {Array} * @public */ -res.clearCookie = function clearCookie(name, options) { - var opts = merge({ expires: new Date(1), path: '/' }, options); +defineGetter(req, 'ips', function ips() { + var trust = this.app.get('trust proxy fn'); + var addrs = proxyaddr.all(this, trust); - return this.cookie(name, '', opts); -}; + // reverse the order (to farthest -> closest) + // and remove socket address + addrs.reverse().pop() + + return addrs +}); /** - * Set cookie `name` to `value`, with the given `options`. - * - * Options: - * - * - `maxAge` max-age in milliseconds, converted to `expires` - * - `signed` sign the cookie - * - `path` defaults to "/" - * - * Examples: + * Return subdomains as an array. * - * // "Remember Me" for 15 minutes - * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true }); + * Subdomains are the dot-separated parts of the host before the main domain of + * the app. By default, the domain of the app is assumed to be the last two + * parts of the host. This can be changed by setting "subdomain offset". * - * // same as above - * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true }) + * For example, if the domain is "tobi.ferrets.example.com": + * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`. + * If "subdomain offset" is 3, req.subdomains is `["tobi"]`. * - * @param {String} name - * @param {String|Object} value - * @param {Object} [options] - * @return {ServerResponse} for chaining + * @return {Array} * @public */ -res.cookie = function (name, value, options) { - var opts = merge({}, options); - var secret = this.req.secret; - var signed = opts.signed; - - if (signed && !secret) { - throw new Error('cookieParser("secret") required for signed cookies'); - } - - var val = typeof value === 'object' - ? 'j:' + JSON.stringify(value) - : String(value); - - if (signed) { - val = 's:' + sign(val, secret); - } - - if ('maxAge' in opts) { - opts.expires = new Date(Date.now() + opts.maxAge); - opts.maxAge /= 1000; - } +defineGetter(req, 'subdomains', function subdomains() { + var hostname = this.hostname; - if (opts.path == null) { - opts.path = '/'; - } + if (!hostname) return []; - this.append('Set-Cookie', cookie.serialize(name, String(val), opts)); + var offset = this.app.get('subdomain offset'); + var subdomains = !isIP(hostname) + ? hostname.split('.').reverse() + : [hostname]; - return this; -}; + return subdomains.slice(offset); +}); /** - * Set the location header to `url`. - * - * The given `url` can also be "back", which redirects - * to the _Referrer_ or _Referer_ headers or "/". - * - * Examples: - * - * res.location('/foo/bar').; - * res.location('http://example.com'); - * res.location('../login'); + * Short-hand for `url.parse(req.url).pathname`. * - * @param {String} url - * @return {ServerResponse} for chaining + * @return {String} * @public */ -res.location = function location(url) { - var loc = url; - - // "back" is an alias for the referrer - if (url === 'back') { - loc = this.req.get('Referrer') || '/'; - } - - // set location - return this.set('Location', encodeUrl(loc)); -}; +defineGetter(req, 'path', function path() { + return parse(this).pathname; +}); /** - * Redirect to the given `url` with optional response `status` - * defaulting to 302. - * - * The resulting `url` is determined by `res.location()`, so - * it will play nicely with mounted apps, relative paths, - * `"back"` etc. - * - * Examples: + * Parse the "Host" header field to a hostname. * - * res.redirect('/foo/bar'); - * res.redirect('http://example.com'); - * res.redirect(301, 'http://example.com'); - * res.redirect('../login'); // /blog/post/1 -> /blog/login + * When the "trust proxy" setting trusts the socket + * address, the "X-Forwarded-Host" header field will + * be trusted. * + * @return {String} * @public */ -res.redirect = function redirect(url) { - var address = url; - var body; - var status = 302; +defineGetter(req, 'hostname', function hostname(){ + var trust = this.app.get('trust proxy fn'); + var host = this.get('X-Forwarded-Host'); - // allow status / url - if (arguments.length === 2) { - if (typeof arguments[0] === 'number') { - status = arguments[0]; - address = arguments[1]; - } else { - deprecate('res.redirect(url, status): Use res.redirect(status, url) instead'); - status = arguments[1]; - } + if (!host || !trust(this.connection.remoteAddress, 0)) { + host = this.get('Host'); + } else if (host.indexOf(',') !== -1) { + // Note: X-Forwarded-Host is normally only ever a + // single value, but this is to be safe. + host = host.substring(0, host.indexOf(',')).trimRight() } - // Set location header - address = this.location(address).get('Location'); - - // Support text/{plain,html} by default - this.format({ - text: function(){ - body = statuses[status] + '. Redirecting to ' + address - }, + if (!host) return; - html: function(){ - var u = escapeHtml(address); - body = '

' + statuses[status] + '. Redirecting to ' + u + '

' - }, + // IPv6 literal support + var offset = host[0] === '[' + ? host.indexOf(']') + 1 + : 0; + var index = host.indexOf(':', offset); - default: function(){ - body = ''; - } - }); + return index !== -1 + ? host.substring(0, index) + : host; +}); - // Respond - this.statusCode = status; - this.set('Content-Length', Buffer.byteLength(body)); +// TODO: change req.host to return host in next major - if (this.req.method === 'HEAD') { - this.end(); - } else { - this.end(body); - } -}; +defineGetter(req, 'host', deprecate.function(function host(){ + return this.hostname; +}, 'req.host: Use req.hostname instead')); /** - * Add `field` to Vary. If already present in the Vary set, then - * this call is simply ignored. + * Check if the request is fresh, aka + * Last-Modified and/or the ETag + * still match. * - * @param {Array|String} field - * @return {ServerResponse} for chaining + * @return {Boolean} * @public */ -res.vary = function(field){ - // checks for back-compat - if (!field || (Array.isArray(field) && !field.length)) { - deprecate('res.vary(): Provide a field name'); - return this; - } +defineGetter(req, 'fresh', function(){ + var method = this.method; + var res = this.res + var status = res.statusCode - vary(this, field); + // GET or HEAD for weak freshness validation only + if ('GET' !== method && 'HEAD' !== method) return false; - return this; -}; + // 2xx or 304 as per rfc2616 14.26 + if ((status >= 200 && status < 300) || 304 === status) { + return fresh(this.headers, { + 'etag': res.get('ETag'), + 'last-modified': res.get('Last-Modified') + }) + } + + return false; +}); /** - * Render `view` with the given `options` and optional callback `fn`. - * When a callback function is given a response will _not_ be made - * automatically, otherwise a response of _200_ and _text/html_ is given. - * - * Options: - * - * - `cache` boolean hinting to the engine it should cache - * - `filename` filename of the view being rendered + * Check if the request is stale, aka + * "Last-Modified" and / or the "ETag" for the + * resource has changed. * + * @return {Boolean} * @public */ -res.render = function render(view, options, callback) { - var app = this.req.app; - var done = callback; - var opts = options || {}; - var req = this.req; - var self = this; +defineGetter(req, 'stale', function stale(){ + return !this.fresh; +}); - // support callback function as second arg - if (typeof options === 'function') { - done = options; - opts = {}; - } - - // merge res.locals - opts._locals = self.locals; - - // default callback to respond - done = done || function (err, str) { - if (err) return req.next(err); - self.send(str); - }; - - // render - app.render(view, opts, done); -}; - -// pipe the send file stream -function sendfile(res, file, options, callback) { - var done = false; - var streaming; - - // request aborted - function onaborted() { - if (done) return; - done = true; - - var err = new Error('Request aborted'); - err.code = 'ECONNABORTED'; - callback(err); - } - - // directory - function ondirectory() { - if (done) return; - done = true; - - var err = new Error('EISDIR, read'); - err.code = 'EISDIR'; - callback(err); - } - - // errors - function onerror(err) { - if (done) return; - done = true; - callback(err); - } - - // ended - function onend() { - if (done) return; - done = true; - callback(); - } - - // file - function onfile() { - streaming = false; - } - - // finished - function onfinish(err) { - if (err && err.code === 'ECONNRESET') return onaborted(); - if (err) return onerror(err); - if (done) return; - - setImmediate(function () { - if (streaming !== false && !done) { - onaborted(); - return; - } - - if (done) return; - done = true; - callback(); - }); - } - - // streaming - function onstream() { - streaming = true; - } - - file.on('directory', ondirectory); - file.on('end', onend); - file.on('error', onerror); - file.on('file', onfile); - file.on('stream', onstream); - onFinished(res, onfinish); - - if (options.headers) { - // set headers on successful transfer - file.on('headers', function headers(res) { - var obj = options.headers; - var keys = Object.keys(obj); - - for (var i = 0; i < keys.length; i++) { - var k = keys[i]; - res.setHeader(k, obj[k]); - } - }); - } +/** + * Check if the request was an _XMLHttpRequest_. + * + * @return {Boolean} + * @public + */ - // pipe - file.pipe(res); -} +defineGetter(req, 'xhr', function xhr(){ + var val = this.get('X-Requested-With') || ''; + return val.toLowerCase() === 'xmlhttprequest'; +}); /** - * Stringify JSON, like JSON.stringify, but v8 optimized, with the - * ability to escape characters that can trigger HTML sniffing. + * Helper function for creating a getter on an object. * - * @param {*} value - * @param {function} replaces - * @param {number} spaces - * @param {boolean} escape - * @returns {string} + * @param {Object} obj + * @param {String} name + * @param {Function} getter * @private */ - -function stringify (value, replacer, spaces, escape) { - // v8 checks arguments.length for optimizing simple call - // https://bugs.chromium.org/p/v8/issues/detail?id=4730 - var json = replacer || spaces - ? JSON.stringify(value, replacer, spaces) - : JSON.stringify(value); - - if (escape && typeof json === 'string') { - json = json.replace(/[<>&]/g, function (c) { - switch (c.charCodeAt(0)) { - case 0x3c: - return '\\u003c' - case 0x3e: - return '\\u003e' - case 0x26: - return '\\u0026' - /* istanbul ignore next: unreachable default */ - default: - return c - } - }) - } - - return json +function defineGetter(obj, name, getter) { + Object.defineProperty(obj, name, { + configurable: true, + enumerable: true, + get: getter + }); } /***/ }), -/***/ 24963: +/***/ 64934: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /*! * express * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2013 Roman Shtylman * Copyright(c) 2014-2015 Douglas Christopher Wilson * MIT Licensed */ @@ -38911,853 +39571,1144 @@ function stringify (value, replacer, spaces, escape) { * @private */ -var Route = __nccwpck_require__(23699); -var Layer = __nccwpck_require__(25624); -var methods = __nccwpck_require__(58752); -var mixin = __nccwpck_require__(44429); -var debug = __nccwpck_require__(52529)('express:router'); +var Buffer = (__nccwpck_require__(21867).Buffer) +var contentDisposition = __nccwpck_require__(53921); var deprecate = __nccwpck_require__(18883)('express'); -var flatten = __nccwpck_require__(62003); -var parseUrl = __nccwpck_require__(89808); -var setPrototypeOf = __nccwpck_require__(40414) +var encodeUrl = __nccwpck_require__(16592); +var escapeHtml = __nccwpck_require__(94070); +var http = __nccwpck_require__(13685); +var isAbsolute = (__nccwpck_require__(53561).isAbsolute); +var onFinished = __nccwpck_require__(24694); +var path = __nccwpck_require__(71017); +var statuses = __nccwpck_require__(57415) +var merge = __nccwpck_require__(44429); +var sign = (__nccwpck_require__(61579).sign); +var normalizeType = (__nccwpck_require__(53561).normalizeType); +var normalizeTypes = (__nccwpck_require__(53561).normalizeTypes); +var setCharset = (__nccwpck_require__(53561).setCharset); +var cookie = __nccwpck_require__(93658); +var send = __nccwpck_require__(95287); +var extname = path.extname; +var mime = send.mime; +var resolve = path.resolve; +var vary = __nccwpck_require__(85931); /** - * Module variables. - * @private + * Response prototype. + * @public */ -var objectRegExp = /^\[object (\S+)\]$/; -var slice = Array.prototype.slice; -var toString = Object.prototype.toString; +var res = Object.create(http.ServerResponse.prototype) /** - * Initialize a new `Router` with the given `options`. - * - * @param {Object} [options] - * @return {Router} which is an callable function + * Module exports. * @public */ -var proto = module.exports = function(options) { - var opts = options || {}; +module.exports = res - function router(req, res, next) { - router.handle(req, res, next); - } +/** + * Module variables. + * @private + */ - // mixin Router class functions - setPrototypeOf(router, proto) +var charsetRegExp = /;\s*charset\s*=/; - router.params = {}; - router._params = []; - router.caseSensitive = opts.caseSensitive; - router.mergeParams = opts.mergeParams; - router.strict = opts.strict; - router.stack = []; +/** + * Set status `code`. + * + * @param {Number} code + * @return {ServerResponse} + * @public + */ - return router; +res.status = function status(code) { + this.statusCode = code; + return this; }; /** - * Map the given param placeholder `name`(s) to the given callback. + * Set Link header field with the given `links`. * - * Parameter mapping is used to provide pre-conditions to routes - * which use normalized placeholders. For example a _:user_id_ parameter - * could automatically load a user's information from the database without - * any additional code, + * Examples: * - * The callback uses the same signature as middleware, the only difference - * being that the value of the placeholder is passed, in this case the _id_ - * of the user. Once the `next()` function is invoked, just like middleware - * it will continue on to execute the route, or subsequent parameter functions. + * res.links({ + * next: 'http://api.example.com/users?page=2', + * last: 'http://api.example.com/users?page=5' + * }); * - * Just like in middleware, you must either respond to the request or call next - * to avoid stalling the request. + * @param {Object} links + * @return {ServerResponse} + * @public + */ + +res.links = function(links){ + var link = this.get('Link') || ''; + if (link) link += ', '; + return this.set('Link', link + Object.keys(links).map(function(rel){ + return '<' + links[rel] + '>; rel="' + rel + '"'; + }).join(', ')); +}; + +/** + * Send a response. * - * app.param('user_id', function(req, res, next, id){ - * User.find(id, function(err, user){ - * if (err) { - * return next(err); - * } else if (!user) { - * return next(new Error('failed to load user')); - * } - * req.user = user; - * next(); - * }); - * }); + * Examples: * - * @param {String} name - * @param {Function} fn - * @return {app} for chaining + * res.send(Buffer.from('wahoo')); + * res.send({ some: 'json' }); + * res.send('

some html

'); + * + * @param {string|number|boolean|object|Buffer} body * @public */ -proto.param = function param(name, fn) { - // param logic - if (typeof name === 'function') { - deprecate('router.param(fn): Refactor to use path params'); - this._params.push(name); - return; - } +res.send = function send(body) { + var chunk = body; + var encoding; + var req = this.req; + var type; - // apply param functions - var params = this._params; - var len = params.length; - var ret; + // settings + var app = this.app; - if (name[0] === ':') { - deprecate('router.param(' + JSON.stringify(name) + ', fn): Use router.param(' + JSON.stringify(name.substr(1)) + ', fn) instead'); - name = name.substr(1); + // allow status / body + if (arguments.length === 2) { + // res.send(body, status) backwards compat + if (typeof arguments[0] !== 'number' && typeof arguments[1] === 'number') { + deprecate('res.send(body, status): Use res.status(status).send(body) instead'); + this.statusCode = arguments[1]; + } else { + deprecate('res.send(status, body): Use res.status(status).send(body) instead'); + this.statusCode = arguments[0]; + chunk = arguments[1]; + } } - for (var i = 0; i < len; ++i) { - if (ret = params[i](name, fn)) { - fn = ret; + // disambiguate res.send(status) and res.send(status, num) + if (typeof chunk === 'number' && arguments.length === 1) { + // res.send(status) will set status message as text string + if (!this.get('Content-Type')) { + this.type('txt'); } - } - // ensure we end up with a - // middleware function - if ('function' !== typeof fn) { - throw new Error('invalid param() call for ' + name + ', got ' + fn); + deprecate('res.send(status): Use res.sendStatus(status) instead'); + this.statusCode = chunk; + chunk = statuses[chunk] } - (this.params[name] = this.params[name] || []).push(fn); - return this; -}; - -/** - * Dispatch a req, res into the router. - * @private - */ + switch (typeof chunk) { + // string defaulting to html + case 'string': + if (!this.get('Content-Type')) { + this.type('html'); + } + break; + case 'boolean': + case 'number': + case 'object': + if (chunk === null) { + chunk = ''; + } else if (Buffer.isBuffer(chunk)) { + if (!this.get('Content-Type')) { + this.type('bin'); + } + } else { + return this.json(chunk); + } + break; + } -proto.handle = function handle(req, res, out) { - var self = this; + // write strings in utf-8 + if (typeof chunk === 'string') { + encoding = 'utf8'; + type = this.get('Content-Type'); - debug('dispatching %s %s', req.method, req.url); + // reflect this in content-type + if (typeof type === 'string') { + this.set('Content-Type', setCharset(type, 'utf-8')); + } + } - var idx = 0; - var protohost = getProtohost(req.url) || '' - var removed = ''; - var slashAdded = false; - var paramcalled = {}; + // determine if ETag should be generated + var etagFn = app.get('etag fn') + var generateETag = !this.get('ETag') && typeof etagFn === 'function' - // store options for OPTIONS request - // only used if OPTIONS request - var options = []; + // populate Content-Length + var len + if (chunk !== undefined) { + if (Buffer.isBuffer(chunk)) { + // get length of Buffer + len = chunk.length + } else if (!generateETag && chunk.length < 1000) { + // just calculate length when no ETag + small chunk + len = Buffer.byteLength(chunk, encoding) + } else { + // convert chunk to Buffer and calculate + chunk = Buffer.from(chunk, encoding) + encoding = undefined; + len = chunk.length + } - // middleware and routes - var stack = self.stack; + this.set('Content-Length', len); + } - // manage inter-router variables - var parentParams = req.params; - var parentUrl = req.baseUrl || ''; - var done = restore(out, req, 'baseUrl', 'next', 'params'); + // populate ETag + var etag; + if (generateETag && len !== undefined) { + if ((etag = etagFn(chunk, encoding))) { + this.set('ETag', etag); + } + } - // setup next layer - req.next = next; + // freshness + if (req.fresh) this.statusCode = 304; - // for options requests, respond with a default if nothing else responds - if (req.method === 'OPTIONS') { - done = wrap(done, function(old, err) { - if (err || options.length === 0) return old(err); - sendOptionsResponse(res, options, old); - }); + // strip irrelevant headers + if (204 === this.statusCode || 304 === this.statusCode) { + this.removeHeader('Content-Type'); + this.removeHeader('Content-Length'); + this.removeHeader('Transfer-Encoding'); + chunk = ''; } - // setup basic req values - req.baseUrl = parentUrl; - req.originalUrl = req.originalUrl || req.url; - - next(); + if (req.method === 'HEAD') { + // skip body for HEAD + this.end(); + } else { + // respond + this.end(chunk, encoding); + } - function next(err) { - var layerError = err === 'route' - ? null - : err; + return this; +}; - // remove added slash - if (slashAdded) { - req.url = req.url.substr(1); - slashAdded = false; - } +/** + * Send JSON response. + * + * Examples: + * + * res.json(null); + * res.json({ user: 'tj' }); + * + * @param {string|number|boolean|object} obj + * @public + */ - // restore altered req.url - if (removed.length !== 0) { - req.baseUrl = parentUrl; - req.url = protohost + removed + req.url.substr(protohost.length); - removed = ''; - } +res.json = function json(obj) { + var val = obj; - // signal to exit router - if (layerError === 'router') { - setImmediate(done, null) - return + // allow status / body + if (arguments.length === 2) { + // res.json(body, status) backwards compat + if (typeof arguments[1] === 'number') { + deprecate('res.json(obj, status): Use res.status(status).json(obj) instead'); + this.statusCode = arguments[1]; + } else { + deprecate('res.json(status, obj): Use res.status(status).json(obj) instead'); + this.statusCode = arguments[0]; + val = arguments[1]; } + } - // no more matching layers - if (idx >= stack.length) { - setImmediate(done, layerError); - return; - } + // settings + var app = this.app; + var escape = app.get('json escape') + var replacer = app.get('json replacer'); + var spaces = app.get('json spaces'); + var body = stringify(val, replacer, spaces, escape) - // get pathname of request - var path = getPathname(req); + // content-type + if (!this.get('Content-Type')) { + this.set('Content-Type', 'application/json'); + } - if (path == null) { - return done(layerError); - } + return this.send(body); +}; - // find next matching layer - var layer; - var match; - var route; - - while (match !== true && idx < stack.length) { - layer = stack[idx++]; - match = matchLayer(layer, path); - route = layer.route; - - if (typeof match !== 'boolean') { - // hold on to layerError - layerError = layerError || match; - } +/** + * Send JSON response with JSONP callback support. + * + * Examples: + * + * res.jsonp(null); + * res.jsonp({ user: 'tj' }); + * + * @param {string|number|boolean|object} obj + * @public + */ - if (match !== true) { - continue; - } +res.jsonp = function jsonp(obj) { + var val = obj; - if (!route) { - // process non-route handlers normally - continue; - } + // allow status / body + if (arguments.length === 2) { + // res.jsonp(body, status) backwards compat + if (typeof arguments[1] === 'number') { + deprecate('res.jsonp(obj, status): Use res.status(status).jsonp(obj) instead'); + this.statusCode = arguments[1]; + } else { + deprecate('res.jsonp(status, obj): Use res.status(status).jsonp(obj) instead'); + this.statusCode = arguments[0]; + val = arguments[1]; + } + } - if (layerError) { - // routes do not match with a pending error - match = false; - continue; - } + // settings + var app = this.app; + var escape = app.get('json escape') + var replacer = app.get('json replacer'); + var spaces = app.get('json spaces'); + var body = stringify(val, replacer, spaces, escape) + var callback = this.req.query[app.get('jsonp callback name')]; - var method = req.method; - var has_method = route._handles_method(method); + // content-type + if (!this.get('Content-Type')) { + this.set('X-Content-Type-Options', 'nosniff'); + this.set('Content-Type', 'application/json'); + } - // build up automatic options response - if (!has_method && method === 'OPTIONS') { - appendMethods(options, route._options()); - } + // fixup callback + if (Array.isArray(callback)) { + callback = callback[0]; + } - // don't even bother matching route - if (!has_method && method !== 'HEAD') { - match = false; - continue; - } - } + // jsonp + if (typeof callback === 'string' && callback.length !== 0) { + this.set('X-Content-Type-Options', 'nosniff'); + this.set('Content-Type', 'text/javascript'); - // no match - if (match !== true) { - return done(layerError); - } + // restrict callback charset + callback = callback.replace(/[^\[\]\w$.]/g, ''); - // store route for dispatch on change - if (route) { - req.route = route; + if (body === undefined) { + // empty argument + body = '' + } else if (typeof body === 'string') { + // replace chars not allowed in JavaScript that are in JSON + body = body + .replace(/\u2028/g, '\\u2028') + .replace(/\u2029/g, '\\u2029') } - // Capture one-time layer values - req.params = self.mergeParams - ? mergeParams(layer.params, parentParams) - : layer.params; - var layerPath = layer.path; - - // this should be done for the layer - self.process_params(layer, paramcalled, req, res, function (err) { - if (err) { - return next(layerError || err); - } - - if (route) { - return layer.handle_request(req, res, next); - } - - trim_prefix(layer, layerError, layerPath, path); - }); + // the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse" + // the typeof check is just to reduce client error noise + body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');'; } - function trim_prefix(layer, layerError, layerPath, path) { - if (layerPath.length !== 0) { - // Validate path is a prefix match - if (layerPath !== path.substr(0, layerPath.length)) { - next(layerError) - return - } - - // Validate path breaks on a path separator - var c = path[layerPath.length] - if (c && c !== '/' && c !== '.') return next(layerError) - - // Trim off the part of the url that matches the route - // middleware (.use stuff) needs to have the path stripped - debug('trim prefix (%s) from url %s', layerPath, req.url); - removed = layerPath; - req.url = protohost + req.url.substr(protohost.length + removed.length); + return this.send(body); +}; - // Ensure leading slash - if (!protohost && req.url[0] !== '/') { - req.url = '/' + req.url; - slashAdded = true; - } +/** + * Send given HTTP status code. + * + * Sets the response status to `statusCode` and the body of the + * response to the standard description from node's http.STATUS_CODES + * or the statusCode number if no description. + * + * Examples: + * + * res.sendStatus(200); + * + * @param {number} statusCode + * @public + */ - // Setup base URL (no trailing slash) - req.baseUrl = parentUrl + (removed[removed.length - 1] === '/' - ? removed.substring(0, removed.length - 1) - : removed); - } +res.sendStatus = function sendStatus(statusCode) { + var body = statuses[statusCode] || String(statusCode) - debug('%s %s : %s', layer.name, layerPath, req.originalUrl); + this.statusCode = statusCode; + this.type('txt'); - if (layerError) { - layer.handle_error(layerError, req, res, next); - } else { - layer.handle_request(req, res, next); - } - } + return this.send(body); }; /** - * Process any parameters for the layer. - * @private + * Transfer the file at the given `path`. + * + * Automatically sets the _Content-Type_ response header field. + * The callback `callback(err)` is invoked when the transfer is complete + * or when an error occurs. Be sure to check `res.headersSent` + * if you wish to attempt responding, as the header and some data + * may have already been transferred. + * + * Options: + * + * - `maxAge` defaulting to 0 (can be string converted by `ms`) + * - `root` root directory for relative filenames + * - `headers` object of headers to serve with file + * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them + * + * Other options are passed along to `send`. + * + * Examples: + * + * The following example illustrates how `res.sendFile()` may + * be used as an alternative for the `static()` middleware for + * dynamic situations. The code backing `res.sendFile()` is actually + * the same code, so HTTP cache support etc is identical. + * + * app.get('/user/:uid/photos/:file', function(req, res){ + * var uid = req.params.uid + * , file = req.params.file; + * + * req.user.mayViewFilesFrom(uid, function(yes){ + * if (yes) { + * res.sendFile('/uploads/' + uid + '/' + file); + * } else { + * res.send(403, 'Sorry! you cant see that.'); + * } + * }); + * }); + * + * @public */ -proto.process_params = function process_params(layer, called, req, res, done) { - var params = this.params; +res.sendFile = function sendFile(path, options, callback) { + var done = callback; + var req = this.req; + var res = this; + var next = req.next; + var opts = options || {}; - // captured parameters from the layer, keys and values - var keys = layer.keys; + if (!path) { + throw new TypeError('path argument is required to res.sendFile'); + } - // fast track - if (!keys || keys.length === 0) { - return done(); + if (typeof path !== 'string') { + throw new TypeError('path must be a string to res.sendFile') } - var i = 0; - var name; - var paramIndex = 0; - var key; - var paramVal; - var paramCallbacks; - var paramCalled; + // support function as second arg + if (typeof options === 'function') { + done = options; + opts = {}; + } - // process params in order - // param callbacks can be async - function param(err) { - if (err) { - return done(err); - } + if (!opts.root && !isAbsolute(path)) { + throw new TypeError('path must be absolute or specify root to res.sendFile'); + } - if (i >= keys.length ) { - return done(); - } + // create file stream + var pathname = encodeURI(path); + var file = send(req, pathname, opts); - paramIndex = 0; - key = keys[i++]; - name = key.name; - paramVal = req.params[name]; - paramCallbacks = params[name]; - paramCalled = called[name]; + // transfer + sendfile(res, file, opts, function (err) { + if (done) return done(err); + if (err && err.code === 'EISDIR') return next(); - if (paramVal === undefined || !paramCallbacks) { - return param(); + // next() all but write errors + if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') { + next(err); } + }); +}; - // param previously called with same value or error occurred - if (paramCalled && (paramCalled.match === paramVal - || (paramCalled.error && paramCalled.error !== 'route'))) { - // restore value - req.params[name] = paramCalled.value; - - // next param - return param(paramCalled.error); - } +/** + * Transfer the file at the given `path`. + * + * Automatically sets the _Content-Type_ response header field. + * The callback `callback(err)` is invoked when the transfer is complete + * or when an error occurs. Be sure to check `res.headersSent` + * if you wish to attempt responding, as the header and some data + * may have already been transferred. + * + * Options: + * + * - `maxAge` defaulting to 0 (can be string converted by `ms`) + * - `root` root directory for relative filenames + * - `headers` object of headers to serve with file + * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them + * + * Other options are passed along to `send`. + * + * Examples: + * + * The following example illustrates how `res.sendfile()` may + * be used as an alternative for the `static()` middleware for + * dynamic situations. The code backing `res.sendfile()` is actually + * the same code, so HTTP cache support etc is identical. + * + * app.get('/user/:uid/photos/:file', function(req, res){ + * var uid = req.params.uid + * , file = req.params.file; + * + * req.user.mayViewFilesFrom(uid, function(yes){ + * if (yes) { + * res.sendfile('/uploads/' + uid + '/' + file); + * } else { + * res.send(403, 'Sorry! you cant see that.'); + * } + * }); + * }); + * + * @public + */ - called[name] = paramCalled = { - error: null, - match: paramVal, - value: paramVal - }; +res.sendfile = function (path, options, callback) { + var done = callback; + var req = this.req; + var res = this; + var next = req.next; + var opts = options || {}; - paramCallback(); + // support function as second arg + if (typeof options === 'function') { + done = options; + opts = {}; } - // single param callbacks - function paramCallback(err) { - var fn = paramCallbacks[paramIndex++]; - - // store updated value - paramCalled.value = req.params[key.name]; - - if (err) { - // store error - paramCalled.error = err; - param(err); - return; - } + // create file stream + var file = send(req, path, opts); - if (!fn) return param(); + // transfer + sendfile(res, file, opts, function (err) { + if (done) return done(err); + if (err && err.code === 'EISDIR') return next(); - try { - fn(req, res, paramCallback, paramVal, key.name); - } catch (e) { - paramCallback(e); + // next() all but write errors + if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') { + next(err); } - } - - param(); + }); }; +res.sendfile = deprecate.function(res.sendfile, + 'res.sendfile: Use res.sendFile instead'); + /** - * Use the given middleware function, with optional path, defaulting to "/". + * Transfer the file at the given `path` as an attachment. * - * Use (like `.all`) will run for any http METHOD, but it will not add - * handlers for those methods so OPTIONS requests will not consider `.use` - * functions even if they could respond. + * Optionally providing an alternate attachment `filename`, + * and optional callback `callback(err)`. The callback is invoked + * when the data transfer is complete, or when an error has + * ocurred. Be sure to check `res.headersSent` if you plan to respond. * - * The other difference is that _route_ path is stripped and not visible - * to the handler function. The main effect of this feature is that mounted - * handlers can operate without any code changes regardless of the "prefix" - * pathname. + * Optionally providing an `options` object to use with `res.sendFile()`. + * This function will set the `Content-Disposition` header, overriding + * any `Content-Disposition` header passed as header options in order + * to set the attachment and filename. + * + * This method uses `res.sendFile()`. * * @public */ -proto.use = function use(fn) { - var offset = 0; - var path = '/'; - - // default path to '/' - // disambiguate router.use([fn]) - if (typeof fn !== 'function') { - var arg = fn; - - while (Array.isArray(arg) && arg.length !== 0) { - arg = arg[0]; - } - - // first arg is the path - if (typeof arg !== 'function') { - offset = 1; - path = fn; - } - } - - var callbacks = flatten(slice.call(arguments, offset)); +res.download = function download (path, filename, options, callback) { + var done = callback; + var name = filename; + var opts = options || null - if (callbacks.length === 0) { - throw new TypeError('Router.use() requires a middleware function') + // support function as second or third arg + if (typeof filename === 'function') { + done = filename; + name = null; + opts = null + } else if (typeof options === 'function') { + done = options + opts = null } - for (var i = 0; i < callbacks.length; i++) { - var fn = callbacks[i]; + // set Content-Disposition when file is sent + var headers = { + 'Content-Disposition': contentDisposition(name || path) + }; - if (typeof fn !== 'function') { - throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn)) + // merge user-provided headers + if (opts && opts.headers) { + var keys = Object.keys(opts.headers) + for (var i = 0; i < keys.length; i++) { + var key = keys[i] + if (key.toLowerCase() !== 'content-disposition') { + headers[key] = opts.headers[key] + } } + } - // add the middleware - debug('use %o %s', path, fn.name || '') - - var layer = new Layer(path, { - sensitive: this.caseSensitive, - strict: false, - end: false - }, fn); - - layer.route = undefined; + // merge user-provided options + opts = Object.create(opts) + opts.headers = headers - this.stack.push(layer); - } + // Resolve the full path for sendFile + var fullPath = resolve(path); - return this; + // send file + return this.sendFile(fullPath, opts, done) }; /** - * Create a new Route for the given path. + * Set _Content-Type_ response header with `type` through `mime.lookup()` + * when it does not contain "/", or set the Content-Type to `type` otherwise. * - * Each route contains a separate middleware stack and VERB handlers. + * Examples: * - * See the Route api documentation for details on adding handlers - * and middleware to routes. + * res.type('.html'); + * res.type('html'); + * res.type('json'); + * res.type('application/json'); + * res.type('png'); * - * @param {String} path - * @return {Route} + * @param {String} type + * @return {ServerResponse} for chaining * @public */ -proto.route = function route(path) { - var route = new Route(path); - - var layer = new Layer(path, { - sensitive: this.caseSensitive, - strict: this.strict, - end: true - }, route.dispatch.bind(route)); - - layer.route = route; +res.contentType = +res.type = function contentType(type) { + var ct = type.indexOf('/') === -1 + ? mime.lookup(type) + : type; - this.stack.push(layer); - return route; + return this.set('Content-Type', ct); }; -// create Router#VERB functions -methods.concat('all').forEach(function(method){ - proto[method] = function(path){ - var route = this.route(path) - route[method].apply(route, slice.call(arguments, 1)); - return this; - }; -}); - -// append methods to a list of methods -function appendMethods(list, addition) { - for (var i = 0; i < addition.length; i++) { - var method = addition[i]; - if (list.indexOf(method) === -1) { - list.push(method); - } - } -} - -// get pathname of request -function getPathname(req) { - try { - return parseUrl(req).pathname; - } catch (err) { - return undefined; - } -} +/** + * Respond to the Acceptable formats using an `obj` + * of mime-type callbacks. + * + * This method uses `req.accepted`, an array of + * acceptable types ordered by their quality values. + * When "Accept" is not present the _first_ callback + * is invoked, otherwise the first match is used. When + * no match is performed the server responds with + * 406 "Not Acceptable". + * + * Content-Type is set for you, however if you choose + * you may alter this within the callback using `res.type()` + * or `res.set('Content-Type', ...)`. + * + * res.format({ + * 'text/plain': function(){ + * res.send('hey'); + * }, + * + * 'text/html': function(){ + * res.send('

hey

'); + * }, + * + * 'application/json': function () { + * res.send({ message: 'hey' }); + * } + * }); + * + * In addition to canonicalized MIME types you may + * also use extnames mapped to these types: + * + * res.format({ + * text: function(){ + * res.send('hey'); + * }, + * + * html: function(){ + * res.send('

hey

'); + * }, + * + * json: function(){ + * res.send({ message: 'hey' }); + * } + * }); + * + * By default Express passes an `Error` + * with a `.status` of 406 to `next(err)` + * if a match is not made. If you provide + * a `.default` callback it will be invoked + * instead. + * + * @param {Object} obj + * @return {ServerResponse} for chaining + * @public + */ -// Get get protocol + host for a URL -function getProtohost(url) { - if (typeof url !== 'string' || url.length === 0 || url[0] === '/') { - return undefined - } +res.format = function(obj){ + var req = this.req; + var next = req.next; - var searchIndex = url.indexOf('?') - var pathLength = searchIndex !== -1 - ? searchIndex - : url.length - var fqdnIndex = url.substr(0, pathLength).indexOf('://') + var fn = obj.default; + if (fn) delete obj.default; + var keys = Object.keys(obj); - return fqdnIndex !== -1 - ? url.substr(0, url.indexOf('/', 3 + fqdnIndex)) - : undefined -} + var key = keys.length > 0 + ? req.accepts(keys) + : false; -// get type for error message -function gettype(obj) { - var type = typeof obj; + this.vary("Accept"); - if (type !== 'object') { - return type; + if (key) { + this.set('Content-Type', normalizeType(key).value); + obj[key](req, this, next); + } else if (fn) { + fn(); + } else { + var err = new Error('Not Acceptable'); + err.status = err.statusCode = 406; + err.types = normalizeTypes(keys).map(function(o){ return o.value }); + next(err); } - // inspect [[Class]] for objects - return toString.call(obj) - .replace(objectRegExp, '$1'); -} + return this; +}; /** - * Match path to a layer. + * Set _Content-Disposition_ header to _attachment_ with optional `filename`. * - * @param {Layer} layer - * @param {string} path - * @private + * @param {String} filename + * @return {ServerResponse} + * @public */ -function matchLayer(layer, path) { - try { - return layer.match(path); - } catch (err) { - return err; - } -} - -// merge params with parent params -function mergeParams(params, parent) { - if (typeof parent !== 'object' || !parent) { - return params; - } - - // make copy of parent for base - var obj = mixin({}, parent); - - // simple non-numeric merging - if (!(0 in params) || !(0 in parent)) { - return mixin(obj, params); +res.attachment = function attachment(filename) { + if (filename) { + this.type(extname(filename)); } - var i = 0; - var o = 0; + this.set('Content-Disposition', contentDisposition(filename)); - // determine numeric gaps - while (i in params) { - i++; - } + return this; +}; - while (o in parent) { - o++; - } +/** + * Append additional header `field` with value `val`. + * + * Example: + * + * res.append('Link', ['', '']); + * res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly'); + * res.append('Warning', '199 Miscellaneous warning'); + * + * @param {String} field + * @param {String|Array} val + * @return {ServerResponse} for chaining + * @public + */ - // offset numeric indices in params before merge - for (i--; i >= 0; i--) { - params[i + o] = params[i]; +res.append = function append(field, val) { + var prev = this.get(field); + var value = val; - // create holes for the merge when necessary - if (i < o) { - delete params[i]; - } + if (prev) { + // concat the new and prev vals + value = Array.isArray(prev) ? prev.concat(val) + : Array.isArray(val) ? [prev].concat(val) + : [prev, val] } - return mixin(obj, params); -} + return this.set(field, value); +}; -// restore obj props after function -function restore(fn, obj) { - var props = new Array(arguments.length - 2); - var vals = new Array(arguments.length - 2); +/** + * Set header `field` to `val`, or pass + * an object of header fields. + * + * Examples: + * + * res.set('Foo', ['bar', 'baz']); + * res.set('Accept', 'application/json'); + * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' }); + * + * Aliased as `res.header()`. + * + * @param {String|Object} field + * @param {String|Array} val + * @return {ServerResponse} for chaining + * @public + */ - for (var i = 0; i < props.length; i++) { - props[i] = arguments[i + 2]; - vals[i] = obj[props[i]]; - } +res.set = +res.header = function header(field, val) { + if (arguments.length === 2) { + var value = Array.isArray(val) + ? val.map(String) + : String(val); - return function () { - // restore vals - for (var i = 0; i < props.length; i++) { - obj[props[i]] = vals[i]; + // add charset to content-type + if (field.toLowerCase() === 'content-type') { + if (Array.isArray(value)) { + throw new TypeError('Content-Type cannot be set to an Array'); + } + if (!charsetRegExp.test(value)) { + var charset = mime.charsets.lookup(value.split(';')[0]); + if (charset) value += '; charset=' + charset.toLowerCase(); + } } - return fn.apply(this, arguments); - }; -} - -// send an OPTIONS response -function sendOptionsResponse(res, options, next) { - try { - var body = options.join(','); - res.set('Allow', body); - res.send(body); - } catch (err) { - next(err); - } -} - -// wrap a function -function wrap(old, fn) { - return function proxy() { - var args = new Array(arguments.length + 1); - - args[0] = old; - for (var i = 0, len = arguments.length; i < len; i++) { - args[i + 1] = arguments[i]; + this.setHeader(field, value); + } else { + for (var key in field) { + this.set(key, field[key]); } - - fn.apply(this, args); - }; -} - - -/***/ }), - -/***/ 25624: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -/*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2013 Roman Shtylman - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ - - + } + return this; +}; /** - * Module dependencies. - * @private + * Get value for header `field`. + * + * @param {String} field + * @return {String} + * @public */ -var pathRegexp = __nccwpck_require__(37819); -var debug = __nccwpck_require__(52529)('express:router:layer'); +res.get = function(field){ + return this.getHeader(field); +}; /** - * Module variables. - * @private + * Clear cookie `name`. + * + * @param {String} name + * @param {Object} [options] + * @return {ServerResponse} for chaining + * @public */ -var hasOwnProperty = Object.prototype.hasOwnProperty; +res.clearCookie = function clearCookie(name, options) { + var opts = merge({ expires: new Date(1), path: '/' }, options); + + return this.cookie(name, '', opts); +}; /** - * Module exports. + * Set cookie `name` to `value`, with the given `options`. + * + * Options: + * + * - `maxAge` max-age in milliseconds, converted to `expires` + * - `signed` sign the cookie + * - `path` defaults to "/" + * + * Examples: + * + * // "Remember Me" for 15 minutes + * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true }); + * + * // same as above + * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true }) + * + * @param {String} name + * @param {String|Object} value + * @param {Object} [options] + * @return {ServerResponse} for chaining * @public */ -module.exports = Layer; +res.cookie = function (name, value, options) { + var opts = merge({}, options); + var secret = this.req.secret; + var signed = opts.signed; -function Layer(path, options, fn) { - if (!(this instanceof Layer)) { - return new Layer(path, options, fn); + if (signed && !secret) { + throw new Error('cookieParser("secret") required for signed cookies'); } - debug('new %o', path) - var opts = options || {}; - - this.handle = fn; - this.name = fn.name || ''; - this.params = undefined; - this.path = undefined; - this.regexp = pathRegexp(path, this.keys = [], opts); - - // set fast path flags - this.regexp.fast_star = path === '*' - this.regexp.fast_slash = path === '/' && opts.end === false -} - -/** - * Handle the error for the layer. - * - * @param {Error} error - * @param {Request} req - * @param {Response} res - * @param {function} next - * @api private - */ + var val = typeof value === 'object' + ? 'j:' + JSON.stringify(value) + : String(value); -Layer.prototype.handle_error = function handle_error(error, req, res, next) { - var fn = this.handle; + if (signed) { + val = 's:' + sign(val, secret); + } - if (fn.length !== 4) { - // not a standard error handler - return next(error); + if ('maxAge' in opts) { + opts.expires = new Date(Date.now() + opts.maxAge); + opts.maxAge /= 1000; } - try { - fn(error, req, res, next); - } catch (err) { - next(err); + if (opts.path == null) { + opts.path = '/'; } + + this.append('Set-Cookie', cookie.serialize(name, String(val), opts)); + + return this; }; /** - * Handle the request for the layer. + * Set the location header to `url`. * - * @param {Request} req - * @param {Response} res - * @param {function} next - * @api private + * The given `url` can also be "back", which redirects + * to the _Referrer_ or _Referer_ headers or "/". + * + * Examples: + * + * res.location('/foo/bar').; + * res.location('http://example.com'); + * res.location('../login'); + * + * @param {String} url + * @return {ServerResponse} for chaining + * @public */ -Layer.prototype.handle_request = function handle(req, res, next) { - var fn = this.handle; +res.location = function location(url) { + var loc = url; - if (fn.length > 3) { - // not a standard request handler - return next(); + // "back" is an alias for the referrer + if (url === 'back') { + loc = this.req.get('Referrer') || '/'; } - try { - fn(req, res, next); - } catch (err) { - next(err); - } + // set location + return this.set('Location', encodeUrl(loc)); }; /** - * Check if this route matches `path`, if so - * populate `.params`. + * Redirect to the given `url` with optional response `status` + * defaulting to 302. * - * @param {String} path - * @return {Boolean} - * @api private + * The resulting `url` is determined by `res.location()`, so + * it will play nicely with mounted apps, relative paths, + * `"back"` etc. + * + * Examples: + * + * res.redirect('/foo/bar'); + * res.redirect('http://example.com'); + * res.redirect(301, 'http://example.com'); + * res.redirect('../login'); // /blog/post/1 -> /blog/login + * + * @public */ -Layer.prototype.match = function match(path) { - var match - - if (path != null) { - // fast path non-ending match for / (any path matches) - if (this.regexp.fast_slash) { - this.params = {} - this.path = '' - return true - } +res.redirect = function redirect(url) { + var address = url; + var body; + var status = 302; - // fast path for * (everything matched in a param) - if (this.regexp.fast_star) { - this.params = {'0': decode_param(path)} - this.path = path - return true + // allow status / url + if (arguments.length === 2) { + if (typeof arguments[0] === 'number') { + status = arguments[0]; + address = arguments[1]; + } else { + deprecate('res.redirect(url, status): Use res.redirect(status, url) instead'); + status = arguments[1]; } - - // match the path - match = this.regexp.exec(path) - } - - if (!match) { - this.params = undefined; - this.path = undefined; - return false; } - // store values - this.params = {}; - this.path = match[0] + // Set location header + address = this.location(address).get('Location'); - var keys = this.keys; - var params = this.params; + // Support text/{plain,html} by default + this.format({ + text: function(){ + body = statuses[status] + '. Redirecting to ' + address + }, - for (var i = 1; i < match.length; i++) { - var key = keys[i - 1]; - var prop = key.name; - var val = decode_param(match[i]) + html: function(){ + var u = escapeHtml(address); + body = '

' + statuses[status] + '. Redirecting to ' + u + '

' + }, - if (val !== undefined || !(hasOwnProperty.call(params, prop))) { - params[prop] = val; + default: function(){ + body = ''; } - } + }); - return true; -}; + // Respond + this.statusCode = status; + this.set('Content-Length', Buffer.byteLength(body)); + + if (this.req.method === 'HEAD') { + this.end(); + } else { + this.end(body); + } +}; /** - * Decode param value. + * Add `field` to Vary. If already present in the Vary set, then + * this call is simply ignored. * - * @param {string} val - * @return {string} - * @private + * @param {Array|String} field + * @return {ServerResponse} for chaining + * @public */ -function decode_param(val) { - if (typeof val !== 'string' || val.length === 0) { - return val; +res.vary = function(field){ + // checks for back-compat + if (!field || (Array.isArray(field) && !field.length)) { + deprecate('res.vary(): Provide a field name'); + return this; } - try { - return decodeURIComponent(val); - } catch (err) { - if (err instanceof URIError) { - err.message = 'Failed to decode param \'' + val + '\''; - err.status = err.statusCode = 400; - } + vary(this, field); - throw err; + return this; +}; + +/** + * Render `view` with the given `options` and optional callback `fn`. + * When a callback function is given a response will _not_ be made + * automatically, otherwise a response of _200_ and _text/html_ is given. + * + * Options: + * + * - `cache` boolean hinting to the engine it should cache + * - `filename` filename of the view being rendered + * + * @public + */ + +res.render = function render(view, options, callback) { + var app = this.req.app; + var done = callback; + var opts = options || {}; + var req = this.req; + var self = this; + + // support callback function as second arg + if (typeof options === 'function') { + done = options; + opts = {}; + } + + // merge res.locals + opts._locals = self.locals; + + // default callback to respond + done = done || function (err, str) { + if (err) return req.next(err); + self.send(str); + }; + + // render + app.render(view, opts, done); +}; + +// pipe the send file stream +function sendfile(res, file, options, callback) { + var done = false; + var streaming; + + // request aborted + function onaborted() { + if (done) return; + done = true; + + var err = new Error('Request aborted'); + err.code = 'ECONNABORTED'; + callback(err); + } + + // directory + function ondirectory() { + if (done) return; + done = true; + + var err = new Error('EISDIR, read'); + err.code = 'EISDIR'; + callback(err); + } + + // errors + function onerror(err) { + if (done) return; + done = true; + callback(err); + } + + // ended + function onend() { + if (done) return; + done = true; + callback(); + } + + // file + function onfile() { + streaming = false; + } + + // finished + function onfinish(err) { + if (err && err.code === 'ECONNRESET') return onaborted(); + if (err) return onerror(err); + if (done) return; + + setImmediate(function () { + if (streaming !== false && !done) { + onaborted(); + return; + } + + if (done) return; + done = true; + callback(); + }); + } + + // streaming + function onstream() { + streaming = true; + } + + file.on('directory', ondirectory); + file.on('end', onend); + file.on('error', onerror); + file.on('file', onfile); + file.on('stream', onstream); + onFinished(res, onfinish); + + if (options.headers) { + // set headers on successful transfer + file.on('headers', function headers(res) { + var obj = options.headers; + var keys = Object.keys(obj); + + for (var i = 0; i < keys.length; i++) { + var k = keys[i]; + res.setHeader(k, obj[k]); + } + }); + } + + // pipe + file.pipe(res); +} + +/** + * Stringify JSON, like JSON.stringify, but v8 optimized, with the + * ability to escape characters that can trigger HTML sniffing. + * + * @param {*} value + * @param {function} replaces + * @param {number} spaces + * @param {boolean} escape + * @returns {string} + * @private + */ + +function stringify (value, replacer, spaces, escape) { + // v8 checks arguments.length for optimizing simple call + // https://bugs.chromium.org/p/v8/issues/detail?id=4730 + var json = replacer || spaces + ? JSON.stringify(value, replacer, spaces) + : JSON.stringify(value); + + if (escape && typeof json === 'string') { + json = json.replace(/[<>&]/g, function (c) { + switch (c.charCodeAt(0)) { + case 0x3c: + return '\\u003c' + case 0x3e: + return '\\u003e' + case 0x26: + return '\\u0026' + /* istanbul ignore next: unreachable default */ + default: + return c + } + }) } + + return json } /***/ }), -/***/ 23699: +/***/ 24963: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -39776,26546 +40727,25480 @@ function decode_param(val) { * @private */ -var debug = __nccwpck_require__(52529)('express:router:route'); -var flatten = __nccwpck_require__(62003); +var Route = __nccwpck_require__(23699); var Layer = __nccwpck_require__(25624); var methods = __nccwpck_require__(58752); +var mixin = __nccwpck_require__(44429); +var debug = __nccwpck_require__(52529)('express:router'); +var deprecate = __nccwpck_require__(18883)('express'); +var flatten = __nccwpck_require__(62003); +var parseUrl = __nccwpck_require__(89808); +var setPrototypeOf = __nccwpck_require__(40414) /** * Module variables. * @private */ +var objectRegExp = /^\[object (\S+)\]$/; var slice = Array.prototype.slice; var toString = Object.prototype.toString; /** - * Module exports. + * Initialize a new `Router` with the given `options`. + * + * @param {Object} [options] + * @return {Router} which is an callable function * @public */ -module.exports = Route; +var proto = module.exports = function(options) { + var opts = options || {}; -/** - * Initialize `Route` with the given `path`, - * - * @param {String} path - * @public - */ + function router(req, res, next) { + router.handle(req, res, next); + } -function Route(path) { - this.path = path; - this.stack = []; + // mixin Router class functions + setPrototypeOf(router, proto) - debug('new %o', path) + router.params = {}; + router._params = []; + router.caseSensitive = opts.caseSensitive; + router.mergeParams = opts.mergeParams; + router.strict = opts.strict; + router.stack = []; - // route handlers for various http methods - this.methods = {}; -} + return router; +}; /** - * Determine if the route handles a given method. - * @private + * Map the given param placeholder `name`(s) to the given callback. + * + * Parameter mapping is used to provide pre-conditions to routes + * which use normalized placeholders. For example a _:user_id_ parameter + * could automatically load a user's information from the database without + * any additional code, + * + * The callback uses the same signature as middleware, the only difference + * being that the value of the placeholder is passed, in this case the _id_ + * of the user. Once the `next()` function is invoked, just like middleware + * it will continue on to execute the route, or subsequent parameter functions. + * + * Just like in middleware, you must either respond to the request or call next + * to avoid stalling the request. + * + * app.param('user_id', function(req, res, next, id){ + * User.find(id, function(err, user){ + * if (err) { + * return next(err); + * } else if (!user) { + * return next(new Error('failed to load user')); + * } + * req.user = user; + * next(); + * }); + * }); + * + * @param {String} name + * @param {Function} fn + * @return {app} for chaining + * @public */ -Route.prototype._handles_method = function _handles_method(method) { - if (this.methods._all) { - return true; +proto.param = function param(name, fn) { + // param logic + if (typeof name === 'function') { + deprecate('router.param(fn): Refactor to use path params'); + this._params.push(name); + return; } - var name = method.toLowerCase(); + // apply param functions + var params = this._params; + var len = params.length; + var ret; - if (name === 'head' && !this.methods['head']) { - name = 'get'; + if (name[0] === ':') { + deprecate('router.param(' + JSON.stringify(name) + ', fn): Use router.param(' + JSON.stringify(name.substr(1)) + ', fn) instead'); + name = name.substr(1); } - return Boolean(this.methods[name]); -}; - -/** - * @return {Array} supported HTTP methods - * @private - */ - -Route.prototype._options = function _options() { - var methods = Object.keys(this.methods); - - // append automatic head - if (this.methods.get && !this.methods.head) { - methods.push('head'); + for (var i = 0; i < len; ++i) { + if (ret = params[i](name, fn)) { + fn = ret; + } } - for (var i = 0; i < methods.length; i++) { - // make upper case - methods[i] = methods[i].toUpperCase(); + // ensure we end up with a + // middleware function + if ('function' !== typeof fn) { + throw new Error('invalid param() call for ' + name + ', got ' + fn); } - return methods; + (this.params[name] = this.params[name] || []).push(fn); + return this; }; /** - * dispatch req, res into this route + * Dispatch a req, res into the router. * @private */ -Route.prototype.dispatch = function dispatch(req, res, done) { +proto.handle = function handle(req, res, out) { + var self = this; + + debug('dispatching %s %s', req.method, req.url); + var idx = 0; - var stack = this.stack; - if (stack.length === 0) { - return done(); - } + var protohost = getProtohost(req.url) || '' + var removed = ''; + var slashAdded = false; + var paramcalled = {}; - var method = req.method.toLowerCase(); - if (method === 'head' && !this.methods['head']) { - method = 'get'; + // store options for OPTIONS request + // only used if OPTIONS request + var options = []; + + // middleware and routes + var stack = self.stack; + + // manage inter-router variables + var parentParams = req.params; + var parentUrl = req.baseUrl || ''; + var done = restore(out, req, 'baseUrl', 'next', 'params'); + + // setup next layer + req.next = next; + + // for options requests, respond with a default if nothing else responds + if (req.method === 'OPTIONS') { + done = wrap(done, function(old, err) { + if (err || options.length === 0) return old(err); + sendOptionsResponse(res, options, old); + }); } - req.route = this; + // setup basic req values + req.baseUrl = parentUrl; + req.originalUrl = req.originalUrl || req.url; next(); function next(err) { - // signal to exit route - if (err && err === 'route') { - return done(); - } + var layerError = err === 'route' + ? null + : err; - // signal to exit router - if (err && err === 'router') { - return done(err) + // remove added slash + if (slashAdded) { + req.url = req.url.substr(1); + slashAdded = false; } - var layer = stack[idx++]; - if (!layer) { - return done(err); + // restore altered req.url + if (removed.length !== 0) { + req.baseUrl = parentUrl; + req.url = protohost + removed + req.url.substr(protohost.length); + removed = ''; } - if (layer.method && layer.method !== method) { - return next(err); + // signal to exit router + if (layerError === 'router') { + setImmediate(done, null) + return } - if (err) { - layer.handle_error(err, req, res, next); - } else { - layer.handle_request(req, res, next); + // no more matching layers + if (idx >= stack.length) { + setImmediate(done, layerError); + return; } - } -}; - -/** - * Add a handler for all HTTP verbs to this route. - * - * Behaves just like middleware and can respond or call `next` - * to continue processing. - * - * You can use multiple `.all` call to add multiple handlers. - * - * function check_something(req, res, next){ - * next(); - * }; - * - * function validate_user(req, res, next){ - * next(); - * }; - * - * route - * .all(validate_user) - * .all(check_something) - * .get(function(req, res, next){ - * res.send('hello world'); - * }); - * - * @param {function} handler - * @return {Route} for chaining - * @api public - */ - -Route.prototype.all = function all() { - var handles = flatten(slice.call(arguments)); - for (var i = 0; i < handles.length; i++) { - var handle = handles[i]; + // get pathname of request + var path = getPathname(req); - if (typeof handle !== 'function') { - var type = toString.call(handle); - var msg = 'Route.all() requires a callback function but got a ' + type - throw new TypeError(msg); + if (path == null) { + return done(layerError); } - var layer = Layer('/', {}, handle); - layer.method = undefined; + // find next matching layer + var layer; + var match; + var route; - this.methods._all = true; - this.stack.push(layer); - } + while (match !== true && idx < stack.length) { + layer = stack[idx++]; + match = matchLayer(layer, path); + route = layer.route; - return this; -}; + if (typeof match !== 'boolean') { + // hold on to layerError + layerError = layerError || match; + } -methods.forEach(function(method){ - Route.prototype[method] = function(){ - var handles = flatten(slice.call(arguments)); + if (match !== true) { + continue; + } - for (var i = 0; i < handles.length; i++) { - var handle = handles[i]; + if (!route) { + // process non-route handlers normally + continue; + } - if (typeof handle !== 'function') { - var type = toString.call(handle); - var msg = 'Route.' + method + '() requires a callback function but got a ' + type - throw new Error(msg); + if (layerError) { + // routes do not match with a pending error + match = false; + continue; } - debug('%s %o', method, this.path) + var method = req.method; + var has_method = route._handles_method(method); - var layer = Layer('/', {}, handle); - layer.method = method; + // build up automatic options response + if (!has_method && method === 'OPTIONS') { + appendMethods(options, route._options()); + } - this.methods[method] = true; - this.stack.push(layer); + // don't even bother matching route + if (!has_method && method !== 'HEAD') { + match = false; + continue; + } } - return this; - }; -}); + // no match + if (match !== true) { + return done(layerError); + } + // store route for dispatch on change + if (route) { + req.route = route; + } -/***/ }), - -/***/ 53561: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; -/*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ + // Capture one-time layer values + req.params = self.mergeParams + ? mergeParams(layer.params, parentParams) + : layer.params; + var layerPath = layer.path; + // this should be done for the layer + self.process_params(layer, paramcalled, req, res, function (err) { + if (err) { + return next(layerError || err); + } + if (route) { + return layer.handle_request(req, res, next); + } -/** - * Module dependencies. - * @api private - */ + trim_prefix(layer, layerError, layerPath, path); + }); + } -var Buffer = (__nccwpck_require__(41894).Buffer) -var contentDisposition = __nccwpck_require__(53921); -var contentType = __nccwpck_require__(99915); -var deprecate = __nccwpck_require__(18883)('express'); -var flatten = __nccwpck_require__(62003); -var mime = (__nccwpck_require__(95287).mime); -var etag = __nccwpck_require__(69972); -var proxyaddr = __nccwpck_require__(80140); -var qs = __nccwpck_require__(22760); -var querystring = __nccwpck_require__(63477); + function trim_prefix(layer, layerError, layerPath, path) { + if (layerPath.length !== 0) { + // Validate path is a prefix match + if (layerPath !== path.substr(0, layerPath.length)) { + next(layerError) + return + } -/** - * Return strong ETag for `body`. - * - * @param {String|Buffer} body - * @param {String} [encoding] - * @return {String} - * @api private - */ + // Validate path breaks on a path separator + var c = path[layerPath.length] + if (c && c !== '/' && c !== '.') return next(layerError) -exports.etag = createETagGenerator({ weak: false }) + // Trim off the part of the url that matches the route + // middleware (.use stuff) needs to have the path stripped + debug('trim prefix (%s) from url %s', layerPath, req.url); + removed = layerPath; + req.url = protohost + req.url.substr(protohost.length + removed.length); -/** - * Return weak ETag for `body`. - * - * @param {String|Buffer} body - * @param {String} [encoding] - * @return {String} - * @api private - */ + // Ensure leading slash + if (!protohost && req.url[0] !== '/') { + req.url = '/' + req.url; + slashAdded = true; + } -exports.wetag = createETagGenerator({ weak: true }) + // Setup base URL (no trailing slash) + req.baseUrl = parentUrl + (removed[removed.length - 1] === '/' + ? removed.substring(0, removed.length - 1) + : removed); + } -/** - * Check if `path` looks absolute. - * - * @param {String} path - * @return {Boolean} - * @api private - */ + debug('%s %s : %s', layer.name, layerPath, req.originalUrl); -exports.isAbsolute = function(path){ - if ('/' === path[0]) return true; - if (':' === path[1] && ('\\' === path[2] || '/' === path[2])) return true; // Windows device path - if ('\\\\' === path.substring(0, 2)) return true; // Microsoft Azure absolute path + if (layerError) { + layer.handle_error(layerError, req, res, next); + } else { + layer.handle_request(req, res, next); + } + } }; /** - * Flatten the given `arr`. - * - * @param {Array} arr - * @return {Array} - * @api private + * Process any parameters for the layer. + * @private */ -exports.flatten = deprecate.function(flatten, - 'utils.flatten: use array-flatten npm module instead'); +proto.process_params = function process_params(layer, called, req, res, done) { + var params = this.params; -/** - * Normalize the given `type`, for example "html" becomes "text/html". - * - * @param {String} type - * @return {Object} - * @api private - */ + // captured parameters from the layer, keys and values + var keys = layer.keys; -exports.normalizeType = function(type){ - return ~type.indexOf('/') - ? acceptParams(type) - : { value: mime.lookup(type), params: {} }; -}; + // fast track + if (!keys || keys.length === 0) { + return done(); + } -/** - * Normalize `types`, for example "html" becomes "text/html". - * - * @param {Array} types - * @return {Array} - * @api private - */ + var i = 0; + var name; + var paramIndex = 0; + var key; + var paramVal; + var paramCallbacks; + var paramCalled; -exports.normalizeTypes = function(types){ - var ret = []; + // process params in order + // param callbacks can be async + function param(err) { + if (err) { + return done(err); + } - for (var i = 0; i < types.length; ++i) { - ret.push(exports.normalizeType(types[i])); - } + if (i >= keys.length ) { + return done(); + } - return ret; -}; + paramIndex = 0; + key = keys[i++]; + name = key.name; + paramVal = req.params[name]; + paramCallbacks = params[name]; + paramCalled = called[name]; -/** - * Generate Content-Disposition header appropriate for the filename. - * non-ascii filenames are urlencoded and a filename* parameter is added - * - * @param {String} filename - * @return {String} - * @api private - */ + if (paramVal === undefined || !paramCallbacks) { + return param(); + } -exports.contentDisposition = deprecate.function(contentDisposition, - 'utils.contentDisposition: use content-disposition npm module instead'); + // param previously called with same value or error occurred + if (paramCalled && (paramCalled.match === paramVal + || (paramCalled.error && paramCalled.error !== 'route'))) { + // restore value + req.params[name] = paramCalled.value; -/** - * Parse accept params `str` returning an - * object with `.value`, `.quality` and `.params`. - * also includes `.originalIndex` for stable sorting - * - * @param {String} str - * @return {Object} - * @api private - */ + // next param + return param(paramCalled.error); + } -function acceptParams(str, index) { - var parts = str.split(/ *; */); - var ret = { value: parts[0], quality: 1, params: {}, originalIndex: index }; + called[name] = paramCalled = { + error: null, + match: paramVal, + value: paramVal + }; - for (var i = 1; i < parts.length; ++i) { - var pms = parts[i].split(/ *= */); - if ('q' === pms[0]) { - ret.quality = parseFloat(pms[1]); - } else { - ret.params[pms[0]] = pms[1]; - } + paramCallback(); } - return ret; -} + // single param callbacks + function paramCallback(err) { + var fn = paramCallbacks[paramIndex++]; -/** - * Compile "etag" value to function. - * - * @param {Boolean|String|Function} val - * @return {Function} - * @api private - */ + // store updated value + paramCalled.value = req.params[key.name]; -exports.compileETag = function(val) { - var fn; + if (err) { + // store error + paramCalled.error = err; + param(err); + return; + } - if (typeof val === 'function') { - return val; - } + if (!fn) return param(); - switch (val) { - case true: - case 'weak': - fn = exports.wetag; - break; - case false: - break; - case 'strong': - fn = exports.etag; - break; - default: - throw new TypeError('unknown value for etag function: ' + val); + try { + fn(req, res, paramCallback, paramVal, key.name); + } catch (e) { + paramCallback(e); + } } - return fn; -} + param(); +}; /** - * Compile "query parser" value to function. + * Use the given middleware function, with optional path, defaulting to "/". * - * @param {String|Function} val - * @return {Function} - * @api private + * Use (like `.all`) will run for any http METHOD, but it will not add + * handlers for those methods so OPTIONS requests will not consider `.use` + * functions even if they could respond. + * + * The other difference is that _route_ path is stripped and not visible + * to the handler function. The main effect of this feature is that mounted + * handlers can operate without any code changes regardless of the "prefix" + * pathname. + * + * @public */ -exports.compileQueryParser = function compileQueryParser(val) { - var fn; +proto.use = function use(fn) { + var offset = 0; + var path = '/'; - if (typeof val === 'function') { - return val; + // default path to '/' + // disambiguate router.use([fn]) + if (typeof fn !== 'function') { + var arg = fn; + + while (Array.isArray(arg) && arg.length !== 0) { + arg = arg[0]; + } + + // first arg is the path + if (typeof arg !== 'function') { + offset = 1; + path = fn; + } } - switch (val) { - case true: - case 'simple': - fn = querystring.parse; - break; - case false: - fn = newObject; - break; - case 'extended': - fn = parseExtendedQueryString; - break; - default: - throw new TypeError('unknown value for query parser function: ' + val); + var callbacks = flatten(slice.call(arguments, offset)); + + if (callbacks.length === 0) { + throw new TypeError('Router.use() requires a middleware function') } - return fn; -} + for (var i = 0; i < callbacks.length; i++) { + var fn = callbacks[i]; -/** - * Compile "proxy trust" value to function. - * - * @param {Boolean|String|Number|Array|Function} val - * @return {Function} - * @api private - */ + if (typeof fn !== 'function') { + throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn)) + } -exports.compileTrust = function(val) { - if (typeof val === 'function') return val; + // add the middleware + debug('use %o %s', path, fn.name || '') - if (val === true) { - // Support plain true/false - return function(){ return true }; - } + var layer = new Layer(path, { + sensitive: this.caseSensitive, + strict: false, + end: false + }, fn); - if (typeof val === 'number') { - // Support trusting hop count - return function(a, i){ return i < val }; - } + layer.route = undefined; - if (typeof val === 'string') { - // Support comma-separated values - val = val.split(/ *, */); + this.stack.push(layer); } - return proxyaddr.compile(val || []); -} + return this; +}; /** - * Set the charset in a given Content-Type string. + * Create a new Route for the given path. * - * @param {String} type - * @param {String} charset - * @return {String} - * @api private + * Each route contains a separate middleware stack and VERB handlers. + * + * See the Route api documentation for details on adding handlers + * and middleware to routes. + * + * @param {String} path + * @return {Route} + * @public */ -exports.setCharset = function setCharset(type, charset) { - if (!type || !charset) { - return type; - } +proto.route = function route(path) { + var route = new Route(path); - // parse type - var parsed = contentType.parse(type); + var layer = new Layer(path, { + sensitive: this.caseSensitive, + strict: this.strict, + end: true + }, route.dispatch.bind(route)); - // set charset - parsed.parameters.charset = charset; + layer.route = route; - // format type - return contentType.format(parsed); + this.stack.push(layer); + return route; }; -/** - * Create an ETag generator function, generating ETags with - * the given options. - * - * @param {object} options - * @return {function} - * @private - */ +// create Router#VERB functions +methods.concat('all').forEach(function(method){ + proto[method] = function(path){ + var route = this.route(path) + route[method].apply(route, slice.call(arguments, 1)); + return this; + }; +}); -function createETagGenerator (options) { - return function generateETag (body, encoding) { - var buf = !Buffer.isBuffer(body) - ? Buffer.from(body, encoding) - : body +// append methods to a list of methods +function appendMethods(list, addition) { + for (var i = 0; i < addition.length; i++) { + var method = addition[i]; + if (list.indexOf(method) === -1) { + list.push(method); + } + } +} - return etag(buf, options) +// get pathname of request +function getPathname(req) { + try { + return parseUrl(req).pathname; + } catch (err) { + return undefined; } } -/** - * Parse an extended query string with qs. - * - * @return {Object} - * @private - */ +// Get get protocol + host for a URL +function getProtohost(url) { + if (typeof url !== 'string' || url.length === 0 || url[0] === '/') { + return undefined + } -function parseExtendedQueryString(str) { - return qs.parse(str, { - allowPrototypes: true - }); + var searchIndex = url.indexOf('?') + var pathLength = searchIndex !== -1 + ? searchIndex + : url.length + var fqdnIndex = url.substr(0, pathLength).indexOf('://') + + return fqdnIndex !== -1 + ? url.substr(0, url.indexOf('/', 3 + fqdnIndex)) + : undefined +} + +// get type for error message +function gettype(obj) { + var type = typeof obj; + + if (type !== 'object') { + return type; + } + + // inspect [[Class]] for objects + return toString.call(obj) + .replace(objectRegExp, '$1'); } /** - * Return new empty object. + * Match path to a layer. * - * @return {Object} - * @api private + * @param {Layer} layer + * @param {string} path + * @private */ -function newObject() { - return {}; +function matchLayer(layer, path) { + try { + return layer.match(path); + } catch (err) { + return err; + } } +// merge params with parent params +function mergeParams(params, parent) { + if (typeof parent !== 'object' || !parent) { + return params; + } -/***/ }), + // make copy of parent for base + var obj = mixin({}, parent); -/***/ 99209: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // simple non-numeric merging + if (!(0 in params) || !(0 in parent)) { + return mixin(obj, params); + } -"use strict"; -/*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2013 Roman Shtylman - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ + var i = 0; + var o = 0; + // determine numeric gaps + while (i in params) { + i++; + } + while (o in parent) { + o++; + } -/** - * Module dependencies. - * @private - */ - -var debug = __nccwpck_require__(52529)('express:view'); -var path = __nccwpck_require__(71017); -var fs = __nccwpck_require__(57147); - -/** - * Module variables. - * @private - */ - -var dirname = path.dirname; -var basename = path.basename; -var extname = path.extname; -var join = path.join; -var resolve = path.resolve; - -/** - * Module exports. - * @public - */ - -module.exports = View; + // offset numeric indices in params before merge + for (i--; i >= 0; i--) { + params[i + o] = params[i]; -/** - * Initialize a new `View` with the given `name`. - * - * Options: - * - * - `defaultEngine` the default template engine name - * - `engines` template engine require() cache - * - `root` root path for view lookup - * - * @param {string} name - * @param {object} options - * @public - */ + // create holes for the merge when necessary + if (i < o) { + delete params[i]; + } + } -function View(name, options) { - var opts = options || {}; + return mixin(obj, params); +} - this.defaultEngine = opts.defaultEngine; - this.ext = extname(name); - this.name = name; - this.root = opts.root; +// restore obj props after function +function restore(fn, obj) { + var props = new Array(arguments.length - 2); + var vals = new Array(arguments.length - 2); - if (!this.ext && !this.defaultEngine) { - throw new Error('No default engine was specified and no extension was provided.'); + for (var i = 0; i < props.length; i++) { + props[i] = arguments[i + 2]; + vals[i] = obj[props[i]]; } - var fileName = name; + return function () { + // restore vals + for (var i = 0; i < props.length; i++) { + obj[props[i]] = vals[i]; + } - if (!this.ext) { - // get extension from default engine name - this.ext = this.defaultEngine[0] !== '.' - ? '.' + this.defaultEngine - : this.defaultEngine; + return fn.apply(this, arguments); + }; +} - fileName += this.ext; +// send an OPTIONS response +function sendOptionsResponse(res, options, next) { + try { + var body = options.join(','); + res.set('Allow', body); + res.send(body); + } catch (err) { + next(err); } +} - if (!opts.engines[this.ext]) { - // load engine - var mod = this.ext.substr(1) - debug('require "%s"', mod) - - // default engine export - var fn = require(mod).__express +// wrap a function +function wrap(old, fn) { + return function proxy() { + var args = new Array(arguments.length + 1); - if (typeof fn !== 'function') { - throw new Error('Module "' + mod + '" does not provide a view engine.') + args[0] = old; + for (var i = 0, len = arguments.length; i < len; i++) { + args[i + 1] = arguments[i]; } - opts.engines[this.ext] = fn - } - - // store loaded engine - this.engine = opts.engines[this.ext]; - - // lookup path - this.path = this.lookup(fileName); + fn.apply(this, args); + }; } -/** - * Lookup view by the given `name` - * - * @param {string} name - * @private - */ - -View.prototype.lookup = function lookup(name) { - var path; - var roots = [].concat(this.root); - debug('lookup "%s"', name); +/***/ }), - for (var i = 0; i < roots.length && !path; i++) { - var root = roots[i]; +/***/ 25624: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // resolve the path - var loc = resolve(root, name); - var dir = dirname(loc); - var file = basename(loc); +"use strict"; +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ - // resolve the file - path = this.resolve(dir, file); - } - return path; -}; /** - * Render with the given options. - * - * @param {object} options - * @param {function} callback + * Module dependencies. * @private */ -View.prototype.render = function render(options, callback) { - debug('render "%s"', this.path); - this.engine(this.path, options, callback); -}; +var pathRegexp = __nccwpck_require__(37819); +var debug = __nccwpck_require__(52529)('express:router:layer'); /** - * Resolve the file within the given directory. - * - * @param {string} dir - * @param {string} file + * Module variables. * @private */ -View.prototype.resolve = function resolve(dir, file) { - var ext = this.ext; - - // . - var path = join(dir, file); - var stat = tryStat(path); - - if (stat && stat.isFile()) { - return path; - } - - // /index. - path = join(dir, basename(file, ext), 'index' + ext); - stat = tryStat(path); - - if (stat && stat.isFile()) { - return path; - } -}; +var hasOwnProperty = Object.prototype.hasOwnProperty; /** - * Return a stat, maybe. - * - * @param {string} path - * @return {fs.Stats} - * @private + * Module exports. + * @public */ -function tryStat(path) { - debug('stat "%s"', path); +module.exports = Layer; - try { - return fs.statSync(path); - } catch (e) { - return undefined; +function Layer(path, options, fn) { + if (!(this instanceof Layer)) { + return new Layer(path, options, fn); } -} + debug('new %o', path) + var opts = options || {}; -/***/ }), + this.handle = fn; + this.name = fn.name || ''; + this.params = undefined; + this.path = undefined; + this.regexp = pathRegexp(path, this.keys = [], opts); -/***/ 36654: -/***/ ((module, exports, __nccwpck_require__) => { + // set fast path flags + this.regexp.fast_star = path === '*' + this.regexp.fast_slash = path === '/' && opts.end === false +} /** - * This is the web browser implementation of `debug()`. + * Handle the error for the layer. * - * Expose `debug()` as the module. + * @param {Error} error + * @param {Request} req + * @param {Response} res + * @param {function} next + * @api private */ -exports = module.exports = __nccwpck_require__(86991); -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.storage = 'undefined' != typeof chrome - && 'undefined' != typeof chrome.storage - ? chrome.storage.local - : localstorage(); +Layer.prototype.handle_error = function handle_error(error, req, res, next) { + var fn = this.handle; -/** - * Colors. - */ + if (fn.length !== 4) { + // not a standard error handler + return next(error); + } -exports.colors = [ - 'lightseagreen', - 'forestgreen', - 'goldenrod', - 'dodgerblue', - 'darkorchid', - 'crimson' -]; + try { + fn(error, req, res, next); + } catch (err) { + next(err); + } +}; /** - * Currently only WebKit-based Web Inspectors, Firefox >= v31, - * and the Firebug extension (any Firefox version) are known - * to support "%c" CSS customizations. + * Handle the request for the layer. * - * TODO: add a `localStorage` variable to explicitly enable/disable colors + * @param {Request} req + * @param {Response} res + * @param {function} next + * @api private */ -function useColors() { - // NB: In an Electron preload script, document will be defined but not fully - // initialized. Since we know we're in Chrome, we'll just detect this case - // explicitly - if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') { - return true; - } - - // is webkit? http://stackoverflow.com/a/16459606/376773 - // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 - return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || - // is firebug? http://stackoverflow.com/a/398120/376773 - (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || - // is firefox >= v31? - // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || - // double check webkit in userAgent just in case we are in a worker - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); -} +Layer.prototype.handle_request = function handle(req, res, next) { + var fn = this.handle; -/** - * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. - */ + if (fn.length > 3) { + // not a standard request handler + return next(); + } -exports.formatters.j = function(v) { try { - return JSON.stringify(v); + fn(req, res, next); } catch (err) { - return '[UnexpectedJSONParseError]: ' + err.message; + next(err); } }; - /** - * Colorize log arguments if enabled. + * Check if this route matches `path`, if so + * populate `.params`. * - * @api public + * @param {String} path + * @return {Boolean} + * @api private */ -function formatArgs(args) { - var useColors = this.useColors; - - args[0] = (useColors ? '%c' : '') - + this.namespace - + (useColors ? ' %c' : ' ') - + args[0] - + (useColors ? '%c ' : ' ') - + '+' + exports.humanize(this.diff); - - if (!useColors) return; +Layer.prototype.match = function match(path) { + var match - var c = 'color: ' + this.color; - args.splice(1, 0, c, 'color: inherit') + if (path != null) { + // fast path non-ending match for / (any path matches) + if (this.regexp.fast_slash) { + this.params = {} + this.path = '' + return true + } - // the final "%c" is somewhat tricky, because there could be other - // arguments passed either before or after the %c, so we need to - // figure out the correct index to insert the CSS into - var index = 0; - var lastC = 0; - args[0].replace(/%[a-zA-Z%]/g, function(match) { - if ('%%' === match) return; - index++; - if ('%c' === match) { - // we only are interested in the *last* %c - // (the user may have provided their own) - lastC = index; + // fast path for * (everything matched in a param) + if (this.regexp.fast_star) { + this.params = {'0': decode_param(path)} + this.path = path + return true } - }); - args.splice(lastC, 0, c); -} + // match the path + match = this.regexp.exec(path) + } -/** - * Invokes `console.log()` when available. - * No-op when `console.log` is not a "function". - * - * @api public - */ + if (!match) { + this.params = undefined; + this.path = undefined; + return false; + } -function log() { - // this hackery is required for IE8/9, where - // the `console.log` function doesn't have 'apply' - return 'object' === typeof console - && console.log - && Function.prototype.apply.call(console.log, console, arguments); -} + // store values + this.params = {}; + this.path = match[0] -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ + var keys = this.keys; + var params = this.params; -function save(namespaces) { - try { - if (null == namespaces) { - exports.storage.removeItem('debug'); - } else { - exports.storage.debug = namespaces; + for (var i = 1; i < match.length; i++) { + var key = keys[i - 1]; + var prop = key.name; + var val = decode_param(match[i]) + + if (val !== undefined || !(hasOwnProperty.call(params, prop))) { + params[prop] = val; } - } catch(e) {} -} + } + + return true; +}; /** - * Load `namespaces`. + * Decode param value. * - * @return {String} returns the previously persisted debug modes - * @api private + * @param {string} val + * @return {string} + * @private */ -function load() { - var r; +function decode_param(val) { + if (typeof val !== 'string' || val.length === 0) { + return val; + } + try { - r = exports.storage.debug; - } catch(e) {} + return decodeURIComponent(val); + } catch (err) { + if (err instanceof URIError) { + err.message = 'Failed to decode param \'' + val + '\''; + err.status = err.statusCode = 400; + } - // If debug isn't set in LS, and we're in Electron, try to load $DEBUG - if (!r && typeof process !== 'undefined' && 'env' in process) { - r = process.env.DEBUG; + throw err; } - - return r; } -/** - * Enable namespaces listed in `localStorage.debug` initially. - */ -exports.enable(load()); +/***/ }), -/** - * Localstorage attempts to return the localstorage. - * - * This is necessary because safari throws - * when a user disables cookies/localstorage - * and you attempt to access it. - * - * @return {LocalStorage} - * @api private - */ +/***/ 23699: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -function localstorage() { - try { - return window.localStorage; - } catch (e) {} -} +"use strict"; +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ -/***/ }), -/***/ 86991: -/***/ ((module, exports, __nccwpck_require__) => { +/** + * Module dependencies. + * @private + */ +var debug = __nccwpck_require__(52529)('express:router:route'); +var flatten = __nccwpck_require__(62003); +var Layer = __nccwpck_require__(25624); +var methods = __nccwpck_require__(58752); /** - * This is the common logic for both the Node.js and web browser - * implementations of `debug()`. - * - * Expose `debug()` as the module. + * Module variables. + * @private */ -exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; -exports.coerce = coerce; -exports.disable = disable; -exports.enable = enable; -exports.enabled = enabled; -exports.humanize = __nccwpck_require__(27025); +var slice = Array.prototype.slice; +var toString = Object.prototype.toString; /** - * The currently active debug mode names, and names to skip. + * Module exports. + * @public */ -exports.names = []; -exports.skips = []; +module.exports = Route; /** - * Map of special "%n" handling functions, for the debug "format" argument. + * Initialize `Route` with the given `path`, * - * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + * @param {String} path + * @public */ -exports.formatters = {}; +function Route(path) { + this.path = path; + this.stack = []; -/** - * Previous log timestamp. - */ + debug('new %o', path) -var prevTime; + // route handlers for various http methods + this.methods = {}; +} /** - * Select a color. - * @param {String} namespace - * @return {Number} - * @api private + * Determine if the route handles a given method. + * @private */ -function selectColor(namespace) { - var hash = 0, i; +Route.prototype._handles_method = function _handles_method(method) { + if (this.methods._all) { + return true; + } - for (i in namespace) { - hash = ((hash << 5) - hash) + namespace.charCodeAt(i); - hash |= 0; // Convert to 32bit integer + var name = method.toLowerCase(); + + if (name === 'head' && !this.methods['head']) { + name = 'get'; } - return exports.colors[Math.abs(hash) % exports.colors.length]; -} + return Boolean(this.methods[name]); +}; /** - * Create a debugger with the given `namespace`. - * - * @param {String} namespace - * @return {Function} - * @api public + * @return {Array} supported HTTP methods + * @private */ -function createDebug(namespace) { - - function debug() { - // disabled? - if (!debug.enabled) return; - - var self = debug; - - // set `diff` timestamp - var curr = +new Date(); - var ms = curr - (prevTime || curr); - self.diff = ms; - self.prev = prevTime; - self.curr = curr; - prevTime = curr; - - // turn the `arguments` into a proper Array - var args = new Array(arguments.length); - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i]; - } - - args[0] = exports.coerce(args[0]); +Route.prototype._options = function _options() { + var methods = Object.keys(this.methods); - if ('string' !== typeof args[0]) { - // anything else let's inspect with %O - args.unshift('%O'); - } + // append automatic head + if (this.methods.get && !this.methods.head) { + methods.push('head'); + } - // apply any `formatters` transformations - var index = 0; - args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) { - // if we encounter an escaped % then don't increase the array index - if (match === '%%') return match; - index++; - var formatter = exports.formatters[format]; - if ('function' === typeof formatter) { - var val = args[index]; - match = formatter.call(self, val); + for (var i = 0; i < methods.length; i++) { + // make upper case + methods[i] = methods[i].toUpperCase(); + } - // now we need to remove `args[index]` since it's inlined in the `format` - args.splice(index, 1); - index--; - } - return match; - }); + return methods; +}; - // apply env-specific formatting (colors, etc.) - exports.formatArgs.call(self, args); +/** + * dispatch req, res into this route + * @private + */ - var logFn = debug.log || exports.log || console.log.bind(console); - logFn.apply(self, args); +Route.prototype.dispatch = function dispatch(req, res, done) { + var idx = 0; + var stack = this.stack; + if (stack.length === 0) { + return done(); } - debug.namespace = namespace; - debug.enabled = exports.enabled(namespace); - debug.useColors = exports.useColors(); - debug.color = selectColor(namespace); - - // env-specific initialization logic for debug instances - if ('function' === typeof exports.init) { - exports.init(debug); + var method = req.method.toLowerCase(); + if (method === 'head' && !this.methods['head']) { + method = 'get'; } - return debug; -} + req.route = this; -/** - * Enables a debug mode by namespaces. This can include modes - * separated by a colon and wildcards. - * - * @param {String} namespaces - * @api public - */ + next(); -function enable(namespaces) { - exports.save(namespaces); + function next(err) { + // signal to exit route + if (err && err === 'route') { + return done(); + } - exports.names = []; - exports.skips = []; + // signal to exit router + if (err && err === 'router') { + return done(err) + } - var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); - var len = split.length; + var layer = stack[idx++]; + if (!layer) { + return done(err); + } - for (var i = 0; i < len; i++) { - if (!split[i]) continue; // ignore empty strings - namespaces = split[i].replace(/\*/g, '.*?'); - if (namespaces[0] === '-') { - exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); + if (layer.method && layer.method !== method) { + return next(err); + } + + if (err) { + layer.handle_error(err, req, res, next); } else { - exports.names.push(new RegExp('^' + namespaces + '$')); + layer.handle_request(req, res, next); } } -} +}; /** - * Disable debug output. + * Add a handler for all HTTP verbs to this route. + * + * Behaves just like middleware and can respond or call `next` + * to continue processing. + * + * You can use multiple `.all` call to add multiple handlers. + * + * function check_something(req, res, next){ + * next(); + * }; + * + * function validate_user(req, res, next){ + * next(); + * }; + * + * route + * .all(validate_user) + * .all(check_something) + * .get(function(req, res, next){ + * res.send('hello world'); + * }); * + * @param {function} handler + * @return {Route} for chaining * @api public */ -function disable() { - exports.enable(''); -} +Route.prototype.all = function all() { + var handles = flatten(slice.call(arguments)); -/** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ + for (var i = 0; i < handles.length; i++) { + var handle = handles[i]; -function enabled(name) { - var i, len; - for (i = 0, len = exports.skips.length; i < len; i++) { - if (exports.skips[i].test(name)) { - return false; - } - } - for (i = 0, len = exports.names.length; i < len; i++) { - if (exports.names[i].test(name)) { - return true; + if (typeof handle !== 'function') { + var type = toString.call(handle); + var msg = 'Route.all() requires a callback function but got a ' + type + throw new TypeError(msg); } + + var layer = Layer('/', {}, handle); + layer.method = undefined; + + this.methods._all = true; + this.stack.push(layer); } - return false; -} -/** - * Coerce `val`. - * - * @param {Mixed} val - * @return {Mixed} - * @api private - */ + return this; +}; -function coerce(val) { - if (val instanceof Error) return val.stack || val.message; - return val; -} +methods.forEach(function(method){ + Route.prototype[method] = function(){ + var handles = flatten(slice.call(arguments)); + + for (var i = 0; i < handles.length; i++) { + var handle = handles[i]; + if (typeof handle !== 'function') { + var type = toString.call(handle); + var msg = 'Route.' + method + '() requires a callback function but got a ' + type + throw new Error(msg); + } -/***/ }), + debug('%s %o', method, this.path) -/***/ 52529: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + var layer = Layer('/', {}, handle); + layer.method = method; -/** - * Detect Electron renderer process, which is node, but we should - * treat as a browser. - */ + this.methods[method] = true; + this.stack.push(layer); + } -if (typeof process !== 'undefined' && process.type === 'renderer') { - module.exports = __nccwpck_require__(36654); -} else { - module.exports = __nccwpck_require__(25696); -} + return this; + }; +}); /***/ }), -/***/ 25696: -/***/ ((module, exports, __nccwpck_require__) => { +/***/ 53561: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + + /** * Module dependencies. + * @api private */ -var tty = __nccwpck_require__(76224); -var util = __nccwpck_require__(73837); +var Buffer = (__nccwpck_require__(21867).Buffer) +var contentDisposition = __nccwpck_require__(53921); +var contentType = __nccwpck_require__(99915); +var deprecate = __nccwpck_require__(18883)('express'); +var flatten = __nccwpck_require__(62003); +var mime = (__nccwpck_require__(95287).mime); +var etag = __nccwpck_require__(69972); +var proxyaddr = __nccwpck_require__(80140); +var qs = __nccwpck_require__(22760); +var querystring = __nccwpck_require__(63477); /** - * This is the Node.js implementation of `debug()`. + * Return strong ETag for `body`. * - * Expose `debug()` as the module. + * @param {String|Buffer} body + * @param {String} [encoding] + * @return {String} + * @api private */ -exports = module.exports = __nccwpck_require__(86991); -exports.init = init; -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; +exports.etag = createETagGenerator({ weak: false }) /** - * Colors. + * Return weak ETag for `body`. + * + * @param {String|Buffer} body + * @param {String} [encoding] + * @return {String} + * @api private */ -exports.colors = [6, 2, 3, 4, 5, 1]; +exports.wetag = createETagGenerator({ weak: true }) /** - * Build up the default `inspectOpts` object from the environment variables. + * Check if `path` looks absolute. * - * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + * @param {String} path + * @return {Boolean} + * @api private */ -exports.inspectOpts = Object.keys(process.env).filter(function (key) { - return /^debug_/i.test(key); -}).reduce(function (obj, key) { - // camel-case - var prop = key - .substring(6) - .toLowerCase() - .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() }); - - // coerce string value into JS value - var val = process.env[key]; - if (/^(yes|on|true|enabled)$/i.test(val)) val = true; - else if (/^(no|off|false|disabled)$/i.test(val)) val = false; - else if (val === 'null') val = null; - else val = Number(val); - - obj[prop] = val; - return obj; -}, {}); +exports.isAbsolute = function(path){ + if ('/' === path[0]) return true; + if (':' === path[1] && ('\\' === path[2] || '/' === path[2])) return true; // Windows device path + if ('\\\\' === path.substring(0, 2)) return true; // Microsoft Azure absolute path +}; /** - * The file descriptor to write the `debug()` calls to. - * Set the `DEBUG_FD` env variable to override with another value. i.e.: + * Flatten the given `arr`. * - * $ DEBUG_FD=3 node script.js 3>debug.log + * @param {Array} arr + * @return {Array} + * @api private */ -var fd = parseInt(process.env.DEBUG_FD, 10) || 2; - -if (1 !== fd && 2 !== fd) { - util.deprecate(function(){}, 'except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)')() -} - -var stream = 1 === fd ? process.stdout : - 2 === fd ? process.stderr : - createWritableStdioStream(fd); +exports.flatten = deprecate.function(flatten, + 'utils.flatten: use array-flatten npm module instead'); /** - * Is stdout a TTY? Colored output is enabled when `true`. + * Normalize the given `type`, for example "html" becomes "text/html". + * + * @param {String} type + * @return {Object} + * @api private */ -function useColors() { - return 'colors' in exports.inspectOpts - ? Boolean(exports.inspectOpts.colors) - : tty.isatty(fd); -} +exports.normalizeType = function(type){ + return ~type.indexOf('/') + ? acceptParams(type) + : { value: mime.lookup(type), params: {} }; +}; /** - * Map %o to `util.inspect()`, all on a single line. + * Normalize `types`, for example "html" becomes "text/html". + * + * @param {Array} types + * @return {Array} + * @api private */ -exports.formatters.o = function(v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts) - .split('\n').map(function(str) { - return str.trim() - }).join(' '); +exports.normalizeTypes = function(types){ + var ret = []; + + for (var i = 0; i < types.length; ++i) { + ret.push(exports.normalizeType(types[i])); + } + + return ret; }; /** - * Map %o to `util.inspect()`, allowing multiple lines if needed. + * Generate Content-Disposition header appropriate for the filename. + * non-ascii filenames are urlencoded and a filename* parameter is added + * + * @param {String} filename + * @return {String} + * @api private */ -exports.formatters.O = function(v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts); -}; +exports.contentDisposition = deprecate.function(contentDisposition, + 'utils.contentDisposition: use content-disposition npm module instead'); /** - * Adds ANSI color escape codes if enabled. + * Parse accept params `str` returning an + * object with `.value`, `.quality` and `.params`. + * also includes `.originalIndex` for stable sorting * - * @api public + * @param {String} str + * @return {Object} + * @api private */ -function formatArgs(args) { - var name = this.namespace; - var useColors = this.useColors; - - if (useColors) { - var c = this.color; - var prefix = ' \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m'; +function acceptParams(str, index) { + var parts = str.split(/ *; */); + var ret = { value: parts[0], quality: 1, params: {}, originalIndex: index }; - args[0] = prefix + args[0].split('\n').join('\n' + prefix); - args.push('\u001b[3' + c + 'm+' + exports.humanize(this.diff) + '\u001b[0m'); - } else { - args[0] = new Date().toUTCString() - + ' ' + name + ' ' + args[0]; + for (var i = 1; i < parts.length; ++i) { + var pms = parts[i].split(/ *= */); + if ('q' === pms[0]) { + ret.quality = parseFloat(pms[1]); + } else { + ret.params[pms[0]] = pms[1]; + } } -} - -/** - * Invokes `util.format()` with the specified arguments and writes to `stream`. - */ -function log() { - return stream.write(util.format.apply(util, arguments) + '\n'); + return ret; } /** - * Save `namespaces`. + * Compile "etag" value to function. * - * @param {String} namespaces + * @param {Boolean|String|Function} val + * @return {Function} * @api private */ -function save(namespaces) { - if (null == namespaces) { - // If you set a process.env field to null or undefined, it gets cast to the - // string 'null' or 'undefined'. Just delete instead. - delete process.env.DEBUG; - } else { - process.env.DEBUG = namespaces; +exports.compileETag = function(val) { + var fn; + + if (typeof val === 'function') { + return val; + } + + switch (val) { + case true: + case 'weak': + fn = exports.wetag; + break; + case false: + break; + case 'strong': + fn = exports.etag; + break; + default: + throw new TypeError('unknown value for etag function: ' + val); } + + return fn; } /** - * Load `namespaces`. + * Compile "query parser" value to function. * - * @return {String} returns the previously persisted debug modes + * @param {String|Function} val + * @return {Function} * @api private */ -function load() { - return process.env.DEBUG; +exports.compileQueryParser = function compileQueryParser(val) { + var fn; + + if (typeof val === 'function') { + return val; + } + + switch (val) { + case true: + case 'simple': + fn = querystring.parse; + break; + case false: + fn = newObject; + break; + case 'extended': + fn = parseExtendedQueryString; + break; + default: + throw new TypeError('unknown value for query parser function: ' + val); + } + + return fn; } /** - * Copied from `node/src/node.js`. + * Compile "proxy trust" value to function. * - * XXX: It's lame that node doesn't expose this API out-of-the-box. It also - * relies on the undocumented `tty_wrap.guessHandleType()` which is also lame. + * @param {Boolean|String|Number|Array|Function} val + * @return {Function} + * @api private */ -function createWritableStdioStream (fd) { - var stream; - var tty_wrap = process.binding('tty_wrap'); +exports.compileTrust = function(val) { + if (typeof val === 'function') return val; - // Note stream._type is used for test-module-load-list.js - - switch (tty_wrap.guessHandleType(fd)) { - case 'TTY': - stream = new tty.WriteStream(fd); - stream._type = 'tty'; - - // Hack to have stream not keep the event loop alive. - // See https://github.com/joyent/node/issues/1726 - if (stream._handle && stream._handle.unref) { - stream._handle.unref(); - } - break; + if (val === true) { + // Support plain true/false + return function(){ return true }; + } - case 'FILE': - var fs = __nccwpck_require__(57147); - stream = new fs.SyncWriteStream(fd, { autoClose: false }); - stream._type = 'fs'; - break; + if (typeof val === 'number') { + // Support trusting hop count + return function(a, i){ return i < val }; + } - case 'PIPE': - case 'TCP': - var net = __nccwpck_require__(41808); - stream = new net.Socket({ - fd: fd, - readable: false, - writable: true - }); + if (typeof val === 'string') { + // Support comma-separated values + val = val.split(/ *, */); + } - // FIXME Should probably have an option in net.Socket to create a - // stream from an existing fd which is writable only. But for now - // we'll just add this hack and set the `readable` member to false. - // Test: ./node test/fixtures/echo.js < /etc/passwd - stream.readable = false; - stream.read = null; - stream._type = 'pipe'; + return proxyaddr.compile(val || []); +} - // FIXME Hack to have stream not keep the event loop alive. - // See https://github.com/joyent/node/issues/1726 - if (stream._handle && stream._handle.unref) { - stream._handle.unref(); - } - break; +/** + * Set the charset in a given Content-Type string. + * + * @param {String} type + * @param {String} charset + * @return {String} + * @api private + */ - default: - // Probably an error on in uv_guess_handle() - throw new Error('Implement me. Unknown stream file type!'); +exports.setCharset = function setCharset(type, charset) { + if (!type || !charset) { + return type; } - // For supporting legacy API we put the FD here. - stream.fd = fd; + // parse type + var parsed = contentType.parse(type); - stream._isStdio = true; + // set charset + parsed.parameters.charset = charset; - return stream; -} + // format type + return contentType.format(parsed); +}; /** - * Init logic for `debug` instances. + * Create an ETag generator function, generating ETags with + * the given options. * - * Create a new `inspectOpts` object in case `useColors` is set - * differently for a particular `debug` instance. + * @param {object} options + * @return {function} + * @private */ -function init (debug) { - debug.inspectOpts = {}; +function createETagGenerator (options) { + return function generateETag (body, encoding) { + var buf = !Buffer.isBuffer(body) + ? Buffer.from(body, encoding) + : body - var keys = Object.keys(exports.inspectOpts); - for (var i = 0; i < keys.length; i++) { - debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + return etag(buf, options) } } /** - * Enable namespaces listed in `process.env.DEBUG` initially. + * Parse an extended query string with qs. + * + * @return {Object} + * @private */ -exports.enable(load()); +function parseExtendedQueryString(str) { + return qs.parse(str, { + allowPrototypes: true + }); +} + +/** + * Return new empty object. + * + * @return {Object} + * @api private + */ + +function newObject() { + return {}; +} /***/ }), -/***/ 27025: -/***/ ((module) => { +/***/ 99209: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * Helpers. +"use strict"; +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed */ -var s = 1000; -var m = s * 60; -var h = m * 60; -var d = h * 24; -var y = d * 365.25; + /** - * Parse or format the given `val`. - * - * Options: - * - * - `long` verbose formatting [false] - * - * @param {String|Number} val - * @param {Object} [options] - * @throws {Error} throw an error if val is not a non-empty string or a number - * @return {String|Number} - * @api public + * Module dependencies. + * @private */ -module.exports = function(val, options) { - options = options || {}; - var type = typeof val; - if (type === 'string' && val.length > 0) { - return parse(val); - } else if (type === 'number' && isNaN(val) === false) { - return options.long ? fmtLong(val) : fmtShort(val); - } - throw new Error( - 'val is not a non-empty string or a valid number. val=' + - JSON.stringify(val) - ); -}; +var debug = __nccwpck_require__(52529)('express:view'); +var path = __nccwpck_require__(71017); +var fs = __nccwpck_require__(57147); /** - * Parse the given `str` and return milliseconds. - * - * @param {String} str - * @return {Number} - * @api private + * Module variables. + * @private */ -function parse(str) { - str = String(str); - if (str.length > 100) { - return; - } - var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec( - str - ); - if (!match) { - return; - } - var n = parseFloat(match[1]); - var type = (match[2] || 'ms').toLowerCase(); - switch (type) { - case 'years': - case 'year': - case 'yrs': - case 'yr': - case 'y': - return n * y; - case 'days': - case 'day': - case 'd': - return n * d; - case 'hours': - case 'hour': - case 'hrs': - case 'hr': - case 'h': - return n * h; - case 'minutes': - case 'minute': - case 'mins': - case 'min': - case 'm': - return n * m; - case 'seconds': - case 'second': - case 'secs': - case 'sec': - case 's': - return n * s; - case 'milliseconds': - case 'millisecond': - case 'msecs': - case 'msec': - case 'ms': - return n; - default: - return undefined; - } -} +var dirname = path.dirname; +var basename = path.basename; +var extname = path.extname; +var join = path.join; +var resolve = path.resolve; /** - * Short format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private + * Module exports. + * @public */ -function fmtShort(ms) { - if (ms >= d) { - return Math.round(ms / d) + 'd'; - } - if (ms >= h) { - return Math.round(ms / h) + 'h'; - } - if (ms >= m) { - return Math.round(ms / m) + 'm'; - } - if (ms >= s) { - return Math.round(ms / s) + 's'; - } - return ms + 'ms'; -} +module.exports = View; /** - * Long format for `ms`. + * Initialize a new `View` with the given `name`. * - * @param {Number} ms - * @return {String} - * @api private + * Options: + * + * - `defaultEngine` the default template engine name + * - `engines` template engine require() cache + * - `root` root path for view lookup + * + * @param {string} name + * @param {object} options + * @public */ -function fmtLong(ms) { - return plural(ms, d, 'day') || - plural(ms, h, 'hour') || - plural(ms, m, 'minute') || - plural(ms, s, 'second') || - ms + ' ms'; -} +function View(name, options) { + var opts = options || {}; -/** - * Pluralization helper. - */ + this.defaultEngine = opts.defaultEngine; + this.ext = extname(name); + this.name = name; + this.root = opts.root; -function plural(ms, n, name) { - if (ms < n) { - return; - } - if (ms < n * 1.5) { - return Math.floor(ms / n) + ' ' + name; + if (!this.ext && !this.defaultEngine) { + throw new Error('No default engine was specified and no extension was provided.'); } - return Math.ceil(ms / n) + ' ' + name + 's'; -} - - -/***/ }), -/***/ 41894: -/***/ ((module, exports, __nccwpck_require__) => { + var fileName = name; -/*! safe-buffer. MIT License. Feross Aboukhadijeh */ -/* eslint-disable node/no-deprecated-api */ -var buffer = __nccwpck_require__(14300) -var Buffer = buffer.Buffer + if (!this.ext) { + // get extension from default engine name + this.ext = this.defaultEngine[0] !== '.' + ? '.' + this.defaultEngine + : this.defaultEngine; -// alternative to using Object.keys for old browsers -function copyProps (src, dst) { - for (var key in src) { - dst[key] = src[key] + fileName += this.ext; } -} -if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { - module.exports = buffer -} else { - // Copy properties from require('buffer') - copyProps(buffer, exports) - exports.Buffer = SafeBuffer -} -function SafeBuffer (arg, encodingOrOffset, length) { - return Buffer(arg, encodingOrOffset, length) -} + if (!opts.engines[this.ext]) { + // load engine + var mod = this.ext.substr(1) + debug('require "%s"', mod) -SafeBuffer.prototype = Object.create(Buffer.prototype) + // default engine export + var fn = require(mod).__express -// Copy static methods from Buffer -copyProps(Buffer, SafeBuffer) + if (typeof fn !== 'function') { + throw new Error('Module "' + mod + '" does not provide a view engine.') + } -SafeBuffer.from = function (arg, encodingOrOffset, length) { - if (typeof arg === 'number') { - throw new TypeError('Argument must not be a number') + opts.engines[this.ext] = fn } - return Buffer(arg, encodingOrOffset, length) -} -SafeBuffer.alloc = function (size, fill, encoding) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - var buf = Buffer(size) - if (fill !== undefined) { - if (typeof encoding === 'string') { - buf.fill(fill, encoding) - } else { - buf.fill(fill) - } - } else { - buf.fill(0) - } - return buf -} + // store loaded engine + this.engine = opts.engines[this.ext]; -SafeBuffer.allocUnsafe = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - return Buffer(size) + // lookup path + this.path = this.lookup(fileName); } -SafeBuffer.allocUnsafeSlow = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - return buffer.SlowBuffer(size) -} +/** + * Lookup view by the given `name` + * + * @param {string} name + * @private + */ +View.prototype.lookup = function lookup(name) { + var path; + var roots = [].concat(this.root); -/***/ }), + debug('lookup "%s"', name); -/***/ 24826: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + for (var i = 0; i < roots.length && !path; i++) { + var root = roots[i]; -"use strict"; + // resolve the path + var loc = resolve(root, name); + var dir = dirname(loc); + var file = basename(loc); + // resolve the file + path = this.resolve(dir, file); + } -const validator = __nccwpck_require__(74174) -const parse = __nccwpck_require__(96214) -const redactor = __nccwpck_require__(17333) -const restorer = __nccwpck_require__(98806) -const { groupRedact, nestedRedact } = __nccwpck_require__(54865) -const state = __nccwpck_require__(41012) -const rx = __nccwpck_require__(9158) -const validate = validator() -const noop = (o) => o -noop.restore = noop + return path; +}; -const DEFAULT_CENSOR = '[REDACTED]' -fastRedact.rx = rx -fastRedact.validator = validator +/** + * Render with the given options. + * + * @param {object} options + * @param {function} callback + * @private + */ -module.exports = fastRedact +View.prototype.render = function render(options, callback) { + debug('render "%s"', this.path); + this.engine(this.path, options, callback); +}; -function fastRedact (opts = {}) { - const paths = Array.from(new Set(opts.paths || [])) - const serialize = 'serialize' in opts ? ( - opts.serialize === false ? opts.serialize - : (typeof opts.serialize === 'function' ? opts.serialize : JSON.stringify) - ) : JSON.stringify - const remove = opts.remove - if (remove === true && serialize !== JSON.stringify) { - throw Error('fast-redact – remove option may only be set when serializer is JSON.stringify') - } - const censor = remove === true - ? undefined - : 'censor' in opts ? opts.censor : DEFAULT_CENSOR +/** + * Resolve the file within the given directory. + * + * @param {string} dir + * @param {string} file + * @private + */ - const isCensorFct = typeof censor === 'function' - const censorFctTakesPath = isCensorFct && censor.length > 1 +View.prototype.resolve = function resolve(dir, file) { + var ext = this.ext; - if (paths.length === 0) return serialize || noop + // . + var path = join(dir, file); + var stat = tryStat(path); - validate({ paths, serialize, censor }) + if (stat && stat.isFile()) { + return path; + } - const { wildcards, wcLen, secret } = parse({ paths, censor }) + // /index. + path = join(dir, basename(file, ext), 'index' + ext); + stat = tryStat(path); - const compileRestore = restorer({ secret, wcLen }) - const strict = 'strict' in opts ? opts.strict : true + if (stat && stat.isFile()) { + return path; + } +}; - return redactor({ secret, wcLen, serialize, strict, isCensorFct, censorFctTakesPath }, state({ - secret, - censor, - compileRestore, - serialize, - groupRedact, - nestedRedact, - wildcards, - wcLen - })) +/** + * Return a stat, maybe. + * + * @param {string} path + * @return {fs.Stats} + * @private + */ + +function tryStat(path) { + debug('stat "%s"', path); + + try { + return fs.statSync(path); + } catch (e) { + return undefined; + } } /***/ }), -/***/ 54865: -/***/ ((module) => { +/***/ 36654: +/***/ ((module, exports, __nccwpck_require__) => { -"use strict"; +/** + * This is the web browser implementation of `debug()`. + * + * Expose `debug()` as the module. + */ +exports = module.exports = __nccwpck_require__(86991); +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = 'undefined' != typeof chrome + && 'undefined' != typeof chrome.storage + ? chrome.storage.local + : localstorage(); -module.exports = { - groupRedact, - groupRestore, - nestedRedact, - nestedRestore -} - -function groupRestore ({ keys, values, target }) { - if (target == null) return - const length = keys.length - for (var i = 0; i < length; i++) { - const k = keys[i] - target[k] = values[i] - } -} +/** + * Colors. + */ -function groupRedact (o, path, censor, isCensorFct, censorFctTakesPath) { - const target = get(o, path) - if (target == null) return { keys: null, values: null, target: null, flat: true } - const keys = Object.keys(target) - const keysLength = keys.length - const pathLength = path.length - const pathWithKey = censorFctTakesPath ? [...path] : undefined - const values = new Array(keysLength) +exports.colors = [ + 'lightseagreen', + 'forestgreen', + 'goldenrod', + 'dodgerblue', + 'darkorchid', + 'crimson' +]; - for (var i = 0; i < keysLength; i++) { - const key = keys[i] - values[i] = target[key] +/** + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. + * + * TODO: add a `localStorage` variable to explicitly enable/disable colors + */ - if (censorFctTakesPath) { - pathWithKey[pathLength] = key - target[key] = censor(target[key], pathWithKey) - } else if (isCensorFct) { - target[key] = censor(target[key]) - } else { - target[key] = censor - } +function useColors() { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') { + return true; } - return { keys, values, target, flat: true } -} -function nestedRestore (arr) { - const length = arr.length - for (var i = 0; i < length; i++) { - const { key, target, value } = arr[i] - target[key] = value - } + // is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || + // is firebug? http://stackoverflow.com/a/398120/376773 + (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || + // is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || + // double check webkit in userAgent just in case we are in a worker + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); } -function nestedRedact (store, o, path, ns, censor, isCensorFct, censorFctTakesPath) { - const target = get(o, path) - if (target == null) return - const keys = Object.keys(target) - const keysLength = keys.length - for (var i = 0; i < keysLength; i++) { - const key = keys[i] - const { value, parent, exists } = - specialSet(target, key, path, ns, censor, isCensorFct, censorFctTakesPath) +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ - if (exists === true && parent !== null) { - store.push({ key: ns[ns.length - 1], target: parent, value }) - } +exports.formatters.j = function(v) { + try { + return JSON.stringify(v); + } catch (err) { + return '[UnexpectedJSONParseError]: ' + err.message; } - return store -} +}; -function has (obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop) -} -function specialSet (o, k, path, afterPath, censor, isCensorFct, censorFctTakesPath) { - const afterPathLen = afterPath.length - const lastPathIndex = afterPathLen - 1 - const originalKey = k - var i = -1 - var n - var nv - var ov - var oov = null - var exists = true - ov = n = o[k] - if (typeof n !== 'object') return { value: null, parent: null, exists } - while (n != null && ++i < afterPathLen) { - k = afterPath[i] - oov = ov - if (!(k in n)) { - exists = false - break - } - ov = n[k] - nv = (i !== lastPathIndex) - ? ov - : (isCensorFct - ? (censorFctTakesPath ? censor(ov, [...path, originalKey, ...afterPath]) : censor(ov)) - : censor) - n[k] = (has(n, k) && nv === ov) || (nv === undefined && censor !== undefined) ? n[k] : nv - n = n[k] - if (typeof n !== 'object') break - } - return { value: ov, parent: oov, exists } -} +/** + * Colorize log arguments if enabled. + * + * @api public + */ -function get (o, p) { - var i = -1 - var l = p.length - var n = o - while (n != null && ++i < l) { - n = n[p[i]] - } - return n -} +function formatArgs(args) { + var useColors = this.useColors; + args[0] = (useColors ? '%c' : '') + + this.namespace + + (useColors ? ' %c' : ' ') + + args[0] + + (useColors ? '%c ' : ' ') + + '+' + exports.humanize(this.diff); -/***/ }), + if (!useColors) return; -/***/ 96214: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + var c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit') -"use strict"; + // the final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + var index = 0; + var lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, function(match) { + if ('%%' === match) return; + index++; + if ('%c' === match) { + // we only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); + args.splice(lastC, 0, c); +} -const rx = __nccwpck_require__(9158) +/** + * Invokes `console.log()` when available. + * No-op when `console.log` is not a "function". + * + * @api public + */ -module.exports = parse +function log() { + // this hackery is required for IE8/9, where + // the `console.log` function doesn't have 'apply' + return 'object' === typeof console + && console.log + && Function.prototype.apply.call(console.log, console, arguments); +} -function parse ({ paths }) { - const wildcards = [] - var wcLen = 0 - const secret = paths.reduce(function (o, strPath, ix) { - var path = strPath.match(rx).map((p) => p.replace(/'|"|`/g, '')) - const leadingBracket = strPath[0] === '[' - path = path.map((p) => { - if (p[0] === '[') return p.substr(1, p.length - 2) - else return p - }) - const star = path.indexOf('*') - if (star > -1) { - const before = path.slice(0, star) - const beforeStr = before.join('.') - const after = path.slice(star + 1, path.length) - if (after.indexOf('*') > -1) throw Error('fast-redact – Only one wildcard per path is supported') - const nested = after.length > 0 - wcLen++ - wildcards.push({ - before, - beforeStr, - after, - nested - }) +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ + +function save(namespaces) { + try { + if (null == namespaces) { + exports.storage.removeItem('debug'); } else { - o[strPath] = { - path: path, - val: undefined, - precensored: false, - circle: '', - escPath: JSON.stringify(strPath), - leadingBracket: leadingBracket - } + exports.storage.debug = namespaces; } - return o - }, {}) - - return { wildcards, wcLen, secret } + } catch(e) {} } +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ -/***/ }), - -/***/ 17333: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; +function load() { + var r; + try { + r = exports.storage.debug; + } catch(e) {} + // If debug isn't set in LS, and we're in Electron, try to load $DEBUG + if (!r && typeof process !== 'undefined' && 'env' in process) { + r = process.env.DEBUG; + } -const rx = __nccwpck_require__(9158) + return r; +} -module.exports = redactor +/** + * Enable namespaces listed in `localStorage.debug` initially. + */ -function redactor ({ secret, serialize, wcLen, strict, isCensorFct, censorFctTakesPath }, state) { - /* eslint-disable-next-line */ - const redact = Function('o', ` - if (typeof o !== 'object' || o == null) { - ${strictImpl(strict, serialize)} - } - const { censor, secret } = this - ${redactTmpl(secret, isCensorFct, censorFctTakesPath)} - this.compileRestore() - ${dynamicRedactTmpl(wcLen > 0, isCensorFct, censorFctTakesPath)} - ${resultTmpl(serialize)} - `).bind(state) +exports.enable(load()); - if (serialize === false) { - redact.restore = (o) => state.restore(o) - } +/** + * Localstorage attempts to return the localstorage. + * + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. + * + * @return {LocalStorage} + * @api private + */ - return redact +function localstorage() { + try { + return window.localStorage; + } catch (e) {} } -function redactTmpl (secret, isCensorFct, censorFctTakesPath) { - return Object.keys(secret).map((path) => { - const { escPath, leadingBracket, path: arrPath } = secret[path] - const skip = leadingBracket ? 1 : 0 - const delim = leadingBracket ? '' : '.' - const hops = [] - var match - while ((match = rx.exec(path)) !== null) { - const [ , ix ] = match - const { index, input } = match - if (index > skip) hops.push(input.substring(0, index - (ix ? 0 : 1))) - } - var existence = hops.map((p) => `o${delim}${p}`).join(' && ') - if (existence.length === 0) existence += `o${delim}${path} != null` - else existence += ` && o${delim}${path} != null` - const circularDetection = ` - switch (true) { - ${hops.reverse().map((p) => ` - case o${delim}${p} === censor: - secret[${escPath}].circle = ${JSON.stringify(p)} - break - `).join('\n')} - } - ` +/***/ }), - const censorArgs = censorFctTakesPath - ? `val, ${JSON.stringify(arrPath)}` - : `val` +/***/ 86991: +/***/ ((module, exports, __nccwpck_require__) => { - return ` - if (${existence}) { - const val = o${delim}${path} - if (val === censor) { - secret[${escPath}].precensored = true - } else { - secret[${escPath}].val = val - o${delim}${path} = ${isCensorFct ? `censor(${censorArgs})` : 'censor'} - ${circularDetection} - } - } - ` - }).join('\n') -} -function dynamicRedactTmpl (hasWildcards, isCensorFct, censorFctTakesPath) { - return hasWildcards === true ? ` - { - const { wildcards, wcLen, groupRedact, nestedRedact } = this - for (var i = 0; i < wcLen; i++) { - const { before, beforeStr, after, nested } = wildcards[i] - if (nested === true) { - secret[beforeStr] = secret[beforeStr] || [] - nestedRedact(secret[beforeStr], o, before, after, censor, ${isCensorFct}, ${censorFctTakesPath}) - } else secret[beforeStr] = groupRedact(o, before, censor, ${isCensorFct}, ${censorFctTakesPath}) - } - } - ` : '' -} +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + * + * Expose `debug()` as the module. + */ -function resultTmpl (serialize) { - return serialize === false ? `return o` : ` - var s = this.serialize(o) - this.restore(o) - return s - ` -} +exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; +exports.coerce = coerce; +exports.disable = disable; +exports.enable = enable; +exports.enabled = enabled; +exports.humanize = __nccwpck_require__(27025); -function strictImpl (strict, serialize) { - return strict === true - ? `throw Error('fast-redact: primitives cannot be redacted')` - : serialize === false ? `return o` : `return this.serialize(o)` -} +/** + * The currently active debug mode names, and names to skip. + */ +exports.names = []; +exports.skips = []; -/***/ }), +/** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + */ -/***/ 98806: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +exports.formatters = {}; -"use strict"; +/** + * Previous log timestamp. + */ +var prevTime; -const { groupRestore, nestedRestore } = __nccwpck_require__(54865) +/** + * Select a color. + * @param {String} namespace + * @return {Number} + * @api private + */ -module.exports = restorer +function selectColor(namespace) { + var hash = 0, i; -function restorer ({ secret, wcLen }) { - return function compileRestore () { - if (this.restore) return - const paths = Object.keys(secret) - const resetters = resetTmpl(secret, paths) - const hasWildcards = wcLen > 0 - const state = hasWildcards ? { secret, groupRestore, nestedRestore } : { secret } - /* eslint-disable-next-line */ - this.restore = Function( - 'o', - restoreTmpl(resetters, paths, hasWildcards) - ).bind(state) + for (i in namespace) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer } -} -/** - * Mutates the original object to be censored by restoring its original values - * prior to censoring. - * - * @param {object} secret Compiled object describing which target fields should - * be censored and the field states. - * @param {string[]} paths The list of paths to censor as provided at - * initialization time. - * - * @returns {string} String of JavaScript to be used by `Function()`. The - * string compiles to the function that does the work in the description. - */ -function resetTmpl (secret, paths) { - return paths.map((path) => { - const { circle, escPath, leadingBracket } = secret[path] - const delim = leadingBracket ? '' : '.' - const reset = circle - ? `o.${circle} = secret[${escPath}].val` - : `o${delim}${path} = secret[${escPath}].val` - const clear = `secret[${escPath}].val = undefined` - return ` - if (secret[${escPath}].val !== undefined) { - try { ${reset} } catch (e) {} - ${clear} - } - ` - }).join('') + return exports.colors[Math.abs(hash) % exports.colors.length]; } /** - * Creates the body of the restore function - * - * Restoration of the redacted object happens - * backwards, in reverse order of redactions, - * so that repeated redactions on the same object - * property can be eventually rolled back to the - * original value. - * - * This way dynamic redactions are restored first, - * starting from the last one working backwards and - * followed by the static ones. + * Create a debugger with the given `namespace`. * - * @returns {string} the body of the restore function + * @param {String} namespace + * @return {Function} + * @api public */ -function restoreTmpl (resetters, paths, hasWildcards) { - const dynamicReset = hasWildcards === true ? ` - const keys = Object.keys(secret) - const len = keys.length - for (var i = len - 1; i >= ${paths.length}; i--) { - const k = keys[i] - const o = secret[k] - if (o.flat === true) this.groupRestore(o) - else this.nestedRestore(o) - secret[k] = null - } - ` : '' - return ` - const secret = this.secret - ${dynamicReset} - ${resetters} - return o - ` -} +function createDebug(namespace) { + function debug() { + // disabled? + if (!debug.enabled) return; -/***/ }), + var self = debug; -/***/ 9158: -/***/ ((module) => { + // set `diff` timestamp + var curr = +new Date(); + var ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; -"use strict"; + // turn the `arguments` into a proper Array + var args = new Array(arguments.length); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i]; + } + args[0] = exports.coerce(args[0]); -module.exports = /[^.[\]]+|\[((?:.)*?)\]/g - -/* -Regular expression explanation: - -Alt 1: /[^.[\]]+/ - Match one or more characters that are *not* a dot (.) - opening square bracket ([) or closing square bracket (]) - -Alt 2: /\[((?:.)*?)\]/ - If the char IS dot or square bracket, then create a capture - group (which will be capture group $1) that matches anything - within square brackets. Expansion is lazy so it will - stop matching as soon as the first closing bracket is met `]` - (rather than continuing to match until the final closing bracket). -*/ + if ('string' !== typeof args[0]) { + // anything else let's inspect with %O + args.unshift('%O'); + } + // apply any `formatters` transformations + var index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) { + // if we encounter an escaped % then don't increase the array index + if (match === '%%') return match; + index++; + var formatter = exports.formatters[format]; + if ('function' === typeof formatter) { + var val = args[index]; + match = formatter.call(self, val); -/***/ }), + // now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); -/***/ 41012: -/***/ ((module) => { + // apply env-specific formatting (colors, etc.) + exports.formatArgs.call(self, args); -"use strict"; + var logFn = debug.log || exports.log || console.log.bind(console); + logFn.apply(self, args); + } + debug.namespace = namespace; + debug.enabled = exports.enabled(namespace); + debug.useColors = exports.useColors(); + debug.color = selectColor(namespace); -module.exports = state + // env-specific initialization logic for debug instances + if ('function' === typeof exports.init) { + exports.init(debug); + } -function state (o) { - const { - secret, - censor, - compileRestore, - serialize, - groupRedact, - nestedRedact, - wildcards, - wcLen - } = o - const builder = [{ secret, censor, compileRestore }] - if (serialize !== false) builder.push({ serialize }) - if (wcLen > 0) builder.push({ groupRedact, nestedRedact, wildcards, wcLen }) - return Object.assign(...builder) + return debug; } +/** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ -/***/ }), - -/***/ 74174: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const { createContext, runInContext } = __nccwpck_require__(26144) +function enable(namespaces) { + exports.save(namespaces); -module.exports = validator + exports.names = []; + exports.skips = []; -function validator (opts = {}) { - const { - ERR_PATHS_MUST_BE_STRINGS = () => 'fast-redact - Paths must be (non-empty) strings', - ERR_INVALID_PATH = (s) => `fast-redact – Invalid path (${s})` - } = opts + var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + var len = split.length; - return function validate ({ paths }) { - paths.forEach((s) => { - if (typeof s !== 'string') { - throw Error(ERR_PATHS_MUST_BE_STRINGS()) - } - try { - if (/〇/.test(s)) throw Error() - const proxy = new Proxy({}, { get: () => proxy, set: () => { throw Error() } }) - const expr = (s[0] === '[' ? '' : '.') + s.replace(/^\*/, '〇').replace(/\.\*/g, '.〇').replace(/\[\*\]/g, '[〇]') - if (/\n|\r|;/.test(expr)) throw Error() - if (/\/\*/.test(expr)) throw Error() - runInContext(` - (function () { - 'use strict' - o${expr} - if ([o${expr}].length !== 1) throw Error() - })() - `, createContext({ o: proxy, 〇: null }), { - codeGeneration: { strings: false, wasm: false } - }) - } catch (e) { - throw Error(ERR_INVALID_PATH(s)) - } - }) + for (var i = 0; i < len; i++) { + if (!split[i]) continue; // ignore empty strings + namespaces = split[i].replace(/\*/g, '.*?'); + if (namespaces[0] === '-') { + exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); + } else { + exports.names.push(new RegExp('^' + namespaces + '$')); + } } } +/** + * Disable debug output. + * + * @api public + */ -/***/ }), - -/***/ 17676: -/***/ ((module) => { - -module.exports = stringify -stringify.default = stringify -stringify.stable = deterministicStringify -stringify.stableStringify = deterministicStringify - -var LIMIT_REPLACE_NODE = '[...]' -var CIRCULAR_REPLACE_NODE = '[Circular]' - -var arr = [] -var replacerStack = [] - -function defaultOptions () { - return { - depthLimit: Number.MAX_SAFE_INTEGER, - edgesLimit: Number.MAX_SAFE_INTEGER - } +function disable() { + exports.enable(''); } -// Regular stringify -function stringify (obj, replacer, spacer, options) { - if (typeof options === 'undefined') { - options = defaultOptions() - } +/** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ - decirc(obj, '', 0, [], undefined, 0, options) - var res - try { - if (replacerStack.length === 0) { - res = JSON.stringify(obj, replacer, spacer) - } else { - res = JSON.stringify(obj, replaceGetterValues(replacer), spacer) - } - } catch (_) { - return JSON.stringify('[unable to serialize, circular reference is too complex to analyze]') - } finally { - while (arr.length !== 0) { - var part = arr.pop() - if (part.length === 4) { - Object.defineProperty(part[0], part[1], part[3]) - } else { - part[0][part[1]] = part[2] - } +function enabled(name) { + var i, len; + for (i = 0, len = exports.skips.length; i < len; i++) { + if (exports.skips[i].test(name)) { + return false; } } - return res -} - -function setReplace (replace, val, k, parent) { - var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k) - if (propertyDescriptor.get !== undefined) { - if (propertyDescriptor.configurable) { - Object.defineProperty(parent, k, { value: replace }) - arr.push([parent, k, val, propertyDescriptor]) - } else { - replacerStack.push([val, k, replace]) + for (i = 0, len = exports.names.length; i < len; i++) { + if (exports.names[i].test(name)) { + return true; } - } else { - parent[k] = replace - arr.push([parent, k, val]) } + return false; } -function decirc (val, k, edgeIndex, stack, parent, depth, options) { - depth += 1 - var i - if (typeof val === 'object' && val !== null) { - for (i = 0; i < stack.length; i++) { - if (stack[i] === val) { - setReplace(CIRCULAR_REPLACE_NODE, val, k, parent) - return - } - } +/** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ - if ( - typeof options.depthLimit !== 'undefined' && - depth > options.depthLimit - ) { - setReplace(LIMIT_REPLACE_NODE, val, k, parent) - return - } +function coerce(val) { + if (val instanceof Error) return val.stack || val.message; + return val; +} - if ( - typeof options.edgesLimit !== 'undefined' && - edgeIndex + 1 > options.edgesLimit - ) { - setReplace(LIMIT_REPLACE_NODE, val, k, parent) - return - } - stack.push(val) - // Optimize for Arrays. Big arrays could kill the performance otherwise! - if (Array.isArray(val)) { - for (i = 0; i < val.length; i++) { - decirc(val[i], i, i, stack, val, depth, options) - } - } else { - var keys = Object.keys(val) - for (i = 0; i < keys.length; i++) { - var key = keys[i] - decirc(val[key], key, i, stack, val, depth, options) - } - } - stack.pop() - } -} +/***/ }), -// Stable-stringify -function compareFunction (a, b) { - if (a < b) { - return -1 - } - if (a > b) { - return 1 - } - return 0 -} +/***/ 52529: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -function deterministicStringify (obj, replacer, spacer, options) { - if (typeof options === 'undefined') { - options = defaultOptions() - } +/** + * Detect Electron renderer process, which is node, but we should + * treat as a browser. + */ - var tmp = deterministicDecirc(obj, '', 0, [], undefined, 0, options) || obj - var res - try { - if (replacerStack.length === 0) { - res = JSON.stringify(tmp, replacer, spacer) - } else { - res = JSON.stringify(tmp, replaceGetterValues(replacer), spacer) - } - } catch (_) { - return JSON.stringify('[unable to serialize, circular reference is too complex to analyze]') - } finally { - // Ensure that we restore the object as it was. - while (arr.length !== 0) { - var part = arr.pop() - if (part.length === 4) { - Object.defineProperty(part[0], part[1], part[3]) - } else { - part[0][part[1]] = part[2] - } - } - } - return res +if (typeof process !== 'undefined' && process.type === 'renderer') { + module.exports = __nccwpck_require__(36654); +} else { + module.exports = __nccwpck_require__(25696); } -function deterministicDecirc (val, k, edgeIndex, stack, parent, depth, options) { - depth += 1 - var i - if (typeof val === 'object' && val !== null) { - for (i = 0; i < stack.length; i++) { - if (stack[i] === val) { - setReplace(CIRCULAR_REPLACE_NODE, val, k, parent) - return - } - } - try { - if (typeof val.toJSON === 'function') { - return - } - } catch (_) { - return - } - if ( - typeof options.depthLimit !== 'undefined' && - depth > options.depthLimit - ) { - setReplace(LIMIT_REPLACE_NODE, val, k, parent) - return - } +/***/ }), - if ( - typeof options.edgesLimit !== 'undefined' && - edgeIndex + 1 > options.edgesLimit - ) { - setReplace(LIMIT_REPLACE_NODE, val, k, parent) - return - } +/***/ 25696: +/***/ ((module, exports, __nccwpck_require__) => { - stack.push(val) - // Optimize for Arrays. Big arrays could kill the performance otherwise! - if (Array.isArray(val)) { - for (i = 0; i < val.length; i++) { - deterministicDecirc(val[i], i, i, stack, val, depth, options) - } - } else { - // Create a temporary object in the required way - var tmp = {} - var keys = Object.keys(val).sort(compareFunction) - for (i = 0; i < keys.length; i++) { - var key = keys[i] - deterministicDecirc(val[key], key, i, stack, val, depth, options) - tmp[key] = val[key] - } - if (typeof parent !== 'undefined') { - arr.push([parent, k, val]) - parent[k] = tmp - } else { - return tmp - } - } - stack.pop() - } -} +/** + * Module dependencies. + */ -// wraps replacer function to handle values we couldn't replace -// and mark them as replaced value -function replaceGetterValues (replacer) { - replacer = - typeof replacer !== 'undefined' - ? replacer - : function (k, v) { - return v - } - return function (key, val) { - if (replacerStack.length > 0) { - for (var i = 0; i < replacerStack.length; i++) { - var part = replacerStack[i] - if (part[1] === key && part[0] === val) { - val = part[2] - replacerStack.splice(i, 1) - break - } - } - } - return replacer.call(this, key, val) - } -} +var tty = __nccwpck_require__(76224); +var util = __nccwpck_require__(73837); +/** + * This is the Node.js implementation of `debug()`. + * + * Expose `debug()` as the module. + */ -/***/ }), +exports = module.exports = __nccwpck_require__(86991); +exports.init = init; +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; -/***/ 34578: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/** + * Colors. + */ -"use strict"; +exports.colors = [6, 2, 3, 4, 5, 1]; -/* -Copyright (c) 2014 Petka Antonov +/** + * Build up the default `inspectOpts` object from the environment variables. + * + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + */ -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: +exports.inspectOpts = Object.keys(process.env).filter(function (key) { + return /^debug_/i.test(key); +}).reduce(function (obj, key) { + // camel-case + var prop = key + .substring(6) + .toLowerCase() + .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() }); -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. + // coerce string value into JS value + var val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) val = true; + else if (/^(no|off|false|disabled)$/i.test(val)) val = false; + else if (val === 'null') val = null; + else val = Number(val); -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -*/ -function Url() { - //For more efficient internal representation and laziness. - //The non-underscore versions of these properties are accessor functions - //defined on the prototype. - this._protocol = null; - this._href = ""; - this._port = -1; - this._query = null; + obj[prop] = val; + return obj; +}, {}); - this.auth = null; - this.slashes = null; - this.host = null; - this.hostname = null; - this.hash = null; - this.search = null; - this.pathname = null; +/** + * The file descriptor to write the `debug()` calls to. + * Set the `DEBUG_FD` env variable to override with another value. i.e.: + * + * $ DEBUG_FD=3 node script.js 3>debug.log + */ - this._prependSlash = false; -} +var fd = parseInt(process.env.DEBUG_FD, 10) || 2; -var querystring = __nccwpck_require__(63477); +if (1 !== fd && 2 !== fd) { + util.deprecate(function(){}, 'except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)')() +} -Url.queryString = querystring; +var stream = 1 === fd ? process.stdout : + 2 === fd ? process.stderr : + createWritableStdioStream(fd); -Url.prototype.parse = -function Url$parse(str, parseQueryString, hostDenotesSlash, disableAutoEscapeChars) { - if (typeof str !== "string") { - throw new TypeError("Parameter 'url' must be a string, not " + - typeof str); - } - var start = 0; - var end = str.length - 1; +/** + * Is stdout a TTY? Colored output is enabled when `true`. + */ - //Trim leading and trailing ws - while (str.charCodeAt(start) <= 0x20 /*' '*/) start++; - while (str.charCodeAt(end) <= 0x20 /*' '*/) end--; +function useColors() { + return 'colors' in exports.inspectOpts + ? Boolean(exports.inspectOpts.colors) + : tty.isatty(fd); +} - start = this._parseProtocol(str, start, end); +/** + * Map %o to `util.inspect()`, all on a single line. + */ - //Javascript doesn't have host - if (this._protocol !== "javascript") { - start = this._parseHost(str, start, end, hostDenotesSlash); - var proto = this._protocol; - if (!this.hostname && - (this.slashes || (proto && !slashProtocols[proto]))) { - this.hostname = this.host = ""; - } - } - - if (start <= end) { - var ch = str.charCodeAt(start); - - if (ch === 0x2F /*'/'*/ || ch === 0x5C /*'\'*/) { - this._parsePath(str, start, end, disableAutoEscapeChars); - } - else if (ch === 0x3F /*'?'*/) { - this._parseQuery(str, start, end, disableAutoEscapeChars); - } - else if (ch === 0x23 /*'#'*/) { - this._parseHash(str, start, end, disableAutoEscapeChars); - } - else if (this._protocol !== "javascript") { - this._parsePath(str, start, end, disableAutoEscapeChars); - } - else { //For javascript the pathname is just the rest of it - this.pathname = str.slice(start, end + 1 ); - } - - } - - if (!this.pathname && this.hostname && - this._slashProtocols[this._protocol]) { - this.pathname = "/"; - } - - if (parseQueryString) { - var search = this.search; - if (search == null) { - search = this.search = ""; - } - if (search.charCodeAt(0) === 0x3F /*'?'*/) { - search = search.slice(1); - } - //This calls a setter function, there is no .query data property - this.query = Url.queryString.parse(search); - } -}; - -Url.prototype.resolve = function Url$resolve(relative) { - return this.resolveObject(Url.parse(relative, false, true)).format(); +exports.formatters.o = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts) + .split('\n').map(function(str) { + return str.trim() + }).join(' '); }; -Url.prototype.format = function Url$format() { - var auth = this.auth || ""; - - if (auth) { - auth = encodeURIComponent(auth); - auth = auth.replace(/%3A/i, ":"); - auth += "@"; - } - - var protocol = this.protocol || ""; - var pathname = this.pathname || ""; - var hash = this.hash || ""; - var search = this.search || ""; - var query = ""; - var hostname = this.hostname || ""; - var port = this.port || ""; - var host = false; - var scheme = ""; - - //Cache the result of the getter function - var q = this.query; - if (q && typeof q === "object") { - query = Url.queryString.stringify(q); - } - - if (!search) { - search = query ? "?" + query : ""; - } +/** + * Map %o to `util.inspect()`, allowing multiple lines if needed. + */ - if (protocol && protocol.charCodeAt(protocol.length - 1) !== 0x3A /*':'*/) - protocol += ":"; +exports.formatters.O = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); +}; - if (this.host) { - host = auth + this.host; - } - else if (hostname) { - var ip6 = hostname.indexOf(":") > -1; - if (ip6) hostname = "[" + hostname + "]"; - host = auth + hostname + (port ? ":" + port : ""); - } +/** + * Adds ANSI color escape codes if enabled. + * + * @api public + */ - var slashes = this.slashes || - ((!protocol || - slashProtocols[protocol]) && host !== false); +function formatArgs(args) { + var name = this.namespace; + var useColors = this.useColors; + if (useColors) { + var c = this.color; + var prefix = ' \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m'; - if (protocol) scheme = protocol + (slashes ? "//" : ""); - else if (slashes) scheme = "//"; + args[0] = prefix + args[0].split('\n').join('\n' + prefix); + args.push('\u001b[3' + c + 'm+' + exports.humanize(this.diff) + '\u001b[0m'); + } else { + args[0] = new Date().toUTCString() + + ' ' + name + ' ' + args[0]; + } +} - if (slashes && pathname && pathname.charCodeAt(0) !== 0x2F /*'/'*/) { - pathname = "/" + pathname; - } - if (search && search.charCodeAt(0) !== 0x3F /*'?'*/) - search = "?" + search; - if (hash && hash.charCodeAt(0) !== 0x23 /*'#'*/) - hash = "#" + hash; +/** + * Invokes `util.format()` with the specified arguments and writes to `stream`. + */ - pathname = escapePathName(pathname); - search = escapeSearch(search); +function log() { + return stream.write(util.format.apply(util, arguments) + '\n'); +} - return scheme + (host === false ? "" : host) + pathname + search + hash; -}; +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ -Url.prototype.resolveObject = function Url$resolveObject(relative) { - if (typeof relative === "string") - relative = Url.parse(relative, false, true); +function save(namespaces) { + if (null == namespaces) { + // If you set a process.env field to null or undefined, it gets cast to the + // string 'null' or 'undefined'. Just delete instead. + delete process.env.DEBUG; + } else { + process.env.DEBUG = namespaces; + } +} - var result = this._clone(); +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ - // hash is always overridden, no matter what. - // even href="" will remove it. - result.hash = relative.hash; +function load() { + return process.env.DEBUG; +} - // if the relative url is empty, then there"s nothing left to do here. - if (!relative.href) { - result._href = ""; - return result; - } +/** + * Copied from `node/src/node.js`. + * + * XXX: It's lame that node doesn't expose this API out-of-the-box. It also + * relies on the undocumented `tty_wrap.guessHandleType()` which is also lame. + */ - // hrefs like //foo/bar always cut to the protocol. - if (relative.slashes && !relative._protocol) { - relative._copyPropsTo(result, true); +function createWritableStdioStream (fd) { + var stream; + var tty_wrap = process.binding('tty_wrap'); - if (slashProtocols[result._protocol] && - result.hostname && !result.pathname) { - result.pathname = "/"; - } - result._href = ""; - return result; - } + // Note stream._type is used for test-module-load-list.js - if (relative._protocol && relative._protocol !== result._protocol) { - // if it"s a known url protocol, then changing - // the protocol does weird things - // first, if it"s not file:, then we MUST have a host, - // and if there was a path - // to begin with, then we MUST have a path. - // if it is file:, then the host is dropped, - // because that"s known to be hostless. - // anything else is assumed to be absolute. - if (!slashProtocols[relative._protocol]) { - relative._copyPropsTo(result, false); - result._href = ""; - return result; - } + switch (tty_wrap.guessHandleType(fd)) { + case 'TTY': + stream = new tty.WriteStream(fd); + stream._type = 'tty'; - result._protocol = relative._protocol; - if (!relative.host && relative._protocol !== "javascript") { - var relPath = (relative.pathname || "").split("/"); - while (relPath.length && !(relative.host = relPath.shift())); - if (!relative.host) relative.host = ""; - if (!relative.hostname) relative.hostname = ""; - if (relPath[0] !== "") relPath.unshift(""); - if (relPath.length < 2) relPath.unshift(""); - result.pathname = relPath.join("/"); - } else { - result.pathname = relative.pathname; - } + // Hack to have stream not keep the event loop alive. + // See https://github.com/joyent/node/issues/1726 + if (stream._handle && stream._handle.unref) { + stream._handle.unref(); + } + break; - result.search = relative.search; - result.host = relative.host || ""; - result.auth = relative.auth; - result.hostname = relative.hostname || relative.host; - result._port = relative._port; - result.slashes = result.slashes || relative.slashes; - result._href = ""; - return result; - } + case 'FILE': + var fs = __nccwpck_require__(57147); + stream = new fs.SyncWriteStream(fd, { autoClose: false }); + stream._type = 'fs'; + break; - var isSourceAbs = - (result.pathname && result.pathname.charCodeAt(0) === 0x2F /*'/'*/); - var isRelAbs = ( - relative.host || - (relative.pathname && - relative.pathname.charCodeAt(0) === 0x2F /*'/'*/) - ); - var mustEndAbs = (isRelAbs || isSourceAbs || - (result.host && relative.pathname)); + case 'PIPE': + case 'TCP': + var net = __nccwpck_require__(41808); + stream = new net.Socket({ + fd: fd, + readable: false, + writable: true + }); - var removeAllDots = mustEndAbs; + // FIXME Should probably have an option in net.Socket to create a + // stream from an existing fd which is writable only. But for now + // we'll just add this hack and set the `readable` member to false. + // Test: ./node test/fixtures/echo.js < /etc/passwd + stream.readable = false; + stream.read = null; + stream._type = 'pipe'; - var srcPath = result.pathname && result.pathname.split("/") || []; - var relPath = relative.pathname && relative.pathname.split("/") || []; - var psychotic = result._protocol && !slashProtocols[result._protocol]; + // FIXME Hack to have stream not keep the event loop alive. + // See https://github.com/joyent/node/issues/1726 + if (stream._handle && stream._handle.unref) { + stream._handle.unref(); + } + break; - // if the url is a non-slashed url, then relative - // links like ../.. should be able - // to crawl up to the hostname, as well. This is strange. - // result.protocol has already been set by now. - // Later on, put the first path part into the host field. - if (psychotic) { - result.hostname = ""; - result._port = -1; - if (result.host) { - if (srcPath[0] === "") srcPath[0] = result.host; - else srcPath.unshift(result.host); - } - result.host = ""; - if (relative._protocol) { - relative.hostname = ""; - relative._port = -1; - if (relative.host) { - if (relPath[0] === "") relPath[0] = relative.host; - else relPath.unshift(relative.host); - } - relative.host = ""; - } - mustEndAbs = mustEndAbs && (relPath[0] === "" || srcPath[0] === ""); - } + default: + // Probably an error on in uv_guess_handle() + throw new Error('Implement me. Unknown stream file type!'); + } - if (isRelAbs) { - // it"s absolute. - result.host = relative.host ? - relative.host : result.host; - result.hostname = relative.hostname ? - relative.hostname : result.hostname; - result.search = relative.search; - srcPath = relPath; - // fall through to the dot-handling below. - } else if (relPath.length) { - // it"s relative - // throw away the existing file, and take the new path instead. - if (!srcPath) srcPath = []; - srcPath.pop(); - srcPath = srcPath.concat(relPath); - result.search = relative.search; - } else if (relative.search) { - // just pull out the search. - // like href="?foo". - // Put this after the other two cases because it simplifies the booleans - if (psychotic) { - result.hostname = result.host = srcPath.shift(); - //occationaly the auth can get stuck only in host - //this especialy happens in cases like - //url.resolveObject("mailto:local1@domain1", "local2@domain2") - var authInHost = result.host && result.host.indexOf("@") > 0 ? - result.host.split("@") : false; - if (authInHost) { - result.auth = authInHost.shift(); - result.host = result.hostname = authInHost.shift(); - } - } - result.search = relative.search; - result._href = ""; - return result; - } + // For supporting legacy API we put the FD here. + stream.fd = fd; - if (!srcPath.length) { - // no path at all. easy. - // we"ve already handled the other stuff above. - result.pathname = null; - result._href = ""; - return result; - } + stream._isStdio = true; - // if a url ENDs in . or .., then it must get a trailing slash. - // however, if it ends in anything else non-slashy, - // then it must NOT get a trailing slash. - var last = srcPath.slice(-1)[0]; - var hasTrailingSlash = ( - (result.host || relative.host) && (last === "." || last === "..") || - last === ""); + return stream; +} - // strip single dots, resolve double dots to parent dir - // if the path tries to go above the root, `up` ends up > 0 - var up = 0; - for (var i = srcPath.length; i >= 0; i--) { - last = srcPath[i]; - if (last === ".") { - srcPath.splice(i, 1); - } else if (last === "..") { - srcPath.splice(i, 1); - up++; - } else if (up) { - srcPath.splice(i, 1); - up--; - } - } +/** + * Init logic for `debug` instances. + * + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. + */ - // if the path is allowed to go above the root, restore leading ..s - if (!mustEndAbs && !removeAllDots) { - for (; up--; up) { - srcPath.unshift(".."); - } - } +function init (debug) { + debug.inspectOpts = {}; - if (mustEndAbs && srcPath[0] !== "" && - (!srcPath[0] || srcPath[0].charCodeAt(0) !== 0x2F /*'/'*/)) { - srcPath.unshift(""); - } + var keys = Object.keys(exports.inspectOpts); + for (var i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } +} - if (hasTrailingSlash && (srcPath.join("/").substr(-1) !== "/")) { - srcPath.push(""); - } +/** + * Enable namespaces listed in `process.env.DEBUG` initially. + */ - var isAbsolute = srcPath[0] === "" || - (srcPath[0] && srcPath[0].charCodeAt(0) === 0x2F /*'/'*/); +exports.enable(load()); - // put the host back - if (psychotic) { - result.hostname = result.host = isAbsolute ? "" : - srcPath.length ? srcPath.shift() : ""; - //occationaly the auth can get stuck only in host - //this especialy happens in cases like - //url.resolveObject("mailto:local1@domain1", "local2@domain2") - var authInHost = result.host && result.host.indexOf("@") > 0 ? - result.host.split("@") : false; - if (authInHost) { - result.auth = authInHost.shift(); - result.host = result.hostname = authInHost.shift(); - } - } - mustEndAbs = mustEndAbs || (result.host && srcPath.length); +/***/ }), - if (mustEndAbs && !isAbsolute) { - srcPath.unshift(""); - } +/***/ 27025: +/***/ ((module) => { - result.pathname = srcPath.length === 0 ? null : srcPath.join("/"); - result.auth = relative.auth || result.auth; - result.slashes = result.slashes || relative.slashes; - result._href = ""; - return result; -}; +/** + * Helpers. + */ -var punycode = __nccwpck_require__(85477); -Url.prototype._hostIdna = function Url$_hostIdna(hostname) { - // IDNA Support: Returns a punycoded representation of "domain". - // It only converts parts of the domain name that - // have non-ASCII characters, i.e. it doesn't matter if - // you call it with a domain that already is ASCII-only. - return punycode.toASCII(hostname); -}; +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var y = d * 365.25; -var escapePathName = Url.prototype._escapePathName = -function Url$_escapePathName(pathname) { - if (!containsCharacter2(pathname, 0x23 /*'#'*/, 0x3F /*'?'*/)) { - return pathname; - } - //Avoid closure creation to keep this inlinable - return _escapePath(pathname); -}; +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ -var escapeSearch = Url.prototype._escapeSearch = -function Url$_escapeSearch(search) { - if (!containsCharacter2(search, 0x23 /*'#'*/, -1)) return search; - //Avoid closure creation to keep this inlinable - return _escapeSearch(search); +module.exports = function(val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isNaN(val) === false) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); }; -Url.prototype._parseProtocol = function Url$_parseProtocol(str, start, end) { - var doLowerCase = false; - var protocolCharacters = this._protocolCharacters; - - for (var i = start; i <= end; ++i) { - var ch = str.charCodeAt(i); +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ - if (ch === 0x3A /*':'*/) { - var protocol = str.slice(start, i); - if (doLowerCase) protocol = protocol.toLowerCase(); - this._protocol = protocol; - return i + 1; - } - else if (protocolCharacters[ch] === 1) { - if (ch < 0x61 /*'a'*/) - doLowerCase = true; - } - else { - return start; - } +function parse(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; + } +} - } - return start; -}; +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ -Url.prototype._parseAuth = function Url$_parseAuth(str, start, end, decode) { - var auth = str.slice(start, end + 1); - if (decode) { - auth = decodeURIComponent(auth); - } - this.auth = auth; -}; +function fmtShort(ms) { + if (ms >= d) { + return Math.round(ms / d) + 'd'; + } + if (ms >= h) { + return Math.round(ms / h) + 'h'; + } + if (ms >= m) { + return Math.round(ms / m) + 'm'; + } + if (ms >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; +} -Url.prototype._parsePort = function Url$_parsePort(str, start, end) { - //Internal format is integer for more efficient parsing - //and for efficient trimming of leading zeros - var port = 0; - //Distinguish between :0 and : (no port number at all) - var hadChars = false; - var validPort = true; +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ - for (var i = start; i <= end; ++i) { - var ch = str.charCodeAt(i); +function fmtLong(ms) { + return plural(ms, d, 'day') || + plural(ms, h, 'hour') || + plural(ms, m, 'minute') || + plural(ms, s, 'second') || + ms + ' ms'; +} - if (0x30 /*'0'*/ <= ch && ch <= 0x39 /*'9'*/) { - port = (10 * port) + (ch - 0x30 /*'0'*/); - hadChars = true; - } - else { - validPort = false; - if (ch === 0x5C/*'\'*/ || ch === 0x2F/*'/'*/) { - validPort = true; - } - break; - } +/** + * Pluralization helper. + */ - } - if ((port === 0 && !hadChars) || !validPort) { - if (!validPort) { - this._port = -2; - } - return 0; - } +function plural(ms, n, name) { + if (ms < n) { + return; + } + if (ms < n * 1.5) { + return Math.floor(ms / n) + ' ' + name; + } + return Math.ceil(ms / n) + ' ' + name + 's'; +} - this._port = port; - return i - start; -}; -Url.prototype._parseHost = -function Url$_parseHost(str, start, end, slashesDenoteHost) { - var hostEndingCharacters = this._hostEndingCharacters; - var first = str.charCodeAt(start); - var second = str.charCodeAt(start + 1); - if ((first === 0x2F /*'/'*/ || first === 0x5C /*'\'*/) && - (second === 0x2F /*'/'*/ || second === 0x5C /*'\'*/)) { - this.slashes = true; +/***/ }), - //The string starts with // - if (start === 0) { - //The string is just "//" - if (end < 2) return start; - //If slashes do not denote host and there is no auth, - //there is no host when the string starts with // - var hasAuth = - containsCharacter(str, 0x40 /*'@'*/, 2, hostEndingCharacters); - if (!hasAuth && !slashesDenoteHost) { - this.slashes = null; - return start; - } - } - //There is a host that starts after the // - start += 2; - } - //If there is no slashes, there is no hostname if - //1. there was no protocol at all - else if (!this._protocol || - //2. there was a protocol that requires slashes - //e.g. in 'http:asd' 'asd' is not a hostname - slashProtocols[this._protocol] - ) { - return start; - } +/***/ 24826: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - var doLowerCase = false; - var idna = false; - var hostNameStart = start; - var hostNameEnd = end; - var lastCh = -1; - var portLength = 0; - var charsAfterDot = 0; - var authNeedsDecoding = false; +"use strict"; - var j = -1; - //Find the last occurrence of an @-sign until hostending character is met - //also mark if decoding is needed for the auth portion - for (var i = start; i <= end; ++i) { - var ch = str.charCodeAt(i); +const validator = __nccwpck_require__(74174) +const parse = __nccwpck_require__(96214) +const redactor = __nccwpck_require__(17333) +const restorer = __nccwpck_require__(98806) +const { groupRedact, nestedRedact } = __nccwpck_require__(54865) +const state = __nccwpck_require__(41012) +const rx = __nccwpck_require__(9158) +const validate = validator() +const noop = (o) => o +noop.restore = noop - if (ch === 0x40 /*'@'*/) { - j = i; - } - //This check is very, very cheap. Unneeded decodeURIComponent is very - //very expensive - else if (ch === 0x25 /*'%'*/) { - authNeedsDecoding = true; - } - else if (hostEndingCharacters[ch] === 1) { - break; - } - } +const DEFAULT_CENSOR = '[REDACTED]' +fastRedact.rx = rx +fastRedact.validator = validator - //@-sign was found at index j, everything to the left from it - //is auth part - if (j > -1) { - this._parseAuth(str, start, j - 1, authNeedsDecoding); - //hostname starts after the last @-sign - start = hostNameStart = j + 1; - } +module.exports = fastRedact - //Host name is starting with a [ - if (str.charCodeAt(start) === 0x5B /*'['*/) { - for (var i = start + 1; i <= end; ++i) { - var ch = str.charCodeAt(i); +function fastRedact (opts = {}) { + const paths = Array.from(new Set(opts.paths || [])) + const serialize = 'serialize' in opts ? ( + opts.serialize === false ? opts.serialize + : (typeof opts.serialize === 'function' ? opts.serialize : JSON.stringify) + ) : JSON.stringify + const remove = opts.remove + if (remove === true && serialize !== JSON.stringify) { + throw Error('fast-redact – remove option may only be set when serializer is JSON.stringify') + } + const censor = remove === true + ? undefined + : 'censor' in opts ? opts.censor : DEFAULT_CENSOR - //Assume valid IP6 is between the brackets - if (ch === 0x5D /*']'*/) { - if (str.charCodeAt(i + 1) === 0x3A /*':'*/) { - portLength = this._parsePort(str, i + 2, end) + 1; - } - var hostname = str.slice(start + 1, i).toLowerCase(); - this.hostname = hostname; - this.host = this._port > 0 ? - "[" + hostname + "]:" + this._port : - "[" + hostname + "]"; - this.pathname = "/"; - return i + portLength + 1; - } - } - //Empty hostname, [ starts a path - return start; - } + const isCensorFct = typeof censor === 'function' + const censorFctTakesPath = isCensorFct && censor.length > 1 - for (var i = start; i <= end; ++i) { - if (charsAfterDot > 62) { - this.hostname = this.host = str.slice(start, i); - return i; - } - var ch = str.charCodeAt(i); + if (paths.length === 0) return serialize || noop - if (ch === 0x3A /*':'*/) { - portLength = this._parsePort(str, i + 1, end) + 1; - hostNameEnd = i - 1; - break; - } - else if (ch < 0x61 /*'a'*/) { - if (ch === 0x2E /*'.'*/) { - //Node.js ignores this error - /* - if (lastCh === DOT || lastCh === -1) { - this.hostname = this.host = ""; - return start; - } - */ - charsAfterDot = -1; - } - else if (0x41 /*'A'*/ <= ch && ch <= 0x5A /*'Z'*/) { - doLowerCase = true; - } - //Valid characters other than ASCII letters -, _, +, 0-9 - else if (!(ch === 0x2D /*'-'*/ || - ch === 0x5F /*'_'*/ || - ch === 0x2B /*'+'*/ || - (0x30 /*'0'*/ <= ch && ch <= 0x39 /*'9'*/)) - ) { - if (hostEndingCharacters[ch] === 0 && - this._noPrependSlashHostEnders[ch] === 0) { - this._prependSlash = true; - } - hostNameEnd = i - 1; - break; - } - } - else if (ch >= 0x7B /*'{'*/) { - if (ch <= 0x7E /*'~'*/) { - if (this._noPrependSlashHostEnders[ch] === 0) { - this._prependSlash = true; - } - hostNameEnd = i - 1; - break; - } - idna = true; - } - lastCh = ch; - charsAfterDot++; - } + validate({ paths, serialize, censor }) - //Node.js ignores this error - /* - if (lastCh === DOT) { - hostNameEnd--; - } - */ + const { wildcards, wcLen, secret } = parse({ paths, censor }) - if (hostNameEnd + 1 !== start && - hostNameEnd - hostNameStart <= 256) { - var hostname = str.slice(hostNameStart, hostNameEnd + 1); - if (doLowerCase) hostname = hostname.toLowerCase(); - if (idna) hostname = this._hostIdna(hostname); - this.hostname = hostname; - this.host = this._port > 0 ? hostname + ":" + this._port : hostname; - } + const compileRestore = restorer({ secret, wcLen }) + const strict = 'strict' in opts ? opts.strict : true - return hostNameEnd + 1 + portLength; + return redactor({ secret, wcLen, serialize, strict, isCensorFct, censorFctTakesPath }, state({ + secret, + censor, + compileRestore, + serialize, + groupRedact, + nestedRedact, + wildcards, + wcLen + })) +} -}; -Url.prototype._copyPropsTo = function Url$_copyPropsTo(input, noProtocol) { - if (!noProtocol) { - input._protocol = this._protocol; - } - input._href = this._href; - input._port = this._port; - input._prependSlash = this._prependSlash; - input.auth = this.auth; - input.slashes = this.slashes; - input.host = this.host; - input.hostname = this.hostname; - input.hash = this.hash; - input.search = this.search; - input.pathname = this.pathname; -}; +/***/ }), -Url.prototype._clone = function Url$_clone() { - var ret = new Url(); - ret._protocol = this._protocol; - ret._href = this._href; - ret._port = this._port; - ret._prependSlash = this._prependSlash; - ret.auth = this.auth; - ret.slashes = this.slashes; - ret.host = this.host; - ret.hostname = this.hostname; - ret.hash = this.hash; - ret.search = this.search; - ret.pathname = this.pathname; - return ret; -}; +/***/ 54865: +/***/ ((module) => { -Url.prototype._getComponentEscaped = -function Url$_getComponentEscaped(str, start, end, isAfterQuery) { - var cur = start; - var i = start; - var ret = ""; - var autoEscapeMap = isAfterQuery ? - this._afterQueryAutoEscapeMap : this._autoEscapeMap; - for (; i <= end; ++i) { - var ch = str.charCodeAt(i); - var escaped = autoEscapeMap[ch]; +"use strict"; - if (escaped !== "" && escaped !== undefined) { - if (cur < i) ret += str.slice(cur, i); - ret += escaped; - cur = i + 1; - } - } - if (cur < i + 1) ret += str.slice(cur, i); - return ret; -}; -Url.prototype._parsePath = -function Url$_parsePath(str, start, end, disableAutoEscapeChars) { - var pathStart = start; - var pathEnd = end; - var escape = false; - var autoEscapeCharacters = this._autoEscapeCharacters; - var prePath = this._port === -2 ? "/:" : ""; +module.exports = { + groupRedact, + groupRestore, + nestedRedact, + nestedRestore +} - for (var i = start; i <= end; ++i) { - var ch = str.charCodeAt(i); - if (ch === 0x23 /*'#'*/) { - this._parseHash(str, i, end, disableAutoEscapeChars); - pathEnd = i - 1; - break; - } - else if (ch === 0x3F /*'?'*/) { - this._parseQuery(str, i, end, disableAutoEscapeChars); - pathEnd = i - 1; - break; - } - else if (!disableAutoEscapeChars && !escape && autoEscapeCharacters[ch] === 1) { - escape = true; - } - } +function groupRestore ({ keys, values, target }) { + if (target == null) return + const length = keys.length + for (var i = 0; i < length; i++) { + const k = keys[i] + target[k] = values[i] + } +} - if (pathStart > pathEnd) { - this.pathname = prePath === "" ? "/" : prePath; - return; - } +function groupRedact (o, path, censor, isCensorFct, censorFctTakesPath) { + const target = get(o, path) + if (target == null) return { keys: null, values: null, target: null, flat: true } + const keys = Object.keys(target) + const keysLength = keys.length + const pathLength = path.length + const pathWithKey = censorFctTakesPath ? [...path] : undefined + const values = new Array(keysLength) - var path; - if (escape) { - path = this._getComponentEscaped(str, pathStart, pathEnd, false); - } - else { - path = str.slice(pathStart, pathEnd + 1); + for (var i = 0; i < keysLength; i++) { + const key = keys[i] + values[i] = target[key] + + if (censorFctTakesPath) { + pathWithKey[pathLength] = key + target[key] = censor(target[key], pathWithKey) + } else if (isCensorFct) { + target[key] = censor(target[key]) + } else { + target[key] = censor } - this.pathname = prePath === "" - ? (this._prependSlash ? "/" + path : path) - : prePath + path; -}; + } + return { keys, values, target, flat: true } +} -Url.prototype._parseQuery = function Url$_parseQuery(str, start, end, disableAutoEscapeChars) { - var queryStart = start; - var queryEnd = end; - var escape = false; - var autoEscapeCharacters = this._autoEscapeCharacters; +function nestedRestore (arr) { + const length = arr.length + for (var i = 0; i < length; i++) { + const { key, target, value } = arr[i] + target[key] = value + } +} - for (var i = start; i <= end; ++i) { - var ch = str.charCodeAt(i); +function nestedRedact (store, o, path, ns, censor, isCensorFct, censorFctTakesPath) { + const target = get(o, path) + if (target == null) return + const keys = Object.keys(target) + const keysLength = keys.length + for (var i = 0; i < keysLength; i++) { + const key = keys[i] + const { value, parent, exists } = + specialSet(target, key, path, ns, censor, isCensorFct, censorFctTakesPath) - if (ch === 0x23 /*'#'*/) { - this._parseHash(str, i, end, disableAutoEscapeChars); - queryEnd = i - 1; - break; - } - else if (!disableAutoEscapeChars && !escape && autoEscapeCharacters[ch] === 1) { - escape = true; - } + if (exists === true && parent !== null) { + store.push({ key: ns[ns.length - 1], target: parent, value }) } + } + return store +} - if (queryStart > queryEnd) { - this.search = ""; - return; - } +function has (obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop) +} - var query; - if (escape) { - query = this._getComponentEscaped(str, queryStart, queryEnd, true); - } - else { - query = str.slice(queryStart, queryEnd + 1); +function specialSet (o, k, path, afterPath, censor, isCensorFct, censorFctTakesPath) { + const afterPathLen = afterPath.length + const lastPathIndex = afterPathLen - 1 + const originalKey = k + var i = -1 + var n + var nv + var ov + var oov = null + var exists = true + ov = n = o[k] + if (typeof n !== 'object') return { value: null, parent: null, exists } + while (n != null && ++i < afterPathLen) { + k = afterPath[i] + oov = ov + if (!(k in n)) { + exists = false + break } - this.search = query; -}; + ov = n[k] + nv = (i !== lastPathIndex) + ? ov + : (isCensorFct + ? (censorFctTakesPath ? censor(ov, [...path, originalKey, ...afterPath]) : censor(ov)) + : censor) + n[k] = (has(n, k) && nv === ov) || (nv === undefined && censor !== undefined) ? n[k] : nv + n = n[k] + if (typeof n !== 'object') break + } + return { value: ov, parent: oov, exists } +} -Url.prototype._parseHash = function Url$_parseHash(str, start, end, disableAutoEscapeChars) { - if (start > end) { - this.hash = ""; - return; - } +function get (o, p) { + var i = -1 + var l = p.length + var n = o + while (n != null && ++i < l) { + n = n[p[i]] + } + return n +} - this.hash = disableAutoEscapeChars ? - str.slice(start, end + 1) : this._getComponentEscaped(str, start, end, true); -}; -Object.defineProperty(Url.prototype, "port", { - get: function() { - if (this._port >= 0) { - return ("" + this._port); - } - return null; - }, - set: function(v) { - if (v == null) { - this._port = -1; - } - else { - this._port = parseInt(v, 10); - } - } -}); +/***/ }), -Object.defineProperty(Url.prototype, "query", { - get: function() { - var query = this._query; - if (query != null) { - return query; - } - var search = this.search; +/***/ 96214: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (search) { - if (search.charCodeAt(0) === 0x3F /*'?'*/) { - search = search.slice(1); - } - if (search !== "") { - this._query = search; - return search; - } - } - return search; - }, - set: function(v) { - this._query = v; - } -}); +"use strict"; -Object.defineProperty(Url.prototype, "path", { - get: function() { - var p = this.pathname || ""; - var s = this.search || ""; - if (p || s) { - return p + s; - } - return (p == null && s) ? ("/" + s) : null; - }, - set: function() {} -}); -Object.defineProperty(Url.prototype, "protocol", { - get: function() { - var proto = this._protocol; - return proto ? proto + ":" : proto; - }, - set: function(v) { - if (typeof v === "string") { - var end = v.length - 1; - if (v.charCodeAt(end) === 0x3A /*':'*/) { - this._protocol = v.slice(0, end); - } - else { - this._protocol = v; - } - } - else if (v == null) { - this._protocol = null; - } - } -}); +const rx = __nccwpck_require__(9158) -Object.defineProperty(Url.prototype, "href", { - get: function() { - var href = this._href; - if (!href) { - href = this._href = this.format(); - } - return href; - }, - set: function(v) { - this._href = v; +module.exports = parse + +function parse ({ paths }) { + const wildcards = [] + var wcLen = 0 + const secret = paths.reduce(function (o, strPath, ix) { + var path = strPath.match(rx).map((p) => p.replace(/'|"|`/g, '')) + const leadingBracket = strPath[0] === '[' + path = path.map((p) => { + if (p[0] === '[') return p.substr(1, p.length - 2) + else return p + }) + const star = path.indexOf('*') + if (star > -1) { + const before = path.slice(0, star) + const beforeStr = before.join('.') + const after = path.slice(star + 1, path.length) + if (after.indexOf('*') > -1) throw Error('fast-redact – Only one wildcard per path is supported') + const nested = after.length > 0 + wcLen++ + wildcards.push({ + before, + beforeStr, + after, + nested + }) + } else { + o[strPath] = { + path: path, + val: undefined, + precensored: false, + circle: '', + escPath: JSON.stringify(strPath), + leadingBracket: leadingBracket + } } -}); + return o + }, {}) -Url.parse = function Url$Parse(str, parseQueryString, hostDenotesSlash, disableAutoEscapeChars) { - if (str instanceof Url) return str; - var ret = new Url(); - ret.parse(str, !!parseQueryString, !!hostDenotesSlash, !!disableAutoEscapeChars); - return ret; -}; + return { wildcards, wcLen, secret } +} -Url.format = function Url$Format(obj) { - if (typeof obj === "string") { - obj = Url.parse(obj); - } - if (!(obj instanceof Url)) { - return Url.prototype.format.call(obj); - } - return obj.format(); -}; -Url.resolve = function Url$Resolve(source, relative) { - return Url.parse(source, false, true).resolve(relative); -}; +/***/ }), -Url.resolveObject = function Url$ResolveObject(source, relative) { - if (!source) return relative; - return Url.parse(source, false, true).resolveObject(relative); -}; +/***/ 17333: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -function _escapePath(pathname) { - return pathname.replace(/[?#]/g, function(match) { - return encodeURIComponent(match); - }); -} +"use strict"; -function _escapeSearch(search) { - return search.replace(/#/g, function(match) { - return encodeURIComponent(match); - }); -} -//Search `char1` (integer code for a character) in `string` -//starting from `fromIndex` and ending at `string.length - 1` -//or when a stop character is found -function containsCharacter(string, char1, fromIndex, stopCharacterTable) { - var len = string.length; - for (var i = fromIndex; i < len; ++i) { - var ch = string.charCodeAt(i); +const rx = __nccwpck_require__(9158) - if (ch === char1) { - return true; - } - else if (stopCharacterTable[ch] === 1) { - return false; - } - } - return false; -} +module.exports = redactor -//See if `char1` or `char2` (integer codes for characters) -//is contained in `string` -function containsCharacter2(string, char1, char2) { - for (var i = 0, len = string.length; i < len; ++i) { - var ch = string.charCodeAt(i); - if (ch === char1 || ch === char2) return true; +function redactor ({ secret, serialize, wcLen, strict, isCensorFct, censorFctTakesPath }, state) { + /* eslint-disable-next-line */ + const redact = Function('o', ` + if (typeof o !== 'object' || o == null) { + ${strictImpl(strict, serialize)} } - return false; -} - -//Makes an array of 128 uint8's which represent boolean values. -//Spec is an array of ascii code points or ascii code point ranges -//ranges are expressed as [start, end] + const { censor, secret } = this + ${redactTmpl(secret, isCensorFct, censorFctTakesPath)} + this.compileRestore() + ${dynamicRedactTmpl(wcLen > 0, isCensorFct, censorFctTakesPath)} + ${resultTmpl(serialize)} + `).bind(state) -//Create a table with the characters 0x30-0x39 (decimals '0' - '9') and -//0x7A (lowercaseletter 'z') as `true`: -// -//var a = makeAsciiTable([[0x30, 0x39], 0x7A]); -//a[0x30]; //1 -//a[0x15]; //0 -//a[0x35]; //1 -function makeAsciiTable(spec) { - var ret = new Uint8Array(128); - spec.forEach(function(item){ - if (typeof item === "number") { - ret[item] = 1; - } - else { - var start = item[0]; - var end = item[1]; - for (var j = start; j <= end; ++j) { - ret[j] = 1; - } - } - }); + if (serialize === false) { + redact.restore = (o) => state.restore(o) + } - return ret; + return redact } +function redactTmpl (secret, isCensorFct, censorFctTakesPath) { + return Object.keys(secret).map((path) => { + const { escPath, leadingBracket, path: arrPath } = secret[path] + const skip = leadingBracket ? 1 : 0 + const delim = leadingBracket ? '' : '.' + const hops = [] + var match + while ((match = rx.exec(path)) !== null) { + const [ , ix ] = match + const { index, input } = match + if (index > skip) hops.push(input.substring(0, index - (ix ? 0 : 1))) + } + var existence = hops.map((p) => `o${delim}${p}`).join(' && ') + if (existence.length === 0) existence += `o${delim}${path} != null` + else existence += ` && o${delim}${path} != null` -var autoEscape = ["<", ">", "\"", "`", " ", "\r", "\n", - "\t", "{", "}", "|", "\\", "^", "`", "'"]; + const circularDetection = ` + switch (true) { + ${hops.reverse().map((p) => ` + case o${delim}${p} === censor: + secret[${escPath}].circle = ${JSON.stringify(p)} + break + `).join('\n')} + } + ` -var autoEscapeMap = new Array(128); + const censorArgs = censorFctTakesPath + ? `val, ${JSON.stringify(arrPath)}` + : `val` + return ` + if (${existence}) { + const val = o${delim}${path} + if (val === censor) { + secret[${escPath}].precensored = true + } else { + secret[${escPath}].val = val + o${delim}${path} = ${isCensorFct ? `censor(${censorArgs})` : 'censor'} + ${circularDetection} + } + } + ` + }).join('\n') +} +function dynamicRedactTmpl (hasWildcards, isCensorFct, censorFctTakesPath) { + return hasWildcards === true ? ` + { + const { wildcards, wcLen, groupRedact, nestedRedact } = this + for (var i = 0; i < wcLen; i++) { + const { before, beforeStr, after, nested } = wildcards[i] + if (nested === true) { + secret[beforeStr] = secret[beforeStr] || [] + nestedRedact(secret[beforeStr], o, before, after, censor, ${isCensorFct}, ${censorFctTakesPath}) + } else secret[beforeStr] = groupRedact(o, before, censor, ${isCensorFct}, ${censorFctTakesPath}) + } + } + ` : '' +} -for (var i = 0, len = autoEscapeMap.length; i < len; ++i) { - autoEscapeMap[i] = ""; +function resultTmpl (serialize) { + return serialize === false ? `return o` : ` + var s = this.serialize(o) + this.restore(o) + return s + ` } -for (var i = 0, len = autoEscape.length; i < len; ++i) { - var c = autoEscape[i]; - var esc = encodeURIComponent(c); - if (esc === c) { - esc = escape(c); - } - autoEscapeMap[c.charCodeAt(0)] = esc; +function strictImpl (strict, serialize) { + return strict === true + ? `throw Error('fast-redact: primitives cannot be redacted')` + : serialize === false ? `return o` : `return this.serialize(o)` } -var afterQueryAutoEscapeMap = autoEscapeMap.slice(); -autoEscapeMap[0x5C /*'\'*/] = "/"; -var slashProtocols = Url.prototype._slashProtocols = { - http: true, - https: true, - gopher: true, - file: true, - ftp: true, - "http:": true, - "https:": true, - "gopher:": true, - "file:": true, - "ftp:": true -}; +/***/ }), -//Optimize back from normalized object caused by non-identifier keys -function f(){} -f.prototype = slashProtocols; +/***/ 98806: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -Url.prototype._protocolCharacters = makeAsciiTable([ - [0x61 /*'a'*/, 0x7A /*'z'*/], - [0x41 /*'A'*/, 0x5A /*'Z'*/], - 0x2E /*'.'*/, 0x2B /*'+'*/, 0x2D /*'-'*/ -]); +"use strict"; -Url.prototype._hostEndingCharacters = makeAsciiTable([ - 0x23 /*'#'*/, 0x3F /*'?'*/, 0x2F /*'/'*/, 0x5C /*'\'*/ -]); -Url.prototype._autoEscapeCharacters = makeAsciiTable( - autoEscape.map(function(v) { - return v.charCodeAt(0); - }) -); +const { groupRestore, nestedRestore } = __nccwpck_require__(54865) -//If these characters end a host name, the path will not be prepended a / -Url.prototype._noPrependSlashHostEnders = makeAsciiTable( - [ - "<", ">", "'", "`", " ", "\r", - "\n", "\t", "{", "}", "|", - "^", "`", "\"", "%", ";" - ].map(function(v) { - return v.charCodeAt(0); - }) -); +module.exports = restorer -Url.prototype._autoEscapeMap = autoEscapeMap; -Url.prototype._afterQueryAutoEscapeMap = afterQueryAutoEscapeMap; +function restorer ({ secret, wcLen }) { + return function compileRestore () { + if (this.restore) return + const paths = Object.keys(secret) + const resetters = resetTmpl(secret, paths) + const hasWildcards = wcLen > 0 + const state = hasWildcards ? { secret, groupRestore, nestedRestore } : { secret } + /* eslint-disable-next-line */ + this.restore = Function( + 'o', + restoreTmpl(resetters, paths, hasWildcards) + ).bind(state) + } +} -module.exports = Url; +/** + * Mutates the original object to be censored by restoring its original values + * prior to censoring. + * + * @param {object} secret Compiled object describing which target fields should + * be censored and the field states. + * @param {string[]} paths The list of paths to censor as provided at + * initialization time. + * + * @returns {string} String of JavaScript to be used by `Function()`. The + * string compiles to the function that does the work in the description. + */ +function resetTmpl (secret, paths) { + return paths.map((path) => { + const { circle, escPath, leadingBracket } = secret[path] + const delim = leadingBracket ? '' : '.' + const reset = circle + ? `o.${circle} = secret[${escPath}].val` + : `o${delim}${path} = secret[${escPath}].val` + const clear = `secret[${escPath}].val = undefined` + return ` + if (secret[${escPath}].val !== undefined) { + try { ${reset} } catch (e) {} + ${clear} + } + ` + }).join('') +} -Url.replace = function Url$Replace() { - require.cache.url = { - exports: Url - }; -}; +/** + * Creates the body of the restore function + * + * Restoration of the redacted object happens + * backwards, in reverse order of redactions, + * so that repeated redactions on the same object + * property can be eventually rolled back to the + * original value. + * + * This way dynamic redactions are restored first, + * starting from the last one working backwards and + * followed by the static ones. + * + * @returns {string} the body of the restore function + */ +function restoreTmpl (resetters, paths, hasWildcards) { + const dynamicReset = hasWildcards === true ? ` + const keys = Object.keys(secret) + const len = keys.length + for (var i = len - 1; i >= ${paths.length}; i--) { + const k = keys[i] + const o = secret[k] + if (o.flat === true) this.groupRestore(o) + else this.nestedRestore(o) + secret[k] = null + } + ` : '' + + return ` + const secret = this.secret + ${dynamicReset} + ${resetters} + return o + ` +} /***/ }), -/***/ 30810: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 9158: +/***/ ((module) => { "use strict"; -/*! - * finalhandler - * Copyright(c) 2014-2017 Douglas Christopher Wilson - * MIT Licensed - */ +module.exports = /[^.[\]]+|\[((?:.)*?)\]/g -/** - * Module dependencies. - * @private - */ +/* +Regular expression explanation: -var debug = __nccwpck_require__(65612)('finalhandler') -var encodeUrl = __nccwpck_require__(16592) -var escapeHtml = __nccwpck_require__(94070) -var onFinished = __nccwpck_require__(24694) -var parseUrl = __nccwpck_require__(89808) -var statuses = __nccwpck_require__(57415) -var unpipe = __nccwpck_require__(3124) +Alt 1: /[^.[\]]+/ - Match one or more characters that are *not* a dot (.) + opening square bracket ([) or closing square bracket (]) -/** - * Module variables. - * @private - */ +Alt 2: /\[((?:.)*?)\]/ - If the char IS dot or square bracket, then create a capture + group (which will be capture group $1) that matches anything + within square brackets. Expansion is lazy so it will + stop matching as soon as the first closing bracket is met `]` + (rather than continuing to match until the final closing bracket). +*/ -var DOUBLE_SPACE_REGEXP = /\x20{2}/g -var NEWLINE_REGEXP = /\n/g -/* istanbul ignore next */ -var defer = typeof setImmediate === 'function' - ? setImmediate - : function (fn) { process.nextTick(fn.bind.apply(fn, arguments)) } -var isFinished = onFinished.isFinished +/***/ }), -/** - * Create a minimal HTML document. - * - * @param {string} message - * @private - */ +/***/ 41012: +/***/ ((module) => { -function createHtmlDocument (message) { - var body = escapeHtml(message) - .replace(NEWLINE_REGEXP, '
') - .replace(DOUBLE_SPACE_REGEXP, '  ') +"use strict"; - return '\n' + - '\n' + - '\n' + - '\n' + - 'Error\n' + - '\n' + - '\n' + - '
' + body + '
\n' + - '\n' + - '\n' -} -/** - * Module exports. - * @public - */ +module.exports = state -module.exports = finalhandler +function state (o) { + const { + secret, + censor, + compileRestore, + serialize, + groupRedact, + nestedRedact, + wildcards, + wcLen + } = o + const builder = [{ secret, censor, compileRestore }] + if (serialize !== false) builder.push({ serialize }) + if (wcLen > 0) builder.push({ groupRedact, nestedRedact, wildcards, wcLen }) + return Object.assign(...builder) +} -/** - * Create a function to handle the final response. - * - * @param {Request} req - * @param {Response} res - * @param {Object} [options] - * @return {Function} - * @public - */ -function finalhandler (req, res, options) { - var opts = options || {} +/***/ }), - // get environment - var env = opts.env || process.env.NODE_ENV || 'development' +/***/ 74174: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // get error callback - var onerror = opts.onerror +"use strict"; - return function (err) { - var headers - var msg - var status - // ignore 404 on in-flight response - if (!err && headersSent(res)) { - debug('cannot 404 after headers sent') - return - } +const { createContext, runInContext } = __nccwpck_require__(26144) - // unhandled error - if (err) { - // respect status code from error - status = getErrorStatusCode(err) +module.exports = validator - if (status === undefined) { - // fallback to status code on response - status = getResponseStatusCode(res) - } else { - // respect headers from error - headers = getErrorHeaders(err) +function validator (opts = {}) { + const { + ERR_PATHS_MUST_BE_STRINGS = () => 'fast-redact - Paths must be (non-empty) strings', + ERR_INVALID_PATH = (s) => `fast-redact – Invalid path (${s})` + } = opts + + return function validate ({ paths }) { + paths.forEach((s) => { + if (typeof s !== 'string') { + throw Error(ERR_PATHS_MUST_BE_STRINGS()) + } + try { + if (/〇/.test(s)) throw Error() + const proxy = new Proxy({}, { get: () => proxy, set: () => { throw Error() } }) + const expr = (s[0] === '[' ? '' : '.') + s.replace(/^\*/, '〇').replace(/\.\*/g, '.〇').replace(/\[\*\]/g, '[〇]') + if (/\n|\r|;/.test(expr)) throw Error() + if (/\/\*/.test(expr)) throw Error() + runInContext(` + (function () { + 'use strict' + o${expr} + if ([o${expr}].length !== 1) throw Error() + })() + `, createContext({ o: proxy, 〇: null }), { + codeGeneration: { strings: false, wasm: false } + }) + } catch (e) { + throw Error(ERR_INVALID_PATH(s)) } + }) + } +} - // get error message - msg = getErrorMessage(err, status, env) - } else { - // not found - status = 404 - msg = 'Cannot ' + req.method + ' ' + encodeUrl(getResourceName(req)) - } - debug('default %s', status) +/***/ }), - // schedule onerror callback - if (err && onerror) { - defer(onerror, err, req, res) - } +/***/ 17676: +/***/ ((module) => { - // cannot actually respond - if (headersSent(res)) { - debug('cannot %d after headers sent', status) - req.socket.destroy() - return - } +module.exports = stringify +stringify.default = stringify +stringify.stable = deterministicStringify +stringify.stableStringify = deterministicStringify - // send response - send(req, res, status, headers, msg) - } -} +var LIMIT_REPLACE_NODE = '[...]' +var CIRCULAR_REPLACE_NODE = '[Circular]' -/** - * Get headers from Error object. - * - * @param {Error} err - * @return {object} - * @private - */ +var arr = [] +var replacerStack = [] -function getErrorHeaders (err) { - if (!err.headers || typeof err.headers !== 'object') { - return undefined +function defaultOptions () { + return { + depthLimit: Number.MAX_SAFE_INTEGER, + edgesLimit: Number.MAX_SAFE_INTEGER } +} - var headers = Object.create(null) - var keys = Object.keys(err.headers) +// Regular stringify +function stringify (obj, replacer, spacer, options) { + if (typeof options === 'undefined') { + options = defaultOptions() + } - for (var i = 0; i < keys.length; i++) { - var key = keys[i] - headers[key] = err.headers[key] + decirc(obj, '', 0, [], undefined, 0, options) + var res + try { + if (replacerStack.length === 0) { + res = JSON.stringify(obj, replacer, spacer) + } else { + res = JSON.stringify(obj, replaceGetterValues(replacer), spacer) + } + } catch (_) { + return JSON.stringify('[unable to serialize, circular reference is too complex to analyze]') + } finally { + while (arr.length !== 0) { + var part = arr.pop() + if (part.length === 4) { + Object.defineProperty(part[0], part[1], part[3]) + } else { + part[0][part[1]] = part[2] + } + } } + return res +} - return headers +function setReplace (replace, val, k, parent) { + var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k) + if (propertyDescriptor.get !== undefined) { + if (propertyDescriptor.configurable) { + Object.defineProperty(parent, k, { value: replace }) + arr.push([parent, k, val, propertyDescriptor]) + } else { + replacerStack.push([val, k, replace]) + } + } else { + parent[k] = replace + arr.push([parent, k, val]) + } } -/** - * Get message from Error object, fallback to status message. - * - * @param {Error} err - * @param {number} status - * @param {string} env - * @return {string} - * @private - */ +function decirc (val, k, edgeIndex, stack, parent, depth, options) { + depth += 1 + var i + if (typeof val === 'object' && val !== null) { + for (i = 0; i < stack.length; i++) { + if (stack[i] === val) { + setReplace(CIRCULAR_REPLACE_NODE, val, k, parent) + return + } + } -function getErrorMessage (err, status, env) { - var msg + if ( + typeof options.depthLimit !== 'undefined' && + depth > options.depthLimit + ) { + setReplace(LIMIT_REPLACE_NODE, val, k, parent) + return + } - if (env !== 'production') { - // use err.stack, which typically includes err.message - msg = err.stack + if ( + typeof options.edgesLimit !== 'undefined' && + edgeIndex + 1 > options.edgesLimit + ) { + setReplace(LIMIT_REPLACE_NODE, val, k, parent) + return + } - // fallback to err.toString() when possible - if (!msg && typeof err.toString === 'function') { - msg = err.toString() + stack.push(val) + // Optimize for Arrays. Big arrays could kill the performance otherwise! + if (Array.isArray(val)) { + for (i = 0; i < val.length; i++) { + decirc(val[i], i, i, stack, val, depth, options) + } + } else { + var keys = Object.keys(val) + for (i = 0; i < keys.length; i++) { + var key = keys[i] + decirc(val[key], key, i, stack, val, depth, options) + } } + stack.pop() } - - return msg || statuses[status] } -/** - * Get status code from Error object. - * - * @param {Error} err - * @return {number} - * @private - */ - -function getErrorStatusCode (err) { - // check err.status - if (typeof err.status === 'number' && err.status >= 400 && err.status < 600) { - return err.status +// Stable-stringify +function compareFunction (a, b) { + if (a < b) { + return -1 } - - // check err.statusCode - if (typeof err.statusCode === 'number' && err.statusCode >= 400 && err.statusCode < 600) { - return err.statusCode + if (a > b) { + return 1 } - - return undefined + return 0 } -/** - * Get resource name for the request. - * - * This is typically just the original pathname of the request - * but will fallback to "resource" is that cannot be determined. - * - * @param {IncomingMessage} req - * @return {string} - * @private - */ +function deterministicStringify (obj, replacer, spacer, options) { + if (typeof options === 'undefined') { + options = defaultOptions() + } -function getResourceName (req) { + var tmp = deterministicDecirc(obj, '', 0, [], undefined, 0, options) || obj + var res try { - return parseUrl.original(req).pathname - } catch (e) { - return 'resource' + if (replacerStack.length === 0) { + res = JSON.stringify(tmp, replacer, spacer) + } else { + res = JSON.stringify(tmp, replaceGetterValues(replacer), spacer) + } + } catch (_) { + return JSON.stringify('[unable to serialize, circular reference is too complex to analyze]') + } finally { + // Ensure that we restore the object as it was. + while (arr.length !== 0) { + var part = arr.pop() + if (part.length === 4) { + Object.defineProperty(part[0], part[1], part[3]) + } else { + part[0][part[1]] = part[2] + } + } } + return res } -/** - * Get status code from response. - * - * @param {OutgoingMessage} res - * @return {number} - * @private - */ +function deterministicDecirc (val, k, edgeIndex, stack, parent, depth, options) { + depth += 1 + var i + if (typeof val === 'object' && val !== null) { + for (i = 0; i < stack.length; i++) { + if (stack[i] === val) { + setReplace(CIRCULAR_REPLACE_NODE, val, k, parent) + return + } + } + try { + if (typeof val.toJSON === 'function') { + return + } + } catch (_) { + return + } -function getResponseStatusCode (res) { - var status = res.statusCode + if ( + typeof options.depthLimit !== 'undefined' && + depth > options.depthLimit + ) { + setReplace(LIMIT_REPLACE_NODE, val, k, parent) + return + } - // default status code to 500 if outside valid range - if (typeof status !== 'number' || status < 400 || status > 599) { - status = 500 - } + if ( + typeof options.edgesLimit !== 'undefined' && + edgeIndex + 1 > options.edgesLimit + ) { + setReplace(LIMIT_REPLACE_NODE, val, k, parent) + return + } - return status + stack.push(val) + // Optimize for Arrays. Big arrays could kill the performance otherwise! + if (Array.isArray(val)) { + for (i = 0; i < val.length; i++) { + deterministicDecirc(val[i], i, i, stack, val, depth, options) + } + } else { + // Create a temporary object in the required way + var tmp = {} + var keys = Object.keys(val).sort(compareFunction) + for (i = 0; i < keys.length; i++) { + var key = keys[i] + deterministicDecirc(val[key], key, i, stack, val, depth, options) + tmp[key] = val[key] + } + if (typeof parent !== 'undefined') { + arr.push([parent, k, val]) + parent[k] = tmp + } else { + return tmp + } + } + stack.pop() + } } -/** - * Determine if the response headers have been sent. - * - * @param {object} res - * @returns {boolean} - * @private - */ - -function headersSent (res) { - return typeof res.headersSent !== 'boolean' - ? Boolean(res._header) - : res.headersSent +// wraps replacer function to handle values we couldn't replace +// and mark them as replaced value +function replaceGetterValues (replacer) { + replacer = + typeof replacer !== 'undefined' + ? replacer + : function (k, v) { + return v + } + return function (key, val) { + if (replacerStack.length > 0) { + for (var i = 0; i < replacerStack.length; i++) { + var part = replacerStack[i] + if (part[1] === key && part[0] === val) { + val = part[2] + replacerStack.splice(i, 1) + break + } + } + } + return replacer.call(this, key, val) + } } -/** - * Send response. - * - * @param {IncomingMessage} req - * @param {OutgoingMessage} res - * @param {number} status - * @param {object} headers - * @param {string} message - * @private - */ - -function send (req, res, status, headers, message) { - function write () { - // response body - var body = createHtmlDocument(message) - - // response status - res.statusCode = status - res.statusMessage = statuses[status] - - // response headers - setHeaders(res, headers) - // security headers - res.setHeader('Content-Security-Policy', "default-src 'none'") - res.setHeader('X-Content-Type-Options', 'nosniff') +/***/ }), - // standard headers - res.setHeader('Content-Type', 'text/html; charset=utf-8') - res.setHeader('Content-Length', Buffer.byteLength(body, 'utf8')) +/***/ 34578: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (req.method === 'HEAD') { - res.end() - return - } +"use strict"; - res.end(body, 'utf8') - } +/* +Copyright (c) 2014 Petka Antonov - if (isFinished(req)) { - write() - return - } +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: - // unpipe everything from the request - unpipe(req) +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. - // flush the request - onFinished(req, write) - req.resume() -} - -/** - * Set response headers from an object. - * - * @param {OutgoingMessage} res - * @param {object} headers - * @private - */ +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ +function Url() { + //For more efficient internal representation and laziness. + //The non-underscore versions of these properties are accessor functions + //defined on the prototype. + this._protocol = null; + this._href = ""; + this._port = -1; + this._query = null; -function setHeaders (res, headers) { - if (!headers) { - return - } + this.auth = null; + this.slashes = null; + this.host = null; + this.hostname = null; + this.hash = null; + this.search = null; + this.pathname = null; - var keys = Object.keys(headers) - for (var i = 0; i < keys.length; i++) { - var key = keys[i] - res.setHeader(key, headers[key]) - } + this._prependSlash = false; } +var querystring = __nccwpck_require__(63477); -/***/ }), +Url.queryString = querystring; -/***/ 56401: -/***/ ((module, exports, __nccwpck_require__) => { +Url.prototype.parse = +function Url$parse(str, parseQueryString, hostDenotesSlash, disableAutoEscapeChars) { + if (typeof str !== "string") { + throw new TypeError("Parameter 'url' must be a string, not " + + typeof str); + } + var start = 0; + var end = str.length - 1; -/** - * This is the web browser implementation of `debug()`. - * - * Expose `debug()` as the module. - */ + //Trim leading and trailing ws + while (str.charCodeAt(start) <= 0x20 /*' '*/) start++; + while (str.charCodeAt(end) <= 0x20 /*' '*/) end--; -exports = module.exports = __nccwpck_require__(60545); -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.storage = 'undefined' != typeof chrome - && 'undefined' != typeof chrome.storage - ? chrome.storage.local - : localstorage(); + start = this._parseProtocol(str, start, end); -/** - * Colors. - */ + //Javascript doesn't have host + if (this._protocol !== "javascript") { + start = this._parseHost(str, start, end, hostDenotesSlash); + var proto = this._protocol; + if (!this.hostname && + (this.slashes || (proto && !slashProtocols[proto]))) { + this.hostname = this.host = ""; + } + } -exports.colors = [ - 'lightseagreen', - 'forestgreen', - 'goldenrod', - 'dodgerblue', - 'darkorchid', - 'crimson' -]; + if (start <= end) { + var ch = str.charCodeAt(start); -/** - * Currently only WebKit-based Web Inspectors, Firefox >= v31, - * and the Firebug extension (any Firefox version) are known - * to support "%c" CSS customizations. - * - * TODO: add a `localStorage` variable to explicitly enable/disable colors - */ + if (ch === 0x2F /*'/'*/ || ch === 0x5C /*'\'*/) { + this._parsePath(str, start, end, disableAutoEscapeChars); + } + else if (ch === 0x3F /*'?'*/) { + this._parseQuery(str, start, end, disableAutoEscapeChars); + } + else if (ch === 0x23 /*'#'*/) { + this._parseHash(str, start, end, disableAutoEscapeChars); + } + else if (this._protocol !== "javascript") { + this._parsePath(str, start, end, disableAutoEscapeChars); + } + else { //For javascript the pathname is just the rest of it + this.pathname = str.slice(start, end + 1 ); + } -function useColors() { - // NB: In an Electron preload script, document will be defined but not fully - // initialized. Since we know we're in Chrome, we'll just detect this case - // explicitly - if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') { - return true; - } + } - // is webkit? http://stackoverflow.com/a/16459606/376773 - // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 - return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || - // is firebug? http://stackoverflow.com/a/398120/376773 - (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || - // is firefox >= v31? - // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || - // double check webkit in userAgent just in case we are in a worker - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); -} + if (!this.pathname && this.hostname && + this._slashProtocols[this._protocol]) { + this.pathname = "/"; + } -/** - * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. - */ + if (parseQueryString) { + var search = this.search; + if (search == null) { + search = this.search = ""; + } + if (search.charCodeAt(0) === 0x3F /*'?'*/) { + search = search.slice(1); + } + //This calls a setter function, there is no .query data property + this.query = Url.queryString.parse(search); + } +}; -exports.formatters.j = function(v) { - try { - return JSON.stringify(v); - } catch (err) { - return '[UnexpectedJSONParseError]: ' + err.message; - } +Url.prototype.resolve = function Url$resolve(relative) { + return this.resolveObject(Url.parse(relative, false, true)).format(); }; +Url.prototype.format = function Url$format() { + var auth = this.auth || ""; -/** - * Colorize log arguments if enabled. - * - * @api public - */ + if (auth) { + auth = encodeURIComponent(auth); + auth = auth.replace(/%3A/i, ":"); + auth += "@"; + } -function formatArgs(args) { - var useColors = this.useColors; + var protocol = this.protocol || ""; + var pathname = this.pathname || ""; + var hash = this.hash || ""; + var search = this.search || ""; + var query = ""; + var hostname = this.hostname || ""; + var port = this.port || ""; + var host = false; + var scheme = ""; - args[0] = (useColors ? '%c' : '') - + this.namespace - + (useColors ? ' %c' : ' ') - + args[0] - + (useColors ? '%c ' : ' ') - + '+' + exports.humanize(this.diff); + //Cache the result of the getter function + var q = this.query; + if (q && typeof q === "object") { + query = Url.queryString.stringify(q); + } - if (!useColors) return; + if (!search) { + search = query ? "?" + query : ""; + } - var c = 'color: ' + this.color; - args.splice(1, 0, c, 'color: inherit') + if (protocol && protocol.charCodeAt(protocol.length - 1) !== 0x3A /*':'*/) + protocol += ":"; - // the final "%c" is somewhat tricky, because there could be other - // arguments passed either before or after the %c, so we need to - // figure out the correct index to insert the CSS into - var index = 0; - var lastC = 0; - args[0].replace(/%[a-zA-Z%]/g, function(match) { - if ('%%' === match) return; - index++; - if ('%c' === match) { - // we only are interested in the *last* %c - // (the user may have provided their own) - lastC = index; + if (this.host) { + host = auth + this.host; + } + else if (hostname) { + var ip6 = hostname.indexOf(":") > -1; + if (ip6) hostname = "[" + hostname + "]"; + host = auth + hostname + (port ? ":" + port : ""); } - }); - - args.splice(lastC, 0, c); -} -/** - * Invokes `console.log()` when available. - * No-op when `console.log` is not a "function". - * - * @api public - */ + var slashes = this.slashes || + ((!protocol || + slashProtocols[protocol]) && host !== false); -function log() { - // this hackery is required for IE8/9, where - // the `console.log` function doesn't have 'apply' - return 'object' === typeof console - && console.log - && Function.prototype.apply.call(console.log, console, arguments); -} -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ + if (protocol) scheme = protocol + (slashes ? "//" : ""); + else if (slashes) scheme = "//"; -function save(namespaces) { - try { - if (null == namespaces) { - exports.storage.removeItem('debug'); - } else { - exports.storage.debug = namespaces; + if (slashes && pathname && pathname.charCodeAt(0) !== 0x2F /*'/'*/) { + pathname = "/" + pathname; } - } catch(e) {} -} - -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ + if (search && search.charCodeAt(0) !== 0x3F /*'?'*/) + search = "?" + search; + if (hash && hash.charCodeAt(0) !== 0x23 /*'#'*/) + hash = "#" + hash; -function load() { - var r; - try { - r = exports.storage.debug; - } catch(e) {} + pathname = escapePathName(pathname); + search = escapeSearch(search); - // If debug isn't set in LS, and we're in Electron, try to load $DEBUG - if (!r && typeof process !== 'undefined' && 'env' in process) { - r = process.env.DEBUG; - } + return scheme + (host === false ? "" : host) + pathname + search + hash; +}; - return r; -} +Url.prototype.resolveObject = function Url$resolveObject(relative) { + if (typeof relative === "string") + relative = Url.parse(relative, false, true); -/** - * Enable namespaces listed in `localStorage.debug` initially. - */ + var result = this._clone(); -exports.enable(load()); + // hash is always overridden, no matter what. + // even href="" will remove it. + result.hash = relative.hash; -/** - * Localstorage attempts to return the localstorage. - * - * This is necessary because safari throws - * when a user disables cookies/localstorage - * and you attempt to access it. - * - * @return {LocalStorage} - * @api private - */ + // if the relative url is empty, then there"s nothing left to do here. + if (!relative.href) { + result._href = ""; + return result; + } -function localstorage() { - try { - return window.localStorage; - } catch (e) {} -} + // hrefs like //foo/bar always cut to the protocol. + if (relative.slashes && !relative._protocol) { + relative._copyPropsTo(result, true); + if (slashProtocols[result._protocol] && + result.hostname && !result.pathname) { + result.pathname = "/"; + } + result._href = ""; + return result; + } -/***/ }), + if (relative._protocol && relative._protocol !== result._protocol) { + // if it"s a known url protocol, then changing + // the protocol does weird things + // first, if it"s not file:, then we MUST have a host, + // and if there was a path + // to begin with, then we MUST have a path. + // if it is file:, then the host is dropped, + // because that"s known to be hostless. + // anything else is assumed to be absolute. + if (!slashProtocols[relative._protocol]) { + relative._copyPropsTo(result, false); + result._href = ""; + return result; + } -/***/ 60545: -/***/ ((module, exports, __nccwpck_require__) => { + result._protocol = relative._protocol; + if (!relative.host && relative._protocol !== "javascript") { + var relPath = (relative.pathname || "").split("/"); + while (relPath.length && !(relative.host = relPath.shift())); + if (!relative.host) relative.host = ""; + if (!relative.hostname) relative.hostname = ""; + if (relPath[0] !== "") relPath.unshift(""); + if (relPath.length < 2) relPath.unshift(""); + result.pathname = relPath.join("/"); + } else { + result.pathname = relative.pathname; + } + result.search = relative.search; + result.host = relative.host || ""; + result.auth = relative.auth; + result.hostname = relative.hostname || relative.host; + result._port = relative._port; + result.slashes = result.slashes || relative.slashes; + result._href = ""; + return result; + } -/** - * This is the common logic for both the Node.js and web browser - * implementations of `debug()`. - * - * Expose `debug()` as the module. - */ + var isSourceAbs = + (result.pathname && result.pathname.charCodeAt(0) === 0x2F /*'/'*/); + var isRelAbs = ( + relative.host || + (relative.pathname && + relative.pathname.charCodeAt(0) === 0x2F /*'/'*/) + ); + var mustEndAbs = (isRelAbs || isSourceAbs || + (result.host && relative.pathname)); -exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; -exports.coerce = coerce; -exports.disable = disable; -exports.enable = enable; -exports.enabled = enabled; -exports.humanize = __nccwpck_require__(80761); + var removeAllDots = mustEndAbs; -/** - * The currently active debug mode names, and names to skip. - */ + var srcPath = result.pathname && result.pathname.split("/") || []; + var relPath = relative.pathname && relative.pathname.split("/") || []; + var psychotic = result._protocol && !slashProtocols[result._protocol]; -exports.names = []; -exports.skips = []; + // if the url is a non-slashed url, then relative + // links like ../.. should be able + // to crawl up to the hostname, as well. This is strange. + // result.protocol has already been set by now. + // Later on, put the first path part into the host field. + if (psychotic) { + result.hostname = ""; + result._port = -1; + if (result.host) { + if (srcPath[0] === "") srcPath[0] = result.host; + else srcPath.unshift(result.host); + } + result.host = ""; + if (relative._protocol) { + relative.hostname = ""; + relative._port = -1; + if (relative.host) { + if (relPath[0] === "") relPath[0] = relative.host; + else relPath.unshift(relative.host); + } + relative.host = ""; + } + mustEndAbs = mustEndAbs && (relPath[0] === "" || srcPath[0] === ""); + } -/** - * Map of special "%n" handling functions, for the debug "format" argument. - * - * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". - */ + if (isRelAbs) { + // it"s absolute. + result.host = relative.host ? + relative.host : result.host; + result.hostname = relative.hostname ? + relative.hostname : result.hostname; + result.search = relative.search; + srcPath = relPath; + // fall through to the dot-handling below. + } else if (relPath.length) { + // it"s relative + // throw away the existing file, and take the new path instead. + if (!srcPath) srcPath = []; + srcPath.pop(); + srcPath = srcPath.concat(relPath); + result.search = relative.search; + } else if (relative.search) { + // just pull out the search. + // like href="?foo". + // Put this after the other two cases because it simplifies the booleans + if (psychotic) { + result.hostname = result.host = srcPath.shift(); + //occationaly the auth can get stuck only in host + //this especialy happens in cases like + //url.resolveObject("mailto:local1@domain1", "local2@domain2") + var authInHost = result.host && result.host.indexOf("@") > 0 ? + result.host.split("@") : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + result.search = relative.search; + result._href = ""; + return result; + } -exports.formatters = {}; + if (!srcPath.length) { + // no path at all. easy. + // we"ve already handled the other stuff above. + result.pathname = null; + result._href = ""; + return result; + } -/** - * Previous log timestamp. - */ + // if a url ENDs in . or .., then it must get a trailing slash. + // however, if it ends in anything else non-slashy, + // then it must NOT get a trailing slash. + var last = srcPath.slice(-1)[0]; + var hasTrailingSlash = ( + (result.host || relative.host) && (last === "." || last === "..") || + last === ""); -var prevTime; + // strip single dots, resolve double dots to parent dir + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = srcPath.length; i >= 0; i--) { + last = srcPath[i]; + if (last === ".") { + srcPath.splice(i, 1); + } else if (last === "..") { + srcPath.splice(i, 1); + up++; + } else if (up) { + srcPath.splice(i, 1); + up--; + } + } -/** - * Select a color. - * @param {String} namespace - * @return {Number} - * @api private - */ + // if the path is allowed to go above the root, restore leading ..s + if (!mustEndAbs && !removeAllDots) { + for (; up--; up) { + srcPath.unshift(".."); + } + } -function selectColor(namespace) { - var hash = 0, i; + if (mustEndAbs && srcPath[0] !== "" && + (!srcPath[0] || srcPath[0].charCodeAt(0) !== 0x2F /*'/'*/)) { + srcPath.unshift(""); + } - for (i in namespace) { - hash = ((hash << 5) - hash) + namespace.charCodeAt(i); - hash |= 0; // Convert to 32bit integer - } + if (hasTrailingSlash && (srcPath.join("/").substr(-1) !== "/")) { + srcPath.push(""); + } - return exports.colors[Math.abs(hash) % exports.colors.length]; -} + var isAbsolute = srcPath[0] === "" || + (srcPath[0] && srcPath[0].charCodeAt(0) === 0x2F /*'/'*/); -/** - * Create a debugger with the given `namespace`. - * - * @param {String} namespace - * @return {Function} - * @api public - */ + // put the host back + if (psychotic) { + result.hostname = result.host = isAbsolute ? "" : + srcPath.length ? srcPath.shift() : ""; + //occationaly the auth can get stuck only in host + //this especialy happens in cases like + //url.resolveObject("mailto:local1@domain1", "local2@domain2") + var authInHost = result.host && result.host.indexOf("@") > 0 ? + result.host.split("@") : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } -function createDebug(namespace) { + mustEndAbs = mustEndAbs || (result.host && srcPath.length); - function debug() { - // disabled? - if (!debug.enabled) return; + if (mustEndAbs && !isAbsolute) { + srcPath.unshift(""); + } - var self = debug; + result.pathname = srcPath.length === 0 ? null : srcPath.join("/"); + result.auth = relative.auth || result.auth; + result.slashes = result.slashes || relative.slashes; + result._href = ""; + return result; +}; - // set `diff` timestamp - var curr = +new Date(); - var ms = curr - (prevTime || curr); - self.diff = ms; - self.prev = prevTime; - self.curr = curr; - prevTime = curr; +var punycode = __nccwpck_require__(85477); +Url.prototype._hostIdna = function Url$_hostIdna(hostname) { + // IDNA Support: Returns a punycoded representation of "domain". + // It only converts parts of the domain name that + // have non-ASCII characters, i.e. it doesn't matter if + // you call it with a domain that already is ASCII-only. + return punycode.toASCII(hostname); +}; - // turn the `arguments` into a proper Array - var args = new Array(arguments.length); - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i]; +var escapePathName = Url.prototype._escapePathName = +function Url$_escapePathName(pathname) { + if (!containsCharacter2(pathname, 0x23 /*'#'*/, 0x3F /*'?'*/)) { + return pathname; } + //Avoid closure creation to keep this inlinable + return _escapePath(pathname); +}; - args[0] = exports.coerce(args[0]); - - if ('string' !== typeof args[0]) { - // anything else let's inspect with %O - args.unshift('%O'); - } +var escapeSearch = Url.prototype._escapeSearch = +function Url$_escapeSearch(search) { + if (!containsCharacter2(search, 0x23 /*'#'*/, -1)) return search; + //Avoid closure creation to keep this inlinable + return _escapeSearch(search); +}; - // apply any `formatters` transformations - var index = 0; - args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) { - // if we encounter an escaped % then don't increase the array index - if (match === '%%') return match; - index++; - var formatter = exports.formatters[format]; - if ('function' === typeof formatter) { - var val = args[index]; - match = formatter.call(self, val); +Url.prototype._parseProtocol = function Url$_parseProtocol(str, start, end) { + var doLowerCase = false; + var protocolCharacters = this._protocolCharacters; - // now we need to remove `args[index]` since it's inlined in the `format` - args.splice(index, 1); - index--; - } - return match; - }); + for (var i = start; i <= end; ++i) { + var ch = str.charCodeAt(i); - // apply env-specific formatting (colors, etc.) - exports.formatArgs.call(self, args); + if (ch === 0x3A /*':'*/) { + var protocol = str.slice(start, i); + if (doLowerCase) protocol = protocol.toLowerCase(); + this._protocol = protocol; + return i + 1; + } + else if (protocolCharacters[ch] === 1) { + if (ch < 0x61 /*'a'*/) + doLowerCase = true; + } + else { + return start; + } - var logFn = debug.log || exports.log || console.log.bind(console); - logFn.apply(self, args); - } + } + return start; +}; - debug.namespace = namespace; - debug.enabled = exports.enabled(namespace); - debug.useColors = exports.useColors(); - debug.color = selectColor(namespace); +Url.prototype._parseAuth = function Url$_parseAuth(str, start, end, decode) { + var auth = str.slice(start, end + 1); + if (decode) { + auth = decodeURIComponent(auth); + } + this.auth = auth; +}; - // env-specific initialization logic for debug instances - if ('function' === typeof exports.init) { - exports.init(debug); - } +Url.prototype._parsePort = function Url$_parsePort(str, start, end) { + //Internal format is integer for more efficient parsing + //and for efficient trimming of leading zeros + var port = 0; + //Distinguish between :0 and : (no port number at all) + var hadChars = false; + var validPort = true; - return debug; -} + for (var i = start; i <= end; ++i) { + var ch = str.charCodeAt(i); -/** - * Enables a debug mode by namespaces. This can include modes - * separated by a colon and wildcards. - * - * @param {String} namespaces - * @api public - */ + if (0x30 /*'0'*/ <= ch && ch <= 0x39 /*'9'*/) { + port = (10 * port) + (ch - 0x30 /*'0'*/); + hadChars = true; + } + else { + validPort = false; + if (ch === 0x5C/*'\'*/ || ch === 0x2F/*'/'*/) { + validPort = true; + } + break; + } -function enable(namespaces) { - exports.save(namespaces); + } + if ((port === 0 && !hadChars) || !validPort) { + if (!validPort) { + this._port = -2; + } + return 0; + } - exports.names = []; - exports.skips = []; + this._port = port; + return i - start; +}; - var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); - var len = split.length; +Url.prototype._parseHost = +function Url$_parseHost(str, start, end, slashesDenoteHost) { + var hostEndingCharacters = this._hostEndingCharacters; + var first = str.charCodeAt(start); + var second = str.charCodeAt(start + 1); + if ((first === 0x2F /*'/'*/ || first === 0x5C /*'\'*/) && + (second === 0x2F /*'/'*/ || second === 0x5C /*'\'*/)) { + this.slashes = true; - for (var i = 0; i < len; i++) { - if (!split[i]) continue; // ignore empty strings - namespaces = split[i].replace(/\*/g, '.*?'); - if (namespaces[0] === '-') { - exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); - } else { - exports.names.push(new RegExp('^' + namespaces + '$')); + //The string starts with // + if (start === 0) { + //The string is just "//" + if (end < 2) return start; + //If slashes do not denote host and there is no auth, + //there is no host when the string starts with // + var hasAuth = + containsCharacter(str, 0x40 /*'@'*/, 2, hostEndingCharacters); + if (!hasAuth && !slashesDenoteHost) { + this.slashes = null; + return start; + } + } + //There is a host that starts after the // + start += 2; + } + //If there is no slashes, there is no hostname if + //1. there was no protocol at all + else if (!this._protocol || + //2. there was a protocol that requires slashes + //e.g. in 'http:asd' 'asd' is not a hostname + slashProtocols[this._protocol] + ) { + return start; } - } -} -/** - * Disable debug output. - * - * @api public - */ + var doLowerCase = false; + var idna = false; + var hostNameStart = start; + var hostNameEnd = end; + var lastCh = -1; + var portLength = 0; + var charsAfterDot = 0; + var authNeedsDecoding = false; -function disable() { - exports.enable(''); -} + var j = -1; -/** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ + //Find the last occurrence of an @-sign until hostending character is met + //also mark if decoding is needed for the auth portion + for (var i = start; i <= end; ++i) { + var ch = str.charCodeAt(i); -function enabled(name) { - var i, len; - for (i = 0, len = exports.skips.length; i < len; i++) { - if (exports.skips[i].test(name)) { - return false; - } - } - for (i = 0, len = exports.names.length; i < len; i++) { - if (exports.names[i].test(name)) { - return true; + if (ch === 0x40 /*'@'*/) { + j = i; + } + //This check is very, very cheap. Unneeded decodeURIComponent is very + //very expensive + else if (ch === 0x25 /*'%'*/) { + authNeedsDecoding = true; + } + else if (hostEndingCharacters[ch] === 1) { + break; + } } - } - return false; -} - -/** - * Coerce `val`. - * - * @param {Mixed} val - * @return {Mixed} - * @api private - */ -function coerce(val) { - if (val instanceof Error) return val.stack || val.message; - return val; -} + //@-sign was found at index j, everything to the left from it + //is auth part + if (j > -1) { + this._parseAuth(str, start, j - 1, authNeedsDecoding); + //hostname starts after the last @-sign + start = hostNameStart = j + 1; + } + //Host name is starting with a [ + if (str.charCodeAt(start) === 0x5B /*'['*/) { + for (var i = start + 1; i <= end; ++i) { + var ch = str.charCodeAt(i); -/***/ }), + //Assume valid IP6 is between the brackets + if (ch === 0x5D /*']'*/) { + if (str.charCodeAt(i + 1) === 0x3A /*':'*/) { + portLength = this._parsePort(str, i + 2, end) + 1; + } + var hostname = str.slice(start + 1, i).toLowerCase(); + this.hostname = hostname; + this.host = this._port > 0 ? + "[" + hostname + "]:" + this._port : + "[" + hostname + "]"; + this.pathname = "/"; + return i + portLength + 1; + } + } + //Empty hostname, [ starts a path + return start; + } -/***/ 65612: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + for (var i = start; i <= end; ++i) { + if (charsAfterDot > 62) { + this.hostname = this.host = str.slice(start, i); + return i; + } + var ch = str.charCodeAt(i); -/** - * Detect Electron renderer process, which is node, but we should - * treat as a browser. - */ + if (ch === 0x3A /*':'*/) { + portLength = this._parsePort(str, i + 1, end) + 1; + hostNameEnd = i - 1; + break; + } + else if (ch < 0x61 /*'a'*/) { + if (ch === 0x2E /*'.'*/) { + //Node.js ignores this error + /* + if (lastCh === DOT || lastCh === -1) { + this.hostname = this.host = ""; + return start; + } + */ + charsAfterDot = -1; + } + else if (0x41 /*'A'*/ <= ch && ch <= 0x5A /*'Z'*/) { + doLowerCase = true; + } + //Valid characters other than ASCII letters -, _, +, 0-9 + else if (!(ch === 0x2D /*'-'*/ || + ch === 0x5F /*'_'*/ || + ch === 0x2B /*'+'*/ || + (0x30 /*'0'*/ <= ch && ch <= 0x39 /*'9'*/)) + ) { + if (hostEndingCharacters[ch] === 0 && + this._noPrependSlashHostEnders[ch] === 0) { + this._prependSlash = true; + } + hostNameEnd = i - 1; + break; + } + } + else if (ch >= 0x7B /*'{'*/) { + if (ch <= 0x7E /*'~'*/) { + if (this._noPrependSlashHostEnders[ch] === 0) { + this._prependSlash = true; + } + hostNameEnd = i - 1; + break; + } + idna = true; + } + lastCh = ch; + charsAfterDot++; + } -if (typeof process !== 'undefined' && process.type === 'renderer') { - module.exports = __nccwpck_require__(56401); -} else { - module.exports = __nccwpck_require__(4706); -} + //Node.js ignores this error + /* + if (lastCh === DOT) { + hostNameEnd--; + } + */ + if (hostNameEnd + 1 !== start && + hostNameEnd - hostNameStart <= 256) { + var hostname = str.slice(hostNameStart, hostNameEnd + 1); + if (doLowerCase) hostname = hostname.toLowerCase(); + if (idna) hostname = this._hostIdna(hostname); + this.hostname = hostname; + this.host = this._port > 0 ? hostname + ":" + this._port : hostname; + } -/***/ }), + return hostNameEnd + 1 + portLength; -/***/ 4706: -/***/ ((module, exports, __nccwpck_require__) => { +}; -/** - * Module dependencies. - */ +Url.prototype._copyPropsTo = function Url$_copyPropsTo(input, noProtocol) { + if (!noProtocol) { + input._protocol = this._protocol; + } + input._href = this._href; + input._port = this._port; + input._prependSlash = this._prependSlash; + input.auth = this.auth; + input.slashes = this.slashes; + input.host = this.host; + input.hostname = this.hostname; + input.hash = this.hash; + input.search = this.search; + input.pathname = this.pathname; +}; -var tty = __nccwpck_require__(76224); -var util = __nccwpck_require__(73837); +Url.prototype._clone = function Url$_clone() { + var ret = new Url(); + ret._protocol = this._protocol; + ret._href = this._href; + ret._port = this._port; + ret._prependSlash = this._prependSlash; + ret.auth = this.auth; + ret.slashes = this.slashes; + ret.host = this.host; + ret.hostname = this.hostname; + ret.hash = this.hash; + ret.search = this.search; + ret.pathname = this.pathname; + return ret; +}; -/** - * This is the Node.js implementation of `debug()`. - * - * Expose `debug()` as the module. - */ +Url.prototype._getComponentEscaped = +function Url$_getComponentEscaped(str, start, end, isAfterQuery) { + var cur = start; + var i = start; + var ret = ""; + var autoEscapeMap = isAfterQuery ? + this._afterQueryAutoEscapeMap : this._autoEscapeMap; + for (; i <= end; ++i) { + var ch = str.charCodeAt(i); + var escaped = autoEscapeMap[ch]; -exports = module.exports = __nccwpck_require__(60545); -exports.init = init; -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; + if (escaped !== "" && escaped !== undefined) { + if (cur < i) ret += str.slice(cur, i); + ret += escaped; + cur = i + 1; + } + } + if (cur < i + 1) ret += str.slice(cur, i); + return ret; +}; -/** - * Colors. - */ +Url.prototype._parsePath = +function Url$_parsePath(str, start, end, disableAutoEscapeChars) { + var pathStart = start; + var pathEnd = end; + var escape = false; + var autoEscapeCharacters = this._autoEscapeCharacters; + var prePath = this._port === -2 ? "/:" : ""; -exports.colors = [6, 2, 3, 4, 5, 1]; + for (var i = start; i <= end; ++i) { + var ch = str.charCodeAt(i); + if (ch === 0x23 /*'#'*/) { + this._parseHash(str, i, end, disableAutoEscapeChars); + pathEnd = i - 1; + break; + } + else if (ch === 0x3F /*'?'*/) { + this._parseQuery(str, i, end, disableAutoEscapeChars); + pathEnd = i - 1; + break; + } + else if (!disableAutoEscapeChars && !escape && autoEscapeCharacters[ch] === 1) { + escape = true; + } + } -/** - * Build up the default `inspectOpts` object from the environment variables. - * - * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js - */ + if (pathStart > pathEnd) { + this.pathname = prePath === "" ? "/" : prePath; + return; + } -exports.inspectOpts = Object.keys(process.env).filter(function (key) { - return /^debug_/i.test(key); -}).reduce(function (obj, key) { - // camel-case - var prop = key - .substring(6) - .toLowerCase() - .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() }); + var path; + if (escape) { + path = this._getComponentEscaped(str, pathStart, pathEnd, false); + } + else { + path = str.slice(pathStart, pathEnd + 1); + } + this.pathname = prePath === "" + ? (this._prependSlash ? "/" + path : path) + : prePath + path; +}; - // coerce string value into JS value - var val = process.env[key]; - if (/^(yes|on|true|enabled)$/i.test(val)) val = true; - else if (/^(no|off|false|disabled)$/i.test(val)) val = false; - else if (val === 'null') val = null; - else val = Number(val); +Url.prototype._parseQuery = function Url$_parseQuery(str, start, end, disableAutoEscapeChars) { + var queryStart = start; + var queryEnd = end; + var escape = false; + var autoEscapeCharacters = this._autoEscapeCharacters; - obj[prop] = val; - return obj; -}, {}); + for (var i = start; i <= end; ++i) { + var ch = str.charCodeAt(i); -/** - * The file descriptor to write the `debug()` calls to. - * Set the `DEBUG_FD` env variable to override with another value. i.e.: - * - * $ DEBUG_FD=3 node script.js 3>debug.log - */ + if (ch === 0x23 /*'#'*/) { + this._parseHash(str, i, end, disableAutoEscapeChars); + queryEnd = i - 1; + break; + } + else if (!disableAutoEscapeChars && !escape && autoEscapeCharacters[ch] === 1) { + escape = true; + } + } -var fd = parseInt(process.env.DEBUG_FD, 10) || 2; + if (queryStart > queryEnd) { + this.search = ""; + return; + } -if (1 !== fd && 2 !== fd) { - util.deprecate(function(){}, 'except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)')() -} + var query; + if (escape) { + query = this._getComponentEscaped(str, queryStart, queryEnd, true); + } + else { + query = str.slice(queryStart, queryEnd + 1); + } + this.search = query; +}; -var stream = 1 === fd ? process.stdout : - 2 === fd ? process.stderr : - createWritableStdioStream(fd); +Url.prototype._parseHash = function Url$_parseHash(str, start, end, disableAutoEscapeChars) { + if (start > end) { + this.hash = ""; + return; + } -/** - * Is stdout a TTY? Colored output is enabled when `true`. - */ + this.hash = disableAutoEscapeChars ? + str.slice(start, end + 1) : this._getComponentEscaped(str, start, end, true); +}; -function useColors() { - return 'colors' in exports.inspectOpts - ? Boolean(exports.inspectOpts.colors) - : tty.isatty(fd); -} +Object.defineProperty(Url.prototype, "port", { + get: function() { + if (this._port >= 0) { + return ("" + this._port); + } + return null; + }, + set: function(v) { + if (v == null) { + this._port = -1; + } + else { + this._port = parseInt(v, 10); + } + } +}); -/** - * Map %o to `util.inspect()`, all on a single line. - */ +Object.defineProperty(Url.prototype, "query", { + get: function() { + var query = this._query; + if (query != null) { + return query; + } + var search = this.search; -exports.formatters.o = function(v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts) - .split('\n').map(function(str) { - return str.trim() - }).join(' '); -}; + if (search) { + if (search.charCodeAt(0) === 0x3F /*'?'*/) { + search = search.slice(1); + } + if (search !== "") { + this._query = search; + return search; + } + } + return search; + }, + set: function(v) { + this._query = v; + } +}); -/** - * Map %o to `util.inspect()`, allowing multiple lines if needed. - */ +Object.defineProperty(Url.prototype, "path", { + get: function() { + var p = this.pathname || ""; + var s = this.search || ""; + if (p || s) { + return p + s; + } + return (p == null && s) ? ("/" + s) : null; + }, + set: function() {} +}); -exports.formatters.O = function(v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts); +Object.defineProperty(Url.prototype, "protocol", { + get: function() { + var proto = this._protocol; + return proto ? proto + ":" : proto; + }, + set: function(v) { + if (typeof v === "string") { + var end = v.length - 1; + if (v.charCodeAt(end) === 0x3A /*':'*/) { + this._protocol = v.slice(0, end); + } + else { + this._protocol = v; + } + } + else if (v == null) { + this._protocol = null; + } + } +}); + +Object.defineProperty(Url.prototype, "href", { + get: function() { + var href = this._href; + if (!href) { + href = this._href = this.format(); + } + return href; + }, + set: function(v) { + this._href = v; + } +}); + +Url.parse = function Url$Parse(str, parseQueryString, hostDenotesSlash, disableAutoEscapeChars) { + if (str instanceof Url) return str; + var ret = new Url(); + ret.parse(str, !!parseQueryString, !!hostDenotesSlash, !!disableAutoEscapeChars); + return ret; }; -/** - * Adds ANSI color escape codes if enabled. - * - * @api public - */ +Url.format = function Url$Format(obj) { + if (typeof obj === "string") { + obj = Url.parse(obj); + } + if (!(obj instanceof Url)) { + return Url.prototype.format.call(obj); + } + return obj.format(); +}; -function formatArgs(args) { - var name = this.namespace; - var useColors = this.useColors; +Url.resolve = function Url$Resolve(source, relative) { + return Url.parse(source, false, true).resolve(relative); +}; - if (useColors) { - var c = this.color; - var prefix = ' \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m'; +Url.resolveObject = function Url$ResolveObject(source, relative) { + if (!source) return relative; + return Url.parse(source, false, true).resolveObject(relative); +}; - args[0] = prefix + args[0].split('\n').join('\n' + prefix); - args.push('\u001b[3' + c + 'm+' + exports.humanize(this.diff) + '\u001b[0m'); - } else { - args[0] = new Date().toUTCString() - + ' ' + name + ' ' + args[0]; - } +function _escapePath(pathname) { + return pathname.replace(/[?#]/g, function(match) { + return encodeURIComponent(match); + }); } -/** - * Invokes `util.format()` with the specified arguments and writes to `stream`. - */ - -function log() { - return stream.write(util.format.apply(util, arguments) + '\n'); +function _escapeSearch(search) { + return search.replace(/#/g, function(match) { + return encodeURIComponent(match); + }); } -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ +//Search `char1` (integer code for a character) in `string` +//starting from `fromIndex` and ending at `string.length - 1` +//or when a stop character is found +function containsCharacter(string, char1, fromIndex, stopCharacterTable) { + var len = string.length; + for (var i = fromIndex; i < len; ++i) { + var ch = string.charCodeAt(i); -function save(namespaces) { - if (null == namespaces) { - // If you set a process.env field to null or undefined, it gets cast to the - // string 'null' or 'undefined'. Just delete instead. - delete process.env.DEBUG; - } else { - process.env.DEBUG = namespaces; - } + if (ch === char1) { + return true; + } + else if (stopCharacterTable[ch] === 1) { + return false; + } + } + return false; } -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ - -function load() { - return process.env.DEBUG; +//See if `char1` or `char2` (integer codes for characters) +//is contained in `string` +function containsCharacter2(string, char1, char2) { + for (var i = 0, len = string.length; i < len; ++i) { + var ch = string.charCodeAt(i); + if (ch === char1 || ch === char2) return true; + } + return false; } -/** - * Copied from `node/src/node.js`. - * - * XXX: It's lame that node doesn't expose this API out-of-the-box. It also - * relies on the undocumented `tty_wrap.guessHandleType()` which is also lame. - */ +//Makes an array of 128 uint8's which represent boolean values. +//Spec is an array of ascii code points or ascii code point ranges +//ranges are expressed as [start, end] -function createWritableStdioStream (fd) { - var stream; - var tty_wrap = process.binding('tty_wrap'); +//Create a table with the characters 0x30-0x39 (decimals '0' - '9') and +//0x7A (lowercaseletter 'z') as `true`: +// +//var a = makeAsciiTable([[0x30, 0x39], 0x7A]); +//a[0x30]; //1 +//a[0x15]; //0 +//a[0x35]; //1 +function makeAsciiTable(spec) { + var ret = new Uint8Array(128); + spec.forEach(function(item){ + if (typeof item === "number") { + ret[item] = 1; + } + else { + var start = item[0]; + var end = item[1]; + for (var j = start; j <= end; ++j) { + ret[j] = 1; + } + } + }); - // Note stream._type is used for test-module-load-list.js + return ret; +} - switch (tty_wrap.guessHandleType(fd)) { - case 'TTY': - stream = new tty.WriteStream(fd); - stream._type = 'tty'; - // Hack to have stream not keep the event loop alive. - // See https://github.com/joyent/node/issues/1726 - if (stream._handle && stream._handle.unref) { - stream._handle.unref(); - } - break; +var autoEscape = ["<", ">", "\"", "`", " ", "\r", "\n", + "\t", "{", "}", "|", "\\", "^", "`", "'"]; - case 'FILE': - var fs = __nccwpck_require__(57147); - stream = new fs.SyncWriteStream(fd, { autoClose: false }); - stream._type = 'fs'; - break; +var autoEscapeMap = new Array(128); - case 'PIPE': - case 'TCP': - var net = __nccwpck_require__(41808); - stream = new net.Socket({ - fd: fd, - readable: false, - writable: true - }); - // FIXME Should probably have an option in net.Socket to create a - // stream from an existing fd which is writable only. But for now - // we'll just add this hack and set the `readable` member to false. - // Test: ./node test/fixtures/echo.js < /etc/passwd - stream.readable = false; - stream.read = null; - stream._type = 'pipe'; - // FIXME Hack to have stream not keep the event loop alive. - // See https://github.com/joyent/node/issues/1726 - if (stream._handle && stream._handle.unref) { - stream._handle.unref(); - } - break; +for (var i = 0, len = autoEscapeMap.length; i < len; ++i) { + autoEscapeMap[i] = ""; +} - default: - // Probably an error on in uv_guess_handle() - throw new Error('Implement me. Unknown stream file type!'); - } +for (var i = 0, len = autoEscape.length; i < len; ++i) { + var c = autoEscape[i]; + var esc = encodeURIComponent(c); + if (esc === c) { + esc = escape(c); + } + autoEscapeMap[c.charCodeAt(0)] = esc; +} +var afterQueryAutoEscapeMap = autoEscapeMap.slice(); +autoEscapeMap[0x5C /*'\'*/] = "/"; - // For supporting legacy API we put the FD here. - stream.fd = fd; +var slashProtocols = Url.prototype._slashProtocols = { + http: true, + https: true, + gopher: true, + file: true, + ftp: true, - stream._isStdio = true; + "http:": true, + "https:": true, + "gopher:": true, + "file:": true, + "ftp:": true +}; - return stream; -} +//Optimize back from normalized object caused by non-identifier keys +function f(){} +f.prototype = slashProtocols; -/** - * Init logic for `debug` instances. - * - * Create a new `inspectOpts` object in case `useColors` is set - * differently for a particular `debug` instance. - */ +Url.prototype._protocolCharacters = makeAsciiTable([ + [0x61 /*'a'*/, 0x7A /*'z'*/], + [0x41 /*'A'*/, 0x5A /*'Z'*/], + 0x2E /*'.'*/, 0x2B /*'+'*/, 0x2D /*'-'*/ +]); -function init (debug) { - debug.inspectOpts = {}; +Url.prototype._hostEndingCharacters = makeAsciiTable([ + 0x23 /*'#'*/, 0x3F /*'?'*/, 0x2F /*'/'*/, 0x5C /*'\'*/ +]); - var keys = Object.keys(exports.inspectOpts); - for (var i = 0; i < keys.length; i++) { - debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; - } -} +Url.prototype._autoEscapeCharacters = makeAsciiTable( + autoEscape.map(function(v) { + return v.charCodeAt(0); + }) +); -/** - * Enable namespaces listed in `process.env.DEBUG` initially. - */ +//If these characters end a host name, the path will not be prepended a / +Url.prototype._noPrependSlashHostEnders = makeAsciiTable( + [ + "<", ">", "'", "`", " ", "\r", + "\n", "\t", "{", "}", "|", + "^", "`", "\"", "%", ";" + ].map(function(v) { + return v.charCodeAt(0); + }) +); -exports.enable(load()); +Url.prototype._autoEscapeMap = autoEscapeMap; +Url.prototype._afterQueryAutoEscapeMap = afterQueryAutoEscapeMap; + +module.exports = Url; + +Url.replace = function Url$Replace() { + require.cache.url = { + exports: Url + }; +}; /***/ }), -/***/ 80761: -/***/ ((module) => { +/***/ 30810: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; +/*! + * finalhandler + * Copyright(c) 2014-2017 Douglas Christopher Wilson + * MIT Licensed + */ + + /** - * Helpers. + * Module dependencies. + * @private */ -var s = 1000; -var m = s * 60; -var h = m * 60; -var d = h * 24; -var y = d * 365.25; +var debug = __nccwpck_require__(65612)('finalhandler') +var encodeUrl = __nccwpck_require__(16592) +var escapeHtml = __nccwpck_require__(94070) +var onFinished = __nccwpck_require__(24694) +var parseUrl = __nccwpck_require__(89808) +var statuses = __nccwpck_require__(57415) +var unpipe = __nccwpck_require__(3124) /** - * Parse or format the given `val`. - * - * Options: - * - * - `long` verbose formatting [false] - * - * @param {String|Number} val - * @param {Object} [options] - * @throws {Error} throw an error if val is not a non-empty string or a number - * @return {String|Number} - * @api public + * Module variables. + * @private */ -module.exports = function(val, options) { - options = options || {}; - var type = typeof val; - if (type === 'string' && val.length > 0) { - return parse(val); - } else if (type === 'number' && isNaN(val) === false) { - return options.long ? fmtLong(val) : fmtShort(val); - } - throw new Error( - 'val is not a non-empty string or a valid number. val=' + - JSON.stringify(val) - ); -}; +var DOUBLE_SPACE_REGEXP = /\x20{2}/g +var NEWLINE_REGEXP = /\n/g + +/* istanbul ignore next */ +var defer = typeof setImmediate === 'function' + ? setImmediate + : function (fn) { process.nextTick(fn.bind.apply(fn, arguments)) } +var isFinished = onFinished.isFinished /** - * Parse the given `str` and return milliseconds. + * Create a minimal HTML document. * - * @param {String} str - * @return {Number} - * @api private + * @param {string} message + * @private */ -function parse(str) { - str = String(str); - if (str.length > 100) { - return; - } - var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec( - str - ); - if (!match) { - return; - } - var n = parseFloat(match[1]); - var type = (match[2] || 'ms').toLowerCase(); - switch (type) { - case 'years': - case 'year': - case 'yrs': - case 'yr': - case 'y': - return n * y; - case 'days': - case 'day': - case 'd': - return n * d; - case 'hours': - case 'hour': - case 'hrs': - case 'hr': - case 'h': - return n * h; - case 'minutes': - case 'minute': - case 'mins': - case 'min': - case 'm': - return n * m; - case 'seconds': - case 'second': - case 'secs': - case 'sec': - case 's': - return n * s; - case 'milliseconds': - case 'millisecond': - case 'msecs': - case 'msec': - case 'ms': - return n; - default: - return undefined; - } -} - -/** - * Short format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ +function createHtmlDocument (message) { + var body = escapeHtml(message) + .replace(NEWLINE_REGEXP, '
') + .replace(DOUBLE_SPACE_REGEXP, '  ') -function fmtShort(ms) { - if (ms >= d) { - return Math.round(ms / d) + 'd'; - } - if (ms >= h) { - return Math.round(ms / h) + 'h'; - } - if (ms >= m) { - return Math.round(ms / m) + 'm'; - } - if (ms >= s) { - return Math.round(ms / s) + 's'; - } - return ms + 'ms'; + return '\n' + + '\n' + + '\n' + + '\n' + + 'Error\n' + + '\n' + + '\n' + + '
' + body + '
\n' + + '\n' + + '\n' } /** - * Long format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private + * Module exports. + * @public */ -function fmtLong(ms) { - return plural(ms, d, 'day') || - plural(ms, h, 'hour') || - plural(ms, m, 'minute') || - plural(ms, s, 'second') || - ms + ' ms'; -} +module.exports = finalhandler /** - * Pluralization helper. + * Create a function to handle the final response. + * + * @param {Request} req + * @param {Response} res + * @param {Object} [options] + * @return {Function} + * @public */ -function plural(ms, n, name) { - if (ms < n) { - return; - } - if (ms < n * 1.5) { - return Math.floor(ms / n) + ' ' + name; - } - return Math.ceil(ms / n) + ' ' + name + 's'; -} - - -/***/ }), - -/***/ 35298: -/***/ ((module) => { - -"use strict"; +function finalhandler (req, res, options) { + var opts = options || {} + // get environment + var env = opts.env || process.env.NODE_ENV || 'development' -// You may be tempted to copy and paste this, -// but take a look at the commit history first, -// this is a moving target so relying on the module -// is the best way to make sure the optimization -// method is kept up to date and compatible with -// every Node version. + // get error callback + var onerror = opts.onerror -function flatstr (s) { - s | 0 - return s -} + return function (err) { + var headers + var msg + var status -module.exports = flatstr + // ignore 404 on in-flight response + if (!err && headersSent(res)) { + debug('cannot 404 after headers sent') + return + } -/***/ }), + // unhandled error + if (err) { + // respect status code from error + status = getErrorStatusCode(err) -/***/ 46868: -/***/ ((module) => { + if (status === undefined) { + // fallback to status code on response + status = getResponseStatusCode(res) + } else { + // respect headers from error + headers = getErrorHeaders(err) + } -"use strict"; -/*! - * forwarded - * Copyright(c) 2014-2017 Douglas Christopher Wilson - * MIT Licensed - */ + // get error message + msg = getErrorMessage(err, status, env) + } else { + // not found + status = 404 + msg = 'Cannot ' + req.method + ' ' + encodeUrl(getResourceName(req)) + } + debug('default %s', status) + // schedule onerror callback + if (err && onerror) { + defer(onerror, err, req, res) + } -/** - * Module exports. - * @public - */ + // cannot actually respond + if (headersSent(res)) { + debug('cannot %d after headers sent', status) + req.socket.destroy() + return + } -module.exports = forwarded + // send response + send(req, res, status, headers, msg) + } +} /** - * Get all addresses in the request, using the `X-Forwarded-For` header. + * Get headers from Error object. * - * @param {object} req - * @return {array} - * @public + * @param {Error} err + * @return {object} + * @private */ -function forwarded (req) { - if (!req) { - throw new TypeError('argument req is required') +function getErrorHeaders (err) { + if (!err.headers || typeof err.headers !== 'object') { + return undefined } - // simple header parsing - var proxyAddrs = parse(req.headers['x-forwarded-for'] || '') - var socketAddr = getSocketAddr(req) - var addrs = [socketAddr].concat(proxyAddrs) + var headers = Object.create(null) + var keys = Object.keys(err.headers) - // return all addresses - return addrs + for (var i = 0; i < keys.length; i++) { + var key = keys[i] + headers[key] = err.headers[key] + } + + return headers } /** - * Get the socket address for a request. + * Get message from Error object, fallback to status message. * - * @param {object} req + * @param {Error} err + * @param {number} status + * @param {string} env * @return {string} * @private */ -function getSocketAddr (req) { - return req.socket - ? req.socket.remoteAddress - : req.connection.remoteAddress +function getErrorMessage (err, status, env) { + var msg + + if (env !== 'production') { + // use err.stack, which typically includes err.message + msg = err.stack + + // fallback to err.toString() when possible + if (!msg && typeof err.toString === 'function') { + msg = err.toString() + } + } + + return msg || statuses[status] } /** - * Parse the X-Forwarded-For header. + * Get status code from Error object. * - * @param {string} header + * @param {Error} err + * @return {number} * @private */ -function parse (header) { - var end = header.length - var list = [] - var start = header.length - - // gather addresses, backwards - for (var i = header.length - 1; i >= 0; i--) { - switch (header.charCodeAt(i)) { - case 0x20: /* */ - if (start === end) { - start = end = i - } - break - case 0x2c: /* , */ - if (start !== end) { - list.push(header.substring(start, end)) - } - start = end = i - break - default: - start = i - break - } +function getErrorStatusCode (err) { + // check err.status + if (typeof err.status === 'number' && err.status >= 400 && err.status < 600) { + return err.status } - // final address - if (start !== end) { - list.push(header.substring(start, end)) + // check err.statusCode + if (typeof err.statusCode === 'number' && err.statusCode >= 400 && err.statusCode < 600) { + return err.statusCode } - return list + return undefined } - -/***/ }), - -/***/ 83136: -/***/ ((module) => { - -"use strict"; -/*! - * fresh - * Copyright(c) 2012 TJ Holowaychuk - * Copyright(c) 2016-2017 Douglas Christopher Wilson - * MIT Licensed +/** + * Get resource name for the request. + * + * This is typically just the original pathname of the request + * but will fallback to "resource" is that cannot be determined. + * + * @param {IncomingMessage} req + * @return {string} + * @private */ - +function getResourceName (req) { + try { + return parseUrl.original(req).pathname + } catch (e) { + return 'resource' + } +} /** - * RegExp to check for no-cache token in Cache-Control. + * Get status code from response. + * + * @param {OutgoingMessage} res + * @return {number} * @private */ -var CACHE_CONTROL_NO_CACHE_REGEXP = /(?:^|,)\s*?no-cache\s*?(?:,|$)/ +function getResponseStatusCode (res) { + var status = res.statusCode + + // default status code to 500 if outside valid range + if (typeof status !== 'number' || status < 400 || status > 599) { + status = 500 + } + + return status +} /** - * Module exports. - * @public + * Determine if the response headers have been sent. + * + * @param {object} res + * @returns {boolean} + * @private */ -module.exports = fresh +function headersSent (res) { + return typeof res.headersSent !== 'boolean' + ? Boolean(res._header) + : res.headersSent +} /** - * Check freshness of the response using request and response headers. + * Send response. * - * @param {Object} reqHeaders - * @param {Object} resHeaders - * @return {Boolean} - * @public + * @param {IncomingMessage} req + * @param {OutgoingMessage} res + * @param {number} status + * @param {object} headers + * @param {string} message + * @private */ -function fresh (reqHeaders, resHeaders) { - // fields - var modifiedSince = reqHeaders['if-modified-since'] - var noneMatch = reqHeaders['if-none-match'] +function send (req, res, status, headers, message) { + function write () { + // response body + var body = createHtmlDocument(message) - // unconditional request - if (!modifiedSince && !noneMatch) { - return false - } + // response status + res.statusCode = status + res.statusMessage = statuses[status] - // Always return stale when Cache-Control: no-cache - // to support end-to-end reload requests - // https://tools.ietf.org/html/rfc2616#section-14.9.4 - var cacheControl = reqHeaders['cache-control'] - if (cacheControl && CACHE_CONTROL_NO_CACHE_REGEXP.test(cacheControl)) { - return false - } + // response headers + setHeaders(res, headers) - // if-none-match - if (noneMatch && noneMatch !== '*') { - var etag = resHeaders['etag'] + // security headers + res.setHeader('Content-Security-Policy', "default-src 'none'") + res.setHeader('X-Content-Type-Options', 'nosniff') - if (!etag) { - return false - } + // standard headers + res.setHeader('Content-Type', 'text/html; charset=utf-8') + res.setHeader('Content-Length', Buffer.byteLength(body, 'utf8')) - var etagStale = true - var matches = parseTokenList(noneMatch) - for (var i = 0; i < matches.length; i++) { - var match = matches[i] - if (match === etag || match === 'W/' + etag || 'W/' + match === etag) { - etagStale = false - break - } + if (req.method === 'HEAD') { + res.end() + return } - if (etagStale) { - return false - } + res.end(body, 'utf8') } - // if-modified-since - if (modifiedSince) { - var lastModified = resHeaders['last-modified'] - var modifiedStale = !lastModified || !(parseHttpDate(lastModified) <= parseHttpDate(modifiedSince)) - - if (modifiedStale) { - return false - } + if (isFinished(req)) { + write() + return } - return true -} - -/** - * Parse an HTTP Date into a number. - * - * @param {string} date - * @private - */ - -function parseHttpDate (date) { - var timestamp = date && Date.parse(date) + // unpipe everything from the request + unpipe(req) - // istanbul ignore next: guard against date.js Date.parse patching - return typeof timestamp === 'number' - ? timestamp - : NaN + // flush the request + onFinished(req, write) + req.resume() } /** - * Parse a HTTP token list. + * Set response headers from an object. * - * @param {string} str + * @param {OutgoingMessage} res + * @param {object} headers * @private */ -function parseTokenList (str) { - var end = 0 - var list = [] - var start = 0 - - // gather tokens - for (var i = 0, len = str.length; i < len; i++) { - switch (str.charCodeAt(i)) { - case 0x20: /* */ - if (start === end) { - start = end = i + 1 - } - break - case 0x2c: /* , */ - list.push(str.substring(start, end)) - start = end = i + 1 - break - default: - end = i + 1 - break - } +function setHeaders (res, headers) { + if (!headers) { + return } - // final token - list.push(str.substring(start, end)) - - return list + var keys = Object.keys(headers) + for (var i = 0; i < keys.length; i++) { + var key = keys[i] + res.setHeader(key, headers[key]) + } } /***/ }), -/***/ 19320: -/***/ ((module) => { +/***/ 56401: +/***/ ((module, exports, __nccwpck_require__) => { -"use strict"; +/** + * This is the web browser implementation of `debug()`. + * + * Expose `debug()` as the module. + */ +exports = module.exports = __nccwpck_require__(60545); +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = 'undefined' != typeof chrome + && 'undefined' != typeof chrome.storage + ? chrome.storage.local + : localstorage(); -/* eslint no-invalid-this: 1 */ +/** + * Colors. + */ -var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; -var slice = Array.prototype.slice; -var toStr = Object.prototype.toString; -var funcType = '[object Function]'; - -module.exports = function bind(that) { - var target = this; - if (typeof target !== 'function' || toStr.call(target) !== funcType) { - throw new TypeError(ERROR_MESSAGE + target); - } - var args = slice.call(arguments, 1); +exports.colors = [ + 'lightseagreen', + 'forestgreen', + 'goldenrod', + 'dodgerblue', + 'darkorchid', + 'crimson' +]; - var bound; - var binder = function () { - if (this instanceof bound) { - var result = target.apply( - this, - args.concat(slice.call(arguments)) - ); - if (Object(result) === result) { - return result; - } - return this; - } else { - return target.apply( - that, - args.concat(slice.call(arguments)) - ); - } - }; +/** + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. + * + * TODO: add a `localStorage` variable to explicitly enable/disable colors + */ - var boundLength = Math.max(0, target.length - args.length); - var boundArgs = []; - for (var i = 0; i < boundLength; i++) { - boundArgs.push('$' + i); - } +function useColors() { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') { + return true; + } - bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder); + // is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || + // is firebug? http://stackoverflow.com/a/398120/376773 + (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || + // is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || + // double check webkit in userAgent just in case we are in a worker + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); +} - if (target.prototype) { - var Empty = function Empty() {}; - Empty.prototype = target.prototype; - bound.prototype = new Empty(); - Empty.prototype = null; - } +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ - return bound; +exports.formatters.j = function(v) { + try { + return JSON.stringify(v); + } catch (err) { + return '[UnexpectedJSONParseError]: ' + err.message; + } }; -/***/ }), +/** + * Colorize log arguments if enabled. + * + * @api public + */ -/***/ 88334: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +function formatArgs(args) { + var useColors = this.useColors; -"use strict"; + args[0] = (useColors ? '%c' : '') + + this.namespace + + (useColors ? ' %c' : ' ') + + args[0] + + (useColors ? '%c ' : ' ') + + '+' + exports.humanize(this.diff); + if (!useColors) return; -var implementation = __nccwpck_require__(19320); + var c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit') -module.exports = Function.prototype.bind || implementation; + // the final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + var index = 0; + var lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, function(match) { + if ('%%' === match) return; + index++; + if ('%c' === match) { + // we only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); + args.splice(lastC, 0, c); +} -/***/ }), +/** + * Invokes `console.log()` when available. + * No-op when `console.log` is not a "function". + * + * @api public + */ -/***/ 67356: -/***/ ((module) => { +function log() { + // this hackery is required for IE8/9, where + // the `console.log` function doesn't have 'apply' + return 'object' === typeof console + && console.log + && Function.prototype.apply.call(console.log, console, arguments); +} -"use strict"; +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ +function save(namespaces) { + try { + if (null == namespaces) { + exports.storage.removeItem('debug'); + } else { + exports.storage.debug = namespaces; + } + } catch(e) {} +} -module.exports = clone +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ -var getPrototypeOf = Object.getPrototypeOf || function (obj) { - return obj.__proto__ +function load() { + var r; + try { + r = exports.storage.debug; + } catch(e) {} + + // If debug isn't set in LS, and we're in Electron, try to load $DEBUG + if (!r && typeof process !== 'undefined' && 'env' in process) { + r = process.env.DEBUG; + } + + return r; } -function clone (obj) { - if (obj === null || typeof obj !== 'object') - return obj +/** + * Enable namespaces listed in `localStorage.debug` initially. + */ - if (obj instanceof Object) - var copy = { __proto__: getPrototypeOf(obj) } - else - var copy = Object.create(null) +exports.enable(load()); - Object.getOwnPropertyNames(obj).forEach(function (key) { - Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key)) - }) +/** + * Localstorage attempts to return the localstorage. + * + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. + * + * @return {LocalStorage} + * @api private + */ - return copy +function localstorage() { + try { + return window.localStorage; + } catch (e) {} } /***/ }), -/***/ 77758: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var fs = __nccwpck_require__(57147) -var polyfills = __nccwpck_require__(20263) -var legacy = __nccwpck_require__(73086) -var clone = __nccwpck_require__(67356) - -var util = __nccwpck_require__(73837) +/***/ 60545: +/***/ ((module, exports, __nccwpck_require__) => { -/* istanbul ignore next - node 0.x polyfill */ -var gracefulQueue -var previousSymbol -/* istanbul ignore else - node 0.x polyfill */ -if (typeof Symbol === 'function' && typeof Symbol.for === 'function') { - gracefulQueue = Symbol.for('graceful-fs.queue') - // This is used in testing by future versions - previousSymbol = Symbol.for('graceful-fs.previous') -} else { - gracefulQueue = '___graceful-fs.queue' - previousSymbol = '___graceful-fs.previous' -} +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + * + * Expose `debug()` as the module. + */ -function noop () {} +exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; +exports.coerce = coerce; +exports.disable = disable; +exports.enable = enable; +exports.enabled = enabled; +exports.humanize = __nccwpck_require__(80761); -function publishQueue(context, queue) { - Object.defineProperty(context, gracefulQueue, { - get: function() { - return queue - } - }) -} +/** + * The currently active debug mode names, and names to skip. + */ -var debug = noop -if (util.debuglog) - debug = util.debuglog('gfs4') -else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) - debug = function() { - var m = util.format.apply(util, arguments) - m = 'GFS4: ' + m.split(/\n/).join('\nGFS4: ') - console.error(m) - } +exports.names = []; +exports.skips = []; -// Once time initialization -if (!fs[gracefulQueue]) { - // This queue can be shared by multiple loaded instances - var queue = global[gracefulQueue] || [] - publishQueue(fs, queue) +/** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + */ - // Patch fs.close/closeSync to shared queue version, because we need - // to retry() whenever a close happens *anywhere* in the program. - // This is essential when multiple graceful-fs instances are - // in play at the same time. - fs.close = (function (fs$close) { - function close (fd, cb) { - return fs$close.call(fs, fd, function (err) { - // This function uses the graceful-fs shared queue - if (!err) { - resetQueue() - } +exports.formatters = {}; - if (typeof cb === 'function') - cb.apply(this, arguments) - }) - } +/** + * Previous log timestamp. + */ - Object.defineProperty(close, previousSymbol, { - value: fs$close - }) - return close - })(fs.close) +var prevTime; - fs.closeSync = (function (fs$closeSync) { - function closeSync (fd) { - // This function uses the graceful-fs shared queue - fs$closeSync.apply(fs, arguments) - resetQueue() - } +/** + * Select a color. + * @param {String} namespace + * @return {Number} + * @api private + */ - Object.defineProperty(closeSync, previousSymbol, { - value: fs$closeSync - }) - return closeSync - })(fs.closeSync) +function selectColor(namespace) { + var hash = 0, i; - if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) { - process.on('exit', function() { - debug(fs[gracefulQueue]) - __nccwpck_require__(39491).equal(fs[gracefulQueue].length, 0) - }) + for (i in namespace) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer } -} -if (!global[gracefulQueue]) { - publishQueue(global, fs[gracefulQueue]); + return exports.colors[Math.abs(hash) % exports.colors.length]; } -module.exports = patch(clone(fs)) -if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs.__patched) { - module.exports = patch(fs) - fs.__patched = true; -} +/** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ -function patch (fs) { - // Everything that references the open() function needs to be in here - polyfills(fs) - fs.gracefulify = patch +function createDebug(namespace) { - fs.createReadStream = createReadStream - fs.createWriteStream = createWriteStream - var fs$readFile = fs.readFile - fs.readFile = readFile - function readFile (path, options, cb) { - if (typeof options === 'function') - cb = options, options = null + function debug() { + // disabled? + if (!debug.enabled) return; - return go$readFile(path, options, cb) + var self = debug; - function go$readFile (path, options, cb, startTime) { - return fs$readFile(path, options, function (err) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$readFile, [path, options, cb], err, startTime || Date.now(), Date.now()]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - } - }) - } - } + // set `diff` timestamp + var curr = +new Date(); + var ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; - var fs$writeFile = fs.writeFile - fs.writeFile = writeFile - function writeFile (path, data, options, cb) { - if (typeof options === 'function') - cb = options, options = null + // turn the `arguments` into a proper Array + var args = new Array(arguments.length); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i]; + } - return go$writeFile(path, data, options, cb) + args[0] = exports.coerce(args[0]); - function go$writeFile (path, data, options, cb, startTime) { - return fs$writeFile(path, data, options, function (err) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$writeFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - } - }) + if ('string' !== typeof args[0]) { + // anything else let's inspect with %O + args.unshift('%O'); } - } - var fs$appendFile = fs.appendFile - if (fs$appendFile) - fs.appendFile = appendFile - function appendFile (path, data, options, cb) { - if (typeof options === 'function') - cb = options, options = null + // apply any `formatters` transformations + var index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) { + // if we encounter an escaped % then don't increase the array index + if (match === '%%') return match; + index++; + var formatter = exports.formatters[format]; + if ('function' === typeof formatter) { + var val = args[index]; + match = formatter.call(self, val); - return go$appendFile(path, data, options, cb) + // now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); - function go$appendFile (path, data, options, cb, startTime) { - return fs$appendFile(path, data, options, function (err) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$appendFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - } - }) - } + // apply env-specific formatting (colors, etc.) + exports.formatArgs.call(self, args); + + var logFn = debug.log || exports.log || console.log.bind(console); + logFn.apply(self, args); } - var fs$copyFile = fs.copyFile - if (fs$copyFile) - fs.copyFile = copyFile - function copyFile (src, dest, flags, cb) { - if (typeof flags === 'function') { - cb = flags - flags = 0 - } - return go$copyFile(src, dest, flags, cb) + debug.namespace = namespace; + debug.enabled = exports.enabled(namespace); + debug.useColors = exports.useColors(); + debug.color = selectColor(namespace); - function go$copyFile (src, dest, flags, cb, startTime) { - return fs$copyFile(src, dest, flags, function (err) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$copyFile, [src, dest, flags, cb], err, startTime || Date.now(), Date.now()]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - } - }) - } + // env-specific initialization logic for debug instances + if ('function' === typeof exports.init) { + exports.init(debug); } - var fs$readdir = fs.readdir - fs.readdir = readdir - function readdir (path, options, cb) { - if (typeof options === 'function') - cb = options, options = null + return debug; +} - return go$readdir(path, options, cb) +/** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ - function go$readdir (path, options, cb, startTime) { - return fs$readdir(path, options, function (err, files) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$readdir, [path, options, cb], err, startTime || Date.now(), Date.now()]) - else { - if (files && files.sort) - files.sort() +function enable(namespaces) { + exports.save(namespaces); - if (typeof cb === 'function') - cb.call(this, err, files) - } - }) - } - } + exports.names = []; + exports.skips = []; - if (process.version.substr(0, 4) === 'v0.8') { - var legStreams = legacy(fs) - ReadStream = legStreams.ReadStream - WriteStream = legStreams.WriteStream - } + var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + var len = split.length; - var fs$ReadStream = fs.ReadStream - if (fs$ReadStream) { - ReadStream.prototype = Object.create(fs$ReadStream.prototype) - ReadStream.prototype.open = ReadStream$open + for (var i = 0; i < len; i++) { + if (!split[i]) continue; // ignore empty strings + namespaces = split[i].replace(/\*/g, '.*?'); + if (namespaces[0] === '-') { + exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); + } else { + exports.names.push(new RegExp('^' + namespaces + '$')); + } } +} - var fs$WriteStream = fs.WriteStream - if (fs$WriteStream) { - WriteStream.prototype = Object.create(fs$WriteStream.prototype) - WriteStream.prototype.open = WriteStream$open - } - - Object.defineProperty(fs, 'ReadStream', { - get: function () { - return ReadStream - }, - set: function (val) { - ReadStream = val - }, - enumerable: true, - configurable: true - }) - Object.defineProperty(fs, 'WriteStream', { - get: function () { - return WriteStream - }, - set: function (val) { - WriteStream = val - }, - enumerable: true, - configurable: true - }) - - // legacy names - var FileReadStream = ReadStream - Object.defineProperty(fs, 'FileReadStream', { - get: function () { - return FileReadStream - }, - set: function (val) { - FileReadStream = val - }, - enumerable: true, - configurable: true - }) - var FileWriteStream = WriteStream - Object.defineProperty(fs, 'FileWriteStream', { - get: function () { - return FileWriteStream - }, - set: function (val) { - FileWriteStream = val - }, - enumerable: true, - configurable: true - }) - - function ReadStream (path, options) { - if (this instanceof ReadStream) - return fs$ReadStream.apply(this, arguments), this - else - return ReadStream.apply(Object.create(ReadStream.prototype), arguments) - } - - function ReadStream$open () { - var that = this - open(that.path, that.flags, that.mode, function (err, fd) { - if (err) { - if (that.autoClose) - that.destroy() - - that.emit('error', err) - } else { - that.fd = fd - that.emit('open', fd) - that.read() - } - }) - } - - function WriteStream (path, options) { - if (this instanceof WriteStream) - return fs$WriteStream.apply(this, arguments), this - else - return WriteStream.apply(Object.create(WriteStream.prototype), arguments) - } +/** + * Disable debug output. + * + * @api public + */ - function WriteStream$open () { - var that = this - open(that.path, that.flags, that.mode, function (err, fd) { - if (err) { - that.destroy() - that.emit('error', err) - } else { - that.fd = fd - that.emit('open', fd) - } - }) - } +function disable() { + exports.enable(''); +} - function createReadStream (path, options) { - return new fs.ReadStream(path, options) - } +/** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ - function createWriteStream (path, options) { - return new fs.WriteStream(path, options) +function enabled(name) { + var i, len; + for (i = 0, len = exports.skips.length; i < len; i++) { + if (exports.skips[i].test(name)) { + return false; + } } - - var fs$open = fs.open - fs.open = open - function open (path, flags, mode, cb) { - if (typeof mode === 'function') - cb = mode, mode = null - - return go$open(path, flags, mode, cb) - - function go$open (path, flags, mode, cb, startTime) { - return fs$open(path, flags, mode, function (err, fd) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$open, [path, flags, mode, cb], err, startTime || Date.now(), Date.now()]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - } - }) + for (i = 0, len = exports.names.length; i < len; i++) { + if (exports.names[i].test(name)) { + return true; } } - - return fs -} - -function enqueue (elem) { - debug('ENQUEUE', elem[0].name, elem[1]) - fs[gracefulQueue].push(elem) - retry() + return false; } -// keep track of the timeout between retry() calls -var retryTimer +/** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ -// reset the startTime and lastTime to now -// this resets the start of the 60 second overall timeout as well as the -// delay between attempts so that we'll retry these jobs sooner -function resetQueue () { - var now = Date.now() - for (var i = 0; i < fs[gracefulQueue].length; ++i) { - // entries that are only a length of 2 are from an older version, don't - // bother modifying those since they'll be retried anyway. - if (fs[gracefulQueue][i].length > 2) { - fs[gracefulQueue][i][3] = now // startTime - fs[gracefulQueue][i][4] = now // lastTime - } - } - // call retry to make sure we're actively processing the queue - retry() +function coerce(val) { + if (val instanceof Error) return val.stack || val.message; + return val; } -function retry () { - // clear the timer and remove it to help prevent unintended concurrency - clearTimeout(retryTimer) - retryTimer = undefined - if (fs[gracefulQueue].length === 0) - return +/***/ }), - var elem = fs[gracefulQueue].shift() - var fn = elem[0] - var args = elem[1] - // these items may be unset if they were added by an older graceful-fs - var err = elem[2] - var startTime = elem[3] - var lastTime = elem[4] +/***/ 65612: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // if we don't have a startTime we have no way of knowing if we've waited - // long enough, so go ahead and retry this item now - if (startTime === undefined) { - debug('RETRY', fn.name, args) - fn.apply(null, args) - } else if (Date.now() - startTime >= 60000) { - // it's been more than 60 seconds total, bail now - debug('TIMEOUT', fn.name, args) - var cb = args.pop() - if (typeof cb === 'function') - cb.call(null, err) - } else { - // the amount of time between the last attempt and right now - var sinceAttempt = Date.now() - lastTime - // the amount of time between when we first tried, and when we last tried - // rounded up to at least 1 - var sinceStart = Math.max(lastTime - startTime, 1) - // backoff. wait longer than the total time we've been retrying, but only - // up to a maximum of 100ms - var desiredDelay = Math.min(sinceStart * 1.2, 100) - // it's been long enough since the last retry, do it again - if (sinceAttempt >= desiredDelay) { - debug('RETRY', fn.name, args) - fn.apply(null, args.concat([startTime])) - } else { - // if we can't do this job yet, push it to the end of the queue - // and let the next iteration check again - fs[gracefulQueue].push(elem) - } - } +/** + * Detect Electron renderer process, which is node, but we should + * treat as a browser. + */ - // schedule our next run if one isn't already scheduled - if (retryTimer === undefined) { - retryTimer = setTimeout(retry, 0) - } +if (typeof process !== 'undefined' && process.type === 'renderer') { + module.exports = __nccwpck_require__(56401); +} else { + module.exports = __nccwpck_require__(4706); } /***/ }), -/***/ 73086: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var Stream = (__nccwpck_require__(12781).Stream) - -module.exports = legacy - -function legacy (fs) { - return { - ReadStream: ReadStream, - WriteStream: WriteStream - } +/***/ 4706: +/***/ ((module, exports, __nccwpck_require__) => { - function ReadStream (path, options) { - if (!(this instanceof ReadStream)) return new ReadStream(path, options); +/** + * Module dependencies. + */ - Stream.call(this); +var tty = __nccwpck_require__(76224); +var util = __nccwpck_require__(73837); - var self = this; +/** + * This is the Node.js implementation of `debug()`. + * + * Expose `debug()` as the module. + */ - this.path = path; - this.fd = null; - this.readable = true; - this.paused = false; +exports = module.exports = __nccwpck_require__(60545); +exports.init = init; +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; - this.flags = 'r'; - this.mode = 438; /*=0666*/ - this.bufferSize = 64 * 1024; +/** + * Colors. + */ - options = options || {}; +exports.colors = [6, 2, 3, 4, 5, 1]; - // Mixin options into this - var keys = Object.keys(options); - for (var index = 0, length = keys.length; index < length; index++) { - var key = keys[index]; - this[key] = options[key]; - } +/** + * Build up the default `inspectOpts` object from the environment variables. + * + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + */ - if (this.encoding) this.setEncoding(this.encoding); +exports.inspectOpts = Object.keys(process.env).filter(function (key) { + return /^debug_/i.test(key); +}).reduce(function (obj, key) { + // camel-case + var prop = key + .substring(6) + .toLowerCase() + .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() }); - if (this.start !== undefined) { - if ('number' !== typeof this.start) { - throw TypeError('start must be a Number'); - } - if (this.end === undefined) { - this.end = Infinity; - } else if ('number' !== typeof this.end) { - throw TypeError('end must be a Number'); - } + // coerce string value into JS value + var val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) val = true; + else if (/^(no|off|false|disabled)$/i.test(val)) val = false; + else if (val === 'null') val = null; + else val = Number(val); - if (this.start > this.end) { - throw new Error('start must be <= end'); - } + obj[prop] = val; + return obj; +}, {}); - this.pos = this.start; - } +/** + * The file descriptor to write the `debug()` calls to. + * Set the `DEBUG_FD` env variable to override with another value. i.e.: + * + * $ DEBUG_FD=3 node script.js 3>debug.log + */ - if (this.fd !== null) { - process.nextTick(function() { - self._read(); - }); - return; - } +var fd = parseInt(process.env.DEBUG_FD, 10) || 2; - fs.open(this.path, this.flags, this.mode, function (err, fd) { - if (err) { - self.emit('error', err); - self.readable = false; - return; - } +if (1 !== fd && 2 !== fd) { + util.deprecate(function(){}, 'except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)')() +} - self.fd = fd; - self.emit('open', fd); - self._read(); - }) - } +var stream = 1 === fd ? process.stdout : + 2 === fd ? process.stderr : + createWritableStdioStream(fd); - function WriteStream (path, options) { - if (!(this instanceof WriteStream)) return new WriteStream(path, options); +/** + * Is stdout a TTY? Colored output is enabled when `true`. + */ - Stream.call(this); +function useColors() { + return 'colors' in exports.inspectOpts + ? Boolean(exports.inspectOpts.colors) + : tty.isatty(fd); +} - this.path = path; - this.fd = null; - this.writable = true; +/** + * Map %o to `util.inspect()`, all on a single line. + */ - this.flags = 'w'; - this.encoding = 'binary'; - this.mode = 438; /*=0666*/ - this.bytesWritten = 0; +exports.formatters.o = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts) + .split('\n').map(function(str) { + return str.trim() + }).join(' '); +}; - options = options || {}; +/** + * Map %o to `util.inspect()`, allowing multiple lines if needed. + */ - // Mixin options into this - var keys = Object.keys(options); - for (var index = 0, length = keys.length; index < length; index++) { - var key = keys[index]; - this[key] = options[key]; - } +exports.formatters.O = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); +}; - if (this.start !== undefined) { - if ('number' !== typeof this.start) { - throw TypeError('start must be a Number'); - } - if (this.start < 0) { - throw new Error('start must be >= zero'); - } +/** + * Adds ANSI color escape codes if enabled. + * + * @api public + */ - this.pos = this.start; - } +function formatArgs(args) { + var name = this.namespace; + var useColors = this.useColors; - this.busy = false; - this._queue = []; + if (useColors) { + var c = this.color; + var prefix = ' \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m'; - if (this.fd === null) { - this._open = fs.open; - this._queue.push([this._open, this.path, this.flags, this.mode, undefined]); - this.flush(); - } + args[0] = prefix + args[0].split('\n').join('\n' + prefix); + args.push('\u001b[3' + c + 'm+' + exports.humanize(this.diff) + '\u001b[0m'); + } else { + args[0] = new Date().toUTCString() + + ' ' + name + ' ' + args[0]; } } +/** + * Invokes `util.format()` with the specified arguments and writes to `stream`. + */ -/***/ }), - -/***/ 20263: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +function log() { + return stream.write(util.format.apply(util, arguments) + '\n'); +} -var constants = __nccwpck_require__(22057) +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ -var origCwd = process.cwd -var cwd = null +function save(namespaces) { + if (null == namespaces) { + // If you set a process.env field to null or undefined, it gets cast to the + // string 'null' or 'undefined'. Just delete instead. + delete process.env.DEBUG; + } else { + process.env.DEBUG = namespaces; + } +} -var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ -process.cwd = function() { - if (!cwd) - cwd = origCwd.call(process) - return cwd +function load() { + return process.env.DEBUG; } -try { - process.cwd() -} catch (er) {} -// This check is needed until node.js 12 is required -if (typeof process.chdir === 'function') { - var chdir = process.chdir - process.chdir = function (d) { - cwd = null - chdir.call(process, d) - } - if (Object.setPrototypeOf) Object.setPrototypeOf(process.chdir, chdir) -} +/** + * Copied from `node/src/node.js`. + * + * XXX: It's lame that node doesn't expose this API out-of-the-box. It also + * relies on the undocumented `tty_wrap.guessHandleType()` which is also lame. + */ -module.exports = patch +function createWritableStdioStream (fd) { + var stream; + var tty_wrap = process.binding('tty_wrap'); -function patch (fs) { - // (re-)implement some things that are known busted or missing. + // Note stream._type is used for test-module-load-list.js - // lchmod, broken prior to 0.6.2 - // back-port the fix here. - if (constants.hasOwnProperty('O_SYMLINK') && - process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) { - patchLchmod(fs) - } + switch (tty_wrap.guessHandleType(fd)) { + case 'TTY': + stream = new tty.WriteStream(fd); + stream._type = 'tty'; - // lutimes implementation, or no-op - if (!fs.lutimes) { - patchLutimes(fs) - } + // Hack to have stream not keep the event loop alive. + // See https://github.com/joyent/node/issues/1726 + if (stream._handle && stream._handle.unref) { + stream._handle.unref(); + } + break; - // https://github.com/isaacs/node-graceful-fs/issues/4 - // Chown should not fail on einval or eperm if non-root. - // It should not fail on enosys ever, as this just indicates - // that a fs doesn't support the intended operation. + case 'FILE': + var fs = __nccwpck_require__(57147); + stream = new fs.SyncWriteStream(fd, { autoClose: false }); + stream._type = 'fs'; + break; - fs.chown = chownFix(fs.chown) - fs.fchown = chownFix(fs.fchown) - fs.lchown = chownFix(fs.lchown) + case 'PIPE': + case 'TCP': + var net = __nccwpck_require__(41808); + stream = new net.Socket({ + fd: fd, + readable: false, + writable: true + }); - fs.chmod = chmodFix(fs.chmod) - fs.fchmod = chmodFix(fs.fchmod) - fs.lchmod = chmodFix(fs.lchmod) + // FIXME Should probably have an option in net.Socket to create a + // stream from an existing fd which is writable only. But for now + // we'll just add this hack and set the `readable` member to false. + // Test: ./node test/fixtures/echo.js < /etc/passwd + stream.readable = false; + stream.read = null; + stream._type = 'pipe'; - fs.chownSync = chownFixSync(fs.chownSync) - fs.fchownSync = chownFixSync(fs.fchownSync) - fs.lchownSync = chownFixSync(fs.lchownSync) + // FIXME Hack to have stream not keep the event loop alive. + // See https://github.com/joyent/node/issues/1726 + if (stream._handle && stream._handle.unref) { + stream._handle.unref(); + } + break; - fs.chmodSync = chmodFixSync(fs.chmodSync) - fs.fchmodSync = chmodFixSync(fs.fchmodSync) - fs.lchmodSync = chmodFixSync(fs.lchmodSync) + default: + // Probably an error on in uv_guess_handle() + throw new Error('Implement me. Unknown stream file type!'); + } - fs.stat = statFix(fs.stat) - fs.fstat = statFix(fs.fstat) - fs.lstat = statFix(fs.lstat) + // For supporting legacy API we put the FD here. + stream.fd = fd; - fs.statSync = statFixSync(fs.statSync) - fs.fstatSync = statFixSync(fs.fstatSync) - fs.lstatSync = statFixSync(fs.lstatSync) + stream._isStdio = true; - // if lchmod/lchown do not exist, then make them no-ops - if (!fs.lchmod) { - fs.lchmod = function (path, mode, cb) { - if (cb) process.nextTick(cb) - } - fs.lchmodSync = function () {} - } - if (!fs.lchown) { - fs.lchown = function (path, uid, gid, cb) { - if (cb) process.nextTick(cb) - } - fs.lchownSync = function () {} - } + return stream; +} - // on Windows, A/V software can lock the directory, causing this - // to fail with an EACCES or EPERM if the directory contains newly - // created files. Try again on failure, for up to 60 seconds. +/** + * Init logic for `debug` instances. + * + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. + */ - // Set the timeout this long because some Windows Anti-Virus, such as Parity - // bit9, may lock files for up to a minute, causing npm package install - // failures. Also, take care to yield the scheduler. Windows scheduling gives - // CPU to a busy looping process, which can cause the program causing the lock - // contention to be starved of CPU by node, so the contention doesn't resolve. - if (platform === "win32") { - fs.rename = (function (fs$rename) { return function (from, to, cb) { - var start = Date.now() - var backoff = 0; - fs$rename(from, to, function CB (er) { - if (er - && (er.code === "EACCES" || er.code === "EPERM") - && Date.now() - start < 60000) { - setTimeout(function() { - fs.stat(to, function (stater, st) { - if (stater && stater.code === "ENOENT") - fs$rename(from, to, CB); - else - cb(er) - }) - }, backoff) - if (backoff < 100) - backoff += 10; - return; - } - if (cb) cb(er) - }) - }})(fs.rename) +function init (debug) { + debug.inspectOpts = {}; + + var keys = Object.keys(exports.inspectOpts); + for (var i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; } +} - // if read() returns EAGAIN, then just try it again. - fs.read = (function (fs$read) { - function read (fd, buffer, offset, length, position, callback_) { - var callback - if (callback_ && typeof callback_ === 'function') { - var eagCounter = 0 - callback = function (er, _, __) { - if (er && er.code === 'EAGAIN' && eagCounter < 10) { - eagCounter ++ - return fs$read.call(fs, fd, buffer, offset, length, position, callback) - } - callback_.apply(this, arguments) - } - } - return fs$read.call(fs, fd, buffer, offset, length, position, callback) - } +/** + * Enable namespaces listed in `process.env.DEBUG` initially. + */ - // This ensures `util.promisify` works as it does for native `fs.read`. - if (Object.setPrototypeOf) Object.setPrototypeOf(read, fs$read) - return read - })(fs.read) +exports.enable(load()); - fs.readSync = (function (fs$readSync) { return function (fd, buffer, offset, length, position) { - var eagCounter = 0 - while (true) { - try { - return fs$readSync.call(fs, fd, buffer, offset, length, position) - } catch (er) { - if (er.code === 'EAGAIN' && eagCounter < 10) { - eagCounter ++ - continue - } - throw er - } - } - }})(fs.readSync) - function patchLchmod (fs) { - fs.lchmod = function (path, mode, callback) { - fs.open( path - , constants.O_WRONLY | constants.O_SYMLINK - , mode - , function (err, fd) { - if (err) { - if (callback) callback(err) - return - } - // prefer to return the chmod error, if one occurs, - // but still try to close, and report closing errors if they occur. - fs.fchmod(fd, mode, function (err) { - fs.close(fd, function(err2) { - if (callback) callback(err || err2) - }) - }) - }) - } +/***/ }), - fs.lchmodSync = function (path, mode) { - var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode) +/***/ 80761: +/***/ ((module) => { - // prefer to return the chmod error, if one occurs, - // but still try to close, and report closing errors if they occur. - var threw = true - var ret - try { - ret = fs.fchmodSync(fd, mode) - threw = false - } finally { - if (threw) { - try { - fs.closeSync(fd) - } catch (er) {} - } else { - fs.closeSync(fd) - } - } - return ret - } - } +/** + * Helpers. + */ - function patchLutimes (fs) { - if (constants.hasOwnProperty("O_SYMLINK")) { - fs.lutimes = function (path, at, mt, cb) { - fs.open(path, constants.O_SYMLINK, function (er, fd) { - if (er) { - if (cb) cb(er) - return - } - fs.futimes(fd, at, mt, function (er) { - fs.close(fd, function (er2) { - if (cb) cb(er || er2) - }) - }) - }) - } +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var y = d * 365.25; - fs.lutimesSync = function (path, at, mt) { - var fd = fs.openSync(path, constants.O_SYMLINK) - var ret - var threw = true - try { - ret = fs.futimesSync(fd, at, mt) - threw = false - } finally { - if (threw) { - try { - fs.closeSync(fd) - } catch (er) {} - } else { - fs.closeSync(fd) - } - } - return ret - } +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ - } else { - fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb) } - fs.lutimesSync = function () {} - } +module.exports = function(val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isNaN(val) === false) { + return options.long ? fmtLong(val) : fmtShort(val); } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); +}; - function chmodFix (orig) { - if (!orig) return orig - return function (target, mode, cb) { - return orig.call(fs, target, mode, function (er) { - if (chownErOk(er)) er = null - if (cb) cb.apply(this, arguments) - }) - } - } +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ - function chmodFixSync (orig) { - if (!orig) return orig - return function (target, mode) { - try { - return orig.call(fs, target, mode) - } catch (er) { - if (!chownErOk(er)) throw er - } - } +function parse(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; } +} +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ - function chownFix (orig) { - if (!orig) return orig - return function (target, uid, gid, cb) { - return orig.call(fs, target, uid, gid, function (er) { - if (chownErOk(er)) er = null - if (cb) cb.apply(this, arguments) - }) - } +function fmtShort(ms) { + if (ms >= d) { + return Math.round(ms / d) + 'd'; } - - function chownFixSync (orig) { - if (!orig) return orig - return function (target, uid, gid) { - try { - return orig.call(fs, target, uid, gid) - } catch (er) { - if (!chownErOk(er)) throw er - } - } + if (ms >= h) { + return Math.round(ms / h) + 'h'; } - - function statFix (orig) { - if (!orig) return orig - // Older versions of Node erroneously returned signed integers for - // uid + gid. - return function (target, options, cb) { - if (typeof options === 'function') { - cb = options - options = null - } - function callback (er, stats) { - if (stats) { - if (stats.uid < 0) stats.uid += 0x100000000 - if (stats.gid < 0) stats.gid += 0x100000000 - } - if (cb) cb.apply(this, arguments) - } - return options ? orig.call(fs, target, options, callback) - : orig.call(fs, target, callback) - } + if (ms >= m) { + return Math.round(ms / m) + 'm'; } - - function statFixSync (orig) { - if (!orig) return orig - // Older versions of Node erroneously returned signed integers for - // uid + gid. - return function (target, options) { - var stats = options ? orig.call(fs, target, options) - : orig.call(fs, target) - if (stats) { - if (stats.uid < 0) stats.uid += 0x100000000 - if (stats.gid < 0) stats.gid += 0x100000000 - } - return stats; - } + if (ms >= s) { + return Math.round(ms / s) + 's'; } + return ms + 'ms'; +} - // ENOSYS means that the fs doesn't support the op. Just ignore - // that, because it doesn't matter. - // - // if there's no getuid, or if getuid() is something other - // than 0, and the error is EINVAL or EPERM, then just ignore - // it. - // - // This specific case is a silent failure in cp, install, tar, - // and most other unix tools that manage permissions. - // - // When running as root, or if other types of errors are - // encountered, then it's strict. - function chownErOk (er) { - if (!er) - return true +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ - if (er.code === "ENOSYS") - return true +function fmtLong(ms) { + return plural(ms, d, 'day') || + plural(ms, h, 'hour') || + plural(ms, m, 'minute') || + plural(ms, s, 'second') || + ms + ' ms'; +} - var nonroot = !process.getuid || process.getuid() !== 0 - if (nonroot) { - if (er.code === "EINVAL" || er.code === "EPERM") - return true - } +/** + * Pluralization helper. + */ - return false +function plural(ms, n, name) { + if (ms < n) { + return; + } + if (ms < n * 1.5) { + return Math.floor(ms / n) + ' ' + name; } + return Math.ceil(ms / n) + ' ' + name + 's'; } /***/ }), -/***/ 31621: +/***/ 35298: /***/ ((module) => { "use strict"; -module.exports = (flag, argv = process.argv) => { - const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); - const position = argv.indexOf(prefix + flag); - const terminatorPosition = argv.indexOf('--'); - return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); -}; - - -/***/ }), - -/***/ 76339: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var bind = __nccwpck_require__(88334); +// You may be tempted to copy and paste this, +// but take a look at the commit history first, +// this is a moving target so relying on the module +// is the best way to make sure the optimization +// method is kept up to date and compatible with +// every Node version. -module.exports = bind.call(Function.call, Object.prototype.hasOwnProperty); +function flatstr (s) { + s | 0 + return s +} +module.exports = flatstr /***/ }), -/***/ 95193: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 46868: +/***/ ((module) => { "use strict"; /*! - * http-errors - * Copyright(c) 2014 Jonathan Ong - * Copyright(c) 2016 Douglas Christopher Wilson + * forwarded + * Copyright(c) 2014-2017 Douglas Christopher Wilson * MIT Licensed */ -/** - * Module dependencies. - * @private - */ - -var deprecate = __nccwpck_require__(18883)('http-errors') -var setPrototypeOf = __nccwpck_require__(40414) -var statuses = __nccwpck_require__(57415) -var inherits = __nccwpck_require__(44124) -var toIdentifier = __nccwpck_require__(46399) - /** * Module exports. * @public */ -module.exports = createError -module.exports.HttpError = createHttpErrorConstructor() -module.exports.isHttpError = createIsHttpErrorFunction(module.exports.HttpError) +module.exports = forwarded -// Populate exports for all constructors -populateConstructorExports(module.exports, statuses.codes, module.exports.HttpError) +/** + * Get all addresses in the request, using the `X-Forwarded-For` header. + * + * @param {object} req + * @return {array} + * @public + */ + +function forwarded (req) { + if (!req) { + throw new TypeError('argument req is required') + } + + // simple header parsing + var proxyAddrs = parse(req.headers['x-forwarded-for'] || '') + var socketAddr = getSocketAddr(req) + var addrs = [socketAddr].concat(proxyAddrs) + + // return all addresses + return addrs +} /** - * Get the code class of a status code. + * Get the socket address for a request. + * + * @param {object} req + * @return {string} * @private */ -function codeClass (status) { - return Number(String(status).charAt(0) + '00') +function getSocketAddr (req) { + return req.socket + ? req.socket.remoteAddress + : req.connection.remoteAddress } /** - * Create a new HTTP Error. + * Parse the X-Forwarded-For header. * - * @returns {Error} - * @public + * @param {string} header + * @private */ -function createError () { - // so much arity going on ~_~ - var err - var msg - var status = 500 - var props = {} - for (var i = 0; i < arguments.length; i++) { - var arg = arguments[i] - if (arg instanceof Error) { - err = arg - status = err.status || err.statusCode || status - continue - } - switch (typeof arg) { - case 'string': - msg = arg +function parse (header) { + var end = header.length + var list = [] + var start = header.length + + // gather addresses, backwards + for (var i = header.length - 1; i >= 0; i--) { + switch (header.charCodeAt(i)) { + case 0x20: /* */ + if (start === end) { + start = end = i + } break - case 'number': - status = arg - if (i !== 0) { - deprecate('non-first-argument status code; replace with createError(' + arg + ', ...)') + case 0x2c: /* , */ + if (start !== end) { + list.push(header.substring(start, end)) } + start = end = i break - case 'object': - props = arg + default: + start = i break } } - if (typeof status === 'number' && (status < 400 || status >= 600)) { - deprecate('non-error status code; use only 4xx or 5xx status codes') + // final address + if (start !== end) { + list.push(header.substring(start, end)) } - if (typeof status !== 'number' || - (!statuses[status] && (status < 400 || status >= 600))) { - status = 500 - } + return list +} - // constructor - var HttpError = createError[status] || createError[codeClass(status)] - if (!err) { - // create error - err = HttpError - ? new HttpError(msg) - : new Error(msg || statuses[status]) - Error.captureStackTrace(err, createError) - } +/***/ }), - if (!HttpError || !(err instanceof HttpError) || err.status !== status) { - // add properties to generic error - err.expose = status < 500 - err.status = err.statusCode = status - } +/***/ 83136: +/***/ ((module) => { + +"use strict"; +/*! + * fresh + * Copyright(c) 2012 TJ Holowaychuk + * Copyright(c) 2016-2017 Douglas Christopher Wilson + * MIT Licensed + */ - for (var key in props) { - if (key !== 'status' && key !== 'statusCode') { - err[key] = props[key] - } - } - return err -} /** - * Create HTTP error abstract base class. + * RegExp to check for no-cache token in Cache-Control. * @private */ -function createHttpErrorConstructor () { - function HttpError () { - throw new TypeError('cannot construct abstract class') - } +var CACHE_CONTROL_NO_CACHE_REGEXP = /(?:^|,)\s*?no-cache\s*?(?:,|$)/ - inherits(HttpError, Error) +/** + * Module exports. + * @public + */ - return HttpError -} +module.exports = fresh /** - * Create a constructor for a client error. - * @private + * Check freshness of the response using request and response headers. + * + * @param {Object} reqHeaders + * @param {Object} resHeaders + * @return {Boolean} + * @public */ -function createClientErrorConstructor (HttpError, name, code) { - var className = toClassName(name) +function fresh (reqHeaders, resHeaders) { + // fields + var modifiedSince = reqHeaders['if-modified-since'] + var noneMatch = reqHeaders['if-none-match'] - function ClientError (message) { - // create the error object - var msg = message != null ? message : statuses[code] - var err = new Error(msg) + // unconditional request + if (!modifiedSince && !noneMatch) { + return false + } - // capture a stack trace to the construction point - Error.captureStackTrace(err, ClientError) + // Always return stale when Cache-Control: no-cache + // to support end-to-end reload requests + // https://tools.ietf.org/html/rfc2616#section-14.9.4 + var cacheControl = reqHeaders['cache-control'] + if (cacheControl && CACHE_CONTROL_NO_CACHE_REGEXP.test(cacheControl)) { + return false + } - // adjust the [[Prototype]] - setPrototypeOf(err, ClientError.prototype) + // if-none-match + if (noneMatch && noneMatch !== '*') { + var etag = resHeaders['etag'] - // redefine the error message - Object.defineProperty(err, 'message', { - enumerable: true, - configurable: true, - value: msg, - writable: true - }) + if (!etag) { + return false + } - // redefine the error name - Object.defineProperty(err, 'name', { - enumerable: false, - configurable: true, - value: className, - writable: true - }) + var etagStale = true + var matches = parseTokenList(noneMatch) + for (var i = 0; i < matches.length; i++) { + var match = matches[i] + if (match === etag || match === 'W/' + etag || 'W/' + match === etag) { + etagStale = false + break + } + } - return err + if (etagStale) { + return false + } } - inherits(ClientError, HttpError) - nameFunc(ClientError, className) + // if-modified-since + if (modifiedSince) { + var lastModified = resHeaders['last-modified'] + var modifiedStale = !lastModified || !(parseHttpDate(lastModified) <= parseHttpDate(modifiedSince)) - ClientError.prototype.status = code - ClientError.prototype.statusCode = code - ClientError.prototype.expose = true + if (modifiedStale) { + return false + } + } - return ClientError + return true } /** - * Create function to test is a value is a HttpError. + * Parse an HTTP Date into a number. + * + * @param {string} date * @private */ -function createIsHttpErrorFunction (HttpError) { - return function isHttpError (val) { - if (!val || typeof val !== 'object') { - return false - } - - if (val instanceof HttpError) { - return true - } +function parseHttpDate (date) { + var timestamp = date && Date.parse(date) - return val instanceof Error && - typeof val.expose === 'boolean' && - typeof val.statusCode === 'number' && val.status === val.statusCode - } + // istanbul ignore next: guard against date.js Date.parse patching + return typeof timestamp === 'number' + ? timestamp + : NaN } /** - * Create a constructor for a server error. + * Parse a HTTP token list. + * + * @param {string} str * @private */ -function createServerErrorConstructor (HttpError, name, code) { - var className = toClassName(name) +function parseTokenList (str) { + var end = 0 + var list = [] + var start = 0 - function ServerError (message) { - // create the error object - var msg = message != null ? message : statuses[code] - var err = new Error(msg) + // gather tokens + for (var i = 0, len = str.length; i < len; i++) { + switch (str.charCodeAt(i)) { + case 0x20: /* */ + if (start === end) { + start = end = i + 1 + } + break + case 0x2c: /* , */ + list.push(str.substring(start, end)) + start = end = i + 1 + break + default: + end = i + 1 + break + } + } - // capture a stack trace to the construction point - Error.captureStackTrace(err, ServerError) + // final token + list.push(str.substring(start, end)) - // adjust the [[Prototype]] - setPrototypeOf(err, ServerError.prototype) + return list +} - // redefine the error message - Object.defineProperty(err, 'message', { - enumerable: true, - configurable: true, - value: msg, - writable: true - }) - // redefine the error name - Object.defineProperty(err, 'name', { - enumerable: false, - configurable: true, - value: className, - writable: true - }) +/***/ }), - return err - } +/***/ 19320: +/***/ ((module) => { - inherits(ServerError, HttpError) - nameFunc(ServerError, className) +"use strict"; - ServerError.prototype.status = code - ServerError.prototype.statusCode = code - ServerError.prototype.expose = false - return ServerError -} +/* eslint no-invalid-this: 1 */ -/** - * Set the name of a function, if possible. - * @private - */ +var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; +var slice = Array.prototype.slice; +var toStr = Object.prototype.toString; +var funcType = '[object Function]'; -function nameFunc (func, name) { - var desc = Object.getOwnPropertyDescriptor(func, 'name') +module.exports = function bind(that) { + var target = this; + if (typeof target !== 'function' || toStr.call(target) !== funcType) { + throw new TypeError(ERROR_MESSAGE + target); + } + var args = slice.call(arguments, 1); - if (desc && desc.configurable) { - desc.value = name - Object.defineProperty(func, 'name', desc) - } -} + var bound; + var binder = function () { + if (this instanceof bound) { + var result = target.apply( + this, + args.concat(slice.call(arguments)) + ); + if (Object(result) === result) { + return result; + } + return this; + } else { + return target.apply( + that, + args.concat(slice.call(arguments)) + ); + } + }; -/** - * Populate the exports object with constructors for every error class. - * @private - */ + var boundLength = Math.max(0, target.length - args.length); + var boundArgs = []; + for (var i = 0; i < boundLength; i++) { + boundArgs.push('$' + i); + } -function populateConstructorExports (exports, codes, HttpError) { - codes.forEach(function forEachCode (code) { - var CodeError - var name = toIdentifier(statuses[code]) + bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder); - switch (codeClass(code)) { - case 400: - CodeError = createClientErrorConstructor(HttpError, name, code) - break - case 500: - CodeError = createServerErrorConstructor(HttpError, name, code) - break + if (target.prototype) { + var Empty = function Empty() {}; + Empty.prototype = target.prototype; + bound.prototype = new Empty(); + Empty.prototype = null; } - if (CodeError) { - // export the constructor - exports[code] = CodeError - exports[name] = CodeError - } - }) + return bound; +}; - // backwards-compatibility - exports["I'mateapot"] = deprecate.function(exports.ImATeapot, - '"I\'mateapot"; use "ImATeapot" instead') + +/***/ }), + +/***/ 88334: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var implementation = __nccwpck_require__(19320); + +module.exports = Function.prototype.bind || implementation; + + +/***/ }), + +/***/ 67356: +/***/ ((module) => { + +"use strict"; + + +module.exports = clone + +var getPrototypeOf = Object.getPrototypeOf || function (obj) { + return obj.__proto__ } -/** - * Get a class name from a name identifier. - * @private - */ +function clone (obj) { + if (obj === null || typeof obj !== 'object') + return obj -function toClassName (name) { - return name.substr(-5) !== 'Error' - ? name + 'Error' - : name + if (obj instanceof Object) + var copy = { __proto__: getPrototypeOf(obj) } + else + var copy = Object.create(null) + + Object.getOwnPropertyNames(obj).forEach(function (key) { + Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key)) + }) + + return copy } /***/ }), -/***/ 15098: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ 77758: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +var fs = __nccwpck_require__(57147) +var polyfills = __nccwpck_require__(20263) +var legacy = __nccwpck_require__(73086) +var clone = __nccwpck_require__(67356) -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const net_1 = __importDefault(__nccwpck_require__(41808)); -const tls_1 = __importDefault(__nccwpck_require__(24404)); -const url_1 = __importDefault(__nccwpck_require__(57310)); -const assert_1 = __importDefault(__nccwpck_require__(39491)); -const debug_1 = __importDefault(__nccwpck_require__(38237)); -const agent_base_1 = __nccwpck_require__(49690); -const parse_proxy_response_1 = __importDefault(__nccwpck_require__(595)); -const debug = debug_1.default('https-proxy-agent:agent'); -/** - * The `HttpsProxyAgent` implements an HTTP Agent subclass that connects to - * the specified "HTTP(s) proxy server" in order to proxy HTTPS requests. - * - * Outgoing HTTP requests are first tunneled through the proxy server using the - * `CONNECT` HTTP request method to establish a connection to the proxy server, - * and then the proxy server connects to the destination target and issues the - * HTTP request from the proxy server. - * - * `https:` requests have their socket connection upgraded to TLS once - * the connection to the proxy server has been established. - * - * @api public - */ -class HttpsProxyAgent extends agent_base_1.Agent { - constructor(_opts) { - let opts; - if (typeof _opts === 'string') { - opts = url_1.default.parse(_opts); - } - else { - opts = _opts; - } - if (!opts) { - throw new Error('an HTTP(S) proxy server `host` and `port` must be specified!'); - } - debug('creating new HttpsProxyAgent instance: %o', opts); - super(opts); - const proxy = Object.assign({}, opts); - // If `true`, then connect to the proxy server over TLS. - // Defaults to `false`. - this.secureProxy = opts.secureProxy || isHTTPS(proxy.protocol); - // Prefer `hostname` over `host`, and set the `port` if needed. - proxy.host = proxy.hostname || proxy.host; - if (typeof proxy.port === 'string') { - proxy.port = parseInt(proxy.port, 10); - } - if (!proxy.port && proxy.host) { - proxy.port = this.secureProxy ? 443 : 80; - } - // ALPN is supported by Node.js >= v5. - // attempt to negotiate http/1.1 for proxy servers that support http/2 - if (this.secureProxy && !('ALPNProtocols' in proxy)) { - proxy.ALPNProtocols = ['http 1.1']; - } - if (proxy.host && proxy.path) { - // If both a `host` and `path` are specified then it's most likely - // the result of a `url.parse()` call... we need to remove the - // `path` portion so that `net.connect()` doesn't attempt to open - // that as a Unix socket file. - delete proxy.path; - delete proxy.pathname; - } - this.proxy = proxy; - } - /** - * Called when the node-core HTTP client library is creating a - * new HTTP request. - * - * @api protected - */ - callback(req, opts) { - return __awaiter(this, void 0, void 0, function* () { - const { proxy, secureProxy } = this; - // Create a socket connection to the proxy server. - let socket; - if (secureProxy) { - debug('Creating `tls.Socket`: %o', proxy); - socket = tls_1.default.connect(proxy); - } - else { - debug('Creating `net.Socket`: %o', proxy); - socket = net_1.default.connect(proxy); - } - const headers = Object.assign({}, proxy.headers); - const hostname = `${opts.host}:${opts.port}`; - let payload = `CONNECT ${hostname} HTTP/1.1\r\n`; - // Inject the `Proxy-Authorization` header if necessary. - if (proxy.auth) { - headers['Proxy-Authorization'] = `Basic ${Buffer.from(proxy.auth).toString('base64')}`; - } - // The `Host` header should only include the port - // number when it is not the default port. - let { host, port, secureEndpoint } = opts; - if (!isDefaultPort(port, secureEndpoint)) { - host += `:${port}`; - } - headers.Host = host; - headers.Connection = 'close'; - for (const name of Object.keys(headers)) { - payload += `${name}: ${headers[name]}\r\n`; - } - const proxyResponsePromise = parse_proxy_response_1.default(socket); - socket.write(`${payload}\r\n`); - const { statusCode, buffered } = yield proxyResponsePromise; - if (statusCode === 200) { - req.once('socket', resume); - if (opts.secureEndpoint) { - const servername = opts.servername || opts.host; - if (!servername) { - throw new Error('Could not determine "servername"'); - } - // The proxy is connecting to a TLS server, so upgrade - // this socket connection to a TLS connection. - debug('Upgrading socket connection to TLS'); - return tls_1.default.connect(Object.assign(Object.assign({}, omit(opts, 'host', 'hostname', 'path', 'port')), { socket, - servername })); - } - return socket; - } - // Some other status code that's not 200... need to re-play the HTTP - // header "data" events onto the socket once the HTTP machinery is - // attached so that the node core `http` can parse and handle the - // error status code. - // Close the original socket, and a new "fake" socket is returned - // instead, so that the proxy doesn't get the HTTP request - // written to it (which may contain `Authorization` headers or other - // sensitive data). - // - // See: https://hackerone.com/reports/541502 - socket.destroy(); - const fakeSocket = new net_1.default.Socket(); - fakeSocket.readable = true; - // Need to wait for the "socket" event to re-play the "data" events. - req.once('socket', (s) => { - debug('replaying proxy buffer for failed request'); - assert_1.default(s.listenerCount('data') > 0); - // Replay the "buffered" Buffer onto the fake `socket`, since at - // this point the HTTP module machinery has been hooked up for - // the user. - s.push(buffered); - s.push(null); - }); - return fakeSocket; - }); - } -} -exports["default"] = HttpsProxyAgent; -function resume(socket) { - socket.resume(); -} -function isDefaultPort(port, secure) { - return Boolean((!secure && port === 80) || (secure && port === 443)); -} -function isHTTPS(protocol) { - return typeof protocol === 'string' ? /^https:?$/i.test(protocol) : false; -} -function omit(obj, ...keys) { - const ret = {}; - let key; - for (key in obj) { - if (!keys.includes(key)) { - ret[key] = obj[key]; - } - } - return ret; -} -//# sourceMappingURL=agent.js.map - -/***/ }), - -/***/ 77219: -/***/ (function(module, __unused_webpack_exports, __nccwpck_require__) { +var util = __nccwpck_require__(73837) -"use strict"; +/* istanbul ignore next - node 0.x polyfill */ +var gracefulQueue +var previousSymbol -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -const agent_1 = __importDefault(__nccwpck_require__(15098)); -function createHttpsProxyAgent(opts) { - return new agent_1.default(opts); +/* istanbul ignore else - node 0.x polyfill */ +if (typeof Symbol === 'function' && typeof Symbol.for === 'function') { + gracefulQueue = Symbol.for('graceful-fs.queue') + // This is used in testing by future versions + previousSymbol = Symbol.for('graceful-fs.previous') +} else { + gracefulQueue = '___graceful-fs.queue' + previousSymbol = '___graceful-fs.previous' } -(function (createHttpsProxyAgent) { - createHttpsProxyAgent.HttpsProxyAgent = agent_1.default; - createHttpsProxyAgent.prototype = agent_1.default.prototype; -})(createHttpsProxyAgent || (createHttpsProxyAgent = {})); -module.exports = createHttpsProxyAgent; -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 595: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { -"use strict"; +function noop () {} -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const debug_1 = __importDefault(__nccwpck_require__(38237)); -const debug = debug_1.default('https-proxy-agent:parse-proxy-response'); -function parseProxyResponse(socket) { - return new Promise((resolve, reject) => { - // we need to buffer any HTTP traffic that happens with the proxy before we get - // the CONNECT response, so that if the response is anything other than an "200" - // response code, then we can re-play the "data" events on the socket once the - // HTTP parser is hooked up... - let buffersLength = 0; - const buffers = []; - function read() { - const b = socket.read(); - if (b) - ondata(b); - else - socket.once('readable', read); - } - function cleanup() { - socket.removeListener('end', onend); - socket.removeListener('error', onerror); - socket.removeListener('close', onclose); - socket.removeListener('readable', read); - } - function onclose(err) { - debug('onclose had error %o', err); - } - function onend() { - debug('onend'); - } - function onerror(err) { - cleanup(); - debug('onerror %o', err); - reject(err); - } - function ondata(b) { - buffers.push(b); - buffersLength += b.length; - const buffered = Buffer.concat(buffers, buffersLength); - const endOfHeaders = buffered.indexOf('\r\n\r\n'); - if (endOfHeaders === -1) { - // keep buffering - debug('have not received end of HTTP headers yet...'); - read(); - return; - } - const firstLine = buffered.toString('ascii', 0, buffered.indexOf('\r\n')); - const statusCode = +firstLine.split(' ')[1]; - debug('got proxy server response: %o', firstLine); - resolve({ - statusCode, - buffered - }); - } - socket.on('error', onerror); - socket.on('close', onclose); - socket.on('end', onend); - read(); - }); +function publishQueue(context, queue) { + Object.defineProperty(context, gracefulQueue, { + get: function() { + return queue + } + }) } -exports["default"] = parseProxyResponse; -//# sourceMappingURL=parse-proxy-response.js.map -/***/ }), - -/***/ 39695: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -var Buffer = (__nccwpck_require__(15118).Buffer); +var debug = noop +if (util.debuglog) + debug = util.debuglog('gfs4') +else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) + debug = function() { + var m = util.format.apply(util, arguments) + m = 'GFS4: ' + m.split(/\n/).join('\nGFS4: ') + console.error(m) + } -// Multibyte codec. In this scheme, a character is represented by 1 or more bytes. -// Our codec supports UTF-16 surrogates, extensions for GB18030 and unicode sequences. -// To save memory and loading time, we read table files only when requested. +// Once time initialization +if (!fs[gracefulQueue]) { + // This queue can be shared by multiple loaded instances + var queue = global[gracefulQueue] || [] + publishQueue(fs, queue) -exports._dbcs = DBCSCodec; + // Patch fs.close/closeSync to shared queue version, because we need + // to retry() whenever a close happens *anywhere* in the program. + // This is essential when multiple graceful-fs instances are + // in play at the same time. + fs.close = (function (fs$close) { + function close (fd, cb) { + return fs$close.call(fs, fd, function (err) { + // This function uses the graceful-fs shared queue + if (!err) { + resetQueue() + } -var UNASSIGNED = -1, - GB18030_CODE = -2, - SEQ_START = -10, - NODE_START = -1000, - UNASSIGNED_NODE = new Array(0x100), - DEF_CHAR = -1; + if (typeof cb === 'function') + cb.apply(this, arguments) + }) + } -for (var i = 0; i < 0x100; i++) - UNASSIGNED_NODE[i] = UNASSIGNED; + Object.defineProperty(close, previousSymbol, { + value: fs$close + }) + return close + })(fs.close) + fs.closeSync = (function (fs$closeSync) { + function closeSync (fd) { + // This function uses the graceful-fs shared queue + fs$closeSync.apply(fs, arguments) + resetQueue() + } -// Class DBCSCodec reads and initializes mapping tables. -function DBCSCodec(codecOptions, iconv) { - this.encodingName = codecOptions.encodingName; - if (!codecOptions) - throw new Error("DBCS codec is called without the data.") - if (!codecOptions.table) - throw new Error("Encoding '" + this.encodingName + "' has no data."); + Object.defineProperty(closeSync, previousSymbol, { + value: fs$closeSync + }) + return closeSync + })(fs.closeSync) - // Load tables. - var mappingTable = codecOptions.table(); + if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) { + process.on('exit', function() { + debug(fs[gracefulQueue]) + __nccwpck_require__(39491).equal(fs[gracefulQueue].length, 0) + }) + } +} +if (!global[gracefulQueue]) { + publishQueue(global, fs[gracefulQueue]); +} - // Decode tables: MBCS -> Unicode. +module.exports = patch(clone(fs)) +if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs.__patched) { + module.exports = patch(fs) + fs.__patched = true; +} - // decodeTables is a trie, encoded as an array of arrays of integers. Internal arrays are trie nodes and all have len = 256. - // Trie root is decodeTables[0]. - // Values: >= 0 -> unicode character code. can be > 0xFFFF - // == UNASSIGNED -> unknown/unassigned sequence. - // == GB18030_CODE -> this is the end of a GB18030 4-byte sequence. - // <= NODE_START -> index of the next node in our trie to process next byte. - // <= SEQ_START -> index of the start of a character code sequence, in decodeTableSeq. - this.decodeTables = []; - this.decodeTables[0] = UNASSIGNED_NODE.slice(0); // Create root node. +function patch (fs) { + // Everything that references the open() function needs to be in here + polyfills(fs) + fs.gracefulify = patch - // Sometimes a MBCS char corresponds to a sequence of unicode chars. We store them as arrays of integers here. - this.decodeTableSeq = []; + fs.createReadStream = createReadStream + fs.createWriteStream = createWriteStream + var fs$readFile = fs.readFile + fs.readFile = readFile + function readFile (path, options, cb) { + if (typeof options === 'function') + cb = options, options = null - // Actual mapping tables consist of chunks. Use them to fill up decode tables. - for (var i = 0; i < mappingTable.length; i++) - this._addDecodeChunk(mappingTable[i]); + return go$readFile(path, options, cb) - this.defaultCharUnicode = iconv.defaultCharUnicode; + function go$readFile (path, options, cb, startTime) { + return fs$readFile(path, options, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$readFile, [path, options, cb], err, startTime || Date.now(), Date.now()]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + } + }) + } + } - - // Encode tables: Unicode -> DBCS. + var fs$writeFile = fs.writeFile + fs.writeFile = writeFile + function writeFile (path, data, options, cb) { + if (typeof options === 'function') + cb = options, options = null - // `encodeTable` is array mapping from unicode char to encoded char. All its values are integers for performance. - // Because it can be sparse, it is represented as array of buckets by 256 chars each. Bucket can be null. - // Values: >= 0 -> it is a normal char. Write the value (if <=256 then 1 byte, if <=65536 then 2 bytes, etc.). - // == UNASSIGNED -> no conversion found. Output a default char. - // <= SEQ_START -> it's an index in encodeTableSeq, see below. The character starts a sequence. - this.encodeTable = []; - - // `encodeTableSeq` is used when a sequence of unicode characters is encoded as a single code. We use a tree of - // objects where keys correspond to characters in sequence and leafs are the encoded dbcs values. A special DEF_CHAR key - // means end of sequence (needed when one sequence is a strict subsequence of another). - // Objects are kept separately from encodeTable to increase performance. - this.encodeTableSeq = []; + return go$writeFile(path, data, options, cb) - // Some chars can be decoded, but need not be encoded. - var skipEncodeChars = {}; - if (codecOptions.encodeSkipVals) - for (var i = 0; i < codecOptions.encodeSkipVals.length; i++) { - var val = codecOptions.encodeSkipVals[i]; - if (typeof val === 'number') - skipEncodeChars[val] = true; - else - for (var j = val.from; j <= val.to; j++) - skipEncodeChars[j] = true; + function go$writeFile (path, data, options, cb, startTime) { + return fs$writeFile(path, data, options, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$writeFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) } - - // Use decode trie to recursively fill out encode tables. - this._fillEncodeTable(0, 0, skipEncodeChars); - - // Add more encoding pairs when needed. - if (codecOptions.encodeAdd) { - for (var uChar in codecOptions.encodeAdd) - if (Object.prototype.hasOwnProperty.call(codecOptions.encodeAdd, uChar)) - this._setEncodeChar(uChar.charCodeAt(0), codecOptions.encodeAdd[uChar]); + }) } + } - this.defCharSB = this.encodeTable[0][iconv.defaultCharSingleByte.charCodeAt(0)]; - if (this.defCharSB === UNASSIGNED) this.defCharSB = this.encodeTable[0]['?']; - if (this.defCharSB === UNASSIGNED) this.defCharSB = "?".charCodeAt(0); - + var fs$appendFile = fs.appendFile + if (fs$appendFile) + fs.appendFile = appendFile + function appendFile (path, data, options, cb) { + if (typeof options === 'function') + cb = options, options = null - // Load & create GB18030 tables when needed. - if (typeof codecOptions.gb18030 === 'function') { - this.gb18030 = codecOptions.gb18030(); // Load GB18030 ranges. + return go$appendFile(path, data, options, cb) - // Add GB18030 decode tables. - var thirdByteNodeIdx = this.decodeTables.length; - var thirdByteNode = this.decodeTables[thirdByteNodeIdx] = UNASSIGNED_NODE.slice(0); + function go$appendFile (path, data, options, cb, startTime) { + return fs$appendFile(path, data, options, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$appendFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + } + }) + } + } - var fourthByteNodeIdx = this.decodeTables.length; - var fourthByteNode = this.decodeTables[fourthByteNodeIdx] = UNASSIGNED_NODE.slice(0); + var fs$copyFile = fs.copyFile + if (fs$copyFile) + fs.copyFile = copyFile + function copyFile (src, dest, flags, cb) { + if (typeof flags === 'function') { + cb = flags + flags = 0 + } + return go$copyFile(src, dest, flags, cb) - for (var i = 0x81; i <= 0xFE; i++) { - var secondByteNodeIdx = NODE_START - this.decodeTables[0][i]; - var secondByteNode = this.decodeTables[secondByteNodeIdx]; - for (var j = 0x30; j <= 0x39; j++) - secondByteNode[j] = NODE_START - thirdByteNodeIdx; + function go$copyFile (src, dest, flags, cb, startTime) { + return fs$copyFile(src, dest, flags, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$copyFile, [src, dest, flags, cb], err, startTime || Date.now(), Date.now()]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) } - for (var i = 0x81; i <= 0xFE; i++) - thirdByteNode[i] = NODE_START - fourthByteNodeIdx; - for (var i = 0x30; i <= 0x39; i++) - fourthByteNode[i] = GB18030_CODE - } -} + }) + } + } -DBCSCodec.prototype.encoder = DBCSEncoder; -DBCSCodec.prototype.decoder = DBCSDecoder; + var fs$readdir = fs.readdir + fs.readdir = readdir + function readdir (path, options, cb) { + if (typeof options === 'function') + cb = options, options = null -// Decoder helpers -DBCSCodec.prototype._getDecodeTrieNode = function(addr) { - var bytes = []; - for (; addr > 0; addr >>= 8) - bytes.push(addr & 0xFF); - if (bytes.length == 0) - bytes.push(0); + return go$readdir(path, options, cb) - var node = this.decodeTables[0]; - for (var i = bytes.length-1; i > 0; i--) { // Traverse nodes deeper into the trie. - var val = node[bytes[i]]; + function go$readdir (path, options, cb, startTime) { + return fs$readdir(path, options, function (err, files) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$readdir, [path, options, cb], err, startTime || Date.now(), Date.now()]) + else { + if (files && files.sort) + files.sort() - if (val == UNASSIGNED) { // Create new node. - node[bytes[i]] = NODE_START - this.decodeTables.length; - this.decodeTables.push(node = UNASSIGNED_NODE.slice(0)); - } - else if (val <= NODE_START) { // Existing node. - node = this.decodeTables[NODE_START - val]; + if (typeof cb === 'function') + cb.call(this, err, files) } - else - throw new Error("Overwrite byte in " + this.encodingName + ", addr: " + addr.toString(16)); + }) } - return node; -} + } + if (process.version.substr(0, 4) === 'v0.8') { + var legStreams = legacy(fs) + ReadStream = legStreams.ReadStream + WriteStream = legStreams.WriteStream + } -DBCSCodec.prototype._addDecodeChunk = function(chunk) { - // First element of chunk is the hex mbcs code where we start. - var curAddr = parseInt(chunk[0], 16); + var fs$ReadStream = fs.ReadStream + if (fs$ReadStream) { + ReadStream.prototype = Object.create(fs$ReadStream.prototype) + ReadStream.prototype.open = ReadStream$open + } - // Choose the decoding node where we'll write our chars. - var writeTable = this._getDecodeTrieNode(curAddr); - curAddr = curAddr & 0xFF; + var fs$WriteStream = fs.WriteStream + if (fs$WriteStream) { + WriteStream.prototype = Object.create(fs$WriteStream.prototype) + WriteStream.prototype.open = WriteStream$open + } - // Write all other elements of the chunk to the table. - for (var k = 1; k < chunk.length; k++) { - var part = chunk[k]; - if (typeof part === "string") { // String, write as-is. - for (var l = 0; l < part.length;) { - var code = part.charCodeAt(l++); - if (0xD800 <= code && code < 0xDC00) { // Decode surrogate - var codeTrail = part.charCodeAt(l++); - if (0xDC00 <= codeTrail && codeTrail < 0xE000) - writeTable[curAddr++] = 0x10000 + (code - 0xD800) * 0x400 + (codeTrail - 0xDC00); - else - throw new Error("Incorrect surrogate pair in " + this.encodingName + " at chunk " + chunk[0]); - } - else if (0x0FF0 < code && code <= 0x0FFF) { // Character sequence (our own encoding used) - var len = 0xFFF - code + 2; - var seq = []; - for (var m = 0; m < len; m++) - seq.push(part.charCodeAt(l++)); // Simple variation: don't support surrogates or subsequences in seq. + Object.defineProperty(fs, 'ReadStream', { + get: function () { + return ReadStream + }, + set: function (val) { + ReadStream = val + }, + enumerable: true, + configurable: true + }) + Object.defineProperty(fs, 'WriteStream', { + get: function () { + return WriteStream + }, + set: function (val) { + WriteStream = val + }, + enumerable: true, + configurable: true + }) - writeTable[curAddr++] = SEQ_START - this.decodeTableSeq.length; - this.decodeTableSeq.push(seq); - } - else - writeTable[curAddr++] = code; // Basic char - } - } - else if (typeof part === "number") { // Integer, meaning increasing sequence starting with prev character. - var charCode = writeTable[curAddr - 1] + 1; - for (var l = 0; l < part; l++) - writeTable[curAddr++] = charCode++; - } - else - throw new Error("Incorrect type '" + typeof part + "' given in " + this.encodingName + " at chunk " + chunk[0]); - } - if (curAddr > 0xFF) - throw new Error("Incorrect chunk in " + this.encodingName + " at addr " + chunk[0] + ": too long" + curAddr); -} + // legacy names + var FileReadStream = ReadStream + Object.defineProperty(fs, 'FileReadStream', { + get: function () { + return FileReadStream + }, + set: function (val) { + FileReadStream = val + }, + enumerable: true, + configurable: true + }) + var FileWriteStream = WriteStream + Object.defineProperty(fs, 'FileWriteStream', { + get: function () { + return FileWriteStream + }, + set: function (val) { + FileWriteStream = val + }, + enumerable: true, + configurable: true + }) -// Encoder helpers -DBCSCodec.prototype._getEncodeBucket = function(uCode) { - var high = uCode >> 8; // This could be > 0xFF because of astral characters. - if (this.encodeTable[high] === undefined) - this.encodeTable[high] = UNASSIGNED_NODE.slice(0); // Create bucket on demand. - return this.encodeTable[high]; -} + function ReadStream (path, options) { + if (this instanceof ReadStream) + return fs$ReadStream.apply(this, arguments), this + else + return ReadStream.apply(Object.create(ReadStream.prototype), arguments) + } -DBCSCodec.prototype._setEncodeChar = function(uCode, dbcsCode) { - var bucket = this._getEncodeBucket(uCode); - var low = uCode & 0xFF; - if (bucket[low] <= SEQ_START) - this.encodeTableSeq[SEQ_START-bucket[low]][DEF_CHAR] = dbcsCode; // There's already a sequence, set a single-char subsequence of it. - else if (bucket[low] == UNASSIGNED) - bucket[low] = dbcsCode; -} + function ReadStream$open () { + var that = this + open(that.path, that.flags, that.mode, function (err, fd) { + if (err) { + if (that.autoClose) + that.destroy() -DBCSCodec.prototype._setEncodeSequence = function(seq, dbcsCode) { - - // Get the root of character tree according to first character of the sequence. - var uCode = seq[0]; - var bucket = this._getEncodeBucket(uCode); - var low = uCode & 0xFF; + that.emit('error', err) + } else { + that.fd = fd + that.emit('open', fd) + that.read() + } + }) + } - var node; - if (bucket[low] <= SEQ_START) { - // There's already a sequence with - use it. - node = this.encodeTableSeq[SEQ_START-bucket[low]]; - } - else { - // There was no sequence object - allocate a new one. - node = {}; - if (bucket[low] !== UNASSIGNED) node[DEF_CHAR] = bucket[low]; // If a char was set before - make it a single-char subsequence. - bucket[low] = SEQ_START - this.encodeTableSeq.length; - this.encodeTableSeq.push(node); - } + function WriteStream (path, options) { + if (this instanceof WriteStream) + return fs$WriteStream.apply(this, arguments), this + else + return WriteStream.apply(Object.create(WriteStream.prototype), arguments) + } - // Traverse the character tree, allocating new nodes as needed. - for (var j = 1; j < seq.length-1; j++) { - var oldVal = node[uCode]; - if (typeof oldVal === 'object') - node = oldVal; + function WriteStream$open () { + var that = this + open(that.path, that.flags, that.mode, function (err, fd) { + if (err) { + that.destroy() + that.emit('error', err) + } else { + that.fd = fd + that.emit('open', fd) + } + }) + } + + function createReadStream (path, options) { + return new fs.ReadStream(path, options) + } + + function createWriteStream (path, options) { + return new fs.WriteStream(path, options) + } + + var fs$open = fs.open + fs.open = open + function open (path, flags, mode, cb) { + if (typeof mode === 'function') + cb = mode, mode = null + + return go$open(path, flags, mode, cb) + + function go$open (path, flags, mode, cb, startTime) { + return fs$open(path, flags, mode, function (err, fd) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$open, [path, flags, mode, cb], err, startTime || Date.now(), Date.now()]) else { - node = node[uCode] = {} - if (oldVal !== undefined) - node[DEF_CHAR] = oldVal + if (typeof cb === 'function') + cb.apply(this, arguments) } + }) } + } - // Set the leaf to given dbcsCode. - uCode = seq[seq.length-1]; - node[uCode] = dbcsCode; + return fs } -DBCSCodec.prototype._fillEncodeTable = function(nodeIdx, prefix, skipEncodeChars) { - var node = this.decodeTables[nodeIdx]; - for (var i = 0; i < 0x100; i++) { - var uCode = node[i]; - var mbCode = prefix + i; - if (skipEncodeChars[mbCode]) - continue; +function enqueue (elem) { + debug('ENQUEUE', elem[0].name, elem[1]) + fs[gracefulQueue].push(elem) + retry() +} - if (uCode >= 0) - this._setEncodeChar(uCode, mbCode); - else if (uCode <= NODE_START) - this._fillEncodeTable(NODE_START - uCode, mbCode << 8, skipEncodeChars); - else if (uCode <= SEQ_START) - this._setEncodeSequence(this.decodeTableSeq[SEQ_START - uCode], mbCode); +// keep track of the timeout between retry() calls +var retryTimer + +// reset the startTime and lastTime to now +// this resets the start of the 60 second overall timeout as well as the +// delay between attempts so that we'll retry these jobs sooner +function resetQueue () { + var now = Date.now() + for (var i = 0; i < fs[gracefulQueue].length; ++i) { + // entries that are only a length of 2 are from an older version, don't + // bother modifying those since they'll be retried anyway. + if (fs[gracefulQueue][i].length > 2) { + fs[gracefulQueue][i][3] = now // startTime + fs[gracefulQueue][i][4] = now // lastTime } + } + // call retry to make sure we're actively processing the queue + retry() } +function retry () { + // clear the timer and remove it to help prevent unintended concurrency + clearTimeout(retryTimer) + retryTimer = undefined + if (fs[gracefulQueue].length === 0) + return -// == Encoder ================================================================== + var elem = fs[gracefulQueue].shift() + var fn = elem[0] + var args = elem[1] + // these items may be unset if they were added by an older graceful-fs + var err = elem[2] + var startTime = elem[3] + var lastTime = elem[4] -function DBCSEncoder(options, codec) { - // Encoder state - this.leadSurrogate = -1; - this.seqObj = undefined; - - // Static data - this.encodeTable = codec.encodeTable; - this.encodeTableSeq = codec.encodeTableSeq; - this.defaultCharSingleByte = codec.defCharSB; - this.gb18030 = codec.gb18030; + // if we don't have a startTime we have no way of knowing if we've waited + // long enough, so go ahead and retry this item now + if (startTime === undefined) { + debug('RETRY', fn.name, args) + fn.apply(null, args) + } else if (Date.now() - startTime >= 60000) { + // it's been more than 60 seconds total, bail now + debug('TIMEOUT', fn.name, args) + var cb = args.pop() + if (typeof cb === 'function') + cb.call(null, err) + } else { + // the amount of time between the last attempt and right now + var sinceAttempt = Date.now() - lastTime + // the amount of time between when we first tried, and when we last tried + // rounded up to at least 1 + var sinceStart = Math.max(lastTime - startTime, 1) + // backoff. wait longer than the total time we've been retrying, but only + // up to a maximum of 100ms + var desiredDelay = Math.min(sinceStart * 1.2, 100) + // it's been long enough since the last retry, do it again + if (sinceAttempt >= desiredDelay) { + debug('RETRY', fn.name, args) + fn.apply(null, args.concat([startTime])) + } else { + // if we can't do this job yet, push it to the end of the queue + // and let the next iteration check again + fs[gracefulQueue].push(elem) + } + } + + // schedule our next run if one isn't already scheduled + if (retryTimer === undefined) { + retryTimer = setTimeout(retry, 0) + } } -DBCSEncoder.prototype.write = function(str) { - var newBuf = Buffer.alloc(str.length * (this.gb18030 ? 4 : 3)), - leadSurrogate = this.leadSurrogate, - seqObj = this.seqObj, nextChar = -1, - i = 0, j = 0; - while (true) { - // 0. Get next character. - if (nextChar === -1) { - if (i == str.length) break; - var uCode = str.charCodeAt(i++); - } - else { - var uCode = nextChar; - nextChar = -1; - } +/***/ }), - // 1. Handle surrogates. - if (0xD800 <= uCode && uCode < 0xE000) { // Char is one of surrogates. - if (uCode < 0xDC00) { // We've got lead surrogate. - if (leadSurrogate === -1) { - leadSurrogate = uCode; - continue; - } else { - leadSurrogate = uCode; - // Double lead surrogate found. - uCode = UNASSIGNED; - } - } else { // We've got trail surrogate. - if (leadSurrogate !== -1) { - uCode = 0x10000 + (leadSurrogate - 0xD800) * 0x400 + (uCode - 0xDC00); - leadSurrogate = -1; - } else { - // Incomplete surrogate pair - only trail surrogate found. - uCode = UNASSIGNED; - } - - } - } - else if (leadSurrogate !== -1) { - // Incomplete surrogate pair - only lead surrogate found. - nextChar = uCode; uCode = UNASSIGNED; // Write an error, then current char. - leadSurrogate = -1; - } +/***/ 73086: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // 2. Convert uCode character. - var dbcsCode = UNASSIGNED; - if (seqObj !== undefined && uCode != UNASSIGNED) { // We are in the middle of the sequence - var resCode = seqObj[uCode]; - if (typeof resCode === 'object') { // Sequence continues. - seqObj = resCode; - continue; +var Stream = (__nccwpck_require__(12781).Stream) - } else if (typeof resCode == 'number') { // Sequence finished. Write it. - dbcsCode = resCode; +module.exports = legacy - } else if (resCode == undefined) { // Current character is not part of the sequence. +function legacy (fs) { + return { + ReadStream: ReadStream, + WriteStream: WriteStream + } - // Try default character for this sequence - resCode = seqObj[DEF_CHAR]; - if (resCode !== undefined) { - dbcsCode = resCode; // Found. Write it. - nextChar = uCode; // Current character will be written too in the next iteration. + function ReadStream (path, options) { + if (!(this instanceof ReadStream)) return new ReadStream(path, options); - } else { - // TODO: What if we have no default? (resCode == undefined) - // Then, we should write first char of the sequence as-is and try the rest recursively. - // Didn't do it for now because no encoding has this situation yet. - // Currently, just skip the sequence and write current char. - } - } - seqObj = undefined; - } - else if (uCode >= 0) { // Regular character - var subtable = this.encodeTable[uCode >> 8]; - if (subtable !== undefined) - dbcsCode = subtable[uCode & 0xFF]; - - if (dbcsCode <= SEQ_START) { // Sequence start - seqObj = this.encodeTableSeq[SEQ_START-dbcsCode]; - continue; - } + Stream.call(this); - if (dbcsCode == UNASSIGNED && this.gb18030) { - // Use GB18030 algorithm to find character(s) to write. - var idx = findIdx(this.gb18030.uChars, uCode); - if (idx != -1) { - var dbcsCode = this.gb18030.gbChars[idx] + (uCode - this.gb18030.uChars[idx]); - newBuf[j++] = 0x81 + Math.floor(dbcsCode / 12600); dbcsCode = dbcsCode % 12600; - newBuf[j++] = 0x30 + Math.floor(dbcsCode / 1260); dbcsCode = dbcsCode % 1260; - newBuf[j++] = 0x81 + Math.floor(dbcsCode / 10); dbcsCode = dbcsCode % 10; - newBuf[j++] = 0x30 + dbcsCode; - continue; - } - } - } + var self = this; - // 3. Write dbcsCode character. - if (dbcsCode === UNASSIGNED) - dbcsCode = this.defaultCharSingleByte; - - if (dbcsCode < 0x100) { - newBuf[j++] = dbcsCode; - } - else if (dbcsCode < 0x10000) { - newBuf[j++] = dbcsCode >> 8; // high byte - newBuf[j++] = dbcsCode & 0xFF; // low byte - } - else { - newBuf[j++] = dbcsCode >> 16; - newBuf[j++] = (dbcsCode >> 8) & 0xFF; - newBuf[j++] = dbcsCode & 0xFF; - } + this.path = path; + this.fd = null; + this.readable = true; + this.paused = false; + + this.flags = 'r'; + this.mode = 438; /*=0666*/ + this.bufferSize = 64 * 1024; + + options = options || {}; + + // Mixin options into this + var keys = Object.keys(options); + for (var index = 0, length = keys.length; index < length; index++) { + var key = keys[index]; + this[key] = options[key]; } - this.seqObj = seqObj; - this.leadSurrogate = leadSurrogate; - return newBuf.slice(0, j); -} + if (this.encoding) this.setEncoding(this.encoding); -DBCSEncoder.prototype.end = function() { - if (this.leadSurrogate === -1 && this.seqObj === undefined) - return; // All clean. Most often case. + if (this.start !== undefined) { + if ('number' !== typeof this.start) { + throw TypeError('start must be a Number'); + } + if (this.end === undefined) { + this.end = Infinity; + } else if ('number' !== typeof this.end) { + throw TypeError('end must be a Number'); + } - var newBuf = Buffer.alloc(10), j = 0; + if (this.start > this.end) { + throw new Error('start must be <= end'); + } - if (this.seqObj) { // We're in the sequence. - var dbcsCode = this.seqObj[DEF_CHAR]; - if (dbcsCode !== undefined) { // Write beginning of the sequence. - if (dbcsCode < 0x100) { - newBuf[j++] = dbcsCode; - } - else { - newBuf[j++] = dbcsCode >> 8; // high byte - newBuf[j++] = dbcsCode & 0xFF; // low byte - } - } else { - // See todo above. - } - this.seqObj = undefined; + this.pos = this.start; } - if (this.leadSurrogate !== -1) { - // Incomplete surrogate pair - only lead surrogate found. - newBuf[j++] = this.defaultCharSingleByte; - this.leadSurrogate = -1; + if (this.fd !== null) { + process.nextTick(function() { + self._read(); + }); + return; } - - return newBuf.slice(0, j); -} - -// Export for testing -DBCSEncoder.prototype.findIdx = findIdx; + fs.open(this.path, this.flags, this.mode, function (err, fd) { + if (err) { + self.emit('error', err); + self.readable = false; + return; + } -// == Decoder ================================================================== + self.fd = fd; + self.emit('open', fd); + self._read(); + }) + } -function DBCSDecoder(options, codec) { - // Decoder state - this.nodeIdx = 0; - this.prevBuf = Buffer.alloc(0); + function WriteStream (path, options) { + if (!(this instanceof WriteStream)) return new WriteStream(path, options); - // Static data - this.decodeTables = codec.decodeTables; - this.decodeTableSeq = codec.decodeTableSeq; - this.defaultCharUnicode = codec.defaultCharUnicode; - this.gb18030 = codec.gb18030; -} + Stream.call(this); -DBCSDecoder.prototype.write = function(buf) { - var newBuf = Buffer.alloc(buf.length*2), - nodeIdx = this.nodeIdx, - prevBuf = this.prevBuf, prevBufOffset = this.prevBuf.length, - seqStart = -this.prevBuf.length, // idx of the start of current parsed sequence. - uCode; + this.path = path; + this.fd = null; + this.writable = true; - if (prevBufOffset > 0) // Make prev buf overlap a little to make it easier to slice later. - prevBuf = Buffer.concat([prevBuf, buf.slice(0, 10)]); - - for (var i = 0, j = 0; i < buf.length; i++) { - var curByte = (i >= 0) ? buf[i] : prevBuf[i + prevBufOffset]; + this.flags = 'w'; + this.encoding = 'binary'; + this.mode = 438; /*=0666*/ + this.bytesWritten = 0; - // Lookup in current trie node. - var uCode = this.decodeTables[nodeIdx][curByte]; + options = options || {}; - if (uCode >= 0) { - // Normal character, just use it. - } - else if (uCode === UNASSIGNED) { // Unknown char. - // TODO: Callback with seq. - //var curSeq = (seqStart >= 0) ? buf.slice(seqStart, i+1) : prevBuf.slice(seqStart + prevBufOffset, i+1 + prevBufOffset); - i = seqStart; // Try to parse again, after skipping first byte of the sequence ('i' will be incremented by 'for' cycle). - uCode = this.defaultCharUnicode.charCodeAt(0); - } - else if (uCode === GB18030_CODE) { - var curSeq = (seqStart >= 0) ? buf.slice(seqStart, i+1) : prevBuf.slice(seqStart + prevBufOffset, i+1 + prevBufOffset); - var ptr = (curSeq[0]-0x81)*12600 + (curSeq[1]-0x30)*1260 + (curSeq[2]-0x81)*10 + (curSeq[3]-0x30); - var idx = findIdx(this.gb18030.gbChars, ptr); - uCode = this.gb18030.uChars[idx] + ptr - this.gb18030.gbChars[idx]; - } - else if (uCode <= NODE_START) { // Go to next trie node. - nodeIdx = NODE_START - uCode; - continue; - } - else if (uCode <= SEQ_START) { // Output a sequence of chars. - var seq = this.decodeTableSeq[SEQ_START - uCode]; - for (var k = 0; k < seq.length - 1; k++) { - uCode = seq[k]; - newBuf[j++] = uCode & 0xFF; - newBuf[j++] = uCode >> 8; - } - uCode = seq[seq.length-1]; - } - else - throw new Error("iconv-lite internal error: invalid decoding table value " + uCode + " at " + nodeIdx + "/" + curByte); - - // Write the character to buffer, handling higher planes using surrogate pair. - if (uCode > 0xFFFF) { - uCode -= 0x10000; - var uCodeLead = 0xD800 + Math.floor(uCode / 0x400); - newBuf[j++] = uCodeLead & 0xFF; - newBuf[j++] = uCodeLead >> 8; - - uCode = 0xDC00 + uCode % 0x400; - } - newBuf[j++] = uCode & 0xFF; - newBuf[j++] = uCode >> 8; - - // Reset trie node. - nodeIdx = 0; seqStart = i+1; + // Mixin options into this + var keys = Object.keys(options); + for (var index = 0, length = keys.length; index < length; index++) { + var key = keys[index]; + this[key] = options[key]; } - this.nodeIdx = nodeIdx; - this.prevBuf = (seqStart >= 0) ? buf.slice(seqStart) : prevBuf.slice(seqStart + prevBufOffset); - return newBuf.slice(0, j).toString('ucs2'); -} - -DBCSDecoder.prototype.end = function() { - var ret = ''; - - // Try to parse all remaining chars. - while (this.prevBuf.length > 0) { - // Skip 1 character in the buffer. - ret += this.defaultCharUnicode; - var buf = this.prevBuf.slice(1); + if (this.start !== undefined) { + if ('number' !== typeof this.start) { + throw TypeError('start must be a Number'); + } + if (this.start < 0) { + throw new Error('start must be >= zero'); + } - // Parse remaining as usual. - this.prevBuf = Buffer.alloc(0); - this.nodeIdx = 0; - if (buf.length > 0) - ret += this.write(buf); + this.pos = this.start; } - this.nodeIdx = 0; - return ret; -} - -// Binary search for GB18030. Returns largest i such that table[i] <= val. -function findIdx(table, val) { - if (table[0] > val) - return -1; + this.busy = false; + this._queue = []; - var l = 0, r = table.length; - while (l < r-1) { // always table[l] <= val < table[r] - var mid = l + Math.floor((r-l+1)/2); - if (table[mid] <= val) - l = mid; - else - r = mid; + if (this.fd === null) { + this._open = fs.open; + this._queue.push([this._open, this.path, this.flags, this.mode, undefined]); + this.flush(); } - return l; + } } - /***/ }), -/***/ 91386: +/***/ 20263: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +var constants = __nccwpck_require__(22057) +var origCwd = process.cwd +var cwd = null -// Description of supported double byte encodings and aliases. -// Tables are not require()-d until they are needed to speed up library load. -// require()-s are direct to support Browserify. +var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform -module.exports = { - - // == Japanese/ShiftJIS ==================================================== - // All japanese encodings are based on JIS X set of standards: - // JIS X 0201 - Single-byte encoding of ASCII + ¥ + Kana chars at 0xA1-0xDF. - // JIS X 0208 - Main set of 6879 characters, placed in 94x94 plane, to be encoded by 2 bytes. - // Has several variations in 1978, 1983, 1990 and 1997. - // JIS X 0212 - Supplementary plane of 6067 chars in 94x94 plane. 1990. Effectively dead. - // JIS X 0213 - Extension and modern replacement of 0208 and 0212. Total chars: 11233. - // 2 planes, first is superset of 0208, second - revised 0212. - // Introduced in 2000, revised 2004. Some characters are in Unicode Plane 2 (0x2xxxx) +process.cwd = function() { + if (!cwd) + cwd = origCwd.call(process) + return cwd +} +try { + process.cwd() +} catch (er) {} - // Byte encodings are: - // * Shift_JIS: Compatible with 0201, uses not defined chars in top half as lead bytes for double-byte - // encoding of 0208. Lead byte ranges: 0x81-0x9F, 0xE0-0xEF; Trail byte ranges: 0x40-0x7E, 0x80-0x9E, 0x9F-0xFC. - // Windows CP932 is a superset of Shift_JIS. Some companies added more chars, notably KDDI. - // * EUC-JP: Up to 3 bytes per character. Used mostly on *nixes. - // 0x00-0x7F - lower part of 0201 - // 0x8E, 0xA1-0xDF - upper part of 0201 - // (0xA1-0xFE)x2 - 0208 plane (94x94). - // 0x8F, (0xA1-0xFE)x2 - 0212 plane (94x94). - // * JIS X 208: 7-bit, direct encoding of 0208. Byte ranges: 0x21-0x7E (94 values). Uncommon. - // Used as-is in ISO2022 family. - // * ISO2022-JP: Stateful encoding, with escape sequences to switch between ASCII, - // 0201-1976 Roman, 0208-1978, 0208-1983. - // * ISO2022-JP-1: Adds esc seq for 0212-1990. - // * ISO2022-JP-2: Adds esc seq for GB2313-1980, KSX1001-1992, ISO8859-1, ISO8859-7. - // * ISO2022-JP-3: Adds esc seq for 0201-1976 Kana set, 0213-2000 Planes 1, 2. - // * ISO2022-JP-2004: Adds 0213-2004 Plane 1. - // - // After JIS X 0213 appeared, Shift_JIS-2004, EUC-JISX0213 and ISO2022-JP-2004 followed, with just changing the planes. - // - // Overall, it seems that it's a mess :( http://www8.plala.or.jp/tkubota1/unicode-symbols-map2.html +// This check is needed until node.js 12 is required +if (typeof process.chdir === 'function') { + var chdir = process.chdir + process.chdir = function (d) { + cwd = null + chdir.call(process, d) + } + if (Object.setPrototypeOf) Object.setPrototypeOf(process.chdir, chdir) +} - 'shiftjis': { - type: '_dbcs', - table: function() { return __nccwpck_require__(27014) }, - encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E}, - encodeSkipVals: [{from: 0xED40, to: 0xF940}], - }, - 'csshiftjis': 'shiftjis', - 'mskanji': 'shiftjis', - 'sjis': 'shiftjis', - 'windows31j': 'shiftjis', - 'ms31j': 'shiftjis', - 'xsjis': 'shiftjis', - 'windows932': 'shiftjis', - 'ms932': 'shiftjis', - '932': 'shiftjis', - 'cp932': 'shiftjis', +module.exports = patch - 'eucjp': { - type: '_dbcs', - table: function() { return __nccwpck_require__(31532) }, - encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E}, - }, +function patch (fs) { + // (re-)implement some things that are known busted or missing. - // TODO: KDDI extension to Shift_JIS - // TODO: IBM CCSID 942 = CP932, but F0-F9 custom chars and other char changes. - // TODO: IBM CCSID 943 = Shift_JIS = CP932 with original Shift_JIS lower 128 chars. + // lchmod, broken prior to 0.6.2 + // back-port the fix here. + if (constants.hasOwnProperty('O_SYMLINK') && + process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) { + patchLchmod(fs) + } + // lutimes implementation, or no-op + if (!fs.lutimes) { + patchLutimes(fs) + } - // == Chinese/GBK ========================================================== - // http://en.wikipedia.org/wiki/GBK - // We mostly implement W3C recommendation: https://www.w3.org/TR/encoding/#gbk-encoder + // https://github.com/isaacs/node-graceful-fs/issues/4 + // Chown should not fail on einval or eperm if non-root. + // It should not fail on enosys ever, as this just indicates + // that a fs doesn't support the intended operation. - // Oldest GB2312 (1981, ~7600 chars) is a subset of CP936 - 'gb2312': 'cp936', - 'gb231280': 'cp936', - 'gb23121980': 'cp936', - 'csgb2312': 'cp936', - 'csiso58gb231280': 'cp936', - 'euccn': 'cp936', + fs.chown = chownFix(fs.chown) + fs.fchown = chownFix(fs.fchown) + fs.lchown = chownFix(fs.lchown) - // Microsoft's CP936 is a subset and approximation of GBK. - 'windows936': 'cp936', - 'ms936': 'cp936', - '936': 'cp936', - 'cp936': { - type: '_dbcs', - table: function() { return __nccwpck_require__(13336) }, - }, + fs.chmod = chmodFix(fs.chmod) + fs.fchmod = chmodFix(fs.fchmod) + fs.lchmod = chmodFix(fs.lchmod) - // GBK (~22000 chars) is an extension of CP936 that added user-mapped chars and some other. - 'gbk': { - type: '_dbcs', - table: function() { return (__nccwpck_require__(13336).concat)(__nccwpck_require__(44346)) }, - }, - 'xgbk': 'gbk', - 'isoir58': 'gbk', + fs.chownSync = chownFixSync(fs.chownSync) + fs.fchownSync = chownFixSync(fs.fchownSync) + fs.lchownSync = chownFixSync(fs.lchownSync) - // GB18030 is an algorithmic extension of GBK. - // Main source: https://www.w3.org/TR/encoding/#gbk-encoder - // http://icu-project.org/docs/papers/gb18030.html - // http://source.icu-project.org/repos/icu/data/trunk/charset/data/xml/gb-18030-2000.xml - // http://www.khngai.com/chinese/charmap/tblgbk.php?page=0 - 'gb18030': { - type: '_dbcs', - table: function() { return (__nccwpck_require__(13336).concat)(__nccwpck_require__(44346)) }, - gb18030: function() { return __nccwpck_require__(36258) }, - encodeSkipVals: [0x80], - encodeAdd: {'€': 0xA2E3}, - }, + fs.chmodSync = chmodFixSync(fs.chmodSync) + fs.fchmodSync = chmodFixSync(fs.fchmodSync) + fs.lchmodSync = chmodFixSync(fs.lchmodSync) - 'chinese': 'gb18030', + fs.stat = statFix(fs.stat) + fs.fstat = statFix(fs.fstat) + fs.lstat = statFix(fs.lstat) + fs.statSync = statFixSync(fs.statSync) + fs.fstatSync = statFixSync(fs.fstatSync) + fs.lstatSync = statFixSync(fs.lstatSync) - // == Korean =============================================================== - // EUC-KR, KS_C_5601 and KS X 1001 are exactly the same. - 'windows949': 'cp949', - 'ms949': 'cp949', - '949': 'cp949', - 'cp949': { - type: '_dbcs', - table: function() { return __nccwpck_require__(77348) }, - }, + // if lchmod/lchown do not exist, then make them no-ops + if (!fs.lchmod) { + fs.lchmod = function (path, mode, cb) { + if (cb) process.nextTick(cb) + } + fs.lchmodSync = function () {} + } + if (!fs.lchown) { + fs.lchown = function (path, uid, gid, cb) { + if (cb) process.nextTick(cb) + } + fs.lchownSync = function () {} + } - 'cseuckr': 'cp949', - 'csksc56011987': 'cp949', - 'euckr': 'cp949', - 'isoir149': 'cp949', - 'korean': 'cp949', - 'ksc56011987': 'cp949', - 'ksc56011989': 'cp949', - 'ksc5601': 'cp949', + // on Windows, A/V software can lock the directory, causing this + // to fail with an EACCES or EPERM if the directory contains newly + // created files. Try again on failure, for up to 60 seconds. + // Set the timeout this long because some Windows Anti-Virus, such as Parity + // bit9, may lock files for up to a minute, causing npm package install + // failures. Also, take care to yield the scheduler. Windows scheduling gives + // CPU to a busy looping process, which can cause the program causing the lock + // contention to be starved of CPU by node, so the contention doesn't resolve. + if (platform === "win32") { + fs.rename = (function (fs$rename) { return function (from, to, cb) { + var start = Date.now() + var backoff = 0; + fs$rename(from, to, function CB (er) { + if (er + && (er.code === "EACCES" || er.code === "EPERM") + && Date.now() - start < 60000) { + setTimeout(function() { + fs.stat(to, function (stater, st) { + if (stater && stater.code === "ENOENT") + fs$rename(from, to, CB); + else + cb(er) + }) + }, backoff) + if (backoff < 100) + backoff += 10; + return; + } + if (cb) cb(er) + }) + }})(fs.rename) + } - // == Big5/Taiwan/Hong Kong ================================================ - // There are lots of tables for Big5 and cp950. Please see the following links for history: - // http://moztw.org/docs/big5/ http://www.haible.de/bruno/charsets/conversion-tables/Big5.html - // Variations, in roughly number of defined chars: - // * Windows CP 950: Microsoft variant of Big5. Canonical: http://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP950.TXT - // * Windows CP 951: Microsoft variant of Big5-HKSCS-2001. Seems to be never public. http://me.abelcheung.org/articles/research/what-is-cp951/ - // * Big5-2003 (Taiwan standard) almost superset of cp950. - // * Unicode-at-on (UAO) / Mozilla 1.8. Falling out of use on the Web. Not supported by other browsers. - // * Big5-HKSCS (-2001, -2004, -2008). Hong Kong standard. - // many unicode code points moved from PUA to Supplementary plane (U+2XXXX) over the years. - // Plus, it has 4 combining sequences. - // Seems that Mozilla refused to support it for 10 yrs. https://bugzilla.mozilla.org/show_bug.cgi?id=162431 https://bugzilla.mozilla.org/show_bug.cgi?id=310299 - // because big5-hkscs is the only encoding to include astral characters in non-algorithmic way. - // Implementations are not consistent within browsers; sometimes labeled as just big5. - // MS Internet Explorer switches from big5 to big5-hkscs when a patch applied. - // Great discussion & recap of what's going on https://bugzilla.mozilla.org/show_bug.cgi?id=912470#c31 - // In the encoder, it might make sense to support encoding old PUA mappings to Big5 bytes seq-s. - // Official spec: http://www.ogcio.gov.hk/en/business/tech_promotion/ccli/terms/doc/2003cmp_2008.txt - // http://www.ogcio.gov.hk/tc/business/tech_promotion/ccli/terms/doc/hkscs-2008-big5-iso.txt - // - // Current understanding of how to deal with Big5(-HKSCS) is in the Encoding Standard, http://encoding.spec.whatwg.org/#big5-encoder - // Unicode mapping (http://www.unicode.org/Public/MAPPINGS/OBSOLETE/EASTASIA/OTHER/BIG5.TXT) is said to be wrong. + // if read() returns EAGAIN, then just try it again. + fs.read = (function (fs$read) { + function read (fd, buffer, offset, length, position, callback_) { + var callback + if (callback_ && typeof callback_ === 'function') { + var eagCounter = 0 + callback = function (er, _, __) { + if (er && er.code === 'EAGAIN' && eagCounter < 10) { + eagCounter ++ + return fs$read.call(fs, fd, buffer, offset, length, position, callback) + } + callback_.apply(this, arguments) + } + } + return fs$read.call(fs, fd, buffer, offset, length, position, callback) + } - 'windows950': 'cp950', - 'ms950': 'cp950', - '950': 'cp950', - 'cp950': { - type: '_dbcs', - table: function() { return __nccwpck_require__(74284) }, - }, + // This ensures `util.promisify` works as it does for native `fs.read`. + if (Object.setPrototypeOf) Object.setPrototypeOf(read, fs$read) + return read + })(fs.read) - // Big5 has many variations and is an extension of cp950. We use Encoding Standard's as a consensus. - 'big5': 'big5hkscs', - 'big5hkscs': { - type: '_dbcs', - table: function() { return (__nccwpck_require__(74284).concat)(__nccwpck_require__(63480)) }, - encodeSkipVals: [0xa2cc], - }, + fs.readSync = (function (fs$readSync) { return function (fd, buffer, offset, length, position) { + var eagCounter = 0 + while (true) { + try { + return fs$readSync.call(fs, fd, buffer, offset, length, position) + } catch (er) { + if (er.code === 'EAGAIN' && eagCounter < 10) { + eagCounter ++ + continue + } + throw er + } + } + }})(fs.readSync) - 'cnbig5': 'big5hkscs', - 'csbig5': 'big5hkscs', - 'xxbig5': 'big5hkscs', -}; + function patchLchmod (fs) { + fs.lchmod = function (path, mode, callback) { + fs.open( path + , constants.O_WRONLY | constants.O_SYMLINK + , mode + , function (err, fd) { + if (err) { + if (callback) callback(err) + return + } + // prefer to return the chmod error, if one occurs, + // but still try to close, and report closing errors if they occur. + fs.fchmod(fd, mode, function (err) { + fs.close(fd, function(err2) { + if (callback) callback(err || err2) + }) + }) + }) + } + fs.lchmodSync = function (path, mode) { + var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode) -/***/ }), + // prefer to return the chmod error, if one occurs, + // but still try to close, and report closing errors if they occur. + var threw = true + var ret + try { + ret = fs.fchmodSync(fd, mode) + threw = false + } finally { + if (threw) { + try { + fs.closeSync(fd) + } catch (er) {} + } else { + fs.closeSync(fd) + } + } + return ret + } + } -/***/ 82733: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + function patchLutimes (fs) { + if (constants.hasOwnProperty("O_SYMLINK")) { + fs.lutimes = function (path, at, mt, cb) { + fs.open(path, constants.O_SYMLINK, function (er, fd) { + if (er) { + if (cb) cb(er) + return + } + fs.futimes(fd, at, mt, function (er) { + fs.close(fd, function (er2) { + if (cb) cb(er || er2) + }) + }) + }) + } -"use strict"; + fs.lutimesSync = function (path, at, mt) { + var fd = fs.openSync(path, constants.O_SYMLINK) + var ret + var threw = true + try { + ret = fs.futimesSync(fd, at, mt) + threw = false + } finally { + if (threw) { + try { + fs.closeSync(fd) + } catch (er) {} + } else { + fs.closeSync(fd) + } + } + return ret + } + } else { + fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb) } + fs.lutimesSync = function () {} + } + } -// Update this array if you add/rename/remove files in this directory. -// We support Browserify by skipping automatic module discovery and requiring modules directly. -var modules = [ - __nccwpck_require__(12376), - __nccwpck_require__(11155), - __nccwpck_require__(51644), - __nccwpck_require__(26657), - __nccwpck_require__(41080), - __nccwpck_require__(21012), - __nccwpck_require__(39695), - __nccwpck_require__(91386), -]; + function chmodFix (orig) { + if (!orig) return orig + return function (target, mode, cb) { + return orig.call(fs, target, mode, function (er) { + if (chownErOk(er)) er = null + if (cb) cb.apply(this, arguments) + }) + } + } -// Put all encoding/alias/codec definitions to single object and export it. -for (var i = 0; i < modules.length; i++) { - var module = modules[i]; - for (var enc in module) - if (Object.prototype.hasOwnProperty.call(module, enc)) - exports[enc] = module[enc]; -} + function chmodFixSync (orig) { + if (!orig) return orig + return function (target, mode) { + try { + return orig.call(fs, target, mode) + } catch (er) { + if (!chownErOk(er)) throw er + } + } + } -/***/ }), + function chownFix (orig) { + if (!orig) return orig + return function (target, uid, gid, cb) { + return orig.call(fs, target, uid, gid, function (er) { + if (chownErOk(er)) er = null + if (cb) cb.apply(this, arguments) + }) + } + } -/***/ 12376: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + function chownFixSync (orig) { + if (!orig) return orig + return function (target, uid, gid) { + try { + return orig.call(fs, target, uid, gid) + } catch (er) { + if (!chownErOk(er)) throw er + } + } + } -"use strict"; + function statFix (orig) { + if (!orig) return orig + // Older versions of Node erroneously returned signed integers for + // uid + gid. + return function (target, options, cb) { + if (typeof options === 'function') { + cb = options + options = null + } + function callback (er, stats) { + if (stats) { + if (stats.uid < 0) stats.uid += 0x100000000 + if (stats.gid < 0) stats.gid += 0x100000000 + } + if (cb) cb.apply(this, arguments) + } + return options ? orig.call(fs, target, options, callback) + : orig.call(fs, target, callback) + } + } -var Buffer = (__nccwpck_require__(15118).Buffer); + function statFixSync (orig) { + if (!orig) return orig + // Older versions of Node erroneously returned signed integers for + // uid + gid. + return function (target, options) { + var stats = options ? orig.call(fs, target, options) + : orig.call(fs, target) + if (stats) { + if (stats.uid < 0) stats.uid += 0x100000000 + if (stats.gid < 0) stats.gid += 0x100000000 + } + return stats; + } + } -// Export Node.js internal encodings. + // ENOSYS means that the fs doesn't support the op. Just ignore + // that, because it doesn't matter. + // + // if there's no getuid, or if getuid() is something other + // than 0, and the error is EINVAL or EPERM, then just ignore + // it. + // + // This specific case is a silent failure in cp, install, tar, + // and most other unix tools that manage permissions. + // + // When running as root, or if other types of errors are + // encountered, then it's strict. + function chownErOk (er) { + if (!er) + return true -module.exports = { - // Encodings - utf8: { type: "_internal", bomAware: true}, - cesu8: { type: "_internal", bomAware: true}, - unicode11utf8: "utf8", + if (er.code === "ENOSYS") + return true - ucs2: { type: "_internal", bomAware: true}, - utf16le: "ucs2", + var nonroot = !process.getuid || process.getuid() !== 0 + if (nonroot) { + if (er.code === "EINVAL" || er.code === "EPERM") + return true + } - binary: { type: "_internal" }, - base64: { type: "_internal" }, - hex: { type: "_internal" }, + return false + } +} - // Codec. - _internal: InternalCodec, -}; -//------------------------------------------------------------------------------ +/***/ }), -function InternalCodec(codecOptions, iconv) { - this.enc = codecOptions.encodingName; - this.bomAware = codecOptions.bomAware; +/***/ 31621: +/***/ ((module) => { - if (this.enc === "base64") - this.encoder = InternalEncoderBase64; - else if (this.enc === "cesu8") { - this.enc = "utf8"; // Use utf8 for decoding. - this.encoder = InternalEncoderCesu8; +"use strict"; - // Add decoder for versions of Node not supporting CESU-8 - if (Buffer.from('eda0bdedb2a9', 'hex').toString() !== '💩') { - this.decoder = InternalDecoderCesu8; - this.defaultCharUnicode = iconv.defaultCharUnicode; - } - } -} -InternalCodec.prototype.encoder = InternalEncoder; -InternalCodec.prototype.decoder = InternalDecoder; +module.exports = (flag, argv = process.argv) => { + const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); + const position = argv.indexOf(prefix + flag); + const terminatorPosition = argv.indexOf('--'); + return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); +}; -//------------------------------------------------------------------------------ -// We use node.js internal decoder. Its signature is the same as ours. -var StringDecoder = (__nccwpck_require__(71576).StringDecoder); +/***/ }), -if (!StringDecoder.prototype.end) // Node v0.8 doesn't have this method. - StringDecoder.prototype.end = function() {}; +/***/ 76339: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +"use strict"; -function InternalDecoder(options, codec) { - StringDecoder.call(this, codec.enc); -} -InternalDecoder.prototype = StringDecoder.prototype; +var bind = __nccwpck_require__(88334); +module.exports = bind.call(Function.call, Object.prototype.hasOwnProperty); -//------------------------------------------------------------------------------ -// Encoder is mostly trivial -function InternalEncoder(options, codec) { - this.enc = codec.enc; -} +/***/ }), -InternalEncoder.prototype.write = function(str) { - return Buffer.from(str, this.enc); -} +/***/ 95193: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -InternalEncoder.prototype.end = function() { -} +"use strict"; +/*! + * http-errors + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2016 Douglas Christopher Wilson + * MIT Licensed + */ -//------------------------------------------------------------------------------ -// Except base64 encoder, which must keep its state. -function InternalEncoderBase64(options, codec) { - this.prevStr = ''; -} +/** + * Module dependencies. + * @private + */ -InternalEncoderBase64.prototype.write = function(str) { - str = this.prevStr + str; - var completeQuads = str.length - (str.length % 4); - this.prevStr = str.slice(completeQuads); - str = str.slice(0, completeQuads); +var deprecate = __nccwpck_require__(18883)('http-errors') +var setPrototypeOf = __nccwpck_require__(40414) +var statuses = __nccwpck_require__(57415) +var inherits = __nccwpck_require__(44124) +var toIdentifier = __nccwpck_require__(46399) - return Buffer.from(str, "base64"); -} +/** + * Module exports. + * @public + */ -InternalEncoderBase64.prototype.end = function() { - return Buffer.from(this.prevStr, "base64"); -} +module.exports = createError +module.exports.HttpError = createHttpErrorConstructor() +module.exports.isHttpError = createIsHttpErrorFunction(module.exports.HttpError) +// Populate exports for all constructors +populateConstructorExports(module.exports, statuses.codes, module.exports.HttpError) -//------------------------------------------------------------------------------ -// CESU-8 encoder is also special. +/** + * Get the code class of a status code. + * @private + */ -function InternalEncoderCesu8(options, codec) { +function codeClass (status) { + return Number(String(status).charAt(0) + '00') } -InternalEncoderCesu8.prototype.write = function(str) { - var buf = Buffer.alloc(str.length * 3), bufIdx = 0; - for (var i = 0; i < str.length; i++) { - var charCode = str.charCodeAt(i); - // Naive implementation, but it works because CESU-8 is especially easy - // to convert from UTF-16 (which all JS strings are encoded in). - if (charCode < 0x80) - buf[bufIdx++] = charCode; - else if (charCode < 0x800) { - buf[bufIdx++] = 0xC0 + (charCode >>> 6); - buf[bufIdx++] = 0x80 + (charCode & 0x3f); - } - else { // charCode will always be < 0x10000 in javascript. - buf[bufIdx++] = 0xE0 + (charCode >>> 12); - buf[bufIdx++] = 0x80 + ((charCode >>> 6) & 0x3f); - buf[bufIdx++] = 0x80 + (charCode & 0x3f); +/** + * Create a new HTTP Error. + * + * @returns {Error} + * @public + */ + +function createError () { + // so much arity going on ~_~ + var err + var msg + var status = 500 + var props = {} + for (var i = 0; i < arguments.length; i++) { + var arg = arguments[i] + if (arg instanceof Error) { + err = arg + status = err.status || err.statusCode || status + continue + } + switch (typeof arg) { + case 'string': + msg = arg + break + case 'number': + status = arg + if (i !== 0) { + deprecate('non-first-argument status code; replace with createError(' + arg + ', ...)') } + break + case 'object': + props = arg + break } - return buf.slice(0, bufIdx); -} + } -InternalEncoderCesu8.prototype.end = function() { -} + if (typeof status === 'number' && (status < 400 || status >= 600)) { + deprecate('non-error status code; use only 4xx or 5xx status codes') + } -//------------------------------------------------------------------------------ -// CESU-8 decoder is not implemented in Node v4.0+ + if (typeof status !== 'number' || + (!statuses[status] && (status < 400 || status >= 600))) { + status = 500 + } -function InternalDecoderCesu8(options, codec) { - this.acc = 0; - this.contBytes = 0; - this.accBytes = 0; - this.defaultCharUnicode = codec.defaultCharUnicode; -} + // constructor + var HttpError = createError[status] || createError[codeClass(status)] -InternalDecoderCesu8.prototype.write = function(buf) { - var acc = this.acc, contBytes = this.contBytes, accBytes = this.accBytes, - res = ''; - for (var i = 0; i < buf.length; i++) { - var curByte = buf[i]; - if ((curByte & 0xC0) !== 0x80) { // Leading byte - if (contBytes > 0) { // Previous code is invalid - res += this.defaultCharUnicode; - contBytes = 0; - } + if (!err) { + // create error + err = HttpError + ? new HttpError(msg) + : new Error(msg || statuses[status]) + Error.captureStackTrace(err, createError) + } - if (curByte < 0x80) { // Single-byte code - res += String.fromCharCode(curByte); - } else if (curByte < 0xE0) { // Two-byte code - acc = curByte & 0x1F; - contBytes = 1; accBytes = 1; - } else if (curByte < 0xF0) { // Three-byte code - acc = curByte & 0x0F; - contBytes = 2; accBytes = 1; - } else { // Four or more are not supported for CESU-8. - res += this.defaultCharUnicode; - } - } else { // Continuation byte - if (contBytes > 0) { // We're waiting for it. - acc = (acc << 6) | (curByte & 0x3f); - contBytes--; accBytes++; - if (contBytes === 0) { - // Check for overlong encoding, but support Modified UTF-8 (encoding NULL as C0 80) - if (accBytes === 2 && acc < 0x80 && acc > 0) - res += this.defaultCharUnicode; - else if (accBytes === 3 && acc < 0x800) - res += this.defaultCharUnicode; - else - // Actually add character. - res += String.fromCharCode(acc); - } - } else { // Unexpected continuation byte - res += this.defaultCharUnicode; - } - } + if (!HttpError || !(err instanceof HttpError) || err.status !== status) { + // add properties to generic error + err.expose = status < 500 + err.status = err.statusCode = status + } + + for (var key in props) { + if (key !== 'status' && key !== 'statusCode') { + err[key] = props[key] } - this.acc = acc; this.contBytes = contBytes; this.accBytes = accBytes; - return res; -} + } -InternalDecoderCesu8.prototype.end = function() { - var res = 0; - if (this.contBytes > 0) - res += this.defaultCharUnicode; - return res; + return err } +/** + * Create HTTP error abstract base class. + * @private + */ -/***/ }), +function createHttpErrorConstructor () { + function HttpError () { + throw new TypeError('cannot construct abstract class') + } -/***/ 26657: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + inherits(HttpError, Error) -"use strict"; + return HttpError +} -var Buffer = (__nccwpck_require__(15118).Buffer); +/** + * Create a constructor for a client error. + * @private + */ -// Single-byte codec. Needs a 'chars' string parameter that contains 256 or 128 chars that -// correspond to encoded bytes (if 128 - then lower half is ASCII). +function createClientErrorConstructor (HttpError, name, code) { + var className = toClassName(name) -exports._sbcs = SBCSCodec; -function SBCSCodec(codecOptions, iconv) { - if (!codecOptions) - throw new Error("SBCS codec is called without the data.") - - // Prepare char buffer for decoding. - if (!codecOptions.chars || (codecOptions.chars.length !== 128 && codecOptions.chars.length !== 256)) - throw new Error("Encoding '"+codecOptions.type+"' has incorrect 'chars' (must be of len 128 or 256)"); - - if (codecOptions.chars.length === 128) { - var asciiString = ""; - for (var i = 0; i < 128; i++) - asciiString += String.fromCharCode(i); - codecOptions.chars = asciiString + codecOptions.chars; - } + function ClientError (message) { + // create the error object + var msg = message != null ? message : statuses[code] + var err = new Error(msg) - this.decodeBuf = Buffer.from(codecOptions.chars, 'ucs2'); - - // Encoding buffer. - var encodeBuf = Buffer.alloc(65536, iconv.defaultCharSingleByte.charCodeAt(0)); + // capture a stack trace to the construction point + Error.captureStackTrace(err, ClientError) - for (var i = 0; i < codecOptions.chars.length; i++) - encodeBuf[codecOptions.chars.charCodeAt(i)] = i; + // adjust the [[Prototype]] + setPrototypeOf(err, ClientError.prototype) - this.encodeBuf = encodeBuf; -} + // redefine the error message + Object.defineProperty(err, 'message', { + enumerable: true, + configurable: true, + value: msg, + writable: true + }) -SBCSCodec.prototype.encoder = SBCSEncoder; -SBCSCodec.prototype.decoder = SBCSDecoder; + // redefine the error name + Object.defineProperty(err, 'name', { + enumerable: false, + configurable: true, + value: className, + writable: true + }) + return err + } -function SBCSEncoder(options, codec) { - this.encodeBuf = codec.encodeBuf; -} + inherits(ClientError, HttpError) + nameFunc(ClientError, className) -SBCSEncoder.prototype.write = function(str) { - var buf = Buffer.alloc(str.length); - for (var i = 0; i < str.length; i++) - buf[i] = this.encodeBuf[str.charCodeAt(i)]; - - return buf; -} + ClientError.prototype.status = code + ClientError.prototype.statusCode = code + ClientError.prototype.expose = true -SBCSEncoder.prototype.end = function() { + return ClientError } +/** + * Create function to test is a value is a HttpError. + * @private + */ -function SBCSDecoder(options, codec) { - this.decodeBuf = codec.decodeBuf; -} +function createIsHttpErrorFunction (HttpError) { + return function isHttpError (val) { + if (!val || typeof val !== 'object') { + return false + } -SBCSDecoder.prototype.write = function(buf) { - // Strings are immutable in JS -> we use ucs2 buffer to speed up computations. - var decodeBuf = this.decodeBuf; - var newBuf = Buffer.alloc(buf.length*2); - var idx1 = 0, idx2 = 0; - for (var i = 0; i < buf.length; i++) { - idx1 = buf[i]*2; idx2 = i*2; - newBuf[idx2] = decodeBuf[idx1]; - newBuf[idx2+1] = decodeBuf[idx1+1]; + if (val instanceof HttpError) { + return true } - return newBuf.toString('ucs2'); -} -SBCSDecoder.prototype.end = function() { + return val instanceof Error && + typeof val.expose === 'boolean' && + typeof val.statusCode === 'number' && val.status === val.statusCode + } } +/** + * Create a constructor for a server error. + * @private + */ -/***/ }), +function createServerErrorConstructor (HttpError, name, code) { + var className = toClassName(name) -/***/ 21012: -/***/ ((module) => { + function ServerError (message) { + // create the error object + var msg = message != null ? message : statuses[code] + var err = new Error(msg) -"use strict"; + // capture a stack trace to the construction point + Error.captureStackTrace(err, ServerError) + // adjust the [[Prototype]] + setPrototypeOf(err, ServerError.prototype) -// Generated data for sbcs codec. Don't edit manually. Regenerate using generation/gen-sbcs.js script. -module.exports = { - "437": "cp437", - "737": "cp737", - "775": "cp775", - "850": "cp850", - "852": "cp852", - "855": "cp855", - "856": "cp856", - "857": "cp857", - "858": "cp858", - "860": "cp860", - "861": "cp861", - "862": "cp862", - "863": "cp863", - "864": "cp864", - "865": "cp865", - "866": "cp866", - "869": "cp869", - "874": "windows874", - "922": "cp922", - "1046": "cp1046", - "1124": "cp1124", - "1125": "cp1125", - "1129": "cp1129", - "1133": "cp1133", - "1161": "cp1161", - "1162": "cp1162", - "1163": "cp1163", - "1250": "windows1250", - "1251": "windows1251", - "1252": "windows1252", - "1253": "windows1253", - "1254": "windows1254", - "1255": "windows1255", - "1256": "windows1256", - "1257": "windows1257", - "1258": "windows1258", - "28591": "iso88591", - "28592": "iso88592", - "28593": "iso88593", - "28594": "iso88594", - "28595": "iso88595", - "28596": "iso88596", - "28597": "iso88597", - "28598": "iso88598", - "28599": "iso88599", - "28600": "iso885910", - "28601": "iso885911", - "28603": "iso885913", - "28604": "iso885914", - "28605": "iso885915", - "28606": "iso885916", - "windows874": { - "type": "_sbcs", - "chars": "€����…�����������‘’“”•–—�������� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" - }, - "win874": "windows874", - "cp874": "windows874", - "windows1250": { - "type": "_sbcs", - "chars": "€�‚�„…†‡�‰Š‹ŚŤŽŹ�‘’“”•–—�™š›śťžź ˇ˘Ł¤Ą¦§¨©Ş«¬­®Ż°±˛ł´µ¶·¸ąş»Ľ˝ľżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙" - }, - "win1250": "windows1250", - "cp1250": "windows1250", - "windows1251": { - "type": "_sbcs", - "chars": "ЂЃ‚ѓ„…†‡€‰Љ‹ЊЌЋЏђ‘’“”•–—�™љ›њќћџ ЎўЈ¤Ґ¦§Ё©Є«¬­®Ї°±Ііґµ¶·ё№є»јЅѕїАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" - }, - "win1251": "windows1251", - "cp1251": "windows1251", - "windows1252": { - "type": "_sbcs", - "chars": "€�‚ƒ„…†‡ˆ‰Š‹Œ�Ž��‘’“”•–—˜™š›œ�žŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" - }, - "win1252": "windows1252", - "cp1252": "windows1252", - "windows1253": { - "type": "_sbcs", - "chars": "€�‚ƒ„…†‡�‰�‹�����‘’“”•–—�™�›���� ΅Ά£¤¥¦§¨©�«¬­®―°±²³΄µ¶·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�" - }, - "win1253": "windows1253", - "cp1253": "windows1253", - "windows1254": { - "type": "_sbcs", - "chars": "€�‚ƒ„…†‡ˆ‰Š‹Œ����‘’“”•–—˜™š›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖ×ØÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ" - }, - "win1254": "windows1254", - "cp1254": "windows1254", - "windows1255": { - "type": "_sbcs", - "chars": "€�‚ƒ„…†‡ˆ‰�‹�����‘’“”•–—˜™�›���� ¡¢£₪¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾¿ְֱֲֳִֵֶַָֹֺֻּֽ־ֿ׀ׁׂ׃װױײ׳״�������אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�" - }, - "win1255": "windows1255", - "cp1255": "windows1255", - "windows1256": { - "type": "_sbcs", - "chars": "€پ‚ƒ„…†‡ˆ‰ٹ‹Œچژڈگ‘’“”•–—ک™ڑ›œ‌‍ں ،¢£¤¥¦§¨©ھ«¬­®¯°±²³´µ¶·¸¹؛»¼½¾؟ہءآأؤإئابةتثجحخدذرزسشصض×طظعغـفقكàلâمنهوçèéêëىيîïًٌٍَôُِ÷ّùْûü‎‏ے" - }, - "win1256": "windows1256", - "cp1256": "windows1256", - "windows1257": { - "type": "_sbcs", - "chars": "€�‚�„…†‡�‰�‹�¨ˇ¸�‘’“”•–—�™�›�¯˛� �¢£¤�¦§Ø©Ŗ«¬­®Æ°±²³´µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž˙" - }, - "win1257": "windows1257", - "cp1257": "windows1257", - "windows1258": { - "type": "_sbcs", - "chars": "€�‚ƒ„…†‡ˆ‰�‹Œ����‘’“”•–—˜™�›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖ×ØÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" - }, - "win1258": "windows1258", - "cp1258": "windows1258", - "iso88591": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" - }, - "cp28591": "iso88591", - "iso88592": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ą˘Ł¤ĽŚ§¨ŠŞŤŹ­ŽŻ°ą˛ł´ľśˇ¸šşťź˝žżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙" - }, - "cp28592": "iso88592", - "iso88593": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ħ˘£¤�Ĥ§¨İŞĞĴ­�Ż°ħ²³´µĥ·¸ışğĵ½�żÀÁÂ�ÄĊĈÇÈÉÊËÌÍÎÏ�ÑÒÓÔĠÖ×ĜÙÚÛÜŬŜßàáâ�äċĉçèéêëìíîï�ñòóôġö÷ĝùúûüŭŝ˙" - }, - "cp28593": "iso88593", - "iso88594": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄĸŖ¤ĨĻ§¨ŠĒĢŦ­Ž¯°ą˛ŗ´ĩļˇ¸šēģŧŊžŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎĪĐŅŌĶÔÕÖ×ØŲÚÛÜŨŪßāáâãäåæįčéęëėíîīđņōķôõö÷øųúûüũū˙" - }, - "cp28594": "iso88594", - "iso88595": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ЁЂЃЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђѓєѕіїјљњћќ§ўџ" - }, - "cp28595": "iso88595", - "iso88596": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ���¤�������،­�������������؛���؟�ءآأؤإئابةتثجحخدذرزسشصضطظعغ�����ـفقكلمنهوىيًٌٍَُِّْ�������������" - }, - "cp28596": "iso88596", - "iso88597": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ‘’£€₯¦§¨©ͺ«¬­�―°±²³΄΅Ά·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�" - }, - "cp28597": "iso88597", - "iso88598": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ �¢£¤¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾��������������������������������‗אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�" - }, - "cp28598": "iso88598", - "iso88599": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖ×ØÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ" - }, - "cp28599": "iso88599", - "iso885910": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄĒĢĪĨĶ§ĻĐŠŦŽ­ŪŊ°ąēģīĩķ·ļđšŧž―ūŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎÏÐŅŌÓÔÕÖŨØŲÚÛÜÝÞßāáâãäåæįčéęëėíîïðņōóôõöũøųúûüýþĸ" - }, - "cp28600": "iso885910", - "iso885911": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" - }, - "cp28601": "iso885911", - "iso885913": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ”¢£¤„¦§Ø©Ŗ«¬­®Æ°±²³“µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž’" - }, - "cp28603": "iso885913", - "iso885914": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ḃḃ£ĊċḊ§Ẁ©ẂḋỲ­®ŸḞḟĠġṀṁ¶ṖẁṗẃṠỳẄẅṡÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŴÑÒÓÔÕÖṪØÙÚÛÜÝŶßàáâãäåæçèéêëìíîïŵñòóôõöṫøùúûüýŷÿ" - }, - "cp28604": "iso885914", - "iso885915": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£€¥Š§š©ª«¬­®¯°±²³Žµ¶·ž¹º»ŒœŸ¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" - }, - "cp28605": "iso885915", - "iso885916": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄąŁ€„Š§š©Ș«Ź­źŻ°±ČłŽ”¶·žčș»ŒœŸżÀÁÂĂÄĆÆÇÈÉÊËÌÍÎÏĐŃÒÓÔŐÖŚŰÙÚÛÜĘȚßàáâăäćæçèéêëìíîïđńòóôőöśűùúûüęțÿ" - }, - "cp28606": "iso885916", - "cp437": { - "type": "_sbcs", - "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " - }, - "ibm437": "cp437", - "csibm437": "cp437", - "cp737": { - "type": "_sbcs", - "chars": "ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩαβγδεζηθικλμνξοπρσςτυφχψ░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀ωάέήϊίόύϋώΆΈΉΊΌΎΏ±≥≤ΪΫ÷≈°∙·√ⁿ²■ " - }, - "ibm737": "cp737", - "csibm737": "cp737", - "cp775": { - "type": "_sbcs", - "chars": "ĆüéāäģåćłēŖŗīŹÄÅÉæÆōöĢ¢ŚśÖÜø£ØפĀĪóŻżź”¦©®¬½¼Ł«»░▒▓│┤ĄČĘĖ╣║╗╝ĮŠ┐└┴┬├─┼ŲŪ╚╔╩╦╠═╬Žąčęėįšųūž┘┌█▄▌▐▀ÓßŌŃõÕµńĶķĻļņĒŅ’­±“¾¶§÷„°∙·¹³²■ " - }, - "ibm775": "cp775", - "csibm775": "cp775", - "cp850": { - "type": "_sbcs", - "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø׃áíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈıÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´­±‗¾¶§÷¸°¨·¹³²■ " - }, - "ibm850": "cp850", - "csibm850": "cp850", - "cp852": { - "type": "_sbcs", - "chars": "ÇüéâäůćçłëŐőîŹÄĆÉĹĺôöĽľŚśÖÜŤťŁ×čáíóúĄąŽžĘ꬟Ⱥ«»░▒▓│┤ÁÂĚŞ╣║╗╝Żż┐└┴┬├─┼Ăă╚╔╩╦╠═╬¤đĐĎËďŇÍÎě┘┌█▄ŢŮ▀ÓßÔŃńňŠšŔÚŕŰýÝţ´­˝˛ˇ˘§÷¸°¨˙űŘř■ " - }, - "ibm852": "cp852", - "csibm852": "cp852", - "cp855": { - "type": "_sbcs", - "chars": "ђЂѓЃёЁєЄѕЅіІїЇјЈљЉњЊћЋќЌўЎџЏюЮъЪаАбБцЦдДеЕфФгГ«»░▒▓│┤хХиИ╣║╗╝йЙ┐└┴┬├─┼кК╚╔╩╦╠═╬¤лЛмМнНоОп┘┌█▄Пя▀ЯрРсСтТуУжЖвВьЬ№­ыЫзЗшШэЭщЩчЧ§■ " - }, - "ibm855": "cp855", - "csibm855": "cp855", - "cp856": { - "type": "_sbcs", - "chars": "אבגדהוזחטיךכלםמןנסעףפץצקרשת�£�×����������®¬½¼�«»░▒▓│┤���©╣║╗╝¢¥┐└┴┬├─┼��╚╔╩╦╠═╬¤���������┘┌█▄¦�▀������µ�������¯´­±‗¾¶§÷¸°¨·¹³²■ " - }, - "ibm856": "cp856", - "csibm856": "cp856", - "cp857": { - "type": "_sbcs", - "chars": "ÇüéâäàåçêëèïîıÄÅÉæÆôöòûùİÖÜø£ØŞşáíóúñÑĞ𿮬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ºªÊËÈ�ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµ�×ÚÛÙìÿ¯´­±�¾¶§÷¸°¨·¹³²■ " - }, - "ibm857": "cp857", - "csibm857": "cp857", - "cp858": { - "type": "_sbcs", - "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø׃áíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈ€ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´­±‗¾¶§÷¸°¨·¹³²■ " - }, - "ibm858": "cp858", - "csibm858": "cp858", - "cp860": { - "type": "_sbcs", - "chars": "ÇüéâãàÁçêÊèÍÔìÃÂÉÀÈôõòÚùÌÕÜ¢£Ù₧ÓáíóúñѪº¿Ò¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " - }, - "ibm860": "cp860", - "csibm860": "cp860", - "cp861": { - "type": "_sbcs", - "chars": "ÇüéâäàåçêëèÐðÞÄÅÉæÆôöþûÝýÖÜø£Ø₧ƒáíóúÁÍÓÚ¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " - }, - "ibm861": "cp861", - "csibm861": "cp861", - "cp862": { - "type": "_sbcs", - "chars": "אבגדהוזחטיךכלםמןנסעףפץצקרשת¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " - }, - "ibm862": "cp862", - "csibm862": "cp862", - "cp863": { - "type": "_sbcs", - "chars": "ÇüéâÂà¶çêëèïî‗À§ÉÈÊôËÏûù¤ÔÜ¢£ÙÛƒ¦´óú¨¸³¯Î⌐¬½¼¾«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " - }, - "ibm863": "cp863", - "csibm863": "cp863", - "cp864": { - "type": "_sbcs", - "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$٪&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~°·∙√▒─│┼┤┬├┴┐┌└┘β∞φ±½¼≈«»ﻷﻸ��ﻻﻼ� ­ﺂ£¤ﺄ��ﺎﺏﺕﺙ،ﺝﺡﺥ٠١٢٣٤٥٦٧٨٩ﻑ؛ﺱﺵﺹ؟¢ﺀﺁﺃﺅﻊﺋﺍﺑﺓﺗﺛﺟﺣﺧﺩﺫﺭﺯﺳﺷﺻﺿﻁﻅﻋﻏ¦¬÷×ﻉـﻓﻗﻛﻟﻣﻧﻫﻭﻯﻳﺽﻌﻎﻍﻡﹽّﻥﻩﻬﻰﻲﻐﻕﻵﻶﻝﻙﻱ■�" - }, - "ibm864": "cp864", - "csibm864": "cp864", - "cp865": { - "type": "_sbcs", - "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø₧ƒáíóúñѪº¿⌐¬½¼¡«¤░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " - }, - "ibm865": "cp865", - "csibm865": "cp865", - "cp866": { - "type": "_sbcs", - "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№¤■ " - }, - "ibm866": "cp866", - "csibm866": "cp866", - "cp869": { - "type": "_sbcs", - "chars": "������Ά�·¬¦‘’Έ―ΉΊΪΌ��ΎΫ©Ώ²³ά£έήίϊΐόύΑΒΓΔΕΖΗ½ΘΙ«»░▒▓│┤ΚΛΜΝ╣║╗╝ΞΟ┐└┴┬├─┼ΠΡ╚╔╩╦╠═╬ΣΤΥΦΧΨΩαβγ┘┌█▄δε▀ζηθικλμνξοπρσςτ΄­±υφχ§ψ΅°¨ωϋΰώ■ " - }, - "ibm869": "cp869", - "csibm869": "cp869", - "cp922": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®‾°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŠÑÒÓÔÕÖ×ØÙÚÛÜÝŽßàáâãäåæçèéêëìíîïšñòóôõö÷øùúûüýžÿ" - }, - "ibm922": "cp922", - "csibm922": "cp922", - "cp1046": { - "type": "_sbcs", - "chars": "ﺈ×÷ﹱˆ■│─┐┌└┘ﹹﹻﹽﹿﹷﺊﻰﻳﻲﻎﻏﻐﻶﻸﻺﻼ ¤ﺋﺑﺗﺛﺟﺣ،­ﺧﺳ٠١٢٣٤٥٦٧٨٩ﺷ؛ﺻﺿﻊ؟ﻋءآأؤإئابةتثجحخدذرزسشصضطﻇعغﻌﺂﺄﺎﻓـفقكلمنهوىيًٌٍَُِّْﻗﻛﻟﻵﻷﻹﻻﻣﻧﻬﻩ�" - }, - "ibm1046": "cp1046", - "csibm1046": "cp1046", - "cp1124": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ЁЂҐЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђґєѕіїјљњћќ§ўџ" - }, - "ibm1124": "cp1124", - "csibm1124": "cp1124", - "cp1125": { - "type": "_sbcs", - "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёҐґЄєІіЇї·√№¤■ " - }, - "ibm1125": "cp1125", - "csibm1125": "cp1125", - "cp1129": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§œ©ª«¬­®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖ×ØÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" - }, - "ibm1129": "cp1129", - "csibm1129": "cp1129", - "cp1133": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ກຂຄງຈສຊຍດຕຖທນບປຜຝພຟມຢຣລວຫອຮ���ຯະາຳິີຶືຸູຼັົຽ���ເແໂໃໄ່້໊໋໌ໍໆ�ໜໝ₭����������������໐໑໒໓໔໕໖໗໘໙��¢¬¦�" - }, - "ibm1133": "cp1133", - "csibm1133": "cp1133", - "cp1161": { - "type": "_sbcs", - "chars": "��������������������������������่กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู้๊๋€฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛¢¬¦ " - }, - "ibm1161": "cp1161", - "csibm1161": "cp1161", - "cp1162": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" - }, - "ibm1162": "cp1162", - "csibm1162": "cp1162", - "cp1163": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£€¥¦§œ©ª«¬­®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖ×ØÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" - }, - "ibm1163": "cp1163", - "csibm1163": "cp1163", - "maccroatian": { - "type": "_sbcs", - "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø¿¡¬√ƒ≈Ć«Č… ÀÃÕŒœĐ—“”‘’÷◊�©⁄¤‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ" - }, - "maccyrillic": { - "type": "_sbcs", - "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°¢£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµ∂ЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤" - }, - "macgreek": { - "type": "_sbcs", - "chars": "Ĺ²É³ÖÜ΅àâä΄¨çéèê룙î‰ôö¦­ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩάΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ�" - }, - "maciceland": { - "type": "_sbcs", - "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüÝ°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" - }, - "macroman": { - "type": "_sbcs", - "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" - }, - "macromania": { - "type": "_sbcs", - "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂŞ∞±≤≥¥µ∂∑∏π∫ªºΩăş¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›Ţţ‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" - }, - "macthai": { - "type": "_sbcs", - "chars": "«»…“”�•‘’� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู​–—฿เแโใไๅๆ็่้๊๋์ํ™๏๐๑๒๓๔๕๖๗๘๙®©����" - }, - "macturkish": { - "type": "_sbcs", - "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙ�ˆ˜¯˘˙˚¸˝˛ˇ" - }, - "macukraine": { - "type": "_sbcs", - "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤" - }, - "koi8r": { - "type": "_sbcs", - "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ё╓╔╕╖╗╘╙╚╛╜╝╞╟╠╡Ё╢╣╤╥╦╧╨╩╪╫╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" - }, - "koi8u": { - "type": "_sbcs", - "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґ╝╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪Ґ╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" - }, - "koi8ru": { - "type": "_sbcs", - "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґў╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪ҐЎ©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" - }, - "koi8t": { - "type": "_sbcs", - "chars": "қғ‚Ғ„…†‡�‰ҳ‹ҲҷҶ�Қ‘’“”•–—�™�›�����ӯӮё¤ӣ¦§���«¬­®�°±²Ё�Ӣ¶·�№�»���©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" - }, - "armscii8": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ �և։)(»«—.՝,-֊…՜՛՞ԱաԲբԳգԴդԵեԶզԷէԸըԹթԺժԻիԼլԽխԾծԿկՀհՁձՂղՃճՄմՅյՆնՇշՈոՉչՊպՋջՌռՍսՎվՏտՐրՑցՒւՓփՔքՕօՖֆ՚�" - }, - "rk1048": { - "type": "_sbcs", - "chars": "ЂЃ‚ѓ„…†‡€‰Љ‹ЊҚҺЏђ‘’“”•–—�™љ›њқһџ ҰұӘ¤Ө¦§Ё©Ғ«¬­®Ү°±Ііөµ¶·ё№ғ»әҢңүАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" - }, - "tcvn": { - "type": "_sbcs", - "chars": "\u0000ÚỤ\u0003ỪỬỮ\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010ỨỰỲỶỸÝỴ\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ÀẢÃÁẠẶẬÈẺẼÉẸỆÌỈĨÍỊÒỎÕÓỌỘỜỞỠỚỢÙỦŨ ĂÂÊÔƠƯĐăâêôơưđẶ̀̀̉̃́àảãáạẲằẳẵắẴẮẦẨẪẤỀặầẩẫấậèỂẻẽéẹềểễếệìỉỄẾỒĩíịòỔỏõóọồổỗốộờởỡớợùỖủũúụừửữứựỳỷỹýỵỐ" - }, - "georgianacademy": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზთიკლმნოპჟრსტუფქღყშჩცძწჭხჯჰჱჲჳჴჵჶçèéêëìíîïðñòóôõö÷øùúûüýþÿ" - }, - "georgianps": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზჱთიკლმნჲოპჟრსტჳუფქღყშჩცძწჭხჴჯჰჵæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" - }, - "pt154": { - "type": "_sbcs", - "chars": "ҖҒӮғ„…ҶҮҲүҠӢҢҚҺҸҗ‘’“”•–—ҳҷҡӣңқһҹ ЎўЈӨҘҰ§Ё©Ә«¬ӯ®Ҝ°ұІіҙө¶·ё№ә»јҪҫҝАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" - }, - "viscii": { - "type": "_sbcs", - "chars": "\u0000\u0001Ẳ\u0003\u0004ẴẪ\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013Ỷ\u0015\u0016\u0017\u0018Ỹ\u001a\u001b\u001c\u001dỴ\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ẠẮẰẶẤẦẨẬẼẸẾỀỂỄỆỐỒỔỖỘỢỚỜỞỊỎỌỈỦŨỤỲÕắằặấầẩậẽẹếềểễệốồổỗỠƠộờởịỰỨỪỬơớƯÀÁÂÃẢĂẳẵÈÉÊẺÌÍĨỳĐứÒÓÔạỷừửÙÚỹỵÝỡưàáâãảăữẫèéêẻìíĩỉđựòóôõỏọụùúũủýợỮ" - }, - "iso646cn": { - "type": "_sbcs", - "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#¥%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������" - }, - "iso646jp": { - "type": "_sbcs", - "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[¥]^_`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������" - }, - "hproman8": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ÀÂÈÊËÎÏ´ˋˆ¨˜ÙÛ₤¯Ýý°ÇçÑñ¡¿¤£¥§ƒ¢âêôûáéóúàèòùäëöüÅîØÆåíøæÄìÖÜÉïßÔÁÃãÐðÍÌÓÒÕõŠšÚŸÿÞþ·µ¶¾—¼½ªº«■»±�" - }, - "macintosh": { - "type": "_sbcs", - "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" - }, - "ascii": { - "type": "_sbcs", - "chars": "��������������������������������������������������������������������������������������������������������������������������������" - }, - "tis620": { - "type": "_sbcs", - "chars": "���������������������������������กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" + // redefine the error message + Object.defineProperty(err, 'message', { + enumerable: true, + configurable: true, + value: msg, + writable: true + }) + + // redefine the error name + Object.defineProperty(err, 'name', { + enumerable: false, + configurable: true, + value: className, + writable: true + }) + + return err } + + inherits(ServerError, HttpError) + nameFunc(ServerError, className) + + ServerError.prototype.status = code + ServerError.prototype.statusCode = code + ServerError.prototype.expose = false + + return ServerError } -/***/ }), +/** + * Set the name of a function, if possible. + * @private + */ -/***/ 41080: -/***/ ((module) => { +function nameFunc (func, name) { + var desc = Object.getOwnPropertyDescriptor(func, 'name') -"use strict"; + if (desc && desc.configurable) { + desc.value = name + Object.defineProperty(func, 'name', desc) + } +} +/** + * Populate the exports object with constructors for every error class. + * @private + */ -// Manually added data to be used by sbcs codec in addition to generated one. +function populateConstructorExports (exports, codes, HttpError) { + codes.forEach(function forEachCode (code) { + var CodeError + var name = toIdentifier(statuses[code]) -module.exports = { - // Not supported by iconv, not sure why. - "10029": "maccenteuro", - "maccenteuro": { - "type": "_sbcs", - "chars": "ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ" - }, + switch (codeClass(code)) { + case 400: + CodeError = createClientErrorConstructor(HttpError, name, code) + break + case 500: + CodeError = createServerErrorConstructor(HttpError, name, code) + break + } - "808": "cp808", - "ibm808": "cp808", - "cp808": { - "type": "_sbcs", - "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№€■ " - }, + if (CodeError) { + // export the constructor + exports[code] = CodeError + exports[name] = CodeError + } + }) - "mik": { - "type": "_sbcs", - "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя└┴┬├─┼╣║╚╔╩╦╠═╬┐░▒▓│┤№§╗╝┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " - }, + // backwards-compatibility + exports["I'mateapot"] = deprecate.function(exports.ImATeapot, + '"I\'mateapot"; use "ImATeapot" instead') +} - // Aliases of generated encodings. - "ascii8bit": "ascii", - "usascii": "ascii", - "ansix34": "ascii", - "ansix341968": "ascii", - "ansix341986": "ascii", - "csascii": "ascii", - "cp367": "ascii", - "ibm367": "ascii", - "isoir6": "ascii", - "iso646us": "ascii", - "iso646irv": "ascii", - "us": "ascii", +/** + * Get a class name from a name identifier. + * @private + */ - "latin1": "iso88591", - "latin2": "iso88592", - "latin3": "iso88593", - "latin4": "iso88594", - "latin5": "iso88599", - "latin6": "iso885910", - "latin7": "iso885913", - "latin8": "iso885914", - "latin9": "iso885915", - "latin10": "iso885916", - - "csisolatin1": "iso88591", - "csisolatin2": "iso88592", - "csisolatin3": "iso88593", - "csisolatin4": "iso88594", - "csisolatincyrillic": "iso88595", - "csisolatinarabic": "iso88596", - "csisolatingreek" : "iso88597", - "csisolatinhebrew": "iso88598", - "csisolatin5": "iso88599", - "csisolatin6": "iso885910", - - "l1": "iso88591", - "l2": "iso88592", - "l3": "iso88593", - "l4": "iso88594", - "l5": "iso88599", - "l6": "iso885910", - "l7": "iso885913", - "l8": "iso885914", - "l9": "iso885915", - "l10": "iso885916", - - "isoir14": "iso646jp", - "isoir57": "iso646cn", - "isoir100": "iso88591", - "isoir101": "iso88592", - "isoir109": "iso88593", - "isoir110": "iso88594", - "isoir144": "iso88595", - "isoir127": "iso88596", - "isoir126": "iso88597", - "isoir138": "iso88598", - "isoir148": "iso88599", - "isoir157": "iso885910", - "isoir166": "tis620", - "isoir179": "iso885913", - "isoir199": "iso885914", - "isoir203": "iso885915", - "isoir226": "iso885916", - - "cp819": "iso88591", - "ibm819": "iso88591", - - "cyrillic": "iso88595", - - "arabic": "iso88596", - "arabic8": "iso88596", - "ecma114": "iso88596", - "asmo708": "iso88596", - - "greek" : "iso88597", - "greek8" : "iso88597", - "ecma118" : "iso88597", - "elot928" : "iso88597", - - "hebrew": "iso88598", - "hebrew8": "iso88598", - - "turkish": "iso88599", - "turkish8": "iso88599", - - "thai": "iso885911", - "thai8": "iso885911", +function toClassName (name) { + return name.substr(-5) !== 'Error' + ? name + 'Error' + : name +} - "celtic": "iso885914", - "celtic8": "iso885914", - "isoceltic": "iso885914", - "tis6200": "tis620", - "tis62025291": "tis620", - "tis62025330": "tis620", +/***/ }), - "10000": "macroman", - "10006": "macgreek", - "10007": "maccyrillic", - "10079": "maciceland", - "10081": "macturkish", +/***/ 15098: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - "cspc8codepage437": "cp437", - "cspc775baltic": "cp775", - "cspc850multilingual": "cp850", - "cspcp852": "cp852", - "cspc862latinhebrew": "cp862", - "cpgr": "cp869", +"use strict"; - "msee": "cp1250", - "mscyrl": "cp1251", - "msansi": "cp1252", - "msgreek": "cp1253", - "msturk": "cp1254", - "mshebr": "cp1255", - "msarab": "cp1256", - "winbaltrim": "cp1257", +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const net_1 = __importDefault(__nccwpck_require__(41808)); +const tls_1 = __importDefault(__nccwpck_require__(24404)); +const url_1 = __importDefault(__nccwpck_require__(57310)); +const assert_1 = __importDefault(__nccwpck_require__(39491)); +const debug_1 = __importDefault(__nccwpck_require__(38237)); +const agent_base_1 = __nccwpck_require__(49690); +const parse_proxy_response_1 = __importDefault(__nccwpck_require__(595)); +const debug = debug_1.default('https-proxy-agent:agent'); +/** + * The `HttpsProxyAgent` implements an HTTP Agent subclass that connects to + * the specified "HTTP(s) proxy server" in order to proxy HTTPS requests. + * + * Outgoing HTTP requests are first tunneled through the proxy server using the + * `CONNECT` HTTP request method to establish a connection to the proxy server, + * and then the proxy server connects to the destination target and issues the + * HTTP request from the proxy server. + * + * `https:` requests have their socket connection upgraded to TLS once + * the connection to the proxy server has been established. + * + * @api public + */ +class HttpsProxyAgent extends agent_base_1.Agent { + constructor(_opts) { + let opts; + if (typeof _opts === 'string') { + opts = url_1.default.parse(_opts); + } + else { + opts = _opts; + } + if (!opts) { + throw new Error('an HTTP(S) proxy server `host` and `port` must be specified!'); + } + debug('creating new HttpsProxyAgent instance: %o', opts); + super(opts); + const proxy = Object.assign({}, opts); + // If `true`, then connect to the proxy server over TLS. + // Defaults to `false`. + this.secureProxy = opts.secureProxy || isHTTPS(proxy.protocol); + // Prefer `hostname` over `host`, and set the `port` if needed. + proxy.host = proxy.hostname || proxy.host; + if (typeof proxy.port === 'string') { + proxy.port = parseInt(proxy.port, 10); + } + if (!proxy.port && proxy.host) { + proxy.port = this.secureProxy ? 443 : 80; + } + // ALPN is supported by Node.js >= v5. + // attempt to negotiate http/1.1 for proxy servers that support http/2 + if (this.secureProxy && !('ALPNProtocols' in proxy)) { + proxy.ALPNProtocols = ['http 1.1']; + } + if (proxy.host && proxy.path) { + // If both a `host` and `path` are specified then it's most likely + // the result of a `url.parse()` call... we need to remove the + // `path` portion so that `net.connect()` doesn't attempt to open + // that as a Unix socket file. + delete proxy.path; + delete proxy.pathname; + } + this.proxy = proxy; + } + /** + * Called when the node-core HTTP client library is creating a + * new HTTP request. + * + * @api protected + */ + callback(req, opts) { + return __awaiter(this, void 0, void 0, function* () { + const { proxy, secureProxy } = this; + // Create a socket connection to the proxy server. + let socket; + if (secureProxy) { + debug('Creating `tls.Socket`: %o', proxy); + socket = tls_1.default.connect(proxy); + } + else { + debug('Creating `net.Socket`: %o', proxy); + socket = net_1.default.connect(proxy); + } + const headers = Object.assign({}, proxy.headers); + const hostname = `${opts.host}:${opts.port}`; + let payload = `CONNECT ${hostname} HTTP/1.1\r\n`; + // Inject the `Proxy-Authorization` header if necessary. + if (proxy.auth) { + headers['Proxy-Authorization'] = `Basic ${Buffer.from(proxy.auth).toString('base64')}`; + } + // The `Host` header should only include the port + // number when it is not the default port. + let { host, port, secureEndpoint } = opts; + if (!isDefaultPort(port, secureEndpoint)) { + host += `:${port}`; + } + headers.Host = host; + headers.Connection = 'close'; + for (const name of Object.keys(headers)) { + payload += `${name}: ${headers[name]}\r\n`; + } + const proxyResponsePromise = parse_proxy_response_1.default(socket); + socket.write(`${payload}\r\n`); + const { statusCode, buffered } = yield proxyResponsePromise; + if (statusCode === 200) { + req.once('socket', resume); + if (opts.secureEndpoint) { + const servername = opts.servername || opts.host; + if (!servername) { + throw new Error('Could not determine "servername"'); + } + // The proxy is connecting to a TLS server, so upgrade + // this socket connection to a TLS connection. + debug('Upgrading socket connection to TLS'); + return tls_1.default.connect(Object.assign(Object.assign({}, omit(opts, 'host', 'hostname', 'path', 'port')), { socket, + servername })); + } + return socket; + } + // Some other status code that's not 200... need to re-play the HTTP + // header "data" events onto the socket once the HTTP machinery is + // attached so that the node core `http` can parse and handle the + // error status code. + // Close the original socket, and a new "fake" socket is returned + // instead, so that the proxy doesn't get the HTTP request + // written to it (which may contain `Authorization` headers or other + // sensitive data). + // + // See: https://hackerone.com/reports/541502 + socket.destroy(); + const fakeSocket = new net_1.default.Socket(); + fakeSocket.readable = true; + // Need to wait for the "socket" event to re-play the "data" events. + req.once('socket', (s) => { + debug('replaying proxy buffer for failed request'); + assert_1.default(s.listenerCount('data') > 0); + // Replay the "buffered" Buffer onto the fake `socket`, since at + // this point the HTTP module machinery has been hooked up for + // the user. + s.push(buffered); + s.push(null); + }); + return fakeSocket; + }); + } +} +exports["default"] = HttpsProxyAgent; +function resume(socket) { + socket.resume(); +} +function isDefaultPort(port, secure) { + return Boolean((!secure && port === 80) || (secure && port === 443)); +} +function isHTTPS(protocol) { + return typeof protocol === 'string' ? /^https:?$/i.test(protocol) : false; +} +function omit(obj, ...keys) { + const ret = {}; + let key; + for (key in obj) { + if (!keys.includes(key)) { + ret[key] = obj[key]; + } + } + return ret; +} +//# sourceMappingURL=agent.js.map - "cp20866": "koi8r", - "20866": "koi8r", - "ibm878": "koi8r", - "cskoi8r": "koi8r", +/***/ }), - "cp21866": "koi8u", - "21866": "koi8u", - "ibm1168": "koi8u", +/***/ 77219: +/***/ (function(module, __unused_webpack_exports, __nccwpck_require__) { - "strk10482002": "rk1048", +"use strict"; - "tcvn5712": "tcvn", - "tcvn57121": "tcvn", +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +const agent_1 = __importDefault(__nccwpck_require__(15098)); +function createHttpsProxyAgent(opts) { + return new agent_1.default(opts); +} +(function (createHttpsProxyAgent) { + createHttpsProxyAgent.HttpsProxyAgent = agent_1.default; + createHttpsProxyAgent.prototype = agent_1.default.prototype; +})(createHttpsProxyAgent || (createHttpsProxyAgent = {})); +module.exports = createHttpsProxyAgent; +//# sourceMappingURL=index.js.map - "gb198880": "iso646cn", - "cn": "iso646cn", +/***/ }), - "csiso14jisc6220ro": "iso646jp", - "jisc62201969ro": "iso646jp", - "jp": "iso646jp", +/***/ 595: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - "cshproman8": "hproman8", - "r8": "hproman8", - "roman8": "hproman8", - "xroman8": "hproman8", - "ibm1051": "hproman8", +"use strict"; - "mac": "macintosh", - "csmacintosh": "macintosh", +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; }; - - +Object.defineProperty(exports, "__esModule", ({ value: true })); +const debug_1 = __importDefault(__nccwpck_require__(38237)); +const debug = debug_1.default('https-proxy-agent:parse-proxy-response'); +function parseProxyResponse(socket) { + return new Promise((resolve, reject) => { + // we need to buffer any HTTP traffic that happens with the proxy before we get + // the CONNECT response, so that if the response is anything other than an "200" + // response code, then we can re-play the "data" events on the socket once the + // HTTP parser is hooked up... + let buffersLength = 0; + const buffers = []; + function read() { + const b = socket.read(); + if (b) + ondata(b); + else + socket.once('readable', read); + } + function cleanup() { + socket.removeListener('end', onend); + socket.removeListener('error', onerror); + socket.removeListener('close', onclose); + socket.removeListener('readable', read); + } + function onclose(err) { + debug('onclose had error %o', err); + } + function onend() { + debug('onend'); + } + function onerror(err) { + cleanup(); + debug('onerror %o', err); + reject(err); + } + function ondata(b) { + buffers.push(b); + buffersLength += b.length; + const buffered = Buffer.concat(buffers, buffersLength); + const endOfHeaders = buffered.indexOf('\r\n\r\n'); + if (endOfHeaders === -1) { + // keep buffering + debug('have not received end of HTTP headers yet...'); + read(); + return; + } + const firstLine = buffered.toString('ascii', 0, buffered.indexOf('\r\n')); + const statusCode = +firstLine.split(' ')[1]; + debug('got proxy server response: %o', firstLine); + resolve({ + statusCode, + buffered + }); + } + socket.on('error', onerror); + socket.on('close', onclose); + socket.on('end', onend); + read(); + }); +} +exports["default"] = parseProxyResponse; +//# sourceMappingURL=parse-proxy-response.js.map /***/ }), -/***/ 11155: +/***/ 39695: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; var Buffer = (__nccwpck_require__(15118).Buffer); -// Note: UTF16-LE (or UCS2) codec is Node.js native. See encodings/internal.js +// Multibyte codec. In this scheme, a character is represented by 1 or more bytes. +// Our codec supports UTF-16 surrogates, extensions for GB18030 and unicode sequences. +// To save memory and loading time, we read table files only when requested. -// == UTF16-BE codec. ========================================================== +exports._dbcs = DBCSCodec; -exports.utf16be = Utf16BECodec; -function Utf16BECodec() { -} +var UNASSIGNED = -1, + GB18030_CODE = -2, + SEQ_START = -10, + NODE_START = -1000, + UNASSIGNED_NODE = new Array(0x100), + DEF_CHAR = -1; -Utf16BECodec.prototype.encoder = Utf16BEEncoder; -Utf16BECodec.prototype.decoder = Utf16BEDecoder; -Utf16BECodec.prototype.bomAware = true; +for (var i = 0; i < 0x100; i++) + UNASSIGNED_NODE[i] = UNASSIGNED; -// -- Encoding +// Class DBCSCodec reads and initializes mapping tables. +function DBCSCodec(codecOptions, iconv) { + this.encodingName = codecOptions.encodingName; + if (!codecOptions) + throw new Error("DBCS codec is called without the data.") + if (!codecOptions.table) + throw new Error("Encoding '" + this.encodingName + "' has no data."); -function Utf16BEEncoder() { -} + // Load tables. + var mappingTable = codecOptions.table(); -Utf16BEEncoder.prototype.write = function(str) { - var buf = Buffer.from(str, 'ucs2'); - for (var i = 0; i < buf.length; i += 2) { - var tmp = buf[i]; buf[i] = buf[i+1]; buf[i+1] = tmp; - } - return buf; -} -Utf16BEEncoder.prototype.end = function() { -} + // Decode tables: MBCS -> Unicode. + + // decodeTables is a trie, encoded as an array of arrays of integers. Internal arrays are trie nodes and all have len = 256. + // Trie root is decodeTables[0]. + // Values: >= 0 -> unicode character code. can be > 0xFFFF + // == UNASSIGNED -> unknown/unassigned sequence. + // == GB18030_CODE -> this is the end of a GB18030 4-byte sequence. + // <= NODE_START -> index of the next node in our trie to process next byte. + // <= SEQ_START -> index of the start of a character code sequence, in decodeTableSeq. + this.decodeTables = []; + this.decodeTables[0] = UNASSIGNED_NODE.slice(0); // Create root node. + // Sometimes a MBCS char corresponds to a sequence of unicode chars. We store them as arrays of integers here. + this.decodeTableSeq = []; -// -- Decoding + // Actual mapping tables consist of chunks. Use them to fill up decode tables. + for (var i = 0; i < mappingTable.length; i++) + this._addDecodeChunk(mappingTable[i]); -function Utf16BEDecoder() { - this.overflowByte = -1; -} + this.defaultCharUnicode = iconv.defaultCharUnicode; -Utf16BEDecoder.prototype.write = function(buf) { - if (buf.length == 0) - return ''; + + // Encode tables: Unicode -> DBCS. - var buf2 = Buffer.alloc(buf.length + 1), - i = 0, j = 0; + // `encodeTable` is array mapping from unicode char to encoded char. All its values are integers for performance. + // Because it can be sparse, it is represented as array of buckets by 256 chars each. Bucket can be null. + // Values: >= 0 -> it is a normal char. Write the value (if <=256 then 1 byte, if <=65536 then 2 bytes, etc.). + // == UNASSIGNED -> no conversion found. Output a default char. + // <= SEQ_START -> it's an index in encodeTableSeq, see below. The character starts a sequence. + this.encodeTable = []; + + // `encodeTableSeq` is used when a sequence of unicode characters is encoded as a single code. We use a tree of + // objects where keys correspond to characters in sequence and leafs are the encoded dbcs values. A special DEF_CHAR key + // means end of sequence (needed when one sequence is a strict subsequence of another). + // Objects are kept separately from encodeTable to increase performance. + this.encodeTableSeq = []; - if (this.overflowByte !== -1) { - buf2[0] = buf[0]; - buf2[1] = this.overflowByte; - i = 1; j = 2; - } + // Some chars can be decoded, but need not be encoded. + var skipEncodeChars = {}; + if (codecOptions.encodeSkipVals) + for (var i = 0; i < codecOptions.encodeSkipVals.length; i++) { + var val = codecOptions.encodeSkipVals[i]; + if (typeof val === 'number') + skipEncodeChars[val] = true; + else + for (var j = val.from; j <= val.to; j++) + skipEncodeChars[j] = true; + } + + // Use decode trie to recursively fill out encode tables. + this._fillEncodeTable(0, 0, skipEncodeChars); - for (; i < buf.length-1; i += 2, j+= 2) { - buf2[j] = buf[i+1]; - buf2[j+1] = buf[i]; + // Add more encoding pairs when needed. + if (codecOptions.encodeAdd) { + for (var uChar in codecOptions.encodeAdd) + if (Object.prototype.hasOwnProperty.call(codecOptions.encodeAdd, uChar)) + this._setEncodeChar(uChar.charCodeAt(0), codecOptions.encodeAdd[uChar]); } - this.overflowByte = (i == buf.length-1) ? buf[buf.length-1] : -1; + this.defCharSB = this.encodeTable[0][iconv.defaultCharSingleByte.charCodeAt(0)]; + if (this.defCharSB === UNASSIGNED) this.defCharSB = this.encodeTable[0]['?']; + if (this.defCharSB === UNASSIGNED) this.defCharSB = "?".charCodeAt(0); - return buf2.slice(0, j).toString('ucs2'); -} - -Utf16BEDecoder.prototype.end = function() { -} + // Load & create GB18030 tables when needed. + if (typeof codecOptions.gb18030 === 'function') { + this.gb18030 = codecOptions.gb18030(); // Load GB18030 ranges. -// == UTF-16 codec ============================================================= -// Decoder chooses automatically from UTF-16LE and UTF-16BE using BOM and space-based heuristic. -// Defaults to UTF-16LE, as it's prevalent and default in Node. -// http://en.wikipedia.org/wiki/UTF-16 and http://encoding.spec.whatwg.org/#utf-16le -// Decoder default can be changed: iconv.decode(buf, 'utf16', {defaultEncoding: 'utf-16be'}); + // Add GB18030 decode tables. + var thirdByteNodeIdx = this.decodeTables.length; + var thirdByteNode = this.decodeTables[thirdByteNodeIdx] = UNASSIGNED_NODE.slice(0); -// Encoder uses UTF-16LE and prepends BOM (which can be overridden with addBOM: false). + var fourthByteNodeIdx = this.decodeTables.length; + var fourthByteNode = this.decodeTables[fourthByteNodeIdx] = UNASSIGNED_NODE.slice(0); -exports.utf16 = Utf16Codec; -function Utf16Codec(codecOptions, iconv) { - this.iconv = iconv; + for (var i = 0x81; i <= 0xFE; i++) { + var secondByteNodeIdx = NODE_START - this.decodeTables[0][i]; + var secondByteNode = this.decodeTables[secondByteNodeIdx]; + for (var j = 0x30; j <= 0x39; j++) + secondByteNode[j] = NODE_START - thirdByteNodeIdx; + } + for (var i = 0x81; i <= 0xFE; i++) + thirdByteNode[i] = NODE_START - fourthByteNodeIdx; + for (var i = 0x30; i <= 0x39; i++) + fourthByteNode[i] = GB18030_CODE + } } -Utf16Codec.prototype.encoder = Utf16Encoder; -Utf16Codec.prototype.decoder = Utf16Decoder; - - -// -- Encoding (pass-through) +DBCSCodec.prototype.encoder = DBCSEncoder; +DBCSCodec.prototype.decoder = DBCSDecoder; -function Utf16Encoder(options, codec) { - options = options || {}; - if (options.addBOM === undefined) - options.addBOM = true; - this.encoder = codec.iconv.getEncoder('utf-16le', options); -} +// Decoder helpers +DBCSCodec.prototype._getDecodeTrieNode = function(addr) { + var bytes = []; + for (; addr > 0; addr >>= 8) + bytes.push(addr & 0xFF); + if (bytes.length == 0) + bytes.push(0); -Utf16Encoder.prototype.write = function(str) { - return this.encoder.write(str); -} + var node = this.decodeTables[0]; + for (var i = bytes.length-1; i > 0; i--) { // Traverse nodes deeper into the trie. + var val = node[bytes[i]]; -Utf16Encoder.prototype.end = function() { - return this.encoder.end(); + if (val == UNASSIGNED) { // Create new node. + node[bytes[i]] = NODE_START - this.decodeTables.length; + this.decodeTables.push(node = UNASSIGNED_NODE.slice(0)); + } + else if (val <= NODE_START) { // Existing node. + node = this.decodeTables[NODE_START - val]; + } + else + throw new Error("Overwrite byte in " + this.encodingName + ", addr: " + addr.toString(16)); + } + return node; } -// -- Decoding - -function Utf16Decoder(options, codec) { - this.decoder = null; - this.initialBytes = []; - this.initialBytesLen = 0; +DBCSCodec.prototype._addDecodeChunk = function(chunk) { + // First element of chunk is the hex mbcs code where we start. + var curAddr = parseInt(chunk[0], 16); - this.options = options || {}; - this.iconv = codec.iconv; -} + // Choose the decoding node where we'll write our chars. + var writeTable = this._getDecodeTrieNode(curAddr); + curAddr = curAddr & 0xFF; -Utf16Decoder.prototype.write = function(buf) { - if (!this.decoder) { - // Codec is not chosen yet. Accumulate initial bytes. - this.initialBytes.push(buf); - this.initialBytesLen += buf.length; - - if (this.initialBytesLen < 16) // We need more bytes to use space heuristic (see below) - return ''; + // Write all other elements of the chunk to the table. + for (var k = 1; k < chunk.length; k++) { + var part = chunk[k]; + if (typeof part === "string") { // String, write as-is. + for (var l = 0; l < part.length;) { + var code = part.charCodeAt(l++); + if (0xD800 <= code && code < 0xDC00) { // Decode surrogate + var codeTrail = part.charCodeAt(l++); + if (0xDC00 <= codeTrail && codeTrail < 0xE000) + writeTable[curAddr++] = 0x10000 + (code - 0xD800) * 0x400 + (codeTrail - 0xDC00); + else + throw new Error("Incorrect surrogate pair in " + this.encodingName + " at chunk " + chunk[0]); + } + else if (0x0FF0 < code && code <= 0x0FFF) { // Character sequence (our own encoding used) + var len = 0xFFF - code + 2; + var seq = []; + for (var m = 0; m < len; m++) + seq.push(part.charCodeAt(l++)); // Simple variation: don't support surrogates or subsequences in seq. - // We have enough bytes -> detect endianness. - var buf = Buffer.concat(this.initialBytes), - encoding = detectEncoding(buf, this.options.defaultEncoding); - this.decoder = this.iconv.getDecoder(encoding, this.options); - this.initialBytes.length = this.initialBytesLen = 0; + writeTable[curAddr++] = SEQ_START - this.decodeTableSeq.length; + this.decodeTableSeq.push(seq); + } + else + writeTable[curAddr++] = code; // Basic char + } + } + else if (typeof part === "number") { // Integer, meaning increasing sequence starting with prev character. + var charCode = writeTable[curAddr - 1] + 1; + for (var l = 0; l < part; l++) + writeTable[curAddr++] = charCode++; + } + else + throw new Error("Incorrect type '" + typeof part + "' given in " + this.encodingName + " at chunk " + chunk[0]); } + if (curAddr > 0xFF) + throw new Error("Incorrect chunk in " + this.encodingName + " at addr " + chunk[0] + ": too long" + curAddr); +} - return this.decoder.write(buf); +// Encoder helpers +DBCSCodec.prototype._getEncodeBucket = function(uCode) { + var high = uCode >> 8; // This could be > 0xFF because of astral characters. + if (this.encodeTable[high] === undefined) + this.encodeTable[high] = UNASSIGNED_NODE.slice(0); // Create bucket on demand. + return this.encodeTable[high]; } -Utf16Decoder.prototype.end = function() { - if (!this.decoder) { - var buf = Buffer.concat(this.initialBytes), - encoding = detectEncoding(buf, this.options.defaultEncoding); - this.decoder = this.iconv.getDecoder(encoding, this.options); +DBCSCodec.prototype._setEncodeChar = function(uCode, dbcsCode) { + var bucket = this._getEncodeBucket(uCode); + var low = uCode & 0xFF; + if (bucket[low] <= SEQ_START) + this.encodeTableSeq[SEQ_START-bucket[low]][DEF_CHAR] = dbcsCode; // There's already a sequence, set a single-char subsequence of it. + else if (bucket[low] == UNASSIGNED) + bucket[low] = dbcsCode; +} - var res = this.decoder.write(buf), - trail = this.decoder.end(); +DBCSCodec.prototype._setEncodeSequence = function(seq, dbcsCode) { + + // Get the root of character tree according to first character of the sequence. + var uCode = seq[0]; + var bucket = this._getEncodeBucket(uCode); + var low = uCode & 0xFF; - return trail ? (res + trail) : res; + var node; + if (bucket[low] <= SEQ_START) { + // There's already a sequence with - use it. + node = this.encodeTableSeq[SEQ_START-bucket[low]]; + } + else { + // There was no sequence object - allocate a new one. + node = {}; + if (bucket[low] !== UNASSIGNED) node[DEF_CHAR] = bucket[low]; // If a char was set before - make it a single-char subsequence. + bucket[low] = SEQ_START - this.encodeTableSeq.length; + this.encodeTableSeq.push(node); } - return this.decoder.end(); -} - -function detectEncoding(buf, defaultEncoding) { - var enc = defaultEncoding || 'utf-16le'; - if (buf.length >= 2) { - // Check BOM. - if (buf[0] == 0xFE && buf[1] == 0xFF) // UTF-16BE BOM - enc = 'utf-16be'; - else if (buf[0] == 0xFF && buf[1] == 0xFE) // UTF-16LE BOM - enc = 'utf-16le'; + // Traverse the character tree, allocating new nodes as needed. + for (var j = 1; j < seq.length-1; j++) { + var oldVal = node[uCode]; + if (typeof oldVal === 'object') + node = oldVal; else { - // No BOM found. Try to deduce encoding from initial content. - // Most of the time, the content has ASCII chars (U+00**), but the opposite (U+**00) is uncommon. - // So, we count ASCII as if it was LE or BE, and decide from that. - var asciiCharsLE = 0, asciiCharsBE = 0, // Counts of chars in both positions - _len = Math.min(buf.length - (buf.length % 2), 64); // Len is always even. - - for (var i = 0; i < _len; i += 2) { - if (buf[i] === 0 && buf[i+1] !== 0) asciiCharsBE++; - if (buf[i] !== 0 && buf[i+1] === 0) asciiCharsLE++; - } - - if (asciiCharsBE > asciiCharsLE) - enc = 'utf-16be'; - else if (asciiCharsBE < asciiCharsLE) - enc = 'utf-16le'; + node = node[uCode] = {} + if (oldVal !== undefined) + node[DEF_CHAR] = oldVal } } - return enc; + // Set the leaf to given dbcsCode. + uCode = seq[seq.length-1]; + node[uCode] = dbcsCode; } +DBCSCodec.prototype._fillEncodeTable = function(nodeIdx, prefix, skipEncodeChars) { + var node = this.decodeTables[nodeIdx]; + for (var i = 0; i < 0x100; i++) { + var uCode = node[i]; + var mbCode = prefix + i; + if (skipEncodeChars[mbCode]) + continue; + if (uCode >= 0) + this._setEncodeChar(uCode, mbCode); + else if (uCode <= NODE_START) + this._fillEncodeTable(NODE_START - uCode, mbCode << 8, skipEncodeChars); + else if (uCode <= SEQ_START) + this._setEncodeSequence(this.decodeTableSeq[SEQ_START - uCode], mbCode); + } +} -/***/ }), - -/***/ 51644: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; -var Buffer = (__nccwpck_require__(15118).Buffer); +// == Encoder ================================================================== -// UTF-7 codec, according to https://tools.ietf.org/html/rfc2152 -// See also below a UTF-7-IMAP codec, according to http://tools.ietf.org/html/rfc3501#section-5.1.3 +function DBCSEncoder(options, codec) { + // Encoder state + this.leadSurrogate = -1; + this.seqObj = undefined; + + // Static data + this.encodeTable = codec.encodeTable; + this.encodeTableSeq = codec.encodeTableSeq; + this.defaultCharSingleByte = codec.defCharSB; + this.gb18030 = codec.gb18030; +} -exports.utf7 = Utf7Codec; -exports.unicode11utf7 = 'utf7'; // Alias UNICODE-1-1-UTF-7 -function Utf7Codec(codecOptions, iconv) { - this.iconv = iconv; -}; +DBCSEncoder.prototype.write = function(str) { + var newBuf = Buffer.alloc(str.length * (this.gb18030 ? 4 : 3)), + leadSurrogate = this.leadSurrogate, + seqObj = this.seqObj, nextChar = -1, + i = 0, j = 0; -Utf7Codec.prototype.encoder = Utf7Encoder; -Utf7Codec.prototype.decoder = Utf7Decoder; -Utf7Codec.prototype.bomAware = true; + while (true) { + // 0. Get next character. + if (nextChar === -1) { + if (i == str.length) break; + var uCode = str.charCodeAt(i++); + } + else { + var uCode = nextChar; + nextChar = -1; + } + // 1. Handle surrogates. + if (0xD800 <= uCode && uCode < 0xE000) { // Char is one of surrogates. + if (uCode < 0xDC00) { // We've got lead surrogate. + if (leadSurrogate === -1) { + leadSurrogate = uCode; + continue; + } else { + leadSurrogate = uCode; + // Double lead surrogate found. + uCode = UNASSIGNED; + } + } else { // We've got trail surrogate. + if (leadSurrogate !== -1) { + uCode = 0x10000 + (leadSurrogate - 0xD800) * 0x400 + (uCode - 0xDC00); + leadSurrogate = -1; + } else { + // Incomplete surrogate pair - only trail surrogate found. + uCode = UNASSIGNED; + } + + } + } + else if (leadSurrogate !== -1) { + // Incomplete surrogate pair - only lead surrogate found. + nextChar = uCode; uCode = UNASSIGNED; // Write an error, then current char. + leadSurrogate = -1; + } -// -- Encoding + // 2. Convert uCode character. + var dbcsCode = UNASSIGNED; + if (seqObj !== undefined && uCode != UNASSIGNED) { // We are in the middle of the sequence + var resCode = seqObj[uCode]; + if (typeof resCode === 'object') { // Sequence continues. + seqObj = resCode; + continue; -var nonDirectChars = /[^A-Za-z0-9'\(\),-\.\/:\? \n\r\t]+/g; + } else if (typeof resCode == 'number') { // Sequence finished. Write it. + dbcsCode = resCode; -function Utf7Encoder(options, codec) { - this.iconv = codec.iconv; -} + } else if (resCode == undefined) { // Current character is not part of the sequence. -Utf7Encoder.prototype.write = function(str) { - // Naive implementation. - // Non-direct chars are encoded as "+-"; single "+" char is encoded as "+-". - return Buffer.from(str.replace(nonDirectChars, function(chunk) { - return "+" + (chunk === '+' ? '' : - this.iconv.encode(chunk, 'utf16-be').toString('base64').replace(/=+$/, '')) - + "-"; - }.bind(this))); -} + // Try default character for this sequence + resCode = seqObj[DEF_CHAR]; + if (resCode !== undefined) { + dbcsCode = resCode; // Found. Write it. + nextChar = uCode; // Current character will be written too in the next iteration. -Utf7Encoder.prototype.end = function() { -} + } else { + // TODO: What if we have no default? (resCode == undefined) + // Then, we should write first char of the sequence as-is and try the rest recursively. + // Didn't do it for now because no encoding has this situation yet. + // Currently, just skip the sequence and write current char. + } + } + seqObj = undefined; + } + else if (uCode >= 0) { // Regular character + var subtable = this.encodeTable[uCode >> 8]; + if (subtable !== undefined) + dbcsCode = subtable[uCode & 0xFF]; + + if (dbcsCode <= SEQ_START) { // Sequence start + seqObj = this.encodeTableSeq[SEQ_START-dbcsCode]; + continue; + } + if (dbcsCode == UNASSIGNED && this.gb18030) { + // Use GB18030 algorithm to find character(s) to write. + var idx = findIdx(this.gb18030.uChars, uCode); + if (idx != -1) { + var dbcsCode = this.gb18030.gbChars[idx] + (uCode - this.gb18030.uChars[idx]); + newBuf[j++] = 0x81 + Math.floor(dbcsCode / 12600); dbcsCode = dbcsCode % 12600; + newBuf[j++] = 0x30 + Math.floor(dbcsCode / 1260); dbcsCode = dbcsCode % 1260; + newBuf[j++] = 0x81 + Math.floor(dbcsCode / 10); dbcsCode = dbcsCode % 10; + newBuf[j++] = 0x30 + dbcsCode; + continue; + } + } + } -// -- Decoding + // 3. Write dbcsCode character. + if (dbcsCode === UNASSIGNED) + dbcsCode = this.defaultCharSingleByte; + + if (dbcsCode < 0x100) { + newBuf[j++] = dbcsCode; + } + else if (dbcsCode < 0x10000) { + newBuf[j++] = dbcsCode >> 8; // high byte + newBuf[j++] = dbcsCode & 0xFF; // low byte + } + else { + newBuf[j++] = dbcsCode >> 16; + newBuf[j++] = (dbcsCode >> 8) & 0xFF; + newBuf[j++] = dbcsCode & 0xFF; + } + } -function Utf7Decoder(options, codec) { - this.iconv = codec.iconv; - this.inBase64 = false; - this.base64Accum = ''; + this.seqObj = seqObj; + this.leadSurrogate = leadSurrogate; + return newBuf.slice(0, j); } -var base64Regex = /[A-Za-z0-9\/+]/; -var base64Chars = []; -for (var i = 0; i < 256; i++) - base64Chars[i] = base64Regex.test(String.fromCharCode(i)); - -var plusChar = '+'.charCodeAt(0), - minusChar = '-'.charCodeAt(0), - andChar = '&'.charCodeAt(0); - -Utf7Decoder.prototype.write = function(buf) { - var res = "", lastI = 0, - inBase64 = this.inBase64, - base64Accum = this.base64Accum; +DBCSEncoder.prototype.end = function() { + if (this.leadSurrogate === -1 && this.seqObj === undefined) + return; // All clean. Most often case. - // The decoder is more involved as we must handle chunks in stream. + var newBuf = Buffer.alloc(10), j = 0; - for (var i = 0; i < buf.length; i++) { - if (!inBase64) { // We're in direct mode. - // Write direct chars until '+' - if (buf[i] == plusChar) { - res += this.iconv.decode(buf.slice(lastI, i), "ascii"); // Write direct chars. - lastI = i+1; - inBase64 = true; + if (this.seqObj) { // We're in the sequence. + var dbcsCode = this.seqObj[DEF_CHAR]; + if (dbcsCode !== undefined) { // Write beginning of the sequence. + if (dbcsCode < 0x100) { + newBuf[j++] = dbcsCode; } - } else { // We decode base64. - if (!base64Chars[buf[i]]) { // Base64 ended. - if (i == lastI && buf[i] == minusChar) {// "+-" -> "+" - res += "+"; - } else { - var b64str = base64Accum + buf.slice(lastI, i).toString(); - res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); - } - - if (buf[i] != minusChar) // Minus is absorbed after base64. - i--; - - lastI = i+1; - inBase64 = false; - base64Accum = ''; + else { + newBuf[j++] = dbcsCode >> 8; // high byte + newBuf[j++] = dbcsCode & 0xFF; // low byte } + } else { + // See todo above. } + this.seqObj = undefined; } - if (!inBase64) { - res += this.iconv.decode(buf.slice(lastI), "ascii"); // Write direct chars. - } else { - var b64str = base64Accum + buf.slice(lastI).toString(); - - var canBeDecoded = b64str.length - (b64str.length % 8); // Minimal chunk: 2 quads -> 2x3 bytes -> 3 chars. - base64Accum = b64str.slice(canBeDecoded); // The rest will be decoded in future. - b64str = b64str.slice(0, canBeDecoded); - - res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); + if (this.leadSurrogate !== -1) { + // Incomplete surrogate pair - only lead surrogate found. + newBuf[j++] = this.defaultCharSingleByte; + this.leadSurrogate = -1; } - - this.inBase64 = inBase64; - this.base64Accum = base64Accum; - - return res; + + return newBuf.slice(0, j); } -Utf7Decoder.prototype.end = function() { - var res = ""; - if (this.inBase64 && this.base64Accum.length > 0) - res = this.iconv.decode(Buffer.from(this.base64Accum, 'base64'), "utf16-be"); - - this.inBase64 = false; - this.base64Accum = ''; - return res; -} +// Export for testing +DBCSEncoder.prototype.findIdx = findIdx; -// UTF-7-IMAP codec. -// RFC3501 Sec. 5.1.3 Modified UTF-7 (http://tools.ietf.org/html/rfc3501#section-5.1.3) -// Differences: -// * Base64 part is started by "&" instead of "+" -// * Direct characters are 0x20-0x7E, except "&" (0x26) -// * In Base64, "," is used instead of "/" -// * Base64 must not be used to represent direct characters. -// * No implicit shift back from Base64 (should always end with '-') -// * String must end in non-shifted position. -// * "-&" while in base64 is not allowed. +// == Decoder ================================================================== +function DBCSDecoder(options, codec) { + // Decoder state + this.nodeIdx = 0; + this.prevBuf = Buffer.alloc(0); -exports.utf7imap = Utf7IMAPCodec; -function Utf7IMAPCodec(codecOptions, iconv) { - this.iconv = iconv; -}; + // Static data + this.decodeTables = codec.decodeTables; + this.decodeTableSeq = codec.decodeTableSeq; + this.defaultCharUnicode = codec.defaultCharUnicode; + this.gb18030 = codec.gb18030; +} -Utf7IMAPCodec.prototype.encoder = Utf7IMAPEncoder; -Utf7IMAPCodec.prototype.decoder = Utf7IMAPDecoder; -Utf7IMAPCodec.prototype.bomAware = true; +DBCSDecoder.prototype.write = function(buf) { + var newBuf = Buffer.alloc(buf.length*2), + nodeIdx = this.nodeIdx, + prevBuf = this.prevBuf, prevBufOffset = this.prevBuf.length, + seqStart = -this.prevBuf.length, // idx of the start of current parsed sequence. + uCode; + if (prevBufOffset > 0) // Make prev buf overlap a little to make it easier to slice later. + prevBuf = Buffer.concat([prevBuf, buf.slice(0, 10)]); + + for (var i = 0, j = 0; i < buf.length; i++) { + var curByte = (i >= 0) ? buf[i] : prevBuf[i + prevBufOffset]; -// -- Encoding + // Lookup in current trie node. + var uCode = this.decodeTables[nodeIdx][curByte]; -function Utf7IMAPEncoder(options, codec) { - this.iconv = codec.iconv; - this.inBase64 = false; - this.base64Accum = Buffer.alloc(6); - this.base64AccumIdx = 0; -} + if (uCode >= 0) { + // Normal character, just use it. + } + else if (uCode === UNASSIGNED) { // Unknown char. + // TODO: Callback with seq. + //var curSeq = (seqStart >= 0) ? buf.slice(seqStart, i+1) : prevBuf.slice(seqStart + prevBufOffset, i+1 + prevBufOffset); + i = seqStart; // Try to parse again, after skipping first byte of the sequence ('i' will be incremented by 'for' cycle). + uCode = this.defaultCharUnicode.charCodeAt(0); + } + else if (uCode === GB18030_CODE) { + var curSeq = (seqStart >= 0) ? buf.slice(seqStart, i+1) : prevBuf.slice(seqStart + prevBufOffset, i+1 + prevBufOffset); + var ptr = (curSeq[0]-0x81)*12600 + (curSeq[1]-0x30)*1260 + (curSeq[2]-0x81)*10 + (curSeq[3]-0x30); + var idx = findIdx(this.gb18030.gbChars, ptr); + uCode = this.gb18030.uChars[idx] + ptr - this.gb18030.gbChars[idx]; + } + else if (uCode <= NODE_START) { // Go to next trie node. + nodeIdx = NODE_START - uCode; + continue; + } + else if (uCode <= SEQ_START) { // Output a sequence of chars. + var seq = this.decodeTableSeq[SEQ_START - uCode]; + for (var k = 0; k < seq.length - 1; k++) { + uCode = seq[k]; + newBuf[j++] = uCode & 0xFF; + newBuf[j++] = uCode >> 8; + } + uCode = seq[seq.length-1]; + } + else + throw new Error("iconv-lite internal error: invalid decoding table value " + uCode + " at " + nodeIdx + "/" + curByte); -Utf7IMAPEncoder.prototype.write = function(str) { - var inBase64 = this.inBase64, - base64Accum = this.base64Accum, - base64AccumIdx = this.base64AccumIdx, - buf = Buffer.alloc(str.length*5 + 10), bufIdx = 0; + // Write the character to buffer, handling higher planes using surrogate pair. + if (uCode > 0xFFFF) { + uCode -= 0x10000; + var uCodeLead = 0xD800 + Math.floor(uCode / 0x400); + newBuf[j++] = uCodeLead & 0xFF; + newBuf[j++] = uCodeLead >> 8; - for (var i = 0; i < str.length; i++) { - var uChar = str.charCodeAt(i); - if (0x20 <= uChar && uChar <= 0x7E) { // Direct character or '&'. - if (inBase64) { - if (base64AccumIdx > 0) { - bufIdx += buf.write(base64Accum.slice(0, base64AccumIdx).toString('base64').replace(/\//g, ',').replace(/=+$/, ''), bufIdx); - base64AccumIdx = 0; - } + uCode = 0xDC00 + uCode % 0x400; + } + newBuf[j++] = uCode & 0xFF; + newBuf[j++] = uCode >> 8; - buf[bufIdx++] = minusChar; // Write '-', then go to direct mode. - inBase64 = false; - } + // Reset trie node. + nodeIdx = 0; seqStart = i+1; + } - if (!inBase64) { - buf[bufIdx++] = uChar; // Write direct character + this.nodeIdx = nodeIdx; + this.prevBuf = (seqStart >= 0) ? buf.slice(seqStart) : prevBuf.slice(seqStart + prevBufOffset); + return newBuf.slice(0, j).toString('ucs2'); +} - if (uChar === andChar) // Ampersand -> '&-' - buf[bufIdx++] = minusChar; - } +DBCSDecoder.prototype.end = function() { + var ret = ''; - } else { // Non-direct character - if (!inBase64) { - buf[bufIdx++] = andChar; // Write '&', then go to base64 mode. - inBase64 = true; - } - if (inBase64) { - base64Accum[base64AccumIdx++] = uChar >> 8; - base64Accum[base64AccumIdx++] = uChar & 0xFF; + // Try to parse all remaining chars. + while (this.prevBuf.length > 0) { + // Skip 1 character in the buffer. + ret += this.defaultCharUnicode; + var buf = this.prevBuf.slice(1); - if (base64AccumIdx == base64Accum.length) { - bufIdx += buf.write(base64Accum.toString('base64').replace(/\//g, ','), bufIdx); - base64AccumIdx = 0; - } - } - } + // Parse remaining as usual. + this.prevBuf = Buffer.alloc(0); + this.nodeIdx = 0; + if (buf.length > 0) + ret += this.write(buf); } - this.inBase64 = inBase64; - this.base64AccumIdx = base64AccumIdx; - - return buf.slice(0, bufIdx); + this.nodeIdx = 0; + return ret; } -Utf7IMAPEncoder.prototype.end = function() { - var buf = Buffer.alloc(10), bufIdx = 0; - if (this.inBase64) { - if (this.base64AccumIdx > 0) { - bufIdx += buf.write(this.base64Accum.slice(0, this.base64AccumIdx).toString('base64').replace(/\//g, ',').replace(/=+$/, ''), bufIdx); - this.base64AccumIdx = 0; - } +// Binary search for GB18030. Returns largest i such that table[i] <= val. +function findIdx(table, val) { + if (table[0] > val) + return -1; - buf[bufIdx++] = minusChar; // Write '-', then go to direct mode. - this.inBase64 = false; + var l = 0, r = table.length; + while (l < r-1) { // always table[l] <= val < table[r] + var mid = l + Math.floor((r-l+1)/2); + if (table[mid] <= val) + l = mid; + else + r = mid; } - - return buf.slice(0, bufIdx); + return l; } -// -- Decoding - -function Utf7IMAPDecoder(options, codec) { - this.iconv = codec.iconv; - this.inBase64 = false; - this.base64Accum = ''; -} -var base64IMAPChars = base64Chars.slice(); -base64IMAPChars[','.charCodeAt(0)] = true; +/***/ }), -Utf7IMAPDecoder.prototype.write = function(buf) { - var res = "", lastI = 0, - inBase64 = this.inBase64, - base64Accum = this.base64Accum; +/***/ 91386: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // The decoder is more involved as we must handle chunks in stream. - // It is forgiving, closer to standard UTF-7 (for example, '-' is optional at the end). +"use strict"; - for (var i = 0; i < buf.length; i++) { - if (!inBase64) { // We're in direct mode. - // Write direct chars until '&' - if (buf[i] == andChar) { - res += this.iconv.decode(buf.slice(lastI, i), "ascii"); // Write direct chars. - lastI = i+1; - inBase64 = true; - } - } else { // We decode base64. - if (!base64IMAPChars[buf[i]]) { // Base64 ended. - if (i == lastI && buf[i] == minusChar) { // "&-" -> "&" - res += "&"; - } else { - var b64str = base64Accum + buf.slice(lastI, i).toString().replace(/,/g, '/'); - res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); - } - if (buf[i] != minusChar) // Minus may be absorbed after base64. - i--; +// Description of supported double byte encodings and aliases. +// Tables are not require()-d until they are needed to speed up library load. +// require()-s are direct to support Browserify. - lastI = i+1; - inBase64 = false; - base64Accum = ''; - } - } - } +module.exports = { + + // == Japanese/ShiftJIS ==================================================== + // All japanese encodings are based on JIS X set of standards: + // JIS X 0201 - Single-byte encoding of ASCII + ¥ + Kana chars at 0xA1-0xDF. + // JIS X 0208 - Main set of 6879 characters, placed in 94x94 plane, to be encoded by 2 bytes. + // Has several variations in 1978, 1983, 1990 and 1997. + // JIS X 0212 - Supplementary plane of 6067 chars in 94x94 plane. 1990. Effectively dead. + // JIS X 0213 - Extension and modern replacement of 0208 and 0212. Total chars: 11233. + // 2 planes, first is superset of 0208, second - revised 0212. + // Introduced in 2000, revised 2004. Some characters are in Unicode Plane 2 (0x2xxxx) - if (!inBase64) { - res += this.iconv.decode(buf.slice(lastI), "ascii"); // Write direct chars. - } else { - var b64str = base64Accum + buf.slice(lastI).toString().replace(/,/g, '/'); + // Byte encodings are: + // * Shift_JIS: Compatible with 0201, uses not defined chars in top half as lead bytes for double-byte + // encoding of 0208. Lead byte ranges: 0x81-0x9F, 0xE0-0xEF; Trail byte ranges: 0x40-0x7E, 0x80-0x9E, 0x9F-0xFC. + // Windows CP932 is a superset of Shift_JIS. Some companies added more chars, notably KDDI. + // * EUC-JP: Up to 3 bytes per character. Used mostly on *nixes. + // 0x00-0x7F - lower part of 0201 + // 0x8E, 0xA1-0xDF - upper part of 0201 + // (0xA1-0xFE)x2 - 0208 plane (94x94). + // 0x8F, (0xA1-0xFE)x2 - 0212 plane (94x94). + // * JIS X 208: 7-bit, direct encoding of 0208. Byte ranges: 0x21-0x7E (94 values). Uncommon. + // Used as-is in ISO2022 family. + // * ISO2022-JP: Stateful encoding, with escape sequences to switch between ASCII, + // 0201-1976 Roman, 0208-1978, 0208-1983. + // * ISO2022-JP-1: Adds esc seq for 0212-1990. + // * ISO2022-JP-2: Adds esc seq for GB2313-1980, KSX1001-1992, ISO8859-1, ISO8859-7. + // * ISO2022-JP-3: Adds esc seq for 0201-1976 Kana set, 0213-2000 Planes 1, 2. + // * ISO2022-JP-2004: Adds 0213-2004 Plane 1. + // + // After JIS X 0213 appeared, Shift_JIS-2004, EUC-JISX0213 and ISO2022-JP-2004 followed, with just changing the planes. + // + // Overall, it seems that it's a mess :( http://www8.plala.or.jp/tkubota1/unicode-symbols-map2.html - var canBeDecoded = b64str.length - (b64str.length % 8); // Minimal chunk: 2 quads -> 2x3 bytes -> 3 chars. - base64Accum = b64str.slice(canBeDecoded); // The rest will be decoded in future. - b64str = b64str.slice(0, canBeDecoded); + 'shiftjis': { + type: '_dbcs', + table: function() { return __nccwpck_require__(27014) }, + encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E}, + encodeSkipVals: [{from: 0xED40, to: 0xF940}], + }, + 'csshiftjis': 'shiftjis', + 'mskanji': 'shiftjis', + 'sjis': 'shiftjis', + 'windows31j': 'shiftjis', + 'ms31j': 'shiftjis', + 'xsjis': 'shiftjis', + 'windows932': 'shiftjis', + 'ms932': 'shiftjis', + '932': 'shiftjis', + 'cp932': 'shiftjis', - res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); - } + 'eucjp': { + type: '_dbcs', + table: function() { return __nccwpck_require__(31532) }, + encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E}, + }, - this.inBase64 = inBase64; - this.base64Accum = base64Accum; + // TODO: KDDI extension to Shift_JIS + // TODO: IBM CCSID 942 = CP932, but F0-F9 custom chars and other char changes. + // TODO: IBM CCSID 943 = Shift_JIS = CP932 with original Shift_JIS lower 128 chars. - return res; -} -Utf7IMAPDecoder.prototype.end = function() { - var res = ""; - if (this.inBase64 && this.base64Accum.length > 0) - res = this.iconv.decode(Buffer.from(this.base64Accum, 'base64'), "utf16-be"); + // == Chinese/GBK ========================================================== + // http://en.wikipedia.org/wiki/GBK + // We mostly implement W3C recommendation: https://www.w3.org/TR/encoding/#gbk-encoder - this.inBase64 = false; - this.base64Accum = ''; - return res; -} + // Oldest GB2312 (1981, ~7600 chars) is a subset of CP936 + 'gb2312': 'cp936', + 'gb231280': 'cp936', + 'gb23121980': 'cp936', + 'csgb2312': 'cp936', + 'csiso58gb231280': 'cp936', + 'euccn': 'cp936', + // Microsoft's CP936 is a subset and approximation of GBK. + 'windows936': 'cp936', + 'ms936': 'cp936', + '936': 'cp936', + 'cp936': { + type: '_dbcs', + table: function() { return __nccwpck_require__(13336) }, + }, + // GBK (~22000 chars) is an extension of CP936 that added user-mapped chars and some other. + 'gbk': { + type: '_dbcs', + table: function() { return (__nccwpck_require__(13336).concat)(__nccwpck_require__(44346)) }, + }, + 'xgbk': 'gbk', + 'isoir58': 'gbk', + // GB18030 is an algorithmic extension of GBK. + // Main source: https://www.w3.org/TR/encoding/#gbk-encoder + // http://icu-project.org/docs/papers/gb18030.html + // http://source.icu-project.org/repos/icu/data/trunk/charset/data/xml/gb-18030-2000.xml + // http://www.khngai.com/chinese/charmap/tblgbk.php?page=0 + 'gb18030': { + type: '_dbcs', + table: function() { return (__nccwpck_require__(13336).concat)(__nccwpck_require__(44346)) }, + gb18030: function() { return __nccwpck_require__(36258) }, + encodeSkipVals: [0x80], + encodeAdd: {'€': 0xA2E3}, + }, -/***/ }), + 'chinese': 'gb18030', -/***/ 67961: -/***/ ((__unused_webpack_module, exports) => { -"use strict"; + // == Korean =============================================================== + // EUC-KR, KS_C_5601 and KS X 1001 are exactly the same. + 'windows949': 'cp949', + 'ms949': 'cp949', + '949': 'cp949', + 'cp949': { + type: '_dbcs', + table: function() { return __nccwpck_require__(77348) }, + }, + 'cseuckr': 'cp949', + 'csksc56011987': 'cp949', + 'euckr': 'cp949', + 'isoir149': 'cp949', + 'korean': 'cp949', + 'ksc56011987': 'cp949', + 'ksc56011989': 'cp949', + 'ksc5601': 'cp949', -var BOMChar = '\uFEFF'; -exports.PrependBOM = PrependBOMWrapper -function PrependBOMWrapper(encoder, options) { - this.encoder = encoder; - this.addBOM = true; -} + // == Big5/Taiwan/Hong Kong ================================================ + // There are lots of tables for Big5 and cp950. Please see the following links for history: + // http://moztw.org/docs/big5/ http://www.haible.de/bruno/charsets/conversion-tables/Big5.html + // Variations, in roughly number of defined chars: + // * Windows CP 950: Microsoft variant of Big5. Canonical: http://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP950.TXT + // * Windows CP 951: Microsoft variant of Big5-HKSCS-2001. Seems to be never public. http://me.abelcheung.org/articles/research/what-is-cp951/ + // * Big5-2003 (Taiwan standard) almost superset of cp950. + // * Unicode-at-on (UAO) / Mozilla 1.8. Falling out of use on the Web. Not supported by other browsers. + // * Big5-HKSCS (-2001, -2004, -2008). Hong Kong standard. + // many unicode code points moved from PUA to Supplementary plane (U+2XXXX) over the years. + // Plus, it has 4 combining sequences. + // Seems that Mozilla refused to support it for 10 yrs. https://bugzilla.mozilla.org/show_bug.cgi?id=162431 https://bugzilla.mozilla.org/show_bug.cgi?id=310299 + // because big5-hkscs is the only encoding to include astral characters in non-algorithmic way. + // Implementations are not consistent within browsers; sometimes labeled as just big5. + // MS Internet Explorer switches from big5 to big5-hkscs when a patch applied. + // Great discussion & recap of what's going on https://bugzilla.mozilla.org/show_bug.cgi?id=912470#c31 + // In the encoder, it might make sense to support encoding old PUA mappings to Big5 bytes seq-s. + // Official spec: http://www.ogcio.gov.hk/en/business/tech_promotion/ccli/terms/doc/2003cmp_2008.txt + // http://www.ogcio.gov.hk/tc/business/tech_promotion/ccli/terms/doc/hkscs-2008-big5-iso.txt + // + // Current understanding of how to deal with Big5(-HKSCS) is in the Encoding Standard, http://encoding.spec.whatwg.org/#big5-encoder + // Unicode mapping (http://www.unicode.org/Public/MAPPINGS/OBSOLETE/EASTASIA/OTHER/BIG5.TXT) is said to be wrong. -PrependBOMWrapper.prototype.write = function(str) { - if (this.addBOM) { - str = BOMChar + str; - this.addBOM = false; - } + 'windows950': 'cp950', + 'ms950': 'cp950', + '950': 'cp950', + 'cp950': { + type: '_dbcs', + table: function() { return __nccwpck_require__(74284) }, + }, - return this.encoder.write(str); -} + // Big5 has many variations and is an extension of cp950. We use Encoding Standard's as a consensus. + 'big5': 'big5hkscs', + 'big5hkscs': { + type: '_dbcs', + table: function() { return (__nccwpck_require__(74284).concat)(__nccwpck_require__(63480)) }, + encodeSkipVals: [0xa2cc], + }, -PrependBOMWrapper.prototype.end = function() { - return this.encoder.end(); -} + 'cnbig5': 'big5hkscs', + 'csbig5': 'big5hkscs', + 'xxbig5': 'big5hkscs', +}; -//------------------------------------------------------------------------------ +/***/ }), -exports.StripBOM = StripBOMWrapper; -function StripBOMWrapper(decoder, options) { - this.decoder = decoder; - this.pass = false; - this.options = options || {}; -} +/***/ 82733: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -StripBOMWrapper.prototype.write = function(buf) { - var res = this.decoder.write(buf); - if (this.pass || !res) - return res; +"use strict"; - if (res[0] === BOMChar) { - res = res.slice(1); - if (typeof this.options.stripBOM === 'function') - this.options.stripBOM(); - } - this.pass = true; - return res; -} +// Update this array if you add/rename/remove files in this directory. +// We support Browserify by skipping automatic module discovery and requiring modules directly. +var modules = [ + __nccwpck_require__(12376), + __nccwpck_require__(11155), + __nccwpck_require__(51644), + __nccwpck_require__(26657), + __nccwpck_require__(41080), + __nccwpck_require__(21012), + __nccwpck_require__(39695), + __nccwpck_require__(91386), +]; -StripBOMWrapper.prototype.end = function() { - return this.decoder.end(); +// Put all encoding/alias/codec definitions to single object and export it. +for (var i = 0; i < modules.length; i++) { + var module = modules[i]; + for (var enc in module) + if (Object.prototype.hasOwnProperty.call(module, enc)) + exports[enc] = module[enc]; } - /***/ }), -/***/ 30393: +/***/ 12376: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -var Buffer = (__nccwpck_require__(14300).Buffer); -// Note: not polyfilled with safer-buffer on a purpose, as overrides Buffer - -// == Extend Node primitives to use iconv-lite ================================= - -module.exports = function (iconv) { - var original = undefined; // Place to keep original methods. +var Buffer = (__nccwpck_require__(15118).Buffer); - // Node authors rewrote Buffer internals to make it compatible with - // Uint8Array and we cannot patch key functions since then. - // Note: this does use older Buffer API on a purpose - iconv.supportsNodeEncodingsExtension = !(Buffer.from || new Buffer(0) instanceof Uint8Array); +// Export Node.js internal encodings. - iconv.extendNodeEncodings = function extendNodeEncodings() { - if (original) return; - original = {}; +module.exports = { + // Encodings + utf8: { type: "_internal", bomAware: true}, + cesu8: { type: "_internal", bomAware: true}, + unicode11utf8: "utf8", - if (!iconv.supportsNodeEncodingsExtension) { - console.error("ACTION NEEDED: require('iconv-lite').extendNodeEncodings() is not supported in your version of Node"); - console.error("See more info at https://github.com/ashtuchkin/iconv-lite/wiki/Node-v4-compatibility"); - return; - } + ucs2: { type: "_internal", bomAware: true}, + utf16le: "ucs2", - var nodeNativeEncodings = { - 'hex': true, 'utf8': true, 'utf-8': true, 'ascii': true, 'binary': true, - 'base64': true, 'ucs2': true, 'ucs-2': true, 'utf16le': true, 'utf-16le': true, - }; + binary: { type: "_internal" }, + base64: { type: "_internal" }, + hex: { type: "_internal" }, - Buffer.isNativeEncoding = function(enc) { - return enc && nodeNativeEncodings[enc.toLowerCase()]; - } + // Codec. + _internal: InternalCodec, +}; - // -- SlowBuffer ----------------------------------------------------------- - var SlowBuffer = (__nccwpck_require__(14300).SlowBuffer); +//------------------------------------------------------------------------------ - original.SlowBufferToString = SlowBuffer.prototype.toString; - SlowBuffer.prototype.toString = function(encoding, start, end) { - encoding = String(encoding || 'utf8').toLowerCase(); +function InternalCodec(codecOptions, iconv) { + this.enc = codecOptions.encodingName; + this.bomAware = codecOptions.bomAware; - // Use native conversion when possible - if (Buffer.isNativeEncoding(encoding)) - return original.SlowBufferToString.call(this, encoding, start, end); + if (this.enc === "base64") + this.encoder = InternalEncoderBase64; + else if (this.enc === "cesu8") { + this.enc = "utf8"; // Use utf8 for decoding. + this.encoder = InternalEncoderCesu8; - // Otherwise, use our decoding method. - if (typeof start == 'undefined') start = 0; - if (typeof end == 'undefined') end = this.length; - return iconv.decode(this.slice(start, end), encoding); + // Add decoder for versions of Node not supporting CESU-8 + if (Buffer.from('eda0bdedb2a9', 'hex').toString() !== '💩') { + this.decoder = InternalDecoderCesu8; + this.defaultCharUnicode = iconv.defaultCharUnicode; } + } +} - original.SlowBufferWrite = SlowBuffer.prototype.write; - SlowBuffer.prototype.write = function(string, offset, length, encoding) { - // Support both (string, offset, length, encoding) - // and the legacy (string, encoding, offset, length) - if (isFinite(offset)) { - if (!isFinite(length)) { - encoding = length; - length = undefined; - } - } else { // legacy - var swap = encoding; - encoding = offset; - offset = length; - length = swap; - } +InternalCodec.prototype.encoder = InternalEncoder; +InternalCodec.prototype.decoder = InternalDecoder; - offset = +offset || 0; - var remaining = this.length - offset; - if (!length) { - length = remaining; - } else { - length = +length; - if (length > remaining) { - length = remaining; - } - } - encoding = String(encoding || 'utf8').toLowerCase(); +//------------------------------------------------------------------------------ - // Use native conversion when possible - if (Buffer.isNativeEncoding(encoding)) - return original.SlowBufferWrite.call(this, string, offset, length, encoding); +// We use node.js internal decoder. Its signature is the same as ours. +var StringDecoder = (__nccwpck_require__(71576).StringDecoder); - if (string.length > 0 && (length < 0 || offset < 0)) - throw new RangeError('attempt to write beyond buffer bounds'); - - // Otherwise, use our encoding method. - var buf = iconv.encode(string, encoding); - if (buf.length < length) length = buf.length; - buf.copy(this, offset, 0, length); - return length; - } - - // -- Buffer --------------------------------------------------------------- - - original.BufferIsEncoding = Buffer.isEncoding; - Buffer.isEncoding = function(encoding) { - return Buffer.isNativeEncoding(encoding) || iconv.encodingExists(encoding); - } - - original.BufferByteLength = Buffer.byteLength; - Buffer.byteLength = SlowBuffer.byteLength = function(str, encoding) { - encoding = String(encoding || 'utf8').toLowerCase(); - - // Use native conversion when possible - if (Buffer.isNativeEncoding(encoding)) - return original.BufferByteLength.call(this, str, encoding); - - // Slow, I know, but we don't have a better way yet. - return iconv.encode(str, encoding).length; - } - - original.BufferToString = Buffer.prototype.toString; - Buffer.prototype.toString = function(encoding, start, end) { - encoding = String(encoding || 'utf8').toLowerCase(); - - // Use native conversion when possible - if (Buffer.isNativeEncoding(encoding)) - return original.BufferToString.call(this, encoding, start, end); - - // Otherwise, use our decoding method. - if (typeof start == 'undefined') start = 0; - if (typeof end == 'undefined') end = this.length; - return iconv.decode(this.slice(start, end), encoding); - } - - original.BufferWrite = Buffer.prototype.write; - Buffer.prototype.write = function(string, offset, length, encoding) { - var _offset = offset, _length = length, _encoding = encoding; - // Support both (string, offset, length, encoding) - // and the legacy (string, encoding, offset, length) - if (isFinite(offset)) { - if (!isFinite(length)) { - encoding = length; - length = undefined; - } - } else { // legacy - var swap = encoding; - encoding = offset; - offset = length; - length = swap; - } - - encoding = String(encoding || 'utf8').toLowerCase(); - - // Use native conversion when possible - if (Buffer.isNativeEncoding(encoding)) - return original.BufferWrite.call(this, string, _offset, _length, _encoding); - - offset = +offset || 0; - var remaining = this.length - offset; - if (!length) { - length = remaining; - } else { - length = +length; - if (length > remaining) { - length = remaining; - } - } - - if (string.length > 0 && (length < 0 || offset < 0)) - throw new RangeError('attempt to write beyond buffer bounds'); - - // Otherwise, use our encoding method. - var buf = iconv.encode(string, encoding); - if (buf.length < length) length = buf.length; - buf.copy(this, offset, 0, length); - return length; - - // TODO: Set _charsWritten. - } - - - // -- Readable ------------------------------------------------------------- - if (iconv.supportsStreams) { - var Readable = (__nccwpck_require__(12781).Readable); - - original.ReadableSetEncoding = Readable.prototype.setEncoding; - Readable.prototype.setEncoding = function setEncoding(enc, options) { - // Use our own decoder, it has the same interface. - // We cannot use original function as it doesn't handle BOM-s. - this._readableState.decoder = iconv.getDecoder(enc, options); - this._readableState.encoding = enc; - } - - Readable.prototype.collect = iconv._collect; - } - } - - // Remove iconv-lite Node primitive extensions. - iconv.undoExtendNodeEncodings = function undoExtendNodeEncodings() { - if (!iconv.supportsNodeEncodingsExtension) - return; - if (!original) - throw new Error("require('iconv-lite').undoExtendNodeEncodings(): Nothing to undo; extendNodeEncodings() is not called.") - - delete Buffer.isNativeEncoding; - - var SlowBuffer = (__nccwpck_require__(14300).SlowBuffer); - - SlowBuffer.prototype.toString = original.SlowBufferToString; - SlowBuffer.prototype.write = original.SlowBufferWrite; - - Buffer.isEncoding = original.BufferIsEncoding; - Buffer.byteLength = original.BufferByteLength; - Buffer.prototype.toString = original.BufferToString; - Buffer.prototype.write = original.BufferWrite; - - if (iconv.supportsStreams) { - var Readable = (__nccwpck_require__(12781).Readable); +if (!StringDecoder.prototype.end) // Node v0.8 doesn't have this method. + StringDecoder.prototype.end = function() {}; - Readable.prototype.setEncoding = original.ReadableSetEncoding; - delete Readable.prototype.collect; - } - original = undefined; - } +function InternalDecoder(options, codec) { + StringDecoder.call(this, codec.enc); } +InternalDecoder.prototype = StringDecoder.prototype; -/***/ }), - -/***/ 19032: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -// Some environments don't have global Buffer (e.g. React Native). -// Solution would be installing npm modules "buffer" and "stream" explicitly. -var Buffer = (__nccwpck_require__(15118).Buffer); - -var bomHandling = __nccwpck_require__(67961), - iconv = module.exports; - -// All codecs and aliases are kept here, keyed by encoding name/alias. -// They are lazy loaded in `iconv.getCodec` from `encodings/index.js`. -iconv.encodings = null; - -// Characters emitted in case of error. -iconv.defaultCharUnicode = '�'; -iconv.defaultCharSingleByte = '?'; - -// Public API. -iconv.encode = function encode(str, encoding, options) { - str = "" + (str || ""); // Ensure string. - var encoder = iconv.getEncoder(encoding, options); +//------------------------------------------------------------------------------ +// Encoder is mostly trivial - var res = encoder.write(str); - var trail = encoder.end(); - - return (trail && trail.length > 0) ? Buffer.concat([res, trail]) : res; +function InternalEncoder(options, codec) { + this.enc = codec.enc; } -iconv.decode = function decode(buf, encoding, options) { - if (typeof buf === 'string') { - if (!iconv.skipDecodeWarning) { - console.error('Iconv-lite warning: decode()-ing strings is deprecated. Refer to https://github.com/ashtuchkin/iconv-lite/wiki/Use-Buffers-when-decoding'); - iconv.skipDecodeWarning = true; - } - - buf = Buffer.from("" + (buf || ""), "binary"); // Ensure buffer. - } - - var decoder = iconv.getDecoder(encoding, options); - - var res = decoder.write(buf); - var trail = decoder.end(); - - return trail ? (res + trail) : res; +InternalEncoder.prototype.write = function(str) { + return Buffer.from(str, this.enc); } -iconv.encodingExists = function encodingExists(enc) { - try { - iconv.getCodec(enc); - return true; - } catch (e) { - return false; - } +InternalEncoder.prototype.end = function() { } -// Legacy aliases to convert functions -iconv.toEncoding = iconv.encode; -iconv.fromEncoding = iconv.decode; - -// Search for a codec in iconv.encodings. Cache codec data in iconv._codecDataCache. -iconv._codecDataCache = {}; -iconv.getCodec = function getCodec(encoding) { - if (!iconv.encodings) - iconv.encodings = __nccwpck_require__(82733); // Lazy load all encoding definitions. - - // Canonicalize encoding name: strip all non-alphanumeric chars and appended year. - var enc = iconv._canonicalizeEncoding(encoding); - // Traverse iconv.encodings to find actual codec. - var codecOptions = {}; - while (true) { - var codec = iconv._codecDataCache[enc]; - if (codec) - return codec; +//------------------------------------------------------------------------------ +// Except base64 encoder, which must keep its state. - var codecDef = iconv.encodings[enc]; +function InternalEncoderBase64(options, codec) { + this.prevStr = ''; +} - switch (typeof codecDef) { - case "string": // Direct alias to other encoding. - enc = codecDef; - break; +InternalEncoderBase64.prototype.write = function(str) { + str = this.prevStr + str; + var completeQuads = str.length - (str.length % 4); + this.prevStr = str.slice(completeQuads); + str = str.slice(0, completeQuads); - case "object": // Alias with options. Can be layered. - for (var key in codecDef) - codecOptions[key] = codecDef[key]; + return Buffer.from(str, "base64"); +} - if (!codecOptions.encodingName) - codecOptions.encodingName = enc; - - enc = codecDef.type; - break; +InternalEncoderBase64.prototype.end = function() { + return Buffer.from(this.prevStr, "base64"); +} - case "function": // Codec itself. - if (!codecOptions.encodingName) - codecOptions.encodingName = enc; - // The codec function must load all tables and return object with .encoder and .decoder methods. - // It'll be called only once (for each different options object). - codec = new codecDef(codecOptions, iconv); +//------------------------------------------------------------------------------ +// CESU-8 encoder is also special. - iconv._codecDataCache[codecOptions.encodingName] = codec; // Save it to be reused later. - return codec; +function InternalEncoderCesu8(options, codec) { +} - default: - throw new Error("Encoding not recognized: '" + encoding + "' (searched as: '"+enc+"')"); +InternalEncoderCesu8.prototype.write = function(str) { + var buf = Buffer.alloc(str.length * 3), bufIdx = 0; + for (var i = 0; i < str.length; i++) { + var charCode = str.charCodeAt(i); + // Naive implementation, but it works because CESU-8 is especially easy + // to convert from UTF-16 (which all JS strings are encoded in). + if (charCode < 0x80) + buf[bufIdx++] = charCode; + else if (charCode < 0x800) { + buf[bufIdx++] = 0xC0 + (charCode >>> 6); + buf[bufIdx++] = 0x80 + (charCode & 0x3f); + } + else { // charCode will always be < 0x10000 in javascript. + buf[bufIdx++] = 0xE0 + (charCode >>> 12); + buf[bufIdx++] = 0x80 + ((charCode >>> 6) & 0x3f); + buf[bufIdx++] = 0x80 + (charCode & 0x3f); } } + return buf.slice(0, bufIdx); } -iconv._canonicalizeEncoding = function(encoding) { - // Canonicalize encoding name: strip all non-alphanumeric chars and appended year. - return (''+encoding).toLowerCase().replace(/:\d{4}$|[^0-9a-z]/g, ""); -} - -iconv.getEncoder = function getEncoder(encoding, options) { - var codec = iconv.getCodec(encoding), - encoder = new codec.encoder(options, codec); - - if (codec.bomAware && options && options.addBOM) - encoder = new bomHandling.PrependBOM(encoder, options); - - return encoder; +InternalEncoderCesu8.prototype.end = function() { } -iconv.getDecoder = function getDecoder(encoding, options) { - var codec = iconv.getCodec(encoding), - decoder = new codec.decoder(options, codec); - - if (codec.bomAware && !(options && options.stripBOM === false)) - decoder = new bomHandling.StripBOM(decoder, options); +//------------------------------------------------------------------------------ +// CESU-8 decoder is not implemented in Node v4.0+ - return decoder; +function InternalDecoderCesu8(options, codec) { + this.acc = 0; + this.contBytes = 0; + this.accBytes = 0; + this.defaultCharUnicode = codec.defaultCharUnicode; } +InternalDecoderCesu8.prototype.write = function(buf) { + var acc = this.acc, contBytes = this.contBytes, accBytes = this.accBytes, + res = ''; + for (var i = 0; i < buf.length; i++) { + var curByte = buf[i]; + if ((curByte & 0xC0) !== 0x80) { // Leading byte + if (contBytes > 0) { // Previous code is invalid + res += this.defaultCharUnicode; + contBytes = 0; + } -// Load extensions in Node. All of them are omitted in Browserify build via 'browser' field in package.json. -var nodeVer = typeof process !== 'undefined' && process.versions && process.versions.node; -if (nodeVer) { - - // Load streaming support in Node v0.10+ - var nodeVerArr = nodeVer.split(".").map(Number); - if (nodeVerArr[0] > 0 || nodeVerArr[1] >= 10) { - __nccwpck_require__(76409)(iconv); + if (curByte < 0x80) { // Single-byte code + res += String.fromCharCode(curByte); + } else if (curByte < 0xE0) { // Two-byte code + acc = curByte & 0x1F; + contBytes = 1; accBytes = 1; + } else if (curByte < 0xF0) { // Three-byte code + acc = curByte & 0x0F; + contBytes = 2; accBytes = 1; + } else { // Four or more are not supported for CESU-8. + res += this.defaultCharUnicode; + } + } else { // Continuation byte + if (contBytes > 0) { // We're waiting for it. + acc = (acc << 6) | (curByte & 0x3f); + contBytes--; accBytes++; + if (contBytes === 0) { + // Check for overlong encoding, but support Modified UTF-8 (encoding NULL as C0 80) + if (accBytes === 2 && acc < 0x80 && acc > 0) + res += this.defaultCharUnicode; + else if (accBytes === 3 && acc < 0x800) + res += this.defaultCharUnicode; + else + // Actually add character. + res += String.fromCharCode(acc); + } + } else { // Unexpected continuation byte + res += this.defaultCharUnicode; + } + } } - - // Load Node primitive extensions. - __nccwpck_require__(30393)(iconv); + this.acc = acc; this.contBytes = contBytes; this.accBytes = accBytes; + return res; } -if (false) {} +InternalDecoderCesu8.prototype.end = function() { + var res = 0; + if (this.contBytes > 0) + res += this.defaultCharUnicode; + return res; +} /***/ }), -/***/ 76409: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 26657: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; +var Buffer = (__nccwpck_require__(15118).Buffer); -var Buffer = (__nccwpck_require__(14300).Buffer), - Transform = (__nccwpck_require__(12781).Transform); - +// Single-byte codec. Needs a 'chars' string parameter that contains 256 or 128 chars that +// correspond to encoded bytes (if 128 - then lower half is ASCII). -// == Exports ================================================================== -module.exports = function(iconv) { +exports._sbcs = SBCSCodec; +function SBCSCodec(codecOptions, iconv) { + if (!codecOptions) + throw new Error("SBCS codec is called without the data.") - // Additional Public API. - iconv.encodeStream = function encodeStream(encoding, options) { - return new IconvLiteEncoderStream(iconv.getEncoder(encoding, options), options); - } - - iconv.decodeStream = function decodeStream(encoding, options) { - return new IconvLiteDecoderStream(iconv.getDecoder(encoding, options), options); + // Prepare char buffer for decoding. + if (!codecOptions.chars || (codecOptions.chars.length !== 128 && codecOptions.chars.length !== 256)) + throw new Error("Encoding '"+codecOptions.type+"' has incorrect 'chars' (must be of len 128 or 256)"); + + if (codecOptions.chars.length === 128) { + var asciiString = ""; + for (var i = 0; i < 128; i++) + asciiString += String.fromCharCode(i); + codecOptions.chars = asciiString + codecOptions.chars; } - iconv.supportsStreams = true; - - - // Not published yet. - iconv.IconvLiteEncoderStream = IconvLiteEncoderStream; - iconv.IconvLiteDecoderStream = IconvLiteDecoderStream; - iconv._collect = IconvLiteDecoderStream.prototype.collect; -}; + this.decodeBuf = Buffer.from(codecOptions.chars, 'ucs2'); + + // Encoding buffer. + var encodeBuf = Buffer.alloc(65536, iconv.defaultCharSingleByte.charCodeAt(0)); + for (var i = 0; i < codecOptions.chars.length; i++) + encodeBuf[codecOptions.chars.charCodeAt(i)] = i; -// == Encoder stream ======================================================= -function IconvLiteEncoderStream(conv, options) { - this.conv = conv; - options = options || {}; - options.decodeStrings = false; // We accept only strings, so we don't need to decode them. - Transform.call(this, options); + this.encodeBuf = encodeBuf; } -IconvLiteEncoderStream.prototype = Object.create(Transform.prototype, { - constructor: { value: IconvLiteEncoderStream } -}); +SBCSCodec.prototype.encoder = SBCSEncoder; +SBCSCodec.prototype.decoder = SBCSDecoder; -IconvLiteEncoderStream.prototype._transform = function(chunk, encoding, done) { - if (typeof chunk != 'string') - return done(new Error("Iconv encoding stream needs strings as its input.")); - try { - var res = this.conv.write(chunk); - if (res && res.length) this.push(res); - done(); - } - catch (e) { - done(e); - } -} -IconvLiteEncoderStream.prototype._flush = function(done) { - try { - var res = this.conv.end(); - if (res && res.length) this.push(res); - done(); - } - catch (e) { - done(e); - } +function SBCSEncoder(options, codec) { + this.encodeBuf = codec.encodeBuf; } -IconvLiteEncoderStream.prototype.collect = function(cb) { - var chunks = []; - this.on('error', cb); - this.on('data', function(chunk) { chunks.push(chunk); }); - this.on('end', function() { - cb(null, Buffer.concat(chunks)); - }); - return this; +SBCSEncoder.prototype.write = function(str) { + var buf = Buffer.alloc(str.length); + for (var i = 0; i < str.length; i++) + buf[i] = this.encodeBuf[str.charCodeAt(i)]; + + return buf; } - -// == Decoder stream ======================================================= -function IconvLiteDecoderStream(conv, options) { - this.conv = conv; - options = options || {}; - options.encoding = this.encoding = 'utf8'; // We output strings. - Transform.call(this, options); +SBCSEncoder.prototype.end = function() { } -IconvLiteDecoderStream.prototype = Object.create(Transform.prototype, { - constructor: { value: IconvLiteDecoderStream } -}); -IconvLiteDecoderStream.prototype._transform = function(chunk, encoding, done) { - if (!Buffer.isBuffer(chunk)) - return done(new Error("Iconv decoding stream needs buffers as its input.")); - try { - var res = this.conv.write(chunk); - if (res && res.length) this.push(res, this.encoding); - done(); - } - catch (e) { - done(e); - } +function SBCSDecoder(options, codec) { + this.decodeBuf = codec.decodeBuf; } -IconvLiteDecoderStream.prototype._flush = function(done) { - try { - var res = this.conv.end(); - if (res && res.length) this.push(res, this.encoding); - done(); - } - catch (e) { - done(e); +SBCSDecoder.prototype.write = function(buf) { + // Strings are immutable in JS -> we use ucs2 buffer to speed up computations. + var decodeBuf = this.decodeBuf; + var newBuf = Buffer.alloc(buf.length*2); + var idx1 = 0, idx2 = 0; + for (var i = 0; i < buf.length; i++) { + idx1 = buf[i]*2; idx2 = i*2; + newBuf[idx2] = decodeBuf[idx1]; + newBuf[idx2+1] = decodeBuf[idx1+1]; } + return newBuf.toString('ucs2'); } -IconvLiteDecoderStream.prototype.collect = function(cb) { - var res = ''; - this.on('error', cb); - this.on('data', function(chunk) { res += chunk; }); - this.on('end', function() { - cb(null, res); - }); - return this; +SBCSDecoder.prototype.end = function() { } - /***/ }), -/***/ 91230: +/***/ 21012: /***/ ((module) => { -// A simple implementation of make-array -function makeArray (subject) { - return Array.isArray(subject) - ? subject - : [subject] +"use strict"; + + +// Generated data for sbcs codec. Don't edit manually. Regenerate using generation/gen-sbcs.js script. +module.exports = { + "437": "cp437", + "737": "cp737", + "775": "cp775", + "850": "cp850", + "852": "cp852", + "855": "cp855", + "856": "cp856", + "857": "cp857", + "858": "cp858", + "860": "cp860", + "861": "cp861", + "862": "cp862", + "863": "cp863", + "864": "cp864", + "865": "cp865", + "866": "cp866", + "869": "cp869", + "874": "windows874", + "922": "cp922", + "1046": "cp1046", + "1124": "cp1124", + "1125": "cp1125", + "1129": "cp1129", + "1133": "cp1133", + "1161": "cp1161", + "1162": "cp1162", + "1163": "cp1163", + "1250": "windows1250", + "1251": "windows1251", + "1252": "windows1252", + "1253": "windows1253", + "1254": "windows1254", + "1255": "windows1255", + "1256": "windows1256", + "1257": "windows1257", + "1258": "windows1258", + "28591": "iso88591", + "28592": "iso88592", + "28593": "iso88593", + "28594": "iso88594", + "28595": "iso88595", + "28596": "iso88596", + "28597": "iso88597", + "28598": "iso88598", + "28599": "iso88599", + "28600": "iso885910", + "28601": "iso885911", + "28603": "iso885913", + "28604": "iso885914", + "28605": "iso885915", + "28606": "iso885916", + "windows874": { + "type": "_sbcs", + "chars": "€����…�����������‘’“”•–—�������� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" + }, + "win874": "windows874", + "cp874": "windows874", + "windows1250": { + "type": "_sbcs", + "chars": "€�‚�„…†‡�‰Š‹ŚŤŽŹ�‘’“”•–—�™š›śťžź ˇ˘Ł¤Ą¦§¨©Ş«¬­®Ż°±˛ł´µ¶·¸ąş»Ľ˝ľżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙" + }, + "win1250": "windows1250", + "cp1250": "windows1250", + "windows1251": { + "type": "_sbcs", + "chars": "ЂЃ‚ѓ„…†‡€‰Љ‹ЊЌЋЏђ‘’“”•–—�™љ›њќћџ ЎўЈ¤Ґ¦§Ё©Є«¬­®Ї°±Ііґµ¶·ё№є»јЅѕїАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" + }, + "win1251": "windows1251", + "cp1251": "windows1251", + "windows1252": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡ˆ‰Š‹Œ�Ž��‘’“”•–—˜™š›œ�žŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "win1252": "windows1252", + "cp1252": "windows1252", + "windows1253": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡�‰�‹�����‘’“”•–—�™�›���� ΅Ά£¤¥¦§¨©�«¬­®―°±²³΄µ¶·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�" + }, + "win1253": "windows1253", + "cp1253": "windows1253", + "windows1254": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡ˆ‰Š‹Œ����‘’“”•–—˜™š›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖ×ØÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ" + }, + "win1254": "windows1254", + "cp1254": "windows1254", + "windows1255": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡ˆ‰�‹�����‘’“”•–—˜™�›���� ¡¢£₪¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾¿ְֱֲֳִֵֶַָֹֺֻּֽ־ֿ׀ׁׂ׃װױײ׳״�������אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�" + }, + "win1255": "windows1255", + "cp1255": "windows1255", + "windows1256": { + "type": "_sbcs", + "chars": "€پ‚ƒ„…†‡ˆ‰ٹ‹Œچژڈگ‘’“”•–—ک™ڑ›œ‌‍ں ،¢£¤¥¦§¨©ھ«¬­®¯°±²³´µ¶·¸¹؛»¼½¾؟ہءآأؤإئابةتثجحخدذرزسشصض×طظعغـفقكàلâمنهوçèéêëىيîïًٌٍَôُِ÷ّùْûü‎‏ے" + }, + "win1256": "windows1256", + "cp1256": "windows1256", + "windows1257": { + "type": "_sbcs", + "chars": "€�‚�„…†‡�‰�‹�¨ˇ¸�‘’“”•–—�™�›�¯˛� �¢£¤�¦§Ø©Ŗ«¬­®Æ°±²³´µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž˙" + }, + "win1257": "windows1257", + "cp1257": "windows1257", + "windows1258": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡ˆ‰�‹Œ����‘’“”•–—˜™�›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖ×ØÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" + }, + "win1258": "windows1258", + "cp1258": "windows1258", + "iso88591": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "cp28591": "iso88591", + "iso88592": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ą˘Ł¤ĽŚ§¨ŠŞŤŹ­ŽŻ°ą˛ł´ľśˇ¸šşťź˝žżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙" + }, + "cp28592": "iso88592", + "iso88593": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ħ˘£¤�Ĥ§¨İŞĞĴ­�Ż°ħ²³´µĥ·¸ışğĵ½�żÀÁÂ�ÄĊĈÇÈÉÊËÌÍÎÏ�ÑÒÓÔĠÖ×ĜÙÚÛÜŬŜßàáâ�äċĉçèéêëìíîï�ñòóôġö÷ĝùúûüŭŝ˙" + }, + "cp28593": "iso88593", + "iso88594": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄĸŖ¤ĨĻ§¨ŠĒĢŦ­Ž¯°ą˛ŗ´ĩļˇ¸šēģŧŊžŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎĪĐŅŌĶÔÕÖ×ØŲÚÛÜŨŪßāáâãäåæįčéęëėíîīđņōķôõö÷øųúûüũū˙" + }, + "cp28594": "iso88594", + "iso88595": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ЁЂЃЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђѓєѕіїјљњћќ§ўџ" + }, + "cp28595": "iso88595", + "iso88596": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ���¤�������،­�������������؛���؟�ءآأؤإئابةتثجحخدذرزسشصضطظعغ�����ـفقكلمنهوىيًٌٍَُِّْ�������������" + }, + "cp28596": "iso88596", + "iso88597": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ‘’£€₯¦§¨©ͺ«¬­�―°±²³΄΅Ά·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�" + }, + "cp28597": "iso88597", + "iso88598": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ �¢£¤¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾��������������������������������‗אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�" + }, + "cp28598": "iso88598", + "iso88599": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖ×ØÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ" + }, + "cp28599": "iso88599", + "iso885910": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄĒĢĪĨĶ§ĻĐŠŦŽ­ŪŊ°ąēģīĩķ·ļđšŧž―ūŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎÏÐŅŌÓÔÕÖŨØŲÚÛÜÝÞßāáâãäåæįčéęëėíîïðņōóôõöũøųúûüýþĸ" + }, + "cp28600": "iso885910", + "iso885911": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" + }, + "cp28601": "iso885911", + "iso885913": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ”¢£¤„¦§Ø©Ŗ«¬­®Æ°±²³“µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž’" + }, + "cp28603": "iso885913", + "iso885914": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ḃḃ£ĊċḊ§Ẁ©ẂḋỲ­®ŸḞḟĠġṀṁ¶ṖẁṗẃṠỳẄẅṡÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŴÑÒÓÔÕÖṪØÙÚÛÜÝŶßàáâãäåæçèéêëìíîïŵñòóôõöṫøùúûüýŷÿ" + }, + "cp28604": "iso885914", + "iso885915": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£€¥Š§š©ª«¬­®¯°±²³Žµ¶·ž¹º»ŒœŸ¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "cp28605": "iso885915", + "iso885916": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄąŁ€„Š§š©Ș«Ź­źŻ°±ČłŽ”¶·žčș»ŒœŸżÀÁÂĂÄĆÆÇÈÉÊËÌÍÎÏĐŃÒÓÔŐÖŚŰÙÚÛÜĘȚßàáâăäćæçèéêëìíîïđńòóôőöśűùúûüęțÿ" + }, + "cp28606": "iso885916", + "cp437": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm437": "cp437", + "csibm437": "cp437", + "cp737": { + "type": "_sbcs", + "chars": "ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩαβγδεζηθικλμνξοπρσςτυφχψ░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀ωάέήϊίόύϋώΆΈΉΊΌΎΏ±≥≤ΪΫ÷≈°∙·√ⁿ²■ " + }, + "ibm737": "cp737", + "csibm737": "cp737", + "cp775": { + "type": "_sbcs", + "chars": "ĆüéāäģåćłēŖŗīŹÄÅÉæÆōöĢ¢ŚśÖÜø£ØפĀĪóŻżź”¦©®¬½¼Ł«»░▒▓│┤ĄČĘĖ╣║╗╝ĮŠ┐└┴┬├─┼ŲŪ╚╔╩╦╠═╬Žąčęėįšųūž┘┌█▄▌▐▀ÓßŌŃõÕµńĶķĻļņĒŅ’­±“¾¶§÷„°∙·¹³²■ " + }, + "ibm775": "cp775", + "csibm775": "cp775", + "cp850": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø׃áíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈıÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´­±‗¾¶§÷¸°¨·¹³²■ " + }, + "ibm850": "cp850", + "csibm850": "cp850", + "cp852": { + "type": "_sbcs", + "chars": "ÇüéâäůćçłëŐőîŹÄĆÉĹĺôöĽľŚśÖÜŤťŁ×čáíóúĄąŽžĘ꬟Ⱥ«»░▒▓│┤ÁÂĚŞ╣║╗╝Żż┐└┴┬├─┼Ăă╚╔╩╦╠═╬¤đĐĎËďŇÍÎě┘┌█▄ŢŮ▀ÓßÔŃńňŠšŔÚŕŰýÝţ´­˝˛ˇ˘§÷¸°¨˙űŘř■ " + }, + "ibm852": "cp852", + "csibm852": "cp852", + "cp855": { + "type": "_sbcs", + "chars": "ђЂѓЃёЁєЄѕЅіІїЇјЈљЉњЊћЋќЌўЎџЏюЮъЪаАбБцЦдДеЕфФгГ«»░▒▓│┤хХиИ╣║╗╝йЙ┐└┴┬├─┼кК╚╔╩╦╠═╬¤лЛмМнНоОп┘┌█▄Пя▀ЯрРсСтТуУжЖвВьЬ№­ыЫзЗшШэЭщЩчЧ§■ " + }, + "ibm855": "cp855", + "csibm855": "cp855", + "cp856": { + "type": "_sbcs", + "chars": "אבגדהוזחטיךכלםמןנסעףפץצקרשת�£�×����������®¬½¼�«»░▒▓│┤���©╣║╗╝¢¥┐└┴┬├─┼��╚╔╩╦╠═╬¤���������┘┌█▄¦�▀������µ�������¯´­±‗¾¶§÷¸°¨·¹³²■ " + }, + "ibm856": "cp856", + "csibm856": "cp856", + "cp857": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîıÄÅÉæÆôöòûùİÖÜø£ØŞşáíóúñÑĞ𿮬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ºªÊËÈ�ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµ�×ÚÛÙìÿ¯´­±�¾¶§÷¸°¨·¹³²■ " + }, + "ibm857": "cp857", + "csibm857": "cp857", + "cp858": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø׃áíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈ€ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´­±‗¾¶§÷¸°¨·¹³²■ " + }, + "ibm858": "cp858", + "csibm858": "cp858", + "cp860": { + "type": "_sbcs", + "chars": "ÇüéâãàÁçêÊèÍÔìÃÂÉÀÈôõòÚùÌÕÜ¢£Ù₧ÓáíóúñѪº¿Ò¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm860": "cp860", + "csibm860": "cp860", + "cp861": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèÐðÞÄÅÉæÆôöþûÝýÖÜø£Ø₧ƒáíóúÁÍÓÚ¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm861": "cp861", + "csibm861": "cp861", + "cp862": { + "type": "_sbcs", + "chars": "אבגדהוזחטיךכלםמןנסעףפץצקרשת¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm862": "cp862", + "csibm862": "cp862", + "cp863": { + "type": "_sbcs", + "chars": "ÇüéâÂà¶çêëèïî‗À§ÉÈÊôËÏûù¤ÔÜ¢£ÙÛƒ¦´óú¨¸³¯Î⌐¬½¼¾«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm863": "cp863", + "csibm863": "cp863", + "cp864": { + "type": "_sbcs", + "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$٪&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~°·∙√▒─│┼┤┬├┴┐┌└┘β∞φ±½¼≈«»ﻷﻸ��ﻻﻼ� ­ﺂ£¤ﺄ��ﺎﺏﺕﺙ،ﺝﺡﺥ٠١٢٣٤٥٦٧٨٩ﻑ؛ﺱﺵﺹ؟¢ﺀﺁﺃﺅﻊﺋﺍﺑﺓﺗﺛﺟﺣﺧﺩﺫﺭﺯﺳﺷﺻﺿﻁﻅﻋﻏ¦¬÷×ﻉـﻓﻗﻛﻟﻣﻧﻫﻭﻯﻳﺽﻌﻎﻍﻡﹽّﻥﻩﻬﻰﻲﻐﻕﻵﻶﻝﻙﻱ■�" + }, + "ibm864": "cp864", + "csibm864": "cp864", + "cp865": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø₧ƒáíóúñѪº¿⌐¬½¼¡«¤░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm865": "cp865", + "csibm865": "cp865", + "cp866": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№¤■ " + }, + "ibm866": "cp866", + "csibm866": "cp866", + "cp869": { + "type": "_sbcs", + "chars": "������Ά�·¬¦‘’Έ―ΉΊΪΌ��ΎΫ©Ώ²³ά£έήίϊΐόύΑΒΓΔΕΖΗ½ΘΙ«»░▒▓│┤ΚΛΜΝ╣║╗╝ΞΟ┐└┴┬├─┼ΠΡ╚╔╩╦╠═╬ΣΤΥΦΧΨΩαβγ┘┌█▄δε▀ζηθικλμνξοπρσςτ΄­±υφχ§ψ΅°¨ωϋΰώ■ " + }, + "ibm869": "cp869", + "csibm869": "cp869", + "cp922": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®‾°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŠÑÒÓÔÕÖ×ØÙÚÛÜÝŽßàáâãäåæçèéêëìíîïšñòóôõö÷øùúûüýžÿ" + }, + "ibm922": "cp922", + "csibm922": "cp922", + "cp1046": { + "type": "_sbcs", + "chars": "ﺈ×÷ﹱˆ■│─┐┌└┘ﹹﹻﹽﹿﹷﺊﻰﻳﻲﻎﻏﻐﻶﻸﻺﻼ ¤ﺋﺑﺗﺛﺟﺣ،­ﺧﺳ٠١٢٣٤٥٦٧٨٩ﺷ؛ﺻﺿﻊ؟ﻋءآأؤإئابةتثجحخدذرزسشصضطﻇعغﻌﺂﺄﺎﻓـفقكلمنهوىيًٌٍَُِّْﻗﻛﻟﻵﻷﻹﻻﻣﻧﻬﻩ�" + }, + "ibm1046": "cp1046", + "csibm1046": "cp1046", + "cp1124": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ЁЂҐЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђґєѕіїјљњћќ§ўџ" + }, + "ibm1124": "cp1124", + "csibm1124": "cp1124", + "cp1125": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёҐґЄєІіЇї·√№¤■ " + }, + "ibm1125": "cp1125", + "csibm1125": "cp1125", + "cp1129": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§œ©ª«¬­®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖ×ØÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" + }, + "ibm1129": "cp1129", + "csibm1129": "cp1129", + "cp1133": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ກຂຄງຈສຊຍດຕຖທນບປຜຝພຟມຢຣລວຫອຮ���ຯະາຳິີຶືຸູຼັົຽ���ເແໂໃໄ່້໊໋໌ໍໆ�ໜໝ₭����������������໐໑໒໓໔໕໖໗໘໙��¢¬¦�" + }, + "ibm1133": "cp1133", + "csibm1133": "cp1133", + "cp1161": { + "type": "_sbcs", + "chars": "��������������������������������่กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู้๊๋€฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛¢¬¦ " + }, + "ibm1161": "cp1161", + "csibm1161": "cp1161", + "cp1162": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" + }, + "ibm1162": "cp1162", + "csibm1162": "cp1162", + "cp1163": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£€¥¦§œ©ª«¬­®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖ×ØÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" + }, + "ibm1163": "cp1163", + "csibm1163": "cp1163", + "maccroatian": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø¿¡¬√ƒ≈Ć«Č… ÀÃÕŒœĐ—“”‘’÷◊�©⁄¤‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ" + }, + "maccyrillic": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°¢£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµ∂ЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤" + }, + "macgreek": { + "type": "_sbcs", + "chars": "Ĺ²É³ÖÜ΅àâä΄¨çéèê룙î‰ôö¦­ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩάΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ�" + }, + "maciceland": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüÝ°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" + }, + "macroman": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" + }, + "macromania": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂŞ∞±≤≥¥µ∂∑∏π∫ªºΩăş¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›Ţţ‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" + }, + "macthai": { + "type": "_sbcs", + "chars": "«»…“”�•‘’� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู​–—฿เแโใไๅๆ็่้๊๋์ํ™๏๐๑๒๓๔๕๖๗๘๙®©����" + }, + "macturkish": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙ�ˆ˜¯˘˙˚¸˝˛ˇ" + }, + "macukraine": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤" + }, + "koi8r": { + "type": "_sbcs", + "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ё╓╔╕╖╗╘╙╚╛╜╝╞╟╠╡Ё╢╣╤╥╦╧╨╩╪╫╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" + }, + "koi8u": { + "type": "_sbcs", + "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґ╝╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪Ґ╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" + }, + "koi8ru": { + "type": "_sbcs", + "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґў╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪ҐЎ©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" + }, + "koi8t": { + "type": "_sbcs", + "chars": "қғ‚Ғ„…†‡�‰ҳ‹ҲҷҶ�Қ‘’“”•–—�™�›�����ӯӮё¤ӣ¦§���«¬­®�°±²Ё�Ӣ¶·�№�»���©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" + }, + "armscii8": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ �և։)(»«—.՝,-֊…՜՛՞ԱաԲբԳգԴդԵեԶզԷէԸըԹթԺժԻիԼլԽխԾծԿկՀհՁձՂղՃճՄմՅյՆնՇշՈոՉչՊպՋջՌռՍսՎվՏտՐրՑցՒւՓփՔքՕօՖֆ՚�" + }, + "rk1048": { + "type": "_sbcs", + "chars": "ЂЃ‚ѓ„…†‡€‰Љ‹ЊҚҺЏђ‘’“”•–—�™љ›њқһџ ҰұӘ¤Ө¦§Ё©Ғ«¬­®Ү°±Ііөµ¶·ё№ғ»әҢңүАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" + }, + "tcvn": { + "type": "_sbcs", + "chars": "\u0000ÚỤ\u0003ỪỬỮ\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010ỨỰỲỶỸÝỴ\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ÀẢÃÁẠẶẬÈẺẼÉẸỆÌỈĨÍỊÒỎÕÓỌỘỜỞỠỚỢÙỦŨ ĂÂÊÔƠƯĐăâêôơưđẶ̀̀̉̃́àảãáạẲằẳẵắẴẮẦẨẪẤỀặầẩẫấậèỂẻẽéẹềểễếệìỉỄẾỒĩíịòỔỏõóọồổỗốộờởỡớợùỖủũúụừửữứựỳỷỹýỵỐ" + }, + "georgianacademy": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზთიკლმნოპჟრსტუფქღყშჩცძწჭხჯჰჱჲჳჴჵჶçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "georgianps": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზჱთიკლმნჲოპჟრსტჳუფქღყშჩცძწჭხჴჯჰჵæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "pt154": { + "type": "_sbcs", + "chars": "ҖҒӮғ„…ҶҮҲүҠӢҢҚҺҸҗ‘’“”•–—ҳҷҡӣңқһҹ ЎўЈӨҘҰ§Ё©Ә«¬ӯ®Ҝ°ұІіҙө¶·ё№ә»јҪҫҝАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" + }, + "viscii": { + "type": "_sbcs", + "chars": "\u0000\u0001Ẳ\u0003\u0004ẴẪ\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013Ỷ\u0015\u0016\u0017\u0018Ỹ\u001a\u001b\u001c\u001dỴ\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ẠẮẰẶẤẦẨẬẼẸẾỀỂỄỆỐỒỔỖỘỢỚỜỞỊỎỌỈỦŨỤỲÕắằặấầẩậẽẹếềểễệốồổỗỠƠộờởịỰỨỪỬơớƯÀÁÂÃẢĂẳẵÈÉÊẺÌÍĨỳĐứÒÓÔạỷừửÙÚỹỵÝỡưàáâãảăữẫèéêẻìíĩỉđựòóôõỏọụùúũủýợỮ" + }, + "iso646cn": { + "type": "_sbcs", + "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#¥%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������" + }, + "iso646jp": { + "type": "_sbcs", + "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[¥]^_`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������" + }, + "hproman8": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ÀÂÈÊËÎÏ´ˋˆ¨˜ÙÛ₤¯Ýý°ÇçÑñ¡¿¤£¥§ƒ¢âêôûáéóúàèòùäëöüÅîØÆåíøæÄìÖÜÉïßÔÁÃãÐðÍÌÓÒÕõŠšÚŸÿÞþ·µ¶¾—¼½ªº«■»±�" + }, + "macintosh": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" + }, + "ascii": { + "type": "_sbcs", + "chars": "��������������������������������������������������������������������������������������������������������������������������������" + }, + "tis620": { + "type": "_sbcs", + "chars": "���������������������������������กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" + } } -const EMPTY = '' -const SPACE = ' ' -const ESCAPE = '\\' -const REGEX_TEST_BLANK_LINE = /^\s+$/ -const REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/ -const REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\#/ -const REGEX_SPLITALL_CRLF = /\r?\n/g -// /foo, -// ./foo, -// ../foo, -// . -// .. -const REGEX_TEST_INVALID_PATH = /^\.*\/|^\.+$/ +/***/ }), -const SLASH = '/' -const KEY_IGNORE = typeof Symbol !== 'undefined' - ? Symbol.for('node-ignore') - /* istanbul ignore next */ - : 'node-ignore' +/***/ 41080: +/***/ ((module) => { -const define = (object, key, value) => - Object.defineProperty(object, key, {value}) +"use strict"; -const REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g -const RETURN_FALSE = () => false +// Manually added data to be used by sbcs codec in addition to generated one. -// Sanitize the range of a regular expression -// The cases are complicated, see test cases for details -const sanitizeRange = range => range.replace( - REGEX_REGEXP_RANGE, - (match, from, to) => from.charCodeAt(0) <= to.charCodeAt(0) - ? match - // Invalid range (out of order) which is ok for gitignore rules but - // fatal for JavaScript regular expression, so eliminate it. - : EMPTY -) +module.exports = { + // Not supported by iconv, not sure why. + "10029": "maccenteuro", + "maccenteuro": { + "type": "_sbcs", + "chars": "ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ" + }, -// See fixtures #59 -const cleanRangeBackSlash = slashes => { - const {length} = slashes - return slashes.slice(0, length - length % 2) -} + "808": "cp808", + "ibm808": "cp808", + "cp808": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№€■ " + }, -// > If the pattern ends with a slash, -// > it is removed for the purpose of the following description, -// > but it would only find a match with a directory. -// > In other words, foo/ will match a directory foo and paths underneath it, -// > but will not match a regular file or a symbolic link foo -// > (this is consistent with the way how pathspec works in general in Git). -// '`foo/`' will not match regular file '`foo`' or symbolic link '`foo`' -// -> ignore-rules will not deal with it, because it costs extra `fs.stat` call -// you could use option `mark: true` with `glob` - -// '`foo/`' should not continue with the '`..`' -const REPLACERS = [ - - // > Trailing spaces are ignored unless they are quoted with backslash ("\") - [ - // (a\ ) -> (a ) - // (a ) -> (a) - // (a \ ) -> (a ) - /\\?\s+$/, - match => match.indexOf('\\') === 0 - ? SPACE - : EMPTY - ], - - // replace (\ ) with ' ' - [ - /\\\s/g, - () => SPACE - ], - - // Escape metacharacters - // which is written down by users but means special for regular expressions. - - // > There are 12 characters with special meanings: - // > - the backslash \, - // > - the caret ^, - // > - the dollar sign $, - // > - the period or dot ., - // > - the vertical bar or pipe symbol |, - // > - the question mark ?, - // > - the asterisk or star *, - // > - the plus sign +, - // > - the opening parenthesis (, - // > - the closing parenthesis ), - // > - and the opening square bracket [, - // > - the opening curly brace {, - // > These special characters are often called "metacharacters". - [ - /[\\$.|*+(){^]/g, - match => `\\${match}` - ], - - [ - // > a question mark (?) matches a single character - /(?!\\)\?/g, - () => '[^/]' - ], - - // leading slash - [ - - // > A leading slash matches the beginning of the pathname. - // > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c". - // A leading slash matches the beginning of the pathname - /^\//, - () => '^' - ], - - // replace special metacharacter slash after the leading slash - [ - /\//g, - () => '\\/' - ], - - [ - // > A leading "**" followed by a slash means match in all directories. - // > For example, "**/foo" matches file or directory "foo" anywhere, - // > the same as pattern "foo". - // > "**/foo/bar" matches file or directory "bar" anywhere that is directly - // > under directory "foo". - // Notice that the '*'s have been replaced as '\\*' - /^\^*\\\*\\\*\\\//, - - // '**/foo' <-> 'foo' - () => '^(?:.*\\/)?' - ], - - // starting - [ - // there will be no leading '/' - // (which has been replaced by section "leading slash") - // If starts with '**', adding a '^' to the regular expression also works - /^(?=[^^])/, - function startingReplacer () { - // If has a slash `/` at the beginning or middle - return !/\/(?!$)/.test(this) - // > Prior to 2.22.1 - // > If the pattern does not contain a slash /, - // > Git treats it as a shell glob pattern - // Actually, if there is only a trailing slash, - // git also treats it as a shell glob pattern - - // After 2.22.1 (compatible but clearer) - // > If there is a separator at the beginning or middle (or both) - // > of the pattern, then the pattern is relative to the directory - // > level of the particular .gitignore file itself. - // > Otherwise the pattern may also match at any level below - // > the .gitignore level. - ? '(?:^|\\/)' - - // > Otherwise, Git treats the pattern as a shell glob suitable for - // > consumption by fnmatch(3) - : '^' - } - ], - - // two globstars - [ - // Use lookahead assertions so that we could match more than one `'/**'` - /\\\/\\\*\\\*(?=\\\/|$)/g, - - // Zero, one or several directories - // should not use '*', or it will be replaced by the next replacer - - // Check if it is not the last `'/**'` - (_, index, str) => index + 6 < str.length - - // case: /**/ - // > A slash followed by two consecutive asterisks then a slash matches - // > zero or more directories. - // > For example, "a/**/b" matches "a/b", "a/x/b", "a/x/y/b" and so on. - // '/**/' - ? '(?:\\/[^\\/]+)*' - - // case: /** - // > A trailing `"/**"` matches everything inside. - - // #21: everything inside but it should not include the current folder - : '\\/.+' - ], - - // intermediate wildcards - [ - // Never replace escaped '*' - // ignore rule '\*' will match the path '*' - - // 'abc.*/' -> go - // 'abc.*' -> skip this rule - /(^|[^\\]+)\\\*(?=.+)/g, - - // '*.js' matches '.js' - // '*.js' doesn't match 'abc' - (_, p1) => `${p1}[^\\/]*` - ], - - [ - // unescape, revert step 3 except for back slash - // For example, if a user escape a '\\*', - // after step 3, the result will be '\\\\\\*' - /\\\\\\(?=[$.|*+(){^])/g, - () => ESCAPE - ], - - [ - // '\\\\' -> '\\' - /\\\\/g, - () => ESCAPE - ], - - [ - // > The range notation, e.g. [a-zA-Z], - // > can be used to match one of the characters in a range. - - // `\` is escaped by step 3 - /(\\)?\[([^\]/]*?)(\\*)($|\])/g, - (match, leadEscape, range, endEscape, close) => leadEscape === ESCAPE - // '\\[bar]' -> '\\\\[bar\\]' - ? `\\[${range}${cleanRangeBackSlash(endEscape)}${close}` - : close === ']' - ? endEscape.length % 2 === 0 - // A normal case, and it is a range notation - // '[bar]' - // '[bar\\\\]' - ? `[${sanitizeRange(range)}${endEscape}]` - // Invalid range notaton - // '[bar\\]' -> '[bar\\\\]' - : '[]' - : '[]' - ], - - // ending - [ - // 'js' will not match 'js.' - // 'ab' will not match 'abc' - /(?:[^*])$/, - - // WTF! - // https://git-scm.com/docs/gitignore - // changes in [2.22.1](https://git-scm.com/docs/gitignore/2.22.1) - // which re-fixes #24, #38 - - // > If there is a separator at the end of the pattern then the pattern - // > will only match directories, otherwise the pattern can match both - // > files and directories. - - // 'js*' will not match 'a.js' - // 'js/' will not match 'a.js' - // 'js' will match 'a.js' and 'a.js/' - match => /\/$/.test(match) - // foo/ will not match 'foo' - ? `${match}$` - // foo matches 'foo' and 'foo/' - : `${match}(?=$|\\/$)` - ], - - // trailing wildcard - [ - /(\^|\\\/)?\\\*$/, - (_, p1) => { - const prefix = p1 - // '\^': - // '/*' does not match EMPTY - // '/*' does not match everything - - // '\\\/': - // 'abc/*' does not match 'abc/' - ? `${p1}[^/]+` - - // 'a*' matches 'a' - // 'a*' matches 'aa' - : '[^/]*' - - return `${prefix}(?=$|\\/$)` - } - ], -] - -// A simple cache, because an ignore rule only has only one certain meaning -const regexCache = Object.create(null) - -// @param {pattern} -const makeRegex = (pattern, ignoreCase) => { - let source = regexCache[pattern] - - if (!source) { - source = REPLACERS.reduce( - (prev, current) => prev.replace(current[0], current[1].bind(pattern)), - pattern - ) - regexCache[pattern] = source - } - - return ignoreCase - ? new RegExp(source, 'i') - : new RegExp(source) -} - -const isString = subject => typeof subject === 'string' - -// > A blank line matches no files, so it can serve as a separator for readability. -const checkPattern = pattern => pattern - && isString(pattern) - && !REGEX_TEST_BLANK_LINE.test(pattern) - - // > A line starting with # serves as a comment. - && pattern.indexOf('#') !== 0 - -const splitPattern = pattern => pattern.split(REGEX_SPLITALL_CRLF) - -class IgnoreRule { - constructor ( - origin, - pattern, - negative, - regex - ) { - this.origin = origin - this.pattern = pattern - this.negative = negative - this.regex = regex - } -} - -const createRule = (pattern, ignoreCase) => { - const origin = pattern - let negative = false - - // > An optional prefix "!" which negates the pattern; - if (pattern.indexOf('!') === 0) { - negative = true - pattern = pattern.substr(1) - } - - pattern = pattern - // > Put a backslash ("\") in front of the first "!" for patterns that - // > begin with a literal "!", for example, `"\!important!.txt"`. - .replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, '!') - // > Put a backslash ("\") in front of the first hash for patterns that - // > begin with a hash. - .replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, '#') - - const regex = makeRegex(pattern, ignoreCase) - - return new IgnoreRule( - origin, - pattern, - negative, - regex - ) -} - -const throwError = (message, Ctor) => { - throw new Ctor(message) -} - -const checkPath = (path, originalPath, doThrow) => { - if (!isString(path)) { - return doThrow( - `path must be a string, but got \`${originalPath}\``, - TypeError - ) - } - - // We don't know if we should ignore EMPTY, so throw - if (!path) { - return doThrow(`path must not be empty`, TypeError) - } - - // Check if it is a relative path - if (checkPath.isNotRelative(path)) { - const r = '`path.relative()`d' - return doThrow( - `path should be a ${r} string, but got "${originalPath}"`, - RangeError - ) - } - - return true -} - -const isNotRelative = path => REGEX_TEST_INVALID_PATH.test(path) + "mik": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя└┴┬├─┼╣║╚╔╩╦╠═╬┐░▒▓│┤№§╗╝┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, -checkPath.isNotRelative = isNotRelative -checkPath.convert = p => p + // Aliases of generated encodings. + "ascii8bit": "ascii", + "usascii": "ascii", + "ansix34": "ascii", + "ansix341968": "ascii", + "ansix341986": "ascii", + "csascii": "ascii", + "cp367": "ascii", + "ibm367": "ascii", + "isoir6": "ascii", + "iso646us": "ascii", + "iso646irv": "ascii", + "us": "ascii", -class Ignore { - constructor ({ - ignorecase = true, - ignoreCase = ignorecase, - allowRelativePaths = false - } = {}) { - define(this, KEY_IGNORE, true) + "latin1": "iso88591", + "latin2": "iso88592", + "latin3": "iso88593", + "latin4": "iso88594", + "latin5": "iso88599", + "latin6": "iso885910", + "latin7": "iso885913", + "latin8": "iso885914", + "latin9": "iso885915", + "latin10": "iso885916", - this._rules = [] - this._ignoreCase = ignoreCase - this._allowRelativePaths = allowRelativePaths - this._initCache() - } + "csisolatin1": "iso88591", + "csisolatin2": "iso88592", + "csisolatin3": "iso88593", + "csisolatin4": "iso88594", + "csisolatincyrillic": "iso88595", + "csisolatinarabic": "iso88596", + "csisolatingreek" : "iso88597", + "csisolatinhebrew": "iso88598", + "csisolatin5": "iso88599", + "csisolatin6": "iso885910", - _initCache () { - this._ignoreCache = Object.create(null) - this._testCache = Object.create(null) - } + "l1": "iso88591", + "l2": "iso88592", + "l3": "iso88593", + "l4": "iso88594", + "l5": "iso88599", + "l6": "iso885910", + "l7": "iso885913", + "l8": "iso885914", + "l9": "iso885915", + "l10": "iso885916", - _addPattern (pattern) { - // #32 - if (pattern && pattern[KEY_IGNORE]) { - this._rules = this._rules.concat(pattern._rules) - this._added = true - return - } + "isoir14": "iso646jp", + "isoir57": "iso646cn", + "isoir100": "iso88591", + "isoir101": "iso88592", + "isoir109": "iso88593", + "isoir110": "iso88594", + "isoir144": "iso88595", + "isoir127": "iso88596", + "isoir126": "iso88597", + "isoir138": "iso88598", + "isoir148": "iso88599", + "isoir157": "iso885910", + "isoir166": "tis620", + "isoir179": "iso885913", + "isoir199": "iso885914", + "isoir203": "iso885915", + "isoir226": "iso885916", - if (checkPattern(pattern)) { - const rule = createRule(pattern, this._ignoreCase) - this._added = true - this._rules.push(rule) - } - } + "cp819": "iso88591", + "ibm819": "iso88591", - // @param {Array | string | Ignore} pattern - add (pattern) { - this._added = false + "cyrillic": "iso88595", - makeArray( - isString(pattern) - ? splitPattern(pattern) - : pattern - ).forEach(this._addPattern, this) + "arabic": "iso88596", + "arabic8": "iso88596", + "ecma114": "iso88596", + "asmo708": "iso88596", - // Some rules have just added to the ignore, - // making the behavior changed. - if (this._added) { - this._initCache() - } + "greek" : "iso88597", + "greek8" : "iso88597", + "ecma118" : "iso88597", + "elot928" : "iso88597", - return this - } + "hebrew": "iso88598", + "hebrew8": "iso88598", - // legacy - addPattern (pattern) { - return this.add(pattern) - } + "turkish": "iso88599", + "turkish8": "iso88599", - // | ignored : unignored - // negative | 0:0 | 0:1 | 1:0 | 1:1 - // -------- | ------- | ------- | ------- | -------- - // 0 | TEST | TEST | SKIP | X - // 1 | TESTIF | SKIP | TEST | X + "thai": "iso885911", + "thai8": "iso885911", - // - SKIP: always skip - // - TEST: always test - // - TESTIF: only test if checkUnignored - // - X: that never happen + "celtic": "iso885914", + "celtic8": "iso885914", + "isoceltic": "iso885914", - // @param {boolean} whether should check if the path is unignored, - // setting `checkUnignored` to `false` could reduce additional - // path matching. + "tis6200": "tis620", + "tis62025291": "tis620", + "tis62025330": "tis620", - // @returns {TestResult} true if a file is ignored - _testOne (path, checkUnignored) { - let ignored = false - let unignored = false + "10000": "macroman", + "10006": "macgreek", + "10007": "maccyrillic", + "10079": "maciceland", + "10081": "macturkish", - this._rules.forEach(rule => { - const {negative} = rule - if ( - unignored === negative && ignored !== unignored - || negative && !ignored && !unignored && !checkUnignored - ) { - return - } + "cspc8codepage437": "cp437", + "cspc775baltic": "cp775", + "cspc850multilingual": "cp850", + "cspcp852": "cp852", + "cspc862latinhebrew": "cp862", + "cpgr": "cp869", + + "msee": "cp1250", + "mscyrl": "cp1251", + "msansi": "cp1252", + "msgreek": "cp1253", + "msturk": "cp1254", + "mshebr": "cp1255", + "msarab": "cp1256", + "winbaltrim": "cp1257", + + "cp20866": "koi8r", + "20866": "koi8r", + "ibm878": "koi8r", + "cskoi8r": "koi8r", + + "cp21866": "koi8u", + "21866": "koi8u", + "ibm1168": "koi8u", + + "strk10482002": "rk1048", + + "tcvn5712": "tcvn", + "tcvn57121": "tcvn", + + "gb198880": "iso646cn", + "cn": "iso646cn", + + "csiso14jisc6220ro": "iso646jp", + "jisc62201969ro": "iso646jp", + "jp": "iso646jp", + + "cshproman8": "hproman8", + "r8": "hproman8", + "roman8": "hproman8", + "xroman8": "hproman8", + "ibm1051": "hproman8", + + "mac": "macintosh", + "csmacintosh": "macintosh", +}; - const matched = rule.regex.test(path) - - if (matched) { - ignored = !negative - unignored = negative - } - }) - - return { - ignored, - unignored - } - } - - // @returns {TestResult} - _test (originalPath, cache, checkUnignored, slices) { - const path = originalPath - // Supports nullable path - && checkPath.convert(originalPath) - - checkPath( - path, - originalPath, - this._allowRelativePaths - ? RETURN_FALSE - : throwError - ) - - return this._t(path, cache, checkUnignored, slices) - } - - _t (path, cache, checkUnignored, slices) { - if (path in cache) { - return cache[path] - } - - if (!slices) { - // path/to/a.js - // ['path', 'to', 'a.js'] - slices = path.split(SLASH) - } - - slices.pop() - - // If the path has no parent directory, just test it - if (!slices.length) { - return cache[path] = this._testOne(path, checkUnignored) - } - - const parent = this._t( - slices.join(SLASH) + SLASH, - cache, - checkUnignored, - slices - ) - - // If the path contains a parent directory, check the parent first - return cache[path] = parent.ignored - // > It is not possible to re-include a file if a parent directory of - // > that file is excluded. - ? parent - : this._testOne(path, checkUnignored) - } - - ignores (path) { - return this._test(path, this._ignoreCache, false).ignored - } - - createFilter () { - return path => !this.ignores(path) - } - - filter (paths) { - return makeArray(paths).filter(this.createFilter()) - } - - // @returns {TestResult} - test (path) { - return this._test(path, this._testCache, true) - } -} - -const factory = options => new Ignore(options) - -const isPathValid = path => - checkPath(path && checkPath.convert(path), path, RETURN_FALSE) - -factory.isPathValid = isPathValid - -// Fixes typescript -factory.default = factory - -module.exports = factory - -// Windows -// -------------------------------------------------------------- -/* istanbul ignore if */ -if ( - // Detect `process` so that it can run in browsers. - typeof process !== 'undefined' - && ( - process.env && process.env.IGNORE_TEST_WIN32 - || process.platform === 'win32' - ) -) { - /* eslint no-control-regex: "off" */ - const makePosix = str => /^\\\\\?\\/.test(str) - || /["<>|\u0000-\u001F]+/u.test(str) - ? str - : str.replace(/\\/g, '/') - - checkPath.convert = makePosix - - // 'C:\\foo' <- 'C:\\foo' has been converted to 'C:/' - // 'd:\\foo' - const REGIX_IS_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i - checkPath.isNotRelative = path => - REGIX_IS_WINDOWS_PATH_ABSOLUTE.test(path) - || isNotRelative(path) -} - - -/***/ }), - -/***/ 98043: -/***/ ((module) => { - -"use strict"; - - -module.exports = (string, count = 1, options) => { - options = { - indent: ' ', - includeEmptyLines: false, - ...options - }; - - if (typeof string !== 'string') { - throw new TypeError( - `Expected \`input\` to be a \`string\`, got \`${typeof string}\`` - ); - } - - if (typeof count !== 'number') { - throw new TypeError( - `Expected \`count\` to be a \`number\`, got \`${typeof count}\`` - ); - } - - if (typeof options.indent !== 'string') { - throw new TypeError( - `Expected \`options.indent\` to be a \`string\`, got \`${typeof options.indent}\`` - ); - } - - if (count === 0) { - return string; - } - - const regex = options.includeEmptyLines ? /^/gm : /^(?!\s*$)/gm; - - return string.replace(regex, options.indent.repeat(count)); -}; - - -/***/ }), - -/***/ 44124: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -try { - var util = __nccwpck_require__(73837); - /* istanbul ignore next */ - if (typeof util.inherits !== 'function') throw ''; - module.exports = util.inherits; -} catch (e) { - /* istanbul ignore next */ - module.exports = __nccwpck_require__(8544); -} - - -/***/ }), - -/***/ 8544: -/***/ ((module) => { - -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }) - } - }; -} else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor - } - } -} - - -/***/ }), - -/***/ 30545: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const command_1 = __nccwpck_require__(90803); -const utils_1 = __nccwpck_require__(94832); -const RedisParser = __nccwpck_require__(53315); -const SubscriptionSet_1 = __nccwpck_require__(73527); -const debug = utils_1.Debug("dataHandler"); -class DataHandler { - constructor(redis, parserOptions) { - this.redis = redis; - const parser = new RedisParser({ - stringNumbers: parserOptions.stringNumbers, - returnBuffers: !parserOptions.dropBufferSupport, - returnError: (err) => { - this.returnError(err); - }, - returnFatalError: (err) => { - this.returnFatalError(err); - }, - returnReply: (reply) => { - this.returnReply(reply); - }, - }); - redis.stream.on("data", (data) => { - parser.execute(data); - }); - } - returnFatalError(err) { - err.message += ". Please report this."; - this.redis.recoverFromFatalError(err, err, { offlineQueue: false }); - } - returnError(err) { - const item = this.shiftCommand(err); - if (!item) { - return; - } - err.command = { - name: item.command.name, - args: item.command.args, - }; - this.redis.handleReconnection(err, item); - } - returnReply(reply) { - if (this.handleMonitorReply(reply)) { - return; - } - if (this.handleSubscriberReply(reply)) { - return; - } - const item = this.shiftCommand(reply); - if (!item) { - return; - } - if (command_1.default.checkFlag("ENTER_SUBSCRIBER_MODE", item.command.name)) { - this.redis.condition.subscriber = new SubscriptionSet_1.default(); - this.redis.condition.subscriber.add(item.command.name, reply[1].toString()); - if (!fillSubCommand(item.command, reply[2])) { - this.redis.commandQueue.unshift(item); - } - } - else if (command_1.default.checkFlag("EXIT_SUBSCRIBER_MODE", item.command.name)) { - if (!fillUnsubCommand(item.command, reply[2])) { - this.redis.commandQueue.unshift(item); - } - } - else { - item.command.resolve(reply); - } - } - handleSubscriberReply(reply) { - if (!this.redis.condition.subscriber) { - return false; - } - const replyType = Array.isArray(reply) ? reply[0].toString() : null; - debug('receive reply "%s" in subscriber mode', replyType); - switch (replyType) { - case "message": - if (this.redis.listeners("message").length > 0) { - // Check if there're listeners to avoid unnecessary `toString()`. - this.redis.emit("message", reply[1].toString(), reply[2] ? reply[2].toString() : ''); - } - this.redis.emit("messageBuffer", reply[1], reply[2]); - break; - case "pmessage": { - const pattern = reply[1].toString(); - if (this.redis.listeners("pmessage").length > 0) { - this.redis.emit("pmessage", pattern, reply[2].toString(), reply[3].toString()); - } - this.redis.emit("pmessageBuffer", pattern, reply[2], reply[3]); - break; - } - case "subscribe": - case "psubscribe": { - const channel = reply[1].toString(); - this.redis.condition.subscriber.add(replyType, channel); - const item = this.shiftCommand(reply); - if (!item) { - return; - } - if (!fillSubCommand(item.command, reply[2])) { - this.redis.commandQueue.unshift(item); - } - break; - } - case "unsubscribe": - case "punsubscribe": { - const channel = reply[1] ? reply[1].toString() : null; - if (channel) { - this.redis.condition.subscriber.del(replyType, channel); - } - const count = reply[2]; - if (count === 0) { - this.redis.condition.subscriber = false; - } - const item = this.shiftCommand(reply); - if (!item) { - return; - } - if (!fillUnsubCommand(item.command, count)) { - this.redis.commandQueue.unshift(item); - } - break; - } - default: { - const item = this.shiftCommand(reply); - if (!item) { - return; - } - item.command.resolve(reply); - } - } - return true; - } - handleMonitorReply(reply) { - if (this.redis.status !== "monitoring") { - return false; - } - const replyStr = reply.toString(); - if (replyStr === "OK") { - // Valid commands in the monitoring mode are AUTH and MONITOR, - // both of which always reply with 'OK'. - // So if we got an 'OK', we can make certain that - // the reply is made to AUTH & MONITO. - return false; - } - // Since commands sent in the monitoring mode will trigger an exception, - // any replies we received in the monitoring mode should consider to be - // realtime monitor data instead of result of commands. - const len = replyStr.indexOf(" "); - const timestamp = replyStr.slice(0, len); - const argindex = replyStr.indexOf('"'); - const args = replyStr - .slice(argindex + 1, -1) - .split('" "') - .map((elem) => elem.replace(/\\"/g, '"')); - const dbAndSource = replyStr.slice(len + 2, argindex - 2).split(" "); - this.redis.emit("monitor", timestamp, args, dbAndSource[1], dbAndSource[0]); - return true; - } - shiftCommand(reply) { - const item = this.redis.commandQueue.shift(); - if (!item) { - const message = "Command queue state error. If you can reproduce this, please report it."; - const error = new Error(message + - (reply instanceof Error - ? ` Last error: ${reply.message}` - : ` Last reply: ${reply.toString()}`)); - this.redis.emit("error", error); - return null; - } - return item; - } -} -exports["default"] = DataHandler; -function fillSubCommand(command, count) { - // TODO: use WeakMap here - if (typeof command.remainReplies === "undefined") { - command.remainReplies = command.args.length; - } - if (--command.remainReplies === 0) { - command.resolve(count); - return true; - } - return false; -} -function fillUnsubCommand(command, count) { - if (typeof command.remainReplies === "undefined") { - command.remainReplies = command.args.length; - } - if (command.remainReplies === 0) { - if (count === 0) { - command.resolve(count); - return true; - } - return false; - } - if (--command.remainReplies === 0) { - command.resolve(count); - return true; - } - return false; -} - - -/***/ }), - -/***/ 6134: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const stream_1 = __nccwpck_require__(12781); -/** - * Convenient class to convert the process of scaning keys to a readable stream. - * - * @export - * @class ScanStream - * @extends {Readable} - */ -class ScanStream extends stream_1.Readable { - constructor(opt) { - super(opt); - this.opt = opt; - this._redisCursor = "0"; - this._redisDrained = false; - } - _read() { - if (this._redisDrained) { - this.push(null); - return; - } - const args = [this._redisCursor]; - if (this.opt.key) { - args.unshift(this.opt.key); - } - if (this.opt.match) { - args.push("MATCH", this.opt.match); - } - if (this.opt.type) { - args.push("TYPE", this.opt.type); - } - if (this.opt.count) { - args.push("COUNT", String(this.opt.count)); - } - this.opt.redis[this.opt.command](args, (err, res) => { - if (err) { - this.emit("error", err); - return; - } - this._redisCursor = res[0] instanceof Buffer ? res[0].toString() : res[0]; - if (this._redisCursor === "0") { - this._redisDrained = true; - } - this.push(res[1]); - }); - } - close() { - this._redisDrained = true; - } -} -exports["default"] = ScanStream; - - -/***/ }), - -/***/ 73527: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -/** - * Tiny class to simplify dealing with subscription set - * - * @export - * @class SubscriptionSet - */ -class SubscriptionSet { - constructor() { - this.set = { - subscribe: {}, - psubscribe: {}, - }; - } - add(set, channel) { - this.set[mapSet(set)][channel] = true; - } - del(set, channel) { - delete this.set[mapSet(set)][channel]; - } - channels(set) { - return Object.keys(this.set[mapSet(set)]); - } - isEmpty() { - return (this.channels("subscribe").length === 0 && - this.channels("psubscribe").length === 0); - } -} -exports["default"] = SubscriptionSet; -function mapSet(set) { - if (set === "unsubscribe") { - return "subscribe"; - } - if (set === "punsubscribe") { - return "psubscribe"; - } - return set; -} - - -/***/ }), - -/***/ 97873: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const PromiseContainer = __nccwpck_require__(71475); -const lodash_1 = __nccwpck_require__(20961); -const calculateSlot = __nccwpck_require__(48481); -const standard_as_callback_1 = __nccwpck_require__(91543); -exports.kExec = Symbol("exec"); -exports.kCallbacks = Symbol("callbacks"); -exports.notAllowedAutoPipelineCommands = [ - "auth", - "info", - "script", - "quit", - "cluster", - "pipeline", - "multi", - "subscribe", - "psubscribe", - "unsubscribe", - "unpsubscribe", -]; -function executeAutoPipeline(client, slotKey) { - /* - If a pipeline is already executing, keep queueing up commands - since ioredis won't serve two pipelines at the same time - */ - if (client._runningAutoPipelines.has(slotKey)) { - return; - } - if (!client._autoPipelines.has(slotKey)) { - /* - Rare edge case. Somehow, something has deleted this running autopipeline in an immediate - call to executeAutoPipeline. - - Maybe the callback in the pipeline.exec is sometimes called in the same tick, - e.g. if redis is disconnected? - */ - return; - } - client._runningAutoPipelines.add(slotKey); - // Get the pipeline and immediately delete it so that new commands are queued on a new pipeline - const pipeline = client._autoPipelines.get(slotKey); - client._autoPipelines.delete(slotKey); - const callbacks = pipeline[exports.kCallbacks]; - // Stop keeping a reference to callbacks immediately after the callbacks stop being used. - // This allows the GC to reclaim objects referenced by callbacks, especially with 16384 slots - // in Redis.Cluster - pipeline[exports.kCallbacks] = null; - // Perform the call - pipeline.exec(function (err, results) { - client._runningAutoPipelines.delete(slotKey); - /* - Invoke all callback in nextTick so the stack is cleared - and callbacks can throw errors without affecting other callbacks. - */ - if (err) { - for (let i = 0; i < callbacks.length; i++) { - process.nextTick(callbacks[i], err); - } - } - else { - for (let i = 0; i < callbacks.length; i++) { - process.nextTick(callbacks[i], ...results[i]); - } - } - // If there is another pipeline on the same node, immediately execute it without waiting for nextTick - if (client._autoPipelines.has(slotKey)) { - executeAutoPipeline(client, slotKey); - } - }); -} -function shouldUseAutoPipelining(client, functionName, commandName) { - return (functionName && - client.options.enableAutoPipelining && - !client.isPipeline && - !exports.notAllowedAutoPipelineCommands.includes(commandName) && - !client.options.autoPipeliningIgnoredCommands.includes(commandName)); -} -exports.shouldUseAutoPipelining = shouldUseAutoPipelining; -/** - * @private - */ -function getFirstValueInFlattenedArray(args) { - for (let i = 0; i < args.length; i++) { - const arg = args[i]; - if (typeof arg === "string") { - return arg; - } - else if (Array.isArray(arg) || lodash_1.isArguments(arg)) { - if (arg.length === 0) { - continue; - } - return arg[0]; - } - const flattened = lodash_1.flatten([arg]); - if (flattened.length > 0) { - return flattened[0]; - } - } - return undefined; -} -exports.getFirstValueInFlattenedArray = getFirstValueInFlattenedArray; -function executeWithAutoPipelining(client, functionName, commandName, args, callback) { - const CustomPromise = PromiseContainer.get(); - // On cluster mode let's wait for slots to be available - if (client.isCluster && !client.slots.length) { - if (client.status === "wait") - client.connect().catch(lodash_1.noop); - return standard_as_callback_1.default(new CustomPromise(function (resolve, reject) { - client.delayUntilReady((err) => { - if (err) { - reject(err); - return; - } - executeWithAutoPipelining(client, functionName, commandName, args, null).then(resolve, reject); - }); - }), callback); - } - // If we have slot information, we can improve routing by grouping slots served by the same subset of nodes - // Note that the first value in args may be a (possibly empty) array. - // ioredis will only flatten one level of the array, in the Command constructor. - const prefix = client.options.keyPrefix || ""; - const slotKey = client.isCluster - ? client.slots[calculateSlot(`${prefix}${getFirstValueInFlattenedArray(args)}`)].join(",") - : "main"; - if (!client._autoPipelines.has(slotKey)) { - const pipeline = client.pipeline(); - pipeline[exports.kExec] = false; - pipeline[exports.kCallbacks] = []; - client._autoPipelines.set(slotKey, pipeline); - } - const pipeline = client._autoPipelines.get(slotKey); - /* - Mark the pipeline as scheduled. - The symbol will make sure that the pipeline is only scheduled once per tick. - New commands are appended to an already scheduled pipeline. - */ - if (!pipeline[exports.kExec]) { - pipeline[exports.kExec] = true; - /* - Deferring with setImmediate so we have a chance to capture multiple - commands that can be scheduled by I/O events already in the event loop queue. - */ - setImmediate(executeAutoPipeline, client, slotKey); - } - // Create the promise which will execute the command in the pipeline. - const autoPipelinePromise = new CustomPromise(function (resolve, reject) { - pipeline[exports.kCallbacks].push(function (err, value) { - if (err) { - reject(err); - return; - } - resolve(value); - }); - pipeline[functionName](...args); - }); - return standard_as_callback_1.default(autoPipelinePromise, callback); -} -exports.executeWithAutoPipelining = executeWithAutoPipelining; - - -/***/ }), - -/***/ 35835: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const dns_1 = __nccwpck_require__(9523); -exports.DEFAULT_CLUSTER_OPTIONS = { - clusterRetryStrategy: (times) => Math.min(100 + times * 2, 2000), - enableOfflineQueue: true, - enableReadyCheck: true, - scaleReads: "master", - maxRedirections: 16, - retryDelayOnMoved: 0, - retryDelayOnFailover: 100, - retryDelayOnClusterDown: 100, - retryDelayOnTryAgain: 100, - slotsRefreshTimeout: 1000, - slotsRefreshInterval: 5000, - useSRVRecords: false, - resolveSrv: dns_1.resolveSrv, - dnsLookup: dns_1.lookup, - enableAutoPipelining: false, - autoPipeliningIgnoredCommands: [], - maxScriptsCachingTime: 60000, -}; - - -/***/ }), - -/***/ 18394: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const util_1 = __nccwpck_require__(94582); -const utils_1 = __nccwpck_require__(94832); -const redis_1 = __nccwpck_require__(83609); -const debug = utils_1.Debug("cluster:subscriber"); -class ClusterSubscriber { - constructor(connectionPool, emitter) { - this.connectionPool = connectionPool; - this.emitter = emitter; - this.started = false; - this.subscriber = null; - this.connectionPool.on("-node", (_, key) => { - if (!this.started || !this.subscriber) { - return; - } - if (util_1.getNodeKey(this.subscriber.options) === key) { - debug("subscriber has left, selecting a new one..."); - this.selectSubscriber(); - } - }); - this.connectionPool.on("+node", () => { - if (!this.started || this.subscriber) { - return; - } - debug("a new node is discovered and there is no subscriber, selecting a new one..."); - this.selectSubscriber(); - }); - } - getInstance() { - return this.subscriber; - } - selectSubscriber() { - const lastActiveSubscriber = this.lastActiveSubscriber; - // Disconnect the previous subscriber even if there - // will not be a new one. - if (lastActiveSubscriber) { - lastActiveSubscriber.disconnect(); - } - if (this.subscriber) { - this.subscriber.disconnect(); - } - const sampleNode = utils_1.sample(this.connectionPool.getNodes()); - if (!sampleNode) { - debug("selecting subscriber failed since there is no node discovered in the cluster yet"); - this.subscriber = null; - return; - } - const { options } = sampleNode; - debug("selected a subscriber %s:%s", options.host, options.port); - /* - * Create a specialized Redis connection for the subscription. - * Note that auto reconnection is enabled here. - * - * `enableReadyCheck` is also enabled because although subscription is allowed - * while redis is loading data from the disk, we can check if the password - * provided for the subscriber is correct, and if not, the current subscriber - * will be disconnected and a new subscriber will be selected. - */ - this.subscriber = new redis_1.default({ - port: options.port, - host: options.host, - username: options.username, - password: options.password, - enableReadyCheck: true, - connectionName: util_1.getConnectionName("subscriber", options.connectionName), - lazyConnect: true, - tls: options.tls, - }); - // Ignore the errors since they're handled in the connection pool. - this.subscriber.on("error", utils_1.noop); - // Re-subscribe previous channels - const previousChannels = { subscribe: [], psubscribe: [] }; - if (lastActiveSubscriber) { - const condition = lastActiveSubscriber.condition || lastActiveSubscriber.prevCondition; - if (condition && condition.subscriber) { - previousChannels.subscribe = condition.subscriber.channels("subscribe"); - previousChannels.psubscribe = condition.subscriber.channels("psubscribe"); - } - } - if (previousChannels.subscribe.length || - previousChannels.psubscribe.length) { - let pending = 0; - for (const type of ["subscribe", "psubscribe"]) { - const channels = previousChannels[type]; - if (channels.length) { - pending += 1; - debug("%s %d channels", type, channels.length); - this.subscriber[type](channels) - .then(() => { - if (!--pending) { - this.lastActiveSubscriber = this.subscriber; - } - }) - .catch(() => { - // TODO: should probably disconnect the subscriber and try again. - debug("failed to %s %d channels", type, channels.length); - }); - } - } - } - else { - this.lastActiveSubscriber = this.subscriber; - } - for (const event of ["message", "messageBuffer"]) { - this.subscriber.on(event, (arg1, arg2) => { - this.emitter.emit(event, arg1, arg2); - }); - } - for (const event of ["pmessage", "pmessageBuffer"]) { - this.subscriber.on(event, (arg1, arg2, arg3) => { - this.emitter.emit(event, arg1, arg2, arg3); - }); - } - } - start() { - this.started = true; - this.selectSubscriber(); - debug("started"); - } - stop() { - this.started = false; - if (this.subscriber) { - this.subscriber.disconnect(); - this.subscriber = null; - } - debug("stopped"); - } -} -exports["default"] = ClusterSubscriber; - - -/***/ }), - -/***/ 34589: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const events_1 = __nccwpck_require__(82361); -const utils_1 = __nccwpck_require__(94832); -const util_1 = __nccwpck_require__(94582); -const redis_1 = __nccwpck_require__(83609); -const debug = utils_1.Debug("cluster:connectionPool"); -class ConnectionPool extends events_1.EventEmitter { - constructor(redisOptions) { - super(); - this.redisOptions = redisOptions; - // master + slave = all - this.nodes = { - all: {}, - master: {}, - slave: {}, - }; - this.specifiedOptions = {}; - } - getNodes(role = "all") { - const nodes = this.nodes[role]; - return Object.keys(nodes).map((key) => nodes[key]); - } - getInstanceByKey(key) { - return this.nodes.all[key]; - } - getSampleInstance(role) { - const keys = Object.keys(this.nodes[role]); - const sampleKey = utils_1.sample(keys); - return this.nodes[role][sampleKey]; - } - /** - * Find or create a connection to the node - * - * @param {IRedisOptions} node - * @param {boolean} [readOnly=false] - * @returns {*} - * @memberof ConnectionPool - */ - findOrCreate(node, readOnly = false) { - const key = util_1.getNodeKey(node); - readOnly = Boolean(readOnly); - if (this.specifiedOptions[key]) { - Object.assign(node, this.specifiedOptions[key]); - } - else { - this.specifiedOptions[key] = node; - } - let redis; - if (this.nodes.all[key]) { - redis = this.nodes.all[key]; - if (redis.options.readOnly !== readOnly) { - redis.options.readOnly = readOnly; - debug("Change role of %s to %s", key, readOnly ? "slave" : "master"); - redis[readOnly ? "readonly" : "readwrite"]().catch(utils_1.noop); - if (readOnly) { - delete this.nodes.master[key]; - this.nodes.slave[key] = redis; - } - else { - delete this.nodes.slave[key]; - this.nodes.master[key] = redis; - } - } - } - else { - debug("Connecting to %s as %s", key, readOnly ? "slave" : "master"); - redis = new redis_1.default(utils_1.defaults({ - // Never try to reconnect when a node is lose, - // instead, waiting for a `MOVED` error and - // fetch the slots again. - retryStrategy: null, - // Offline queue should be enabled so that - // we don't need to wait for the `ready` event - // before sending commands to the node. - enableOfflineQueue: true, - readOnly: readOnly, - }, node, this.redisOptions, { lazyConnect: true })); - this.nodes.all[key] = redis; - this.nodes[readOnly ? "slave" : "master"][key] = redis; - redis.once("end", () => { - this.removeNode(key); - this.emit("-node", redis, key); - if (!Object.keys(this.nodes.all).length) { - this.emit("drain"); - } - }); - this.emit("+node", redis, key); - redis.on("error", function (error) { - this.emit("nodeError", error, key); - }); - } - return redis; - } - /** - * Remove a node from the pool. - */ - removeNode(key) { - const { nodes } = this; - if (nodes.all[key]) { - debug("Remove %s from the pool", key); - delete nodes.all[key]; - } - delete nodes.master[key]; - delete nodes.slave[key]; - } - /** - * Reset the pool with a set of nodes. - * The old node will be removed. - * - * @param {(Array)} nodes - * @memberof ConnectionPool - */ - reset(nodes) { - debug("Reset with %O", nodes); - const newNodes = {}; - nodes.forEach((node) => { - const key = util_1.getNodeKey(node); - // Don't override the existing (master) node - // when the current one is slave. - if (!(node.readOnly && newNodes[key])) { - newNodes[key] = node; - } - }); - Object.keys(this.nodes.all).forEach((key) => { - if (!newNodes[key]) { - debug("Disconnect %s because the node does not hold any slot", key); - this.nodes.all[key].disconnect(); - this.removeNode(key); - } - }); - Object.keys(newNodes).forEach((key) => { - const node = newNodes[key]; - this.findOrCreate(node, node.readOnly); - }); - } -} -exports["default"] = ConnectionPool; - - -/***/ }), - -/***/ 12770: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const utils_1 = __nccwpck_require__(94832); -const Deque = __nccwpck_require__(42342); -const debug = utils_1.Debug("delayqueue"); -/** - * Queue that runs items after specified duration - * - * @export - * @class DelayQueue - */ -class DelayQueue { - constructor() { - this.queues = {}; - this.timeouts = {}; - } - /** - * Add a new item to the queue - * - * @param {string} bucket bucket name - * @param {Function} item function that will run later - * @param {IDelayQueueOptions} options - * @memberof DelayQueue - */ - push(bucket, item, options) { - const callback = options.callback || process.nextTick; - if (!this.queues[bucket]) { - this.queues[bucket] = new Deque(); - } - const queue = this.queues[bucket]; - queue.push(item); - if (!this.timeouts[bucket]) { - this.timeouts[bucket] = setTimeout(() => { - callback(() => { - this.timeouts[bucket] = null; - this.execute(bucket); - }); - }, options.timeout); - } - } - execute(bucket) { - const queue = this.queues[bucket]; - if (!queue) { - return; - } - const { length } = queue; - if (!length) { - return; - } - debug("send %d commands in %s queue", length, bucket); - this.queues[bucket] = null; - while (queue.length > 0) { - queue.shift()(); - } - } -} -exports["default"] = DelayQueue; - - -/***/ }), - -/***/ 17208: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const events_1 = __nccwpck_require__(82361); -const ClusterAllFailedError_1 = __nccwpck_require__(97282); -const utils_1 = __nccwpck_require__(94832); -const ConnectionPool_1 = __nccwpck_require__(34589); -const util_1 = __nccwpck_require__(94582); -const ClusterSubscriber_1 = __nccwpck_require__(18394); -const DelayQueue_1 = __nccwpck_require__(12770); -const ScanStream_1 = __nccwpck_require__(6134); -const redis_errors_1 = __nccwpck_require__(81879); -const standard_as_callback_1 = __nccwpck_require__(91543); -const PromiseContainer = __nccwpck_require__(71475); -const ClusterOptions_1 = __nccwpck_require__(35835); -const utils_2 = __nccwpck_require__(94832); -const commands = __nccwpck_require__(98020); -const command_1 = __nccwpck_require__(90803); -const redis_1 = __nccwpck_require__(83609); -const commander_1 = __nccwpck_require__(33642); -const Deque = __nccwpck_require__(42342); -const debug = utils_1.Debug("cluster"); -/** - * Client for the official Redis Cluster - * - * @class Cluster - * @extends {EventEmitter} - */ -class Cluster extends events_1.EventEmitter { - /** - * Creates an instance of Cluster. - * - * @param {((string | number | object)[])} startupNodes - * @param {IClusterOptions} [options={}] - * @memberof Cluster - */ - constructor(startupNodes, options = {}) { - super(); - this.slots = []; - this.retryAttempts = 0; - this.delayQueue = new DelayQueue_1.default(); - this.offlineQueue = new Deque(); - this.isRefreshing = false; - this.isCluster = true; - this._autoPipelines = new Map(); - this._groupsIds = {}; - this._groupsBySlot = Array(16384); - this._runningAutoPipelines = new Set(); - this._readyDelayedCallbacks = []; - this._addedScriptHashes = {}; - /** - * Every time Cluster#connect() is called, this value will be - * auto-incrementing. The purpose of this value is used for - * discarding previous connect attampts when creating a new - * connection. - * - * @private - * @type {number} - * @memberof Cluster - */ - this.connectionEpoch = 0; - commander_1.default.call(this); - this.startupNodes = startupNodes; - this.options = utils_1.defaults({}, options, ClusterOptions_1.DEFAULT_CLUSTER_OPTIONS, this.options); - // validate options - if (typeof this.options.scaleReads !== "function" && - ["all", "master", "slave"].indexOf(this.options.scaleReads) === -1) { - throw new Error('Invalid option scaleReads "' + - this.options.scaleReads + - '". Expected "all", "master", "slave" or a custom function'); - } - this.connectionPool = new ConnectionPool_1.default(this.options.redisOptions); - this.connectionPool.on("-node", (redis, key) => { - this.emit("-node", redis); - }); - this.connectionPool.on("+node", (redis) => { - this.emit("+node", redis); - }); - this.connectionPool.on("drain", () => { - this.setStatus("close"); - }); - this.connectionPool.on("nodeError", (error, key) => { - this.emit("node error", error, key); - }); - this.subscriber = new ClusterSubscriber_1.default(this.connectionPool, this); - if (this.options.lazyConnect) { - this.setStatus("wait"); - } - else { - this.connect().catch((err) => { - debug("connecting failed: %s", err); - }); - } - } - resetOfflineQueue() { - this.offlineQueue = new Deque(); - } - clearNodesRefreshInterval() { - if (this.slotsTimer) { - clearTimeout(this.slotsTimer); - this.slotsTimer = null; - } - } - resetNodesRefreshInterval() { - if (this.slotsTimer) { - return; - } - const nextRound = () => { - this.slotsTimer = setTimeout(() => { - debug('refreshing slot caches... (triggered by "slotsRefreshInterval" option)'); - this.refreshSlotsCache(() => { - nextRound(); - }); - }, this.options.slotsRefreshInterval); - }; - nextRound(); - } - /** - * Connect to a cluster - * - * @returns {Promise} - * @memberof Cluster - */ - connect() { - const Promise = PromiseContainer.get(); - return new Promise((resolve, reject) => { - if (this.status === "connecting" || - this.status === "connect" || - this.status === "ready") { - reject(new Error("Redis is already connecting/connected")); - return; - } - // Make sure only one timer is active at a time - clearInterval(this._addedScriptHashesCleanInterval); - // Start the script cache cleaning - this._addedScriptHashesCleanInterval = setInterval(() => { - this._addedScriptHashes = {}; - }, this.options.maxScriptsCachingTime); - const epoch = ++this.connectionEpoch; - this.setStatus("connecting"); - this.resolveStartupNodeHostnames() - .then((nodes) => { - if (this.connectionEpoch !== epoch) { - debug("discard connecting after resolving startup nodes because epoch not match: %d != %d", epoch, this.connectionEpoch); - reject(new redis_errors_1.RedisError("Connection is discarded because a new connection is made")); - return; - } - if (this.status !== "connecting") { - debug("discard connecting after resolving startup nodes because the status changed to %s", this.status); - reject(new redis_errors_1.RedisError("Connection is aborted")); - return; - } - this.connectionPool.reset(nodes); - function readyHandler() { - this.setStatus("ready"); - this.retryAttempts = 0; - this.executeOfflineCommands(); - this.resetNodesRefreshInterval(); - resolve(); - } - let closeListener = undefined; - const refreshListener = () => { - this.invokeReadyDelayedCallbacks(undefined); - this.removeListener("close", closeListener); - this.manuallyClosing = false; - this.setStatus("connect"); - if (this.options.enableReadyCheck) { - this.readyCheck((err, fail) => { - if (err || fail) { - debug("Ready check failed (%s). Reconnecting...", err || fail); - if (this.status === "connect") { - this.disconnect(true); - } - } - else { - readyHandler.call(this); - } - }); - } - else { - readyHandler.call(this); - } - }; - closeListener = function () { - const error = new Error("None of startup nodes is available"); - this.removeListener("refresh", refreshListener); - this.invokeReadyDelayedCallbacks(error); - reject(error); - }; - this.once("refresh", refreshListener); - this.once("close", closeListener); - this.once("close", this.handleCloseEvent.bind(this)); - this.refreshSlotsCache(function (err) { - if (err && err.message === "Failed to refresh slots cache.") { - redis_1.default.prototype.silentEmit.call(this, "error", err); - this.connectionPool.reset([]); - } - }.bind(this)); - this.subscriber.start(); - }) - .catch((err) => { - this.setStatus("close"); - this.handleCloseEvent(err); - this.invokeReadyDelayedCallbacks(err); - reject(err); - }); - }); - } - /** - * Called when closed to check whether a reconnection should be made - * - * @private - * @memberof Cluster - */ - handleCloseEvent(reason) { - if (reason) { - debug("closed because %s", reason); - } - let retryDelay; - if (!this.manuallyClosing && - typeof this.options.clusterRetryStrategy === "function") { - retryDelay = this.options.clusterRetryStrategy.call(this, ++this.retryAttempts, reason); - } - if (typeof retryDelay === "number") { - this.setStatus("reconnecting"); - this.reconnectTimeout = setTimeout(function () { - this.reconnectTimeout = null; - debug("Cluster is disconnected. Retrying after %dms", retryDelay); - this.connect().catch(function (err) { - debug("Got error %s when reconnecting. Ignoring...", err); - }); - }.bind(this), retryDelay); - } - else { - this.setStatus("end"); - this.flushQueue(new Error("None of startup nodes is available")); - } - } - /** - * Disconnect from every node in the cluster. - * - * @param {boolean} [reconnect=false] - * @memberof Cluster - */ - disconnect(reconnect = false) { - const status = this.status; - this.setStatus("disconnecting"); - clearInterval(this._addedScriptHashesCleanInterval); - this._addedScriptHashesCleanInterval = null; - if (!reconnect) { - this.manuallyClosing = true; - } - if (this.reconnectTimeout && !reconnect) { - clearTimeout(this.reconnectTimeout); - this.reconnectTimeout = null; - debug("Canceled reconnecting attempts"); - } - this.clearNodesRefreshInterval(); - this.subscriber.stop(); - if (status === "wait") { - this.setStatus("close"); - this.handleCloseEvent(); - } - else { - this.connectionPool.reset([]); - } - } - /** - * Quit the cluster gracefully. - * - * @param {CallbackFunction<'OK'>} [callback] - * @returns {Promise<'OK'>} - * @memberof Cluster - */ - quit(callback) { - const status = this.status; - this.setStatus("disconnecting"); - clearInterval(this._addedScriptHashesCleanInterval); - this._addedScriptHashesCleanInterval = null; - this.manuallyClosing = true; - if (this.reconnectTimeout) { - clearTimeout(this.reconnectTimeout); - this.reconnectTimeout = null; - } - this.clearNodesRefreshInterval(); - this.subscriber.stop(); - const Promise = PromiseContainer.get(); - if (status === "wait") { - const ret = standard_as_callback_1.default(Promise.resolve("OK"), callback); - // use setImmediate to make sure "close" event - // being emitted after quit() is returned - setImmediate(function () { - this.setStatus("close"); - this.handleCloseEvent(); - }.bind(this)); - return ret; - } - return standard_as_callback_1.default(Promise.all(this.nodes().map((node) => node.quit().catch((err) => { - // Ignore the error caused by disconnecting since - // we're disconnecting... - if (err.message === utils_2.CONNECTION_CLOSED_ERROR_MSG) { - return "OK"; - } - throw err; - }))).then(() => "OK"), callback); - } - /** - * Create a new instance with the same startup nodes and options as the current one. - * - * @example - * ```js - * var cluster = new Redis.Cluster([{ host: "127.0.0.1", port: "30001" }]); - * var anotherCluster = cluster.duplicate(); - * ``` - * - * @public - * @param {((string | number | object)[])} [overrideStartupNodes=[]] - * @param {IClusterOptions} [overrideOptions={}] - * @memberof Cluster - */ - duplicate(overrideStartupNodes = [], overrideOptions = {}) { - const startupNodes = overrideStartupNodes.length > 0 - ? overrideStartupNodes - : this.startupNodes.slice(0); - const options = Object.assign({}, this.options, overrideOptions); - return new Cluster(startupNodes, options); - } - /** - * Get nodes with the specified role - * - * @param {NodeRole} [role='all'] - * @returns {any[]} - * @memberof Cluster - */ - nodes(role = "all") { - if (role !== "all" && role !== "master" && role !== "slave") { - throw new Error('Invalid role "' + role + '". Expected "all", "master" or "slave"'); - } - return this.connectionPool.getNodes(role); - } - // This is needed in order not to install a listener for each auto pipeline - delayUntilReady(callback) { - this._readyDelayedCallbacks.push(callback); - } - /** - * Get the number of commands queued in automatic pipelines. - * - * This is not available (and returns 0) until the cluster is connected and slots information have been received. - */ - get autoPipelineQueueSize() { - let queued = 0; - for (const pipeline of this._autoPipelines.values()) { - queued += pipeline.length; - } - return queued; - } - /** - * Change cluster instance's status - * - * @private - * @param {ClusterStatus} status - * @memberof Cluster - */ - setStatus(status) { - debug("status: %s -> %s", this.status || "[empty]", status); - this.status = status; - process.nextTick(() => { - this.emit(status); - }); - } - /** - * Refresh the slot cache - * - * @private - * @param {CallbackFunction} [callback] - * @memberof Cluster - */ - refreshSlotsCache(callback) { - if (this.isRefreshing) { - if (typeof callback === "function") { - process.nextTick(callback); - } - return; - } - this.isRefreshing = true; - const _this = this; - const wrapper = function (error) { - _this.isRefreshing = false; - if (typeof callback === "function") { - callback(error); - } - }; - const nodes = utils_2.shuffle(this.connectionPool.getNodes()); - let lastNodeError = null; - function tryNode(index) { - if (index === nodes.length) { - const error = new ClusterAllFailedError_1.default("Failed to refresh slots cache.", lastNodeError); - return wrapper(error); - } - const node = nodes[index]; - const key = `${node.options.host}:${node.options.port}`; - debug("getting slot cache from %s", key); - _this.getInfoFromNode(node, function (err) { - switch (_this.status) { - case "close": - case "end": - return wrapper(new Error("Cluster is disconnected.")); - case "disconnecting": - return wrapper(new Error("Cluster is disconnecting.")); - } - if (err) { - _this.emit("node error", err, key); - lastNodeError = err; - tryNode(index + 1); - } - else { - _this.emit("refresh"); - wrapper(); - } - }); - } - tryNode(0); - } - /** - * Flush offline queue with error. - * - * @param {Error} error - * @memberof Cluster - */ - flushQueue(error) { - let item; - while (this.offlineQueue.length > 0) { - item = this.offlineQueue.shift(); - item.command.reject(error); - } - } - executeOfflineCommands() { - if (this.offlineQueue.length) { - debug("send %d commands in offline queue", this.offlineQueue.length); - const offlineQueue = this.offlineQueue; - this.resetOfflineQueue(); - while (offlineQueue.length > 0) { - const item = offlineQueue.shift(); - this.sendCommand(item.command, item.stream, item.node); - } - } - } - natMapper(nodeKey) { - if (this.options.natMap && typeof this.options.natMap === "object") { - const key = typeof nodeKey === "string" - ? nodeKey - : `${nodeKey.host}:${nodeKey.port}`; - const mapped = this.options.natMap[key]; - if (mapped) { - debug("NAT mapping %s -> %O", key, mapped); - return Object.assign({}, mapped); - } - } - return typeof nodeKey === "string" - ? util_1.nodeKeyToRedisOptions(nodeKey) - : nodeKey; - } - sendCommand(command, stream, node) { - if (this.status === "wait") { - this.connect().catch(utils_1.noop); - } - if (this.status === "end") { - command.reject(new Error(utils_2.CONNECTION_CLOSED_ERROR_MSG)); - return command.promise; - } - let to = this.options.scaleReads; - if (to !== "master") { - const isCommandReadOnly = command.isReadOnly || - (commands.exists(command.name) && - commands.hasFlag(command.name, "readonly")); - if (!isCommandReadOnly) { - to = "master"; - } - } - let targetSlot = node ? node.slot : command.getSlot(); - const ttl = {}; - const _this = this; - if (!node && !command.__is_reject_overwritten) { - // eslint-disable-next-line @typescript-eslint/camelcase - command.__is_reject_overwritten = true; - const reject = command.reject; - command.reject = function (err) { - const partialTry = tryConnection.bind(null, true); - _this.handleError(err, ttl, { - moved: function (slot, key) { - debug("command %s is moved to %s", command.name, key); - targetSlot = Number(slot); - if (_this.slots[slot]) { - _this.slots[slot][0] = key; - } - else { - _this.slots[slot] = [key]; - } - _this._groupsBySlot[slot] = _this._groupsIds[_this.slots[slot].join(';')]; - _this.connectionPool.findOrCreate(_this.natMapper(key)); - tryConnection(); - debug("refreshing slot caches... (triggered by MOVED error)"); - _this.refreshSlotsCache(); - }, - ask: function (slot, key) { - debug("command %s is required to ask %s:%s", command.name, key); - const mapped = _this.natMapper(key); - _this.connectionPool.findOrCreate(mapped); - tryConnection(false, `${mapped.host}:${mapped.port}`); - }, - tryagain: partialTry, - clusterDown: partialTry, - connectionClosed: partialTry, - maxRedirections: function (redirectionError) { - reject.call(command, redirectionError); - }, - defaults: function () { - reject.call(command, err); - }, - }); - }; - } - tryConnection(); - function tryConnection(random, asking) { - if (_this.status === "end") { - command.reject(new redis_errors_1.AbortError("Cluster is ended.")); - return; - } - let redis; - if (_this.status === "ready" || command.name === "cluster") { - if (node && node.redis) { - redis = node.redis; - } - else if (command_1.default.checkFlag("ENTER_SUBSCRIBER_MODE", command.name) || - command_1.default.checkFlag("EXIT_SUBSCRIBER_MODE", command.name)) { - redis = _this.subscriber.getInstance(); - if (!redis) { - command.reject(new redis_errors_1.AbortError("No subscriber for the cluster")); - return; - } - } - else { - if (!random) { - if (typeof targetSlot === "number" && _this.slots[targetSlot]) { - const nodeKeys = _this.slots[targetSlot]; - if (typeof to === "function") { - const nodes = nodeKeys.map(function (key) { - return _this.connectionPool.getInstanceByKey(key); - }); - redis = to(nodes, command); - if (Array.isArray(redis)) { - redis = utils_2.sample(redis); - } - if (!redis) { - redis = nodes[0]; - } - } - else { - let key; - if (to === "all") { - key = utils_2.sample(nodeKeys); - } - else if (to === "slave" && nodeKeys.length > 1) { - key = utils_2.sample(nodeKeys, 1); - } - else { - key = nodeKeys[0]; - } - redis = _this.connectionPool.getInstanceByKey(key); - } - } - if (asking) { - redis = _this.connectionPool.getInstanceByKey(asking); - redis.asking(); - } - } - if (!redis) { - redis = - (typeof to === "function" - ? null - : _this.connectionPool.getSampleInstance(to)) || - _this.connectionPool.getSampleInstance("all"); - } - } - if (node && !node.redis) { - node.redis = redis; - } - } - if (redis) { - redis.sendCommand(command, stream); - } - else if (_this.options.enableOfflineQueue) { - _this.offlineQueue.push({ - command: command, - stream: stream, - node: node, - }); - } - else { - command.reject(new Error("Cluster isn't ready and enableOfflineQueue options is false")); - } - } - return command.promise; - } - handleError(error, ttl, handlers) { - if (typeof ttl.value === "undefined") { - ttl.value = this.options.maxRedirections; - } - else { - ttl.value -= 1; - } - if (ttl.value <= 0) { - handlers.maxRedirections(new Error("Too many Cluster redirections. Last error: " + error)); - return; - } - const errv = error.message.split(" "); - if (errv[0] === "MOVED") { - const timeout = this.options.retryDelayOnMoved; - if (timeout && typeof timeout === "number") { - this.delayQueue.push("moved", handlers.moved.bind(null, errv[1], errv[2]), { timeout }); - } - else { - handlers.moved(errv[1], errv[2]); - } - } - else if (errv[0] === "ASK") { - handlers.ask(errv[1], errv[2]); - } - else if (errv[0] === "TRYAGAIN") { - this.delayQueue.push("tryagain", handlers.tryagain, { - timeout: this.options.retryDelayOnTryAgain, - }); - } - else if (errv[0] === "CLUSTERDOWN" && - this.options.retryDelayOnClusterDown > 0) { - this.delayQueue.push("clusterdown", handlers.connectionClosed, { - timeout: this.options.retryDelayOnClusterDown, - callback: this.refreshSlotsCache.bind(this), - }); - } - else if (error.message === utils_2.CONNECTION_CLOSED_ERROR_MSG && - this.options.retryDelayOnFailover > 0 && - this.status === "ready") { - this.delayQueue.push("failover", handlers.connectionClosed, { - timeout: this.options.retryDelayOnFailover, - callback: this.refreshSlotsCache.bind(this), - }); - } - else { - handlers.defaults(); - } - } - getInfoFromNode(redis, callback) { - if (!redis) { - return callback(new Error("Node is disconnected")); - } - // Use a duplication of the connection to avoid - // timeouts when the connection is in the blocking - // mode (e.g. waiting for BLPOP). - const duplicatedConnection = redis.duplicate({ - enableOfflineQueue: true, - enableReadyCheck: false, - retryStrategy: null, - connectionName: util_1.getConnectionName("refresher", this.options.redisOptions && this.options.redisOptions.connectionName), - }); - // Ignore error events since we will handle - // exceptions for the CLUSTER SLOTS command. - duplicatedConnection.on("error", utils_1.noop); - duplicatedConnection.cluster("slots", utils_2.timeout((err, result) => { - duplicatedConnection.disconnect(); - if (err) { - return callback(err); - } - if (this.status === "disconnecting" || - this.status === "close" || - this.status === "end") { - debug("ignore CLUSTER.SLOTS results (count: %d) since cluster status is %s", result.length, this.status); - callback(); - return; - } - const nodes = []; - debug("cluster slots result count: %d", result.length); - for (let i = 0; i < result.length; ++i) { - const items = result[i]; - const slotRangeStart = items[0]; - const slotRangeEnd = items[1]; - const keys = []; - for (let j = 2; j < items.length; j++) { - if (!items[j][0]) { - continue; - } - items[j] = this.natMapper({ host: items[j][0], port: items[j][1] }); - items[j].readOnly = j !== 2; - nodes.push(items[j]); - keys.push(items[j].host + ":" + items[j].port); - } - debug("cluster slots result [%d]: slots %d~%d served by %s", i, slotRangeStart, slotRangeEnd, keys); - for (let slot = slotRangeStart; slot <= slotRangeEnd; slot++) { - this.slots[slot] = keys; - } - } - // Assign to each node keys a numeric value to make autopipeline comparison faster. - this._groupsIds = Object.create(null); - let j = 0; - for (let i = 0; i < 16384; i++) { - const target = (this.slots[i] || []).join(';'); - if (!target.length) { - this._groupsBySlot[i] = undefined; - continue; - } - if (!this._groupsIds[target]) { - this._groupsIds[target] = ++j; - } - this._groupsBySlot[i] = this._groupsIds[target]; - } - this.connectionPool.reset(nodes); - callback(); - }, this.options.slotsRefreshTimeout)); - } - invokeReadyDelayedCallbacks(err) { - for (const c of this._readyDelayedCallbacks) { - process.nextTick(c, err); - } - this._readyDelayedCallbacks = []; - } - /** - * Check whether Cluster is able to process commands - * - * @param {Function} callback - * @private - */ - readyCheck(callback) { - this.cluster("info", function (err, res) { - if (err) { - return callback(err); - } - if (typeof res !== "string") { - return callback(); - } - let state; - const lines = res.split("\r\n"); - for (let i = 0; i < lines.length; ++i) { - const parts = lines[i].split(":"); - if (parts[0] === "cluster_state") { - state = parts[1]; - break; - } - } - if (state === "fail") { - debug("cluster state not ok (%s)", state); - callback(null, state); - } - else { - callback(); - } - }); - } - resolveSrv(hostname) { - return new Promise((resolve, reject) => { - this.options.resolveSrv(hostname, (err, records) => { - if (err) { - return reject(err); - } - const self = this, groupedRecords = util_1.groupSrvRecords(records), sortedKeys = Object.keys(groupedRecords).sort((a, b) => parseInt(a) - parseInt(b)); - function tryFirstOne(err) { - if (!sortedKeys.length) { - return reject(err); - } - const key = sortedKeys[0], group = groupedRecords[key], record = util_1.weightSrvRecords(group); - if (!group.records.length) { - sortedKeys.shift(); - } - self.dnsLookup(record.name).then((host) => resolve({ - host, - port: record.port, - }), tryFirstOne); - } - tryFirstOne(); - }); - }); - } - dnsLookup(hostname) { - return new Promise((resolve, reject) => { - this.options.dnsLookup(hostname, (err, address) => { - if (err) { - debug("failed to resolve hostname %s to IP: %s", hostname, err.message); - reject(err); - } - else { - debug("resolved hostname %s to IP %s", hostname, address); - resolve(address); - } - }); - }); - } - /** - * Normalize startup nodes, and resolving hostnames to IPs. - * - * This process happens every time when #connect() is called since - * #startupNodes and DNS records may chanage. - * - * @private - * @returns {Promise} - */ - resolveStartupNodeHostnames() { - if (!Array.isArray(this.startupNodes) || this.startupNodes.length === 0) { - return Promise.reject(new Error("`startupNodes` should contain at least one node.")); - } - const startupNodes = util_1.normalizeNodeOptions(this.startupNodes); - const hostnames = util_1.getUniqueHostnamesFromOptions(startupNodes); - if (hostnames.length === 0) { - return Promise.resolve(startupNodes); - } - return Promise.all(hostnames.map((this.options.useSRVRecords ? this.resolveSrv : this.dnsLookup).bind(this))).then((configs) => { - const hostnameToConfig = utils_2.zipMap(hostnames, configs); - return startupNodes.map((node) => { - const config = hostnameToConfig.get(node.host); - if (!config) { - return node; - } - else if (this.options.useSRVRecords) { - return Object.assign({}, node, config); - } - else { - return Object.assign({}, node, { host: config }); - } - }); - }); - } -} -Object.getOwnPropertyNames(commander_1.default.prototype).forEach((name) => { - if (!Cluster.prototype.hasOwnProperty(name)) { - Cluster.prototype[name] = commander_1.default.prototype[name]; - } -}); -const scanCommands = [ - "sscan", - "hscan", - "zscan", - "sscanBuffer", - "hscanBuffer", - "zscanBuffer", -]; -scanCommands.forEach((command) => { - Cluster.prototype[command + "Stream"] = function (key, options) { - return new ScanStream_1.default(utils_1.defaults({ - objectMode: true, - key: key, - redis: this, - command: command, - }, options)); - }; -}); -(__nccwpck_require__(14645).addTransactionSupport)(Cluster.prototype); -exports["default"] = Cluster; /***/ }), -/***/ 94582: +/***/ 11155: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const utils_1 = __nccwpck_require__(94832); -const net_1 = __nccwpck_require__(41808); -function getNodeKey(node) { - node.port = node.port || 6379; - node.host = node.host || "127.0.0.1"; - return node.host + ":" + node.port; +var Buffer = (__nccwpck_require__(15118).Buffer); + +// Note: UTF16-LE (or UCS2) codec is Node.js native. See encodings/internal.js + +// == UTF16-BE codec. ========================================================== + +exports.utf16be = Utf16BECodec; +function Utf16BECodec() { } -exports.getNodeKey = getNodeKey; -function nodeKeyToRedisOptions(nodeKey) { - const portIndex = nodeKey.lastIndexOf(":"); - if (portIndex === -1) { - throw new Error(`Invalid node key ${nodeKey}`); - } - return { - host: nodeKey.slice(0, portIndex), - port: Number(nodeKey.slice(portIndex + 1)), - }; + +Utf16BECodec.prototype.encoder = Utf16BEEncoder; +Utf16BECodec.prototype.decoder = Utf16BEDecoder; +Utf16BECodec.prototype.bomAware = true; + + +// -- Encoding + +function Utf16BEEncoder() { } -exports.nodeKeyToRedisOptions = nodeKeyToRedisOptions; -function normalizeNodeOptions(nodes) { - return nodes.map((node) => { - const options = {}; - if (typeof node === "object") { - Object.assign(options, node); - } - else if (typeof node === "string") { - Object.assign(options, utils_1.parseURL(node)); - } - else if (typeof node === "number") { - options.port = node; - } - else { - throw new Error("Invalid argument " + node); - } - if (typeof options.port === "string") { - options.port = parseInt(options.port, 10); - } - // Cluster mode only support db 0 - delete options.db; - if (!options.port) { - options.port = 6379; - } - if (!options.host) { - options.host = "127.0.0.1"; - } - return utils_1.resolveTLSProfile(options); - }); + +Utf16BEEncoder.prototype.write = function(str) { + var buf = Buffer.from(str, 'ucs2'); + for (var i = 0; i < buf.length; i += 2) { + var tmp = buf[i]; buf[i] = buf[i+1]; buf[i+1] = tmp; + } + return buf; } -exports.normalizeNodeOptions = normalizeNodeOptions; -function getUniqueHostnamesFromOptions(nodes) { - const uniqueHostsMap = {}; - nodes.forEach((node) => { - uniqueHostsMap[node.host] = true; - }); - return Object.keys(uniqueHostsMap).filter((host) => !net_1.isIP(host)); + +Utf16BEEncoder.prototype.end = function() { } -exports.getUniqueHostnamesFromOptions = getUniqueHostnamesFromOptions; -function groupSrvRecords(records) { - const recordsByPriority = {}; - for (const record of records) { - if (!recordsByPriority.hasOwnProperty(record.priority)) { - recordsByPriority[record.priority] = { - totalWeight: record.weight, - records: [record], - }; - } - else { - recordsByPriority[record.priority].totalWeight += record.weight; - recordsByPriority[record.priority].records.push(record); - } - } - return recordsByPriority; + + +// -- Decoding + +function Utf16BEDecoder() { + this.overflowByte = -1; } -exports.groupSrvRecords = groupSrvRecords; -function weightSrvRecords(recordsGroup) { - if (recordsGroup.records.length === 1) { - recordsGroup.totalWeight = 0; - return recordsGroup.records.shift(); + +Utf16BEDecoder.prototype.write = function(buf) { + if (buf.length == 0) + return ''; + + var buf2 = Buffer.alloc(buf.length + 1), + i = 0, j = 0; + + if (this.overflowByte !== -1) { + buf2[0] = buf[0]; + buf2[1] = this.overflowByte; + i = 1; j = 2; } - // + `recordsGroup.records.length` to support `weight` 0 - const random = Math.floor(Math.random() * (recordsGroup.totalWeight + recordsGroup.records.length)); - let total = 0; - for (const [i, record] of recordsGroup.records.entries()) { - total += 1 + record.weight; - if (total > random) { - recordsGroup.totalWeight -= record.weight; - recordsGroup.records.splice(i, 1); - return record; - } + + for (; i < buf.length-1; i += 2, j+= 2) { + buf2[j] = buf[i+1]; + buf2[j+1] = buf[i]; } + + this.overflowByte = (i == buf.length-1) ? buf[buf.length-1] : -1; + + return buf2.slice(0, j).toString('ucs2'); } -exports.weightSrvRecords = weightSrvRecords; -function getConnectionName(component, nodeConnectionName) { - const prefix = `ioredis-cluster(${component})`; - return nodeConnectionName ? `${prefix}:${nodeConnectionName}` : prefix; + +Utf16BEDecoder.prototype.end = function() { } -exports.getConnectionName = getConnectionName; -/***/ }), +// == UTF-16 codec ============================================================= +// Decoder chooses automatically from UTF-16LE and UTF-16BE using BOM and space-based heuristic. +// Defaults to UTF-16LE, as it's prevalent and default in Node. +// http://en.wikipedia.org/wiki/UTF-16 and http://encoding.spec.whatwg.org/#utf-16le +// Decoder default can be changed: iconv.decode(buf, 'utf16', {defaultEncoding: 'utf-16be'}); -/***/ 90803: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +// Encoder uses UTF-16LE and prepends BOM (which can be overridden with addBOM: false). -"use strict"; +exports.utf16 = Utf16Codec; +function Utf16Codec(codecOptions, iconv) { + this.iconv = iconv; +} -Object.defineProperty(exports, "__esModule", ({ value: true })); -const commands = __nccwpck_require__(98020); -const calculateSlot = __nccwpck_require__(48481); -const standard_as_callback_1 = __nccwpck_require__(91543); -const utils_1 = __nccwpck_require__(94832); -const lodash_1 = __nccwpck_require__(20961); -const promiseContainer_1 = __nccwpck_require__(71475); -/** - * Command instance - * - * It's rare that you need to create a Command instance yourself. - * - * @export - * @class Command - * - * @example - * ```js - * var infoCommand = new Command('info', null, function (err, result) { - * console.log('result', result); - * }); - * - * redis.sendCommand(infoCommand); - * - * // When no callback provided, Command instance will have a `promise` property, - * // which will resolve/reject with the result of the command. - * var getCommand = new Command('get', ['foo']); - * getCommand.promise.then(function (result) { - * console.log('result', result); - * }); - * ``` - * @see {@link Redis#sendCommand} which can send a Command instance to Redis - */ -class Command { - /** - * Creates an instance of Command. - * @param {string} name Command name - * @param {(Array)} [args=[]] An array of command arguments - * @param {ICommandOptions} [options={}] - * @param {CallbackFunction} [callback] The callback that handles the response. - * If omit, the response will be handled via Promise - * @memberof Command - */ - constructor(name, args = [], options = {}, callback) { - this.name = name; - this.transformed = false; - this.isCustomCommand = false; - this.inTransaction = false; - this.isResolved = false; - this.replyEncoding = options.replyEncoding; - this.errorStack = options.errorStack; - this.args = lodash_1.flatten(args); - this.callback = callback; - this.initPromise(); - if (options.keyPrefix) { - this._iterateKeys((key) => options.keyPrefix + key); - } - if (options.readOnly) { - this.isReadOnly = true; - } - } - static getFlagMap() { - if (!this.flagMap) { - this.flagMap = Object.keys(Command.FLAGS).reduce((map, flagName) => { - map[flagName] = {}; - Command.FLAGS[flagName].forEach((commandName) => { - map[flagName][commandName] = true; - }); - return map; - }, {}); - } - return this.flagMap; - } - /** - * Check whether the command has the flag - * - * @param {string} flagName - * @param {string} commandName - * @return {boolean} - */ - static checkFlag(flagName, commandName) { - return !!this.getFlagMap()[flagName][commandName]; - } - static setArgumentTransformer(name, func) { - this._transformer.argument[name] = func; - } - static setReplyTransformer(name, func) { - this._transformer.reply[name] = func; - } - initPromise() { - const Promise = promiseContainer_1.get(); - const promise = new Promise((resolve, reject) => { - if (!this.transformed) { - this.transformed = true; - const transformer = Command._transformer.argument[this.name]; - if (transformer) { - this.args = transformer(this.args); - } - this.stringifyArguments(); - } - this.resolve = this._convertValue(resolve); - if (this.errorStack) { - this.reject = (err) => { - reject(utils_1.optimizeErrorStack(err, this.errorStack.stack, __dirname)); - }; - } - else { - this.reject = reject; - } - }); - this.promise = standard_as_callback_1.default(promise, this.callback); - } - getSlot() { - if (typeof this.slot === "undefined") { - const key = this.getKeys()[0]; - this.slot = key == null ? null : calculateSlot(key); - } - return this.slot; +Utf16Codec.prototype.encoder = Utf16Encoder; +Utf16Codec.prototype.decoder = Utf16Decoder; + + +// -- Encoding (pass-through) + +function Utf16Encoder(options, codec) { + options = options || {}; + if (options.addBOM === undefined) + options.addBOM = true; + this.encoder = codec.iconv.getEncoder('utf-16le', options); +} + +Utf16Encoder.prototype.write = function(str) { + return this.encoder.write(str); +} + +Utf16Encoder.prototype.end = function() { + return this.encoder.end(); +} + + +// -- Decoding + +function Utf16Decoder(options, codec) { + this.decoder = null; + this.initialBytes = []; + this.initialBytesLen = 0; + + this.options = options || {}; + this.iconv = codec.iconv; +} + +Utf16Decoder.prototype.write = function(buf) { + if (!this.decoder) { + // Codec is not chosen yet. Accumulate initial bytes. + this.initialBytes.push(buf); + this.initialBytesLen += buf.length; + + if (this.initialBytesLen < 16) // We need more bytes to use space heuristic (see below) + return ''; + + // We have enough bytes -> detect endianness. + var buf = Buffer.concat(this.initialBytes), + encoding = detectEncoding(buf, this.options.defaultEncoding); + this.decoder = this.iconv.getDecoder(encoding, this.options); + this.initialBytes.length = this.initialBytesLen = 0; } - getKeys() { - return this._iterateKeys(); + + return this.decoder.write(buf); +} + +Utf16Decoder.prototype.end = function() { + if (!this.decoder) { + var buf = Buffer.concat(this.initialBytes), + encoding = detectEncoding(buf, this.options.defaultEncoding); + this.decoder = this.iconv.getDecoder(encoding, this.options); + + var res = this.decoder.write(buf), + trail = this.decoder.end(); + + return trail ? (res + trail) : res; } - /** - * Iterate through the command arguments that are considered keys. - * - * @param {Function} [transform=(key) => key] The transformation that should be applied to - * each key. The transformations will persist. - * @returns {string[]} The keys of the command. - * @memberof Command - */ - _iterateKeys(transform = (key) => key) { - if (typeof this.keys === "undefined") { - this.keys = []; - if (commands.exists(this.name)) { - const keyIndexes = commands.getKeyIndexes(this.name, this.args); - for (const index of keyIndexes) { - this.args[index] = transform(this.args[index]); - this.keys.push(this.args[index]); - } + return this.decoder.end(); +} + +function detectEncoding(buf, defaultEncoding) { + var enc = defaultEncoding || 'utf-16le'; + + if (buf.length >= 2) { + // Check BOM. + if (buf[0] == 0xFE && buf[1] == 0xFF) // UTF-16BE BOM + enc = 'utf-16be'; + else if (buf[0] == 0xFF && buf[1] == 0xFE) // UTF-16LE BOM + enc = 'utf-16le'; + else { + // No BOM found. Try to deduce encoding from initial content. + // Most of the time, the content has ASCII chars (U+00**), but the opposite (U+**00) is uncommon. + // So, we count ASCII as if it was LE or BE, and decide from that. + var asciiCharsLE = 0, asciiCharsBE = 0, // Counts of chars in both positions + _len = Math.min(buf.length - (buf.length % 2), 64); // Len is always even. + + for (var i = 0; i < _len; i += 2) { + if (buf[i] === 0 && buf[i+1] !== 0) asciiCharsBE++; + if (buf[i] !== 0 && buf[i+1] === 0) asciiCharsLE++; } + + if (asciiCharsBE > asciiCharsLE) + enc = 'utf-16be'; + else if (asciiCharsBE < asciiCharsLE) + enc = 'utf-16le'; } - return this.keys; } - /** - * Convert command to writable buffer or string - * - * @return {string|Buffer} - * @see {@link Redis#sendCommand} - * @public - */ - toWritable() { - let bufferMode = false; - for (const arg of this.args) { - if (arg instanceof Buffer) { - bufferMode = true; - break; + + return enc; +} + + + + +/***/ }), + +/***/ 51644: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +var Buffer = (__nccwpck_require__(15118).Buffer); + +// UTF-7 codec, according to https://tools.ietf.org/html/rfc2152 +// See also below a UTF-7-IMAP codec, according to http://tools.ietf.org/html/rfc3501#section-5.1.3 + +exports.utf7 = Utf7Codec; +exports.unicode11utf7 = 'utf7'; // Alias UNICODE-1-1-UTF-7 +function Utf7Codec(codecOptions, iconv) { + this.iconv = iconv; +}; + +Utf7Codec.prototype.encoder = Utf7Encoder; +Utf7Codec.prototype.decoder = Utf7Decoder; +Utf7Codec.prototype.bomAware = true; + + +// -- Encoding + +var nonDirectChars = /[^A-Za-z0-9'\(\),-\.\/:\? \n\r\t]+/g; + +function Utf7Encoder(options, codec) { + this.iconv = codec.iconv; +} + +Utf7Encoder.prototype.write = function(str) { + // Naive implementation. + // Non-direct chars are encoded as "+-"; single "+" char is encoded as "+-". + return Buffer.from(str.replace(nonDirectChars, function(chunk) { + return "+" + (chunk === '+' ? '' : + this.iconv.encode(chunk, 'utf16-be').toString('base64').replace(/=+$/, '')) + + "-"; + }.bind(this))); +} + +Utf7Encoder.prototype.end = function() { +} + + +// -- Decoding + +function Utf7Decoder(options, codec) { + this.iconv = codec.iconv; + this.inBase64 = false; + this.base64Accum = ''; +} + +var base64Regex = /[A-Za-z0-9\/+]/; +var base64Chars = []; +for (var i = 0; i < 256; i++) + base64Chars[i] = base64Regex.test(String.fromCharCode(i)); + +var plusChar = '+'.charCodeAt(0), + minusChar = '-'.charCodeAt(0), + andChar = '&'.charCodeAt(0); + +Utf7Decoder.prototype.write = function(buf) { + var res = "", lastI = 0, + inBase64 = this.inBase64, + base64Accum = this.base64Accum; + + // The decoder is more involved as we must handle chunks in stream. + + for (var i = 0; i < buf.length; i++) { + if (!inBase64) { // We're in direct mode. + // Write direct chars until '+' + if (buf[i] == plusChar) { + res += this.iconv.decode(buf.slice(lastI, i), "ascii"); // Write direct chars. + lastI = i+1; + inBase64 = true; } - } - let result; - const commandStr = "*" + - (this.args.length + 1) + - "\r\n$" + - Buffer.byteLength(this.name) + - "\r\n" + - this.name + - "\r\n"; - if (bufferMode) { - const buffers = new MixedBuffers(); - buffers.push(commandStr); - for (const arg of this.args) { - if (arg instanceof Buffer) { - if (arg.length === 0) { - buffers.push("$0\r\n\r\n"); - } - else { - buffers.push("$" + arg.length + "\r\n"); - buffers.push(arg); - buffers.push("\r\n"); - } - } - else { - buffers.push("$" + - Buffer.byteLength(arg) + - "\r\n" + - arg + - "\r\n"); + } else { // We decode base64. + if (!base64Chars[buf[i]]) { // Base64 ended. + if (i == lastI && buf[i] == minusChar) {// "+-" -> "+" + res += "+"; + } else { + var b64str = base64Accum + buf.slice(lastI, i).toString(); + res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); } - } - result = buffers.toBuffer(); - } - else { - result = commandStr; - for (const arg of this.args) { - result += - "$" + - Buffer.byteLength(arg) + - "\r\n" + - arg + - "\r\n"; + + if (buf[i] != minusChar) // Minus is absorbed after base64. + i--; + + lastI = i+1; + inBase64 = false; + base64Accum = ''; } } - return result; } - stringifyArguments() { - for (let i = 0; i < this.args.length; ++i) { - const arg = this.args[i]; - if (!(arg instanceof Buffer) && typeof arg !== "string") { - this.args[i] = utils_1.toArg(arg); - } - } + + if (!inBase64) { + res += this.iconv.decode(buf.slice(lastI), "ascii"); // Write direct chars. + } else { + var b64str = base64Accum + buf.slice(lastI).toString(); + + var canBeDecoded = b64str.length - (b64str.length % 8); // Minimal chunk: 2 quads -> 2x3 bytes -> 3 chars. + base64Accum = b64str.slice(canBeDecoded); // The rest will be decoded in future. + b64str = b64str.slice(0, canBeDecoded); + + res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); } - /** - * Convert the value from buffer to the target encoding. - * - * @private - * @param {Function} resolve The resolve function of the Promise - * @returns {Function} A function to transform and resolve a value - * @memberof Command - */ - _convertValue(resolve) { - return (value) => { - try { - const existingTimer = this._commandTimeoutTimer; - if (existingTimer) { - clearTimeout(existingTimer); - delete this._commandTimeoutTimer; + + this.inBase64 = inBase64; + this.base64Accum = base64Accum; + + return res; +} + +Utf7Decoder.prototype.end = function() { + var res = ""; + if (this.inBase64 && this.base64Accum.length > 0) + res = this.iconv.decode(Buffer.from(this.base64Accum, 'base64'), "utf16-be"); + + this.inBase64 = false; + this.base64Accum = ''; + return res; +} + + +// UTF-7-IMAP codec. +// RFC3501 Sec. 5.1.3 Modified UTF-7 (http://tools.ietf.org/html/rfc3501#section-5.1.3) +// Differences: +// * Base64 part is started by "&" instead of "+" +// * Direct characters are 0x20-0x7E, except "&" (0x26) +// * In Base64, "," is used instead of "/" +// * Base64 must not be used to represent direct characters. +// * No implicit shift back from Base64 (should always end with '-') +// * String must end in non-shifted position. +// * "-&" while in base64 is not allowed. + + +exports.utf7imap = Utf7IMAPCodec; +function Utf7IMAPCodec(codecOptions, iconv) { + this.iconv = iconv; +}; + +Utf7IMAPCodec.prototype.encoder = Utf7IMAPEncoder; +Utf7IMAPCodec.prototype.decoder = Utf7IMAPDecoder; +Utf7IMAPCodec.prototype.bomAware = true; + + +// -- Encoding + +function Utf7IMAPEncoder(options, codec) { + this.iconv = codec.iconv; + this.inBase64 = false; + this.base64Accum = Buffer.alloc(6); + this.base64AccumIdx = 0; +} + +Utf7IMAPEncoder.prototype.write = function(str) { + var inBase64 = this.inBase64, + base64Accum = this.base64Accum, + base64AccumIdx = this.base64AccumIdx, + buf = Buffer.alloc(str.length*5 + 10), bufIdx = 0; + + for (var i = 0; i < str.length; i++) { + var uChar = str.charCodeAt(i); + if (0x20 <= uChar && uChar <= 0x7E) { // Direct character or '&'. + if (inBase64) { + if (base64AccumIdx > 0) { + bufIdx += buf.write(base64Accum.slice(0, base64AccumIdx).toString('base64').replace(/\//g, ',').replace(/=+$/, ''), bufIdx); + base64AccumIdx = 0; } - resolve(this.transformReply(value)); - this.isResolved = true; + + buf[bufIdx++] = minusChar; // Write '-', then go to direct mode. + inBase64 = false; } - catch (err) { - this.reject(err); + + if (!inBase64) { + buf[bufIdx++] = uChar; // Write direct character + + if (uChar === andChar) // Ampersand -> '&-' + buf[bufIdx++] = minusChar; } - return this.promise; - }; - } - /** - * Convert buffer/buffer[] to string/string[], - * and apply reply transformer. - * - * @memberof Command - */ - transformReply(result) { - if (this.replyEncoding) { - result = utils_1.convertBufferToString(result, this.replyEncoding); - } - const transformer = Command._transformer.reply[this.name]; - if (transformer) { - result = transformer(result); - } - return result; - } - /** - * Set the wait time before terminating the attempt to execute a command - * and generating an error. - */ - setTimeout(ms) { - if (!this._commandTimeoutTimer) { - this._commandTimeoutTimer = setTimeout(() => { - if (!this.isResolved) { - this.reject(new Error("Command timed out")); + + } else { // Non-direct character + if (!inBase64) { + buf[bufIdx++] = andChar; // Write '&', then go to base64 mode. + inBase64 = true; + } + if (inBase64) { + base64Accum[base64AccumIdx++] = uChar >> 8; + base64Accum[base64AccumIdx++] = uChar & 0xFF; + + if (base64AccumIdx == base64Accum.length) { + bufIdx += buf.write(base64Accum.toString('base64').replace(/\//g, ','), bufIdx); + base64AccumIdx = 0; } - }, ms); + } } } + + this.inBase64 = inBase64; + this.base64AccumIdx = base64AccumIdx; + + return buf.slice(0, bufIdx); } -exports["default"] = Command; -Command.FLAGS = { - VALID_IN_SUBSCRIBER_MODE: [ - "subscribe", - "psubscribe", - "unsubscribe", - "punsubscribe", - "ping", - "quit", - ], - VALID_IN_MONITOR_MODE: ["monitor", "auth"], - ENTER_SUBSCRIBER_MODE: ["subscribe", "psubscribe"], - EXIT_SUBSCRIBER_MODE: ["unsubscribe", "punsubscribe"], - WILL_DISCONNECT: ["quit"], -}; -Command._transformer = { - argument: {}, - reply: {}, -}; -const msetArgumentTransformer = function (args) { - if (args.length === 1) { - if (typeof Map !== "undefined" && args[0] instanceof Map) { - return utils_1.convertMapToArray(args[0]); - } - if (typeof args[0] === "object" && args[0] !== null) { - return utils_1.convertObjectToArray(args[0]); - } - } - return args; -}; -const hsetArgumentTransformer = function (args) { - if (args.length === 2) { - if (typeof Map !== "undefined" && args[1] instanceof Map) { - return [args[0]].concat(utils_1.convertMapToArray(args[1])); - } - if (typeof args[1] === "object" && args[1] !== null) { - return [args[0]].concat(utils_1.convertObjectToArray(args[1])); + +Utf7IMAPEncoder.prototype.end = function() { + var buf = Buffer.alloc(10), bufIdx = 0; + if (this.inBase64) { + if (this.base64AccumIdx > 0) { + bufIdx += buf.write(this.base64Accum.slice(0, this.base64AccumIdx).toString('base64').replace(/\//g, ',').replace(/=+$/, ''), bufIdx); + this.base64AccumIdx = 0; } + + buf[bufIdx++] = minusChar; // Write '-', then go to direct mode. + this.inBase64 = false; } - return args; -}; -Command.setArgumentTransformer("mset", msetArgumentTransformer); -Command.setArgumentTransformer("msetnx", msetArgumentTransformer); -Command.setArgumentTransformer("hset", hsetArgumentTransformer); -Command.setArgumentTransformer("hmset", hsetArgumentTransformer); -Command.setReplyTransformer("hgetall", function (result) { - if (Array.isArray(result)) { - const obj = {}; - for (let i = 0; i < result.length; i += 2) { - const key = result[i]; - const value = result[i + 1]; - if (key in obj) { - // can only be truthy if the property is special somehow, like '__proto__' or 'constructor' - // https://github.com/luin/ioredis/issues/1267 - Object.defineProperty(obj, key, { - value, - configurable: true, - enumerable: true, - writable: true, - }); + + return buf.slice(0, bufIdx); +} + + +// -- Decoding + +function Utf7IMAPDecoder(options, codec) { + this.iconv = codec.iconv; + this.inBase64 = false; + this.base64Accum = ''; +} + +var base64IMAPChars = base64Chars.slice(); +base64IMAPChars[','.charCodeAt(0)] = true; + +Utf7IMAPDecoder.prototype.write = function(buf) { + var res = "", lastI = 0, + inBase64 = this.inBase64, + base64Accum = this.base64Accum; + + // The decoder is more involved as we must handle chunks in stream. + // It is forgiving, closer to standard UTF-7 (for example, '-' is optional at the end). + + for (var i = 0; i < buf.length; i++) { + if (!inBase64) { // We're in direct mode. + // Write direct chars until '&' + if (buf[i] == andChar) { + res += this.iconv.decode(buf.slice(lastI, i), "ascii"); // Write direct chars. + lastI = i+1; + inBase64 = true; } - else { - obj[key] = value; + } else { // We decode base64. + if (!base64IMAPChars[buf[i]]) { // Base64 ended. + if (i == lastI && buf[i] == minusChar) { // "&-" -> "&" + res += "&"; + } else { + var b64str = base64Accum + buf.slice(lastI, i).toString().replace(/,/g, '/'); + res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); + } + + if (buf[i] != minusChar) // Minus may be absorbed after base64. + i--; + + lastI = i+1; + inBase64 = false; + base64Accum = ''; } } - return obj; - } - return result; -}); -class MixedBuffers { - constructor() { - this.length = 0; - this.items = []; } - push(x) { - this.length += Buffer.byteLength(x); - this.items.push(x); - } - toBuffer() { - const result = Buffer.allocUnsafe(this.length); - let offset = 0; - for (const item of this.items) { - const length = Buffer.byteLength(item); - Buffer.isBuffer(item) - ? item.copy(result, offset) - : result.write(item, offset, length); - offset += length; - } - return result; + + if (!inBase64) { + res += this.iconv.decode(buf.slice(lastI), "ascii"); // Write direct chars. + } else { + var b64str = base64Accum + buf.slice(lastI).toString().replace(/,/g, '/'); + + var canBeDecoded = b64str.length - (b64str.length % 8); // Minimal chunk: 2 quads -> 2x3 bytes -> 3 chars. + base64Accum = b64str.slice(canBeDecoded); // The rest will be decoded in future. + b64str = b64str.slice(0, canBeDecoded); + + res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); } + + this.inBase64 = inBase64; + this.base64Accum = base64Accum; + + return res; +} + +Utf7IMAPDecoder.prototype.end = function() { + var res = ""; + if (this.inBase64 && this.base64Accum.length > 0) + res = this.iconv.decode(Buffer.from(this.base64Accum, 'base64'), "utf16-be"); + + this.inBase64 = false; + this.base64Accum = ''; + return res; } + + /***/ }), -/***/ 33642: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 67961: +/***/ ((__unused_webpack_module, exports) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const lodash_1 = __nccwpck_require__(20961); -const command_1 = __nccwpck_require__(90803); -const script_1 = __nccwpck_require__(88540); -const PromiseContainer = __nccwpck_require__(71475); -const standard_as_callback_1 = __nccwpck_require__(91543); -const autoPipelining_1 = __nccwpck_require__(97873); -const DROP_BUFFER_SUPPORT_ERROR = "*Buffer methods are not available " + - 'because "dropBufferSupport" option is enabled.' + - "Refer to https://github.com/luin/ioredis/wiki/Improve-Performance for more details."; -/** - * Commander - * - * This is the base class of Redis, Redis.Cluster and Pipeline - * - * @param {boolean} [options.showFriendlyErrorStack=false] - Whether to show a friendly error stack. - * Will decrease the performance significantly. - * @constructor - */ -function Commander() { - this.options = lodash_1.defaults({}, this.options || {}, { - showFriendlyErrorStack: false, - }); - this.scriptsSet = {}; - this.addedBuiltinSet = new Set(); + +var BOMChar = '\uFEFF'; + +exports.PrependBOM = PrependBOMWrapper +function PrependBOMWrapper(encoder, options) { + this.encoder = encoder; + this.addBOM = true; } -exports["default"] = Commander; -const commands = (__nccwpck_require__(98020).list.filter)(function (command) { - return command !== "monitor"; -}); -commands.push("sentinel"); -/** - * Return supported builtin commands - * - * @return {string[]} command list - * @public - */ -Commander.prototype.getBuiltinCommands = function () { - return commands.slice(0); -}; -/** - * Create a builtin command - * - * @param {string} commandName - command name - * @return {object} functions - * @public - */ -Commander.prototype.createBuiltinCommand = function (commandName) { - return { - string: generateFunction(null, commandName, "utf8"), - buffer: generateFunction(null, commandName, null), - }; -}; -/** - * Create add builtin command - * - * @param {string} commandName - command name - * @return {object} functions - * @public - */ -Commander.prototype.addBuiltinCommand = function (commandName) { - this.addedBuiltinSet.add(commandName); - this[commandName] = generateFunction(commandName, commandName, "utf8"); - this[commandName + "Buffer"] = generateFunction(commandName + "Buffer", commandName, null); -}; -commands.forEach(function (commandName) { - Commander.prototype[commandName] = generateFunction(commandName, commandName, "utf8"); - Commander.prototype[commandName + "Buffer"] = generateFunction(commandName + "Buffer", commandName, null); -}); -Commander.prototype.call = generateFunction("call", "utf8"); -Commander.prototype.callBuffer = generateFunction("callBuffer", null); -// eslint-disable-next-line @typescript-eslint/camelcase -Commander.prototype.send_command = Commander.prototype.call; -/** - * Define a custom command using lua script - * - * @param {string} name - the command name - * @param {object} definition - * @param {string} definition.lua - the lua code - * @param {number} [definition.numberOfKeys=null] - the number of keys. - * @param {boolean} [definition.readOnly=false] - force this script to be readonly so it executes on slaves as well. - * If omit, you have to pass the number of keys as the first argument every time you invoke the command - */ -Commander.prototype.defineCommand = function (name, definition) { - const script = new script_1.default(definition.lua, definition.numberOfKeys, this.options.keyPrefix, definition.readOnly); - this.scriptsSet[name] = script; - this[name] = generateScriptingFunction(name, name, script, "utf8"); - this[name + "Buffer"] = generateScriptingFunction(name + "Buffer", name, script, null); -}; -/** - * Send a command - * - * @abstract - * @public - */ -Commander.prototype.sendCommand = function () { }; -function generateFunction(functionName, _commandName, _encoding) { - if (typeof _encoding === "undefined") { - _encoding = _commandName; - _commandName = null; + +PrependBOMWrapper.prototype.write = function(str) { + if (this.addBOM) { + str = BOMChar + str; + this.addBOM = false; + } + + return this.encoder.write(str); +} + +PrependBOMWrapper.prototype.end = function() { + return this.encoder.end(); +} + + +//------------------------------------------------------------------------------ + +exports.StripBOM = StripBOMWrapper; +function StripBOMWrapper(decoder, options) { + this.decoder = decoder; + this.pass = false; + this.options = options || {}; +} + +StripBOMWrapper.prototype.write = function(buf) { + var res = this.decoder.write(buf); + if (this.pass || !res) + return res; + + if (res[0] === BOMChar) { + res = res.slice(1); + if (typeof this.options.stripBOM === 'function') + this.options.stripBOM(); } - return function (...args) { - const commandName = _commandName || args.shift(); - let callback = args[args.length - 1]; - if (typeof callback === "function") { - args.pop(); - } - else { - callback = undefined; + + this.pass = true; + return res; +} + +StripBOMWrapper.prototype.end = function() { + return this.decoder.end(); +} + + + +/***/ }), + +/***/ 30393: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + +var Buffer = (__nccwpck_require__(14300).Buffer); +// Note: not polyfilled with safer-buffer on a purpose, as overrides Buffer + +// == Extend Node primitives to use iconv-lite ================================= + +module.exports = function (iconv) { + var original = undefined; // Place to keep original methods. + + // Node authors rewrote Buffer internals to make it compatible with + // Uint8Array and we cannot patch key functions since then. + // Note: this does use older Buffer API on a purpose + iconv.supportsNodeEncodingsExtension = !(Buffer.from || new Buffer(0) instanceof Uint8Array); + + iconv.extendNodeEncodings = function extendNodeEncodings() { + if (original) return; + original = {}; + + if (!iconv.supportsNodeEncodingsExtension) { + console.error("ACTION NEEDED: require('iconv-lite').extendNodeEncodings() is not supported in your version of Node"); + console.error("See more info at https://github.com/ashtuchkin/iconv-lite/wiki/Node-v4-compatibility"); + return; } - const options = { - errorStack: this.options.showFriendlyErrorStack ? new Error() : undefined, - keyPrefix: this.options.keyPrefix, - replyEncoding: _encoding, + + var nodeNativeEncodings = { + 'hex': true, 'utf8': true, 'utf-8': true, 'ascii': true, 'binary': true, + 'base64': true, 'ucs2': true, 'ucs-2': true, 'utf16le': true, 'utf-16le': true, }; - if (this.options.dropBufferSupport && !_encoding) { - return standard_as_callback_1.default(PromiseContainer.get().reject(new Error(DROP_BUFFER_SUPPORT_ERROR)), callback); + + Buffer.isNativeEncoding = function(enc) { + return enc && nodeNativeEncodings[enc.toLowerCase()]; } - // No auto pipeline, use regular command sending - if (!autoPipelining_1.shouldUseAutoPipelining(this, functionName, commandName)) { - return this.sendCommand(new command_1.default(commandName, args, options, callback)); + + // -- SlowBuffer ----------------------------------------------------------- + var SlowBuffer = (__nccwpck_require__(14300).SlowBuffer); + + original.SlowBufferToString = SlowBuffer.prototype.toString; + SlowBuffer.prototype.toString = function(encoding, start, end) { + encoding = String(encoding || 'utf8').toLowerCase(); + + // Use native conversion when possible + if (Buffer.isNativeEncoding(encoding)) + return original.SlowBufferToString.call(this, encoding, start, end); + + // Otherwise, use our decoding method. + if (typeof start == 'undefined') start = 0; + if (typeof end == 'undefined') end = this.length; + return iconv.decode(this.slice(start, end), encoding); } - // Create a new pipeline and make sure it's scheduled - return autoPipelining_1.executeWithAutoPipelining(this, functionName, commandName, args, callback); - }; -} -function generateScriptingFunction(functionName, commandName, script, encoding) { - return function () { - let length = arguments.length; - const lastArgIndex = length - 1; - let callback = arguments[lastArgIndex]; - if (typeof callback !== "function") { - callback = undefined; + + original.SlowBufferWrite = SlowBuffer.prototype.write; + SlowBuffer.prototype.write = function(string, offset, length, encoding) { + // Support both (string, offset, length, encoding) + // and the legacy (string, encoding, offset, length) + if (isFinite(offset)) { + if (!isFinite(length)) { + encoding = length; + length = undefined; + } + } else { // legacy + var swap = encoding; + encoding = offset; + offset = length; + length = swap; + } + + offset = +offset || 0; + var remaining = this.length - offset; + if (!length) { + length = remaining; + } else { + length = +length; + if (length > remaining) { + length = remaining; + } + } + encoding = String(encoding || 'utf8').toLowerCase(); + + // Use native conversion when possible + if (Buffer.isNativeEncoding(encoding)) + return original.SlowBufferWrite.call(this, string, offset, length, encoding); + + if (string.length > 0 && (length < 0 || offset < 0)) + throw new RangeError('attempt to write beyond buffer bounds'); + + // Otherwise, use our encoding method. + var buf = iconv.encode(string, encoding); + if (buf.length < length) length = buf.length; + buf.copy(this, offset, 0, length); + return length; } - else { - length = lastArgIndex; + + // -- Buffer --------------------------------------------------------------- + + original.BufferIsEncoding = Buffer.isEncoding; + Buffer.isEncoding = function(encoding) { + return Buffer.isNativeEncoding(encoding) || iconv.encodingExists(encoding); } - const args = new Array(length); - for (let i = 0; i < length; i++) { - args[i] = arguments[i]; + + original.BufferByteLength = Buffer.byteLength; + Buffer.byteLength = SlowBuffer.byteLength = function(str, encoding) { + encoding = String(encoding || 'utf8').toLowerCase(); + + // Use native conversion when possible + if (Buffer.isNativeEncoding(encoding)) + return original.BufferByteLength.call(this, str, encoding); + + // Slow, I know, but we don't have a better way yet. + return iconv.encode(str, encoding).length; } - let options; - if (this.options.dropBufferSupport) { - if (!encoding) { - return standard_as_callback_1.default(PromiseContainer.get().reject(new Error(DROP_BUFFER_SUPPORT_ERROR)), callback); - } - options = { replyEncoding: null }; + + original.BufferToString = Buffer.prototype.toString; + Buffer.prototype.toString = function(encoding, start, end) { + encoding = String(encoding || 'utf8').toLowerCase(); + + // Use native conversion when possible + if (Buffer.isNativeEncoding(encoding)) + return original.BufferToString.call(this, encoding, start, end); + + // Otherwise, use our decoding method. + if (typeof start == 'undefined') start = 0; + if (typeof end == 'undefined') end = this.length; + return iconv.decode(this.slice(start, end), encoding); } - else { - options = { replyEncoding: encoding }; + + original.BufferWrite = Buffer.prototype.write; + Buffer.prototype.write = function(string, offset, length, encoding) { + var _offset = offset, _length = length, _encoding = encoding; + // Support both (string, offset, length, encoding) + // and the legacy (string, encoding, offset, length) + if (isFinite(offset)) { + if (!isFinite(length)) { + encoding = length; + length = undefined; + } + } else { // legacy + var swap = encoding; + encoding = offset; + offset = length; + length = swap; + } + + encoding = String(encoding || 'utf8').toLowerCase(); + + // Use native conversion when possible + if (Buffer.isNativeEncoding(encoding)) + return original.BufferWrite.call(this, string, _offset, _length, _encoding); + + offset = +offset || 0; + var remaining = this.length - offset; + if (!length) { + length = remaining; + } else { + length = +length; + if (length > remaining) { + length = remaining; + } + } + + if (string.length > 0 && (length < 0 || offset < 0)) + throw new RangeError('attempt to write beyond buffer bounds'); + + // Otherwise, use our encoding method. + var buf = iconv.encode(string, encoding); + if (buf.length < length) length = buf.length; + buf.copy(this, offset, 0, length); + return length; + + // TODO: Set _charsWritten. } - if (this.options.showFriendlyErrorStack) { - options.errorStack = new Error(); + + + // -- Readable ------------------------------------------------------------- + if (iconv.supportsStreams) { + var Readable = (__nccwpck_require__(12781).Readable); + + original.ReadableSetEncoding = Readable.prototype.setEncoding; + Readable.prototype.setEncoding = function setEncoding(enc, options) { + // Use our own decoder, it has the same interface. + // We cannot use original function as it doesn't handle BOM-s. + this._readableState.decoder = iconv.getDecoder(enc, options); + this._readableState.encoding = enc; + } + + Readable.prototype.collect = iconv._collect; } - // No auto pipeline, use regular command sending - if (!autoPipelining_1.shouldUseAutoPipelining(this, functionName, commandName)) { - return script.execute(this, args, options, callback); + } + + // Remove iconv-lite Node primitive extensions. + iconv.undoExtendNodeEncodings = function undoExtendNodeEncodings() { + if (!iconv.supportsNodeEncodingsExtension) + return; + if (!original) + throw new Error("require('iconv-lite').undoExtendNodeEncodings(): Nothing to undo; extendNodeEncodings() is not called.") + + delete Buffer.isNativeEncoding; + + var SlowBuffer = (__nccwpck_require__(14300).SlowBuffer); + + SlowBuffer.prototype.toString = original.SlowBufferToString; + SlowBuffer.prototype.write = original.SlowBufferWrite; + + Buffer.isEncoding = original.BufferIsEncoding; + Buffer.byteLength = original.BufferByteLength; + Buffer.prototype.toString = original.BufferToString; + Buffer.prototype.write = original.BufferWrite; + + if (iconv.supportsStreams) { + var Readable = (__nccwpck_require__(12781).Readable); + + Readable.prototype.setEncoding = original.ReadableSetEncoding; + delete Readable.prototype.collect; } - // Create a new pipeline and make sure it's scheduled - return autoPipelining_1.executeWithAutoPipelining(this, functionName, commandName, args, callback); - }; + + original = undefined; + } } /***/ }), -/***/ 72712: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 19032: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const utils_1 = __nccwpck_require__(94832); -const debug = utils_1.Debug("AbstractConnector"); -class AbstractConnector { - constructor(disconnectTimeout) { - this.connecting = false; - this.disconnectTimeout = disconnectTimeout; + +// Some environments don't have global Buffer (e.g. React Native). +// Solution would be installing npm modules "buffer" and "stream" explicitly. +var Buffer = (__nccwpck_require__(15118).Buffer); + +var bomHandling = __nccwpck_require__(67961), + iconv = module.exports; + +// All codecs and aliases are kept here, keyed by encoding name/alias. +// They are lazy loaded in `iconv.getCodec` from `encodings/index.js`. +iconv.encodings = null; + +// Characters emitted in case of error. +iconv.defaultCharUnicode = '�'; +iconv.defaultCharSingleByte = '?'; + +// Public API. +iconv.encode = function encode(str, encoding, options) { + str = "" + (str || ""); // Ensure string. + + var encoder = iconv.getEncoder(encoding, options); + + var res = encoder.write(str); + var trail = encoder.end(); + + return (trail && trail.length > 0) ? Buffer.concat([res, trail]) : res; +} + +iconv.decode = function decode(buf, encoding, options) { + if (typeof buf === 'string') { + if (!iconv.skipDecodeWarning) { + console.error('Iconv-lite warning: decode()-ing strings is deprecated. Refer to https://github.com/ashtuchkin/iconv-lite/wiki/Use-Buffers-when-decoding'); + iconv.skipDecodeWarning = true; + } + + buf = Buffer.from("" + (buf || ""), "binary"); // Ensure buffer. } - check(info) { + + var decoder = iconv.getDecoder(encoding, options); + + var res = decoder.write(buf); + var trail = decoder.end(); + + return trail ? (res + trail) : res; +} + +iconv.encodingExists = function encodingExists(enc) { + try { + iconv.getCodec(enc); return true; + } catch (e) { + return false; } - disconnect() { - this.connecting = false; - if (this.stream) { - const stream = this.stream; // Make sure callbacks refer to the same instance - const timeout = setTimeout(() => { - debug("stream %s:%s still open, destroying it", stream.remoteAddress, stream.remotePort); - stream.destroy(); - }, this.disconnectTimeout); - stream.on("close", () => clearTimeout(timeout)); - stream.end(); +} + +// Legacy aliases to convert functions +iconv.toEncoding = iconv.encode; +iconv.fromEncoding = iconv.decode; + +// Search for a codec in iconv.encodings. Cache codec data in iconv._codecDataCache. +iconv._codecDataCache = {}; +iconv.getCodec = function getCodec(encoding) { + if (!iconv.encodings) + iconv.encodings = __nccwpck_require__(82733); // Lazy load all encoding definitions. + + // Canonicalize encoding name: strip all non-alphanumeric chars and appended year. + var enc = iconv._canonicalizeEncoding(encoding); + + // Traverse iconv.encodings to find actual codec. + var codecOptions = {}; + while (true) { + var codec = iconv._codecDataCache[enc]; + if (codec) + return codec; + + var codecDef = iconv.encodings[enc]; + + switch (typeof codecDef) { + case "string": // Direct alias to other encoding. + enc = codecDef; + break; + + case "object": // Alias with options. Can be layered. + for (var key in codecDef) + codecOptions[key] = codecDef[key]; + + if (!codecOptions.encodingName) + codecOptions.encodingName = enc; + + enc = codecDef.type; + break; + + case "function": // Codec itself. + if (!codecOptions.encodingName) + codecOptions.encodingName = enc; + + // The codec function must load all tables and return object with .encoder and .decoder methods. + // It'll be called only once (for each different options object). + codec = new codecDef(codecOptions, iconv); + + iconv._codecDataCache[codecOptions.encodingName] = codec; // Save it to be reused later. + return codec; + + default: + throw new Error("Encoding not recognized: '" + encoding + "' (searched as: '"+enc+"')"); } } } -exports["default"] = AbstractConnector; + +iconv._canonicalizeEncoding = function(encoding) { + // Canonicalize encoding name: strip all non-alphanumeric chars and appended year. + return (''+encoding).toLowerCase().replace(/:\d{4}$|[^0-9a-z]/g, ""); +} + +iconv.getEncoder = function getEncoder(encoding, options) { + var codec = iconv.getCodec(encoding), + encoder = new codec.encoder(options, codec); + + if (codec.bomAware && options && options.addBOM) + encoder = new bomHandling.PrependBOM(encoder, options); + + return encoder; +} + +iconv.getDecoder = function getDecoder(encoding, options) { + var codec = iconv.getCodec(encoding), + decoder = new codec.decoder(options, codec); + + if (codec.bomAware && !(options && options.stripBOM === false)) + decoder = new bomHandling.StripBOM(decoder, options); + + return decoder; +} + + +// Load extensions in Node. All of them are omitted in Browserify build via 'browser' field in package.json. +var nodeVer = typeof process !== 'undefined' && process.versions && process.versions.node; +if (nodeVer) { + + // Load streaming support in Node v0.10+ + var nodeVerArr = nodeVer.split(".").map(Number); + if (nodeVerArr[0] > 0 || nodeVerArr[1] >= 10) { + __nccwpck_require__(76409)(iconv); + } + + // Load Node primitive extensions. + __nccwpck_require__(30393)(iconv); +} + +if (false) {} /***/ }), -/***/ 22913: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ 76409: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const utils_1 = __nccwpck_require__(94832); -const debug = utils_1.Debug("FailoverDetector"); -const CHANNEL_NAME = "+switch-master"; -class FailoverDetector { - // sentinels can't be used for regular commands after this - constructor(connector, sentinels) { - this.isDisconnected = false; - this.connector = connector; - this.sentinels = sentinels; - } - cleanup() { - this.isDisconnected = true; - for (const sentinel of this.sentinels) { - sentinel.client.disconnect(); - } - } - subscribe() { - return __awaiter(this, void 0, void 0, function* () { - debug("Starting FailoverDetector"); - const promises = []; - for (const sentinel of this.sentinels) { - const promise = sentinel.client.subscribe(CHANNEL_NAME).catch((err) => { - debug("Failed to subscribe to failover messages on sentinel %s:%s (%s)", sentinel.address.host || "127.0.0.1", sentinel.address.port || 26739, err.message); - }); - promises.push(promise); - sentinel.client.on("message", (channel) => { - if (!this.isDisconnected && channel === CHANNEL_NAME) { - this.disconnect(); - } - }); - } - yield Promise.all(promises); - }); + +var Buffer = (__nccwpck_require__(14300).Buffer), + Transform = (__nccwpck_require__(12781).Transform); + + +// == Exports ================================================================== +module.exports = function(iconv) { + + // Additional Public API. + iconv.encodeStream = function encodeStream(encoding, options) { + return new IconvLiteEncoderStream(iconv.getEncoder(encoding, options), options); } - disconnect() { - // Avoid disconnecting more than once per failover. - // A new FailoverDetector will be created after reconnecting. - this.isDisconnected = true; - debug("Failover detected, disconnecting"); - // Will call this.cleanup() - this.connector.disconnect(); + + iconv.decodeStream = function decodeStream(encoding, options) { + return new IconvLiteDecoderStream(iconv.getDecoder(encoding, options), options); } -} -exports.FailoverDetector = FailoverDetector; + iconv.supportsStreams = true; -/***/ }), -/***/ 72225: -/***/ ((__unused_webpack_module, exports) => { + // Not published yet. + iconv.IconvLiteEncoderStream = IconvLiteEncoderStream; + iconv.IconvLiteDecoderStream = IconvLiteDecoderStream; + iconv._collect = IconvLiteDecoderStream.prototype.collect; +}; -"use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -function isSentinelEql(a, b) { - return ((a.host || "127.0.0.1") === (b.host || "127.0.0.1") && - (a.port || 26379) === (b.port || 26379)); +// == Encoder stream ======================================================= +function IconvLiteEncoderStream(conv, options) { + this.conv = conv; + options = options || {}; + options.decodeStrings = false; // We accept only strings, so we don't need to decode them. + Transform.call(this, options); } -class SentinelIterator { - constructor(sentinels) { - this.cursor = 0; - this.sentinels = sentinels.slice(0); - } - next() { - const done = this.cursor >= this.sentinels.length; - return { done, value: done ? undefined : this.sentinels[this.cursor++] }; + +IconvLiteEncoderStream.prototype = Object.create(Transform.prototype, { + constructor: { value: IconvLiteEncoderStream } +}); + +IconvLiteEncoderStream.prototype._transform = function(chunk, encoding, done) { + if (typeof chunk != 'string') + return done(new Error("Iconv encoding stream needs strings as its input.")); + try { + var res = this.conv.write(chunk); + if (res && res.length) this.push(res); + done(); } - reset(moveCurrentEndpointToFirst) { - if (moveCurrentEndpointToFirst && - this.sentinels.length > 1 && - this.cursor !== 1) { - this.sentinels.unshift(...this.sentinels.splice(this.cursor - 1)); - } - this.cursor = 0; + catch (e) { + done(e); } - add(sentinel) { - for (let i = 0; i < this.sentinels.length; i++) { - if (isSentinelEql(sentinel, this.sentinels[i])) { - return false; - } - } - this.sentinels.push(sentinel); - return true; +} + +IconvLiteEncoderStream.prototype._flush = function(done) { + try { + var res = this.conv.end(); + if (res && res.length) this.push(res); + done(); } - toString() { - return `${JSON.stringify(this.sentinels)} @${this.cursor}`; + catch (e) { + done(e); } } -exports["default"] = SentinelIterator; +IconvLiteEncoderStream.prototype.collect = function(cb) { + var chunks = []; + this.on('error', cb); + this.on('data', function(chunk) { chunks.push(chunk); }); + this.on('end', function() { + cb(null, Buffer.concat(chunks)); + }); + return this; +} -/***/ }), -/***/ 10379: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +// == Decoder stream ======================================================= +function IconvLiteDecoderStream(conv, options) { + this.conv = conv; + options = options || {}; + options.encoding = this.encoding = 'utf8'; // We output strings. + Transform.call(this, options); +} -"use strict"; +IconvLiteDecoderStream.prototype = Object.create(Transform.prototype, { + constructor: { value: IconvLiteDecoderStream } +}); -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const net_1 = __nccwpck_require__(41808); -const utils_1 = __nccwpck_require__(94832); -const tls_1 = __nccwpck_require__(24404); -const StandaloneConnector_1 = __nccwpck_require__(8774); -const SentinelIterator_1 = __nccwpck_require__(72225); -exports.SentinelIterator = SentinelIterator_1.default; -const AbstractConnector_1 = __nccwpck_require__(72712); -const redis_1 = __nccwpck_require__(83609); -const FailoverDetector_1 = __nccwpck_require__(22913); -const debug = utils_1.Debug("SentinelConnector"); -class SentinelConnector extends AbstractConnector_1.default { - constructor(options) { - super(options.disconnectTimeout); - this.options = options; - this.failoverDetector = null; - this.emitter = null; - if (!this.options.sentinels.length) { - throw new Error("Requires at least one sentinel to connect to."); - } - if (!this.options.name) { - throw new Error("Requires the name of master."); - } - this.sentinelIterator = new SentinelIterator_1.default(this.options.sentinels); - } - check(info) { - const roleMatches = !info.role || this.options.role === info.role; - if (!roleMatches) { - debug("role invalid, expected %s, but got %s", this.options.role, info.role); - // Start from the next item. - // Note that `reset` will move the cursor to the previous element, - // so we advance two steps here. - this.sentinelIterator.next(); - this.sentinelIterator.next(); - this.sentinelIterator.reset(true); - } - return roleMatches; - } - disconnect() { - super.disconnect(); - if (this.failoverDetector) { - this.failoverDetector.cleanup(); - } - } - connect(eventEmitter) { - this.connecting = true; - this.retryAttempts = 0; - let lastError; - const connectToNext = () => __awaiter(this, void 0, void 0, function* () { - const endpoint = this.sentinelIterator.next(); - if (endpoint.done) { - this.sentinelIterator.reset(false); - const retryDelay = typeof this.options.sentinelRetryStrategy === "function" - ? this.options.sentinelRetryStrategy(++this.retryAttempts) - : null; - let errorMsg = typeof retryDelay !== "number" - ? "All sentinels are unreachable and retry is disabled." - : `All sentinels are unreachable. Retrying from scratch after ${retryDelay}ms.`; - if (lastError) { - errorMsg += ` Last error: ${lastError.message}`; - } - debug(errorMsg); - const error = new Error(errorMsg); - if (typeof retryDelay === "number") { - eventEmitter("error", error); - yield new Promise((resolve) => setTimeout(resolve, retryDelay)); - return connectToNext(); - } - else { - throw error; - } - } - let resolved = null; - let err = null; - try { - resolved = yield this.resolve(endpoint.value); - } - catch (error) { - err = error; - } - if (!this.connecting) { - throw new Error(utils_1.CONNECTION_CLOSED_ERROR_MSG); - } - const endpointAddress = endpoint.value.host + ":" + endpoint.value.port; - if (resolved) { - debug("resolved: %s:%s from sentinel %s", resolved.host, resolved.port, endpointAddress); - if (this.options.enableTLSForSentinelMode && this.options.tls) { - Object.assign(resolved, this.options.tls); - this.stream = tls_1.connect(resolved); - } - else { - this.stream = net_1.createConnection(resolved); - } - this.stream.once("connect", () => this.initFailoverDetector()); - this.stream.once("error", (err) => { - this.firstError = err; - }); - return this.stream; - } - else { - const errorMsg = err - ? "failed to connect to sentinel " + - endpointAddress + - " because " + - err.message - : "connected to sentinel " + - endpointAddress + - " successfully, but got an invalid reply: " + - resolved; - debug(errorMsg); - eventEmitter("sentinelError", new Error(errorMsg)); - if (err) { - lastError = err; - } - return connectToNext(); - } - }); - return connectToNext(); - } - updateSentinels(client) { - return __awaiter(this, void 0, void 0, function* () { - if (!this.options.updateSentinels) { - return; - } - const result = yield client.sentinel("sentinels", this.options.name); - if (!Array.isArray(result)) { - return; - } - result - .map(utils_1.packObject) - .forEach((sentinel) => { - const flags = sentinel.flags ? sentinel.flags.split(",") : []; - if (flags.indexOf("disconnected") === -1 && - sentinel.ip && - sentinel.port) { - const endpoint = this.sentinelNatResolve(addressResponseToAddress(sentinel)); - if (this.sentinelIterator.add(endpoint)) { - debug("adding sentinel %s:%s", endpoint.host, endpoint.port); - } - } - }); - debug("Updated internal sentinels: %s", this.sentinelIterator); - }); - } - resolveMaster(client) { - return __awaiter(this, void 0, void 0, function* () { - const result = yield client.sentinel("get-master-addr-by-name", this.options.name); - yield this.updateSentinels(client); - return this.sentinelNatResolve(Array.isArray(result) - ? { host: result[0], port: Number(result[1]) } - : null); - }); - } - resolveSlave(client) { - return __awaiter(this, void 0, void 0, function* () { - const result = yield client.sentinel("slaves", this.options.name); - if (!Array.isArray(result)) { - return null; - } - const availableSlaves = result - .map(utils_1.packObject) - .filter((slave) => slave.flags && !slave.flags.match(/(disconnected|s_down|o_down)/)); - return this.sentinelNatResolve(selectPreferredSentinel(availableSlaves, this.options.preferredSlaves)); - }); - } - sentinelNatResolve(item) { - if (!item || !this.options.natMap) - return item; - return this.options.natMap[`${item.host}:${item.port}`] || item; - } - connectToSentinel(endpoint, options) { - return new redis_1.default(Object.assign({ port: endpoint.port || 26379, host: endpoint.host, username: this.options.sentinelUsername || null, password: this.options.sentinelPassword || null, family: endpoint.family || - (StandaloneConnector_1.isIIpcConnectionOptions(this.options) - ? undefined - : this.options.family), tls: this.options.sentinelTLS, retryStrategy: null, enableReadyCheck: false, connectTimeout: this.options.connectTimeout, commandTimeout: this.options.sentinelCommandTimeout, dropBufferSupport: true }, options)); - } - resolve(endpoint) { - return __awaiter(this, void 0, void 0, function* () { - const client = this.connectToSentinel(endpoint); - // ignore the errors since resolve* methods will handle them - client.on("error", noop); - try { - if (this.options.role === "slave") { - return yield this.resolveSlave(client); - } - else { - return yield this.resolveMaster(client); - } - } - finally { - client.disconnect(); - } - }); +IconvLiteDecoderStream.prototype._transform = function(chunk, encoding, done) { + if (!Buffer.isBuffer(chunk)) + return done(new Error("Iconv decoding stream needs buffers as its input.")); + try { + var res = this.conv.write(chunk); + if (res && res.length) this.push(res, this.encoding); + done(); } - initFailoverDetector() { - var _a; - return __awaiter(this, void 0, void 0, function* () { - if (!this.options.failoverDetector) { - return; - } - // Move the current sentinel to the first position - this.sentinelIterator.reset(true); - const sentinels = []; - // In case of a large amount of sentinels, limit the number of concurrent connections - while (sentinels.length < this.options.sentinelMaxConnections) { - const { done, value } = this.sentinelIterator.next(); - if (done) { - break; - } - const client = this.connectToSentinel(value, { - lazyConnect: true, - retryStrategy: this.options.sentinelReconnectStrategy, - }); - client.on("reconnecting", () => { - var _a; - // Tests listen to this event - (_a = this.emitter) === null || _a === void 0 ? void 0 : _a.emit("sentinelReconnecting"); - }); - sentinels.push({ address: value, client }); - } - this.sentinelIterator.reset(false); - if (this.failoverDetector) { - // Clean up previous detector - this.failoverDetector.cleanup(); - } - this.failoverDetector = new FailoverDetector_1.FailoverDetector(this, sentinels); - yield this.failoverDetector.subscribe(); - // Tests listen to this event - (_a = this.emitter) === null || _a === void 0 ? void 0 : _a.emit("failoverSubscribed"); - }); + catch (e) { + done(e); } } -exports["default"] = SentinelConnector; -function selectPreferredSentinel(availableSlaves, preferredSlaves) { - if (availableSlaves.length === 0) { - return null; - } - let selectedSlave; - if (typeof preferredSlaves === "function") { - selectedSlave = preferredSlaves(availableSlaves); - } - else if (preferredSlaves !== null && typeof preferredSlaves === "object") { - const preferredSlavesArray = Array.isArray(preferredSlaves) - ? preferredSlaves - : [preferredSlaves]; - // sort by priority - preferredSlavesArray.sort((a, b) => { - // default the priority to 1 - if (!a.prio) { - a.prio = 1; - } - if (!b.prio) { - b.prio = 1; - } - // lowest priority first - if (a.prio < b.prio) { - return -1; - } - if (a.prio > b.prio) { - return 1; - } - return 0; - }); - // loop over preferred slaves and return the first match - for (let p = 0; p < preferredSlavesArray.length; p++) { - for (let a = 0; a < availableSlaves.length; a++) { - const slave = availableSlaves[a]; - if (slave.ip === preferredSlavesArray[p].ip) { - if (slave.port === preferredSlavesArray[p].port) { - selectedSlave = slave; - break; - } - } - } - if (selectedSlave) { - break; - } - } + +IconvLiteDecoderStream.prototype._flush = function(done) { + try { + var res = this.conv.end(); + if (res && res.length) this.push(res, this.encoding); + done(); } - // if none of the preferred slaves are available, a random available slave is returned - if (!selectedSlave) { - selectedSlave = utils_1.sample(availableSlaves); + catch (e) { + done(e); } - return addressResponseToAddress(selectedSlave); } -function addressResponseToAddress(input) { - return { host: input.ip, port: Number(input.port) }; + +IconvLiteDecoderStream.prototype.collect = function(cb) { + var res = ''; + this.on('error', cb); + this.on('data', function(chunk) { res += chunk; }); + this.on('end', function() { + cb(null, res); + }); + return this; } -function noop() { } -/***/ }), -/***/ 8774: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ }), + +/***/ 91230: +/***/ ((module) => { + +// A simple implementation of make-array +function makeArray (subject) { + return Array.isArray(subject) + ? subject + : [subject] +} + +const EMPTY = '' +const SPACE = ' ' +const ESCAPE = '\\' +const REGEX_TEST_BLANK_LINE = /^\s+$/ +const REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/ +const REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\#/ +const REGEX_SPLITALL_CRLF = /\r?\n/g +// /foo, +// ./foo, +// ../foo, +// . +// .. +const REGEX_TEST_INVALID_PATH = /^\.*\/|^\.+$/ + +const SLASH = '/' +const KEY_IGNORE = typeof Symbol !== 'undefined' + ? Symbol.for('node-ignore') + /* istanbul ignore next */ + : 'node-ignore' + +const define = (object, key, value) => + Object.defineProperty(object, key, {value}) + +const REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g + +const RETURN_FALSE = () => false + +// Sanitize the range of a regular expression +// The cases are complicated, see test cases for details +const sanitizeRange = range => range.replace( + REGEX_REGEXP_RANGE, + (match, from, to) => from.charCodeAt(0) <= to.charCodeAt(0) + ? match + // Invalid range (out of order) which is ok for gitignore rules but + // fatal for JavaScript regular expression, so eliminate it. + : EMPTY +) + +// See fixtures #59 +const cleanRangeBackSlash = slashes => { + const {length} = slashes + return slashes.slice(0, length - length % 2) +} + +// > If the pattern ends with a slash, +// > it is removed for the purpose of the following description, +// > but it would only find a match with a directory. +// > In other words, foo/ will match a directory foo and paths underneath it, +// > but will not match a regular file or a symbolic link foo +// > (this is consistent with the way how pathspec works in general in Git). +// '`foo/`' will not match regular file '`foo`' or symbolic link '`foo`' +// -> ignore-rules will not deal with it, because it costs extra `fs.stat` call +// you could use option `mark: true` with `glob` + +// '`foo/`' should not continue with the '`..`' +const REPLACERS = [ + + // > Trailing spaces are ignored unless they are quoted with backslash ("\") + [ + // (a\ ) -> (a ) + // (a ) -> (a) + // (a \ ) -> (a ) + /\\?\s+$/, + match => match.indexOf('\\') === 0 + ? SPACE + : EMPTY + ], + + // replace (\ ) with ' ' + [ + /\\\s/g, + () => SPACE + ], + + // Escape metacharacters + // which is written down by users but means special for regular expressions. + + // > There are 12 characters with special meanings: + // > - the backslash \, + // > - the caret ^, + // > - the dollar sign $, + // > - the period or dot ., + // > - the vertical bar or pipe symbol |, + // > - the question mark ?, + // > - the asterisk or star *, + // > - the plus sign +, + // > - the opening parenthesis (, + // > - the closing parenthesis ), + // > - and the opening square bracket [, + // > - the opening curly brace {, + // > These special characters are often called "metacharacters". + [ + /[\\$.|*+(){^]/g, + match => `\\${match}` + ], + + [ + // > a question mark (?) matches a single character + /(?!\\)\?/g, + () => '[^/]' + ], + + // leading slash + [ -"use strict"; + // > A leading slash matches the beginning of the pathname. + // > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c". + // A leading slash matches the beginning of the pathname + /^\//, + () => '^' + ], -Object.defineProperty(exports, "__esModule", ({ value: true })); -const net_1 = __nccwpck_require__(41808); -const tls_1 = __nccwpck_require__(24404); -const utils_1 = __nccwpck_require__(94832); -const AbstractConnector_1 = __nccwpck_require__(72712); -function isIIpcConnectionOptions(value) { - return value.path; -} -exports.isIIpcConnectionOptions = isIIpcConnectionOptions; -class StandaloneConnector extends AbstractConnector_1.default { - constructor(options) { - super(options.disconnectTimeout); - this.options = options; - } - connect(_) { - const { options } = this; - this.connecting = true; - let connectionOptions; - if (isIIpcConnectionOptions(options)) { - connectionOptions = { - path: options.path, - }; - } - else { - connectionOptions = {}; - if (options.port != null) { - connectionOptions.port = options.port; - } - if (options.host != null) { - connectionOptions.host = options.host; - } - if (options.family != null) { - connectionOptions.family = options.family; - } - } - if (options.tls) { - Object.assign(connectionOptions, options.tls); - } - // TODO: - // We use native Promise here since other Promise - // implementation may use different schedulers that - // cause issue when the stream is resolved in the - // next tick. - // Should use the provided promise in the next major - // version and do not connect before resolved. - return new Promise((resolve, reject) => { - process.nextTick(() => { - if (!this.connecting) { - reject(new Error(utils_1.CONNECTION_CLOSED_ERROR_MSG)); - return; - } - try { - if (options.tls) { - this.stream = tls_1.connect(connectionOptions); - } - else { - this.stream = net_1.createConnection(connectionOptions); - } - } - catch (err) { - reject(err); - return; - } - this.stream.once("error", (err) => { - this.firstError = err; - }); - resolve(this.stream); - }); - }); + // replace special metacharacter slash after the leading slash + [ + /\//g, + () => '\\/' + ], + + [ + // > A leading "**" followed by a slash means match in all directories. + // > For example, "**/foo" matches file or directory "foo" anywhere, + // > the same as pattern "foo". + // > "**/foo/bar" matches file or directory "bar" anywhere that is directly + // > under directory "foo". + // Notice that the '*'s have been replaced as '\\*' + /^\^*\\\*\\\*\\\//, + + // '**/foo' <-> 'foo' + () => '^(?:.*\\/)?' + ], + + // starting + [ + // there will be no leading '/' + // (which has been replaced by section "leading slash") + // If starts with '**', adding a '^' to the regular expression also works + /^(?=[^^])/, + function startingReplacer () { + // If has a slash `/` at the beginning or middle + return !/\/(?!$)/.test(this) + // > Prior to 2.22.1 + // > If the pattern does not contain a slash /, + // > Git treats it as a shell glob pattern + // Actually, if there is only a trailing slash, + // git also treats it as a shell glob pattern + + // After 2.22.1 (compatible but clearer) + // > If there is a separator at the beginning or middle (or both) + // > of the pattern, then the pattern is relative to the directory + // > level of the particular .gitignore file itself. + // > Otherwise the pattern may also match at any level below + // > the .gitignore level. + ? '(?:^|\\/)' + + // > Otherwise, Git treats the pattern as a shell glob suitable for + // > consumption by fnmatch(3) + : '^' } -} -exports["default"] = StandaloneConnector; + ], + // two globstars + [ + // Use lookahead assertions so that we could match more than one `'/**'` + /\\\/\\\*\\\*(?=\\\/|$)/g, -/***/ }), + // Zero, one or several directories + // should not use '*', or it will be replaced by the next replacer -/***/ 72340: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + // Check if it is not the last `'/**'` + (_, index, str) => index + 6 < str.length -"use strict"; + // case: /**/ + // > A slash followed by two consecutive asterisks then a slash matches + // > zero or more directories. + // > For example, "a/**/b" matches "a/b", "a/x/b", "a/x/y/b" and so on. + // '/**/' + ? '(?:\\/[^\\/]+)*' -Object.defineProperty(exports, "__esModule", ({ value: true })); -const StandaloneConnector_1 = __nccwpck_require__(8774); -exports.StandaloneConnector = StandaloneConnector_1.default; -const SentinelConnector_1 = __nccwpck_require__(10379); -exports.SentinelConnector = SentinelConnector_1.default; + // case: /** + // > A trailing `"/**"` matches everything inside. + // #21: everything inside but it should not include the current folder + : '\\/.+' + ], -/***/ }), + // intermediate wildcards + [ + // Never replace escaped '*' + // ignore rule '\*' will match the path '*' -/***/ 61823: -/***/ ((__unused_webpack_module, exports) => { + // 'abc.*/' -> go + // 'abc.*' -> skip this rule + /(^|[^\\]+)\\\*(?=.+)/g, -"use strict"; + // '*.js' matches '.js' + // '*.js' doesn't match 'abc' + (_, p1) => `${p1}[^\\/]*` + ], -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = { - /** - * TLS settings for Redis.com Cloud Fixed plan. Updated on 2021-10-06. - */ - RedisCloudFixed: { - ca: "-----BEGIN CERTIFICATE-----\n" + - "MIIDTzCCAjegAwIBAgIJAKSVpiDswLcwMA0GCSqGSIb3DQEBBQUAMD4xFjAUBgNV\n" + - "BAoMDUdhcmFudGlhIERhdGExJDAiBgNVBAMMG1NTTCBDZXJ0aWZpY2F0aW9uIEF1\n" + - "dGhvcml0eTAeFw0xMzEwMDExMjE0NTVaFw0yMzA5MjkxMjE0NTVaMD4xFjAUBgNV\n" + - "BAoMDUdhcmFudGlhIERhdGExJDAiBgNVBAMMG1NTTCBDZXJ0aWZpY2F0aW9uIEF1\n" + - "dGhvcml0eTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALZqkh/DczWP\n" + - "JnxnHLQ7QL0T4B4CDKWBKCcisriGbA6ZePWVNo4hfKQC6JrzfR+081NeD6VcWUiz\n" + - "rmd+jtPhIY4c+WVQYm5PKaN6DT1imYdxQw7aqO5j2KUCEh/cznpLxeSHoTxlR34E\n" + - "QwF28Wl3eg2vc5ct8LjU3eozWVk3gb7alx9mSA2SgmuX5lEQawl++rSjsBStemY2\n" + - "BDwOpAMXIrdEyP/cVn8mkvi/BDs5M5G+09j0gfhyCzRWMQ7Hn71u1eolRxwVxgi3\n" + - "TMn+/vTaFSqxKjgck6zuAYjBRPaHe7qLxHNr1So/Mc9nPy+3wHebFwbIcnUojwbp\n" + - "4nctkWbjb2cCAwEAAaNQME4wHQYDVR0OBBYEFP1whtcrydmW3ZJeuSoKZIKjze3w\n" + - "MB8GA1UdIwQYMBaAFP1whtcrydmW3ZJeuSoKZIKjze3wMAwGA1UdEwQFMAMBAf8w\n" + - "DQYJKoZIhvcNAQEFBQADggEBAG2erXhwRAa7+ZOBs0B6X57Hwyd1R4kfmXcs0rta\n" + - "lbPpvgULSiB+TCbf3EbhJnHGyvdCY1tvlffLjdA7HJ0PCOn+YYLBA0pTU/dyvrN6\n" + - "Su8NuS5yubnt9mb13nDGYo1rnt0YRfxN+8DM3fXIVr038A30UlPX2Ou1ExFJT0MZ\n" + - "uFKY6ZvLdI6/1cbgmguMlAhM+DhKyV6Sr5699LM3zqeI816pZmlREETYkGr91q7k\n" + - "BpXJu/dtHaGxg1ZGu6w/PCsYGUcECWENYD4VQPd8N32JjOfu6vEgoEAwfPP+3oGp\n" + - "Z4m3ewACcWOAenqflb+cQYC4PsF7qbXDmRaWrbKntOlZ3n0=\n" + - "-----END CERTIFICATE-----\n", - }, - /** - * TLS settings for Redis.com Cloud Flexible plan. Updated on 2021-10-06. - */ - RedisCloudFlexible: { - ca: "-----BEGIN CERTIFICATE-----\n" + - "MIIGMTCCBBmgAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwajELMAkGA1UEBhMCVVMx\n" + - "CzAJBgNVBAgMAkNBMQswCQYDVQQHDAJDQTESMBAGA1UECgwJUmVkaXNMYWJzMS0w\n" + - "KwYDVQQDDCRSZWRpc0xhYnMgUm9vdCBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkwHhcN\n" + - "MTgwMjI1MTUzNzM3WhcNMjgwMjIzMTUzNzM3WjBfMQswCQYDVQQGEwJVUzELMAkG\n" + - "A1UECAwCQ0ExEjAQBgNVBAoMCVJlZGlzTGFiczEvMC0GA1UEAwwmUkNQIEludGVy\n" + - "bWVkaWF0ZSBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkwggIiMA0GCSqGSIb3DQEBAQUA\n" + - "A4ICDwAwggIKAoICAQDf9dqbxc8Bq7Ctq9rWcxrGNKKHivqLAFpPq02yLPx6fsOv\n" + - "Tq7GsDChAYBBc4v7Y2Ap9RD5Vs3dIhEANcnolf27QwrG9RMnnvzk8pCvp1o6zSU4\n" + - "VuOE1W66/O1/7e2rVxyrnTcP7UgK43zNIXu7+tiAqWsO92uSnuMoGPGpeaUm1jym\n" + - "hjWKtkAwDFSqvHY+XL5qDVBEjeUe+WHkYUg40cAXjusAqgm2hZt29c2wnVrxW25W\n" + - "P0meNlzHGFdA2AC5z54iRiqj57dTfBTkHoBczQxcyw6hhzxZQ4e5I5zOKjXXEhZN\n" + - "r0tA3YC14CTabKRus/JmZieyZzRgEy2oti64tmLYTqSlAD78pRL40VNoaSYetXLw\n" + - "hhNsXCHgWaY6d5bLOc/aIQMAV5oLvZQKvuXAF1IDmhPA+bZbpWipp0zagf1P1H3s\n" + - "UzsMdn2KM0ejzgotbtNlj5TcrVwpmvE3ktvUAuA+hi3FkVx1US+2Gsp5x4YOzJ7u\n" + - "P1WPk6ShF0JgnJH2ILdj6kttTWwFzH17keSFICWDfH/+kM+k7Y1v3EXMQXE7y0T9\n" + - "MjvJskz6d/nv+sQhY04xt64xFMGTnZjlJMzfQNi7zWFLTZnDD0lPowq7l3YiPoTT\n" + - "t5Xky83lu0KZsZBo0WlWaDG00gLVdtRgVbcuSWxpi5BdLb1kRab66JptWjxwXQID\n" + - "AQABo4HrMIHoMDoGA1UdHwQzMDEwL6AtoCuGKWh0dHBzOi8vcmwtY2Etc2VydmVy\n" + - "LnJlZGlzbGFicy5jb20vdjEvY3JsMEYGCCsGAQUFBwEBBDowODA2BggrBgEFBQcw\n" + - "AYYqaHR0cHM6Ly9ybC1jYS1zZXJ2ZXIucmVkaXNsYWJzLmNvbS92MS9vY3NwMB0G\n" + - "A1UdDgQWBBQHar5OKvQUpP2qWt6mckzToeCOHDAfBgNVHSMEGDAWgBQi42wH6hM4\n" + - "L2sujEvLM0/u8lRXTzASBgNVHRMBAf8ECDAGAQH/AgEAMA4GA1UdDwEB/wQEAwIB\n" + - "hjANBgkqhkiG9w0BAQsFAAOCAgEAirEn/iTsAKyhd+pu2W3Z5NjCko4NPU0EYUbr\n" + - "AP7+POK2rzjIrJO3nFYQ/LLuC7KCXG+2qwan2SAOGmqWst13Y+WHp44Kae0kaChW\n" + - "vcYLXXSoGQGC8QuFSNUdaeg3RbMDYFT04dOkqufeWVccoHVxyTSg9eD8LZuHn5jw\n" + - "7QDLiEECBmIJHk5Eeo2TAZrx4Yx6ufSUX5HeVjlAzqwtAqdt99uCJ/EL8bgpWbe+\n" + - "XoSpvUv0SEC1I1dCAhCKAvRlIOA6VBcmzg5Am12KzkqTul12/VEFIgzqu0Zy2Jbc\n" + - "AUPrYVu/+tOGXQaijy7YgwH8P8n3s7ZeUa1VABJHcxrxYduDDJBLZi+MjheUDaZ1\n" + - "jQRHYevI2tlqeSBqdPKG4zBY5lS0GiAlmuze5oENt0P3XboHoZPHiqcK3VECgTVh\n" + - "/BkJcuudETSJcZDmQ8YfoKfBzRQNg2sv/hwvUv73Ss51Sco8GEt2lD8uEdib1Q6z\n" + - "zDT5lXJowSzOD5ZA9OGDjnSRL+2riNtKWKEqvtEG3VBJoBzu9GoxbAc7wIZLxmli\n" + - "iF5a/Zf5X+UXD3s4TMmy6C4QZJpAA2egsSQCnraWO2ULhh7iXMysSkF/nzVfZn43\n" + - "iqpaB8++9a37hWq14ZmOv0TJIDz//b2+KC4VFXWQ5W5QC6whsjT+OlG4p5ZYG0jo\n" + - "616pxqo=\n" + - "-----END CERTIFICATE-----\n" + - "-----BEGIN CERTIFICATE-----\n" + - "MIIFujCCA6KgAwIBAgIJAJ1aTT1lu2ScMA0GCSqGSIb3DQEBCwUAMGoxCzAJBgNV\n" + - "BAYTAlVTMQswCQYDVQQIDAJDQTELMAkGA1UEBwwCQ0ExEjAQBgNVBAoMCVJlZGlz\n" + - "TGFiczEtMCsGA1UEAwwkUmVkaXNMYWJzIFJvb3QgQ2VydGlmaWNhdGUgQXV0aG9y\n" + - "aXR5MB4XDTE4MDIyNTE1MjA0MloXDTM4MDIyMDE1MjA0MlowajELMAkGA1UEBhMC\n" + - "VVMxCzAJBgNVBAgMAkNBMQswCQYDVQQHDAJDQTESMBAGA1UECgwJUmVkaXNMYWJz\n" + - "MS0wKwYDVQQDDCRSZWRpc0xhYnMgUm9vdCBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkw\n" + - "ggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDLEjXy7YrbN5Waau5cd6g1\n" + - "G5C2tMmeTpZ0duFAPxNU4oE3RHS5gGiok346fUXuUxbZ6QkuzeN2/2Z+RmRcJhQY\n" + - "Dm0ZgdG4x59An1TJfnzKKoWj8ISmoHS/TGNBdFzXV7FYNLBuqZouqePI6ReC6Qhl\n" + - "pp45huV32Q3a6IDrrvx7Wo5ZczEQeFNbCeCOQYNDdTmCyEkHqc2AGo8eoIlSTutT\n" + - "ULOC7R5gzJVTS0e1hesQ7jmqHjbO+VQS1NAL4/5K6cuTEqUl+XhVhPdLWBXJQ5ag\n" + - "54qhX4v+ojLzeU1R/Vc6NjMvVtptWY6JihpgplprN0Yh2556ewcXMeturcKgXfGJ\n" + - "xeYzsjzXerEjrVocX5V8BNrg64NlifzTMKNOOv4fVZszq1SIHR8F9ROrqiOdh8iC\n" + - "JpUbLpXH9hWCSEO6VRMB2xJoKu3cgl63kF30s77x7wLFMEHiwsQRKxooE1UhgS9K\n" + - "2sO4TlQ1eWUvFvHSTVDQDlGQ6zu4qjbOpb3Q8bQwoK+ai2alkXVR4Ltxe9QlgYK3\n" + - "StsnPhruzZGA0wbXdpw0bnM+YdlEm5ffSTpNIfgHeaa7Dtb801FtA71ZlH7A6TaI\n" + - "SIQuUST9EKmv7xrJyx0W1pGoPOLw5T029aTjnICSLdtV9bLwysrLhIYG5bnPq78B\n" + - "cS+jZHFGzD7PUVGQD01nOQIDAQABo2MwYTAdBgNVHQ4EFgQUIuNsB+oTOC9rLoxL\n" + - "yzNP7vJUV08wHwYDVR0jBBgwFoAUIuNsB+oTOC9rLoxLyzNP7vJUV08wDwYDVR0T\n" + - "AQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAYYwDQYJKoZIhvcNAQELBQADggIBAHfg\n" + - "z5pMNUAKdMzK1aS1EDdK9yKz4qicILz5czSLj1mC7HKDRy8cVADUxEICis++CsCu\n" + - "rYOvyCVergHQLREcxPq4rc5Nq1uj6J6649NEeh4WazOOjL4ZfQ1jVznMbGy+fJm3\n" + - "3Hoelv6jWRG9iqeJZja7/1s6YC6bWymI/OY1e4wUKeNHAo+Vger7MlHV+RuabaX+\n" + - "hSJ8bJAM59NCM7AgMTQpJCncrcdLeceYniGy5Q/qt2b5mJkQVkIdy4TPGGB+AXDJ\n" + - "D0q3I/JDRkDUFNFdeW0js7fHdsvCR7O3tJy5zIgEV/o/BCkmJVtuwPYOrw/yOlKj\n" + - "TY/U7ATAx9VFF6/vYEOMYSmrZlFX+98L6nJtwDqfLB5VTltqZ4H/KBxGE3IRSt9l\n" + - "FXy40U+LnXzhhW+7VBAvyYX8GEXhHkKU8Gqk1xitrqfBXY74xKgyUSTolFSfFVgj\n" + - "mcM/X4K45bka+qpkj7Kfv/8D4j6aZekwhN2ly6hhC1SmQ8qjMjpG/mrWOSSHZFmf\n" + - "ybu9iD2AYHeIOkshIl6xYIa++Q/00/vs46IzAbQyriOi0XxlSMMVtPx0Q3isp+ji\n" + - "n8Mq9eOuxYOEQ4of8twUkUDd528iwGtEdwf0Q01UyT84S62N8AySl1ZBKXJz6W4F\n" + - "UhWfa/HQYOAPDdEjNgnVwLI23b8t0TozyCWw7q8h\n" + - "-----END CERTIFICATE-----\n", - }, -}; + [ + // unescape, revert step 3 except for back slash + // For example, if a user escape a '\\*', + // after step 3, the result will be '\\\\\\*' + /\\\\\\(?=[$.|*+(){^])/g, + () => ESCAPE + ], + [ + // '\\\\' -> '\\' + /\\\\/g, + () => ESCAPE + ], -/***/ }), + [ + // > The range notation, e.g. [a-zA-Z], + // > can be used to match one of the characters in a range. -/***/ 97282: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + // `\` is escaped by step 3 + /(\\)?\[([^\]/]*?)(\\*)($|\])/g, + (match, leadEscape, range, endEscape, close) => leadEscape === ESCAPE + // '\\[bar]' -> '\\\\[bar\\]' + ? `\\[${range}${cleanRangeBackSlash(endEscape)}${close}` + : close === ']' + ? endEscape.length % 2 === 0 + // A normal case, and it is a range notation + // '[bar]' + // '[bar\\\\]' + ? `[${sanitizeRange(range)}${endEscape}]` + // Invalid range notaton + // '[bar\\]' -> '[bar\\\\]' + : '[]' + : '[]' + ], -"use strict"; + // ending + [ + // 'js' will not match 'js.' + // 'ab' will not match 'abc' + /(?:[^*])$/, -Object.defineProperty(exports, "__esModule", ({ value: true })); -const redis_errors_1 = __nccwpck_require__(81879); -class ClusterAllFailedError extends redis_errors_1.RedisError { - constructor(message, lastNodeError) { - super(message); - this.lastNodeError = lastNodeError; - Error.captureStackTrace(this, this.constructor); - } - get name() { - return this.constructor.name; + // WTF! + // https://git-scm.com/docs/gitignore + // changes in [2.22.1](https://git-scm.com/docs/gitignore/2.22.1) + // which re-fixes #24, #38 + + // > If there is a separator at the end of the pattern then the pattern + // > will only match directories, otherwise the pattern can match both + // > files and directories. + + // 'js*' will not match 'a.js' + // 'js/' will not match 'a.js' + // 'js' will match 'a.js' and 'a.js/' + match => /\/$/.test(match) + // foo/ will not match 'foo' + ? `${match}$` + // foo matches 'foo' and 'foo/' + : `${match}(?=$|\\/$)` + ], + + // trailing wildcard + [ + /(\^|\\\/)?\\\*$/, + (_, p1) => { + const prefix = p1 + // '\^': + // '/*' does not match EMPTY + // '/*' does not match everything + + // '\\\/': + // 'abc/*' does not match 'abc/' + ? `${p1}[^/]+` + + // 'a*' matches 'a' + // 'a*' matches 'aa' + : '[^/]*' + + return `${prefix}(?=$|\\/$)` } + ], +] + +// A simple cache, because an ignore rule only has only one certain meaning +const regexCache = Object.create(null) + +// @param {pattern} +const makeRegex = (pattern, ignoreCase) => { + let source = regexCache[pattern] + + if (!source) { + source = REPLACERS.reduce( + (prev, current) => prev.replace(current[0], current[1].bind(pattern)), + pattern + ) + regexCache[pattern] = source + } + + return ignoreCase + ? new RegExp(source, 'i') + : new RegExp(source) } -exports["default"] = ClusterAllFailedError; +const isString = subject => typeof subject === 'string' -/***/ }), +// > A blank line matches no files, so it can serve as a separator for readability. +const checkPattern = pattern => pattern + && isString(pattern) + && !REGEX_TEST_BLANK_LINE.test(pattern) -/***/ 90735: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + // > A line starting with # serves as a comment. + && pattern.indexOf('#') !== 0 -"use strict"; +const splitPattern = pattern => pattern.split(REGEX_SPLITALL_CRLF) -Object.defineProperty(exports, "__esModule", ({ value: true })); -const redis_errors_1 = __nccwpck_require__(81879); -class MaxRetriesPerRequestError extends redis_errors_1.AbortError { - constructor(maxRetriesPerRequest) { - const message = `Reached the max retries per request limit (which is ${maxRetriesPerRequest}). Refer to "maxRetriesPerRequest" option for details.`; - super(message); - Error.captureStackTrace(this, this.constructor); - } - get name() { - return this.constructor.name; - } +class IgnoreRule { + constructor ( + origin, + pattern, + negative, + regex + ) { + this.origin = origin + this.pattern = pattern + this.negative = negative + this.regex = regex + } } -exports["default"] = MaxRetriesPerRequestError; +const createRule = (pattern, ignoreCase) => { + const origin = pattern + let negative = false + + // > An optional prefix "!" which negates the pattern; + if (pattern.indexOf('!') === 0) { + negative = true + pattern = pattern.substr(1) + } + + pattern = pattern + // > Put a backslash ("\") in front of the first "!" for patterns that + // > begin with a literal "!", for example, `"\!important!.txt"`. + .replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, '!') + // > Put a backslash ("\") in front of the first hash for patterns that + // > begin with a hash. + .replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, '#') + + const regex = makeRegex(pattern, ignoreCase) + + return new IgnoreRule( + origin, + pattern, + negative, + regex + ) +} + +const throwError = (message, Ctor) => { + throw new Ctor(message) +} + +const checkPath = (path, originalPath, doThrow) => { + if (!isString(path)) { + return doThrow( + `path must be a string, but got \`${originalPath}\``, + TypeError + ) + } + + // We don't know if we should ignore EMPTY, so throw + if (!path) { + return doThrow(`path must not be empty`, TypeError) + } + + // Check if it is a relative path + if (checkPath.isNotRelative(path)) { + const r = '`path.relative()`d' + return doThrow( + `path should be a ${r} string, but got "${originalPath}"`, + RangeError + ) + } + + return true +} + +const isNotRelative = path => REGEX_TEST_INVALID_PATH.test(path) + +checkPath.isNotRelative = isNotRelative +checkPath.convert = p => p + +class Ignore { + constructor ({ + ignorecase = true, + ignoreCase = ignorecase, + allowRelativePaths = false + } = {}) { + define(this, KEY_IGNORE, true) + + this._rules = [] + this._ignoreCase = ignoreCase + this._allowRelativePaths = allowRelativePaths + this._initCache() + } -/***/ }), + _initCache () { + this._ignoreCache = Object.create(null) + this._testCache = Object.create(null) + } -/***/ 23961: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + _addPattern (pattern) { + // #32 + if (pattern && pattern[KEY_IGNORE]) { + this._rules = this._rules.concat(pattern._rules) + this._added = true + return + } -"use strict"; + if (checkPattern(pattern)) { + const rule = createRule(pattern, this._ignoreCase) + this._added = true + this._rules.push(rule) + } + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -const MaxRetriesPerRequestError_1 = __nccwpck_require__(90735); -exports.MaxRetriesPerRequestError = MaxRetriesPerRequestError_1.default; + // @param {Array | string | Ignore} pattern + add (pattern) { + this._added = false + makeArray( + isString(pattern) + ? splitPattern(pattern) + : pattern + ).forEach(this._addPattern, this) -/***/ }), + // Some rules have just added to the ignore, + // making the behavior changed. + if (this._added) { + this._initCache() + } -/***/ 45069: -/***/ ((module, exports, __nccwpck_require__) => { + return this + } -"use strict"; + // legacy + addPattern (pattern) { + return this.add(pattern) + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports = module.exports = __nccwpck_require__(83609)["default"]; -var redis_1 = __nccwpck_require__(83609); -exports["default"] = redis_1.default; -var cluster_1 = __nccwpck_require__(17208); -exports.Cluster = cluster_1.default; -var command_1 = __nccwpck_require__(90803); -exports.Command = command_1.default; -var ScanStream_1 = __nccwpck_require__(6134); -exports.ScanStream = ScanStream_1.default; -var pipeline_1 = __nccwpck_require__(42803); -exports.Pipeline = pipeline_1.default; -var AbstractConnector_1 = __nccwpck_require__(72712); -exports.AbstractConnector = AbstractConnector_1.default; -var SentinelConnector_1 = __nccwpck_require__(10379); -exports.SentinelConnector = SentinelConnector_1.default; -exports.SentinelIterator = SentinelConnector_1.SentinelIterator; -// No TS typings -exports.ReplyError = __nccwpck_require__(81879).ReplyError; -const PromiseContainer = __nccwpck_require__(71475); -Object.defineProperty(exports, "Promise", ({ - get() { - return PromiseContainer.get(); - }, - set(lib) { - PromiseContainer.set(lib); - }, -})); -function print(err, reply) { - if (err) { - console.log("Error: " + err); - } - else { - console.log("Reply: " + reply); - } -} -exports.print = print; + // | ignored : unignored + // negative | 0:0 | 0:1 | 1:0 | 1:1 + // -------- | ------- | ------- | ------- | -------- + // 0 | TEST | TEST | SKIP | X + // 1 | TESTIF | SKIP | TEST | X + // - SKIP: always skip + // - TEST: always test + // - TESTIF: only test if checkUnignored + // - X: that never happen -/***/ }), + // @param {boolean} whether should check if the path is unignored, + // setting `checkUnignored` to `false` could reduce additional + // path matching. -/***/ 42803: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + // @returns {TestResult} true if a file is ignored + _testOne (path, checkUnignored) { + let ignored = false + let unignored = false -"use strict"; + this._rules.forEach(rule => { + const {negative} = rule + if ( + unignored === negative && ignored !== unignored + || negative && !ignored && !unignored && !checkUnignored + ) { + return + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -const command_1 = __nccwpck_require__(90803); -const util_1 = __nccwpck_require__(73837); -const standard_as_callback_1 = __nccwpck_require__(91543); -const redis_commands_1 = __nccwpck_require__(98020); -const calculateSlot = __nccwpck_require__(48481); -const pMap = __nccwpck_require__(12071); -const PromiseContainer = __nccwpck_require__(71475); -const commander_1 = __nccwpck_require__(33642); -const utils_1 = __nccwpck_require__(94832); -/* - This function derives from the cluster-key-slot implementation. - Instead of checking that all keys have the same slot, it checks that all slots are served by the same set of nodes. - If this is satisfied, it returns the first key's slot. -*/ -function generateMultiWithNodes(redis, keys) { - const slot = calculateSlot(keys[0]); - const target = redis._groupsBySlot[slot]; - for (let i = 1; i < keys.length; i++) { - if (redis._groupsBySlot[calculateSlot(keys[i])] !== target) { - return -1; - } - } - return slot; -} -function Pipeline(redis) { - commander_1.default.call(this); - this.redis = redis; - this.isCluster = - this.redis.constructor.name === "Cluster" || this.redis.isCluster; - this.isPipeline = true; - this.options = redis.options; - this._queue = []; - this._result = []; - this._transactions = 0; - this._shaToScript = {}; - Object.keys(redis.scriptsSet).forEach((name) => { - const script = redis.scriptsSet[name]; - this._shaToScript[script.sha] = script; - this[name] = redis[name]; - this[name + "Buffer"] = redis[name + "Buffer"]; - }); - redis.addedBuiltinSet.forEach((name) => { - this[name] = redis[name]; - this[name + "Buffer"] = redis[name + "Buffer"]; - }); - const Promise = PromiseContainer.get(); - this.promise = new Promise((resolve, reject) => { - this.resolve = resolve; - this.reject = reject; - }); - const _this = this; - Object.defineProperty(this, "length", { - get: function () { - return _this._queue.length; - }, - }); -} -exports["default"] = Pipeline; -Object.assign(Pipeline.prototype, commander_1.default.prototype); -Pipeline.prototype.fillResult = function (value, position) { - if (this._queue[position].name === "exec" && Array.isArray(value[1])) { - const execLength = value[1].length; - for (let i = 0; i < execLength; i++) { - if (value[1][i] instanceof Error) { - continue; - } - const cmd = this._queue[position - (execLength - i)]; - try { - value[1][i] = cmd.transformReply(value[1][i]); - } - catch (err) { - value[1][i] = err; - } - } - } - this._result[position] = value; - if (--this.replyPending) { - return; - } - if (this.isCluster) { - let retriable = true; - let commonError; - for (let i = 0; i < this._result.length; ++i) { - const error = this._result[i][0]; - const command = this._queue[i]; - if (error) { - if (command.name === "exec" && - error.message === - "EXECABORT Transaction discarded because of previous errors.") { - continue; - } - if (!commonError) { - commonError = { - name: error.name, - message: error.message, - }; - } - else if (commonError.name !== error.name || - commonError.message !== error.message) { - retriable = false; - break; - } - } - else if (!command.inTransaction) { - const isReadOnly = redis_commands_1.exists(command.name) && redis_commands_1.hasFlag(command.name, "readonly"); - if (!isReadOnly) { - retriable = false; - break; - } - } - } - if (commonError && retriable) { - const _this = this; - const errv = commonError.message.split(" "); - const queue = this._queue; - let inTransaction = false; - this._queue = []; - for (let i = 0; i < queue.length; ++i) { - if (errv[0] === "ASK" && - !inTransaction && - queue[i].name !== "asking" && - (!queue[i - 1] || queue[i - 1].name !== "asking")) { - const asking = new command_1.default("asking"); - asking.ignore = true; - this.sendCommand(asking); - } - queue[i].initPromise(); - this.sendCommand(queue[i]); - inTransaction = queue[i].inTransaction; - } - let matched = true; - if (typeof this.leftRedirections === "undefined") { - this.leftRedirections = {}; - } - const exec = function () { - _this.exec(); - }; - this.redis.handleError(commonError, this.leftRedirections, { - moved: function (slot, key) { - _this.preferKey = key; - _this.redis.slots[errv[1]] = [key]; - _this.redis._groupsBySlot[errv[1]] = - _this.redis._groupsIds[_this.redis.slots[errv[1]].join(";")]; - _this.redis.refreshSlotsCache(); - _this.exec(); - }, - ask: function (slot, key) { - _this.preferKey = key; - _this.exec(); - }, - tryagain: exec, - clusterDown: exec, - connectionClosed: exec, - maxRedirections: () => { - matched = false; - }, - defaults: () => { - matched = false; - }, - }); - if (matched) { - return; - } - } - } - let ignoredCount = 0; - for (let i = 0; i < this._queue.length - ignoredCount; ++i) { - if (this._queue[i + ignoredCount].ignore) { - ignoredCount += 1; - } - this._result[i] = this._result[i + ignoredCount]; - } - this.resolve(this._result.slice(0, this._result.length - ignoredCount)); -}; -Pipeline.prototype.sendCommand = function (command) { - if (this._transactions > 0) { - command.inTransaction = true; - } - const position = this._queue.length; - command.pipelineIndex = position; - command.promise - .then((result) => { - this.fillResult([null, result], position); + const matched = rule.regex.test(path) + + if (matched) { + ignored = !negative + unignored = negative + } }) - .catch((error) => { - this.fillResult([error], position); - }); - this._queue.push(command); - return this; -}; -Pipeline.prototype.addBatch = function (commands) { - let command, commandName, args; - for (let i = 0; i < commands.length; ++i) { - command = commands[i]; - commandName = command[0]; - args = command.slice(1); - this[commandName].apply(this, args); - } - return this; -}; -const multi = Pipeline.prototype.multi; -Pipeline.prototype.multi = function () { - this._transactions += 1; - return multi.apply(this, arguments); -}; -const execBuffer = Pipeline.prototype.execBuffer; -const exec = Pipeline.prototype.exec; -Pipeline.prototype.execBuffer = util_1.deprecate(function () { - if (this._transactions > 0) { - this._transactions -= 1; - } - return execBuffer.apply(this, arguments); -}, "Pipeline#execBuffer: Use Pipeline#exec instead"); -// NOTE: To avoid an unhandled promise rejection, this will unconditionally always return this.promise, -// which always has the rejection handled by standard-as-callback -// adding the provided rejection callback. -// -// If a different promise instance were returned, that promise would cause its own unhandled promise rejection -// errors, even if that promise unconditionally resolved to **the resolved value of** this.promise. -Pipeline.prototype.exec = function (callback) { - // Wait for the cluster to be connected, since we need nodes information before continuing - if (this.isCluster && !this.redis.slots.length) { - if (this.redis.status === "wait") - this.redis.connect().catch(utils_1.noop); - this.redis.delayUntilReady((err) => { - if (err) { - callback(err); - return; - } - this.exec(callback); - }); - return this.promise; - } - if (this._transactions > 0) { - this._transactions -= 1; - return (this.options.dropBufferSupport ? exec : execBuffer).apply(this, arguments); - } - if (!this.nodeifiedPromise) { - this.nodeifiedPromise = true; - standard_as_callback_1.default(this.promise, callback); - } - if (!this._queue.length) { - this.resolve([]); - } - let pipelineSlot; - if (this.isCluster) { - // List of the first key for each command - const sampleKeys = []; - for (let i = 0; i < this._queue.length; i++) { - const keys = this._queue[i].getKeys(); - if (keys.length) { - sampleKeys.push(keys[0]); - } - // For each command, check that the keys belong to the same slot - if (keys.length && calculateSlot.generateMulti(keys) < 0) { - this.reject(new Error("All the keys in a pipeline command should belong to the same slot")); - return this.promise; - } - } - if (sampleKeys.length) { - pipelineSlot = generateMultiWithNodes(this.redis, sampleKeys); - if (pipelineSlot < 0) { - this.reject(new Error("All keys in the pipeline should belong to the same slots allocation group")); - return this.promise; - } - } - else { - // Send the pipeline to a random node - pipelineSlot = (Math.random() * 16384) | 0; - } - } - // Check whether scripts exists - const scripts = []; - for (let i = 0; i < this._queue.length; ++i) { - const item = this._queue[i]; - if (item.name !== "evalsha") { - continue; - } - const script = this._shaToScript[item.args[0]]; - if (!script || - this.redis._addedScriptHashes[script.sha] || - scripts.includes(script)) { - continue; - } - scripts.push(script); - } - const _this = this; - if (!scripts.length) { - return execPipeline(); - } - // In cluster mode, always load scripts before running the pipeline - if (this.isCluster) { - pMap(scripts, (script) => _this.redis.script("load", script.lua), { - concurrency: 10, - }) - .then(function () { - for (let i = 0; i < scripts.length; i++) { - _this.redis._addedScriptHashes[scripts[i].sha] = true; - } - }) - .then(execPipeline, this.reject); - return this.promise; + + return { + ignored, + unignored } - this.redis - .script("exists", scripts.map(({ sha }) => sha)) - .then(function (results) { - const pending = []; - for (let i = 0; i < results.length; ++i) { - if (!results[i]) { - pending.push(scripts[i]); - } - } - const Promise = PromiseContainer.get(); - return Promise.all(pending.map(function (script) { - return _this.redis.script("load", script.lua); - })); - }) - .then(function () { - for (let i = 0; i < scripts.length; i++) { - _this.redis._addedScriptHashes[scripts[i].sha] = true; - } - }) - .then(execPipeline, this.reject); - return this.promise; - function execPipeline() { - let data = ""; - let buffers; - let writePending = (_this.replyPending = _this._queue.length); - let node; - if (_this.isCluster) { - node = { - slot: pipelineSlot, - redis: _this.redis.connectionPool.nodes.all[_this.preferKey], - }; - } - let bufferMode = false; - const stream = { - write: function (writable) { - if (writable instanceof Buffer) { - bufferMode = true; - } - if (bufferMode) { - if (!buffers) { - buffers = []; - } - if (typeof data === "string") { - buffers.push(Buffer.from(data, "utf8")); - data = undefined; - } - buffers.push(typeof writable === "string" - ? Buffer.from(writable, "utf8") - : writable); - } - else { - data += writable; - } - if (!--writePending) { - let sendData; - if (buffers) { - sendData = Buffer.concat(buffers); - } - else { - sendData = data; - } - if (_this.isCluster) { - node.redis.stream.write(sendData); - } - else { - _this.redis.stream.write(sendData); - } - // Reset writePending for resending - writePending = _this._queue.length; - data = ""; - buffers = undefined; - bufferMode = false; - } - }, - }; - for (let i = 0; i < _this._queue.length; ++i) { - _this.redis.sendCommand(_this._queue[i], stream, node); - } - return _this.promise; + } + + // @returns {TestResult} + _test (originalPath, cache, checkUnignored, slices) { + const path = originalPath + // Supports nullable path + && checkPath.convert(originalPath) + + checkPath( + path, + originalPath, + this._allowRelativePaths + ? RETURN_FALSE + : throwError + ) + + return this._t(path, cache, checkUnignored, slices) + } + + _t (path, cache, checkUnignored, slices) { + if (path in cache) { + return cache[path] } -}; + if (!slices) { + // path/to/a.js + // ['path', 'to', 'a.js'] + slices = path.split(SLASH) + } -/***/ }), + slices.pop() -/***/ 71475: -/***/ ((__unused_webpack_module, exports) => { + // If the path has no parent directory, just test it + if (!slices.length) { + return cache[path] = this._testOne(path, checkUnignored) + } -"use strict"; + const parent = this._t( + slices.join(SLASH) + SLASH, + cache, + checkUnignored, + slices + ) -Object.defineProperty(exports, "__esModule", ({ value: true })); -function isPromise(obj) { - return (!!obj && - (typeof obj === "object" || typeof obj === "function") && - typeof obj.then === "function"); -} -exports.isPromise = isPromise; -let promise = Promise; -function get() { - return promise; + // If the path contains a parent directory, check the parent first + return cache[path] = parent.ignored + // > It is not possible to re-include a file if a parent directory of + // > that file is excluded. + ? parent + : this._testOne(path, checkUnignored) + } + + ignores (path) { + return this._test(path, this._ignoreCache, false).ignored + } + + createFilter () { + return path => !this.ignores(path) + } + + filter (paths) { + return makeArray(paths).filter(this.createFilter()) + } + + // @returns {TestResult} + test (path) { + return this._test(path, this._testCache, true) + } } -exports.get = get; -function set(lib) { - if (typeof lib !== "function") { - throw new Error(`Provided Promise must be a function, got ${lib}`); - } - promise = lib; + +const factory = options => new Ignore(options) + +const isPathValid = path => + checkPath(path && checkPath.convert(path), path, RETURN_FALSE) + +factory.isPathValid = isPathValid + +// Fixes typescript +factory.default = factory + +module.exports = factory + +// Windows +// -------------------------------------------------------------- +/* istanbul ignore if */ +if ( + // Detect `process` so that it can run in browsers. + typeof process !== 'undefined' + && ( + process.env && process.env.IGNORE_TEST_WIN32 + || process.platform === 'win32' + ) +) { + /* eslint no-control-regex: "off" */ + const makePosix = str => /^\\\\\?\\/.test(str) + || /["<>|\u0000-\u001F]+/u.test(str) + ? str + : str.replace(/\\/g, '/') + + checkPath.convert = makePosix + + // 'C:\\foo' <- 'C:\\foo' has been converted to 'C:/' + // 'd:\\foo' + const REGIX_IS_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i + checkPath.isNotRelative = path => + REGIX_IS_WINDOWS_PATH_ABSOLUTE.test(path) + || isNotRelative(path) } -exports.set = set; /***/ }), -/***/ 1422: -/***/ ((__unused_webpack_module, exports) => { +/***/ 98043: +/***/ ((module) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.DEFAULT_REDIS_OPTIONS = { - // Connection - port: 6379, - host: "localhost", - family: 4, - connectTimeout: 10000, - disconnectTimeout: 2000, - retryStrategy: function (times) { - return Math.min(times * 50, 2000); - }, - keepAlive: 0, - noDelay: true, - connectionName: null, - // Sentinel - sentinels: null, - name: null, - role: "master", - sentinelRetryStrategy: function (times) { - return Math.min(times * 10, 1000); - }, - sentinelReconnectStrategy: function () { - // This strategy only applies when sentinels are used for detecting - // a failover, not during initial master resolution. - // The deployment can still function when some of the sentinels are down - // for a long period of time, so we may not want to attempt reconnection - // very often. Therefore the default interval is fairly long (1 minute). - return 60000; - }, - natMap: null, - enableTLSForSentinelMode: false, - updateSentinels: true, - failoverDetector: false, - // Status - username: null, - password: null, - db: 0, - // Others - dropBufferSupport: false, - enableOfflineQueue: true, - enableReadyCheck: true, - autoResubscribe: true, - autoResendUnfulfilledCommands: true, - lazyConnect: false, - keyPrefix: "", - reconnectOnError: null, - readOnly: false, - stringNumbers: false, - maxRetriesPerRequest: 20, - maxLoadingRetryTime: 10000, - enableAutoPipelining: false, - autoPipeliningIgnoredCommands: [], - maxScriptsCachingTime: 60000, - sentinelMaxConnections: 10, + +module.exports = (string, count = 1, options) => { + options = { + indent: ' ', + includeEmptyLines: false, + ...options + }; + + if (typeof string !== 'string') { + throw new TypeError( + `Expected \`input\` to be a \`string\`, got \`${typeof string}\`` + ); + } + + if (typeof count !== 'number') { + throw new TypeError( + `Expected \`count\` to be a \`number\`, got \`${typeof count}\`` + ); + } + + if (typeof options.indent !== 'string') { + throw new TypeError( + `Expected \`options.indent\` to be a \`string\`, got \`${typeof options.indent}\`` + ); + } + + if (count === 0) { + return string; + } + + const regex = options.includeEmptyLines ? /^/gm : /^(?!\s*$)/gm; + + return string.replace(regex, options.indent.repeat(count)); }; /***/ }), -/***/ 74276: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; +/***/ 44124: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -Object.defineProperty(exports, "__esModule", ({ value: true })); -const redis_errors_1 = __nccwpck_require__(81879); -const command_1 = __nccwpck_require__(90803); -const errors_1 = __nccwpck_require__(23961); -const utils_1 = __nccwpck_require__(94832); -const DataHandler_1 = __nccwpck_require__(30545); -const debug = utils_1.Debug("connection"); -function connectHandler(self) { - return function () { - self.setStatus("connect"); - self.resetCommandQueue(); - // AUTH command should be processed before any other commands - let flushed = false; - const { connectionEpoch } = self; - if (self.condition.auth) { - self.auth(self.condition.auth, function (err) { - if (connectionEpoch !== self.connectionEpoch) { - return; - } - if (err) { - if (err.message.indexOf("no password is set") !== -1) { - console.warn("[WARN] Redis server does not require a password, but a password was supplied."); - } - else if (err.message.indexOf("without any password configured for the default user") !== -1) { - console.warn("[WARN] This Redis server's `default` user does not require a password, but a password was supplied"); - } - else if (err.message.indexOf("wrong number of arguments for 'auth' command") !== -1) { - console.warn(`[ERROR] The server returned "wrong number of arguments for 'auth' command". You are probably passing both username and password to Redis version 5 or below. You should only pass the 'password' option for Redis version 5 and under.`); - } - else { - flushed = true; - self.recoverFromFatalError(err, err); - } - } - }); - } - if (self.condition.select) { - self.select(self.condition.select).catch((err) => { - // If the node is in cluster mode, select is disallowed. - // In this case, reconnect won't help. - self.silentEmit("error", err); - }); - } - if (!self.options.enableReadyCheck) { - exports.readyHandler(self)(); - } - /* - No need to keep the reference of DataHandler here - because we don't need to do the cleanup. - `Stream#end()` will remove all listeners for us. - */ - new DataHandler_1.default(self, { - stringNumbers: self.options.stringNumbers, - dropBufferSupport: self.options.dropBufferSupport, - }); - if (self.options.enableReadyCheck) { - self._readyCheck(function (err, info) { - if (connectionEpoch !== self.connectionEpoch) { - return; - } - if (err) { - if (!flushed) { - self.recoverFromFatalError(new Error("Ready check failed: " + err.message), err); - } - } - else { - self.serverInfo = info; - if (self.connector.check(info)) { - exports.readyHandler(self)(); - } - else { - self.disconnect(true); - } - } - }); - } - }; -} -exports.connectHandler = connectHandler; -function abortError(command) { - const err = new redis_errors_1.AbortError("Command aborted due to connection close"); - err.command = { - name: command.name, - args: command.args, - }; - return err; -} -// If a contiguous set of pipeline commands starts from index zero then they -// can be safely reattempted. If however we have a chain of pipelined commands -// starting at index 1 or more it means we received a partial response before -// the connection close and those pipelined commands must be aborted. For -// example, if the queue looks like this: [2, 3, 4, 0, 1, 2] then after -// aborting and purging we'll have a queue that looks like this: [0, 1, 2] -function abortIncompletePipelines(commandQueue) { - let expectedIndex = 0; - for (let i = 0; i < commandQueue.length;) { - const command = commandQueue.peekAt(i).command; - const pipelineIndex = command.pipelineIndex; - if (pipelineIndex === undefined || pipelineIndex === 0) { - expectedIndex = 0; - } - if (pipelineIndex !== undefined && pipelineIndex !== expectedIndex++) { - commandQueue.remove(i, 1); - command.reject(abortError(command)); - continue; - } - i++; - } -} -// If only a partial transaction result was received before connection close, -// we have to abort any transaction fragments that may have ended up in the -// offline queue -function abortTransactionFragments(commandQueue) { - for (let i = 0; i < commandQueue.length;) { - const command = commandQueue.peekAt(i).command; - if (command.name === "multi") { - break; - } - if (command.name === "exec") { - commandQueue.remove(i, 1); - command.reject(abortError(command)); - break; - } - if (command.inTransaction) { - commandQueue.remove(i, 1); - command.reject(abortError(command)); - } - else { - i++; - } - } -} -function closeHandler(self) { - return function () { - self.setStatus("close"); - if (!self.prevCondition) { - self.prevCondition = self.condition; - } - if (self.commandQueue.length) { - abortIncompletePipelines(self.commandQueue); - self.prevCommandQueue = self.commandQueue; - } - if (self.offlineQueue.length) { - abortTransactionFragments(self.offlineQueue); - } - if (self.manuallyClosing) { - self.manuallyClosing = false; - debug("skip reconnecting since the connection is manually closed."); - return close(); - } - if (typeof self.options.retryStrategy !== "function") { - debug("skip reconnecting because `retryStrategy` is not a function"); - return close(); - } - const retryDelay = self.options.retryStrategy(++self.retryAttempts); - if (typeof retryDelay !== "number") { - debug("skip reconnecting because `retryStrategy` doesn't return a number"); - return close(); - } - debug("reconnect in %sms", retryDelay); - self.setStatus("reconnecting", retryDelay); - self.reconnectTimeout = setTimeout(function () { - self.reconnectTimeout = null; - self.connect().catch(utils_1.noop); - }, retryDelay); - const { maxRetriesPerRequest } = self.options; - if (typeof maxRetriesPerRequest === "number") { - if (maxRetriesPerRequest < 0) { - debug("maxRetriesPerRequest is negative, ignoring..."); - } - else { - const remainder = self.retryAttempts % (maxRetriesPerRequest + 1); - if (remainder === 0) { - debug("reach maxRetriesPerRequest limitation, flushing command queue..."); - self.flushQueue(new errors_1.MaxRetriesPerRequestError(maxRetriesPerRequest)); - } - } - } - }; - function close() { - self.setStatus("end"); - self.flushQueue(new Error(utils_1.CONNECTION_CLOSED_ERROR_MSG)); - } -} -exports.closeHandler = closeHandler; -function errorHandler(self) { - return function (error) { - debug("error: %s", error); - self.silentEmit("error", error); - }; +try { + var util = __nccwpck_require__(73837); + /* istanbul ignore next */ + if (typeof util.inherits !== 'function') throw ''; + module.exports = util.inherits; +} catch (e) { + /* istanbul ignore next */ + module.exports = __nccwpck_require__(8544); } -exports.errorHandler = errorHandler; -function readyHandler(self) { - return function () { - self.setStatus("ready"); - self.retryAttempts = 0; - if (self.options.monitor) { - self.call("monitor"); - const { sendCommand } = self; - self.sendCommand = function (command) { - if (command_1.default.checkFlag("VALID_IN_MONITOR_MODE", command.name)) { - return sendCommand.call(self, command); - } - command.reject(new Error("Connection is in monitoring mode, can't process commands.")); - return command.promise; - }; - self.once("close", function () { - delete self.sendCommand; - }); - self.setStatus("monitoring"); - return; - } - const finalSelect = self.prevCondition - ? self.prevCondition.select - : self.condition.select; - if (self.options.connectionName) { - debug("set the connection name [%s]", self.options.connectionName); - self.client("setname", self.options.connectionName).catch(utils_1.noop); - } - if (self.options.readOnly) { - debug("set the connection to readonly mode"); - self.readonly().catch(utils_1.noop); - } - if (self.prevCondition) { - const condition = self.prevCondition; - self.prevCondition = null; - if (condition.subscriber && self.options.autoResubscribe) { - // We re-select the previous db first since - // `SELECT` command is not valid in sub mode. - if (self.condition.select !== finalSelect) { - debug("connect to db [%d]", finalSelect); - self.select(finalSelect); - } - const subscribeChannels = condition.subscriber.channels("subscribe"); - if (subscribeChannels.length) { - debug("subscribe %d channels", subscribeChannels.length); - self.subscribe(subscribeChannels); - } - const psubscribeChannels = condition.subscriber.channels("psubscribe"); - if (psubscribeChannels.length) { - debug("psubscribe %d channels", psubscribeChannels.length); - self.psubscribe(psubscribeChannels); - } - } - } - if (self.prevCommandQueue) { - if (self.options.autoResendUnfulfilledCommands) { - debug("resend %d unfulfilled commands", self.prevCommandQueue.length); - while (self.prevCommandQueue.length > 0) { - const item = self.prevCommandQueue.shift(); - if (item.select !== self.condition.select && - item.command.name !== "select") { - self.select(item.select); - } - self.sendCommand(item.command, item.stream); - } - } - else { - self.prevCommandQueue = null; - } - } - if (self.offlineQueue.length) { - debug("send %d commands in offline queue", self.offlineQueue.length); - const offlineQueue = self.offlineQueue; - self.resetOfflineQueue(); - while (offlineQueue.length > 0) { - const item = offlineQueue.shift(); - if (item.select !== self.condition.select && - item.command.name !== "select") { - self.select(item.select); - } - self.sendCommand(item.command, item.stream); - } - } - if (self.condition.select !== finalSelect) { - debug("connect to db [%d]", finalSelect); - self.select(finalSelect); + + +/***/ }), + +/***/ 8544: +/***/ ((module) => { + +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true } - }; + }) + } + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } + } } -exports.readyHandler = readyHandler; /***/ }), -/***/ 83609: +/***/ 30545: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -const lodash_1 = __nccwpck_require__(20961); -const util_1 = __nccwpck_require__(73837); -const events_1 = __nccwpck_require__(82361); -const Deque = __nccwpck_require__(42342); const command_1 = __nccwpck_require__(90803); -const commander_1 = __nccwpck_require__(33642); const utils_1 = __nccwpck_require__(94832); -const standard_as_callback_1 = __nccwpck_require__(91543); -const eventHandler = __nccwpck_require__(74276); -const connectors_1 = __nccwpck_require__(72340); -const ScanStream_1 = __nccwpck_require__(6134); -const commands = __nccwpck_require__(98020); -const PromiseContainer = __nccwpck_require__(71475); -const transaction_1 = __nccwpck_require__(14645); -const RedisOptions_1 = __nccwpck_require__(1422); -const debug = utils_1.Debug("redis"); -/** - * Creates a Redis instance - * - * @constructor - * @param {(number|string|Object)} [port=6379] - Port of the Redis server, - * or a URL string(see the examples below), - * or the `options` object(see the third argument). - * @param {string|Object} [host=localhost] - Host of the Redis server, - * when the first argument is a URL string, - * this argument is an object represents the options. - * @param {Object} [options] - Other options. - * @param {number} [options.port=6379] - Port of the Redis server. - * @param {string} [options.host=localhost] - Host of the Redis server. - * @param {string} [options.family=4] - Version of IP stack. Defaults to 4. - * @param {string} [options.path=null] - Local domain socket path. If set the `port`, - * `host` and `family` will be ignored. - * @param {number} [options.keepAlive=0] - TCP KeepAlive on the socket with a X ms delay before start. - * Set to a non-number value to disable keepAlive. - * @param {boolean} [options.noDelay=true] - Whether to disable the Nagle's Algorithm. By default we disable - * it to reduce the latency. - * @param {string} [options.connectionName=null] - Connection name. - * @param {number} [options.db=0] - Database index to use. - * @param {string} [options.password=null] - If set, client will send AUTH command - * with the value of this option when connected. - * @param {string} [options.username=null] - Similar to `password`, Provide this for Redis ACL support. - * @param {boolean} [options.dropBufferSupport=false] - Drop the buffer support for better performance. - * This option is recommended to be enabled when - * handling large array response and you don't need the buffer support. - * @param {boolean} [options.enableReadyCheck=true] - When a connection is established to - * the Redis server, the server might still be loading the database from disk. - * While loading, the server not respond to any commands. - * To work around this, when this option is `true`, - * ioredis will check the status of the Redis server, - * and when the Redis server is able to process commands, - * a `ready` event will be emitted. - * @param {boolean} [options.enableOfflineQueue=true] - By default, - * if there is no active connection to the Redis server, - * commands are added to a queue and are executed once the connection is "ready" - * (when `enableReadyCheck` is `true`, - * "ready" means the Redis server has loaded the database from disk, otherwise means the connection - * to the Redis server has been established). If this option is false, - * when execute the command when the connection isn't ready, an error will be returned. - * @param {number} [options.connectTimeout=10000] - The milliseconds before a timeout occurs during the initial - * connection to the Redis server. - * @param {boolean} [options.autoResubscribe=true] - After reconnected, if the previous connection was in the - * subscriber mode, client will auto re-subscribe these channels. - * @param {boolean} [options.autoResendUnfulfilledCommands=true] - If true, client will resend unfulfilled - * commands(e.g. block commands) in the previous connection when reconnected. - * @param {boolean} [options.lazyConnect=false] - By default, - * When a new `Redis` instance is created, it will connect to Redis server automatically. - * If you want to keep the instance disconnected until a command is called, you can pass the `lazyConnect` option to - * the constructor: - * - * ```javascript - * var redis = new Redis({ lazyConnect: true }); - * // No attempting to connect to the Redis server here. - - * // Now let's connect to the Redis server - * redis.get('foo', function () { - * }); - * ``` - * @param {Object} [options.tls] - TLS connection support. See https://github.com/luin/ioredis#tls-options - * @param {string} [options.keyPrefix=''] - The prefix to prepend to all keys in a command. - * @param {function} [options.retryStrategy] - See "Quick Start" section - * @param {number} [options.maxRetriesPerRequest] - See "Quick Start" section - * @param {number} [options.maxLoadingRetryTime=10000] - when redis server is not ready, we will wait for - * `loading_eta_seconds` from `info` command or maxLoadingRetryTime (milliseconds), whichever is smaller. - * @param {function} [options.reconnectOnError] - See "Quick Start" section - * @param {boolean} [options.readOnly=false] - Enable READONLY mode for the connection. - * Only available for cluster mode. - * @param {boolean} [options.stringNumbers=false] - Force numbers to be always returned as JavaScript - * strings. This option is necessary when dealing with big numbers (exceed the [-2^53, +2^53] range). - * @param {boolean} [options.enableTLSForSentinelMode=false] - Whether to support the `tls` option - * when connecting to Redis via sentinel mode. - * @param {NatMap} [options.natMap=null] NAT map for sentinel connector. - * @param {boolean} [options.updateSentinels=true] - Update the given `sentinels` list with new IP - * addresses when communicating with existing sentinels. - * @param {boolean} [options.failoverDetector=false] - Detect failover actively by subscribing to the - * related channels. With this option disabled, ioredis is still able to detect failovers because Redis - * Sentinel will disconnect all clients whenever a failover happens, so ioredis will reconnect to the new - * master. This option is useful when you want to detect failover quicker, but it will create more TCP - * connections to Redis servers in order to subscribe to related channels. -* @param {boolean} [options.enableAutoPipelining=false] - When enabled, all commands issued during an event loop - * iteration are automatically wrapped in a pipeline and sent to the server at the same time. - * This can dramatically improve performance. - * @param {string[]} [options.autoPipeliningIgnoredCommands=[]] - The list of commands which must not be automatically wrapped in pipelines. - * @param {number} [options.maxScriptsCachingTime=60000] Default script definition caching time. - * @extends [EventEmitter](http://nodejs.org/api/events.html#events_class_events_eventemitter) - * @extends Commander - * @example - * ```js - * var Redis = require('ioredis'); - * - * var redis = new Redis(); - * - * var redisOnPort6380 = new Redis(6380); - * var anotherRedis = new Redis(6380, '192.168.100.1'); - * var unixSocketRedis = new Redis({ path: '/tmp/echo.sock' }); - * var unixSocketRedis2 = new Redis('/tmp/echo.sock'); - * var urlRedis = new Redis('redis://user:password@redis-service.com:6379/'); - * var urlRedis2 = new Redis('//localhost:6379'); - * var urlRedisTls = new Redis('rediss://user:password@redis-service.com:6379/'); - * var authedRedis = new Redis(6380, '192.168.100.1', { password: 'password' }); - * ``` - */ -exports["default"] = Redis; -function Redis() { - if (!(this instanceof Redis)) { - console.error(new Error("Calling `Redis()` like a function is deprecated. Using `new Redis()` instead.").stack.replace("Error", "Warning")); - return new Redis(arguments[0], arguments[1], arguments[2]); - } - this.parseOptions(arguments[0], arguments[1], arguments[2]); - events_1.EventEmitter.call(this); - commander_1.default.call(this); - this.resetCommandQueue(); - this.resetOfflineQueue(); - this.connectionEpoch = 0; - if (this.options.Connector) { - this.connector = new this.options.Connector(this.options); - } - else if (this.options.sentinels) { - const sentinelConnector = new connectors_1.SentinelConnector(this.options); - sentinelConnector.emitter = this; - this.connector = sentinelConnector; - } - else { - this.connector = new connectors_1.StandaloneConnector(this.options); +const RedisParser = __nccwpck_require__(53315); +const SubscriptionSet_1 = __nccwpck_require__(73527); +const debug = utils_1.Debug("dataHandler"); +class DataHandler { + constructor(redis, parserOptions) { + this.redis = redis; + const parser = new RedisParser({ + stringNumbers: parserOptions.stringNumbers, + returnBuffers: !parserOptions.dropBufferSupport, + returnError: (err) => { + this.returnError(err); + }, + returnFatalError: (err) => { + this.returnFatalError(err); + }, + returnReply: (reply) => { + this.returnReply(reply); + }, + }); + redis.stream.on("data", (data) => { + parser.execute(data); + }); } - this.retryAttempts = 0; - // Prepare a cache of scripts and setup a interval which regularly clears it - this._addedScriptHashes = {}; - // Prepare autopipelines structures - this._autoPipelines = new Map(); - this._runningAutoPipelines = new Set(); - Object.defineProperty(this, "autoPipelineQueueSize", { - get() { - let queued = 0; - for (const pipeline of this._autoPipelines.values()) { - queued += pipeline.length; - } - return queued; - }, - }); - // end(or wait) -> connecting -> connect -> ready -> end - if (this.options.lazyConnect) { - this.setStatus("wait"); + returnFatalError(err) { + err.message += ". Please report this."; + this.redis.recoverFromFatalError(err, err, { offlineQueue: false }); } - else { - this.connect().catch(lodash_1.noop); + returnError(err) { + const item = this.shiftCommand(err); + if (!item) { + return; + } + err.command = { + name: item.command.name, + args: item.command.args, + }; + this.redis.handleReconnection(err, item); } -} -util_1.inherits(Redis, events_1.EventEmitter); -Object.assign(Redis.prototype, commander_1.default.prototype); -/** - * Create a Redis instance - * - * @deprecated - */ -// @ts-ignore -Redis.createClient = function (...args) { - // @ts-ignore - return new Redis(...args); -}; -/** - * Default options - * - * @var defaultOptions - * @private - */ -Redis.defaultOptions = RedisOptions_1.DEFAULT_REDIS_OPTIONS; -Redis.prototype.resetCommandQueue = function () { - this.commandQueue = new Deque(); -}; -Redis.prototype.resetOfflineQueue = function () { - this.offlineQueue = new Deque(); -}; -Redis.prototype.parseOptions = function () { - this.options = {}; - let isTls = false; - for (let i = 0; i < arguments.length; ++i) { - const arg = arguments[i]; - if (arg === null || typeof arg === "undefined") { - continue; + returnReply(reply) { + if (this.handleMonitorReply(reply)) { + return; } - if (typeof arg === "object") { - lodash_1.defaults(this.options, arg); + if (this.handleSubscriberReply(reply)) { + return; } - else if (typeof arg === "string") { - lodash_1.defaults(this.options, utils_1.parseURL(arg)); - if (arg.startsWith("rediss://")) { - isTls = true; + const item = this.shiftCommand(reply); + if (!item) { + return; + } + if (command_1.default.checkFlag("ENTER_SUBSCRIBER_MODE", item.command.name)) { + this.redis.condition.subscriber = new SubscriptionSet_1.default(); + this.redis.condition.subscriber.add(item.command.name, reply[1].toString()); + if (!fillSubCommand(item.command, reply[2])) { + this.redis.commandQueue.unshift(item); } } - else if (typeof arg === "number") { - this.options.port = arg; + else if (command_1.default.checkFlag("EXIT_SUBSCRIBER_MODE", item.command.name)) { + if (!fillUnsubCommand(item.command, reply[2])) { + this.redis.commandQueue.unshift(item); + } } else { - throw new Error("Invalid argument " + arg); + item.command.resolve(reply); } } - if (isTls) { - lodash_1.defaults(this.options, { tls: true }); - } - lodash_1.defaults(this.options, Redis.defaultOptions); - if (typeof this.options.port === "string") { - this.options.port = parseInt(this.options.port, 10); - } - if (typeof this.options.db === "string") { - this.options.db = parseInt(this.options.db, 10); - } - if (this.options.parser === "hiredis") { - console.warn("Hiredis parser is abandoned since ioredis v3.0, and JavaScript parser will be used"); - } - this.options = utils_1.resolveTLSProfile(this.options); -}; -/** - * Change instance's status - * @private - */ -Redis.prototype.setStatus = function (status, arg) { - // @ts-ignore - if (debug.enabled) { - debug("status[%s]: %s -> %s", this._getDescription(), this.status || "[empty]", status); - } - this.status = status; - process.nextTick(this.emit.bind(this, status, arg)); -}; -/** - * Create a connection to Redis. - * This method will be invoked automatically when creating a new Redis instance - * unless `lazyConnect: true` is passed. - * - * When calling this method manually, a Promise is returned, which will - * be resolved when the connection status is ready. - * @param {function} [callback] - * @return {Promise} - * @public - */ -Redis.prototype.connect = function (callback) { - const _Promise = PromiseContainer.get(); - const promise = new _Promise((resolve, reject) => { - if (this.status === "connecting" || - this.status === "connect" || - this.status === "ready") { - reject(new Error("Redis is already connecting/connected")); - return; + handleSubscriberReply(reply) { + if (!this.redis.condition.subscriber) { + return false; } - // Make sure only one timer is active at a time - clearInterval(this._addedScriptHashesCleanInterval); - // Start the script cache cleaning - this._addedScriptHashesCleanInterval = setInterval(() => { - this._addedScriptHashes = {}; - }, this.options.maxScriptsCachingTime); - this.connectionEpoch += 1; - this.setStatus("connecting"); - const { options } = this; - this.condition = { - select: options.db, - auth: options.username - ? [options.username, options.password] - : options.password, - subscriber: false, - }; - const _this = this; - standard_as_callback_1.default(this.connector.connect(function (type, err) { - _this.silentEmit(type, err); - }), function (err, stream) { - if (err) { - _this.flushQueue(err); - _this.silentEmit("error", err); - reject(err); - _this.setStatus("end"); - return; - } - let CONNECT_EVENT = options.tls ? "secureConnect" : "connect"; - if (options.sentinels && !options.enableTLSForSentinelMode) { - CONNECT_EVENT = "connect"; - } - _this.stream = stream; - if (typeof options.keepAlive === "number") { - stream.setKeepAlive(true, options.keepAlive); - } - if (stream.connecting) { - stream.once(CONNECT_EVENT, eventHandler.connectHandler(_this)); - if (options.connectTimeout) { - /* - * Typically, Socket#setTimeout(0) will clear the timer - * set before. However, in some platforms (Electron 3.x~4.x), - * the timer will not be cleared. So we introduce a variable here. - * - * See https://github.com/electron/electron/issues/14915 - */ - let connectTimeoutCleared = false; - stream.setTimeout(options.connectTimeout, function () { - if (connectTimeoutCleared) { - return; - } - stream.setTimeout(0); - stream.destroy(); - const err = new Error("connect ETIMEDOUT"); - // @ts-ignore - err.errorno = "ETIMEDOUT"; - // @ts-ignore - err.code = "ETIMEDOUT"; - // @ts-ignore - err.syscall = "connect"; - eventHandler.errorHandler(_this)(err); - }); - stream.once(CONNECT_EVENT, function () { - connectTimeoutCleared = true; - stream.setTimeout(0); - }); + const replyType = Array.isArray(reply) ? reply[0].toString() : null; + debug('receive reply "%s" in subscriber mode', replyType); + switch (replyType) { + case "message": + if (this.redis.listeners("message").length > 0) { + // Check if there're listeners to avoid unnecessary `toString()`. + this.redis.emit("message", reply[1].toString(), reply[2] ? reply[2].toString() : ''); } - } - else if (stream.destroyed) { - const firstError = _this.connector.firstError; - if (firstError) { - process.nextTick(() => { - eventHandler.errorHandler(_this)(firstError); - }); + this.redis.emit("messageBuffer", reply[1], reply[2]); + break; + case "pmessage": { + const pattern = reply[1].toString(); + if (this.redis.listeners("pmessage").length > 0) { + this.redis.emit("pmessage", pattern, reply[2].toString(), reply[3].toString()); } - process.nextTick(eventHandler.closeHandler(_this)); + this.redis.emit("pmessageBuffer", pattern, reply[2], reply[3]); + break; } - else { - process.nextTick(eventHandler.connectHandler(_this)); + case "subscribe": + case "psubscribe": { + const channel = reply[1].toString(); + this.redis.condition.subscriber.add(replyType, channel); + const item = this.shiftCommand(reply); + if (!item) { + return; + } + if (!fillSubCommand(item.command, reply[2])) { + this.redis.commandQueue.unshift(item); + } + break; } - if (!stream.destroyed) { - stream.once("error", eventHandler.errorHandler(_this)); - stream.once("close", eventHandler.closeHandler(_this)); + case "unsubscribe": + case "punsubscribe": { + const channel = reply[1] ? reply[1].toString() : null; + if (channel) { + this.redis.condition.subscriber.del(replyType, channel); + } + const count = reply[2]; + if (count === 0) { + this.redis.condition.subscriber = false; + } + const item = this.shiftCommand(reply); + if (!item) { + return; + } + if (!fillUnsubCommand(item.command, count)) { + this.redis.commandQueue.unshift(item); + } + break; } - if (options.noDelay) { - stream.setNoDelay(true); + default: { + const item = this.shiftCommand(reply); + if (!item) { + return; + } + item.command.resolve(reply); } - const connectionReadyHandler = function () { - _this.removeListener("close", connectionCloseHandler); - resolve(); - }; - var connectionCloseHandler = function () { - _this.removeListener("ready", connectionReadyHandler); - reject(new Error(utils_1.CONNECTION_CLOSED_ERROR_MSG)); - }; - _this.once("ready", connectionReadyHandler); - _this.once("close", connectionCloseHandler); - }); - }); - return standard_as_callback_1.default(promise, callback); -}; -/** - * Disconnect from Redis. - * - * This method closes the connection immediately, - * and may lose some pending replies that haven't written to client. - * If you want to wait for the pending replies, use Redis#quit instead. - * @public - */ -Redis.prototype.disconnect = function (reconnect) { - clearInterval(this._addedScriptHashesCleanInterval); - this._addedScriptHashesCleanInterval = null; - if (!reconnect) { - this.manuallyClosing = true; + } + return true; } - if (this.reconnectTimeout && !reconnect) { - clearTimeout(this.reconnectTimeout); - this.reconnectTimeout = null; + handleMonitorReply(reply) { + if (this.redis.status !== "monitoring") { + return false; + } + const replyStr = reply.toString(); + if (replyStr === "OK") { + // Valid commands in the monitoring mode are AUTH and MONITOR, + // both of which always reply with 'OK'. + // So if we got an 'OK', we can make certain that + // the reply is made to AUTH & MONITO. + return false; + } + // Since commands sent in the monitoring mode will trigger an exception, + // any replies we received in the monitoring mode should consider to be + // realtime monitor data instead of result of commands. + const len = replyStr.indexOf(" "); + const timestamp = replyStr.slice(0, len); + const argindex = replyStr.indexOf('"'); + const args = replyStr + .slice(argindex + 1, -1) + .split('" "') + .map((elem) => elem.replace(/\\"/g, '"')); + const dbAndSource = replyStr.slice(len + 2, argindex - 2).split(" "); + this.redis.emit("monitor", timestamp, args, dbAndSource[1], dbAndSource[0]); + return true; } - if (this.status === "wait") { - eventHandler.closeHandler(this)(); + shiftCommand(reply) { + const item = this.redis.commandQueue.shift(); + if (!item) { + const message = "Command queue state error. If you can reproduce this, please report it."; + const error = new Error(message + + (reply instanceof Error + ? ` Last error: ${reply.message}` + : ` Last reply: ${reply.toString()}`)); + this.redis.emit("error", error); + return null; + } + return item; } - else { - this.connector.disconnect(); +} +exports["default"] = DataHandler; +function fillSubCommand(command, count) { + // TODO: use WeakMap here + if (typeof command.remainReplies === "undefined") { + command.remainReplies = command.args.length; } -}; -/** - * Disconnect from Redis. - * - * @deprecated - */ -Redis.prototype.end = function () { - this.disconnect(); -}; -/** - * Create a new instance with the same options as the current one. - * - * @example - * ```js - * var redis = new Redis(6380); - * var anotherRedis = redis.duplicate(); - * ``` - * - * @public - */ -Redis.prototype.duplicate = function (override) { - return new Redis(Object.assign({}, this.options, override || {})); -}; -Redis.prototype.recoverFromFatalError = function (commandError, err, options) { - this.flushQueue(err, options); - this.silentEmit("error", err); - this.disconnect(true); -}; -Redis.prototype.handleReconnection = function handleReconnection(err, item) { - let needReconnect = false; - if (this.options.reconnectOnError) { - needReconnect = this.options.reconnectOnError(err); + if (--command.remainReplies === 0) { + command.resolve(count); + return true; } - switch (needReconnect) { - case 1: - case true: - if (this.status !== "reconnecting") { - this.disconnect(true); - } - item.command.reject(err); - break; - case 2: - if (this.status !== "reconnecting") { - this.disconnect(true); - } - if (this.condition.select !== item.select && - item.command.name !== "select") { - this.select(item.select); - } - this.sendCommand(item.command); - break; - default: - item.command.reject(err); + return false; +} +function fillUnsubCommand(command, count) { + if (typeof command.remainReplies === "undefined") { + command.remainReplies = command.args.length; } -}; -/** - * Flush offline queue and command queue with error. - * - * @param {Error} error - The error object to send to the commands - * @param {object} options - * @private - */ -Redis.prototype.flushQueue = function (error, options) { - options = lodash_1.defaults({}, options, { - offlineQueue: true, - commandQueue: true, - }); - let item; - if (options.offlineQueue) { - while (this.offlineQueue.length > 0) { - item = this.offlineQueue.shift(); - item.command.reject(error); + if (command.remainReplies === 0) { + if (count === 0) { + command.resolve(count); + return true; } + return false; } - if (options.commandQueue) { - if (this.commandQueue.length > 0) { - if (this.stream) { - this.stream.removeAllListeners("data"); - } - while (this.commandQueue.length > 0) { - item = this.commandQueue.shift(); - item.command.reject(error); - } - } + if (--command.remainReplies === 0) { + command.resolve(count); + return true; } -}; + return false; +} + + +/***/ }), + +/***/ 6134: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const stream_1 = __nccwpck_require__(12781); /** - * Check whether Redis has finished loading the persistent data and is able to - * process commands. + * Convenient class to convert the process of scaning keys to a readable stream. * - * @param {Function} callback - * @private + * @export + * @class ScanStream + * @extends {Readable} */ -Redis.prototype._readyCheck = function (callback) { - const _this = this; - this.info(function (err, res) { - if (err) { - return callback(err); - } - if (typeof res !== "string") { - return callback(null, res); +class ScanStream extends stream_1.Readable { + constructor(opt) { + super(opt); + this.opt = opt; + this._redisCursor = "0"; + this._redisDrained = false; + } + _read() { + if (this._redisDrained) { + this.push(null); + return; } - const info = {}; - const lines = res.split("\r\n"); - for (let i = 0; i < lines.length; ++i) { - const [fieldName, ...fieldValueParts] = lines[i].split(":"); - const fieldValue = fieldValueParts.join(":"); - if (fieldValue) { - info[fieldName] = fieldValue; - } + const args = [this._redisCursor]; + if (this.opt.key) { + args.unshift(this.opt.key); } - if (!info.loading || info.loading === "0") { - callback(null, info); + if (this.opt.match) { + args.push("MATCH", this.opt.match); } - else { - const loadingEtaMs = (info.loading_eta_seconds || 1) * 1000; - const retryTime = _this.options.maxLoadingRetryTime && - _this.options.maxLoadingRetryTime < loadingEtaMs - ? _this.options.maxLoadingRetryTime - : loadingEtaMs; - debug("Redis server still loading, trying again in " + retryTime + "ms"); - setTimeout(function () { - _this._readyCheck(callback); - }, retryTime); + if (this.opt.type) { + args.push("TYPE", this.opt.type); } - }); -}; -/** - * Emit only when there's at least one listener. - * - * @param {string} eventName - Event to emit - * @param {...*} arguments - Arguments - * @return {boolean} Returns true if event had listeners, false otherwise. - * @private - */ -Redis.prototype.silentEmit = function (eventName) { - let error; - if (eventName === "error") { - error = arguments[1]; - if (this.status === "end") { - return; + if (this.opt.count) { + args.push("COUNT", String(this.opt.count)); } - if (this.manuallyClosing) { - // ignore connection related errors when manually disconnecting - if (error instanceof Error && - (error.message === utils_1.CONNECTION_CLOSED_ERROR_MSG || - // @ts-ignore - error.syscall === "connect" || - // @ts-ignore - error.syscall === "read")) { + this.opt.redis[this.opt.command](args, (err, res) => { + if (err) { + this.emit("error", err); return; } - } - } - if (this.listeners(eventName).length > 0) { - return this.emit.apply(this, arguments); + this._redisCursor = res[0] instanceof Buffer ? res[0].toString() : res[0]; + if (this._redisCursor === "0") { + this._redisDrained = true; + } + this.push(res[1]); + }); } - if (error && error instanceof Error) { - console.error("[ioredis] Unhandled error event:", error.stack); + close() { + this._redisDrained = true; } - return false; -}; -/** - * Listen for all requests received by the server in real time. - * - * This command will create a new connection to Redis and send a - * MONITOR command via the new connection in order to avoid disturbing - * the current connection. - * - * @param {function} [callback] The callback function. If omit, a promise will be returned. - * @example - * ```js - * var redis = new Redis(); - * redis.monitor(function (err, monitor) { - * // Entering monitoring mode. - * monitor.on('monitor', function (time, args, source, database) { - * console.log(time + ": " + util.inspect(args)); - * }); - * }); - * - * // supports promise as well as other commands - * redis.monitor().then(function (monitor) { - * monitor.on('monitor', function (time, args, source, database) { - * console.log(time + ": " + util.inspect(args)); - * }); - * }); - * ``` - * @public - */ -Redis.prototype.monitor = function (callback) { - const monitorInstance = this.duplicate({ - monitor: true, - lazyConnect: false, - }); - const Promise = PromiseContainer.get(); - return standard_as_callback_1.default(new Promise(function (resolve) { - monitorInstance.once("monitoring", function () { - resolve(monitorInstance); - }); - }), callback); -}; -transaction_1.addTransactionSupport(Redis.prototype); +} +exports["default"] = ScanStream; + + +/***/ }), + +/***/ 73527: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); /** - * Send a command to Redis - * - * This method is used internally by the `Redis#set`, `Redis#lpush` etc. - * Most of the time you won't invoke this method directly. - * However when you want to send a command that is not supported by ioredis yet, - * this command will be useful. - * - * @method sendCommand - * @memberOf Redis# - * @param {Command} command - The Command instance to send. - * @see {@link Command} - * @example - * ```js - * var redis = new Redis(); - * - * // Use callback - * var get = new Command('get', ['foo'], 'utf8', function (err, result) { - * console.log(result); - * }); - * redis.sendCommand(get); + * Tiny class to simplify dealing with subscription set * - * // Use promise - * var set = new Command('set', ['foo', 'bar'], 'utf8'); - * set.promise.then(function (result) { - * console.log(result); - * }); - * redis.sendCommand(set); - * ``` - * @private + * @export + * @class SubscriptionSet */ -Redis.prototype.sendCommand = function (command, stream) { - if (this.status === "wait") { - this.connect().catch(lodash_1.noop); - } - if (this.status === "end") { - command.reject(new Error(utils_1.CONNECTION_CLOSED_ERROR_MSG)); - return command.promise; +class SubscriptionSet { + constructor() { + this.set = { + subscribe: {}, + psubscribe: {}, + }; } - if (this.condition.subscriber && - !command_1.default.checkFlag("VALID_IN_SUBSCRIBER_MODE", command.name)) { - command.reject(new Error("Connection in subscriber mode, only subscriber commands may be used")); - return command.promise; + add(set, channel) { + this.set[mapSet(set)][channel] = true; } - if (typeof this.options.commandTimeout === "number") { - command.setTimeout(this.options.commandTimeout); + del(set, channel) { + delete this.set[mapSet(set)][channel]; } - if (command.name === "quit") { - clearInterval(this._addedScriptHashesCleanInterval); - this._addedScriptHashesCleanInterval = null; + channels(set) { + return Object.keys(this.set[mapSet(set)]); } - let writable = this.status === "ready" || - (!stream && - this.status === "connect" && - commands.exists(command.name) && - commands.hasFlag(command.name, "loading")); - if (!this.stream) { - writable = false; + isEmpty() { + return (this.channels("subscribe").length === 0 && + this.channels("psubscribe").length === 0); } - else if (!this.stream.writable) { - writable = false; +} +exports["default"] = SubscriptionSet; +function mapSet(set) { + if (set === "unsubscribe") { + return "subscribe"; } - else if (this.stream._writableState && this.stream._writableState.ended) { - // https://github.com/iojs/io.js/pull/1217 - writable = false; + if (set === "punsubscribe") { + return "psubscribe"; } - if (!writable && !this.options.enableOfflineQueue) { - command.reject(new Error("Stream isn't writeable and enableOfflineQueue options is false")); - return command.promise; + return set; +} + + +/***/ }), + +/***/ 97873: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const PromiseContainer = __nccwpck_require__(71475); +const lodash_1 = __nccwpck_require__(20961); +const calculateSlot = __nccwpck_require__(48481); +const standard_as_callback_1 = __nccwpck_require__(91543); +exports.kExec = Symbol("exec"); +exports.kCallbacks = Symbol("callbacks"); +exports.notAllowedAutoPipelineCommands = [ + "auth", + "info", + "script", + "quit", + "cluster", + "pipeline", + "multi", + "subscribe", + "psubscribe", + "unsubscribe", + "unpsubscribe", +]; +function executeAutoPipeline(client, slotKey) { + /* + If a pipeline is already executing, keep queueing up commands + since ioredis won't serve two pipelines at the same time + */ + if (client._runningAutoPipelines.has(slotKey)) { + return; } - if (!writable && command.name === "quit" && this.offlineQueue.length === 0) { - this.disconnect(); - command.resolve(Buffer.from("OK")); - return command.promise; + if (!client._autoPipelines.has(slotKey)) { + /* + Rare edge case. Somehow, something has deleted this running autopipeline in an immediate + call to executeAutoPipeline. + + Maybe the callback in the pipeline.exec is sometimes called in the same tick, + e.g. if redis is disconnected? + */ + return; } - if (writable) { - // @ts-ignore - if (debug.enabled) { - debug("write command[%s]: %d -> %s(%o)", this._getDescription(), this.condition.select, command.name, command.args); - } - (stream || this.stream).write(command.toWritable()); - this.commandQueue.push({ - command: command, - stream: stream, - select: this.condition.select, - }); - if (command_1.default.checkFlag("WILL_DISCONNECT", command.name)) { - this.manuallyClosing = true; + client._runningAutoPipelines.add(slotKey); + // Get the pipeline and immediately delete it so that new commands are queued on a new pipeline + const pipeline = client._autoPipelines.get(slotKey); + client._autoPipelines.delete(slotKey); + const callbacks = pipeline[exports.kCallbacks]; + // Stop keeping a reference to callbacks immediately after the callbacks stop being used. + // This allows the GC to reclaim objects referenced by callbacks, especially with 16384 slots + // in Redis.Cluster + pipeline[exports.kCallbacks] = null; + // Perform the call + pipeline.exec(function (err, results) { + client._runningAutoPipelines.delete(slotKey); + /* + Invoke all callback in nextTick so the stack is cleared + and callbacks can throw errors without affecting other callbacks. + */ + if (err) { + for (let i = 0; i < callbacks.length; i++) { + process.nextTick(callbacks[i], err); + } } - } - else if (this.options.enableOfflineQueue) { - // @ts-ignore - if (debug.enabled) { - debug("queue command[%s]: %d -> %s(%o)", this._getDescription(), this.condition.select, command.name, command.args); + else { + for (let i = 0; i < callbacks.length; i++) { + process.nextTick(callbacks[i], ...results[i]); + } } - this.offlineQueue.push({ - command: command, - stream: stream, - select: this.condition.select, - }); - } - if (command.name === "select" && utils_1.isInt(command.args[0])) { - const db = parseInt(command.args[0], 10); - if (this.condition.select !== db) { - this.condition.select = db; - this.emit("select", db); - debug("switch to db [%d]", this.condition.select); + // If there is another pipeline on the same node, immediately execute it without waiting for nextTick + if (client._autoPipelines.has(slotKey)) { + executeAutoPipeline(client, slotKey); } - } - return command.promise; -}; + }); +} +function shouldUseAutoPipelining(client, functionName, commandName) { + return (functionName && + client.options.enableAutoPipelining && + !client.isPipeline && + !exports.notAllowedAutoPipelineCommands.includes(commandName) && + !client.options.autoPipeliningIgnoredCommands.includes(commandName)); +} +exports.shouldUseAutoPipelining = shouldUseAutoPipelining; /** - * Get description of the connection. Used for debugging. * @private */ -Redis.prototype._getDescription = function () { - let description; - if (this.options.path) { - description = this.options.path; +function getFirstValueInFlattenedArray(args) { + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + if (typeof arg === "string") { + return arg; + } + else if (Array.isArray(arg) || lodash_1.isArguments(arg)) { + if (arg.length === 0) { + continue; + } + return arg[0]; + } + const flattened = lodash_1.flatten([arg]); + if (flattened.length > 0) { + return flattened[0]; + } } - else if (this.stream && - this.stream.remoteAddress && - this.stream.remotePort) { - description = this.stream.remoteAddress + ":" + this.stream.remotePort; + return undefined; +} +exports.getFirstValueInFlattenedArray = getFirstValueInFlattenedArray; +function executeWithAutoPipelining(client, functionName, commandName, args, callback) { + const CustomPromise = PromiseContainer.get(); + // On cluster mode let's wait for slots to be available + if (client.isCluster && !client.slots.length) { + if (client.status === "wait") + client.connect().catch(lodash_1.noop); + return standard_as_callback_1.default(new CustomPromise(function (resolve, reject) { + client.delayUntilReady((err) => { + if (err) { + reject(err); + return; + } + executeWithAutoPipelining(client, functionName, commandName, args, null).then(resolve, reject); + }); + }), callback); } - else { - description = this.options.host + ":" + this.options.port; + // If we have slot information, we can improve routing by grouping slots served by the same subset of nodes + // Note that the first value in args may be a (possibly empty) array. + // ioredis will only flatten one level of the array, in the Command constructor. + const prefix = client.options.keyPrefix || ""; + const slotKey = client.isCluster + ? client.slots[calculateSlot(`${prefix}${getFirstValueInFlattenedArray(args)}`)].join(",") + : "main"; + if (!client._autoPipelines.has(slotKey)) { + const pipeline = client.pipeline(); + pipeline[exports.kExec] = false; + pipeline[exports.kCallbacks] = []; + client._autoPipelines.set(slotKey, pipeline); } - if (this.options.connectionName) { - description += ` (${this.options.connectionName})`; + const pipeline = client._autoPipelines.get(slotKey); + /* + Mark the pipeline as scheduled. + The symbol will make sure that the pipeline is only scheduled once per tick. + New commands are appended to an already scheduled pipeline. + */ + if (!pipeline[exports.kExec]) { + pipeline[exports.kExec] = true; + /* + Deferring with setImmediate so we have a chance to capture multiple + commands that can be scheduled by I/O events already in the event loop queue. + */ + setImmediate(executeAutoPipeline, client, slotKey); } - return description; -}; -[ - "scan", - "sscan", - "hscan", - "zscan", - "scanBuffer", - "sscanBuffer", - "hscanBuffer", - "zscanBuffer", -].forEach(function (command) { - Redis.prototype[command + "Stream"] = function (key, options) { - if (command === "scan" || command === "scanBuffer") { - options = key; - key = null; - } - return new ScanStream_1.default(lodash_1.defaults({ - objectMode: true, - key: key, - redis: this, - command: command, - }, options)); - }; -}); + // Create the promise which will execute the command in the pipeline. + const autoPipelinePromise = new CustomPromise(function (resolve, reject) { + pipeline[exports.kCallbacks].push(function (err, value) { + if (err) { + reject(err); + return; + } + resolve(value); + }); + pipeline[functionName](...args); + }); + return standard_as_callback_1.default(autoPipelinePromise, callback); +} +exports.executeWithAutoPipelining = executeWithAutoPipelining; /***/ }), -/***/ 88540: +/***/ 35835: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -const crypto_1 = __nccwpck_require__(6113); -const promiseContainer_1 = __nccwpck_require__(71475); -const command_1 = __nccwpck_require__(90803); -const standard_as_callback_1 = __nccwpck_require__(91543); -class Script { - constructor(lua, numberOfKeys = null, keyPrefix = "", readOnly = false) { - this.lua = lua; - this.numberOfKeys = numberOfKeys; - this.keyPrefix = keyPrefix; - this.readOnly = readOnly; - this.sha = crypto_1.createHash("sha1").update(lua).digest("hex"); - } - execute(container, args, options, callback) { - if (typeof this.numberOfKeys === "number") { - args.unshift(this.numberOfKeys); - } - if (this.keyPrefix) { - options.keyPrefix = this.keyPrefix; - } - if (this.readOnly) { - options.readOnly = true; - } - const evalsha = new command_1.default("evalsha", [this.sha].concat(args), options); - evalsha.isCustomCommand = true; - const result = container.sendCommand(evalsha); - if (promiseContainer_1.isPromise(result)) { - return standard_as_callback_1.default(result.catch((err) => { - if (err.toString().indexOf("NOSCRIPT") === -1) { - throw err; - } - return container.sendCommand(new command_1.default("eval", [this.lua].concat(args), options)); - }), callback); - } - // result is not a Promise--probably returned from a pipeline chain; however, - // we still need the callback to fire when the script is evaluated - standard_as_callback_1.default(evalsha.promise, callback); - return result; - } -} -exports["default"] = Script; +const dns_1 = __nccwpck_require__(9523); +exports.DEFAULT_CLUSTER_OPTIONS = { + clusterRetryStrategy: (times) => Math.min(100 + times * 2, 2000), + enableOfflineQueue: true, + enableReadyCheck: true, + scaleReads: "master", + maxRedirections: 16, + retryDelayOnMoved: 0, + retryDelayOnFailover: 100, + retryDelayOnClusterDown: 100, + retryDelayOnTryAgain: 100, + slotsRefreshTimeout: 1000, + slotsRefreshInterval: 5000, + useSRVRecords: false, + resolveSrv: dns_1.resolveSrv, + dnsLookup: dns_1.lookup, + enableAutoPipelining: false, + autoPipeliningIgnoredCommands: [], + maxScriptsCachingTime: 60000, +}; /***/ }), -/***/ 14645: +/***/ 18394: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); +const util_1 = __nccwpck_require__(94582); const utils_1 = __nccwpck_require__(94832); -const standard_as_callback_1 = __nccwpck_require__(91543); -const pipeline_1 = __nccwpck_require__(42803); -function addTransactionSupport(redis) { - redis.pipeline = function (commands) { - const pipeline = new pipeline_1.default(this); - if (Array.isArray(commands)) { - pipeline.addBatch(commands); +const redis_1 = __nccwpck_require__(83609); +const debug = utils_1.Debug("cluster:subscriber"); +class ClusterSubscriber { + constructor(connectionPool, emitter) { + this.connectionPool = connectionPool; + this.emitter = emitter; + this.started = false; + this.subscriber = null; + this.connectionPool.on("-node", (_, key) => { + if (!this.started || !this.subscriber) { + return; + } + if (util_1.getNodeKey(this.subscriber.options) === key) { + debug("subscriber has left, selecting a new one..."); + this.selectSubscriber(); + } + }); + this.connectionPool.on("+node", () => { + if (!this.started || this.subscriber) { + return; + } + debug("a new node is discovered and there is no subscriber, selecting a new one..."); + this.selectSubscriber(); + }); + } + getInstance() { + return this.subscriber; + } + selectSubscriber() { + const lastActiveSubscriber = this.lastActiveSubscriber; + // Disconnect the previous subscriber even if there + // will not be a new one. + if (lastActiveSubscriber) { + lastActiveSubscriber.disconnect(); } - return pipeline; - }; - const { multi } = redis; - redis.multi = function (commands, options) { - if (typeof options === "undefined" && !Array.isArray(commands)) { - options = commands; - commands = null; + if (this.subscriber) { + this.subscriber.disconnect(); } - if (options && options.pipeline === false) { - return multi.call(this); + const sampleNode = utils_1.sample(this.connectionPool.getNodes()); + if (!sampleNode) { + debug("selecting subscriber failed since there is no node discovered in the cluster yet"); + this.subscriber = null; + return; } - const pipeline = new pipeline_1.default(this); - pipeline.multi(); - if (Array.isArray(commands)) { - pipeline.addBatch(commands); + const { options } = sampleNode; + debug("selected a subscriber %s:%s", options.host, options.port); + /* + * Create a specialized Redis connection for the subscription. + * Note that auto reconnection is enabled here. + * + * `enableReadyCheck` is also enabled because although subscription is allowed + * while redis is loading data from the disk, we can check if the password + * provided for the subscriber is correct, and if not, the current subscriber + * will be disconnected and a new subscriber will be selected. + */ + this.subscriber = new redis_1.default({ + port: options.port, + host: options.host, + username: options.username, + password: options.password, + enableReadyCheck: true, + connectionName: util_1.getConnectionName("subscriber", options.connectionName), + lazyConnect: true, + tls: options.tls, + }); + // Ignore the errors since they're handled in the connection pool. + this.subscriber.on("error", utils_1.noop); + // Re-subscribe previous channels + const previousChannels = { subscribe: [], psubscribe: [] }; + if (lastActiveSubscriber) { + const condition = lastActiveSubscriber.condition || lastActiveSubscriber.prevCondition; + if (condition && condition.subscriber) { + previousChannels.subscribe = condition.subscriber.channels("subscribe"); + previousChannels.psubscribe = condition.subscriber.channels("psubscribe"); + } } - const exec = pipeline.exec; - pipeline.exec = function (callback) { - // Wait for the cluster to be connected, since we need nodes information before continuing - if (this.isCluster && !this.redis.slots.length) { - if (this.redis.status === "wait") - this.redis.connect().catch(utils_1.noop); - return standard_as_callback_1.default(new Promise((resolve, reject) => { - this.redis.delayUntilReady((err) => { - if (err) { - reject(err); - return; + if (previousChannels.subscribe.length || + previousChannels.psubscribe.length) { + let pending = 0; + for (const type of ["subscribe", "psubscribe"]) { + const channels = previousChannels[type]; + if (channels.length) { + pending += 1; + debug("%s %d channels", type, channels.length); + this.subscriber[type](channels) + .then(() => { + if (!--pending) { + this.lastActiveSubscriber = this.subscriber; } - this.exec(pipeline).then(resolve, reject); + }) + .catch(() => { + // TODO: should probably disconnect the subscriber and try again. + debug("failed to %s %d channels", type, channels.length); }); - }), callback); - } - if (this._transactions > 0) { - exec.call(pipeline); - } - // Returns directly when the pipeline - // has been called multiple times (retries). - if (this.nodeifiedPromise) { - return exec.call(pipeline); - } - const promise = exec.call(pipeline); - return standard_as_callback_1.default(promise.then(function (result) { - const execResult = result[result.length - 1]; - if (typeof execResult === "undefined") { - throw new Error("Pipeline cannot be used to send any commands when the `exec()` has been called on it."); - } - if (execResult[0]) { - execResult[0].previousErrors = []; - for (let i = 0; i < result.length - 1; ++i) { - if (result[i][0]) { - execResult[0].previousErrors.push(result[i][0]); - } - } - throw execResult[0]; } - return utils_1.wrapMultiResult(execResult[1]); - }), callback); - }; - const { execBuffer } = pipeline; - pipeline.execBuffer = function (callback) { - if (this._transactions > 0) { - execBuffer.call(pipeline); - } - return pipeline.exec(callback); - }; - return pipeline; - }; - const { exec } = redis; - redis.exec = function (callback) { - return standard_as_callback_1.default(exec.call(this).then(function (results) { - if (Array.isArray(results)) { - results = utils_1.wrapMultiResult(results); } - return results; - }), callback); - }; + } + else { + this.lastActiveSubscriber = this.subscriber; + } + for (const event of ["message", "messageBuffer"]) { + this.subscriber.on(event, (arg1, arg2) => { + this.emitter.emit(event, arg1, arg2); + }); + } + for (const event of ["pmessage", "pmessageBuffer"]) { + this.subscriber.on(event, (arg1, arg2, arg3) => { + this.emitter.emit(event, arg1, arg2, arg3); + }); + } + } + start() { + this.started = true; + this.selectSubscriber(); + debug("started"); + } + stop() { + this.started = false; + if (this.subscriber) { + this.subscriber.disconnect(); + this.subscriber = null; + } + debug("stopped"); + } } -exports.addTransactionSupport = addTransactionSupport; +exports["default"] = ClusterSubscriber; /***/ }), -/***/ 85356: +/***/ 34589: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -const debug_1 = __nccwpck_require__(38237); -const MAX_ARGUMENT_LENGTH = 200; -exports.MAX_ARGUMENT_LENGTH = MAX_ARGUMENT_LENGTH; -const NAMESPACE_PREFIX = "ioredis"; -/** - * helper function that tried to get a string value for - * arbitrary "debug" arg - */ -function getStringValue(v) { - if (v === null) { - return; +const events_1 = __nccwpck_require__(82361); +const utils_1 = __nccwpck_require__(94832); +const util_1 = __nccwpck_require__(94582); +const redis_1 = __nccwpck_require__(83609); +const debug = utils_1.Debug("cluster:connectionPool"); +class ConnectionPool extends events_1.EventEmitter { + constructor(redisOptions) { + super(); + this.redisOptions = redisOptions; + // master + slave = all + this.nodes = { + all: {}, + master: {}, + slave: {}, + }; + this.specifiedOptions = {}; } - switch (typeof v) { - case "boolean": - return; - case "number": - return; - case "object": - if (Buffer.isBuffer(v)) { - return v.toString("hex"); - } - if (Array.isArray(v)) { - return v.join(","); - } - try { - return JSON.stringify(v); - } - catch (e) { - return; + getNodes(role = "all") { + const nodes = this.nodes[role]; + return Object.keys(nodes).map((key) => nodes[key]); + } + getInstanceByKey(key) { + return this.nodes.all[key]; + } + getSampleInstance(role) { + const keys = Object.keys(this.nodes[role]); + const sampleKey = utils_1.sample(keys); + return this.nodes[role][sampleKey]; + } + /** + * Find or create a connection to the node + * + * @param {IRedisOptions} node + * @param {boolean} [readOnly=false] + * @returns {*} + * @memberof ConnectionPool + */ + findOrCreate(node, readOnly = false) { + const key = util_1.getNodeKey(node); + readOnly = Boolean(readOnly); + if (this.specifiedOptions[key]) { + Object.assign(node, this.specifiedOptions[key]); + } + else { + this.specifiedOptions[key] = node; + } + let redis; + if (this.nodes.all[key]) { + redis = this.nodes.all[key]; + if (redis.options.readOnly !== readOnly) { + redis.options.readOnly = readOnly; + debug("Change role of %s to %s", key, readOnly ? "slave" : "master"); + redis[readOnly ? "readonly" : "readwrite"]().catch(utils_1.noop); + if (readOnly) { + delete this.nodes.master[key]; + this.nodes.slave[key] = redis; + } + else { + delete this.nodes.slave[key]; + this.nodes.master[key] = redis; + } } - case "string": - return v; + } + else { + debug("Connecting to %s as %s", key, readOnly ? "slave" : "master"); + redis = new redis_1.default(utils_1.defaults({ + // Never try to reconnect when a node is lose, + // instead, waiting for a `MOVED` error and + // fetch the slots again. + retryStrategy: null, + // Offline queue should be enabled so that + // we don't need to wait for the `ready` event + // before sending commands to the node. + enableOfflineQueue: true, + readOnly: readOnly, + }, node, this.redisOptions, { lazyConnect: true })); + this.nodes.all[key] = redis; + this.nodes[readOnly ? "slave" : "master"][key] = redis; + redis.once("end", () => { + this.removeNode(key); + this.emit("-node", redis, key); + if (!Object.keys(this.nodes.all).length) { + this.emit("drain"); + } + }); + this.emit("+node", redis, key); + redis.on("error", function (error) { + this.emit("nodeError", error, key); + }); + } + return redis; } -} -exports.getStringValue = getStringValue; -/** - * helper function that redacts a string representation of a "debug" arg - */ -function genRedactedString(str, maxLen) { - const { length } = str; - return length <= maxLen - ? str - : str.slice(0, maxLen) + ' ... '; -} -exports.genRedactedString = genRedactedString; -/** - * a wrapper for the `debug` module, used to generate - * "debug functions" that trim the values in their output - */ -function genDebugFunction(namespace) { - const fn = debug_1.default(`${NAMESPACE_PREFIX}:${namespace}`); - function wrappedDebug(...args) { - if (!fn.enabled) { - return; // no-op + /** + * Remove a node from the pool. + */ + removeNode(key) { + const { nodes } = this; + if (nodes.all[key]) { + debug("Remove %s from the pool", key); + delete nodes.all[key]; } - // we skip the first arg because that is the message - for (let i = 1; i < args.length; i++) { - const str = getStringValue(args[i]); - if (typeof str === "string" && str.length > MAX_ARGUMENT_LENGTH) { - args[i] = genRedactedString(str, MAX_ARGUMENT_LENGTH); + delete nodes.master[key]; + delete nodes.slave[key]; + } + /** + * Reset the pool with a set of nodes. + * The old node will be removed. + * + * @param {(Array)} nodes + * @memberof ConnectionPool + */ + reset(nodes) { + debug("Reset with %O", nodes); + const newNodes = {}; + nodes.forEach((node) => { + const key = util_1.getNodeKey(node); + // Don't override the existing (master) node + // when the current one is slave. + if (!(node.readOnly && newNodes[key])) { + newNodes[key] = node; } - } - return fn.apply(null, args); + }); + Object.keys(this.nodes.all).forEach((key) => { + if (!newNodes[key]) { + debug("Disconnect %s because the node does not hold any slot", key); + this.nodes.all[key].disconnect(); + this.removeNode(key); + } + }); + Object.keys(newNodes).forEach((key) => { + const node = newNodes[key]; + this.findOrCreate(node, node.readOnly); + }); } - Object.defineProperties(wrappedDebug, { - namespace: { - get() { - return fn.namespace; - }, - }, - enabled: { - get() { - return fn.enabled; - }, - }, - destroy: { - get() { - return fn.destroy; - }, - }, - log: { - get() { - return fn.log; - }, - set(l) { - fn.log = l; - }, - }, - }); - return wrappedDebug; } -exports["default"] = genDebugFunction; +exports["default"] = ConnectionPool; /***/ }), -/***/ 94832: +/***/ 12770: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -const url_1 = __nccwpck_require__(57310); -const lodash_1 = __nccwpck_require__(20961); -exports.defaults = lodash_1.defaults; -exports.noop = lodash_1.noop; -exports.flatten = lodash_1.flatten; -const debug_1 = __nccwpck_require__(85356); -exports.Debug = debug_1.default; -const TLSProfiles_1 = __nccwpck_require__(61823); +const utils_1 = __nccwpck_require__(94832); +const Deque = __nccwpck_require__(42342); +const debug = utils_1.Debug("delayqueue"); /** - * Test if two buffers are equal + * Queue that runs items after specified duration * * @export - * @param {Buffer} a - * @param {Buffer} b - * @returns {boolean} Whether the two buffers are equal + * @class DelayQueue */ -function bufferEqual(a, b) { - if (typeof a.equals === "function") { - return a.equals(b); - } - if (a.length !== b.length) { - return false; +class DelayQueue { + constructor() { + this.queues = {}; + this.timeouts = {}; } - for (let i = 0; i < a.length; ++i) { - if (a[i] !== b[i]) { - return false; + /** + * Add a new item to the queue + * + * @param {string} bucket bucket name + * @param {Function} item function that will run later + * @param {IDelayQueueOptions} options + * @memberof DelayQueue + */ + push(bucket, item, options) { + const callback = options.callback || process.nextTick; + if (!this.queues[bucket]) { + this.queues[bucket] = new Deque(); + } + const queue = this.queues[bucket]; + queue.push(item); + if (!this.timeouts[bucket]) { + this.timeouts[bucket] = setTimeout(() => { + callback(() => { + this.timeouts[bucket] = null; + this.execute(bucket); + }); + }, options.timeout); } } - return true; -} -exports.bufferEqual = bufferEqual; -/** - * Convert a buffer to string, supports buffer array - * - * @param {*} value - The input value - * @param {string} encoding - string encoding - * @return {*} The result - * @example - * ```js - * var input = [Buffer.from('foo'), [Buffer.from('bar')]] - * var res = convertBufferToString(input, 'utf8') - * expect(res).to.eql(['foo', ['bar']]) - * ``` - * @private - */ -function convertBufferToString(value, encoding) { - if (value instanceof Buffer) { - return value.toString(encoding); - } - if (Array.isArray(value)) { - const length = value.length; - const res = Array(length); - for (let i = 0; i < length; ++i) { - res[i] = - value[i] instanceof Buffer && encoding === "utf8" - ? value[i].toString() - : convertBufferToString(value[i], encoding); + execute(bucket) { + const queue = this.queues[bucket]; + if (!queue) { + return; + } + const { length } = queue; + if (!length) { + return; + } + debug("send %d commands in %s queue", length, bucket); + this.queues[bucket] = null; + while (queue.length > 0) { + queue.shift()(); } - return res; } - return value; } -exports.convertBufferToString = convertBufferToString; +exports["default"] = DelayQueue; + + +/***/ }), + +/***/ 17208: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const events_1 = __nccwpck_require__(82361); +const ClusterAllFailedError_1 = __nccwpck_require__(97282); +const utils_1 = __nccwpck_require__(94832); +const ConnectionPool_1 = __nccwpck_require__(34589); +const util_1 = __nccwpck_require__(94582); +const ClusterSubscriber_1 = __nccwpck_require__(18394); +const DelayQueue_1 = __nccwpck_require__(12770); +const ScanStream_1 = __nccwpck_require__(6134); +const redis_errors_1 = __nccwpck_require__(81879); +const standard_as_callback_1 = __nccwpck_require__(91543); +const PromiseContainer = __nccwpck_require__(71475); +const ClusterOptions_1 = __nccwpck_require__(35835); +const utils_2 = __nccwpck_require__(94832); +const commands = __nccwpck_require__(98020); +const command_1 = __nccwpck_require__(90803); +const redis_1 = __nccwpck_require__(83609); +const commander_1 = __nccwpck_require__(33642); +const Deque = __nccwpck_require__(42342); +const debug = utils_1.Debug("cluster"); /** - * Convert a list of results to node-style + * Client for the official Redis Cluster * - * @param {Array} arr - The input value - * @return {Array} The output value - * @example - * ```js - * var input = ['a', 'b', new Error('c'), 'd'] - * var output = exports.wrapMultiResult(input) - * expect(output).to.eql([[null, 'a'], [null, 'b'], [new Error('c')], [null, 'd']) - * ``` - * @private + * @class Cluster + * @extends {EventEmitter} */ -function wrapMultiResult(arr) { - // When using WATCH/EXEC transactions, the EXEC will return - // a null instead of an array - if (!arr) { - return null; - } - const result = []; - const length = arr.length; - for (let i = 0; i < length; ++i) { - const item = arr[i]; - if (item instanceof Error) { - result.push([item]); +class Cluster extends events_1.EventEmitter { + /** + * Creates an instance of Cluster. + * + * @param {((string | number | object)[])} startupNodes + * @param {IClusterOptions} [options={}] + * @memberof Cluster + */ + constructor(startupNodes, options = {}) { + super(); + this.slots = []; + this.retryAttempts = 0; + this.delayQueue = new DelayQueue_1.default(); + this.offlineQueue = new Deque(); + this.isRefreshing = false; + this.isCluster = true; + this._autoPipelines = new Map(); + this._groupsIds = {}; + this._groupsBySlot = Array(16384); + this._runningAutoPipelines = new Set(); + this._readyDelayedCallbacks = []; + this._addedScriptHashes = {}; + /** + * Every time Cluster#connect() is called, this value will be + * auto-incrementing. The purpose of this value is used for + * discarding previous connect attampts when creating a new + * connection. + * + * @private + * @type {number} + * @memberof Cluster + */ + this.connectionEpoch = 0; + commander_1.default.call(this); + this.startupNodes = startupNodes; + this.options = utils_1.defaults({}, options, ClusterOptions_1.DEFAULT_CLUSTER_OPTIONS, this.options); + // validate options + if (typeof this.options.scaleReads !== "function" && + ["all", "master", "slave"].indexOf(this.options.scaleReads) === -1) { + throw new Error('Invalid option scaleReads "' + + this.options.scaleReads + + '". Expected "all", "master", "slave" or a custom function'); + } + this.connectionPool = new ConnectionPool_1.default(this.options.redisOptions); + this.connectionPool.on("-node", (redis, key) => { + this.emit("-node", redis); + }); + this.connectionPool.on("+node", (redis) => { + this.emit("+node", redis); + }); + this.connectionPool.on("drain", () => { + this.setStatus("close"); + }); + this.connectionPool.on("nodeError", (error, key) => { + this.emit("node error", error, key); + }); + this.subscriber = new ClusterSubscriber_1.default(this.connectionPool, this); + if (this.options.lazyConnect) { + this.setStatus("wait"); } else { - result.push([null, item]); + this.connect().catch((err) => { + debug("connecting failed: %s", err); + }); } } - return result; -} -exports.wrapMultiResult = wrapMultiResult; -/** - * Detect if the argument is a int - * - * @param {string} value - * @return {boolean} Whether the value is a int - * @example - * ```js - * > isInt('123') - * true - * > isInt('123.3') - * false - * > isInt('1x') - * false - * > isInt(123) - * true - * > isInt(true) - * false - * ``` - * @private - */ -function isInt(value) { - const x = parseFloat(value); - return !isNaN(value) && (x | 0) === x; -} -exports.isInt = isInt; -/** - * Pack an array to an Object - * - * @param {array} array - * @return {object} - * @example - * ```js - * > packObject(['a', 'b', 'c', 'd']) - * { a: 'b', c: 'd' } - * ``` - */ -function packObject(array) { - const result = {}; - const length = array.length; - for (let i = 1; i < length; i += 2) { - result[array[i - 1]] = array[i]; + resetOfflineQueue() { + this.offlineQueue = new Deque(); } - return result; -} -exports.packObject = packObject; -/** - * Return a callback with timeout - * - * @param {function} callback - * @param {number} timeout - * @return {function} - */ -function timeout(callback, timeout) { - let timer; - const run = function () { - if (timer) { - clearTimeout(timer); - timer = null; - callback.apply(this, arguments); + clearNodesRefreshInterval() { + if (this.slotsTimer) { + clearTimeout(this.slotsTimer); + this.slotsTimer = null; } - }; - timer = setTimeout(run, timeout, new Error("timeout")); - return run; -} -exports.timeout = timeout; -/** - * Convert an object to an array - * - * @param {object} obj - * @return {array} - * @example - * ```js - * > convertObjectToArray({ a: '1' }) - * ['a', '1'] - * ``` - */ -function convertObjectToArray(obj) { - const result = []; - const keys = Object.keys(obj); // Object.entries requires node 7+ - for (let i = 0, l = keys.length; i < l; i++) { - result.push(keys[i], obj[keys[i]]); - } - return result; -} -exports.convertObjectToArray = convertObjectToArray; -/** - * Convert a map to an array - * - * @param {Map} map - * @return {array} - * @example - * ```js - * > convertMapToArray(new Map([[1, '2']])) - * [1, '2'] - * ``` - */ -function convertMapToArray(map) { - const result = []; - let pos = 0; - map.forEach(function (value, key) { - result[pos] = key; - result[pos + 1] = value; - pos += 2; - }); - return result; -} -exports.convertMapToArray = convertMapToArray; -/** - * Convert a non-string arg to a string - * - * @param {*} arg - * @return {string} - */ -function toArg(arg) { - if (arg === null || typeof arg === "undefined") { - return ""; } - return String(arg); -} -exports.toArg = toArg; -/** - * Optimize error stack - * - * @param {Error} error - actually error - * @param {string} friendlyStack - the stack that more meaningful - * @param {string} filterPath - only show stacks with the specified path - */ -function optimizeErrorStack(error, friendlyStack, filterPath) { - const stacks = friendlyStack.split("\n"); - let lines = ""; - let i; - for (i = 1; i < stacks.length; ++i) { - if (stacks[i].indexOf(filterPath) === -1) { - break; + resetNodesRefreshInterval() { + if (this.slotsTimer) { + return; } + const nextRound = () => { + this.slotsTimer = setTimeout(() => { + debug('refreshing slot caches... (triggered by "slotsRefreshInterval" option)'); + this.refreshSlotsCache(() => { + nextRound(); + }); + }, this.options.slotsRefreshInterval); + }; + nextRound(); } - for (let j = i; j < stacks.length; ++j) { - lines += "\n" + stacks[j]; - } - const pos = error.stack.indexOf("\n"); - error.stack = error.stack.slice(0, pos) + lines; - return error; -} -exports.optimizeErrorStack = optimizeErrorStack; -/** - * Parse the redis protocol url - * - * @param {string} url - the redis protocol url - * @return {Object} - */ -function parseURL(url) { - if (isInt(url)) { - return { port: url }; - } - let parsed = url_1.parse(url, true, true); - if (!parsed.slashes && url[0] !== "/") { - url = "//" + url; - parsed = url_1.parse(url, true, true); + /** + * Connect to a cluster + * + * @returns {Promise} + * @memberof Cluster + */ + connect() { + const Promise = PromiseContainer.get(); + return new Promise((resolve, reject) => { + if (this.status === "connecting" || + this.status === "connect" || + this.status === "ready") { + reject(new Error("Redis is already connecting/connected")); + return; + } + // Make sure only one timer is active at a time + clearInterval(this._addedScriptHashesCleanInterval); + // Start the script cache cleaning + this._addedScriptHashesCleanInterval = setInterval(() => { + this._addedScriptHashes = {}; + }, this.options.maxScriptsCachingTime); + const epoch = ++this.connectionEpoch; + this.setStatus("connecting"); + this.resolveStartupNodeHostnames() + .then((nodes) => { + if (this.connectionEpoch !== epoch) { + debug("discard connecting after resolving startup nodes because epoch not match: %d != %d", epoch, this.connectionEpoch); + reject(new redis_errors_1.RedisError("Connection is discarded because a new connection is made")); + return; + } + if (this.status !== "connecting") { + debug("discard connecting after resolving startup nodes because the status changed to %s", this.status); + reject(new redis_errors_1.RedisError("Connection is aborted")); + return; + } + this.connectionPool.reset(nodes); + function readyHandler() { + this.setStatus("ready"); + this.retryAttempts = 0; + this.executeOfflineCommands(); + this.resetNodesRefreshInterval(); + resolve(); + } + let closeListener = undefined; + const refreshListener = () => { + this.invokeReadyDelayedCallbacks(undefined); + this.removeListener("close", closeListener); + this.manuallyClosing = false; + this.setStatus("connect"); + if (this.options.enableReadyCheck) { + this.readyCheck((err, fail) => { + if (err || fail) { + debug("Ready check failed (%s). Reconnecting...", err || fail); + if (this.status === "connect") { + this.disconnect(true); + } + } + else { + readyHandler.call(this); + } + }); + } + else { + readyHandler.call(this); + } + }; + closeListener = function () { + const error = new Error("None of startup nodes is available"); + this.removeListener("refresh", refreshListener); + this.invokeReadyDelayedCallbacks(error); + reject(error); + }; + this.once("refresh", refreshListener); + this.once("close", closeListener); + this.once("close", this.handleCloseEvent.bind(this)); + this.refreshSlotsCache(function (err) { + if (err && err.message === "Failed to refresh slots cache.") { + redis_1.default.prototype.silentEmit.call(this, "error", err); + this.connectionPool.reset([]); + } + }.bind(this)); + this.subscriber.start(); + }) + .catch((err) => { + this.setStatus("close"); + this.handleCloseEvent(err); + this.invokeReadyDelayedCallbacks(err); + reject(err); + }); + }); } - const options = parsed.query || {}; - const allowUsernameInURI = options.allowUsernameInURI && options.allowUsernameInURI !== "false"; - delete options.allowUsernameInURI; - const result = {}; - if (parsed.auth) { - const index = parsed.auth.indexOf(":"); - if (allowUsernameInURI) { - result.username = - index === -1 ? parsed.auth : parsed.auth.slice(0, index); + /** + * Called when closed to check whether a reconnection should be made + * + * @private + * @memberof Cluster + */ + handleCloseEvent(reason) { + if (reason) { + debug("closed because %s", reason); + } + let retryDelay; + if (!this.manuallyClosing && + typeof this.options.clusterRetryStrategy === "function") { + retryDelay = this.options.clusterRetryStrategy.call(this, ++this.retryAttempts, reason); + } + if (typeof retryDelay === "number") { + this.setStatus("reconnecting"); + this.reconnectTimeout = setTimeout(function () { + this.reconnectTimeout = null; + debug("Cluster is disconnected. Retrying after %dms", retryDelay); + this.connect().catch(function (err) { + debug("Got error %s when reconnecting. Ignoring...", err); + }); + }.bind(this), retryDelay); + } + else { + this.setStatus("end"); + this.flushQueue(new Error("None of startup nodes is available")); } - result.password = index === -1 ? "" : parsed.auth.slice(index + 1); } - if (parsed.pathname) { - if (parsed.protocol === "redis:" || parsed.protocol === "rediss:") { - if (parsed.pathname.length > 1) { - result.db = parsed.pathname.slice(1); - } + /** + * Disconnect from every node in the cluster. + * + * @param {boolean} [reconnect=false] + * @memberof Cluster + */ + disconnect(reconnect = false) { + const status = this.status; + this.setStatus("disconnecting"); + clearInterval(this._addedScriptHashesCleanInterval); + this._addedScriptHashesCleanInterval = null; + if (!reconnect) { + this.manuallyClosing = true; + } + if (this.reconnectTimeout && !reconnect) { + clearTimeout(this.reconnectTimeout); + this.reconnectTimeout = null; + debug("Canceled reconnecting attempts"); + } + this.clearNodesRefreshInterval(); + this.subscriber.stop(); + if (status === "wait") { + this.setStatus("close"); + this.handleCloseEvent(); } else { - result.path = parsed.pathname; + this.connectionPool.reset([]); } } - if (parsed.host) { - result.host = parsed.hostname; + /** + * Quit the cluster gracefully. + * + * @param {CallbackFunction<'OK'>} [callback] + * @returns {Promise<'OK'>} + * @memberof Cluster + */ + quit(callback) { + const status = this.status; + this.setStatus("disconnecting"); + clearInterval(this._addedScriptHashesCleanInterval); + this._addedScriptHashesCleanInterval = null; + this.manuallyClosing = true; + if (this.reconnectTimeout) { + clearTimeout(this.reconnectTimeout); + this.reconnectTimeout = null; + } + this.clearNodesRefreshInterval(); + this.subscriber.stop(); + const Promise = PromiseContainer.get(); + if (status === "wait") { + const ret = standard_as_callback_1.default(Promise.resolve("OK"), callback); + // use setImmediate to make sure "close" event + // being emitted after quit() is returned + setImmediate(function () { + this.setStatus("close"); + this.handleCloseEvent(); + }.bind(this)); + return ret; + } + return standard_as_callback_1.default(Promise.all(this.nodes().map((node) => node.quit().catch((err) => { + // Ignore the error caused by disconnecting since + // we're disconnecting... + if (err.message === utils_2.CONNECTION_CLOSED_ERROR_MSG) { + return "OK"; + } + throw err; + }))).then(() => "OK"), callback); } - if (parsed.port) { - result.port = parsed.port; + /** + * Create a new instance with the same startup nodes and options as the current one. + * + * @example + * ```js + * var cluster = new Redis.Cluster([{ host: "127.0.0.1", port: "30001" }]); + * var anotherCluster = cluster.duplicate(); + * ``` + * + * @public + * @param {((string | number | object)[])} [overrideStartupNodes=[]] + * @param {IClusterOptions} [overrideOptions={}] + * @memberof Cluster + */ + duplicate(overrideStartupNodes = [], overrideOptions = {}) { + const startupNodes = overrideStartupNodes.length > 0 + ? overrideStartupNodes + : this.startupNodes.slice(0); + const options = Object.assign({}, this.options, overrideOptions); + return new Cluster(startupNodes, options); } - lodash_1.defaults(result, options); - return result; -} -exports.parseURL = parseURL; -/** - * Resolve TLS profile shortcut in connection options - * - * @param {Object} options - the redis connection options - * @return {Object} - */ -function resolveTLSProfile(options) { - let tls = options === null || options === void 0 ? void 0 : options.tls; - if (typeof tls === "string") - tls = { profile: tls }; - const profile = TLSProfiles_1.default[tls === null || tls === void 0 ? void 0 : tls.profile]; - if (profile) { - tls = Object.assign({}, profile, tls); - delete tls.profile; - options = Object.assign({}, options, { tls }); + /** + * Get nodes with the specified role + * + * @param {NodeRole} [role='all'] + * @returns {any[]} + * @memberof Cluster + */ + nodes(role = "all") { + if (role !== "all" && role !== "master" && role !== "slave") { + throw new Error('Invalid role "' + role + '". Expected "all", "master" or "slave"'); + } + return this.connectionPool.getNodes(role); } - return options; -} -exports.resolveTLSProfile = resolveTLSProfile; -/** - * Get a random element from `array` - * - * @export - * @template T - * @param {T[]} array the array - * @param {number} [from=0] start index - * @returns {T} - */ -function sample(array, from = 0) { - const length = array.length; - if (from >= length) { - return; + // This is needed in order not to install a listener for each auto pipeline + delayUntilReady(callback) { + this._readyDelayedCallbacks.push(callback); } - return array[from + Math.floor(Math.random() * (length - from))]; -} -exports.sample = sample; -/** - * Shuffle the array using the Fisher-Yates Shuffle. - * This method will mutate the original array. - * - * @export - * @template T - * @param {T[]} array - * @returns {T[]} - */ -function shuffle(array) { - let counter = array.length; - // While there are elements in the array - while (counter > 0) { - // Pick a random index - const index = Math.floor(Math.random() * counter); - // Decrease counter by 1 - counter--; - // And swap the last element with it - [array[counter], array[index]] = [array[index], array[counter]]; + /** + * Get the number of commands queued in automatic pipelines. + * + * This is not available (and returns 0) until the cluster is connected and slots information have been received. + */ + get autoPipelineQueueSize() { + let queued = 0; + for (const pipeline of this._autoPipelines.values()) { + queued += pipeline.length; + } + return queued; } - return array; -} -exports.shuffle = shuffle; -/** - * Error message for connection being disconnected - */ -exports.CONNECTION_CLOSED_ERROR_MSG = "Connection is closed."; -function zipMap(keys, values) { - const map = new Map(); - keys.forEach((key, index) => { - map.set(key, values[index]); - }); - return map; -} -exports.zipMap = zipMap; - - -/***/ }), - -/***/ 20961: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const defaults = __nccwpck_require__(11289); -exports.defaults = defaults; -const flatten = __nccwpck_require__(48919); -exports.flatten = flatten; -const isArguments = __nccwpck_require__(44130); -exports.isArguments = isArguments; -function noop() { } -exports.noop = noop; - - -/***/ }), - -/***/ 12071: -/***/ ((module) => { - -"use strict"; - - -const pMap = (iterable, mapper, options) => new Promise((resolve, reject) => { - options = Object.assign({ - concurrency: Infinity - }, options); - - if (typeof mapper !== 'function') { - throw new TypeError('Mapper function is required'); - } - - const {concurrency} = options; - - if (!(typeof concurrency === 'number' && concurrency >= 1)) { - throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${concurrency}\` (${typeof concurrency})`); - } - - const ret = []; - const iterator = iterable[Symbol.iterator](); - let isRejected = false; - let isIterableDone = false; - let resolvingCount = 0; - let currentIndex = 0; - - const next = () => { - if (isRejected) { - return; - } - - const nextItem = iterator.next(); - const i = currentIndex; - currentIndex++; - - if (nextItem.done) { - isIterableDone = true; - - if (resolvingCount === 0) { - resolve(ret); - } - - return; - } - - resolvingCount++; - - Promise.resolve(nextItem.value) - .then(element => mapper(element, i)) - .then( - value => { - ret[i] = value; - resolvingCount--; - next(); - }, - error => { - isRejected = true; - reject(error); - } - ); - }; - - for (let i = 0; i < concurrency; i++) { - next(); - - if (isIterableDone) { - break; - } - } -}); - -module.exports = pMap; -// TODO: Remove this for the next major release -module.exports["default"] = pMap; - - -/***/ }), - -/***/ 37263: -/***/ (function(module, __unused_webpack_exports, __nccwpck_require__) { - -/* module decorator */ module = __nccwpck_require__.nmd(module); -(function() { - var expandIPv6, ipaddr, ipv4Part, ipv4Regexes, ipv6Part, ipv6Regexes, matchCIDR, root, zoneIndex; - - ipaddr = {}; - - root = this; - - if (( true && module !== null) && module.exports) { - module.exports = ipaddr; - } else { - root['ipaddr'] = ipaddr; - } - - matchCIDR = function(first, second, partSize, cidrBits) { - var part, shift; - if (first.length !== second.length) { - throw new Error("ipaddr: cannot match CIDR for objects with different lengths"); + /** + * Change cluster instance's status + * + * @private + * @param {ClusterStatus} status + * @memberof Cluster + */ + setStatus(status) { + debug("status: %s -> %s", this.status || "[empty]", status); + this.status = status; + process.nextTick(() => { + this.emit(status); + }); } - part = 0; - while (cidrBits > 0) { - shift = partSize - cidrBits; - if (shift < 0) { - shift = 0; - } - if (first[part] >> shift !== second[part] >> shift) { - return false; - } - cidrBits -= partSize; - part += 1; + /** + * Refresh the slot cache + * + * @private + * @param {CallbackFunction} [callback] + * @memberof Cluster + */ + refreshSlotsCache(callback) { + if (this.isRefreshing) { + if (typeof callback === "function") { + process.nextTick(callback); + } + return; + } + this.isRefreshing = true; + const _this = this; + const wrapper = function (error) { + _this.isRefreshing = false; + if (typeof callback === "function") { + callback(error); + } + }; + const nodes = utils_2.shuffle(this.connectionPool.getNodes()); + let lastNodeError = null; + function tryNode(index) { + if (index === nodes.length) { + const error = new ClusterAllFailedError_1.default("Failed to refresh slots cache.", lastNodeError); + return wrapper(error); + } + const node = nodes[index]; + const key = `${node.options.host}:${node.options.port}`; + debug("getting slot cache from %s", key); + _this.getInfoFromNode(node, function (err) { + switch (_this.status) { + case "close": + case "end": + return wrapper(new Error("Cluster is disconnected.")); + case "disconnecting": + return wrapper(new Error("Cluster is disconnecting.")); + } + if (err) { + _this.emit("node error", err, key); + lastNodeError = err; + tryNode(index + 1); + } + else { + _this.emit("refresh"); + wrapper(); + } + }); + } + tryNode(0); } - return true; - }; - - ipaddr.subnetMatch = function(address, rangeList, defaultName) { - var k, len, rangeName, rangeSubnets, subnet; - if (defaultName == null) { - defaultName = 'unicast'; + /** + * Flush offline queue with error. + * + * @param {Error} error + * @memberof Cluster + */ + flushQueue(error) { + let item; + while (this.offlineQueue.length > 0) { + item = this.offlineQueue.shift(); + item.command.reject(error); + } } - for (rangeName in rangeList) { - rangeSubnets = rangeList[rangeName]; - if (rangeSubnets[0] && !(rangeSubnets[0] instanceof Array)) { - rangeSubnets = [rangeSubnets]; - } - for (k = 0, len = rangeSubnets.length; k < len; k++) { - subnet = rangeSubnets[k]; - if (address.kind() === subnet[0].kind()) { - if (address.match.apply(address, subnet)) { - return rangeName; - } + executeOfflineCommands() { + if (this.offlineQueue.length) { + debug("send %d commands in offline queue", this.offlineQueue.length); + const offlineQueue = this.offlineQueue; + this.resetOfflineQueue(); + while (offlineQueue.length > 0) { + const item = offlineQueue.shift(); + this.sendCommand(item.command, item.stream, item.node); + } } - } } - return defaultName; - }; - - ipaddr.IPv4 = (function() { - function IPv4(octets) { - var k, len, octet; - if (octets.length !== 4) { - throw new Error("ipaddr: ipv4 octet count should be 4"); - } - for (k = 0, len = octets.length; k < len; k++) { - octet = octets[k]; - if (!((0 <= octet && octet <= 255))) { - throw new Error("ipaddr: ipv4 octet should fit in 8 bits"); + natMapper(nodeKey) { + if (this.options.natMap && typeof this.options.natMap === "object") { + const key = typeof nodeKey === "string" + ? nodeKey + : `${nodeKey.host}:${nodeKey.port}`; + const mapped = this.options.natMap[key]; + if (mapped) { + debug("NAT mapping %s -> %O", key, mapped); + return Object.assign({}, mapped); + } } - } - this.octets = octets; + return typeof nodeKey === "string" + ? util_1.nodeKeyToRedisOptions(nodeKey) + : nodeKey; } - - IPv4.prototype.kind = function() { - return 'ipv4'; - }; - - IPv4.prototype.toString = function() { - return this.octets.join("."); - }; - - IPv4.prototype.toNormalizedString = function() { - return this.toString(); - }; - - IPv4.prototype.toByteArray = function() { - return this.octets.slice(0); - }; - - IPv4.prototype.match = function(other, cidrRange) { - var ref; - if (cidrRange === void 0) { - ref = other, other = ref[0], cidrRange = ref[1]; - } - if (other.kind() !== 'ipv4') { - throw new Error("ipaddr: cannot match ipv4 address with non-ipv4 one"); - } - return matchCIDR(this.octets, other.octets, 8, cidrRange); - }; - - IPv4.prototype.SpecialRanges = { - unspecified: [[new IPv4([0, 0, 0, 0]), 8]], - broadcast: [[new IPv4([255, 255, 255, 255]), 32]], - multicast: [[new IPv4([224, 0, 0, 0]), 4]], - linkLocal: [[new IPv4([169, 254, 0, 0]), 16]], - loopback: [[new IPv4([127, 0, 0, 0]), 8]], - carrierGradeNat: [[new IPv4([100, 64, 0, 0]), 10]], - "private": [[new IPv4([10, 0, 0, 0]), 8], [new IPv4([172, 16, 0, 0]), 12], [new IPv4([192, 168, 0, 0]), 16]], - reserved: [[new IPv4([192, 0, 0, 0]), 24], [new IPv4([192, 0, 2, 0]), 24], [new IPv4([192, 88, 99, 0]), 24], [new IPv4([198, 51, 100, 0]), 24], [new IPv4([203, 0, 113, 0]), 24], [new IPv4([240, 0, 0, 0]), 4]] - }; - - IPv4.prototype.range = function() { - return ipaddr.subnetMatch(this, this.SpecialRanges); - }; - - IPv4.prototype.toIPv4MappedAddress = function() { - return ipaddr.IPv6.parse("::ffff:" + (this.toString())); - }; - - IPv4.prototype.prefixLengthFromSubnetMask = function() { - var cidr, i, k, octet, stop, zeros, zerotable; - zerotable = { - 0: 8, - 128: 7, - 192: 6, - 224: 5, - 240: 4, - 248: 3, - 252: 2, - 254: 1, - 255: 0 - }; - cidr = 0; - stop = false; - for (i = k = 3; k >= 0; i = k += -1) { - octet = this.octets[i]; - if (octet in zerotable) { - zeros = zerotable[octet]; - if (stop && zeros !== 0) { - return null; - } - if (zeros !== 8) { - stop = true; - } - cidr += zeros; - } else { - return null; + sendCommand(command, stream, node) { + if (this.status === "wait") { + this.connect().catch(utils_1.noop); } - } - return 32 - cidr; - }; - - return IPv4; - - })(); - - ipv4Part = "(0?\\d+|0x[a-f0-9]+)"; - - ipv4Regexes = { - fourOctet: new RegExp("^" + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "$", 'i'), - longValue: new RegExp("^" + ipv4Part + "$", 'i') - }; - - ipaddr.IPv4.parser = function(string) { - var match, parseIntAuto, part, shift, value; - parseIntAuto = function(string) { - if (string[0] === "0" && string[1] !== "x") { - return parseInt(string, 8); - } else { - return parseInt(string); - } - }; - if (match = string.match(ipv4Regexes.fourOctet)) { - return (function() { - var k, len, ref, results; - ref = match.slice(1, 6); - results = []; - for (k = 0, len = ref.length; k < len; k++) { - part = ref[k]; - results.push(parseIntAuto(part)); + if (this.status === "end") { + command.reject(new Error(utils_2.CONNECTION_CLOSED_ERROR_MSG)); + return command.promise; } - return results; - })(); - } else if (match = string.match(ipv4Regexes.longValue)) { - value = parseIntAuto(match[1]); - if (value > 0xffffffff || value < 0) { - throw new Error("ipaddr: address outside defined range"); - } - return ((function() { - var k, results; - results = []; - for (shift = k = 0; k <= 24; shift = k += 8) { - results.push((value >> shift) & 0xff); + let to = this.options.scaleReads; + if (to !== "master") { + const isCommandReadOnly = command.isReadOnly || + (commands.exists(command.name) && + commands.hasFlag(command.name, "readonly")); + if (!isCommandReadOnly) { + to = "master"; + } } - return results; - })()).reverse(); - } else { - return null; + let targetSlot = node ? node.slot : command.getSlot(); + const ttl = {}; + const _this = this; + if (!node && !command.__is_reject_overwritten) { + // eslint-disable-next-line @typescript-eslint/camelcase + command.__is_reject_overwritten = true; + const reject = command.reject; + command.reject = function (err) { + const partialTry = tryConnection.bind(null, true); + _this.handleError(err, ttl, { + moved: function (slot, key) { + debug("command %s is moved to %s", command.name, key); + targetSlot = Number(slot); + if (_this.slots[slot]) { + _this.slots[slot][0] = key; + } + else { + _this.slots[slot] = [key]; + } + _this._groupsBySlot[slot] = _this._groupsIds[_this.slots[slot].join(';')]; + _this.connectionPool.findOrCreate(_this.natMapper(key)); + tryConnection(); + debug("refreshing slot caches... (triggered by MOVED error)"); + _this.refreshSlotsCache(); + }, + ask: function (slot, key) { + debug("command %s is required to ask %s:%s", command.name, key); + const mapped = _this.natMapper(key); + _this.connectionPool.findOrCreate(mapped); + tryConnection(false, `${mapped.host}:${mapped.port}`); + }, + tryagain: partialTry, + clusterDown: partialTry, + connectionClosed: partialTry, + maxRedirections: function (redirectionError) { + reject.call(command, redirectionError); + }, + defaults: function () { + reject.call(command, err); + }, + }); + }; + } + tryConnection(); + function tryConnection(random, asking) { + if (_this.status === "end") { + command.reject(new redis_errors_1.AbortError("Cluster is ended.")); + return; + } + let redis; + if (_this.status === "ready" || command.name === "cluster") { + if (node && node.redis) { + redis = node.redis; + } + else if (command_1.default.checkFlag("ENTER_SUBSCRIBER_MODE", command.name) || + command_1.default.checkFlag("EXIT_SUBSCRIBER_MODE", command.name)) { + redis = _this.subscriber.getInstance(); + if (!redis) { + command.reject(new redis_errors_1.AbortError("No subscriber for the cluster")); + return; + } + } + else { + if (!random) { + if (typeof targetSlot === "number" && _this.slots[targetSlot]) { + const nodeKeys = _this.slots[targetSlot]; + if (typeof to === "function") { + const nodes = nodeKeys.map(function (key) { + return _this.connectionPool.getInstanceByKey(key); + }); + redis = to(nodes, command); + if (Array.isArray(redis)) { + redis = utils_2.sample(redis); + } + if (!redis) { + redis = nodes[0]; + } + } + else { + let key; + if (to === "all") { + key = utils_2.sample(nodeKeys); + } + else if (to === "slave" && nodeKeys.length > 1) { + key = utils_2.sample(nodeKeys, 1); + } + else { + key = nodeKeys[0]; + } + redis = _this.connectionPool.getInstanceByKey(key); + } + } + if (asking) { + redis = _this.connectionPool.getInstanceByKey(asking); + redis.asking(); + } + } + if (!redis) { + redis = + (typeof to === "function" + ? null + : _this.connectionPool.getSampleInstance(to)) || + _this.connectionPool.getSampleInstance("all"); + } + } + if (node && !node.redis) { + node.redis = redis; + } + } + if (redis) { + redis.sendCommand(command, stream); + } + else if (_this.options.enableOfflineQueue) { + _this.offlineQueue.push({ + command: command, + stream: stream, + node: node, + }); + } + else { + command.reject(new Error("Cluster isn't ready and enableOfflineQueue options is false")); + } + } + return command.promise; } - }; - - ipaddr.IPv6 = (function() { - function IPv6(parts, zoneId) { - var i, k, l, len, part, ref; - if (parts.length === 16) { - this.parts = []; - for (i = k = 0; k <= 14; i = k += 2) { - this.parts.push((parts[i] << 8) | parts[i + 1]); + handleError(error, ttl, handlers) { + if (typeof ttl.value === "undefined") { + ttl.value = this.options.maxRedirections; } - } else if (parts.length === 8) { - this.parts = parts; - } else { - throw new Error("ipaddr: ipv6 part count should be 8 or 16"); - } - ref = this.parts; - for (l = 0, len = ref.length; l < len; l++) { - part = ref[l]; - if (!((0 <= part && part <= 0xffff))) { - throw new Error("ipaddr: ipv6 part should fit in 16 bits"); + else { + ttl.value -= 1; + } + if (ttl.value <= 0) { + handlers.maxRedirections(new Error("Too many Cluster redirections. Last error: " + error)); + return; + } + const errv = error.message.split(" "); + if (errv[0] === "MOVED") { + const timeout = this.options.retryDelayOnMoved; + if (timeout && typeof timeout === "number") { + this.delayQueue.push("moved", handlers.moved.bind(null, errv[1], errv[2]), { timeout }); + } + else { + handlers.moved(errv[1], errv[2]); + } + } + else if (errv[0] === "ASK") { + handlers.ask(errv[1], errv[2]); + } + else if (errv[0] === "TRYAGAIN") { + this.delayQueue.push("tryagain", handlers.tryagain, { + timeout: this.options.retryDelayOnTryAgain, + }); + } + else if (errv[0] === "CLUSTERDOWN" && + this.options.retryDelayOnClusterDown > 0) { + this.delayQueue.push("clusterdown", handlers.connectionClosed, { + timeout: this.options.retryDelayOnClusterDown, + callback: this.refreshSlotsCache.bind(this), + }); + } + else if (error.message === utils_2.CONNECTION_CLOSED_ERROR_MSG && + this.options.retryDelayOnFailover > 0 && + this.status === "ready") { + this.delayQueue.push("failover", handlers.connectionClosed, { + timeout: this.options.retryDelayOnFailover, + callback: this.refreshSlotsCache.bind(this), + }); + } + else { + handlers.defaults(); } - } - if (zoneId) { - this.zoneId = zoneId; - } } - - IPv6.prototype.kind = function() { - return 'ipv6'; - }; - - IPv6.prototype.toString = function() { - return this.toNormalizedString().replace(/((^|:)(0(:|$))+)/, '::'); - }; - - IPv6.prototype.toRFC5952String = function() { - var bestMatchIndex, bestMatchLength, match, regex, string; - regex = /((^|:)(0(:|$)){2,})/g; - string = this.toNormalizedString(); - bestMatchIndex = 0; - bestMatchLength = -1; - while ((match = regex.exec(string))) { - if (match[0].length > bestMatchLength) { - bestMatchIndex = match.index; - bestMatchLength = match[0].length; + getInfoFromNode(redis, callback) { + if (!redis) { + return callback(new Error("Node is disconnected")); } - } - if (bestMatchLength < 0) { - return string; - } - return string.substring(0, bestMatchIndex) + '::' + string.substring(bestMatchIndex + bestMatchLength); - }; - - IPv6.prototype.toByteArray = function() { - var bytes, k, len, part, ref; - bytes = []; - ref = this.parts; - for (k = 0, len = ref.length; k < len; k++) { - part = ref[k]; - bytes.push(part >> 8); - bytes.push(part & 0xff); - } - return bytes; - }; - - IPv6.prototype.toNormalizedString = function() { - var addr, part, suffix; - addr = ((function() { - var k, len, ref, results; - ref = this.parts; - results = []; - for (k = 0, len = ref.length; k < len; k++) { - part = ref[k]; - results.push(part.toString(16)); + // Use a duplication of the connection to avoid + // timeouts when the connection is in the blocking + // mode (e.g. waiting for BLPOP). + const duplicatedConnection = redis.duplicate({ + enableOfflineQueue: true, + enableReadyCheck: false, + retryStrategy: null, + connectionName: util_1.getConnectionName("refresher", this.options.redisOptions && this.options.redisOptions.connectionName), + }); + // Ignore error events since we will handle + // exceptions for the CLUSTER SLOTS command. + duplicatedConnection.on("error", utils_1.noop); + duplicatedConnection.cluster("slots", utils_2.timeout((err, result) => { + duplicatedConnection.disconnect(); + if (err) { + return callback(err); + } + if (this.status === "disconnecting" || + this.status === "close" || + this.status === "end") { + debug("ignore CLUSTER.SLOTS results (count: %d) since cluster status is %s", result.length, this.status); + callback(); + return; + } + const nodes = []; + debug("cluster slots result count: %d", result.length); + for (let i = 0; i < result.length; ++i) { + const items = result[i]; + const slotRangeStart = items[0]; + const slotRangeEnd = items[1]; + const keys = []; + for (let j = 2; j < items.length; j++) { + if (!items[j][0]) { + continue; + } + items[j] = this.natMapper({ host: items[j][0], port: items[j][1] }); + items[j].readOnly = j !== 2; + nodes.push(items[j]); + keys.push(items[j].host + ":" + items[j].port); + } + debug("cluster slots result [%d]: slots %d~%d served by %s", i, slotRangeStart, slotRangeEnd, keys); + for (let slot = slotRangeStart; slot <= slotRangeEnd; slot++) { + this.slots[slot] = keys; + } + } + // Assign to each node keys a numeric value to make autopipeline comparison faster. + this._groupsIds = Object.create(null); + let j = 0; + for (let i = 0; i < 16384; i++) { + const target = (this.slots[i] || []).join(';'); + if (!target.length) { + this._groupsBySlot[i] = undefined; + continue; + } + if (!this._groupsIds[target]) { + this._groupsIds[target] = ++j; + } + this._groupsBySlot[i] = this._groupsIds[target]; + } + this.connectionPool.reset(nodes); + callback(); + }, this.options.slotsRefreshTimeout)); + } + invokeReadyDelayedCallbacks(err) { + for (const c of this._readyDelayedCallbacks) { + process.nextTick(c, err); + } + this._readyDelayedCallbacks = []; + } + /** + * Check whether Cluster is able to process commands + * + * @param {Function} callback + * @private + */ + readyCheck(callback) { + this.cluster("info", function (err, res) { + if (err) { + return callback(err); + } + if (typeof res !== "string") { + return callback(); + } + let state; + const lines = res.split("\r\n"); + for (let i = 0; i < lines.length; ++i) { + const parts = lines[i].split(":"); + if (parts[0] === "cluster_state") { + state = parts[1]; + break; + } + } + if (state === "fail") { + debug("cluster state not ok (%s)", state); + callback(null, state); + } + else { + callback(); + } + }); + } + resolveSrv(hostname) { + return new Promise((resolve, reject) => { + this.options.resolveSrv(hostname, (err, records) => { + if (err) { + return reject(err); + } + const self = this, groupedRecords = util_1.groupSrvRecords(records), sortedKeys = Object.keys(groupedRecords).sort((a, b) => parseInt(a) - parseInt(b)); + function tryFirstOne(err) { + if (!sortedKeys.length) { + return reject(err); + } + const key = sortedKeys[0], group = groupedRecords[key], record = util_1.weightSrvRecords(group); + if (!group.records.length) { + sortedKeys.shift(); + } + self.dnsLookup(record.name).then((host) => resolve({ + host, + port: record.port, + }), tryFirstOne); + } + tryFirstOne(); + }); + }); + } + dnsLookup(hostname) { + return new Promise((resolve, reject) => { + this.options.dnsLookup(hostname, (err, address) => { + if (err) { + debug("failed to resolve hostname %s to IP: %s", hostname, err.message); + reject(err); + } + else { + debug("resolved hostname %s to IP %s", hostname, address); + resolve(address); + } + }); + }); + } + /** + * Normalize startup nodes, and resolving hostnames to IPs. + * + * This process happens every time when #connect() is called since + * #startupNodes and DNS records may chanage. + * + * @private + * @returns {Promise} + */ + resolveStartupNodeHostnames() { + if (!Array.isArray(this.startupNodes) || this.startupNodes.length === 0) { + return Promise.reject(new Error("`startupNodes` should contain at least one node.")); } - return results; - }).call(this)).join(":"); - suffix = ''; - if (this.zoneId) { - suffix = '%' + this.zoneId; - } - return addr + suffix; - }; - - IPv6.prototype.toFixedLengthString = function() { - var addr, part, suffix; - addr = ((function() { - var k, len, ref, results; - ref = this.parts; - results = []; - for (k = 0, len = ref.length; k < len; k++) { - part = ref[k]; - results.push(part.toString(16).padStart(4, '0')); + const startupNodes = util_1.normalizeNodeOptions(this.startupNodes); + const hostnames = util_1.getUniqueHostnamesFromOptions(startupNodes); + if (hostnames.length === 0) { + return Promise.resolve(startupNodes); } - return results; - }).call(this)).join(":"); - suffix = ''; - if (this.zoneId) { - suffix = '%' + this.zoneId; - } - return addr + suffix; + return Promise.all(hostnames.map((this.options.useSRVRecords ? this.resolveSrv : this.dnsLookup).bind(this))).then((configs) => { + const hostnameToConfig = utils_2.zipMap(hostnames, configs); + return startupNodes.map((node) => { + const config = hostnameToConfig.get(node.host); + if (!config) { + return node; + } + else if (this.options.useSRVRecords) { + return Object.assign({}, node, config); + } + else { + return Object.assign({}, node, { host: config }); + } + }); + }); + } +} +Object.getOwnPropertyNames(commander_1.default.prototype).forEach((name) => { + if (!Cluster.prototype.hasOwnProperty(name)) { + Cluster.prototype[name] = commander_1.default.prototype[name]; + } +}); +const scanCommands = [ + "sscan", + "hscan", + "zscan", + "sscanBuffer", + "hscanBuffer", + "zscanBuffer", +]; +scanCommands.forEach((command) => { + Cluster.prototype[command + "Stream"] = function (key, options) { + return new ScanStream_1.default(utils_1.defaults({ + objectMode: true, + key: key, + redis: this, + command: command, + }, options)); }; +}); +(__nccwpck_require__(14645).addTransactionSupport)(Cluster.prototype); +exports["default"] = Cluster; - IPv6.prototype.match = function(other, cidrRange) { - var ref; - if (cidrRange === void 0) { - ref = other, other = ref[0], cidrRange = ref[1]; - } - if (other.kind() !== 'ipv6') { - throw new Error("ipaddr: cannot match ipv6 address with non-ipv6 one"); - } - return matchCIDR(this.parts, other.parts, 16, cidrRange); - }; - IPv6.prototype.SpecialRanges = { - unspecified: [new IPv6([0, 0, 0, 0, 0, 0, 0, 0]), 128], - linkLocal: [new IPv6([0xfe80, 0, 0, 0, 0, 0, 0, 0]), 10], - multicast: [new IPv6([0xff00, 0, 0, 0, 0, 0, 0, 0]), 8], - loopback: [new IPv6([0, 0, 0, 0, 0, 0, 0, 1]), 128], - uniqueLocal: [new IPv6([0xfc00, 0, 0, 0, 0, 0, 0, 0]), 7], - ipv4Mapped: [new IPv6([0, 0, 0, 0, 0, 0xffff, 0, 0]), 96], - rfc6145: [new IPv6([0, 0, 0, 0, 0xffff, 0, 0, 0]), 96], - rfc6052: [new IPv6([0x64, 0xff9b, 0, 0, 0, 0, 0, 0]), 96], - '6to4': [new IPv6([0x2002, 0, 0, 0, 0, 0, 0, 0]), 16], - teredo: [new IPv6([0x2001, 0, 0, 0, 0, 0, 0, 0]), 32], - reserved: [[new IPv6([0x2001, 0xdb8, 0, 0, 0, 0, 0, 0]), 32]] - }; +/***/ }), - IPv6.prototype.range = function() { - return ipaddr.subnetMatch(this, this.SpecialRanges); - }; +/***/ 94582: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - IPv6.prototype.isIPv4MappedAddress = function() { - return this.range() === 'ipv4Mapped'; - }; +"use strict"; - IPv6.prototype.toIPv4Address = function() { - var high, low, ref; - if (!this.isIPv4MappedAddress()) { - throw new Error("ipaddr: trying to convert a generic ipv6 address to ipv4"); - } - ref = this.parts.slice(-2), high = ref[0], low = ref[1]; - return new ipaddr.IPv4([high >> 8, high & 0xff, low >> 8, low & 0xff]); +Object.defineProperty(exports, "__esModule", ({ value: true })); +const utils_1 = __nccwpck_require__(94832); +const net_1 = __nccwpck_require__(41808); +function getNodeKey(node) { + node.port = node.port || 6379; + node.host = node.host || "127.0.0.1"; + return node.host + ":" + node.port; +} +exports.getNodeKey = getNodeKey; +function nodeKeyToRedisOptions(nodeKey) { + const portIndex = nodeKey.lastIndexOf(":"); + if (portIndex === -1) { + throw new Error(`Invalid node key ${nodeKey}`); + } + return { + host: nodeKey.slice(0, portIndex), + port: Number(nodeKey.slice(portIndex + 1)), }; - - IPv6.prototype.prefixLengthFromSubnetMask = function() { - var cidr, i, k, part, stop, zeros, zerotable; - zerotable = { - 0: 16, - 32768: 15, - 49152: 14, - 57344: 13, - 61440: 12, - 63488: 11, - 64512: 10, - 65024: 9, - 65280: 8, - 65408: 7, - 65472: 6, - 65504: 5, - 65520: 4, - 65528: 3, - 65532: 2, - 65534: 1, - 65535: 0 - }; - cidr = 0; - stop = false; - for (i = k = 7; k >= 0; i = k += -1) { - part = this.parts[i]; - if (part in zerotable) { - zeros = zerotable[part]; - if (stop && zeros !== 0) { - return null; - } - if (zeros !== 16) { - stop = true; - } - cidr += zeros; - } else { - return null; +} +exports.nodeKeyToRedisOptions = nodeKeyToRedisOptions; +function normalizeNodeOptions(nodes) { + return nodes.map((node) => { + const options = {}; + if (typeof node === "object") { + Object.assign(options, node); } - } - return 128 - cidr; - }; - - return IPv6; + else if (typeof node === "string") { + Object.assign(options, utils_1.parseURL(node)); + } + else if (typeof node === "number") { + options.port = node; + } + else { + throw new Error("Invalid argument " + node); + } + if (typeof options.port === "string") { + options.port = parseInt(options.port, 10); + } + // Cluster mode only support db 0 + delete options.db; + if (!options.port) { + options.port = 6379; + } + if (!options.host) { + options.host = "127.0.0.1"; + } + return utils_1.resolveTLSProfile(options); + }); +} +exports.normalizeNodeOptions = normalizeNodeOptions; +function getUniqueHostnamesFromOptions(nodes) { + const uniqueHostsMap = {}; + nodes.forEach((node) => { + uniqueHostsMap[node.host] = true; + }); + return Object.keys(uniqueHostsMap).filter((host) => !net_1.isIP(host)); +} +exports.getUniqueHostnamesFromOptions = getUniqueHostnamesFromOptions; +function groupSrvRecords(records) { + const recordsByPriority = {}; + for (const record of records) { + if (!recordsByPriority.hasOwnProperty(record.priority)) { + recordsByPriority[record.priority] = { + totalWeight: record.weight, + records: [record], + }; + } + else { + recordsByPriority[record.priority].totalWeight += record.weight; + recordsByPriority[record.priority].records.push(record); + } + } + return recordsByPriority; +} +exports.groupSrvRecords = groupSrvRecords; +function weightSrvRecords(recordsGroup) { + if (recordsGroup.records.length === 1) { + recordsGroup.totalWeight = 0; + return recordsGroup.records.shift(); + } + // + `recordsGroup.records.length` to support `weight` 0 + const random = Math.floor(Math.random() * (recordsGroup.totalWeight + recordsGroup.records.length)); + let total = 0; + for (const [i, record] of recordsGroup.records.entries()) { + total += 1 + record.weight; + if (total > random) { + recordsGroup.totalWeight -= record.weight; + recordsGroup.records.splice(i, 1); + return record; + } + } +} +exports.weightSrvRecords = weightSrvRecords; +function getConnectionName(component, nodeConnectionName) { + const prefix = `ioredis-cluster(${component})`; + return nodeConnectionName ? `${prefix}:${nodeConnectionName}` : prefix; +} +exports.getConnectionName = getConnectionName; - })(); - ipv6Part = "(?:[0-9a-f]+::?)+"; +/***/ }), - zoneIndex = "%[0-9a-z]{1,}"; +/***/ 90803: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - ipv6Regexes = { - zoneIndex: new RegExp(zoneIndex, 'i'), - "native": new RegExp("^(::)?(" + ipv6Part + ")?([0-9a-f]+)?(::)?(" + zoneIndex + ")?$", 'i'), - transitional: new RegExp(("^((?:" + ipv6Part + ")|(?:::)(?:" + ipv6Part + ")?)") + (ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part) + ("(" + zoneIndex + ")?$"), 'i') - }; +"use strict"; - expandIPv6 = function(string, parts) { - var colonCount, lastColon, part, replacement, replacementCount, zoneId; - if (string.indexOf('::') !== string.lastIndexOf('::')) { - return null; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const commands = __nccwpck_require__(98020); +const calculateSlot = __nccwpck_require__(48481); +const standard_as_callback_1 = __nccwpck_require__(91543); +const utils_1 = __nccwpck_require__(94832); +const lodash_1 = __nccwpck_require__(20961); +const promiseContainer_1 = __nccwpck_require__(71475); +/** + * Command instance + * + * It's rare that you need to create a Command instance yourself. + * + * @export + * @class Command + * + * @example + * ```js + * var infoCommand = new Command('info', null, function (err, result) { + * console.log('result', result); + * }); + * + * redis.sendCommand(infoCommand); + * + * // When no callback provided, Command instance will have a `promise` property, + * // which will resolve/reject with the result of the command. + * var getCommand = new Command('get', ['foo']); + * getCommand.promise.then(function (result) { + * console.log('result', result); + * }); + * ``` + * @see {@link Redis#sendCommand} which can send a Command instance to Redis + */ +class Command { + /** + * Creates an instance of Command. + * @param {string} name Command name + * @param {(Array)} [args=[]] An array of command arguments + * @param {ICommandOptions} [options={}] + * @param {CallbackFunction} [callback] The callback that handles the response. + * If omit, the response will be handled via Promise + * @memberof Command + */ + constructor(name, args = [], options = {}, callback) { + this.name = name; + this.transformed = false; + this.isCustomCommand = false; + this.inTransaction = false; + this.isResolved = false; + this.replyEncoding = options.replyEncoding; + this.errorStack = options.errorStack; + this.args = lodash_1.flatten(args); + this.callback = callback; + this.initPromise(); + if (options.keyPrefix) { + this._iterateKeys((key) => options.keyPrefix + key); + } + if (options.readOnly) { + this.isReadOnly = true; + } } - zoneId = (string.match(ipv6Regexes['zoneIndex']) || [])[0]; - if (zoneId) { - zoneId = zoneId.substring(1); - string = string.replace(/%.+$/, ''); + static getFlagMap() { + if (!this.flagMap) { + this.flagMap = Object.keys(Command.FLAGS).reduce((map, flagName) => { + map[flagName] = {}; + Command.FLAGS[flagName].forEach((commandName) => { + map[flagName][commandName] = true; + }); + return map; + }, {}); + } + return this.flagMap; } - colonCount = 0; - lastColon = -1; - while ((lastColon = string.indexOf(':', lastColon + 1)) >= 0) { - colonCount++; + /** + * Check whether the command has the flag + * + * @param {string} flagName + * @param {string} commandName + * @return {boolean} + */ + static checkFlag(flagName, commandName) { + return !!this.getFlagMap()[flagName][commandName]; } - if (string.substr(0, 2) === '::') { - colonCount--; + static setArgumentTransformer(name, func) { + this._transformer.argument[name] = func; } - if (string.substr(-2, 2) === '::') { - colonCount--; + static setReplyTransformer(name, func) { + this._transformer.reply[name] = func; } - if (colonCount > parts) { - return null; + initPromise() { + const Promise = promiseContainer_1.get(); + const promise = new Promise((resolve, reject) => { + if (!this.transformed) { + this.transformed = true; + const transformer = Command._transformer.argument[this.name]; + if (transformer) { + this.args = transformer(this.args); + } + this.stringifyArguments(); + } + this.resolve = this._convertValue(resolve); + if (this.errorStack) { + this.reject = (err) => { + reject(utils_1.optimizeErrorStack(err, this.errorStack.stack, __dirname)); + }; + } + else { + this.reject = reject; + } + }); + this.promise = standard_as_callback_1.default(promise, this.callback); } - replacementCount = parts - colonCount; - replacement = ':'; - while (replacementCount--) { - replacement += '0:'; + getSlot() { + if (typeof this.slot === "undefined") { + const key = this.getKeys()[0]; + this.slot = key == null ? null : calculateSlot(key); + } + return this.slot; } - string = string.replace('::', replacement); - if (string[0] === ':') { - string = string.slice(1); + getKeys() { + return this._iterateKeys(); } - if (string[string.length - 1] === ':') { - string = string.slice(0, -1); + /** + * Iterate through the command arguments that are considered keys. + * + * @param {Function} [transform=(key) => key] The transformation that should be applied to + * each key. The transformations will persist. + * @returns {string[]} The keys of the command. + * @memberof Command + */ + _iterateKeys(transform = (key) => key) { + if (typeof this.keys === "undefined") { + this.keys = []; + if (commands.exists(this.name)) { + const keyIndexes = commands.getKeyIndexes(this.name, this.args); + for (const index of keyIndexes) { + this.args[index] = transform(this.args[index]); + this.keys.push(this.args[index]); + } + } + } + return this.keys; } - parts = (function() { - var k, len, ref, results; - ref = string.split(":"); - results = []; - for (k = 0, len = ref.length; k < len; k++) { - part = ref[k]; - results.push(parseInt(part, 16)); - } - return results; - })(); - return { - parts: parts, - zoneId: zoneId - }; - }; - - ipaddr.IPv6.parser = function(string) { - var addr, k, len, match, octet, octets, zoneId; - if (ipv6Regexes['native'].test(string)) { - return expandIPv6(string, 8); - } else if (match = string.match(ipv6Regexes['transitional'])) { - zoneId = match[6] || ''; - addr = expandIPv6(match[1].slice(0, -1) + zoneId, 6); - if (addr.parts) { - octets = [parseInt(match[2]), parseInt(match[3]), parseInt(match[4]), parseInt(match[5])]; - for (k = 0, len = octets.length; k < len; k++) { - octet = octets[k]; - if (!((0 <= octet && octet <= 255))) { - return null; - } + /** + * Convert command to writable buffer or string + * + * @return {string|Buffer} + * @see {@link Redis#sendCommand} + * @public + */ + toWritable() { + let bufferMode = false; + for (const arg of this.args) { + if (arg instanceof Buffer) { + bufferMode = true; + break; + } + } + let result; + const commandStr = "*" + + (this.args.length + 1) + + "\r\n$" + + Buffer.byteLength(this.name) + + "\r\n" + + this.name + + "\r\n"; + if (bufferMode) { + const buffers = new MixedBuffers(); + buffers.push(commandStr); + for (const arg of this.args) { + if (arg instanceof Buffer) { + if (arg.length === 0) { + buffers.push("$0\r\n\r\n"); + } + else { + buffers.push("$" + arg.length + "\r\n"); + buffers.push(arg); + buffers.push("\r\n"); + } + } + else { + buffers.push("$" + + Buffer.byteLength(arg) + + "\r\n" + + arg + + "\r\n"); + } + } + result = buffers.toBuffer(); } - addr.parts.push(octets[0] << 8 | octets[1]); - addr.parts.push(octets[2] << 8 | octets[3]); - return { - parts: addr.parts, - zoneId: addr.zoneId - }; - } - } - return null; - }; - - ipaddr.IPv4.isIPv4 = ipaddr.IPv6.isIPv6 = function(string) { - return this.parser(string) !== null; - }; - - ipaddr.IPv4.isValid = function(string) { - var e; - try { - new this(this.parser(string)); - return true; - } catch (error1) { - e = error1; - return false; - } - }; - - ipaddr.IPv4.isValidFourPartDecimal = function(string) { - if (ipaddr.IPv4.isValid(string) && string.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/)) { - return true; - } else { - return false; - } - }; - - ipaddr.IPv6.isValid = function(string) { - var addr, e; - if (typeof string === "string" && string.indexOf(":") === -1) { - return false; + else { + result = commandStr; + for (const arg of this.args) { + result += + "$" + + Buffer.byteLength(arg) + + "\r\n" + + arg + + "\r\n"; + } + } + return result; } - try { - addr = this.parser(string); - new this(addr.parts, addr.zoneId); - return true; - } catch (error1) { - e = error1; - return false; + stringifyArguments() { + for (let i = 0; i < this.args.length; ++i) { + const arg = this.args[i]; + if (!(arg instanceof Buffer) && typeof arg !== "string") { + this.args[i] = utils_1.toArg(arg); + } + } } - }; - - ipaddr.IPv4.parse = function(string) { - var parts; - parts = this.parser(string); - if (parts === null) { - throw new Error("ipaddr: string is not formatted like ip address"); + /** + * Convert the value from buffer to the target encoding. + * + * @private + * @param {Function} resolve The resolve function of the Promise + * @returns {Function} A function to transform and resolve a value + * @memberof Command + */ + _convertValue(resolve) { + return (value) => { + try { + const existingTimer = this._commandTimeoutTimer; + if (existingTimer) { + clearTimeout(existingTimer); + delete this._commandTimeoutTimer; + } + resolve(this.transformReply(value)); + this.isResolved = true; + } + catch (err) { + this.reject(err); + } + return this.promise; + }; } - return new this(parts); - }; - - ipaddr.IPv6.parse = function(string) { - var addr; - addr = this.parser(string); - if (addr.parts === null) { - throw new Error("ipaddr: string is not formatted like ip address"); + /** + * Convert buffer/buffer[] to string/string[], + * and apply reply transformer. + * + * @memberof Command + */ + transformReply(result) { + if (this.replyEncoding) { + result = utils_1.convertBufferToString(result, this.replyEncoding); + } + const transformer = Command._transformer.reply[this.name]; + if (transformer) { + result = transformer(result); + } + return result; } - return new this(addr.parts, addr.zoneId); - }; - - ipaddr.IPv4.parseCIDR = function(string) { - var maskLength, match, parsed; - if (match = string.match(/^(.+)\/(\d+)$/)) { - maskLength = parseInt(match[2]); - if (maskLength >= 0 && maskLength <= 32) { - parsed = [this.parse(match[1]), maskLength]; - Object.defineProperty(parsed, 'toString', { - value: function() { - return this.join('/'); - } - }); - return parsed; - } + /** + * Set the wait time before terminating the attempt to execute a command + * and generating an error. + */ + setTimeout(ms) { + if (!this._commandTimeoutTimer) { + this._commandTimeoutTimer = setTimeout(() => { + if (!this.isResolved) { + this.reject(new Error("Command timed out")); + } + }, ms); + } } - throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range"); - }; - - ipaddr.IPv4.subnetMaskFromPrefixLength = function(prefix) { - var filledOctetCount, j, octets; - prefix = parseInt(prefix); - if (prefix < 0 || prefix > 32) { - throw new Error('ipaddr: invalid IPv4 prefix length'); +} +exports["default"] = Command; +Command.FLAGS = { + VALID_IN_SUBSCRIBER_MODE: [ + "subscribe", + "psubscribe", + "unsubscribe", + "punsubscribe", + "ping", + "quit", + ], + VALID_IN_MONITOR_MODE: ["monitor", "auth"], + ENTER_SUBSCRIBER_MODE: ["subscribe", "psubscribe"], + EXIT_SUBSCRIBER_MODE: ["unsubscribe", "punsubscribe"], + WILL_DISCONNECT: ["quit"], +}; +Command._transformer = { + argument: {}, + reply: {}, +}; +const msetArgumentTransformer = function (args) { + if (args.length === 1) { + if (typeof Map !== "undefined" && args[0] instanceof Map) { + return utils_1.convertMapToArray(args[0]); + } + if (typeof args[0] === "object" && args[0] !== null) { + return utils_1.convertObjectToArray(args[0]); + } } - octets = [0, 0, 0, 0]; - j = 0; - filledOctetCount = Math.floor(prefix / 8); - while (j < filledOctetCount) { - octets[j] = 255; - j++; + return args; +}; +const hsetArgumentTransformer = function (args) { + if (args.length === 2) { + if (typeof Map !== "undefined" && args[1] instanceof Map) { + return [args[0]].concat(utils_1.convertMapToArray(args[1])); + } + if (typeof args[1] === "object" && args[1] !== null) { + return [args[0]].concat(utils_1.convertObjectToArray(args[1])); + } } - if (filledOctetCount < 4) { - octets[filledOctetCount] = Math.pow(2, prefix % 8) - 1 << 8 - (prefix % 8); + return args; +}; +Command.setArgumentTransformer("mset", msetArgumentTransformer); +Command.setArgumentTransformer("msetnx", msetArgumentTransformer); +Command.setArgumentTransformer("hset", hsetArgumentTransformer); +Command.setArgumentTransformer("hmset", hsetArgumentTransformer); +Command.setReplyTransformer("hgetall", function (result) { + if (Array.isArray(result)) { + const obj = {}; + for (let i = 0; i < result.length; i += 2) { + const key = result[i]; + const value = result[i + 1]; + if (key in obj) { + // can only be truthy if the property is special somehow, like '__proto__' or 'constructor' + // https://github.com/luin/ioredis/issues/1267 + Object.defineProperty(obj, key, { + value, + configurable: true, + enumerable: true, + writable: true, + }); + } + else { + obj[key] = value; + } + } + return obj; } - return new this(octets); - }; - - ipaddr.IPv4.broadcastAddressFromCIDR = function(string) { - var cidr, error, i, ipInterfaceOctets, octets, subnetMaskOctets; - try { - cidr = this.parseCIDR(string); - ipInterfaceOctets = cidr[0].toByteArray(); - subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray(); - octets = []; - i = 0; - while (i < 4) { - octets.push(parseInt(ipInterfaceOctets[i], 10) | parseInt(subnetMaskOctets[i], 10) ^ 255); - i++; - } - return new this(octets); - } catch (error1) { - error = error1; - throw new Error('ipaddr: the address does not have IPv4 CIDR format'); + return result; +}); +class MixedBuffers { + constructor() { + this.length = 0; + this.items = []; } - }; - - ipaddr.IPv4.networkAddressFromCIDR = function(string) { - var cidr, error, i, ipInterfaceOctets, octets, subnetMaskOctets; - try { - cidr = this.parseCIDR(string); - ipInterfaceOctets = cidr[0].toByteArray(); - subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray(); - octets = []; - i = 0; - while (i < 4) { - octets.push(parseInt(ipInterfaceOctets[i], 10) & parseInt(subnetMaskOctets[i], 10)); - i++; - } - return new this(octets); - } catch (error1) { - error = error1; - throw new Error('ipaddr: the address does not have IPv4 CIDR format'); + push(x) { + this.length += Buffer.byteLength(x); + this.items.push(x); } - }; - - ipaddr.IPv6.parseCIDR = function(string) { - var maskLength, match, parsed; - if (match = string.match(/^(.+)\/(\d+)$/)) { - maskLength = parseInt(match[2]); - if (maskLength >= 0 && maskLength <= 128) { - parsed = [this.parse(match[1]), maskLength]; - Object.defineProperty(parsed, 'toString', { - value: function() { - return this.join('/'); - } - }); - return parsed; - } + toBuffer() { + const result = Buffer.allocUnsafe(this.length); + let offset = 0; + for (const item of this.items) { + const length = Buffer.byteLength(item); + Buffer.isBuffer(item) + ? item.copy(result, offset) + : result.write(item, offset, length); + offset += length; + } + return result; } - throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range"); - }; +} - ipaddr.isValid = function(string) { - return ipaddr.IPv6.isValid(string) || ipaddr.IPv4.isValid(string); - }; - ipaddr.parse = function(string) { - if (ipaddr.IPv6.isValid(string)) { - return ipaddr.IPv6.parse(string); - } else if (ipaddr.IPv4.isValid(string)) { - return ipaddr.IPv4.parse(string); - } else { - throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format"); - } - }; +/***/ }), - ipaddr.parseCIDR = function(string) { - var e; - try { - return ipaddr.IPv6.parseCIDR(string); - } catch (error1) { - e = error1; - try { - return ipaddr.IPv4.parseCIDR(string); - } catch (error1) { - e = error1; - throw new Error("ipaddr: the address has neither IPv6 nor IPv4 CIDR format"); - } - } - }; +/***/ 33642: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - ipaddr.fromByteArray = function(bytes) { - var length; - length = bytes.length; - if (length === 4) { - return new ipaddr.IPv4(bytes); - } else if (length === 16) { - return new ipaddr.IPv6(bytes); - } else { - throw new Error("ipaddr: the binary input is neither an IPv6 nor IPv4 address"); - } - }; +"use strict"; - ipaddr.process = function(string) { - var addr; - addr = this.parse(string); - if (addr.kind() === 'ipv6' && addr.isIPv4MappedAddress()) { - return addr.toIPv4Address(); - } else { - return addr; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const lodash_1 = __nccwpck_require__(20961); +const command_1 = __nccwpck_require__(90803); +const script_1 = __nccwpck_require__(88540); +const PromiseContainer = __nccwpck_require__(71475); +const standard_as_callback_1 = __nccwpck_require__(91543); +const autoPipelining_1 = __nccwpck_require__(97873); +const DROP_BUFFER_SUPPORT_ERROR = "*Buffer methods are not available " + + 'because "dropBufferSupport" option is enabled.' + + "Refer to https://github.com/luin/ioredis/wiki/Improve-Performance for more details."; +/** + * Commander + * + * This is the base class of Redis, Redis.Cluster and Pipeline + * + * @param {boolean} [options.showFriendlyErrorStack=false] - Whether to show a friendly error stack. + * Will decrease the performance significantly. + * @constructor + */ +function Commander() { + this.options = lodash_1.defaults({}, this.options || {}, { + showFriendlyErrorStack: false, + }); + this.scriptsSet = {}; + this.addedBuiltinSet = new Set(); +} +exports["default"] = Commander; +const commands = (__nccwpck_require__(98020).list.filter)(function (command) { + return command !== "monitor"; +}); +commands.push("sentinel"); +/** + * Return supported builtin commands + * + * @return {string[]} command list + * @public + */ +Commander.prototype.getBuiltinCommands = function () { + return commands.slice(0); +}; +/** + * Create a builtin command + * + * @param {string} commandName - command name + * @return {object} functions + * @public + */ +Commander.prototype.createBuiltinCommand = function (commandName) { + return { + string: generateFunction(null, commandName, "utf8"), + buffer: generateFunction(null, commandName, null), + }; +}; +/** + * Create add builtin command + * + * @param {string} commandName - command name + * @return {object} functions + * @public + */ +Commander.prototype.addBuiltinCommand = function (commandName) { + this.addedBuiltinSet.add(commandName); + this[commandName] = generateFunction(commandName, commandName, "utf8"); + this[commandName + "Buffer"] = generateFunction(commandName + "Buffer", commandName, null); +}; +commands.forEach(function (commandName) { + Commander.prototype[commandName] = generateFunction(commandName, commandName, "utf8"); + Commander.prototype[commandName + "Buffer"] = generateFunction(commandName + "Buffer", commandName, null); +}); +Commander.prototype.call = generateFunction("call", "utf8"); +Commander.prototype.callBuffer = generateFunction("callBuffer", null); +// eslint-disable-next-line @typescript-eslint/camelcase +Commander.prototype.send_command = Commander.prototype.call; +/** + * Define a custom command using lua script + * + * @param {string} name - the command name + * @param {object} definition + * @param {string} definition.lua - the lua code + * @param {number} [definition.numberOfKeys=null] - the number of keys. + * @param {boolean} [definition.readOnly=false] - force this script to be readonly so it executes on slaves as well. + * If omit, you have to pass the number of keys as the first argument every time you invoke the command + */ +Commander.prototype.defineCommand = function (name, definition) { + const script = new script_1.default(definition.lua, definition.numberOfKeys, this.options.keyPrefix, definition.readOnly); + this.scriptsSet[name] = script; + this[name] = generateScriptingFunction(name, name, script, "utf8"); + this[name + "Buffer"] = generateScriptingFunction(name + "Buffer", name, script, null); +}; +/** + * Send a command + * + * @abstract + * @public + */ +Commander.prototype.sendCommand = function () { }; +function generateFunction(functionName, _commandName, _encoding) { + if (typeof _encoding === "undefined") { + _encoding = _commandName; + _commandName = null; } - }; - -}).call(this); + return function (...args) { + const commandName = _commandName || args.shift(); + let callback = args[args.length - 1]; + if (typeof callback === "function") { + args.pop(); + } + else { + callback = undefined; + } + const options = { + errorStack: this.options.showFriendlyErrorStack ? new Error() : undefined, + keyPrefix: this.options.keyPrefix, + replyEncoding: _encoding, + }; + if (this.options.dropBufferSupport && !_encoding) { + return standard_as_callback_1.default(PromiseContainer.get().reject(new Error(DROP_BUFFER_SUPPORT_ERROR)), callback); + } + // No auto pipeline, use regular command sending + if (!autoPipelining_1.shouldUseAutoPipelining(this, functionName, commandName)) { + return this.sendCommand(new command_1.default(commandName, args, options, callback)); + } + // Create a new pipeline and make sure it's scheduled + return autoPipelining_1.executeWithAutoPipelining(this, functionName, commandName, args, callback); + }; +} +function generateScriptingFunction(functionName, commandName, script, encoding) { + return function () { + let length = arguments.length; + const lastArgIndex = length - 1; + let callback = arguments[lastArgIndex]; + if (typeof callback !== "function") { + callback = undefined; + } + else { + length = lastArgIndex; + } + const args = new Array(length); + for (let i = 0; i < length; i++) { + args[i] = arguments[i]; + } + let options; + if (this.options.dropBufferSupport) { + if (!encoding) { + return standard_as_callback_1.default(PromiseContainer.get().reject(new Error(DROP_BUFFER_SUPPORT_ERROR)), callback); + } + options = { replyEncoding: null }; + } + else { + options = { replyEncoding: encoding }; + } + if (this.options.showFriendlyErrorStack) { + options.errorStack = new Error(); + } + // No auto pipeline, use regular command sending + if (!autoPipelining_1.shouldUseAutoPipelining(this, functionName, commandName)) { + return script.execute(this, args, options, callback); + } + // Create a new pipeline and make sure it's scheduled + return autoPipelining_1.executeWithAutoPipelining(this, functionName, commandName, args, callback); + }; +} /***/ }), -/***/ 7604: -/***/ ((module) => { +/***/ 72712: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; - -module.exports = function isArrayish(obj) { - if (!obj) { - return false; - } - - return obj instanceof Array || Array.isArray(obj) || - (obj.length >= 0 && obj.splice instanceof Function); -}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const utils_1 = __nccwpck_require__(94832); +const debug = utils_1.Debug("AbstractConnector"); +class AbstractConnector { + constructor(disconnectTimeout) { + this.connecting = false; + this.disconnectTimeout = disconnectTimeout; + } + check(info) { + return true; + } + disconnect() { + this.connecting = false; + if (this.stream) { + const stream = this.stream; // Make sure callbacks refer to the same instance + const timeout = setTimeout(() => { + debug("stream %s:%s still open, destroying it", stream.remoteAddress, stream.remotePort); + stream.destroy(); + }, this.disconnectTimeout); + stream.on("close", () => clearTimeout(timeout)); + stream.end(); + } + } +} +exports["default"] = AbstractConnector; /***/ }), -/***/ 31310: -/***/ (function(module, exports) { - -;(function(root) { - 'use strict'; - - function isBase64(v, opts) { - if (v instanceof Boolean || typeof v === 'boolean') { - return false - } +/***/ 22913: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - if (!(opts instanceof Object)) { - opts = {} - } +"use strict"; - if (opts.allowEmpty === false && v === '') { - return false +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const utils_1 = __nccwpck_require__(94832); +const debug = utils_1.Debug("FailoverDetector"); +const CHANNEL_NAME = "+switch-master"; +class FailoverDetector { + // sentinels can't be used for regular commands after this + constructor(connector, sentinels) { + this.isDisconnected = false; + this.connector = connector; + this.sentinels = sentinels; } - - var regex = '(?:[A-Za-z0-9+\\/]{4})*(?:[A-Za-z0-9+\\/]{2}==|[A-Za-z0-9+\/]{3}=)?' - var mimeRegex = '(data:\\w+\\/[a-zA-Z\\+\\-\\.]+;base64,)' - - if (opts.mimeRequired === true) { - regex = mimeRegex + regex - } else if (opts.allowMime === true) { - regex = mimeRegex + '?' + regex + cleanup() { + this.isDisconnected = true; + for (const sentinel of this.sentinels) { + sentinel.client.disconnect(); + } } - - if (opts.paddingRequired === false) { - regex = '(?:[A-Za-z0-9+\\/]{4})*(?:[A-Za-z0-9+\\/]{2}(==)?|[A-Za-z0-9+\\/]{3}=?)?' + subscribe() { + return __awaiter(this, void 0, void 0, function* () { + debug("Starting FailoverDetector"); + const promises = []; + for (const sentinel of this.sentinels) { + const promise = sentinel.client.subscribe(CHANNEL_NAME).catch((err) => { + debug("Failed to subscribe to failover messages on sentinel %s:%s (%s)", sentinel.address.host || "127.0.0.1", sentinel.address.port || 26739, err.message); + }); + promises.push(promise); + sentinel.client.on("message", (channel) => { + if (!this.isDisconnected && channel === CHANNEL_NAME) { + this.disconnect(); + } + }); + } + yield Promise.all(promises); + }); } - - return (new RegExp('^' + regex + '$', 'gi')).test(v) - } - - if (true) { - if ( true && module.exports) { - exports = module.exports = isBase64 + disconnect() { + // Avoid disconnecting more than once per failover. + // A new FailoverDetector will be created after reconnecting. + this.isDisconnected = true; + debug("Failover detected, disconnecting"); + // Will call this.cleanup() + this.connector.disconnect(); } - exports.isBase64 = isBase64 - } else {} -})(this); +} +exports.FailoverDetector = FailoverDetector; /***/ }), -/***/ 56873: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 72225: +/***/ ((__unused_webpack_module, exports) => { "use strict"; - -var has = __nccwpck_require__(76339); - -function specifierIncluded(current, specifier) { - var nodeParts = current.split('.'); - var parts = specifier.split(' '); - var op = parts.length > 1 ? parts[0] : '='; - var versionParts = (parts.length > 1 ? parts[1] : parts[0]).split('.'); - - for (var i = 0; i < 3; ++i) { - var cur = parseInt(nodeParts[i] || 0, 10); - var ver = parseInt(versionParts[i] || 0, 10); - if (cur === ver) { - continue; // eslint-disable-line no-restricted-syntax, no-continue - } - if (op === '<') { - return cur < ver; - } - if (op === '>=') { - return cur >= ver; - } - return false; - } - return op === '>='; +Object.defineProperty(exports, "__esModule", ({ value: true })); +function isSentinelEql(a, b) { + return ((a.host || "127.0.0.1") === (b.host || "127.0.0.1") && + (a.port || 26379) === (b.port || 26379)); } - -function matchesRange(current, range) { - var specifiers = range.split(/ ?&& ?/); - if (specifiers.length === 0) { - return false; - } - for (var i = 0; i < specifiers.length; ++i) { - if (!specifierIncluded(current, specifiers[i])) { - return false; - } - } - return true; +class SentinelIterator { + constructor(sentinels) { + this.cursor = 0; + this.sentinels = sentinels.slice(0); + } + next() { + const done = this.cursor >= this.sentinels.length; + return { done, value: done ? undefined : this.sentinels[this.cursor++] }; + } + reset(moveCurrentEndpointToFirst) { + if (moveCurrentEndpointToFirst && + this.sentinels.length > 1 && + this.cursor !== 1) { + this.sentinels.unshift(...this.sentinels.splice(this.cursor - 1)); + } + this.cursor = 0; + } + add(sentinel) { + for (let i = 0; i < this.sentinels.length; i++) { + if (isSentinelEql(sentinel, this.sentinels[i])) { + return false; + } + } + this.sentinels.push(sentinel); + return true; + } + toString() { + return `${JSON.stringify(this.sentinels)} @${this.cursor}`; + } } +exports["default"] = SentinelIterator; -function versionIncluded(nodeVersion, specifierValue) { - if (typeof specifierValue === 'boolean') { - return specifierValue; - } - var current = typeof nodeVersion === 'undefined' - ? process.versions && process.versions.node - : nodeVersion; +/***/ }), - if (typeof current !== 'string') { - throw new TypeError(typeof nodeVersion === 'undefined' ? 'Unable to determine current node version' : 'If provided, a valid node version is required'); - } +/***/ 10379: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - if (specifierValue && typeof specifierValue === 'object') { - for (var i = 0; i < specifierValue.length; ++i) { - if (matchesRange(current, specifierValue[i])) { - return true; - } - } - return false; - } - return matchesRange(current, specifierValue); +"use strict"; + +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const net_1 = __nccwpck_require__(41808); +const utils_1 = __nccwpck_require__(94832); +const tls_1 = __nccwpck_require__(24404); +const StandaloneConnector_1 = __nccwpck_require__(8774); +const SentinelIterator_1 = __nccwpck_require__(72225); +exports.SentinelIterator = SentinelIterator_1.default; +const AbstractConnector_1 = __nccwpck_require__(72712); +const redis_1 = __nccwpck_require__(83609); +const FailoverDetector_1 = __nccwpck_require__(22913); +const debug = utils_1.Debug("SentinelConnector"); +class SentinelConnector extends AbstractConnector_1.default { + constructor(options) { + super(options.disconnectTimeout); + this.options = options; + this.failoverDetector = null; + this.emitter = null; + if (!this.options.sentinels.length) { + throw new Error("Requires at least one sentinel to connect to."); + } + if (!this.options.name) { + throw new Error("Requires the name of master."); + } + this.sentinelIterator = new SentinelIterator_1.default(this.options.sentinels); + } + check(info) { + const roleMatches = !info.role || this.options.role === info.role; + if (!roleMatches) { + debug("role invalid, expected %s, but got %s", this.options.role, info.role); + // Start from the next item. + // Note that `reset` will move the cursor to the previous element, + // so we advance two steps here. + this.sentinelIterator.next(); + this.sentinelIterator.next(); + this.sentinelIterator.reset(true); + } + return roleMatches; + } + disconnect() { + super.disconnect(); + if (this.failoverDetector) { + this.failoverDetector.cleanup(); + } + } + connect(eventEmitter) { + this.connecting = true; + this.retryAttempts = 0; + let lastError; + const connectToNext = () => __awaiter(this, void 0, void 0, function* () { + const endpoint = this.sentinelIterator.next(); + if (endpoint.done) { + this.sentinelIterator.reset(false); + const retryDelay = typeof this.options.sentinelRetryStrategy === "function" + ? this.options.sentinelRetryStrategy(++this.retryAttempts) + : null; + let errorMsg = typeof retryDelay !== "number" + ? "All sentinels are unreachable and retry is disabled." + : `All sentinels are unreachable. Retrying from scratch after ${retryDelay}ms.`; + if (lastError) { + errorMsg += ` Last error: ${lastError.message}`; + } + debug(errorMsg); + const error = new Error(errorMsg); + if (typeof retryDelay === "number") { + eventEmitter("error", error); + yield new Promise((resolve) => setTimeout(resolve, retryDelay)); + return connectToNext(); + } + else { + throw error; + } + } + let resolved = null; + let err = null; + try { + resolved = yield this.resolve(endpoint.value); + } + catch (error) { + err = error; + } + if (!this.connecting) { + throw new Error(utils_1.CONNECTION_CLOSED_ERROR_MSG); + } + const endpointAddress = endpoint.value.host + ":" + endpoint.value.port; + if (resolved) { + debug("resolved: %s:%s from sentinel %s", resolved.host, resolved.port, endpointAddress); + if (this.options.enableTLSForSentinelMode && this.options.tls) { + Object.assign(resolved, this.options.tls); + this.stream = tls_1.connect(resolved); + } + else { + this.stream = net_1.createConnection(resolved); + } + this.stream.once("connect", () => this.initFailoverDetector()); + this.stream.once("error", (err) => { + this.firstError = err; + }); + return this.stream; + } + else { + const errorMsg = err + ? "failed to connect to sentinel " + + endpointAddress + + " because " + + err.message + : "connected to sentinel " + + endpointAddress + + " successfully, but got an invalid reply: " + + resolved; + debug(errorMsg); + eventEmitter("sentinelError", new Error(errorMsg)); + if (err) { + lastError = err; + } + return connectToNext(); + } + }); + return connectToNext(); + } + updateSentinels(client) { + return __awaiter(this, void 0, void 0, function* () { + if (!this.options.updateSentinels) { + return; + } + const result = yield client.sentinel("sentinels", this.options.name); + if (!Array.isArray(result)) { + return; + } + result + .map(utils_1.packObject) + .forEach((sentinel) => { + const flags = sentinel.flags ? sentinel.flags.split(",") : []; + if (flags.indexOf("disconnected") === -1 && + sentinel.ip && + sentinel.port) { + const endpoint = this.sentinelNatResolve(addressResponseToAddress(sentinel)); + if (this.sentinelIterator.add(endpoint)) { + debug("adding sentinel %s:%s", endpoint.host, endpoint.port); + } + } + }); + debug("Updated internal sentinels: %s", this.sentinelIterator); + }); + } + resolveMaster(client) { + return __awaiter(this, void 0, void 0, function* () { + const result = yield client.sentinel("get-master-addr-by-name", this.options.name); + yield this.updateSentinels(client); + return this.sentinelNatResolve(Array.isArray(result) + ? { host: result[0], port: Number(result[1]) } + : null); + }); + } + resolveSlave(client) { + return __awaiter(this, void 0, void 0, function* () { + const result = yield client.sentinel("slaves", this.options.name); + if (!Array.isArray(result)) { + return null; + } + const availableSlaves = result + .map(utils_1.packObject) + .filter((slave) => slave.flags && !slave.flags.match(/(disconnected|s_down|o_down)/)); + return this.sentinelNatResolve(selectPreferredSentinel(availableSlaves, this.options.preferredSlaves)); + }); + } + sentinelNatResolve(item) { + if (!item || !this.options.natMap) + return item; + return this.options.natMap[`${item.host}:${item.port}`] || item; + } + connectToSentinel(endpoint, options) { + return new redis_1.default(Object.assign({ port: endpoint.port || 26379, host: endpoint.host, username: this.options.sentinelUsername || null, password: this.options.sentinelPassword || null, family: endpoint.family || + (StandaloneConnector_1.isIIpcConnectionOptions(this.options) + ? undefined + : this.options.family), tls: this.options.sentinelTLS, retryStrategy: null, enableReadyCheck: false, connectTimeout: this.options.connectTimeout, commandTimeout: this.options.sentinelCommandTimeout, dropBufferSupport: true }, options)); + } + resolve(endpoint) { + return __awaiter(this, void 0, void 0, function* () { + const client = this.connectToSentinel(endpoint); + // ignore the errors since resolve* methods will handle them + client.on("error", noop); + try { + if (this.options.role === "slave") { + return yield this.resolveSlave(client); + } + else { + return yield this.resolveMaster(client); + } + } + finally { + client.disconnect(); + } + }); + } + initFailoverDetector() { + var _a; + return __awaiter(this, void 0, void 0, function* () { + if (!this.options.failoverDetector) { + return; + } + // Move the current sentinel to the first position + this.sentinelIterator.reset(true); + const sentinels = []; + // In case of a large amount of sentinels, limit the number of concurrent connections + while (sentinels.length < this.options.sentinelMaxConnections) { + const { done, value } = this.sentinelIterator.next(); + if (done) { + break; + } + const client = this.connectToSentinel(value, { + lazyConnect: true, + retryStrategy: this.options.sentinelReconnectStrategy, + }); + client.on("reconnecting", () => { + var _a; + // Tests listen to this event + (_a = this.emitter) === null || _a === void 0 ? void 0 : _a.emit("sentinelReconnecting"); + }); + sentinels.push({ address: value, client }); + } + this.sentinelIterator.reset(false); + if (this.failoverDetector) { + // Clean up previous detector + this.failoverDetector.cleanup(); + } + this.failoverDetector = new FailoverDetector_1.FailoverDetector(this, sentinels); + yield this.failoverDetector.subscribe(); + // Tests listen to this event + (_a = this.emitter) === null || _a === void 0 ? void 0 : _a.emit("failoverSubscribed"); + }); + } +} +exports["default"] = SentinelConnector; +function selectPreferredSentinel(availableSlaves, preferredSlaves) { + if (availableSlaves.length === 0) { + return null; + } + let selectedSlave; + if (typeof preferredSlaves === "function") { + selectedSlave = preferredSlaves(availableSlaves); + } + else if (preferredSlaves !== null && typeof preferredSlaves === "object") { + const preferredSlavesArray = Array.isArray(preferredSlaves) + ? preferredSlaves + : [preferredSlaves]; + // sort by priority + preferredSlavesArray.sort((a, b) => { + // default the priority to 1 + if (!a.prio) { + a.prio = 1; + } + if (!b.prio) { + b.prio = 1; + } + // lowest priority first + if (a.prio < b.prio) { + return -1; + } + if (a.prio > b.prio) { + return 1; + } + return 0; + }); + // loop over preferred slaves and return the first match + for (let p = 0; p < preferredSlavesArray.length; p++) { + for (let a = 0; a < availableSlaves.length; a++) { + const slave = availableSlaves[a]; + if (slave.ip === preferredSlavesArray[p].ip) { + if (slave.port === preferredSlavesArray[p].port) { + selectedSlave = slave; + break; + } + } + } + if (selectedSlave) { + break; + } + } + } + // if none of the preferred slaves are available, a random available slave is returned + if (!selectedSlave) { + selectedSlave = utils_1.sample(availableSlaves); + } + return addressResponseToAddress(selectedSlave); } - -var data = __nccwpck_require__(66151); - -module.exports = function isCore(x, nodeVersion) { - return has(data, x) && versionIncluded(nodeVersion, data[x]); -}; +function addressResponseToAddress(input) { + return { host: input.ip, port: Number(input.port) }; +} +function noop() { } /***/ }), -/***/ 63287: -/***/ ((__unused_webpack_module, exports) => { +/***/ 8774: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; - Object.defineProperty(exports, "__esModule", ({ value: true })); - -/*! - * is-plain-object - * - * Copyright (c) 2014-2017, Jon Schlinkert. - * Released under the MIT License. - */ - -function isObject(o) { - return Object.prototype.toString.call(o) === '[object Object]'; -} - -function isPlainObject(o) { - var ctor,prot; - - if (isObject(o) === false) return false; - - // If has modified constructor - ctor = o.constructor; - if (ctor === undefined) return true; - - // If has modified prototype - prot = ctor.prototype; - if (isObject(prot) === false) return false; - - // If constructor does not have an Object-specific method - if (prot.hasOwnProperty('isPrototypeOf') === false) { - return false; - } - - // Most likely a plain Object - return true; +const net_1 = __nccwpck_require__(41808); +const tls_1 = __nccwpck_require__(24404); +const utils_1 = __nccwpck_require__(94832); +const AbstractConnector_1 = __nccwpck_require__(72712); +function isIIpcConnectionOptions(value) { + return value.path; } - -exports.isPlainObject = isPlainObject; - - -/***/ }), - -/***/ 87783: -/***/ ((__unused_webpack_module, exports) => { - -(function(exports) { - "use strict"; - - function isArray(obj) { - if (obj !== null) { - return Object.prototype.toString.call(obj) === "[object Array]"; - } else { - return false; - } - } - - function isObject(obj) { - if (obj !== null) { - return Object.prototype.toString.call(obj) === "[object Object]"; - } else { - return false; - } - } - - function strictDeepEqual(first, second) { - // Check the scalar case first. - if (first === second) { - return true; - } - - // Check if they are the same type. - var firstType = Object.prototype.toString.call(first); - if (firstType !== Object.prototype.toString.call(second)) { - return false; - } - // We know that first and second have the same type so we can just check the - // first type from now on. - if (isArray(first) === true) { - // Short circuit if they're not the same length; - if (first.length !== second.length) { - return false; - } - for (var i = 0; i < first.length; i++) { - if (strictDeepEqual(first[i], second[i]) === false) { - return false; - } - } - return true; +exports.isIIpcConnectionOptions = isIIpcConnectionOptions; +class StandaloneConnector extends AbstractConnector_1.default { + constructor(options) { + super(options.disconnectTimeout); + this.options = options; } - if (isObject(first) === true) { - // An object is equal if it has the same key/value pairs. - var keysSeen = {}; - for (var key in first) { - if (hasOwnProperty.call(first, key)) { - if (strictDeepEqual(first[key], second[key]) === false) { - return false; - } - keysSeen[key] = true; - } - } - // Now check that there aren't any keys in second that weren't - // in first. - for (var key2 in second) { - if (hasOwnProperty.call(second, key2)) { - if (keysSeen[key2] !== true) { - return false; - } + connect(_) { + const { options } = this; + this.connecting = true; + let connectionOptions; + if (isIIpcConnectionOptions(options)) { + connectionOptions = { + path: options.path, + }; } - } - return true; - } - return false; - } - - function isFalse(obj) { - // From the spec: - // A false value corresponds to the following values: - // Empty list - // Empty object - // Empty string - // False boolean - // null value - - // First check the scalar values. - if (obj === "" || obj === false || obj === null) { - return true; - } else if (isArray(obj) && obj.length === 0) { - // Check for an empty array. - return true; - } else if (isObject(obj)) { - // Check for an empty object. - for (var key in obj) { - // If there are any keys, then - // the object is not empty so the object - // is not false. - if (obj.hasOwnProperty(key)) { - return false; + else { + connectionOptions = {}; + if (options.port != null) { + connectionOptions.port = options.port; + } + if (options.host != null) { + connectionOptions.host = options.host; + } + if (options.family != null) { + connectionOptions.family = options.family; } } - return true; - } else { - return false; - } - } - - function objValues(obj) { - var keys = Object.keys(obj); - var values = []; - for (var i = 0; i < keys.length; i++) { - values.push(obj[keys[i]]); + if (options.tls) { + Object.assign(connectionOptions, options.tls); + } + // TODO: + // We use native Promise here since other Promise + // implementation may use different schedulers that + // cause issue when the stream is resolved in the + // next tick. + // Should use the provided promise in the next major + // version and do not connect before resolved. + return new Promise((resolve, reject) => { + process.nextTick(() => { + if (!this.connecting) { + reject(new Error(utils_1.CONNECTION_CLOSED_ERROR_MSG)); + return; + } + try { + if (options.tls) { + this.stream = tls_1.connect(connectionOptions); + } + else { + this.stream = net_1.createConnection(connectionOptions); + } + } + catch (err) { + reject(err); + return; + } + this.stream.once("error", (err) => { + this.firstError = err; + }); + resolve(this.stream); + }); + }); } - return values; - } - - function merge(a, b) { - var merged = {}; - for (var key in a) { - merged[key] = a[key]; - } - for (var key2 in b) { - merged[key2] = b[key2]; - } - return merged; - } - - var trimLeft; - if (typeof String.prototype.trimLeft === "function") { - trimLeft = function(str) { - return str.trimLeft(); - }; - } else { - trimLeft = function(str) { - return str.match(/^\s*(.*)/)[1]; - }; - } +} +exports["default"] = StandaloneConnector; - // Type constants used to define functions. - var TYPE_NUMBER = 0; - var TYPE_ANY = 1; - var TYPE_STRING = 2; - var TYPE_ARRAY = 3; - var TYPE_OBJECT = 4; - var TYPE_BOOLEAN = 5; - var TYPE_EXPREF = 6; - var TYPE_NULL = 7; - var TYPE_ARRAY_NUMBER = 8; - var TYPE_ARRAY_STRING = 9; - var TOK_EOF = "EOF"; - var TOK_UNQUOTEDIDENTIFIER = "UnquotedIdentifier"; - var TOK_QUOTEDIDENTIFIER = "QuotedIdentifier"; - var TOK_RBRACKET = "Rbracket"; - var TOK_RPAREN = "Rparen"; - var TOK_COMMA = "Comma"; - var TOK_COLON = "Colon"; - var TOK_RBRACE = "Rbrace"; - var TOK_NUMBER = "Number"; - var TOK_CURRENT = "Current"; - var TOK_EXPREF = "Expref"; - var TOK_PIPE = "Pipe"; - var TOK_OR = "Or"; - var TOK_AND = "And"; - var TOK_EQ = "EQ"; - var TOK_GT = "GT"; - var TOK_LT = "LT"; - var TOK_GTE = "GTE"; - var TOK_LTE = "LTE"; - var TOK_NE = "NE"; - var TOK_FLATTEN = "Flatten"; - var TOK_STAR = "Star"; - var TOK_FILTER = "Filter"; - var TOK_DOT = "Dot"; - var TOK_NOT = "Not"; - var TOK_LBRACE = "Lbrace"; - var TOK_LBRACKET = "Lbracket"; - var TOK_LPAREN= "Lparen"; - var TOK_LITERAL= "Literal"; +/***/ }), - // The "&", "[", "<", ">" tokens - // are not in basicToken because - // there are two token variants - // ("&&", "[?", "<=", ">="). This is specially handled - // below. +/***/ 72340: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - var basicTokens = { - ".": TOK_DOT, - "*": TOK_STAR, - ",": TOK_COMMA, - ":": TOK_COLON, - "{": TOK_LBRACE, - "}": TOK_RBRACE, - "]": TOK_RBRACKET, - "(": TOK_LPAREN, - ")": TOK_RPAREN, - "@": TOK_CURRENT - }; +"use strict"; - var operatorStartToken = { - "<": true, - ">": true, - "=": true, - "!": true - }; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const StandaloneConnector_1 = __nccwpck_require__(8774); +exports.StandaloneConnector = StandaloneConnector_1.default; +const SentinelConnector_1 = __nccwpck_require__(10379); +exports.SentinelConnector = SentinelConnector_1.default; - var skipChars = { - " ": true, - "\t": true, - "\n": true - }; +/***/ }), - function isAlpha(ch) { - return (ch >= "a" && ch <= "z") || - (ch >= "A" && ch <= "Z") || - ch === "_"; - } +/***/ 61823: +/***/ ((__unused_webpack_module, exports) => { - function isNum(ch) { - return (ch >= "0" && ch <= "9") || - ch === "-"; - } - function isAlphaNum(ch) { - return (ch >= "a" && ch <= "z") || - (ch >= "A" && ch <= "Z") || - (ch >= "0" && ch <= "9") || - ch === "_"; - } +"use strict"; - function Lexer() { - } - Lexer.prototype = { - tokenize: function(stream) { - var tokens = []; - this._current = 0; - var start; - var identifier; - var token; - while (this._current < stream.length) { - if (isAlpha(stream[this._current])) { - start = this._current; - identifier = this._consumeUnquotedIdentifier(stream); - tokens.push({type: TOK_UNQUOTEDIDENTIFIER, - value: identifier, - start: start}); - } else if (basicTokens[stream[this._current]] !== undefined) { - tokens.push({type: basicTokens[stream[this._current]], - value: stream[this._current], - start: this._current}); - this._current++; - } else if (isNum(stream[this._current])) { - token = this._consumeNumber(stream); - tokens.push(token); - } else if (stream[this._current] === "[") { - // No need to increment this._current. This happens - // in _consumeLBracket - token = this._consumeLBracket(stream); - tokens.push(token); - } else if (stream[this._current] === "\"") { - start = this._current; - identifier = this._consumeQuotedIdentifier(stream); - tokens.push({type: TOK_QUOTEDIDENTIFIER, - value: identifier, - start: start}); - } else if (stream[this._current] === "'") { - start = this._current; - identifier = this._consumeRawStringLiteral(stream); - tokens.push({type: TOK_LITERAL, - value: identifier, - start: start}); - } else if (stream[this._current] === "`") { - start = this._current; - var literal = this._consumeLiteral(stream); - tokens.push({type: TOK_LITERAL, - value: literal, - start: start}); - } else if (operatorStartToken[stream[this._current]] !== undefined) { - tokens.push(this._consumeOperator(stream)); - } else if (skipChars[stream[this._current]] !== undefined) { - // Ignore whitespace. - this._current++; - } else if (stream[this._current] === "&") { - start = this._current; - this._current++; - if (stream[this._current] === "&") { - this._current++; - tokens.push({type: TOK_AND, value: "&&", start: start}); - } else { - tokens.push({type: TOK_EXPREF, value: "&", start: start}); - } - } else if (stream[this._current] === "|") { - start = this._current; - this._current++; - if (stream[this._current] === "|") { - this._current++; - tokens.push({type: TOK_OR, value: "||", start: start}); - } else { - tokens.push({type: TOK_PIPE, value: "|", start: start}); - } - } else { - var error = new Error("Unknown character:" + stream[this._current]); - error.name = "LexerError"; - throw error; - } - } - return tokens; - }, +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports["default"] = { + /** + * TLS settings for Redis.com Cloud Fixed plan. Updated on 2021-10-06. + */ + RedisCloudFixed: { + ca: "-----BEGIN CERTIFICATE-----\n" + + "MIIDTzCCAjegAwIBAgIJAKSVpiDswLcwMA0GCSqGSIb3DQEBBQUAMD4xFjAUBgNV\n" + + "BAoMDUdhcmFudGlhIERhdGExJDAiBgNVBAMMG1NTTCBDZXJ0aWZpY2F0aW9uIEF1\n" + + "dGhvcml0eTAeFw0xMzEwMDExMjE0NTVaFw0yMzA5MjkxMjE0NTVaMD4xFjAUBgNV\n" + + "BAoMDUdhcmFudGlhIERhdGExJDAiBgNVBAMMG1NTTCBDZXJ0aWZpY2F0aW9uIEF1\n" + + "dGhvcml0eTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALZqkh/DczWP\n" + + "JnxnHLQ7QL0T4B4CDKWBKCcisriGbA6ZePWVNo4hfKQC6JrzfR+081NeD6VcWUiz\n" + + "rmd+jtPhIY4c+WVQYm5PKaN6DT1imYdxQw7aqO5j2KUCEh/cznpLxeSHoTxlR34E\n" + + "QwF28Wl3eg2vc5ct8LjU3eozWVk3gb7alx9mSA2SgmuX5lEQawl++rSjsBStemY2\n" + + "BDwOpAMXIrdEyP/cVn8mkvi/BDs5M5G+09j0gfhyCzRWMQ7Hn71u1eolRxwVxgi3\n" + + "TMn+/vTaFSqxKjgck6zuAYjBRPaHe7qLxHNr1So/Mc9nPy+3wHebFwbIcnUojwbp\n" + + "4nctkWbjb2cCAwEAAaNQME4wHQYDVR0OBBYEFP1whtcrydmW3ZJeuSoKZIKjze3w\n" + + "MB8GA1UdIwQYMBaAFP1whtcrydmW3ZJeuSoKZIKjze3wMAwGA1UdEwQFMAMBAf8w\n" + + "DQYJKoZIhvcNAQEFBQADggEBAG2erXhwRAa7+ZOBs0B6X57Hwyd1R4kfmXcs0rta\n" + + "lbPpvgULSiB+TCbf3EbhJnHGyvdCY1tvlffLjdA7HJ0PCOn+YYLBA0pTU/dyvrN6\n" + + "Su8NuS5yubnt9mb13nDGYo1rnt0YRfxN+8DM3fXIVr038A30UlPX2Ou1ExFJT0MZ\n" + + "uFKY6ZvLdI6/1cbgmguMlAhM+DhKyV6Sr5699LM3zqeI816pZmlREETYkGr91q7k\n" + + "BpXJu/dtHaGxg1ZGu6w/PCsYGUcECWENYD4VQPd8N32JjOfu6vEgoEAwfPP+3oGp\n" + + "Z4m3ewACcWOAenqflb+cQYC4PsF7qbXDmRaWrbKntOlZ3n0=\n" + + "-----END CERTIFICATE-----\n", + }, + /** + * TLS settings for Redis.com Cloud Flexible plan. Updated on 2021-10-06. + */ + RedisCloudFlexible: { + ca: "-----BEGIN CERTIFICATE-----\n" + + "MIIGMTCCBBmgAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwajELMAkGA1UEBhMCVVMx\n" + + "CzAJBgNVBAgMAkNBMQswCQYDVQQHDAJDQTESMBAGA1UECgwJUmVkaXNMYWJzMS0w\n" + + "KwYDVQQDDCRSZWRpc0xhYnMgUm9vdCBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkwHhcN\n" + + "MTgwMjI1MTUzNzM3WhcNMjgwMjIzMTUzNzM3WjBfMQswCQYDVQQGEwJVUzELMAkG\n" + + "A1UECAwCQ0ExEjAQBgNVBAoMCVJlZGlzTGFiczEvMC0GA1UEAwwmUkNQIEludGVy\n" + + "bWVkaWF0ZSBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkwggIiMA0GCSqGSIb3DQEBAQUA\n" + + "A4ICDwAwggIKAoICAQDf9dqbxc8Bq7Ctq9rWcxrGNKKHivqLAFpPq02yLPx6fsOv\n" + + "Tq7GsDChAYBBc4v7Y2Ap9RD5Vs3dIhEANcnolf27QwrG9RMnnvzk8pCvp1o6zSU4\n" + + "VuOE1W66/O1/7e2rVxyrnTcP7UgK43zNIXu7+tiAqWsO92uSnuMoGPGpeaUm1jym\n" + + "hjWKtkAwDFSqvHY+XL5qDVBEjeUe+WHkYUg40cAXjusAqgm2hZt29c2wnVrxW25W\n" + + "P0meNlzHGFdA2AC5z54iRiqj57dTfBTkHoBczQxcyw6hhzxZQ4e5I5zOKjXXEhZN\n" + + "r0tA3YC14CTabKRus/JmZieyZzRgEy2oti64tmLYTqSlAD78pRL40VNoaSYetXLw\n" + + "hhNsXCHgWaY6d5bLOc/aIQMAV5oLvZQKvuXAF1IDmhPA+bZbpWipp0zagf1P1H3s\n" + + "UzsMdn2KM0ejzgotbtNlj5TcrVwpmvE3ktvUAuA+hi3FkVx1US+2Gsp5x4YOzJ7u\n" + + "P1WPk6ShF0JgnJH2ILdj6kttTWwFzH17keSFICWDfH/+kM+k7Y1v3EXMQXE7y0T9\n" + + "MjvJskz6d/nv+sQhY04xt64xFMGTnZjlJMzfQNi7zWFLTZnDD0lPowq7l3YiPoTT\n" + + "t5Xky83lu0KZsZBo0WlWaDG00gLVdtRgVbcuSWxpi5BdLb1kRab66JptWjxwXQID\n" + + "AQABo4HrMIHoMDoGA1UdHwQzMDEwL6AtoCuGKWh0dHBzOi8vcmwtY2Etc2VydmVy\n" + + "LnJlZGlzbGFicy5jb20vdjEvY3JsMEYGCCsGAQUFBwEBBDowODA2BggrBgEFBQcw\n" + + "AYYqaHR0cHM6Ly9ybC1jYS1zZXJ2ZXIucmVkaXNsYWJzLmNvbS92MS9vY3NwMB0G\n" + + "A1UdDgQWBBQHar5OKvQUpP2qWt6mckzToeCOHDAfBgNVHSMEGDAWgBQi42wH6hM4\n" + + "L2sujEvLM0/u8lRXTzASBgNVHRMBAf8ECDAGAQH/AgEAMA4GA1UdDwEB/wQEAwIB\n" + + "hjANBgkqhkiG9w0BAQsFAAOCAgEAirEn/iTsAKyhd+pu2W3Z5NjCko4NPU0EYUbr\n" + + "AP7+POK2rzjIrJO3nFYQ/LLuC7KCXG+2qwan2SAOGmqWst13Y+WHp44Kae0kaChW\n" + + "vcYLXXSoGQGC8QuFSNUdaeg3RbMDYFT04dOkqufeWVccoHVxyTSg9eD8LZuHn5jw\n" + + "7QDLiEECBmIJHk5Eeo2TAZrx4Yx6ufSUX5HeVjlAzqwtAqdt99uCJ/EL8bgpWbe+\n" + + "XoSpvUv0SEC1I1dCAhCKAvRlIOA6VBcmzg5Am12KzkqTul12/VEFIgzqu0Zy2Jbc\n" + + "AUPrYVu/+tOGXQaijy7YgwH8P8n3s7ZeUa1VABJHcxrxYduDDJBLZi+MjheUDaZ1\n" + + "jQRHYevI2tlqeSBqdPKG4zBY5lS0GiAlmuze5oENt0P3XboHoZPHiqcK3VECgTVh\n" + + "/BkJcuudETSJcZDmQ8YfoKfBzRQNg2sv/hwvUv73Ss51Sco8GEt2lD8uEdib1Q6z\n" + + "zDT5lXJowSzOD5ZA9OGDjnSRL+2riNtKWKEqvtEG3VBJoBzu9GoxbAc7wIZLxmli\n" + + "iF5a/Zf5X+UXD3s4TMmy6C4QZJpAA2egsSQCnraWO2ULhh7iXMysSkF/nzVfZn43\n" + + "iqpaB8++9a37hWq14ZmOv0TJIDz//b2+KC4VFXWQ5W5QC6whsjT+OlG4p5ZYG0jo\n" + + "616pxqo=\n" + + "-----END CERTIFICATE-----\n" + + "-----BEGIN CERTIFICATE-----\n" + + "MIIFujCCA6KgAwIBAgIJAJ1aTT1lu2ScMA0GCSqGSIb3DQEBCwUAMGoxCzAJBgNV\n" + + "BAYTAlVTMQswCQYDVQQIDAJDQTELMAkGA1UEBwwCQ0ExEjAQBgNVBAoMCVJlZGlz\n" + + "TGFiczEtMCsGA1UEAwwkUmVkaXNMYWJzIFJvb3QgQ2VydGlmaWNhdGUgQXV0aG9y\n" + + "aXR5MB4XDTE4MDIyNTE1MjA0MloXDTM4MDIyMDE1MjA0MlowajELMAkGA1UEBhMC\n" + + "VVMxCzAJBgNVBAgMAkNBMQswCQYDVQQHDAJDQTESMBAGA1UECgwJUmVkaXNMYWJz\n" + + "MS0wKwYDVQQDDCRSZWRpc0xhYnMgUm9vdCBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkw\n" + + "ggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDLEjXy7YrbN5Waau5cd6g1\n" + + "G5C2tMmeTpZ0duFAPxNU4oE3RHS5gGiok346fUXuUxbZ6QkuzeN2/2Z+RmRcJhQY\n" + + "Dm0ZgdG4x59An1TJfnzKKoWj8ISmoHS/TGNBdFzXV7FYNLBuqZouqePI6ReC6Qhl\n" + + "pp45huV32Q3a6IDrrvx7Wo5ZczEQeFNbCeCOQYNDdTmCyEkHqc2AGo8eoIlSTutT\n" + + "ULOC7R5gzJVTS0e1hesQ7jmqHjbO+VQS1NAL4/5K6cuTEqUl+XhVhPdLWBXJQ5ag\n" + + "54qhX4v+ojLzeU1R/Vc6NjMvVtptWY6JihpgplprN0Yh2556ewcXMeturcKgXfGJ\n" + + "xeYzsjzXerEjrVocX5V8BNrg64NlifzTMKNOOv4fVZszq1SIHR8F9ROrqiOdh8iC\n" + + "JpUbLpXH9hWCSEO6VRMB2xJoKu3cgl63kF30s77x7wLFMEHiwsQRKxooE1UhgS9K\n" + + "2sO4TlQ1eWUvFvHSTVDQDlGQ6zu4qjbOpb3Q8bQwoK+ai2alkXVR4Ltxe9QlgYK3\n" + + "StsnPhruzZGA0wbXdpw0bnM+YdlEm5ffSTpNIfgHeaa7Dtb801FtA71ZlH7A6TaI\n" + + "SIQuUST9EKmv7xrJyx0W1pGoPOLw5T029aTjnICSLdtV9bLwysrLhIYG5bnPq78B\n" + + "cS+jZHFGzD7PUVGQD01nOQIDAQABo2MwYTAdBgNVHQ4EFgQUIuNsB+oTOC9rLoxL\n" + + "yzNP7vJUV08wHwYDVR0jBBgwFoAUIuNsB+oTOC9rLoxLyzNP7vJUV08wDwYDVR0T\n" + + "AQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAYYwDQYJKoZIhvcNAQELBQADggIBAHfg\n" + + "z5pMNUAKdMzK1aS1EDdK9yKz4qicILz5czSLj1mC7HKDRy8cVADUxEICis++CsCu\n" + + "rYOvyCVergHQLREcxPq4rc5Nq1uj6J6649NEeh4WazOOjL4ZfQ1jVznMbGy+fJm3\n" + + "3Hoelv6jWRG9iqeJZja7/1s6YC6bWymI/OY1e4wUKeNHAo+Vger7MlHV+RuabaX+\n" + + "hSJ8bJAM59NCM7AgMTQpJCncrcdLeceYniGy5Q/qt2b5mJkQVkIdy4TPGGB+AXDJ\n" + + "D0q3I/JDRkDUFNFdeW0js7fHdsvCR7O3tJy5zIgEV/o/BCkmJVtuwPYOrw/yOlKj\n" + + "TY/U7ATAx9VFF6/vYEOMYSmrZlFX+98L6nJtwDqfLB5VTltqZ4H/KBxGE3IRSt9l\n" + + "FXy40U+LnXzhhW+7VBAvyYX8GEXhHkKU8Gqk1xitrqfBXY74xKgyUSTolFSfFVgj\n" + + "mcM/X4K45bka+qpkj7Kfv/8D4j6aZekwhN2ly6hhC1SmQ8qjMjpG/mrWOSSHZFmf\n" + + "ybu9iD2AYHeIOkshIl6xYIa++Q/00/vs46IzAbQyriOi0XxlSMMVtPx0Q3isp+ji\n" + + "n8Mq9eOuxYOEQ4of8twUkUDd528iwGtEdwf0Q01UyT84S62N8AySl1ZBKXJz6W4F\n" + + "UhWfa/HQYOAPDdEjNgnVwLI23b8t0TozyCWw7q8h\n" + + "-----END CERTIFICATE-----\n", + }, +}; - _consumeUnquotedIdentifier: function(stream) { - var start = this._current; - this._current++; - while (this._current < stream.length && isAlphaNum(stream[this._current])) { - this._current++; - } - return stream.slice(start, this._current); - }, - _consumeQuotedIdentifier: function(stream) { - var start = this._current; - this._current++; - var maxLength = stream.length; - while (stream[this._current] !== "\"" && this._current < maxLength) { - // You can escape a double quote and you can escape an escape. - var current = this._current; - if (stream[current] === "\\" && (stream[current + 1] === "\\" || - stream[current + 1] === "\"")) { - current += 2; - } else { - current++; - } - this._current = current; - } - this._current++; - return JSON.parse(stream.slice(start, this._current)); - }, +/***/ }), - _consumeRawStringLiteral: function(stream) { - var start = this._current; - this._current++; - var maxLength = stream.length; - while (stream[this._current] !== "'" && this._current < maxLength) { - // You can escape a single quote and you can escape an escape. - var current = this._current; - if (stream[current] === "\\" && (stream[current + 1] === "\\" || - stream[current + 1] === "'")) { - current += 2; - } else { - current++; - } - this._current = current; - } - this._current++; - var literal = stream.slice(start + 1, this._current - 1); - return literal.replace("\\'", "'"); - }, +/***/ 97282: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - _consumeNumber: function(stream) { - var start = this._current; - this._current++; - var maxLength = stream.length; - while (isNum(stream[this._current]) && this._current < maxLength) { - this._current++; - } - var value = parseInt(stream.slice(start, this._current)); - return {type: TOK_NUMBER, value: value, start: start}; - }, +"use strict"; - _consumeLBracket: function(stream) { - var start = this._current; - this._current++; - if (stream[this._current] === "?") { - this._current++; - return {type: TOK_FILTER, value: "[?", start: start}; - } else if (stream[this._current] === "]") { - this._current++; - return {type: TOK_FLATTEN, value: "[]", start: start}; - } else { - return {type: TOK_LBRACKET, value: "[", start: start}; - } - }, +Object.defineProperty(exports, "__esModule", ({ value: true })); +const redis_errors_1 = __nccwpck_require__(81879); +class ClusterAllFailedError extends redis_errors_1.RedisError { + constructor(message, lastNodeError) { + super(message); + this.lastNodeError = lastNodeError; + Error.captureStackTrace(this, this.constructor); + } + get name() { + return this.constructor.name; + } +} +exports["default"] = ClusterAllFailedError; - _consumeOperator: function(stream) { - var start = this._current; - var startingChar = stream[start]; - this._current++; - if (startingChar === "!") { - if (stream[this._current] === "=") { - this._current++; - return {type: TOK_NE, value: "!=", start: start}; - } else { - return {type: TOK_NOT, value: "!", start: start}; - } - } else if (startingChar === "<") { - if (stream[this._current] === "=") { - this._current++; - return {type: TOK_LTE, value: "<=", start: start}; - } else { - return {type: TOK_LT, value: "<", start: start}; - } - } else if (startingChar === ">") { - if (stream[this._current] === "=") { - this._current++; - return {type: TOK_GTE, value: ">=", start: start}; - } else { - return {type: TOK_GT, value: ">", start: start}; - } - } else if (startingChar === "=") { - if (stream[this._current] === "=") { - this._current++; - return {type: TOK_EQ, value: "==", start: start}; - } - } - }, - _consumeLiteral: function(stream) { - this._current++; - var start = this._current; - var maxLength = stream.length; - var literal; - while(stream[this._current] !== "`" && this._current < maxLength) { - // You can escape a literal char or you can escape the escape. - var current = this._current; - if (stream[current] === "\\" && (stream[current + 1] === "\\" || - stream[current + 1] === "`")) { - current += 2; - } else { - current++; - } - this._current = current; - } - var literalString = trimLeft(stream.slice(start, this._current)); - literalString = literalString.replace("\\`", "`"); - if (this._looksLikeJSON(literalString)) { - literal = JSON.parse(literalString); - } else { - // Try to JSON parse it as "" - literal = JSON.parse("\"" + literalString + "\""); - } - // +1 gets us to the ending "`", +1 to move on to the next char. - this._current++; - return literal; - }, +/***/ }), - _looksLikeJSON: function(literalString) { - var startingChars = "[{\""; - var jsonLiterals = ["true", "false", "null"]; - var numberLooking = "-0123456789"; +/***/ 90735: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (literalString === "") { - return false; - } else if (startingChars.indexOf(literalString[0]) >= 0) { - return true; - } else if (jsonLiterals.indexOf(literalString) >= 0) { - return true; - } else if (numberLooking.indexOf(literalString[0]) >= 0) { - try { - JSON.parse(literalString); - return true; - } catch (ex) { - return false; - } - } else { - return false; - } - } - }; +"use strict"; - var bindingPower = {}; - bindingPower[TOK_EOF] = 0; - bindingPower[TOK_UNQUOTEDIDENTIFIER] = 0; - bindingPower[TOK_QUOTEDIDENTIFIER] = 0; - bindingPower[TOK_RBRACKET] = 0; - bindingPower[TOK_RPAREN] = 0; - bindingPower[TOK_COMMA] = 0; - bindingPower[TOK_RBRACE] = 0; - bindingPower[TOK_NUMBER] = 0; - bindingPower[TOK_CURRENT] = 0; - bindingPower[TOK_EXPREF] = 0; - bindingPower[TOK_PIPE] = 1; - bindingPower[TOK_OR] = 2; - bindingPower[TOK_AND] = 3; - bindingPower[TOK_EQ] = 5; - bindingPower[TOK_GT] = 5; - bindingPower[TOK_LT] = 5; - bindingPower[TOK_GTE] = 5; - bindingPower[TOK_LTE] = 5; - bindingPower[TOK_NE] = 5; - bindingPower[TOK_FLATTEN] = 9; - bindingPower[TOK_STAR] = 20; - bindingPower[TOK_FILTER] = 21; - bindingPower[TOK_DOT] = 40; - bindingPower[TOK_NOT] = 45; - bindingPower[TOK_LBRACE] = 50; - bindingPower[TOK_LBRACKET] = 55; - bindingPower[TOK_LPAREN] = 60; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const redis_errors_1 = __nccwpck_require__(81879); +class MaxRetriesPerRequestError extends redis_errors_1.AbortError { + constructor(maxRetriesPerRequest) { + const message = `Reached the max retries per request limit (which is ${maxRetriesPerRequest}). Refer to "maxRetriesPerRequest" option for details.`; + super(message); + Error.captureStackTrace(this, this.constructor); + } + get name() { + return this.constructor.name; + } +} +exports["default"] = MaxRetriesPerRequestError; - function Parser() { - } - Parser.prototype = { - parse: function(expression) { - this._loadTokens(expression); - this.index = 0; - var ast = this.expression(0); - if (this._lookahead(0) !== TOK_EOF) { - var t = this._lookaheadToken(0); - var error = new Error( - "Unexpected token type: " + t.type + ", value: " + t.value); - error.name = "ParserError"; - throw error; - } - return ast; - }, +/***/ }), - _loadTokens: function(expression) { - var lexer = new Lexer(); - var tokens = lexer.tokenize(expression); - tokens.push({type: TOK_EOF, value: "", start: expression.length}); - this.tokens = tokens; - }, +/***/ 23961: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - expression: function(rbp) { - var leftToken = this._lookaheadToken(0); - this._advance(); - var left = this.nud(leftToken); - var currentToken = this._lookahead(0); - while (rbp < bindingPower[currentToken]) { - this._advance(); - left = this.led(currentToken, left); - currentToken = this._lookahead(0); - } - return left; - }, +"use strict"; - _lookahead: function(number) { - return this.tokens[this.index + number].type; - }, +Object.defineProperty(exports, "__esModule", ({ value: true })); +const MaxRetriesPerRequestError_1 = __nccwpck_require__(90735); +exports.MaxRetriesPerRequestError = MaxRetriesPerRequestError_1.default; - _lookaheadToken: function(number) { - return this.tokens[this.index + number]; - }, - _advance: function() { - this.index++; - }, +/***/ }), - nud: function(token) { - var left; - var right; - var expression; - switch (token.type) { - case TOK_LITERAL: - return {type: "Literal", value: token.value}; - case TOK_UNQUOTEDIDENTIFIER: - return {type: "Field", name: token.value}; - case TOK_QUOTEDIDENTIFIER: - var node = {type: "Field", name: token.value}; - if (this._lookahead(0) === TOK_LPAREN) { - throw new Error("Quoted identifier not allowed for function names."); - } else { - return node; +/***/ 45069: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports = module.exports = __nccwpck_require__(83609)["default"]; +var redis_1 = __nccwpck_require__(83609); +exports["default"] = redis_1.default; +var cluster_1 = __nccwpck_require__(17208); +exports.Cluster = cluster_1.default; +var command_1 = __nccwpck_require__(90803); +exports.Command = command_1.default; +var ScanStream_1 = __nccwpck_require__(6134); +exports.ScanStream = ScanStream_1.default; +var pipeline_1 = __nccwpck_require__(42803); +exports.Pipeline = pipeline_1.default; +var AbstractConnector_1 = __nccwpck_require__(72712); +exports.AbstractConnector = AbstractConnector_1.default; +var SentinelConnector_1 = __nccwpck_require__(10379); +exports.SentinelConnector = SentinelConnector_1.default; +exports.SentinelIterator = SentinelConnector_1.SentinelIterator; +// No TS typings +exports.ReplyError = __nccwpck_require__(81879).ReplyError; +const PromiseContainer = __nccwpck_require__(71475); +Object.defineProperty(exports, "Promise", ({ + get() { + return PromiseContainer.get(); + }, + set(lib) { + PromiseContainer.set(lib); + }, +})); +function print(err, reply) { + if (err) { + console.log("Error: " + err); + } + else { + console.log("Reply: " + reply); + } +} +exports.print = print; + + +/***/ }), + +/***/ 42803: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const command_1 = __nccwpck_require__(90803); +const util_1 = __nccwpck_require__(73837); +const standard_as_callback_1 = __nccwpck_require__(91543); +const redis_commands_1 = __nccwpck_require__(98020); +const calculateSlot = __nccwpck_require__(48481); +const pMap = __nccwpck_require__(91855); +const PromiseContainer = __nccwpck_require__(71475); +const commander_1 = __nccwpck_require__(33642); +const utils_1 = __nccwpck_require__(94832); +/* + This function derives from the cluster-key-slot implementation. + Instead of checking that all keys have the same slot, it checks that all slots are served by the same set of nodes. + If this is satisfied, it returns the first key's slot. +*/ +function generateMultiWithNodes(redis, keys) { + const slot = calculateSlot(keys[0]); + const target = redis._groupsBySlot[slot]; + for (let i = 1; i < keys.length; i++) { + if (redis._groupsBySlot[calculateSlot(keys[i])] !== target) { + return -1; + } + } + return slot; +} +function Pipeline(redis) { + commander_1.default.call(this); + this.redis = redis; + this.isCluster = + this.redis.constructor.name === "Cluster" || this.redis.isCluster; + this.isPipeline = true; + this.options = redis.options; + this._queue = []; + this._result = []; + this._transactions = 0; + this._shaToScript = {}; + Object.keys(redis.scriptsSet).forEach((name) => { + const script = redis.scriptsSet[name]; + this._shaToScript[script.sha] = script; + this[name] = redis[name]; + this[name + "Buffer"] = redis[name + "Buffer"]; + }); + redis.addedBuiltinSet.forEach((name) => { + this[name] = redis[name]; + this[name + "Buffer"] = redis[name + "Buffer"]; + }); + const Promise = PromiseContainer.get(); + this.promise = new Promise((resolve, reject) => { + this.resolve = resolve; + this.reject = reject; + }); + const _this = this; + Object.defineProperty(this, "length", { + get: function () { + return _this._queue.length; + }, + }); +} +exports["default"] = Pipeline; +Object.assign(Pipeline.prototype, commander_1.default.prototype); +Pipeline.prototype.fillResult = function (value, position) { + if (this._queue[position].name === "exec" && Array.isArray(value[1])) { + const execLength = value[1].length; + for (let i = 0; i < execLength; i++) { + if (value[1][i] instanceof Error) { + continue; + } + const cmd = this._queue[position - (execLength - i)]; + try { + value[1][i] = cmd.transformReply(value[1][i]); + } + catch (err) { + value[1][i] = err; + } + } + } + this._result[position] = value; + if (--this.replyPending) { + return; + } + if (this.isCluster) { + let retriable = true; + let commonError; + for (let i = 0; i < this._result.length; ++i) { + const error = this._result[i][0]; + const command = this._queue[i]; + if (error) { + if (command.name === "exec" && + error.message === + "EXECABORT Transaction discarded because of previous errors.") { + continue; + } + if (!commonError) { + commonError = { + name: error.name, + message: error.message, + }; + } + else if (commonError.name !== error.name || + commonError.message !== error.message) { + retriable = false; + break; + } + } + else if (!command.inTransaction) { + const isReadOnly = redis_commands_1.exists(command.name) && redis_commands_1.hasFlag(command.name, "readonly"); + if (!isReadOnly) { + retriable = false; + break; + } + } + } + if (commonError && retriable) { + const _this = this; + const errv = commonError.message.split(" "); + const queue = this._queue; + let inTransaction = false; + this._queue = []; + for (let i = 0; i < queue.length; ++i) { + if (errv[0] === "ASK" && + !inTransaction && + queue[i].name !== "asking" && + (!queue[i - 1] || queue[i - 1].name !== "asking")) { + const asking = new command_1.default("asking"); + asking.ignore = true; + this.sendCommand(asking); + } + queue[i].initPromise(); + this.sendCommand(queue[i]); + inTransaction = queue[i].inTransaction; + } + let matched = true; + if (typeof this.leftRedirections === "undefined") { + this.leftRedirections = {}; + } + const exec = function () { + _this.exec(); + }; + this.redis.handleError(commonError, this.leftRedirections, { + moved: function (slot, key) { + _this.preferKey = key; + _this.redis.slots[errv[1]] = [key]; + _this.redis._groupsBySlot[errv[1]] = + _this.redis._groupsIds[_this.redis.slots[errv[1]].join(";")]; + _this.redis.refreshSlotsCache(); + _this.exec(); + }, + ask: function (slot, key) { + _this.preferKey = key; + _this.exec(); + }, + tryagain: exec, + clusterDown: exec, + connectionClosed: exec, + maxRedirections: () => { + matched = false; + }, + defaults: () => { + matched = false; + }, + }); + if (matched) { + return; } - break; - case TOK_NOT: - right = this.expression(bindingPower.Not); - return {type: "NotExpression", children: [right]}; - case TOK_STAR: - left = {type: "Identity"}; - right = null; - if (this._lookahead(0) === TOK_RBRACKET) { - // This can happen in a multiselect, - // [a, b, *] - right = {type: "Identity"}; - } else { - right = this._parseProjectionRHS(bindingPower.Star); + } + } + let ignoredCount = 0; + for (let i = 0; i < this._queue.length - ignoredCount; ++i) { + if (this._queue[i + ignoredCount].ignore) { + ignoredCount += 1; + } + this._result[i] = this._result[i + ignoredCount]; + } + this.resolve(this._result.slice(0, this._result.length - ignoredCount)); +}; +Pipeline.prototype.sendCommand = function (command) { + if (this._transactions > 0) { + command.inTransaction = true; + } + const position = this._queue.length; + command.pipelineIndex = position; + command.promise + .then((result) => { + this.fillResult([null, result], position); + }) + .catch((error) => { + this.fillResult([error], position); + }); + this._queue.push(command); + return this; +}; +Pipeline.prototype.addBatch = function (commands) { + let command, commandName, args; + for (let i = 0; i < commands.length; ++i) { + command = commands[i]; + commandName = command[0]; + args = command.slice(1); + this[commandName].apply(this, args); + } + return this; +}; +const multi = Pipeline.prototype.multi; +Pipeline.prototype.multi = function () { + this._transactions += 1; + return multi.apply(this, arguments); +}; +const execBuffer = Pipeline.prototype.execBuffer; +const exec = Pipeline.prototype.exec; +Pipeline.prototype.execBuffer = util_1.deprecate(function () { + if (this._transactions > 0) { + this._transactions -= 1; + } + return execBuffer.apply(this, arguments); +}, "Pipeline#execBuffer: Use Pipeline#exec instead"); +// NOTE: To avoid an unhandled promise rejection, this will unconditionally always return this.promise, +// which always has the rejection handled by standard-as-callback +// adding the provided rejection callback. +// +// If a different promise instance were returned, that promise would cause its own unhandled promise rejection +// errors, even if that promise unconditionally resolved to **the resolved value of** this.promise. +Pipeline.prototype.exec = function (callback) { + // Wait for the cluster to be connected, since we need nodes information before continuing + if (this.isCluster && !this.redis.slots.length) { + if (this.redis.status === "wait") + this.redis.connect().catch(utils_1.noop); + this.redis.delayUntilReady((err) => { + if (err) { + callback(err); + return; } - return {type: "ValueProjection", children: [left, right]}; - case TOK_FILTER: - return this.led(token.type, {type: "Identity"}); - case TOK_LBRACE: - return this._parseMultiselectHash(); - case TOK_FLATTEN: - left = {type: TOK_FLATTEN, children: [{type: "Identity"}]}; - right = this._parseProjectionRHS(bindingPower.Flatten); - return {type: "Projection", children: [left, right]}; - case TOK_LBRACKET: - if (this._lookahead(0) === TOK_NUMBER || this._lookahead(0) === TOK_COLON) { - right = this._parseIndexExpression(); - return this._projectIfSlice({type: "Identity"}, right); - } else if (this._lookahead(0) === TOK_STAR && - this._lookahead(1) === TOK_RBRACKET) { - this._advance(); - this._advance(); - right = this._parseProjectionRHS(bindingPower.Star); - return {type: "Projection", - children: [{type: "Identity"}, right]}; - } else { - return this._parseMultiselectList(); + this.exec(callback); + }); + return this.promise; + } + if (this._transactions > 0) { + this._transactions -= 1; + return (this.options.dropBufferSupport ? exec : execBuffer).apply(this, arguments); + } + if (!this.nodeifiedPromise) { + this.nodeifiedPromise = true; + standard_as_callback_1.default(this.promise, callback); + } + if (!this._queue.length) { + this.resolve([]); + } + let pipelineSlot; + if (this.isCluster) { + // List of the first key for each command + const sampleKeys = []; + for (let i = 0; i < this._queue.length; i++) { + const keys = this._queue[i].getKeys(); + if (keys.length) { + sampleKeys.push(keys[0]); } - break; - case TOK_CURRENT: - return {type: TOK_CURRENT}; - case TOK_EXPREF: - expression = this.expression(bindingPower.Expref); - return {type: "ExpressionReference", children: [expression]}; - case TOK_LPAREN: - var args = []; - while (this._lookahead(0) !== TOK_RPAREN) { - if (this._lookahead(0) === TOK_CURRENT) { - expression = {type: TOK_CURRENT}; - this._advance(); - } else { - expression = this.expression(0); - } - args.push(expression); + // For each command, check that the keys belong to the same slot + if (keys.length && calculateSlot.generateMulti(keys) < 0) { + this.reject(new Error("All the keys in a pipeline command should belong to the same slot")); + return this.promise; } - this._match(TOK_RPAREN); - return args[0]; - default: - this._errorToken(token); } - }, - - led: function(tokenName, left) { - var right; - switch(tokenName) { - case TOK_DOT: - var rbp = bindingPower.Dot; - if (this._lookahead(0) !== TOK_STAR) { - right = this._parseDotRHS(rbp); - return {type: "Subexpression", children: [left, right]}; - } else { - // Creating a projection. - this._advance(); - right = this._parseProjectionRHS(rbp); - return {type: "ValueProjection", children: [left, right]}; - } - break; - case TOK_PIPE: - right = this.expression(bindingPower.Pipe); - return {type: TOK_PIPE, children: [left, right]}; - case TOK_OR: - right = this.expression(bindingPower.Or); - return {type: "OrExpression", children: [left, right]}; - case TOK_AND: - right = this.expression(bindingPower.And); - return {type: "AndExpression", children: [left, right]}; - case TOK_LPAREN: - var name = left.name; - var args = []; - var expression, node; - while (this._lookahead(0) !== TOK_RPAREN) { - if (this._lookahead(0) === TOK_CURRENT) { - expression = {type: TOK_CURRENT}; - this._advance(); - } else { - expression = this.expression(0); - } - if (this._lookahead(0) === TOK_COMMA) { - this._match(TOK_COMMA); - } - args.push(expression); + if (sampleKeys.length) { + pipelineSlot = generateMultiWithNodes(this.redis, sampleKeys); + if (pipelineSlot < 0) { + this.reject(new Error("All keys in the pipeline should belong to the same slots allocation group")); + return this.promise; } - this._match(TOK_RPAREN); - node = {type: "Function", name: name, children: args}; - return node; - case TOK_FILTER: - var condition = this.expression(0); - this._match(TOK_RBRACKET); - if (this._lookahead(0) === TOK_FLATTEN) { - right = {type: "Identity"}; - } else { - right = this._parseProjectionRHS(bindingPower.Filter); + } + else { + // Send the pipeline to a random node + pipelineSlot = (Math.random() * 16384) | 0; + } + } + // Check whether scripts exists + const scripts = []; + for (let i = 0; i < this._queue.length; ++i) { + const item = this._queue[i]; + if (item.name !== "evalsha") { + continue; + } + const script = this._shaToScript[item.args[0]]; + if (!script || + this.redis._addedScriptHashes[script.sha] || + scripts.includes(script)) { + continue; + } + scripts.push(script); + } + const _this = this; + if (!scripts.length) { + return execPipeline(); + } + // In cluster mode, always load scripts before running the pipeline + if (this.isCluster) { + pMap(scripts, (script) => _this.redis.script("load", script.lua), { + concurrency: 10, + }) + .then(function () { + for (let i = 0; i < scripts.length; i++) { + _this.redis._addedScriptHashes[scripts[i].sha] = true; } - return {type: "FilterProjection", children: [left, right, condition]}; - case TOK_FLATTEN: - var leftNode = {type: TOK_FLATTEN, children: [left]}; - var rightNode = this._parseProjectionRHS(bindingPower.Flatten); - return {type: "Projection", children: [leftNode, rightNode]}; - case TOK_EQ: - case TOK_NE: - case TOK_GT: - case TOK_GTE: - case TOK_LT: - case TOK_LTE: - return this._parseComparator(left, tokenName); - case TOK_LBRACKET: - var token = this._lookaheadToken(0); - if (token.type === TOK_NUMBER || token.type === TOK_COLON) { - right = this._parseIndexExpression(); - return this._projectIfSlice(left, right); - } else { - this._match(TOK_STAR); - this._match(TOK_RBRACKET); - right = this._parseProjectionRHS(bindingPower.Star); - return {type: "Projection", children: [left, right]}; + }) + .then(execPipeline, this.reject); + return this.promise; + } + this.redis + .script("exists", scripts.map(({ sha }) => sha)) + .then(function (results) { + const pending = []; + for (let i = 0; i < results.length; ++i) { + if (!results[i]) { + pending.push(scripts[i]); } - break; - default: - this._errorToken(this._lookaheadToken(0)); } - }, + const Promise = PromiseContainer.get(); + return Promise.all(pending.map(function (script) { + return _this.redis.script("load", script.lua); + })); + }) + .then(function () { + for (let i = 0; i < scripts.length; i++) { + _this.redis._addedScriptHashes[scripts[i].sha] = true; + } + }) + .then(execPipeline, this.reject); + return this.promise; + function execPipeline() { + let data = ""; + let buffers; + let writePending = (_this.replyPending = _this._queue.length); + let node; + if (_this.isCluster) { + node = { + slot: pipelineSlot, + redis: _this.redis.connectionPool.nodes.all[_this.preferKey], + }; + } + let bufferMode = false; + const stream = { + write: function (writable) { + if (writable instanceof Buffer) { + bufferMode = true; + } + if (bufferMode) { + if (!buffers) { + buffers = []; + } + if (typeof data === "string") { + buffers.push(Buffer.from(data, "utf8")); + data = undefined; + } + buffers.push(typeof writable === "string" + ? Buffer.from(writable, "utf8") + : writable); + } + else { + data += writable; + } + if (!--writePending) { + let sendData; + if (buffers) { + sendData = Buffer.concat(buffers); + } + else { + sendData = data; + } + if (_this.isCluster) { + node.redis.stream.write(sendData); + } + else { + _this.redis.stream.write(sendData); + } + // Reset writePending for resending + writePending = _this._queue.length; + data = ""; + buffers = undefined; + bufferMode = false; + } + }, + }; + for (let i = 0; i < _this._queue.length; ++i) { + _this.redis.sendCommand(_this._queue[i], stream, node); + } + return _this.promise; + } +}; - _match: function(tokenType) { - if (this._lookahead(0) === tokenType) { - this._advance(); - } else { - var t = this._lookaheadToken(0); - var error = new Error("Expected " + tokenType + ", got: " + t.type); - error.name = "ParserError"; - throw error; - } - }, - _errorToken: function(token) { - var error = new Error("Invalid token (" + - token.type + "): \"" + - token.value + "\""); - error.name = "ParserError"; - throw error; - }, +/***/ }), +/***/ 71475: +/***/ ((__unused_webpack_module, exports) => { - _parseIndexExpression: function() { - if (this._lookahead(0) === TOK_COLON || this._lookahead(1) === TOK_COLON) { - return this._parseSliceExpression(); - } else { - var node = { - type: "Index", - value: this._lookaheadToken(0).value}; - this._advance(); - this._match(TOK_RBRACKET); - return node; - } - }, +"use strict"; - _projectIfSlice: function(left, right) { - var indexExpr = {type: "IndexExpression", children: [left, right]}; - if (right.type === "Slice") { - return { - type: "Projection", - children: [indexExpr, this._parseProjectionRHS(bindingPower.Star)] - }; - } else { - return indexExpr; - } - }, +Object.defineProperty(exports, "__esModule", ({ value: true })); +function isPromise(obj) { + return (!!obj && + (typeof obj === "object" || typeof obj === "function") && + typeof obj.then === "function"); +} +exports.isPromise = isPromise; +let promise = Promise; +function get() { + return promise; +} +exports.get = get; +function set(lib) { + if (typeof lib !== "function") { + throw new Error(`Provided Promise must be a function, got ${lib}`); + } + promise = lib; +} +exports.set = set; - _parseSliceExpression: function() { - // [start:end:step] where each part is optional, as well as the last - // colon. - var parts = [null, null, null]; - var index = 0; - var currentToken = this._lookahead(0); - while (currentToken !== TOK_RBRACKET && index < 3) { - if (currentToken === TOK_COLON) { - index++; - this._advance(); - } else if (currentToken === TOK_NUMBER) { - parts[index] = this._lookaheadToken(0).value; - this._advance(); - } else { - var t = this._lookahead(0); - var error = new Error("Syntax error, unexpected token: " + - t.value + "(" + t.type + ")"); - error.name = "Parsererror"; - throw error; - } - currentToken = this._lookahead(0); - } - this._match(TOK_RBRACKET); - return { - type: "Slice", - children: parts - }; - }, - _parseComparator: function(left, comparator) { - var right = this.expression(bindingPower[comparator]); - return {type: "Comparator", name: comparator, children: [left, right]}; - }, +/***/ }), - _parseDotRHS: function(rbp) { - var lookahead = this._lookahead(0); - var exprTokens = [TOK_UNQUOTEDIDENTIFIER, TOK_QUOTEDIDENTIFIER, TOK_STAR]; - if (exprTokens.indexOf(lookahead) >= 0) { - return this.expression(rbp); - } else if (lookahead === TOK_LBRACKET) { - this._match(TOK_LBRACKET); - return this._parseMultiselectList(); - } else if (lookahead === TOK_LBRACE) { - this._match(TOK_LBRACE); - return this._parseMultiselectHash(); - } - }, +/***/ 1422: +/***/ ((__unused_webpack_module, exports) => { - _parseProjectionRHS: function(rbp) { - var right; - if (bindingPower[this._lookahead(0)] < 10) { - right = {type: "Identity"}; - } else if (this._lookahead(0) === TOK_LBRACKET) { - right = this.expression(rbp); - } else if (this._lookahead(0) === TOK_FILTER) { - right = this.expression(rbp); - } else if (this._lookahead(0) === TOK_DOT) { - this._match(TOK_DOT); - right = this._parseDotRHS(rbp); - } else { - var t = this._lookaheadToken(0); - var error = new Error("Sytanx error, unexpected token: " + - t.value + "(" + t.type + ")"); - error.name = "ParserError"; - throw error; - } - return right; - }, +"use strict"; - _parseMultiselectList: function() { - var expressions = []; - while (this._lookahead(0) !== TOK_RBRACKET) { - var expression = this.expression(0); - expressions.push(expression); - if (this._lookahead(0) === TOK_COMMA) { - this._match(TOK_COMMA); - if (this._lookahead(0) === TOK_RBRACKET) { - throw new Error("Unexpected token Rbracket"); - } - } - } - this._match(TOK_RBRACKET); - return {type: "MultiSelectList", children: expressions}; - }, +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.DEFAULT_REDIS_OPTIONS = { + // Connection + port: 6379, + host: "localhost", + family: 4, + connectTimeout: 10000, + disconnectTimeout: 2000, + retryStrategy: function (times) { + return Math.min(times * 50, 2000); + }, + keepAlive: 0, + noDelay: true, + connectionName: null, + // Sentinel + sentinels: null, + name: null, + role: "master", + sentinelRetryStrategy: function (times) { + return Math.min(times * 10, 1000); + }, + sentinelReconnectStrategy: function () { + // This strategy only applies when sentinels are used for detecting + // a failover, not during initial master resolution. + // The deployment can still function when some of the sentinels are down + // for a long period of time, so we may not want to attempt reconnection + // very often. Therefore the default interval is fairly long (1 minute). + return 60000; + }, + natMap: null, + enableTLSForSentinelMode: false, + updateSentinels: true, + failoverDetector: false, + // Status + username: null, + password: null, + db: 0, + // Others + dropBufferSupport: false, + enableOfflineQueue: true, + enableReadyCheck: true, + autoResubscribe: true, + autoResendUnfulfilledCommands: true, + lazyConnect: false, + keyPrefix: "", + reconnectOnError: null, + readOnly: false, + stringNumbers: false, + maxRetriesPerRequest: 20, + maxLoadingRetryTime: 10000, + enableAutoPipelining: false, + autoPipeliningIgnoredCommands: [], + maxScriptsCachingTime: 60000, + sentinelMaxConnections: 10, +}; - _parseMultiselectHash: function() { - var pairs = []; - var identifierTypes = [TOK_UNQUOTEDIDENTIFIER, TOK_QUOTEDIDENTIFIER]; - var keyToken, keyName, value, node; - for (;;) { - keyToken = this._lookaheadToken(0); - if (identifierTypes.indexOf(keyToken.type) < 0) { - throw new Error("Expecting an identifier token, got: " + - keyToken.type); - } - keyName = keyToken.value; - this._advance(); - this._match(TOK_COLON); - value = this.expression(0); - node = {type: "KeyValuePair", name: keyName, value: value}; - pairs.push(node); - if (this._lookahead(0) === TOK_COMMA) { - this._match(TOK_COMMA); - } else if (this._lookahead(0) === TOK_RBRACE) { - this._match(TOK_RBRACE); - break; - } - } - return {type: "MultiSelectHash", children: pairs}; - } - }; +/***/ }), - function TreeInterpreter(runtime) { - this.runtime = runtime; - } +/***/ 74276: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - TreeInterpreter.prototype = { - search: function(node, value) { - return this.visit(node, value); - }, +"use strict"; - visit: function(node, value) { - var matched, current, result, first, second, field, left, right, collected, i; - switch (node.type) { - case "Field": - if (value === null ) { - return null; - } else if (isObject(value)) { - field = value[node.name]; - if (field === undefined) { - return null; - } else { - return field; - } - } else { - return null; - } - break; - case "Subexpression": - result = this.visit(node.children[0], value); - for (i = 1; i < node.children.length; i++) { - result = this.visit(node.children[1], result); - if (result === null) { - return null; - } - } - return result; - case "IndexExpression": - left = this.visit(node.children[0], value); - right = this.visit(node.children[1], left); - return right; - case "Index": - if (!isArray(value)) { - return null; - } - var index = node.value; - if (index < 0) { - index = value.length + index; - } - result = value[index]; - if (result === undefined) { - result = null; - } - return result; - case "Slice": - if (!isArray(value)) { - return null; - } - var sliceParams = node.children.slice(0); - var computed = this.computeSliceParams(value.length, sliceParams); - var start = computed[0]; - var stop = computed[1]; - var step = computed[2]; - result = []; - if (step > 0) { - for (i = start; i < stop; i += step) { - result.push(value[i]); - } - } else { - for (i = start; i > stop; i += step) { - result.push(value[i]); - } - } - return result; - case "Projection": - // Evaluate left child. - var base = this.visit(node.children[0], value); - if (!isArray(base)) { - return null; - } - collected = []; - for (i = 0; i < base.length; i++) { - current = this.visit(node.children[1], base[i]); - if (current !== null) { - collected.push(current); +Object.defineProperty(exports, "__esModule", ({ value: true })); +const redis_errors_1 = __nccwpck_require__(81879); +const command_1 = __nccwpck_require__(90803); +const errors_1 = __nccwpck_require__(23961); +const utils_1 = __nccwpck_require__(94832); +const DataHandler_1 = __nccwpck_require__(30545); +const debug = utils_1.Debug("connection"); +function connectHandler(self) { + return function () { + self.setStatus("connect"); + self.resetCommandQueue(); + // AUTH command should be processed before any other commands + let flushed = false; + const { connectionEpoch } = self; + if (self.condition.auth) { + self.auth(self.condition.auth, function (err) { + if (connectionEpoch !== self.connectionEpoch) { + return; } - } - return collected; - case "ValueProjection": - // Evaluate left child. - base = this.visit(node.children[0], value); - if (!isObject(base)) { - return null; - } - collected = []; - var values = objValues(base); - for (i = 0; i < values.length; i++) { - current = this.visit(node.children[1], values[i]); - if (current !== null) { - collected.push(current); + if (err) { + if (err.message.indexOf("no password is set") !== -1) { + console.warn("[WARN] Redis server does not require a password, but a password was supplied."); + } + else if (err.message.indexOf("without any password configured for the default user") !== -1) { + console.warn("[WARN] This Redis server's `default` user does not require a password, but a password was supplied"); + } + else if (err.message.indexOf("wrong number of arguments for 'auth' command") !== -1) { + console.warn(`[ERROR] The server returned "wrong number of arguments for 'auth' command". You are probably passing both username and password to Redis version 5 or below. You should only pass the 'password' option for Redis version 5 and under.`); + } + else { + flushed = true; + self.recoverFromFatalError(err, err); + } } - } - return collected; - case "FilterProjection": - base = this.visit(node.children[0], value); - if (!isArray(base)) { - return null; - } - var filtered = []; - var finalResults = []; - for (i = 0; i < base.length; i++) { - matched = this.visit(node.children[2], base[i]); - if (!isFalse(matched)) { - filtered.push(base[i]); + }); + } + if (self.condition.select) { + self.select(self.condition.select).catch((err) => { + // If the node is in cluster mode, select is disallowed. + // In this case, reconnect won't help. + self.silentEmit("error", err); + }); + } + if (!self.options.enableReadyCheck) { + exports.readyHandler(self)(); + } + /* + No need to keep the reference of DataHandler here + because we don't need to do the cleanup. + `Stream#end()` will remove all listeners for us. + */ + new DataHandler_1.default(self, { + stringNumbers: self.options.stringNumbers, + dropBufferSupport: self.options.dropBufferSupport, + }); + if (self.options.enableReadyCheck) { + self._readyCheck(function (err, info) { + if (connectionEpoch !== self.connectionEpoch) { + return; } - } - for (var j = 0; j < filtered.length; j++) { - current = this.visit(node.children[1], filtered[j]); - if (current !== null) { - finalResults.push(current); + if (err) { + if (!flushed) { + self.recoverFromFatalError(new Error("Ready check failed: " + err.message), err); + } } - } - return finalResults; - case "Comparator": - first = this.visit(node.children[0], value); - second = this.visit(node.children[1], value); - switch(node.name) { - case TOK_EQ: - result = strictDeepEqual(first, second); - break; - case TOK_NE: - result = !strictDeepEqual(first, second); - break; - case TOK_GT: - result = first > second; - break; - case TOK_GTE: - result = first >= second; - break; - case TOK_LT: - result = first < second; - break; - case TOK_LTE: - result = first <= second; - break; - default: - throw new Error("Unknown comparator: " + node.name); - } - return result; - case TOK_FLATTEN: - var original = this.visit(node.children[0], value); - if (!isArray(original)) { - return null; - } - var merged = []; - for (i = 0; i < original.length; i++) { - current = original[i]; - if (isArray(current)) { - merged.push.apply(merged, current); - } else { - merged.push(current); + else { + self.serverInfo = info; + if (self.connector.check(info)) { + exports.readyHandler(self)(); + } + else { + self.disconnect(true); + } } - } - return merged; - case "Identity": - return value; - case "MultiSelectList": - if (value === null) { - return null; - } - collected = []; - for (i = 0; i < node.children.length; i++) { - collected.push(this.visit(node.children[i], value)); - } - return collected; - case "MultiSelectHash": - if (value === null) { - return null; - } - collected = {}; - var child; - for (i = 0; i < node.children.length; i++) { - child = node.children[i]; - collected[child.name] = this.visit(child.value, value); - } - return collected; - case "OrExpression": - matched = this.visit(node.children[0], value); - if (isFalse(matched)) { - matched = this.visit(node.children[1], value); - } - return matched; - case "AndExpression": - first = this.visit(node.children[0], value); - - if (isFalse(first) === true) { - return first; - } - return this.visit(node.children[1], value); - case "NotExpression": - first = this.visit(node.children[0], value); - return isFalse(first); - case "Literal": - return node.value; - case TOK_PIPE: - left = this.visit(node.children[0], value); - return this.visit(node.children[1], left); - case TOK_CURRENT: - return value; - case "Function": - var resolvedArgs = []; - for (i = 0; i < node.children.length; i++) { - resolvedArgs.push(this.visit(node.children[i], value)); - } - return this.runtime.callFunction(node.name, resolvedArgs); - case "ExpressionReference": - var refNode = node.children[0]; - // Tag the node with a specific attribute so the type - // checker verify the type. - refNode.jmespathType = TOK_EXPREF; - return refNode; - default: - throw new Error("Unknown node type: " + node.type); - } - }, - - computeSliceParams: function(arrayLength, sliceParams) { - var start = sliceParams[0]; - var stop = sliceParams[1]; - var step = sliceParams[2]; - var computed = [null, null, null]; - if (step === null) { - step = 1; - } else if (step === 0) { - var error = new Error("Invalid slice, step cannot be 0"); - error.name = "RuntimeError"; - throw error; + }); } - var stepValueNegative = step < 0 ? true : false; - - if (start === null) { - start = stepValueNegative ? arrayLength - 1 : 0; - } else { - start = this.capSliceRange(arrayLength, start, step); + }; +} +exports.connectHandler = connectHandler; +function abortError(command) { + const err = new redis_errors_1.AbortError("Command aborted due to connection close"); + err.command = { + name: command.name, + args: command.args, + }; + return err; +} +// If a contiguous set of pipeline commands starts from index zero then they +// can be safely reattempted. If however we have a chain of pipelined commands +// starting at index 1 or more it means we received a partial response before +// the connection close and those pipelined commands must be aborted. For +// example, if the queue looks like this: [2, 3, 4, 0, 1, 2] then after +// aborting and purging we'll have a queue that looks like this: [0, 1, 2] +function abortIncompletePipelines(commandQueue) { + let expectedIndex = 0; + for (let i = 0; i < commandQueue.length;) { + const command = commandQueue.peekAt(i).command; + const pipelineIndex = command.pipelineIndex; + if (pipelineIndex === undefined || pipelineIndex === 0) { + expectedIndex = 0; } - - if (stop === null) { - stop = stepValueNegative ? -1 : arrayLength; - } else { - stop = this.capSliceRange(arrayLength, stop, step); + if (pipelineIndex !== undefined && pipelineIndex !== expectedIndex++) { + commandQueue.remove(i, 1); + command.reject(abortError(command)); + continue; } - computed[0] = start; - computed[1] = stop; - computed[2] = step; - return computed; - }, - - capSliceRange: function(arrayLength, actualValue, step) { - if (actualValue < 0) { - actualValue += arrayLength; - if (actualValue < 0) { - actualValue = step < 0 ? -1 : 0; - } - } else if (actualValue >= arrayLength) { - actualValue = step < 0 ? arrayLength - 1 : arrayLength; - } - return actualValue; - } - - }; - - function Runtime(interpreter) { - this._interpreter = interpreter; - this.functionTable = { - // name: [function, ] - // The can be: - // - // { - // args: [[type1, type2], [type1, type2]], - // variadic: true|false - // } - // - // Each arg in the arg list is a list of valid types - // (if the function is overloaded and supports multiple - // types. If the type is "any" then no type checking - // occurs on the argument. Variadic is optional - // and if not provided is assumed to be false. - abs: {_func: this._functionAbs, _signature: [{types: [TYPE_NUMBER]}]}, - avg: {_func: this._functionAvg, _signature: [{types: [TYPE_ARRAY_NUMBER]}]}, - ceil: {_func: this._functionCeil, _signature: [{types: [TYPE_NUMBER]}]}, - contains: { - _func: this._functionContains, - _signature: [{types: [TYPE_STRING, TYPE_ARRAY]}, - {types: [TYPE_ANY]}]}, - "ends_with": { - _func: this._functionEndsWith, - _signature: [{types: [TYPE_STRING]}, {types: [TYPE_STRING]}]}, - floor: {_func: this._functionFloor, _signature: [{types: [TYPE_NUMBER]}]}, - length: { - _func: this._functionLength, - _signature: [{types: [TYPE_STRING, TYPE_ARRAY, TYPE_OBJECT]}]}, - map: { - _func: this._functionMap, - _signature: [{types: [TYPE_EXPREF]}, {types: [TYPE_ARRAY]}]}, - max: { - _func: this._functionMax, - _signature: [{types: [TYPE_ARRAY_NUMBER, TYPE_ARRAY_STRING]}]}, - "merge": { - _func: this._functionMerge, - _signature: [{types: [TYPE_OBJECT], variadic: true}] - }, - "max_by": { - _func: this._functionMaxBy, - _signature: [{types: [TYPE_ARRAY]}, {types: [TYPE_EXPREF]}] - }, - sum: {_func: this._functionSum, _signature: [{types: [TYPE_ARRAY_NUMBER]}]}, - "starts_with": { - _func: this._functionStartsWith, - _signature: [{types: [TYPE_STRING]}, {types: [TYPE_STRING]}]}, - min: { - _func: this._functionMin, - _signature: [{types: [TYPE_ARRAY_NUMBER, TYPE_ARRAY_STRING]}]}, - "min_by": { - _func: this._functionMinBy, - _signature: [{types: [TYPE_ARRAY]}, {types: [TYPE_EXPREF]}] - }, - type: {_func: this._functionType, _signature: [{types: [TYPE_ANY]}]}, - keys: {_func: this._functionKeys, _signature: [{types: [TYPE_OBJECT]}]}, - values: {_func: this._functionValues, _signature: [{types: [TYPE_OBJECT]}]}, - sort: {_func: this._functionSort, _signature: [{types: [TYPE_ARRAY_STRING, TYPE_ARRAY_NUMBER]}]}, - "sort_by": { - _func: this._functionSortBy, - _signature: [{types: [TYPE_ARRAY]}, {types: [TYPE_EXPREF]}] - }, - join: { - _func: this._functionJoin, - _signature: [ - {types: [TYPE_STRING]}, - {types: [TYPE_ARRAY_STRING]} - ] - }, - reverse: { - _func: this._functionReverse, - _signature: [{types: [TYPE_STRING, TYPE_ARRAY]}]}, - "to_array": {_func: this._functionToArray, _signature: [{types: [TYPE_ANY]}]}, - "to_string": {_func: this._functionToString, _signature: [{types: [TYPE_ANY]}]}, - "to_number": {_func: this._functionToNumber, _signature: [{types: [TYPE_ANY]}]}, - "not_null": { - _func: this._functionNotNull, - _signature: [{types: [TYPE_ANY], variadic: true}] + i++; + } +} +// If only a partial transaction result was received before connection close, +// we have to abort any transaction fragments that may have ended up in the +// offline queue +function abortTransactionFragments(commandQueue) { + for (let i = 0; i < commandQueue.length;) { + const command = commandQueue.peekAt(i).command; + if (command.name === "multi") { + break; } - }; - } - - Runtime.prototype = { - callFunction: function(name, resolvedArgs) { - var functionEntry = this.functionTable[name]; - if (functionEntry === undefined) { - throw new Error("Unknown function: " + name + "()"); - } - this._validateArgs(name, resolvedArgs, functionEntry._signature); - return functionEntry._func.call(this, resolvedArgs); - }, - - _validateArgs: function(name, args, signature) { - // Validating the args requires validating - // the correct arity and the correct type of each arg. - // If the last argument is declared as variadic, then we need - // a minimum number of args to be required. Otherwise it has to - // be an exact amount. - var pluralized; - if (signature[signature.length - 1].variadic) { - if (args.length < signature.length) { - pluralized = signature.length === 1 ? " argument" : " arguments"; - throw new Error("ArgumentError: " + name + "() " + - "takes at least" + signature.length + pluralized + - " but received " + args.length); - } - } else if (args.length !== signature.length) { - pluralized = signature.length === 1 ? " argument" : " arguments"; - throw new Error("ArgumentError: " + name + "() " + - "takes " + signature.length + pluralized + - " but received " + args.length); + if (command.name === "exec") { + commandQueue.remove(i, 1); + command.reject(abortError(command)); + break; } - var currentSpec; - var actualType; - var typeMatched; - for (var i = 0; i < signature.length; i++) { - typeMatched = false; - currentSpec = signature[i].types; - actualType = this._getTypeName(args[i]); - for (var j = 0; j < currentSpec.length; j++) { - if (this._typeMatches(actualType, currentSpec[j], args[i])) { - typeMatched = true; - break; - } + if (command.inTransaction) { + commandQueue.remove(i, 1); + command.reject(abortError(command)); + } + else { + i++; + } + } +} +function closeHandler(self) { + return function () { + self.setStatus("close"); + if (!self.prevCondition) { + self.prevCondition = self.condition; + } + if (self.commandQueue.length) { + abortIncompletePipelines(self.commandQueue); + self.prevCommandQueue = self.commandQueue; + } + if (self.offlineQueue.length) { + abortTransactionFragments(self.offlineQueue); + } + if (self.manuallyClosing) { + self.manuallyClosing = false; + debug("skip reconnecting since the connection is manually closed."); + return close(); + } + if (typeof self.options.retryStrategy !== "function") { + debug("skip reconnecting because `retryStrategy` is not a function"); + return close(); + } + const retryDelay = self.options.retryStrategy(++self.retryAttempts); + if (typeof retryDelay !== "number") { + debug("skip reconnecting because `retryStrategy` doesn't return a number"); + return close(); + } + debug("reconnect in %sms", retryDelay); + self.setStatus("reconnecting", retryDelay); + self.reconnectTimeout = setTimeout(function () { + self.reconnectTimeout = null; + self.connect().catch(utils_1.noop); + }, retryDelay); + const { maxRetriesPerRequest } = self.options; + if (typeof maxRetriesPerRequest === "number") { + if (maxRetriesPerRequest < 0) { + debug("maxRetriesPerRequest is negative, ignoring..."); } - if (!typeMatched) { - throw new Error("TypeError: " + name + "() " + - "expected argument " + (i + 1) + - " to be type " + currentSpec + - " but received type " + actualType + - " instead."); + else { + const remainder = self.retryAttempts % (maxRetriesPerRequest + 1); + if (remainder === 0) { + debug("reach maxRetriesPerRequest limitation, flushing command queue..."); + self.flushQueue(new errors_1.MaxRetriesPerRequestError(maxRetriesPerRequest)); + } } } - }, - - _typeMatches: function(actual, expected, argValue) { - if (expected === TYPE_ANY) { - return true; + }; + function close() { + self.setStatus("end"); + self.flushQueue(new Error(utils_1.CONNECTION_CLOSED_ERROR_MSG)); + } +} +exports.closeHandler = closeHandler; +function errorHandler(self) { + return function (error) { + debug("error: %s", error); + self.silentEmit("error", error); + }; +} +exports.errorHandler = errorHandler; +function readyHandler(self) { + return function () { + self.setStatus("ready"); + self.retryAttempts = 0; + if (self.options.monitor) { + self.call("monitor"); + const { sendCommand } = self; + self.sendCommand = function (command) { + if (command_1.default.checkFlag("VALID_IN_MONITOR_MODE", command.name)) { + return sendCommand.call(self, command); + } + command.reject(new Error("Connection is in monitoring mode, can't process commands.")); + return command.promise; + }; + self.once("close", function () { + delete self.sendCommand; + }); + self.setStatus("monitoring"); + return; } - if (expected === TYPE_ARRAY_STRING || - expected === TYPE_ARRAY_NUMBER || - expected === TYPE_ARRAY) { - // The expected type can either just be array, - // or it can require a specific subtype (array of numbers). - // - // The simplest case is if "array" with no subtype is specified. - if (expected === TYPE_ARRAY) { - return actual === TYPE_ARRAY; - } else if (actual === TYPE_ARRAY) { - // Otherwise we need to check subtypes. - // I think this has potential to be improved. - var subtype; - if (expected === TYPE_ARRAY_NUMBER) { - subtype = TYPE_NUMBER; - } else if (expected === TYPE_ARRAY_STRING) { - subtype = TYPE_STRING; + const finalSelect = self.prevCondition + ? self.prevCondition.select + : self.condition.select; + if (self.options.connectionName) { + debug("set the connection name [%s]", self.options.connectionName); + self.client("setname", self.options.connectionName).catch(utils_1.noop); + } + if (self.options.readOnly) { + debug("set the connection to readonly mode"); + self.readonly().catch(utils_1.noop); + } + if (self.prevCondition) { + const condition = self.prevCondition; + self.prevCondition = null; + if (condition.subscriber && self.options.autoResubscribe) { + // We re-select the previous db first since + // `SELECT` command is not valid in sub mode. + if (self.condition.select !== finalSelect) { + debug("connect to db [%d]", finalSelect); + self.select(finalSelect); } - for (var i = 0; i < argValue.length; i++) { - if (!this._typeMatches( - this._getTypeName(argValue[i]), subtype, - argValue[i])) { - return false; + const subscribeChannels = condition.subscriber.channels("subscribe"); + if (subscribeChannels.length) { + debug("subscribe %d channels", subscribeChannels.length); + self.subscribe(subscribeChannels); + } + const psubscribeChannels = condition.subscriber.channels("psubscribe"); + if (psubscribeChannels.length) { + debug("psubscribe %d channels", psubscribeChannels.length); + self.psubscribe(psubscribeChannels); + } + } + } + if (self.prevCommandQueue) { + if (self.options.autoResendUnfulfilledCommands) { + debug("resend %d unfulfilled commands", self.prevCommandQueue.length); + while (self.prevCommandQueue.length > 0) { + const item = self.prevCommandQueue.shift(); + if (item.select !== self.condition.select && + item.command.name !== "select") { + self.select(item.select); } + self.sendCommand(item.command, item.stream); } - return true; } - } else { - return actual === expected; + else { + self.prevCommandQueue = null; + } } - }, - _getTypeName: function(obj) { - switch (Object.prototype.toString.call(obj)) { - case "[object String]": - return TYPE_STRING; - case "[object Number]": - return TYPE_NUMBER; - case "[object Array]": - return TYPE_ARRAY; - case "[object Boolean]": - return TYPE_BOOLEAN; - case "[object Null]": - return TYPE_NULL; - case "[object Object]": - // Check if it's an expref. If it has, it's been - // tagged with a jmespathType attr of 'Expref'; - if (obj.jmespathType === TOK_EXPREF) { - return TYPE_EXPREF; - } else { - return TYPE_OBJECT; - } + if (self.offlineQueue.length) { + debug("send %d commands in offline queue", self.offlineQueue.length); + const offlineQueue = self.offlineQueue; + self.resetOfflineQueue(); + while (offlineQueue.length > 0) { + const item = offlineQueue.shift(); + if (item.select !== self.condition.select && + item.command.name !== "select") { + self.select(item.select); + } + self.sendCommand(item.command, item.stream); + } } - }, - - _functionStartsWith: function(resolvedArgs) { - return resolvedArgs[0].lastIndexOf(resolvedArgs[1]) === 0; - }, - - _functionEndsWith: function(resolvedArgs) { - var searchStr = resolvedArgs[0]; - var suffix = resolvedArgs[1]; - return searchStr.indexOf(suffix, searchStr.length - suffix.length) !== -1; - }, - - _functionReverse: function(resolvedArgs) { - var typeName = this._getTypeName(resolvedArgs[0]); - if (typeName === TYPE_STRING) { - var originalStr = resolvedArgs[0]; - var reversedStr = ""; - for (var i = originalStr.length - 1; i >= 0; i--) { - reversedStr += originalStr[i]; - } - return reversedStr; - } else { - var reversedArray = resolvedArgs[0].slice(0); - reversedArray.reverse(); - return reversedArray; + if (self.condition.select !== finalSelect) { + debug("connect to db [%d]", finalSelect); + self.select(finalSelect); } - }, - - _functionAbs: function(resolvedArgs) { - return Math.abs(resolvedArgs[0]); - }, - - _functionCeil: function(resolvedArgs) { - return Math.ceil(resolvedArgs[0]); - }, + }; +} +exports.readyHandler = readyHandler; - _functionAvg: function(resolvedArgs) { - var sum = 0; - var inputArray = resolvedArgs[0]; - for (var i = 0; i < inputArray.length; i++) { - sum += inputArray[i]; - } - return sum / inputArray.length; - }, - _functionContains: function(resolvedArgs) { - return resolvedArgs[0].indexOf(resolvedArgs[1]) >= 0; - }, +/***/ }), - _functionFloor: function(resolvedArgs) { - return Math.floor(resolvedArgs[0]); - }, +/***/ 83609: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - _functionLength: function(resolvedArgs) { - if (!isObject(resolvedArgs[0])) { - return resolvedArgs[0].length; - } else { - // As far as I can tell, there's no way to get the length - // of an object without O(n) iteration through the object. - return Object.keys(resolvedArgs[0]).length; - } - }, +"use strict"; - _functionMap: function(resolvedArgs) { - var mapped = []; - var interpreter = this._interpreter; - var exprefNode = resolvedArgs[0]; - var elements = resolvedArgs[1]; - for (var i = 0; i < elements.length; i++) { - mapped.push(interpreter.visit(exprefNode, elements[i])); - } - return mapped; - }, +Object.defineProperty(exports, "__esModule", ({ value: true })); +const lodash_1 = __nccwpck_require__(20961); +const util_1 = __nccwpck_require__(73837); +const events_1 = __nccwpck_require__(82361); +const Deque = __nccwpck_require__(42342); +const command_1 = __nccwpck_require__(90803); +const commander_1 = __nccwpck_require__(33642); +const utils_1 = __nccwpck_require__(94832); +const standard_as_callback_1 = __nccwpck_require__(91543); +const eventHandler = __nccwpck_require__(74276); +const connectors_1 = __nccwpck_require__(72340); +const ScanStream_1 = __nccwpck_require__(6134); +const commands = __nccwpck_require__(98020); +const PromiseContainer = __nccwpck_require__(71475); +const transaction_1 = __nccwpck_require__(14645); +const RedisOptions_1 = __nccwpck_require__(1422); +const debug = utils_1.Debug("redis"); +/** + * Creates a Redis instance + * + * @constructor + * @param {(number|string|Object)} [port=6379] - Port of the Redis server, + * or a URL string(see the examples below), + * or the `options` object(see the third argument). + * @param {string|Object} [host=localhost] - Host of the Redis server, + * when the first argument is a URL string, + * this argument is an object represents the options. + * @param {Object} [options] - Other options. + * @param {number} [options.port=6379] - Port of the Redis server. + * @param {string} [options.host=localhost] - Host of the Redis server. + * @param {string} [options.family=4] - Version of IP stack. Defaults to 4. + * @param {string} [options.path=null] - Local domain socket path. If set the `port`, + * `host` and `family` will be ignored. + * @param {number} [options.keepAlive=0] - TCP KeepAlive on the socket with a X ms delay before start. + * Set to a non-number value to disable keepAlive. + * @param {boolean} [options.noDelay=true] - Whether to disable the Nagle's Algorithm. By default we disable + * it to reduce the latency. + * @param {string} [options.connectionName=null] - Connection name. + * @param {number} [options.db=0] - Database index to use. + * @param {string} [options.password=null] - If set, client will send AUTH command + * with the value of this option when connected. + * @param {string} [options.username=null] - Similar to `password`, Provide this for Redis ACL support. + * @param {boolean} [options.dropBufferSupport=false] - Drop the buffer support for better performance. + * This option is recommended to be enabled when + * handling large array response and you don't need the buffer support. + * @param {boolean} [options.enableReadyCheck=true] - When a connection is established to + * the Redis server, the server might still be loading the database from disk. + * While loading, the server not respond to any commands. + * To work around this, when this option is `true`, + * ioredis will check the status of the Redis server, + * and when the Redis server is able to process commands, + * a `ready` event will be emitted. + * @param {boolean} [options.enableOfflineQueue=true] - By default, + * if there is no active connection to the Redis server, + * commands are added to a queue and are executed once the connection is "ready" + * (when `enableReadyCheck` is `true`, + * "ready" means the Redis server has loaded the database from disk, otherwise means the connection + * to the Redis server has been established). If this option is false, + * when execute the command when the connection isn't ready, an error will be returned. + * @param {number} [options.connectTimeout=10000] - The milliseconds before a timeout occurs during the initial + * connection to the Redis server. + * @param {boolean} [options.autoResubscribe=true] - After reconnected, if the previous connection was in the + * subscriber mode, client will auto re-subscribe these channels. + * @param {boolean} [options.autoResendUnfulfilledCommands=true] - If true, client will resend unfulfilled + * commands(e.g. block commands) in the previous connection when reconnected. + * @param {boolean} [options.lazyConnect=false] - By default, + * When a new `Redis` instance is created, it will connect to Redis server automatically. + * If you want to keep the instance disconnected until a command is called, you can pass the `lazyConnect` option to + * the constructor: + * + * ```javascript + * var redis = new Redis({ lazyConnect: true }); + * // No attempting to connect to the Redis server here. - _functionMerge: function(resolvedArgs) { - var merged = {}; - for (var i = 0; i < resolvedArgs.length; i++) { - var current = resolvedArgs[i]; - for (var key in current) { - merged[key] = current[key]; + * // Now let's connect to the Redis server + * redis.get('foo', function () { + * }); + * ``` + * @param {Object} [options.tls] - TLS connection support. See https://github.com/luin/ioredis#tls-options + * @param {string} [options.keyPrefix=''] - The prefix to prepend to all keys in a command. + * @param {function} [options.retryStrategy] - See "Quick Start" section + * @param {number} [options.maxRetriesPerRequest] - See "Quick Start" section + * @param {number} [options.maxLoadingRetryTime=10000] - when redis server is not ready, we will wait for + * `loading_eta_seconds` from `info` command or maxLoadingRetryTime (milliseconds), whichever is smaller. + * @param {function} [options.reconnectOnError] - See "Quick Start" section + * @param {boolean} [options.readOnly=false] - Enable READONLY mode for the connection. + * Only available for cluster mode. + * @param {boolean} [options.stringNumbers=false] - Force numbers to be always returned as JavaScript + * strings. This option is necessary when dealing with big numbers (exceed the [-2^53, +2^53] range). + * @param {boolean} [options.enableTLSForSentinelMode=false] - Whether to support the `tls` option + * when connecting to Redis via sentinel mode. + * @param {NatMap} [options.natMap=null] NAT map for sentinel connector. + * @param {boolean} [options.updateSentinels=true] - Update the given `sentinels` list with new IP + * addresses when communicating with existing sentinels. + * @param {boolean} [options.failoverDetector=false] - Detect failover actively by subscribing to the + * related channels. With this option disabled, ioredis is still able to detect failovers because Redis + * Sentinel will disconnect all clients whenever a failover happens, so ioredis will reconnect to the new + * master. This option is useful when you want to detect failover quicker, but it will create more TCP + * connections to Redis servers in order to subscribe to related channels. +* @param {boolean} [options.enableAutoPipelining=false] - When enabled, all commands issued during an event loop + * iteration are automatically wrapped in a pipeline and sent to the server at the same time. + * This can dramatically improve performance. + * @param {string[]} [options.autoPipeliningIgnoredCommands=[]] - The list of commands which must not be automatically wrapped in pipelines. + * @param {number} [options.maxScriptsCachingTime=60000] Default script definition caching time. + * @extends [EventEmitter](http://nodejs.org/api/events.html#events_class_events_eventemitter) + * @extends Commander + * @example + * ```js + * var Redis = require('ioredis'); + * + * var redis = new Redis(); + * + * var redisOnPort6380 = new Redis(6380); + * var anotherRedis = new Redis(6380, '192.168.100.1'); + * var unixSocketRedis = new Redis({ path: '/tmp/echo.sock' }); + * var unixSocketRedis2 = new Redis('/tmp/echo.sock'); + * var urlRedis = new Redis('redis://user:password@redis-service.com:6379/'); + * var urlRedis2 = new Redis('//localhost:6379'); + * var urlRedisTls = new Redis('rediss://user:password@redis-service.com:6379/'); + * var authedRedis = new Redis(6380, '192.168.100.1', { password: 'password' }); + * ``` + */ +exports["default"] = Redis; +function Redis() { + if (!(this instanceof Redis)) { + console.error(new Error("Calling `Redis()` like a function is deprecated. Using `new Redis()` instead.").stack.replace("Error", "Warning")); + return new Redis(arguments[0], arguments[1], arguments[2]); + } + this.parseOptions(arguments[0], arguments[1], arguments[2]); + events_1.EventEmitter.call(this); + commander_1.default.call(this); + this.resetCommandQueue(); + this.resetOfflineQueue(); + this.connectionEpoch = 0; + if (this.options.Connector) { + this.connector = new this.options.Connector(this.options); + } + else if (this.options.sentinels) { + const sentinelConnector = new connectors_1.SentinelConnector(this.options); + sentinelConnector.emitter = this; + this.connector = sentinelConnector; + } + else { + this.connector = new connectors_1.StandaloneConnector(this.options); + } + this.retryAttempts = 0; + // Prepare a cache of scripts and setup a interval which regularly clears it + this._addedScriptHashes = {}; + // Prepare autopipelines structures + this._autoPipelines = new Map(); + this._runningAutoPipelines = new Set(); + Object.defineProperty(this, "autoPipelineQueueSize", { + get() { + let queued = 0; + for (const pipeline of this._autoPipelines.values()) { + queued += pipeline.length; + } + return queued; + }, + }); + // end(or wait) -> connecting -> connect -> ready -> end + if (this.options.lazyConnect) { + this.setStatus("wait"); + } + else { + this.connect().catch(lodash_1.noop); + } +} +util_1.inherits(Redis, events_1.EventEmitter); +Object.assign(Redis.prototype, commander_1.default.prototype); +/** + * Create a Redis instance + * + * @deprecated + */ +// @ts-ignore +Redis.createClient = function (...args) { + // @ts-ignore + return new Redis(...args); +}; +/** + * Default options + * + * @var defaultOptions + * @private + */ +Redis.defaultOptions = RedisOptions_1.DEFAULT_REDIS_OPTIONS; +Redis.prototype.resetCommandQueue = function () { + this.commandQueue = new Deque(); +}; +Redis.prototype.resetOfflineQueue = function () { + this.offlineQueue = new Deque(); +}; +Redis.prototype.parseOptions = function () { + this.options = {}; + let isTls = false; + for (let i = 0; i < arguments.length; ++i) { + const arg = arguments[i]; + if (arg === null || typeof arg === "undefined") { + continue; } - } - return merged; - }, - - _functionMax: function(resolvedArgs) { - if (resolvedArgs[0].length > 0) { - var typeName = this._getTypeName(resolvedArgs[0][0]); - if (typeName === TYPE_NUMBER) { - return Math.max.apply(Math, resolvedArgs[0]); - } else { - var elements = resolvedArgs[0]; - var maxElement = elements[0]; - for (var i = 1; i < elements.length; i++) { - if (maxElement.localeCompare(elements[i]) < 0) { - maxElement = elements[i]; - } - } - return maxElement; + if (typeof arg === "object") { + lodash_1.defaults(this.options, arg); } - } else { - return null; - } - }, - - _functionMin: function(resolvedArgs) { - if (resolvedArgs[0].length > 0) { - var typeName = this._getTypeName(resolvedArgs[0][0]); - if (typeName === TYPE_NUMBER) { - return Math.min.apply(Math, resolvedArgs[0]); - } else { - var elements = resolvedArgs[0]; - var minElement = elements[0]; - for (var i = 1; i < elements.length; i++) { - if (elements[i].localeCompare(minElement) < 0) { - minElement = elements[i]; - } - } - return minElement; + else if (typeof arg === "string") { + lodash_1.defaults(this.options, utils_1.parseURL(arg)); + if (arg.startsWith("rediss://")) { + isTls = true; + } } - } else { - return null; - } - }, - - _functionSum: function(resolvedArgs) { - var sum = 0; - var listToSum = resolvedArgs[0]; - for (var i = 0; i < listToSum.length; i++) { - sum += listToSum[i]; - } - return sum; - }, - - _functionType: function(resolvedArgs) { - switch (this._getTypeName(resolvedArgs[0])) { - case TYPE_NUMBER: - return "number"; - case TYPE_STRING: - return "string"; - case TYPE_ARRAY: - return "array"; - case TYPE_OBJECT: - return "object"; - case TYPE_BOOLEAN: - return "boolean"; - case TYPE_EXPREF: - return "expref"; - case TYPE_NULL: - return "null"; + else if (typeof arg === "number") { + this.options.port = arg; } - }, - - _functionKeys: function(resolvedArgs) { - return Object.keys(resolvedArgs[0]); - }, - - _functionValues: function(resolvedArgs) { - var obj = resolvedArgs[0]; - var keys = Object.keys(obj); - var values = []; - for (var i = 0; i < keys.length; i++) { - values.push(obj[keys[i]]); + else { + throw new Error("Invalid argument " + arg); } - return values; - }, - - _functionJoin: function(resolvedArgs) { - var joinChar = resolvedArgs[0]; - var listJoin = resolvedArgs[1]; - return listJoin.join(joinChar); - }, - - _functionToArray: function(resolvedArgs) { - if (this._getTypeName(resolvedArgs[0]) === TYPE_ARRAY) { - return resolvedArgs[0]; - } else { - return [resolvedArgs[0]]; + } + if (isTls) { + lodash_1.defaults(this.options, { tls: true }); + } + lodash_1.defaults(this.options, Redis.defaultOptions); + if (typeof this.options.port === "string") { + this.options.port = parseInt(this.options.port, 10); + } + if (typeof this.options.db === "string") { + this.options.db = parseInt(this.options.db, 10); + } + if (this.options.parser === "hiredis") { + console.warn("Hiredis parser is abandoned since ioredis v3.0, and JavaScript parser will be used"); + } + this.options = utils_1.resolveTLSProfile(this.options); +}; +/** + * Change instance's status + * @private + */ +Redis.prototype.setStatus = function (status, arg) { + // @ts-ignore + if (debug.enabled) { + debug("status[%s]: %s -> %s", this._getDescription(), this.status || "[empty]", status); + } + this.status = status; + process.nextTick(this.emit.bind(this, status, arg)); +}; +/** + * Create a connection to Redis. + * This method will be invoked automatically when creating a new Redis instance + * unless `lazyConnect: true` is passed. + * + * When calling this method manually, a Promise is returned, which will + * be resolved when the connection status is ready. + * @param {function} [callback] + * @return {Promise} + * @public + */ +Redis.prototype.connect = function (callback) { + const _Promise = PromiseContainer.get(); + const promise = new _Promise((resolve, reject) => { + if (this.status === "connecting" || + this.status === "connect" || + this.status === "ready") { + reject(new Error("Redis is already connecting/connected")); + return; } - }, - - _functionToString: function(resolvedArgs) { - if (this._getTypeName(resolvedArgs[0]) === TYPE_STRING) { - return resolvedArgs[0]; - } else { - return JSON.stringify(resolvedArgs[0]); + // Make sure only one timer is active at a time + clearInterval(this._addedScriptHashesCleanInterval); + // Start the script cache cleaning + this._addedScriptHashesCleanInterval = setInterval(() => { + this._addedScriptHashes = {}; + }, this.options.maxScriptsCachingTime); + this.connectionEpoch += 1; + this.setStatus("connecting"); + const { options } = this; + this.condition = { + select: options.db, + auth: options.username + ? [options.username, options.password] + : options.password, + subscriber: false, + }; + const _this = this; + standard_as_callback_1.default(this.connector.connect(function (type, err) { + _this.silentEmit(type, err); + }), function (err, stream) { + if (err) { + _this.flushQueue(err); + _this.silentEmit("error", err); + reject(err); + _this.setStatus("end"); + return; + } + let CONNECT_EVENT = options.tls ? "secureConnect" : "connect"; + if (options.sentinels && !options.enableTLSForSentinelMode) { + CONNECT_EVENT = "connect"; + } + _this.stream = stream; + if (typeof options.keepAlive === "number") { + stream.setKeepAlive(true, options.keepAlive); + } + if (stream.connecting) { + stream.once(CONNECT_EVENT, eventHandler.connectHandler(_this)); + if (options.connectTimeout) { + /* + * Typically, Socket#setTimeout(0) will clear the timer + * set before. However, in some platforms (Electron 3.x~4.x), + * the timer will not be cleared. So we introduce a variable here. + * + * See https://github.com/electron/electron/issues/14915 + */ + let connectTimeoutCleared = false; + stream.setTimeout(options.connectTimeout, function () { + if (connectTimeoutCleared) { + return; + } + stream.setTimeout(0); + stream.destroy(); + const err = new Error("connect ETIMEDOUT"); + // @ts-ignore + err.errorno = "ETIMEDOUT"; + // @ts-ignore + err.code = "ETIMEDOUT"; + // @ts-ignore + err.syscall = "connect"; + eventHandler.errorHandler(_this)(err); + }); + stream.once(CONNECT_EVENT, function () { + connectTimeoutCleared = true; + stream.setTimeout(0); + }); + } + } + else if (stream.destroyed) { + const firstError = _this.connector.firstError; + if (firstError) { + process.nextTick(() => { + eventHandler.errorHandler(_this)(firstError); + }); + } + process.nextTick(eventHandler.closeHandler(_this)); + } + else { + process.nextTick(eventHandler.connectHandler(_this)); + } + if (!stream.destroyed) { + stream.once("error", eventHandler.errorHandler(_this)); + stream.once("close", eventHandler.closeHandler(_this)); + } + if (options.noDelay) { + stream.setNoDelay(true); + } + const connectionReadyHandler = function () { + _this.removeListener("close", connectionCloseHandler); + resolve(); + }; + var connectionCloseHandler = function () { + _this.removeListener("ready", connectionReadyHandler); + reject(new Error(utils_1.CONNECTION_CLOSED_ERROR_MSG)); + }; + _this.once("ready", connectionReadyHandler); + _this.once("close", connectionCloseHandler); + }); + }); + return standard_as_callback_1.default(promise, callback); +}; +/** + * Disconnect from Redis. + * + * This method closes the connection immediately, + * and may lose some pending replies that haven't written to client. + * If you want to wait for the pending replies, use Redis#quit instead. + * @public + */ +Redis.prototype.disconnect = function (reconnect) { + clearInterval(this._addedScriptHashesCleanInterval); + this._addedScriptHashesCleanInterval = null; + if (!reconnect) { + this.manuallyClosing = true; + } + if (this.reconnectTimeout && !reconnect) { + clearTimeout(this.reconnectTimeout); + this.reconnectTimeout = null; + } + if (this.status === "wait") { + eventHandler.closeHandler(this)(); + } + else { + this.connector.disconnect(); + } +}; +/** + * Disconnect from Redis. + * + * @deprecated + */ +Redis.prototype.end = function () { + this.disconnect(); +}; +/** + * Create a new instance with the same options as the current one. + * + * @example + * ```js + * var redis = new Redis(6380); + * var anotherRedis = redis.duplicate(); + * ``` + * + * @public + */ +Redis.prototype.duplicate = function (override) { + return new Redis(Object.assign({}, this.options, override || {})); +}; +Redis.prototype.recoverFromFatalError = function (commandError, err, options) { + this.flushQueue(err, options); + this.silentEmit("error", err); + this.disconnect(true); +}; +Redis.prototype.handleReconnection = function handleReconnection(err, item) { + let needReconnect = false; + if (this.options.reconnectOnError) { + needReconnect = this.options.reconnectOnError(err); + } + switch (needReconnect) { + case 1: + case true: + if (this.status !== "reconnecting") { + this.disconnect(true); + } + item.command.reject(err); + break; + case 2: + if (this.status !== "reconnecting") { + this.disconnect(true); + } + if (this.condition.select !== item.select && + item.command.name !== "select") { + this.select(item.select); + } + this.sendCommand(item.command); + break; + default: + item.command.reject(err); + } +}; +/** + * Flush offline queue and command queue with error. + * + * @param {Error} error - The error object to send to the commands + * @param {object} options + * @private + */ +Redis.prototype.flushQueue = function (error, options) { + options = lodash_1.defaults({}, options, { + offlineQueue: true, + commandQueue: true, + }); + let item; + if (options.offlineQueue) { + while (this.offlineQueue.length > 0) { + item = this.offlineQueue.shift(); + item.command.reject(error); } - }, - - _functionToNumber: function(resolvedArgs) { - var typeName = this._getTypeName(resolvedArgs[0]); - var convertedValue; - if (typeName === TYPE_NUMBER) { - return resolvedArgs[0]; - } else if (typeName === TYPE_STRING) { - convertedValue = +resolvedArgs[0]; - if (!isNaN(convertedValue)) { - return convertedValue; + } + if (options.commandQueue) { + if (this.commandQueue.length > 0) { + if (this.stream) { + this.stream.removeAllListeners("data"); + } + while (this.commandQueue.length > 0) { + item = this.commandQueue.shift(); + item.command.reject(error); } } - return null; - }, - - _functionNotNull: function(resolvedArgs) { - for (var i = 0; i < resolvedArgs.length; i++) { - if (this._getTypeName(resolvedArgs[i]) !== TYPE_NULL) { - return resolvedArgs[i]; + } +}; +/** + * Check whether Redis has finished loading the persistent data and is able to + * process commands. + * + * @param {Function} callback + * @private + */ +Redis.prototype._readyCheck = function (callback) { + const _this = this; + this.info(function (err, res) { + if (err) { + return callback(err); + } + if (typeof res !== "string") { + return callback(null, res); + } + const info = {}; + const lines = res.split("\r\n"); + for (let i = 0; i < lines.length; ++i) { + const [fieldName, ...fieldValueParts] = lines[i].split(":"); + const fieldValue = fieldValueParts.join(":"); + if (fieldValue) { + info[fieldName] = fieldValue; } } - return null; - }, - - _functionSort: function(resolvedArgs) { - var sortedArray = resolvedArgs[0].slice(0); - sortedArray.sort(); - return sortedArray; - }, - - _functionSortBy: function(resolvedArgs) { - var sortedArray = resolvedArgs[0].slice(0); - if (sortedArray.length === 0) { - return sortedArray; + if (!info.loading || info.loading === "0") { + callback(null, info); } - var interpreter = this._interpreter; - var exprefNode = resolvedArgs[1]; - var requiredType = this._getTypeName( - interpreter.visit(exprefNode, sortedArray[0])); - if ([TYPE_NUMBER, TYPE_STRING].indexOf(requiredType) < 0) { - throw new Error("TypeError"); + else { + const loadingEtaMs = (info.loading_eta_seconds || 1) * 1000; + const retryTime = _this.options.maxLoadingRetryTime && + _this.options.maxLoadingRetryTime < loadingEtaMs + ? _this.options.maxLoadingRetryTime + : loadingEtaMs; + debug("Redis server still loading, trying again in " + retryTime + "ms"); + setTimeout(function () { + _this._readyCheck(callback); + }, retryTime); } - var that = this; - // In order to get a stable sort out of an unstable - // sort algorithm, we decorate/sort/undecorate (DSU) - // by creating a new list of [index, element] pairs. - // In the cmp function, if the evaluated elements are - // equal, then the index will be used as the tiebreaker. - // After the decorated list has been sorted, it will be - // undecorated to extract the original elements. - var decorated = []; - for (var i = 0; i < sortedArray.length; i++) { - decorated.push([i, sortedArray[i]]); + }); +}; +/** + * Emit only when there's at least one listener. + * + * @param {string} eventName - Event to emit + * @param {...*} arguments - Arguments + * @return {boolean} Returns true if event had listeners, false otherwise. + * @private + */ +Redis.prototype.silentEmit = function (eventName) { + let error; + if (eventName === "error") { + error = arguments[1]; + if (this.status === "end") { + return; } - decorated.sort(function(a, b) { - var exprA = interpreter.visit(exprefNode, a[1]); - var exprB = interpreter.visit(exprefNode, b[1]); - if (that._getTypeName(exprA) !== requiredType) { - throw new Error( - "TypeError: expected " + requiredType + ", received " + - that._getTypeName(exprA)); - } else if (that._getTypeName(exprB) !== requiredType) { - throw new Error( - "TypeError: expected " + requiredType + ", received " + - that._getTypeName(exprB)); - } - if (exprA > exprB) { - return 1; - } else if (exprA < exprB) { - return -1; - } else { - // If they're equal compare the items by their - // order to maintain relative order of equal keys - // (i.e. to get a stable sort). - return a[0] - b[0]; - } + if (this.manuallyClosing) { + // ignore connection related errors when manually disconnecting + if (error instanceof Error && + (error.message === utils_1.CONNECTION_CLOSED_ERROR_MSG || + // @ts-ignore + error.syscall === "connect" || + // @ts-ignore + error.syscall === "read")) { + return; + } + } + } + if (this.listeners(eventName).length > 0) { + return this.emit.apply(this, arguments); + } + if (error && error instanceof Error) { + console.error("[ioredis] Unhandled error event:", error.stack); + } + return false; +}; +/** + * Listen for all requests received by the server in real time. + * + * This command will create a new connection to Redis and send a + * MONITOR command via the new connection in order to avoid disturbing + * the current connection. + * + * @param {function} [callback] The callback function. If omit, a promise will be returned. + * @example + * ```js + * var redis = new Redis(); + * redis.monitor(function (err, monitor) { + * // Entering monitoring mode. + * monitor.on('monitor', function (time, args, source, database) { + * console.log(time + ": " + util.inspect(args)); + * }); + * }); + * + * // supports promise as well as other commands + * redis.monitor().then(function (monitor) { + * monitor.on('monitor', function (time, args, source, database) { + * console.log(time + ": " + util.inspect(args)); + * }); + * }); + * ``` + * @public + */ +Redis.prototype.monitor = function (callback) { + const monitorInstance = this.duplicate({ + monitor: true, + lazyConnect: false, + }); + const Promise = PromiseContainer.get(); + return standard_as_callback_1.default(new Promise(function (resolve) { + monitorInstance.once("monitoring", function () { + resolve(monitorInstance); }); - // Undecorate: extract out the original list elements. - for (var j = 0; j < decorated.length; j++) { - sortedArray[j] = decorated[j][1]; + }), callback); +}; +transaction_1.addTransactionSupport(Redis.prototype); +/** + * Send a command to Redis + * + * This method is used internally by the `Redis#set`, `Redis#lpush` etc. + * Most of the time you won't invoke this method directly. + * However when you want to send a command that is not supported by ioredis yet, + * this command will be useful. + * + * @method sendCommand + * @memberOf Redis# + * @param {Command} command - The Command instance to send. + * @see {@link Command} + * @example + * ```js + * var redis = new Redis(); + * + * // Use callback + * var get = new Command('get', ['foo'], 'utf8', function (err, result) { + * console.log(result); + * }); + * redis.sendCommand(get); + * + * // Use promise + * var set = new Command('set', ['foo', 'bar'], 'utf8'); + * set.promise.then(function (result) { + * console.log(result); + * }); + * redis.sendCommand(set); + * ``` + * @private + */ +Redis.prototype.sendCommand = function (command, stream) { + if (this.status === "wait") { + this.connect().catch(lodash_1.noop); + } + if (this.status === "end") { + command.reject(new Error(utils_1.CONNECTION_CLOSED_ERROR_MSG)); + return command.promise; + } + if (this.condition.subscriber && + !command_1.default.checkFlag("VALID_IN_SUBSCRIBER_MODE", command.name)) { + command.reject(new Error("Connection in subscriber mode, only subscriber commands may be used")); + return command.promise; + } + if (typeof this.options.commandTimeout === "number") { + command.setTimeout(this.options.commandTimeout); + } + if (command.name === "quit") { + clearInterval(this._addedScriptHashesCleanInterval); + this._addedScriptHashesCleanInterval = null; + } + let writable = this.status === "ready" || + (!stream && + this.status === "connect" && + commands.exists(command.name) && + commands.hasFlag(command.name, "loading")); + if (!this.stream) { + writable = false; + } + else if (!this.stream.writable) { + writable = false; + } + else if (this.stream._writableState && this.stream._writableState.ended) { + // https://github.com/iojs/io.js/pull/1217 + writable = false; + } + if (!writable && !this.options.enableOfflineQueue) { + command.reject(new Error("Stream isn't writeable and enableOfflineQueue options is false")); + return command.promise; + } + if (!writable && command.name === "quit" && this.offlineQueue.length === 0) { + this.disconnect(); + command.resolve(Buffer.from("OK")); + return command.promise; + } + if (writable) { + // @ts-ignore + if (debug.enabled) { + debug("write command[%s]: %d -> %s(%o)", this._getDescription(), this.condition.select, command.name, command.args); } - return sortedArray; - }, - - _functionMaxBy: function(resolvedArgs) { - var exprefNode = resolvedArgs[1]; - var resolvedArray = resolvedArgs[0]; - var keyFunction = this.createKeyFunction(exprefNode, [TYPE_NUMBER, TYPE_STRING]); - var maxNumber = -Infinity; - var maxRecord; - var current; - for (var i = 0; i < resolvedArray.length; i++) { - current = keyFunction(resolvedArray[i]); - if (current > maxNumber) { - maxNumber = current; - maxRecord = resolvedArray[i]; + (stream || this.stream).write(command.toWritable()); + this.commandQueue.push({ + command: command, + stream: stream, + select: this.condition.select, + }); + if (command_1.default.checkFlag("WILL_DISCONNECT", command.name)) { + this.manuallyClosing = true; } - } - return maxRecord; - }, - - _functionMinBy: function(resolvedArgs) { - var exprefNode = resolvedArgs[1]; - var resolvedArray = resolvedArgs[0]; - var keyFunction = this.createKeyFunction(exprefNode, [TYPE_NUMBER, TYPE_STRING]); - var minNumber = Infinity; - var minRecord; - var current; - for (var i = 0; i < resolvedArray.length; i++) { - current = keyFunction(resolvedArray[i]); - if (current < minNumber) { - minNumber = current; - minRecord = resolvedArray[i]; + } + else if (this.options.enableOfflineQueue) { + // @ts-ignore + if (debug.enabled) { + debug("queue command[%s]: %d -> %s(%o)", this._getDescription(), this.condition.select, command.name, command.args); } - } - return minRecord; - }, - - createKeyFunction: function(exprefNode, allowedTypes) { - var that = this; - var interpreter = this._interpreter; - var keyFunc = function(x) { - var current = interpreter.visit(exprefNode, x); - if (allowedTypes.indexOf(that._getTypeName(current)) < 0) { - var msg = "TypeError: expected one of " + allowedTypes + - ", received " + that._getTypeName(current); - throw new Error(msg); + this.offlineQueue.push({ + command: command, + stream: stream, + select: this.condition.select, + }); + } + if (command.name === "select" && utils_1.isInt(command.args[0])) { + const db = parseInt(command.args[0], 10); + if (this.condition.select !== db) { + this.condition.select = db; + this.emit("select", db); + debug("switch to db [%d]", this.condition.select); } - return current; - }; - return keyFunc; } - - }; - - function compile(stream) { - var parser = new Parser(); - var ast = parser.parse(stream); - return ast; - } - - function tokenize(stream) { - var lexer = new Lexer(); - return lexer.tokenize(stream); - } - - function search(data, expression) { - var parser = new Parser(); - // This needs to be improved. Both the interpreter and runtime depend on - // each other. The runtime needs the interpreter to support exprefs. - // There's likely a clean way to avoid the cyclic dependency. - var runtime = new Runtime(); - var interpreter = new TreeInterpreter(runtime); - runtime._interpreter = interpreter; - var node = parser.parse(expression); - return interpreter.search(node, data); - } - - exports.tokenize = tokenize; - exports.compile = compile; - exports.search = search; - exports.strictDeepEqual = strictDeepEqual; -})( false ? 0 : exports); + return command.promise; +}; +/** + * Get description of the connection. Used for debugging. + * @private + */ +Redis.prototype._getDescription = function () { + let description; + if (this.options.path) { + description = this.options.path; + } + else if (this.stream && + this.stream.remoteAddress && + this.stream.remotePort) { + description = this.stream.remoteAddress + ":" + this.stream.remotePort; + } + else { + description = this.options.host + ":" + this.options.port; + } + if (this.options.connectionName) { + description += ` (${this.options.connectionName})`; + } + return description; +}; +[ + "scan", + "sscan", + "hscan", + "zscan", + "scanBuffer", + "sscanBuffer", + "hscanBuffer", + "zscanBuffer", +].forEach(function (command) { + Redis.prototype[command + "Stream"] = function (key, options) { + if (command === "scan" || command === "scanBuffer") { + options = key; + key = null; + } + return new ScanStream_1.default(lodash_1.defaults({ + objectMode: true, + key: key, + redis: this, + command: command, + }, options)); + }; +}); /***/ }), -/***/ 46014: +/***/ 88540: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; - -const Clone = __nccwpck_require__(85578); - -const Common = __nccwpck_require__(72448); - - -const internals = { - annotations: Symbol('annotations') -}; - - -exports.error = function (stripColorCodes) { - - if (!this._original || - typeof this._original !== 'object') { - - return this.details[0].message; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const crypto_1 = __nccwpck_require__(6113); +const promiseContainer_1 = __nccwpck_require__(71475); +const command_1 = __nccwpck_require__(90803); +const standard_as_callback_1 = __nccwpck_require__(91543); +class Script { + constructor(lua, numberOfKeys = null, keyPrefix = "", readOnly = false) { + this.lua = lua; + this.numberOfKeys = numberOfKeys; + this.keyPrefix = keyPrefix; + this.readOnly = readOnly; + this.sha = crypto_1.createHash("sha1").update(lua).digest("hex"); } - - const redFgEscape = stripColorCodes ? '' : '\u001b[31m'; - const redBgEscape = stripColorCodes ? '' : '\u001b[41m'; - const endColor = stripColorCodes ? '' : '\u001b[0m'; - - const obj = Clone(this._original); - - for (let i = this.details.length - 1; i >= 0; --i) { // Reverse order to process deepest child first - const pos = i + 1; - const error = this.details[i]; - const path = error.path; - let node = obj; - for (let j = 0; ; ++j) { - const seg = path[j]; - - if (Common.isSchema(node)) { - node = node.clone(); // joi schemas are not cloned by hoek, we have to take this extra step - } - - if (j + 1 < path.length && - typeof node[seg] !== 'string') { - - node = node[seg]; - } - else { - const refAnnotations = node[internals.annotations] || { errors: {}, missing: {} }; - node[internals.annotations] = refAnnotations; - - const cacheKey = seg || error.context.key; - - if (node[seg] !== undefined) { - refAnnotations.errors[cacheKey] = refAnnotations.errors[cacheKey] || []; - refAnnotations.errors[cacheKey].push(pos); - } - else { - refAnnotations.missing[cacheKey] = pos; + execute(container, args, options, callback) { + if (typeof this.numberOfKeys === "number") { + args.unshift(this.numberOfKeys); + } + if (this.keyPrefix) { + options.keyPrefix = this.keyPrefix; + } + if (this.readOnly) { + options.readOnly = true; + } + const evalsha = new command_1.default("evalsha", [this.sha].concat(args), options); + evalsha.isCustomCommand = true; + const result = container.sendCommand(evalsha); + if (promiseContainer_1.isPromise(result)) { + return standard_as_callback_1.default(result.catch((err) => { + if (err.toString().indexOf("NOSCRIPT") === -1) { + throw err; } - - break; - } + return container.sendCommand(new command_1.default("eval", [this.lua].concat(args), options)); + }), callback); } + // result is not a Promise--probably returned from a pipeline chain; however, + // we still need the callback to fire when the script is evaluated + standard_as_callback_1.default(evalsha.promise, callback); + return result; } - - const replacers = { - key: /_\$key\$_([, \d]+)_\$end\$_"/g, - missing: /"_\$miss\$_([^|]+)\|(\d+)_\$end\$_": "__missing__"/g, - arrayIndex: /\s*"_\$idx\$_([, \d]+)_\$end\$_",?\n(.*)/g, - specials: /"\[(NaN|Symbol.*|-?Infinity|function.*|\(.*)]"/g - }; - - let message = internals.safeStringify(obj, 2) - .replace(replacers.key, ($0, $1) => `" ${redFgEscape}[${$1}]${endColor}`) - .replace(replacers.missing, ($0, $1, $2) => `${redBgEscape}"${$1}"${endColor}${redFgEscape} [${$2}]: -- missing --${endColor}`) - .replace(replacers.arrayIndex, ($0, $1, $2) => `\n${$2} ${redFgEscape}[${$1}]${endColor}`) - .replace(replacers.specials, ($0, $1) => $1); - - message = `${message}\n${redFgEscape}`; - - for (let i = 0; i < this.details.length; ++i) { - const pos = i + 1; - message = `${message}\n[${pos}] ${this.details[i].message}`; - } - - message = message + endColor; - - return message; -}; - - -// Inspired by json-stringify-safe - -internals.safeStringify = function (obj, spaces) { - - return JSON.stringify(obj, internals.serializer(), spaces); -}; +} +exports["default"] = Script; -internals.serializer = function () { +/***/ }), - const keys = []; - const stack = []; +/***/ 14645: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - const cycleReplacer = (key, value) => { +"use strict"; - if (stack[0] === value) { - return '[Circular ~]'; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const utils_1 = __nccwpck_require__(94832); +const standard_as_callback_1 = __nccwpck_require__(91543); +const pipeline_1 = __nccwpck_require__(42803); +function addTransactionSupport(redis) { + redis.pipeline = function (commands) { + const pipeline = new pipeline_1.default(this); + if (Array.isArray(commands)) { + pipeline.addBatch(commands); } - - return '[Circular ~.' + keys.slice(0, stack.indexOf(value)).join('.') + ']'; + return pipeline; }; - - return function (key, value) { - - if (stack.length > 0) { - const thisPos = stack.indexOf(this); - if (~thisPos) { - stack.length = thisPos + 1; - keys.length = thisPos + 1; - keys[thisPos] = key; + const { multi } = redis; + redis.multi = function (commands, options) { + if (typeof options === "undefined" && !Array.isArray(commands)) { + options = commands; + commands = null; + } + if (options && options.pipeline === false) { + return multi.call(this); + } + const pipeline = new pipeline_1.default(this); + pipeline.multi(); + if (Array.isArray(commands)) { + pipeline.addBatch(commands); + } + const exec = pipeline.exec; + pipeline.exec = function (callback) { + // Wait for the cluster to be connected, since we need nodes information before continuing + if (this.isCluster && !this.redis.slots.length) { + if (this.redis.status === "wait") + this.redis.connect().catch(utils_1.noop); + return standard_as_callback_1.default(new Promise((resolve, reject) => { + this.redis.delayUntilReady((err) => { + if (err) { + reject(err); + return; + } + this.exec(pipeline).then(resolve, reject); + }); + }), callback); } - else { - stack.push(this); - keys.push(key); + if (this._transactions > 0) { + exec.call(pipeline); } - - if (~stack.indexOf(value)) { - value = cycleReplacer.call(this, key, value); + // Returns directly when the pipeline + // has been called multiple times (retries). + if (this.nodeifiedPromise) { + return exec.call(pipeline); + } + const promise = exec.call(pipeline); + return standard_as_callback_1.default(promise.then(function (result) { + const execResult = result[result.length - 1]; + if (typeof execResult === "undefined") { + throw new Error("Pipeline cannot be used to send any commands when the `exec()` has been called on it."); + } + if (execResult[0]) { + execResult[0].previousErrors = []; + for (let i = 0; i < result.length - 1; ++i) { + if (result[i][0]) { + execResult[0].previousErrors.push(result[i][0]); + } + } + throw execResult[0]; + } + return utils_1.wrapMultiResult(execResult[1]); + }), callback); + }; + const { execBuffer } = pipeline; + pipeline.execBuffer = function (callback) { + if (this._transactions > 0) { + execBuffer.call(pipeline); + } + return pipeline.exec(callback); + }; + return pipeline; + }; + const { exec } = redis; + redis.exec = function (callback) { + return standard_as_callback_1.default(exec.call(this).then(function (results) { + if (Array.isArray(results)) { + results = utils_1.wrapMultiResult(results); } - } - else { - stack.push(value); - } - - if (value) { - const annotations = value[internals.annotations]; - if (annotations) { - if (Array.isArray(value)) { - const annotated = []; + return results; + }), callback); + }; +} +exports.addTransactionSupport = addTransactionSupport; - for (let i = 0; i < value.length; ++i) { - if (annotations.errors[i]) { - annotated.push(`_$idx$_${annotations.errors[i].sort().join(', ')}_$end$_`); - } - annotated.push(value[i]); - } +/***/ }), - value = annotated; - } - else { - for (const errorKey in annotations.errors) { - value[`${errorKey}_$key$_${annotations.errors[errorKey].sort().join(', ')}_$end$_`] = value[errorKey]; - value[errorKey] = undefined; - } +/***/ 85356: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - for (const missingKey in annotations.missing) { - value[`_$miss$_${missingKey}|${annotations.missing[missingKey]}_$end$_`] = '__missing__'; - } - } +"use strict"; - return value; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const debug_1 = __nccwpck_require__(38237); +const MAX_ARGUMENT_LENGTH = 200; +exports.MAX_ARGUMENT_LENGTH = MAX_ARGUMENT_LENGTH; +const NAMESPACE_PREFIX = "ioredis"; +/** + * helper function that tried to get a string value for + * arbitrary "debug" arg + */ +function getStringValue(v) { + if (v === null) { + return; + } + switch (typeof v) { + case "boolean": + return; + case "number": + return; + case "object": + if (Buffer.isBuffer(v)) { + return v.toString("hex"); + } + if (Array.isArray(v)) { + return v.join(","); + } + try { + return JSON.stringify(v); + } + catch (e) { + return; } + case "string": + return v; + } +} +exports.getStringValue = getStringValue; +/** + * helper function that redacts a string representation of a "debug" arg + */ +function genRedactedString(str, maxLen) { + const { length } = str; + return length <= maxLen + ? str + : str.slice(0, maxLen) + ' ... '; +} +exports.genRedactedString = genRedactedString; +/** + * a wrapper for the `debug` module, used to generate + * "debug functions" that trim the values in their output + */ +function genDebugFunction(namespace) { + const fn = debug_1.default(`${NAMESPACE_PREFIX}:${namespace}`); + function wrappedDebug(...args) { + if (!fn.enabled) { + return; // no-op } - - if (value === Infinity || - value === -Infinity || - Number.isNaN(value) || - typeof value === 'function' || - typeof value === 'symbol') { - - return '[' + value.toString() + ']'; + // we skip the first arg because that is the message + for (let i = 1; i < args.length; i++) { + const str = getStringValue(args[i]); + if (typeof str === "string" && str.length > MAX_ARGUMENT_LENGTH) { + args[i] = genRedactedString(str, MAX_ARGUMENT_LENGTH); + } } - - return value; - }; -}; + return fn.apply(null, args); + } + Object.defineProperties(wrappedDebug, { + namespace: { + get() { + return fn.namespace; + }, + }, + enabled: { + get() { + return fn.enabled; + }, + }, + destroy: { + get() { + return fn.destroy; + }, + }, + log: { + get() { + return fn.log; + }, + set(l) { + fn.log = l; + }, + }, + }); + return wrappedDebug; +} +exports["default"] = genDebugFunction; /***/ }), -/***/ 95184: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 94832: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const url_1 = __nccwpck_require__(57310); +const lodash_1 = __nccwpck_require__(20961); +exports.defaults = lodash_1.defaults; +exports.noop = lodash_1.noop; +exports.flatten = lodash_1.flatten; +const debug_1 = __nccwpck_require__(85356); +exports.Debug = debug_1.default; +const TLSProfiles_1 = __nccwpck_require__(61823); +/** + * Test if two buffers are equal + * + * @export + * @param {Buffer} a + * @param {Buffer} b + * @returns {boolean} Whether the two buffers are equal + */ +function bufferEqual(a, b) { + if (typeof a.equals === "function") { + return a.equals(b); + } + if (a.length !== b.length) { + return false; + } + for (let i = 0; i < a.length; ++i) { + if (a[i] !== b[i]) { + return false; + } + } + return true; +} +exports.bufferEqual = bufferEqual; +/** + * Convert a buffer to string, supports buffer array + * + * @param {*} value - The input value + * @param {string} encoding - string encoding + * @return {*} The result + * @example + * ```js + * var input = [Buffer.from('foo'), [Buffer.from('bar')]] + * var res = convertBufferToString(input, 'utf8') + * expect(res).to.eql(['foo', ['bar']]) + * ``` + * @private + */ +function convertBufferToString(value, encoding) { + if (value instanceof Buffer) { + return value.toString(encoding); + } + if (Array.isArray(value)) { + const length = value.length; + const res = Array(length); + for (let i = 0; i < length; ++i) { + res[i] = + value[i] instanceof Buffer && encoding === "utf8" + ? value[i].toString() + : convertBufferToString(value[i], encoding); + } + return res; + } + return value; +} +exports.convertBufferToString = convertBufferToString; +/** + * Convert a list of results to node-style + * + * @param {Array} arr - The input value + * @return {Array} The output value + * @example + * ```js + * var input = ['a', 'b', new Error('c'), 'd'] + * var output = exports.wrapMultiResult(input) + * expect(output).to.eql([[null, 'a'], [null, 'b'], [new Error('c')], [null, 'd']) + * ``` + * @private + */ +function wrapMultiResult(arr) { + // When using WATCH/EXEC transactions, the EXEC will return + // a null instead of an array + if (!arr) { + return null; + } + const result = []; + const length = arr.length; + for (let i = 0; i < length; ++i) { + const item = arr[i]; + if (item instanceof Error) { + result.push([item]); + } + else { + result.push([null, item]); + } + } + return result; +} +exports.wrapMultiResult = wrapMultiResult; +/** + * Detect if the argument is a int + * + * @param {string} value + * @return {boolean} Whether the value is a int + * @example + * ```js + * > isInt('123') + * true + * > isInt('123.3') + * false + * > isInt('1x') + * false + * > isInt(123) + * true + * > isInt(true) + * false + * ``` + * @private + */ +function isInt(value) { + const x = parseFloat(value); + return !isNaN(value) && (x | 0) === x; +} +exports.isInt = isInt; +/** + * Pack an array to an Object + * + * @param {array} array + * @return {object} + * @example + * ```js + * > packObject(['a', 'b', 'c', 'd']) + * { a: 'b', c: 'd' } + * ``` + */ +function packObject(array) { + const result = {}; + const length = array.length; + for (let i = 1; i < length; i += 2) { + result[array[i - 1]] = array[i]; + } + return result; +} +exports.packObject = packObject; +/** + * Return a callback with timeout + * + * @param {function} callback + * @param {number} timeout + * @return {function} + */ +function timeout(callback, timeout) { + let timer; + const run = function () { + if (timer) { + clearTimeout(timer); + timer = null; + callback.apply(this, arguments); + } + }; + timer = setTimeout(run, timeout, new Error("timeout")); + return run; +} +exports.timeout = timeout; +/** + * Convert an object to an array + * + * @param {object} obj + * @return {array} + * @example + * ```js + * > convertObjectToArray({ a: '1' }) + * ['a', '1'] + * ``` + */ +function convertObjectToArray(obj) { + const result = []; + const keys = Object.keys(obj); // Object.entries requires node 7+ + for (let i = 0, l = keys.length; i < l; i++) { + result.push(keys[i], obj[keys[i]]); + } + return result; +} +exports.convertObjectToArray = convertObjectToArray; +/** + * Convert a map to an array + * + * @param {Map} map + * @return {array} + * @example + * ```js + * > convertMapToArray(new Map([[1, '2']])) + * [1, '2'] + * ``` + */ +function convertMapToArray(map) { + const result = []; + let pos = 0; + map.forEach(function (value, key) { + result[pos] = key; + result[pos + 1] = value; + pos += 2; + }); + return result; +} +exports.convertMapToArray = convertMapToArray; +/** + * Convert a non-string arg to a string + * + * @param {*} arg + * @return {string} + */ +function toArg(arg) { + if (arg === null || typeof arg === "undefined") { + return ""; + } + return String(arg); +} +exports.toArg = toArg; +/** + * Optimize error stack + * + * @param {Error} error - actually error + * @param {string} friendlyStack - the stack that more meaningful + * @param {string} filterPath - only show stacks with the specified path + */ +function optimizeErrorStack(error, friendlyStack, filterPath) { + const stacks = friendlyStack.split("\n"); + let lines = ""; + let i; + for (i = 1; i < stacks.length; ++i) { + if (stacks[i].indexOf(filterPath) === -1) { + break; + } + } + for (let j = i; j < stacks.length; ++j) { + lines += "\n" + stacks[j]; + } + const pos = error.stack.indexOf("\n"); + error.stack = error.stack.slice(0, pos) + lines; + return error; +} +exports.optimizeErrorStack = optimizeErrorStack; +/** + * Parse the redis protocol url + * + * @param {string} url - the redis protocol url + * @return {Object} + */ +function parseURL(url) { + if (isInt(url)) { + return { port: url }; + } + let parsed = url_1.parse(url, true, true); + if (!parsed.slashes && url[0] !== "/") { + url = "//" + url; + parsed = url_1.parse(url, true, true); + } + const options = parsed.query || {}; + const allowUsernameInURI = options.allowUsernameInURI && options.allowUsernameInURI !== "false"; + delete options.allowUsernameInURI; + const result = {}; + if (parsed.auth) { + const index = parsed.auth.indexOf(":"); + if (allowUsernameInURI) { + result.username = + index === -1 ? parsed.auth : parsed.auth.slice(0, index); + } + result.password = index === -1 ? "" : parsed.auth.slice(index + 1); + } + if (parsed.pathname) { + if (parsed.protocol === "redis:" || parsed.protocol === "rediss:") { + if (parsed.pathname.length > 1) { + result.db = parsed.pathname.slice(1); + } + } + else { + result.path = parsed.pathname; + } + } + if (parsed.host) { + result.host = parsed.hostname; + } + if (parsed.port) { + result.port = parsed.port; + } + lodash_1.defaults(result, options); + return result; +} +exports.parseURL = parseURL; +/** + * Resolve TLS profile shortcut in connection options + * + * @param {Object} options - the redis connection options + * @return {Object} + */ +function resolveTLSProfile(options) { + let tls = options === null || options === void 0 ? void 0 : options.tls; + if (typeof tls === "string") + tls = { profile: tls }; + const profile = TLSProfiles_1.default[tls === null || tls === void 0 ? void 0 : tls.profile]; + if (profile) { + tls = Object.assign({}, profile, tls); + delete tls.profile; + options = Object.assign({}, options, { tls }); + } + return options; +} +exports.resolveTLSProfile = resolveTLSProfile; +/** + * Get a random element from `array` + * + * @export + * @template T + * @param {T[]} array the array + * @param {number} [from=0] start index + * @returns {T} + */ +function sample(array, from = 0) { + const length = array.length; + if (from >= length) { + return; + } + return array[from + Math.floor(Math.random() * (length - from))]; +} +exports.sample = sample; +/** + * Shuffle the array using the Fisher-Yates Shuffle. + * This method will mutate the original array. + * + * @export + * @template T + * @param {T[]} array + * @returns {T[]} + */ +function shuffle(array) { + let counter = array.length; + // While there are elements in the array + while (counter > 0) { + // Pick a random index + const index = Math.floor(Math.random() * counter); + // Decrease counter by 1 + counter--; + // And swap the last element with it + [array[counter], array[index]] = [array[index], array[counter]]; + } + return array; +} +exports.shuffle = shuffle; +/** + * Error message for connection being disconnected + */ +exports.CONNECTION_CLOSED_ERROR_MSG = "Connection is closed."; +function zipMap(keys, values) { + const map = new Map(); + keys.forEach((key, index) => { + map.set(key, values[index]); + }); + return map; +} +exports.zipMap = zipMap; -const Assert = __nccwpck_require__(32718); -const Clone = __nccwpck_require__(85578); -const DeepEqual = __nccwpck_require__(55801); -const Merge = __nccwpck_require__(60445); - -const Cache = __nccwpck_require__(63355); -const Common = __nccwpck_require__(72448); -const Compile = __nccwpck_require__(3038); -const Errors = __nccwpck_require__(69490); -const Extend = __nccwpck_require__(86680); -const Manifest = __nccwpck_require__(87997); -const Messages = __nccwpck_require__(86103); -const Modify = __nccwpck_require__(81290); -const Ref = __nccwpck_require__(73838); -const Trace = __nccwpck_require__(43171); -const Validator = __nccwpck_require__(91804); -const Values = __nccwpck_require__(71944); - - -const internals = {}; +/***/ }), -internals.Base = class { +/***/ 20961: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - constructor(type) { +"use strict"; - // Naming: public, _private, $_extension, $_mutate{action} +Object.defineProperty(exports, "__esModule", ({ value: true })); +const defaults = __nccwpck_require__(11289); +exports.defaults = defaults; +const flatten = __nccwpck_require__(48919); +exports.flatten = flatten; +const isArguments = __nccwpck_require__(44130); +exports.isArguments = isArguments; +function noop() { } +exports.noop = noop; - this.type = type; - this.$_root = null; - this._definition = {}; - this._reset(); - } +/***/ }), - _reset() { +/***/ 37263: +/***/ (function(module, __unused_webpack_exports, __nccwpck_require__) { - this._ids = new Modify.Ids(); - this._preferences = null; - this._refs = new Ref.Manager(); - this._cache = null; +/* module decorator */ module = __nccwpck_require__.nmd(module); +(function() { + var expandIPv6, ipaddr, ipv4Part, ipv4Regexes, ipv6Part, ipv6Regexes, matchCIDR, root, zoneIndex; - this._valids = null; - this._invalids = null; + ipaddr = {}; - this._flags = {}; - this._rules = []; - this._singleRules = new Map(); // The rule options passed for non-multi rules + root = this; - this.$_terms = {}; // Hash of arrays of immutable objects (extended by other types) + if (( true && module !== null) && module.exports) { + module.exports = ipaddr; + } else { + root['ipaddr'] = ipaddr; + } - this.$_temp = { // Runtime state (not cloned) - ruleset: null, // null: use last, false: error, number: start position - whens: {} // Runtime cache of generated whens - }; + matchCIDR = function(first, second, partSize, cidrBits) { + var part, shift; + if (first.length !== second.length) { + throw new Error("ipaddr: cannot match CIDR for objects with different lengths"); } - - // Manifest - - describe() { - - Assert(typeof Manifest.describe === 'function', 'Manifest functionality disabled'); - return Manifest.describe(this); + part = 0; + while (cidrBits > 0) { + shift = partSize - cidrBits; + if (shift < 0) { + shift = 0; + } + if (first[part] >> shift !== second[part] >> shift) { + return false; + } + cidrBits -= partSize; + part += 1; } + return true; + }; - // Rules - - allow(...values) { - - Common.verifyFlat(values, 'allow'); - return this._values(values, '_valids'); + ipaddr.subnetMatch = function(address, rangeList, defaultName) { + var k, len, rangeName, rangeSubnets, subnet; + if (defaultName == null) { + defaultName = 'unicast'; } - - alter(targets) { - - Assert(targets && typeof targets === 'object' && !Array.isArray(targets), 'Invalid targets argument'); - Assert(!this._inRuleset(), 'Cannot set alterations inside a ruleset'); - - const obj = this.clone(); - obj.$_terms.alterations = obj.$_terms.alterations || []; - for (const target in targets) { - const adjuster = targets[target]; - Assert(typeof adjuster === 'function', 'Alteration adjuster for', target, 'must be a function'); - obj.$_terms.alterations.push({ target, adjuster }); + for (rangeName in rangeList) { + rangeSubnets = rangeList[rangeName]; + if (rangeSubnets[0] && !(rangeSubnets[0] instanceof Array)) { + rangeSubnets = [rangeSubnets]; + } + for (k = 0, len = rangeSubnets.length; k < len; k++) { + subnet = rangeSubnets[k]; + if (address.kind() === subnet[0].kind()) { + if (address.match.apply(address, subnet)) { + return rangeName; + } } - - obj.$_temp.ruleset = false; - return obj; + } } + return defaultName; + }; - artifact(id) { - - Assert(id !== undefined, 'Artifact cannot be undefined'); - Assert(!this._cache, 'Cannot set an artifact with a rule cache'); - - return this.$_setFlag('artifact', id); + ipaddr.IPv4 = (function() { + function IPv4(octets) { + var k, len, octet; + if (octets.length !== 4) { + throw new Error("ipaddr: ipv4 octet count should be 4"); + } + for (k = 0, len = octets.length; k < len; k++) { + octet = octets[k]; + if (!((0 <= octet && octet <= 255))) { + throw new Error("ipaddr: ipv4 octet should fit in 8 bits"); + } + } + this.octets = octets; } - cast(to) { - - Assert(to === false || typeof to === 'string', 'Invalid to value'); - Assert(to === false || this._definition.cast[to], 'Type', this.type, 'does not support casting to', to); - - return this.$_setFlag('cast', to === false ? undefined : to); - } + IPv4.prototype.kind = function() { + return 'ipv4'; + }; - default(value, options) { + IPv4.prototype.toString = function() { + return this.octets.join("."); + }; - return this._default('default', value, options); - } + IPv4.prototype.toNormalizedString = function() { + return this.toString(); + }; - description(desc) { + IPv4.prototype.toByteArray = function() { + return this.octets.slice(0); + }; - Assert(desc && typeof desc === 'string', 'Description must be a non-empty string'); + IPv4.prototype.match = function(other, cidrRange) { + var ref; + if (cidrRange === void 0) { + ref = other, other = ref[0], cidrRange = ref[1]; + } + if (other.kind() !== 'ipv4') { + throw new Error("ipaddr: cannot match ipv4 address with non-ipv4 one"); + } + return matchCIDR(this.octets, other.octets, 8, cidrRange); + }; - return this.$_setFlag('description', desc); - } + IPv4.prototype.SpecialRanges = { + unspecified: [[new IPv4([0, 0, 0, 0]), 8]], + broadcast: [[new IPv4([255, 255, 255, 255]), 32]], + multicast: [[new IPv4([224, 0, 0, 0]), 4]], + linkLocal: [[new IPv4([169, 254, 0, 0]), 16]], + loopback: [[new IPv4([127, 0, 0, 0]), 8]], + carrierGradeNat: [[new IPv4([100, 64, 0, 0]), 10]], + "private": [[new IPv4([10, 0, 0, 0]), 8], [new IPv4([172, 16, 0, 0]), 12], [new IPv4([192, 168, 0, 0]), 16]], + reserved: [[new IPv4([192, 0, 0, 0]), 24], [new IPv4([192, 0, 2, 0]), 24], [new IPv4([192, 88, 99, 0]), 24], [new IPv4([198, 51, 100, 0]), 24], [new IPv4([203, 0, 113, 0]), 24], [new IPv4([240, 0, 0, 0]), 4]] + }; - empty(schema) { + IPv4.prototype.range = function() { + return ipaddr.subnetMatch(this, this.SpecialRanges); + }; - const obj = this.clone(); + IPv4.prototype.toIPv4MappedAddress = function() { + return ipaddr.IPv6.parse("::ffff:" + (this.toString())); + }; - if (schema !== undefined) { - schema = obj.$_compile(schema, { override: false }); + IPv4.prototype.prefixLengthFromSubnetMask = function() { + var cidr, i, k, octet, stop, zeros, zerotable; + zerotable = { + 0: 8, + 128: 7, + 192: 6, + 224: 5, + 240: 4, + 248: 3, + 252: 2, + 254: 1, + 255: 0 + }; + cidr = 0; + stop = false; + for (i = k = 3; k >= 0; i = k += -1) { + octet = this.octets[i]; + if (octet in zerotable) { + zeros = zerotable[octet]; + if (stop && zeros !== 0) { + return null; + } + if (zeros !== 8) { + stop = true; + } + cidr += zeros; + } else { + return null; } + } + return 32 - cidr; + }; - return obj.$_setFlag('empty', schema, { clone: false }); - } - - error(err) { - - Assert(err, 'Missing error'); - Assert(err instanceof Error || typeof err === 'function', 'Must provide a valid Error object or a function'); - - return this.$_setFlag('error', err); - } - - example(example, options = {}) { + return IPv4; - Assert(example !== undefined, 'Missing example'); - Common.assertOptions(options, ['override']); + })(); - return this._inner('examples', example, { single: true, override: options.override }); - } + ipv4Part = "(0?\\d+|0x[a-f0-9]+)"; - external(method, description) { + ipv4Regexes = { + fourOctet: new RegExp("^" + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "$", 'i'), + longValue: new RegExp("^" + ipv4Part + "$", 'i') + }; - if (typeof method === 'object') { - Assert(!description, 'Cannot combine options with description'); - description = method.description; - method = method.method; + ipaddr.IPv4.parser = function(string) { + var match, parseIntAuto, part, shift, value; + parseIntAuto = function(string) { + if (string[0] === "0" && string[1] !== "x") { + return parseInt(string, 8); + } else { + return parseInt(string); + } + }; + if (match = string.match(ipv4Regexes.fourOctet)) { + return (function() { + var k, len, ref, results; + ref = match.slice(1, 6); + results = []; + for (k = 0, len = ref.length; k < len; k++) { + part = ref[k]; + results.push(parseIntAuto(part)); } - - Assert(typeof method === 'function', 'Method must be a function'); - Assert(description === undefined || description && typeof description === 'string', 'Description must be a non-empty string'); - - return this._inner('externals', { method, description }, { single: true }); + return results; + })(); + } else if (match = string.match(ipv4Regexes.longValue)) { + value = parseIntAuto(match[1]); + if (value > 0xffffffff || value < 0) { + throw new Error("ipaddr: address outside defined range"); + } + return ((function() { + var k, results; + results = []; + for (shift = k = 0; k <= 24; shift = k += 8) { + results.push((value >> shift) & 0xff); + } + return results; + })()).reverse(); + } else { + return null; } + }; - failover(value, options) { - - return this._default('failover', value, options); + ipaddr.IPv6 = (function() { + function IPv6(parts, zoneId) { + var i, k, l, len, part, ref; + if (parts.length === 16) { + this.parts = []; + for (i = k = 0; k <= 14; i = k += 2) { + this.parts.push((parts[i] << 8) | parts[i + 1]); + } + } else if (parts.length === 8) { + this.parts = parts; + } else { + throw new Error("ipaddr: ipv6 part count should be 8 or 16"); + } + ref = this.parts; + for (l = 0, len = ref.length; l < len; l++) { + part = ref[l]; + if (!((0 <= part && part <= 0xffff))) { + throw new Error("ipaddr: ipv6 part should fit in 16 bits"); + } + } + if (zoneId) { + this.zoneId = zoneId; + } } - forbidden() { - - return this.presence('forbidden'); - } + IPv6.prototype.kind = function() { + return 'ipv6'; + }; - id(id) { + IPv6.prototype.toString = function() { + return this.toNormalizedString().replace(/((^|:)(0(:|$))+)/, '::'); + }; - if (!id) { - return this.$_setFlag('id', undefined); + IPv6.prototype.toRFC5952String = function() { + var bestMatchIndex, bestMatchLength, match, regex, string; + regex = /((^|:)(0(:|$)){2,})/g; + string = this.toNormalizedString(); + bestMatchIndex = 0; + bestMatchLength = -1; + while ((match = regex.exec(string))) { + if (match[0].length > bestMatchLength) { + bestMatchIndex = match.index; + bestMatchLength = match[0].length; } + } + if (bestMatchLength < 0) { + return string; + } + return string.substring(0, bestMatchIndex) + '::' + string.substring(bestMatchIndex + bestMatchLength); + }; - Assert(typeof id === 'string', 'id must be a non-empty string'); - Assert(/^[^\.]+$/.test(id), 'id cannot contain period character'); - - return this.$_setFlag('id', id); - } - - invalid(...values) { - - return this._values(values, '_invalids'); - } + IPv6.prototype.toByteArray = function() { + var bytes, k, len, part, ref; + bytes = []; + ref = this.parts; + for (k = 0, len = ref.length; k < len; k++) { + part = ref[k]; + bytes.push(part >> 8); + bytes.push(part & 0xff); + } + return bytes; + }; - label(name) { + IPv6.prototype.toNormalizedString = function() { + var addr, part, suffix; + addr = ((function() { + var k, len, ref, results; + ref = this.parts; + results = []; + for (k = 0, len = ref.length; k < len; k++) { + part = ref[k]; + results.push(part.toString(16)); + } + return results; + }).call(this)).join(":"); + suffix = ''; + if (this.zoneId) { + suffix = '%' + this.zoneId; + } + return addr + suffix; + }; - Assert(name && typeof name === 'string', 'Label name must be a non-empty string'); + IPv6.prototype.toFixedLengthString = function() { + var addr, part, suffix; + addr = ((function() { + var k, len, ref, results; + ref = this.parts; + results = []; + for (k = 0, len = ref.length; k < len; k++) { + part = ref[k]; + results.push(part.toString(16).padStart(4, '0')); + } + return results; + }).call(this)).join(":"); + suffix = ''; + if (this.zoneId) { + suffix = '%' + this.zoneId; + } + return addr + suffix; + }; - return this.$_setFlag('label', name); - } + IPv6.prototype.match = function(other, cidrRange) { + var ref; + if (cidrRange === void 0) { + ref = other, other = ref[0], cidrRange = ref[1]; + } + if (other.kind() !== 'ipv6') { + throw new Error("ipaddr: cannot match ipv6 address with non-ipv6 one"); + } + return matchCIDR(this.parts, other.parts, 16, cidrRange); + }; - meta(meta) { + IPv6.prototype.SpecialRanges = { + unspecified: [new IPv6([0, 0, 0, 0, 0, 0, 0, 0]), 128], + linkLocal: [new IPv6([0xfe80, 0, 0, 0, 0, 0, 0, 0]), 10], + multicast: [new IPv6([0xff00, 0, 0, 0, 0, 0, 0, 0]), 8], + loopback: [new IPv6([0, 0, 0, 0, 0, 0, 0, 1]), 128], + uniqueLocal: [new IPv6([0xfc00, 0, 0, 0, 0, 0, 0, 0]), 7], + ipv4Mapped: [new IPv6([0, 0, 0, 0, 0, 0xffff, 0, 0]), 96], + rfc6145: [new IPv6([0, 0, 0, 0, 0xffff, 0, 0, 0]), 96], + rfc6052: [new IPv6([0x64, 0xff9b, 0, 0, 0, 0, 0, 0]), 96], + '6to4': [new IPv6([0x2002, 0, 0, 0, 0, 0, 0, 0]), 16], + teredo: [new IPv6([0x2001, 0, 0, 0, 0, 0, 0, 0]), 32], + reserved: [[new IPv6([0x2001, 0xdb8, 0, 0, 0, 0, 0, 0]), 32]] + }; - Assert(meta !== undefined, 'Meta cannot be undefined'); + IPv6.prototype.range = function() { + return ipaddr.subnetMatch(this, this.SpecialRanges); + }; - return this._inner('metas', meta, { single: true }); - } + IPv6.prototype.isIPv4MappedAddress = function() { + return this.range() === 'ipv4Mapped'; + }; - note(...notes) { + IPv6.prototype.toIPv4Address = function() { + var high, low, ref; + if (!this.isIPv4MappedAddress()) { + throw new Error("ipaddr: trying to convert a generic ipv6 address to ipv4"); + } + ref = this.parts.slice(-2), high = ref[0], low = ref[1]; + return new ipaddr.IPv4([high >> 8, high & 0xff, low >> 8, low & 0xff]); + }; - Assert(notes.length, 'Missing notes'); - for (const note of notes) { - Assert(note && typeof note === 'string', 'Notes must be non-empty strings'); + IPv6.prototype.prefixLengthFromSubnetMask = function() { + var cidr, i, k, part, stop, zeros, zerotable; + zerotable = { + 0: 16, + 32768: 15, + 49152: 14, + 57344: 13, + 61440: 12, + 63488: 11, + 64512: 10, + 65024: 9, + 65280: 8, + 65408: 7, + 65472: 6, + 65504: 5, + 65520: 4, + 65528: 3, + 65532: 2, + 65534: 1, + 65535: 0 + }; + cidr = 0; + stop = false; + for (i = k = 7; k >= 0; i = k += -1) { + part = this.parts[i]; + if (part in zerotable) { + zeros = zerotable[part]; + if (stop && zeros !== 0) { + return null; + } + if (zeros !== 16) { + stop = true; + } + cidr += zeros; + } else { + return null; } + } + return 128 - cidr; + }; - return this._inner('notes', notes); - } - - only(mode = true) { - - Assert(typeof mode === 'boolean', 'Invalid mode:', mode); - - return this.$_setFlag('only', mode); - } - - optional() { + return IPv6; - return this.presence('optional'); - } + })(); - prefs(prefs) { + ipv6Part = "(?:[0-9a-f]+::?)+"; - Assert(prefs, 'Missing preferences'); - Assert(prefs.context === undefined, 'Cannot override context'); - Assert(prefs.externals === undefined, 'Cannot override externals'); - Assert(prefs.warnings === undefined, 'Cannot override warnings'); - Assert(prefs.debug === undefined, 'Cannot override debug'); + zoneIndex = "%[0-9a-z]{1,}"; - Common.checkPreferences(prefs); + ipv6Regexes = { + zoneIndex: new RegExp(zoneIndex, 'i'), + "native": new RegExp("^(::)?(" + ipv6Part + ")?([0-9a-f]+)?(::)?(" + zoneIndex + ")?$", 'i'), + transitional: new RegExp(("^((?:" + ipv6Part + ")|(?:::)(?:" + ipv6Part + ")?)") + (ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part) + ("(" + zoneIndex + ")?$"), 'i') + }; - const obj = this.clone(); - obj._preferences = Common.preferences(obj._preferences, prefs); - return obj; + expandIPv6 = function(string, parts) { + var colonCount, lastColon, part, replacement, replacementCount, zoneId; + if (string.indexOf('::') !== string.lastIndexOf('::')) { + return null; } - - presence(mode) { - - Assert(['optional', 'required', 'forbidden'].includes(mode), 'Unknown presence mode', mode); - - return this.$_setFlag('presence', mode); + zoneId = (string.match(ipv6Regexes['zoneIndex']) || [])[0]; + if (zoneId) { + zoneId = zoneId.substring(1); + string = string.replace(/%.+$/, ''); } - - raw(enabled = true) { - - return this.$_setFlag('result', enabled ? 'raw' : undefined); + colonCount = 0; + lastColon = -1; + while ((lastColon = string.indexOf(':', lastColon + 1)) >= 0) { + colonCount++; } - - result(mode) { - - Assert(['raw', 'strip'].includes(mode), 'Unknown result mode', mode); - - return this.$_setFlag('result', mode); + if (string.substr(0, 2) === '::') { + colonCount--; } - - required() { - - return this.presence('required'); + if (string.substr(-2, 2) === '::') { + colonCount--; } - - strict(enabled) { - - const obj = this.clone(); - - const convert = enabled === undefined ? false : !enabled; - obj._preferences = Common.preferences(obj._preferences, { convert }); - return obj; + if (colonCount > parts) { + return null; } - - strip(enabled = true) { - - return this.$_setFlag('result', enabled ? 'strip' : undefined); + replacementCount = parts - colonCount; + replacement = ':'; + while (replacementCount--) { + replacement += '0:'; } + string = string.replace('::', replacement); + if (string[0] === ':') { + string = string.slice(1); + } + if (string[string.length - 1] === ':') { + string = string.slice(0, -1); + } + parts = (function() { + var k, len, ref, results; + ref = string.split(":"); + results = []; + for (k = 0, len = ref.length; k < len; k++) { + part = ref[k]; + results.push(parseInt(part, 16)); + } + return results; + })(); + return { + parts: parts, + zoneId: zoneId + }; + }; - tag(...tags) { - - Assert(tags.length, 'Missing tags'); - for (const tag of tags) { - Assert(tag && typeof tag === 'string', 'Tags must be non-empty strings'); + ipaddr.IPv6.parser = function(string) { + var addr, k, len, match, octet, octets, zoneId; + if (ipv6Regexes['native'].test(string)) { + return expandIPv6(string, 8); + } else if (match = string.match(ipv6Regexes['transitional'])) { + zoneId = match[6] || ''; + addr = expandIPv6(match[1].slice(0, -1) + zoneId, 6); + if (addr.parts) { + octets = [parseInt(match[2]), parseInt(match[3]), parseInt(match[4]), parseInt(match[5])]; + for (k = 0, len = octets.length; k < len; k++) { + octet = octets[k]; + if (!((0 <= octet && octet <= 255))) { + return null; + } } - - return this._inner('tags', tags); + addr.parts.push(octets[0] << 8 | octets[1]); + addr.parts.push(octets[2] << 8 | octets[3]); + return { + parts: addr.parts, + zoneId: addr.zoneId + }; + } } + return null; + }; - unit(name) { - - Assert(name && typeof name === 'string', 'Unit name must be a non-empty string'); + ipaddr.IPv4.isIPv4 = ipaddr.IPv6.isIPv6 = function(string) { + return this.parser(string) !== null; + }; - return this.$_setFlag('unit', name); + ipaddr.IPv4.isValid = function(string) { + var e; + try { + new this(this.parser(string)); + return true; + } catch (error1) { + e = error1; + return false; } + }; - valid(...values) { - - Common.verifyFlat(values, 'valid'); - - const obj = this.allow(...values); - obj.$_setFlag('only', !!obj._valids, { clone: false }); - return obj; + ipaddr.IPv4.isValidFourPartDecimal = function(string) { + if (ipaddr.IPv4.isValid(string) && string.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/)) { + return true; + } else { + return false; } + }; - when(condition, options) { - - const obj = this.clone(); - - if (!obj.$_terms.whens) { - obj.$_terms.whens = []; - } - - const when = Compile.when(obj, condition, options); - if (!['any', 'link'].includes(obj.type)) { - const conditions = when.is ? [when] : when.switch; - for (const item of conditions) { - Assert(!item.then || item.then.type === 'any' || item.then.type === obj.type, 'Cannot combine', obj.type, 'with', item.then && item.then.type); - Assert(!item.otherwise || item.otherwise.type === 'any' || item.otherwise.type === obj.type, 'Cannot combine', obj.type, 'with', item.otherwise && item.otherwise.type); - - } - } - - obj.$_terms.whens.push(when); - return obj.$_mutateRebuild(); + ipaddr.IPv6.isValid = function(string) { + var addr, e; + if (typeof string === "string" && string.indexOf(":") === -1) { + return false; } - - // Helpers - - cache(cache) { - - Assert(!this._inRuleset(), 'Cannot set caching inside a ruleset'); - Assert(!this._cache, 'Cannot override schema cache'); - Assert(this._flags.artifact === undefined, 'Cannot cache a rule with an artifact'); - - const obj = this.clone(); - obj._cache = cache || Cache.provider.provision(); - obj.$_temp.ruleset = false; - return obj; + try { + addr = this.parser(string); + new this(addr.parts, addr.zoneId); + return true; + } catch (error1) { + e = error1; + return false; } + }; - clone() { - - const obj = Object.create(Object.getPrototypeOf(this)); - return this._assign(obj); + ipaddr.IPv4.parse = function(string) { + var parts; + parts = this.parser(string); + if (parts === null) { + throw new Error("ipaddr: string is not formatted like ip address"); } + return new this(parts); + }; - concat(source) { - - Assert(Common.isSchema(source), 'Invalid schema object'); - Assert(this.type === 'any' || source.type === 'any' || source.type === this.type, 'Cannot merge type', this.type, 'with another type:', source.type); - Assert(!this._inRuleset(), 'Cannot concatenate onto a schema with open ruleset'); - Assert(!source._inRuleset(), 'Cannot concatenate a schema with open ruleset'); - - let obj = this.clone(); - - if (this.type === 'any' && - source.type !== 'any') { - - // Change obj to match source type - - const tmpObj = source.clone(); - for (const key of Object.keys(obj)) { - if (key !== 'type') { - tmpObj[key] = obj[key]; - } - } - - obj = tmpObj; - } - - obj._ids.concat(source._ids); - obj._refs.register(source, Ref.toSibling); - - obj._preferences = obj._preferences ? Common.preferences(obj._preferences, source._preferences) : source._preferences; - obj._valids = Values.merge(obj._valids, source._valids, source._invalids); - obj._invalids = Values.merge(obj._invalids, source._invalids, source._valids); - - // Remove unique rules present in source - - for (const name of source._singleRules.keys()) { - if (obj._singleRules.has(name)) { - obj._rules = obj._rules.filter((target) => target.keep || target.name !== name); - obj._singleRules.delete(name); - } - } - - // Rules - - for (const test of source._rules) { - if (!source._definition.rules[test.method].multi) { - obj._singleRules.set(test.name, test); - } - - obj._rules.push(test); - } - - // Flags - - if (obj._flags.empty && - source._flags.empty) { - - obj._flags.empty = obj._flags.empty.concat(source._flags.empty); - const flags = Object.assign({}, source._flags); - delete flags.empty; - Merge(obj._flags, flags); - } - else if (source._flags.empty) { - obj._flags.empty = source._flags.empty; - const flags = Object.assign({}, source._flags); - delete flags.empty; - Merge(obj._flags, flags); - } - else { - Merge(obj._flags, source._flags); - } - - // Terms - - for (const key in source.$_terms) { - const terms = source.$_terms[key]; - if (!terms) { - if (!obj.$_terms[key]) { - obj.$_terms[key] = terms; - } - - continue; - } - - if (!obj.$_terms[key]) { - obj.$_terms[key] = terms.slice(); - continue; - } - - obj.$_terms[key] = obj.$_terms[key].concat(terms); - } - - // Tracing - - if (this.$_root._tracer) { - this.$_root._tracer._combine(obj, [this, source]); - } - - // Rebuild - - return obj.$_mutateRebuild(); + ipaddr.IPv6.parse = function(string) { + var addr; + addr = this.parser(string); + if (addr.parts === null) { + throw new Error("ipaddr: string is not formatted like ip address"); } + return new this(addr.parts, addr.zoneId); + }; - extend(options) { - - Assert(!options.base, 'Cannot extend type with another base'); - - return Extend.type(this, options); + ipaddr.IPv4.parseCIDR = function(string) { + var maskLength, match, parsed; + if (match = string.match(/^(.+)\/(\d+)$/)) { + maskLength = parseInt(match[2]); + if (maskLength >= 0 && maskLength <= 32) { + parsed = [this.parse(match[1]), maskLength]; + Object.defineProperty(parsed, 'toString', { + value: function() { + return this.join('/'); + } + }); + return parsed; + } } + throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range"); + }; - extract(path) { - - path = Array.isArray(path) ? path : path.split('.'); - return this._ids.reach(path); + ipaddr.IPv4.subnetMaskFromPrefixLength = function(prefix) { + var filledOctetCount, j, octets; + prefix = parseInt(prefix); + if (prefix < 0 || prefix > 32) { + throw new Error('ipaddr: invalid IPv4 prefix length'); } + octets = [0, 0, 0, 0]; + j = 0; + filledOctetCount = Math.floor(prefix / 8); + while (j < filledOctetCount) { + octets[j] = 255; + j++; + } + if (filledOctetCount < 4) { + octets[filledOctetCount] = Math.pow(2, prefix % 8) - 1 << 8 - (prefix % 8); + } + return new this(octets); + }; - fork(paths, adjuster) { - - Assert(!this._inRuleset(), 'Cannot fork inside a ruleset'); - - let obj = this; // eslint-disable-line consistent-this - for (let path of [].concat(paths)) { - path = Array.isArray(path) ? path : path.split('.'); - obj = obj._ids.fork(path, adjuster, obj); - } - - obj.$_temp.ruleset = false; - return obj; + ipaddr.IPv4.broadcastAddressFromCIDR = function(string) { + var cidr, error, i, ipInterfaceOctets, octets, subnetMaskOctets; + try { + cidr = this.parseCIDR(string); + ipInterfaceOctets = cidr[0].toByteArray(); + subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray(); + octets = []; + i = 0; + while (i < 4) { + octets.push(parseInt(ipInterfaceOctets[i], 10) | parseInt(subnetMaskOctets[i], 10) ^ 255); + i++; + } + return new this(octets); + } catch (error1) { + error = error1; + throw new Error('ipaddr: the address does not have IPv4 CIDR format'); } + }; - rule(options) { + ipaddr.IPv4.networkAddressFromCIDR = function(string) { + var cidr, error, i, ipInterfaceOctets, octets, subnetMaskOctets; + try { + cidr = this.parseCIDR(string); + ipInterfaceOctets = cidr[0].toByteArray(); + subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray(); + octets = []; + i = 0; + while (i < 4) { + octets.push(parseInt(ipInterfaceOctets[i], 10) & parseInt(subnetMaskOctets[i], 10)); + i++; + } + return new this(octets); + } catch (error1) { + error = error1; + throw new Error('ipaddr: the address does not have IPv4 CIDR format'); + } + }; - const def = this._definition; - Common.assertOptions(options, Object.keys(def.modifiers)); + ipaddr.IPv6.parseCIDR = function(string) { + var maskLength, match, parsed; + if (match = string.match(/^(.+)\/(\d+)$/)) { + maskLength = parseInt(match[2]); + if (maskLength >= 0 && maskLength <= 128) { + parsed = [this.parse(match[1]), maskLength]; + Object.defineProperty(parsed, 'toString', { + value: function() { + return this.join('/'); + } + }); + return parsed; + } + } + throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range"); + }; - Assert(this.$_temp.ruleset !== false, 'Cannot apply rules to empty ruleset or the last rule added does not support rule properties'); - const start = this.$_temp.ruleset === null ? this._rules.length - 1 : this.$_temp.ruleset; - Assert(start >= 0 && start < this._rules.length, 'Cannot apply rules to empty ruleset'); + ipaddr.isValid = function(string) { + return ipaddr.IPv6.isValid(string) || ipaddr.IPv4.isValid(string); + }; - const obj = this.clone(); + ipaddr.parse = function(string) { + if (ipaddr.IPv6.isValid(string)) { + return ipaddr.IPv6.parse(string); + } else if (ipaddr.IPv4.isValid(string)) { + return ipaddr.IPv4.parse(string); + } else { + throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format"); + } + }; - for (let i = start; i < obj._rules.length; ++i) { - const original = obj._rules[i]; - const rule = Clone(original); + ipaddr.parseCIDR = function(string) { + var e; + try { + return ipaddr.IPv6.parseCIDR(string); + } catch (error1) { + e = error1; + try { + return ipaddr.IPv4.parseCIDR(string); + } catch (error1) { + e = error1; + throw new Error("ipaddr: the address has neither IPv6 nor IPv4 CIDR format"); + } + } + }; - for (const name in options) { - def.modifiers[name](rule, options[name]); - Assert(rule.name === original.name, 'Cannot change rule name'); - } + ipaddr.fromByteArray = function(bytes) { + var length; + length = bytes.length; + if (length === 4) { + return new ipaddr.IPv4(bytes); + } else if (length === 16) { + return new ipaddr.IPv6(bytes); + } else { + throw new Error("ipaddr: the binary input is neither an IPv6 nor IPv4 address"); + } + }; - obj._rules[i] = rule; + ipaddr.process = function(string) { + var addr; + addr = this.parse(string); + if (addr.kind() === 'ipv6' && addr.isIPv4MappedAddress()) { + return addr.toIPv4Address(); + } else { + return addr; + } + }; - if (obj._singleRules.get(rule.name) === original) { - obj._singleRules.set(rule.name, rule); - } - } +}).call(this); - obj.$_temp.ruleset = false; - return obj.$_mutateRebuild(); - } - get ruleset() { +/***/ }), - Assert(!this._inRuleset(), 'Cannot start a new ruleset without closing the previous one'); +/***/ 7604: +/***/ ((module) => { - const obj = this.clone(); - obj.$_temp.ruleset = obj._rules.length; - return obj; - } +"use strict"; - get $() { - return this.ruleset; - } +module.exports = function isArrayish(obj) { + if (!obj) { + return false; + } - tailor(targets) { + return obj instanceof Array || Array.isArray(obj) || + (obj.length >= 0 && obj.splice instanceof Function); +}; - targets = [].concat(targets); - Assert(!this._inRuleset(), 'Cannot tailor inside a ruleset'); +/***/ }), - let obj = this; // eslint-disable-line consistent-this +/***/ 31310: +/***/ (function(module, exports) { - if (this.$_terms.alterations) { - for (const { target, adjuster } of this.$_terms.alterations) { - if (targets.includes(target)) { - obj = adjuster(obj); - Assert(Common.isSchema(obj), 'Alteration adjuster for', target, 'failed to return a schema object'); - } - } - } +;(function(root) { + 'use strict'; - obj = obj.$_modify({ each: (item) => item.tailor(targets), ref: false }); - obj.$_temp.ruleset = false; - return obj.$_mutateRebuild(); + function isBase64(v, opts) { + if (v instanceof Boolean || typeof v === 'boolean') { + return false } - tracer() { - - return Trace.location ? Trace.location(this) : this; // $lab:coverage:ignore$ + if (!(opts instanceof Object)) { + opts = {} } - validate(value, options) { - - return Validator.entry(value, this, options); + if (opts.allowEmpty === false && v === '') { + return false } - validateAsync(value, options) { + var regex = '(?:[A-Za-z0-9+\\/]{4})*(?:[A-Za-z0-9+\\/]{2}==|[A-Za-z0-9+\/]{3}=)?' + var mimeRegex = '(data:\\w+\\/[a-zA-Z\\+\\-\\.]+;base64,)' - return Validator.entryAsync(value, this, options); + if (opts.mimeRequired === true) { + regex = mimeRegex + regex + } else if (opts.allowMime === true) { + regex = mimeRegex + '?' + regex } - // Extensions + if (opts.paddingRequired === false) { + regex = '(?:[A-Za-z0-9+\\/]{4})*(?:[A-Za-z0-9+\\/]{2}(==)?|[A-Za-z0-9+\\/]{3}=?)?' + } - $_addRule(options) { + return (new RegExp('^' + regex + '$', 'gi')).test(v) + } - // Normalize rule + if (true) { + if ( true && module.exports) { + exports = module.exports = isBase64 + } + exports.isBase64 = isBase64 + } else {} +})(this); - if (typeof options === 'string') { - options = { name: options }; - } - Assert(options && typeof options === 'object', 'Invalid options'); - Assert(options.name && typeof options.name === 'string', 'Invalid rule name'); +/***/ }), - for (const key in options) { - Assert(key[0] !== '_', 'Cannot set private rule properties'); - } +/***/ 56873: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - const rule = Object.assign({}, options); // Shallow cloned - rule._resolve = []; - rule.method = rule.method || rule.name; +"use strict"; - const definition = this._definition.rules[rule.method]; - const args = rule.args; - Assert(definition, 'Unknown rule', rule.method); +var has = __nccwpck_require__(76339); - // Args +function specifierIncluded(current, specifier) { + var nodeParts = current.split('.'); + var parts = specifier.split(' '); + var op = parts.length > 1 ? parts[0] : '='; + var versionParts = (parts.length > 1 ? parts[1] : parts[0]).split('.'); - const obj = this.clone(); + for (var i = 0; i < 3; ++i) { + var cur = parseInt(nodeParts[i] || 0, 10); + var ver = parseInt(versionParts[i] || 0, 10); + if (cur === ver) { + continue; // eslint-disable-line no-restricted-syntax, no-continue + } + if (op === '<') { + return cur < ver; + } + if (op === '>=') { + return cur >= ver; + } + return false; + } + return op === '>='; +} - if (args) { - Assert(Object.keys(args).length === 1 || Object.keys(args).length === this._definition.rules[rule.name].args.length, 'Invalid rule definition for', this.type, rule.name); +function matchesRange(current, range) { + var specifiers = range.split(/ ?&& ?/); + if (specifiers.length === 0) { + return false; + } + for (var i = 0; i < specifiers.length; ++i) { + if (!specifierIncluded(current, specifiers[i])) { + return false; + } + } + return true; +} - for (const key in args) { - let arg = args[key]; - if (arg === undefined) { - delete args[key]; - continue; - } +function versionIncluded(nodeVersion, specifierValue) { + if (typeof specifierValue === 'boolean') { + return specifierValue; + } - if (definition.argsByName) { - const resolver = definition.argsByName.get(key); + var current = typeof nodeVersion === 'undefined' + ? process.versions && process.versions.node + : nodeVersion; - if (resolver.ref && - Common.isResolvable(arg)) { + if (typeof current !== 'string') { + throw new TypeError(typeof nodeVersion === 'undefined' ? 'Unable to determine current node version' : 'If provided, a valid node version is required'); + } - rule._resolve.push(key); - obj.$_mutateRegister(arg); - } - else { - if (resolver.normalize) { - arg = resolver.normalize(arg); - args[key] = arg; - } + if (specifierValue && typeof specifierValue === 'object') { + for (var i = 0; i < specifierValue.length; ++i) { + if (matchesRange(current, specifierValue[i])) { + return true; + } + } + return false; + } + return matchesRange(current, specifierValue); +} - if (resolver.assert) { - const error = Common.validateArg(arg, key, resolver); - Assert(!error, error, 'or reference'); - } - } - } +var data = __nccwpck_require__(66151); - args[key] = arg; - } - } +module.exports = function isCore(x, nodeVersion) { + return has(data, x) && versionIncluded(nodeVersion, data[x]); +}; - // Unique rules - if (!definition.multi) { - obj._ruleRemove(rule.name, { clone: false }); - obj._singleRules.set(rule.name, rule); - } +/***/ }), - if (obj.$_temp.ruleset === false) { - obj.$_temp.ruleset = null; - } +/***/ 64882: +/***/ ((module) => { - if (definition.priority) { - obj._rules.unshift(rule); - } - else { - obj._rules.push(rule); - } +"use strict"; +/* eslint-disable yoda */ - return obj; - } - $_compile(schema, options) { +const isFullwidthCodePoint = codePoint => { + if (Number.isNaN(codePoint)) { + return false; + } - return Compile.schema(this.$_root, schema, options); - } + // Code points are derived from: + // http://www.unix.org/Public/UNIDATA/EastAsianWidth.txt + if ( + codePoint >= 0x1100 && ( + codePoint <= 0x115F || // Hangul Jamo + codePoint === 0x2329 || // LEFT-POINTING ANGLE BRACKET + codePoint === 0x232A || // RIGHT-POINTING ANGLE BRACKET + // CJK Radicals Supplement .. Enclosed CJK Letters and Months + (0x2E80 <= codePoint && codePoint <= 0x3247 && codePoint !== 0x303F) || + // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A + (0x3250 <= codePoint && codePoint <= 0x4DBF) || + // CJK Unified Ideographs .. Yi Radicals + (0x4E00 <= codePoint && codePoint <= 0xA4C6) || + // Hangul Jamo Extended-A + (0xA960 <= codePoint && codePoint <= 0xA97C) || + // Hangul Syllables + (0xAC00 <= codePoint && codePoint <= 0xD7A3) || + // CJK Compatibility Ideographs + (0xF900 <= codePoint && codePoint <= 0xFAFF) || + // Vertical Forms + (0xFE10 <= codePoint && codePoint <= 0xFE19) || + // CJK Compatibility Forms .. Small Form Variants + (0xFE30 <= codePoint && codePoint <= 0xFE6B) || + // Halfwidth and Fullwidth Forms + (0xFF01 <= codePoint && codePoint <= 0xFF60) || + (0xFFE0 <= codePoint && codePoint <= 0xFFE6) || + // Kana Supplement + (0x1B000 <= codePoint && codePoint <= 0x1B001) || + // Enclosed Ideographic Supplement + (0x1F200 <= codePoint && codePoint <= 0x1F251) || + // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane + (0x20000 <= codePoint && codePoint <= 0x3FFFD) + ) + ) { + return true; + } - $_createError(code, value, local, state, prefs, options = {}) { + return false; +}; - const flags = options.flags !== false ? this._flags : {}; - const messages = options.messages ? Messages.merge(this._definition.messages, options.messages) : this._definition.messages; - return new Errors.Report(code, value, local, flags, messages, state, prefs); - } +module.exports = isFullwidthCodePoint; +module.exports["default"] = isFullwidthCodePoint; - $_getFlag(name) { - return this._flags[name]; - } +/***/ }), - $_getRule(name) { +/***/ 63287: +/***/ ((__unused_webpack_module, exports) => { - return this._singleRules.get(name); - } +"use strict"; - $_mapLabels(path) { - path = Array.isArray(path) ? path : path.split('.'); - return this._ids.labels(path); - } +Object.defineProperty(exports, "__esModule", ({ value: true })); - $_match(value, state, prefs, overrides) { +/*! + * is-plain-object + * + * Copyright (c) 2014-2017, Jon Schlinkert. + * Released under the MIT License. + */ - prefs = Object.assign({}, prefs); // Shallow cloned - prefs.abortEarly = true; - prefs._externals = false; +function isObject(o) { + return Object.prototype.toString.call(o) === '[object Object]'; +} - state.snapshot(); - const result = !Validator.validate(value, this, state, prefs, overrides).errors; - state.restore(); +function isPlainObject(o) { + var ctor,prot; - return result; - } + if (isObject(o) === false) return false; - $_modify(options) { + // If has modified constructor + ctor = o.constructor; + if (ctor === undefined) return true; - Common.assertOptions(options, ['each', 'once', 'ref', 'schema']); - return Modify.schema(this, options) || this; - } + // If has modified prototype + prot = ctor.prototype; + if (isObject(prot) === false) return false; - $_mutateRebuild() { + // If constructor does not have an Object-specific method + if (prot.hasOwnProperty('isPrototypeOf') === false) { + return false; + } - Assert(!this._inRuleset(), 'Cannot add this rule inside a ruleset'); + // Most likely a plain Object + return true; +} - this._refs.reset(); - this._ids.reset(); +exports.isPlainObject = isPlainObject; - const each = (item, { source, name, path, key }) => { - const family = this._definition[source][name] && this._definition[source][name].register; - if (family !== false) { - this.$_mutateRegister(item, { family, key }); - } - }; +/***/ }), - this.$_modify({ each }); +/***/ 87783: +/***/ ((__unused_webpack_module, exports) => { - if (this._definition.rebuild) { - this._definition.rebuild(this); - } +(function(exports) { + "use strict"; - this.$_temp.ruleset = false; - return this; + function isArray(obj) { + if (obj !== null) { + return Object.prototype.toString.call(obj) === "[object Array]"; + } else { + return false; } + } - $_mutateRegister(schema, { family, key } = {}) { - - this._refs.register(schema, family); - this._ids.register(schema, { key }); + function isObject(obj) { + if (obj !== null) { + return Object.prototype.toString.call(obj) === "[object Object]"; + } else { + return false; } + } - $_property(name) { - - return this._definition.properties[name]; + function strictDeepEqual(first, second) { + // Check the scalar case first. + if (first === second) { + return true; } - $_reach(path) { - - return this._ids.reach(path); + // Check if they are the same type. + var firstType = Object.prototype.toString.call(first); + if (firstType !== Object.prototype.toString.call(second)) { + return false; } - - $_rootReferences() { - - return this._refs.roots(); + // We know that first and second have the same type so we can just check the + // first type from now on. + if (isArray(first) === true) { + // Short circuit if they're not the same length; + if (first.length !== second.length) { + return false; + } + for (var i = 0; i < first.length; i++) { + if (strictDeepEqual(first[i], second[i]) === false) { + return false; + } + } + return true; } + if (isObject(first) === true) { + // An object is equal if it has the same key/value pairs. + var keysSeen = {}; + for (var key in first) { + if (hasOwnProperty.call(first, key)) { + if (strictDeepEqual(first[key], second[key]) === false) { + return false; + } + keysSeen[key] = true; + } + } + // Now check that there aren't any keys in second that weren't + // in first. + for (var key2 in second) { + if (hasOwnProperty.call(second, key2)) { + if (keysSeen[key2] !== true) { + return false; + } + } + } + return true; + } + return false; + } - $_setFlag(name, value, options = {}) { - - Assert(name[0] === '_' || !this._inRuleset(), 'Cannot set flag inside a ruleset'); + function isFalse(obj) { + // From the spec: + // A false value corresponds to the following values: + // Empty list + // Empty object + // Empty string + // False boolean + // null value - const flag = this._definition.flags[name] || {}; - if (DeepEqual(value, flag.default)) { - value = undefined; + // First check the scalar values. + if (obj === "" || obj === false || obj === null) { + return true; + } else if (isArray(obj) && obj.length === 0) { + // Check for an empty array. + return true; + } else if (isObject(obj)) { + // Check for an empty object. + for (var key in obj) { + // If there are any keys, then + // the object is not empty so the object + // is not false. + if (obj.hasOwnProperty(key)) { + return false; + } } + return true; + } else { + return false; + } + } - if (DeepEqual(value, this._flags[name])) { - return this; - } + function objValues(obj) { + var keys = Object.keys(obj); + var values = []; + for (var i = 0; i < keys.length; i++) { + values.push(obj[keys[i]]); + } + return values; + } - const obj = options.clone !== false ? this.clone() : this; + function merge(a, b) { + var merged = {}; + for (var key in a) { + merged[key] = a[key]; + } + for (var key2 in b) { + merged[key2] = b[key2]; + } + return merged; + } - if (value !== undefined) { - obj._flags[name] = value; - obj.$_mutateRegister(value); - } - else { - delete obj._flags[name]; - } + var trimLeft; + if (typeof String.prototype.trimLeft === "function") { + trimLeft = function(str) { + return str.trimLeft(); + }; + } else { + trimLeft = function(str) { + return str.match(/^\s*(.*)/)[1]; + }; + } - if (name[0] !== '_') { - obj.$_temp.ruleset = false; - } + // Type constants used to define functions. + var TYPE_NUMBER = 0; + var TYPE_ANY = 1; + var TYPE_STRING = 2; + var TYPE_ARRAY = 3; + var TYPE_OBJECT = 4; + var TYPE_BOOLEAN = 5; + var TYPE_EXPREF = 6; + var TYPE_NULL = 7; + var TYPE_ARRAY_NUMBER = 8; + var TYPE_ARRAY_STRING = 9; - return obj; - } + var TOK_EOF = "EOF"; + var TOK_UNQUOTEDIDENTIFIER = "UnquotedIdentifier"; + var TOK_QUOTEDIDENTIFIER = "QuotedIdentifier"; + var TOK_RBRACKET = "Rbracket"; + var TOK_RPAREN = "Rparen"; + var TOK_COMMA = "Comma"; + var TOK_COLON = "Colon"; + var TOK_RBRACE = "Rbrace"; + var TOK_NUMBER = "Number"; + var TOK_CURRENT = "Current"; + var TOK_EXPREF = "Expref"; + var TOK_PIPE = "Pipe"; + var TOK_OR = "Or"; + var TOK_AND = "And"; + var TOK_EQ = "EQ"; + var TOK_GT = "GT"; + var TOK_LT = "LT"; + var TOK_GTE = "GTE"; + var TOK_LTE = "LTE"; + var TOK_NE = "NE"; + var TOK_FLATTEN = "Flatten"; + var TOK_STAR = "Star"; + var TOK_FILTER = "Filter"; + var TOK_DOT = "Dot"; + var TOK_NOT = "Not"; + var TOK_LBRACE = "Lbrace"; + var TOK_LBRACKET = "Lbracket"; + var TOK_LPAREN= "Lparen"; + var TOK_LITERAL= "Literal"; - $_parent(method, ...args) { + // The "&", "[", "<", ">" tokens + // are not in basicToken because + // there are two token variants + // ("&&", "[?", "<=", ">="). This is specially handled + // below. - return this[method][Common.symbols.parent].call(this, ...args); - } + var basicTokens = { + ".": TOK_DOT, + "*": TOK_STAR, + ",": TOK_COMMA, + ":": TOK_COLON, + "{": TOK_LBRACE, + "}": TOK_RBRACE, + "]": TOK_RBRACKET, + "(": TOK_LPAREN, + ")": TOK_RPAREN, + "@": TOK_CURRENT + }; - $_validate(value, state, prefs) { + var operatorStartToken = { + "<": true, + ">": true, + "=": true, + "!": true + }; - return Validator.validate(value, this, state, prefs); - } + var skipChars = { + " ": true, + "\t": true, + "\n": true + }; - // Internals - _assign(target) { + function isAlpha(ch) { + return (ch >= "a" && ch <= "z") || + (ch >= "A" && ch <= "Z") || + ch === "_"; + } - target.type = this.type; + function isNum(ch) { + return (ch >= "0" && ch <= "9") || + ch === "-"; + } + function isAlphaNum(ch) { + return (ch >= "a" && ch <= "z") || + (ch >= "A" && ch <= "Z") || + (ch >= "0" && ch <= "9") || + ch === "_"; + } - target.$_root = this.$_root; + function Lexer() { + } + Lexer.prototype = { + tokenize: function(stream) { + var tokens = []; + this._current = 0; + var start; + var identifier; + var token; + while (this._current < stream.length) { + if (isAlpha(stream[this._current])) { + start = this._current; + identifier = this._consumeUnquotedIdentifier(stream); + tokens.push({type: TOK_UNQUOTEDIDENTIFIER, + value: identifier, + start: start}); + } else if (basicTokens[stream[this._current]] !== undefined) { + tokens.push({type: basicTokens[stream[this._current]], + value: stream[this._current], + start: this._current}); + this._current++; + } else if (isNum(stream[this._current])) { + token = this._consumeNumber(stream); + tokens.push(token); + } else if (stream[this._current] === "[") { + // No need to increment this._current. This happens + // in _consumeLBracket + token = this._consumeLBracket(stream); + tokens.push(token); + } else if (stream[this._current] === "\"") { + start = this._current; + identifier = this._consumeQuotedIdentifier(stream); + tokens.push({type: TOK_QUOTEDIDENTIFIER, + value: identifier, + start: start}); + } else if (stream[this._current] === "'") { + start = this._current; + identifier = this._consumeRawStringLiteral(stream); + tokens.push({type: TOK_LITERAL, + value: identifier, + start: start}); + } else if (stream[this._current] === "`") { + start = this._current; + var literal = this._consumeLiteral(stream); + tokens.push({type: TOK_LITERAL, + value: literal, + start: start}); + } else if (operatorStartToken[stream[this._current]] !== undefined) { + tokens.push(this._consumeOperator(stream)); + } else if (skipChars[stream[this._current]] !== undefined) { + // Ignore whitespace. + this._current++; + } else if (stream[this._current] === "&") { + start = this._current; + this._current++; + if (stream[this._current] === "&") { + this._current++; + tokens.push({type: TOK_AND, value: "&&", start: start}); + } else { + tokens.push({type: TOK_EXPREF, value: "&", start: start}); + } + } else if (stream[this._current] === "|") { + start = this._current; + this._current++; + if (stream[this._current] === "|") { + this._current++; + tokens.push({type: TOK_OR, value: "||", start: start}); + } else { + tokens.push({type: TOK_PIPE, value: "|", start: start}); + } + } else { + var error = new Error("Unknown character:" + stream[this._current]); + error.name = "LexerError"; + throw error; + } + } + return tokens; + }, - target.$_temp = Object.assign({}, this.$_temp); - target.$_temp.whens = {}; + _consumeUnquotedIdentifier: function(stream) { + var start = this._current; + this._current++; + while (this._current < stream.length && isAlphaNum(stream[this._current])) { + this._current++; + } + return stream.slice(start, this._current); + }, - target._ids = this._ids.clone(); - target._preferences = this._preferences; - target._valids = this._valids && this._valids.clone(); - target._invalids = this._invalids && this._invalids.clone(); - target._rules = this._rules.slice(); - target._singleRules = Clone(this._singleRules, { shallow: true }); - target._refs = this._refs.clone(); - target._flags = Object.assign({}, this._flags); - target._cache = null; + _consumeQuotedIdentifier: function(stream) { + var start = this._current; + this._current++; + var maxLength = stream.length; + while (stream[this._current] !== "\"" && this._current < maxLength) { + // You can escape a double quote and you can escape an escape. + var current = this._current; + if (stream[current] === "\\" && (stream[current + 1] === "\\" || + stream[current + 1] === "\"")) { + current += 2; + } else { + current++; + } + this._current = current; + } + this._current++; + return JSON.parse(stream.slice(start, this._current)); + }, - target.$_terms = {}; - for (const key in this.$_terms) { - target.$_terms[key] = this.$_terms[key] ? this.$_terms[key].slice() : null; - } + _consumeRawStringLiteral: function(stream) { + var start = this._current; + this._current++; + var maxLength = stream.length; + while (stream[this._current] !== "'" && this._current < maxLength) { + // You can escape a single quote and you can escape an escape. + var current = this._current; + if (stream[current] === "\\" && (stream[current + 1] === "\\" || + stream[current + 1] === "'")) { + current += 2; + } else { + current++; + } + this._current = current; + } + this._current++; + var literal = stream.slice(start + 1, this._current - 1); + return literal.replace("\\'", "'"); + }, - // Backwards compatibility + _consumeNumber: function(stream) { + var start = this._current; + this._current++; + var maxLength = stream.length; + while (isNum(stream[this._current]) && this._current < maxLength) { + this._current++; + } + var value = parseInt(stream.slice(start, this._current)); + return {type: TOK_NUMBER, value: value, start: start}; + }, - target.$_super = {}; - for (const override in this.$_super) { - target.$_super[override] = this._super[override].bind(target); - } + _consumeLBracket: function(stream) { + var start = this._current; + this._current++; + if (stream[this._current] === "?") { + this._current++; + return {type: TOK_FILTER, value: "[?", start: start}; + } else if (stream[this._current] === "]") { + this._current++; + return {type: TOK_FLATTEN, value: "[]", start: start}; + } else { + return {type: TOK_LBRACKET, value: "[", start: start}; + } + }, - return target; - } + _consumeOperator: function(stream) { + var start = this._current; + var startingChar = stream[start]; + this._current++; + if (startingChar === "!") { + if (stream[this._current] === "=") { + this._current++; + return {type: TOK_NE, value: "!=", start: start}; + } else { + return {type: TOK_NOT, value: "!", start: start}; + } + } else if (startingChar === "<") { + if (stream[this._current] === "=") { + this._current++; + return {type: TOK_LTE, value: "<=", start: start}; + } else { + return {type: TOK_LT, value: "<", start: start}; + } + } else if (startingChar === ">") { + if (stream[this._current] === "=") { + this._current++; + return {type: TOK_GTE, value: ">=", start: start}; + } else { + return {type: TOK_GT, value: ">", start: start}; + } + } else if (startingChar === "=") { + if (stream[this._current] === "=") { + this._current++; + return {type: TOK_EQ, value: "==", start: start}; + } + } + }, - _bare() { + _consumeLiteral: function(stream) { + this._current++; + var start = this._current; + var maxLength = stream.length; + var literal; + while(stream[this._current] !== "`" && this._current < maxLength) { + // You can escape a literal char or you can escape the escape. + var current = this._current; + if (stream[current] === "\\" && (stream[current + 1] === "\\" || + stream[current + 1] === "`")) { + current += 2; + } else { + current++; + } + this._current = current; + } + var literalString = trimLeft(stream.slice(start, this._current)); + literalString = literalString.replace("\\`", "`"); + if (this._looksLikeJSON(literalString)) { + literal = JSON.parse(literalString); + } else { + // Try to JSON parse it as "" + literal = JSON.parse("\"" + literalString + "\""); + } + // +1 gets us to the ending "`", +1 to move on to the next char. + this._current++; + return literal; + }, - const obj = this.clone(); - obj._reset(); + _looksLikeJSON: function(literalString) { + var startingChars = "[{\""; + var jsonLiterals = ["true", "false", "null"]; + var numberLooking = "-0123456789"; - const terms = obj._definition.terms; - for (const name in terms) { - const term = terms[name]; - obj.$_terms[name] = term.init; - } + if (literalString === "") { + return false; + } else if (startingChars.indexOf(literalString[0]) >= 0) { + return true; + } else if (jsonLiterals.indexOf(literalString) >= 0) { + return true; + } else if (numberLooking.indexOf(literalString[0]) >= 0) { + try { + JSON.parse(literalString); + return true; + } catch (ex) { + return false; + } + } else { + return false; + } + } + }; - return obj.$_mutateRebuild(); - } + var bindingPower = {}; + bindingPower[TOK_EOF] = 0; + bindingPower[TOK_UNQUOTEDIDENTIFIER] = 0; + bindingPower[TOK_QUOTEDIDENTIFIER] = 0; + bindingPower[TOK_RBRACKET] = 0; + bindingPower[TOK_RPAREN] = 0; + bindingPower[TOK_COMMA] = 0; + bindingPower[TOK_RBRACE] = 0; + bindingPower[TOK_NUMBER] = 0; + bindingPower[TOK_CURRENT] = 0; + bindingPower[TOK_EXPREF] = 0; + bindingPower[TOK_PIPE] = 1; + bindingPower[TOK_OR] = 2; + bindingPower[TOK_AND] = 3; + bindingPower[TOK_EQ] = 5; + bindingPower[TOK_GT] = 5; + bindingPower[TOK_LT] = 5; + bindingPower[TOK_GTE] = 5; + bindingPower[TOK_LTE] = 5; + bindingPower[TOK_NE] = 5; + bindingPower[TOK_FLATTEN] = 9; + bindingPower[TOK_STAR] = 20; + bindingPower[TOK_FILTER] = 21; + bindingPower[TOK_DOT] = 40; + bindingPower[TOK_NOT] = 45; + bindingPower[TOK_LBRACE] = 50; + bindingPower[TOK_LBRACKET] = 55; + bindingPower[TOK_LPAREN] = 60; - _default(flag, value, options = {}) { + function Parser() { + } - Common.assertOptions(options, 'literal'); + Parser.prototype = { + parse: function(expression) { + this._loadTokens(expression); + this.index = 0; + var ast = this.expression(0); + if (this._lookahead(0) !== TOK_EOF) { + var t = this._lookaheadToken(0); + var error = new Error( + "Unexpected token type: " + t.type + ", value: " + t.value); + error.name = "ParserError"; + throw error; + } + return ast; + }, - Assert(value !== undefined, 'Missing', flag, 'value'); - Assert(typeof value === 'function' || !options.literal, 'Only function value supports literal option'); + _loadTokens: function(expression) { + var lexer = new Lexer(); + var tokens = lexer.tokenize(expression); + tokens.push({type: TOK_EOF, value: "", start: expression.length}); + this.tokens = tokens; + }, - if (typeof value === 'function' && - options.literal) { + expression: function(rbp) { + var leftToken = this._lookaheadToken(0); + this._advance(); + var left = this.nud(leftToken); + var currentToken = this._lookahead(0); + while (rbp < bindingPower[currentToken]) { + this._advance(); + left = this.led(currentToken, left); + currentToken = this._lookahead(0); + } + return left; + }, - value = { - [Common.symbols.literal]: true, - literal: value - }; - } + _lookahead: function(number) { + return this.tokens[this.index + number].type; + }, - const obj = this.$_setFlag(flag, value); - return obj; - } + _lookaheadToken: function(number) { + return this.tokens[this.index + number]; + }, - _generate(value, state, prefs) { + _advance: function() { + this.index++; + }, - if (!this.$_terms.whens) { - return { schema: this }; + nud: function(token) { + var left; + var right; + var expression; + switch (token.type) { + case TOK_LITERAL: + return {type: "Literal", value: token.value}; + case TOK_UNQUOTEDIDENTIFIER: + return {type: "Field", name: token.value}; + case TOK_QUOTEDIDENTIFIER: + var node = {type: "Field", name: token.value}; + if (this._lookahead(0) === TOK_LPAREN) { + throw new Error("Quoted identifier not allowed for function names."); + } else { + return node; + } + break; + case TOK_NOT: + right = this.expression(bindingPower.Not); + return {type: "NotExpression", children: [right]}; + case TOK_STAR: + left = {type: "Identity"}; + right = null; + if (this._lookahead(0) === TOK_RBRACKET) { + // This can happen in a multiselect, + // [a, b, *] + right = {type: "Identity"}; + } else { + right = this._parseProjectionRHS(bindingPower.Star); + } + return {type: "ValueProjection", children: [left, right]}; + case TOK_FILTER: + return this.led(token.type, {type: "Identity"}); + case TOK_LBRACE: + return this._parseMultiselectHash(); + case TOK_FLATTEN: + left = {type: TOK_FLATTEN, children: [{type: "Identity"}]}; + right = this._parseProjectionRHS(bindingPower.Flatten); + return {type: "Projection", children: [left, right]}; + case TOK_LBRACKET: + if (this._lookahead(0) === TOK_NUMBER || this._lookahead(0) === TOK_COLON) { + right = this._parseIndexExpression(); + return this._projectIfSlice({type: "Identity"}, right); + } else if (this._lookahead(0) === TOK_STAR && + this._lookahead(1) === TOK_RBRACKET) { + this._advance(); + this._advance(); + right = this._parseProjectionRHS(bindingPower.Star); + return {type: "Projection", + children: [{type: "Identity"}, right]}; + } else { + return this._parseMultiselectList(); + } + break; + case TOK_CURRENT: + return {type: TOK_CURRENT}; + case TOK_EXPREF: + expression = this.expression(bindingPower.Expref); + return {type: "ExpressionReference", children: [expression]}; + case TOK_LPAREN: + var args = []; + while (this._lookahead(0) !== TOK_RPAREN) { + if (this._lookahead(0) === TOK_CURRENT) { + expression = {type: TOK_CURRENT}; + this._advance(); + } else { + expression = this.expression(0); + } + args.push(expression); + } + this._match(TOK_RPAREN); + return args[0]; + default: + this._errorToken(token); } + }, - // Collect matching whens - - const whens = []; - const ids = []; - for (let i = 0; i < this.$_terms.whens.length; ++i) { - const when = this.$_terms.whens[i]; - - if (when.concat) { - whens.push(when.concat); - ids.push(`${i}.concat`); - continue; + led: function(tokenName, left) { + var right; + switch(tokenName) { + case TOK_DOT: + var rbp = bindingPower.Dot; + if (this._lookahead(0) !== TOK_STAR) { + right = this._parseDotRHS(rbp); + return {type: "Subexpression", children: [left, right]}; + } else { + // Creating a projection. + this._advance(); + right = this._parseProjectionRHS(rbp); + return {type: "ValueProjection", children: [left, right]}; + } + break; + case TOK_PIPE: + right = this.expression(bindingPower.Pipe); + return {type: TOK_PIPE, children: [left, right]}; + case TOK_OR: + right = this.expression(bindingPower.Or); + return {type: "OrExpression", children: [left, right]}; + case TOK_AND: + right = this.expression(bindingPower.And); + return {type: "AndExpression", children: [left, right]}; + case TOK_LPAREN: + var name = left.name; + var args = []; + var expression, node; + while (this._lookahead(0) !== TOK_RPAREN) { + if (this._lookahead(0) === TOK_CURRENT) { + expression = {type: TOK_CURRENT}; + this._advance(); + } else { + expression = this.expression(0); + } + if (this._lookahead(0) === TOK_COMMA) { + this._match(TOK_COMMA); + } + args.push(expression); } - - const input = when.ref ? when.ref.resolve(value, state, prefs) : value; - const tests = when.is ? [when] : when.switch; - const before = ids.length; - - for (let j = 0; j < tests.length; ++j) { - const { is, then, otherwise } = tests[j]; - - const baseId = `${i}${when.switch ? '.' + j : ''}`; - if (is.$_match(input, state.nest(is, `${baseId}.is`), prefs)) { - if (then) { - const localState = state.localize([...state.path, `${baseId}.then`], state.ancestors, state.schemas); - const { schema: generated, id } = then._generate(value, localState, prefs); - whens.push(generated); - ids.push(`${baseId}.then${id ? `(${id})` : ''}`); - break; - } - } - else if (otherwise) { - const localState = state.localize([...state.path, `${baseId}.otherwise`], state.ancestors, state.schemas); - const { schema: generated, id } = otherwise._generate(value, localState, prefs); - whens.push(generated); - ids.push(`${baseId}.otherwise${id ? `(${id})` : ''}`); - break; - } + this._match(TOK_RPAREN); + node = {type: "Function", name: name, children: args}; + return node; + case TOK_FILTER: + var condition = this.expression(0); + this._match(TOK_RBRACKET); + if (this._lookahead(0) === TOK_FLATTEN) { + right = {type: "Identity"}; + } else { + right = this._parseProjectionRHS(bindingPower.Filter); } - - if (when.break && - ids.length > before) { // Something matched - - break; + return {type: "FilterProjection", children: [left, right, condition]}; + case TOK_FLATTEN: + var leftNode = {type: TOK_FLATTEN, children: [left]}; + var rightNode = this._parseProjectionRHS(bindingPower.Flatten); + return {type: "Projection", children: [leftNode, rightNode]}; + case TOK_EQ: + case TOK_NE: + case TOK_GT: + case TOK_GTE: + case TOK_LT: + case TOK_LTE: + return this._parseComparator(left, tokenName); + case TOK_LBRACKET: + var token = this._lookaheadToken(0); + if (token.type === TOK_NUMBER || token.type === TOK_COLON) { + right = this._parseIndexExpression(); + return this._projectIfSlice(left, right); + } else { + this._match(TOK_STAR); + this._match(TOK_RBRACKET); + right = this._parseProjectionRHS(bindingPower.Star); + return {type: "Projection", children: [left, right]}; } + break; + default: + this._errorToken(this._lookaheadToken(0)); } + }, - // Check cache - - const id = ids.join(', '); - state.mainstay.tracer.debug(state, 'rule', 'when', id); - - if (!id) { - return { schema: this }; - } - - if (!state.mainstay.tracer.active && - this.$_temp.whens[id]) { - - return { schema: this.$_temp.whens[id], id }; - } - - // Generate dynamic schema - - let obj = this; // eslint-disable-line consistent-this - if (this._definition.generate) { - obj = this._definition.generate(this, value, state, prefs); - } - - // Apply whens - - for (const when of whens) { - obj = obj.concat(when); - } - - // Tracing - - if (this.$_root._tracer) { - this.$_root._tracer._combine(obj, [this, ...whens]); - } - - // Cache result - - this.$_temp.whens[id] = obj; - return { schema: obj, id }; - } + _match: function(tokenType) { + if (this._lookahead(0) === tokenType) { + this._advance(); + } else { + var t = this._lookaheadToken(0); + var error = new Error("Expected " + tokenType + ", got: " + t.type); + error.name = "ParserError"; + throw error; + } + }, - _inner(type, values, options = {}) { + _errorToken: function(token) { + var error = new Error("Invalid token (" + + token.type + "): \"" + + token.value + "\""); + error.name = "ParserError"; + throw error; + }, - Assert(!this._inRuleset(), `Cannot set ${type} inside a ruleset`); - const obj = this.clone(); - if (!obj.$_terms[type] || - options.override) { + _parseIndexExpression: function() { + if (this._lookahead(0) === TOK_COLON || this._lookahead(1) === TOK_COLON) { + return this._parseSliceExpression(); + } else { + var node = { + type: "Index", + value: this._lookaheadToken(0).value}; + this._advance(); + this._match(TOK_RBRACKET); + return node; + } + }, - obj.$_terms[type] = []; - } + _projectIfSlice: function(left, right) { + var indexExpr = {type: "IndexExpression", children: [left, right]}; + if (right.type === "Slice") { + return { + type: "Projection", + children: [indexExpr, this._parseProjectionRHS(bindingPower.Star)] + }; + } else { + return indexExpr; + } + }, - if (options.single) { - obj.$_terms[type].push(values); - } - else { - obj.$_terms[type].push(...values); - } + _parseSliceExpression: function() { + // [start:end:step] where each part is optional, as well as the last + // colon. + var parts = [null, null, null]; + var index = 0; + var currentToken = this._lookahead(0); + while (currentToken !== TOK_RBRACKET && index < 3) { + if (currentToken === TOK_COLON) { + index++; + this._advance(); + } else if (currentToken === TOK_NUMBER) { + parts[index] = this._lookaheadToken(0).value; + this._advance(); + } else { + var t = this._lookahead(0); + var error = new Error("Syntax error, unexpected token: " + + t.value + "(" + t.type + ")"); + error.name = "Parsererror"; + throw error; + } + currentToken = this._lookahead(0); + } + this._match(TOK_RBRACKET); + return { + type: "Slice", + children: parts + }; + }, - obj.$_temp.ruleset = false; - return obj; - } + _parseComparator: function(left, comparator) { + var right = this.expression(bindingPower[comparator]); + return {type: "Comparator", name: comparator, children: [left, right]}; + }, - _inRuleset() { + _parseDotRHS: function(rbp) { + var lookahead = this._lookahead(0); + var exprTokens = [TOK_UNQUOTEDIDENTIFIER, TOK_QUOTEDIDENTIFIER, TOK_STAR]; + if (exprTokens.indexOf(lookahead) >= 0) { + return this.expression(rbp); + } else if (lookahead === TOK_LBRACKET) { + this._match(TOK_LBRACKET); + return this._parseMultiselectList(); + } else if (lookahead === TOK_LBRACE) { + this._match(TOK_LBRACE); + return this._parseMultiselectHash(); + } + }, - return this.$_temp.ruleset !== null && this.$_temp.ruleset !== false; - } + _parseProjectionRHS: function(rbp) { + var right; + if (bindingPower[this._lookahead(0)] < 10) { + right = {type: "Identity"}; + } else if (this._lookahead(0) === TOK_LBRACKET) { + right = this.expression(rbp); + } else if (this._lookahead(0) === TOK_FILTER) { + right = this.expression(rbp); + } else if (this._lookahead(0) === TOK_DOT) { + this._match(TOK_DOT); + right = this._parseDotRHS(rbp); + } else { + var t = this._lookaheadToken(0); + var error = new Error("Sytanx error, unexpected token: " + + t.value + "(" + t.type + ")"); + error.name = "ParserError"; + throw error; + } + return right; + }, - _ruleRemove(name, options = {}) { + _parseMultiselectList: function() { + var expressions = []; + while (this._lookahead(0) !== TOK_RBRACKET) { + var expression = this.expression(0); + expressions.push(expression); + if (this._lookahead(0) === TOK_COMMA) { + this._match(TOK_COMMA); + if (this._lookahead(0) === TOK_RBRACKET) { + throw new Error("Unexpected token Rbracket"); + } + } + } + this._match(TOK_RBRACKET); + return {type: "MultiSelectList", children: expressions}; + }, - if (!this._singleRules.has(name)) { - return this; + _parseMultiselectHash: function() { + var pairs = []; + var identifierTypes = [TOK_UNQUOTEDIDENTIFIER, TOK_QUOTEDIDENTIFIER]; + var keyToken, keyName, value, node; + for (;;) { + keyToken = this._lookaheadToken(0); + if (identifierTypes.indexOf(keyToken.type) < 0) { + throw new Error("Expecting an identifier token, got: " + + keyToken.type); + } + keyName = keyToken.value; + this._advance(); + this._match(TOK_COLON); + value = this.expression(0); + node = {type: "KeyValuePair", name: keyName, value: value}; + pairs.push(node); + if (this._lookahead(0) === TOK_COMMA) { + this._match(TOK_COMMA); + } else if (this._lookahead(0) === TOK_RBRACE) { + this._match(TOK_RBRACE); + break; + } } + return {type: "MultiSelectHash", children: pairs}; + } + }; - const obj = options.clone !== false ? this.clone() : this; - - obj._singleRules.delete(name); - const filtered = []; - for (let i = 0; i < obj._rules.length; ++i) { - const test = obj._rules[i]; - if (test.name === name && - !test.keep) { + function TreeInterpreter(runtime) { + this.runtime = runtime; + } - if (obj._inRuleset() && - i < obj.$_temp.ruleset) { + TreeInterpreter.prototype = { + search: function(node, value) { + return this.visit(node, value); + }, - --obj.$_temp.ruleset; + visit: function(node, value) { + var matched, current, result, first, second, field, left, right, collected, i; + switch (node.type) { + case "Field": + if (value === null ) { + return null; + } else if (isObject(value)) { + field = value[node.name]; + if (field === undefined) { + return null; + } else { + return field; + } + } else { + return null; + } + break; + case "Subexpression": + result = this.visit(node.children[0], value); + for (i = 1; i < node.children.length; i++) { + result = this.visit(node.children[1], result); + if (result === null) { + return null; + } + } + return result; + case "IndexExpression": + left = this.visit(node.children[0], value); + right = this.visit(node.children[1], left); + return right; + case "Index": + if (!isArray(value)) { + return null; + } + var index = node.value; + if (index < 0) { + index = value.length + index; + } + result = value[index]; + if (result === undefined) { + result = null; + } + return result; + case "Slice": + if (!isArray(value)) { + return null; + } + var sliceParams = node.children.slice(0); + var computed = this.computeSliceParams(value.length, sliceParams); + var start = computed[0]; + var stop = computed[1]; + var step = computed[2]; + result = []; + if (step > 0) { + for (i = start; i < stop; i += step) { + result.push(value[i]); + } + } else { + for (i = start; i > stop; i += step) { + result.push(value[i]); + } + } + return result; + case "Projection": + // Evaluate left child. + var base = this.visit(node.children[0], value); + if (!isArray(base)) { + return null; + } + collected = []; + for (i = 0; i < base.length; i++) { + current = this.visit(node.children[1], base[i]); + if (current !== null) { + collected.push(current); + } + } + return collected; + case "ValueProjection": + // Evaluate left child. + base = this.visit(node.children[0], value); + if (!isObject(base)) { + return null; + } + collected = []; + var values = objValues(base); + for (i = 0; i < values.length; i++) { + current = this.visit(node.children[1], values[i]); + if (current !== null) { + collected.push(current); + } + } + return collected; + case "FilterProjection": + base = this.visit(node.children[0], value); + if (!isArray(base)) { + return null; + } + var filtered = []; + var finalResults = []; + for (i = 0; i < base.length; i++) { + matched = this.visit(node.children[2], base[i]); + if (!isFalse(matched)) { + filtered.push(base[i]); + } + } + for (var j = 0; j < filtered.length; j++) { + current = this.visit(node.children[1], filtered[j]); + if (current !== null) { + finalResults.push(current); + } + } + return finalResults; + case "Comparator": + first = this.visit(node.children[0], value); + second = this.visit(node.children[1], value); + switch(node.name) { + case TOK_EQ: + result = strictDeepEqual(first, second); + break; + case TOK_NE: + result = !strictDeepEqual(first, second); + break; + case TOK_GT: + result = first > second; + break; + case TOK_GTE: + result = first >= second; + break; + case TOK_LT: + result = first < second; + break; + case TOK_LTE: + result = first <= second; + break; + default: + throw new Error("Unknown comparator: " + node.name); + } + return result; + case TOK_FLATTEN: + var original = this.visit(node.children[0], value); + if (!isArray(original)) { + return null; + } + var merged = []; + for (i = 0; i < original.length; i++) { + current = original[i]; + if (isArray(current)) { + merged.push.apply(merged, current); + } else { + merged.push(current); } + } + return merged; + case "Identity": + return value; + case "MultiSelectList": + if (value === null) { + return null; + } + collected = []; + for (i = 0; i < node.children.length; i++) { + collected.push(this.visit(node.children[i], value)); + } + return collected; + case "MultiSelectHash": + if (value === null) { + return null; + } + collected = {}; + var child; + for (i = 0; i < node.children.length; i++) { + child = node.children[i]; + collected[child.name] = this.visit(child.value, value); + } + return collected; + case "OrExpression": + matched = this.visit(node.children[0], value); + if (isFalse(matched)) { + matched = this.visit(node.children[1], value); + } + return matched; + case "AndExpression": + first = this.visit(node.children[0], value); - continue; - } + if (isFalse(first) === true) { + return first; + } + return this.visit(node.children[1], value); + case "NotExpression": + first = this.visit(node.children[0], value); + return isFalse(first); + case "Literal": + return node.value; + case TOK_PIPE: + left = this.visit(node.children[0], value); + return this.visit(node.children[1], left); + case TOK_CURRENT: + return value; + case "Function": + var resolvedArgs = []; + for (i = 0; i < node.children.length; i++) { + resolvedArgs.push(this.visit(node.children[i], value)); + } + return this.runtime.callFunction(node.name, resolvedArgs); + case "ExpressionReference": + var refNode = node.children[0]; + // Tag the node with a specific attribute so the type + // checker verify the type. + refNode.jmespathType = TOK_EXPREF; + return refNode; + default: + throw new Error("Unknown node type: " + node.type); + } + }, - filtered.push(test); + computeSliceParams: function(arrayLength, sliceParams) { + var start = sliceParams[0]; + var stop = sliceParams[1]; + var step = sliceParams[2]; + var computed = [null, null, null]; + if (step === null) { + step = 1; + } else if (step === 0) { + var error = new Error("Invalid slice, step cannot be 0"); + error.name = "RuntimeError"; + throw error; } + var stepValueNegative = step < 0 ? true : false; - obj._rules = filtered; - return obj; - } + if (start === null) { + start = stepValueNegative ? arrayLength - 1 : 0; + } else { + start = this.capSliceRange(arrayLength, start, step); + } - _values(values, key) { + if (stop === null) { + stop = stepValueNegative ? -1 : arrayLength; + } else { + stop = this.capSliceRange(arrayLength, stop, step); + } + computed[0] = start; + computed[1] = stop; + computed[2] = step; + return computed; + }, - Common.verifyFlat(values, key.slice(1, -1)); + capSliceRange: function(arrayLength, actualValue, step) { + if (actualValue < 0) { + actualValue += arrayLength; + if (actualValue < 0) { + actualValue = step < 0 ? -1 : 0; + } + } else if (actualValue >= arrayLength) { + actualValue = step < 0 ? arrayLength - 1 : arrayLength; + } + return actualValue; + } - const obj = this.clone(); + }; - const override = values[0] === Common.symbols.override; - if (override) { - values = values.slice(1); + function Runtime(interpreter) { + this._interpreter = interpreter; + this.functionTable = { + // name: [function, ] + // The can be: + // + // { + // args: [[type1, type2], [type1, type2]], + // variadic: true|false + // } + // + // Each arg in the arg list is a list of valid types + // (if the function is overloaded and supports multiple + // types. If the type is "any" then no type checking + // occurs on the argument. Variadic is optional + // and if not provided is assumed to be false. + abs: {_func: this._functionAbs, _signature: [{types: [TYPE_NUMBER]}]}, + avg: {_func: this._functionAvg, _signature: [{types: [TYPE_ARRAY_NUMBER]}]}, + ceil: {_func: this._functionCeil, _signature: [{types: [TYPE_NUMBER]}]}, + contains: { + _func: this._functionContains, + _signature: [{types: [TYPE_STRING, TYPE_ARRAY]}, + {types: [TYPE_ANY]}]}, + "ends_with": { + _func: this._functionEndsWith, + _signature: [{types: [TYPE_STRING]}, {types: [TYPE_STRING]}]}, + floor: {_func: this._functionFloor, _signature: [{types: [TYPE_NUMBER]}]}, + length: { + _func: this._functionLength, + _signature: [{types: [TYPE_STRING, TYPE_ARRAY, TYPE_OBJECT]}]}, + map: { + _func: this._functionMap, + _signature: [{types: [TYPE_EXPREF]}, {types: [TYPE_ARRAY]}]}, + max: { + _func: this._functionMax, + _signature: [{types: [TYPE_ARRAY_NUMBER, TYPE_ARRAY_STRING]}]}, + "merge": { + _func: this._functionMerge, + _signature: [{types: [TYPE_OBJECT], variadic: true}] + }, + "max_by": { + _func: this._functionMaxBy, + _signature: [{types: [TYPE_ARRAY]}, {types: [TYPE_EXPREF]}] + }, + sum: {_func: this._functionSum, _signature: [{types: [TYPE_ARRAY_NUMBER]}]}, + "starts_with": { + _func: this._functionStartsWith, + _signature: [{types: [TYPE_STRING]}, {types: [TYPE_STRING]}]}, + min: { + _func: this._functionMin, + _signature: [{types: [TYPE_ARRAY_NUMBER, TYPE_ARRAY_STRING]}]}, + "min_by": { + _func: this._functionMinBy, + _signature: [{types: [TYPE_ARRAY]}, {types: [TYPE_EXPREF]}] + }, + type: {_func: this._functionType, _signature: [{types: [TYPE_ANY]}]}, + keys: {_func: this._functionKeys, _signature: [{types: [TYPE_OBJECT]}]}, + values: {_func: this._functionValues, _signature: [{types: [TYPE_OBJECT]}]}, + sort: {_func: this._functionSort, _signature: [{types: [TYPE_ARRAY_STRING, TYPE_ARRAY_NUMBER]}]}, + "sort_by": { + _func: this._functionSortBy, + _signature: [{types: [TYPE_ARRAY]}, {types: [TYPE_EXPREF]}] + }, + join: { + _func: this._functionJoin, + _signature: [ + {types: [TYPE_STRING]}, + {types: [TYPE_ARRAY_STRING]} + ] + }, + reverse: { + _func: this._functionReverse, + _signature: [{types: [TYPE_STRING, TYPE_ARRAY]}]}, + "to_array": {_func: this._functionToArray, _signature: [{types: [TYPE_ANY]}]}, + "to_string": {_func: this._functionToString, _signature: [{types: [TYPE_ANY]}]}, + "to_number": {_func: this._functionToNumber, _signature: [{types: [TYPE_ANY]}]}, + "not_null": { + _func: this._functionNotNull, + _signature: [{types: [TYPE_ANY], variadic: true}] } + }; + } - if (!obj[key] && - values.length) { + Runtime.prototype = { + callFunction: function(name, resolvedArgs) { + var functionEntry = this.functionTable[name]; + if (functionEntry === undefined) { + throw new Error("Unknown function: " + name + "()"); + } + this._validateArgs(name, resolvedArgs, functionEntry._signature); + return functionEntry._func.call(this, resolvedArgs); + }, - obj[key] = new Values(); - } - else if (override) { - obj[key] = values.length ? new Values() : null; - obj.$_mutateRebuild(); + _validateArgs: function(name, args, signature) { + // Validating the args requires validating + // the correct arity and the correct type of each arg. + // If the last argument is declared as variadic, then we need + // a minimum number of args to be required. Otherwise it has to + // be an exact amount. + var pluralized; + if (signature[signature.length - 1].variadic) { + if (args.length < signature.length) { + pluralized = signature.length === 1 ? " argument" : " arguments"; + throw new Error("ArgumentError: " + name + "() " + + "takes at least" + signature.length + pluralized + + " but received " + args.length); + } + } else if (args.length !== signature.length) { + pluralized = signature.length === 1 ? " argument" : " arguments"; + throw new Error("ArgumentError: " + name + "() " + + "takes " + signature.length + pluralized + + " but received " + args.length); } - - if (!obj[key]) { - return obj; + var currentSpec; + var actualType; + var typeMatched; + for (var i = 0; i < signature.length; i++) { + typeMatched = false; + currentSpec = signature[i].types; + actualType = this._getTypeName(args[i]); + for (var j = 0; j < currentSpec.length; j++) { + if (this._typeMatches(actualType, currentSpec[j], args[i])) { + typeMatched = true; + break; + } + } + if (!typeMatched) { + throw new Error("TypeError: " + name + "() " + + "expected argument " + (i + 1) + + " to be type " + currentSpec + + " but received type " + actualType + + " instead."); + } } + }, - if (override) { - obj[key].override(); + _typeMatches: function(actual, expected, argValue) { + if (expected === TYPE_ANY) { + return true; } - - for (const value of values) { - Assert(value !== undefined, 'Cannot call allow/valid/invalid with undefined'); - Assert(value !== Common.symbols.override, 'Override must be the first value'); - - const other = key === '_invalids' ? '_valids' : '_invalids'; - if (obj[other]) { - obj[other].remove(value); - if (!obj[other].length) { - Assert(key === '_valids' || !obj._flags.only, 'Setting invalid value', value, 'leaves schema rejecting all values due to previous valid rule'); - obj[other] = null; + if (expected === TYPE_ARRAY_STRING || + expected === TYPE_ARRAY_NUMBER || + expected === TYPE_ARRAY) { + // The expected type can either just be array, + // or it can require a specific subtype (array of numbers). + // + // The simplest case is if "array" with no subtype is specified. + if (expected === TYPE_ARRAY) { + return actual === TYPE_ARRAY; + } else if (actual === TYPE_ARRAY) { + // Otherwise we need to check subtypes. + // I think this has potential to be improved. + var subtype; + if (expected === TYPE_ARRAY_NUMBER) { + subtype = TYPE_NUMBER; + } else if (expected === TYPE_ARRAY_STRING) { + subtype = TYPE_STRING; + } + for (var i = 0; i < argValue.length; i++) { + if (!this._typeMatches( + this._getTypeName(argValue[i]), subtype, + argValue[i])) { + return false; + } } + return true; } - - obj[key].add(value, obj._refs); + } else { + return actual === expected; } + }, + _getTypeName: function(obj) { + switch (Object.prototype.toString.call(obj)) { + case "[object String]": + return TYPE_STRING; + case "[object Number]": + return TYPE_NUMBER; + case "[object Array]": + return TYPE_ARRAY; + case "[object Boolean]": + return TYPE_BOOLEAN; + case "[object Null]": + return TYPE_NULL; + case "[object Object]": + // Check if it's an expref. If it has, it's been + // tagged with a jmespathType attr of 'Expref'; + if (obj.jmespathType === TOK_EXPREF) { + return TYPE_EXPREF; + } else { + return TYPE_OBJECT; + } + } + }, - return obj; - } -}; - - -internals.Base.prototype[Common.symbols.any] = { - version: Common.version, - compile: Compile.compile, - root: '$_root' -}; - - -internals.Base.prototype.isImmutable = true; // Prevents Hoek from deep cloning schema objects (must be on prototype) - - -// Aliases - -internals.Base.prototype.deny = internals.Base.prototype.invalid; -internals.Base.prototype.disallow = internals.Base.prototype.invalid; -internals.Base.prototype.equal = internals.Base.prototype.valid; -internals.Base.prototype.exist = internals.Base.prototype.required; -internals.Base.prototype.not = internals.Base.prototype.invalid; -internals.Base.prototype.options = internals.Base.prototype.prefs; -internals.Base.prototype.preferences = internals.Base.prototype.prefs; - - -module.exports = new internals.Base(); - - -/***/ }), - -/***/ 63355: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -const Assert = __nccwpck_require__(32718); -const Clone = __nccwpck_require__(85578); - -const Common = __nccwpck_require__(72448); - - -const internals = { - max: 1000, - supported: new Set(['undefined', 'boolean', 'number', 'string']) -}; - - -exports.provider = { - - provision(options) { - - return new internals.Cache(options); - } -}; - - -// Least Recently Used (LRU) Cache + _functionStartsWith: function(resolvedArgs) { + return resolvedArgs[0].lastIndexOf(resolvedArgs[1]) === 0; + }, -internals.Cache = class { + _functionEndsWith: function(resolvedArgs) { + var searchStr = resolvedArgs[0]; + var suffix = resolvedArgs[1]; + return searchStr.indexOf(suffix, searchStr.length - suffix.length) !== -1; + }, - constructor(options = {}) { + _functionReverse: function(resolvedArgs) { + var typeName = this._getTypeName(resolvedArgs[0]); + if (typeName === TYPE_STRING) { + var originalStr = resolvedArgs[0]; + var reversedStr = ""; + for (var i = originalStr.length - 1; i >= 0; i--) { + reversedStr += originalStr[i]; + } + return reversedStr; + } else { + var reversedArray = resolvedArgs[0].slice(0); + reversedArray.reverse(); + return reversedArray; + } + }, - Common.assertOptions(options, ['max']); - Assert(options.max === undefined || options.max && options.max > 0 && isFinite(options.max), 'Invalid max cache size'); + _functionAbs: function(resolvedArgs) { + return Math.abs(resolvedArgs[0]); + }, - this._max = options.max || internals.max; + _functionCeil: function(resolvedArgs) { + return Math.ceil(resolvedArgs[0]); + }, - this._map = new Map(); // Map of nodes by key - this._list = new internals.List(); // List of nodes (most recently used in head) - } + _functionAvg: function(resolvedArgs) { + var sum = 0; + var inputArray = resolvedArgs[0]; + for (var i = 0; i < inputArray.length; i++) { + sum += inputArray[i]; + } + return sum / inputArray.length; + }, - get length() { + _functionContains: function(resolvedArgs) { + return resolvedArgs[0].indexOf(resolvedArgs[1]) >= 0; + }, - return this._map.size; - } + _functionFloor: function(resolvedArgs) { + return Math.floor(resolvedArgs[0]); + }, - set(key, value) { + _functionLength: function(resolvedArgs) { + if (!isObject(resolvedArgs[0])) { + return resolvedArgs[0].length; + } else { + // As far as I can tell, there's no way to get the length + // of an object without O(n) iteration through the object. + return Object.keys(resolvedArgs[0]).length; + } + }, - if (key !== null && - !internals.supported.has(typeof key)) { + _functionMap: function(resolvedArgs) { + var mapped = []; + var interpreter = this._interpreter; + var exprefNode = resolvedArgs[0]; + var elements = resolvedArgs[1]; + for (var i = 0; i < elements.length; i++) { + mapped.push(interpreter.visit(exprefNode, elements[i])); + } + return mapped; + }, - return; + _functionMerge: function(resolvedArgs) { + var merged = {}; + for (var i = 0; i < resolvedArgs.length; i++) { + var current = resolvedArgs[i]; + for (var key in current) { + merged[key] = current[key]; } + } + return merged; + }, - let node = this._map.get(key); - if (node) { - node.value = value; - this._list.first(node); - return; + _functionMax: function(resolvedArgs) { + if (resolvedArgs[0].length > 0) { + var typeName = this._getTypeName(resolvedArgs[0][0]); + if (typeName === TYPE_NUMBER) { + return Math.max.apply(Math, resolvedArgs[0]); + } else { + var elements = resolvedArgs[0]; + var maxElement = elements[0]; + for (var i = 1; i < elements.length; i++) { + if (maxElement.localeCompare(elements[i]) < 0) { + maxElement = elements[i]; + } + } + return maxElement; } + } else { + return null; + } + }, - node = this._list.unshift({ key, value }); - this._map.set(key, node); - this._compact(); - } - - get(key) { - - const node = this._map.get(key); - if (node) { - this._list.first(node); - return Clone(node.value); + _functionMin: function(resolvedArgs) { + if (resolvedArgs[0].length > 0) { + var typeName = this._getTypeName(resolvedArgs[0][0]); + if (typeName === TYPE_NUMBER) { + return Math.min.apply(Math, resolvedArgs[0]); + } else { + var elements = resolvedArgs[0]; + var minElement = elements[0]; + for (var i = 1; i < elements.length; i++) { + if (elements[i].localeCompare(minElement) < 0) { + minElement = elements[i]; + } + } + return minElement; } - } + } else { + return null; + } + }, - _compact() { + _functionSum: function(resolvedArgs) { + var sum = 0; + var listToSum = resolvedArgs[0]; + for (var i = 0; i < listToSum.length; i++) { + sum += listToSum[i]; + } + return sum; + }, - if (this._map.size > this._max) { - const node = this._list.pop(); - this._map.delete(node.key); + _functionType: function(resolvedArgs) { + switch (this._getTypeName(resolvedArgs[0])) { + case TYPE_NUMBER: + return "number"; + case TYPE_STRING: + return "string"; + case TYPE_ARRAY: + return "array"; + case TYPE_OBJECT: + return "object"; + case TYPE_BOOLEAN: + return "boolean"; + case TYPE_EXPREF: + return "expref"; + case TYPE_NULL: + return "null"; } - } -}; - - -internals.List = class { - - constructor() { + }, - this.tail = null; - this.head = null; - } + _functionKeys: function(resolvedArgs) { + return Object.keys(resolvedArgs[0]); + }, - unshift(node) { + _functionValues: function(resolvedArgs) { + var obj = resolvedArgs[0]; + var keys = Object.keys(obj); + var values = []; + for (var i = 0; i < keys.length; i++) { + values.push(obj[keys[i]]); + } + return values; + }, - node.next = null; - node.prev = this.head; + _functionJoin: function(resolvedArgs) { + var joinChar = resolvedArgs[0]; + var listJoin = resolvedArgs[1]; + return listJoin.join(joinChar); + }, - if (this.head) { - this.head.next = node; + _functionToArray: function(resolvedArgs) { + if (this._getTypeName(resolvedArgs[0]) === TYPE_ARRAY) { + return resolvedArgs[0]; + } else { + return [resolvedArgs[0]]; } + }, - this.head = node; + _functionToString: function(resolvedArgs) { + if (this._getTypeName(resolvedArgs[0]) === TYPE_STRING) { + return resolvedArgs[0]; + } else { + return JSON.stringify(resolvedArgs[0]); + } + }, - if (!this.tail) { - this.tail = node; + _functionToNumber: function(resolvedArgs) { + var typeName = this._getTypeName(resolvedArgs[0]); + var convertedValue; + if (typeName === TYPE_NUMBER) { + return resolvedArgs[0]; + } else if (typeName === TYPE_STRING) { + convertedValue = +resolvedArgs[0]; + if (!isNaN(convertedValue)) { + return convertedValue; + } } + return null; + }, - return node; - } + _functionNotNull: function(resolvedArgs) { + for (var i = 0; i < resolvedArgs.length; i++) { + if (this._getTypeName(resolvedArgs[i]) !== TYPE_NULL) { + return resolvedArgs[i]; + } + } + return null; + }, - first(node) { + _functionSort: function(resolvedArgs) { + var sortedArray = resolvedArgs[0].slice(0); + sortedArray.sort(); + return sortedArray; + }, - if (node === this.head) { - return; + _functionSortBy: function(resolvedArgs) { + var sortedArray = resolvedArgs[0].slice(0); + if (sortedArray.length === 0) { + return sortedArray; + } + var interpreter = this._interpreter; + var exprefNode = resolvedArgs[1]; + var requiredType = this._getTypeName( + interpreter.visit(exprefNode, sortedArray[0])); + if ([TYPE_NUMBER, TYPE_STRING].indexOf(requiredType) < 0) { + throw new Error("TypeError"); + } + var that = this; + // In order to get a stable sort out of an unstable + // sort algorithm, we decorate/sort/undecorate (DSU) + // by creating a new list of [index, element] pairs. + // In the cmp function, if the evaluated elements are + // equal, then the index will be used as the tiebreaker. + // After the decorated list has been sorted, it will be + // undecorated to extract the original elements. + var decorated = []; + for (var i = 0; i < sortedArray.length; i++) { + decorated.push([i, sortedArray[i]]); + } + decorated.sort(function(a, b) { + var exprA = interpreter.visit(exprefNode, a[1]); + var exprB = interpreter.visit(exprefNode, b[1]); + if (that._getTypeName(exprA) !== requiredType) { + throw new Error( + "TypeError: expected " + requiredType + ", received " + + that._getTypeName(exprA)); + } else if (that._getTypeName(exprB) !== requiredType) { + throw new Error( + "TypeError: expected " + requiredType + ", received " + + that._getTypeName(exprB)); + } + if (exprA > exprB) { + return 1; + } else if (exprA < exprB) { + return -1; + } else { + // If they're equal compare the items by their + // order to maintain relative order of equal keys + // (i.e. to get a stable sort). + return a[0] - b[0]; + } + }); + // Undecorate: extract out the original list elements. + for (var j = 0; j < decorated.length; j++) { + sortedArray[j] = decorated[j][1]; } + return sortedArray; + }, - this._remove(node); - this.unshift(node); - } + _functionMaxBy: function(resolvedArgs) { + var exprefNode = resolvedArgs[1]; + var resolvedArray = resolvedArgs[0]; + var keyFunction = this.createKeyFunction(exprefNode, [TYPE_NUMBER, TYPE_STRING]); + var maxNumber = -Infinity; + var maxRecord; + var current; + for (var i = 0; i < resolvedArray.length; i++) { + current = keyFunction(resolvedArray[i]); + if (current > maxNumber) { + maxNumber = current; + maxRecord = resolvedArray[i]; + } + } + return maxRecord; + }, - pop() { + _functionMinBy: function(resolvedArgs) { + var exprefNode = resolvedArgs[1]; + var resolvedArray = resolvedArgs[0]; + var keyFunction = this.createKeyFunction(exprefNode, [TYPE_NUMBER, TYPE_STRING]); + var minNumber = Infinity; + var minRecord; + var current; + for (var i = 0; i < resolvedArray.length; i++) { + current = keyFunction(resolvedArray[i]); + if (current < minNumber) { + minNumber = current; + minRecord = resolvedArray[i]; + } + } + return minRecord; + }, - return this._remove(this.tail); + createKeyFunction: function(exprefNode, allowedTypes) { + var that = this; + var interpreter = this._interpreter; + var keyFunc = function(x) { + var current = interpreter.visit(exprefNode, x); + if (allowedTypes.indexOf(that._getTypeName(current)) < 0) { + var msg = "TypeError: expected one of " + allowedTypes + + ", received " + that._getTypeName(current); + throw new Error(msg); + } + return current; + }; + return keyFunc; } - _remove(node) { - - const { next, prev } = node; - - next.prev = prev; + }; - if (prev) { - prev.next = next; - } + function compile(stream) { + var parser = new Parser(); + var ast = parser.parse(stream); + return ast; + } - if (node === this.tail) { - this.tail = next; - } + function tokenize(stream) { + var lexer = new Lexer(); + return lexer.tokenize(stream); + } - node.prev = null; - node.next = null; + function search(data, expression) { + var parser = new Parser(); + // This needs to be improved. Both the interpreter and runtime depend on + // each other. The runtime needs the interpreter to support exprefs. + // There's likely a clean way to avoid the cyclic dependency. + var runtime = new Runtime(); + var interpreter = new TreeInterpreter(runtime); + runtime._interpreter = interpreter; + var node = parser.parse(expression); + return interpreter.search(node, data); + } - return node; - } -}; + exports.tokenize = tokenize; + exports.compile = compile; + exports.search = search; + exports.strictDeepEqual = strictDeepEqual; +})( false ? 0 : exports); /***/ }), -/***/ 72448: +/***/ 46014: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -const Assert = __nccwpck_require__(32718); -const AssertError = __nccwpck_require__(35563); - -const Pkg = __nccwpck_require__(77045); +const Clone = __nccwpck_require__(85578); -let Messages; -let Schemas; +const Common = __nccwpck_require__(72448); const internals = { - isoDate: /^(?:[-+]\d{2})?(?:\d{4}(?!\d{2}\b))(?:(-?)(?:(?:0[1-9]|1[0-2])(?:\1(?:[12]\d|0[1-9]|3[01]))?|W(?:[0-4]\d|5[0-2])(?:-?[1-7])?|(?:00[1-9]|0[1-9]\d|[12]\d{2}|3(?:[0-5]\d|6[1-6])))(?![T]$|[T][\d]+Z$)(?:[T\s](?:(?:(?:[01]\d|2[0-3])(?:(:?)[0-5]\d)?|24\:?00)(?:[.,]\d+(?!:))?)(?:\2[0-5]\d(?:[.,]\d+)?)?(?:[Z]|(?:[+-])(?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?)?$/ + annotations: Symbol('annotations') }; -exports.version = Pkg.version; - +exports.error = function (stripColorCodes) { -exports.defaults = { - abortEarly: true, - allowUnknown: false, - artifacts: false, - cache: true, - context: null, - convert: true, - dateFormat: 'iso', - errors: { - escapeHtml: false, - label: 'path', - language: null, - render: true, - stack: false, - wrap: { - label: '"', - array: '[]' - } - }, - externals: true, - messages: {}, - nonEnumerables: false, - noDefaults: false, - presence: 'optional', - skipFunctions: false, - stripUnknown: false, - warnings: false -}; + if (!this._original || + typeof this._original !== 'object') { + return this.details[0].message; + } -exports.symbols = { - any: Symbol.for('@hapi/joi/schema'), // Used to internally identify any-based types (shared with other joi versions) - arraySingle: Symbol('arraySingle'), - deepDefault: Symbol('deepDefault'), - errors: Symbol('errors'), - literal: Symbol('literal'), - override: Symbol('override'), - parent: Symbol('parent'), - prefs: Symbol('prefs'), - ref: Symbol('ref'), - template: Symbol('template'), - values: Symbol('values') -}; + const redFgEscape = stripColorCodes ? '' : '\u001b[31m'; + const redBgEscape = stripColorCodes ? '' : '\u001b[41m'; + const endColor = stripColorCodes ? '' : '\u001b[0m'; + const obj = Clone(this._original); -exports.assertOptions = function (options, keys, name = 'Options') { + for (let i = this.details.length - 1; i >= 0; --i) { // Reverse order to process deepest child first + const pos = i + 1; + const error = this.details[i]; + const path = error.path; + let node = obj; + for (let j = 0; ; ++j) { + const seg = path[j]; - Assert(options && typeof options === 'object' && !Array.isArray(options), 'Options must be of type object'); - const unknownKeys = Object.keys(options).filter((k) => !keys.includes(k)); - Assert(unknownKeys.length === 0, `${name} contain unknown keys: ${unknownKeys}`); -}; + if (Common.isSchema(node)) { + node = node.clone(); // joi schemas are not cloned by hoek, we have to take this extra step + } + if (j + 1 < path.length && + typeof node[seg] !== 'string') { -exports.checkPreferences = function (prefs) { + node = node[seg]; + } + else { + const refAnnotations = node[internals.annotations] || { errors: {}, missing: {} }; + node[internals.annotations] = refAnnotations; - Schemas = Schemas || __nccwpck_require__(85614); + const cacheKey = seg || error.context.key; - const result = Schemas.preferences.validate(prefs); + if (node[seg] !== undefined) { + refAnnotations.errors[cacheKey] = refAnnotations.errors[cacheKey] || []; + refAnnotations.errors[cacheKey].push(pos); + } + else { + refAnnotations.missing[cacheKey] = pos; + } - if (result.error) { - throw new AssertError([result.error.details[0].message]); + break; + } + } } -}; + const replacers = { + key: /_\$key\$_([, \d]+)_\$end\$_"/g, + missing: /"_\$miss\$_([^|]+)\|(\d+)_\$end\$_": "__missing__"/g, + arrayIndex: /\s*"_\$idx\$_([, \d]+)_\$end\$_",?\n(.*)/g, + specials: /"\[(NaN|Symbol.*|-?Infinity|function.*|\(.*)]"/g + }; -exports.compare = function (a, b, operator) { + let message = internals.safeStringify(obj, 2) + .replace(replacers.key, ($0, $1) => `" ${redFgEscape}[${$1}]${endColor}`) + .replace(replacers.missing, ($0, $1, $2) => `${redBgEscape}"${$1}"${endColor}${redFgEscape} [${$2}]: -- missing --${endColor}`) + .replace(replacers.arrayIndex, ($0, $1, $2) => `\n${$2} ${redFgEscape}[${$1}]${endColor}`) + .replace(replacers.specials, ($0, $1) => $1); - switch (operator) { - case '=': return a === b; - case '>': return a > b; - case '<': return a < b; - case '>=': return a >= b; - case '<=': return a <= b; - } -}; + message = `${message}\n${redFgEscape}`; + for (let i = 0; i < this.details.length; ++i) { + const pos = i + 1; + message = `${message}\n[${pos}] ${this.details[i].message}`; + } -exports["default"] = function (value, defaultValue) { + message = message + endColor; - return value === undefined ? defaultValue : value; + return message; }; -exports.isIsoDate = function (date) { - - return internals.isoDate.test(date); -}; - +// Inspired by json-stringify-safe -exports.isNumber = function (value) { +internals.safeStringify = function (obj, spaces) { - return typeof value === 'number' && !isNaN(value); + return JSON.stringify(obj, internals.serializer(), spaces); }; -exports.isResolvable = function (obj) { - - if (!obj) { - return false; - } +internals.serializer = function () { - return obj[exports.symbols.ref] || obj[exports.symbols.template]; -}; + const keys = []; + const stack = []; + const cycleReplacer = (key, value) => { -exports.isSchema = function (schema, options = {}) { + if (stack[0] === value) { + return '[Circular ~]'; + } - const any = schema && schema[exports.symbols.any]; - if (!any) { - return false; - } + return '[Circular ~.' + keys.slice(0, stack.indexOf(value)).join('.') + ']'; + }; - Assert(options.legacy || any.version === exports.version, 'Cannot mix different versions of joi schemas'); - return true; -}; + return function (key, value) { + if (stack.length > 0) { + const thisPos = stack.indexOf(this); + if (~thisPos) { + stack.length = thisPos + 1; + keys.length = thisPos + 1; + keys[thisPos] = key; + } + else { + stack.push(this); + keys.push(key); + } -exports.isValues = function (obj) { + if (~stack.indexOf(value)) { + value = cycleReplacer.call(this, key, value); + } + } + else { + stack.push(value); + } - return obj[exports.symbols.values]; -}; + if (value) { + const annotations = value[internals.annotations]; + if (annotations) { + if (Array.isArray(value)) { + const annotated = []; + for (let i = 0; i < value.length; ++i) { + if (annotations.errors[i]) { + annotated.push(`_$idx$_${annotations.errors[i].sort().join(', ')}_$end$_`); + } -exports.limit = function (value) { + annotated.push(value[i]); + } - return Number.isSafeInteger(value) && value >= 0; -}; + value = annotated; + } + else { + for (const errorKey in annotations.errors) { + value[`${errorKey}_$key$_${annotations.errors[errorKey].sort().join(', ')}_$end$_`] = value[errorKey]; + value[errorKey] = undefined; + } + for (const missingKey in annotations.missing) { + value[`_$miss$_${missingKey}|${annotations.missing[missingKey]}_$end$_`] = '__missing__'; + } + } -exports.preferences = function (target, source) { + return value; + } + } - Messages = Messages || __nccwpck_require__(86103); + if (value === Infinity || + value === -Infinity || + Number.isNaN(value) || + typeof value === 'function' || + typeof value === 'symbol') { - target = target || {}; - source = source || {}; + return '[' + value.toString() + ']'; + } - const merged = Object.assign({}, target, source); - if (source.errors && - target.errors) { + return value; + }; +}; - merged.errors = Object.assign({}, target.errors, source.errors); - merged.errors.wrap = Object.assign({}, target.errors.wrap, source.errors.wrap); - } - if (source.messages) { - merged.messages = Messages.compile(source.messages, target.messages); - } +/***/ }), - delete merged[exports.symbols.prefs]; - return merged; -}; +/***/ 95184: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +"use strict"; -exports.tryWithPath = function (fn, key, options = {}) { - try { - return fn(); - } - catch (err) { - if (err.path !== undefined) { - err.path = key + '.' + err.path; - } - else { - err.path = key; - } +const Assert = __nccwpck_require__(32718); +const Clone = __nccwpck_require__(85578); +const DeepEqual = __nccwpck_require__(55801); +const Merge = __nccwpck_require__(60445); - if (options.append) { - err.message = `${err.message} (${err.path})`; - } +const Cache = __nccwpck_require__(63355); +const Common = __nccwpck_require__(72448); +const Compile = __nccwpck_require__(3038); +const Errors = __nccwpck_require__(69490); +const Extend = __nccwpck_require__(86680); +const Manifest = __nccwpck_require__(87997); +const Messages = __nccwpck_require__(86103); +const Modify = __nccwpck_require__(81290); +const Ref = __nccwpck_require__(73838); +const Trace = __nccwpck_require__(43171); +const Validator = __nccwpck_require__(91804); +const Values = __nccwpck_require__(71944); - throw err; - } -}; +const internals = {}; -exports.validateArg = function (value, label, { assert, message }) { - if (exports.isSchema(assert)) { - const result = assert.validate(value); - if (!result.error) { - return; - } +internals.Base = class { - return result.error.message; - } - else if (!assert(value)) { - return label ? `${label} ${message}` : message; - } -}; + constructor(type) { + // Naming: public, _private, $_extension, $_mutate{action} -exports.verifyFlat = function (args, method) { + this.type = type; - for (const arg of args) { - Assert(!Array.isArray(arg), 'Method no longer accepts array arguments:', method); + this.$_root = null; + this._definition = {}; + this._reset(); } -}; + _reset() { -/***/ }), + this._ids = new Modify.Ids(); + this._preferences = null; + this._refs = new Ref.Manager(); + this._cache = null; -/***/ 3038: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + this._valids = null; + this._invalids = null; -"use strict"; + this._flags = {}; + this._rules = []; + this._singleRules = new Map(); // The rule options passed for non-multi rules + + this.$_terms = {}; // Hash of arrays of immutable objects (extended by other types) + this.$_temp = { // Runtime state (not cloned) + ruleset: null, // null: use last, false: error, number: start position + whens: {} // Runtime cache of generated whens + }; + } -const Assert = __nccwpck_require__(32718); + // Manifest -const Common = __nccwpck_require__(72448); -const Ref = __nccwpck_require__(73838); + describe() { + Assert(typeof Manifest.describe === 'function', 'Manifest functionality disabled'); + return Manifest.describe(this); + } -const internals = {}; + // Rules + allow(...values) { -exports.schema = function (Joi, config, options = {}) { + Common.verifyFlat(values, 'allow'); + return this._values(values, '_valids'); + } - Common.assertOptions(options, ['appendPath', 'override']); + alter(targets) { - try { - return internals.schema(Joi, config, options); - } - catch (err) { - if (options.appendPath && - err.path !== undefined) { + Assert(targets && typeof targets === 'object' && !Array.isArray(targets), 'Invalid targets argument'); + Assert(!this._inRuleset(), 'Cannot set alterations inside a ruleset'); - err.message = `${err.message} (${err.path})`; + const obj = this.clone(); + obj.$_terms.alterations = obj.$_terms.alterations || []; + for (const target in targets) { + const adjuster = targets[target]; + Assert(typeof adjuster === 'function', 'Alteration adjuster for', target, 'must be a function'); + obj.$_terms.alterations.push({ target, adjuster }); } - throw err; + obj.$_temp.ruleset = false; + return obj; } -}; - - -internals.schema = function (Joi, config, options) { - Assert(config !== undefined, 'Invalid undefined schema'); + artifact(id) { - if (Array.isArray(config)) { - Assert(config.length, 'Invalid empty array schema'); + Assert(id !== undefined, 'Artifact cannot be undefined'); + Assert(!this._cache, 'Cannot set an artifact with a rule cache'); - if (config.length === 1) { - config = config[0]; - } + return this.$_setFlag('artifact', id); } - const valid = (base, ...values) => { - - if (options.override !== false) { - return base.valid(Joi.override, ...values); - } + cast(to) { - return base.valid(...values); - }; + Assert(to === false || typeof to === 'string', 'Invalid to value'); + Assert(to === false || this._definition.cast[to], 'Type', this.type, 'does not support casting to', to); - if (internals.simple(config)) { - return valid(Joi, config); + return this.$_setFlag('cast', to === false ? undefined : to); } - if (typeof config === 'function') { - return Joi.custom(config); + default(value, options) { + + return this._default('default', value, options); } - Assert(typeof config === 'object', 'Invalid schema content:', typeof config); + description(desc) { - if (Common.isResolvable(config)) { - return valid(Joi, config); - } + Assert(desc && typeof desc === 'string', 'Description must be a non-empty string'); - if (Common.isSchema(config)) { - return config; + return this.$_setFlag('description', desc); } - if (Array.isArray(config)) { - for (const item of config) { - if (!internals.simple(item)) { - return Joi.alternatives().try(...config); - } - } + empty(schema) { - return valid(Joi, ...config); - } + const obj = this.clone(); - if (config instanceof RegExp) { - return Joi.string().regex(config); - } + if (schema !== undefined) { + schema = obj.$_compile(schema, { override: false }); + } - if (config instanceof Date) { - return valid(Joi.date(), config); + return obj.$_setFlag('empty', schema, { clone: false }); } - Assert(Object.getPrototypeOf(config) === Object.getPrototypeOf({}), 'Schema can only contain plain objects'); + error(err) { - return Joi.object().keys(config); -}; + Assert(err, 'Missing error'); + Assert(err instanceof Error || typeof err === 'function', 'Must provide a valid Error object or a function'); + return this.$_setFlag('error', err); + } -exports.ref = function (id, options) { + example(example, options = {}) { - return Ref.isRef(id) ? id : Ref.create(id, options); -}; + Assert(example !== undefined, 'Missing example'); + Common.assertOptions(options, ['override']); + return this._inner('examples', example, { single: true, override: options.override }); + } -exports.compile = function (root, schema, options = {}) { + external(method, description) { - Common.assertOptions(options, ['legacy']); + if (typeof method === 'object') { + Assert(!description, 'Cannot combine options with description'); + description = method.description; + method = method.method; + } - // Compiled by any supported version + Assert(typeof method === 'function', 'Method must be a function'); + Assert(description === undefined || description && typeof description === 'string', 'Description must be a non-empty string'); - const any = schema && schema[Common.symbols.any]; - if (any) { - Assert(options.legacy || any.version === Common.version, 'Cannot mix different versions of joi schemas:', any.version, Common.version); - return schema; + return this._inner('externals', { method, description }, { single: true }); } - // Uncompiled root - - if (typeof schema !== 'object' || - !options.legacy) { + failover(value, options) { - return exports.schema(root, schema, { appendPath: true }); // Will error if schema contains other versions + return this._default('failover', value, options); } - // Scan schema for compiled parts + forbidden() { - const compiler = internals.walk(schema); - if (!compiler) { - return exports.schema(root, schema, { appendPath: true }); + return this.presence('forbidden'); } - return compiler.compile(compiler.root, schema); -}; + id(id) { + if (!id) { + return this.$_setFlag('id', undefined); + } -internals.walk = function (schema) { + Assert(typeof id === 'string', 'id must be a non-empty string'); + Assert(/^[^\.]+$/.test(id), 'id cannot contain period character'); - if (typeof schema !== 'object') { - return null; + return this.$_setFlag('id', id); } - if (Array.isArray(schema)) { - for (const item of schema) { - const compiler = internals.walk(item); - if (compiler) { - return compiler; - } - } + invalid(...values) { - return null; + return this._values(values, '_invalids'); } - const any = schema[Common.symbols.any]; - if (any) { - return { root: schema[any.root], compile: any.compile }; - } + label(name) { - Assert(Object.getPrototypeOf(schema) === Object.getPrototypeOf({}), 'Schema can only contain plain objects'); + Assert(name && typeof name === 'string', 'Label name must be a non-empty string'); - for (const key in schema) { - const compiler = internals.walk(schema[key]); - if (compiler) { - return compiler; - } + return this.$_setFlag('label', name); } - return null; -}; - - -internals.simple = function (value) { + meta(meta) { - return value === null || ['boolean', 'string', 'number'].includes(typeof value); -}; + Assert(meta !== undefined, 'Meta cannot be undefined'); + return this._inner('metas', meta, { single: true }); + } -exports.when = function (schema, condition, options) { + note(...notes) { - if (options === undefined) { - Assert(condition && typeof condition === 'object', 'Missing options'); + Assert(notes.length, 'Missing notes'); + for (const note of notes) { + Assert(note && typeof note === 'string', 'Notes must be non-empty strings'); + } - options = condition; - condition = Ref.create('.'); + return this._inner('notes', notes); } - if (Array.isArray(options)) { - options = { switch: options }; - } + only(mode = true) { - Common.assertOptions(options, ['is', 'not', 'then', 'otherwise', 'switch', 'break']); + Assert(typeof mode === 'boolean', 'Invalid mode:', mode); - // Schema condition + return this.$_setFlag('only', mode); + } - if (Common.isSchema(condition)) { - Assert(options.is === undefined, '"is" can not be used with a schema condition'); - Assert(options.not === undefined, '"not" can not be used with a schema condition'); - Assert(options.switch === undefined, '"switch" can not be used with a schema condition'); + optional() { - return internals.condition(schema, { is: condition, then: options.then, otherwise: options.otherwise, break: options.break }); + return this.presence('optional'); } - // Single condition + prefs(prefs) { - Assert(Ref.isRef(condition) || typeof condition === 'string', 'Invalid condition:', condition); - Assert(options.not === undefined || options.is === undefined, 'Cannot combine "is" with "not"'); + Assert(prefs, 'Missing preferences'); + Assert(prefs.context === undefined, 'Cannot override context'); + Assert(prefs.externals === undefined, 'Cannot override externals'); + Assert(prefs.warnings === undefined, 'Cannot override warnings'); + Assert(prefs.debug === undefined, 'Cannot override debug'); - if (options.switch === undefined) { - let rule = options; - if (options.not !== undefined) { - rule = { is: options.not, then: options.otherwise, otherwise: options.then, break: options.break }; - } + Common.checkPreferences(prefs); - let is = rule.is !== undefined ? schema.$_compile(rule.is) : schema.$_root.invalid(null, false, 0, '').required(); - Assert(rule.then !== undefined || rule.otherwise !== undefined, 'options must have at least one of "then", "otherwise", or "switch"'); - Assert(rule.break === undefined || rule.then === undefined || rule.otherwise === undefined, 'Cannot specify then, otherwise, and break all together'); + const obj = this.clone(); + obj._preferences = Common.preferences(obj._preferences, prefs); + return obj; + } - if (options.is !== undefined && - !Ref.isRef(options.is) && - !Common.isSchema(options.is)) { + presence(mode) { - is = is.required(); // Only apply required if this wasn't already a schema or a ref - } + Assert(['optional', 'required', 'forbidden'].includes(mode), 'Unknown presence mode', mode); - return internals.condition(schema, { ref: exports.ref(condition), is, then: rule.then, otherwise: rule.otherwise, break: rule.break }); + return this.$_setFlag('presence', mode); } - // Switch statement - - Assert(Array.isArray(options.switch), '"switch" must be an array'); - Assert(options.is === undefined, 'Cannot combine "switch" with "is"'); - Assert(options.not === undefined, 'Cannot combine "switch" with "not"'); - Assert(options.then === undefined, 'Cannot combine "switch" with "then"'); + raw(enabled = true) { - const rule = { - ref: exports.ref(condition), - switch: [], - break: options.break - }; + return this.$_setFlag('result', enabled ? 'raw' : undefined); + } - for (let i = 0; i < options.switch.length; ++i) { - const test = options.switch[i]; - const last = i === options.switch.length - 1; + result(mode) { - Common.assertOptions(test, last ? ['is', 'then', 'otherwise'] : ['is', 'then']); + Assert(['raw', 'strip'].includes(mode), 'Unknown result mode', mode); - Assert(test.is !== undefined, 'Switch statement missing "is"'); - Assert(test.then !== undefined, 'Switch statement missing "then"'); + return this.$_setFlag('result', mode); + } - const item = { - is: schema.$_compile(test.is), - then: schema.$_compile(test.then) - }; + required() { - if (!Ref.isRef(test.is) && - !Common.isSchema(test.is)) { + return this.presence('required'); + } - item.is = item.is.required(); // Only apply required if this wasn't already a schema or a ref - } + strict(enabled) { - if (last) { - Assert(options.otherwise === undefined || test.otherwise === undefined, 'Cannot specify "otherwise" inside and outside a "switch"'); - const otherwise = options.otherwise !== undefined ? options.otherwise : test.otherwise; - if (otherwise !== undefined) { - Assert(rule.break === undefined, 'Cannot specify both otherwise and break'); - item.otherwise = schema.$_compile(otherwise); - } - } + const obj = this.clone(); - rule.switch.push(item); + const convert = enabled === undefined ? false : !enabled; + obj._preferences = Common.preferences(obj._preferences, { convert }); + return obj; } - return rule; -}; + strip(enabled = true) { + return this.$_setFlag('result', enabled ? 'strip' : undefined); + } -internals.condition = function (schema, condition) { + tag(...tags) { - for (const key of ['then', 'otherwise']) { - if (condition[key] === undefined) { - delete condition[key]; - } - else { - condition[key] = schema.$_compile(condition[key]); + Assert(tags.length, 'Missing tags'); + for (const tag of tags) { + Assert(tag && typeof tag === 'string', 'Tags must be non-empty strings'); } + + return this._inner('tags', tags); } - return condition; -}; + unit(name) { + Assert(name && typeof name === 'string', 'Unit name must be a non-empty string'); -/***/ }), + return this.$_setFlag('unit', name); + } -/***/ 69490: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + valid(...values) { -"use strict"; + Common.verifyFlat(values, 'valid'); + const obj = this.allow(...values); + obj.$_setFlag('only', !!obj._valids, { clone: false }); + return obj; + } -const Annotate = __nccwpck_require__(46014); -const Common = __nccwpck_require__(72448); -const Template = __nccwpck_require__(51396); + when(condition, options) { + const obj = this.clone(); -const internals = {}; + if (!obj.$_terms.whens) { + obj.$_terms.whens = []; + } + const when = Compile.when(obj, condition, options); + if (!['any', 'link'].includes(obj.type)) { + const conditions = when.is ? [when] : when.switch; + for (const item of conditions) { + Assert(!item.then || item.then.type === 'any' || item.then.type === obj.type, 'Cannot combine', obj.type, 'with', item.then && item.then.type); + Assert(!item.otherwise || item.otherwise.type === 'any' || item.otherwise.type === obj.type, 'Cannot combine', obj.type, 'with', item.otherwise && item.otherwise.type); -exports.Report = class { + } + } - constructor(code, value, local, flags, messages, state, prefs) { + obj.$_terms.whens.push(when); + return obj.$_mutateRebuild(); + } - this.code = code; - this.flags = flags; - this.messages = messages; - this.path = state.path; - this.prefs = prefs; - this.state = state; - this.value = value; + // Helpers - this.message = null; - this.template = null; + cache(cache) { - this.local = local || {}; - this.local.label = exports.label(this.flags, this.state, this.prefs, this.messages); + Assert(!this._inRuleset(), 'Cannot set caching inside a ruleset'); + Assert(!this._cache, 'Cannot override schema cache'); + Assert(this._flags.artifact === undefined, 'Cannot cache a rule with an artifact'); - if (this.value !== undefined && - !this.local.hasOwnProperty('value')) { + const obj = this.clone(); + obj._cache = cache || Cache.provider.provision(); + obj.$_temp.ruleset = false; + return obj; + } - this.local.value = this.value; - } + clone() { - if (this.path.length) { - const key = this.path[this.path.length - 1]; - if (typeof key !== 'object') { - this.local.key = key; - } - } + const obj = Object.create(Object.getPrototypeOf(this)); + return this._assign(obj); } - _setTemplate(template) { - - this.template = template; + concat(source) { - if (!this.flags.label && - this.path.length === 0) { + Assert(Common.isSchema(source), 'Invalid schema object'); + Assert(this.type === 'any' || source.type === 'any' || source.type === this.type, 'Cannot merge type', this.type, 'with another type:', source.type); + Assert(!this._inRuleset(), 'Cannot concatenate onto a schema with open ruleset'); + Assert(!source._inRuleset(), 'Cannot concatenate a schema with open ruleset'); - const localized = this._template(this.template, 'root'); - if (localized) { - this.local.label = localized; - } - } - } + let obj = this.clone(); - toString() { + if (this.type === 'any' && + source.type !== 'any') { - if (this.message) { - return this.message; - } + // Change obj to match source type - const code = this.code; + const tmpObj = source.clone(); + for (const key of Object.keys(obj)) { + if (key !== 'type') { + tmpObj[key] = obj[key]; + } + } - if (!this.prefs.errors.render) { - return this.code; + obj = tmpObj; } - const template = this._template(this.template) || - this._template(this.prefs.messages) || - this._template(this.messages); + obj._ids.concat(source._ids); + obj._refs.register(source, Ref.toSibling); - if (template === undefined) { - return `Error code "${code}" is not defined, your custom type is missing the correct messages definition`; - } + obj._preferences = obj._preferences ? Common.preferences(obj._preferences, source._preferences) : source._preferences; + obj._valids = Values.merge(obj._valids, source._valids, source._invalids); + obj._invalids = Values.merge(obj._invalids, source._invalids, source._valids); - // Render and cache result + // Remove unique rules present in source - this.message = template.render(this.value, this.state, this.prefs, this.local, { errors: this.prefs.errors, messages: [this.prefs.messages, this.messages] }); - if (!this.prefs.errors.label) { - this.message = this.message.replace(/^"" /, '').trim(); + for (const name of source._singleRules.keys()) { + if (obj._singleRules.has(name)) { + obj._rules = obj._rules.filter((target) => target.keep || target.name !== name); + obj._singleRules.delete(name); + } } - return this.message; - } + // Rules - _template(messages, code) { + for (const test of source._rules) { + if (!source._definition.rules[test.method].multi) { + obj._singleRules.set(test.name, test); + } - return exports.template(this.value, messages, code || this.code, this.state, this.prefs); - } -}; + obj._rules.push(test); + } + // Flags -exports.path = function (path) { + if (obj._flags.empty && + source._flags.empty) { - let label = ''; - for (const segment of path) { - if (typeof segment === 'object') { // Exclude array single path segment - continue; + obj._flags.empty = obj._flags.empty.concat(source._flags.empty); + const flags = Object.assign({}, source._flags); + delete flags.empty; + Merge(obj._flags, flags); } - - if (typeof segment === 'string') { - if (label) { - label += '.'; - } - - label += segment; + else if (source._flags.empty) { + obj._flags.empty = source._flags.empty; + const flags = Object.assign({}, source._flags); + delete flags.empty; + Merge(obj._flags, flags); } else { - label += `[${segment}]`; + Merge(obj._flags, source._flags); } - } - return label; -}; - - -exports.template = function (value, messages, code, state, prefs) { - - if (!messages) { - return; - } - - if (Template.isTemplate(messages)) { - return code !== 'root' ? messages : null; - } + // Terms - let lang = prefs.errors.language; - if (Common.isResolvable(lang)) { - lang = lang.resolve(value, state, prefs); - } + for (const key in source.$_terms) { + const terms = source.$_terms[key]; + if (!terms) { + if (!obj.$_terms[key]) { + obj.$_terms[key] = terms; + } - if (lang && - messages[lang]) { + continue; + } - if (messages[lang][code] !== undefined) { - return messages[lang][code]; - } + if (!obj.$_terms[key]) { + obj.$_terms[key] = terms.slice(); + continue; + } - if (messages[lang]['*'] !== undefined) { - return messages[lang]['*']; + obj.$_terms[key] = obj.$_terms[key].concat(terms); } - } - - if (!messages[code]) { - return messages['*']; - } - return messages[code]; -}; + // Tracing + if (this.$_root._tracer) { + this.$_root._tracer._combine(obj, [this, source]); + } -exports.label = function (flags, state, prefs, messages) { + // Rebuild - if (flags.label) { - return flags.label; + return obj.$_mutateRebuild(); } - if (!prefs.errors.label) { - return ''; - } + extend(options) { - let path = state.path; - if (prefs.errors.label === 'key' && - state.path.length > 1) { + Assert(!options.base, 'Cannot extend type with another base'); - path = state.path.slice(-1); + return Extend.type(this, options); } - const normalized = exports.path(path); - if (normalized) { - return normalized; - } + extract(path) { - return exports.template(null, prefs.messages, 'root', state, prefs) || - messages && exports.template(null, messages, 'root', state, prefs) || - 'value'; -}; + path = Array.isArray(path) ? path : path.split('.'); + return this._ids.reach(path); + } + fork(paths, adjuster) { -exports.process = function (errors, original, prefs) { + Assert(!this._inRuleset(), 'Cannot fork inside a ruleset'); - if (!errors) { - return null; - } + let obj = this; // eslint-disable-line consistent-this + for (let path of [].concat(paths)) { + path = Array.isArray(path) ? path : path.split('.'); + obj = obj._ids.fork(path, adjuster, obj); + } - const { override, message, details } = exports.details(errors); - if (override) { - return override; + obj.$_temp.ruleset = false; + return obj; } - if (prefs.errors.stack) { - return new exports.ValidationError(message, details, original); - } + rule(options) { - const limit = Error.stackTraceLimit; - Error.stackTraceLimit = 0; - const validationError = new exports.ValidationError(message, details, original); - Error.stackTraceLimit = limit; - return validationError; -}; + const def = this._definition; + Common.assertOptions(options, Object.keys(def.modifiers)); + Assert(this.$_temp.ruleset !== false, 'Cannot apply rules to empty ruleset or the last rule added does not support rule properties'); + const start = this.$_temp.ruleset === null ? this._rules.length - 1 : this.$_temp.ruleset; + Assert(start >= 0 && start < this._rules.length, 'Cannot apply rules to empty ruleset'); -exports.details = function (errors, options = {}) { + const obj = this.clone(); - let messages = []; - const details = []; + for (let i = start; i < obj._rules.length; ++i) { + const original = obj._rules[i]; + const rule = Clone(original); - for (const item of errors) { + for (const name in options) { + def.modifiers[name](rule, options[name]); + Assert(rule.name === original.name, 'Cannot change rule name'); + } - // Override + obj._rules[i] = rule; - if (item instanceof Error) { - if (options.override !== false) { - return { override: item }; + if (obj._singleRules.get(rule.name) === original) { + obj._singleRules.set(rule.name, rule); } + } - const message = item.toString(); - messages.push(message); + obj.$_temp.ruleset = false; + return obj.$_mutateRebuild(); + } - details.push({ - message, - type: 'override', - context: { error: item } - }); + get ruleset() { - continue; - } + Assert(!this._inRuleset(), 'Cannot start a new ruleset without closing the previous one'); - // Report + const obj = this.clone(); + obj.$_temp.ruleset = obj._rules.length; + return obj; + } - const message = item.toString(); - messages.push(message); + get $() { - details.push({ - message, - path: item.path.filter((v) => typeof v !== 'object'), - type: item.code, - context: item.local - }); + return this.ruleset; } - if (messages.length > 1) { - messages = [...new Set(messages)]; - } + tailor(targets) { - return { message: messages.join('. '), details }; -}; + targets = [].concat(targets); + Assert(!this._inRuleset(), 'Cannot tailor inside a ruleset'); -exports.ValidationError = class extends Error { + let obj = this; // eslint-disable-line consistent-this - constructor(message, details, original) { + if (this.$_terms.alterations) { + for (const { target, adjuster } of this.$_terms.alterations) { + if (targets.includes(target)) { + obj = adjuster(obj); + Assert(Common.isSchema(obj), 'Alteration adjuster for', target, 'failed to return a schema object'); + } + } + } - super(message); - this._original = original; - this.details = details; + obj = obj.$_modify({ each: (item) => item.tailor(targets), ref: false }); + obj.$_temp.ruleset = false; + return obj.$_mutateRebuild(); } - static isError(err) { + tracer() { - return err instanceof exports.ValidationError; + return Trace.location ? Trace.location(this) : this; // $lab:coverage:ignore$ } -}; + validate(value, options) { -exports.ValidationError.prototype.isJoi = true; + return Validator.entry(value, this, options); + } -exports.ValidationError.prototype.name = 'ValidationError'; + validateAsync(value, options) { -exports.ValidationError.prototype.annotate = Annotate.error; + return Validator.entryAsync(value, this, options); + } + // Extensions -/***/ }), + $_addRule(options) { -/***/ 86680: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + // Normalize rule -"use strict"; + if (typeof options === 'string') { + options = { name: options }; + } + Assert(options && typeof options === 'object', 'Invalid options'); + Assert(options.name && typeof options.name === 'string', 'Invalid rule name'); -const Assert = __nccwpck_require__(32718); -const Clone = __nccwpck_require__(85578); + for (const key in options) { + Assert(key[0] !== '_', 'Cannot set private rule properties'); + } -const Common = __nccwpck_require__(72448); -const Messages = __nccwpck_require__(86103); + const rule = Object.assign({}, options); // Shallow cloned + rule._resolve = []; + rule.method = rule.method || rule.name; + const definition = this._definition.rules[rule.method]; + const args = rule.args; -const internals = {}; + Assert(definition, 'Unknown rule', rule.method); + // Args -exports.type = function (from, options) { + const obj = this.clone(); - const base = Object.getPrototypeOf(from); - const prototype = Clone(base); - const schema = from._assign(Object.create(prototype)); - const def = Object.assign({}, options); // Shallow cloned - delete def.base; + if (args) { + Assert(Object.keys(args).length === 1 || Object.keys(args).length === this._definition.rules[rule.name].args.length, 'Invalid rule definition for', this.type, rule.name); - prototype._definition = def; + for (const key in args) { + let arg = args[key]; + if (arg === undefined) { + delete args[key]; + continue; + } - const parent = base._definition || {}; - def.messages = Messages.merge(parent.messages, def.messages); - def.properties = Object.assign({}, parent.properties, def.properties); + if (definition.argsByName) { + const resolver = definition.argsByName.get(key); - // Type + if (resolver.ref && + Common.isResolvable(arg)) { - schema.type = def.type; + rule._resolve.push(key); + obj.$_mutateRegister(arg); + } + else { + if (resolver.normalize) { + arg = resolver.normalize(arg); + args[key] = arg; + } - // Flags + if (resolver.assert) { + const error = Common.validateArg(arg, key, resolver); + Assert(!error, error, 'or reference'); + } + } + } - def.flags = Object.assign({}, parent.flags, def.flags); + args[key] = arg; + } + } - // Terms + // Unique rules - const terms = Object.assign({}, parent.terms); - if (def.terms) { - for (const name in def.terms) { // Only apply own terms - const term = def.terms[name]; - Assert(schema.$_terms[name] === undefined, 'Invalid term override for', def.type, name); - schema.$_terms[name] = term.init; - terms[name] = term; + if (!definition.multi) { + obj._ruleRemove(rule.name, { clone: false }); + obj._singleRules.set(rule.name, rule); } - } - def.terms = terms; + if (obj.$_temp.ruleset === false) { + obj.$_temp.ruleset = null; + } - // Constructor arguments + if (definition.priority) { + obj._rules.unshift(rule); + } + else { + obj._rules.push(rule); + } - if (!def.args) { - def.args = parent.args; + return obj; } - // Prepare - - def.prepare = internals.prepare(def.prepare, parent.prepare); - - // Coerce - - if (def.coerce) { - if (typeof def.coerce === 'function') { - def.coerce = { method: def.coerce }; - } - - if (def.coerce.from && - !Array.isArray(def.coerce.from)) { + $_compile(schema, options) { - def.coerce = { method: def.coerce.method, from: [].concat(def.coerce.from) }; - } + return Compile.schema(this.$_root, schema, options); } - def.coerce = internals.coerce(def.coerce, parent.coerce); - - // Validate + $_createError(code, value, local, state, prefs, options = {}) { - def.validate = internals.validate(def.validate, parent.validate); + const flags = options.flags !== false ? this._flags : {}; + const messages = options.messages ? Messages.merge(this._definition.messages, options.messages) : this._definition.messages; + return new Errors.Report(code, value, local, flags, messages, state, prefs); + } - // Rules + $_getFlag(name) { - const rules = Object.assign({}, parent.rules); - if (def.rules) { - for (const name in def.rules) { - const rule = def.rules[name]; - Assert(typeof rule === 'object', 'Invalid rule definition for', def.type, name); + return this._flags[name]; + } - let method = rule.method; - if (method === undefined) { - method = function () { + $_getRule(name) { - return this.$_addRule(name); - }; - } + return this._singleRules.get(name); + } - if (method) { - Assert(!prototype[name], 'Rule conflict in', def.type, name); - prototype[name] = method; - } + $_mapLabels(path) { - Assert(!rules[name], 'Rule conflict in', def.type, name); - rules[name] = rule; + path = Array.isArray(path) ? path : path.split('.'); + return this._ids.labels(path); + } - if (rule.alias) { - const aliases = [].concat(rule.alias); - for (const alias of aliases) { - prototype[alias] = rule.method; - } - } + $_match(value, state, prefs, overrides) { - if (rule.args) { - rule.argsByName = new Map(); - rule.args = rule.args.map((arg) => { + prefs = Object.assign({}, prefs); // Shallow cloned + prefs.abortEarly = true; + prefs._externals = false; - if (typeof arg === 'string') { - arg = { name: arg }; - } + state.snapshot(); + const result = !Validator.validate(value, this, state, prefs, overrides).errors; + state.restore(); - Assert(!rule.argsByName.has(arg.name), 'Duplicated argument name', arg.name); + return result; + } - if (Common.isSchema(arg.assert)) { - arg.assert = arg.assert.strict().label(arg.name); - } + $_modify(options) { - rule.argsByName.set(arg.name, arg); - return arg; - }); - } - } + Common.assertOptions(options, ['each', 'once', 'ref', 'schema']); + return Modify.schema(this, options) || this; } - def.rules = rules; + $_mutateRebuild() { - // Modifiers + Assert(!this._inRuleset(), 'Cannot add this rule inside a ruleset'); - const modifiers = Object.assign({}, parent.modifiers); - if (def.modifiers) { - for (const name in def.modifiers) { - Assert(!prototype[name], 'Rule conflict in', def.type, name); + this._refs.reset(); + this._ids.reset(); - const modifier = def.modifiers[name]; - Assert(typeof modifier === 'function', 'Invalid modifier definition for', def.type, name); + const each = (item, { source, name, path, key }) => { - const method = function (arg) { + const family = this._definition[source][name] && this._definition[source][name].register; + if (family !== false) { + this.$_mutateRegister(item, { family, key }); + } + }; - return this.rule({ [name]: arg }); - }; + this.$_modify({ each }); - prototype[name] = method; - modifiers[name] = modifier; + if (this._definition.rebuild) { + this._definition.rebuild(this); } + + this.$_temp.ruleset = false; + return this; } - def.modifiers = modifiers; + $_mutateRegister(schema, { family, key } = {}) { - // Overrides + this._refs.register(schema, family); + this._ids.register(schema, { key }); + } - if (def.overrides) { - prototype._super = base; - schema.$_super = {}; // Backwards compatibility - for (const override in def.overrides) { - Assert(base[override], 'Cannot override missing', override); - def.overrides[override][Common.symbols.parent] = base[override]; - schema.$_super[override] = base[override].bind(schema); // Backwards compatibility - } + $_property(name) { - Object.assign(prototype, def.overrides); + return this._definition.properties[name]; } - // Casts + $_reach(path) { - def.cast = Object.assign({}, parent.cast, def.cast); + return this._ids.reach(path); + } - // Manifest + $_rootReferences() { - const manifest = Object.assign({}, parent.manifest, def.manifest); - manifest.build = internals.build(def.manifest && def.manifest.build, parent.manifest && parent.manifest.build); - def.manifest = manifest; + return this._refs.roots(); + } - // Rebuild + $_setFlag(name, value, options = {}) { - def.rebuild = internals.rebuild(def.rebuild, parent.rebuild); + Assert(name[0] === '_' || !this._inRuleset(), 'Cannot set flag inside a ruleset'); - return schema; -}; + const flag = this._definition.flags[name] || {}; + if (DeepEqual(value, flag.default)) { + value = undefined; + } + if (DeepEqual(value, this._flags[name])) { + return this; + } -// Helpers + const obj = options.clone !== false ? this.clone() : this; -internals.build = function (child, parent) { + if (value !== undefined) { + obj._flags[name] = value; + obj.$_mutateRegister(value); + } + else { + delete obj._flags[name]; + } - if (!child || - !parent) { + if (name[0] !== '_') { + obj.$_temp.ruleset = false; + } - return child || parent; + return obj; } - return function (obj, desc) { - - return parent(child(obj, desc), desc); - }; -}; - - -internals.coerce = function (child, parent) { - - if (!child || - !parent) { + $_parent(method, ...args) { - return child || parent; + return this[method][Common.symbols.parent].call(this, ...args); } - return { - from: child.from && parent.from ? [...new Set([...child.from, ...parent.from])] : null, - method(value, helpers) { - - let coerced; - if (!parent.from || - parent.from.includes(typeof value)) { - - coerced = parent.method(value, helpers); - if (coerced) { - if (coerced.errors || - coerced.value === undefined) { - - return coerced; - } - - value = coerced.value; - } - } - - if (!child.from || - child.from.includes(typeof value)) { + $_validate(value, state, prefs) { - const own = child.method(value, helpers); - if (own) { - return own; - } - } + return Validator.validate(value, this, state, prefs); + } - return coerced; - } - }; -}; + // Internals + _assign(target) { -internals.prepare = function (child, parent) { + target.type = this.type; - if (!child || - !parent) { + target.$_root = this.$_root; - return child || parent; - } + target.$_temp = Object.assign({}, this.$_temp); + target.$_temp.whens = {}; - return function (value, helpers) { + target._ids = this._ids.clone(); + target._preferences = this._preferences; + target._valids = this._valids && this._valids.clone(); + target._invalids = this._invalids && this._invalids.clone(); + target._rules = this._rules.slice(); + target._singleRules = Clone(this._singleRules, { shallow: true }); + target._refs = this._refs.clone(); + target._flags = Object.assign({}, this._flags); + target._cache = null; - const prepared = child(value, helpers); - if (prepared) { - if (prepared.errors || - prepared.value === undefined) { + target.$_terms = {}; + for (const key in this.$_terms) { + target.$_terms[key] = this.$_terms[key] ? this.$_terms[key].slice() : null; + } - return prepared; - } + // Backwards compatibility - value = prepared.value; + target.$_super = {}; + for (const override in this.$_super) { + target.$_super[override] = this._super[override].bind(target); } - return parent(value, helpers) || prepared; - }; -}; + return target; + } + _bare() { -internals.rebuild = function (child, parent) { + const obj = this.clone(); + obj._reset(); - if (!child || - !parent) { + const terms = obj._definition.terms; + for (const name in terms) { + const term = terms[name]; + obj.$_terms[name] = term.init; + } - return child || parent; + return obj.$_mutateRebuild(); } - return function (schema) { + _default(flag, value, options = {}) { - parent(schema); - child(schema); - }; -}; + Common.assertOptions(options, 'literal'); + Assert(value !== undefined, 'Missing', flag, 'value'); + Assert(typeof value === 'function' || !options.literal, 'Only function value supports literal option'); -internals.validate = function (child, parent) { + if (typeof value === 'function' && + options.literal) { - if (!child || - !parent) { + value = { + [Common.symbols.literal]: true, + literal: value + }; + } - return child || parent; + const obj = this.$_setFlag(flag, value); + return obj; } - return function (value, helpers) { + _generate(value, state, prefs) { - const result = parent(value, helpers); - if (result) { - if (result.errors && - (!Array.isArray(result.errors) || result.errors.length)) { + if (!this.$_terms.whens) { + return { schema: this }; + } - return result; - } + // Collect matching whens - value = result.value; - } + const whens = []; + const ids = []; + for (let i = 0; i < this.$_terms.whens.length; ++i) { + const when = this.$_terms.whens[i]; - return child(value, helpers) || result; - }; -}; + if (when.concat) { + whens.push(when.concat); + ids.push(`${i}.concat`); + continue; + } + const input = when.ref ? when.ref.resolve(value, state, prefs) : value; + const tests = when.is ? [when] : when.switch; + const before = ids.length; -/***/ }), + for (let j = 0; j < tests.length; ++j) { + const { is, then, otherwise } = tests[j]; -/***/ 20918: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + const baseId = `${i}${when.switch ? '.' + j : ''}`; + if (is.$_match(input, state.nest(is, `${baseId}.is`), prefs)) { + if (then) { + const localState = state.localize([...state.path, `${baseId}.then`], state.ancestors, state.schemas); + const { schema: generated, id } = then._generate(value, localState, prefs); + whens.push(generated); + ids.push(`${baseId}.then${id ? `(${id})` : ''}`); + break; + } + } + else if (otherwise) { + const localState = state.localize([...state.path, `${baseId}.otherwise`], state.ancestors, state.schemas); + const { schema: generated, id } = otherwise._generate(value, localState, prefs); + whens.push(generated); + ids.push(`${baseId}.otherwise${id ? `(${id})` : ''}`); + break; + } + } -"use strict"; + if (when.break && + ids.length > before) { // Something matched + break; + } + } -const Assert = __nccwpck_require__(32718); -const Clone = __nccwpck_require__(85578); + // Check cache -const Cache = __nccwpck_require__(63355); -const Common = __nccwpck_require__(72448); -const Compile = __nccwpck_require__(3038); -const Errors = __nccwpck_require__(69490); -const Extend = __nccwpck_require__(86680); -const Manifest = __nccwpck_require__(87997); -const Ref = __nccwpck_require__(73838); -const Template = __nccwpck_require__(51396); -const Trace = __nccwpck_require__(43171); + const id = ids.join(', '); + state.mainstay.tracer.debug(state, 'rule', 'when', id); -let Schemas; + if (!id) { + return { schema: this }; + } + if (!state.mainstay.tracer.active && + this.$_temp.whens[id]) { -const internals = { - types: { - alternatives: __nccwpck_require__(26867), - any: __nccwpck_require__(9512), - array: __nccwpck_require__(20270), - boolean: __nccwpck_require__(47489), - date: __nccwpck_require__(6624), - function: __nccwpck_require__(62269), - link: __nccwpck_require__(69869), - number: __nccwpck_require__(15855), - object: __nccwpck_require__(46878), - string: __nccwpck_require__(72260), - symbol: __nccwpck_require__(40971) - }, - aliases: { - alt: 'alternatives', - bool: 'boolean', - func: 'function' - } -}; + return { schema: this.$_temp.whens[id], id }; + } + // Generate dynamic schema -if (Buffer) { // $lab:coverage:ignore$ - internals.types.binary = __nccwpck_require__(34288); -} + let obj = this; // eslint-disable-line consistent-this + if (this._definition.generate) { + obj = this._definition.generate(this, value, state, prefs); + } + // Apply whens -internals.root = function () { + for (const when of whens) { + obj = obj.concat(when); + } - const root = { - _types: new Set(Object.keys(internals.types)) - }; + // Tracing - // Types + if (this.$_root._tracer) { + this.$_root._tracer._combine(obj, [this, ...whens]); + } - for (const type of root._types) { - root[type] = function (...args) { + // Cache result - Assert(!args.length || ['alternatives', 'link', 'object'].includes(type), 'The', type, 'type does not allow arguments'); - return internals.generate(this, internals.types[type], args); - }; + this.$_temp.whens[id] = obj; + return { schema: obj, id }; } - // Shortcuts - - for (const method of ['allow', 'custom', 'disallow', 'equal', 'exist', 'forbidden', 'invalid', 'not', 'only', 'optional', 'options', 'prefs', 'preferences', 'required', 'strip', 'valid', 'when']) { - root[method] = function (...args) { + _inner(type, values, options = {}) { - return this.any()[method](...args); - }; - } + Assert(!this._inRuleset(), `Cannot set ${type} inside a ruleset`); - // Methods + const obj = this.clone(); + if (!obj.$_terms[type] || + options.override) { - Object.assign(root, internals.methods); + obj.$_terms[type] = []; + } - // Aliases + if (options.single) { + obj.$_terms[type].push(values); + } + else { + obj.$_terms[type].push(...values); + } - for (const alias in internals.aliases) { - const target = internals.aliases[alias]; - root[alias] = root[target]; + obj.$_temp.ruleset = false; + return obj; } - root.x = root.expression; - - // Trace + _inRuleset() { - if (Trace.setup) { // $lab:coverage:ignore$ - Trace.setup(root); + return this.$_temp.ruleset !== null && this.$_temp.ruleset !== false; } - return root; -}; - + _ruleRemove(name, options = {}) { -internals.methods = { + if (!this._singleRules.has(name)) { + return this; + } - ValidationError: Errors.ValidationError, - version: Common.version, - cache: Cache.provider, + const obj = options.clone !== false ? this.clone() : this; - assert(value, schema, ...args /* [message], [options] */) { + obj._singleRules.delete(name); - internals.assert(value, schema, true, args); - }, + const filtered = []; + for (let i = 0; i < obj._rules.length; ++i) { + const test = obj._rules[i]; + if (test.name === name && + !test.keep) { - attempt(value, schema, ...args /* [message], [options] */) { + if (obj._inRuleset() && + i < obj.$_temp.ruleset) { - return internals.assert(value, schema, false, args); - }, + --obj.$_temp.ruleset; + } - build(desc) { + continue; + } - Assert(typeof Manifest.build === 'function', 'Manifest functionality disabled'); - return Manifest.build(this, desc); - }, + filtered.push(test); + } - checkPreferences(prefs) { + obj._rules = filtered; + return obj; + } - Common.checkPreferences(prefs); - }, + _values(values, key) { - compile(schema, options) { + Common.verifyFlat(values, key.slice(1, -1)); - return Compile.compile(this, schema, options); - }, + const obj = this.clone(); - defaults(modifier) { + const override = values[0] === Common.symbols.override; + if (override) { + values = values.slice(1); + } - Assert(typeof modifier === 'function', 'modifier must be a function'); + if (!obj[key] && + values.length) { - const joi = Object.assign({}, this); - for (const type of joi._types) { - const schema = modifier(joi[type]()); - Assert(Common.isSchema(schema), 'modifier must return a valid schema object'); + obj[key] = new Values(); + } + else if (override) { + obj[key] = values.length ? new Values() : null; + obj.$_mutateRebuild(); + } - joi[type] = function (...args) { + if (!obj[key]) { + return obj; + } - return internals.generate(this, schema, args); - }; + if (override) { + obj[key].override(); } - return joi; - }, + for (const value of values) { + Assert(value !== undefined, 'Cannot call allow/valid/invalid with undefined'); + Assert(value !== Common.symbols.override, 'Override must be the first value'); - expression(...args) { + const other = key === '_invalids' ? '_valids' : '_invalids'; + if (obj[other]) { + obj[other].remove(value); + if (!obj[other].length) { + Assert(key === '_valids' || !obj._flags.only, 'Setting invalid value', value, 'leaves schema rejecting all values due to previous valid rule'); + obj[other] = null; + } + } - return new Template(...args); - }, + obj[key].add(value, obj._refs); + } - extend(...extensions) { + return obj; + } +}; - Common.verifyFlat(extensions, 'extend'); - Schemas = Schemas || __nccwpck_require__(85614); +internals.Base.prototype[Common.symbols.any] = { + version: Common.version, + compile: Compile.compile, + root: '$_root' +}; - Assert(extensions.length, 'You need to provide at least one extension'); - this.assert(extensions, Schemas.extensions); - const joi = Object.assign({}, this); - joi._types = new Set(joi._types); +internals.Base.prototype.isImmutable = true; // Prevents Hoek from deep cloning schema objects (must be on prototype) - for (let extension of extensions) { - if (typeof extension === 'function') { - extension = extension(joi); - } - this.assert(extension, Schemas.extension); +// Aliases - const expanded = internals.expandExtension(extension, joi); - for (const item of expanded) { - Assert(joi[item.type] === undefined || joi._types.has(item.type), 'Cannot override name', item.type); +internals.Base.prototype.deny = internals.Base.prototype.invalid; +internals.Base.prototype.disallow = internals.Base.prototype.invalid; +internals.Base.prototype.equal = internals.Base.prototype.valid; +internals.Base.prototype.exist = internals.Base.prototype.required; +internals.Base.prototype.not = internals.Base.prototype.invalid; +internals.Base.prototype.options = internals.Base.prototype.prefs; +internals.Base.prototype.preferences = internals.Base.prototype.prefs; - const base = item.base || this.any(); - const schema = Extend.type(base, item); - joi._types.add(item.type); - joi[item.type] = function (...args) { +module.exports = new internals.Base(); - return internals.generate(this, schema, args); - }; - } - } - return joi; - }, +/***/ }), - isError: Errors.ValidationError.isError, - isExpression: Template.isTemplate, - isRef: Ref.isRef, - isSchema: Common.isSchema, +/***/ 63355: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - in(...args) { +"use strict"; - return Ref.in(...args); - }, - override: Common.symbols.override, +const Assert = __nccwpck_require__(32718); +const Clone = __nccwpck_require__(85578); - ref(...args) { +const Common = __nccwpck_require__(72448); - return Ref.create(...args); - }, - types() { +const internals = { + max: 1000, + supported: new Set(['undefined', 'boolean', 'number', 'string']) +}; - const types = {}; - for (const type of this._types) { - types[type] = this[type](); - } - for (const target in internals.aliases) { - types[target] = this[target](); - } +exports.provider = { - return types; + provision(options) { + + return new internals.Cache(options); } }; -// Helpers - -internals.assert = function (value, schema, annotate, args /* [message], [options] */) { +// Least Recently Used (LRU) Cache - const message = args[0] instanceof Error || typeof args[0] === 'string' ? args[0] : null; - const options = message ? args[1] : args[0]; - const result = schema.validate(value, Common.preferences({ errors: { stack: true } }, options || {})); +internals.Cache = class { - let error = result.error; - if (!error) { - return result.value; - } + constructor(options = {}) { - if (message instanceof Error) { - throw message; - } + Common.assertOptions(options, ['max']); + Assert(options.max === undefined || options.max && options.max > 0 && isFinite(options.max), 'Invalid max cache size'); - const display = annotate && typeof error.annotate === 'function' ? error.annotate() : error.message; + this._max = options.max || internals.max; - if (error instanceof Errors.ValidationError === false) { - error = Clone(error); + this._map = new Map(); // Map of nodes by key + this._list = new internals.List(); // List of nodes (most recently used in head) } - error.message = message ? `${message} ${display}` : display; - throw error; -}; + get length() { + return this._map.size; + } -internals.generate = function (root, schema, args) { + set(key, value) { - Assert(root, 'Must be invoked on a Joi instance.'); + if (key !== null && + !internals.supported.has(typeof key)) { - schema.$_root = root; + return; + } - if (!schema._definition.args || - !args.length) { + let node = this._map.get(key); + if (node) { + node.value = value; + this._list.first(node); + return; + } - return schema; + node = this._list.unshift({ key, value }); + this._map.set(key, node); + this._compact(); } - return schema._definition.args(schema, ...args); -}; - - -internals.expandExtension = function (extension, joi) { + get(key) { - if (typeof extension.type === 'string') { - return [extension]; + const node = this._map.get(key); + if (node) { + this._list.first(node); + return Clone(node.value); + } } - const extended = []; - for (const type of joi._types) { - if (extension.type.test(type)) { - const item = Object.assign({}, extension); - item.type = type; - item.base = joi[type](); - extended.push(item); + _compact() { + + if (this._map.size > this._max) { + const node = this._list.pop(); + this._map.delete(node.key); } } - - return extended; }; -module.exports = internals.root(); - - -/***/ }), - -/***/ 87997: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -const Assert = __nccwpck_require__(32718); -const Clone = __nccwpck_require__(85578); - -const Common = __nccwpck_require__(72448); -const Messages = __nccwpck_require__(86103); -const Ref = __nccwpck_require__(73838); -const Template = __nccwpck_require__(51396); +internals.List = class { -let Schemas; + constructor() { + this.tail = null; + this.head = null; + } -const internals = {}; + unshift(node) { + node.next = null; + node.prev = this.head; -exports.describe = function (schema) { + if (this.head) { + this.head.next = node; + } - const def = schema._definition; + this.head = node; - // Type + if (!this.tail) { + this.tail = node; + } - const desc = { - type: schema.type, - flags: {}, - rules: [] - }; + return node; + } - // Flags + first(node) { - for (const flag in schema._flags) { - if (flag[0] !== '_') { - desc.flags[flag] = internals.describe(schema._flags[flag]); + if (node === this.head) { + return; } - } - if (!Object.keys(desc.flags).length) { - delete desc.flags; + this._remove(node); + this.unshift(node); } - // Preferences + pop() { - if (schema._preferences) { - desc.preferences = Clone(schema._preferences, { shallow: ['messages'] }); - delete desc.preferences[Common.symbols.prefs]; - if (desc.preferences.messages) { - desc.preferences.messages = Messages.decompile(desc.preferences.messages); - } + return this._remove(this.tail); } - // Allow / Invalid + _remove(node) { - if (schema._valids) { - desc.allow = schema._valids.describe(); - } + const { next, prev } = node; - if (schema._invalids) { - desc.invalid = schema._invalids.describe(); - } + next.prev = prev; - // Rules + if (prev) { + prev.next = next; + } - for (const rule of schema._rules) { - const ruleDef = def.rules[rule.name]; - if (ruleDef.manifest === false) { // Defaults to true - continue; + if (node === this.tail) { + this.tail = next; } - const item = { name: rule.name }; + node.prev = null; + node.next = null; - for (const custom in def.modifiers) { - if (rule[custom] !== undefined) { - item[custom] = internals.describe(rule[custom]); - } - } + return node; + } +}; - if (rule.args) { - item.args = {}; - for (const key in rule.args) { - const arg = rule.args[key]; - if (key === 'options' && - !Object.keys(arg).length) { - continue; - } +/***/ }), - item.args[key] = internals.describe(arg, { assign: key }); - } +/***/ 72448: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (!Object.keys(item.args).length) { - delete item.args; - } - } +"use strict"; - desc.rules.push(item); - } - if (!desc.rules.length) { - delete desc.rules; - } +const Assert = __nccwpck_require__(32718); +const AssertError = __nccwpck_require__(35563); - // Terms (must be last to verify no name conflicts) +const Pkg = __nccwpck_require__(77045); - for (const term in schema.$_terms) { - if (term[0] === '_') { - continue; - } +let Messages; +let Schemas; - Assert(!desc[term], 'Cannot describe schema due to internal name conflict with', term); - const items = schema.$_terms[term]; - if (!items) { - continue; - } +const internals = { + isoDate: /^(?:[-+]\d{2})?(?:\d{4}(?!\d{2}\b))(?:(-?)(?:(?:0[1-9]|1[0-2])(?:\1(?:[12]\d|0[1-9]|3[01]))?|W(?:[0-4]\d|5[0-2])(?:-?[1-7])?|(?:00[1-9]|0[1-9]\d|[12]\d{2}|3(?:[0-5]\d|6[1-6])))(?![T]$|[T][\d]+Z$)(?:[T\s](?:(?:(?:[01]\d|2[0-3])(?:(:?)[0-5]\d)?|24\:?00)(?:[.,]\d+(?!:))?)(?:\2[0-5]\d(?:[.,]\d+)?)?(?:[Z]|(?:[+-])(?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?)?$/ +}; - if (items instanceof Map) { - if (items.size) { - desc[term] = [...items.entries()]; - } - continue; - } +exports.version = Pkg.version; - if (Common.isValues(items)) { - desc[term] = items.describe(); - continue; + +exports.defaults = { + abortEarly: true, + allowUnknown: false, + artifacts: false, + cache: true, + context: null, + convert: true, + dateFormat: 'iso', + errors: { + escapeHtml: false, + label: 'path', + language: null, + render: true, + stack: false, + wrap: { + label: '"', + array: '[]' } + }, + externals: true, + messages: {}, + nonEnumerables: false, + noDefaults: false, + presence: 'optional', + skipFunctions: false, + stripUnknown: false, + warnings: false +}; - Assert(def.terms[term], 'Term', term, 'missing configuration'); - const manifest = def.terms[term].manifest; - const mapped = typeof manifest === 'object'; - if (!items.length && - !mapped) { - continue; - } +exports.symbols = { + any: Symbol.for('@hapi/joi/schema'), // Used to internally identify any-based types (shared with other joi versions) + arraySingle: Symbol('arraySingle'), + deepDefault: Symbol('deepDefault'), + errors: Symbol('errors'), + literal: Symbol('literal'), + override: Symbol('override'), + parent: Symbol('parent'), + prefs: Symbol('prefs'), + ref: Symbol('ref'), + template: Symbol('template'), + values: Symbol('values') +}; - const normalized = []; - for (const item of items) { - normalized.push(internals.describe(item)); - } - // Mapped +exports.assertOptions = function (options, keys, name = 'Options') { - if (mapped) { - const { from, to } = manifest.mapped; - desc[term] = {}; - for (const item of normalized) { - desc[term][item[to]] = item[from]; - } + Assert(options && typeof options === 'object' && !Array.isArray(options), 'Options must be of type object'); + const unknownKeys = Object.keys(options).filter((k) => !keys.includes(k)); + Assert(unknownKeys.length === 0, `${name} contain unknown keys: ${unknownKeys}`); +}; - continue; - } - // Single +exports.checkPreferences = function (prefs) { - if (manifest === 'single') { - Assert(normalized.length === 1, 'Term', term, 'contains more than one item'); - desc[term] = normalized[0]; - continue; - } + Schemas = Schemas || __nccwpck_require__(85614); - // Array + const result = Schemas.preferences.validate(prefs); - desc[term] = normalized; + if (result.error) { + throw new AssertError([result.error.details[0].message]); } - - internals.validate(schema.$_root, desc); - return desc; }; -internals.describe = function (item, options = {}) { +exports.compare = function (a, b, operator) { - if (Array.isArray(item)) { - return item.map(internals.describe); + switch (operator) { + case '=': return a === b; + case '>': return a > b; + case '<': return a < b; + case '>=': return a >= b; + case '<=': return a <= b; } +}; - if (item === Common.symbols.deepDefault) { - return { special: 'deep' }; - } - if (typeof item !== 'object' || - item === null) { +exports["default"] = function (value, defaultValue) { - return item; - } + return value === undefined ? defaultValue : value; +}; - if (options.assign === 'options') { - return Clone(item); - } - if (Buffer && Buffer.isBuffer(item)) { // $lab:coverage:ignore$ - return { buffer: item.toString('binary') }; - } +exports.isIsoDate = function (date) { - if (item instanceof Date) { - return item.toISOString(); - } + return internals.isoDate.test(date); +}; - if (item instanceof Error) { - return item; - } - if (item instanceof RegExp) { - if (options.assign === 'regex') { - return item.toString(); - } +exports.isNumber = function (value) { - return { regex: item.toString() }; - } + return typeof value === 'number' && !isNaN(value); +}; - if (item[Common.symbols.literal]) { - return { function: item.literal }; - } - if (typeof item.describe === 'function') { - if (options.assign === 'ref') { - return item.describe().ref; - } +exports.isResolvable = function (obj) { - return item.describe(); + if (!obj) { + return false; } - const normalized = {}; - for (const key in item) { - const value = item[key]; - if (value === undefined) { - continue; - } + return obj[exports.symbols.ref] || obj[exports.symbols.template]; +}; - normalized[key] = internals.describe(value, { assign: key }); + +exports.isSchema = function (schema, options = {}) { + + const any = schema && schema[exports.symbols.any]; + if (!any) { + return false; } - return normalized; + Assert(options.legacy || any.version === exports.version, 'Cannot mix different versions of joi schemas'); + return true; }; -exports.build = function (joi, desc) { +exports.isValues = function (obj) { - const builder = new internals.Builder(joi); - return builder.parse(desc); + return obj[exports.symbols.values]; }; -internals.Builder = class { +exports.limit = function (value) { - constructor(joi) { + return Number.isSafeInteger(value) && value >= 0; +}; - this.joi = joi; - } - parse(desc) { +exports.preferences = function (target, source) { - internals.validate(this.joi, desc); + Messages = Messages || __nccwpck_require__(86103); - // Type + target = target || {}; + source = source || {}; - let schema = this.joi[desc.type]()._bare(); - const def = schema._definition; + const merged = Object.assign({}, target, source); + if (source.errors && + target.errors) { - // Flags + merged.errors = Object.assign({}, target.errors, source.errors); + merged.errors.wrap = Object.assign({}, target.errors.wrap, source.errors.wrap); + } - if (desc.flags) { - for (const flag in desc.flags) { - const setter = def.flags[flag] && def.flags[flag].setter || flag; - Assert(typeof schema[setter] === 'function', 'Invalid flag', flag, 'for type', desc.type); - schema = schema[setter](this.build(desc.flags[flag])); - } - } + if (source.messages) { + merged.messages = Messages.compile(source.messages, target.messages); + } - // Preferences + delete merged[exports.symbols.prefs]; + return merged; +}; - if (desc.preferences) { - schema = schema.preferences(this.build(desc.preferences)); - } - // Allow / Invalid +exports.tryWithPath = function (fn, key, options = {}) { - if (desc.allow) { - schema = schema.allow(...this.build(desc.allow)); + try { + return fn(); + } + catch (err) { + if (err.path !== undefined) { + err.path = key + '.' + err.path; + } + else { + err.path = key; } - if (desc.invalid) { - schema = schema.invalid(...this.build(desc.invalid)); + if (options.append) { + err.message = `${err.message} (${err.path})`; } - // Rules + throw err; + } +}; - if (desc.rules) { - for (const rule of desc.rules) { - Assert(typeof schema[rule.name] === 'function', 'Invalid rule', rule.name, 'for type', desc.type); - const args = []; - if (rule.args) { - const built = {}; - for (const key in rule.args) { - built[key] = this.build(rule.args[key], { assign: key }); - } +exports.validateArg = function (value, label, { assert, message }) { - const keys = Object.keys(built); - const definition = def.rules[rule.name].args; - if (definition) { - Assert(keys.length <= definition.length, 'Invalid number of arguments for', desc.type, rule.name, '(expected up to', definition.length, ', found', keys.length, ')'); - for (const { name } of definition) { - args.push(built[name]); - } - } - else { - Assert(keys.length === 1, 'Invalid number of arguments for', desc.type, rule.name, '(expected up to 1, found', keys.length, ')'); - args.push(built[keys[0]]); - } - } + if (exports.isSchema(assert)) { + const result = assert.validate(value); + if (!result.error) { + return; + } - // Apply + return result.error.message; + } + else if (!assert(value)) { + return label ? `${label} ${message}` : message; + } +}; - schema = schema[rule.name](...args); - // Ruleset +exports.verifyFlat = function (args, method) { - const options = {}; - for (const custom in def.modifiers) { - if (rule[custom] !== undefined) { - options[custom] = this.build(rule[custom]); - } - } + for (const arg of args) { + Assert(!Array.isArray(arg), 'Method no longer accepts array arguments:', method); + } +}; - if (Object.keys(options).length) { - schema = schema.rule(options); - } - } - } - // Terms +/***/ }), - const terms = {}; - for (const key in desc) { - if (['allow', 'flags', 'invalid', 'whens', 'preferences', 'rules', 'type'].includes(key)) { - continue; - } +/***/ 3038: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - Assert(def.terms[key], 'Term', key, 'missing configuration'); - const manifest = def.terms[key].manifest; +"use strict"; - if (manifest === 'schema') { - terms[key] = desc[key].map((item) => this.parse(item)); - continue; - } - if (manifest === 'values') { - terms[key] = desc[key].map((item) => this.build(item)); - continue; - } +const Assert = __nccwpck_require__(32718); - if (manifest === 'single') { - terms[key] = this.build(desc[key]); - continue; - } +const Common = __nccwpck_require__(72448); +const Ref = __nccwpck_require__(73838); - if (typeof manifest === 'object') { - terms[key] = {}; - for (const name in desc[key]) { - const value = desc[key][name]; - terms[key][name] = this.parse(value); - } - continue; - } +const internals = {}; - terms[key] = this.build(desc[key]); - } - if (desc.whens) { - terms.whens = desc.whens.map((when) => this.build(when)); - } +exports.schema = function (Joi, config, options = {}) { - schema = def.manifest.build(schema, terms); - schema.$_temp.ruleset = false; - return schema; - } + Common.assertOptions(options, ['appendPath', 'override']); - build(desc, options = {}) { + try { + return internals.schema(Joi, config, options); + } + catch (err) { + if (options.appendPath && + err.path !== undefined) { - if (desc === null) { - return null; + err.message = `${err.message} (${err.path})`; } - if (Array.isArray(desc)) { - return desc.map((item) => this.build(item)); - } + throw err; + } +}; - if (desc instanceof Error) { - return desc; - } - if (options.assign === 'options') { - return Clone(desc); - } +internals.schema = function (Joi, config, options) { - if (options.assign === 'regex') { - return internals.regex(desc); - } + Assert(config !== undefined, 'Invalid undefined schema'); - if (options.assign === 'ref') { - return Ref.build(desc); - } + if (Array.isArray(config)) { + Assert(config.length, 'Invalid empty array schema'); - if (typeof desc !== 'object') { - return desc; + if (config.length === 1) { + config = config[0]; } + } - if (Object.keys(desc).length === 1) { - if (desc.buffer) { - Assert(Buffer, 'Buffers are not supported'); - return Buffer && Buffer.from(desc.buffer, 'binary'); // $lab:coverage:ignore$ - } - - if (desc.function) { - return { [Common.symbols.literal]: true, literal: desc.function }; - } + const valid = (base, ...values) => { - if (desc.override) { - return Common.symbols.override; - } + if (options.override !== false) { + return base.valid(Joi.override, ...values); + } - if (desc.ref) { - return Ref.build(desc.ref); - } + return base.valid(...values); + }; - if (desc.regex) { - return internals.regex(desc.regex); - } + if (internals.simple(config)) { + return valid(Joi, config); + } - if (desc.special) { - Assert(['deep'].includes(desc.special), 'Unknown special value', desc.special); - return Common.symbols.deepDefault; - } + if (typeof config === 'function') { + return Joi.custom(config); + } - if (desc.value) { - return Clone(desc.value); - } - } + Assert(typeof config === 'object', 'Invalid schema content:', typeof config); - if (desc.type) { - return this.parse(desc); - } + if (Common.isResolvable(config)) { + return valid(Joi, config); + } - if (desc.template) { - return Template.build(desc); - } + if (Common.isSchema(config)) { + return config; + } - const normalized = {}; - for (const key in desc) { - normalized[key] = this.build(desc[key], { assign: key }); + if (Array.isArray(config)) { + for (const item of config) { + if (!internals.simple(item)) { + return Joi.alternatives().try(...config); + } } - return normalized; + return valid(Joi, ...config); } -}; - - -internals.regex = function (string) { - - const end = string.lastIndexOf('/'); - const exp = string.slice(1, end); - const flags = string.slice(end + 1); - return new RegExp(exp, flags); -}; + if (config instanceof RegExp) { + return Joi.string().regex(config); + } -internals.validate = function (joi, desc) { + if (config instanceof Date) { + return valid(Joi.date(), config); + } - Schemas = Schemas || __nccwpck_require__(85614); + Assert(Object.getPrototypeOf(config) === Object.getPrototypeOf({}), 'Schema can only contain plain objects'); - joi.assert(desc, Schemas.description); + return Joi.object().keys(config); }; -/***/ }), - -/***/ 86103: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; +exports.ref = function (id, options) { + return Ref.isRef(id) ? id : Ref.create(id, options); +}; -const Assert = __nccwpck_require__(32718); -const Clone = __nccwpck_require__(85578); -const Template = __nccwpck_require__(51396); +exports.compile = function (root, schema, options = {}) { + Common.assertOptions(options, ['legacy']); -const internals = {}; + // Compiled by any supported version + const any = schema && schema[Common.symbols.any]; + if (any) { + Assert(options.legacy || any.version === Common.version, 'Cannot mix different versions of joi schemas:', any.version, Common.version); + return schema; + } -exports.compile = function (messages, target) { + // Uncompiled root - // Single value string ('plain error message', 'template {error} message') + if (typeof schema !== 'object' || + !options.legacy) { - if (typeof messages === 'string') { - Assert(!target, 'Cannot set single message string'); - return new Template(messages); + return exports.schema(root, schema, { appendPath: true }); // Will error if schema contains other versions } - // Single value template + // Scan schema for compiled parts - if (Template.isTemplate(messages)) { - Assert(!target, 'Cannot set single message template'); - return messages; + const compiler = internals.walk(schema); + if (!compiler) { + return exports.schema(root, schema, { appendPath: true }); } - // By error code { 'number.min': } - - Assert(typeof messages === 'object' && !Array.isArray(messages), 'Invalid message options'); - - target = target ? Clone(target) : {}; + return compiler.compile(compiler.root, schema); +}; - for (let code in messages) { - const message = messages[code]; - if (code === 'root' || - Template.isTemplate(message)) { +internals.walk = function (schema) { - target[code] = message; - continue; - } + if (typeof schema !== 'object') { + return null; + } - if (typeof message === 'string') { - target[code] = new Template(message); - continue; + if (Array.isArray(schema)) { + for (const item of schema) { + const compiler = internals.walk(item); + if (compiler) { + return compiler; + } } - // By language { english: { 'number.min': } } - - Assert(typeof message === 'object' && !Array.isArray(message), 'Invalid message for', code); - - const language = code; - target[language] = target[language] || {}; - - for (code in message) { - const localized = message[code]; + return null; + } - if (code === 'root' || - Template.isTemplate(localized)) { + const any = schema[Common.symbols.any]; + if (any) { + return { root: schema[any.root], compile: any.compile }; + } - target[language][code] = localized; - continue; - } + Assert(Object.getPrototypeOf(schema) === Object.getPrototypeOf({}), 'Schema can only contain plain objects'); - Assert(typeof localized === 'string', 'Invalid message for', code, 'in', language); - target[language][code] = new Template(localized); + for (const key in schema) { + const compiler = internals.walk(schema[key]); + if (compiler) { + return compiler; } } - return target; + return null; }; -exports.decompile = function (messages) { +internals.simple = function (value) { - // By error code { 'number.min': } + return value === null || ['boolean', 'string', 'number'].includes(typeof value); +}; - const target = {}; - for (let code in messages) { - const message = messages[code]; - if (code === 'root') { - target.root = message; - continue; - } +exports.when = function (schema, condition, options) { - if (Template.isTemplate(message)) { - target[code] = message.describe({ compact: true }); - continue; - } + if (options === undefined) { + Assert(condition && typeof condition === 'object', 'Missing options'); - // By language { english: { 'number.min': } } + options = condition; + condition = Ref.create('.'); + } - const language = code; - target[language] = {}; + if (Array.isArray(options)) { + options = { switch: options }; + } - for (code in message) { - const localized = message[code]; + Common.assertOptions(options, ['is', 'not', 'then', 'otherwise', 'switch', 'break']); - if (code === 'root') { - target[language].root = localized; - continue; - } + // Schema condition - target[language][code] = localized.describe({ compact: true }); - } + if (Common.isSchema(condition)) { + Assert(options.is === undefined, '"is" can not be used with a schema condition'); + Assert(options.not === undefined, '"not" can not be used with a schema condition'); + Assert(options.switch === undefined, '"switch" can not be used with a schema condition'); + + return internals.condition(schema, { is: condition, then: options.then, otherwise: options.otherwise, break: options.break }); } - return target; -}; + // Single condition + Assert(Ref.isRef(condition) || typeof condition === 'string', 'Invalid condition:', condition); + Assert(options.not === undefined || options.is === undefined, 'Cannot combine "is" with "not"'); -exports.merge = function (base, extended) { + if (options.switch === undefined) { + let rule = options; + if (options.not !== undefined) { + rule = { is: options.not, then: options.otherwise, otherwise: options.then, break: options.break }; + } - if (!base) { - return exports.compile(extended); - } + let is = rule.is !== undefined ? schema.$_compile(rule.is) : schema.$_root.invalid(null, false, 0, '').required(); + Assert(rule.then !== undefined || rule.otherwise !== undefined, 'options must have at least one of "then", "otherwise", or "switch"'); + Assert(rule.break === undefined || rule.then === undefined || rule.otherwise === undefined, 'Cannot specify then, otherwise, and break all together'); - if (!extended) { - return base; - } + if (options.is !== undefined && + !Ref.isRef(options.is) && + !Common.isSchema(options.is)) { - // Single value string + is = is.required(); // Only apply required if this wasn't already a schema or a ref + } - if (typeof extended === 'string') { - return new Template(extended); + return internals.condition(schema, { ref: exports.ref(condition), is, then: rule.then, otherwise: rule.otherwise, break: rule.break }); } - // Single value template + // Switch statement - if (Template.isTemplate(extended)) { - return extended; - } + Assert(Array.isArray(options.switch), '"switch" must be an array'); + Assert(options.is === undefined, 'Cannot combine "switch" with "is"'); + Assert(options.not === undefined, 'Cannot combine "switch" with "not"'); + Assert(options.then === undefined, 'Cannot combine "switch" with "then"'); - // By error code { 'number.min': } + const rule = { + ref: exports.ref(condition), + switch: [], + break: options.break + }; - const target = Clone(base); + for (let i = 0; i < options.switch.length; ++i) { + const test = options.switch[i]; + const last = i === options.switch.length - 1; - for (let code in extended) { - const message = extended[code]; + Common.assertOptions(test, last ? ['is', 'then', 'otherwise'] : ['is', 'then']); - if (code === 'root' || - Template.isTemplate(message)) { + Assert(test.is !== undefined, 'Switch statement missing "is"'); + Assert(test.then !== undefined, 'Switch statement missing "then"'); - target[code] = message; - continue; - } + const item = { + is: schema.$_compile(test.is), + then: schema.$_compile(test.then) + }; - if (typeof message === 'string') { - target[code] = new Template(message); - continue; - } + if (!Ref.isRef(test.is) && + !Common.isSchema(test.is)) { - // By language { english: { 'number.min': } } + item.is = item.is.required(); // Only apply required if this wasn't already a schema or a ref + } - Assert(typeof message === 'object' && !Array.isArray(message), 'Invalid message for', code); + if (last) { + Assert(options.otherwise === undefined || test.otherwise === undefined, 'Cannot specify "otherwise" inside and outside a "switch"'); + const otherwise = options.otherwise !== undefined ? options.otherwise : test.otherwise; + if (otherwise !== undefined) { + Assert(rule.break === undefined, 'Cannot specify both otherwise and break'); + item.otherwise = schema.$_compile(otherwise); + } + } - const language = code; - target[language] = target[language] || {}; + rule.switch.push(item); + } - for (code in message) { - const localized = message[code]; + return rule; +}; - if (code === 'root' || - Template.isTemplate(localized)) { - target[language][code] = localized; - continue; - } +internals.condition = function (schema, condition) { - Assert(typeof localized === 'string', 'Invalid message for', code, 'in', language); - target[language][code] = new Template(localized); + for (const key of ['then', 'otherwise']) { + if (condition[key] === undefined) { + delete condition[key]; + } + else { + condition[key] = schema.$_compile(condition[key]); } } - return target; + return condition; }; /***/ }), -/***/ 81290: +/***/ 69490: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -const Assert = __nccwpck_require__(32718); - +const Annotate = __nccwpck_require__(46014); const Common = __nccwpck_require__(72448); -const Ref = __nccwpck_require__(73838); +const Template = __nccwpck_require__(51396); const internals = {}; +exports.Report = class { -exports.Ids = internals.Ids = class { - - constructor() { - - this._byId = new Map(); - this._byKey = new Map(); - this._schemaChain = false; - } - - clone() { + constructor(code, value, local, flags, messages, state, prefs) { - const clone = new internals.Ids(); - clone._byId = new Map(this._byId); - clone._byKey = new Map(this._byKey); - clone._schemaChain = this._schemaChain; - return clone; - } + this.code = code; + this.flags = flags; + this.messages = messages; + this.path = state.path; + this.prefs = prefs; + this.state = state; + this.value = value; - concat(source) { + this.message = null; + this.template = null; - if (source._schemaChain) { - this._schemaChain = true; - } + this.local = local || {}; + this.local.label = exports.label(this.flags, this.state, this.prefs, this.messages); - for (const [id, value] of source._byId.entries()) { - Assert(!this._byKey.has(id), 'Schema id conflicts with existing key:', id); - this._byId.set(id, value); - } + if (this.value !== undefined && + !this.local.hasOwnProperty('value')) { - for (const [key, value] of source._byKey.entries()) { - Assert(!this._byId.has(key), 'Schema key conflicts with existing id:', key); - this._byKey.set(key, value); + this.local.value = this.value; } - } - - fork(path, adjuster, root) { - - const chain = this._collect(path); - chain.push({ schema: root }); - const tail = chain.shift(); - let adjusted = { id: tail.id, schema: adjuster(tail.schema) }; - Assert(Common.isSchema(adjusted.schema), 'adjuster function failed to return a joi schema type'); - - for (const node of chain) { - adjusted = { id: node.id, schema: internals.fork(node.schema, adjusted.id, adjusted.schema) }; + if (this.path.length) { + const key = this.path[this.path.length - 1]; + if (typeof key !== 'object') { + this.local.key = key; + } } - - return adjusted.schema; } - labels(path, behind = []) { - - const current = path[0]; - const node = this._get(current); - if (!node) { - return [...behind, ...path].join('.'); - } - - const forward = path.slice(1); - behind = [...behind, node.schema._flags.label || current]; - if (!forward.length) { - return behind.join('.'); - } - - return node.schema._ids.labels(forward, behind); - } + _setTemplate(template) { - reach(path, behind = []) { + this.template = template; - const current = path[0]; - const node = this._get(current); - Assert(node, 'Schema does not contain path', [...behind, ...path].join('.')); + if (!this.flags.label && + this.path.length === 0) { - const forward = path.slice(1); - if (!forward.length) { - return node.schema; + const localized = this._template(this.template, 'root'); + if (localized) { + this.local.label = localized; + } } - - return node.schema._ids.reach(forward, [...behind, current]); } - register(schema, { key } = {}) { - - if (!schema || - !Common.isSchema(schema)) { - - return; - } - - if (schema.$_property('schemaChain') || - schema._ids._schemaChain) { + toString() { - this._schemaChain = true; + if (this.message) { + return this.message; } - const id = schema._flags.id; - if (id) { - const existing = this._byId.get(id); - Assert(!existing || existing.schema === schema, 'Cannot add different schemas with the same id:', id); - Assert(!this._byKey.has(id), 'Schema id conflicts with existing key:', id); + const code = this.code; - this._byId.set(id, { schema, id }); + if (!this.prefs.errors.render) { + return this.code; } - if (key) { - Assert(!this._byKey.has(key), 'Schema already contains key:', key); - Assert(!this._byId.has(key), 'Schema key conflicts with existing id:', key); + const template = this._template(this.template) || + this._template(this.prefs.messages) || + this._template(this.messages); - this._byKey.set(key, { schema, id: key }); + if (template === undefined) { + return `Error code "${code}" is not defined, your custom type is missing the correct messages definition`; } - } - - reset() { - - this._byId = new Map(); - this._byKey = new Map(); - this._schemaChain = false; - } - _collect(path, behind = [], nodes = []) { - - const current = path[0]; - const node = this._get(current); - Assert(node, 'Schema does not contain path', [...behind, ...path].join('.')); - - nodes = [node, ...nodes]; + // Render and cache result - const forward = path.slice(1); - if (!forward.length) { - return nodes; + this.message = template.render(this.value, this.state, this.prefs, this.local, { errors: this.prefs.errors, messages: [this.prefs.messages, this.messages] }); + if (!this.prefs.errors.label) { + this.message = this.message.replace(/^"" /, '').trim(); } - return node.schema._ids._collect(forward, [...behind, current], nodes); + return this.message; } - _get(id) { + _template(messages, code) { - return this._byId.get(id) || this._byKey.get(id); + return exports.template(this.value, messages, code || this.code, this.state, this.prefs); } }; -internals.fork = function (schema, id, replacement) { - - const each = (item, { key }) => { - - if (id === (item._flags.id || key)) { - return replacement; - } - }; - - const obj = exports.schema(schema, { each, ref: false }); - return obj ? obj.$_mutateRebuild() : schema; -}; - - -exports.schema = function (schema, options) { - - let obj; +exports.path = function (path) { - for (const name in schema._flags) { - if (name[0] === '_') { + let label = ''; + for (const segment of path) { + if (typeof segment === 'object') { // Exclude array single path segment continue; } - const result = internals.scan(schema._flags[name], { source: 'flags', name }, options); - if (result !== undefined) { - obj = obj || schema.clone(); - obj._flags[name] = result; - } - } - - for (let i = 0; i < schema._rules.length; ++i) { - const rule = schema._rules[i]; - const result = internals.scan(rule.args, { source: 'rules', name: rule.name }, options); - if (result !== undefined) { - obj = obj || schema.clone(); - const clone = Object.assign({}, rule); - clone.args = result; - obj._rules[i] = clone; - - const existingUnique = obj._singleRules.get(rule.name); - if (existingUnique === rule) { - obj._singleRules.set(rule.name, clone); + if (typeof segment === 'string') { + if (label) { + label += '.'; } - } - } - for (const name in schema.$_terms) { - if (name[0] === '_') { - continue; + label += segment; } - - const result = internals.scan(schema.$_terms[name], { source: 'terms', name }, options); - if (result !== undefined) { - obj = obj || schema.clone(); - obj.$_terms[name] = result; + else { + label += `[${segment}]`; } } - return obj; + return label; }; -internals.scan = function (item, source, options, _path, _key) { - - const path = _path || []; - - if (item === null || - typeof item !== 'object') { +exports.template = function (value, messages, code, state, prefs) { + if (!messages) { return; } - let clone; - - if (Array.isArray(item)) { - for (let i = 0; i < item.length; ++i) { - const key = source.source === 'terms' && source.name === 'keys' && item[i].key; - const result = internals.scan(item[i], source, options, [i, ...path], key); - if (result !== undefined) { - clone = clone || item.slice(); - clone[i] = result; - } - } + if (Template.isTemplate(messages)) { + return code !== 'root' ? messages : null; + } - return clone; + let lang = prefs.errors.language; + if (Common.isResolvable(lang)) { + lang = lang.resolve(value, state, prefs); } - if (options.schema !== false && Common.isSchema(item) || - options.ref !== false && Ref.isRef(item)) { + if (lang && + messages[lang]) { - const result = options.each(item, { ...source, path, key: _key }); - if (result === item) { - return; + if (messages[lang][code] !== undefined) { + return messages[lang][code]; } - return result; - } - - for (const key in item) { - if (key[0] === '_') { - continue; + if (messages[lang]['*'] !== undefined) { + return messages[lang]['*']; } + } - const result = internals.scan(item[key], source, options, [key, ...path], _key); - if (result !== undefined) { - clone = clone || Object.assign({}, item); - clone[key] = result; - } + if (!messages[code]) { + return messages['*']; } - return clone; + return messages[code]; }; -/***/ }), +exports.label = function (flags, state, prefs, messages) { -/***/ 73838: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + if (flags.label) { + return flags.label; + } -"use strict"; + if (!prefs.errors.label) { + return ''; + } + let path = state.path; + if (prefs.errors.label === 'key' && + state.path.length > 1) { -const Assert = __nccwpck_require__(32718); -const Clone = __nccwpck_require__(85578); -const Reach = __nccwpck_require__(18891); + path = state.path.slice(-1); + } -const Common = __nccwpck_require__(72448); + const normalized = exports.path(path); + if (normalized) { + return normalized; + } -let Template; + return exports.template(null, prefs.messages, 'root', state, prefs) || + messages && exports.template(null, messages, 'root', state, prefs) || + 'value'; +}; -const internals = { - symbol: Symbol('ref'), // Used to internally identify references (shared with other joi versions) - defaults: { - adjust: null, - in: false, - iterables: null, - map: null, - separator: '.', - type: 'value' +exports.process = function (errors, original, prefs) { + + if (!errors) { + return null; + } + + const { override, message, details } = exports.details(errors); + if (override) { + return override; + } + + if (prefs.errors.stack) { + return new exports.ValidationError(message, details, original); } + + const limit = Error.stackTraceLimit; + Error.stackTraceLimit = 0; + const validationError = new exports.ValidationError(message, details, original); + Error.stackTraceLimit = limit; + return validationError; }; -exports.create = function (key, options = {}) { +exports.details = function (errors, options = {}) { - Assert(typeof key === 'string', 'Invalid reference key:', key); - Common.assertOptions(options, ['adjust', 'ancestor', 'in', 'iterables', 'map', 'prefix', 'render', 'separator']); - Assert(!options.prefix || typeof options.prefix === 'object', 'options.prefix must be of type object'); + let messages = []; + const details = []; - const ref = Object.assign({}, internals.defaults, options); - delete ref.prefix; + for (const item of errors) { - const separator = ref.separator; - const context = internals.context(key, separator, options.prefix); - ref.type = context.type; - key = context.key; + // Override - if (ref.type === 'value') { - if (context.root) { - Assert(!separator || key[0] !== separator, 'Cannot specify relative path with root prefix'); - ref.ancestor = 'root'; - if (!key) { - key = null; + if (item instanceof Error) { + if (options.override !== false) { + return { override: item }; } - } - if (separator && - separator === key) { + const message = item.toString(); + messages.push(message); - key = null; - ref.ancestor = 0; - } - else { - if (ref.ancestor !== undefined) { - Assert(!separator || !key || key[0] !== separator, 'Cannot combine prefix with ancestor option'); - } - else { - const [ancestor, slice] = internals.ancestor(key, separator); - if (slice) { - key = key.slice(slice); - if (key === '') { - key = null; - } - } + details.push({ + message, + type: 'override', + context: { error: item } + }); - ref.ancestor = ancestor; - } + continue; } + + // Report + + const message = item.toString(); + messages.push(message); + + details.push({ + message, + path: item.path.filter((v) => typeof v !== 'object'), + type: item.code, + context: item.local + }); } - ref.path = separator ? (key === null ? [] : key.split(separator)) : [key]; + if (messages.length > 1) { + messages = [...new Set(messages)]; + } - return new internals.Ref(ref); + return { message: messages.join('. '), details }; }; -exports["in"] = function (key, options = {}) { +exports.ValidationError = class extends Error { - return exports.create(key, { ...options, in: true }); -}; + constructor(message, details, original) { + super(message); + this._original = original; + this.details = details; + } -exports.isRef = function (ref) { + static isError(err) { - return ref ? !!ref[Common.symbols.ref] : false; + return err instanceof exports.ValidationError; + } }; -internals.Ref = class { - - constructor(options) { +exports.ValidationError.prototype.isJoi = true; - Assert(typeof options === 'object', 'Invalid reference construction'); - Common.assertOptions(options, [ - 'adjust', 'ancestor', 'in', 'iterables', 'map', 'path', 'render', 'separator', 'type', // Copied - 'depth', 'key', 'root', 'display' // Overridden - ]); +exports.ValidationError.prototype.name = 'ValidationError'; - Assert([false, undefined].includes(options.separator) || typeof options.separator === 'string' && options.separator.length === 1, 'Invalid separator'); - Assert(!options.adjust || typeof options.adjust === 'function', 'options.adjust must be a function'); - Assert(!options.map || Array.isArray(options.map), 'options.map must be an array'); - Assert(!options.map || !options.adjust, 'Cannot set both map and adjust options'); +exports.ValidationError.prototype.annotate = Annotate.error; - Object.assign(this, internals.defaults, options); - Assert(this.type === 'value' || this.ancestor === undefined, 'Non-value references cannot reference ancestors'); +/***/ }), - if (Array.isArray(this.map)) { - this.map = new Map(this.map); - } +/***/ 86680: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - this.depth = this.path.length; - this.key = this.path.length ? this.path.join(this.separator) : null; - this.root = this.path[0]; +"use strict"; - this.updateDisplay(); - } - resolve(value, state, prefs, local, options = {}) { +const Assert = __nccwpck_require__(32718); +const Clone = __nccwpck_require__(85578); - Assert(!this.in || options.in, 'Invalid in() reference usage'); +const Common = __nccwpck_require__(72448); +const Messages = __nccwpck_require__(86103); - if (this.type === 'global') { - return this._resolve(prefs.context, state, options); - } - if (this.type === 'local') { - return this._resolve(local, state, options); - } +const internals = {}; - if (!this.ancestor) { - return this._resolve(value, state, options); - } - if (this.ancestor === 'root') { - return this._resolve(state.ancestors[state.ancestors.length - 1], state, options); - } +exports.type = function (from, options) { - Assert(this.ancestor <= state.ancestors.length, 'Invalid reference exceeds the schema root:', this.display); - return this._resolve(state.ancestors[this.ancestor - 1], state, options); - } + const base = Object.getPrototypeOf(from); + const prototype = Clone(base); + const schema = from._assign(Object.create(prototype)); + const def = Object.assign({}, options); // Shallow cloned + delete def.base; - _resolve(target, state, options) { + prototype._definition = def; - let resolved; + const parent = base._definition || {}; + def.messages = Messages.merge(parent.messages, def.messages); + def.properties = Object.assign({}, parent.properties, def.properties); - if (this.type === 'value' && - state.mainstay.shadow && - options.shadow !== false) { + // Type - resolved = state.mainstay.shadow.get(this.absolute(state)); - } + schema.type = def.type; - if (resolved === undefined) { - resolved = Reach(target, this.path, { iterables: this.iterables, functions: true }); - } + // Flags - if (this.adjust) { - resolved = this.adjust(resolved); - } + def.flags = Object.assign({}, parent.flags, def.flags); - if (this.map) { - const mapped = this.map.get(resolved); - if (mapped !== undefined) { - resolved = mapped; - } - } + // Terms - if (state.mainstay) { - state.mainstay.tracer.resolve(state, this, resolved); + const terms = Object.assign({}, parent.terms); + if (def.terms) { + for (const name in def.terms) { // Only apply own terms + const term = def.terms[name]; + Assert(schema.$_terms[name] === undefined, 'Invalid term override for', def.type, name); + schema.$_terms[name] = term.init; + terms[name] = term; } - - return resolved; } - toString() { - - return this.display; - } + def.terms = terms; - absolute(state) { + // Constructor arguments - return [...state.path.slice(0, -this.ancestor), ...this.path]; + if (!def.args) { + def.args = parent.args; } - clone() { - - return new internals.Ref(this); - } + // Prepare - describe() { + def.prepare = internals.prepare(def.prepare, parent.prepare); - const ref = { path: this.path }; + // Coerce - if (this.type !== 'value') { - ref.type = this.type; + if (def.coerce) { + if (typeof def.coerce === 'function') { + def.coerce = { method: def.coerce }; } - if (this.separator !== '.') { - ref.separator = this.separator; + if (def.coerce.from && + !Array.isArray(def.coerce.from)) { + + def.coerce = { method: def.coerce.method, from: [].concat(def.coerce.from) }; } + } - if (this.type === 'value' && - this.ancestor !== 1) { + def.coerce = internals.coerce(def.coerce, parent.coerce); - ref.ancestor = this.ancestor; - } + // Validate - if (this.map) { - ref.map = [...this.map]; - } + def.validate = internals.validate(def.validate, parent.validate); - for (const key of ['adjust', 'iterables', 'render']) { - if (this[key] !== null && - this[key] !== undefined) { + // Rules - ref[key] = this[key]; + const rules = Object.assign({}, parent.rules); + if (def.rules) { + for (const name in def.rules) { + const rule = def.rules[name]; + Assert(typeof rule === 'object', 'Invalid rule definition for', def.type, name); + + let method = rule.method; + if (method === undefined) { + method = function () { + + return this.$_addRule(name); + }; } - } - if (this.in !== false) { - ref.in = true; - } + if (method) { + Assert(!prototype[name], 'Rule conflict in', def.type, name); + prototype[name] = method; + } - return { ref }; - } + Assert(!rules[name], 'Rule conflict in', def.type, name); + rules[name] = rule; - updateDisplay() { + if (rule.alias) { + const aliases = [].concat(rule.alias); + for (const alias of aliases) { + prototype[alias] = rule.method; + } + } - const key = this.key !== null ? this.key : ''; - if (this.type !== 'value') { - this.display = `ref:${this.type}:${key}`; - return; - } + if (rule.args) { + rule.argsByName = new Map(); + rule.args = rule.args.map((arg) => { - if (!this.separator) { - this.display = `ref:${key}`; - return; - } + if (typeof arg === 'string') { + arg = { name: arg }; + } - if (!this.ancestor) { - this.display = `ref:${this.separator}${key}`; - return; - } + Assert(!rule.argsByName.has(arg.name), 'Duplicated argument name', arg.name); - if (this.ancestor === 'root') { - this.display = `ref:root:${key}`; - return; - } + if (Common.isSchema(arg.assert)) { + arg.assert = arg.assert.strict().label(arg.name); + } - if (this.ancestor === 1) { - this.display = `ref:${key || '..'}`; - return; + rule.argsByName.set(arg.name, arg); + return arg; + }); + } } - - const lead = new Array(this.ancestor + 1).fill(this.separator).join(''); - this.display = `ref:${lead}${key || ''}`; } -}; + def.rules = rules; -internals.Ref.prototype[Common.symbols.ref] = true; + // Modifiers + const modifiers = Object.assign({}, parent.modifiers); + if (def.modifiers) { + for (const name in def.modifiers) { + Assert(!prototype[name], 'Rule conflict in', def.type, name); -exports.build = function (desc) { + const modifier = def.modifiers[name]; + Assert(typeof modifier === 'function', 'Invalid modifier definition for', def.type, name); - desc = Object.assign({}, internals.defaults, desc); - if (desc.type === 'value' && - desc.ancestor === undefined) { + const method = function (arg) { - desc.ancestor = 1; + return this.rule({ [name]: arg }); + }; + + prototype[name] = method; + modifiers[name] = modifier; + } } - return new internals.Ref(desc); -}; + def.modifiers = modifiers; + // Overrides -internals.context = function (key, separator, prefix = {}) { + if (def.overrides) { + prototype._super = base; + schema.$_super = {}; // Backwards compatibility + for (const override in def.overrides) { + Assert(base[override], 'Cannot override missing', override); + def.overrides[override][Common.symbols.parent] = base[override]; + schema.$_super[override] = base[override].bind(schema); // Backwards compatibility + } - key = key.trim(); + Object.assign(prototype, def.overrides); + } - if (prefix) { - const globalp = prefix.global === undefined ? '$' : prefix.global; - if (globalp !== separator && - key.startsWith(globalp)) { + // Casts - return { key: key.slice(globalp.length), type: 'global' }; - } + def.cast = Object.assign({}, parent.cast, def.cast); - const local = prefix.local === undefined ? '#' : prefix.local; - if (local !== separator && - key.startsWith(local)) { + // Manifest - return { key: key.slice(local.length), type: 'local' }; - } + const manifest = Object.assign({}, parent.manifest, def.manifest); + manifest.build = internals.build(def.manifest && def.manifest.build, parent.manifest && parent.manifest.build); + def.manifest = manifest; - const root = prefix.root === undefined ? '/' : prefix.root; - if (root !== separator && - key.startsWith(root)) { + // Rebuild - return { key: key.slice(root.length), type: 'value', root: true }; - } - } + def.rebuild = internals.rebuild(def.rebuild, parent.rebuild); - return { key, type: 'value' }; + return schema; }; -internals.ancestor = function (key, separator) { +// Helpers - if (!separator) { - return [1, 0]; // 'a_b' -> 1 (parent) - } +internals.build = function (child, parent) { - if (key[0] !== separator) { // 'a.b' -> 1 (parent) - return [1, 0]; - } + if (!child || + !parent) { - if (key[1] !== separator) { // '.a.b' -> 0 (self) - return [0, 1]; + return child || parent; } - let i = 2; - while (key[i] === separator) { - ++i; - } + return function (obj, desc) { - return [i - 1, i]; // '...a.b.' -> 2 (grandparent) + return parent(child(obj, desc), desc); + }; }; -exports.toSibling = 0; +internals.coerce = function (child, parent) { -exports.toParent = 1; + if (!child || + !parent) { + return child || parent; + } -exports.Manager = class { + return { + from: child.from && parent.from ? [...new Set([...child.from, ...parent.from])] : null, + method(value, helpers) { - constructor() { + let coerced; + if (!parent.from || + parent.from.includes(typeof value)) { - this.refs = []; // 0: [self refs], 1: [parent refs], 2: [grandparent refs], ... - } + coerced = parent.method(value, helpers); + if (coerced) { + if (coerced.errors || + coerced.value === undefined) { - register(source, target) { + return coerced; + } - if (!source) { - return; + value = coerced.value; + } + } + + if (!child.from || + child.from.includes(typeof value)) { + + const own = child.method(value, helpers); + if (own) { + return own; + } + } + + return coerced; } + }; +}; - target = target === undefined ? exports.toParent : target; - // Array +internals.prepare = function (child, parent) { + + if (!child || + !parent) { - if (Array.isArray(source)) { - for (const ref of source) { - this.register(ref, target); - } + return child || parent; + } - return; - } + return function (value, helpers) { - // Schema + const prepared = child(value, helpers); + if (prepared) { + if (prepared.errors || + prepared.value === undefined) { - if (Common.isSchema(source)) { - for (const item of source._refs.refs) { - if (item.ancestor - target >= 0) { - this.refs.push({ ancestor: item.ancestor - target, root: item.root }); - } + return prepared; } - return; + value = prepared.value; } - // Reference - - if (exports.isRef(source) && - source.type === 'value' && - source.ancestor - target >= 0) { + return parent(value, helpers) || prepared; + }; +}; - this.refs.push({ ancestor: source.ancestor - target, root: source.root }); - } - // Template +internals.rebuild = function (child, parent) { - Template = Template || __nccwpck_require__(51396); + if (!child || + !parent) { - if (Template.isTemplate(source)) { - this.register(source.refs(), target); - } + return child || parent; } - get length() { + return function (schema) { - return this.refs.length; - } + parent(schema); + child(schema); + }; +}; - clone() { - const copy = new exports.Manager(); - copy.refs = Clone(this.refs); - return copy; - } +internals.validate = function (child, parent) { - reset() { + if (!child || + !parent) { - this.refs = []; + return child || parent; } - roots() { + return function (value, helpers) { - return this.refs.filter((ref) => !ref.ancestor).map((ref) => ref.root); - } + const result = parent(value, helpers); + if (result) { + if (result.errors && + (!Array.isArray(result.errors) || result.errors.length)) { + + return result; + } + + value = result.value; + } + + return child(value, helpers) || result; + }; }; /***/ }), -/***/ 85614: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 20918: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const Joi = __nccwpck_require__(20918); - +const Assert = __nccwpck_require__(32718); +const Clone = __nccwpck_require__(85578); -const internals = {}; +const Cache = __nccwpck_require__(63355); +const Common = __nccwpck_require__(72448); +const Compile = __nccwpck_require__(3038); +const Errors = __nccwpck_require__(69490); +const Extend = __nccwpck_require__(86680); +const Manifest = __nccwpck_require__(87997); +const Ref = __nccwpck_require__(73838); +const Template = __nccwpck_require__(51396); +const Trace = __nccwpck_require__(43171); +let Schemas; -// Preferences -internals.wrap = Joi.string() - .min(1) - .max(2) - .allow(false); +const internals = { + types: { + alternatives: __nccwpck_require__(26867), + any: __nccwpck_require__(9512), + array: __nccwpck_require__(20270), + boolean: __nccwpck_require__(47489), + date: __nccwpck_require__(6624), + function: __nccwpck_require__(62269), + link: __nccwpck_require__(69869), + number: __nccwpck_require__(15855), + object: __nccwpck_require__(46878), + string: __nccwpck_require__(72260), + symbol: __nccwpck_require__(40971) + }, + aliases: { + alt: 'alternatives', + bool: 'boolean', + func: 'function' + } +}; -exports.preferences = Joi.object({ - allowUnknown: Joi.boolean(), - abortEarly: Joi.boolean(), - artifacts: Joi.boolean(), - cache: Joi.boolean(), - context: Joi.object(), - convert: Joi.boolean(), - dateFormat: Joi.valid('date', 'iso', 'string', 'time', 'utc'), - debug: Joi.boolean(), - errors: { - escapeHtml: Joi.boolean(), - label: Joi.valid('path', 'key', false), - language: [ - Joi.string(), - Joi.object().ref() - ], - render: Joi.boolean(), - stack: Joi.boolean(), - wrap: { - label: internals.wrap, - array: internals.wrap, - string: internals.wrap - } - }, - externals: Joi.boolean(), - messages: Joi.object(), - noDefaults: Joi.boolean(), - nonEnumerables: Joi.boolean(), - presence: Joi.valid('required', 'optional', 'forbidden'), - skipFunctions: Joi.boolean(), - stripUnknown: Joi.object({ - arrays: Joi.boolean(), - objects: Joi.boolean() - }) - .or('arrays', 'objects') - .allow(true, false), - warnings: Joi.boolean() -}) - .strict(); +if (Buffer) { // $lab:coverage:ignore$ + internals.types.binary = __nccwpck_require__(34288); +} -// Extensions +internals.root = function () { -internals.nameRx = /^[a-zA-Z0-9]\w*$/; + const root = { + _types: new Set(Object.keys(internals.types)) + }; + // Types -internals.rule = Joi.object({ - alias: Joi.array().items(Joi.string().pattern(internals.nameRx)).single(), - args: Joi.array().items( - Joi.string(), - Joi.object({ - name: Joi.string().pattern(internals.nameRx).required(), - ref: Joi.boolean(), - assert: Joi.alternatives([ - Joi.function(), - Joi.object().schema() - ]) - .conditional('ref', { is: true, then: Joi.required() }), - normalize: Joi.function(), - message: Joi.string().when('assert', { is: Joi.function(), then: Joi.required() }) - }) - ), - convert: Joi.boolean(), - manifest: Joi.boolean(), - method: Joi.function().allow(false), - multi: Joi.boolean(), - validate: Joi.function() -}); + for (const type of root._types) { + root[type] = function (...args) { + Assert(!args.length || ['alternatives', 'link', 'object'].includes(type), 'The', type, 'type does not allow arguments'); + return internals.generate(this, internals.types[type], args); + }; + } -exports.extension = Joi.object({ - type: Joi.alternatives([ - Joi.string(), - Joi.object().regex() - ]) - .required(), - args: Joi.function(), - cast: Joi.object().pattern(internals.nameRx, Joi.object({ - from: Joi.function().maxArity(1).required(), - to: Joi.function().minArity(1).maxArity(2).required() - })), - base: Joi.object().schema() - .when('type', { is: Joi.object().regex(), then: Joi.forbidden() }), - coerce: [ - Joi.function().maxArity(3), - Joi.object({ method: Joi.function().maxArity(3).required(), from: Joi.array().items(Joi.string()).single() }) - ], - flags: Joi.object().pattern(internals.nameRx, Joi.object({ - setter: Joi.string(), - default: Joi.any() - })), - manifest: { - build: Joi.function().arity(2) - }, - messages: [Joi.object(), Joi.string()], - modifiers: Joi.object().pattern(internals.nameRx, Joi.function().minArity(1).maxArity(2)), - overrides: Joi.object().pattern(internals.nameRx, Joi.function()), - prepare: Joi.function().maxArity(3), - rebuild: Joi.function().arity(1), - rules: Joi.object().pattern(internals.nameRx, internals.rule), - terms: Joi.object().pattern(internals.nameRx, Joi.object({ - init: Joi.array().allow(null).required(), - manifest: Joi.object().pattern(/.+/, [ - Joi.valid('schema', 'single'), - Joi.object({ - mapped: Joi.object({ - from: Joi.string().required(), - to: Joi.string().required() - }) - .required() - }) - ]) - })), - validate: Joi.function().maxArity(3) -}) - .strict(); + // Shortcuts + for (const method of ['allow', 'custom', 'disallow', 'equal', 'exist', 'forbidden', 'invalid', 'not', 'only', 'optional', 'options', 'prefs', 'preferences', 'required', 'strip', 'valid', 'when']) { + root[method] = function (...args) { -exports.extensions = Joi.array().items(Joi.object(), Joi.function().arity(1)).strict(); + return this.any()[method](...args); + }; + } + // Methods -// Manifest + Object.assign(root, internals.methods); -internals.desc = { + // Aliases - buffer: Joi.object({ - buffer: Joi.string() - }), + for (const alias in internals.aliases) { + const target = internals.aliases[alias]; + root[alias] = root[target]; + } - func: Joi.object({ - function: Joi.function().required(), - options: { - literal: true - } - }), + root.x = root.expression; - override: Joi.object({ - override: true - }), + // Trace - ref: Joi.object({ - ref: Joi.object({ - type: Joi.valid('value', 'global', 'local'), - path: Joi.array().required(), - separator: Joi.string().length(1).allow(false), - ancestor: Joi.number().min(0).integer().allow('root'), - map: Joi.array().items(Joi.array().length(2)).min(1), - adjust: Joi.function(), - iterables: Joi.boolean(), - in: Joi.boolean(), - render: Joi.boolean() - }) - .required() - }), + if (Trace.setup) { // $lab:coverage:ignore$ + Trace.setup(root); + } - regex: Joi.object({ - regex: Joi.string().min(3) - }), + return root; +}; - special: Joi.object({ - special: Joi.valid('deep').required() - }), - template: Joi.object({ - template: Joi.string().required(), - options: Joi.object() - }), +internals.methods = { - value: Joi.object({ - value: Joi.alternatives([Joi.object(), Joi.array()]).required() - }) -}; + ValidationError: Errors.ValidationError, + version: Common.version, + cache: Cache.provider, + assert(value, schema, ...args /* [message], [options] */) { -internals.desc.entity = Joi.alternatives([ - Joi.array().items(Joi.link('...')), - Joi.boolean(), - Joi.function(), - Joi.number(), - Joi.string(), - internals.desc.buffer, - internals.desc.func, - internals.desc.ref, - internals.desc.regex, - internals.desc.special, - internals.desc.template, - internals.desc.value, - Joi.link('/') -]); + internals.assert(value, schema, true, args); + }, + attempt(value, schema, ...args /* [message], [options] */) { -internals.desc.values = Joi.array() - .items( - null, - Joi.boolean(), - Joi.function(), - Joi.number().allow(Infinity, -Infinity), - Joi.string().allow(''), - Joi.symbol(), - internals.desc.buffer, - internals.desc.func, - internals.desc.override, - internals.desc.ref, - internals.desc.regex, - internals.desc.template, - internals.desc.value - ); + return internals.assert(value, schema, false, args); + }, + build(desc) { -internals.desc.messages = Joi.object() - .pattern(/.+/, [ - Joi.string(), - internals.desc.template, - Joi.object().pattern(/.+/, [Joi.string(), internals.desc.template]) - ]); + Assert(typeof Manifest.build === 'function', 'Manifest functionality disabled'); + return Manifest.build(this, desc); + }, + checkPreferences(prefs) { -exports.description = Joi.object({ - type: Joi.string().required(), - flags: Joi.object({ - cast: Joi.string(), - default: Joi.any(), - description: Joi.string(), - empty: Joi.link('/'), - failover: internals.desc.entity, - id: Joi.string(), - label: Joi.string(), - only: true, - presence: ['optional', 'required', 'forbidden'], - result: ['raw', 'strip'], - strip: Joi.boolean(), - unit: Joi.string() - }) - .unknown(), - preferences: { - allowUnknown: Joi.boolean(), - abortEarly: Joi.boolean(), - artifacts: Joi.boolean(), - cache: Joi.boolean(), - convert: Joi.boolean(), - dateFormat: ['date', 'iso', 'string', 'time', 'utc'], - errors: { - escapeHtml: Joi.boolean(), - label: ['path', 'key'], - language: [ - Joi.string(), - internals.desc.ref - ], - wrap: { - label: internals.wrap, - array: internals.wrap - } - }, - externals: Joi.boolean(), - messages: internals.desc.messages, - noDefaults: Joi.boolean(), - nonEnumerables: Joi.boolean(), - presence: ['required', 'optional', 'forbidden'], - skipFunctions: Joi.boolean(), - stripUnknown: Joi.object({ - arrays: Joi.boolean(), - objects: Joi.boolean() - }) - .or('arrays', 'objects') - .allow(true, false), - warnings: Joi.boolean() + Common.checkPreferences(prefs); }, - allow: internals.desc.values, - invalid: internals.desc.values, - rules: Joi.array().min(1).items({ - name: Joi.string().required(), - args: Joi.object().min(1), - keep: Joi.boolean(), - message: [ - Joi.string(), - internals.desc.messages - ], - warn: Joi.boolean() - }), - // Terms + compile(schema, options) { - keys: Joi.object().pattern(/.*/, Joi.link('/')), - link: internals.desc.ref -}) - .pattern(/^[a-z]\w*$/, Joi.any()); + return Compile.compile(this, schema, options); + }, + defaults(modifier) { -/***/ }), + Assert(typeof modifier === 'function', 'modifier must be a function'); -/***/ 73634: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + const joi = Object.assign({}, this); + for (const type of joi._types) { + const schema = modifier(joi[type]()); + Assert(Common.isSchema(schema), 'modifier must return a valid schema object'); -"use strict"; + joi[type] = function (...args) { + return internals.generate(this, schema, args); + }; + } -const Clone = __nccwpck_require__(85578); -const Reach = __nccwpck_require__(18891); + return joi; + }, -const Common = __nccwpck_require__(72448); + expression(...args) { + return new Template(...args); + }, -const internals = { - value: Symbol('value') -}; + extend(...extensions) { + Common.verifyFlat(extensions, 'extend'); -module.exports = internals.State = class { + Schemas = Schemas || __nccwpck_require__(85614); - constructor(path, ancestors, state) { + Assert(extensions.length, 'You need to provide at least one extension'); + this.assert(extensions, Schemas.extensions); - this.path = path; - this.ancestors = ancestors; // [parent, ..., root] + const joi = Object.assign({}, this); + joi._types = new Set(joi._types); - this.mainstay = state.mainstay; - this.schemas = state.schemas; // [current, ..., root] - this.debug = null; - } + for (let extension of extensions) { + if (typeof extension === 'function') { + extension = extension(joi); + } - localize(path, ancestors = null, schema = null) { + this.assert(extension, Schemas.extension); - const state = new internals.State(path, ancestors, this); + const expanded = internals.expandExtension(extension, joi); + for (const item of expanded) { + Assert(joi[item.type] === undefined || joi._types.has(item.type), 'Cannot override name', item.type); - if (schema && - state.schemas) { + const base = item.base || this.any(); + const schema = Extend.type(base, item); - state.schemas = [internals.schemas(schema), ...state.schemas]; + joi._types.add(item.type); + joi[item.type] = function (...args) { + + return internals.generate(this, schema, args); + }; + } } - return state; - } + return joi; + }, - nest(schema, debug) { + isError: Errors.ValidationError.isError, + isExpression: Template.isTemplate, + isRef: Ref.isRef, + isSchema: Common.isSchema, - const state = new internals.State(this.path, this.ancestors, this); - state.schemas = state.schemas && [internals.schemas(schema), ...state.schemas]; - state.debug = debug; - return state; - } + in(...args) { + + return Ref.in(...args); + }, + + override: Common.symbols.override, - shadow(value, reason) { + ref(...args) { - this.mainstay.shadow = this.mainstay.shadow || new internals.Shadow(); - this.mainstay.shadow.set(this.path, value, reason); - } + return Ref.create(...args); + }, - snapshot() { + types() { - if (this.mainstay.shadow) { - this._snapshot = Clone(this.mainstay.shadow.node(this.path)); + const types = {}; + for (const type of this._types) { + types[type] = this[type](); } - } - restore() { - - if (this.mainstay.shadow) { - this.mainstay.shadow.override(this.path, this._snapshot); - this._snapshot = undefined; + for (const target in internals.aliases) { + types[target] = this[target](); } + + return types; } }; -internals.schemas = function (schema) { +// Helpers - if (Common.isSchema(schema)) { - return { schema }; - } +internals.assert = function (value, schema, annotate, args /* [message], [options] */) { - return schema; -}; + const message = args[0] instanceof Error || typeof args[0] === 'string' ? args[0] : null; + const options = message ? args[1] : args[0]; + const result = schema.validate(value, Common.preferences({ errors: { stack: true } }, options || {})); + let error = result.error; + if (!error) { + return result.value; + } -internals.Shadow = class { + if (message instanceof Error) { + throw message; + } - constructor() { + const display = annotate && typeof error.annotate === 'function' ? error.annotate() : error.message; - this._values = null; + if (error instanceof Errors.ValidationError === false) { + error = Clone(error); } - set(path, value, reason) { - - if (!path.length) { // No need to store root value - return; - } + error.message = message ? `${message} ${display}` : display; + throw error; +}; - if (reason === 'strip' && - typeof path[path.length - 1] === 'number') { // Cannot store stripped array values (due to shift) - return; - } +internals.generate = function (root, schema, args) { - this._values = this._values || new Map(); + Assert(root, 'Must be invoked on a Joi instance.'); - let node = this._values; - for (let i = 0; i < path.length; ++i) { - const segment = path[i]; - let next = node.get(segment); - if (!next) { - next = new Map(); - node.set(segment, next); - } + schema.$_root = root; - node = next; - } + if (!schema._definition.args || + !args.length) { - node[internals.value] = value; + return schema; } - get(path) { - - const node = this.node(path); - if (node) { - return node[internals.value]; - } - } + return schema._definition.args(schema, ...args); +}; - node(path) { - if (!this._values) { - return; - } +internals.expandExtension = function (extension, joi) { - return Reach(this._values, path, { iterables: true }); + if (typeof extension.type === 'string') { + return [extension]; } - override(path, node) { - - if (!this._values) { - return; + const extended = []; + for (const type of joi._types) { + if (extension.type.test(type)) { + const item = Object.assign({}, extension); + item.type = type; + item.base = joi[type](); + extended.push(item); } + } - const parents = path.slice(0, -1); - const own = path[path.length - 1]; - const parent = Reach(this._values, parents, { iterables: true }); + return extended; +}; - if (node) { - parent.set(own, node); - return; - } - if (parent) { - parent.delete(own); - } - } -}; +module.exports = internals.root(); /***/ }), -/***/ 51396: -/***/ ((module, exports, __nccwpck_require__) => { +/***/ 87997: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; const Assert = __nccwpck_require__(32718); const Clone = __nccwpck_require__(85578); -const EscapeHtml = __nccwpck_require__(24752); -const Formula = __nccwpck_require__(34379); const Common = __nccwpck_require__(72448); -const Errors = __nccwpck_require__(69490); +const Messages = __nccwpck_require__(86103); const Ref = __nccwpck_require__(73838); +const Template = __nccwpck_require__(51396); +let Schemas; -const internals = { - symbol: Symbol('template'), - - opens: new Array(1000).join('\u0000'), - closes: new Array(1000).join('\u0001'), - dateFormat: { - date: Date.prototype.toDateString, - iso: Date.prototype.toISOString, - string: Date.prototype.toString, - time: Date.prototype.toTimeString, - utc: Date.prototype.toUTCString - } -}; +const internals = {}; -module.exports = exports = internals.Template = class { +exports.describe = function (schema) { - constructor(source, options) { + const def = schema._definition; - Assert(typeof source === 'string', 'Template source must be a string'); - Assert(!source.includes('\u0000') && !source.includes('\u0001'), 'Template source cannot contain reserved control characters'); + // Type - this.source = source; - this.rendered = source; + const desc = { + type: schema.type, + flags: {}, + rules: [] + }; - this._template = null; - this._settings = Clone(options); + // Flags - this._parse(); + for (const flag in schema._flags) { + if (flag[0] !== '_') { + desc.flags[flag] = internals.describe(schema._flags[flag]); + } } - _parse() { + if (!Object.keys(desc.flags).length) { + delete desc.flags; + } - // 'text {raw} {{ref}} \\{{ignore}} {{ignore\\}} {{ignore {{ignore}' + // Preferences - if (!this.source.includes('{')) { - return; + if (schema._preferences) { + desc.preferences = Clone(schema._preferences, { shallow: ['messages'] }); + delete desc.preferences[Common.symbols.prefs]; + if (desc.preferences.messages) { + desc.preferences.messages = Messages.decompile(desc.preferences.messages); } + } - // Encode escaped \\{{{{{ - - const encoded = internals.encode(this.source); + // Allow / Invalid - // Split on first { in each set + if (schema._valids) { + desc.allow = schema._valids.describe(); + } - const parts = internals.split(encoded); + if (schema._invalids) { + desc.invalid = schema._invalids.describe(); + } - // Process parts + // Rules - let refs = false; - const processed = []; - const head = parts.shift(); - if (head) { - processed.push(head); + for (const rule of schema._rules) { + const ruleDef = def.rules[rule.name]; + if (ruleDef.manifest === false) { // Defaults to true + continue; } - for (const part of parts) { - const raw = part[0] !== '{'; - const ender = raw ? '}' : '}}'; - const end = part.indexOf(ender); - if (end === -1 || // Ignore non-matching closing - part[1] === '{') { // Ignore more than two { + const item = { name: rule.name }; - processed.push(`{${internals.decode(part)}`); - continue; + for (const custom in def.modifiers) { + if (rule[custom] !== undefined) { + item[custom] = internals.describe(rule[custom]); } + } - let variable = part.slice(raw ? 0 : 1, end); - const wrapped = variable[0] === ':'; - if (wrapped) { - variable = variable.slice(1); - } + if (rule.args) { + item.args = {}; + for (const key in rule.args) { + const arg = rule.args[key]; + if (key === 'options' && + !Object.keys(arg).length) { - const dynamic = this._ref(internals.decode(variable), { raw, wrapped }); - processed.push(dynamic); - if (typeof dynamic !== 'string') { - refs = true; - } + continue; + } - const rest = part.slice(end + ender.length); - if (rest) { - processed.push(internals.decode(rest)); + item.args[key] = internals.describe(arg, { assign: key }); } - } - if (!refs) { - this.rendered = processed.join(''); - return; + if (!Object.keys(item.args).length) { + delete item.args; + } } - this._template = processed; + desc.rules.push(item); } - static date(date, prefs) { - - return internals.dateFormat[prefs.dateFormat].call(date); + if (!desc.rules.length) { + delete desc.rules; } - describe(options = {}) { - - if (!this._settings && - options.compact) { - - return this.source; - } + // Terms (must be last to verify no name conflicts) - const desc = { template: this.source }; - if (this._settings) { - desc.options = this._settings; + for (const term in schema.$_terms) { + if (term[0] === '_') { + continue; } - return desc; - } - - static build(desc) { - - return new internals.Template(desc.template, desc.options); - } - - isDynamic() { - - return !!this._template; - } - - static isTemplate(template) { - - return template ? !!template[Common.symbols.template] : false; - } - - refs() { + Assert(!desc[term], 'Cannot describe schema due to internal name conflict with', term); - if (!this._template) { - return; + const items = schema.$_terms[term]; + if (!items) { + continue; } - const refs = []; - for (const part of this._template) { - if (typeof part !== 'string') { - refs.push(...part.refs); + if (items instanceof Map) { + if (items.size) { + desc[term] = [...items.entries()]; } + + continue; } - return refs; - } + if (Common.isValues(items)) { + desc[term] = items.describe(); + continue; + } - resolve(value, state, prefs, local) { + Assert(def.terms[term], 'Term', term, 'missing configuration'); + const manifest = def.terms[term].manifest; + const mapped = typeof manifest === 'object'; + if (!items.length && + !mapped) { - if (this._template && - this._template.length === 1) { + continue; + } - return this._part(this._template[0], /* context -> [*/ value, state, prefs, local, {} /*] */); + const normalized = []; + for (const item of items) { + normalized.push(internals.describe(item)); } - return this.render(value, state, prefs, local); - } + // Mapped - _part(part, ...args) { + if (mapped) { + const { from, to } = manifest.mapped; + desc[term] = {}; + for (const item of normalized) { + desc[term][item[to]] = item[from]; + } - if (part.ref) { - return part.ref.resolve(...args); + continue; } - return part.formula.evaluate(args); - } - - render(value, state, prefs, local, options = {}) { + // Single - if (!this.isDynamic()) { - return this.rendered; + if (manifest === 'single') { + Assert(normalized.length === 1, 'Term', term, 'contains more than one item'); + desc[term] = normalized[0]; + continue; } - const parts = []; - for (const part of this._template) { - if (typeof part === 'string') { - parts.push(part); - } - else { - const rendered = this._part(part, /* context -> [*/ value, state, prefs, local, options /*] */); - const string = internals.stringify(rendered, value, state, prefs, local, options); - if (string !== undefined) { - const result = part.raw || (options.errors && options.errors.escapeHtml) === false ? string : EscapeHtml(string); - parts.push(internals.wrap(result, part.wrapped && prefs.errors.wrap.label)); - } - } - } + // Array - return parts.join(''); + desc[term] = normalized; } - _ref(content, { raw, wrapped }) { + internals.validate(schema.$_root, desc); + return desc; +}; - const refs = []; - const reference = (variable) => { - const ref = Ref.create(variable, this._settings); - refs.push(ref); - return (context) => ref.resolve(...context); - }; +internals.describe = function (item, options = {}) { - try { - var formula = new Formula.Parser(content, { reference, functions: internals.functions, constants: internals.constants }); - } - catch (err) { - err.message = `Invalid template variable "${content}" fails due to: ${err.message}`; - throw err; - } + if (Array.isArray(item)) { + return item.map(internals.describe); + } - if (formula.single) { - if (formula.single.type === 'reference') { - const ref = refs[0]; - return { ref, raw, refs, wrapped: wrapped || ref.type === 'local' && ref.key === 'label' }; - } + if (item === Common.symbols.deepDefault) { + return { special: 'deep' }; + } - return internals.stringify(formula.single.value); - } + if (typeof item !== 'object' || + item === null) { - return { formula, raw, refs }; + return item; } - toString() { + if (options.assign === 'options') { + return Clone(item); + } - return this.source; + if (Buffer && Buffer.isBuffer(item)) { // $lab:coverage:ignore$ + return { buffer: item.toString('binary') }; } -}; + if (item instanceof Date) { + return item.toISOString(); + } -internals.Template.prototype[Common.symbols.template] = true; -internals.Template.prototype.isImmutable = true; // Prevents Hoek from deep cloning schema objects + if (item instanceof Error) { + return item; + } + if (item instanceof RegExp) { + if (options.assign === 'regex') { + return item.toString(); + } -internals.encode = function (string) { + return { regex: item.toString() }; + } - return string - .replace(/\\(\{+)/g, ($0, $1) => { + if (item[Common.symbols.literal]) { + return { function: item.literal }; + } - return internals.opens.slice(0, $1.length); - }) - .replace(/\\(\}+)/g, ($0, $1) => { + if (typeof item.describe === 'function') { + if (options.assign === 'ref') { + return item.describe().ref; + } - return internals.closes.slice(0, $1.length); - }); -}; + return item.describe(); + } + const normalized = {}; + for (const key in item) { + const value = item[key]; + if (value === undefined) { + continue; + } -internals.decode = function (string) { + normalized[key] = internals.describe(value, { assign: key }); + } - return string - .replace(/\u0000/g, '{') - .replace(/\u0001/g, '}'); + return normalized; }; -internals.split = function (string) { - - const parts = []; - let current = ''; - - for (let i = 0; i < string.length; ++i) { - const char = string[i]; - - if (char === '{') { - let next = ''; - while (i + 1 < string.length && - string[i + 1] === '{') { - - next += '{'; - ++i; - } - - parts.push(current); - current = next; - } - else { - current += char; - } - } +exports.build = function (joi, desc) { - parts.push(current); - return parts; + const builder = new internals.Builder(joi); + return builder.parse(desc); }; -internals.wrap = function (value, ends) { +internals.Builder = class { - if (!ends) { - return value; - } + constructor(joi) { - if (ends.length === 1) { - return `${ends}${value}${ends}`; + this.joi = joi; } - return `${ends[0]}${value}${ends[1]}`; -}; + parse(desc) { + internals.validate(this.joi, desc); -internals.stringify = function (value, original, state, prefs, local, options = {}) { + // Type - const type = typeof value; - const wrap = prefs && prefs.errors && prefs.errors.wrap || {}; + let schema = this.joi[desc.type]()._bare(); + const def = schema._definition; - let skipWrap = false; - if (Ref.isRef(value) && - value.render) { + // Flags + + if (desc.flags) { + for (const flag in desc.flags) { + const setter = def.flags[flag] && def.flags[flag].setter || flag; + Assert(typeof schema[setter] === 'function', 'Invalid flag', flag, 'for type', desc.type); + schema = schema[setter](this.build(desc.flags[flag])); + } + } - skipWrap = value.in; - value = value.resolve(original, state, prefs, local, { in: value.in, ...options }); - } + // Preferences - if (value === null) { - return 'null'; - } + if (desc.preferences) { + schema = schema.preferences(this.build(desc.preferences)); + } - if (type === 'string') { - return internals.wrap(value, options.arrayItems && wrap.string); - } + // Allow / Invalid - if (type === 'number' || - type === 'function' || - type === 'symbol') { + if (desc.allow) { + schema = schema.allow(...this.build(desc.allow)); + } - return value.toString(); - } + if (desc.invalid) { + schema = schema.invalid(...this.build(desc.invalid)); + } - if (type !== 'object') { - return JSON.stringify(value); - } + // Rules - if (value instanceof Date) { - return internals.Template.date(value, prefs); - } + if (desc.rules) { + for (const rule of desc.rules) { + Assert(typeof schema[rule.name] === 'function', 'Invalid rule', rule.name, 'for type', desc.type); - if (value instanceof Map) { - const pairs = []; - for (const [key, sym] of value.entries()) { - pairs.push(`${key.toString()} -> ${sym.toString()}`); - } + const args = []; + if (rule.args) { + const built = {}; + for (const key in rule.args) { + built[key] = this.build(rule.args[key], { assign: key }); + } - value = pairs; - } + const keys = Object.keys(built); + const definition = def.rules[rule.name].args; + if (definition) { + Assert(keys.length <= definition.length, 'Invalid number of arguments for', desc.type, rule.name, '(expected up to', definition.length, ', found', keys.length, ')'); + for (const { name } of definition) { + args.push(built[name]); + } + } + else { + Assert(keys.length === 1, 'Invalid number of arguments for', desc.type, rule.name, '(expected up to 1, found', keys.length, ')'); + args.push(built[keys[0]]); + } + } - if (!Array.isArray(value)) { - return value.toString(); - } + // Apply - const values = []; - for (const item of value) { - values.push(internals.stringify(item, original, state, prefs, local, { arrayItems: true, ...options })); - } + schema = schema[rule.name](...args); - return internals.wrap(values.join(', '), !skipWrap && wrap.array); -}; + // Ruleset + const options = {}; + for (const custom in def.modifiers) { + if (rule[custom] !== undefined) { + options[custom] = this.build(rule[custom]); + } + } -internals.constants = { + if (Object.keys(options).length) { + schema = schema.rule(options); + } + } + } - true: true, - false: false, - null: null, + // Terms - second: 1000, - minute: 60 * 1000, - hour: 60 * 60 * 1000, - day: 24 * 60 * 60 * 1000 -}; + const terms = {}; + for (const key in desc) { + if (['allow', 'flags', 'invalid', 'whens', 'preferences', 'rules', 'type'].includes(key)) { + continue; + } + Assert(def.terms[key], 'Term', key, 'missing configuration'); + const manifest = def.terms[key].manifest; -internals.functions = { + if (manifest === 'schema') { + terms[key] = desc[key].map((item) => this.parse(item)); + continue; + } - if(condition, then, otherwise) { + if (manifest === 'values') { + terms[key] = desc[key].map((item) => this.build(item)); + continue; + } - return condition ? then : otherwise; - }, + if (manifest === 'single') { + terms[key] = this.build(desc[key]); + continue; + } - length(item) { + if (typeof manifest === 'object') { + terms[key] = {}; + for (const name in desc[key]) { + const value = desc[key][name]; + terms[key][name] = this.parse(value); + } - if (typeof item === 'string') { - return item.length; - } + continue; + } - if (!item || typeof item !== 'object') { - return null; + terms[key] = this.build(desc[key]); } - if (Array.isArray(item)) { - return item.length; + if (desc.whens) { + terms.whens = desc.whens.map((when) => this.build(when)); } - return Object.keys(item).length; - }, + schema = def.manifest.build(schema, terms); + schema.$_temp.ruleset = false; + return schema; + } - msg(code) { + build(desc, options = {}) { - const [value, state, prefs, local, options] = this; - const messages = options.messages; - if (!messages) { - return ''; + if (desc === null) { + return null; } - const template = Errors.template(value, messages[0], code, state, prefs) || Errors.template(value, messages[1], code, state, prefs); - if (!template) { - return ''; + if (Array.isArray(desc)) { + return desc.map((item) => this.build(item)); } - return template.render(value, state, prefs, local, options); - }, - - number(value) { + if (desc instanceof Error) { + return desc; + } - if (typeof value === 'number') { - return value; + if (options.assign === 'options') { + return Clone(desc); } - if (typeof value === 'string') { - return parseFloat(value); + if (options.assign === 'regex') { + return internals.regex(desc); } - if (typeof value === 'boolean') { - return value ? 1 : 0; + if (options.assign === 'ref') { + return Ref.build(desc); } - if (value instanceof Date) { - return value.getTime(); + if (typeof desc !== 'object') { + return desc; } - return null; - } -}; + if (Object.keys(desc).length === 1) { + if (desc.buffer) { + Assert(Buffer, 'Buffers are not supported'); + return Buffer && Buffer.from(desc.buffer, 'binary'); // $lab:coverage:ignore$ + } + if (desc.function) { + return { [Common.symbols.literal]: true, literal: desc.function }; + } -/***/ }), + if (desc.override) { + return Common.symbols.override; + } -/***/ 43171: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + if (desc.ref) { + return Ref.build(desc.ref); + } -"use strict"; + if (desc.regex) { + return internals.regex(desc.regex); + } + if (desc.special) { + Assert(['deep'].includes(desc.special), 'Unknown special value', desc.special); + return Common.symbols.deepDefault; + } -const DeepEqual = __nccwpck_require__(55801); -const Pinpoint = __nccwpck_require__(75604); + if (desc.value) { + return Clone(desc.value); + } + } -const Errors = __nccwpck_require__(69490); + if (desc.type) { + return this.parse(desc); + } + if (desc.template) { + return Template.build(desc); + } -const internals = { - codes: { - error: 1, - pass: 2, - full: 3 - }, - labels: { - 0: 'never used', - 1: 'always error', - 2: 'always pass' + const normalized = {}; + for (const key in desc) { + normalized[key] = this.build(desc[key], { assign: key }); + } + + return normalized; } }; -exports.setup = function (root) { +internals.regex = function (string) { - const trace = function () { + const end = string.lastIndexOf('/'); + const exp = string.slice(1, end); + const flags = string.slice(end + 1); + return new RegExp(exp, flags); +}; - root._tracer = root._tracer || new internals.Tracer(); - return root._tracer; - }; - root.trace = trace; - root[Symbol.for('@hapi/lab/coverage/initialize')] = trace; +internals.validate = function (joi, desc) { - root.untrace = () => { + Schemas = Schemas || __nccwpck_require__(85614); - root._tracer = null; - }; + joi.assert(desc, Schemas.description); }; -exports.location = function (schema) { +/***/ }), - return schema.$_setFlag('_tracerLocation', Pinpoint.location(2)); // base.tracer(), caller -}; +/***/ 86103: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +"use strict"; -internals.Tracer = class { - constructor() { +const Assert = __nccwpck_require__(32718); +const Clone = __nccwpck_require__(85578); - this.name = 'Joi'; - this._schemas = new Map(); - } +const Template = __nccwpck_require__(51396); - _register(schema) { - const existing = this._schemas.get(schema); - if (existing) { - return existing.store; - } +const internals = {}; - const store = new internals.Store(schema); - const { filename, line } = schema._flags._tracerLocation || Pinpoint.location(5); // internals.tracer(), internals.entry(), exports.entry(), validate(), caller - this._schemas.set(schema, { filename, line, store }); - return store; - } - _combine(merged, sources) { +exports.compile = function (messages, target) { - for (const { store } of this._schemas.values()) { - store._combine(merged, sources); - } - } + // Single value string ('plain error message', 'template {error} message') - report(file) { + if (typeof messages === 'string') { + Assert(!target, 'Cannot set single message string'); + return new Template(messages); + } - const coverage = []; + // Single value template - // Process each registered schema + if (Template.isTemplate(messages)) { + Assert(!target, 'Cannot set single message template'); + return messages; + } - for (const { filename, line, store } of this._schemas.values()) { - if (file && - file !== filename) { + // By error code { 'number.min': } - continue; - } + Assert(typeof messages === 'object' && !Array.isArray(messages), 'Invalid message options'); - // Process sub schemas of the registered root + target = target ? Clone(target) : {}; - const missing = []; - const skipped = []; + for (let code in messages) { + const message = messages[code]; - for (const [schema, log] of store._sources.entries()) { + if (code === 'root' || + Template.isTemplate(message)) { - // Check if sub schema parent skipped + target[code] = message; + continue; + } - if (internals.sub(log.paths, skipped)) { - continue; - } + if (typeof message === 'string') { + target[code] = new Template(message); + continue; + } - // Check if sub schema reached + // By language { english: { 'number.min': } } - if (!log.entry) { - missing.push({ - status: 'never reached', - paths: [...log.paths] - }); + Assert(typeof message === 'object' && !Array.isArray(message), 'Invalid message for', code); - skipped.push(...log.paths); - continue; - } + const language = code; + target[language] = target[language] || {}; - // Check values + for (code in message) { + const localized = message[code]; - for (const type of ['valid', 'invalid']) { - const set = schema[`_${type}s`]; - if (!set) { - continue; - } + if (code === 'root' || + Template.isTemplate(localized)) { - const values = new Set(set._values); - const refs = new Set(set._refs); - for (const { value, ref } of log[type]) { - values.delete(value); - refs.delete(ref); - } + target[language][code] = localized; + continue; + } - if (values.size || - refs.size) { + Assert(typeof localized === 'string', 'Invalid message for', code, 'in', language); + target[language][code] = new Template(localized); + } + } - missing.push({ - status: [...values, ...[...refs].map((ref) => ref.display)], - rule: `${type}s` - }); - } - } + return target; +}; - // Check rules status - const rules = schema._rules.map((rule) => rule.name); - for (const type of ['default', 'failover']) { - if (schema._flags[type] !== undefined) { - rules.push(type); - } - } +exports.decompile = function (messages) { - for (const name of rules) { - const status = internals.labels[log.rule[name] || 0]; - if (status) { - const report = { rule: name, status }; - if (log.paths.size) { - report.paths = [...log.paths]; - } + // By error code { 'number.min': } - missing.push(report); - } - } - } + const target = {}; + for (let code in messages) { + const message = messages[code]; - if (missing.length) { - coverage.push({ - filename, - line, - missing, - severity: 'error', - message: `Schema missing tests for ${missing.map(internals.message).join(', ')}` - }); - } + if (code === 'root') { + target.root = message; + continue; } - return coverage.length ? coverage : null; - } -}; - + if (Template.isTemplate(message)) { + target[code] = message.describe({ compact: true }); + continue; + } -internals.Store = class { + // By language { english: { 'number.min': } } - constructor(schema) { + const language = code; + target[language] = {}; - this.active = true; - this._sources = new Map(); // schema -> { paths, entry, rule, valid, invalid } - this._combos = new Map(); // merged -> [sources] - this._scan(schema); - } + for (code in message) { + const localized = message[code]; - debug(state, source, name, result) { + if (code === 'root') { + target[language].root = localized; + continue; + } - state.mainstay.debug && state.mainstay.debug.push({ type: source, name, result, path: state.path }); + target[language][code] = localized.describe({ compact: true }); + } } - entry(schema, state) { + return target; +}; - internals.debug(state, { type: 'entry' }); - this._record(schema, (log) => { +exports.merge = function (base, extended) { - log.entry = true; - }); + if (!base) { + return exports.compile(extended); } - filter(schema, state, source, value) { - - internals.debug(state, { type: source, ...value }); - - this._record(schema, (log) => { - - log[source].add(value); - }); + if (!extended) { + return base; } - log(schema, state, source, name, result) { + // Single value string - internals.debug(state, { type: source, name, result: result === 'full' ? 'pass' : result }); + if (typeof extended === 'string') { + return new Template(extended); + } - this._record(schema, (log) => { + // Single value template - log[source][name] = log[source][name] || 0; - log[source][name] |= internals.codes[result]; - }); + if (Template.isTemplate(extended)) { + return extended; } - resolve(state, ref, to) { - - if (!state.mainstay.debug) { - return; - } + // By error code { 'number.min': } - const log = { type: 'resolve', ref: ref.display, to, path: state.path }; - state.mainstay.debug.push(log); - } + const target = Clone(base); - value(state, by, from, to, name) { + for (let code in extended) { + const message = extended[code]; - if (!state.mainstay.debug || - DeepEqual(from, to)) { + if (code === 'root' || + Template.isTemplate(message)) { - return; + target[code] = message; + continue; } - const log = { type: 'value', by, from, to, path: state.path }; - if (name) { - log.name = name; + if (typeof message === 'string') { + target[code] = new Template(message); + continue; } - state.mainstay.debug.push(log); - } + // By language { english: { 'number.min': } } - _record(schema, each) { + Assert(typeof message === 'object' && !Array.isArray(message), 'Invalid message for', code); - const log = this._sources.get(schema); - if (log) { - each(log); - return; - } + const language = code; + target[language] = target[language] || {}; + + for (code in message) { + const localized = message[code]; + + if (code === 'root' || + Template.isTemplate(localized)) { - const sources = this._combos.get(schema); - for (const source of sources) { - this._record(source, each); + target[language][code] = localized; + continue; + } + + Assert(typeof localized === 'string', 'Invalid message for', code, 'in', language); + target[language][code] = new Template(localized); } } - _scan(schema, _path) { - - const path = _path || []; + return target; +}; - let log = this._sources.get(schema); - if (!log) { - log = { - paths: new Set(), - entry: false, - rule: {}, - valid: new Set(), - invalid: new Set() - }; - this._sources.set(schema, log); - } +/***/ }), - if (path.length) { - log.paths.add(path); - } +/***/ 81290: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - const each = (sub, source) => { +"use strict"; - const subId = internals.id(sub, source); - this._scan(sub, path.concat(subId)); - }; - schema.$_modify({ each, ref: false }); - } +const Assert = __nccwpck_require__(32718); - _combine(merged, sources) { +const Common = __nccwpck_require__(72448); +const Ref = __nccwpck_require__(73838); - this._combos.set(merged, sources); - } -}; +const internals = {}; -internals.message = function (item) { - const path = item.paths ? Errors.path(item.paths[0]) + (item.rule ? ':' : '') : ''; - return `${path}${item.rule || ''} (${item.status})`; -}; +exports.Ids = internals.Ids = class { -internals.id = function (schema, { source, name, path, key }) { + constructor() { - if (schema._flags.id) { - return schema._flags.id; + this._byId = new Map(); + this._byKey = new Map(); + this._schemaChain = false; } - if (key) { - return key; + clone() { + + const clone = new internals.Ids(); + clone._byId = new Map(this._byId); + clone._byKey = new Map(this._byKey); + clone._schemaChain = this._schemaChain; + return clone; } - name = `@${name}`; + concat(source) { - if (source === 'terms') { - return [name, path[Math.min(path.length - 1, 1)]]; + if (source._schemaChain) { + this._schemaChain = true; + } + + for (const [id, value] of source._byId.entries()) { + Assert(!this._byKey.has(id), 'Schema id conflicts with existing key:', id); + this._byId.set(id, value); + } + + for (const [key, value] of source._byKey.entries()) { + Assert(!this._byId.has(key), 'Schema key conflicts with existing id:', key); + this._byKey.set(key, value); + } } - return name; -}; + fork(path, adjuster, root) { + const chain = this._collect(path); + chain.push({ schema: root }); + const tail = chain.shift(); + let adjusted = { id: tail.id, schema: adjuster(tail.schema) }; -internals.sub = function (paths, skipped) { + Assert(Common.isSchema(adjusted.schema), 'adjuster function failed to return a joi schema type'); - for (const path of paths) { - for (const skip of skipped) { - if (DeepEqual(path.slice(0, skip.length), skip)) { - return true; - } + for (const node of chain) { + adjusted = { id: node.id, schema: internals.fork(node.schema, adjusted.id, adjusted.schema) }; } + + return adjusted.schema; } - return false; -}; + labels(path, behind = []) { + const current = path[0]; + const node = this._get(current); + if (!node) { + return [...behind, ...path].join('.'); + } -internals.debug = function (state, event) { + const forward = path.slice(1); + behind = [...behind, node.schema._flags.label || current]; + if (!forward.length) { + return behind.join('.'); + } - if (state.mainstay.debug) { - event.path = state.debug ? [...state.path, state.debug] : state.path; - state.mainstay.debug.push(event); + return node.schema._ids.labels(forward, behind); } -}; + reach(path, behind = []) { -/***/ }), + const current = path[0]; + const node = this._get(current); + Assert(node, 'Schema does not contain path', [...behind, ...path].join('.')); -/***/ 26867: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + const forward = path.slice(1); + if (!forward.length) { + return node.schema; + } -"use strict"; + return node.schema._ids.reach(forward, [...behind, current]); + } + register(schema, { key } = {}) { -const Assert = __nccwpck_require__(32718); -const Merge = __nccwpck_require__(60445); + if (!schema || + !Common.isSchema(schema)) { -const Any = __nccwpck_require__(9512); -const Common = __nccwpck_require__(72448); -const Compile = __nccwpck_require__(3038); -const Errors = __nccwpck_require__(69490); -const Ref = __nccwpck_require__(73838); + return; + } + if (schema.$_property('schemaChain') || + schema._ids._schemaChain) { -const internals = {}; + this._schemaChain = true; + } + const id = schema._flags.id; + if (id) { + const existing = this._byId.get(id); + Assert(!existing || existing.schema === schema, 'Cannot add different schemas with the same id:', id); + Assert(!this._byKey.has(id), 'Schema id conflicts with existing key:', id); -module.exports = Any.extend({ + this._byId.set(id, { schema, id }); + } - type: 'alternatives', + if (key) { + Assert(!this._byKey.has(key), 'Schema already contains key:', key); + Assert(!this._byId.has(key), 'Schema key conflicts with existing id:', key); - flags: { + this._byKey.set(key, { schema, id: key }); + } + } - match: { default: 'any' } // 'any', 'one', 'all' - }, + reset() { - terms: { + this._byId = new Map(); + this._byKey = new Map(); + this._schemaChain = false; + } - matches: { init: [], register: Ref.toSibling } - }, + _collect(path, behind = [], nodes = []) { - args(schema, ...schemas) { + const current = path[0]; + const node = this._get(current); + Assert(node, 'Schema does not contain path', [...behind, ...path].join('.')); - if (schemas.length === 1) { - if (Array.isArray(schemas[0])) { - return schema.try(...schemas[0]); - } + nodes = [node, ...nodes]; + + const forward = path.slice(1); + if (!forward.length) { + return nodes; } - return schema.try(...schemas); - }, + return node.schema._ids._collect(forward, [...behind, current], nodes); + } - validate(value, helpers) { + _get(id) { - const { schema, error, state, prefs } = helpers; + return this._byId.get(id) || this._byKey.get(id); + } +}; - // Match all or one - if (schema._flags.match) { - const matched = []; - const failed = []; +internals.fork = function (schema, id, replacement) { - for (let i = 0; i < schema.$_terms.matches.length; ++i) { - const item = schema.$_terms.matches[i]; - const localState = state.nest(item.schema, `match.${i}`); - localState.snapshot(); + const each = (item, { key }) => { - const result = item.schema.$_validate(value, localState, prefs); - if (!result.errors) { - matched.push(result.value); - } - else { - failed.push(result.errors); - localState.restore(); - } - } + if (id === (item._flags.id || key)) { + return replacement; + } + }; - if (matched.length === 0) { - const context = { - details: failed.map((f) => Errors.details(f, { override: false })) - }; + const obj = exports.schema(schema, { each, ref: false }); + return obj ? obj.$_mutateRebuild() : schema; +}; - return { errors: error('alternatives.any', context) }; - } - // Match one +exports.schema = function (schema, options) { - if (schema._flags.match === 'one') { - return matched.length === 1 ? { value: matched[0] } : { errors: error('alternatives.one') }; - } + let obj; - // Match all + for (const name in schema._flags) { + if (name[0] === '_') { + continue; + } - if (matched.length !== schema.$_terms.matches.length) { - const context = { - details: failed.map((f) => Errors.details(f, { override: false })) - }; + const result = internals.scan(schema._flags[name], { source: 'flags', name }, options); + if (result !== undefined) { + obj = obj || schema.clone(); + obj._flags[name] = result; + } + } - return { errors: error('alternatives.all', context) }; + for (let i = 0; i < schema._rules.length; ++i) { + const rule = schema._rules[i]; + const result = internals.scan(rule.args, { source: 'rules', name: rule.name }, options); + if (result !== undefined) { + obj = obj || schema.clone(); + const clone = Object.assign({}, rule); + clone.args = result; + obj._rules[i] = clone; + + const existingUnique = obj._singleRules.get(rule.name); + if (existingUnique === rule) { + obj._singleRules.set(rule.name, clone); } + } + } - const isAnyObj = (alternative) => { + for (const name in schema.$_terms) { + if (name[0] === '_') { + continue; + } - return alternative.$_terms.matches.some((v) => { + const result = internals.scan(schema.$_terms[name], { source: 'terms', name }, options); + if (result !== undefined) { + obj = obj || schema.clone(); + obj.$_terms[name] = result; + } + } - return v.schema.type === 'object' || - (v.schema.type === 'alternatives' && isAnyObj(v.schema)); - }); - }; + return obj; +}; - return isAnyObj(schema) ? { value: matched.reduce((acc, v) => Merge(acc, v, { mergeArrays: false })) } : { value: matched[matched.length - 1] }; - } - // Match any +internals.scan = function (item, source, options, _path, _key) { - const errors = []; - for (let i = 0; i < schema.$_terms.matches.length; ++i) { - const item = schema.$_terms.matches[i]; + const path = _path || []; - // Try + if (item === null || + typeof item !== 'object') { - if (item.schema) { - const localState = state.nest(item.schema, `match.${i}`); - localState.snapshot(); + return; + } - const result = item.schema.$_validate(value, localState, prefs); - if (!result.errors) { - return result; - } + let clone; - localState.restore(); - errors.push({ schema: item.schema, reports: result.errors }); - continue; + if (Array.isArray(item)) { + for (let i = 0; i < item.length; ++i) { + const key = source.source === 'terms' && source.name === 'keys' && item[i].key; + const result = internals.scan(item[i], source, options, [i, ...path], key); + if (result !== undefined) { + clone = clone || item.slice(); + clone[i] = result; } + } - // Conditional + return clone; + } - const input = item.ref ? item.ref.resolve(value, state, prefs) : value; - const tests = item.is ? [item] : item.switch; + if (options.schema !== false && Common.isSchema(item) || + options.ref !== false && Ref.isRef(item)) { - for (let j = 0; j < tests.length; ++j) { - const test = tests[j]; - const { is, then, otherwise } = test; + const result = options.each(item, { ...source, path, key: _key }); + if (result === item) { + return; + } - const id = `match.${i}${item.switch ? '.' + j : ''}`; - if (!is.$_match(input, state.nest(is, `${id}.is`), prefs)) { - if (otherwise) { - return otherwise.$_validate(value, state.nest(otherwise, `${id}.otherwise`), prefs); - } - } - else if (then) { - return then.$_validate(value, state.nest(then, `${id}.then`), prefs); - } - } + return result; + } + + for (const key in item) { + if (key[0] === '_') { + continue; } - return internals.errors(errors, helpers); - }, + const result = internals.scan(item[key], source, options, [key, ...path], _key); + if (result !== undefined) { + clone = clone || Object.assign({}, item); + clone[key] = result; + } + } - rules: { + return clone; +}; - conditional: { - method(condition, options) { - Assert(!this._flags._endedSwitch, 'Unreachable condition'); - Assert(!this._flags.match, 'Cannot combine match mode', this._flags.match, 'with conditional rule'); - Assert(options.break === undefined, 'Cannot use break option with alternatives conditional'); +/***/ }), - const obj = this.clone(); +/***/ 73838: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - const match = Compile.when(obj, condition, options); - const conditions = match.is ? [match] : match.switch; - for (const item of conditions) { - if (item.then && - item.otherwise) { +"use strict"; - obj.$_setFlag('_endedSwitch', true, { clone: false }); - break; - } - } - obj.$_terms.matches.push(match); - return obj.$_mutateRebuild(); - } - }, +const Assert = __nccwpck_require__(32718); +const Clone = __nccwpck_require__(85578); +const Reach = __nccwpck_require__(18891); - match: { - method(mode) { +const Common = __nccwpck_require__(72448); - Assert(['any', 'one', 'all'].includes(mode), 'Invalid alternatives match mode', mode); +let Template; - if (mode !== 'any') { - for (const match of this.$_terms.matches) { - Assert(match.schema, 'Cannot combine match mode', mode, 'with conditional rules'); - } - } - return this.$_setFlag('match', mode); - } - }, +const internals = { + symbol: Symbol('ref'), // Used to internally identify references (shared with other joi versions) + defaults: { + adjust: null, + in: false, + iterables: null, + map: null, + separator: '.', + type: 'value' + } +}; - try: { - method(...schemas) { - Assert(schemas.length, 'Missing alternative schemas'); - Common.verifyFlat(schemas, 'try'); +exports.create = function (key, options = {}) { - Assert(!this._flags._endedSwitch, 'Unreachable condition'); + Assert(typeof key === 'string', 'Invalid reference key:', key); + Common.assertOptions(options, ['adjust', 'ancestor', 'in', 'iterables', 'map', 'prefix', 'render', 'separator']); + Assert(!options.prefix || typeof options.prefix === 'object', 'options.prefix must be of type object'); - const obj = this.clone(); - for (const schema of schemas) { - obj.$_terms.matches.push({ schema: obj.$_compile(schema) }); - } + const ref = Object.assign({}, internals.defaults, options); + delete ref.prefix; - return obj.$_mutateRebuild(); + const separator = ref.separator; + const context = internals.context(key, separator, options.prefix); + ref.type = context.type; + key = context.key; + + if (ref.type === 'value') { + if (context.root) { + Assert(!separator || key[0] !== separator, 'Cannot specify relative path with root prefix'); + ref.ancestor = 'root'; + if (!key) { + key = null; } } - }, - overrides: { + if (separator && + separator === key) { - label(name) { + key = null; + ref.ancestor = 0; + } + else { + if (ref.ancestor !== undefined) { + Assert(!separator || !key || key[0] !== separator, 'Cannot combine prefix with ancestor option'); + } + else { + const [ancestor, slice] = internals.ancestor(key, separator); + if (slice) { + key = key.slice(slice); + if (key === '') { + key = null; + } + } - const obj = this.$_parent('label', name); - const each = (item, source) => (source.path[0] !== 'is' ? item.label(name) : undefined); - return obj.$_modify({ each, ref: false }); + ref.ancestor = ancestor; + } } - }, + } - rebuild(schema) { + ref.path = separator ? (key === null ? [] : key.split(separator)) : [key]; - // Flag when an alternative type is an array + return new internals.Ref(ref); +}; - const each = (item) => { - if (Common.isSchema(item) && - item.type === 'array') { +exports["in"] = function (key, options = {}) { - schema.$_setFlag('_arrayItems', true, { clone: false }); - } - }; + return exports.create(key, { ...options, in: true }); +}; - schema.$_modify({ each }); - }, - manifest: { +exports.isRef = function (ref) { - build(obj, desc) { + return ref ? !!ref[Common.symbols.ref] : false; +}; - if (desc.matches) { - for (const match of desc.matches) { - const { schema, ref, is, not, then, otherwise } = match; - if (schema) { - obj = obj.try(schema); - } - else if (ref) { - obj = obj.conditional(ref, { is, then, not, otherwise, switch: match.switch }); - } - else { - obj = obj.conditional(is, { then, otherwise }); - } - } - } - return obj; - } - }, +internals.Ref = class { - messages: { - 'alternatives.all': '{{#label}} does not match all of the required types', - 'alternatives.any': '{{#label}} does not match any of the allowed types', - 'alternatives.match': '{{#label}} does not match any of the allowed types', - 'alternatives.one': '{{#label}} matches more than one allowed type', - 'alternatives.types': '{{#label}} must be one of {{#types}}' - } -}); + constructor(options) { + Assert(typeof options === 'object', 'Invalid reference construction'); + Common.assertOptions(options, [ + 'adjust', 'ancestor', 'in', 'iterables', 'map', 'path', 'render', 'separator', 'type', // Copied + 'depth', 'key', 'root', 'display' // Overridden + ]); -// Helpers + Assert([false, undefined].includes(options.separator) || typeof options.separator === 'string' && options.separator.length === 1, 'Invalid separator'); + Assert(!options.adjust || typeof options.adjust === 'function', 'options.adjust must be a function'); + Assert(!options.map || Array.isArray(options.map), 'options.map must be an array'); + Assert(!options.map || !options.adjust, 'Cannot set both map and adjust options'); -internals.errors = function (failures, { error, state }) { + Object.assign(this, internals.defaults, options); - // Nothing matched due to type criteria rules + Assert(this.type === 'value' || this.ancestor === undefined, 'Non-value references cannot reference ancestors'); - if (!failures.length) { - return { errors: error('alternatives.any') }; - } + if (Array.isArray(this.map)) { + this.map = new Map(this.map); + } - // Single error + this.depth = this.path.length; + this.key = this.path.length ? this.path.join(this.separator) : null; + this.root = this.path[0]; - if (failures.length === 1) { - return { errors: failures[0].reports }; + this.updateDisplay(); } - // Analyze reasons - - const valids = new Set(); - const complex = []; + resolve(value, state, prefs, local, options = {}) { - for (const { reports, schema } of failures) { + Assert(!this.in || options.in, 'Invalid in() reference usage'); - // Multiple errors (!abortEarly) + if (this.type === 'global') { + return this._resolve(prefs.context, state, options); + } - if (reports.length > 1) { - return internals.unmatched(failures, error); + if (this.type === 'local') { + return this._resolve(local, state, options); } - // Custom error + if (!this.ancestor) { + return this._resolve(value, state, options); + } - const report = reports[0]; - if (report instanceof Errors.Report === false) { - return internals.unmatched(failures, error); + if (this.ancestor === 'root') { + return this._resolve(state.ancestors[state.ancestors.length - 1], state, options); } - // Internal object or array error + Assert(this.ancestor <= state.ancestors.length, 'Invalid reference exceeds the schema root:', this.display); + return this._resolve(state.ancestors[this.ancestor - 1], state, options); + } - if (report.state.path.length !== state.path.length) { - complex.push({ type: schema.type, report }); - continue; - } + _resolve(target, state, options) { - // Valids + let resolved; - if (report.code === 'any.only') { - for (const valid of report.local.valids) { - valids.add(valid); - } + if (this.type === 'value' && + state.mainstay.shadow && + options.shadow !== false) { - continue; + resolved = state.mainstay.shadow.get(this.absolute(state)); } - // Base type + if (resolved === undefined) { + resolved = Reach(target, this.path, { iterables: this.iterables, functions: true }); + } - const [type, code] = report.code.split('.'); - if (code !== 'base') { - complex.push({ type: schema.type, report }); - continue; + if (this.adjust) { + resolved = this.adjust(resolved); } - valids.add(type); - } + if (this.map) { + const mapped = this.map.get(resolved); + if (mapped !== undefined) { + resolved = mapped; + } + } - // All errors are base types or valids + if (state.mainstay) { + state.mainstay.tracer.resolve(state, this, resolved); + } - if (!complex.length) { - return { errors: error('alternatives.types', { types: [...valids] }) }; + return resolved; } - // Single complex error + toString() { - if (complex.length === 1) { - return { errors: complex[0].report }; + return this.display; } - return internals.unmatched(failures, error); -}; + absolute(state) { + return [...state.path.slice(0, -this.ancestor), ...this.path]; + } -internals.unmatched = function (failures, error) { + clone() { - const errors = []; - for (const failure of failures) { - errors.push(...failure.reports); + return new internals.Ref(this); } - return { errors: error('alternatives.match', Errors.details(errors, { override: false })) }; -}; + describe() { + const ref = { path: this.path }; -/***/ }), + if (this.type !== 'value') { + ref.type = this.type; + } -/***/ 9512: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (this.separator !== '.') { + ref.separator = this.separator; + } -"use strict"; + if (this.type === 'value' && + this.ancestor !== 1) { + ref.ancestor = this.ancestor; + } -const Assert = __nccwpck_require__(32718); + if (this.map) { + ref.map = [...this.map]; + } -const Base = __nccwpck_require__(95184); -const Common = __nccwpck_require__(72448); -const Messages = __nccwpck_require__(86103); + for (const key of ['adjust', 'iterables', 'render']) { + if (this[key] !== null && + this[key] !== undefined) { + ref[key] = this[key]; + } + } -const internals = {}; + if (this.in !== false) { + ref.in = true; + } + return { ref }; + } -module.exports = Base.extend({ + updateDisplay() { - type: 'any', + const key = this.key !== null ? this.key : ''; + if (this.type !== 'value') { + this.display = `ref:${this.type}:${key}`; + return; + } - flags: { + if (!this.separator) { + this.display = `ref:${key}`; + return; + } - only: { default: false } - }, + if (!this.ancestor) { + this.display = `ref:${this.separator}${key}`; + return; + } - terms: { + if (this.ancestor === 'root') { + this.display = `ref:root:${key}`; + return; + } - alterations: { init: null }, - examples: { init: null }, - externals: { init: null }, - metas: { init: [] }, - notes: { init: [] }, - shared: { init: null }, - tags: { init: [] }, - whens: { init: null } - }, + if (this.ancestor === 1) { + this.display = `ref:${key || '..'}`; + return; + } - rules: { + const lead = new Array(this.ancestor + 1).fill(this.separator).join(''); + this.display = `ref:${lead}${key || ''}`; + } +}; - custom: { - method(method, description) { - Assert(typeof method === 'function', 'Method must be a function'); - Assert(description === undefined || description && typeof description === 'string', 'Description must be a non-empty string'); +internals.Ref.prototype[Common.symbols.ref] = true; - return this.$_addRule({ name: 'custom', args: { method, description } }); - }, - validate(value, helpers, { method }) { - try { - return method(value, helpers); - } - catch (err) { - return helpers.error('any.custom', { error: err }); - } - }, - args: ['method', 'description'], - multi: true - }, +exports.build = function (desc) { - messages: { - method(messages) { + desc = Object.assign({}, internals.defaults, desc); + if (desc.type === 'value' && + desc.ancestor === undefined) { - return this.prefs({ messages }); - } - }, + desc.ancestor = 1; + } - shared: { - method(schema) { + return new internals.Ref(desc); +}; - Assert(Common.isSchema(schema) && schema._flags.id, 'Schema must be a schema with an id'); - const obj = this.clone(); - obj.$_terms.shared = obj.$_terms.shared || []; - obj.$_terms.shared.push(schema); - obj.$_mutateRegister(schema); - return obj; - } - }, +internals.context = function (key, separator, prefix = {}) { - warning: { - method(code, local) { + key = key.trim(); - Assert(code && typeof code === 'string', 'Invalid warning code'); + if (prefix) { + const globalp = prefix.global === undefined ? '$' : prefix.global; + if (globalp !== separator && + key.startsWith(globalp)) { - return this.$_addRule({ name: 'warning', args: { code, local }, warn: true }); - }, - validate(value, helpers, { code, local }) { + return { key: key.slice(globalp.length), type: 'global' }; + } - return helpers.error(code, local); - }, - args: ['code', 'local'], - multi: true + const local = prefix.local === undefined ? '#' : prefix.local; + if (local !== separator && + key.startsWith(local)) { + + return { key: key.slice(local.length), type: 'local' }; } - }, - modifiers: { + const root = prefix.root === undefined ? '/' : prefix.root; + if (root !== separator && + key.startsWith(root)) { - keep(rule, enabled = true) { + return { key: key.slice(root.length), type: 'value', root: true }; + } + } - rule.keep = enabled; - }, + return { key, type: 'value' }; +}; - message(rule, message) { - rule.message = Messages.compile(message); - }, +internals.ancestor = function (key, separator) { - warn(rule, enabled = true) { + if (!separator) { + return [1, 0]; // 'a_b' -> 1 (parent) + } - rule.warn = enabled; - } - }, + if (key[0] !== separator) { // 'a.b' -> 1 (parent) + return [1, 0]; + } - manifest: { + if (key[1] !== separator) { // '.a.b' -> 0 (self) + return [0, 1]; + } - build(obj, desc) { + let i = 2; + while (key[i] === separator) { + ++i; + } - for (const key in desc) { - const values = desc[key]; + return [i - 1, i]; // '...a.b.' -> 2 (grandparent) +}; - if (['examples', 'externals', 'metas', 'notes', 'tags'].includes(key)) { - for (const value of values) { - obj = obj[key.slice(0, -1)](value); - } - continue; - } +exports.toSibling = 0; - if (key === 'alterations') { - const alter = {}; - for (const { target, adjuster } of values) { - alter[target] = adjuster; - } +exports.toParent = 1; - obj = obj.alter(alter); - continue; - } - if (key === 'whens') { - for (const value of values) { - const { ref, is, not, then, otherwise, concat } = value; - if (concat) { - obj = obj.concat(concat); - } - else if (ref) { - obj = obj.when(ref, { is, not, then, otherwise, switch: value.switch, break: value.break }); - } - else { - obj = obj.when(is, { then, otherwise, break: value.break }); - } - } +exports.Manager = class { - continue; - } + constructor() { - if (key === 'shared') { - for (const value of values) { - obj = obj.shared(value); - } - } - } + this.refs = []; // 0: [self refs], 1: [parent refs], 2: [grandparent refs], ... + } - return obj; + register(source, target) { + + if (!source) { + return; } - }, - messages: { - 'any.custom': '{{#label}} failed custom validation because {{#error.message}}', - 'any.default': '{{#label}} threw an error when running default method', - 'any.failover': '{{#label}} threw an error when running failover method', - 'any.invalid': '{{#label}} contains an invalid value', - 'any.only': '{{#label}} must be {if(#valids.length == 1, "", "one of ")}{{#valids}}', - 'any.ref': '{{#label}} {{#arg}} references {{:#ref}} which {{#reason}}', - 'any.required': '{{#label}} is required', - 'any.unknown': '{{#label}} is not allowed' - } -}); + target = target === undefined ? exports.toParent : target; + // Array -/***/ }), + if (Array.isArray(source)) { + for (const ref of source) { + this.register(ref, target); + } -/***/ 20270: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return; + } -"use strict"; + // Schema + if (Common.isSchema(source)) { + for (const item of source._refs.refs) { + if (item.ancestor - target >= 0) { + this.refs.push({ ancestor: item.ancestor - target, root: item.root }); + } + } -const Assert = __nccwpck_require__(32718); -const DeepEqual = __nccwpck_require__(55801); -const Reach = __nccwpck_require__(18891); + return; + } -const Any = __nccwpck_require__(9512); -const Common = __nccwpck_require__(72448); -const Compile = __nccwpck_require__(3038); + // Reference + if (exports.isRef(source) && + source.type === 'value' && + source.ancestor - target >= 0) { -const internals = {}; + this.refs.push({ ancestor: source.ancestor - target, root: source.root }); + } + // Template -module.exports = Any.extend({ + Template = Template || __nccwpck_require__(51396); - type: 'array', + if (Template.isTemplate(source)) { + this.register(source.refs(), target); + } + } - flags: { + get length() { - single: { default: false }, - sparse: { default: false } - }, + return this.refs.length; + } - terms: { + clone() { - items: { init: [], manifest: 'schema' }, - ordered: { init: [], manifest: 'schema' }, + const copy = new exports.Manager(); + copy.refs = Clone(this.refs); + return copy; + } - _exclusions: { init: [] }, - _inclusions: { init: [] }, - _requireds: { init: [] } - }, + reset() { - coerce: { - from: 'object', - method(value, { schema, state, prefs }) { + this.refs = []; + } - if (!Array.isArray(value)) { - return; - } + roots() { - const sort = schema.$_getRule('sort'); - if (!sort) { - return; - } + return this.refs.filter((ref) => !ref.ancestor).map((ref) => ref.root); + } +}; - return internals.sort(schema, value, sort.args.options, state, prefs); - } - }, - validate(value, { schema, error }) { +/***/ }), - if (!Array.isArray(value)) { - if (schema._flags.single) { - const single = [value]; - single[Common.symbols.arraySingle] = true; - return { value: single }; - } +/***/ 85614: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - return { errors: error('array.base') }; - } +"use strict"; - if (!schema.$_getRule('items') && - !schema.$_terms.externals) { - return; - } +const Joi = __nccwpck_require__(20918); - return { value: value.slice() }; // Clone the array so that we don't modify the original - }, - rules: { +const internals = {}; - has: { - method(schema) { - schema = this.$_compile(schema, { appendPath: true }); - const obj = this.$_addRule({ name: 'has', args: { schema } }); - obj.$_mutateRegister(schema); - return obj; - }, - validate(value, { state, prefs, error }, { schema: has }) { +// Preferences - const ancestors = [value, ...state.ancestors]; - for (let i = 0; i < value.length; ++i) { - const localState = state.localize([...state.path, i], ancestors, has); - if (has.$_match(value[i], localState, prefs)) { - return value; - } - } +internals.wrap = Joi.string() + .min(1) + .max(2) + .allow(false); - const patternLabel = has._flags.label; - if (patternLabel) { - return error('array.hasKnown', { patternLabel }); - } - return error('array.hasUnknown', null); - }, - multi: true - }, +exports.preferences = Joi.object({ + allowUnknown: Joi.boolean(), + abortEarly: Joi.boolean(), + artifacts: Joi.boolean(), + cache: Joi.boolean(), + context: Joi.object(), + convert: Joi.boolean(), + dateFormat: Joi.valid('date', 'iso', 'string', 'time', 'utc'), + debug: Joi.boolean(), + errors: { + escapeHtml: Joi.boolean(), + label: Joi.valid('path', 'key', false), + language: [ + Joi.string(), + Joi.object().ref() + ], + render: Joi.boolean(), + stack: Joi.boolean(), + wrap: { + label: internals.wrap, + array: internals.wrap, + string: internals.wrap + } + }, + externals: Joi.boolean(), + messages: Joi.object(), + noDefaults: Joi.boolean(), + nonEnumerables: Joi.boolean(), + presence: Joi.valid('required', 'optional', 'forbidden'), + skipFunctions: Joi.boolean(), + stripUnknown: Joi.object({ + arrays: Joi.boolean(), + objects: Joi.boolean() + }) + .or('arrays', 'objects') + .allow(true, false), + warnings: Joi.boolean() +}) + .strict(); - items: { - method(...schemas) { - Common.verifyFlat(schemas, 'items'); +// Extensions - const obj = this.$_addRule('items'); +internals.nameRx = /^[a-zA-Z0-9]\w*$/; - for (let i = 0; i < schemas.length; ++i) { - const type = Common.tryWithPath(() => this.$_compile(schemas[i]), i, { append: true }); - obj.$_terms.items.push(type); - } - return obj.$_mutateRebuild(); - }, - validate(value, { schema, error, state, prefs, errorsArray }) { +internals.rule = Joi.object({ + alias: Joi.array().items(Joi.string().pattern(internals.nameRx)).single(), + args: Joi.array().items( + Joi.string(), + Joi.object({ + name: Joi.string().pattern(internals.nameRx).required(), + ref: Joi.boolean(), + assert: Joi.alternatives([ + Joi.function(), + Joi.object().schema() + ]) + .conditional('ref', { is: true, then: Joi.required() }), + normalize: Joi.function(), + message: Joi.string().when('assert', { is: Joi.function(), then: Joi.required() }) + }) + ), + convert: Joi.boolean(), + manifest: Joi.boolean(), + method: Joi.function().allow(false), + multi: Joi.boolean(), + validate: Joi.function() +}); - const requireds = schema.$_terms._requireds.slice(); - const ordereds = schema.$_terms.ordered.slice(); - const inclusions = [...schema.$_terms._inclusions, ...requireds]; - const wasArray = !value[Common.symbols.arraySingle]; - delete value[Common.symbols.arraySingle]; +exports.extension = Joi.object({ + type: Joi.alternatives([ + Joi.string(), + Joi.object().regex() + ]) + .required(), + args: Joi.function(), + cast: Joi.object().pattern(internals.nameRx, Joi.object({ + from: Joi.function().maxArity(1).required(), + to: Joi.function().minArity(1).maxArity(2).required() + })), + base: Joi.object().schema() + .when('type', { is: Joi.object().regex(), then: Joi.forbidden() }), + coerce: [ + Joi.function().maxArity(3), + Joi.object({ method: Joi.function().maxArity(3).required(), from: Joi.array().items(Joi.string()).single() }) + ], + flags: Joi.object().pattern(internals.nameRx, Joi.object({ + setter: Joi.string(), + default: Joi.any() + })), + manifest: { + build: Joi.function().arity(2) + }, + messages: [Joi.object(), Joi.string()], + modifiers: Joi.object().pattern(internals.nameRx, Joi.function().minArity(1).maxArity(2)), + overrides: Joi.object().pattern(internals.nameRx, Joi.function()), + prepare: Joi.function().maxArity(3), + rebuild: Joi.function().arity(1), + rules: Joi.object().pattern(internals.nameRx, internals.rule), + terms: Joi.object().pattern(internals.nameRx, Joi.object({ + init: Joi.array().allow(null).required(), + manifest: Joi.object().pattern(/.+/, [ + Joi.valid('schema', 'single'), + Joi.object({ + mapped: Joi.object({ + from: Joi.string().required(), + to: Joi.string().required() + }) + .required() + }) + ]) + })), + validate: Joi.function().maxArity(3) +}) + .strict(); - const errors = errorsArray(); - let il = value.length; - for (let i = 0; i < il; ++i) { - const item = value[i]; +exports.extensions = Joi.array().items(Joi.object(), Joi.function().arity(1)).strict(); - let errored = false; - let isValid = false; - const key = wasArray ? i : new Number(i); // eslint-disable-line no-new-wrappers - const path = [...state.path, key]; +// Manifest - // Sparse +internals.desc = { - if (!schema._flags.sparse && - item === undefined) { + buffer: Joi.object({ + buffer: Joi.string() + }), - errors.push(error('array.sparse', { key, path, pos: i, value: undefined }, state.localize(path))); - if (prefs.abortEarly) { - return errors; - } + func: Joi.object({ + function: Joi.function().required(), + options: { + literal: true + } + }), - ordereds.shift(); - continue; - } + override: Joi.object({ + override: true + }), - // Exclusions + ref: Joi.object({ + ref: Joi.object({ + type: Joi.valid('value', 'global', 'local'), + path: Joi.array().required(), + separator: Joi.string().length(1).allow(false), + ancestor: Joi.number().min(0).integer().allow('root'), + map: Joi.array().items(Joi.array().length(2)).min(1), + adjust: Joi.function(), + iterables: Joi.boolean(), + in: Joi.boolean(), + render: Joi.boolean() + }) + .required() + }), - const ancestors = [value, ...state.ancestors]; + regex: Joi.object({ + regex: Joi.string().min(3) + }), - for (const exclusion of schema.$_terms._exclusions) { - if (!exclusion.$_match(item, state.localize(path, ancestors, exclusion), prefs, { presence: 'ignore' })) { - continue; - } + special: Joi.object({ + special: Joi.valid('deep').required() + }), - errors.push(error('array.excludes', { pos: i, value: item }, state.localize(path))); - if (prefs.abortEarly) { - return errors; - } + template: Joi.object({ + template: Joi.string().required(), + options: Joi.object() + }), - errored = true; - ordereds.shift(); - break; - } + value: Joi.object({ + value: Joi.alternatives([Joi.object(), Joi.array()]).required() + }) +}; - if (errored) { - continue; - } - // Ordered +internals.desc.entity = Joi.alternatives([ + Joi.array().items(Joi.link('...')), + Joi.boolean(), + Joi.function(), + Joi.number(), + Joi.string(), + internals.desc.buffer, + internals.desc.func, + internals.desc.ref, + internals.desc.regex, + internals.desc.special, + internals.desc.template, + internals.desc.value, + Joi.link('/') +]); - if (schema.$_terms.ordered.length) { - if (ordereds.length) { - const ordered = ordereds.shift(); - const res = ordered.$_validate(item, state.localize(path, ancestors, ordered), prefs); - if (!res.errors) { - if (ordered._flags.result === 'strip') { - internals.fastSplice(value, i); - --i; - --il; - } - else if (!schema._flags.sparse && res.value === undefined) { - errors.push(error('array.sparse', { key, path, pos: i, value: undefined }, state.localize(path))); - if (prefs.abortEarly) { - return errors; - } - continue; - } - else { - value[i] = res.value; - } - } - else { - errors.push(...res.errors); - if (prefs.abortEarly) { - return errors; - } - } +internals.desc.values = Joi.array() + .items( + null, + Joi.boolean(), + Joi.function(), + Joi.number().allow(Infinity, -Infinity), + Joi.string().allow(''), + Joi.symbol(), + internals.desc.buffer, + internals.desc.func, + internals.desc.override, + internals.desc.ref, + internals.desc.regex, + internals.desc.template, + internals.desc.value + ); - continue; - } - else if (!schema.$_terms.items.length) { - errors.push(error('array.orderedLength', { pos: i, limit: schema.$_terms.ordered.length })); - if (prefs.abortEarly) { - return errors; - } - break; // No reason to continue since there are no other rules to validate other than array.orderedLength - } - } +internals.desc.messages = Joi.object() + .pattern(/.+/, [ + Joi.string(), + internals.desc.template, + Joi.object().pattern(/.+/, [Joi.string(), internals.desc.template]) + ]); - // Requireds - const requiredChecks = []; - let jl = requireds.length; - for (let j = 0; j < jl; ++j) { - const localState = state.localize(path, ancestors, requireds[j]); - localState.snapshot(); +exports.description = Joi.object({ + type: Joi.string().required(), + flags: Joi.object({ + cast: Joi.string(), + default: Joi.any(), + description: Joi.string(), + empty: Joi.link('/'), + failover: internals.desc.entity, + id: Joi.string(), + label: Joi.string(), + only: true, + presence: ['optional', 'required', 'forbidden'], + result: ['raw', 'strip'], + strip: Joi.boolean(), + unit: Joi.string() + }) + .unknown(), + preferences: { + allowUnknown: Joi.boolean(), + abortEarly: Joi.boolean(), + artifacts: Joi.boolean(), + cache: Joi.boolean(), + convert: Joi.boolean(), + dateFormat: ['date', 'iso', 'string', 'time', 'utc'], + errors: { + escapeHtml: Joi.boolean(), + label: ['path', 'key'], + language: [ + Joi.string(), + internals.desc.ref + ], + wrap: { + label: internals.wrap, + array: internals.wrap + } + }, + externals: Joi.boolean(), + messages: internals.desc.messages, + noDefaults: Joi.boolean(), + nonEnumerables: Joi.boolean(), + presence: ['required', 'optional', 'forbidden'], + skipFunctions: Joi.boolean(), + stripUnknown: Joi.object({ + arrays: Joi.boolean(), + objects: Joi.boolean() + }) + .or('arrays', 'objects') + .allow(true, false), + warnings: Joi.boolean() + }, + allow: internals.desc.values, + invalid: internals.desc.values, + rules: Joi.array().min(1).items({ + name: Joi.string().required(), + args: Joi.object().min(1), + keep: Joi.boolean(), + message: [ + Joi.string(), + internals.desc.messages + ], + warn: Joi.boolean() + }), - const res = requireds[j].$_validate(item, localState, prefs); - requiredChecks[j] = res; + // Terms - if (!res.errors) { - value[i] = res.value; - isValid = true; - internals.fastSplice(requireds, j); - --j; - --jl; + keys: Joi.object().pattern(/.*/, Joi.link('/')), + link: internals.desc.ref +}) + .pattern(/^[a-z]\w*$/, Joi.any()); - if (!schema._flags.sparse && - res.value === undefined) { - errors.push(error('array.sparse', { key, path, pos: i, value: undefined }, state.localize(path))); - if (prefs.abortEarly) { - return errors; - } - } +/***/ }), - break; - } +/***/ 73634: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - localState.restore(); - } +"use strict"; - if (isValid) { - continue; - } - // Inclusions +const Clone = __nccwpck_require__(85578); +const Reach = __nccwpck_require__(18891); - const stripUnknown = prefs.stripUnknown && !!prefs.stripUnknown.arrays || false; +const Common = __nccwpck_require__(72448); - jl = inclusions.length; - for (const inclusion of inclusions) { - // Avoid re-running requireds that already didn't match in the previous loop +const internals = { + value: Symbol('value') +}; - let res; - const previousCheck = requireds.indexOf(inclusion); - if (previousCheck !== -1) { - res = requiredChecks[previousCheck]; - } - else { - const localState = state.localize(path, ancestors, inclusion); - localState.snapshot(); - res = inclusion.$_validate(item, localState, prefs); - if (!res.errors) { - if (inclusion._flags.result === 'strip') { - internals.fastSplice(value, i); - --i; - --il; - } - else if (!schema._flags.sparse && - res.value === undefined) { +module.exports = internals.State = class { - errors.push(error('array.sparse', { key, path, pos: i, value: undefined }, state.localize(path))); - errored = true; - } - else { - value[i] = res.value; - } + constructor(path, ancestors, state) { - isValid = true; - break; - } + this.path = path; + this.ancestors = ancestors; // [parent, ..., root] - localState.restore(); - } + this.mainstay = state.mainstay; + this.schemas = state.schemas; // [current, ..., root] + this.debug = null; + } - // Return the actual error if only one inclusion defined + localize(path, ancestors = null, schema = null) { - if (jl === 1) { - if (stripUnknown) { - internals.fastSplice(value, i); - --i; - --il; - isValid = true; - break; - } + const state = new internals.State(path, ancestors, this); - errors.push(...res.errors); - if (prefs.abortEarly) { - return errors; - } + if (schema && + state.schemas) { - errored = true; - break; - } - } + state.schemas = [internals.schemas(schema), ...state.schemas]; + } - if (errored) { - continue; - } + return state; + } - if ((schema.$_terms._inclusions.length || schema.$_terms._requireds.length) && - !isValid) { + nest(schema, debug) { - if (stripUnknown) { - internals.fastSplice(value, i); - --i; - --il; - continue; - } + const state = new internals.State(this.path, this.ancestors, this); + state.schemas = state.schemas && [internals.schemas(schema), ...state.schemas]; + state.debug = debug; + return state; + } - errors.push(error('array.includes', { pos: i, value: item }, state.localize(path))); - if (prefs.abortEarly) { - return errors; - } - } - } + shadow(value, reason) { - if (requireds.length) { - internals.fillMissedErrors(schema, errors, requireds, value, state, prefs); - } + this.mainstay.shadow = this.mainstay.shadow || new internals.Shadow(); + this.mainstay.shadow.set(this.path, value, reason); + } - if (ordereds.length) { - internals.fillOrderedErrors(schema, errors, ordereds, value, state, prefs); + snapshot() { - if (!errors.length) { - internals.fillDefault(ordereds, value, state, prefs); - } - } + if (this.mainstay.shadow) { + this._snapshot = Clone(this.mainstay.shadow.node(this.path)); + } + } - return errors.length ? errors : value; - }, + restore() { - priority: true, - manifest: false - }, + if (this.mainstay.shadow) { + this.mainstay.shadow.override(this.path, this._snapshot); + this._snapshot = undefined; + } + } +}; - length: { - method(limit) { - return this.$_addRule({ name: 'length', args: { limit }, operator: '=' }); - }, - validate(value, helpers, { limit }, { name, operator, args }) { +internals.schemas = function (schema) { - if (Common.compare(value.length, limit, operator)) { - return value; - } + if (Common.isSchema(schema)) { + return { schema }; + } - return helpers.error('array.' + name, { limit: args.limit, value }); - }, - args: [ - { - name: 'limit', - ref: true, - assert: Common.limit, - message: 'must be a positive integer' - } - ] - }, + return schema; +}; - max: { - method(limit) { - return this.$_addRule({ name: 'max', method: 'length', args: { limit }, operator: '<=' }); - } - }, +internals.Shadow = class { - min: { - method(limit) { + constructor() { - return this.$_addRule({ name: 'min', method: 'length', args: { limit }, operator: '>=' }); - } - }, + this._values = null; + } - ordered: { - method(...schemas) { + set(path, value, reason) { - Common.verifyFlat(schemas, 'ordered'); + if (!path.length) { // No need to store root value + return; + } - const obj = this.$_addRule('items'); + if (reason === 'strip' && + typeof path[path.length - 1] === 'number') { // Cannot store stripped array values (due to shift) - for (let i = 0; i < schemas.length; ++i) { - const type = Common.tryWithPath(() => this.$_compile(schemas[i]), i, { append: true }); - internals.validateSingle(type, obj); + return; + } - obj.$_mutateRegister(type); - obj.$_terms.ordered.push(type); - } + this._values = this._values || new Map(); - return obj.$_mutateRebuild(); + let node = this._values; + for (let i = 0; i < path.length; ++i) { + const segment = path[i]; + let next = node.get(segment); + if (!next) { + next = new Map(); + node.set(segment, next); } - }, - single: { - method(enabled) { + node = next; + } - const value = enabled === undefined ? true : !!enabled; - Assert(!value || !this._flags._arrayItems, 'Cannot specify single rule when array has array items'); + node[internals.value] = value; + } - return this.$_setFlag('single', value); - } - }, + get(path) { - sort: { - method(options = {}) { + const node = this.node(path); + if (node) { + return node[internals.value]; + } + } - Common.assertOptions(options, ['by', 'order']); + node(path) { - const settings = { - order: options.order || 'ascending' - }; + if (!this._values) { + return; + } - if (options.by) { - settings.by = Compile.ref(options.by, { ancestor: 0 }); - Assert(!settings.by.ancestor, 'Cannot sort by ancestor'); - } + return Reach(this._values, path, { iterables: true }); + } - return this.$_addRule({ name: 'sort', args: { options: settings } }); - }, - validate(value, { error, state, prefs, schema }, { options }) { + override(path, node) { - const { value: sorted, errors } = internals.sort(schema, value, options, state, prefs); - if (errors) { - return errors; - } + if (!this._values) { + return; + } - for (let i = 0; i < value.length; ++i) { - if (value[i] !== sorted[i]) { - return error('array.sort', { order: options.order, by: options.by ? options.by.key : 'value' }); - } - } + const parents = path.slice(0, -1); + const own = path[path.length - 1]; + const parent = Reach(this._values, parents, { iterables: true }); - return value; - }, - convert: true - }, + if (node) { + parent.set(own, node); + return; + } - sparse: { - method(enabled) { + if (parent) { + parent.delete(own); + } + } +}; - const value = enabled === undefined ? true : !!enabled; - if (this._flags.sparse === value) { - return this; - } +/***/ }), - const obj = value ? this.clone() : this.$_addRule('items'); - return obj.$_setFlag('sparse', value, { clone: false }); - } - }, +/***/ 51396: +/***/ ((module, exports, __nccwpck_require__) => { - unique: { - method(comparator, options = {}) { +"use strict"; - Assert(!comparator || typeof comparator === 'function' || typeof comparator === 'string', 'comparator must be a function or a string'); - Common.assertOptions(options, ['ignoreUndefined', 'separator']); - const rule = { name: 'unique', args: { options, comparator } }; +const Assert = __nccwpck_require__(32718); +const Clone = __nccwpck_require__(85578); +const EscapeHtml = __nccwpck_require__(24752); +const Formula = __nccwpck_require__(34379); - if (comparator) { - if (typeof comparator === 'string') { - const separator = Common.default(options.separator, '.'); - rule.path = separator ? comparator.split(separator) : [comparator]; - } - else { - rule.comparator = comparator; - } - } +const Common = __nccwpck_require__(72448); +const Errors = __nccwpck_require__(69490); +const Ref = __nccwpck_require__(73838); - return this.$_addRule(rule); - }, - validate(value, { state, error, schema }, { comparator: raw, options }, { comparator, path }) { - const found = { - string: Object.create(null), - number: Object.create(null), - undefined: Object.create(null), - boolean: Object.create(null), - object: new Map(), - function: new Map(), - custom: new Map() - }; +const internals = { + symbol: Symbol('template'), - const compare = comparator || DeepEqual; - const ignoreUndefined = options.ignoreUndefined; + opens: new Array(1000).join('\u0000'), + closes: new Array(1000).join('\u0001'), - for (let i = 0; i < value.length; ++i) { - const item = path ? Reach(value[i], path) : value[i]; - const records = comparator ? found.custom : found[typeof item]; - Assert(records, 'Failed to find unique map container for type', typeof item); + dateFormat: { + date: Date.prototype.toDateString, + iso: Date.prototype.toISOString, + string: Date.prototype.toString, + time: Date.prototype.toTimeString, + utc: Date.prototype.toUTCString + } +}; - if (records instanceof Map) { - const entries = records.entries(); - let current; - while (!(current = entries.next()).done) { - if (compare(current.value[0], item)) { - const localState = state.localize([...state.path, i], [value, ...state.ancestors]); - const context = { - pos: i, - value: value[i], - dupePos: current.value[1], - dupeValue: value[current.value[1]] - }; - if (path) { - context.path = raw; - } +module.exports = exports = internals.Template = class { - return error('array.unique', context, localState); - } - } + constructor(source, options) { - records.set(item, i); - } - else { - if ((!ignoreUndefined || item !== undefined) && - records[item] !== undefined) { + Assert(typeof source === 'string', 'Template source must be a string'); + Assert(!source.includes('\u0000') && !source.includes('\u0001'), 'Template source cannot contain reserved control characters'); - const context = { - pos: i, - value: value[i], - dupePos: records[item], - dupeValue: value[records[item]] - }; + this.source = source; + this.rendered = source; - if (path) { - context.path = raw; - } + this._template = null; + this._settings = Clone(options); - const localState = state.localize([...state.path, i], [value, ...state.ancestors]); - return error('array.unique', context, localState); - } + this._parse(); + } - records[item] = i; - } - } + _parse() { - return value; - }, - args: ['comparator', 'options'], - multi: true + // 'text {raw} {{ref}} \\{{ignore}} {{ignore\\}} {{ignore {{ignore}' + + if (!this.source.includes('{')) { + return; } - }, - cast: { - set: { - from: Array.isArray, - to(value, helpers) { + // Encode escaped \\{{{{{ - return new Set(value); - } - } - }, + const encoded = internals.encode(this.source); - rebuild(schema) { + // Split on first { in each set - schema.$_terms._inclusions = []; - schema.$_terms._exclusions = []; - schema.$_terms._requireds = []; + const parts = internals.split(encoded); - for (const type of schema.$_terms.items) { - internals.validateSingle(type, schema); + // Process parts - if (type._flags.presence === 'required') { - schema.$_terms._requireds.push(type); - } - else if (type._flags.presence === 'forbidden') { - schema.$_terms._exclusions.push(type); - } - else { - schema.$_terms._inclusions.push(type); - } + let refs = false; + const processed = []; + const head = parts.shift(); + if (head) { + processed.push(head); } - for (const type of schema.$_terms.ordered) { - internals.validateSingle(type, schema); - } - }, + for (const part of parts) { + const raw = part[0] !== '{'; + const ender = raw ? '}' : '}}'; + const end = part.indexOf(ender); + if (end === -1 || // Ignore non-matching closing + part[1] === '{') { // Ignore more than two { - manifest: { + processed.push(`{${internals.decode(part)}`); + continue; + } - build(obj, desc) { + let variable = part.slice(raw ? 0 : 1, end); + const wrapped = variable[0] === ':'; + if (wrapped) { + variable = variable.slice(1); + } - if (desc.items) { - obj = obj.items(...desc.items); + const dynamic = this._ref(internals.decode(variable), { raw, wrapped }); + processed.push(dynamic); + if (typeof dynamic !== 'string') { + refs = true; } - if (desc.ordered) { - obj = obj.ordered(...desc.ordered); + const rest = part.slice(end + ender.length); + if (rest) { + processed.push(internals.decode(rest)); } + } - return obj; + if (!refs) { + this.rendered = processed.join(''); + return; } - }, - messages: { - 'array.base': '{{#label}} must be an array', - 'array.excludes': '{{#label}} contains an excluded value', - 'array.hasKnown': '{{#label}} does not contain at least one required match for type {:#patternLabel}', - 'array.hasUnknown': '{{#label}} does not contain at least one required match', - 'array.includes': '{{#label}} does not match any of the allowed types', - 'array.includesRequiredBoth': '{{#label}} does not contain {{#knownMisses}} and {{#unknownMisses}} other required value(s)', - 'array.includesRequiredKnowns': '{{#label}} does not contain {{#knownMisses}}', - 'array.includesRequiredUnknowns': '{{#label}} does not contain {{#unknownMisses}} required value(s)', - 'array.length': '{{#label}} must contain {{#limit}} items', - 'array.max': '{{#label}} must contain less than or equal to {{#limit}} items', - 'array.min': '{{#label}} must contain at least {{#limit}} items', - 'array.orderedLength': '{{#label}} must contain at most {{#limit}} items', - 'array.sort': '{{#label}} must be sorted in {#order} order by {{#by}}', - 'array.sort.mismatching': '{{#label}} cannot be sorted due to mismatching types', - 'array.sort.unsupported': '{{#label}} cannot be sorted due to unsupported type {#type}', - 'array.sparse': '{{#label}} must not be a sparse array item', - 'array.unique': '{{#label}} contains a duplicate value' + this._template = processed; } -}); + static date(date, prefs) { -// Helpers + return internals.dateFormat[prefs.dateFormat].call(date); + } -internals.fillMissedErrors = function (schema, errors, requireds, value, state, prefs) { + describe(options = {}) { - const knownMisses = []; - let unknownMisses = 0; - for (const required of requireds) { - const label = required._flags.label; - if (label) { - knownMisses.push(label); - } - else { - ++unknownMisses; - } - } + if (!this._settings && + options.compact) { - if (knownMisses.length) { - if (unknownMisses) { - errors.push(schema.$_createError('array.includesRequiredBoth', value, { knownMisses, unknownMisses }, state, prefs)); - } - else { - errors.push(schema.$_createError('array.includesRequiredKnowns', value, { knownMisses }, state, prefs)); + return this.source; } - } - else { - errors.push(schema.$_createError('array.includesRequiredUnknowns', value, { unknownMisses }, state, prefs)); - } -}; + const desc = { template: this.source }; + if (this._settings) { + desc.options = this._settings; + } -internals.fillOrderedErrors = function (schema, errors, ordereds, value, state, prefs) { + return desc; + } - const requiredOrdereds = []; + static build(desc) { - for (const ordered of ordereds) { - if (ordered._flags.presence === 'required') { - requiredOrdereds.push(ordered); - } + return new internals.Template(desc.template, desc.options); } - if (requiredOrdereds.length) { - internals.fillMissedErrors(schema, errors, requiredOrdereds, value, state, prefs); + isDynamic() { + + return !!this._template; } -}; + static isTemplate(template) { -internals.fillDefault = function (ordereds, value, state, prefs) { + return template ? !!template[Common.symbols.template] : false; + } - const overrides = []; - let trailingUndefined = true; + refs() { - for (let i = ordereds.length - 1; i >= 0; --i) { - const ordered = ordereds[i]; - const ancestors = [value, ...state.ancestors]; - const override = ordered.$_validate(undefined, state.localize(state.path, ancestors, ordered), prefs).value; + if (!this._template) { + return; + } - if (trailingUndefined) { - if (override === undefined) { - continue; + const refs = []; + for (const part of this._template) { + if (typeof part !== 'string') { + refs.push(...part.refs); } - - trailingUndefined = false; } - overrides.unshift(override); + return refs; } - if (overrides.length) { - value.push(...overrides); - } -}; + resolve(value, state, prefs, local) { + if (this._template && + this._template.length === 1) { -internals.fastSplice = function (arr, i) { + return this._part(this._template[0], /* context -> [*/ value, state, prefs, local, {} /*] */); + } - let pos = i; - while (pos < arr.length) { - arr[pos++] = arr[pos]; + return this.render(value, state, prefs, local); } - --arr.length; -}; - - -internals.validateSingle = function (type, obj) { + _part(part, ...args) { - if (type.type === 'array' || - type._flags._arrayItems) { + if (part.ref) { + return part.ref.resolve(...args); + } - Assert(!obj._flags.single, 'Cannot specify array item with single rule enabled'); - obj.$_setFlag('_arrayItems', true, { clone: false }); + return part.formula.evaluate(args); } -}; - - -internals.sort = function (schema, value, settings, state, prefs) { - const order = settings.order === 'ascending' ? 1 : -1; - const aFirst = -1 * order; - const bFirst = order; - - const sort = (a, b) => { + render(value, state, prefs, local, options = {}) { - let compare = internals.compare(a, b, aFirst, bFirst); - if (compare !== null) { - return compare; + if (!this.isDynamic()) { + return this.rendered; } - if (settings.by) { - a = settings.by.resolve(a, state, prefs); - b = settings.by.resolve(b, state, prefs); + const parts = []; + for (const part of this._template) { + if (typeof part === 'string') { + parts.push(part); + } + else { + const rendered = this._part(part, /* context -> [*/ value, state, prefs, local, options /*] */); + const string = internals.stringify(rendered, value, state, prefs, local, options); + if (string !== undefined) { + const result = part.raw || (options.errors && options.errors.escapeHtml) === false ? string : EscapeHtml(string); + parts.push(internals.wrap(result, part.wrapped && prefs.errors.wrap.label)); + } + } } - compare = internals.compare(a, b, aFirst, bFirst); - if (compare !== null) { - return compare; - } + return parts.join(''); + } - const type = typeof a; - if (type !== typeof b) { - throw schema.$_createError('array.sort.mismatching', value, null, state, prefs); - } + _ref(content, { raw, wrapped }) { - if (type !== 'number' && - type !== 'string') { + const refs = []; + const reference = (variable) => { - throw schema.$_createError('array.sort.unsupported', value, { type }, state, prefs); - } + const ref = Ref.create(variable, this._settings); + refs.push(ref); + return (context) => ref.resolve(...context); + }; - if (type === 'number') { - return (a - b) * order; + try { + var formula = new Formula.Parser(content, { reference, functions: internals.functions, constants: internals.constants }); + } + catch (err) { + err.message = `Invalid template variable "${content}" fails due to: ${err.message}`; + throw err; } - return a < b ? aFirst : bFirst; - }; - - try { - return { value: value.slice().sort(sort) }; - } - catch (err) { - return { errors: err }; - } -}; - - -internals.compare = function (a, b, aFirst, bFirst) { - - if (a === b) { - return 0; - } - - if (a === undefined) { - return 1; // Always last regardless of sort order - } + if (formula.single) { + if (formula.single.type === 'reference') { + const ref = refs[0]; + return { ref, raw, refs, wrapped: wrapped || ref.type === 'local' && ref.key === 'label' }; + } - if (b === undefined) { - return -1; // Always last regardless of sort order - } + return internals.stringify(formula.single.value); + } - if (a === null) { - return bFirst; + return { formula, raw, refs }; } - if (b === null) { - return aFirst; - } + toString() { - return null; + return this.source; + } }; -/***/ }), +internals.Template.prototype[Common.symbols.template] = true; +internals.Template.prototype.isImmutable = true; // Prevents Hoek from deep cloning schema objects -/***/ 34288: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +internals.encode = function (string) { + return string + .replace(/\\(\{+)/g, ($0, $1) => { -const Assert = __nccwpck_require__(32718); + return internals.opens.slice(0, $1.length); + }) + .replace(/\\(\}+)/g, ($0, $1) => { -const Any = __nccwpck_require__(9512); -const Common = __nccwpck_require__(72448); + return internals.closes.slice(0, $1.length); + }); +}; -const internals = {}; +internals.decode = function (string) { + return string + .replace(/\u0000/g, '{') + .replace(/\u0001/g, '}'); +}; -module.exports = Any.extend({ - type: 'binary', +internals.split = function (string) { - coerce: { - from: 'string', - method(value, { schema }) { + const parts = []; + let current = ''; - try { - return { value: Buffer.from(value, schema._flags.encoding) }; + for (let i = 0; i < string.length; ++i) { + const char = string[i]; + + if (char === '{') { + let next = ''; + while (i + 1 < string.length && + string[i + 1] === '{') { + + next += '{'; + ++i; } - catch (ignoreErr) { } + + parts.push(current); + current = next; } - }, + else { + current += char; + } + } - validate(value, { error }) { + parts.push(current); + return parts; +}; - if (!Buffer.isBuffer(value)) { - return { value, errors: error('binary.base') }; - } - }, - rules: { - encoding: { - method(encoding) { +internals.wrap = function (value, ends) { - Assert(Buffer.isEncoding(encoding), 'Invalid encoding:', encoding); + if (!ends) { + return value; + } - return this.$_setFlag('encoding', encoding); - } - }, + if (ends.length === 1) { + return `${ends}${value}${ends}`; + } - length: { - method(limit) { + return `${ends[0]}${value}${ends[1]}`; +}; - return this.$_addRule({ name: 'length', method: 'length', args: { limit }, operator: '=' }); - }, - validate(value, helpers, { limit }, { name, operator, args }) { - if (Common.compare(value.length, limit, operator)) { - return value; - } +internals.stringify = function (value, original, state, prefs, local, options = {}) { - return helpers.error('binary.' + name, { limit: args.limit, value }); - }, - args: [ - { - name: 'limit', - ref: true, - assert: Common.limit, - message: 'must be a positive integer' - } - ] - }, + const type = typeof value; + const wrap = prefs && prefs.errors && prefs.errors.wrap || {}; - max: { - method(limit) { + let skipWrap = false; + if (Ref.isRef(value) && + value.render) { - return this.$_addRule({ name: 'max', method: 'length', args: { limit }, operator: '<=' }); - } - }, + skipWrap = value.in; + value = value.resolve(original, state, prefs, local, { in: value.in, ...options }); + } - min: { - method(limit) { + if (value === null) { + return 'null'; + } - return this.$_addRule({ name: 'min', method: 'length', args: { limit }, operator: '>=' }); - } - } - }, + if (type === 'string') { + return internals.wrap(value, options.arrayItems && wrap.string); + } - cast: { - string: { - from: (value) => Buffer.isBuffer(value), - to(value, helpers) { + if (type === 'number' || + type === 'function' || + type === 'symbol') { - return value.toString(); - } - } - }, + return value.toString(); + } - messages: { - 'binary.base': '{{#label}} must be a buffer or a string', - 'binary.length': '{{#label}} must be {{#limit}} bytes', - 'binary.max': '{{#label}} must be less than or equal to {{#limit}} bytes', - 'binary.min': '{{#label}} must be at least {{#limit}} bytes' + if (type !== 'object') { + return JSON.stringify(value); } -}); + if (value instanceof Date) { + return internals.Template.date(value, prefs); + } -/***/ }), + if (value instanceof Map) { + const pairs = []; + for (const [key, sym] of value.entries()) { + pairs.push(`${key.toString()} -> ${sym.toString()}`); + } -/***/ 47489: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + value = pairs; + } -"use strict"; + if (!Array.isArray(value)) { + return value.toString(); + } + const values = []; + for (const item of value) { + values.push(internals.stringify(item, original, state, prefs, local, { arrayItems: true, ...options })); + } -const Assert = __nccwpck_require__(32718); + return internals.wrap(values.join(', '), !skipWrap && wrap.array); +}; -const Any = __nccwpck_require__(9512); -const Common = __nccwpck_require__(72448); -const Values = __nccwpck_require__(71944); +internals.constants = { -const internals = {}; + true: true, + false: false, + null: null, + second: 1000, + minute: 60 * 1000, + hour: 60 * 60 * 1000, + day: 24 * 60 * 60 * 1000 +}; -internals.isBool = function (value) { - return typeof value === 'boolean'; -}; +internals.functions = { + if(condition, then, otherwise) { -module.exports = Any.extend({ + return condition ? then : otherwise; + }, - type: 'boolean', + length(item) { - flags: { + if (typeof item === 'string') { + return item.length; + } - sensitive: { default: false } + if (!item || typeof item !== 'object') { + return null; + } + + if (Array.isArray(item)) { + return item.length; + } + + return Object.keys(item).length; }, - terms: { + msg(code) { - falsy: { - init: null, - manifest: 'values' - }, + const [value, state, prefs, local, options] = this; + const messages = options.messages; + if (!messages) { + return ''; + } - truthy: { - init: null, - manifest: 'values' + const template = Errors.template(value, messages[0], code, state, prefs) || Errors.template(value, messages[1], code, state, prefs); + if (!template) { + return ''; } + + return template.render(value, state, prefs, local, options); }, - coerce(value, { schema }) { + number(value) { - if (typeof value === 'boolean') { - return; + if (typeof value === 'number') { + return value; } if (typeof value === 'string') { - const normalized = schema._flags.sensitive ? value : value.toLowerCase(); - value = normalized === 'true' ? true : (normalized === 'false' ? false : value); + return parseFloat(value); } - if (typeof value !== 'boolean') { - value = schema.$_terms.truthy && schema.$_terms.truthy.has(value, null, null, !schema._flags.sensitive) || - (schema.$_terms.falsy && schema.$_terms.falsy.has(value, null, null, !schema._flags.sensitive) ? false : value); + if (typeof value === 'boolean') { + return value ? 1 : 0; } - return { value }; - }, + if (value instanceof Date) { + return value.getTime(); + } - validate(value, { error }) { + return null; + } +}; - if (typeof value !== 'boolean') { - return { value, errors: error('boolean.base') }; - } - }, - rules: { - truthy: { - method(...values) { +/***/ }), - Common.verifyFlat(values, 'truthy'); +/***/ 43171: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - const obj = this.clone(); - obj.$_terms.truthy = obj.$_terms.truthy || new Values(); +"use strict"; - for (let i = 0; i < values.length; ++i) { - const value = values[i]; - Assert(value !== undefined, 'Cannot call truthy with undefined'); - obj.$_terms.truthy.add(value); - } +const DeepEqual = __nccwpck_require__(55801); +const Pinpoint = __nccwpck_require__(75604); - return obj; - } - }, +const Errors = __nccwpck_require__(69490); - falsy: { - method(...values) { - Common.verifyFlat(values, 'falsy'); +const internals = { + codes: { + error: 1, + pass: 2, + full: 3 + }, + labels: { + 0: 'never used', + 1: 'always error', + 2: 'always pass' + } +}; - const obj = this.clone(); - obj.$_terms.falsy = obj.$_terms.falsy || new Values(); - for (let i = 0; i < values.length; ++i) { - const value = values[i]; +exports.setup = function (root) { - Assert(value !== undefined, 'Cannot call falsy with undefined'); - obj.$_terms.falsy.add(value); - } + const trace = function () { - return obj; - } - }, + root._tracer = root._tracer || new internals.Tracer(); + return root._tracer; + }; - sensitive: { - method(enabled = true) { + root.trace = trace; + root[Symbol.for('@hapi/lab/coverage/initialize')] = trace; - return this.$_setFlag('sensitive', enabled); - } - } - }, + root.untrace = () => { - cast: { - number: { - from: internals.isBool, - to(value, helpers) { + root._tracer = null; + }; +}; - return value ? 1 : 0; - } - }, - string: { - from: internals.isBool, - to(value, helpers) { - return value ? 'true' : 'false'; - } - } - }, +exports.location = function (schema) { - manifest: { + return schema.$_setFlag('_tracerLocation', Pinpoint.location(2)); // base.tracer(), caller +}; - build(obj, desc) { - if (desc.truthy) { - obj = obj.truthy(...desc.truthy); - } +internals.Tracer = class { - if (desc.falsy) { - obj = obj.falsy(...desc.falsy); - } + constructor() { - return obj; + this.name = 'Joi'; + this._schemas = new Map(); + } + + _register(schema) { + + const existing = this._schemas.get(schema); + if (existing) { + return existing.store; } - }, - messages: { - 'boolean.base': '{{#label}} must be a boolean' + const store = new internals.Store(schema); + const { filename, line } = schema._flags._tracerLocation || Pinpoint.location(5); // internals.tracer(), internals.entry(), exports.entry(), validate(), caller + this._schemas.set(schema, { filename, line, store }); + return store; } -}); + _combine(merged, sources) { -/***/ }), + for (const { store } of this._schemas.values()) { + store._combine(merged, sources); + } + } -/***/ 6624: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + report(file) { -"use strict"; + const coverage = []; + // Process each registered schema -const Assert = __nccwpck_require__(32718); + for (const { filename, line, store } of this._schemas.values()) { + if (file && + file !== filename) { -const Any = __nccwpck_require__(9512); -const Common = __nccwpck_require__(72448); -const Template = __nccwpck_require__(51396); + continue; + } + // Process sub schemas of the registered root -const internals = {}; + const missing = []; + const skipped = []; + for (const [schema, log] of store._sources.entries()) { -internals.isDate = function (value) { + // Check if sub schema parent skipped - return value instanceof Date; -}; + if (internals.sub(log.paths, skipped)) { + continue; + } + // Check if sub schema reached -module.exports = Any.extend({ + if (!log.entry) { + missing.push({ + status: 'never reached', + paths: [...log.paths] + }); - type: 'date', + skipped.push(...log.paths); + continue; + } - coerce: { - from: ['number', 'string'], - method(value, { schema }) { + // Check values - return { value: internals.parse(value, schema._flags.format) || value }; - } - }, + for (const type of ['valid', 'invalid']) { + const set = schema[`_${type}s`]; + if (!set) { + continue; + } - validate(value, { schema, error, prefs }) { + const values = new Set(set._values); + const refs = new Set(set._refs); + for (const { value, ref } of log[type]) { + values.delete(value); + refs.delete(ref); + } - if (value instanceof Date && - !isNaN(value.getTime())) { + if (values.size || + refs.size) { - return; - } + missing.push({ + status: [...values, ...[...refs].map((ref) => ref.display)], + rule: `${type}s` + }); + } + } - const format = schema._flags.format; + // Check rules status - if (!prefs.convert || - !format || - typeof value !== 'string') { + const rules = schema._rules.map((rule) => rule.name); + for (const type of ['default', 'failover']) { + if (schema._flags[type] !== undefined) { + rules.push(type); + } + } - return { value, errors: error('date.base') }; + for (const name of rules) { + const status = internals.labels[log.rule[name] || 0]; + if (status) { + const report = { rule: name, status }; + if (log.paths.size) { + report.paths = [...log.paths]; + } + + missing.push(report); + } + } + } + + if (missing.length) { + coverage.push({ + filename, + line, + missing, + severity: 'error', + message: `Schema missing tests for ${missing.map(internals.message).join(', ')}` + }); + } } - return { value, errors: error('date.format', { format }) }; - }, + return coverage.length ? coverage : null; + } +}; - rules: { - compare: { - method: false, - validate(value, helpers, { date }, { name, operator, args }) { +internals.Store = class { - const to = date === 'now' ? Date.now() : date.getTime(); - if (Common.compare(value.getTime(), to, operator)) { - return value; - } + constructor(schema) { - return helpers.error('date.' + name, { limit: args.date, value }); - }, - args: [ - { - name: 'date', - ref: true, - normalize: (date) => { + this.active = true; + this._sources = new Map(); // schema -> { paths, entry, rule, valid, invalid } + this._combos = new Map(); // merged -> [sources] + this._scan(schema); + } - return date === 'now' ? date : internals.parse(date); - }, - assert: (date) => date !== null, - message: 'must have a valid date format' - } - ] - }, + debug(state, source, name, result) { + + state.mainstay.debug && state.mainstay.debug.push({ type: source, name, result, path: state.path }); + } + + entry(schema, state) { + + internals.debug(state, { type: 'entry' }); + + this._record(schema, (log) => { - format: { - method(format) { + log.entry = true; + }); + } - Assert(['iso', 'javascript', 'unix'].includes(format), 'Unknown date format', format); + filter(schema, state, source, value) { - return this.$_setFlag('format', format); - } - }, + internals.debug(state, { type: source, ...value }); - greater: { - method(date) { + this._record(schema, (log) => { - return this.$_addRule({ name: 'greater', method: 'compare', args: { date }, operator: '>' }); - } - }, + log[source].add(value); + }); + } - iso: { - method() { + log(schema, state, source, name, result) { - return this.format('iso'); - } - }, + internals.debug(state, { type: source, name, result: result === 'full' ? 'pass' : result }); - less: { - method(date) { + this._record(schema, (log) => { - return this.$_addRule({ name: 'less', method: 'compare', args: { date }, operator: '<' }); - } - }, + log[source][name] = log[source][name] || 0; + log[source][name] |= internals.codes[result]; + }); + } - max: { - method(date) { + resolve(state, ref, to) { - return this.$_addRule({ name: 'max', method: 'compare', args: { date }, operator: '<=' }); - } - }, + if (!state.mainstay.debug) { + return; + } - min: { - method(date) { + const log = { type: 'resolve', ref: ref.display, to, path: state.path }; + state.mainstay.debug.push(log); + } - return this.$_addRule({ name: 'min', method: 'compare', args: { date }, operator: '>=' }); - } - }, + value(state, by, from, to, name) { - timestamp: { - method(type = 'javascript') { + if (!state.mainstay.debug || + DeepEqual(from, to)) { - Assert(['javascript', 'unix'].includes(type), '"type" must be one of "javascript, unix"'); + return; + } - return this.format(type); - } + const log = { type: 'value', by, from, to, path: state.path }; + if (name) { + log.name = name; } - }, - cast: { - number: { - from: internals.isDate, - to(value, helpers) { + state.mainstay.debug.push(log); + } - return value.getTime(); - } - }, - string: { - from: internals.isDate, - to(value, { prefs }) { + _record(schema, each) { - return Template.date(value, prefs); - } + const log = this._sources.get(schema); + if (log) { + each(log); + return; } - }, - messages: { - 'date.base': '{{#label}} must be a valid date', - 'date.format': '{{#label}} must be in {msg("date.format." + #format) || #format} format', - 'date.greater': '{{#label}} must be greater than {{:#limit}}', - 'date.less': '{{#label}} must be less than {{:#limit}}', - 'date.max': '{{#label}} must be less than or equal to {{:#limit}}', - 'date.min': '{{#label}} must be greater than or equal to {{:#limit}}', + const sources = this._combos.get(schema); + for (const source of sources) { + this._record(source, each); + } + } - // Messages used in date.format + _scan(schema, _path) { - 'date.format.iso': 'ISO 8601 date', - 'date.format.javascript': 'timestamp or number of milliseconds', - 'date.format.unix': 'timestamp or number of seconds' - } -}); + const path = _path || []; + let log = this._sources.get(schema); + if (!log) { + log = { + paths: new Set(), + entry: false, + rule: {}, + valid: new Set(), + invalid: new Set() + }; -// Helpers + this._sources.set(schema, log); + } -internals.parse = function (value, format) { + if (path.length) { + log.paths.add(path); + } - if (value instanceof Date) { - return value; - } + const each = (sub, source) => { - if (typeof value !== 'string' && - (isNaN(value) || !isFinite(value))) { + const subId = internals.id(sub, source); + this._scan(sub, path.concat(subId)); + }; - return null; + schema.$_modify({ each, ref: false }); } - if (/^\s*$/.test(value)) { - return null; + _combine(merged, sources) { + + this._combos.set(merged, sources); } +}; - // ISO - if (format === 'iso') { - if (!Common.isIsoDate(value)) { - return null; - } +internals.message = function (item) { - return internals.date(value.toString()); + const path = item.paths ? Errors.path(item.paths[0]) + (item.rule ? ':' : '') : ''; + return `${path}${item.rule || ''} (${item.status})`; +}; + + +internals.id = function (schema, { source, name, path, key }) { + + if (schema._flags.id) { + return schema._flags.id; } - // Normalize number string + if (key) { + return key; + } - const original = value; - if (typeof value === 'string' && - /^[+-]?\d+(\.\d+)?$/.test(value)) { + name = `@${name}`; - value = parseFloat(value); + if (source === 'terms') { + return [name, path[Math.min(path.length - 1, 1)]]; } - // Timestamp + return name; +}; - if (format) { - if (format === 'javascript') { - return internals.date(1 * value); // Casting to number - } - if (format === 'unix') { - return internals.date(1000 * value); - } +internals.sub = function (paths, skipped) { - if (typeof original === 'string') { - return null; + for (const path of paths) { + for (const skip of skipped) { + if (DeepEqual(path.slice(0, skip.length), skip)) { + return true; + } } } - // Plain - - return internals.date(value); + return false; }; -internals.date = function (value) { +internals.debug = function (state, event) { - const date = new Date(value); - if (!isNaN(date.getTime())) { - return date; + if (state.mainstay.debug) { + event.path = state.debug ? [...state.path, state.debug] : state.path; + state.mainstay.debug.push(event); } - - return null; }; /***/ }), -/***/ 62269: +/***/ 26867: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const Assert = __nccwpck_require__(32718); +const Merge = __nccwpck_require__(60445); -const Keys = __nccwpck_require__(79130); +const Any = __nccwpck_require__(9512); +const Common = __nccwpck_require__(72448); +const Compile = __nccwpck_require__(3038); +const Errors = __nccwpck_require__(69490); +const Ref = __nccwpck_require__(73838); const internals = {}; -module.exports = Keys.extend({ +module.exports = Any.extend({ - type: 'function', + type: 'alternatives', - properties: { - typeof: 'function' - }, + flags: { - rules: { - arity: { - method(n) { + match: { default: 'any' } // 'any', 'one', 'all' + }, - Assert(Number.isSafeInteger(n) && n >= 0, 'n must be a positive integer'); + terms: { - return this.$_addRule({ name: 'arity', args: { n } }); - }, - validate(value, helpers, { n }) { + matches: { init: [], register: Ref.toSibling } + }, - if (value.length === n) { - return value; - } + args(schema, ...schemas) { - return helpers.error('function.arity', { n }); + if (schemas.length === 1) { + if (Array.isArray(schemas[0])) { + return schema.try(...schemas[0]); } - }, - - class: { - method() { + } - return this.$_addRule('class'); - }, - validate(value, helpers) { + return schema.try(...schemas); + }, - if ((/^\s*class\s/).test(value.toString())) { - return value; - } + validate(value, helpers) { - return helpers.error('function.class', { value }); - } - }, + const { schema, error, state, prefs } = helpers; - minArity: { - method(n) { + // Match all or one - Assert(Number.isSafeInteger(n) && n > 0, 'n must be a strict positive integer'); + if (schema._flags.match) { + const matched = []; + const failed = []; - return this.$_addRule({ name: 'minArity', args: { n } }); - }, - validate(value, helpers, { n }) { + for (let i = 0; i < schema.$_terms.matches.length; ++i) { + const item = schema.$_terms.matches[i]; + const localState = state.nest(item.schema, `match.${i}`); + localState.snapshot(); - if (value.length >= n) { - return value; + const result = item.schema.$_validate(value, localState, prefs); + if (!result.errors) { + matched.push(result.value); + } + else { + failed.push(result.errors); + localState.restore(); } + } - return helpers.error('function.minArity', { n }); + if (matched.length === 0) { + const context = { + details: failed.map((f) => Errors.details(f, { override: false })) + }; + + return { errors: error('alternatives.any', context) }; } - }, - maxArity: { - method(n) { + // Match one - Assert(Number.isSafeInteger(n) && n >= 0, 'n must be a positive integer'); + if (schema._flags.match === 'one') { + return matched.length === 1 ? { value: matched[0] } : { errors: error('alternatives.one') }; + } - return this.$_addRule({ name: 'maxArity', args: { n } }); - }, - validate(value, helpers, { n }) { + // Match all - if (value.length <= n) { - return value; - } + if (matched.length !== schema.$_terms.matches.length) { + const context = { + details: failed.map((f) => Errors.details(f, { override: false })) + }; - return helpers.error('function.maxArity', { n }); + return { errors: error('alternatives.all', context) }; } - } - }, - messages: { - 'function.arity': '{{#label}} must have an arity of {{#n}}', - 'function.class': '{{#label}} must be a class', - 'function.maxArity': '{{#label}} must have an arity lesser or equal to {{#n}}', - 'function.minArity': '{{#label}} must have an arity greater or equal to {{#n}}' - } -}); + const isAnyObj = (alternative) => { + return alternative.$_terms.matches.some((v) => { -/***/ }), + return v.schema.type === 'object' || + (v.schema.type === 'alternatives' && isAnyObj(v.schema)); + }); + }; -/***/ 79130: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return isAnyObj(schema) ? { value: matched.reduce((acc, v) => Merge(acc, v, { mergeArrays: false })) } : { value: matched[matched.length - 1] }; + } -"use strict"; + // Match any + const errors = []; + for (let i = 0; i < schema.$_terms.matches.length; ++i) { + const item = schema.$_terms.matches[i]; -const ApplyToDefaults = __nccwpck_require__(85545); -const Assert = __nccwpck_require__(32718); -const Clone = __nccwpck_require__(85578); -const Topo = __nccwpck_require__(88392); + // Try -const Any = __nccwpck_require__(9512); -const Common = __nccwpck_require__(72448); -const Compile = __nccwpck_require__(3038); -const Errors = __nccwpck_require__(69490); -const Ref = __nccwpck_require__(73838); -const Template = __nccwpck_require__(51396); + if (item.schema) { + const localState = state.nest(item.schema, `match.${i}`); + localState.snapshot(); + const result = item.schema.$_validate(value, localState, prefs); + if (!result.errors) { + return result; + } -const internals = { - renameDefaults: { - alias: false, // Keep old value in place - multiple: false, // Allow renaming multiple keys into the same target - override: false // Overrides an existing key - } -}; + localState.restore(); + errors.push({ schema: item.schema, reports: result.errors }); + continue; + } + // Conditional -module.exports = Any.extend({ + const input = item.ref ? item.ref.resolve(value, state, prefs) : value; + const tests = item.is ? [item] : item.switch; - type: '_keys', + for (let j = 0; j < tests.length; ++j) { + const test = tests[j]; + const { is, then, otherwise } = test; - properties: { + const id = `match.${i}${item.switch ? '.' + j : ''}`; + if (!is.$_match(input, state.nest(is, `${id}.is`), prefs)) { + if (otherwise) { + return otherwise.$_validate(value, state.nest(otherwise, `${id}.otherwise`), prefs); + } + } + else if (then) { + return then.$_validate(value, state.nest(then, `${id}.then`), prefs); + } + } + } - typeof: 'object' + return internals.errors(errors, helpers); }, - flags: { - - unknown: { default: false } - }, + rules: { - terms: { + conditional: { + method(condition, options) { - dependencies: { init: null }, - keys: { init: null, manifest: { mapped: { from: 'schema', to: 'key' } } }, - patterns: { init: null }, - renames: { init: null } - }, + Assert(!this._flags._endedSwitch, 'Unreachable condition'); + Assert(!this._flags.match, 'Cannot combine match mode', this._flags.match, 'with conditional rule'); + Assert(options.break === undefined, 'Cannot use break option with alternatives conditional'); - args(schema, keys) { + const obj = this.clone(); - return schema.keys(keys); - }, + const match = Compile.when(obj, condition, options); + const conditions = match.is ? [match] : match.switch; + for (const item of conditions) { + if (item.then && + item.otherwise) { - validate(value, { schema, error, state, prefs }) { + obj.$_setFlag('_endedSwitch', true, { clone: false }); + break; + } + } - if (!value || - typeof value !== schema.$_property('typeof') || - Array.isArray(value)) { + obj.$_terms.matches.push(match); + return obj.$_mutateRebuild(); + } + }, - return { value, errors: error('object.base', { type: schema.$_property('typeof') }) }; - } + match: { + method(mode) { - // Skip if there are no other rules to test + Assert(['any', 'one', 'all'].includes(mode), 'Invalid alternatives match mode', mode); - if (!schema.$_terms.renames && - !schema.$_terms.dependencies && - !schema.$_terms.keys && // null allows any keys - !schema.$_terms.patterns && - !schema.$_terms.externals) { + if (mode !== 'any') { + for (const match of this.$_terms.matches) { + Assert(match.schema, 'Cannot combine match mode', mode, 'with conditional rules'); + } + } - return; - } + return this.$_setFlag('match', mode); + } + }, - // Shallow clone value + try: { + method(...schemas) { - value = internals.clone(value, prefs); - const errors = []; + Assert(schemas.length, 'Missing alternative schemas'); + Common.verifyFlat(schemas, 'try'); - // Rename keys + Assert(!this._flags._endedSwitch, 'Unreachable condition'); - if (schema.$_terms.renames && - !internals.rename(schema, value, state, prefs, errors)) { + const obj = this.clone(); + for (const schema of schemas) { + obj.$_terms.matches.push({ schema: obj.$_compile(schema) }); + } - return { value, errors }; + return obj.$_mutateRebuild(); + } } + }, - // Anything allowed + overrides: { - if (!schema.$_terms.keys && // null allows any keys - !schema.$_terms.patterns && - !schema.$_terms.dependencies) { + label(name) { - return { value, errors }; + const obj = this.$_parent('label', name); + const each = (item, source) => (source.path[0] !== 'is' ? item.label(name) : undefined); + return obj.$_modify({ each, ref: false }); } + }, - // Defined keys - - const unprocessed = new Set(Object.keys(value)); + rebuild(schema) { - if (schema.$_terms.keys) { - const ancestors = [value, ...state.ancestors]; + // Flag when an alternative type is an array - for (const child of schema.$_terms.keys) { - const key = child.key; - const item = value[key]; + const each = (item) => { - unprocessed.delete(key); + if (Common.isSchema(item) && + item.type === 'array') { - const localState = state.localize([...state.path, key], ancestors, child); - const result = child.schema.$_validate(item, localState, prefs); + schema.$_setFlag('_arrayItems', true, { clone: false }); + } + }; - if (result.errors) { - if (prefs.abortEarly) { - return { value, errors: result.errors }; - } + schema.$_modify({ each }); + }, - if (result.value !== undefined) { - value[key] = result.value; - } + manifest: { - errors.push(...result.errors); - } - else if (child.schema._flags.result === 'strip' || - result.value === undefined && item !== undefined) { + build(obj, desc) { - delete value[key]; - } - else if (result.value !== undefined) { - value[key] = result.value; + if (desc.matches) { + for (const match of desc.matches) { + const { schema, ref, is, not, then, otherwise } = match; + if (schema) { + obj = obj.try(schema); + } + else if (ref) { + obj = obj.conditional(ref, { is, then, not, otherwise, switch: match.switch }); + } + else { + obj = obj.conditional(is, { then, otherwise }); + } } } + + return obj; } + }, - // Unknown keys + messages: { + 'alternatives.all': '{{#label}} does not match all of the required types', + 'alternatives.any': '{{#label}} does not match any of the allowed types', + 'alternatives.match': '{{#label}} does not match any of the allowed types', + 'alternatives.one': '{{#label}} matches more than one allowed type', + 'alternatives.types': '{{#label}} must be one of {{#types}}' + } +}); - if (unprocessed.size || - schema._flags._hasPatternMatch) { - const early = internals.unknown(schema, value, unprocessed, errors, state, prefs); - if (early) { - return early; - } - } +// Helpers - // Validate dependencies +internals.errors = function (failures, { error, state }) { - if (schema.$_terms.dependencies) { - for (const dep of schema.$_terms.dependencies) { - if (dep.key && - dep.key.resolve(value, state, prefs, null, { shadow: false }) === undefined) { + // Nothing matched due to type criteria rules - continue; - } + if (!failures.length) { + return { errors: error('alternatives.any') }; + } - const failed = internals.dependencies[dep.rel](schema, dep, value, state, prefs); - if (failed) { - const report = schema.$_createError(failed.code, value, failed.context, state, prefs); - if (prefs.abortEarly) { - return { value, errors: report }; - } + // Single error - errors.push(report); - } - } - } + if (failures.length === 1) { + return { errors: failures[0].reports }; + } - return { value, errors }; - }, + // Analyze reasons - rules: { + const valids = new Set(); + const complex = []; - and: { - method(...peers /*, [options] */) { + for (const { reports, schema } of failures) { - Common.verifyFlat(peers, 'and'); + // Multiple errors (!abortEarly) - return internals.dependency(this, 'and', null, peers); - } - }, + if (reports.length > 1) { + return internals.unmatched(failures, error); + } - append: { - method(schema) { + // Custom error - if (schema === null || - schema === undefined || - Object.keys(schema).length === 0) { + const report = reports[0]; + if (report instanceof Errors.Report === false) { + return internals.unmatched(failures, error); + } - return this; - } + // Internal object or array error - return this.keys(schema); - } - }, + if (report.state.path.length !== state.path.length) { + complex.push({ type: schema.type, report }); + continue; + } - assert: { - method(subject, schema, message) { + // Valids - if (!Template.isTemplate(subject)) { - subject = Compile.ref(subject); - } + if (report.code === 'any.only') { + for (const valid of report.local.valids) { + valids.add(valid); + } - Assert(message === undefined || typeof message === 'string', 'Message must be a string'); + continue; + } - schema = this.$_compile(schema, { appendPath: true }); + // Base type - const obj = this.$_addRule({ name: 'assert', args: { subject, schema, message } }); - obj.$_mutateRegister(subject); - obj.$_mutateRegister(schema); - return obj; - }, - validate(value, { error, prefs, state }, { subject, schema, message }) { + const [type, code] = report.code.split('.'); + if (code !== 'base') { + complex.push({ type: schema.type, report }); + continue; + } - const about = subject.resolve(value, state, prefs); - const path = Ref.isRef(subject) ? subject.absolute(state) : []; - if (schema.$_match(about, state.localize(path, [value, ...state.ancestors], schema), prefs)) { - return value; - } + valids.add(type); + } - return error('object.assert', { subject, message }); - }, - args: ['subject', 'schema', 'message'], - multi: true - }, + // All errors are base types or valids - instance: { - method(constructor, name) { + if (!complex.length) { + return { errors: error('alternatives.types', { types: [...valids] }) }; + } - Assert(typeof constructor === 'function', 'constructor must be a function'); + // Single complex error - name = name || constructor.name; + if (complex.length === 1) { + return { errors: complex[0].report }; + } - return this.$_addRule({ name: 'instance', args: { constructor, name } }); - }, - validate(value, helpers, { constructor, name }) { + return internals.unmatched(failures, error); +}; - if (value instanceof constructor) { - return value; - } - return helpers.error('object.instance', { type: name, value }); - }, - args: ['constructor', 'name'] - }, +internals.unmatched = function (failures, error) { - keys: { - method(schema) { + const errors = []; + for (const failure of failures) { + errors.push(...failure.reports); + } - Assert(schema === undefined || typeof schema === 'object', 'Object schema must be a valid object'); - Assert(!Common.isSchema(schema), 'Object schema cannot be a joi schema'); + return { errors: error('alternatives.match', Errors.details(errors, { override: false })) }; +}; - const obj = this.clone(); - if (!schema) { // Allow all - obj.$_terms.keys = null; - } - else if (!Object.keys(schema).length) { // Allow none - obj.$_terms.keys = new internals.Keys(); - } - else { - obj.$_terms.keys = obj.$_terms.keys ? obj.$_terms.keys.filter((child) => !schema.hasOwnProperty(child.key)) : new internals.Keys(); - for (const key in schema) { - Common.tryWithPath(() => obj.$_terms.keys.push({ key, schema: this.$_compile(schema[key]) }), key); - } - } +/***/ }), - return obj.$_mutateRebuild(); - } - }, +/***/ 9512: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - length: { - method(limit) { +"use strict"; - return this.$_addRule({ name: 'length', args: { limit }, operator: '=' }); - }, - validate(value, helpers, { limit }, { name, operator, args }) { - if (Common.compare(Object.keys(value).length, limit, operator)) { - return value; - } +const Assert = __nccwpck_require__(32718); - return helpers.error('object.' + name, { limit: args.limit, value }); - }, - args: [ - { - name: 'limit', - ref: true, - assert: Common.limit, - message: 'must be a positive integer' - } - ] - }, +const Base = __nccwpck_require__(95184); +const Common = __nccwpck_require__(72448); +const Messages = __nccwpck_require__(86103); - max: { - method(limit) { - return this.$_addRule({ name: 'max', method: 'length', args: { limit }, operator: '<=' }); - } - }, +const internals = {}; - min: { - method(limit) { - return this.$_addRule({ name: 'min', method: 'length', args: { limit }, operator: '>=' }); - } - }, +module.exports = Base.extend({ - nand: { - method(...peers /*, [options] */) { + type: 'any', - Common.verifyFlat(peers, 'nand'); + flags: { - return internals.dependency(this, 'nand', null, peers); - } - }, + only: { default: false } + }, - or: { - method(...peers /*, [options] */) { + terms: { - Common.verifyFlat(peers, 'or'); + alterations: { init: null }, + examples: { init: null }, + externals: { init: null }, + metas: { init: [] }, + notes: { init: [] }, + shared: { init: null }, + tags: { init: [] }, + whens: { init: null } + }, - return internals.dependency(this, 'or', null, peers); - } - }, + rules: { - oxor: { - method(...peers /*, [options] */) { + custom: { + method(method, description) { - return internals.dependency(this, 'oxor', null, peers); - } - }, + Assert(typeof method === 'function', 'Method must be a function'); + Assert(description === undefined || description && typeof description === 'string', 'Description must be a non-empty string'); - pattern: { - method(pattern, schema, options = {}) { + return this.$_addRule({ name: 'custom', args: { method, description } }); + }, + validate(value, helpers, { method }) { - const isRegExp = pattern instanceof RegExp; - if (!isRegExp) { - pattern = this.$_compile(pattern, { appendPath: true }); + try { + return method(value, helpers); } - - Assert(schema !== undefined, 'Invalid rule'); - Common.assertOptions(options, ['fallthrough', 'matches']); - - if (isRegExp) { - Assert(!pattern.flags.includes('g') && !pattern.flags.includes('y'), 'pattern should not use global or sticky mode'); + catch (err) { + return helpers.error('any.custom', { error: err }); } + }, + args: ['method', 'description'], + multi: true + }, - schema = this.$_compile(schema, { appendPath: true }); + messages: { + method(messages) { - const obj = this.clone(); - obj.$_terms.patterns = obj.$_terms.patterns || []; - const config = { [isRegExp ? 'regex' : 'schema']: pattern, rule: schema }; - if (options.matches) { - config.matches = this.$_compile(options.matches); - if (config.matches.type !== 'array') { - config.matches = config.matches.$_root.array().items(config.matches); - } + return this.prefs({ messages }); + } + }, - obj.$_mutateRegister(config.matches); - obj.$_setFlag('_hasPatternMatch', true, { clone: false }); - } + shared: { + method(schema) { - if (options.fallthrough) { - config.fallthrough = true; - } + Assert(Common.isSchema(schema) && schema._flags.id, 'Schema must be a schema with an id'); - obj.$_terms.patterns.push(config); + const obj = this.clone(); + obj.$_terms.shared = obj.$_terms.shared || []; + obj.$_terms.shared.push(schema); obj.$_mutateRegister(schema); return obj; } }, - ref: { - method() { + warning: { + method(code, local) { - return this.$_addRule('ref'); + Assert(code && typeof code === 'string', 'Invalid warning code'); + + return this.$_addRule({ name: 'warning', args: { code, local }, warn: true }); }, - validate(value, helpers) { + validate(value, helpers, { code, local }) { - if (Ref.isRef(value)) { - return value; - } + return helpers.error(code, local); + }, + args: ['code', 'local'], + multi: true + } + }, - return helpers.error('object.refType', { value }); - } - }, + modifiers: { - regex: { - method() { + keep(rule, enabled = true) { - return this.$_addRule('regex'); - }, - validate(value, helpers) { + rule.keep = enabled; + }, - if (value instanceof RegExp) { - return value; - } + message(rule, message) { - return helpers.error('object.regex', { value }); - } + rule.message = Messages.compile(message); }, - rename: { - method(from, to, options = {}) { - - Assert(typeof from === 'string' || from instanceof RegExp, 'Rename missing the from argument'); - Assert(typeof to === 'string' || to instanceof Template, 'Invalid rename to argument'); - Assert(to !== from, 'Cannot rename key to same name:', from); + warn(rule, enabled = true) { - Common.assertOptions(options, ['alias', 'ignoreUndefined', 'override', 'multiple']); + rule.warn = enabled; + } + }, - const obj = this.clone(); + manifest: { - obj.$_terms.renames = obj.$_terms.renames || []; - for (const rename of obj.$_terms.renames) { - Assert(rename.from !== from, 'Cannot rename the same key multiple times'); - } + build(obj, desc) { - if (to instanceof Template) { - obj.$_mutateRegister(to); - } + for (const key in desc) { + const values = desc[key]; - obj.$_terms.renames.push({ - from, - to, - options: ApplyToDefaults(internals.renameDefaults, options) - }); + if (['examples', 'externals', 'metas', 'notes', 'tags'].includes(key)) { + for (const value of values) { + obj = obj[key.slice(0, -1)](value); + } - return obj; - } - }, + continue; + } - schema: { - method(type = 'any') { + if (key === 'alterations') { + const alter = {}; + for (const { target, adjuster } of values) { + alter[target] = adjuster; + } - return this.$_addRule({ name: 'schema', args: { type } }); - }, - validate(value, helpers, { type }) { + obj = obj.alter(alter); + continue; + } - if (Common.isSchema(value) && - (type === 'any' || value.type === type)) { + if (key === 'whens') { + for (const value of values) { + const { ref, is, not, then, otherwise, concat } = value; + if (concat) { + obj = obj.concat(concat); + } + else if (ref) { + obj = obj.when(ref, { is, not, then, otherwise, switch: value.switch, break: value.break }); + } + else { + obj = obj.when(is, { then, otherwise, break: value.break }); + } + } - return value; + continue; } - return helpers.error('object.schema', { type }); + if (key === 'shared') { + for (const value of values) { + obj = obj.shared(value); + } + } } - }, - unknown: { - method(allow) { + return obj; + } + }, - return this.$_setFlag('unknown', allow !== false); - } - }, + messages: { + 'any.custom': '{{#label}} failed custom validation because {{#error.message}}', + 'any.default': '{{#label}} threw an error when running default method', + 'any.failover': '{{#label}} threw an error when running failover method', + 'any.invalid': '{{#label}} contains an invalid value', + 'any.only': '{{#label}} must be {if(#valids.length == 1, "", "one of ")}{{#valids}}', + 'any.ref': '{{#label}} {{#arg}} references {{:#ref}} which {{#reason}}', + 'any.required': '{{#label}} is required', + 'any.unknown': '{{#label}} is not allowed' + } +}); - with: { - method(key, peers, options = {}) { - return internals.dependency(this, 'with', key, peers, options); - } - }, +/***/ }), - without: { - method(key, peers, options = {}) { +/***/ 20270: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return internals.dependency(this, 'without', key, peers, options); - } - }, +"use strict"; - xor: { - method(...peers /*, [options] */) { - Common.verifyFlat(peers, 'xor'); +const Assert = __nccwpck_require__(32718); +const DeepEqual = __nccwpck_require__(55801); +const Reach = __nccwpck_require__(18891); - return internals.dependency(this, 'xor', null, peers); - } - } - }, +const Any = __nccwpck_require__(9512); +const Common = __nccwpck_require__(72448); +const Compile = __nccwpck_require__(3038); - overrides: { - default(value, options) { +const internals = {}; - if (value === undefined) { - value = Common.symbols.deepDefault; - } - return this.$_parent('default', value, options); - } - }, +module.exports = Any.extend({ - rebuild(schema) { + type: 'array', - if (schema.$_terms.keys) { - const topo = new Topo.Sorter(); - for (const child of schema.$_terms.keys) { - Common.tryWithPath(() => topo.add(child, { after: child.schema.$_rootReferences(), group: child.key }), child.key); - } + flags: { - schema.$_terms.keys = new internals.Keys(...topo.nodes); - } + single: { default: false }, + sparse: { default: false } }, - manifest: { + terms: { - build(obj, desc) { + items: { init: [], manifest: 'schema' }, + ordered: { init: [], manifest: 'schema' }, - if (desc.keys) { - obj = obj.keys(desc.keys); - } + _exclusions: { init: [] }, + _inclusions: { init: [] }, + _requireds: { init: [] } + }, - if (desc.dependencies) { - for (const { rel, key = null, peers, options } of desc.dependencies) { - obj = internals.dependency(obj, rel, key, peers, options); - } + coerce: { + from: 'object', + method(value, { schema, state, prefs }) { + + if (!Array.isArray(value)) { + return; } - if (desc.patterns) { - for (const { regex, schema, rule, fallthrough, matches } of desc.patterns) { - obj = obj.pattern(regex || schema, rule, { fallthrough, matches }); - } + const sort = schema.$_getRule('sort'); + if (!sort) { + return; } - if (desc.renames) { - for (const { from, to, options } of desc.renames) { - obj = obj.rename(from, to, options); - } + return internals.sort(schema, value, sort.args.options, state, prefs); + } + }, + + validate(value, { schema, error }) { + + if (!Array.isArray(value)) { + if (schema._flags.single) { + const single = [value]; + single[Common.symbols.arraySingle] = true; + return { value: single }; } - return obj; + return { errors: error('array.base') }; } - }, - messages: { - 'object.and': '{{#label}} contains {{#presentWithLabels}} without its required peers {{#missingWithLabels}}', - 'object.assert': '{{#label}} is invalid because {if(#subject.key, `"` + #subject.key + `" failed to ` + (#message || "pass the assertion test"), #message || "the assertion failed")}', - 'object.base': '{{#label}} must be of type {{#type}}', - 'object.instance': '{{#label}} must be an instance of {{:#type}}', - 'object.length': '{{#label}} must have {{#limit}} key{if(#limit == 1, "", "s")}', - 'object.max': '{{#label}} must have less than or equal to {{#limit}} key{if(#limit == 1, "", "s")}', - 'object.min': '{{#label}} must have at least {{#limit}} key{if(#limit == 1, "", "s")}', - 'object.missing': '{{#label}} must contain at least one of {{#peersWithLabels}}', - 'object.nand': '{{:#mainWithLabel}} must not exist simultaneously with {{#peersWithLabels}}', - 'object.oxor': '{{#label}} contains a conflict between optional exclusive peers {{#peersWithLabels}}', - 'object.pattern.match': '{{#label}} keys failed to match pattern requirements', - 'object.refType': '{{#label}} must be a Joi reference', - 'object.regex': '{{#label}} must be a RegExp object', - 'object.rename.multiple': '{{#label}} cannot rename {{:#from}} because multiple renames are disabled and another key was already renamed to {{:#to}}', - 'object.rename.override': '{{#label}} cannot rename {{:#from}} because override is disabled and target {{:#to}} exists', - 'object.schema': '{{#label}} must be a Joi schema of {{#type}} type', - 'object.unknown': '{{#label}} is not allowed', - 'object.with': '{{:#mainWithLabel}} missing required peer {{:#peerWithLabel}}', - 'object.without': '{{:#mainWithLabel}} conflict with forbidden peer {{:#peerWithLabel}}', - 'object.xor': '{{#label}} contains a conflict between exclusive peers {{#peersWithLabels}}' - } -}); + if (!schema.$_getRule('items') && + !schema.$_terms.externals) { + return; + } -// Helpers + return { value: value.slice() }; // Clone the array so that we don't modify the original + }, -internals.clone = function (value, prefs) { + rules: { - // Object + has: { + method(schema) { - if (typeof value === 'object') { - if (prefs.nonEnumerables) { - return Clone(value, { shallow: true }); - } + schema = this.$_compile(schema, { appendPath: true }); + const obj = this.$_addRule({ name: 'has', args: { schema } }); + obj.$_mutateRegister(schema); + return obj; + }, + validate(value, { state, prefs, error }, { schema: has }) { - const clone = Object.create(Object.getPrototypeOf(value)); - Object.assign(clone, value); - return clone; - } + const ancestors = [value, ...state.ancestors]; + for (let i = 0; i < value.length; ++i) { + const localState = state.localize([...state.path, i], ancestors, has); + if (has.$_match(value[i], localState, prefs)) { + return value; + } + } - // Function + const patternLabel = has._flags.label; + if (patternLabel) { + return error('array.hasKnown', { patternLabel }); + } - const clone = function (...args) { + return error('array.hasUnknown', null); + }, + multi: true + }, - return value.apply(this, args); - }; + items: { + method(...schemas) { - clone.prototype = Clone(value.prototype); - Object.defineProperty(clone, 'name', { value: value.name, writable: false }); - Object.defineProperty(clone, 'length', { value: value.length, writable: false }); - Object.assign(clone, value); - return clone; -}; + Common.verifyFlat(schemas, 'items'); + const obj = this.$_addRule('items'); -internals.dependency = function (schema, rel, key, peers, options) { + for (let i = 0; i < schemas.length; ++i) { + const type = Common.tryWithPath(() => this.$_compile(schemas[i]), i, { append: true }); + obj.$_terms.items.push(type); + } - Assert(key === null || typeof key === 'string', rel, 'key must be a strings'); + return obj.$_mutateRebuild(); + }, + validate(value, { schema, error, state, prefs, errorsArray }) { - // Extract options from peers array + const requireds = schema.$_terms._requireds.slice(); + const ordereds = schema.$_terms.ordered.slice(); + const inclusions = [...schema.$_terms._inclusions, ...requireds]; - if (!options) { - options = peers.length > 1 && typeof peers[peers.length - 1] === 'object' ? peers.pop() : {}; - } + const wasArray = !value[Common.symbols.arraySingle]; + delete value[Common.symbols.arraySingle]; - Common.assertOptions(options, ['separator']); + const errors = errorsArray(); - peers = [].concat(peers); + let il = value.length; + for (let i = 0; i < il; ++i) { + const item = value[i]; - // Cast peer paths + let errored = false; + let isValid = false; - const separator = Common.default(options.separator, '.'); - const paths = []; - for (const peer of peers) { - Assert(typeof peer === 'string', rel, 'peers must be strings'); - paths.push(Compile.ref(peer, { separator, ancestor: 0, prefix: false })); - } + const key = wasArray ? i : new Number(i); // eslint-disable-line no-new-wrappers + const path = [...state.path, key]; - // Cast key + // Sparse - if (key !== null) { - key = Compile.ref(key, { separator, ancestor: 0, prefix: false }); - } + if (!schema._flags.sparse && + item === undefined) { - // Add rule + errors.push(error('array.sparse', { key, path, pos: i, value: undefined }, state.localize(path))); + if (prefs.abortEarly) { + return errors; + } - const obj = schema.clone(); - obj.$_terms.dependencies = obj.$_terms.dependencies || []; - obj.$_terms.dependencies.push(new internals.Dependency(rel, key, paths, peers)); - return obj; -}; + ordereds.shift(); + continue; + } + // Exclusions -internals.dependencies = { + const ancestors = [value, ...state.ancestors]; - and(schema, dep, value, state, prefs) { + for (const exclusion of schema.$_terms._exclusions) { + if (!exclusion.$_match(item, state.localize(path, ancestors, exclusion), prefs, { presence: 'ignore' })) { + continue; + } - const missing = []; - const present = []; - const count = dep.peers.length; - for (const peer of dep.peers) { - if (peer.resolve(value, state, prefs, null, { shadow: false }) === undefined) { - missing.push(peer.key); - } - else { - present.push(peer.key); - } - } + errors.push(error('array.excludes', { pos: i, value: item }, state.localize(path))); + if (prefs.abortEarly) { + return errors; + } - if (missing.length !== count && - present.length !== count) { + errored = true; + ordereds.shift(); + break; + } - return { - code: 'object.and', - context: { - present, - presentWithLabels: internals.keysToLabels(schema, present), - missing, - missingWithLabels: internals.keysToLabels(schema, missing) - } - }; - } - }, + if (errored) { + continue; + } - nand(schema, dep, value, state, prefs) { + // Ordered - const present = []; - for (const peer of dep.peers) { - if (peer.resolve(value, state, prefs, null, { shadow: false }) !== undefined) { - present.push(peer.key); - } - } + if (schema.$_terms.ordered.length) { + if (ordereds.length) { + const ordered = ordereds.shift(); + const res = ordered.$_validate(item, state.localize(path, ancestors, ordered), prefs); + if (!res.errors) { + if (ordered._flags.result === 'strip') { + internals.fastSplice(value, i); + --i; + --il; + } + else if (!schema._flags.sparse && res.value === undefined) { + errors.push(error('array.sparse', { key, path, pos: i, value: undefined }, state.localize(path))); + if (prefs.abortEarly) { + return errors; + } - if (present.length !== dep.peers.length) { - return; - } + continue; + } + else { + value[i] = res.value; + } + } + else { + errors.push(...res.errors); + if (prefs.abortEarly) { + return errors; + } + } - const main = dep.paths[0]; - const values = dep.paths.slice(1); - return { - code: 'object.nand', - context: { - main, - mainWithLabel: internals.keysToLabels(schema, main), - peers: values, - peersWithLabels: internals.keysToLabels(schema, values) - } - }; - }, + continue; + } + else if (!schema.$_terms.items.length) { + errors.push(error('array.orderedLength', { pos: i, limit: schema.$_terms.ordered.length })); + if (prefs.abortEarly) { + return errors; + } - or(schema, dep, value, state, prefs) { + break; // No reason to continue since there are no other rules to validate other than array.orderedLength + } + } - for (const peer of dep.peers) { - if (peer.resolve(value, state, prefs, null, { shadow: false }) !== undefined) { - return; - } - } + // Requireds - return { - code: 'object.missing', - context: { - peers: dep.paths, - peersWithLabels: internals.keysToLabels(schema, dep.paths) - } - }; - }, + const requiredChecks = []; + let jl = requireds.length; + for (let j = 0; j < jl; ++j) { + const localState = state.localize(path, ancestors, requireds[j]); + localState.snapshot(); - oxor(schema, dep, value, state, prefs) { + const res = requireds[j].$_validate(item, localState, prefs); + requiredChecks[j] = res; - const present = []; - for (const peer of dep.peers) { - if (peer.resolve(value, state, prefs, null, { shadow: false }) !== undefined) { - present.push(peer.key); - } - } + if (!res.errors) { + value[i] = res.value; + isValid = true; + internals.fastSplice(requireds, j); + --j; + --jl; - if (!present.length || - present.length === 1) { + if (!schema._flags.sparse && + res.value === undefined) { - return; - } + errors.push(error('array.sparse', { key, path, pos: i, value: undefined }, state.localize(path))); + if (prefs.abortEarly) { + return errors; + } + } - const context = { peers: dep.paths, peersWithLabels: internals.keysToLabels(schema, dep.paths) }; - context.present = present; - context.presentWithLabels = internals.keysToLabels(schema, present); - return { code: 'object.oxor', context }; - }, + break; + } - with(schema, dep, value, state, prefs) { + localState.restore(); + } - for (const peer of dep.peers) { - if (peer.resolve(value, state, prefs, null, { shadow: false }) === undefined) { - return { - code: 'object.with', - context: { - main: dep.key.key, - mainWithLabel: internals.keysToLabels(schema, dep.key.key), - peer: peer.key, - peerWithLabel: internals.keysToLabels(schema, peer.key) + if (isValid) { + continue; } - }; - } - } - }, - without(schema, dep, value, state, prefs) { + // Inclusions - for (const peer of dep.peers) { - if (peer.resolve(value, state, prefs, null, { shadow: false }) !== undefined) { - return { - code: 'object.without', - context: { - main: dep.key.key, - mainWithLabel: internals.keysToLabels(schema, dep.key.key), - peer: peer.key, - peerWithLabel: internals.keysToLabels(schema, peer.key) - } - }; - } - } - }, + const stripUnknown = prefs.stripUnknown && !!prefs.stripUnknown.arrays || false; - xor(schema, dep, value, state, prefs) { + jl = inclusions.length; + for (const inclusion of inclusions) { - const present = []; - for (const peer of dep.peers) { - if (peer.resolve(value, state, prefs, null, { shadow: false }) !== undefined) { - present.push(peer.key); - } - } + // Avoid re-running requireds that already didn't match in the previous loop - if (present.length === 1) { - return; - } + let res; + const previousCheck = requireds.indexOf(inclusion); + if (previousCheck !== -1) { + res = requiredChecks[previousCheck]; + } + else { + const localState = state.localize(path, ancestors, inclusion); + localState.snapshot(); - const context = { peers: dep.paths, peersWithLabels: internals.keysToLabels(schema, dep.paths) }; - if (present.length === 0) { - return { code: 'object.missing', context }; - } + res = inclusion.$_validate(item, localState, prefs); + if (!res.errors) { + if (inclusion._flags.result === 'strip') { + internals.fastSplice(value, i); + --i; + --il; + } + else if (!schema._flags.sparse && + res.value === undefined) { - context.present = present; - context.presentWithLabels = internals.keysToLabels(schema, present); - return { code: 'object.xor', context }; - } -}; + errors.push(error('array.sparse', { key, path, pos: i, value: undefined }, state.localize(path))); + errored = true; + } + else { + value[i] = res.value; + } + isValid = true; + break; + } -internals.keysToLabels = function (schema, keys) { + localState.restore(); + } - if (Array.isArray(keys)) { - return keys.map((key) => schema.$_mapLabels(key)); - } + // Return the actual error if only one inclusion defined - return schema.$_mapLabels(keys); -}; + if (jl === 1) { + if (stripUnknown) { + internals.fastSplice(value, i); + --i; + --il; + isValid = true; + break; + } + errors.push(...res.errors); + if (prefs.abortEarly) { + return errors; + } -internals.rename = function (schema, value, state, prefs, errors) { + errored = true; + break; + } + } - const renamed = {}; - for (const rename of schema.$_terms.renames) { - const matches = []; - const pattern = typeof rename.from !== 'string'; + if (errored) { + continue; + } - if (!pattern) { - if (Object.prototype.hasOwnProperty.call(value, rename.from) && - (value[rename.from] !== undefined || !rename.options.ignoreUndefined)) { + if ((schema.$_terms._inclusions.length || schema.$_terms._requireds.length) && + !isValid) { - matches.push(rename); - } - } - else { - for (const from in value) { - if (value[from] === undefined && - rename.options.ignoreUndefined) { + if (stripUnknown) { + internals.fastSplice(value, i); + --i; + --il; + continue; + } - continue; + errors.push(error('array.includes', { pos: i, value: item }, state.localize(path))); + if (prefs.abortEarly) { + return errors; + } + } } - if (from === rename.to) { - continue; + if (requireds.length) { + internals.fillMissedErrors(schema, errors, requireds, value, state, prefs); } - const match = rename.from.exec(from); - if (!match) { - continue; + if (ordereds.length) { + internals.fillOrderedErrors(schema, errors, ordereds, value, state, prefs); + + if (!errors.length) { + internals.fillDefault(ordereds, value, state, prefs); + } } - matches.push({ from, to: rename.to, match }); - } - } + return errors.length ? errors : value; + }, - for (const match of matches) { - const from = match.from; - let to = match.to; - if (to instanceof Template) { - to = to.render(value, state, prefs, match.match); - } + priority: true, + manifest: false + }, - if (from === to) { - continue; - } + length: { + method(limit) { - if (!rename.options.multiple && - renamed[to]) { + return this.$_addRule({ name: 'length', args: { limit }, operator: '=' }); + }, + validate(value, helpers, { limit }, { name, operator, args }) { - errors.push(schema.$_createError('object.rename.multiple', value, { from, to, pattern }, state, prefs)); - if (prefs.abortEarly) { - return false; + if (Common.compare(value.length, limit, operator)) { + return value; } - } - - if (Object.prototype.hasOwnProperty.call(value, to) && - !rename.options.override && - !renamed[to]) { - errors.push(schema.$_createError('object.rename.override', value, { from, to, pattern }, state, prefs)); - if (prefs.abortEarly) { - return false; + return helpers.error('array.' + name, { limit: args.limit, value }); + }, + args: [ + { + name: 'limit', + ref: true, + assert: Common.limit, + message: 'must be a positive integer' } - } + ] + }, + + max: { + method(limit) { - if (value[from] === undefined) { - delete value[to]; - } - else { - value[to] = value[from]; + return this.$_addRule({ name: 'max', method: 'length', args: { limit }, operator: '<=' }); } + }, - renamed[to] = true; + min: { + method(limit) { - if (!rename.options.alias) { - delete value[from]; + return this.$_addRule({ name: 'min', method: 'length', args: { limit }, operator: '>=' }); } - } - } + }, - return true; -}; + ordered: { + method(...schemas) { + Common.verifyFlat(schemas, 'ordered'); -internals.unknown = function (schema, value, unprocessed, errors, state, prefs) { + const obj = this.$_addRule('items'); - if (schema.$_terms.patterns) { - let hasMatches = false; - const matches = schema.$_terms.patterns.map((pattern) => { + for (let i = 0; i < schemas.length; ++i) { + const type = Common.tryWithPath(() => this.$_compile(schemas[i]), i, { append: true }); + internals.validateSingle(type, obj); - if (pattern.matches) { - hasMatches = true; - return []; + obj.$_mutateRegister(type); + obj.$_terms.ordered.push(type); + } + + return obj.$_mutateRebuild(); } - }); + }, - const ancestors = [value, ...state.ancestors]; + single: { + method(enabled) { - for (const key of unprocessed) { - const item = value[key]; - const path = [...state.path, key]; + const value = enabled === undefined ? true : !!enabled; + Assert(!value || !this._flags._arrayItems, 'Cannot specify single rule when array has array items'); - for (let i = 0; i < schema.$_terms.patterns.length; ++i) { - const pattern = schema.$_terms.patterns[i]; - if (pattern.regex) { - const match = pattern.regex.test(key); - state.mainstay.tracer.debug(state, 'rule', `pattern.${i}`, match ? 'pass' : 'error'); - if (!match) { - continue; - } - } - else { - if (!pattern.schema.$_match(key, state.nest(pattern.schema, `pattern.${i}`), prefs)) { - continue; - } - } + return this.$_setFlag('single', value); + } + }, - unprocessed.delete(key); + sort: { + method(options = {}) { - const localState = state.localize(path, ancestors, { schema: pattern.rule, key }); - const result = pattern.rule.$_validate(item, localState, prefs); - if (result.errors) { - if (prefs.abortEarly) { - return { value, errors: result.errors }; - } + Common.assertOptions(options, ['by', 'order']); - errors.push(...result.errors); + const settings = { + order: options.order || 'ascending' + }; + + if (options.by) { + settings.by = Compile.ref(options.by, { ancestor: 0 }); + Assert(!settings.by.ancestor, 'Cannot sort by ancestor'); } - if (pattern.matches) { - matches[i].push(key); + return this.$_addRule({ name: 'sort', args: { options: settings } }); + }, + validate(value, { error, state, prefs, schema }, { options }) { + + const { value: sorted, errors } = internals.sort(schema, value, options, state, prefs); + if (errors) { + return errors; } - value[key] = result.value; - if (!pattern.fallthrough) { - break; + for (let i = 0; i < value.length; ++i) { + if (value[i] !== sorted[i]) { + return error('array.sort', { order: options.order, by: options.by ? options.by.key : 'value' }); + } } - } - } - // Validate pattern matches rules + return value; + }, + convert: true + }, - if (hasMatches) { - for (let i = 0; i < matches.length; ++i) { - const match = matches[i]; - if (!match) { - continue; - } + sparse: { + method(enabled) { - const stpm = schema.$_terms.patterns[i].matches; - const localState = state.localize(state.path, ancestors, stpm); - const result = stpm.$_validate(match, localState, prefs); - if (result.errors) { - const details = Errors.details(result.errors, { override: false }); - details.matches = match; - const report = schema.$_createError('object.pattern.match', value, details, state, prefs); - if (prefs.abortEarly) { - return { value, errors: report }; - } + const value = enabled === undefined ? true : !!enabled; - errors.push(report); + if (this._flags.sparse === value) { + return this; } + + const obj = value ? this.clone() : this.$_addRule('items'); + return obj.$_setFlag('sparse', value, { clone: false }); } - } - } + }, - if (!unprocessed.size || - !schema.$_terms.keys && !schema.$_terms.patterns) { // If no keys or patterns specified, unknown keys allowed + unique: { + method(comparator, options = {}) { - return; - } + Assert(!comparator || typeof comparator === 'function' || typeof comparator === 'string', 'comparator must be a function or a string'); + Common.assertOptions(options, ['ignoreUndefined', 'separator']); - if (prefs.stripUnknown && !schema._flags.unknown || - prefs.skipFunctions) { + const rule = { name: 'unique', args: { options, comparator } }; - const stripUnknown = prefs.stripUnknown ? (prefs.stripUnknown === true ? true : !!prefs.stripUnknown.objects) : false; + if (comparator) { + if (typeof comparator === 'string') { + const separator = Common.default(options.separator, '.'); + rule.path = separator ? comparator.split(separator) : [comparator]; + } + else { + rule.comparator = comparator; + } + } - for (const key of unprocessed) { - if (stripUnknown) { - delete value[key]; - unprocessed.delete(key); - } - else if (typeof value[key] === 'function') { - unprocessed.delete(key); - } - } - } + return this.$_addRule(rule); + }, + validate(value, { state, error, schema }, { comparator: raw, options }, { comparator, path }) { - const forbidUnknown = !Common.default(schema._flags.unknown, prefs.allowUnknown); - if (forbidUnknown) { - for (const unprocessedKey of unprocessed) { - const localState = state.localize([...state.path, unprocessedKey], []); - const report = schema.$_createError('object.unknown', value[unprocessedKey], { child: unprocessedKey }, localState, prefs, { flags: false }); - if (prefs.abortEarly) { - return { value, errors: report }; - } + const found = { + string: Object.create(null), + number: Object.create(null), + undefined: Object.create(null), + boolean: Object.create(null), + object: new Map(), + function: new Map(), + custom: new Map() + }; - errors.push(report); - } - } -}; + const compare = comparator || DeepEqual; + const ignoreUndefined = options.ignoreUndefined; + + for (let i = 0; i < value.length; ++i) { + const item = path ? Reach(value[i], path) : value[i]; + const records = comparator ? found.custom : found[typeof item]; + Assert(records, 'Failed to find unique map container for type', typeof item); + if (records instanceof Map) { + const entries = records.entries(); + let current; + while (!(current = entries.next()).done) { + if (compare(current.value[0], item)) { + const localState = state.localize([...state.path, i], [value, ...state.ancestors]); + const context = { + pos: i, + value: value[i], + dupePos: current.value[1], + dupeValue: value[current.value[1]] + }; -internals.Dependency = class { + if (path) { + context.path = raw; + } - constructor(rel, key, peers, paths) { + return error('array.unique', context, localState); + } + } - this.rel = rel; - this.key = key; - this.peers = peers; - this.paths = paths; - } + records.set(item, i); + } + else { + if ((!ignoreUndefined || item !== undefined) && + records[item] !== undefined) { - describe() { + const context = { + pos: i, + value: value[i], + dupePos: records[item], + dupeValue: value[records[item]] + }; - const desc = { - rel: this.rel, - peers: this.paths - }; + if (path) { + context.path = raw; + } - if (this.key !== null) { - desc.key = this.key.key; - } + const localState = state.localize([...state.path, i], [value, ...state.ancestors]); + return error('array.unique', context, localState); + } - if (this.peers[0].separator !== '.') { - desc.options = { separator: this.peers[0].separator }; - } + records[item] = i; + } + } - return desc; - } -}; + return value; + }, + args: ['comparator', 'options'], + multi: true + } + }, + cast: { + set: { + from: Array.isArray, + to(value, helpers) { -internals.Keys = class extends Array { + return new Set(value); + } + } + }, - concat(source) { + rebuild(schema) { - const result = this.slice(); + schema.$_terms._inclusions = []; + schema.$_terms._exclusions = []; + schema.$_terms._requireds = []; - const keys = new Map(); - for (let i = 0; i < result.length; ++i) { - keys.set(result[i].key, i); - } + for (const type of schema.$_terms.items) { + internals.validateSingle(type, schema); - for (const item of source) { - const key = item.key; - const pos = keys.get(key); - if (pos !== undefined) { - result[pos] = { key, schema: result[pos].schema.concat(item.schema) }; + if (type._flags.presence === 'required') { + schema.$_terms._requireds.push(type); + } + else if (type._flags.presence === 'forbidden') { + schema.$_terms._exclusions.push(type); } else { - result.push(item); + schema.$_terms._inclusions.push(type); } } - return result; - } -}; - - -/***/ }), + for (const type of schema.$_terms.ordered) { + internals.validateSingle(type, schema); + } + }, -/***/ 69869: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + manifest: { -"use strict"; + build(obj, desc) { + if (desc.items) { + obj = obj.items(...desc.items); + } -const Assert = __nccwpck_require__(32718); + if (desc.ordered) { + obj = obj.ordered(...desc.ordered); + } -const Any = __nccwpck_require__(9512); -const Common = __nccwpck_require__(72448); -const Compile = __nccwpck_require__(3038); -const Errors = __nccwpck_require__(69490); + return obj; + } + }, + messages: { + 'array.base': '{{#label}} must be an array', + 'array.excludes': '{{#label}} contains an excluded value', + 'array.hasKnown': '{{#label}} does not contain at least one required match for type {:#patternLabel}', + 'array.hasUnknown': '{{#label}} does not contain at least one required match', + 'array.includes': '{{#label}} does not match any of the allowed types', + 'array.includesRequiredBoth': '{{#label}} does not contain {{#knownMisses}} and {{#unknownMisses}} other required value(s)', + 'array.includesRequiredKnowns': '{{#label}} does not contain {{#knownMisses}}', + 'array.includesRequiredUnknowns': '{{#label}} does not contain {{#unknownMisses}} required value(s)', + 'array.length': '{{#label}} must contain {{#limit}} items', + 'array.max': '{{#label}} must contain less than or equal to {{#limit}} items', + 'array.min': '{{#label}} must contain at least {{#limit}} items', + 'array.orderedLength': '{{#label}} must contain at most {{#limit}} items', + 'array.sort': '{{#label}} must be sorted in {#order} order by {{#by}}', + 'array.sort.mismatching': '{{#label}} cannot be sorted due to mismatching types', + 'array.sort.unsupported': '{{#label}} cannot be sorted due to unsupported type {#type}', + 'array.sparse': '{{#label}} must not be a sparse array item', + 'array.unique': '{{#label}} contains a duplicate value' + } +}); -const internals = {}; +// Helpers -module.exports = Any.extend({ +internals.fillMissedErrors = function (schema, errors, requireds, value, state, prefs) { - type: 'link', + const knownMisses = []; + let unknownMisses = 0; + for (const required of requireds) { + const label = required._flags.label; + if (label) { + knownMisses.push(label); + } + else { + ++unknownMisses; + } + } - properties: { - schemaChain: true - }, + if (knownMisses.length) { + if (unknownMisses) { + errors.push(schema.$_createError('array.includesRequiredBoth', value, { knownMisses, unknownMisses }, state, prefs)); + } + else { + errors.push(schema.$_createError('array.includesRequiredKnowns', value, { knownMisses }, state, prefs)); + } + } + else { + errors.push(schema.$_createError('array.includesRequiredUnknowns', value, { unknownMisses }, state, prefs)); + } +}; - terms: { - link: { init: null, manifest: 'single', register: false } - }, +internals.fillOrderedErrors = function (schema, errors, ordereds, value, state, prefs) { - args(schema, ref) { + const requiredOrdereds = []; - return schema.ref(ref); - }, + for (const ordered of ordereds) { + if (ordered._flags.presence === 'required') { + requiredOrdereds.push(ordered); + } + } - validate(value, { schema, state, prefs }) { + if (requiredOrdereds.length) { + internals.fillMissedErrors(schema, errors, requiredOrdereds, value, state, prefs); + } +}; - Assert(schema.$_terms.link, 'Uninitialized link schema'); - const linked = internals.generate(schema, value, state, prefs); - const ref = schema.$_terms.link[0].ref; - return linked.$_validate(value, state.nest(linked, `link:${ref.display}:${linked.type}`), prefs); - }, +internals.fillDefault = function (ordereds, value, state, prefs) { - generate(schema, value, state, prefs) { + const overrides = []; + let trailingUndefined = true; - return internals.generate(schema, value, state, prefs); - }, + for (let i = ordereds.length - 1; i >= 0; --i) { + const ordered = ordereds[i]; + const ancestors = [value, ...state.ancestors]; + const override = ordered.$_validate(undefined, state.localize(state.path, ancestors, ordered), prefs).value; - rules: { + if (trailingUndefined) { + if (override === undefined) { + continue; + } - ref: { - method(ref) { + trailingUndefined = false; + } - Assert(!this.$_terms.link, 'Cannot reinitialize schema'); + overrides.unshift(override); + } - ref = Compile.ref(ref); + if (overrides.length) { + value.push(...overrides); + } +}; - Assert(ref.type === 'value' || ref.type === 'local', 'Invalid reference type:', ref.type); - Assert(ref.type === 'local' || ref.ancestor === 'root' || ref.ancestor > 0, 'Link cannot reference itself'); - const obj = this.clone(); - obj.$_terms.link = [{ ref }]; - return obj; - } - }, +internals.fastSplice = function (arr, i) { - relative: { - method(enabled = true) { + let pos = i; + while (pos < arr.length) { + arr[pos++] = arr[pos]; + } - return this.$_setFlag('relative', enabled); - } - } - }, + --arr.length; +}; - overrides: { - concat(source) { +internals.validateSingle = function (type, obj) { - Assert(this.$_terms.link, 'Uninitialized link schema'); - Assert(Common.isSchema(source), 'Invalid schema object'); - Assert(source.type !== 'link', 'Cannot merge type link with another link'); + if (type.type === 'array' || + type._flags._arrayItems) { - const obj = this.clone(); + Assert(!obj._flags.single, 'Cannot specify array item with single rule enabled'); + obj.$_setFlag('_arrayItems', true, { clone: false }); + } +}; - if (!obj.$_terms.whens) { - obj.$_terms.whens = []; - } - obj.$_terms.whens.push({ concat: source }); - return obj.$_mutateRebuild(); - } - }, +internals.sort = function (schema, value, settings, state, prefs) { - manifest: { + const order = settings.order === 'ascending' ? 1 : -1; + const aFirst = -1 * order; + const bFirst = order; - build(obj, desc) { + const sort = (a, b) => { - Assert(desc.link, 'Invalid link description missing link'); - return obj.ref(desc.link); + let compare = internals.compare(a, b, aFirst, bFirst); + if (compare !== null) { + return compare; } - } -}); + if (settings.by) { + a = settings.by.resolve(a, state, prefs); + b = settings.by.resolve(b, state, prefs); + } -// Helpers + compare = internals.compare(a, b, aFirst, bFirst); + if (compare !== null) { + return compare; + } -internals.generate = function (schema, value, state, prefs) { + const type = typeof a; + if (type !== typeof b) { + throw schema.$_createError('array.sort.mismatching', value, null, state, prefs); + } - let linked = state.mainstay.links.get(schema); - if (linked) { - return linked._generate(value, state, prefs).schema; - } + if (type !== 'number' && + type !== 'string') { - const ref = schema.$_terms.link[0].ref; - const { perspective, path } = internals.perspective(ref, state); - internals.assert(perspective, 'which is outside of schema boundaries', ref, schema, state, prefs); + throw schema.$_createError('array.sort.unsupported', value, { type }, state, prefs); + } - try { - linked = path.length ? perspective.$_reach(path) : perspective; - } - catch (ignoreErr) { - internals.assert(false, 'to non-existing schema', ref, schema, state, prefs); - } + if (type === 'number') { + return (a - b) * order; + } - internals.assert(linked.type !== 'link', 'which is another link', ref, schema, state, prefs); + return a < b ? aFirst : bFirst; + }; - if (!schema._flags.relative) { - state.mainstay.links.set(schema, linked); + try { + return { value: value.slice().sort(sort) }; + } + catch (err) { + return { errors: err }; } - - return linked._generate(value, state, prefs).schema; }; -internals.perspective = function (ref, state) { - - if (ref.type === 'local') { - for (const { schema, key } of state.schemas) { // From parent to root - const id = schema._flags.id || key; - if (id === ref.path[0]) { - return { perspective: schema, path: ref.path.slice(1) }; - } - - if (schema.$_terms.shared) { - for (const shared of schema.$_terms.shared) { - if (shared._flags.id === ref.path[0]) { - return { perspective: shared, path: ref.path.slice(1) }; - } - } - } - } +internals.compare = function (a, b, aFirst, bFirst) { - return { perspective: null, path: null }; + if (a === b) { + return 0; } - if (ref.ancestor === 'root') { - return { perspective: state.schemas[state.schemas.length - 1].schema, path: ref.path }; + if (a === undefined) { + return 1; // Always last regardless of sort order } - return { perspective: state.schemas[ref.ancestor] && state.schemas[ref.ancestor].schema, path: ref.path }; -}; - + if (b === undefined) { + return -1; // Always last regardless of sort order + } -internals.assert = function (condition, message, ref, schema, state, prefs) { + if (a === null) { + return bFirst; + } - if (condition) { // Manual check to avoid generating error message on success - return; + if (b === null) { + return aFirst; } - Assert(false, `"${Errors.label(schema._flags, state, prefs)}" contains link reference "${ref.display}" ${message}`); + return null; }; /***/ }), -/***/ 15855: +/***/ 34288: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -66327,851 +66212,883 @@ const Any = __nccwpck_require__(9512); const Common = __nccwpck_require__(72448); -const internals = { - numberRx: /^\s*[+-]?(?:(?:\d+(?:\.\d*)?)|(?:\.\d+))(?:e([+-]?\d+))?\s*$/i, - precisionRx: /(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/ -}; +const internals = {}; module.exports = Any.extend({ - type: 'number', - - flags: { - - unsafe: { default: false } - }, + type: 'binary', coerce: { from: 'string', - method(value, { schema, error }) { - - const matches = value.match(internals.numberRx); - if (!matches) { - return; - } - - value = value.trim(); - const result = { value: parseFloat(value) }; - - if (result.value === 0) { - result.value = 0; // -0 - } - - if (!schema._flags.unsafe) { - if (value.match(/e/i)) { - const constructed = internals.normalizeExponent(`${result.value / Math.pow(10, matches[1])}e${matches[1]}`); - if (constructed !== internals.normalizeExponent(value)) { - result.errors = error('number.unsafe'); - return result; - } - } - else { - const string = result.value.toString(); - if (string.match(/e/i)) { - return result; - } + method(value, { schema }) { - if (string !== internals.normalizeDecimal(value)) { - result.errors = error('number.unsafe'); - return result; - } - } + try { + return { value: Buffer.from(value, schema._flags.encoding) }; } - - return result; + catch (ignoreErr) { } } }, - validate(value, { schema, error, prefs }) { - - if (value === Infinity || - value === -Infinity) { + validate(value, { error }) { - return { value, errors: error('number.infinity') }; + if (!Buffer.isBuffer(value)) { + return { value, errors: error('binary.base') }; } + }, - if (!Common.isNumber(value)) { - return { value, errors: error('number.base') }; - } + rules: { + encoding: { + method(encoding) { - const result = { value }; + Assert(Buffer.isEncoding(encoding), 'Invalid encoding:', encoding); - if (prefs.convert) { - const rule = schema.$_getRule('precision'); - if (rule) { - const precision = Math.pow(10, rule.args.limit); // This is conceptually equivalent to using toFixed but it should be much faster - result.value = Math.round(result.value * precision) / precision; + return this.$_setFlag('encoding', encoding); } - } - - if (result.value === 0) { - result.value = 0; // -0 - } - - if (!schema._flags.unsafe && - (value > Number.MAX_SAFE_INTEGER || value < Number.MIN_SAFE_INTEGER)) { - - result.errors = error('number.unsafe'); - } - - return result; - }, + }, - rules: { + length: { + method(limit) { - compare: { - method: false, + return this.$_addRule({ name: 'length', method: 'length', args: { limit }, operator: '=' }); + }, validate(value, helpers, { limit }, { name, operator, args }) { - if (Common.compare(value, limit, operator)) { + if (Common.compare(value.length, limit, operator)) { return value; } - return helpers.error('number.' + name, { limit: args.limit, value }); + return helpers.error('binary.' + name, { limit: args.limit, value }); }, args: [ { name: 'limit', ref: true, - assert: Common.isNumber, - message: 'must be a number' + assert: Common.limit, + message: 'must be a positive integer' } ] }, - greater: { + max: { method(limit) { - return this.$_addRule({ name: 'greater', method: 'compare', args: { limit }, operator: '>' }); + return this.$_addRule({ name: 'max', method: 'length', args: { limit }, operator: '<=' }); } }, - integer: { - method() { + min: { + method(limit) { - return this.$_addRule('integer'); - }, - validate(value, helpers) { + return this.$_addRule({ name: 'min', method: 'length', args: { limit }, operator: '>=' }); + } + } + }, - if (Math.trunc(value) - value === 0) { - return value; - } + cast: { + string: { + from: (value) => Buffer.isBuffer(value), + to(value, helpers) { - return helpers.error('number.integer'); + return value.toString(); } - }, + } + }, - less: { - method(limit) { + messages: { + 'binary.base': '{{#label}} must be a buffer or a string', + 'binary.length': '{{#label}} must be {{#limit}} bytes', + 'binary.max': '{{#label}} must be less than or equal to {{#limit}} bytes', + 'binary.min': '{{#label}} must be at least {{#limit}} bytes' + } +}); - return this.$_addRule({ name: 'less', method: 'compare', args: { limit }, operator: '<' }); - } - }, - max: { - method(limit) { +/***/ }), - return this.$_addRule({ name: 'max', method: 'compare', args: { limit }, operator: '<=' }); - } - }, +/***/ 47489: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - min: { - method(limit) { +"use strict"; - return this.$_addRule({ name: 'min', method: 'compare', args: { limit }, operator: '>=' }); - } - }, - multiple: { - method(base) { +const Assert = __nccwpck_require__(32718); - return this.$_addRule({ name: 'multiple', args: { base } }); - }, - validate(value, helpers, { base }, options) { +const Any = __nccwpck_require__(9512); +const Common = __nccwpck_require__(72448); +const Values = __nccwpck_require__(71944); - if (value * (1 / base) % 1 === 0) { - return value; - } - return helpers.error('number.multiple', { multiple: options.args.base, value }); - }, - args: [ - { - name: 'base', - ref: true, - assert: (value) => typeof value === 'number' && isFinite(value) && value > 0, - message: 'must be a positive number' - } - ], - multi: true - }, +const internals = {}; - negative: { - method() { - return this.sign('negative'); - } - }, +internals.isBool = function (value) { - port: { - method() { + return typeof value === 'boolean'; +}; - return this.$_addRule('port'); - }, - validate(value, helpers) { - if (Number.isSafeInteger(value) && - value >= 0 && - value <= 65535) { +module.exports = Any.extend({ - return value; - } + type: 'boolean', - return helpers.error('number.port'); - } - }, + flags: { - positive: { - method() { + sensitive: { default: false } + }, - return this.sign('positive'); - } + terms: { + + falsy: { + init: null, + manifest: 'values' }, - precision: { - method(limit) { + truthy: { + init: null, + manifest: 'values' + } + }, - Assert(Number.isSafeInteger(limit), 'limit must be an integer'); + coerce(value, { schema }) { - return this.$_addRule({ name: 'precision', args: { limit } }); - }, - validate(value, helpers, { limit }) { + if (typeof value === 'boolean') { + return; + } - const places = value.toString().match(internals.precisionRx); - const decimals = Math.max((places[1] ? places[1].length : 0) - (places[2] ? parseInt(places[2], 10) : 0), 0); - if (decimals <= limit) { - return value; + if (typeof value === 'string') { + const normalized = schema._flags.sensitive ? value : value.toLowerCase(); + value = normalized === 'true' ? true : (normalized === 'false' ? false : value); + } + + if (typeof value !== 'boolean') { + value = schema.$_terms.truthy && schema.$_terms.truthy.has(value, null, null, !schema._flags.sensitive) || + (schema.$_terms.falsy && schema.$_terms.falsy.has(value, null, null, !schema._flags.sensitive) ? false : value); + } + + return { value }; + }, + + validate(value, { error }) { + + if (typeof value !== 'boolean') { + return { value, errors: error('boolean.base') }; + } + }, + + rules: { + truthy: { + method(...values) { + + Common.verifyFlat(values, 'truthy'); + + const obj = this.clone(); + obj.$_terms.truthy = obj.$_terms.truthy || new Values(); + + for (let i = 0; i < values.length; ++i) { + const value = values[i]; + + Assert(value !== undefined, 'Cannot call truthy with undefined'); + obj.$_terms.truthy.add(value); } - return helpers.error('number.precision', { limit, value }); - }, - convert: true + return obj; + } }, - sign: { - method(sign) { + falsy: { + method(...values) { - Assert(['negative', 'positive'].includes(sign), 'Invalid sign', sign); + Common.verifyFlat(values, 'falsy'); - return this.$_addRule({ name: 'sign', args: { sign } }); - }, - validate(value, helpers, { sign }) { + const obj = this.clone(); + obj.$_terms.falsy = obj.$_terms.falsy || new Values(); - if (sign === 'negative' && value < 0 || - sign === 'positive' && value > 0) { + for (let i = 0; i < values.length; ++i) { + const value = values[i]; - return value; + Assert(value !== undefined, 'Cannot call falsy with undefined'); + obj.$_terms.falsy.add(value); } - return helpers.error(`number.${sign}`); + return obj; } }, - unsafe: { + sensitive: { method(enabled = true) { - Assert(typeof enabled === 'boolean', 'enabled must be a boolean'); - - return this.$_setFlag('unsafe', enabled); + return this.$_setFlag('sensitive', enabled); } } }, cast: { + number: { + from: internals.isBool, + to(value, helpers) { + + return value ? 1 : 0; + } + }, string: { - from: (value) => typeof value === 'number', + from: internals.isBool, to(value, helpers) { - return value.toString(); + return value ? 'true' : 'false'; + } + } + }, + + manifest: { + + build(obj, desc) { + + if (desc.truthy) { + obj = obj.truthy(...desc.truthy); } + + if (desc.falsy) { + obj = obj.falsy(...desc.falsy); + } + + return obj; } }, messages: { - 'number.base': '{{#label}} must be a number', - 'number.greater': '{{#label}} must be greater than {{#limit}}', - 'number.infinity': '{{#label}} cannot be infinity', - 'number.integer': '{{#label}} must be an integer', - 'number.less': '{{#label}} must be less than {{#limit}}', - 'number.max': '{{#label}} must be less than or equal to {{#limit}}', - 'number.min': '{{#label}} must be greater than or equal to {{#limit}}', - 'number.multiple': '{{#label}} must be a multiple of {{#multiple}}', - 'number.negative': '{{#label}} must be a negative number', - 'number.port': '{{#label}} must be a valid port', - 'number.positive': '{{#label}} must be a positive number', - 'number.precision': '{{#label}} must have no more than {{#limit}} decimal places', - 'number.unsafe': '{{#label}} must be a safe number' + 'boolean.base': '{{#label}} must be a boolean' } }); -// Helpers +/***/ }), -internals.normalizeExponent = function (str) { +/***/ 6624: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return str - .replace(/E/, 'e') - .replace(/\.(\d*[1-9])?0+e/, '.$1e') - .replace(/\.e/, 'e') - .replace(/e\+/, 'e') - .replace(/^\+/, '') - .replace(/^(-?)0+([1-9])/, '$1$2'); -}; +"use strict"; -internals.normalizeDecimal = function (str) { +const Assert = __nccwpck_require__(32718); - str = str - // Remove leading plus signs - .replace(/^\+/, '') - // Remove trailing zeros if there is a decimal point and unecessary decimal points - .replace(/\.0*$/, '') - // Add a integer 0 if the numbers starts with a decimal point - .replace(/^(-?)\.([^\.]*)$/, '$10.$2') - // Remove leading zeros - .replace(/^(-?)0+([0-9])/, '$1$2'); +const Any = __nccwpck_require__(9512); +const Common = __nccwpck_require__(72448); +const Template = __nccwpck_require__(51396); - if (str.includes('.') && - str.endsWith('0')) { - str = str.replace(/0+$/, ''); - } +const internals = {}; - if (str === '-0') { - return '0'; - } - return str; +internals.isDate = function (value) { + + return value instanceof Date; }; -/***/ }), +module.exports = Any.extend({ + + type: 'date', + + coerce: { + from: ['number', 'string'], + method(value, { schema }) { + + return { value: internals.parse(value, schema._flags.format) || value }; + } + }, + + validate(value, { schema, error, prefs }) { + + if (value instanceof Date && + !isNaN(value.getTime())) { + + return; + } + + const format = schema._flags.format; + + if (!prefs.convert || + !format || + typeof value !== 'string') { + + return { value, errors: error('date.base') }; + } + + return { value, errors: error('date.format', { format }) }; + }, + + rules: { + + compare: { + method: false, + validate(value, helpers, { date }, { name, operator, args }) { + + const to = date === 'now' ? Date.now() : date.getTime(); + if (Common.compare(value.getTime(), to, operator)) { + return value; + } + + return helpers.error('date.' + name, { limit: args.date, value }); + }, + args: [ + { + name: 'date', + ref: true, + normalize: (date) => { + + return date === 'now' ? date : internals.parse(date); + }, + assert: (date) => date !== null, + message: 'must have a valid date format' + } + ] + }, + + format: { + method(format) { + + Assert(['iso', 'javascript', 'unix'].includes(format), 'Unknown date format', format); + + return this.$_setFlag('format', format); + } + }, + + greater: { + method(date) { + + return this.$_addRule({ name: 'greater', method: 'compare', args: { date }, operator: '>' }); + } + }, + + iso: { + method() { + + return this.format('iso'); + } + }, -/***/ 46878: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + less: { + method(date) { -"use strict"; + return this.$_addRule({ name: 'less', method: 'compare', args: { date }, operator: '<' }); + } + }, + max: { + method(date) { -const Keys = __nccwpck_require__(79130); + return this.$_addRule({ name: 'max', method: 'compare', args: { date }, operator: '<=' }); + } + }, + min: { + method(date) { -const internals = {}; + return this.$_addRule({ name: 'min', method: 'compare', args: { date }, operator: '>=' }); + } + }, + timestamp: { + method(type = 'javascript') { -module.exports = Keys.extend({ + Assert(['javascript', 'unix'].includes(type), '"type" must be one of "javascript, unix"'); - type: 'object', + return this.format(type); + } + } + }, cast: { - map: { - from: (value) => value && typeof value === 'object', + number: { + from: internals.isDate, to(value, helpers) { - return new Map(Object.entries(value)); + return value.getTime(); + } + }, + string: { + from: internals.isDate, + to(value, { prefs }) { + + return Template.date(value, prefs); } } + }, + + messages: { + 'date.base': '{{#label}} must be a valid date', + 'date.format': '{{#label}} must be in {msg("date.format." + #format) || #format} format', + 'date.greater': '{{#label}} must be greater than {{:#limit}}', + 'date.less': '{{#label}} must be less than {{:#limit}}', + 'date.max': '{{#label}} must be less than or equal to {{:#limit}}', + 'date.min': '{{#label}} must be greater than or equal to {{:#limit}}', + + // Messages used in date.format + + 'date.format.iso': 'ISO 8601 date', + 'date.format.javascript': 'timestamp or number of milliseconds', + 'date.format.unix': 'timestamp or number of seconds' } }); -/***/ }), +// Helpers -/***/ 72260: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +internals.parse = function (value, format) { -"use strict"; + if (value instanceof Date) { + return value; + } + if (typeof value !== 'string' && + (isNaN(value) || !isFinite(value))) { -const Assert = __nccwpck_require__(32718); -const Domain = __nccwpck_require__(97425); -const Email = __nccwpck_require__(3283); -const Ip = __nccwpck_require__(82337); -const EscapeRegex = __nccwpck_require__(91965); -const Tlds = __nccwpck_require__(53092); -const Uri = __nccwpck_require__(74983); + return null; + } -const Any = __nccwpck_require__(9512); -const Common = __nccwpck_require__(72448); + if (/^\s*$/.test(value)) { + return null; + } + // ISO -const internals = { - tlds: Tlds instanceof Set ? { tlds: { allow: Tlds, deny: null } } : false, // $lab:coverage:ignore$ - base64Regex: { - // paddingRequired - true: { - // urlSafe - true: /^(?:[\w\-]{2}[\w\-]{2})*(?:[\w\-]{2}==|[\w\-]{3}=)?$/, - false: /^(?:[A-Za-z0-9+\/]{2}[A-Za-z0-9+\/]{2})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/ - }, - false: { - true: /^(?:[\w\-]{2}[\w\-]{2})*(?:[\w\-]{2}(==)?|[\w\-]{3}=?)?$/, - false: /^(?:[A-Za-z0-9+\/]{2}[A-Za-z0-9+\/]{2})*(?:[A-Za-z0-9+\/]{2}(==)?|[A-Za-z0-9+\/]{3}=?)?$/ + if (format === 'iso') { + if (!Common.isIsoDate(value)) { + return null; } - }, - dataUriRegex: /^data:[\w+.-]+\/[\w+.-]+;((charset=[\w-]+|base64),)?(.*)$/, - hexRegex: /^[a-f0-9]+$/i, - ipRegex: Ip.regex({ cidr: 'forbidden' }).regex, - isoDurationRegex: /^P(?!$)(\d+Y)?(\d+M)?(\d+W)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?$/, - guidBrackets: { - '{': '}', '[': ']', '(': ')', '': '' - }, - guidVersions: { - uuidv1: '1', - uuidv2: '2', - uuidv3: '3', - uuidv4: '4', - uuidv5: '5' - }, - guidSeparators: new Set([undefined, true, false, '-', ':']), + return internals.date(value.toString()); + } - normalizationForms: ['NFC', 'NFD', 'NFKC', 'NFKD'] -}; + // Normalize number string + + const original = value; + if (typeof value === 'string' && + /^[+-]?\d+(\.\d+)?$/.test(value)) { + value = parseFloat(value); + } -module.exports = Any.extend({ + // Timestamp - type: 'string', + if (format) { + if (format === 'javascript') { + return internals.date(1 * value); // Casting to number + } - flags: { + if (format === 'unix') { + return internals.date(1000 * value); + } - insensitive: { default: false }, - truncate: { default: false } - }, + if (typeof original === 'string') { + return null; + } + } - terms: { + // Plain - replacements: { init: null } - }, + return internals.date(value); +}; - coerce: { - from: 'string', - method(value, { schema, state, prefs }) { - const normalize = schema.$_getRule('normalize'); - if (normalize) { - value = value.normalize(normalize.args.form); - } +internals.date = function (value) { - const casing = schema.$_getRule('case'); - if (casing) { - value = casing.args.direction === 'upper' ? value.toLocaleUpperCase() : value.toLocaleLowerCase(); - } + const date = new Date(value); + if (!isNaN(date.getTime())) { + return date; + } - const trim = schema.$_getRule('trim'); - if (trim && - trim.args.enabled) { + return null; +}; - value = value.trim(); - } - if (schema.$_terms.replacements) { - for (const replacement of schema.$_terms.replacements) { - value = value.replace(replacement.pattern, replacement.replacement); - } - } +/***/ }), - const hex = schema.$_getRule('hex'); - if (hex && - hex.args.options.byteAligned && - value.length % 2 !== 0) { +/***/ 62269: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - value = `0${value}`; - } +"use strict"; - if (schema.$_getRule('isoDate')) { - const iso = internals.isoDate(value); - if (iso) { - value = iso; - } - } - if (schema._flags.truncate) { - const rule = schema.$_getRule('max'); - if (rule) { - let limit = rule.args.limit; - if (Common.isResolvable(limit)) { - limit = limit.resolve(value, state, prefs); - if (!Common.limit(limit)) { - return { value, errors: schema.$_createError('any.ref', limit, { ref: rule.args.limit, arg: 'limit', reason: 'must be a positive integer' }, state, prefs) }; - } - } +const Assert = __nccwpck_require__(32718); - value = value.slice(0, limit); - } - } +const Keys = __nccwpck_require__(79130); - return { value }; - } - }, - validate(value, { schema, error }) { +const internals = {}; - if (typeof value !== 'string') { - return { value, errors: error('string.base') }; - } - if (value === '') { - const min = schema.$_getRule('min'); - if (min && - min.args.limit === 0) { +module.exports = Keys.extend({ - return; - } + type: 'function', - return { value, errors: error('string.empty') }; - } + properties: { + typeof: 'function' }, rules: { + arity: { + method(n) { - alphanum: { + Assert(Number.isSafeInteger(n) && n >= 0, 'n must be a positive integer'); + + return this.$_addRule({ name: 'arity', args: { n } }); + }, + validate(value, helpers, { n }) { + + if (value.length === n) { + return value; + } + + return helpers.error('function.arity', { n }); + } + }, + + class: { method() { - return this.$_addRule('alphanum'); + return this.$_addRule('class'); }, validate(value, helpers) { - if (/^[a-zA-Z0-9]+$/.test(value)) { + if ((/^\s*class\s/).test(value.toString())) { return value; } - return helpers.error('string.alphanum'); + return helpers.error('function.class', { value }); } }, - base64: { - method(options = {}) { - - Common.assertOptions(options, ['paddingRequired', 'urlSafe']); + minArity: { + method(n) { - options = { urlSafe: false, paddingRequired: true, ...options }; - Assert(typeof options.paddingRequired === 'boolean', 'paddingRequired must be boolean'); - Assert(typeof options.urlSafe === 'boolean', 'urlSafe must be boolean'); + Assert(Number.isSafeInteger(n) && n > 0, 'n must be a strict positive integer'); - return this.$_addRule({ name: 'base64', args: { options } }); + return this.$_addRule({ name: 'minArity', args: { n } }); }, - validate(value, helpers, { options }) { + validate(value, helpers, { n }) { - const regex = internals.base64Regex[options.paddingRequired][options.urlSafe]; - if (regex.test(value)) { + if (value.length >= n) { return value; } - return helpers.error('string.base64'); + return helpers.error('function.minArity', { n }); } }, - case: { - method(direction) { + maxArity: { + method(n) { - Assert(['lower', 'upper'].includes(direction), 'Invalid case:', direction); + Assert(Number.isSafeInteger(n) && n >= 0, 'n must be a positive integer'); - return this.$_addRule({ name: 'case', args: { direction } }); + return this.$_addRule({ name: 'maxArity', args: { n } }); }, - validate(value, helpers, { direction }) { - - if (direction === 'lower' && value === value.toLocaleLowerCase() || - direction === 'upper' && value === value.toLocaleUpperCase()) { + validate(value, helpers, { n }) { + if (value.length <= n) { return value; } - return helpers.error(`string.${direction}case`); - }, - convert: true - }, + return helpers.error('function.maxArity', { n }); + } + } + }, - creditCard: { - method() { + messages: { + 'function.arity': '{{#label}} must have an arity of {{#n}}', + 'function.class': '{{#label}} must be a class', + 'function.maxArity': '{{#label}} must have an arity lesser or equal to {{#n}}', + 'function.minArity': '{{#label}} must have an arity greater or equal to {{#n}}' + } +}); - return this.$_addRule('creditCard'); - }, - validate(value, helpers) { - let i = value.length; - let sum = 0; - let mul = 1; +/***/ }), - while (i--) { - const char = value.charAt(i) * mul; - sum = sum + (char - (char > 9) * 9); - mul = mul ^ 3; - } +/***/ 79130: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (sum > 0 && - sum % 10 === 0) { +"use strict"; - return value; - } - return helpers.error('string.creditCard'); - } - }, +const ApplyToDefaults = __nccwpck_require__(85545); +const Assert = __nccwpck_require__(32718); +const Clone = __nccwpck_require__(85578); +const Topo = __nccwpck_require__(88392); - dataUri: { - method(options = {}) { +const Any = __nccwpck_require__(9512); +const Common = __nccwpck_require__(72448); +const Compile = __nccwpck_require__(3038); +const Errors = __nccwpck_require__(69490); +const Ref = __nccwpck_require__(73838); +const Template = __nccwpck_require__(51396); - Common.assertOptions(options, ['paddingRequired']); - options = { paddingRequired: true, ...options }; - Assert(typeof options.paddingRequired === 'boolean', 'paddingRequired must be boolean'); +const internals = { + renameDefaults: { + alias: false, // Keep old value in place + multiple: false, // Allow renaming multiple keys into the same target + override: false // Overrides an existing key + } +}; - return this.$_addRule({ name: 'dataUri', args: { options } }); - }, - validate(value, helpers, { options }) { - const matches = value.match(internals.dataUriRegex); +module.exports = Any.extend({ - if (matches) { - if (!matches[2]) { - return value; - } + type: '_keys', - if (matches[2] !== 'base64') { - return value; - } + properties: { - const base64regex = internals.base64Regex[options.paddingRequired].false; - if (base64regex.test(matches[3])) { - return value; - } - } + typeof: 'object' + }, - return helpers.error('string.dataUri'); - } - }, + flags: { - domain: { - method(options) { + unknown: { default: false } + }, - if (options) { - Common.assertOptions(options, ['allowFullyQualified', 'allowUnicode', 'maxDomainSegments', 'minDomainSegments', 'tlds']); - } + terms: { - const address = internals.addressOptions(options); - return this.$_addRule({ name: 'domain', args: { options }, address }); - }, - validate(value, helpers, args, { address }) { + dependencies: { init: null }, + keys: { init: null, manifest: { mapped: { from: 'schema', to: 'key' } } }, + patterns: { init: null }, + renames: { init: null } + }, - if (Domain.isValid(value, address)) { - return value; - } + args(schema, keys) { - return helpers.error('string.domain'); - } - }, + return schema.keys(keys); + }, - email: { - method(options = {}) { + validate(value, { schema, error, state, prefs }) { - Common.assertOptions(options, ['allowFullyQualified', 'allowUnicode', 'ignoreLength', 'maxDomainSegments', 'minDomainSegments', 'multiple', 'separator', 'tlds']); - Assert(options.multiple === undefined || typeof options.multiple === 'boolean', 'multiple option must be an boolean'); + if (!value || + typeof value !== schema.$_property('typeof') || + Array.isArray(value)) { - const address = internals.addressOptions(options); - const regex = new RegExp(`\\s*[${options.separator ? EscapeRegex(options.separator) : ','}]\\s*`); + return { value, errors: error('object.base', { type: schema.$_property('typeof') }) }; + } - return this.$_addRule({ name: 'email', args: { options }, regex, address }); - }, - validate(value, helpers, { options }, { regex, address }) { + // Skip if there are no other rules to test - const emails = options.multiple ? value.split(regex) : [value]; - const invalids = []; - for (const email of emails) { - if (!Email.isValid(email, address)) { - invalids.push(email); - } - } + if (!schema.$_terms.renames && + !schema.$_terms.dependencies && + !schema.$_terms.keys && // null allows any keys + !schema.$_terms.patterns && + !schema.$_terms.externals) { - if (!invalids.length) { - return value; - } + return; + } - return helpers.error('string.email', { value, invalids }); - } - }, + // Shallow clone value - guid: { - alias: 'uuid', - method(options = {}) { + value = internals.clone(value, prefs); + const errors = []; - Common.assertOptions(options, ['version', 'separator']); + // Rename keys - let versionNumbers = ''; + if (schema.$_terms.renames && + !internals.rename(schema, value, state, prefs, errors)) { - if (options.version) { - const versions = [].concat(options.version); + return { value, errors }; + } - Assert(versions.length >= 1, 'version must have at least 1 valid version specified'); - const set = new Set(); + // Anything allowed - for (let i = 0; i < versions.length; ++i) { - const version = versions[i]; - Assert(typeof version === 'string', 'version at position ' + i + ' must be a string'); - const versionNumber = internals.guidVersions[version.toLowerCase()]; - Assert(versionNumber, 'version at position ' + i + ' must be one of ' + Object.keys(internals.guidVersions).join(', ')); - Assert(!set.has(versionNumber), 'version at position ' + i + ' must not be a duplicate'); + if (!schema.$_terms.keys && // null allows any keys + !schema.$_terms.patterns && + !schema.$_terms.dependencies) { - versionNumbers += versionNumber; - set.add(versionNumber); - } - } + return { value, errors }; + } - Assert(internals.guidSeparators.has(options.separator), 'separator must be one of true, false, "-", or ":"'); - const separator = options.separator === undefined ? '[:-]?' : - options.separator === true ? '[:-]' : - options.separator === false ? '[]?' : `\\${options.separator}`; + // Defined keys - const regex = new RegExp(`^([\\[{\\(]?)[0-9A-F]{8}(${separator})[0-9A-F]{4}\\2?[${versionNumbers || '0-9A-F'}][0-9A-F]{3}\\2?[${versionNumbers ? '89AB' : '0-9A-F'}][0-9A-F]{3}\\2?[0-9A-F]{12}([\\]}\\)]?)$`, 'i'); + const unprocessed = new Set(Object.keys(value)); - return this.$_addRule({ name: 'guid', args: { options }, regex }); - }, - validate(value, helpers, args, { regex }) { + if (schema.$_terms.keys) { + const ancestors = [value, ...state.ancestors]; - const results = regex.exec(value); + for (const child of schema.$_terms.keys) { + const key = child.key; + const item = value[key]; - if (!results) { - return helpers.error('string.guid'); + unprocessed.delete(key); + + const localState = state.localize([...state.path, key], ancestors, child); + const result = child.schema.$_validate(item, localState, prefs); + + if (result.errors) { + if (prefs.abortEarly) { + return { value, errors: result.errors }; + } + + if (result.value !== undefined) { + value[key] = result.value; + } + + errors.push(...result.errors); + } + else if (child.schema._flags.result === 'strip' || + result.value === undefined && item !== undefined) { + + delete value[key]; + } + else if (result.value !== undefined) { + value[key] = result.value; } + } + } - // Matching braces + // Unknown keys - if (internals.guidBrackets[results[1]] !== results[results.length - 1]) { - return helpers.error('string.guid'); - } + if (unprocessed.size || + schema._flags._hasPatternMatch) { - return value; + const early = internals.unknown(schema, value, unprocessed, errors, state, prefs); + if (early) { + return early; } - }, + } - hex: { - method(options = {}) { + // Validate dependencies - Common.assertOptions(options, ['byteAligned']); + if (schema.$_terms.dependencies) { + for (const dep of schema.$_terms.dependencies) { + if (dep.key && + dep.key.resolve(value, state, prefs, null, { shadow: false }) === undefined) { - options = { byteAligned: false, ...options }; - Assert(typeof options.byteAligned === 'boolean', 'byteAligned must be boolean'); + continue; + } - return this.$_addRule({ name: 'hex', args: { options } }); - }, - validate(value, helpers, { options }) { + const failed = internals.dependencies[dep.rel](schema, dep, value, state, prefs); + if (failed) { + const report = schema.$_createError(failed.code, value, failed.context, state, prefs); + if (prefs.abortEarly) { + return { value, errors: report }; + } - if (!internals.hexRegex.test(value)) { - return helpers.error('string.hex'); + errors.push(report); } + } + } - if (options.byteAligned && - value.length % 2 !== 0) { + return { value, errors }; + }, - return helpers.error('string.hexAlign'); - } + rules: { - return value; + and: { + method(...peers /*, [options] */) { + + Common.verifyFlat(peers, 'and'); + + return internals.dependency(this, 'and', null, peers); } }, - hostname: { - method() { - - return this.$_addRule('hostname'); - }, - validate(value, helpers) { + append: { + method(schema) { - if (Domain.isValid(value, { minDomainSegments: 1 }) || - internals.ipRegex.test(value)) { + if (schema === null || + schema === undefined || + Object.keys(schema).length === 0) { - return value; + return this; } - return helpers.error('string.hostname'); + return this.keys(schema); } }, - insensitive: { - method() { + assert: { + method(subject, schema, message) { - return this.$_setFlag('insensitive', true); - } - }, + if (!Template.isTemplate(subject)) { + subject = Compile.ref(subject); + } - ip: { - method(options = {}) { + Assert(message === undefined || typeof message === 'string', 'Message must be a string'); - Common.assertOptions(options, ['cidr', 'version']); + schema = this.$_compile(schema, { appendPath: true }); - const { cidr, versions, regex } = Ip.regex(options); - const version = options.version ? versions : undefined; - return this.$_addRule({ name: 'ip', args: { options: { cidr, version } }, regex }); + const obj = this.$_addRule({ name: 'assert', args: { subject, schema, message } }); + obj.$_mutateRegister(subject); + obj.$_mutateRegister(schema); + return obj; }, - validate(value, helpers, { options }, { regex }) { + validate(value, { error, prefs, state }, { subject, schema, message }) { - if (regex.test(value)) { + const about = subject.resolve(value, state, prefs); + const path = Ref.isRef(subject) ? subject.absolute(state) : []; + if (schema.$_match(about, state.localize(path, [value, ...state.ancestors], schema), prefs)) { return value; } - if (options.version) { - return helpers.error('string.ipVersion', { value, cidr: options.cidr, version: options.version }); - } - - return helpers.error('string.ip', { value, cidr: options.cidr }); - } + return error('object.assert', { subject, message }); + }, + args: ['subject', 'schema', 'message'], + multi: true }, - isoDate: { - method() { + instance: { + method(constructor, name) { - return this.$_addRule('isoDate'); + Assert(typeof constructor === 'function', 'constructor must be a function'); + + name = name || constructor.name; + + return this.$_addRule({ name: 'instance', args: { constructor, name } }); }, - validate(value, { error }) { + validate(value, helpers, { constructor, name }) { - if (internals.isoDate(value)) { + if (value instanceof constructor) { return value; } - return error('string.isoDate'); - } + return helpers.error('object.instance', { type: name, value }); + }, + args: ['constructor', 'name'] }, - isoDuration: { - method() { + keys: { + method(schema) { - return this.$_addRule('isoDuration'); - }, - validate(value, helpers) { + Assert(schema === undefined || typeof schema === 'object', 'Object schema must be a valid object'); + Assert(!Common.isSchema(schema), 'Object schema cannot be a joi schema'); - if (internals.isoDurationRegex.test(value)) { - return value; + const obj = this.clone(); + + if (!schema) { // Allow all + obj.$_terms.keys = null; + } + else if (!Object.keys(schema).length) { // Allow none + obj.$_terms.keys = new internals.Keys(); + } + else { + obj.$_terms.keys = obj.$_terms.keys ? obj.$_terms.keys.filter((child) => !schema.hasOwnProperty(child.key)) : new internals.Keys(); + for (const key in schema) { + Common.tryWithPath(() => obj.$_terms.keys.push({ key, schema: this.$_compile(schema[key]) }), key); + } } - return helpers.error('string.isoDuration'); + return obj.$_mutateRebuild(); } }, length: { - method(limit, encoding) { + method(limit) { - return internals.length(this, 'length', limit, '=', encoding); + return this.$_addRule({ name: 'length', args: { limit }, operator: '=' }); }, - validate(value, helpers, { limit, encoding }, { name, operator, args }) { + validate(value, helpers, { limit }, { name, operator, args }) { - const length = encoding ? Buffer && Buffer.byteLength(value, encoding) : value.length; // $lab:coverage:ignore$ - if (Common.compare(length, limit, operator)) { + if (Common.compare(Object.keys(value).length, limit, operator)) { return value; } - return helpers.error('string.' + name, { limit: args.limit, value, encoding }); + return helpers.error('object.' + name, { limit: args.limit, value }); }, args: [ { @@ -67179,437 +67096,218 @@ module.exports = Any.extend({ ref: true, assert: Common.limit, message: 'must be a positive integer' - }, - 'encoding' + } ] }, - lowercase: { - method() { + max: { + method(limit) { - return this.case('lower'); + return this.$_addRule({ name: 'max', method: 'length', args: { limit }, operator: '<=' }); } }, - max: { - method(limit, encoding) { + min: { + method(limit) { - return internals.length(this, 'max', limit, '<=', encoding); - }, - args: ['limit', 'encoding'] + return this.$_addRule({ name: 'min', method: 'length', args: { limit }, operator: '>=' }); + } }, - min: { - method(limit, encoding) { + nand: { + method(...peers /*, [options] */) { - return internals.length(this, 'min', limit, '>=', encoding); - }, - args: ['limit', 'encoding'] + Common.verifyFlat(peers, 'nand'); + + return internals.dependency(this, 'nand', null, peers); + } }, - normalize: { - method(form = 'NFC') { + or: { + method(...peers /*, [options] */) { - Assert(internals.normalizationForms.includes(form), 'normalization form must be one of ' + internals.normalizationForms.join(', ')); + Common.verifyFlat(peers, 'or'); - return this.$_addRule({ name: 'normalize', args: { form } }); - }, - validate(value, { error }, { form }) { + return internals.dependency(this, 'or', null, peers); + } + }, - if (value === value.normalize(form)) { - return value; - } + oxor: { + method(...peers /*, [options] */) { - return error('string.normalize', { value, form }); - }, - convert: true + return internals.dependency(this, 'oxor', null, peers); + } }, pattern: { - alias: 'regex', - method(regex, options = {}) { - - Assert(regex instanceof RegExp, 'regex must be a RegExp'); - Assert(!regex.flags.includes('g') && !regex.flags.includes('y'), 'regex should not use global or sticky mode'); + method(pattern, schema, options = {}) { - if (typeof options === 'string') { - options = { name: options }; + const isRegExp = pattern instanceof RegExp; + if (!isRegExp) { + pattern = this.$_compile(pattern, { appendPath: true }); } - Common.assertOptions(options, ['invert', 'name']); - - const errorCode = ['string.pattern', options.invert ? '.invert' : '', options.name ? '.name' : '.base'].join(''); - return this.$_addRule({ name: 'pattern', args: { regex, options }, errorCode }); - }, - validate(value, helpers, { regex, options }, { errorCode }) { - - const patternMatch = regex.test(value); + Assert(schema !== undefined, 'Invalid rule'); + Common.assertOptions(options, ['fallthrough', 'matches']); - if (patternMatch ^ options.invert) { - return value; + if (isRegExp) { + Assert(!pattern.flags.includes('g') && !pattern.flags.includes('y'), 'pattern should not use global or sticky mode'); } - return helpers.error(errorCode, { name: options.name, regex, value }); - }, - args: ['regex', 'options'], - multi: true - }, + schema = this.$_compile(schema, { appendPath: true }); - replace: { - method(pattern, replacement) { + const obj = this.clone(); + obj.$_terms.patterns = obj.$_terms.patterns || []; + const config = { [isRegExp ? 'regex' : 'schema']: pattern, rule: schema }; + if (options.matches) { + config.matches = this.$_compile(options.matches); + if (config.matches.type !== 'array') { + config.matches = config.matches.$_root.array().items(config.matches); + } - if (typeof pattern === 'string') { - pattern = new RegExp(EscapeRegex(pattern), 'g'); + obj.$_mutateRegister(config.matches); + obj.$_setFlag('_hasPatternMatch', true, { clone: false }); } - Assert(pattern instanceof RegExp, 'pattern must be a RegExp'); - Assert(typeof replacement === 'string', 'replacement must be a String'); - - const obj = this.clone(); - - if (!obj.$_terms.replacements) { - obj.$_terms.replacements = []; + if (options.fallthrough) { + config.fallthrough = true; } - obj.$_terms.replacements.push({ pattern, replacement }); + obj.$_terms.patterns.push(config); + obj.$_mutateRegister(schema); return obj; } }, - token: { + ref: { method() { - return this.$_addRule('token'); + return this.$_addRule('ref'); }, validate(value, helpers) { - if (/^\w+$/.test(value)) { - return value; - } - - return helpers.error('string.token'); - } - }, - - trim: { - method(enabled = true) { - - Assert(typeof enabled === 'boolean', 'enabled must be a boolean'); - - return this.$_addRule({ name: 'trim', args: { enabled } }); - }, - validate(value, helpers, { enabled }) { - - if (!enabled || - value === value.trim()) { - + if (Ref.isRef(value)) { return value; } - return helpers.error('string.trim'); - }, - convert: true - }, - - truncate: { - method(enabled = true) { - - Assert(typeof enabled === 'boolean', 'enabled must be a boolean'); - - return this.$_setFlag('truncate', enabled); + return helpers.error('object.refType', { value }); } }, - uppercase: { + regex: { method() { - return this.case('upper'); - } - }, - - uri: { - method(options = {}) { - - Common.assertOptions(options, ['allowRelative', 'allowQuerySquareBrackets', 'domain', 'relativeOnly', 'scheme']); - - if (options.domain) { - Common.assertOptions(options.domain, ['allowFullyQualified', 'allowUnicode', 'maxDomainSegments', 'minDomainSegments', 'tlds']); - } - - const { regex, scheme } = Uri.regex(options); - const domain = options.domain ? internals.addressOptions(options.domain) : null; - return this.$_addRule({ name: 'uri', args: { options }, regex, domain, scheme }); + return this.$_addRule('regex'); }, - validate(value, helpers, { options }, { regex, domain, scheme }) { - - if (['http:/', 'https:/'].includes(value)) { // scheme:/ is technically valid but makes no sense - return helpers.error('string.uri'); - } - - const match = regex.exec(value); - if (match) { - const matched = match[1] || match[2]; - if (domain && - (!options.allowRelative || matched) && - !Domain.isValid(matched, domain)) { - - return helpers.error('string.domain', { value: matched }); - } - - return value; - } - - if (options.relativeOnly) { - return helpers.error('string.uriRelativeOnly'); - } - - if (options.scheme) { - return helpers.error('string.uriCustomScheme', { scheme, value }); - } - - return helpers.error('string.uri'); - } - } - }, - - manifest: { - - build(obj, desc) { - - if (desc.replacements) { - for (const { pattern, replacement } of desc.replacements) { - obj = obj.replace(pattern, replacement); - } - } - - return obj; - } - }, - - messages: { - 'string.alphanum': '{{#label}} must only contain alpha-numeric characters', - 'string.base': '{{#label}} must be a string', - 'string.base64': '{{#label}} must be a valid base64 string', - 'string.creditCard': '{{#label}} must be a credit card', - 'string.dataUri': '{{#label}} must be a valid dataUri string', - 'string.domain': '{{#label}} must contain a valid domain name', - 'string.email': '{{#label}} must be a valid email', - 'string.empty': '{{#label}} is not allowed to be empty', - 'string.guid': '{{#label}} must be a valid GUID', - 'string.hex': '{{#label}} must only contain hexadecimal characters', - 'string.hexAlign': '{{#label}} hex decoded representation must be byte aligned', - 'string.hostname': '{{#label}} must be a valid hostname', - 'string.ip': '{{#label}} must be a valid ip address with a {{#cidr}} CIDR', - 'string.ipVersion': '{{#label}} must be a valid ip address of one of the following versions {{#version}} with a {{#cidr}} CIDR', - 'string.isoDate': '{{#label}} must be in iso format', - 'string.isoDuration': '{{#label}} must be a valid ISO 8601 duration', - 'string.length': '{{#label}} length must be {{#limit}} characters long', - 'string.lowercase': '{{#label}} must only contain lowercase characters', - 'string.max': '{{#label}} length must be less than or equal to {{#limit}} characters long', - 'string.min': '{{#label}} length must be at least {{#limit}} characters long', - 'string.normalize': '{{#label}} must be unicode normalized in the {{#form}} form', - 'string.token': '{{#label}} must only contain alpha-numeric and underscore characters', - 'string.pattern.base': '{{#label}} with value {:[.]} fails to match the required pattern: {{#regex}}', - 'string.pattern.name': '{{#label}} with value {:[.]} fails to match the {{#name}} pattern', - 'string.pattern.invert.base': '{{#label}} with value {:[.]} matches the inverted pattern: {{#regex}}', - 'string.pattern.invert.name': '{{#label}} with value {:[.]} matches the inverted {{#name}} pattern', - 'string.trim': '{{#label}} must not have leading or trailing whitespace', - 'string.uri': '{{#label}} must be a valid uri', - 'string.uriCustomScheme': '{{#label}} must be a valid uri with a scheme matching the {{#scheme}} pattern', - 'string.uriRelativeOnly': '{{#label}} must be a valid relative uri', - 'string.uppercase': '{{#label}} must only contain uppercase characters' - } -}); - - -// Helpers - -internals.addressOptions = function (options) { - - if (!options) { - return options; - } - - // minDomainSegments - - Assert(options.minDomainSegments === undefined || - Number.isSafeInteger(options.minDomainSegments) && options.minDomainSegments > 0, 'minDomainSegments must be a positive integer'); - - // maxDomainSegments - - Assert(options.maxDomainSegments === undefined || - Number.isSafeInteger(options.maxDomainSegments) && options.maxDomainSegments > 0, 'maxDomainSegments must be a positive integer'); - - // tlds - - if (options.tlds === false) { - return options; - } - - if (options.tlds === true || - options.tlds === undefined) { - - Assert(internals.tlds, 'Built-in TLD list disabled'); - return Object.assign({}, options, internals.tlds); - } - - Assert(typeof options.tlds === 'object', 'tlds must be true, false, or an object'); - - const deny = options.tlds.deny; - if (deny) { - if (Array.isArray(deny)) { - options = Object.assign({}, options, { tlds: { deny: new Set(deny) } }); - } - - Assert(options.tlds.deny instanceof Set, 'tlds.deny must be an array, Set, or boolean'); - Assert(!options.tlds.allow, 'Cannot specify both tlds.allow and tlds.deny lists'); - internals.validateTlds(options.tlds.deny, 'tlds.deny'); - return options; - } - - const allow = options.tlds.allow; - if (!allow) { - return options; - } - - if (allow === true) { - Assert(internals.tlds, 'Built-in TLD list disabled'); - return Object.assign({}, options, internals.tlds); - } - - if (Array.isArray(allow)) { - options = Object.assign({}, options, { tlds: { allow: new Set(allow) } }); - } - - Assert(options.tlds.allow instanceof Set, 'tlds.allow must be an array, Set, or boolean'); - internals.validateTlds(options.tlds.allow, 'tlds.allow'); - return options; -}; - - -internals.validateTlds = function (set, source) { - - for (const tld of set) { - Assert(Domain.isValid(tld, { minDomainSegments: 1, maxDomainSegments: 1 }), `${source} must contain valid top level domain names`); - } -}; - - -internals.isoDate = function (value) { - - if (!Common.isIsoDate(value)) { - return null; - } - - if (/.*T.*[+-]\d\d$/.test(value)) { // Add missing trailing zeros to timeshift - value += '00'; - } - - const date = new Date(value); - if (isNaN(date.getTime())) { - return null; - } - - return date.toISOString(); -}; - - -internals.length = function (schema, name, limit, operator, encoding) { - - Assert(!encoding || Buffer && Buffer.isEncoding(encoding), 'Invalid encoding:', encoding); // $lab:coverage:ignore$ - - return schema.$_addRule({ name, method: 'length', args: { limit, encoding }, operator }); -}; - + validate(value, helpers) { -/***/ }), + if (value instanceof RegExp) { + return value; + } -/***/ 40971: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return helpers.error('object.regex', { value }); + } + }, -"use strict"; + rename: { + method(from, to, options = {}) { + Assert(typeof from === 'string' || from instanceof RegExp, 'Rename missing the from argument'); + Assert(typeof to === 'string' || to instanceof Template, 'Invalid rename to argument'); + Assert(to !== from, 'Cannot rename key to same name:', from); -const Assert = __nccwpck_require__(32718); + Common.assertOptions(options, ['alias', 'ignoreUndefined', 'override', 'multiple']); -const Any = __nccwpck_require__(9512); + const obj = this.clone(); + obj.$_terms.renames = obj.$_terms.renames || []; + for (const rename of obj.$_terms.renames) { + Assert(rename.from !== from, 'Cannot rename the same key multiple times'); + } -const internals = {}; + if (to instanceof Template) { + obj.$_mutateRegister(to); + } + obj.$_terms.renames.push({ + from, + to, + options: ApplyToDefaults(internals.renameDefaults, options) + }); -internals.Map = class extends Map { + return obj; + } + }, - slice() { + schema: { + method(type = 'any') { - return new internals.Map(this); - } -}; + return this.$_addRule({ name: 'schema', args: { type } }); + }, + validate(value, helpers, { type }) { + if (Common.isSchema(value) && + (type === 'any' || value.type === type)) { -module.exports = Any.extend({ + return value; + } - type: 'symbol', + return helpers.error('object.schema', { type }); + } + }, - terms: { + unknown: { + method(allow) { - map: { init: new internals.Map() } - }, + return this.$_setFlag('unknown', allow !== false); + } + }, - coerce: { - method(value, { schema, error }) { + with: { + method(key, peers, options = {}) { - const lookup = schema.$_terms.map.get(value); - if (lookup) { - value = lookup; + return internals.dependency(this, 'with', key, peers, options); } + }, - if (!schema._flags.only || - typeof value === 'symbol') { + without: { + method(key, peers, options = {}) { - return { value }; + return internals.dependency(this, 'without', key, peers, options); } + }, - return { value, errors: error('symbol.map', { map: schema.$_terms.map }) }; - } - }, + xor: { + method(...peers /*, [options] */) { - validate(value, { error }) { + Common.verifyFlat(peers, 'xor'); - if (typeof value !== 'symbol') { - return { value, errors: error('symbol.base') }; + return internals.dependency(this, 'xor', null, peers); + } } }, - rules: { - map: { - method(iterable) { - - if (iterable && - !iterable[Symbol.iterator] && - typeof iterable === 'object') { - - iterable = Object.entries(iterable); - } - - Assert(iterable && iterable[Symbol.iterator], 'Iterable must be an iterable or object'); + overrides: { - const obj = this.clone(); + default(value, options) { - const symbols = []; - for (const entry of iterable) { - Assert(entry && entry[Symbol.iterator], 'Entry must be an iterable'); - const [key, value] = entry; + if (value === undefined) { + value = Common.symbols.deepDefault; + } - Assert(typeof key !== 'object' && typeof key !== 'function' && typeof key !== 'symbol', 'Key must not be of type object, function, or Symbol'); - Assert(typeof value === 'symbol', 'Value must be a Symbol'); + return this.$_parent('default', value, options); + } + }, - obj.$_terms.map.set(key, value); - symbols.push(value); - } + rebuild(schema) { - return obj.valid(...symbols); + if (schema.$_terms.keys) { + const topo = new Topo.Sorter(); + for (const child of schema.$_terms.keys) { + Common.tryWithPath(() => topo.add(child, { after: child.schema.$_rootReferences(), group: child.key }), child.key); } + + schema.$_terms.keys = new internals.Keys(...topo.nodes); } }, @@ -67617,8 +67315,26 @@ module.exports = Any.extend({ build(obj, desc) { - if (desc.map) { - obj = obj.map(desc.map); + if (desc.keys) { + obj = obj.keys(desc.keys); + } + + if (desc.dependencies) { + for (const { rel, key = null, peers, options } of desc.dependencies) { + obj = internals.dependency(obj, rel, key, peers, options); + } + } + + if (desc.patterns) { + for (const { regex, schema, rule, fallthrough, matches } of desc.patterns) { + obj = obj.pattern(regex || schema, rule, { fallthrough, matches }); + } + } + + if (desc.renames) { + for (const { from, to, options } of desc.renames) { + obj = obj.rename(from, to, options); + } } return obj; @@ -67626,40949 +67342,41294 @@ module.exports = Any.extend({ }, messages: { - 'symbol.base': '{{#label}} must be a symbol', - 'symbol.map': '{{#label}} must be one of {{#map}}' + 'object.and': '{{#label}} contains {{#presentWithLabels}} without its required peers {{#missingWithLabels}}', + 'object.assert': '{{#label}} is invalid because {if(#subject.key, `"` + #subject.key + `" failed to ` + (#message || "pass the assertion test"), #message || "the assertion failed")}', + 'object.base': '{{#label}} must be of type {{#type}}', + 'object.instance': '{{#label}} must be an instance of {{:#type}}', + 'object.length': '{{#label}} must have {{#limit}} key{if(#limit == 1, "", "s")}', + 'object.max': '{{#label}} must have less than or equal to {{#limit}} key{if(#limit == 1, "", "s")}', + 'object.min': '{{#label}} must have at least {{#limit}} key{if(#limit == 1, "", "s")}', + 'object.missing': '{{#label}} must contain at least one of {{#peersWithLabels}}', + 'object.nand': '{{:#mainWithLabel}} must not exist simultaneously with {{#peersWithLabels}}', + 'object.oxor': '{{#label}} contains a conflict between optional exclusive peers {{#peersWithLabels}}', + 'object.pattern.match': '{{#label}} keys failed to match pattern requirements', + 'object.refType': '{{#label}} must be a Joi reference', + 'object.regex': '{{#label}} must be a RegExp object', + 'object.rename.multiple': '{{#label}} cannot rename {{:#from}} because multiple renames are disabled and another key was already renamed to {{:#to}}', + 'object.rename.override': '{{#label}} cannot rename {{:#from}} because override is disabled and target {{:#to}} exists', + 'object.schema': '{{#label}} must be a Joi schema of {{#type}} type', + 'object.unknown': '{{#label}} is not allowed', + 'object.with': '{{:#mainWithLabel}} missing required peer {{:#peerWithLabel}}', + 'object.without': '{{:#mainWithLabel}} conflict with forbidden peer {{:#peerWithLabel}}', + 'object.xor': '{{#label}} contains a conflict between exclusive peers {{#peersWithLabels}}' } }); -/***/ }), - -/***/ 91804: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -const Assert = __nccwpck_require__(32718); -const Clone = __nccwpck_require__(85578); -const Ignore = __nccwpck_require__(12887); -const Reach = __nccwpck_require__(18891); - -const Common = __nccwpck_require__(72448); -const Errors = __nccwpck_require__(69490); -const State = __nccwpck_require__(73634); - - -const internals = { - result: Symbol('result') -}; - +// Helpers -exports.entry = function (value, schema, prefs) { +internals.clone = function (value, prefs) { - let settings = Common.defaults; - if (prefs) { - Assert(prefs.warnings === undefined, 'Cannot override warnings preference in synchronous validation'); - Assert(prefs.artifacts === undefined, 'Cannot override artifacts preference in synchronous validation'); - settings = Common.preferences(Common.defaults, prefs); - } + // Object - const result = internals.entry(value, schema, settings); - Assert(!result.mainstay.externals.length, 'Schema with external rules must use validateAsync()'); - const outcome = { value: result.value }; + if (typeof value === 'object') { + if (prefs.nonEnumerables) { + return Clone(value, { shallow: true }); + } - if (result.error) { - outcome.error = result.error; + const clone = Object.create(Object.getPrototypeOf(value)); + Object.assign(clone, value); + return clone; } - if (result.mainstay.warnings.length) { - outcome.warning = Errors.details(result.mainstay.warnings); - } + // Function - if (result.mainstay.debug) { - outcome.debug = result.mainstay.debug; - } + const clone = function (...args) { - if (result.mainstay.artifacts) { - outcome.artifacts = result.mainstay.artifacts; - } + return value.apply(this, args); + }; - return outcome; + clone.prototype = Clone(value.prototype); + Object.defineProperty(clone, 'name', { value: value.name, writable: false }); + Object.defineProperty(clone, 'length', { value: value.length, writable: false }); + Object.assign(clone, value); + return clone; }; -exports.entryAsync = async function (value, schema, prefs) { +internals.dependency = function (schema, rel, key, peers, options) { - let settings = Common.defaults; - if (prefs) { - settings = Common.preferences(Common.defaults, prefs); - } + Assert(key === null || typeof key === 'string', rel, 'key must be a strings'); - const result = internals.entry(value, schema, settings); - const mainstay = result.mainstay; - if (result.error) { - if (mainstay.debug) { - result.error.debug = mainstay.debug; - } + // Extract options from peers array - throw result.error; + if (!options) { + options = peers.length > 1 && typeof peers[peers.length - 1] === 'object' ? peers.pop() : {}; } - if (mainstay.externals.length) { - let root = result.value; - for (const { method, path, label } of mainstay.externals) { - let node = root; - let key; - let parent; - - if (path.length) { - key = path[path.length - 1]; - parent = Reach(root, path.slice(0, -1)); - node = parent[key]; - } - - try { - const output = await method(node, { prefs }); - if (output === undefined || - output === node) { - - continue; - } - - if (parent) { - parent[key] = output; - } - else { - root = output; - } - } - catch (err) { - if (settings.errors.label) { - err.message += ` (${label})`; // Change message to include path - } - - throw err; - } - } + Common.assertOptions(options, ['separator']); - result.value = root; - } + peers = [].concat(peers); - if (!settings.warnings && - !settings.debug && - !settings.artifacts) { + // Cast peer paths - return result.value; + const separator = Common.default(options.separator, '.'); + const paths = []; + for (const peer of peers) { + Assert(typeof peer === 'string', rel, 'peers must be strings'); + paths.push(Compile.ref(peer, { separator, ancestor: 0, prefix: false })); } - const outcome = { value: result.value }; - if (mainstay.warnings.length) { - outcome.warning = Errors.details(mainstay.warnings); - } + // Cast key - if (mainstay.debug) { - outcome.debug = mainstay.debug; + if (key !== null) { + key = Compile.ref(key, { separator, ancestor: 0, prefix: false }); } - if (mainstay.artifacts) { - outcome.artifacts = mainstay.artifacts; - } + // Add rule - return outcome; + const obj = schema.clone(); + obj.$_terms.dependencies = obj.$_terms.dependencies || []; + obj.$_terms.dependencies.push(new internals.Dependency(rel, key, paths, peers)); + return obj; }; -internals.entry = function (value, schema, prefs) { - - // Prepare state - - const { tracer, cleanup } = internals.tracer(schema, prefs); - const debug = prefs.debug ? [] : null; - const links = schema._ids._schemaChain ? new Map() : null; - const mainstay = { externals: [], warnings: [], tracer, debug, links }; - const schemas = schema._ids._schemaChain ? [{ schema }] : null; - const state = new State([], [], { mainstay, schemas }); - - // Validate value - - const result = exports.validate(value, schema, state, prefs); - - // Process value and errors +internals.dependencies = { - if (cleanup) { - schema.$_root.untrace(); - } + and(schema, dep, value, state, prefs) { - const error = Errors.process(result.errors, value, prefs); - return { value: result.value, error, mainstay }; -}; + const missing = []; + const present = []; + const count = dep.peers.length; + for (const peer of dep.peers) { + if (peer.resolve(value, state, prefs, null, { shadow: false }) === undefined) { + missing.push(peer.key); + } + else { + present.push(peer.key); + } + } + if (missing.length !== count && + present.length !== count) { -internals.tracer = function (schema, prefs) { + return { + code: 'object.and', + context: { + present, + presentWithLabels: internals.keysToLabels(schema, present), + missing, + missingWithLabels: internals.keysToLabels(schema, missing) + } + }; + } + }, - if (schema.$_root._tracer) { - return { tracer: schema.$_root._tracer._register(schema) }; - } + nand(schema, dep, value, state, prefs) { - if (prefs.debug) { - Assert(schema.$_root.trace, 'Debug mode not supported'); - return { tracer: schema.$_root.trace()._register(schema), cleanup: true }; - } + const present = []; + for (const peer of dep.peers) { + if (peer.resolve(value, state, prefs, null, { shadow: false }) !== undefined) { + present.push(peer.key); + } + } - return { tracer: internals.ignore }; -}; + if (present.length !== dep.peers.length) { + return; + } + const main = dep.paths[0]; + const values = dep.paths.slice(1); + return { + code: 'object.nand', + context: { + main, + mainWithLabel: internals.keysToLabels(schema, main), + peers: values, + peersWithLabels: internals.keysToLabels(schema, values) + } + }; + }, -exports.validate = function (value, schema, state, prefs, overrides = {}) { + or(schema, dep, value, state, prefs) { - if (schema.$_terms.whens) { - schema = schema._generate(value, state, prefs).schema; - } + for (const peer of dep.peers) { + if (peer.resolve(value, state, prefs, null, { shadow: false }) !== undefined) { + return; + } + } - // Setup state and settings + return { + code: 'object.missing', + context: { + peers: dep.paths, + peersWithLabels: internals.keysToLabels(schema, dep.paths) + } + }; + }, - if (schema._preferences) { - prefs = internals.prefs(schema, prefs); - } + oxor(schema, dep, value, state, prefs) { - // Cache + const present = []; + for (const peer of dep.peers) { + if (peer.resolve(value, state, prefs, null, { shadow: false }) !== undefined) { + present.push(peer.key); + } + } - if (schema._cache && - prefs.cache) { + if (!present.length || + present.length === 1) { - const result = schema._cache.get(value); - state.mainstay.tracer.debug(state, 'validate', 'cached', !!result); - if (result) { - return result; + return; } - } - // Helpers - - const createError = (code, local, localState) => schema.$_createError(code, value, local, localState || state, prefs); - const helpers = { - original: value, - prefs, - schema, - state, - error: createError, - errorsArray: internals.errorsArray, - warn: (code, local, localState) => state.mainstay.warnings.push(createError(code, local, localState)), - message: (messages, local) => schema.$_createError('custom', value, local, state, prefs, { messages }) - }; + const context = { peers: dep.paths, peersWithLabels: internals.keysToLabels(schema, dep.paths) }; + context.present = present; + context.presentWithLabels = internals.keysToLabels(schema, present); + return { code: 'object.oxor', context }; + }, - // Prepare + with(schema, dep, value, state, prefs) { - state.mainstay.tracer.entry(schema, state); + for (const peer of dep.peers) { + if (peer.resolve(value, state, prefs, null, { shadow: false }) === undefined) { + return { + code: 'object.with', + context: { + main: dep.key.key, + mainWithLabel: internals.keysToLabels(schema, dep.key.key), + peer: peer.key, + peerWithLabel: internals.keysToLabels(schema, peer.key) + } + }; + } + } + }, - const def = schema._definition; - if (def.prepare && - value !== undefined && - prefs.convert) { + without(schema, dep, value, state, prefs) { - const prepared = def.prepare(value, helpers); - if (prepared) { - state.mainstay.tracer.value(state, 'prepare', value, prepared.value); - if (prepared.errors) { - return internals.finalize(prepared.value, [].concat(prepared.errors), helpers); // Prepare error always aborts early + for (const peer of dep.peers) { + if (peer.resolve(value, state, prefs, null, { shadow: false }) !== undefined) { + return { + code: 'object.without', + context: { + main: dep.key.key, + mainWithLabel: internals.keysToLabels(schema, dep.key.key), + peer: peer.key, + peerWithLabel: internals.keysToLabels(schema, peer.key) + } + }; } - - value = prepared.value; } - } - - // Type coercion + }, - if (def.coerce && - value !== undefined && - prefs.convert && - (!def.coerce.from || def.coerce.from.includes(typeof value))) { + xor(schema, dep, value, state, prefs) { - const coerced = def.coerce.method(value, helpers); - if (coerced) { - state.mainstay.tracer.value(state, 'coerced', value, coerced.value); - if (coerced.errors) { - return internals.finalize(coerced.value, [].concat(coerced.errors), helpers); // Coerce error always aborts early + const present = []; + for (const peer of dep.peers) { + if (peer.resolve(value, state, prefs, null, { shadow: false }) !== undefined) { + present.push(peer.key); } + } - value = coerced.value; + if (present.length === 1) { + return; } + + const context = { peers: dep.paths, peersWithLabels: internals.keysToLabels(schema, dep.paths) }; + if (present.length === 0) { + return { code: 'object.missing', context }; + } + + context.present = present; + context.presentWithLabels = internals.keysToLabels(schema, present); + return { code: 'object.xor', context }; } +}; - // Empty value - const empty = schema._flags.empty; - if (empty && - empty.$_match(internals.trim(value, schema), state.nest(empty), Common.defaults)) { +internals.keysToLabels = function (schema, keys) { - state.mainstay.tracer.value(state, 'empty', value, undefined); - value = undefined; + if (Array.isArray(keys)) { + return keys.map((key) => schema.$_mapLabels(key)); } - // Presence requirements (required, optional, forbidden) + return schema.$_mapLabels(keys); +}; - const presence = overrides.presence || schema._flags.presence || (schema._flags._endedSwitch ? null : prefs.presence); - if (value === undefined) { - if (presence === 'forbidden') { - return internals.finalize(value, null, helpers); - } - if (presence === 'required') { - return internals.finalize(value, [schema.$_createError('any.required', value, null, state, prefs)], helpers); - } +internals.rename = function (schema, value, state, prefs, errors) { - if (presence === 'optional') { - if (schema._flags.default !== Common.symbols.deepDefault) { - return internals.finalize(value, null, helpers); - } + const renamed = {}; + for (const rename of schema.$_terms.renames) { + const matches = []; + const pattern = typeof rename.from !== 'string'; - state.mainstay.tracer.value(state, 'default', value, {}); - value = {}; - } - } - else if (presence === 'forbidden') { - return internals.finalize(value, [schema.$_createError('any.unknown', value, null, state, prefs)], helpers); - } + if (!pattern) { + if (Object.prototype.hasOwnProperty.call(value, rename.from) && + (value[rename.from] !== undefined || !rename.options.ignoreUndefined)) { - // Allowed values + matches.push(rename); + } + } + else { + for (const from in value) { + if (value[from] === undefined && + rename.options.ignoreUndefined) { - const errors = []; + continue; + } - if (schema._valids) { - const match = schema._valids.get(value, state, prefs, schema._flags.insensitive); - if (match) { - if (prefs.convert) { - state.mainstay.tracer.value(state, 'valids', value, match.value); - value = match.value; - } + if (from === rename.to) { + continue; + } - state.mainstay.tracer.filter(schema, state, 'valid', match); - return internals.finalize(value, null, helpers); - } + const match = rename.from.exec(from); + if (!match) { + continue; + } - if (schema._flags.only) { - const report = schema.$_createError('any.only', value, { valids: schema._valids.values({ display: true }) }, state, prefs); - if (prefs.abortEarly) { - return internals.finalize(value, [report], helpers); + matches.push({ from, to: rename.to, match }); } - - errors.push(report); } - } - // Denied values + for (const match of matches) { + const from = match.from; + let to = match.to; + if (to instanceof Template) { + to = to.render(value, state, prefs, match.match); + } - if (schema._invalids) { - const match = schema._invalids.get(value, state, prefs, schema._flags.insensitive); - if (match) { - state.mainstay.tracer.filter(schema, state, 'invalid', match); - const report = schema.$_createError('any.invalid', value, { invalids: schema._invalids.values({ display: true }) }, state, prefs); - if (prefs.abortEarly) { - return internals.finalize(value, [report], helpers); + if (from === to) { + continue; } - errors.push(report); - } - } + if (!rename.options.multiple && + renamed[to]) { - // Base type + errors.push(schema.$_createError('object.rename.multiple', value, { from, to, pattern }, state, prefs)); + if (prefs.abortEarly) { + return false; + } + } - if (def.validate) { - const base = def.validate(value, helpers); - if (base) { - state.mainstay.tracer.value(state, 'base', value, base.value); - value = base.value; + if (Object.prototype.hasOwnProperty.call(value, to) && + !rename.options.override && + !renamed[to]) { - if (base.errors) { - if (!Array.isArray(base.errors)) { - errors.push(base.errors); - return internals.finalize(value, errors, helpers); // Base error always aborts early + errors.push(schema.$_createError('object.rename.override', value, { from, to, pattern }, state, prefs)); + if (prefs.abortEarly) { + return false; } + } - if (base.errors.length) { - errors.push(...base.errors); - return internals.finalize(value, errors, helpers); // Base error always aborts early - } + if (value[from] === undefined) { + delete value[to]; + } + else { + value[to] = value[from]; } - } - } - // Validate tests + renamed[to] = true; - if (!schema._rules.length) { - return internals.finalize(value, errors, helpers); + if (!rename.options.alias) { + delete value[from]; + } + } } - return internals.rules(value, errors, helpers); + return true; }; -internals.rules = function (value, errors, helpers) { +internals.unknown = function (schema, value, unprocessed, errors, state, prefs) { - const { schema, state, prefs } = helpers; + if (schema.$_terms.patterns) { + let hasMatches = false; + const matches = schema.$_terms.patterns.map((pattern) => { - for (const rule of schema._rules) { - const definition = schema._definition.rules[rule.method]; + if (pattern.matches) { + hasMatches = true; + return []; + } + }); - // Skip rules that are also applied in coerce step + const ancestors = [value, ...state.ancestors]; - if (definition.convert && - prefs.convert) { + for (const key of unprocessed) { + const item = value[key]; + const path = [...state.path, key]; - state.mainstay.tracer.log(schema, state, 'rule', rule.name, 'full'); - continue; - } + for (let i = 0; i < schema.$_terms.patterns.length; ++i) { + const pattern = schema.$_terms.patterns[i]; + if (pattern.regex) { + const match = pattern.regex.test(key); + state.mainstay.tracer.debug(state, 'rule', `pattern.${i}`, match ? 'pass' : 'error'); + if (!match) { + continue; + } + } + else { + if (!pattern.schema.$_match(key, state.nest(pattern.schema, `pattern.${i}`), prefs)) { + continue; + } + } - // Resolve references + unprocessed.delete(key); - let ret; - let args = rule.args; - if (rule._resolve.length) { - args = Object.assign({}, args); // Shallow copy - for (const key of rule._resolve) { - const resolver = definition.argsByName.get(key); + const localState = state.localize(path, ancestors, { schema: pattern.rule, key }); + const result = pattern.rule.$_validate(item, localState, prefs); + if (result.errors) { + if (prefs.abortEarly) { + return { value, errors: result.errors }; + } - const resolved = args[key].resolve(value, state, prefs); - const normalized = resolver.normalize ? resolver.normalize(resolved) : resolved; + errors.push(...result.errors); + } - const invalid = Common.validateArg(normalized, null, resolver); - if (invalid) { - ret = schema.$_createError('any.ref', resolved, { arg: key, ref: args[key], reason: invalid }, state, prefs); + if (pattern.matches) { + matches[i].push(key); + } + + value[key] = result.value; + if (!pattern.fallthrough) { break; } + } + } - args[key] = normalized; + // Validate pattern matches rules + + if (hasMatches) { + for (let i = 0; i < matches.length; ++i) { + const match = matches[i]; + if (!match) { + continue; + } + + const stpm = schema.$_terms.patterns[i].matches; + const localState = state.localize(state.path, ancestors, stpm); + const result = stpm.$_validate(match, localState, prefs); + if (result.errors) { + const details = Errors.details(result.errors, { override: false }); + details.matches = match; + const report = schema.$_createError('object.pattern.match', value, details, state, prefs); + if (prefs.abortEarly) { + return { value, errors: report }; + } + + errors.push(report); + } } } + } - // Test rule + if (!unprocessed.size || + !schema.$_terms.keys && !schema.$_terms.patterns) { // If no keys or patterns specified, unknown keys allowed - ret = ret || definition.validate(value, helpers, args, rule); // Use ret if already set to reference error + return; + } - const result = internals.rule(ret, rule); - if (result.errors) { - state.mainstay.tracer.log(schema, state, 'rule', rule.name, 'error'); + if (prefs.stripUnknown && !schema._flags.unknown || + prefs.skipFunctions) { - if (rule.warn) { - state.mainstay.warnings.push(...result.errors); - continue; + const stripUnknown = prefs.stripUnknown ? (prefs.stripUnknown === true ? true : !!prefs.stripUnknown.objects) : false; + + for (const key of unprocessed) { + if (stripUnknown) { + delete value[key]; + unprocessed.delete(key); + } + else if (typeof value[key] === 'function') { + unprocessed.delete(key); } + } + } + const forbidUnknown = !Common.default(schema._flags.unknown, prefs.allowUnknown); + if (forbidUnknown) { + for (const unprocessedKey of unprocessed) { + const localState = state.localize([...state.path, unprocessedKey], []); + const report = schema.$_createError('object.unknown', value[unprocessedKey], { child: unprocessedKey }, localState, prefs, { flags: false }); if (prefs.abortEarly) { - return internals.finalize(value, result.errors, helpers); + return { value, errors: report }; } - errors.push(...result.errors); - } - else { - state.mainstay.tracer.log(schema, state, 'rule', rule.name, 'pass'); - state.mainstay.tracer.value(state, 'rule', value, result.value, rule.name); - value = result.value; + errors.push(report); } } - - return internals.finalize(value, errors, helpers); }; -internals.rule = function (ret, rule) { - - if (ret instanceof Errors.Report) { - internals.error(ret, rule); - return { errors: [ret], value: null }; - } +internals.Dependency = class { - if (Array.isArray(ret) && - ret[Common.symbols.errors]) { + constructor(rel, key, peers, paths) { - ret.forEach((report) => internals.error(report, rule)); - return { errors: ret, value: null }; + this.rel = rel; + this.key = key; + this.peers = peers; + this.paths = paths; } - return { errors: null, value: ret }; -}; + describe() { + const desc = { + rel: this.rel, + peers: this.paths + }; -internals.error = function (report, rule) { + if (this.key !== null) { + desc.key = this.key.key; + } - if (rule.message) { - report._setTemplate(rule.message); - } + if (this.peers[0].separator !== '.') { + desc.options = { separator: this.peers[0].separator }; + } - return report; + return desc; + } }; -internals.finalize = function (value, errors, helpers) { +internals.Keys = class extends Array { - errors = errors || []; - const { schema, state, prefs } = helpers; + concat(source) { - // Failover value + const result = this.slice(); - if (errors.length) { - const failover = internals.default('failover', undefined, errors, helpers); - if (failover !== undefined) { - state.mainstay.tracer.value(state, 'failover', value, failover); - value = failover; - errors = []; + const keys = new Map(); + for (let i = 0; i < result.length; ++i) { + keys.set(result[i].key, i); } - } - - // Error override - - if (errors.length && - schema._flags.error) { - if (typeof schema._flags.error === 'function') { - errors = schema._flags.error(errors); - if (!Array.isArray(errors)) { - errors = [errors]; + for (const item of source) { + const key = item.key; + const pos = keys.get(key); + if (pos !== undefined) { + result[pos] = { key, schema: result[pos].schema.concat(item.schema) }; } - - for (const error of errors) { - Assert(error instanceof Error || error instanceof Errors.Report, 'error() must return an Error object'); + else { + result.push(item); } } - else { - errors = [schema._flags.error]; - } + + return result; } +}; - // Default - if (value === undefined) { - const defaulted = internals.default('default', value, errors, helpers); - state.mainstay.tracer.value(state, 'default', value, defaulted); - value = defaulted; - } +/***/ }), - // Cast +/***/ 69869: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (schema._flags.cast && - value !== undefined) { +"use strict"; - const caster = schema._definition.cast[schema._flags.cast]; - if (caster.from(value)) { - const casted = caster.to(value, helpers); - state.mainstay.tracer.value(state, 'cast', value, casted, schema._flags.cast); - value = casted; - } - } - // Externals +const Assert = __nccwpck_require__(32718); - if (schema.$_terms.externals && - prefs.externals && - prefs._externals !== false) { // Disabled for matching +const Any = __nccwpck_require__(9512); +const Common = __nccwpck_require__(72448); +const Compile = __nccwpck_require__(3038); +const Errors = __nccwpck_require__(69490); - for (const { method } of schema.$_terms.externals) { - state.mainstay.externals.push({ method, path: state.path, label: Errors.label(schema._flags, state, prefs) }); - } - } - // Result +const internals = {}; - const result = { value, errors: errors.length ? errors : null }; - if (schema._flags.result) { - result.value = schema._flags.result === 'strip' ? undefined : /* raw */ helpers.original; - state.mainstay.tracer.value(state, schema._flags.result, value, result.value); - state.shadow(value, schema._flags.result); - } +module.exports = Any.extend({ - // Cache + type: 'link', - if (schema._cache && - prefs.cache !== false && - !schema._refs.length) { + properties: { + schemaChain: true + }, - schema._cache.set(helpers.original, result); - } + terms: { - // Artifacts + link: { init: null, manifest: 'single', register: false } + }, - if (value !== undefined && - !result.errors && - schema._flags.artifact !== undefined) { + args(schema, ref) { - state.mainstay.artifacts = state.mainstay.artifacts || new Map(); - if (!state.mainstay.artifacts.has(schema._flags.artifact)) { - state.mainstay.artifacts.set(schema._flags.artifact, []); - } + return schema.ref(ref); + }, - state.mainstay.artifacts.get(schema._flags.artifact).push(state.path); - } + validate(value, { schema, state, prefs }) { - return result; -}; + Assert(schema.$_terms.link, 'Uninitialized link schema'); + const linked = internals.generate(schema, value, state, prefs); + const ref = schema.$_terms.link[0].ref; + return linked.$_validate(value, state.nest(linked, `link:${ref.display}:${linked.type}`), prefs); + }, -internals.prefs = function (schema, prefs) { + generate(schema, value, state, prefs) { - const isDefaultOptions = prefs === Common.defaults; - if (isDefaultOptions && - schema._preferences[Common.symbols.prefs]) { + return internals.generate(schema, value, state, prefs); + }, - return schema._preferences[Common.symbols.prefs]; - } + rules: { - prefs = Common.preferences(prefs, schema._preferences); - if (isDefaultOptions) { - schema._preferences[Common.symbols.prefs] = prefs; - } + ref: { + method(ref) { - return prefs; -}; + Assert(!this.$_terms.link, 'Cannot reinitialize schema'); + ref = Compile.ref(ref); -internals.default = function (flag, value, errors, helpers) { + Assert(ref.type === 'value' || ref.type === 'local', 'Invalid reference type:', ref.type); + Assert(ref.type === 'local' || ref.ancestor === 'root' || ref.ancestor > 0, 'Link cannot reference itself'); + + const obj = this.clone(); + obj.$_terms.link = [{ ref }]; + return obj; + } + }, + + relative: { + method(enabled = true) { + + return this.$_setFlag('relative', enabled); + } + } + }, + + overrides: { + + concat(source) { + + Assert(this.$_terms.link, 'Uninitialized link schema'); + Assert(Common.isSchema(source), 'Invalid schema object'); + Assert(source.type !== 'link', 'Cannot merge type link with another link'); + + const obj = this.clone(); + + if (!obj.$_terms.whens) { + obj.$_terms.whens = []; + } + + obj.$_terms.whens.push({ concat: source }); + return obj.$_mutateRebuild(); + } + }, + + manifest: { + + build(obj, desc) { + + Assert(desc.link, 'Invalid link description missing link'); + return obj.ref(desc.link); + } + } +}); - const { schema, state, prefs } = helpers; - const source = schema._flags[flag]; - if (prefs.noDefaults || - source === undefined) { - return value; - } +// Helpers - state.mainstay.tracer.log(schema, state, 'rule', flag, 'full'); +internals.generate = function (schema, value, state, prefs) { - if (!source) { - return source; + let linked = state.mainstay.links.get(schema); + if (linked) { + return linked._generate(value, state, prefs).schema; } - if (typeof source === 'function') { - const args = source.length ? [Clone(state.ancestors[0]), helpers] : []; + const ref = schema.$_terms.link[0].ref; + const { perspective, path } = internals.perspective(ref, state); + internals.assert(perspective, 'which is outside of schema boundaries', ref, schema, state, prefs); - try { - return source(...args); - } - catch (err) { - errors.push(schema.$_createError(`any.${flag}`, null, { error: err }, state, prefs)); - return; - } + try { + linked = path.length ? perspective.$_reach(path) : perspective; } - - if (typeof source !== 'object') { - return source; + catch (ignoreErr) { + internals.assert(false, 'to non-existing schema', ref, schema, state, prefs); } - if (source[Common.symbols.literal]) { - return source.literal; - } + internals.assert(linked.type !== 'link', 'which is another link', ref, schema, state, prefs); - if (Common.isResolvable(source)) { - return source.resolve(value, state, prefs); + if (!schema._flags.relative) { + state.mainstay.links.set(schema, linked); } - return Clone(source); + return linked._generate(value, state, prefs).schema; }; -internals.trim = function (value, schema) { +internals.perspective = function (ref, state) { - if (typeof value !== 'string') { - return value; - } + if (ref.type === 'local') { + for (const { schema, key } of state.schemas) { // From parent to root + const id = schema._flags.id || key; + if (id === ref.path[0]) { + return { perspective: schema, path: ref.path.slice(1) }; + } - const trim = schema.$_getRule('trim'); - if (!trim || - !trim.args.enabled) { + if (schema.$_terms.shared) { + for (const shared of schema.$_terms.shared) { + if (shared._flags.id === ref.path[0]) { + return { perspective: shared, path: ref.path.slice(1) }; + } + } + } + } - return value; + return { perspective: null, path: null }; } - return value.trim(); -}; - + if (ref.ancestor === 'root') { + return { perspective: state.schemas[state.schemas.length - 1].schema, path: ref.path }; + } -internals.ignore = { - active: false, - debug: Ignore, - entry: Ignore, - filter: Ignore, - log: Ignore, - resolve: Ignore, - value: Ignore + return { perspective: state.schemas[ref.ancestor] && state.schemas[ref.ancestor].schema, path: ref.path }; }; -internals.errorsArray = function () { +internals.assert = function (condition, message, ref, schema, state, prefs) { - const errors = []; - errors[Common.symbols.errors] = true; - return errors; + if (condition) { // Manual check to avoid generating error message on success + return; + } + + Assert(false, `"${Errors.label(schema._flags, state, prefs)}" contains link reference "${ref.display}" ${message}`); }; /***/ }), -/***/ 71944: +/***/ 15855: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const Assert = __nccwpck_require__(32718); -const DeepEqual = __nccwpck_require__(55801); +const Any = __nccwpck_require__(9512); const Common = __nccwpck_require__(72448); -const internals = {}; +const internals = { + numberRx: /^\s*[+-]?(?:(?:\d+(?:\.\d*)?)|(?:\.\d+))(?:e([+-]?\d+))?\s*$/i, + precisionRx: /(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/ +}; -module.exports = internals.Values = class { +module.exports = Any.extend({ - constructor(values, refs) { + type: 'number', - this._values = new Set(values); - this._refs = new Set(refs); - this._lowercase = internals.lowercases(values); + flags: { - this._override = false; - } + unsafe: { default: false } + }, - get length() { + coerce: { + from: 'string', + method(value, { schema, error }) { - return this._values.size + this._refs.size; - } + const matches = value.match(internals.numberRx); + if (!matches) { + return; + } - add(value, refs) { + value = value.trim(); + const result = { value: parseFloat(value) }; - // Reference + if (result.value === 0) { + result.value = 0; // -0 + } - if (Common.isResolvable(value)) { - if (!this._refs.has(value)) { - this._refs.add(value); + if (!schema._flags.unsafe) { + if (value.match(/e/i)) { + const constructed = internals.normalizeExponent(`${result.value / Math.pow(10, matches[1])}e${matches[1]}`); + if (constructed !== internals.normalizeExponent(value)) { + result.errors = error('number.unsafe'); + return result; + } + } + else { + const string = result.value.toString(); + if (string.match(/e/i)) { + return result; + } - if (refs) { // Skipped in a merge - refs.register(value); + if (string !== internals.normalizeDecimal(value)) { + result.errors = error('number.unsafe'); + return result; + } } } - return; + return result; } + }, - // Value + validate(value, { schema, error, prefs }) { - if (!this.has(value, null, null, false)) { - this._values.add(value); + if (value === Infinity || + value === -Infinity) { - if (typeof value === 'string') { - this._lowercase.set(value.toLowerCase(), value); - } + return { value, errors: error('number.infinity') }; } - } - static merge(target, source, remove) { + if (!Common.isNumber(value)) { + return { value, errors: error('number.base') }; + } - target = target || new internals.Values(); + const result = { value }; - if (source) { - if (source._override) { - return source.clone(); + if (prefs.convert) { + const rule = schema.$_getRule('precision'); + if (rule) { + const precision = Math.pow(10, rule.args.limit); // This is conceptually equivalent to using toFixed but it should be much faster + result.value = Math.round(result.value * precision) / precision; } + } - for (const item of [...source._values, ...source._refs]) { - target.add(item); - } + if (result.value === 0) { + result.value = 0; // -0 } - if (remove) { - for (const item of [...remove._values, ...remove._refs]) { - target.remove(item); - } + if (!schema._flags.unsafe && + (value > Number.MAX_SAFE_INTEGER || value < Number.MIN_SAFE_INTEGER)) { + + result.errors = error('number.unsafe'); } - return target.length ? target : null; - } + return result; + }, - remove(value) { + rules: { - // Reference + compare: { + method: false, + validate(value, helpers, { limit }, { name, operator, args }) { - if (Common.isResolvable(value)) { - this._refs.delete(value); - return; - } + if (Common.compare(value, limit, operator)) { + return value; + } - // Value + return helpers.error('number.' + name, { limit: args.limit, value }); + }, + args: [ + { + name: 'limit', + ref: true, + assert: Common.isNumber, + message: 'must be a number' + } + ] + }, - this._values.delete(value); + greater: { + method(limit) { - if (typeof value === 'string') { - this._lowercase.delete(value.toLowerCase()); - } - } + return this.$_addRule({ name: 'greater', method: 'compare', args: { limit }, operator: '>' }); + } + }, - has(value, state, prefs, insensitive) { + integer: { + method() { - return !!this.get(value, state, prefs, insensitive); - } + return this.$_addRule('integer'); + }, + validate(value, helpers) { - get(value, state, prefs, insensitive) { + if (Math.trunc(value) - value === 0) { + return value; + } - if (!this.length) { - return false; - } + return helpers.error('number.integer'); + } + }, - // Simple match + less: { + method(limit) { - if (this._values.has(value)) { - return { value }; - } + return this.$_addRule({ name: 'less', method: 'compare', args: { limit }, operator: '<' }); + } + }, - // Case insensitive string match + max: { + method(limit) { - if (typeof value === 'string' && - value && - insensitive) { + return this.$_addRule({ name: 'max', method: 'compare', args: { limit }, operator: '<=' }); + } + }, - const found = this._lowercase.get(value.toLowerCase()); - if (found) { - return { value: found }; + min: { + method(limit) { + + return this.$_addRule({ name: 'min', method: 'compare', args: { limit }, operator: '>=' }); } - } + }, - if (!this._refs.size && - typeof value !== 'object') { + multiple: { + method(base) { - return false; - } + return this.$_addRule({ name: 'multiple', args: { base } }); + }, + validate(value, helpers, { base }, options) { - // Objects + if (value * (1 / base) % 1 === 0) { + return value; + } - if (typeof value === 'object') { - for (const item of this._values) { - if (DeepEqual(item, value)) { - return { value: item }; + return helpers.error('number.multiple', { multiple: options.args.base, value }); + }, + args: [ + { + name: 'base', + ref: true, + assert: (value) => typeof value === 'number' && isFinite(value) && value > 0, + message: 'must be a positive number' } - } - } + ], + multi: true + }, - // References + negative: { + method() { - if (state) { - for (const ref of this._refs) { - const resolved = ref.resolve(value, state, prefs, null, { in: true }); - if (resolved === undefined) { - continue; - } + return this.sign('negative'); + } + }, - const items = !ref.in || typeof resolved !== 'object' - ? [resolved] - : Array.isArray(resolved) ? resolved : Object.keys(resolved); + port: { + method() { - for (const item of items) { - if (typeof item !== typeof value) { - continue; - } + return this.$_addRule('port'); + }, + validate(value, helpers) { - if (insensitive && - value && - typeof value === 'string') { + if (Number.isSafeInteger(value) && + value >= 0 && + value <= 65535) { - if (item.toLowerCase() === value.toLowerCase()) { - return { value: item, ref }; - } - } - else { - if (DeepEqual(item, value)) { - return { value: item, ref }; - } - } + return value; } + + return helpers.error('number.port'); } - } + }, - return false; - } + positive: { + method() { - override() { + return this.sign('positive'); + } + }, - this._override = true; - } + precision: { + method(limit) { - values(options) { + Assert(Number.isSafeInteger(limit), 'limit must be an integer'); - if (options && - options.display) { + return this.$_addRule({ name: 'precision', args: { limit } }); + }, + validate(value, helpers, { limit }) { - const values = []; + const places = value.toString().match(internals.precisionRx); + const decimals = Math.max((places[1] ? places[1].length : 0) - (places[2] ? parseInt(places[2], 10) : 0), 0); + if (decimals <= limit) { + return value; + } - for (const item of [...this._values, ...this._refs]) { - if (item !== undefined) { - values.push(item); + return helpers.error('number.precision', { limit, value }); + }, + convert: true + }, + + sign: { + method(sign) { + + Assert(['negative', 'positive'].includes(sign), 'Invalid sign', sign); + + return this.$_addRule({ name: 'sign', args: { sign } }); + }, + validate(value, helpers, { sign }) { + + if (sign === 'negative' && value < 0 || + sign === 'positive' && value > 0) { + + return value; } + + return helpers.error(`number.${sign}`); } + }, - return values; + unsafe: { + method(enabled = true) { + + Assert(typeof enabled === 'boolean', 'enabled must be a boolean'); + + return this.$_setFlag('unsafe', enabled); + } } + }, - return Array.from([...this._values, ...this._refs]); - } + cast: { + string: { + from: (value) => typeof value === 'number', + to(value, helpers) { - clone() { + return value.toString(); + } + } + }, - const set = new internals.Values(this._values, this._refs); - set._override = this._override; - return set; + messages: { + 'number.base': '{{#label}} must be a number', + 'number.greater': '{{#label}} must be greater than {{#limit}}', + 'number.infinity': '{{#label}} cannot be infinity', + 'number.integer': '{{#label}} must be an integer', + 'number.less': '{{#label}} must be less than {{#limit}}', + 'number.max': '{{#label}} must be less than or equal to {{#limit}}', + 'number.min': '{{#label}} must be greater than or equal to {{#limit}}', + 'number.multiple': '{{#label}} must be a multiple of {{#multiple}}', + 'number.negative': '{{#label}} must be a negative number', + 'number.port': '{{#label}} must be a valid port', + 'number.positive': '{{#label}} must be a positive number', + 'number.precision': '{{#label}} must have no more than {{#limit}} decimal places', + 'number.unsafe': '{{#label}} must be a safe number' } +}); - concat(source) { - Assert(!source._override, 'Cannot concat override set of values'); +// Helpers - const set = new internals.Values([...this._values, ...source._values], [...this._refs, ...source._refs]); - set._override = this._override; - return set; - } +internals.normalizeExponent = function (str) { - describe() { + return str + .replace(/E/, 'e') + .replace(/\.(\d*[1-9])?0+e/, '.$1e') + .replace(/\.e/, 'e') + .replace(/e\+/, 'e') + .replace(/^\+/, '') + .replace(/^(-?)0+([1-9])/, '$1$2'); +}; - const normalized = []; - if (this._override) { - normalized.push({ override: true }); - } +internals.normalizeDecimal = function (str) { - for (const value of this._values.values()) { - normalized.push(value && typeof value === 'object' ? { value } : value); - } + str = str + // Remove leading plus signs + .replace(/^\+/, '') + // Remove trailing zeros if there is a decimal point and unecessary decimal points + .replace(/\.0*$/, '') + // Add a integer 0 if the numbers starts with a decimal point + .replace(/^(-?)\.([^\.]*)$/, '$10.$2') + // Remove leading zeros + .replace(/^(-?)0+([0-9])/, '$1$2'); - for (const value of this._refs.values()) { - normalized.push(value.describe()); - } + if (str.includes('.') && + str.endsWith('0')) { - return normalized; + str = str.replace(/0+$/, ''); + } + + if (str === '-0') { + return '0'; } + + return str; }; -internals.Values.prototype[Common.symbols.values] = true; +/***/ }), +/***/ 46878: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -// Aliases +"use strict"; -internals.Values.prototype.slice = internals.Values.prototype.clone; +const Keys = __nccwpck_require__(79130); -// Helpers -internals.lowercases = function (from) { +const internals = {}; - const map = new Map(); - if (from) { - for (const value of from) { - if (typeof value === 'string') { - map.set(value.toLowerCase(), value); +module.exports = Keys.extend({ + + type: 'object', + + cast: { + map: { + from: (value) => value && typeof value === 'object', + to(value, helpers) { + + return new Map(Object.entries(value)); } } - } - - return map; -}; + } +}); /***/ }), -/***/ 21917: +/***/ 72260: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; +const Assert = __nccwpck_require__(32718); +const Domain = __nccwpck_require__(97425); +const Email = __nccwpck_require__(3283); +const Ip = __nccwpck_require__(82337); +const EscapeRegex = __nccwpck_require__(91965); +const Tlds = __nccwpck_require__(53092); +const Uri = __nccwpck_require__(74983); -var loader = __nccwpck_require__(51161); -var dumper = __nccwpck_require__(68866); - +const Any = __nccwpck_require__(9512); +const Common = __nccwpck_require__(72448); -function renamed(from, to) { - return function () { - throw new Error('Function yaml.' + from + ' is removed in js-yaml 4. ' + - 'Use yaml.' + to + ' instead, which is now safe by default.'); - }; -} +const internals = { + tlds: Tlds instanceof Set ? { tlds: { allow: Tlds, deny: null } } : false, // $lab:coverage:ignore$ + base64Regex: { + // paddingRequired + true: { + // urlSafe + true: /^(?:[\w\-]{2}[\w\-]{2})*(?:[\w\-]{2}==|[\w\-]{3}=)?$/, + false: /^(?:[A-Za-z0-9+\/]{2}[A-Za-z0-9+\/]{2})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/ + }, + false: { + true: /^(?:[\w\-]{2}[\w\-]{2})*(?:[\w\-]{2}(==)?|[\w\-]{3}=?)?$/, + false: /^(?:[A-Za-z0-9+\/]{2}[A-Za-z0-9+\/]{2})*(?:[A-Za-z0-9+\/]{2}(==)?|[A-Za-z0-9+\/]{3}=?)?$/ + } + }, + dataUriRegex: /^data:[\w+.-]+\/[\w+.-]+;((charset=[\w-]+|base64),)?(.*)$/, + hexRegex: /^[a-f0-9]+$/i, + ipRegex: Ip.regex({ cidr: 'forbidden' }).regex, + isoDurationRegex: /^P(?!$)(\d+Y)?(\d+M)?(\d+W)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?$/, -module.exports.Type = __nccwpck_require__(6073); -module.exports.Schema = __nccwpck_require__(21082); -module.exports.FAILSAFE_SCHEMA = __nccwpck_require__(28562); -module.exports.JSON_SCHEMA = __nccwpck_require__(1035); -module.exports.CORE_SCHEMA = __nccwpck_require__(12011); -module.exports.DEFAULT_SCHEMA = __nccwpck_require__(18759); -module.exports.load = loader.load; -module.exports.loadAll = loader.loadAll; -module.exports.dump = dumper.dump; -module.exports.YAMLException = __nccwpck_require__(68179); + guidBrackets: { + '{': '}', '[': ']', '(': ')', '': '' + }, + guidVersions: { + uuidv1: '1', + uuidv2: '2', + uuidv3: '3', + uuidv4: '4', + uuidv5: '5' + }, + guidSeparators: new Set([undefined, true, false, '-', ':']), -// Re-export all types in case user wants to create custom schema -module.exports.types = { - binary: __nccwpck_require__(77900), - float: __nccwpck_require__(42705), - map: __nccwpck_require__(86150), - null: __nccwpck_require__(20721), - pairs: __nccwpck_require__(96860), - set: __nccwpck_require__(79548), - timestamp: __nccwpck_require__(99212), - bool: __nccwpck_require__(64993), - int: __nccwpck_require__(11615), - merge: __nccwpck_require__(86104), - omap: __nccwpck_require__(19046), - seq: __nccwpck_require__(67283), - str: __nccwpck_require__(23619) + normalizationForms: ['NFC', 'NFD', 'NFKC', 'NFKD'] }; -// Removed functions from JS-YAML 3.0.x -module.exports.safeLoad = renamed('safeLoad', 'load'); -module.exports.safeLoadAll = renamed('safeLoadAll', 'loadAll'); -module.exports.safeDump = renamed('safeDump', 'dump'); - - -/***/ }), - -/***/ 26829: -/***/ ((module) => { - -"use strict"; - - - -function isNothing(subject) { - return (typeof subject === 'undefined') || (subject === null); -} - -function isObject(subject) { - return (typeof subject === 'object') && (subject !== null); -} +module.exports = Any.extend({ + type: 'string', -function toArray(sequence) { - if (Array.isArray(sequence)) return sequence; - else if (isNothing(sequence)) return []; + flags: { - return [ sequence ]; -} + insensitive: { default: false }, + truncate: { default: false } + }, + terms: { -function extend(target, source) { - var index, length, key, sourceKeys; + replacements: { init: null } + }, - if (source) { - sourceKeys = Object.keys(source); + coerce: { + from: 'string', + method(value, { schema, state, prefs }) { - for (index = 0, length = sourceKeys.length; index < length; index += 1) { - key = sourceKeys[index]; - target[key] = source[key]; - } - } + const normalize = schema.$_getRule('normalize'); + if (normalize) { + value = value.normalize(normalize.args.form); + } - return target; -} + const casing = schema.$_getRule('case'); + if (casing) { + value = casing.args.direction === 'upper' ? value.toLocaleUpperCase() : value.toLocaleLowerCase(); + } + const trim = schema.$_getRule('trim'); + if (trim && + trim.args.enabled) { -function repeat(string, count) { - var result = '', cycle; + value = value.trim(); + } - for (cycle = 0; cycle < count; cycle += 1) { - result += string; - } + if (schema.$_terms.replacements) { + for (const replacement of schema.$_terms.replacements) { + value = value.replace(replacement.pattern, replacement.replacement); + } + } - return result; -} + const hex = schema.$_getRule('hex'); + if (hex && + hex.args.options.byteAligned && + value.length % 2 !== 0) { + value = `0${value}`; + } -function isNegativeZero(number) { - return (number === 0) && (Number.NEGATIVE_INFINITY === 1 / number); -} + if (schema.$_getRule('isoDate')) { + const iso = internals.isoDate(value); + if (iso) { + value = iso; + } + } + if (schema._flags.truncate) { + const rule = schema.$_getRule('max'); + if (rule) { + let limit = rule.args.limit; + if (Common.isResolvable(limit)) { + limit = limit.resolve(value, state, prefs); + if (!Common.limit(limit)) { + return { value, errors: schema.$_createError('any.ref', limit, { ref: rule.args.limit, arg: 'limit', reason: 'must be a positive integer' }, state, prefs) }; + } + } -module.exports.isNothing = isNothing; -module.exports.isObject = isObject; -module.exports.toArray = toArray; -module.exports.repeat = repeat; -module.exports.isNegativeZero = isNegativeZero; -module.exports.extend = extend; + value = value.slice(0, limit); + } + } + return { value }; + } + }, -/***/ }), + validate(value, { schema, error }) { -/***/ 68866: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (typeof value !== 'string') { + return { value, errors: error('string.base') }; + } -"use strict"; + if (value === '') { + const min = schema.$_getRule('min'); + if (min && + min.args.limit === 0) { + return; + } -/*eslint-disable no-use-before-define*/ + return { value, errors: error('string.empty') }; + } + }, -var common = __nccwpck_require__(26829); -var YAMLException = __nccwpck_require__(68179); -var DEFAULT_SCHEMA = __nccwpck_require__(18759); + rules: { -var _toString = Object.prototype.toString; -var _hasOwnProperty = Object.prototype.hasOwnProperty; + alphanum: { + method() { -var CHAR_BOM = 0xFEFF; -var CHAR_TAB = 0x09; /* Tab */ -var CHAR_LINE_FEED = 0x0A; /* LF */ -var CHAR_CARRIAGE_RETURN = 0x0D; /* CR */ -var CHAR_SPACE = 0x20; /* Space */ -var CHAR_EXCLAMATION = 0x21; /* ! */ -var CHAR_DOUBLE_QUOTE = 0x22; /* " */ -var CHAR_SHARP = 0x23; /* # */ -var CHAR_PERCENT = 0x25; /* % */ -var CHAR_AMPERSAND = 0x26; /* & */ -var CHAR_SINGLE_QUOTE = 0x27; /* ' */ -var CHAR_ASTERISK = 0x2A; /* * */ -var CHAR_COMMA = 0x2C; /* , */ -var CHAR_MINUS = 0x2D; /* - */ -var CHAR_COLON = 0x3A; /* : */ -var CHAR_EQUALS = 0x3D; /* = */ -var CHAR_GREATER_THAN = 0x3E; /* > */ -var CHAR_QUESTION = 0x3F; /* ? */ -var CHAR_COMMERCIAL_AT = 0x40; /* @ */ -var CHAR_LEFT_SQUARE_BRACKET = 0x5B; /* [ */ -var CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */ -var CHAR_GRAVE_ACCENT = 0x60; /* ` */ -var CHAR_LEFT_CURLY_BRACKET = 0x7B; /* { */ -var CHAR_VERTICAL_LINE = 0x7C; /* | */ -var CHAR_RIGHT_CURLY_BRACKET = 0x7D; /* } */ + return this.$_addRule('alphanum'); + }, + validate(value, helpers) { -var ESCAPE_SEQUENCES = {}; + if (/^[a-zA-Z0-9]+$/.test(value)) { + return value; + } -ESCAPE_SEQUENCES[0x00] = '\\0'; -ESCAPE_SEQUENCES[0x07] = '\\a'; -ESCAPE_SEQUENCES[0x08] = '\\b'; -ESCAPE_SEQUENCES[0x09] = '\\t'; -ESCAPE_SEQUENCES[0x0A] = '\\n'; -ESCAPE_SEQUENCES[0x0B] = '\\v'; -ESCAPE_SEQUENCES[0x0C] = '\\f'; -ESCAPE_SEQUENCES[0x0D] = '\\r'; -ESCAPE_SEQUENCES[0x1B] = '\\e'; -ESCAPE_SEQUENCES[0x22] = '\\"'; -ESCAPE_SEQUENCES[0x5C] = '\\\\'; -ESCAPE_SEQUENCES[0x85] = '\\N'; -ESCAPE_SEQUENCES[0xA0] = '\\_'; -ESCAPE_SEQUENCES[0x2028] = '\\L'; -ESCAPE_SEQUENCES[0x2029] = '\\P'; + return helpers.error('string.alphanum'); + } + }, -var DEPRECATED_BOOLEANS_SYNTAX = [ - 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON', - 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF' -]; + base64: { + method(options = {}) { -var DEPRECATED_BASE60_SYNTAX = /^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/; + Common.assertOptions(options, ['paddingRequired', 'urlSafe']); -function compileStyleMap(schema, map) { - var result, keys, index, length, tag, style, type; + options = { urlSafe: false, paddingRequired: true, ...options }; + Assert(typeof options.paddingRequired === 'boolean', 'paddingRequired must be boolean'); + Assert(typeof options.urlSafe === 'boolean', 'urlSafe must be boolean'); - if (map === null) return {}; + return this.$_addRule({ name: 'base64', args: { options } }); + }, + validate(value, helpers, { options }) { - result = {}; - keys = Object.keys(map); + const regex = internals.base64Regex[options.paddingRequired][options.urlSafe]; + if (regex.test(value)) { + return value; + } - for (index = 0, length = keys.length; index < length; index += 1) { - tag = keys[index]; - style = String(map[tag]); + return helpers.error('string.base64'); + } + }, - if (tag.slice(0, 2) === '!!') { - tag = 'tag:yaml.org,2002:' + tag.slice(2); - } - type = schema.compiledTypeMap['fallback'][tag]; + case: { + method(direction) { - if (type && _hasOwnProperty.call(type.styleAliases, style)) { - style = type.styleAliases[style]; - } + Assert(['lower', 'upper'].includes(direction), 'Invalid case:', direction); - result[tag] = style; - } + return this.$_addRule({ name: 'case', args: { direction } }); + }, + validate(value, helpers, { direction }) { - return result; -} + if (direction === 'lower' && value === value.toLocaleLowerCase() || + direction === 'upper' && value === value.toLocaleUpperCase()) { -function encodeHex(character) { - var string, handle, length; + return value; + } - string = character.toString(16).toUpperCase(); + return helpers.error(`string.${direction}case`); + }, + convert: true + }, - if (character <= 0xFF) { - handle = 'x'; - length = 2; - } else if (character <= 0xFFFF) { - handle = 'u'; - length = 4; - } else if (character <= 0xFFFFFFFF) { - handle = 'U'; - length = 8; - } else { - throw new YAMLException('code point within a string may not be greater than 0xFFFFFFFF'); - } + creditCard: { + method() { - return '\\' + handle + common.repeat('0', length - string.length) + string; -} + return this.$_addRule('creditCard'); + }, + validate(value, helpers) { + let i = value.length; + let sum = 0; + let mul = 1; -var QUOTING_TYPE_SINGLE = 1, - QUOTING_TYPE_DOUBLE = 2; + while (i--) { + const char = value.charAt(i) * mul; + sum = sum + (char - (char > 9) * 9); + mul = mul ^ 3; + } -function State(options) { - this.schema = options['schema'] || DEFAULT_SCHEMA; - this.indent = Math.max(1, (options['indent'] || 2)); - this.noArrayIndent = options['noArrayIndent'] || false; - this.skipInvalid = options['skipInvalid'] || false; - this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']); - this.styleMap = compileStyleMap(this.schema, options['styles'] || null); - this.sortKeys = options['sortKeys'] || false; - this.lineWidth = options['lineWidth'] || 80; - this.noRefs = options['noRefs'] || false; - this.noCompatMode = options['noCompatMode'] || false; - this.condenseFlow = options['condenseFlow'] || false; - this.quotingType = options['quotingType'] === '"' ? QUOTING_TYPE_DOUBLE : QUOTING_TYPE_SINGLE; - this.forceQuotes = options['forceQuotes'] || false; - this.replacer = typeof options['replacer'] === 'function' ? options['replacer'] : null; + if (sum > 0 && + sum % 10 === 0) { - this.implicitTypes = this.schema.compiledImplicit; - this.explicitTypes = this.schema.compiledExplicit; + return value; + } - this.tag = null; - this.result = ''; + return helpers.error('string.creditCard'); + } + }, - this.duplicates = []; - this.usedDuplicates = null; -} + dataUri: { + method(options = {}) { -// Indents every line in a string. Empty lines (\n only) are not indented. -function indentString(string, spaces) { - var ind = common.repeat(' ', spaces), - position = 0, - next = -1, - result = '', - line, - length = string.length; + Common.assertOptions(options, ['paddingRequired']); - while (position < length) { - next = string.indexOf('\n', position); - if (next === -1) { - line = string.slice(position); - position = length; - } else { - line = string.slice(position, next + 1); - position = next + 1; - } + options = { paddingRequired: true, ...options }; + Assert(typeof options.paddingRequired === 'boolean', 'paddingRequired must be boolean'); - if (line.length && line !== '\n') result += ind; + return this.$_addRule({ name: 'dataUri', args: { options } }); + }, + validate(value, helpers, { options }) { - result += line; - } + const matches = value.match(internals.dataUriRegex); - return result; -} + if (matches) { + if (!matches[2]) { + return value; + } -function generateNextLine(state, level) { - return '\n' + common.repeat(' ', state.indent * level); -} + if (matches[2] !== 'base64') { + return value; + } -function testImplicitResolving(state, str) { - var index, length, type; + const base64regex = internals.base64Regex[options.paddingRequired].false; + if (base64regex.test(matches[3])) { + return value; + } + } - for (index = 0, length = state.implicitTypes.length; index < length; index += 1) { - type = state.implicitTypes[index]; + return helpers.error('string.dataUri'); + } + }, - if (type.resolve(str)) { - return true; - } - } + domain: { + method(options) { - return false; -} + if (options) { + Common.assertOptions(options, ['allowFullyQualified', 'allowUnicode', 'maxDomainSegments', 'minDomainSegments', 'tlds']); + } -// [33] s-white ::= s-space | s-tab -function isWhitespace(c) { - return c === CHAR_SPACE || c === CHAR_TAB; -} + const address = internals.addressOptions(options); + return this.$_addRule({ name: 'domain', args: { options }, address }); + }, + validate(value, helpers, args, { address }) { -// Returns true if the character can be printed without escaping. -// From YAML 1.2: "any allowed characters known to be non-printable -// should also be escaped. [However,] This isn’t mandatory" -// Derived from nb-char - \t - #x85 - #xA0 - #x2028 - #x2029. -function isPrintable(c) { - return (0x00020 <= c && c <= 0x00007E) - || ((0x000A1 <= c && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029) - || ((0x0E000 <= c && c <= 0x00FFFD) && c !== CHAR_BOM) - || (0x10000 <= c && c <= 0x10FFFF); -} + if (Domain.isValid(value, address)) { + return value; + } -// [34] ns-char ::= nb-char - s-white -// [27] nb-char ::= c-printable - b-char - c-byte-order-mark -// [26] b-char ::= b-line-feed | b-carriage-return -// Including s-white (for some reason, examples doesn't match specs in this aspect) -// ns-char ::= c-printable - b-line-feed - b-carriage-return - c-byte-order-mark -function isNsCharOrWhitespace(c) { - return isPrintable(c) - && c !== CHAR_BOM - // - b-char - && c !== CHAR_CARRIAGE_RETURN - && c !== CHAR_LINE_FEED; -} + return helpers.error('string.domain'); + } + }, -// [127] ns-plain-safe(c) ::= c = flow-out ⇒ ns-plain-safe-out -// c = flow-in ⇒ ns-plain-safe-in -// c = block-key ⇒ ns-plain-safe-out -// c = flow-key ⇒ ns-plain-safe-in -// [128] ns-plain-safe-out ::= ns-char -// [129] ns-plain-safe-in ::= ns-char - c-flow-indicator -// [130] ns-plain-char(c) ::= ( ns-plain-safe(c) - “:” - “#” ) -// | ( /* An ns-char preceding */ “#” ) -// | ( “:” /* Followed by an ns-plain-safe(c) */ ) -function isPlainSafe(c, prev, inblock) { - var cIsNsCharOrWhitespace = isNsCharOrWhitespace(c); - var cIsNsChar = cIsNsCharOrWhitespace && !isWhitespace(c); - return ( - // ns-plain-safe - inblock ? // c = flow-in - cIsNsCharOrWhitespace - : cIsNsCharOrWhitespace - // - c-flow-indicator - && c !== CHAR_COMMA - && c !== CHAR_LEFT_SQUARE_BRACKET - && c !== CHAR_RIGHT_SQUARE_BRACKET - && c !== CHAR_LEFT_CURLY_BRACKET - && c !== CHAR_RIGHT_CURLY_BRACKET - ) - // ns-plain-char - && c !== CHAR_SHARP // false on '#' - && !(prev === CHAR_COLON && !cIsNsChar) // false on ': ' - || (isNsCharOrWhitespace(prev) && !isWhitespace(prev) && c === CHAR_SHARP) // change to true on '[^ ]#' - || (prev === CHAR_COLON && cIsNsChar); // change to true on ':[^ ]' -} + email: { + method(options = {}) { -// Simplified test for values allowed as the first character in plain style. -function isPlainSafeFirst(c) { - // Uses a subset of ns-char - c-indicator - // where ns-char = nb-char - s-white. - // No support of ( ( “?” | “:” | “-” ) /* Followed by an ns-plain-safe(c)) */ ) part - return isPrintable(c) && c !== CHAR_BOM - && !isWhitespace(c) // - s-white - // - (c-indicator ::= - // “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}” - && c !== CHAR_MINUS - && c !== CHAR_QUESTION - && c !== CHAR_COLON - && c !== CHAR_COMMA - && c !== CHAR_LEFT_SQUARE_BRACKET - && c !== CHAR_RIGHT_SQUARE_BRACKET - && c !== CHAR_LEFT_CURLY_BRACKET - && c !== CHAR_RIGHT_CURLY_BRACKET - // | “#” | “&” | “*” | “!” | “|” | “=” | “>” | “'” | “"” - && c !== CHAR_SHARP - && c !== CHAR_AMPERSAND - && c !== CHAR_ASTERISK - && c !== CHAR_EXCLAMATION - && c !== CHAR_VERTICAL_LINE - && c !== CHAR_EQUALS - && c !== CHAR_GREATER_THAN - && c !== CHAR_SINGLE_QUOTE - && c !== CHAR_DOUBLE_QUOTE - // | “%” | “@” | “`”) - && c !== CHAR_PERCENT - && c !== CHAR_COMMERCIAL_AT - && c !== CHAR_GRAVE_ACCENT; -} + Common.assertOptions(options, ['allowFullyQualified', 'allowUnicode', 'ignoreLength', 'maxDomainSegments', 'minDomainSegments', 'multiple', 'separator', 'tlds']); + Assert(options.multiple === undefined || typeof options.multiple === 'boolean', 'multiple option must be an boolean'); -// Simplified test for values allowed as the last character in plain style. -function isPlainSafeLast(c) { - // just not whitespace or colon, it will be checked to be plain character later - return !isWhitespace(c) && c !== CHAR_COLON; -} + const address = internals.addressOptions(options); + const regex = new RegExp(`\\s*[${options.separator ? EscapeRegex(options.separator) : ','}]\\s*`); -// Same as 'string'.codePointAt(pos), but works in older browsers. -function codePointAt(string, pos) { - var first = string.charCodeAt(pos), second; - if (first >= 0xD800 && first <= 0xDBFF && pos + 1 < string.length) { - second = string.charCodeAt(pos + 1); - if (second >= 0xDC00 && second <= 0xDFFF) { - // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae - return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000; - } - } - return first; -} + return this.$_addRule({ name: 'email', args: { options }, regex, address }); + }, + validate(value, helpers, { options }, { regex, address }) { -// Determines whether block indentation indicator is required. -function needIndentIndicator(string) { - var leadingSpaceRe = /^\n* /; - return leadingSpaceRe.test(string); -} + const emails = options.multiple ? value.split(regex) : [value]; + const invalids = []; + for (const email of emails) { + if (!Email.isValid(email, address)) { + invalids.push(email); + } + } -var STYLE_PLAIN = 1, - STYLE_SINGLE = 2, - STYLE_LITERAL = 3, - STYLE_FOLDED = 4, - STYLE_DOUBLE = 5; + if (!invalids.length) { + return value; + } -// Determines which scalar styles are possible and returns the preferred style. -// lineWidth = -1 => no limit. -// Pre-conditions: str.length > 0. -// Post-conditions: -// STYLE_PLAIN or STYLE_SINGLE => no \n are in the string. -// STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1). -// STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1). -function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, - testAmbiguousType, quotingType, forceQuotes, inblock) { + return helpers.error('string.email', { value, invalids }); + } + }, - var i; - var char = 0; - var prevChar = null; - var hasLineBreak = false; - var hasFoldableLine = false; // only checked if shouldTrackWidth - var shouldTrackWidth = lineWidth !== -1; - var previousLineBreak = -1; // count the first line correctly - var plain = isPlainSafeFirst(codePointAt(string, 0)) - && isPlainSafeLast(codePointAt(string, string.length - 1)); + guid: { + alias: 'uuid', + method(options = {}) { - if (singleLineOnly || forceQuotes) { - // Case: no block styles. - // Check for disallowed characters to rule out plain and single. - for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) { - char = codePointAt(string, i); - if (!isPrintable(char)) { - return STYLE_DOUBLE; - } - plain = plain && isPlainSafe(char, prevChar, inblock); - prevChar = char; - } - } else { - // Case: block styles permitted. - for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) { - char = codePointAt(string, i); - if (char === CHAR_LINE_FEED) { - hasLineBreak = true; - // Check if any line can be folded. - if (shouldTrackWidth) { - hasFoldableLine = hasFoldableLine || - // Foldable line = too long, and not more-indented. - (i - previousLineBreak - 1 > lineWidth && - string[previousLineBreak + 1] !== ' '); - previousLineBreak = i; - } - } else if (!isPrintable(char)) { - return STYLE_DOUBLE; - } - plain = plain && isPlainSafe(char, prevChar, inblock); - prevChar = char; - } - // in case the end is missing a \n - hasFoldableLine = hasFoldableLine || (shouldTrackWidth && - (i - previousLineBreak - 1 > lineWidth && - string[previousLineBreak + 1] !== ' ')); - } - // Although every style can represent \n without escaping, prefer block styles - // for multiline, since they're more readable and they don't add empty lines. - // Also prefer folding a super-long line. - if (!hasLineBreak && !hasFoldableLine) { - // Strings interpretable as another type have to be quoted; - // e.g. the string 'true' vs. the boolean true. - if (plain && !forceQuotes && !testAmbiguousType(string)) { - return STYLE_PLAIN; - } - return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE; - } - // Edge case: block indentation indicator can only have one digit. - if (indentPerLevel > 9 && needIndentIndicator(string)) { - return STYLE_DOUBLE; - } - // At this point we know block styles are valid. - // Prefer literal style unless we want to fold. - if (!forceQuotes) { - return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL; - } - return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE; -} + Common.assertOptions(options, ['version', 'separator']); -// Note: line breaking/folding is implemented for only the folded style. -// NB. We drop the last trailing newline (if any) of a returned block scalar -// since the dumper adds its own newline. This always works: -// • No ending newline => unaffected; already using strip "-" chomping. -// • Ending newline => removed then restored. -// Importantly, this keeps the "+" chomp indicator from gaining an extra line. -function writeScalar(state, string, level, iskey, inblock) { - state.dump = (function () { - if (string.length === 0) { - return state.quotingType === QUOTING_TYPE_DOUBLE ? '""' : "''"; - } - if (!state.noCompatMode) { - if (DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1 || DEPRECATED_BASE60_SYNTAX.test(string)) { - return state.quotingType === QUOTING_TYPE_DOUBLE ? ('"' + string + '"') : ("'" + string + "'"); - } - } + let versionNumbers = ''; - var indent = state.indent * Math.max(1, level); // no 0-indent scalars - // As indentation gets deeper, let the width decrease monotonically - // to the lower bound min(state.lineWidth, 40). - // Note that this implies - // state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound. - // state.lineWidth > 40 + state.indent: width decreases until the lower bound. - // This behaves better than a constant minimum width which disallows narrower options, - // or an indent threshold which causes the width to suddenly increase. - var lineWidth = state.lineWidth === -1 - ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent); + if (options.version) { + const versions = [].concat(options.version); - // Without knowing if keys are implicit/explicit, assume implicit for safety. - var singleLineOnly = iskey - // No block styles in flow mode. - || (state.flowLevel > -1 && level >= state.flowLevel); - function testAmbiguity(string) { - return testImplicitResolving(state, string); - } + Assert(versions.length >= 1, 'version must have at least 1 valid version specified'); + const set = new Set(); - switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, - testAmbiguity, state.quotingType, state.forceQuotes && !iskey, inblock)) { + for (let i = 0; i < versions.length; ++i) { + const version = versions[i]; + Assert(typeof version === 'string', 'version at position ' + i + ' must be a string'); + const versionNumber = internals.guidVersions[version.toLowerCase()]; + Assert(versionNumber, 'version at position ' + i + ' must be one of ' + Object.keys(internals.guidVersions).join(', ')); + Assert(!set.has(versionNumber), 'version at position ' + i + ' must not be a duplicate'); - case STYLE_PLAIN: - return string; - case STYLE_SINGLE: - return "'" + string.replace(/'/g, "''") + "'"; - case STYLE_LITERAL: - return '|' + blockHeader(string, state.indent) - + dropEndingNewline(indentString(string, indent)); - case STYLE_FOLDED: - return '>' + blockHeader(string, state.indent) - + dropEndingNewline(indentString(foldString(string, lineWidth), indent)); - case STYLE_DOUBLE: - return '"' + escapeString(string, lineWidth) + '"'; - default: - throw new YAMLException('impossible error: invalid scalar style'); - } - }()); -} + versionNumbers += versionNumber; + set.add(versionNumber); + } + } -// Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9. -function blockHeader(string, indentPerLevel) { - var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : ''; + Assert(internals.guidSeparators.has(options.separator), 'separator must be one of true, false, "-", or ":"'); + const separator = options.separator === undefined ? '[:-]?' : + options.separator === true ? '[:-]' : + options.separator === false ? '[]?' : `\\${options.separator}`; - // note the special case: the string '\n' counts as a "trailing" empty line. - var clip = string[string.length - 1] === '\n'; - var keep = clip && (string[string.length - 2] === '\n' || string === '\n'); - var chomp = keep ? '+' : (clip ? '' : '-'); + const regex = new RegExp(`^([\\[{\\(]?)[0-9A-F]{8}(${separator})[0-9A-F]{4}\\2?[${versionNumbers || '0-9A-F'}][0-9A-F]{3}\\2?[${versionNumbers ? '89AB' : '0-9A-F'}][0-9A-F]{3}\\2?[0-9A-F]{12}([\\]}\\)]?)$`, 'i'); - return indentIndicator + chomp + '\n'; -} + return this.$_addRule({ name: 'guid', args: { options }, regex }); + }, + validate(value, helpers, args, { regex }) { -// (See the note for writeScalar.) -function dropEndingNewline(string) { - return string[string.length - 1] === '\n' ? string.slice(0, -1) : string; -} + const results = regex.exec(value); -// Note: a long line without a suitable break point will exceed the width limit. -// Pre-conditions: every char in str isPrintable, str.length > 0, width > 0. -function foldString(string, width) { - // In folded style, $k$ consecutive newlines output as $k+1$ newlines— - // unless they're before or after a more-indented line, or at the very - // beginning or end, in which case $k$ maps to $k$. - // Therefore, parse each chunk as newline(s) followed by a content line. - var lineRe = /(\n+)([^\n]*)/g; + if (!results) { + return helpers.error('string.guid'); + } - // first line (possibly an empty line) - var result = (function () { - var nextLF = string.indexOf('\n'); - nextLF = nextLF !== -1 ? nextLF : string.length; - lineRe.lastIndex = nextLF; - return foldLine(string.slice(0, nextLF), width); - }()); - // If we haven't reached the first content line yet, don't add an extra \n. - var prevMoreIndented = string[0] === '\n' || string[0] === ' '; - var moreIndented; + // Matching braces - // rest of the lines - var match; - while ((match = lineRe.exec(string))) { - var prefix = match[1], line = match[2]; - moreIndented = (line[0] === ' '); - result += prefix - + (!prevMoreIndented && !moreIndented && line !== '' - ? '\n' : '') - + foldLine(line, width); - prevMoreIndented = moreIndented; - } + if (internals.guidBrackets[results[1]] !== results[results.length - 1]) { + return helpers.error('string.guid'); + } - return result; -} + return value; + } + }, -// Greedy line breaking. -// Picks the longest line under the limit each time, -// otherwise settles for the shortest line over the limit. -// NB. More-indented lines *cannot* be folded, as that would add an extra \n. -function foldLine(line, width) { - if (line === '' || line[0] === ' ') return line; + hex: { + method(options = {}) { - // Since a more-indented line adds a \n, breaks can't be followed by a space. - var breakRe = / [^ ]/g; // note: the match index will always be <= length-2. - var match; - // start is an inclusive index. end, curr, and next are exclusive. - var start = 0, end, curr = 0, next = 0; - var result = ''; + Common.assertOptions(options, ['byteAligned']); - // Invariants: 0 <= start <= length-1. - // 0 <= curr <= next <= max(0, length-2). curr - start <= width. - // Inside the loop: - // A match implies length >= 2, so curr and next are <= length-2. - while ((match = breakRe.exec(line))) { - next = match.index; - // maintain invariant: curr - start <= width - if (next - start > width) { - end = (curr > start) ? curr : next; // derive end <= length-2 - result += '\n' + line.slice(start, end); - // skip the space that was output as \n - start = end + 1; // derive start <= length-1 - } - curr = next; - } + options = { byteAligned: false, ...options }; + Assert(typeof options.byteAligned === 'boolean', 'byteAligned must be boolean'); - // By the invariants, start <= length-1, so there is something left over. - // It is either the whole string or a part starting from non-whitespace. - result += '\n'; - // Insert a break if the remainder is too long and there is a break available. - if (line.length - start > width && curr > start) { - result += line.slice(start, curr) + '\n' + line.slice(curr + 1); - } else { - result += line.slice(start); - } + return this.$_addRule({ name: 'hex', args: { options } }); + }, + validate(value, helpers, { options }) { - return result.slice(1); // drop extra \n joiner -} + if (!internals.hexRegex.test(value)) { + return helpers.error('string.hex'); + } -// Escapes a double-quoted string. -function escapeString(string) { - var result = ''; - var char = 0; - var escapeSeq; + if (options.byteAligned && + value.length % 2 !== 0) { - for (var i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) { - char = codePointAt(string, i); - escapeSeq = ESCAPE_SEQUENCES[char]; + return helpers.error('string.hexAlign'); + } - if (!escapeSeq && isPrintable(char)) { - result += string[i]; - if (char >= 0x10000) result += string[i + 1]; - } else { - result += escapeSeq || encodeHex(char); - } - } + return value; + } + }, - return result; -} + hostname: { + method() { -function writeFlowSequence(state, level, object) { - var _result = '', - _tag = state.tag, - index, - length, - value; + return this.$_addRule('hostname'); + }, + validate(value, helpers) { - for (index = 0, length = object.length; index < length; index += 1) { - value = object[index]; + if (Domain.isValid(value, { minDomainSegments: 1 }) || + internals.ipRegex.test(value)) { - if (state.replacer) { - value = state.replacer.call(object, String(index), value); - } + return value; + } - // Write only valid elements, put null instead of invalid elements. - if (writeNode(state, level, value, false, false) || - (typeof value === 'undefined' && - writeNode(state, level, null, false, false))) { + return helpers.error('string.hostname'); + } + }, - if (_result !== '') _result += ',' + (!state.condenseFlow ? ' ' : ''); - _result += state.dump; - } - } + insensitive: { + method() { - state.tag = _tag; - state.dump = '[' + _result + ']'; -} + return this.$_setFlag('insensitive', true); + } + }, -function writeBlockSequence(state, level, object, compact) { - var _result = '', - _tag = state.tag, - index, - length, - value; + ip: { + method(options = {}) { - for (index = 0, length = object.length; index < length; index += 1) { - value = object[index]; + Common.assertOptions(options, ['cidr', 'version']); - if (state.replacer) { - value = state.replacer.call(object, String(index), value); - } + const { cidr, versions, regex } = Ip.regex(options); + const version = options.version ? versions : undefined; + return this.$_addRule({ name: 'ip', args: { options: { cidr, version } }, regex }); + }, + validate(value, helpers, { options }, { regex }) { - // Write only valid elements, put null instead of invalid elements. - if (writeNode(state, level + 1, value, true, true, false, true) || - (typeof value === 'undefined' && - writeNode(state, level + 1, null, true, true, false, true))) { + if (regex.test(value)) { + return value; + } - if (!compact || _result !== '') { - _result += generateNextLine(state, level); - } + if (options.version) { + return helpers.error('string.ipVersion', { value, cidr: options.cidr, version: options.version }); + } - if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { - _result += '-'; - } else { - _result += '- '; - } + return helpers.error('string.ip', { value, cidr: options.cidr }); + } + }, - _result += state.dump; - } - } + isoDate: { + method() { - state.tag = _tag; - state.dump = _result || '[]'; // Empty sequence if no valid values. -} + return this.$_addRule('isoDate'); + }, + validate(value, { error }) { -function writeFlowMapping(state, level, object) { - var _result = '', - _tag = state.tag, - objectKeyList = Object.keys(object), - index, - length, - objectKey, - objectValue, - pairBuffer; + if (internals.isoDate(value)) { + return value; + } - for (index = 0, length = objectKeyList.length; index < length; index += 1) { + return error('string.isoDate'); + } + }, - pairBuffer = ''; - if (_result !== '') pairBuffer += ', '; + isoDuration: { + method() { - if (state.condenseFlow) pairBuffer += '"'; + return this.$_addRule('isoDuration'); + }, + validate(value, helpers) { - objectKey = objectKeyList[index]; - objectValue = object[objectKey]; + if (internals.isoDurationRegex.test(value)) { + return value; + } - if (state.replacer) { - objectValue = state.replacer.call(object, objectKey, objectValue); - } + return helpers.error('string.isoDuration'); + } + }, - if (!writeNode(state, level, objectKey, false, false)) { - continue; // Skip this pair because of invalid key; - } + length: { + method(limit, encoding) { + + return internals.length(this, 'length', limit, '=', encoding); + }, + validate(value, helpers, { limit, encoding }, { name, operator, args }) { + + const length = encoding ? Buffer && Buffer.byteLength(value, encoding) : value.length; // $lab:coverage:ignore$ + if (Common.compare(length, limit, operator)) { + return value; + } + + return helpers.error('string.' + name, { limit: args.limit, value, encoding }); + }, + args: [ + { + name: 'limit', + ref: true, + assert: Common.limit, + message: 'must be a positive integer' + }, + 'encoding' + ] + }, - if (state.dump.length > 1024) pairBuffer += '? '; + lowercase: { + method() { - pairBuffer += state.dump + (state.condenseFlow ? '"' : '') + ':' + (state.condenseFlow ? '' : ' '); + return this.case('lower'); + } + }, - if (!writeNode(state, level, objectValue, false, false)) { - continue; // Skip this pair because of invalid value. - } + max: { + method(limit, encoding) { - pairBuffer += state.dump; + return internals.length(this, 'max', limit, '<=', encoding); + }, + args: ['limit', 'encoding'] + }, - // Both key and value are valid. - _result += pairBuffer; - } + min: { + method(limit, encoding) { - state.tag = _tag; - state.dump = '{' + _result + '}'; -} + return internals.length(this, 'min', limit, '>=', encoding); + }, + args: ['limit', 'encoding'] + }, -function writeBlockMapping(state, level, object, compact) { - var _result = '', - _tag = state.tag, - objectKeyList = Object.keys(object), - index, - length, - objectKey, - objectValue, - explicitPair, - pairBuffer; + normalize: { + method(form = 'NFC') { - // Allow sorting keys so that the output file is deterministic - if (state.sortKeys === true) { - // Default sorting - objectKeyList.sort(); - } else if (typeof state.sortKeys === 'function') { - // Custom sort function - objectKeyList.sort(state.sortKeys); - } else if (state.sortKeys) { - // Something is wrong - throw new YAMLException('sortKeys must be a boolean or a function'); - } + Assert(internals.normalizationForms.includes(form), 'normalization form must be one of ' + internals.normalizationForms.join(', ')); - for (index = 0, length = objectKeyList.length; index < length; index += 1) { - pairBuffer = ''; + return this.$_addRule({ name: 'normalize', args: { form } }); + }, + validate(value, { error }, { form }) { - if (!compact || _result !== '') { - pairBuffer += generateNextLine(state, level); - } + if (value === value.normalize(form)) { + return value; + } - objectKey = objectKeyList[index]; - objectValue = object[objectKey]; + return error('string.normalize', { value, form }); + }, + convert: true + }, - if (state.replacer) { - objectValue = state.replacer.call(object, objectKey, objectValue); - } + pattern: { + alias: 'regex', + method(regex, options = {}) { - if (!writeNode(state, level + 1, objectKey, true, true, true)) { - continue; // Skip this pair because of invalid key. - } + Assert(regex instanceof RegExp, 'regex must be a RegExp'); + Assert(!regex.flags.includes('g') && !regex.flags.includes('y'), 'regex should not use global or sticky mode'); - explicitPair = (state.tag !== null && state.tag !== '?') || - (state.dump && state.dump.length > 1024); + if (typeof options === 'string') { + options = { name: options }; + } - if (explicitPair) { - if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { - pairBuffer += '?'; - } else { - pairBuffer += '? '; - } - } + Common.assertOptions(options, ['invert', 'name']); - pairBuffer += state.dump; + const errorCode = ['string.pattern', options.invert ? '.invert' : '', options.name ? '.name' : '.base'].join(''); + return this.$_addRule({ name: 'pattern', args: { regex, options }, errorCode }); + }, + validate(value, helpers, { regex, options }, { errorCode }) { - if (explicitPair) { - pairBuffer += generateNextLine(state, level); - } + const patternMatch = regex.test(value); - if (!writeNode(state, level + 1, objectValue, true, explicitPair)) { - continue; // Skip this pair because of invalid value. - } + if (patternMatch ^ options.invert) { + return value; + } - if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { - pairBuffer += ':'; - } else { - pairBuffer += ': '; - } + return helpers.error(errorCode, { name: options.name, regex, value }); + }, + args: ['regex', 'options'], + multi: true + }, - pairBuffer += state.dump; + replace: { + method(pattern, replacement) { - // Both key and value are valid. - _result += pairBuffer; - } + if (typeof pattern === 'string') { + pattern = new RegExp(EscapeRegex(pattern), 'g'); + } - state.tag = _tag; - state.dump = _result || '{}'; // Empty mapping if no valid pairs. -} + Assert(pattern instanceof RegExp, 'pattern must be a RegExp'); + Assert(typeof replacement === 'string', 'replacement must be a String'); -function detectType(state, object, explicit) { - var _result, typeList, index, length, type, style; + const obj = this.clone(); - typeList = explicit ? state.explicitTypes : state.implicitTypes; + if (!obj.$_terms.replacements) { + obj.$_terms.replacements = []; + } - for (index = 0, length = typeList.length; index < length; index += 1) { - type = typeList[index]; + obj.$_terms.replacements.push({ pattern, replacement }); + return obj; + } + }, - if ((type.instanceOf || type.predicate) && - (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) && - (!type.predicate || type.predicate(object))) { + token: { + method() { - if (explicit) { - if (type.multi && type.representName) { - state.tag = type.representName(object); - } else { - state.tag = type.tag; - } - } else { - state.tag = '?'; - } + return this.$_addRule('token'); + }, + validate(value, helpers) { - if (type.represent) { - style = state.styleMap[type.tag] || type.defaultStyle; + if (/^\w+$/.test(value)) { + return value; + } - if (_toString.call(type.represent) === '[object Function]') { - _result = type.represent(object, style); - } else if (_hasOwnProperty.call(type.represent, style)) { - _result = type.represent[style](object, style); - } else { - throw new YAMLException('!<' + type.tag + '> tag resolver accepts not "' + style + '" style'); - } + return helpers.error('string.token'); + } + }, - state.dump = _result; - } + trim: { + method(enabled = true) { - return true; - } - } + Assert(typeof enabled === 'boolean', 'enabled must be a boolean'); - return false; -} + return this.$_addRule({ name: 'trim', args: { enabled } }); + }, + validate(value, helpers, { enabled }) { -// Serializes `object` and writes it to global `result`. -// Returns true on success, or false on invalid object. -// -function writeNode(state, level, object, block, compact, iskey, isblockseq) { - state.tag = null; - state.dump = object; + if (!enabled || + value === value.trim()) { - if (!detectType(state, object, false)) { - detectType(state, object, true); - } + return value; + } - var type = _toString.call(state.dump); - var inblock = block; - var tagStr; + return helpers.error('string.trim'); + }, + convert: true + }, - if (block) { - block = (state.flowLevel < 0 || state.flowLevel > level); - } + truncate: { + method(enabled = true) { - var objectOrArray = type === '[object Object]' || type === '[object Array]', - duplicateIndex, - duplicate; + Assert(typeof enabled === 'boolean', 'enabled must be a boolean'); - if (objectOrArray) { - duplicateIndex = state.duplicates.indexOf(object); - duplicate = duplicateIndex !== -1; - } + return this.$_setFlag('truncate', enabled); + } + }, - if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) { - compact = false; - } + uppercase: { + method() { - if (duplicate && state.usedDuplicates[duplicateIndex]) { - state.dump = '*ref_' + duplicateIndex; - } else { - if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) { - state.usedDuplicates[duplicateIndex] = true; - } - if (type === '[object Object]') { - if (block && (Object.keys(state.dump).length !== 0)) { - writeBlockMapping(state, level, state.dump, compact); - if (duplicate) { - state.dump = '&ref_' + duplicateIndex + state.dump; - } - } else { - writeFlowMapping(state, level, state.dump); - if (duplicate) { - state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; - } - } - } else if (type === '[object Array]') { - if (block && (state.dump.length !== 0)) { - if (state.noArrayIndent && !isblockseq && level > 0) { - writeBlockSequence(state, level - 1, state.dump, compact); - } else { - writeBlockSequence(state, level, state.dump, compact); - } - if (duplicate) { - state.dump = '&ref_' + duplicateIndex + state.dump; - } - } else { - writeFlowSequence(state, level, state.dump); - if (duplicate) { - state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; - } - } - } else if (type === '[object String]') { - if (state.tag !== '?') { - writeScalar(state, state.dump, level, iskey, inblock); - } - } else if (type === '[object Undefined]') { - return false; - } else { - if (state.skipInvalid) return false; - throw new YAMLException('unacceptable kind of an object to dump ' + type); - } + return this.case('upper'); + } + }, - if (state.tag !== null && state.tag !== '?') { - // Need to encode all characters except those allowed by the spec: - // - // [35] ns-dec-digit ::= [#x30-#x39] /* 0-9 */ - // [36] ns-hex-digit ::= ns-dec-digit - // | [#x41-#x46] /* A-F */ | [#x61-#x66] /* a-f */ - // [37] ns-ascii-letter ::= [#x41-#x5A] /* A-Z */ | [#x61-#x7A] /* a-z */ - // [38] ns-word-char ::= ns-dec-digit | ns-ascii-letter | “-” - // [39] ns-uri-char ::= “%” ns-hex-digit ns-hex-digit | ns-word-char | “#” - // | “;” | “/” | “?” | “:” | “@” | “&” | “=” | “+” | “$” | “,” - // | “_” | “.” | “!” | “~” | “*” | “'” | “(” | “)” | “[” | “]” - // - // Also need to encode '!' because it has special meaning (end of tag prefix). - // - tagStr = encodeURI( - state.tag[0] === '!' ? state.tag.slice(1) : state.tag - ).replace(/!/g, '%21'); + uri: { + method(options = {}) { - if (state.tag[0] === '!') { - tagStr = '!' + tagStr; - } else if (tagStr.slice(0, 18) === 'tag:yaml.org,2002:') { - tagStr = '!!' + tagStr.slice(18); - } else { - tagStr = '!<' + tagStr + '>'; - } + Common.assertOptions(options, ['allowRelative', 'allowQuerySquareBrackets', 'domain', 'relativeOnly', 'scheme']); - state.dump = tagStr + ' ' + state.dump; - } - } + if (options.domain) { + Common.assertOptions(options.domain, ['allowFullyQualified', 'allowUnicode', 'maxDomainSegments', 'minDomainSegments', 'tlds']); + } - return true; -} + const { regex, scheme } = Uri.regex(options); + const domain = options.domain ? internals.addressOptions(options.domain) : null; + return this.$_addRule({ name: 'uri', args: { options }, regex, domain, scheme }); + }, + validate(value, helpers, { options }, { regex, domain, scheme }) { -function getDuplicateReferences(object, state) { - var objects = [], - duplicatesIndexes = [], - index, - length; + if (['http:/', 'https:/'].includes(value)) { // scheme:/ is technically valid but makes no sense + return helpers.error('string.uri'); + } - inspectNode(object, objects, duplicatesIndexes); + const match = regex.exec(value); + if (match) { + const matched = match[1] || match[2]; + if (domain && + (!options.allowRelative || matched) && + !Domain.isValid(matched, domain)) { - for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) { - state.duplicates.push(objects[duplicatesIndexes[index]]); - } - state.usedDuplicates = new Array(length); -} + return helpers.error('string.domain', { value: matched }); + } -function inspectNode(object, objects, duplicatesIndexes) { - var objectKeyList, - index, - length; + return value; + } - if (object !== null && typeof object === 'object') { - index = objects.indexOf(object); - if (index !== -1) { - if (duplicatesIndexes.indexOf(index) === -1) { - duplicatesIndexes.push(index); - } - } else { - objects.push(object); + if (options.relativeOnly) { + return helpers.error('string.uriRelativeOnly'); + } - if (Array.isArray(object)) { - for (index = 0, length = object.length; index < length; index += 1) { - inspectNode(object[index], objects, duplicatesIndexes); - } - } else { - objectKeyList = Object.keys(object); + if (options.scheme) { + return helpers.error('string.uriCustomScheme', { scheme, value }); + } - for (index = 0, length = objectKeyList.length; index < length; index += 1) { - inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes); + return helpers.error('string.uri'); + } } - } - } - } -} - -function dump(input, options) { - options = options || {}; - - var state = new State(options); - - if (!state.noRefs) getDuplicateReferences(input, state); - - var value = input; + }, - if (state.replacer) { - value = state.replacer.call({ '': value }, '', value); - } + manifest: { - if (writeNode(state, 0, value, true, true)) return state.dump + '\n'; + build(obj, desc) { - return ''; -} + if (desc.replacements) { + for (const { pattern, replacement } of desc.replacements) { + obj = obj.replace(pattern, replacement); + } + } -module.exports.dump = dump; + return obj; + } + }, + messages: { + 'string.alphanum': '{{#label}} must only contain alpha-numeric characters', + 'string.base': '{{#label}} must be a string', + 'string.base64': '{{#label}} must be a valid base64 string', + 'string.creditCard': '{{#label}} must be a credit card', + 'string.dataUri': '{{#label}} must be a valid dataUri string', + 'string.domain': '{{#label}} must contain a valid domain name', + 'string.email': '{{#label}} must be a valid email', + 'string.empty': '{{#label}} is not allowed to be empty', + 'string.guid': '{{#label}} must be a valid GUID', + 'string.hex': '{{#label}} must only contain hexadecimal characters', + 'string.hexAlign': '{{#label}} hex decoded representation must be byte aligned', + 'string.hostname': '{{#label}} must be a valid hostname', + 'string.ip': '{{#label}} must be a valid ip address with a {{#cidr}} CIDR', + 'string.ipVersion': '{{#label}} must be a valid ip address of one of the following versions {{#version}} with a {{#cidr}} CIDR', + 'string.isoDate': '{{#label}} must be in iso format', + 'string.isoDuration': '{{#label}} must be a valid ISO 8601 duration', + 'string.length': '{{#label}} length must be {{#limit}} characters long', + 'string.lowercase': '{{#label}} must only contain lowercase characters', + 'string.max': '{{#label}} length must be less than or equal to {{#limit}} characters long', + 'string.min': '{{#label}} length must be at least {{#limit}} characters long', + 'string.normalize': '{{#label}} must be unicode normalized in the {{#form}} form', + 'string.token': '{{#label}} must only contain alpha-numeric and underscore characters', + 'string.pattern.base': '{{#label}} with value {:[.]} fails to match the required pattern: {{#regex}}', + 'string.pattern.name': '{{#label}} with value {:[.]} fails to match the {{#name}} pattern', + 'string.pattern.invert.base': '{{#label}} with value {:[.]} matches the inverted pattern: {{#regex}}', + 'string.pattern.invert.name': '{{#label}} with value {:[.]} matches the inverted {{#name}} pattern', + 'string.trim': '{{#label}} must not have leading or trailing whitespace', + 'string.uri': '{{#label}} must be a valid uri', + 'string.uriCustomScheme': '{{#label}} must be a valid uri with a scheme matching the {{#scheme}} pattern', + 'string.uriRelativeOnly': '{{#label}} must be a valid relative uri', + 'string.uppercase': '{{#label}} must only contain uppercase characters' + } +}); -/***/ }), -/***/ 68179: -/***/ ((module) => { +// Helpers -"use strict"; -// YAML error class. http://stackoverflow.com/questions/8458984 -// +internals.addressOptions = function (options) { + if (!options) { + return options; + } + // minDomainSegments -function formatError(exception, compact) { - var where = '', message = exception.reason || '(unknown reason)'; + Assert(options.minDomainSegments === undefined || + Number.isSafeInteger(options.minDomainSegments) && options.minDomainSegments > 0, 'minDomainSegments must be a positive integer'); - if (!exception.mark) return message; + // maxDomainSegments - if (exception.mark.name) { - where += 'in "' + exception.mark.name + '" '; - } + Assert(options.maxDomainSegments === undefined || + Number.isSafeInteger(options.maxDomainSegments) && options.maxDomainSegments > 0, 'maxDomainSegments must be a positive integer'); - where += '(' + (exception.mark.line + 1) + ':' + (exception.mark.column + 1) + ')'; + // tlds - if (!compact && exception.mark.snippet) { - where += '\n\n' + exception.mark.snippet; - } + if (options.tlds === false) { + return options; + } - return message + ' ' + where; -} + if (options.tlds === true || + options.tlds === undefined) { + Assert(internals.tlds, 'Built-in TLD list disabled'); + return Object.assign({}, options, internals.tlds); + } -function YAMLException(reason, mark) { - // Super constructor - Error.call(this); + Assert(typeof options.tlds === 'object', 'tlds must be true, false, or an object'); - this.name = 'YAMLException'; - this.reason = reason; - this.mark = mark; - this.message = formatError(this, false); + const deny = options.tlds.deny; + if (deny) { + if (Array.isArray(deny)) { + options = Object.assign({}, options, { tlds: { deny: new Set(deny) } }); + } - // Include stack trace in error object - if (Error.captureStackTrace) { - // Chrome and NodeJS - Error.captureStackTrace(this, this.constructor); - } else { - // FF, IE 10+ and Safari 6+. Fallback for others - this.stack = (new Error()).stack || ''; - } -} + Assert(options.tlds.deny instanceof Set, 'tlds.deny must be an array, Set, or boolean'); + Assert(!options.tlds.allow, 'Cannot specify both tlds.allow and tlds.deny lists'); + internals.validateTlds(options.tlds.deny, 'tlds.deny'); + return options; + } + const allow = options.tlds.allow; + if (!allow) { + return options; + } -// Inherit from Error -YAMLException.prototype = Object.create(Error.prototype); -YAMLException.prototype.constructor = YAMLException; + if (allow === true) { + Assert(internals.tlds, 'Built-in TLD list disabled'); + return Object.assign({}, options, internals.tlds); + } + if (Array.isArray(allow)) { + options = Object.assign({}, options, { tlds: { allow: new Set(allow) } }); + } -YAMLException.prototype.toString = function toString(compact) { - return this.name + ': ' + formatError(this, compact); + Assert(options.tlds.allow instanceof Set, 'tlds.allow must be an array, Set, or boolean'); + internals.validateTlds(options.tlds.allow, 'tlds.allow'); + return options; }; -module.exports = YAMLException; - +internals.validateTlds = function (set, source) { -/***/ }), + for (const tld of set) { + Assert(Domain.isValid(tld, { minDomainSegments: 1, maxDomainSegments: 1 }), `${source} must contain valid top level domain names`); + } +}; -/***/ 51161: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +internals.isoDate = function (value) { + if (!Common.isIsoDate(value)) { + return null; + } -/*eslint-disable max-len,no-use-before-define*/ + if (/.*T.*[+-]\d\d$/.test(value)) { // Add missing trailing zeros to timeshift + value += '00'; + } -var common = __nccwpck_require__(26829); -var YAMLException = __nccwpck_require__(68179); -var makeSnippet = __nccwpck_require__(96975); -var DEFAULT_SCHEMA = __nccwpck_require__(18759); + const date = new Date(value); + if (isNaN(date.getTime())) { + return null; + } + return date.toISOString(); +}; -var _hasOwnProperty = Object.prototype.hasOwnProperty; +internals.length = function (schema, name, limit, operator, encoding) { -var CONTEXT_FLOW_IN = 1; -var CONTEXT_FLOW_OUT = 2; -var CONTEXT_BLOCK_IN = 3; -var CONTEXT_BLOCK_OUT = 4; + Assert(!encoding || Buffer && Buffer.isEncoding(encoding), 'Invalid encoding:', encoding); // $lab:coverage:ignore$ + return schema.$_addRule({ name, method: 'length', args: { limit, encoding }, operator }); +}; -var CHOMPING_CLIP = 1; -var CHOMPING_STRIP = 2; -var CHOMPING_KEEP = 3; +/***/ }), -var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; -var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/; -var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/; -var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i; -var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i; +/***/ 40971: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +"use strict"; -function _class(obj) { return Object.prototype.toString.call(obj); } -function is_EOL(c) { - return (c === 0x0A/* LF */) || (c === 0x0D/* CR */); -} +const Assert = __nccwpck_require__(32718); -function is_WHITE_SPACE(c) { - return (c === 0x09/* Tab */) || (c === 0x20/* Space */); -} +const Any = __nccwpck_require__(9512); -function is_WS_OR_EOL(c) { - return (c === 0x09/* Tab */) || - (c === 0x20/* Space */) || - (c === 0x0A/* LF */) || - (c === 0x0D/* CR */); -} -function is_FLOW_INDICATOR(c) { - return c === 0x2C/* , */ || - c === 0x5B/* [ */ || - c === 0x5D/* ] */ || - c === 0x7B/* { */ || - c === 0x7D/* } */; -} +const internals = {}; -function fromHexCode(c) { - var lc; - if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { - return c - 0x30; - } +internals.Map = class extends Map { - /*eslint-disable no-bitwise*/ - lc = c | 0x20; + slice() { - if ((0x61/* a */ <= lc) && (lc <= 0x66/* f */)) { - return lc - 0x61 + 10; - } + return new internals.Map(this); + } +}; - return -1; -} -function escapedHexLen(c) { - if (c === 0x78/* x */) { return 2; } - if (c === 0x75/* u */) { return 4; } - if (c === 0x55/* U */) { return 8; } - return 0; -} +module.exports = Any.extend({ -function fromDecimalCode(c) { - if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { - return c - 0x30; - } + type: 'symbol', - return -1; -} + terms: { -function simpleEscapeSequence(c) { - /* eslint-disable indent */ - return (c === 0x30/* 0 */) ? '\x00' : - (c === 0x61/* a */) ? '\x07' : - (c === 0x62/* b */) ? '\x08' : - (c === 0x74/* t */) ? '\x09' : - (c === 0x09/* Tab */) ? '\x09' : - (c === 0x6E/* n */) ? '\x0A' : - (c === 0x76/* v */) ? '\x0B' : - (c === 0x66/* f */) ? '\x0C' : - (c === 0x72/* r */) ? '\x0D' : - (c === 0x65/* e */) ? '\x1B' : - (c === 0x20/* Space */) ? ' ' : - (c === 0x22/* " */) ? '\x22' : - (c === 0x2F/* / */) ? '/' : - (c === 0x5C/* \ */) ? '\x5C' : - (c === 0x4E/* N */) ? '\x85' : - (c === 0x5F/* _ */) ? '\xA0' : - (c === 0x4C/* L */) ? '\u2028' : - (c === 0x50/* P */) ? '\u2029' : ''; -} + map: { init: new internals.Map() } + }, -function charFromCodepoint(c) { - if (c <= 0xFFFF) { - return String.fromCharCode(c); - } - // Encode UTF-16 surrogate pair - // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF - return String.fromCharCode( - ((c - 0x010000) >> 10) + 0xD800, - ((c - 0x010000) & 0x03FF) + 0xDC00 - ); -} + coerce: { + method(value, { schema, error }) { -var simpleEscapeCheck = new Array(256); // integer, for fast access -var simpleEscapeMap = new Array(256); -for (var i = 0; i < 256; i++) { - simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0; - simpleEscapeMap[i] = simpleEscapeSequence(i); -} + const lookup = schema.$_terms.map.get(value); + if (lookup) { + value = lookup; + } + if (!schema._flags.only || + typeof value === 'symbol') { -function State(input, options) { - this.input = input; + return { value }; + } - this.filename = options['filename'] || null; - this.schema = options['schema'] || DEFAULT_SCHEMA; - this.onWarning = options['onWarning'] || null; - // (Hidden) Remove? makes the loader to expect YAML 1.1 documents - // if such documents have no explicit %YAML directive - this.legacy = options['legacy'] || false; + return { value, errors: error('symbol.map', { map: schema.$_terms.map }) }; + } + }, - this.json = options['json'] || false; - this.listener = options['listener'] || null; + validate(value, { error }) { - this.implicitTypes = this.schema.compiledImplicit; - this.typeMap = this.schema.compiledTypeMap; + if (typeof value !== 'symbol') { + return { value, errors: error('symbol.base') }; + } + }, - this.length = input.length; - this.position = 0; - this.line = 0; - this.lineStart = 0; - this.lineIndent = 0; + rules: { + map: { + method(iterable) { - // position of first leading tab in the current line, - // used to make sure there are no tabs in the indentation - this.firstTabInLine = -1; + if (iterable && + !iterable[Symbol.iterator] && + typeof iterable === 'object') { - this.documents = []; + iterable = Object.entries(iterable); + } - /* - this.version; - this.checkLineBreaks; - this.tagMap; - this.anchorMap; - this.tag; - this.anchor; - this.kind; - this.result;*/ + Assert(iterable && iterable[Symbol.iterator], 'Iterable must be an iterable or object'); -} + const obj = this.clone(); + const symbols = []; + for (const entry of iterable) { + Assert(entry && entry[Symbol.iterator], 'Entry must be an iterable'); + const [key, value] = entry; -function generateError(state, message) { - var mark = { - name: state.filename, - buffer: state.input.slice(0, -1), // omit trailing \0 - position: state.position, - line: state.line, - column: state.position - state.lineStart - }; + Assert(typeof key !== 'object' && typeof key !== 'function' && typeof key !== 'symbol', 'Key must not be of type object, function, or Symbol'); + Assert(typeof value === 'symbol', 'Value must be a Symbol'); - mark.snippet = makeSnippet(mark); + obj.$_terms.map.set(key, value); + symbols.push(value); + } - return new YAMLException(message, mark); -} + return obj.valid(...symbols); + } + } + }, -function throwError(state, message) { - throw generateError(state, message); -} + manifest: { -function throwWarning(state, message) { - if (state.onWarning) { - state.onWarning.call(null, generateError(state, message)); - } -} + build(obj, desc) { + if (desc.map) { + obj = obj.map(desc.map); + } -var directiveHandlers = { + return obj; + } + }, - YAML: function handleYamlDirective(state, name, args) { + messages: { + 'symbol.base': '{{#label}} must be a symbol', + 'symbol.map': '{{#label}} must be one of {{#map}}' + } +}); - var match, major, minor; - if (state.version !== null) { - throwError(state, 'duplication of %YAML directive'); - } +/***/ }), - if (args.length !== 1) { - throwError(state, 'YAML directive accepts exactly one argument'); - } +/***/ 91804: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]); +"use strict"; - if (match === null) { - throwError(state, 'ill-formed argument of the YAML directive'); - } - major = parseInt(match[1], 10); - minor = parseInt(match[2], 10); +const Assert = __nccwpck_require__(32718); +const Clone = __nccwpck_require__(85578); +const Ignore = __nccwpck_require__(12887); +const Reach = __nccwpck_require__(18891); - if (major !== 1) { - throwError(state, 'unacceptable YAML version of the document'); - } +const Common = __nccwpck_require__(72448); +const Errors = __nccwpck_require__(69490); +const State = __nccwpck_require__(73634); - state.version = args[0]; - state.checkLineBreaks = (minor < 2); - if (minor !== 1 && minor !== 2) { - throwWarning(state, 'unsupported YAML version of the document'); - } - }, +const internals = { + result: Symbol('result') +}; - TAG: function handleTagDirective(state, name, args) { - var handle, prefix; +exports.entry = function (value, schema, prefs) { - if (args.length !== 2) { - throwError(state, 'TAG directive accepts exactly two arguments'); + let settings = Common.defaults; + if (prefs) { + Assert(prefs.warnings === undefined, 'Cannot override warnings preference in synchronous validation'); + Assert(prefs.artifacts === undefined, 'Cannot override artifacts preference in synchronous validation'); + settings = Common.preferences(Common.defaults, prefs); } - handle = args[0]; - prefix = args[1]; + const result = internals.entry(value, schema, settings); + Assert(!result.mainstay.externals.length, 'Schema with external rules must use validateAsync()'); + const outcome = { value: result.value }; - if (!PATTERN_TAG_HANDLE.test(handle)) { - throwError(state, 'ill-formed tag handle (first argument) of the TAG directive'); + if (result.error) { + outcome.error = result.error; } - if (_hasOwnProperty.call(state.tagMap, handle)) { - throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle'); + if (result.mainstay.warnings.length) { + outcome.warning = Errors.details(result.mainstay.warnings); } - if (!PATTERN_TAG_URI.test(prefix)) { - throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive'); + if (result.mainstay.debug) { + outcome.debug = result.mainstay.debug; } - try { - prefix = decodeURIComponent(prefix); - } catch (err) { - throwError(state, 'tag prefix is malformed: ' + prefix); + if (result.mainstay.artifacts) { + outcome.artifacts = result.mainstay.artifacts; } - state.tagMap[handle] = prefix; - } + return outcome; }; -function captureSegment(state, start, end, checkJson) { - var _position, _length, _character, _result; +exports.entryAsync = async function (value, schema, prefs) { - if (start < end) { - _result = state.input.slice(start, end); + let settings = Common.defaults; + if (prefs) { + settings = Common.preferences(Common.defaults, prefs); + } - if (checkJson) { - for (_position = 0, _length = _result.length; _position < _length; _position += 1) { - _character = _result.charCodeAt(_position); - if (!(_character === 0x09 || - (0x20 <= _character && _character <= 0x10FFFF))) { - throwError(state, 'expected valid JSON character'); + const result = internals.entry(value, schema, settings); + const mainstay = result.mainstay; + if (result.error) { + if (mainstay.debug) { + result.error.debug = mainstay.debug; } - } - } else if (PATTERN_NON_PRINTABLE.test(_result)) { - throwError(state, 'the stream contains non-printable characters'); + + throw result.error; } - state.result += _result; - } -} + if (mainstay.externals.length) { + let root = result.value; + for (const { method, path, label } of mainstay.externals) { + let node = root; + let key; + let parent; -function mergeMappings(state, destination, source, overridableKeys) { - var sourceKeys, key, index, quantity; + if (path.length) { + key = path[path.length - 1]; + parent = Reach(root, path.slice(0, -1)); + node = parent[key]; + } - if (!common.isObject(source)) { - throwError(state, 'cannot merge mappings; the provided source object is unacceptable'); - } + try { + const output = await method(node, { prefs }); + if (output === undefined || + output === node) { - sourceKeys = Object.keys(source); + continue; + } - for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) { - key = sourceKeys[index]; + if (parent) { + parent[key] = output; + } + else { + root = output; + } + } + catch (err) { + if (settings.errors.label) { + err.message += ` (${label})`; // Change message to include path + } - if (!_hasOwnProperty.call(destination, key)) { - destination[key] = source[key]; - overridableKeys[key] = true; + throw err; + } + } + + result.value = root; } - } -} -function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, - startLine, startLineStart, startPos) { + if (!settings.warnings && + !settings.debug && + !settings.artifacts) { - var index, quantity; + return result.value; + } - // The output is a plain object here, so keys can only be strings. - // We need to convert keyNode to a string, but doing so can hang the process - // (deeply nested arrays that explode exponentially using aliases). - if (Array.isArray(keyNode)) { - keyNode = Array.prototype.slice.call(keyNode); + const outcome = { value: result.value }; + if (mainstay.warnings.length) { + outcome.warning = Errors.details(mainstay.warnings); + } - for (index = 0, quantity = keyNode.length; index < quantity; index += 1) { - if (Array.isArray(keyNode[index])) { - throwError(state, 'nested arrays are not supported inside keys'); - } + if (mainstay.debug) { + outcome.debug = mainstay.debug; + } - if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') { - keyNode[index] = '[object Object]'; - } + if (mainstay.artifacts) { + outcome.artifacts = mainstay.artifacts; } - } - // Avoid code execution in load() via toString property - // (still use its own toString for arrays, timestamps, - // and whatever user schema extensions happen to have @@toStringTag) - if (typeof keyNode === 'object' && _class(keyNode) === '[object Object]') { - keyNode = '[object Object]'; - } + return outcome; +}; - keyNode = String(keyNode); +internals.entry = function (value, schema, prefs) { - if (_result === null) { - _result = {}; - } + // Prepare state - if (keyTag === 'tag:yaml.org,2002:merge') { - if (Array.isArray(valueNode)) { - for (index = 0, quantity = valueNode.length; index < quantity; index += 1) { - mergeMappings(state, _result, valueNode[index], overridableKeys); - } - } else { - mergeMappings(state, _result, valueNode, overridableKeys); - } - } else { - if (!state.json && - !_hasOwnProperty.call(overridableKeys, keyNode) && - _hasOwnProperty.call(_result, keyNode)) { - state.line = startLine || state.line; - state.lineStart = startLineStart || state.lineStart; - state.position = startPos || state.position; - throwError(state, 'duplicated mapping key'); - } + const { tracer, cleanup } = internals.tracer(schema, prefs); + const debug = prefs.debug ? [] : null; + const links = schema._ids._schemaChain ? new Map() : null; + const mainstay = { externals: [], warnings: [], tracer, debug, links }; + const schemas = schema._ids._schemaChain ? [{ schema }] : null; + const state = new State([], [], { mainstay, schemas }); - // used for this specific key only because Object.defineProperty is slow - if (keyNode === '__proto__') { - Object.defineProperty(_result, keyNode, { - configurable: true, - enumerable: true, - writable: true, - value: valueNode - }); - } else { - _result[keyNode] = valueNode; + // Validate value + + const result = exports.validate(value, schema, state, prefs); + + // Process value and errors + + if (cleanup) { + schema.$_root.untrace(); } - delete overridableKeys[keyNode]; - } - return _result; -} + const error = Errors.process(result.errors, value, prefs); + return { value: result.value, error, mainstay }; +}; -function readLineBreak(state) { - var ch; - ch = state.input.charCodeAt(state.position); +internals.tracer = function (schema, prefs) { - if (ch === 0x0A/* LF */) { - state.position++; - } else if (ch === 0x0D/* CR */) { - state.position++; - if (state.input.charCodeAt(state.position) === 0x0A/* LF */) { - state.position++; + if (schema.$_root._tracer) { + return { tracer: schema.$_root._tracer._register(schema) }; + } + + if (prefs.debug) { + Assert(schema.$_root.trace, 'Debug mode not supported'); + return { tracer: schema.$_root.trace()._register(schema), cleanup: true }; } - } else { - throwError(state, 'a line break is expected'); - } - state.line += 1; - state.lineStart = state.position; - state.firstTabInLine = -1; -} + return { tracer: internals.ignore }; +}; -function skipSeparationSpace(state, allowComments, checkIndent) { - var lineBreaks = 0, - ch = state.input.charCodeAt(state.position); - while (ch !== 0) { - while (is_WHITE_SPACE(ch)) { - if (ch === 0x09/* Tab */ && state.firstTabInLine === -1) { - state.firstTabInLine = state.position; - } - ch = state.input.charCodeAt(++state.position); +exports.validate = function (value, schema, state, prefs, overrides = {}) { + + if (schema.$_terms.whens) { + schema = schema._generate(value, state, prefs).schema; } - if (allowComments && ch === 0x23/* # */) { - do { - ch = state.input.charCodeAt(++state.position); - } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0); + // Setup state and settings + + if (schema._preferences) { + prefs = internals.prefs(schema, prefs); } - if (is_EOL(ch)) { - readLineBreak(state); + // Cache - ch = state.input.charCodeAt(state.position); - lineBreaks++; - state.lineIndent = 0; + if (schema._cache && + prefs.cache) { - while (ch === 0x20/* Space */) { - state.lineIndent++; - ch = state.input.charCodeAt(++state.position); - } - } else { - break; + const result = schema._cache.get(value); + state.mainstay.tracer.debug(state, 'validate', 'cached', !!result); + if (result) { + return result; + } } - } - if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) { - throwWarning(state, 'deficient indentation'); - } + // Helpers - return lineBreaks; -} + const createError = (code, local, localState) => schema.$_createError(code, value, local, localState || state, prefs); + const helpers = { + original: value, + prefs, + schema, + state, + error: createError, + errorsArray: internals.errorsArray, + warn: (code, local, localState) => state.mainstay.warnings.push(createError(code, local, localState)), + message: (messages, local) => schema.$_createError('custom', value, local, state, prefs, { messages }) + }; -function testDocumentSeparator(state) { - var _position = state.position, - ch; + // Prepare - ch = state.input.charCodeAt(_position); + state.mainstay.tracer.entry(schema, state); - // Condition state.position === state.lineStart is tested - // in parent on each call, for efficiency. No needs to test here again. - if ((ch === 0x2D/* - */ || ch === 0x2E/* . */) && - ch === state.input.charCodeAt(_position + 1) && - ch === state.input.charCodeAt(_position + 2)) { + const def = schema._definition; + if (def.prepare && + value !== undefined && + prefs.convert) { - _position += 3; + const prepared = def.prepare(value, helpers); + if (prepared) { + state.mainstay.tracer.value(state, 'prepare', value, prepared.value); + if (prepared.errors) { + return internals.finalize(prepared.value, [].concat(prepared.errors), helpers); // Prepare error always aborts early + } - ch = state.input.charCodeAt(_position); + value = prepared.value; + } + } - if (ch === 0 || is_WS_OR_EOL(ch)) { - return true; + // Type coercion + + if (def.coerce && + value !== undefined && + prefs.convert && + (!def.coerce.from || def.coerce.from.includes(typeof value))) { + + const coerced = def.coerce.method(value, helpers); + if (coerced) { + state.mainstay.tracer.value(state, 'coerced', value, coerced.value); + if (coerced.errors) { + return internals.finalize(coerced.value, [].concat(coerced.errors), helpers); // Coerce error always aborts early + } + + value = coerced.value; + } } - } - return false; -} + // Empty value -function writeFoldedLines(state, count) { - if (count === 1) { - state.result += ' '; - } else if (count > 1) { - state.result += common.repeat('\n', count - 1); - } -} + const empty = schema._flags.empty; + if (empty && + empty.$_match(internals.trim(value, schema), state.nest(empty), Common.defaults)) { + state.mainstay.tracer.value(state, 'empty', value, undefined); + value = undefined; + } -function readPlainScalar(state, nodeIndent, withinFlowCollection) { - var preceding, - following, - captureStart, - captureEnd, - hasPendingContent, - _line, - _lineStart, - _lineIndent, - _kind = state.kind, - _result = state.result, - ch; + // Presence requirements (required, optional, forbidden) - ch = state.input.charCodeAt(state.position); + const presence = overrides.presence || schema._flags.presence || (schema._flags._endedSwitch ? null : prefs.presence); + if (value === undefined) { + if (presence === 'forbidden') { + return internals.finalize(value, null, helpers); + } - if (is_WS_OR_EOL(ch) || - is_FLOW_INDICATOR(ch) || - ch === 0x23/* # */ || - ch === 0x26/* & */ || - ch === 0x2A/* * */ || - ch === 0x21/* ! */ || - ch === 0x7C/* | */ || - ch === 0x3E/* > */ || - ch === 0x27/* ' */ || - ch === 0x22/* " */ || - ch === 0x25/* % */ || - ch === 0x40/* @ */ || - ch === 0x60/* ` */) { - return false; - } + if (presence === 'required') { + return internals.finalize(value, [schema.$_createError('any.required', value, null, state, prefs)], helpers); + } - if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) { - following = state.input.charCodeAt(state.position + 1); + if (presence === 'optional') { + if (schema._flags.default !== Common.symbols.deepDefault) { + return internals.finalize(value, null, helpers); + } - if (is_WS_OR_EOL(following) || - withinFlowCollection && is_FLOW_INDICATOR(following)) { - return false; + state.mainstay.tracer.value(state, 'default', value, {}); + value = {}; + } + } + else if (presence === 'forbidden') { + return internals.finalize(value, [schema.$_createError('any.unknown', value, null, state, prefs)], helpers); } - } - state.kind = 'scalar'; - state.result = ''; - captureStart = captureEnd = state.position; - hasPendingContent = false; + // Allowed values - while (ch !== 0) { - if (ch === 0x3A/* : */) { - following = state.input.charCodeAt(state.position + 1); + const errors = []; - if (is_WS_OR_EOL(following) || - withinFlowCollection && is_FLOW_INDICATOR(following)) { - break; - } + if (schema._valids) { + const match = schema._valids.get(value, state, prefs, schema._flags.insensitive); + if (match) { + if (prefs.convert) { + state.mainstay.tracer.value(state, 'valids', value, match.value); + value = match.value; + } - } else if (ch === 0x23/* # */) { - preceding = state.input.charCodeAt(state.position - 1); + state.mainstay.tracer.filter(schema, state, 'valid', match); + return internals.finalize(value, null, helpers); + } - if (is_WS_OR_EOL(preceding)) { - break; - } + if (schema._flags.only) { + const report = schema.$_createError('any.only', value, { valids: schema._valids.values({ display: true }) }, state, prefs); + if (prefs.abortEarly) { + return internals.finalize(value, [report], helpers); + } - } else if ((state.position === state.lineStart && testDocumentSeparator(state)) || - withinFlowCollection && is_FLOW_INDICATOR(ch)) { - break; + errors.push(report); + } + } - } else if (is_EOL(ch)) { - _line = state.line; - _lineStart = state.lineStart; - _lineIndent = state.lineIndent; - skipSeparationSpace(state, false, -1); + // Denied values - if (state.lineIndent >= nodeIndent) { - hasPendingContent = true; - ch = state.input.charCodeAt(state.position); - continue; - } else { - state.position = captureEnd; - state.line = _line; - state.lineStart = _lineStart; - state.lineIndent = _lineIndent; - break; - } + if (schema._invalids) { + const match = schema._invalids.get(value, state, prefs, schema._flags.insensitive); + if (match) { + state.mainstay.tracer.filter(schema, state, 'invalid', match); + const report = schema.$_createError('any.invalid', value, { invalids: schema._invalids.values({ display: true }) }, state, prefs); + if (prefs.abortEarly) { + return internals.finalize(value, [report], helpers); + } + + errors.push(report); + } } - if (hasPendingContent) { - captureSegment(state, captureStart, captureEnd, false); - writeFoldedLines(state, state.line - _line); - captureStart = captureEnd = state.position; - hasPendingContent = false; + // Base type + + if (def.validate) { + const base = def.validate(value, helpers); + if (base) { + state.mainstay.tracer.value(state, 'base', value, base.value); + value = base.value; + + if (base.errors) { + if (!Array.isArray(base.errors)) { + errors.push(base.errors); + return internals.finalize(value, errors, helpers); // Base error always aborts early + } + + if (base.errors.length) { + errors.push(...base.errors); + return internals.finalize(value, errors, helpers); // Base error always aborts early + } + } + } } - if (!is_WHITE_SPACE(ch)) { - captureEnd = state.position + 1; + // Validate tests + + if (!schema._rules.length) { + return internals.finalize(value, errors, helpers); } - ch = state.input.charCodeAt(++state.position); - } + return internals.rules(value, errors, helpers); +}; - captureSegment(state, captureStart, captureEnd, false); - if (state.result) { - return true; - } +internals.rules = function (value, errors, helpers) { - state.kind = _kind; - state.result = _result; - return false; -} + const { schema, state, prefs } = helpers; -function readSingleQuotedScalar(state, nodeIndent) { - var ch, - captureStart, captureEnd; + for (const rule of schema._rules) { + const definition = schema._definition.rules[rule.method]; - ch = state.input.charCodeAt(state.position); + // Skip rules that are also applied in coerce step - if (ch !== 0x27/* ' */) { - return false; - } + if (definition.convert && + prefs.convert) { - state.kind = 'scalar'; - state.result = ''; - state.position++; - captureStart = captureEnd = state.position; + state.mainstay.tracer.log(schema, state, 'rule', rule.name, 'full'); + continue; + } - while ((ch = state.input.charCodeAt(state.position)) !== 0) { - if (ch === 0x27/* ' */) { - captureSegment(state, captureStart, state.position, true); - ch = state.input.charCodeAt(++state.position); + // Resolve references - if (ch === 0x27/* ' */) { - captureStart = state.position; - state.position++; - captureEnd = state.position; - } else { - return true; - } + let ret; + let args = rule.args; + if (rule._resolve.length) { + args = Object.assign({}, args); // Shallow copy + for (const key of rule._resolve) { + const resolver = definition.argsByName.get(key); - } else if (is_EOL(ch)) { - captureSegment(state, captureStart, captureEnd, true); - writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); - captureStart = captureEnd = state.position; + const resolved = args[key].resolve(value, state, prefs); + const normalized = resolver.normalize ? resolver.normalize(resolved) : resolved; - } else if (state.position === state.lineStart && testDocumentSeparator(state)) { - throwError(state, 'unexpected end of the document within a single quoted scalar'); + const invalid = Common.validateArg(normalized, null, resolver); + if (invalid) { + ret = schema.$_createError('any.ref', resolved, { arg: key, ref: args[key], reason: invalid }, state, prefs); + break; + } - } else { - state.position++; - captureEnd = state.position; - } - } + args[key] = normalized; + } + } - throwError(state, 'unexpected end of the stream within a single quoted scalar'); -} + // Test rule -function readDoubleQuotedScalar(state, nodeIndent) { - var captureStart, - captureEnd, - hexLength, - hexResult, - tmp, - ch; + ret = ret || definition.validate(value, helpers, args, rule); // Use ret if already set to reference error - ch = state.input.charCodeAt(state.position); + const result = internals.rule(ret, rule); + if (result.errors) { + state.mainstay.tracer.log(schema, state, 'rule', rule.name, 'error'); - if (ch !== 0x22/* " */) { - return false; - } + if (rule.warn) { + state.mainstay.warnings.push(...result.errors); + continue; + } - state.kind = 'scalar'; - state.result = ''; - state.position++; - captureStart = captureEnd = state.position; + if (prefs.abortEarly) { + return internals.finalize(value, result.errors, helpers); + } - while ((ch = state.input.charCodeAt(state.position)) !== 0) { - if (ch === 0x22/* " */) { - captureSegment(state, captureStart, state.position, true); - state.position++; - return true; + errors.push(...result.errors); + } + else { + state.mainstay.tracer.log(schema, state, 'rule', rule.name, 'pass'); + state.mainstay.tracer.value(state, 'rule', value, result.value, rule.name); + value = result.value; + } + } - } else if (ch === 0x5C/* \ */) { - captureSegment(state, captureStart, state.position, true); - ch = state.input.charCodeAt(++state.position); + return internals.finalize(value, errors, helpers); +}; - if (is_EOL(ch)) { - skipSeparationSpace(state, false, nodeIndent); - // TODO: rework to inline fn with no type cast? - } else if (ch < 256 && simpleEscapeCheck[ch]) { - state.result += simpleEscapeMap[ch]; - state.position++; +internals.rule = function (ret, rule) { - } else if ((tmp = escapedHexLen(ch)) > 0) { - hexLength = tmp; - hexResult = 0; + if (ret instanceof Errors.Report) { + internals.error(ret, rule); + return { errors: [ret], value: null }; + } - for (; hexLength > 0; hexLength--) { - ch = state.input.charCodeAt(++state.position); + if (Array.isArray(ret) && + ret[Common.symbols.errors]) { - if ((tmp = fromHexCode(ch)) >= 0) { - hexResult = (hexResult << 4) + tmp; + ret.forEach((report) => internals.error(report, rule)); + return { errors: ret, value: null }; + } - } else { - throwError(state, 'expected hexadecimal character'); - } - } + return { errors: null, value: ret }; +}; - state.result += charFromCodepoint(hexResult); - state.position++; +internals.error = function (report, rule) { - } else { - throwError(state, 'unknown escape sequence'); - } + if (rule.message) { + report._setTemplate(rule.message); + } - captureStart = captureEnd = state.position; + return report; +}; - } else if (is_EOL(ch)) { - captureSegment(state, captureStart, captureEnd, true); - writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); - captureStart = captureEnd = state.position; - } else if (state.position === state.lineStart && testDocumentSeparator(state)) { - throwError(state, 'unexpected end of the document within a double quoted scalar'); +internals.finalize = function (value, errors, helpers) { - } else { - state.position++; - captureEnd = state.position; + errors = errors || []; + const { schema, state, prefs } = helpers; + + // Failover value + + if (errors.length) { + const failover = internals.default('failover', undefined, errors, helpers); + if (failover !== undefined) { + state.mainstay.tracer.value(state, 'failover', value, failover); + value = failover; + errors = []; + } } - } - throwError(state, 'unexpected end of the stream within a double quoted scalar'); -} + // Error override -function readFlowCollection(state, nodeIndent) { - var readNext = true, - _line, - _lineStart, - _pos, - _tag = state.tag, - _result, - _anchor = state.anchor, - following, - terminator, - isPair, - isExplicitPair, - isMapping, - overridableKeys = Object.create(null), - keyNode, - keyTag, - valueNode, - ch; + if (errors.length && + schema._flags.error) { - ch = state.input.charCodeAt(state.position); + if (typeof schema._flags.error === 'function') { + errors = schema._flags.error(errors); + if (!Array.isArray(errors)) { + errors = [errors]; + } - if (ch === 0x5B/* [ */) { - terminator = 0x5D;/* ] */ - isMapping = false; - _result = []; - } else if (ch === 0x7B/* { */) { - terminator = 0x7D;/* } */ - isMapping = true; - _result = {}; - } else { - return false; - } + for (const error of errors) { + Assert(error instanceof Error || error instanceof Errors.Report, 'error() must return an Error object'); + } + } + else { + errors = [schema._flags.error]; + } + } - if (state.anchor !== null) { - state.anchorMap[state.anchor] = _result; - } + // Default - ch = state.input.charCodeAt(++state.position); + if (value === undefined) { + const defaulted = internals.default('default', value, errors, helpers); + state.mainstay.tracer.value(state, 'default', value, defaulted); + value = defaulted; + } - while (ch !== 0) { - skipSeparationSpace(state, true, nodeIndent); + // Cast - ch = state.input.charCodeAt(state.position); + if (schema._flags.cast && + value !== undefined) { - if (ch === terminator) { - state.position++; - state.tag = _tag; - state.anchor = _anchor; - state.kind = isMapping ? 'mapping' : 'sequence'; - state.result = _result; - return true; - } else if (!readNext) { - throwError(state, 'missed comma between flow collection entries'); - } else if (ch === 0x2C/* , */) { - // "flow collection entries can never be completely empty", as per YAML 1.2, section 7.4 - throwError(state, "expected the node content, but found ','"); + const caster = schema._definition.cast[schema._flags.cast]; + if (caster.from(value)) { + const casted = caster.to(value, helpers); + state.mainstay.tracer.value(state, 'cast', value, casted, schema._flags.cast); + value = casted; + } } - keyTag = keyNode = valueNode = null; - isPair = isExplicitPair = false; + // Externals - if (ch === 0x3F/* ? */) { - following = state.input.charCodeAt(state.position + 1); + if (schema.$_terms.externals && + prefs.externals && + prefs._externals !== false) { // Disabled for matching - if (is_WS_OR_EOL(following)) { - isPair = isExplicitPair = true; - state.position++; - skipSeparationSpace(state, true, nodeIndent); - } + for (const { method } of schema.$_terms.externals) { + state.mainstay.externals.push({ method, path: state.path, label: Errors.label(schema._flags, state, prefs) }); + } } - _line = state.line; // Save the current line. - _lineStart = state.lineStart; - _pos = state.position; - composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); - keyTag = state.tag; - keyNode = state.result; - skipSeparationSpace(state, true, nodeIndent); - - ch = state.input.charCodeAt(state.position); + // Result - if ((isExplicitPair || state.line === _line) && ch === 0x3A/* : */) { - isPair = true; - ch = state.input.charCodeAt(++state.position); - skipSeparationSpace(state, true, nodeIndent); - composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); - valueNode = state.result; - } + const result = { value, errors: errors.length ? errors : null }; - if (isMapping) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos); - } else if (isPair) { - _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos)); - } else { - _result.push(keyNode); + if (schema._flags.result) { + result.value = schema._flags.result === 'strip' ? undefined : /* raw */ helpers.original; + state.mainstay.tracer.value(state, schema._flags.result, value, result.value); + state.shadow(value, schema._flags.result); } - skipSeparationSpace(state, true, nodeIndent); + // Cache - ch = state.input.charCodeAt(state.position); + if (schema._cache && + prefs.cache !== false && + !schema._refs.length) { - if (ch === 0x2C/* , */) { - readNext = true; - ch = state.input.charCodeAt(++state.position); - } else { - readNext = false; + schema._cache.set(helpers.original, result); } - } - throwError(state, 'unexpected end of the stream within a flow collection'); -} + // Artifacts -function readBlockScalar(state, nodeIndent) { - var captureStart, - folding, - chomping = CHOMPING_CLIP, - didReadContent = false, - detectedIndent = false, - textIndent = nodeIndent, - emptyLines = 0, - atMoreIndented = false, - tmp, - ch; + if (value !== undefined && + !result.errors && + schema._flags.artifact !== undefined) { - ch = state.input.charCodeAt(state.position); + state.mainstay.artifacts = state.mainstay.artifacts || new Map(); + if (!state.mainstay.artifacts.has(schema._flags.artifact)) { + state.mainstay.artifacts.set(schema._flags.artifact, []); + } - if (ch === 0x7C/* | */) { - folding = false; - } else if (ch === 0x3E/* > */) { - folding = true; - } else { - return false; - } + state.mainstay.artifacts.get(schema._flags.artifact).push(state.path); + } - state.kind = 'scalar'; - state.result = ''; + return result; +}; - while (ch !== 0) { - ch = state.input.charCodeAt(++state.position); - if (ch === 0x2B/* + */ || ch === 0x2D/* - */) { - if (CHOMPING_CLIP === chomping) { - chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP : CHOMPING_STRIP; - } else { - throwError(state, 'repeat of a chomping mode identifier'); - } +internals.prefs = function (schema, prefs) { - } else if ((tmp = fromDecimalCode(ch)) >= 0) { - if (tmp === 0) { - throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one'); - } else if (!detectedIndent) { - textIndent = nodeIndent + tmp - 1; - detectedIndent = true; - } else { - throwError(state, 'repeat of an indentation width identifier'); - } + const isDefaultOptions = prefs === Common.defaults; + if (isDefaultOptions && + schema._preferences[Common.symbols.prefs]) { - } else { - break; + return schema._preferences[Common.symbols.prefs]; } - } - - if (is_WHITE_SPACE(ch)) { - do { ch = state.input.charCodeAt(++state.position); } - while (is_WHITE_SPACE(ch)); - if (ch === 0x23/* # */) { - do { ch = state.input.charCodeAt(++state.position); } - while (!is_EOL(ch) && (ch !== 0)); + prefs = Common.preferences(prefs, schema._preferences); + if (isDefaultOptions) { + schema._preferences[Common.symbols.prefs] = prefs; } - } - while (ch !== 0) { - readLineBreak(state); - state.lineIndent = 0; + return prefs; +}; - ch = state.input.charCodeAt(state.position); - while ((!detectedIndent || state.lineIndent < textIndent) && - (ch === 0x20/* Space */)) { - state.lineIndent++; - ch = state.input.charCodeAt(++state.position); - } +internals.default = function (flag, value, errors, helpers) { - if (!detectedIndent && state.lineIndent > textIndent) { - textIndent = state.lineIndent; + const { schema, state, prefs } = helpers; + const source = schema._flags[flag]; + if (prefs.noDefaults || + source === undefined) { + + return value; } - if (is_EOL(ch)) { - emptyLines++; - continue; + state.mainstay.tracer.log(schema, state, 'rule', flag, 'full'); + + if (!source) { + return source; } - // End of the scalar. - if (state.lineIndent < textIndent) { + if (typeof source === 'function') { + const args = source.length ? [Clone(state.ancestors[0]), helpers] : []; - // Perform the chomping. - if (chomping === CHOMPING_KEEP) { - state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); - } else if (chomping === CHOMPING_CLIP) { - if (didReadContent) { // i.e. only if the scalar is not empty. - state.result += '\n'; + try { + return source(...args); } - } + catch (err) { + errors.push(schema.$_createError(`any.${flag}`, null, { error: err }, state, prefs)); + return; + } + } - // Break this `while` cycle and go to the funciton's epilogue. - break; + if (typeof source !== 'object') { + return source; } - // Folded style: use fancy rules to handle line breaks. - if (folding) { + if (source[Common.symbols.literal]) { + return source.literal; + } - // Lines starting with white space characters (more-indented lines) are not folded. - if (is_WHITE_SPACE(ch)) { - atMoreIndented = true; - // except for the first content line (cf. Example 8.1) - state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + if (Common.isResolvable(source)) { + return source.resolve(value, state, prefs); + } - // End of more-indented block. - } else if (atMoreIndented) { - atMoreIndented = false; - state.result += common.repeat('\n', emptyLines + 1); + return Clone(source); +}; - // Just one line break - perceive as the same line. - } else if (emptyLines === 0) { - if (didReadContent) { // i.e. only if we have already read some scalar content. - state.result += ' '; - } - // Several line breaks - perceive as different lines. - } else { - state.result += common.repeat('\n', emptyLines); - } +internals.trim = function (value, schema) { - // Literal style: just add exact number of line breaks between content lines. - } else { - // Keep all line breaks except the header line break. - state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + if (typeof value !== 'string') { + return value; } - didReadContent = true; - detectedIndent = true; - emptyLines = 0; - captureStart = state.position; + const trim = schema.$_getRule('trim'); + if (!trim || + !trim.args.enabled) { - while (!is_EOL(ch) && (ch !== 0)) { - ch = state.input.charCodeAt(++state.position); + return value; } - captureSegment(state, captureStart, state.position, false); - } + return value.trim(); +}; - return true; -} -function readBlockSequence(state, nodeIndent) { - var _line, - _tag = state.tag, - _anchor = state.anchor, - _result = [], - following, - detected = false, - ch; +internals.ignore = { + active: false, + debug: Ignore, + entry: Ignore, + filter: Ignore, + log: Ignore, + resolve: Ignore, + value: Ignore +}; - // there is a leading tab before this token, so it can't be a block sequence/mapping; - // it can still be flow sequence/mapping or a scalar - if (state.firstTabInLine !== -1) return false; - if (state.anchor !== null) { - state.anchorMap[state.anchor] = _result; - } +internals.errorsArray = function () { - ch = state.input.charCodeAt(state.position); + const errors = []; + errors[Common.symbols.errors] = true; + return errors; +}; - while (ch !== 0) { - if (state.firstTabInLine !== -1) { - state.position = state.firstTabInLine; - throwError(state, 'tab characters must not be used in indentation'); - } - if (ch !== 0x2D/* - */) { - break; - } +/***/ }), - following = state.input.charCodeAt(state.position + 1); +/***/ 71944: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (!is_WS_OR_EOL(following)) { - break; - } +"use strict"; - detected = true; - state.position++; - if (skipSeparationSpace(state, true, -1)) { - if (state.lineIndent <= nodeIndent) { - _result.push(null); - ch = state.input.charCodeAt(state.position); - continue; - } - } +const Assert = __nccwpck_require__(32718); +const DeepEqual = __nccwpck_require__(55801); - _line = state.line; - composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true); - _result.push(state.result); - skipSeparationSpace(state, true, -1); +const Common = __nccwpck_require__(72448); - ch = state.input.charCodeAt(state.position); - if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { - throwError(state, 'bad indentation of a sequence entry'); - } else if (state.lineIndent < nodeIndent) { - break; - } - } +const internals = {}; - if (detected) { - state.tag = _tag; - state.anchor = _anchor; - state.kind = 'sequence'; - state.result = _result; - return true; - } - return false; -} -function readBlockMapping(state, nodeIndent, flowIndent) { - var following, - allowCompact, - _line, - _keyLine, - _keyLineStart, - _keyPos, - _tag = state.tag, - _anchor = state.anchor, - _result = {}, - overridableKeys = Object.create(null), - keyTag = null, - keyNode = null, - valueNode = null, - atExplicitKey = false, - detected = false, - ch; +module.exports = internals.Values = class { - // there is a leading tab before this token, so it can't be a block sequence/mapping; - // it can still be flow sequence/mapping or a scalar - if (state.firstTabInLine !== -1) return false; + constructor(values, refs) { - if (state.anchor !== null) { - state.anchorMap[state.anchor] = _result; - } + this._values = new Set(values); + this._refs = new Set(refs); + this._lowercase = internals.lowercases(values); - ch = state.input.charCodeAt(state.position); + this._override = false; + } - while (ch !== 0) { - if (!atExplicitKey && state.firstTabInLine !== -1) { - state.position = state.firstTabInLine; - throwError(state, 'tab characters must not be used in indentation'); + get length() { + + return this._values.size + this._refs.size; } - following = state.input.charCodeAt(state.position + 1); - _line = state.line; // Save the current line. + add(value, refs) { - // - // Explicit notation case. There are two separate blocks: - // first for the key (denoted by "?") and second for the value (denoted by ":") - // - if ((ch === 0x3F/* ? */ || ch === 0x3A/* : */) && is_WS_OR_EOL(following)) { + // Reference - if (ch === 0x3F/* ? */) { - if (atExplicitKey) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); - keyTag = keyNode = valueNode = null; - } + if (Common.isResolvable(value)) { + if (!this._refs.has(value)) { + this._refs.add(value); - detected = true; - atExplicitKey = true; - allowCompact = true; + if (refs) { // Skipped in a merge + refs.register(value); + } + } - } else if (atExplicitKey) { - // i.e. 0x3A/* : */ === character after the explicit key. - atExplicitKey = false; - allowCompact = true; + return; + } - } else { - throwError(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line'); - } + // Value - state.position += 1; - ch = following; + if (!this.has(value, null, null, false)) { + this._values.add(value); - // - // Implicit notation case. Flow-style node as the key first, then ":", and the value. - // - } else { - _keyLine = state.line; - _keyLineStart = state.lineStart; - _keyPos = state.position; + if (typeof value === 'string') { + this._lowercase.set(value.toLowerCase(), value); + } + } + } - if (!composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) { - // Neither implicit nor explicit notation. - // Reading is done. Go to the epilogue. - break; - } + static merge(target, source, remove) { - if (state.line === _line) { - ch = state.input.charCodeAt(state.position); + target = target || new internals.Values(); - while (is_WHITE_SPACE(ch)) { - ch = state.input.charCodeAt(++state.position); - } + if (source) { + if (source._override) { + return source.clone(); + } - if (ch === 0x3A/* : */) { - ch = state.input.charCodeAt(++state.position); + for (const item of [...source._values, ...source._refs]) { + target.add(item); + } + } - if (!is_WS_OR_EOL(ch)) { - throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping'); - } + if (remove) { + for (const item of [...remove._values, ...remove._refs]) { + target.remove(item); + } + } - if (atExplicitKey) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); - keyTag = keyNode = valueNode = null; - } + return target.length ? target : null; + } - detected = true; - atExplicitKey = false; - allowCompact = false; - keyTag = state.tag; - keyNode = state.result; + remove(value) { - } else if (detected) { - throwError(state, 'can not read an implicit mapping pair; a colon is missed'); + // Reference - } else { - state.tag = _tag; - state.anchor = _anchor; - return true; // Keep the result of `composeNode`. + if (Common.isResolvable(value)) { + this._refs.delete(value); + return; } - } else if (detected) { - throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key'); + // Value - } else { - state.tag = _tag; - state.anchor = _anchor; - return true; // Keep the result of `composeNode`. - } + this._values.delete(value); + + if (typeof value === 'string') { + this._lowercase.delete(value.toLowerCase()); + } } - // - // Common reading code for both explicit and implicit notations. - // - if (state.line === _line || state.lineIndent > nodeIndent) { - if (atExplicitKey) { - _keyLine = state.line; - _keyLineStart = state.lineStart; - _keyPos = state.position; - } + has(value, state, prefs, insensitive) { - if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) { - if (atExplicitKey) { - keyNode = state.result; - } else { - valueNode = state.result; + return !!this.get(value, state, prefs, insensitive); + } + + get(value, state, prefs, insensitive) { + + if (!this.length) { + return false; } - } - if (!atExplicitKey) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _keyLine, _keyLineStart, _keyPos); - keyTag = keyNode = valueNode = null; - } + // Simple match - skipSeparationSpace(state, true, -1); - ch = state.input.charCodeAt(state.position); - } + if (this._values.has(value)) { + return { value }; + } - if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { - throwError(state, 'bad indentation of a mapping entry'); - } else if (state.lineIndent < nodeIndent) { - break; - } - } + // Case insensitive string match - // - // Epilogue. - // + if (typeof value === 'string' && + value && + insensitive) { - // Special case: last mapping's node contains only the key in explicit notation. - if (atExplicitKey) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); - } + const found = this._lowercase.get(value.toLowerCase()); + if (found) { + return { value: found }; + } + } - // Expose the resulting mapping. - if (detected) { - state.tag = _tag; - state.anchor = _anchor; - state.kind = 'mapping'; - state.result = _result; - } + if (!this._refs.size && + typeof value !== 'object') { - return detected; -} + return false; + } -function readTagProperty(state) { - var _position, - isVerbatim = false, - isNamed = false, - tagHandle, - tagName, - ch; + // Objects - ch = state.input.charCodeAt(state.position); + if (typeof value === 'object') { + for (const item of this._values) { + if (DeepEqual(item, value)) { + return { value: item }; + } + } + } - if (ch !== 0x21/* ! */) return false; + // References - if (state.tag !== null) { - throwError(state, 'duplication of a tag property'); - } + if (state) { + for (const ref of this._refs) { + const resolved = ref.resolve(value, state, prefs, null, { in: true }); + if (resolved === undefined) { + continue; + } - ch = state.input.charCodeAt(++state.position); + const items = !ref.in || typeof resolved !== 'object' + ? [resolved] + : Array.isArray(resolved) ? resolved : Object.keys(resolved); - if (ch === 0x3C/* < */) { - isVerbatim = true; - ch = state.input.charCodeAt(++state.position); + for (const item of items) { + if (typeof item !== typeof value) { + continue; + } - } else if (ch === 0x21/* ! */) { - isNamed = true; - tagHandle = '!!'; - ch = state.input.charCodeAt(++state.position); + if (insensitive && + value && + typeof value === 'string') { - } else { - tagHandle = '!'; - } + if (item.toLowerCase() === value.toLowerCase()) { + return { value: item, ref }; + } + } + else { + if (DeepEqual(item, value)) { + return { value: item, ref }; + } + } + } + } + } - _position = state.position; + return false; + } - if (isVerbatim) { - do { ch = state.input.charCodeAt(++state.position); } - while (ch !== 0 && ch !== 0x3E/* > */); + override() { - if (state.position < state.length) { - tagName = state.input.slice(_position, state.position); - ch = state.input.charCodeAt(++state.position); - } else { - throwError(state, 'unexpected end of the stream within a verbatim tag'); + this._override = true; } - } else { - while (ch !== 0 && !is_WS_OR_EOL(ch)) { - if (ch === 0x21/* ! */) { - if (!isNamed) { - tagHandle = state.input.slice(_position - 1, state.position + 1); + values(options) { - if (!PATTERN_TAG_HANDLE.test(tagHandle)) { - throwError(state, 'named tag handle cannot contain such characters'); - } + if (options && + options.display) { - isNamed = true; - _position = state.position + 1; - } else { - throwError(state, 'tag suffix cannot contain exclamation marks'); + const values = []; + + for (const item of [...this._values, ...this._refs]) { + if (item !== undefined) { + values.push(item); + } + } + + return values; } - } - ch = state.input.charCodeAt(++state.position); + return Array.from([...this._values, ...this._refs]); } - tagName = state.input.slice(_position, state.position); + clone() { - if (PATTERN_FLOW_INDICATORS.test(tagName)) { - throwError(state, 'tag suffix cannot contain flow indicator characters'); + const set = new internals.Values(this._values, this._refs); + set._override = this._override; + return set; } - } - if (tagName && !PATTERN_TAG_URI.test(tagName)) { - throwError(state, 'tag name cannot contain such characters: ' + tagName); - } - - try { - tagName = decodeURIComponent(tagName); - } catch (err) { - throwError(state, 'tag name is malformed: ' + tagName); - } + concat(source) { - if (isVerbatim) { - state.tag = tagName; + Assert(!source._override, 'Cannot concat override set of values'); - } else if (_hasOwnProperty.call(state.tagMap, tagHandle)) { - state.tag = state.tagMap[tagHandle] + tagName; + const set = new internals.Values([...this._values, ...source._values], [...this._refs, ...source._refs]); + set._override = this._override; + return set; + } - } else if (tagHandle === '!') { - state.tag = '!' + tagName; + describe() { - } else if (tagHandle === '!!') { - state.tag = 'tag:yaml.org,2002:' + tagName; + const normalized = []; - } else { - throwError(state, 'undeclared tag handle "' + tagHandle + '"'); - } + if (this._override) { + normalized.push({ override: true }); + } - return true; -} + for (const value of this._values.values()) { + normalized.push(value && typeof value === 'object' ? { value } : value); + } -function readAnchorProperty(state) { - var _position, - ch; + for (const value of this._refs.values()) { + normalized.push(value.describe()); + } - ch = state.input.charCodeAt(state.position); + return normalized; + } +}; - if (ch !== 0x26/* & */) return false; - if (state.anchor !== null) { - throwError(state, 'duplication of an anchor property'); - } +internals.Values.prototype[Common.symbols.values] = true; - ch = state.input.charCodeAt(++state.position); - _position = state.position; - while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { - ch = state.input.charCodeAt(++state.position); - } +// Aliases - if (state.position === _position) { - throwError(state, 'name of an anchor node must contain at least one character'); - } +internals.Values.prototype.slice = internals.Values.prototype.clone; - state.anchor = state.input.slice(_position, state.position); - return true; -} -function readAlias(state) { - var _position, alias, - ch; +// Helpers - ch = state.input.charCodeAt(state.position); +internals.lowercases = function (from) { - if (ch !== 0x2A/* * */) return false; + const map = new Map(); - ch = state.input.charCodeAt(++state.position); - _position = state.position; + if (from) { + for (const value of from) { + if (typeof value === 'string') { + map.set(value.toLowerCase(), value); + } + } + } - while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { - ch = state.input.charCodeAt(++state.position); - } + return map; +}; - if (state.position === _position) { - throwError(state, 'name of an alias node must contain at least one character'); - } - alias = state.input.slice(_position, state.position); +/***/ }), - if (!_hasOwnProperty.call(state.anchorMap, alias)) { - throwError(state, 'unidentified alias "' + alias + '"'); - } +/***/ 21917: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - state.result = state.anchorMap[alias]; - skipSeparationSpace(state, true, -1); - return true; -} +"use strict"; -function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) { - var allowBlockStyles, - allowBlockScalars, - allowBlockCollections, - indentStatus = 1, // 1: this>parent, 0: this=parent, -1: this parentIndent) { - indentStatus = 1; - } else if (state.lineIndent === parentIndent) { - indentStatus = 0; - } else if (state.lineIndent < parentIndent) { - indentStatus = -1; - } - } - } - if (indentStatus === 1) { - while (readTagProperty(state) || readAnchorProperty(state)) { - if (skipSeparationSpace(state, true, -1)) { - atNewLine = true; - allowBlockCollections = allowBlockStyles; +module.exports.Type = __nccwpck_require__(6073); +module.exports.Schema = __nccwpck_require__(21082); +module.exports.FAILSAFE_SCHEMA = __nccwpck_require__(28562); +module.exports.JSON_SCHEMA = __nccwpck_require__(1035); +module.exports.CORE_SCHEMA = __nccwpck_require__(12011); +module.exports.DEFAULT_SCHEMA = __nccwpck_require__(18759); +module.exports.load = loader.load; +module.exports.loadAll = loader.loadAll; +module.exports.dump = dumper.dump; +module.exports.YAMLException = __nccwpck_require__(68179); - if (state.lineIndent > parentIndent) { - indentStatus = 1; - } else if (state.lineIndent === parentIndent) { - indentStatus = 0; - } else if (state.lineIndent < parentIndent) { - indentStatus = -1; - } - } else { - allowBlockCollections = false; - } - } - } +// Re-export all types in case user wants to create custom schema +module.exports.types = { + binary: __nccwpck_require__(77900), + float: __nccwpck_require__(42705), + map: __nccwpck_require__(86150), + null: __nccwpck_require__(20721), + pairs: __nccwpck_require__(96860), + set: __nccwpck_require__(79548), + timestamp: __nccwpck_require__(99212), + bool: __nccwpck_require__(64993), + int: __nccwpck_require__(11615), + merge: __nccwpck_require__(86104), + omap: __nccwpck_require__(19046), + seq: __nccwpck_require__(67283), + str: __nccwpck_require__(23619) +}; - if (allowBlockCollections) { - allowBlockCollections = atNewLine || allowCompact; - } +// Removed functions from JS-YAML 3.0.x +module.exports.safeLoad = renamed('safeLoad', 'load'); +module.exports.safeLoadAll = renamed('safeLoadAll', 'loadAll'); +module.exports.safeDump = renamed('safeDump', 'dump'); - if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) { - if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) { - flowIndent = parentIndent; - } else { - flowIndent = parentIndent + 1; - } - blockIndent = state.position - state.lineStart; +/***/ }), - if (indentStatus === 1) { - if (allowBlockCollections && - (readBlockSequence(state, blockIndent) || - readBlockMapping(state, blockIndent, flowIndent)) || - readFlowCollection(state, flowIndent)) { - hasContent = true; - } else { - if ((allowBlockScalars && readBlockScalar(state, flowIndent)) || - readSingleQuotedScalar(state, flowIndent) || - readDoubleQuotedScalar(state, flowIndent)) { - hasContent = true; +/***/ 26829: +/***/ ((module) => { - } else if (readAlias(state)) { - hasContent = true; +"use strict"; - if (state.tag !== null || state.anchor !== null) { - throwError(state, 'alias node should not have any properties'); - } - } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) { - hasContent = true; - if (state.tag === null) { - state.tag = '?'; - } - } +function isNothing(subject) { + return (typeof subject === 'undefined') || (subject === null); +} - if (state.anchor !== null) { - state.anchorMap[state.anchor] = state.result; - } - } - } else if (indentStatus === 0) { - // Special case: block sequences are allowed to have same indentation level as the parent. - // http://www.yaml.org/spec/1.2/spec.html#id2799784 - hasContent = allowBlockCollections && readBlockSequence(state, blockIndent); - } - } - if (state.tag === null) { - if (state.anchor !== null) { - state.anchorMap[state.anchor] = state.result; - } +function isObject(subject) { + return (typeof subject === 'object') && (subject !== null); +} - } else if (state.tag === '?') { - // Implicit resolving is not allowed for non-scalar types, and '?' - // non-specific tag is only automatically assigned to plain scalars. - // - // We only need to check kind conformity in case user explicitly assigns '?' - // tag, for example like this: "! [0]" - // - if (state.result !== null && state.kind !== 'scalar') { - throwError(state, 'unacceptable node kind for ! tag; it should be "scalar", not "' + state.kind + '"'); - } - for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) { - type = state.implicitTypes[typeIndex]; +function toArray(sequence) { + if (Array.isArray(sequence)) return sequence; + else if (isNothing(sequence)) return []; - if (type.resolve(state.result)) { // `state.result` updated in resolver if matched - state.result = type.construct(state.result); - state.tag = type.tag; - if (state.anchor !== null) { - state.anchorMap[state.anchor] = state.result; - } - break; - } - } - } else if (state.tag !== '!') { - if (_hasOwnProperty.call(state.typeMap[state.kind || 'fallback'], state.tag)) { - type = state.typeMap[state.kind || 'fallback'][state.tag]; - } else { - // looking for multi type - type = null; - typeList = state.typeMap.multi[state.kind || 'fallback']; + return [ sequence ]; +} - for (typeIndex = 0, typeQuantity = typeList.length; typeIndex < typeQuantity; typeIndex += 1) { - if (state.tag.slice(0, typeList[typeIndex].tag.length) === typeList[typeIndex].tag) { - type = typeList[typeIndex]; - break; - } - } - } - if (!type) { - throwError(state, 'unknown tag !<' + state.tag + '>'); - } +function extend(target, source) { + var index, length, key, sourceKeys; - if (state.result !== null && type.kind !== state.kind) { - throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be "' + type.kind + '", not "' + state.kind + '"'); - } + if (source) { + sourceKeys = Object.keys(source); - if (!type.resolve(state.result, state.tag)) { // `state.result` updated in resolver if matched - throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag'); - } else { - state.result = type.construct(state.result, state.tag); - if (state.anchor !== null) { - state.anchorMap[state.anchor] = state.result; - } + for (index = 0, length = sourceKeys.length; index < length; index += 1) { + key = sourceKeys[index]; + target[key] = source[key]; } } - if (state.listener !== null) { - state.listener('close', state); + return target; +} + + +function repeat(string, count) { + var result = '', cycle; + + for (cycle = 0; cycle < count; cycle += 1) { + result += string; } - return state.tag !== null || state.anchor !== null || hasContent; + + return result; } -function readDocument(state) { - var documentStart = state.position, - _position, - directiveName, - directiveArgs, - hasDirectives = false, - ch; - state.version = null; - state.checkLineBreaks = state.legacy; - state.tagMap = Object.create(null); - state.anchorMap = Object.create(null); +function isNegativeZero(number) { + return (number === 0) && (Number.NEGATIVE_INFINITY === 1 / number); +} - while ((ch = state.input.charCodeAt(state.position)) !== 0) { - skipSeparationSpace(state, true, -1); - ch = state.input.charCodeAt(state.position); +module.exports.isNothing = isNothing; +module.exports.isObject = isObject; +module.exports.toArray = toArray; +module.exports.repeat = repeat; +module.exports.isNegativeZero = isNegativeZero; +module.exports.extend = extend; - if (state.lineIndent > 0 || ch !== 0x25/* % */) { - break; - } - hasDirectives = true; - ch = state.input.charCodeAt(++state.position); - _position = state.position; +/***/ }), + +/***/ 68866: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; - while (ch !== 0 && !is_WS_OR_EOL(ch)) { - ch = state.input.charCodeAt(++state.position); - } - directiveName = state.input.slice(_position, state.position); - directiveArgs = []; +/*eslint-disable no-use-before-define*/ - if (directiveName.length < 1) { - throwError(state, 'directive name must not be less than one character in length'); - } +var common = __nccwpck_require__(26829); +var YAMLException = __nccwpck_require__(68179); +var DEFAULT_SCHEMA = __nccwpck_require__(18759); - while (ch !== 0) { - while (is_WHITE_SPACE(ch)) { - ch = state.input.charCodeAt(++state.position); - } +var _toString = Object.prototype.toString; +var _hasOwnProperty = Object.prototype.hasOwnProperty; - if (ch === 0x23/* # */) { - do { ch = state.input.charCodeAt(++state.position); } - while (ch !== 0 && !is_EOL(ch)); - break; - } +var CHAR_BOM = 0xFEFF; +var CHAR_TAB = 0x09; /* Tab */ +var CHAR_LINE_FEED = 0x0A; /* LF */ +var CHAR_CARRIAGE_RETURN = 0x0D; /* CR */ +var CHAR_SPACE = 0x20; /* Space */ +var CHAR_EXCLAMATION = 0x21; /* ! */ +var CHAR_DOUBLE_QUOTE = 0x22; /* " */ +var CHAR_SHARP = 0x23; /* # */ +var CHAR_PERCENT = 0x25; /* % */ +var CHAR_AMPERSAND = 0x26; /* & */ +var CHAR_SINGLE_QUOTE = 0x27; /* ' */ +var CHAR_ASTERISK = 0x2A; /* * */ +var CHAR_COMMA = 0x2C; /* , */ +var CHAR_MINUS = 0x2D; /* - */ +var CHAR_COLON = 0x3A; /* : */ +var CHAR_EQUALS = 0x3D; /* = */ +var CHAR_GREATER_THAN = 0x3E; /* > */ +var CHAR_QUESTION = 0x3F; /* ? */ +var CHAR_COMMERCIAL_AT = 0x40; /* @ */ +var CHAR_LEFT_SQUARE_BRACKET = 0x5B; /* [ */ +var CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */ +var CHAR_GRAVE_ACCENT = 0x60; /* ` */ +var CHAR_LEFT_CURLY_BRACKET = 0x7B; /* { */ +var CHAR_VERTICAL_LINE = 0x7C; /* | */ +var CHAR_RIGHT_CURLY_BRACKET = 0x7D; /* } */ - if (is_EOL(ch)) break; +var ESCAPE_SEQUENCES = {}; - _position = state.position; +ESCAPE_SEQUENCES[0x00] = '\\0'; +ESCAPE_SEQUENCES[0x07] = '\\a'; +ESCAPE_SEQUENCES[0x08] = '\\b'; +ESCAPE_SEQUENCES[0x09] = '\\t'; +ESCAPE_SEQUENCES[0x0A] = '\\n'; +ESCAPE_SEQUENCES[0x0B] = '\\v'; +ESCAPE_SEQUENCES[0x0C] = '\\f'; +ESCAPE_SEQUENCES[0x0D] = '\\r'; +ESCAPE_SEQUENCES[0x1B] = '\\e'; +ESCAPE_SEQUENCES[0x22] = '\\"'; +ESCAPE_SEQUENCES[0x5C] = '\\\\'; +ESCAPE_SEQUENCES[0x85] = '\\N'; +ESCAPE_SEQUENCES[0xA0] = '\\_'; +ESCAPE_SEQUENCES[0x2028] = '\\L'; +ESCAPE_SEQUENCES[0x2029] = '\\P'; - while (ch !== 0 && !is_WS_OR_EOL(ch)) { - ch = state.input.charCodeAt(++state.position); - } +var DEPRECATED_BOOLEANS_SYNTAX = [ + 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON', + 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF' +]; - directiveArgs.push(state.input.slice(_position, state.position)); - } +var DEPRECATED_BASE60_SYNTAX = /^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/; - if (ch !== 0) readLineBreak(state); +function compileStyleMap(schema, map) { + var result, keys, index, length, tag, style, type; - if (_hasOwnProperty.call(directiveHandlers, directiveName)) { - directiveHandlers[directiveName](state, directiveName, directiveArgs); - } else { - throwWarning(state, 'unknown document directive "' + directiveName + '"'); - } - } + if (map === null) return {}; - skipSeparationSpace(state, true, -1); + result = {}; + keys = Object.keys(map); - if (state.lineIndent === 0 && - state.input.charCodeAt(state.position) === 0x2D/* - */ && - state.input.charCodeAt(state.position + 1) === 0x2D/* - */ && - state.input.charCodeAt(state.position + 2) === 0x2D/* - */) { - state.position += 3; - skipSeparationSpace(state, true, -1); + for (index = 0, length = keys.length; index < length; index += 1) { + tag = keys[index]; + style = String(map[tag]); - } else if (hasDirectives) { - throwError(state, 'directives end mark is expected'); - } + if (tag.slice(0, 2) === '!!') { + tag = 'tag:yaml.org,2002:' + tag.slice(2); + } + type = schema.compiledTypeMap['fallback'][tag]; - composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true); - skipSeparationSpace(state, true, -1); + if (type && _hasOwnProperty.call(type.styleAliases, style)) { + style = type.styleAliases[style]; + } - if (state.checkLineBreaks && - PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) { - throwWarning(state, 'non-ASCII line breaks are interpreted as content'); + result[tag] = style; } - state.documents.push(state.result); + return result; +} - if (state.position === state.lineStart && testDocumentSeparator(state)) { +function encodeHex(character) { + var string, handle, length; - if (state.input.charCodeAt(state.position) === 0x2E/* . */) { - state.position += 3; - skipSeparationSpace(state, true, -1); - } - return; - } + string = character.toString(16).toUpperCase(); - if (state.position < (state.length - 1)) { - throwError(state, 'end of the stream or a document separator is expected'); + if (character <= 0xFF) { + handle = 'x'; + length = 2; + } else if (character <= 0xFFFF) { + handle = 'u'; + length = 4; + } else if (character <= 0xFFFFFFFF) { + handle = 'U'; + length = 8; } else { - return; + throw new YAMLException('code point within a string may not be greater than 0xFFFFFFFF'); } + + return '\\' + handle + common.repeat('0', length - string.length) + string; } -function loadDocuments(input, options) { - input = String(input); - options = options || {}; +var QUOTING_TYPE_SINGLE = 1, + QUOTING_TYPE_DOUBLE = 2; - if (input.length !== 0) { +function State(options) { + this.schema = options['schema'] || DEFAULT_SCHEMA; + this.indent = Math.max(1, (options['indent'] || 2)); + this.noArrayIndent = options['noArrayIndent'] || false; + this.skipInvalid = options['skipInvalid'] || false; + this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']); + this.styleMap = compileStyleMap(this.schema, options['styles'] || null); + this.sortKeys = options['sortKeys'] || false; + this.lineWidth = options['lineWidth'] || 80; + this.noRefs = options['noRefs'] || false; + this.noCompatMode = options['noCompatMode'] || false; + this.condenseFlow = options['condenseFlow'] || false; + this.quotingType = options['quotingType'] === '"' ? QUOTING_TYPE_DOUBLE : QUOTING_TYPE_SINGLE; + this.forceQuotes = options['forceQuotes'] || false; + this.replacer = typeof options['replacer'] === 'function' ? options['replacer'] : null; - // Add tailing `\n` if not exists - if (input.charCodeAt(input.length - 1) !== 0x0A/* LF */ && - input.charCodeAt(input.length - 1) !== 0x0D/* CR */) { - input += '\n'; - } + this.implicitTypes = this.schema.compiledImplicit; + this.explicitTypes = this.schema.compiledExplicit; - // Strip BOM - if (input.charCodeAt(0) === 0xFEFF) { - input = input.slice(1); - } - } + this.tag = null; + this.result = ''; - var state = new State(input, options); + this.duplicates = []; + this.usedDuplicates = null; +} - var nullpos = input.indexOf('\0'); +// Indents every line in a string. Empty lines (\n only) are not indented. +function indentString(string, spaces) { + var ind = common.repeat(' ', spaces), + position = 0, + next = -1, + result = '', + line, + length = string.length; - if (nullpos !== -1) { - state.position = nullpos; - throwError(state, 'null byte is not allowed in input'); - } + while (position < length) { + next = string.indexOf('\n', position); + if (next === -1) { + line = string.slice(position); + position = length; + } else { + line = string.slice(position, next + 1); + position = next + 1; + } - // Use 0 as string terminator. That significantly simplifies bounds check. - state.input += '\0'; + if (line.length && line !== '\n') result += ind; - while (state.input.charCodeAt(state.position) === 0x20/* Space */) { - state.lineIndent += 1; - state.position += 1; + result += line; } - while (state.position < (state.length - 1)) { - readDocument(state); - } + return result; +} - return state.documents; +function generateNextLine(state, level) { + return '\n' + common.repeat(' ', state.indent * level); } +function testImplicitResolving(state, str) { + var index, length, type; + + for (index = 0, length = state.implicitTypes.length; index < length; index += 1) { + type = state.implicitTypes[index]; -function loadAll(input, iterator, options) { - if (iterator !== null && typeof iterator === 'object' && typeof options === 'undefined') { - options = iterator; - iterator = null; + if (type.resolve(str)) { + return true; + } } - var documents = loadDocuments(input, options); + return false; +} - if (typeof iterator !== 'function') { - return documents; - } +// [33] s-white ::= s-space | s-tab +function isWhitespace(c) { + return c === CHAR_SPACE || c === CHAR_TAB; +} - for (var index = 0, length = documents.length; index < length; index += 1) { - iterator(documents[index]); - } +// Returns true if the character can be printed without escaping. +// From YAML 1.2: "any allowed characters known to be non-printable +// should also be escaped. [However,] This isn’t mandatory" +// Derived from nb-char - \t - #x85 - #xA0 - #x2028 - #x2029. +function isPrintable(c) { + return (0x00020 <= c && c <= 0x00007E) + || ((0x000A1 <= c && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029) + || ((0x0E000 <= c && c <= 0x00FFFD) && c !== CHAR_BOM) + || (0x10000 <= c && c <= 0x10FFFF); } +// [34] ns-char ::= nb-char - s-white +// [27] nb-char ::= c-printable - b-char - c-byte-order-mark +// [26] b-char ::= b-line-feed | b-carriage-return +// Including s-white (for some reason, examples doesn't match specs in this aspect) +// ns-char ::= c-printable - b-line-feed - b-carriage-return - c-byte-order-mark +function isNsCharOrWhitespace(c) { + return isPrintable(c) + && c !== CHAR_BOM + // - b-char + && c !== CHAR_CARRIAGE_RETURN + && c !== CHAR_LINE_FEED; +} -function load(input, options) { - var documents = loadDocuments(input, options); +// [127] ns-plain-safe(c) ::= c = flow-out ⇒ ns-plain-safe-out +// c = flow-in ⇒ ns-plain-safe-in +// c = block-key ⇒ ns-plain-safe-out +// c = flow-key ⇒ ns-plain-safe-in +// [128] ns-plain-safe-out ::= ns-char +// [129] ns-plain-safe-in ::= ns-char - c-flow-indicator +// [130] ns-plain-char(c) ::= ( ns-plain-safe(c) - “:” - “#” ) +// | ( /* An ns-char preceding */ “#” ) +// | ( “:” /* Followed by an ns-plain-safe(c) */ ) +function isPlainSafe(c, prev, inblock) { + var cIsNsCharOrWhitespace = isNsCharOrWhitespace(c); + var cIsNsChar = cIsNsCharOrWhitespace && !isWhitespace(c); + return ( + // ns-plain-safe + inblock ? // c = flow-in + cIsNsCharOrWhitespace + : cIsNsCharOrWhitespace + // - c-flow-indicator + && c !== CHAR_COMMA + && c !== CHAR_LEFT_SQUARE_BRACKET + && c !== CHAR_RIGHT_SQUARE_BRACKET + && c !== CHAR_LEFT_CURLY_BRACKET + && c !== CHAR_RIGHT_CURLY_BRACKET + ) + // ns-plain-char + && c !== CHAR_SHARP // false on '#' + && !(prev === CHAR_COLON && !cIsNsChar) // false on ': ' + || (isNsCharOrWhitespace(prev) && !isWhitespace(prev) && c === CHAR_SHARP) // change to true on '[^ ]#' + || (prev === CHAR_COLON && cIsNsChar); // change to true on ':[^ ]' +} - if (documents.length === 0) { - /*eslint-disable no-undefined*/ - return undefined; - } else if (documents.length === 1) { - return documents[0]; +// Simplified test for values allowed as the first character in plain style. +function isPlainSafeFirst(c) { + // Uses a subset of ns-char - c-indicator + // where ns-char = nb-char - s-white. + // No support of ( ( “?” | “:” | “-” ) /* Followed by an ns-plain-safe(c)) */ ) part + return isPrintable(c) && c !== CHAR_BOM + && !isWhitespace(c) // - s-white + // - (c-indicator ::= + // “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}” + && c !== CHAR_MINUS + && c !== CHAR_QUESTION + && c !== CHAR_COLON + && c !== CHAR_COMMA + && c !== CHAR_LEFT_SQUARE_BRACKET + && c !== CHAR_RIGHT_SQUARE_BRACKET + && c !== CHAR_LEFT_CURLY_BRACKET + && c !== CHAR_RIGHT_CURLY_BRACKET + // | “#” | “&” | “*” | “!” | “|” | “=” | “>” | “'” | “"” + && c !== CHAR_SHARP + && c !== CHAR_AMPERSAND + && c !== CHAR_ASTERISK + && c !== CHAR_EXCLAMATION + && c !== CHAR_VERTICAL_LINE + && c !== CHAR_EQUALS + && c !== CHAR_GREATER_THAN + && c !== CHAR_SINGLE_QUOTE + && c !== CHAR_DOUBLE_QUOTE + // | “%” | “@” | “`”) + && c !== CHAR_PERCENT + && c !== CHAR_COMMERCIAL_AT + && c !== CHAR_GRAVE_ACCENT; +} + +// Simplified test for values allowed as the last character in plain style. +function isPlainSafeLast(c) { + // just not whitespace or colon, it will be checked to be plain character later + return !isWhitespace(c) && c !== CHAR_COLON; +} + +// Same as 'string'.codePointAt(pos), but works in older browsers. +function codePointAt(string, pos) { + var first = string.charCodeAt(pos), second; + if (first >= 0xD800 && first <= 0xDBFF && pos + 1 < string.length) { + second = string.charCodeAt(pos + 1); + if (second >= 0xDC00 && second <= 0xDFFF) { + // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae + return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000; + } } - throw new YAMLException('expected a single document in the stream, but found more'); + return first; } +// Determines whether block indentation indicator is required. +function needIndentIndicator(string) { + var leadingSpaceRe = /^\n* /; + return leadingSpaceRe.test(string); +} -module.exports.loadAll = loadAll; -module.exports.load = load; +var STYLE_PLAIN = 1, + STYLE_SINGLE = 2, + STYLE_LITERAL = 3, + STYLE_FOLDED = 4, + STYLE_DOUBLE = 5; +// Determines which scalar styles are possible and returns the preferred style. +// lineWidth = -1 => no limit. +// Pre-conditions: str.length > 0. +// Post-conditions: +// STYLE_PLAIN or STYLE_SINGLE => no \n are in the string. +// STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1). +// STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1). +function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, + testAmbiguousType, quotingType, forceQuotes, inblock) { -/***/ }), + var i; + var char = 0; + var prevChar = null; + var hasLineBreak = false; + var hasFoldableLine = false; // only checked if shouldTrackWidth + var shouldTrackWidth = lineWidth !== -1; + var previousLineBreak = -1; // count the first line correctly + var plain = isPlainSafeFirst(codePointAt(string, 0)) + && isPlainSafeLast(codePointAt(string, string.length - 1)); -/***/ 21082: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (singleLineOnly || forceQuotes) { + // Case: no block styles. + // Check for disallowed characters to rule out plain and single. + for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) { + char = codePointAt(string, i); + if (!isPrintable(char)) { + return STYLE_DOUBLE; + } + plain = plain && isPlainSafe(char, prevChar, inblock); + prevChar = char; + } + } else { + // Case: block styles permitted. + for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) { + char = codePointAt(string, i); + if (char === CHAR_LINE_FEED) { + hasLineBreak = true; + // Check if any line can be folded. + if (shouldTrackWidth) { + hasFoldableLine = hasFoldableLine || + // Foldable line = too long, and not more-indented. + (i - previousLineBreak - 1 > lineWidth && + string[previousLineBreak + 1] !== ' '); + previousLineBreak = i; + } + } else if (!isPrintable(char)) { + return STYLE_DOUBLE; + } + plain = plain && isPlainSafe(char, prevChar, inblock); + prevChar = char; + } + // in case the end is missing a \n + hasFoldableLine = hasFoldableLine || (shouldTrackWidth && + (i - previousLineBreak - 1 > lineWidth && + string[previousLineBreak + 1] !== ' ')); + } + // Although every style can represent \n without escaping, prefer block styles + // for multiline, since they're more readable and they don't add empty lines. + // Also prefer folding a super-long line. + if (!hasLineBreak && !hasFoldableLine) { + // Strings interpretable as another type have to be quoted; + // e.g. the string 'true' vs. the boolean true. + if (plain && !forceQuotes && !testAmbiguousType(string)) { + return STYLE_PLAIN; + } + return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE; + } + // Edge case: block indentation indicator can only have one digit. + if (indentPerLevel > 9 && needIndentIndicator(string)) { + return STYLE_DOUBLE; + } + // At this point we know block styles are valid. + // Prefer literal style unless we want to fold. + if (!forceQuotes) { + return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL; + } + return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE; +} -"use strict"; +// Note: line breaking/folding is implemented for only the folded style. +// NB. We drop the last trailing newline (if any) of a returned block scalar +// since the dumper adds its own newline. This always works: +// • No ending newline => unaffected; already using strip "-" chomping. +// • Ending newline => removed then restored. +// Importantly, this keeps the "+" chomp indicator from gaining an extra line. +function writeScalar(state, string, level, iskey, inblock) { + state.dump = (function () { + if (string.length === 0) { + return state.quotingType === QUOTING_TYPE_DOUBLE ? '""' : "''"; + } + if (!state.noCompatMode) { + if (DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1 || DEPRECATED_BASE60_SYNTAX.test(string)) { + return state.quotingType === QUOTING_TYPE_DOUBLE ? ('"' + string + '"') : ("'" + string + "'"); + } + } + var indent = state.indent * Math.max(1, level); // no 0-indent scalars + // As indentation gets deeper, let the width decrease monotonically + // to the lower bound min(state.lineWidth, 40). + // Note that this implies + // state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound. + // state.lineWidth > 40 + state.indent: width decreases until the lower bound. + // This behaves better than a constant minimum width which disallows narrower options, + // or an indent threshold which causes the width to suddenly increase. + var lineWidth = state.lineWidth === -1 + ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent); -/*eslint-disable max-len*/ + // Without knowing if keys are implicit/explicit, assume implicit for safety. + var singleLineOnly = iskey + // No block styles in flow mode. + || (state.flowLevel > -1 && level >= state.flowLevel); + function testAmbiguity(string) { + return testImplicitResolving(state, string); + } -var YAMLException = __nccwpck_require__(68179); -var Type = __nccwpck_require__(6073); + switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, + testAmbiguity, state.quotingType, state.forceQuotes && !iskey, inblock)) { + + case STYLE_PLAIN: + return string; + case STYLE_SINGLE: + return "'" + string.replace(/'/g, "''") + "'"; + case STYLE_LITERAL: + return '|' + blockHeader(string, state.indent) + + dropEndingNewline(indentString(string, indent)); + case STYLE_FOLDED: + return '>' + blockHeader(string, state.indent) + + dropEndingNewline(indentString(foldString(string, lineWidth), indent)); + case STYLE_DOUBLE: + return '"' + escapeString(string, lineWidth) + '"'; + default: + throw new YAMLException('impossible error: invalid scalar style'); + } + }()); +} +// Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9. +function blockHeader(string, indentPerLevel) { + var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : ''; -function compileList(schema, name) { - var result = []; + // note the special case: the string '\n' counts as a "trailing" empty line. + var clip = string[string.length - 1] === '\n'; + var keep = clip && (string[string.length - 2] === '\n' || string === '\n'); + var chomp = keep ? '+' : (clip ? '' : '-'); - schema[name].forEach(function (currentType) { - var newIndex = result.length; + return indentIndicator + chomp + '\n'; +} - result.forEach(function (previousType, previousIndex) { - if (previousType.tag === currentType.tag && - previousType.kind === currentType.kind && - previousType.multi === currentType.multi) { +// (See the note for writeScalar.) +function dropEndingNewline(string) { + return string[string.length - 1] === '\n' ? string.slice(0, -1) : string; +} - newIndex = previousIndex; - } - }); +// Note: a long line without a suitable break point will exceed the width limit. +// Pre-conditions: every char in str isPrintable, str.length > 0, width > 0. +function foldString(string, width) { + // In folded style, $k$ consecutive newlines output as $k+1$ newlines— + // unless they're before or after a more-indented line, or at the very + // beginning or end, in which case $k$ maps to $k$. + // Therefore, parse each chunk as newline(s) followed by a content line. + var lineRe = /(\n+)([^\n]*)/g; - result[newIndex] = currentType; - }); + // first line (possibly an empty line) + var result = (function () { + var nextLF = string.indexOf('\n'); + nextLF = nextLF !== -1 ? nextLF : string.length; + lineRe.lastIndex = nextLF; + return foldLine(string.slice(0, nextLF), width); + }()); + // If we haven't reached the first content line yet, don't add an extra \n. + var prevMoreIndented = string[0] === '\n' || string[0] === ' '; + var moreIndented; + + // rest of the lines + var match; + while ((match = lineRe.exec(string))) { + var prefix = match[1], line = match[2]; + moreIndented = (line[0] === ' '); + result += prefix + + (!prevMoreIndented && !moreIndented && line !== '' + ? '\n' : '') + + foldLine(line, width); + prevMoreIndented = moreIndented; + } return result; } +// Greedy line breaking. +// Picks the longest line under the limit each time, +// otherwise settles for the shortest line over the limit. +// NB. More-indented lines *cannot* be folded, as that would add an extra \n. +function foldLine(line, width) { + if (line === '' || line[0] === ' ') return line; -function compileMap(/* lists... */) { - var result = { - scalar: {}, - sequence: {}, - mapping: {}, - fallback: {}, - multi: { - scalar: [], - sequence: [], - mapping: [], - fallback: [] - } - }, index, length; + // Since a more-indented line adds a \n, breaks can't be followed by a space. + var breakRe = / [^ ]/g; // note: the match index will always be <= length-2. + var match; + // start is an inclusive index. end, curr, and next are exclusive. + var start = 0, end, curr = 0, next = 0; + var result = ''; - function collectType(type) { - if (type.multi) { - result.multi[type.kind].push(type); - result.multi['fallback'].push(type); - } else { - result[type.kind][type.tag] = result['fallback'][type.tag] = type; + // Invariants: 0 <= start <= length-1. + // 0 <= curr <= next <= max(0, length-2). curr - start <= width. + // Inside the loop: + // A match implies length >= 2, so curr and next are <= length-2. + while ((match = breakRe.exec(line))) { + next = match.index; + // maintain invariant: curr - start <= width + if (next - start > width) { + end = (curr > start) ? curr : next; // derive end <= length-2 + result += '\n' + line.slice(start, end); + // skip the space that was output as \n + start = end + 1; // derive start <= length-1 } + curr = next; } - for (index = 0, length = arguments.length; index < length; index += 1) { - arguments[index].forEach(collectType); + // By the invariants, start <= length-1, so there is something left over. + // It is either the whole string or a part starting from non-whitespace. + result += '\n'; + // Insert a break if the remainder is too long and there is a break available. + if (line.length - start > width && curr > start) { + result += line.slice(start, curr) + '\n' + line.slice(curr + 1); + } else { + result += line.slice(start); } - return result; -} - -function Schema(definition) { - return this.extend(definition); + return result.slice(1); // drop extra \n joiner } +// Escapes a double-quoted string. +function escapeString(string) { + var result = ''; + var char = 0; + var escapeSeq; -Schema.prototype.extend = function extend(definition) { - var implicit = []; - var explicit = []; - - if (definition instanceof Type) { - // Schema.extend(type) - explicit.push(definition); + for (var i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) { + char = codePointAt(string, i); + escapeSeq = ESCAPE_SEQUENCES[char]; - } else if (Array.isArray(definition)) { - // Schema.extend([ type1, type2, ... ]) - explicit = explicit.concat(definition); + if (!escapeSeq && isPrintable(char)) { + result += string[i]; + if (char >= 0x10000) result += string[i + 1]; + } else { + result += escapeSeq || encodeHex(char); + } + } - } else if (definition && (Array.isArray(definition.implicit) || Array.isArray(definition.explicit))) { - // Schema.extend({ explicit: [ type1, type2, ... ], implicit: [ type1, type2, ... ] }) - if (definition.implicit) implicit = implicit.concat(definition.implicit); - if (definition.explicit) explicit = explicit.concat(definition.explicit); + return result; +} - } else { - throw new YAMLException('Schema.extend argument should be a Type, [ Type ], ' + - 'or a schema definition ({ implicit: [...], explicit: [...] })'); - } +function writeFlowSequence(state, level, object) { + var _result = '', + _tag = state.tag, + index, + length, + value; - implicit.forEach(function (type) { - if (!(type instanceof Type)) { - throw new YAMLException('Specified list of YAML types (or a single Type object) contains a non-Type object.'); - } + for (index = 0, length = object.length; index < length; index += 1) { + value = object[index]; - if (type.loadKind && type.loadKind !== 'scalar') { - throw new YAMLException('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.'); + if (state.replacer) { + value = state.replacer.call(object, String(index), value); } - if (type.multi) { - throw new YAMLException('There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.'); - } - }); + // Write only valid elements, put null instead of invalid elements. + if (writeNode(state, level, value, false, false) || + (typeof value === 'undefined' && + writeNode(state, level, null, false, false))) { - explicit.forEach(function (type) { - if (!(type instanceof Type)) { - throw new YAMLException('Specified list of YAML types (or a single Type object) contains a non-Type object.'); + if (_result !== '') _result += ',' + (!state.condenseFlow ? ' ' : ''); + _result += state.dump; } - }); + } - var result = Object.create(Schema.prototype); + state.tag = _tag; + state.dump = '[' + _result + ']'; +} - result.implicit = (this.implicit || []).concat(implicit); - result.explicit = (this.explicit || []).concat(explicit); +function writeBlockSequence(state, level, object, compact) { + var _result = '', + _tag = state.tag, + index, + length, + value; - result.compiledImplicit = compileList(result, 'implicit'); - result.compiledExplicit = compileList(result, 'explicit'); - result.compiledTypeMap = compileMap(result.compiledImplicit, result.compiledExplicit); + for (index = 0, length = object.length; index < length; index += 1) { + value = object[index]; - return result; -}; + if (state.replacer) { + value = state.replacer.call(object, String(index), value); + } + // Write only valid elements, put null instead of invalid elements. + if (writeNode(state, level + 1, value, true, true, false, true) || + (typeof value === 'undefined' && + writeNode(state, level + 1, null, true, true, false, true))) { -module.exports = Schema; + if (!compact || _result !== '') { + _result += generateNextLine(state, level); + } + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + _result += '-'; + } else { + _result += '- '; + } -/***/ }), + _result += state.dump; + } + } -/***/ 12011: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + state.tag = _tag; + state.dump = _result || '[]'; // Empty sequence if no valid values. +} -"use strict"; -// Standard YAML's Core schema. -// http://www.yaml.org/spec/1.2/spec.html#id2804923 -// -// NOTE: JS-YAML does not support schema-specific tag resolution restrictions. -// So, Core schema has no distinctions from JSON schema is JS-YAML. +function writeFlowMapping(state, level, object) { + var _result = '', + _tag = state.tag, + objectKeyList = Object.keys(object), + index, + length, + objectKey, + objectValue, + pairBuffer; + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + pairBuffer = ''; + if (_result !== '') pairBuffer += ', '; + if (state.condenseFlow) pairBuffer += '"'; + objectKey = objectKeyList[index]; + objectValue = object[objectKey]; -module.exports = __nccwpck_require__(1035); + if (state.replacer) { + objectValue = state.replacer.call(object, objectKey, objectValue); + } + if (!writeNode(state, level, objectKey, false, false)) { + continue; // Skip this pair because of invalid key; + } -/***/ }), + if (state.dump.length > 1024) pairBuffer += '? '; -/***/ 18759: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + pairBuffer += state.dump + (state.condenseFlow ? '"' : '') + ':' + (state.condenseFlow ? '' : ' '); -"use strict"; -// JS-YAML's default schema for `safeLoad` function. -// It is not described in the YAML specification. -// -// This schema is based on standard YAML's Core schema and includes most of -// extra types described at YAML tag repository. (http://yaml.org/type/) + if (!writeNode(state, level, objectValue, false, false)) { + continue; // Skip this pair because of invalid value. + } + pairBuffer += state.dump; + // Both key and value are valid. + _result += pairBuffer; + } + state.tag = _tag; + state.dump = '{' + _result + '}'; +} +function writeBlockMapping(state, level, object, compact) { + var _result = '', + _tag = state.tag, + objectKeyList = Object.keys(object), + index, + length, + objectKey, + objectValue, + explicitPair, + pairBuffer; -module.exports = (__nccwpck_require__(12011).extend)({ - implicit: [ - __nccwpck_require__(99212), - __nccwpck_require__(86104) - ], - explicit: [ - __nccwpck_require__(77900), - __nccwpck_require__(19046), - __nccwpck_require__(96860), - __nccwpck_require__(79548) - ] -}); + // Allow sorting keys so that the output file is deterministic + if (state.sortKeys === true) { + // Default sorting + objectKeyList.sort(); + } else if (typeof state.sortKeys === 'function') { + // Custom sort function + objectKeyList.sort(state.sortKeys); + } else if (state.sortKeys) { + // Something is wrong + throw new YAMLException('sortKeys must be a boolean or a function'); + } + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + pairBuffer = ''; -/***/ }), + if (!compact || _result !== '') { + pairBuffer += generateNextLine(state, level); + } -/***/ 28562: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + objectKey = objectKeyList[index]; + objectValue = object[objectKey]; -"use strict"; -// Standard YAML's Failsafe schema. -// http://www.yaml.org/spec/1.2/spec.html#id2802346 + if (state.replacer) { + objectValue = state.replacer.call(object, objectKey, objectValue); + } + if (!writeNode(state, level + 1, objectKey, true, true, true)) { + continue; // Skip this pair because of invalid key. + } + explicitPair = (state.tag !== null && state.tag !== '?') || + (state.dump && state.dump.length > 1024); + if (explicitPair) { + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + pairBuffer += '?'; + } else { + pairBuffer += '? '; + } + } + pairBuffer += state.dump; -var Schema = __nccwpck_require__(21082); + if (explicitPair) { + pairBuffer += generateNextLine(state, level); + } + if (!writeNode(state, level + 1, objectValue, true, explicitPair)) { + continue; // Skip this pair because of invalid value. + } -module.exports = new Schema({ - explicit: [ - __nccwpck_require__(23619), - __nccwpck_require__(67283), - __nccwpck_require__(86150) - ] -}); + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + pairBuffer += ':'; + } else { + pairBuffer += ': '; + } + pairBuffer += state.dump; -/***/ }), + // Both key and value are valid. + _result += pairBuffer; + } -/***/ 1035: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + state.tag = _tag; + state.dump = _result || '{}'; // Empty mapping if no valid pairs. +} -"use strict"; -// Standard YAML's JSON schema. -// http://www.yaml.org/spec/1.2/spec.html#id2803231 -// -// NOTE: JS-YAML does not support schema-specific tag resolution restrictions. -// So, this schema is not such strict as defined in the YAML specification. -// It allows numbers in binary notaion, use `Null` and `NULL` as `null`, etc. +function detectType(state, object, explicit) { + var _result, typeList, index, length, type, style; + typeList = explicit ? state.explicitTypes : state.implicitTypes; + for (index = 0, length = typeList.length; index < length; index += 1) { + type = typeList[index]; + if ((type.instanceOf || type.predicate) && + (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) && + (!type.predicate || type.predicate(object))) { + if (explicit) { + if (type.multi && type.representName) { + state.tag = type.representName(object); + } else { + state.tag = type.tag; + } + } else { + state.tag = '?'; + } -module.exports = (__nccwpck_require__(28562).extend)({ - implicit: [ - __nccwpck_require__(20721), - __nccwpck_require__(64993), - __nccwpck_require__(11615), - __nccwpck_require__(42705) - ] -}); + if (type.represent) { + style = state.styleMap[type.tag] || type.defaultStyle; + if (_toString.call(type.represent) === '[object Function]') { + _result = type.represent(object, style); + } else if (_hasOwnProperty.call(type.represent, style)) { + _result = type.represent[style](object, style); + } else { + throw new YAMLException('!<' + type.tag + '> tag resolver accepts not "' + style + '" style'); + } -/***/ }), + state.dump = _result; + } -/***/ 96975: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return true; + } + } -"use strict"; + return false; +} +// Serializes `object` and writes it to global `result`. +// Returns true on success, or false on invalid object. +// +function writeNode(state, level, object, block, compact, iskey, isblockseq) { + state.tag = null; + state.dump = object; + if (!detectType(state, object, false)) { + detectType(state, object, true); + } -var common = __nccwpck_require__(26829); + var type = _toString.call(state.dump); + var inblock = block; + var tagStr; + if (block) { + block = (state.flowLevel < 0 || state.flowLevel > level); + } -// get snippet for a single line, respecting maxLength -function getLine(buffer, lineStart, lineEnd, position, maxLineLength) { - var head = ''; - var tail = ''; - var maxHalfLength = Math.floor(maxLineLength / 2) - 1; + var objectOrArray = type === '[object Object]' || type === '[object Array]', + duplicateIndex, + duplicate; - if (position - lineStart > maxHalfLength) { - head = ' ... '; - lineStart = position - maxHalfLength + head.length; + if (objectOrArray) { + duplicateIndex = state.duplicates.indexOf(object); + duplicate = duplicateIndex !== -1; } - if (lineEnd - position > maxHalfLength) { - tail = ' ...'; - lineEnd = position + maxHalfLength - tail.length; + if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) { + compact = false; } - return { - str: head + buffer.slice(lineStart, lineEnd).replace(/\t/g, '→') + tail, - pos: position - lineStart + head.length // relative position - }; -} + if (duplicate && state.usedDuplicates[duplicateIndex]) { + state.dump = '*ref_' + duplicateIndex; + } else { + if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) { + state.usedDuplicates[duplicateIndex] = true; + } + if (type === '[object Object]') { + if (block && (Object.keys(state.dump).length !== 0)) { + writeBlockMapping(state, level, state.dump, compact); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + state.dump; + } + } else { + writeFlowMapping(state, level, state.dump); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; + } + } + } else if (type === '[object Array]') { + if (block && (state.dump.length !== 0)) { + if (state.noArrayIndent && !isblockseq && level > 0) { + writeBlockSequence(state, level - 1, state.dump, compact); + } else { + writeBlockSequence(state, level, state.dump, compact); + } + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + state.dump; + } + } else { + writeFlowSequence(state, level, state.dump); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; + } + } + } else if (type === '[object String]') { + if (state.tag !== '?') { + writeScalar(state, state.dump, level, iskey, inblock); + } + } else if (type === '[object Undefined]') { + return false; + } else { + if (state.skipInvalid) return false; + throw new YAMLException('unacceptable kind of an object to dump ' + type); + } + + if (state.tag !== null && state.tag !== '?') { + // Need to encode all characters except those allowed by the spec: + // + // [35] ns-dec-digit ::= [#x30-#x39] /* 0-9 */ + // [36] ns-hex-digit ::= ns-dec-digit + // | [#x41-#x46] /* A-F */ | [#x61-#x66] /* a-f */ + // [37] ns-ascii-letter ::= [#x41-#x5A] /* A-Z */ | [#x61-#x7A] /* a-z */ + // [38] ns-word-char ::= ns-dec-digit | ns-ascii-letter | “-” + // [39] ns-uri-char ::= “%” ns-hex-digit ns-hex-digit | ns-word-char | “#” + // | “;” | “/” | “?” | “:” | “@” | “&” | “=” | “+” | “$” | “,” + // | “_” | “.” | “!” | “~” | “*” | “'” | “(” | “)” | “[” | “]” + // + // Also need to encode '!' because it has special meaning (end of tag prefix). + // + tagStr = encodeURI( + state.tag[0] === '!' ? state.tag.slice(1) : state.tag + ).replace(/!/g, '%21'); + + if (state.tag[0] === '!') { + tagStr = '!' + tagStr; + } else if (tagStr.slice(0, 18) === 'tag:yaml.org,2002:') { + tagStr = '!!' + tagStr.slice(18); + } else { + tagStr = '!<' + tagStr + '>'; + } + state.dump = tagStr + ' ' + state.dump; + } + } -function padStart(string, max) { - return common.repeat(' ', max - string.length) + string; + return true; } +function getDuplicateReferences(object, state) { + var objects = [], + duplicatesIndexes = [], + index, + length; -function makeSnippet(mark, options) { - options = Object.create(options || null); + inspectNode(object, objects, duplicatesIndexes); - if (!mark.buffer) return null; + for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) { + state.duplicates.push(objects[duplicatesIndexes[index]]); + } + state.usedDuplicates = new Array(length); +} - if (!options.maxLength) options.maxLength = 79; - if (typeof options.indent !== 'number') options.indent = 1; - if (typeof options.linesBefore !== 'number') options.linesBefore = 3; - if (typeof options.linesAfter !== 'number') options.linesAfter = 2; +function inspectNode(object, objects, duplicatesIndexes) { + var objectKeyList, + index, + length; - var re = /\r?\n|\r|\0/g; - var lineStarts = [ 0 ]; - var lineEnds = []; - var match; - var foundLineNo = -1; + if (object !== null && typeof object === 'object') { + index = objects.indexOf(object); + if (index !== -1) { + if (duplicatesIndexes.indexOf(index) === -1) { + duplicatesIndexes.push(index); + } + } else { + objects.push(object); - while ((match = re.exec(mark.buffer))) { - lineEnds.push(match.index); - lineStarts.push(match.index + match[0].length); + if (Array.isArray(object)) { + for (index = 0, length = object.length; index < length; index += 1) { + inspectNode(object[index], objects, duplicatesIndexes); + } + } else { + objectKeyList = Object.keys(object); - if (mark.position <= match.index && foundLineNo < 0) { - foundLineNo = lineStarts.length - 2; + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes); + } + } } } +} - if (foundLineNo < 0) foundLineNo = lineStarts.length - 1; +function dump(input, options) { + options = options || {}; - var result = '', i, line; - var lineNoLength = Math.min(mark.line + options.linesAfter, lineEnds.length).toString().length; - var maxLineLength = options.maxLength - (options.indent + lineNoLength + 3); + var state = new State(options); - for (i = 1; i <= options.linesBefore; i++) { - if (foundLineNo - i < 0) break; - line = getLine( - mark.buffer, - lineStarts[foundLineNo - i], - lineEnds[foundLineNo - i], - mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo - i]), - maxLineLength - ); - result = common.repeat(' ', options.indent) + padStart((mark.line - i + 1).toString(), lineNoLength) + - ' | ' + line.str + '\n' + result; - } + if (!state.noRefs) getDuplicateReferences(input, state); - line = getLine(mark.buffer, lineStarts[foundLineNo], lineEnds[foundLineNo], mark.position, maxLineLength); - result += common.repeat(' ', options.indent) + padStart((mark.line + 1).toString(), lineNoLength) + - ' | ' + line.str + '\n'; - result += common.repeat('-', options.indent + lineNoLength + 3 + line.pos) + '^' + '\n'; + var value = input; - for (i = 1; i <= options.linesAfter; i++) { - if (foundLineNo + i >= lineEnds.length) break; - line = getLine( - mark.buffer, - lineStarts[foundLineNo + i], - lineEnds[foundLineNo + i], - mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo + i]), - maxLineLength - ); - result += common.repeat(' ', options.indent) + padStart((mark.line + i + 1).toString(), lineNoLength) + - ' | ' + line.str + '\n'; + if (state.replacer) { + value = state.replacer.call({ '': value }, '', value); } - return result.replace(/\n$/, ''); -} + if (writeNode(state, 0, value, true, true)) return state.dump + '\n'; + return ''; +} -module.exports = makeSnippet; +module.exports.dump = dump; /***/ }), -/***/ 6073: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 68179: +/***/ ((module) => { "use strict"; +// YAML error class. http://stackoverflow.com/questions/8458984 +// -var YAMLException = __nccwpck_require__(68179); -var TYPE_CONSTRUCTOR_OPTIONS = [ - 'kind', - 'multi', - 'resolve', - 'construct', - 'instanceOf', - 'predicate', - 'represent', - 'representName', - 'defaultStyle', - 'styleAliases' -]; +function formatError(exception, compact) { + var where = '', message = exception.reason || '(unknown reason)'; -var YAML_NODE_KINDS = [ - 'scalar', - 'sequence', - 'mapping' -]; + if (!exception.mark) return message; -function compileStyleAliases(map) { - var result = {}; + if (exception.mark.name) { + where += 'in "' + exception.mark.name + '" '; + } - if (map !== null) { - Object.keys(map).forEach(function (style) { - map[style].forEach(function (alias) { - result[String(alias)] = style; - }); - }); + where += '(' + (exception.mark.line + 1) + ':' + (exception.mark.column + 1) + ')'; + + if (!compact && exception.mark.snippet) { + where += '\n\n' + exception.mark.snippet; } - return result; + return message + ' ' + where; } -function Type(tag, options) { - options = options || {}; - Object.keys(options).forEach(function (name) { - if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) { - throw new YAMLException('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.'); - } - }); +function YAMLException(reason, mark) { + // Super constructor + Error.call(this); - // TODO: Add tag format check. - this.options = options; // keep original options in case user wants to extend this type later - this.tag = tag; - this.kind = options['kind'] || null; - this.resolve = options['resolve'] || function () { return true; }; - this.construct = options['construct'] || function (data) { return data; }; - this.instanceOf = options['instanceOf'] || null; - this.predicate = options['predicate'] || null; - this.represent = options['represent'] || null; - this.representName = options['representName'] || null; - this.defaultStyle = options['defaultStyle'] || null; - this.multi = options['multi'] || false; - this.styleAliases = compileStyleAliases(options['styleAliases'] || null); + this.name = 'YAMLException'; + this.reason = reason; + this.mark = mark; + this.message = formatError(this, false); - if (YAML_NODE_KINDS.indexOf(this.kind) === -1) { - throw new YAMLException('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.'); + // Include stack trace in error object + if (Error.captureStackTrace) { + // Chrome and NodeJS + Error.captureStackTrace(this, this.constructor); + } else { + // FF, IE 10+ and Safari 6+. Fallback for others + this.stack = (new Error()).stack || ''; } } -module.exports = Type; - - -/***/ }), -/***/ 77900: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +// Inherit from Error +YAMLException.prototype = Object.create(Error.prototype); +YAMLException.prototype.constructor = YAMLException; -"use strict"; +YAMLException.prototype.toString = function toString(compact) { + return this.name + ': ' + formatError(this, compact); +}; -/*eslint-disable no-bitwise*/ +module.exports = YAMLException; -var Type = __nccwpck_require__(6073); +/***/ }), -// [ 64, 65, 66 ] -> [ padding, CR, LF ] -var BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r'; +/***/ 51161: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +"use strict"; -function resolveYamlBinary(data) { - if (data === null) return false; - var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP; +/*eslint-disable max-len,no-use-before-define*/ - // Convert one by one. - for (idx = 0; idx < max; idx++) { - code = map.indexOf(data.charAt(idx)); +var common = __nccwpck_require__(26829); +var YAMLException = __nccwpck_require__(68179); +var makeSnippet = __nccwpck_require__(96975); +var DEFAULT_SCHEMA = __nccwpck_require__(18759); - // Skip CR/LF - if (code > 64) continue; - // Fail on illegal characters - if (code < 0) return false; +var _hasOwnProperty = Object.prototype.hasOwnProperty; - bitlen += 6; - } - // If there are any bits left, source was corrupted - return (bitlen % 8) === 0; -} +var CONTEXT_FLOW_IN = 1; +var CONTEXT_FLOW_OUT = 2; +var CONTEXT_BLOCK_IN = 3; +var CONTEXT_BLOCK_OUT = 4; -function constructYamlBinary(data) { - var idx, tailbits, - input = data.replace(/[\r\n=]/g, ''), // remove CR/LF & padding to simplify scan - max = input.length, - map = BASE64_MAP, - bits = 0, - result = []; - // Collect by 6*4 bits (3 bytes) +var CHOMPING_CLIP = 1; +var CHOMPING_STRIP = 2; +var CHOMPING_KEEP = 3; - for (idx = 0; idx < max; idx++) { - if ((idx % 4 === 0) && idx) { - result.push((bits >> 16) & 0xFF); - result.push((bits >> 8) & 0xFF); - result.push(bits & 0xFF); - } - bits = (bits << 6) | map.indexOf(input.charAt(idx)); - } +var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; +var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/; +var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/; +var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i; +var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i; - // Dump tail - tailbits = (max % 4) * 6; +function _class(obj) { return Object.prototype.toString.call(obj); } - if (tailbits === 0) { - result.push((bits >> 16) & 0xFF); - result.push((bits >> 8) & 0xFF); - result.push(bits & 0xFF); - } else if (tailbits === 18) { - result.push((bits >> 10) & 0xFF); - result.push((bits >> 2) & 0xFF); - } else if (tailbits === 12) { - result.push((bits >> 4) & 0xFF); - } +function is_EOL(c) { + return (c === 0x0A/* LF */) || (c === 0x0D/* CR */); +} - return new Uint8Array(result); +function is_WHITE_SPACE(c) { + return (c === 0x09/* Tab */) || (c === 0x20/* Space */); } -function representYamlBinary(object /*, style*/) { - var result = '', bits = 0, idx, tail, - max = object.length, - map = BASE64_MAP; +function is_WS_OR_EOL(c) { + return (c === 0x09/* Tab */) || + (c === 0x20/* Space */) || + (c === 0x0A/* LF */) || + (c === 0x0D/* CR */); +} - // Convert every three bytes to 4 ASCII characters. +function is_FLOW_INDICATOR(c) { + return c === 0x2C/* , */ || + c === 0x5B/* [ */ || + c === 0x5D/* ] */ || + c === 0x7B/* { */ || + c === 0x7D/* } */; +} - for (idx = 0; idx < max; idx++) { - if ((idx % 3 === 0) && idx) { - result += map[(bits >> 18) & 0x3F]; - result += map[(bits >> 12) & 0x3F]; - result += map[(bits >> 6) & 0x3F]; - result += map[bits & 0x3F]; - } +function fromHexCode(c) { + var lc; - bits = (bits << 8) + object[idx]; + if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { + return c - 0x30; } - // Dump tail - - tail = max % 3; + /*eslint-disable no-bitwise*/ + lc = c | 0x20; - if (tail === 0) { - result += map[(bits >> 18) & 0x3F]; - result += map[(bits >> 12) & 0x3F]; - result += map[(bits >> 6) & 0x3F]; - result += map[bits & 0x3F]; - } else if (tail === 2) { - result += map[(bits >> 10) & 0x3F]; - result += map[(bits >> 4) & 0x3F]; - result += map[(bits << 2) & 0x3F]; - result += map[64]; - } else if (tail === 1) { - result += map[(bits >> 2) & 0x3F]; - result += map[(bits << 4) & 0x3F]; - result += map[64]; - result += map[64]; + if ((0x61/* a */ <= lc) && (lc <= 0x66/* f */)) { + return lc - 0x61 + 10; } - return result; + return -1; } -function isBinary(obj) { - return Object.prototype.toString.call(obj) === '[object Uint8Array]'; +function escapedHexLen(c) { + if (c === 0x78/* x */) { return 2; } + if (c === 0x75/* u */) { return 4; } + if (c === 0x55/* U */) { return 8; } + return 0; } -module.exports = new Type('tag:yaml.org,2002:binary', { - kind: 'scalar', - resolve: resolveYamlBinary, - construct: constructYamlBinary, - predicate: isBinary, - represent: representYamlBinary -}); - - -/***/ }), - -/***/ 64993: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var Type = __nccwpck_require__(6073); - -function resolveYamlBoolean(data) { - if (data === null) return false; - - var max = data.length; - - return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) || - (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE')); -} +function fromDecimalCode(c) { + if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { + return c - 0x30; + } -function constructYamlBoolean(data) { - return data === 'true' || - data === 'True' || - data === 'TRUE'; + return -1; } -function isBoolean(object) { - return Object.prototype.toString.call(object) === '[object Boolean]'; +function simpleEscapeSequence(c) { + /* eslint-disable indent */ + return (c === 0x30/* 0 */) ? '\x00' : + (c === 0x61/* a */) ? '\x07' : + (c === 0x62/* b */) ? '\x08' : + (c === 0x74/* t */) ? '\x09' : + (c === 0x09/* Tab */) ? '\x09' : + (c === 0x6E/* n */) ? '\x0A' : + (c === 0x76/* v */) ? '\x0B' : + (c === 0x66/* f */) ? '\x0C' : + (c === 0x72/* r */) ? '\x0D' : + (c === 0x65/* e */) ? '\x1B' : + (c === 0x20/* Space */) ? ' ' : + (c === 0x22/* " */) ? '\x22' : + (c === 0x2F/* / */) ? '/' : + (c === 0x5C/* \ */) ? '\x5C' : + (c === 0x4E/* N */) ? '\x85' : + (c === 0x5F/* _ */) ? '\xA0' : + (c === 0x4C/* L */) ? '\u2028' : + (c === 0x50/* P */) ? '\u2029' : ''; } -module.exports = new Type('tag:yaml.org,2002:bool', { - kind: 'scalar', - resolve: resolveYamlBoolean, - construct: constructYamlBoolean, - predicate: isBoolean, - represent: { - lowercase: function (object) { return object ? 'true' : 'false'; }, - uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; }, - camelcase: function (object) { return object ? 'True' : 'False'; } - }, - defaultStyle: 'lowercase' -}); - - -/***/ }), - -/***/ 42705: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var common = __nccwpck_require__(26829); -var Type = __nccwpck_require__(6073); - -var YAML_FLOAT_PATTERN = new RegExp( - // 2.5e4, 2.5 and integers - '^(?:[-+]?(?:[0-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?' + - // .2e4, .2 - // special case, seems not from spec - '|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?' + - // .inf - '|[-+]?\\.(?:inf|Inf|INF)' + - // .nan - '|\\.(?:nan|NaN|NAN))$'); - -function resolveYamlFloat(data) { - if (data === null) return false; - - if (!YAML_FLOAT_PATTERN.test(data) || - // Quick hack to not allow integers end with `_` - // Probably should update regexp & check speed - data[data.length - 1] === '_') { - return false; +function charFromCodepoint(c) { + if (c <= 0xFFFF) { + return String.fromCharCode(c); } - - return true; + // Encode UTF-16 surrogate pair + // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF + return String.fromCharCode( + ((c - 0x010000) >> 10) + 0xD800, + ((c - 0x010000) & 0x03FF) + 0xDC00 + ); } -function constructYamlFloat(data) { - var value, sign; - - value = data.replace(/_/g, '').toLowerCase(); - sign = value[0] === '-' ? -1 : 1; - - if ('+-'.indexOf(value[0]) >= 0) { - value = value.slice(1); - } - - if (value === '.inf') { - return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY; - - } else if (value === '.nan') { - return NaN; - } - return sign * parseFloat(value, 10); +var simpleEscapeCheck = new Array(256); // integer, for fast access +var simpleEscapeMap = new Array(256); +for (var i = 0; i < 256; i++) { + simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0; + simpleEscapeMap[i] = simpleEscapeSequence(i); } -var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/; - -function representYamlFloat(object, style) { - var res; - - if (isNaN(object)) { - switch (style) { - case 'lowercase': return '.nan'; - case 'uppercase': return '.NAN'; - case 'camelcase': return '.NaN'; - } - } else if (Number.POSITIVE_INFINITY === object) { - switch (style) { - case 'lowercase': return '.inf'; - case 'uppercase': return '.INF'; - case 'camelcase': return '.Inf'; - } - } else if (Number.NEGATIVE_INFINITY === object) { - switch (style) { - case 'lowercase': return '-.inf'; - case 'uppercase': return '-.INF'; - case 'camelcase': return '-.Inf'; - } - } else if (common.isNegativeZero(object)) { - return '-0.0'; - } +function State(input, options) { + this.input = input; - res = object.toString(10); + this.filename = options['filename'] || null; + this.schema = options['schema'] || DEFAULT_SCHEMA; + this.onWarning = options['onWarning'] || null; + // (Hidden) Remove? makes the loader to expect YAML 1.1 documents + // if such documents have no explicit %YAML directive + this.legacy = options['legacy'] || false; - // JS stringifier can build scientific format without dots: 5e-100, - // while YAML requres dot: 5.e-100. Fix it with simple hack + this.json = options['json'] || false; + this.listener = options['listener'] || null; - return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res; -} + this.implicitTypes = this.schema.compiledImplicit; + this.typeMap = this.schema.compiledTypeMap; -function isFloat(object) { - return (Object.prototype.toString.call(object) === '[object Number]') && - (object % 1 !== 0 || common.isNegativeZero(object)); -} + this.length = input.length; + this.position = 0; + this.line = 0; + this.lineStart = 0; + this.lineIndent = 0; -module.exports = new Type('tag:yaml.org,2002:float', { - kind: 'scalar', - resolve: resolveYamlFloat, - construct: constructYamlFloat, - predicate: isFloat, - represent: representYamlFloat, - defaultStyle: 'lowercase' -}); + // position of first leading tab in the current line, + // used to make sure there are no tabs in the indentation + this.firstTabInLine = -1; + this.documents = []; -/***/ }), + /* + this.version; + this.checkLineBreaks; + this.tagMap; + this.anchorMap; + this.tag; + this.anchor; + this.kind; + this.result;*/ -/***/ 11615: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +} -"use strict"; +function generateError(state, message) { + var mark = { + name: state.filename, + buffer: state.input.slice(0, -1), // omit trailing \0 + position: state.position, + line: state.line, + column: state.position - state.lineStart + }; -var common = __nccwpck_require__(26829); -var Type = __nccwpck_require__(6073); + mark.snippet = makeSnippet(mark); -function isHexCode(c) { - return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) || - ((0x41/* A */ <= c) && (c <= 0x46/* F */)) || - ((0x61/* a */ <= c) && (c <= 0x66/* f */)); + return new YAMLException(message, mark); } -function isOctCode(c) { - return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */)); +function throwError(state, message) { + throw generateError(state, message); } -function isDecCode(c) { - return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)); +function throwWarning(state, message) { + if (state.onWarning) { + state.onWarning.call(null, generateError(state, message)); + } } -function resolveYamlInteger(data) { - if (data === null) return false; - - var max = data.length, - index = 0, - hasDigits = false, - ch; - if (!max) return false; +var directiveHandlers = { - ch = data[index]; + YAML: function handleYamlDirective(state, name, args) { - // sign - if (ch === '-' || ch === '+') { - ch = data[++index]; - } + var match, major, minor; - if (ch === '0') { - // 0 - if (index + 1 === max) return true; - ch = data[++index]; + if (state.version !== null) { + throwError(state, 'duplication of %YAML directive'); + } - // base 2, base 8, base 16 + if (args.length !== 1) { + throwError(state, 'YAML directive accepts exactly one argument'); + } - if (ch === 'b') { - // base 2 - index++; + match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]); - for (; index < max; index++) { - ch = data[index]; - if (ch === '_') continue; - if (ch !== '0' && ch !== '1') return false; - hasDigits = true; - } - return hasDigits && ch !== '_'; + if (match === null) { + throwError(state, 'ill-formed argument of the YAML directive'); } + major = parseInt(match[1], 10); + minor = parseInt(match[2], 10); - if (ch === 'x') { - // base 16 - index++; - - for (; index < max; index++) { - ch = data[index]; - if (ch === '_') continue; - if (!isHexCode(data.charCodeAt(index))) return false; - hasDigits = true; - } - return hasDigits && ch !== '_'; + if (major !== 1) { + throwError(state, 'unacceptable YAML version of the document'); } + state.version = args[0]; + state.checkLineBreaks = (minor < 2); - if (ch === 'o') { - // base 8 - index++; - - for (; index < max; index++) { - ch = data[index]; - if (ch === '_') continue; - if (!isOctCode(data.charCodeAt(index))) return false; - hasDigits = true; - } - return hasDigits && ch !== '_'; + if (minor !== 1 && minor !== 2) { + throwWarning(state, 'unsupported YAML version of the document'); } - } + }, - // base 10 (except 0) + TAG: function handleTagDirective(state, name, args) { - // value should not start with `_`; - if (ch === '_') return false; + var handle, prefix; - for (; index < max; index++) { - ch = data[index]; - if (ch === '_') continue; - if (!isDecCode(data.charCodeAt(index))) { - return false; + if (args.length !== 2) { + throwError(state, 'TAG directive accepts exactly two arguments'); } - hasDigits = true; - } - // Should have digits and should not end with `_` - if (!hasDigits || ch === '_') return false; + handle = args[0]; + prefix = args[1]; - return true; -} + if (!PATTERN_TAG_HANDLE.test(handle)) { + throwError(state, 'ill-formed tag handle (first argument) of the TAG directive'); + } -function constructYamlInteger(data) { - var value = data, sign = 1, ch; + if (_hasOwnProperty.call(state.tagMap, handle)) { + throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle'); + } - if (value.indexOf('_') !== -1) { - value = value.replace(/_/g, ''); - } + if (!PATTERN_TAG_URI.test(prefix)) { + throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive'); + } - ch = value[0]; + try { + prefix = decodeURIComponent(prefix); + } catch (err) { + throwError(state, 'tag prefix is malformed: ' + prefix); + } - if (ch === '-' || ch === '+') { - if (ch === '-') sign = -1; - value = value.slice(1); - ch = value[0]; + state.tagMap[handle] = prefix; } +}; - if (value === '0') return 0; - if (ch === '0') { - if (value[1] === 'b') return sign * parseInt(value.slice(2), 2); - if (value[1] === 'x') return sign * parseInt(value.slice(2), 16); - if (value[1] === 'o') return sign * parseInt(value.slice(2), 8); - } +function captureSegment(state, start, end, checkJson) { + var _position, _length, _character, _result; - return sign * parseInt(value, 10); -} + if (start < end) { + _result = state.input.slice(start, end); -function isInteger(object) { - return (Object.prototype.toString.call(object)) === '[object Number]' && - (object % 1 === 0 && !common.isNegativeZero(object)); -} + if (checkJson) { + for (_position = 0, _length = _result.length; _position < _length; _position += 1) { + _character = _result.charCodeAt(_position); + if (!(_character === 0x09 || + (0x20 <= _character && _character <= 0x10FFFF))) { + throwError(state, 'expected valid JSON character'); + } + } + } else if (PATTERN_NON_PRINTABLE.test(_result)) { + throwError(state, 'the stream contains non-printable characters'); + } -module.exports = new Type('tag:yaml.org,2002:int', { - kind: 'scalar', - resolve: resolveYamlInteger, - construct: constructYamlInteger, - predicate: isInteger, - represent: { - binary: function (obj) { return obj >= 0 ? '0b' + obj.toString(2) : '-0b' + obj.toString(2).slice(1); }, - octal: function (obj) { return obj >= 0 ? '0o' + obj.toString(8) : '-0o' + obj.toString(8).slice(1); }, - decimal: function (obj) { return obj.toString(10); }, - /* eslint-disable max-len */ - hexadecimal: function (obj) { return obj >= 0 ? '0x' + obj.toString(16).toUpperCase() : '-0x' + obj.toString(16).toUpperCase().slice(1); } - }, - defaultStyle: 'decimal', - styleAliases: { - binary: [ 2, 'bin' ], - octal: [ 8, 'oct' ], - decimal: [ 10, 'dec' ], - hexadecimal: [ 16, 'hex' ] + state.result += _result; } -}); - - -/***/ }), - -/***/ 86150: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; +} +function mergeMappings(state, destination, source, overridableKeys) { + var sourceKeys, key, index, quantity; -var Type = __nccwpck_require__(6073); + if (!common.isObject(source)) { + throwError(state, 'cannot merge mappings; the provided source object is unacceptable'); + } -module.exports = new Type('tag:yaml.org,2002:map', { - kind: 'mapping', - construct: function (data) { return data !== null ? data : {}; } -}); + sourceKeys = Object.keys(source); + for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) { + key = sourceKeys[index]; -/***/ }), + if (!_hasOwnProperty.call(destination, key)) { + destination[key] = source[key]; + overridableKeys[key] = true; + } + } +} -/***/ 86104: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, + startLine, startLineStart, startPos) { -"use strict"; + var index, quantity; + // The output is a plain object here, so keys can only be strings. + // We need to convert keyNode to a string, but doing so can hang the process + // (deeply nested arrays that explode exponentially using aliases). + if (Array.isArray(keyNode)) { + keyNode = Array.prototype.slice.call(keyNode); -var Type = __nccwpck_require__(6073); + for (index = 0, quantity = keyNode.length; index < quantity; index += 1) { + if (Array.isArray(keyNode[index])) { + throwError(state, 'nested arrays are not supported inside keys'); + } -function resolveYamlMerge(data) { - return data === '<<' || data === null; -} + if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') { + keyNode[index] = '[object Object]'; + } + } + } -module.exports = new Type('tag:yaml.org,2002:merge', { - kind: 'scalar', - resolve: resolveYamlMerge -}); + // Avoid code execution in load() via toString property + // (still use its own toString for arrays, timestamps, + // and whatever user schema extensions happen to have @@toStringTag) + if (typeof keyNode === 'object' && _class(keyNode) === '[object Object]') { + keyNode = '[object Object]'; + } -/***/ }), + keyNode = String(keyNode); -/***/ 20721: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (_result === null) { + _result = {}; + } -"use strict"; + if (keyTag === 'tag:yaml.org,2002:merge') { + if (Array.isArray(valueNode)) { + for (index = 0, quantity = valueNode.length; index < quantity; index += 1) { + mergeMappings(state, _result, valueNode[index], overridableKeys); + } + } else { + mergeMappings(state, _result, valueNode, overridableKeys); + } + } else { + if (!state.json && + !_hasOwnProperty.call(overridableKeys, keyNode) && + _hasOwnProperty.call(_result, keyNode)) { + state.line = startLine || state.line; + state.lineStart = startLineStart || state.lineStart; + state.position = startPos || state.position; + throwError(state, 'duplicated mapping key'); + } + // used for this specific key only because Object.defineProperty is slow + if (keyNode === '__proto__') { + Object.defineProperty(_result, keyNode, { + configurable: true, + enumerable: true, + writable: true, + value: valueNode + }); + } else { + _result[keyNode] = valueNode; + } + delete overridableKeys[keyNode]; + } -var Type = __nccwpck_require__(6073); + return _result; +} -function resolveYamlNull(data) { - if (data === null) return true; +function readLineBreak(state) { + var ch; - var max = data.length; + ch = state.input.charCodeAt(state.position); - return (max === 1 && data === '~') || - (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL')); -} + if (ch === 0x0A/* LF */) { + state.position++; + } else if (ch === 0x0D/* CR */) { + state.position++; + if (state.input.charCodeAt(state.position) === 0x0A/* LF */) { + state.position++; + } + } else { + throwError(state, 'a line break is expected'); + } -function constructYamlNull() { - return null; + state.line += 1; + state.lineStart = state.position; + state.firstTabInLine = -1; } -function isNull(object) { - return object === null; -} +function skipSeparationSpace(state, allowComments, checkIndent) { + var lineBreaks = 0, + ch = state.input.charCodeAt(state.position); -module.exports = new Type('tag:yaml.org,2002:null', { - kind: 'scalar', - resolve: resolveYamlNull, - construct: constructYamlNull, - predicate: isNull, - represent: { - canonical: function () { return '~'; }, - lowercase: function () { return 'null'; }, - uppercase: function () { return 'NULL'; }, - camelcase: function () { return 'Null'; }, - empty: function () { return ''; } - }, - defaultStyle: 'lowercase' -}); + while (ch !== 0) { + while (is_WHITE_SPACE(ch)) { + if (ch === 0x09/* Tab */ && state.firstTabInLine === -1) { + state.firstTabInLine = state.position; + } + ch = state.input.charCodeAt(++state.position); + } + if (allowComments && ch === 0x23/* # */) { + do { + ch = state.input.charCodeAt(++state.position); + } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0); + } -/***/ }), + if (is_EOL(ch)) { + readLineBreak(state); -/***/ 19046: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + ch = state.input.charCodeAt(state.position); + lineBreaks++; + state.lineIndent = 0; -"use strict"; + while (ch === 0x20/* Space */) { + state.lineIndent++; + ch = state.input.charCodeAt(++state.position); + } + } else { + break; + } + } + if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) { + throwWarning(state, 'deficient indentation'); + } -var Type = __nccwpck_require__(6073); + return lineBreaks; +} -var _hasOwnProperty = Object.prototype.hasOwnProperty; -var _toString = Object.prototype.toString; +function testDocumentSeparator(state) { + var _position = state.position, + ch; -function resolveYamlOmap(data) { - if (data === null) return true; + ch = state.input.charCodeAt(_position); - var objectKeys = [], index, length, pair, pairKey, pairHasKey, - object = data; + // Condition state.position === state.lineStart is tested + // in parent on each call, for efficiency. No needs to test here again. + if ((ch === 0x2D/* - */ || ch === 0x2E/* . */) && + ch === state.input.charCodeAt(_position + 1) && + ch === state.input.charCodeAt(_position + 2)) { - for (index = 0, length = object.length; index < length; index += 1) { - pair = object[index]; - pairHasKey = false; + _position += 3; - if (_toString.call(pair) !== '[object Object]') return false; + ch = state.input.charCodeAt(_position); - for (pairKey in pair) { - if (_hasOwnProperty.call(pair, pairKey)) { - if (!pairHasKey) pairHasKey = true; - else return false; - } + if (ch === 0 || is_WS_OR_EOL(ch)) { + return true; } - - if (!pairHasKey) return false; - - if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey); - else return false; } - return true; + return false; } -function constructYamlOmap(data) { - return data !== null ? data : []; +function writeFoldedLines(state, count) { + if (count === 1) { + state.result += ' '; + } else if (count > 1) { + state.result += common.repeat('\n', count - 1); + } } -module.exports = new Type('tag:yaml.org,2002:omap', { - kind: 'sequence', - resolve: resolveYamlOmap, - construct: constructYamlOmap -}); - - -/***/ }), - -/***/ 96860: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; +function readPlainScalar(state, nodeIndent, withinFlowCollection) { + var preceding, + following, + captureStart, + captureEnd, + hasPendingContent, + _line, + _lineStart, + _lineIndent, + _kind = state.kind, + _result = state.result, + ch; -var Type = __nccwpck_require__(6073); + ch = state.input.charCodeAt(state.position); -var _toString = Object.prototype.toString; + if (is_WS_OR_EOL(ch) || + is_FLOW_INDICATOR(ch) || + ch === 0x23/* # */ || + ch === 0x26/* & */ || + ch === 0x2A/* * */ || + ch === 0x21/* ! */ || + ch === 0x7C/* | */ || + ch === 0x3E/* > */ || + ch === 0x27/* ' */ || + ch === 0x22/* " */ || + ch === 0x25/* % */ || + ch === 0x40/* @ */ || + ch === 0x60/* ` */) { + return false; + } -function resolveYamlPairs(data) { - if (data === null) return true; + if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) { + following = state.input.charCodeAt(state.position + 1); - var index, length, pair, keys, result, - object = data; + if (is_WS_OR_EOL(following) || + withinFlowCollection && is_FLOW_INDICATOR(following)) { + return false; + } + } - result = new Array(object.length); + state.kind = 'scalar'; + state.result = ''; + captureStart = captureEnd = state.position; + hasPendingContent = false; - for (index = 0, length = object.length; index < length; index += 1) { - pair = object[index]; + while (ch !== 0) { + if (ch === 0x3A/* : */) { + following = state.input.charCodeAt(state.position + 1); - if (_toString.call(pair) !== '[object Object]') return false; + if (is_WS_OR_EOL(following) || + withinFlowCollection && is_FLOW_INDICATOR(following)) { + break; + } - keys = Object.keys(pair); + } else if (ch === 0x23/* # */) { + preceding = state.input.charCodeAt(state.position - 1); - if (keys.length !== 1) return false; + if (is_WS_OR_EOL(preceding)) { + break; + } - result[index] = [ keys[0], pair[keys[0]] ]; - } + } else if ((state.position === state.lineStart && testDocumentSeparator(state)) || + withinFlowCollection && is_FLOW_INDICATOR(ch)) { + break; - return true; -} + } else if (is_EOL(ch)) { + _line = state.line; + _lineStart = state.lineStart; + _lineIndent = state.lineIndent; + skipSeparationSpace(state, false, -1); -function constructYamlPairs(data) { - if (data === null) return []; + if (state.lineIndent >= nodeIndent) { + hasPendingContent = true; + ch = state.input.charCodeAt(state.position); + continue; + } else { + state.position = captureEnd; + state.line = _line; + state.lineStart = _lineStart; + state.lineIndent = _lineIndent; + break; + } + } - var index, length, pair, keys, result, - object = data; + if (hasPendingContent) { + captureSegment(state, captureStart, captureEnd, false); + writeFoldedLines(state, state.line - _line); + captureStart = captureEnd = state.position; + hasPendingContent = false; + } - result = new Array(object.length); + if (!is_WHITE_SPACE(ch)) { + captureEnd = state.position + 1; + } - for (index = 0, length = object.length; index < length; index += 1) { - pair = object[index]; + ch = state.input.charCodeAt(++state.position); + } - keys = Object.keys(pair); + captureSegment(state, captureStart, captureEnd, false); - result[index] = [ keys[0], pair[keys[0]] ]; + if (state.result) { + return true; } - return result; + state.kind = _kind; + state.result = _result; + return false; } -module.exports = new Type('tag:yaml.org,2002:pairs', { - kind: 'sequence', - resolve: resolveYamlPairs, - construct: constructYamlPairs -}); - - -/***/ }), +function readSingleQuotedScalar(state, nodeIndent) { + var ch, + captureStart, captureEnd; -/***/ 67283: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + ch = state.input.charCodeAt(state.position); -"use strict"; + if (ch !== 0x27/* ' */) { + return false; + } + state.kind = 'scalar'; + state.result = ''; + state.position++; + captureStart = captureEnd = state.position; -var Type = __nccwpck_require__(6073); + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + if (ch === 0x27/* ' */) { + captureSegment(state, captureStart, state.position, true); + ch = state.input.charCodeAt(++state.position); -module.exports = new Type('tag:yaml.org,2002:seq', { - kind: 'sequence', - construct: function (data) { return data !== null ? data : []; } -}); + if (ch === 0x27/* ' */) { + captureStart = state.position; + state.position++; + captureEnd = state.position; + } else { + return true; + } + } else if (is_EOL(ch)) { + captureSegment(state, captureStart, captureEnd, true); + writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); + captureStart = captureEnd = state.position; -/***/ }), + } else if (state.position === state.lineStart && testDocumentSeparator(state)) { + throwError(state, 'unexpected end of the document within a single quoted scalar'); -/***/ 79548: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + } else { + state.position++; + captureEnd = state.position; + } + } -"use strict"; + throwError(state, 'unexpected end of the stream within a single quoted scalar'); +} +function readDoubleQuotedScalar(state, nodeIndent) { + var captureStart, + captureEnd, + hexLength, + hexResult, + tmp, + ch; -var Type = __nccwpck_require__(6073); + ch = state.input.charCodeAt(state.position); -var _hasOwnProperty = Object.prototype.hasOwnProperty; + if (ch !== 0x22/* " */) { + return false; + } -function resolveYamlSet(data) { - if (data === null) return true; + state.kind = 'scalar'; + state.result = ''; + state.position++; + captureStart = captureEnd = state.position; - var key, object = data; + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + if (ch === 0x22/* " */) { + captureSegment(state, captureStart, state.position, true); + state.position++; + return true; - for (key in object) { - if (_hasOwnProperty.call(object, key)) { - if (object[key] !== null) return false; - } - } + } else if (ch === 0x5C/* \ */) { + captureSegment(state, captureStart, state.position, true); + ch = state.input.charCodeAt(++state.position); - return true; -} + if (is_EOL(ch)) { + skipSeparationSpace(state, false, nodeIndent); -function constructYamlSet(data) { - return data !== null ? data : {}; -} + // TODO: rework to inline fn with no type cast? + } else if (ch < 256 && simpleEscapeCheck[ch]) { + state.result += simpleEscapeMap[ch]; + state.position++; -module.exports = new Type('tag:yaml.org,2002:set', { - kind: 'mapping', - resolve: resolveYamlSet, - construct: constructYamlSet -}); + } else if ((tmp = escapedHexLen(ch)) > 0) { + hexLength = tmp; + hexResult = 0; + for (; hexLength > 0; hexLength--) { + ch = state.input.charCodeAt(++state.position); -/***/ }), + if ((tmp = fromHexCode(ch)) >= 0) { + hexResult = (hexResult << 4) + tmp; -/***/ 23619: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + } else { + throwError(state, 'expected hexadecimal character'); + } + } -"use strict"; + state.result += charFromCodepoint(hexResult); + state.position++; -var Type = __nccwpck_require__(6073); + } else { + throwError(state, 'unknown escape sequence'); + } -module.exports = new Type('tag:yaml.org,2002:str', { - kind: 'scalar', - construct: function (data) { return data !== null ? data : ''; } -}); + captureStart = captureEnd = state.position; + } else if (is_EOL(ch)) { + captureSegment(state, captureStart, captureEnd, true); + writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); + captureStart = captureEnd = state.position; -/***/ }), + } else if (state.position === state.lineStart && testDocumentSeparator(state)) { + throwError(state, 'unexpected end of the document within a double quoted scalar'); -/***/ 99212: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + } else { + state.position++; + captureEnd = state.position; + } + } -"use strict"; + throwError(state, 'unexpected end of the stream within a double quoted scalar'); +} +function readFlowCollection(state, nodeIndent) { + var readNext = true, + _line, + _lineStart, + _pos, + _tag = state.tag, + _result, + _anchor = state.anchor, + following, + terminator, + isPair, + isExplicitPair, + isMapping, + overridableKeys = Object.create(null), + keyNode, + keyTag, + valueNode, + ch; -var Type = __nccwpck_require__(6073); + ch = state.input.charCodeAt(state.position); -var YAML_DATE_REGEXP = new RegExp( - '^([0-9][0-9][0-9][0-9])' + // [1] year - '-([0-9][0-9])' + // [2] month - '-([0-9][0-9])$'); // [3] day + if (ch === 0x5B/* [ */) { + terminator = 0x5D;/* ] */ + isMapping = false; + _result = []; + } else if (ch === 0x7B/* { */) { + terminator = 0x7D;/* } */ + isMapping = true; + _result = {}; + } else { + return false; + } -var YAML_TIMESTAMP_REGEXP = new RegExp( - '^([0-9][0-9][0-9][0-9])' + // [1] year - '-([0-9][0-9]?)' + // [2] month - '-([0-9][0-9]?)' + // [3] day - '(?:[Tt]|[ \\t]+)' + // ... - '([0-9][0-9]?)' + // [4] hour - ':([0-9][0-9])' + // [5] minute - ':([0-9][0-9])' + // [6] second - '(?:\\.([0-9]*))?' + // [7] fraction - '(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour - '(?::([0-9][0-9]))?))?$'); // [11] tz_minute + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; + } -function resolveYamlTimestamp(data) { - if (data === null) return false; - if (YAML_DATE_REGEXP.exec(data) !== null) return true; - if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true; - return false; -} + ch = state.input.charCodeAt(++state.position); -function constructYamlTimestamp(data) { - var match, year, month, day, hour, minute, second, fraction = 0, - delta = null, tz_hour, tz_minute, date; + while (ch !== 0) { + skipSeparationSpace(state, true, nodeIndent); - match = YAML_DATE_REGEXP.exec(data); - if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data); + ch = state.input.charCodeAt(state.position); - if (match === null) throw new Error('Date resolve error'); + if (ch === terminator) { + state.position++; + state.tag = _tag; + state.anchor = _anchor; + state.kind = isMapping ? 'mapping' : 'sequence'; + state.result = _result; + return true; + } else if (!readNext) { + throwError(state, 'missed comma between flow collection entries'); + } else if (ch === 0x2C/* , */) { + // "flow collection entries can never be completely empty", as per YAML 1.2, section 7.4 + throwError(state, "expected the node content, but found ','"); + } - // match: [1] year [2] month [3] day + keyTag = keyNode = valueNode = null; + isPair = isExplicitPair = false; - year = +(match[1]); - month = +(match[2]) - 1; // JS month starts with 0 - day = +(match[3]); + if (ch === 0x3F/* ? */) { + following = state.input.charCodeAt(state.position + 1); - if (!match[4]) { // no hour - return new Date(Date.UTC(year, month, day)); - } + if (is_WS_OR_EOL(following)) { + isPair = isExplicitPair = true; + state.position++; + skipSeparationSpace(state, true, nodeIndent); + } + } - // match: [4] hour [5] minute [6] second [7] fraction + _line = state.line; // Save the current line. + _lineStart = state.lineStart; + _pos = state.position; + composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); + keyTag = state.tag; + keyNode = state.result; + skipSeparationSpace(state, true, nodeIndent); - hour = +(match[4]); - minute = +(match[5]); - second = +(match[6]); + ch = state.input.charCodeAt(state.position); - if (match[7]) { - fraction = match[7].slice(0, 3); - while (fraction.length < 3) { // milli-seconds - fraction += '0'; + if ((isExplicitPair || state.line === _line) && ch === 0x3A/* : */) { + isPair = true; + ch = state.input.charCodeAt(++state.position); + skipSeparationSpace(state, true, nodeIndent); + composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); + valueNode = state.result; } - fraction = +fraction; - } - // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute + if (isMapping) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos); + } else if (isPair) { + _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos)); + } else { + _result.push(keyNode); + } - if (match[9]) { - tz_hour = +(match[10]); - tz_minute = +(match[11] || 0); - delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds - if (match[9] === '-') delta = -delta; - } + skipSeparationSpace(state, true, nodeIndent); - date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction)); + ch = state.input.charCodeAt(state.position); - if (delta) date.setTime(date.getTime() - delta); + if (ch === 0x2C/* , */) { + readNext = true; + ch = state.input.charCodeAt(++state.position); + } else { + readNext = false; + } + } - return date; + throwError(state, 'unexpected end of the stream within a flow collection'); } -function representYamlTimestamp(object /*, style*/) { - return object.toISOString(); -} +function readBlockScalar(state, nodeIndent) { + var captureStart, + folding, + chomping = CHOMPING_CLIP, + didReadContent = false, + detectedIndent = false, + textIndent = nodeIndent, + emptyLines = 0, + atMoreIndented = false, + tmp, + ch; -module.exports = new Type('tag:yaml.org,2002:timestamp', { - kind: 'scalar', - resolve: resolveYamlTimestamp, - construct: constructYamlTimestamp, - instanceOf: Date, - represent: representYamlTimestamp -}); + ch = state.input.charCodeAt(state.position); + if (ch === 0x7C/* | */) { + folding = false; + } else if (ch === 0x3E/* > */) { + folding = true; + } else { + return false; + } -/***/ }), + state.kind = 'scalar'; + state.result = ''; -/***/ 55586: -/***/ ((module) => { + while (ch !== 0) { + ch = state.input.charCodeAt(++state.position); -"use strict"; + if (ch === 0x2B/* + */ || ch === 0x2D/* - */) { + if (CHOMPING_CLIP === chomping) { + chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP : CHOMPING_STRIP; + } else { + throwError(state, 'repeat of a chomping mode identifier'); + } + } else if ((tmp = fromDecimalCode(ch)) >= 0) { + if (tmp === 0) { + throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one'); + } else if (!detectedIndent) { + textIndent = nodeIndent + tmp - 1; + detectedIndent = true; + } else { + throwError(state, 'repeat of an indentation width identifier'); + } -module.exports = parseJson -function parseJson (txt, reviver, context) { - context = context || 20 - try { - return JSON.parse(txt, reviver) - } catch (e) { - if (typeof txt !== 'string') { - const isEmptyArray = Array.isArray(txt) && txt.length === 0 - const errorMessage = 'Cannot parse ' + - (isEmptyArray ? 'an empty array' : String(txt)) - throw new TypeError(errorMessage) - } - const syntaxErr = e.message.match(/^Unexpected token.*position\s+(\d+)/i) - const errIdx = syntaxErr - ? +syntaxErr[1] - : e.message.match(/^Unexpected end of JSON.*/i) - ? txt.length - 1 - : null - if (errIdx != null) { - const start = errIdx <= context - ? 0 - : errIdx - context - const end = errIdx + context >= txt.length - ? txt.length - : errIdx + context - e.message += ` while parsing near '${ - start === 0 ? '' : '...' - }${txt.slice(start, end)}${ - end === txt.length ? '' : '...' - }'` } else { - e.message += ` while parsing '${txt.slice(0, context * 2)}'` + break; } - throw e } -} + if (is_WHITE_SPACE(ch)) { + do { ch = state.input.charCodeAt(++state.position); } + while (is_WHITE_SPACE(ch)); -/***/ }), + if (ch === 0x23/* # */) { + do { ch = state.input.charCodeAt(++state.position); } + while (!is_EOL(ch) && (ch !== 0)); + } + } -/***/ 53359: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + while (ch !== 0) { + readLineBreak(state); + state.lineIndent = 0; -var jws = __nccwpck_require__(4636); + ch = state.input.charCodeAt(state.position); -module.exports = function (jwt, options) { - options = options || {}; - var decoded = jws.decode(jwt, options); - if (!decoded) { return null; } - var payload = decoded.payload; + while ((!detectedIndent || state.lineIndent < textIndent) && + (ch === 0x20/* Space */)) { + state.lineIndent++; + ch = state.input.charCodeAt(++state.position); + } - //try parse the payload - if(typeof payload === 'string') { - try { - var obj = JSON.parse(payload); - if(obj !== null && typeof obj === 'object') { - payload = obj; - } - } catch (e) { } - } + if (!detectedIndent && state.lineIndent > textIndent) { + textIndent = state.lineIndent; + } - //return header if `complete` option is enabled. header includes claims - //such as `kid` and `alg` used to select the key within a JWKS needed to - //verify the signature - if (options.complete === true) { - return { - header: decoded.header, - payload: payload, - signature: decoded.signature - }; - } - return payload; -}; + if (is_EOL(ch)) { + emptyLines++; + continue; + } + + // End of the scalar. + if (state.lineIndent < textIndent) { + + // Perform the chomping. + if (chomping === CHOMPING_KEEP) { + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + } else if (chomping === CHOMPING_CLIP) { + if (didReadContent) { // i.e. only if the scalar is not empty. + state.result += '\n'; + } + } + // Break this `while` cycle and go to the funciton's epilogue. + break; + } -/***/ }), + // Folded style: use fancy rules to handle line breaks. + if (folding) { -/***/ 77486: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // Lines starting with white space characters (more-indented lines) are not folded. + if (is_WHITE_SPACE(ch)) { + atMoreIndented = true; + // except for the first content line (cf. Example 8.1) + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); -module.exports = { - decode: __nccwpck_require__(53359), - verify: __nccwpck_require__(12327), - sign: __nccwpck_require__(82022), - JsonWebTokenError: __nccwpck_require__(405), - NotBeforeError: __nccwpck_require__(4383), - TokenExpiredError: __nccwpck_require__(46637), -}; + // End of more-indented block. + } else if (atMoreIndented) { + atMoreIndented = false; + state.result += common.repeat('\n', emptyLines + 1); + + // Just one line break - perceive as the same line. + } else if (emptyLines === 0) { + if (didReadContent) { // i.e. only if we have already read some scalar content. + state.result += ' '; + } + // Several line breaks - perceive as different lines. + } else { + state.result += common.repeat('\n', emptyLines); + } -/***/ }), + // Literal style: just add exact number of line breaks between content lines. + } else { + // Keep all line breaks except the header line break. + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + } -/***/ 405: -/***/ ((module) => { + didReadContent = true; + detectedIndent = true; + emptyLines = 0; + captureStart = state.position; -var JsonWebTokenError = function (message, error) { - Error.call(this, message); - if(Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); + while (!is_EOL(ch) && (ch !== 0)) { + ch = state.input.charCodeAt(++state.position); + } + + captureSegment(state, captureStart, state.position, false); } - this.name = 'JsonWebTokenError'; - this.message = message; - if (error) this.inner = error; -}; -JsonWebTokenError.prototype = Object.create(Error.prototype); -JsonWebTokenError.prototype.constructor = JsonWebTokenError; + return true; +} -module.exports = JsonWebTokenError; +function readBlockSequence(state, nodeIndent) { + var _line, + _tag = state.tag, + _anchor = state.anchor, + _result = [], + following, + detected = false, + ch; + // there is a leading tab before this token, so it can't be a block sequence/mapping; + // it can still be flow sequence/mapping or a scalar + if (state.firstTabInLine !== -1) return false; -/***/ }), + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; + } -/***/ 4383: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + ch = state.input.charCodeAt(state.position); -var JsonWebTokenError = __nccwpck_require__(405); + while (ch !== 0) { + if (state.firstTabInLine !== -1) { + state.position = state.firstTabInLine; + throwError(state, 'tab characters must not be used in indentation'); + } -var NotBeforeError = function (message, date) { - JsonWebTokenError.call(this, message); - this.name = 'NotBeforeError'; - this.date = date; -}; + if (ch !== 0x2D/* - */) { + break; + } -NotBeforeError.prototype = Object.create(JsonWebTokenError.prototype); + following = state.input.charCodeAt(state.position + 1); -NotBeforeError.prototype.constructor = NotBeforeError; + if (!is_WS_OR_EOL(following)) { + break; + } -module.exports = NotBeforeError; + detected = true; + state.position++; -/***/ }), + if (skipSeparationSpace(state, true, -1)) { + if (state.lineIndent <= nodeIndent) { + _result.push(null); + ch = state.input.charCodeAt(state.position); + continue; + } + } -/***/ 46637: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + _line = state.line; + composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true); + _result.push(state.result); + skipSeparationSpace(state, true, -1); -var JsonWebTokenError = __nccwpck_require__(405); + ch = state.input.charCodeAt(state.position); -var TokenExpiredError = function (message, expiredAt) { - JsonWebTokenError.call(this, message); - this.name = 'TokenExpiredError'; - this.expiredAt = expiredAt; -}; + if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { + throwError(state, 'bad indentation of a sequence entry'); + } else if (state.lineIndent < nodeIndent) { + break; + } + } -TokenExpiredError.prototype = Object.create(JsonWebTokenError.prototype); + if (detected) { + state.tag = _tag; + state.anchor = _anchor; + state.kind = 'sequence'; + state.result = _result; + return true; + } + return false; +} -TokenExpiredError.prototype.constructor = TokenExpiredError; +function readBlockMapping(state, nodeIndent, flowIndent) { + var following, + allowCompact, + _line, + _keyLine, + _keyLineStart, + _keyPos, + _tag = state.tag, + _anchor = state.anchor, + _result = {}, + overridableKeys = Object.create(null), + keyTag = null, + keyNode = null, + valueNode = null, + atExplicitKey = false, + detected = false, + ch; -module.exports = TokenExpiredError; + // there is a leading tab before this token, so it can't be a block sequence/mapping; + // it can still be flow sequence/mapping or a scalar + if (state.firstTabInLine !== -1) return false; -/***/ }), + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; + } -/***/ 59085: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + ch = state.input.charCodeAt(state.position); -var semver = __nccwpck_require__(27174); + while (ch !== 0) { + if (!atExplicitKey && state.firstTabInLine !== -1) { + state.position = state.firstTabInLine; + throwError(state, 'tab characters must not be used in indentation'); + } -module.exports = semver.satisfies(process.version, '^6.12.0 || >=8.0.0'); + following = state.input.charCodeAt(state.position + 1); + _line = state.line; // Save the current line. + // + // Explicit notation case. There are two separate blocks: + // first for the key (denoted by "?") and second for the value (denoted by ":") + // + if ((ch === 0x3F/* ? */ || ch === 0x3A/* : */) && is_WS_OR_EOL(following)) { -/***/ }), + if (ch === 0x3F/* ? */) { + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); + keyTag = keyNode = valueNode = null; + } -/***/ 46098: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + detected = true; + atExplicitKey = true; + allowCompact = true; -var ms = __nccwpck_require__(80900); + } else if (atExplicitKey) { + // i.e. 0x3A/* : */ === character after the explicit key. + atExplicitKey = false; + allowCompact = true; -module.exports = function (time, iat) { - var timestamp = iat || Math.floor(Date.now() / 1000); + } else { + throwError(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line'); + } - if (typeof time === 'string') { - var milliseconds = ms(time); - if (typeof milliseconds === 'undefined') { - return; - } - return Math.floor(timestamp + milliseconds / 1000); - } else if (typeof time === 'number') { - return timestamp + time; - } else { - return; - } + state.position += 1; + ch = following; -}; + // + // Implicit notation case. Flow-style node as the key first, then ":", and the value. + // + } else { + _keyLine = state.line; + _keyLineStart = state.lineStart; + _keyPos = state.position; -/***/ }), + if (!composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) { + // Neither implicit nor explicit notation. + // Reading is done. Go to the epilogue. + break; + } -/***/ 27174: -/***/ ((module, exports) => { + if (state.line === _line) { + ch = state.input.charCodeAt(state.position); -exports = module.exports = SemVer + while (is_WHITE_SPACE(ch)) { + ch = state.input.charCodeAt(++state.position); + } -var debug -/* istanbul ignore next */ -if (typeof process === 'object' && - process.env && - process.env.NODE_DEBUG && - /\bsemver\b/i.test(process.env.NODE_DEBUG)) { - debug = function () { - var args = Array.prototype.slice.call(arguments, 0) - args.unshift('SEMVER') - console.log.apply(console, args) - } -} else { - debug = function () {} -} + if (ch === 0x3A/* : */) { + ch = state.input.charCodeAt(++state.position); -// Note: this is the semver.org version of the spec that it implements -// Not necessarily the package version of this code. -exports.SEMVER_SPEC_VERSION = '2.0.0' + if (!is_WS_OR_EOL(ch)) { + throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping'); + } -var MAX_LENGTH = 256 -var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || - /* istanbul ignore next */ 9007199254740991 + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); + keyTag = keyNode = valueNode = null; + } -// Max safe segment length for coercion. -var MAX_SAFE_COMPONENT_LENGTH = 16 + detected = true; + atExplicitKey = false; + allowCompact = false; + keyTag = state.tag; + keyNode = state.result; -// The actual regexps go on exports.re -var re = exports.re = [] -var src = exports.src = [] -var R = 0 + } else if (detected) { + throwError(state, 'can not read an implicit mapping pair; a colon is missed'); -// The following Regular Expressions can be used for tokenizing, -// validating, and parsing SemVer version strings. + } else { + state.tag = _tag; + state.anchor = _anchor; + return true; // Keep the result of `composeNode`. + } -// ## Numeric Identifier -// A single `0`, or a non-zero digit followed by zero or more digits. + } else if (detected) { + throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key'); -var NUMERICIDENTIFIER = R++ -src[NUMERICIDENTIFIER] = '0|[1-9]\\d*' -var NUMERICIDENTIFIERLOOSE = R++ -src[NUMERICIDENTIFIERLOOSE] = '[0-9]+' + } else { + state.tag = _tag; + state.anchor = _anchor; + return true; // Keep the result of `composeNode`. + } + } -// ## Non-numeric Identifier -// Zero or more digits, followed by a letter or hyphen, and then zero or -// more letters, digits, or hyphens. + // + // Common reading code for both explicit and implicit notations. + // + if (state.line === _line || state.lineIndent > nodeIndent) { + if (atExplicitKey) { + _keyLine = state.line; + _keyLineStart = state.lineStart; + _keyPos = state.position; + } -var NONNUMERICIDENTIFIER = R++ -src[NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*' + if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) { + if (atExplicitKey) { + keyNode = state.result; + } else { + valueNode = state.result; + } + } -// ## Main Version -// Three dot-separated numeric identifiers. + if (!atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _keyLine, _keyLineStart, _keyPos); + keyTag = keyNode = valueNode = null; + } -var MAINVERSION = R++ -src[MAINVERSION] = '(' + src[NUMERICIDENTIFIER] + ')\\.' + - '(' + src[NUMERICIDENTIFIER] + ')\\.' + - '(' + src[NUMERICIDENTIFIER] + ')' + skipSeparationSpace(state, true, -1); + ch = state.input.charCodeAt(state.position); + } -var MAINVERSIONLOOSE = R++ -src[MAINVERSIONLOOSE] = '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + - '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + - '(' + src[NUMERICIDENTIFIERLOOSE] + ')' + if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { + throwError(state, 'bad indentation of a mapping entry'); + } else if (state.lineIndent < nodeIndent) { + break; + } + } -// ## Pre-release Version Identifier -// A numeric identifier, or a non-numeric identifier. + // + // Epilogue. + // -var PRERELEASEIDENTIFIER = R++ -src[PRERELEASEIDENTIFIER] = '(?:' + src[NUMERICIDENTIFIER] + - '|' + src[NONNUMERICIDENTIFIER] + ')' + // Special case: last mapping's node contains only the key in explicit notation. + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); + } -var PRERELEASEIDENTIFIERLOOSE = R++ -src[PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[NUMERICIDENTIFIERLOOSE] + - '|' + src[NONNUMERICIDENTIFIER] + ')' + // Expose the resulting mapping. + if (detected) { + state.tag = _tag; + state.anchor = _anchor; + state.kind = 'mapping'; + state.result = _result; + } -// ## Pre-release Version -// Hyphen, followed by one or more dot-separated pre-release version -// identifiers. + return detected; +} -var PRERELEASE = R++ -src[PRERELEASE] = '(?:-(' + src[PRERELEASEIDENTIFIER] + - '(?:\\.' + src[PRERELEASEIDENTIFIER] + ')*))' +function readTagProperty(state) { + var _position, + isVerbatim = false, + isNamed = false, + tagHandle, + tagName, + ch; -var PRERELEASELOOSE = R++ -src[PRERELEASELOOSE] = '(?:-?(' + src[PRERELEASEIDENTIFIERLOOSE] + - '(?:\\.' + src[PRERELEASEIDENTIFIERLOOSE] + ')*))' + ch = state.input.charCodeAt(state.position); -// ## Build Metadata Identifier -// Any combination of digits, letters, or hyphens. + if (ch !== 0x21/* ! */) return false; -var BUILDIDENTIFIER = R++ -src[BUILDIDENTIFIER] = '[0-9A-Za-z-]+' + if (state.tag !== null) { + throwError(state, 'duplication of a tag property'); + } -// ## Build Metadata -// Plus sign, followed by one or more period-separated build metadata -// identifiers. + ch = state.input.charCodeAt(++state.position); -var BUILD = R++ -src[BUILD] = '(?:\\+(' + src[BUILDIDENTIFIER] + - '(?:\\.' + src[BUILDIDENTIFIER] + ')*))' + if (ch === 0x3C/* < */) { + isVerbatim = true; + ch = state.input.charCodeAt(++state.position); -// ## Full Version String -// A main version, followed optionally by a pre-release version and -// build metadata. + } else if (ch === 0x21/* ! */) { + isNamed = true; + tagHandle = '!!'; + ch = state.input.charCodeAt(++state.position); -// Note that the only major, minor, patch, and pre-release sections of -// the version string are capturing groups. The build metadata is not a -// capturing group, because it should not ever be used in version -// comparison. + } else { + tagHandle = '!'; + } -var FULL = R++ -var FULLPLAIN = 'v?' + src[MAINVERSION] + - src[PRERELEASE] + '?' + - src[BUILD] + '?' + _position = state.position; -src[FULL] = '^' + FULLPLAIN + '$' + if (isVerbatim) { + do { ch = state.input.charCodeAt(++state.position); } + while (ch !== 0 && ch !== 0x3E/* > */); -// like full, but allows v1.2.3 and =1.2.3, which people do sometimes. -// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty -// common in the npm registry. -var LOOSEPLAIN = '[v=\\s]*' + src[MAINVERSIONLOOSE] + - src[PRERELEASELOOSE] + '?' + - src[BUILD] + '?' + if (state.position < state.length) { + tagName = state.input.slice(_position, state.position); + ch = state.input.charCodeAt(++state.position); + } else { + throwError(state, 'unexpected end of the stream within a verbatim tag'); + } + } else { + while (ch !== 0 && !is_WS_OR_EOL(ch)) { -var LOOSE = R++ -src[LOOSE] = '^' + LOOSEPLAIN + '$' + if (ch === 0x21/* ! */) { + if (!isNamed) { + tagHandle = state.input.slice(_position - 1, state.position + 1); -var GTLT = R++ -src[GTLT] = '((?:<|>)?=?)' + if (!PATTERN_TAG_HANDLE.test(tagHandle)) { + throwError(state, 'named tag handle cannot contain such characters'); + } -// Something like "2.*" or "1.2.x". -// Note that "x.x" is a valid xRange identifer, meaning "any version" -// Only the first item is strictly required. -var XRANGEIDENTIFIERLOOSE = R++ -src[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + '|x|X|\\*' -var XRANGEIDENTIFIER = R++ -src[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + '|x|X|\\*' + isNamed = true; + _position = state.position + 1; + } else { + throwError(state, 'tag suffix cannot contain exclamation marks'); + } + } -var XRANGEPLAIN = R++ -src[XRANGEPLAIN] = '[v=\\s]*(' + src[XRANGEIDENTIFIER] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + - '(?:' + src[PRERELEASE] + ')?' + - src[BUILD] + '?' + - ')?)?' + ch = state.input.charCodeAt(++state.position); + } -var XRANGEPLAINLOOSE = R++ -src[XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[XRANGEIDENTIFIERLOOSE] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + - '(?:' + src[PRERELEASELOOSE] + ')?' + - src[BUILD] + '?' + - ')?)?' + tagName = state.input.slice(_position, state.position); -var XRANGE = R++ -src[XRANGE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAIN] + '$' -var XRANGELOOSE = R++ -src[XRANGELOOSE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAINLOOSE] + '$' + if (PATTERN_FLOW_INDICATORS.test(tagName)) { + throwError(state, 'tag suffix cannot contain flow indicator characters'); + } + } -// Coercion. -// Extract anything that could conceivably be a part of a valid semver -var COERCE = R++ -src[COERCE] = '(?:^|[^\\d])' + - '(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' + - '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + - '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + - '(?:$|[^\\d])' + if (tagName && !PATTERN_TAG_URI.test(tagName)) { + throwError(state, 'tag name cannot contain such characters: ' + tagName); + } + + try { + tagName = decodeURIComponent(tagName); + } catch (err) { + throwError(state, 'tag name is malformed: ' + tagName); + } -// Tilde ranges. -// Meaning is "reasonably at or greater than" -var LONETILDE = R++ -src[LONETILDE] = '(?:~>?)' + if (isVerbatim) { + state.tag = tagName; -var TILDETRIM = R++ -src[TILDETRIM] = '(\\s*)' + src[LONETILDE] + '\\s+' -re[TILDETRIM] = new RegExp(src[TILDETRIM], 'g') -var tildeTrimReplace = '$1~' + } else if (_hasOwnProperty.call(state.tagMap, tagHandle)) { + state.tag = state.tagMap[tagHandle] + tagName; -var TILDE = R++ -src[TILDE] = '^' + src[LONETILDE] + src[XRANGEPLAIN] + '$' -var TILDELOOSE = R++ -src[TILDELOOSE] = '^' + src[LONETILDE] + src[XRANGEPLAINLOOSE] + '$' + } else if (tagHandle === '!') { + state.tag = '!' + tagName; -// Caret ranges. -// Meaning is "at least and backwards compatible with" -var LONECARET = R++ -src[LONECARET] = '(?:\\^)' + } else if (tagHandle === '!!') { + state.tag = 'tag:yaml.org,2002:' + tagName; -var CARETTRIM = R++ -src[CARETTRIM] = '(\\s*)' + src[LONECARET] + '\\s+' -re[CARETTRIM] = new RegExp(src[CARETTRIM], 'g') -var caretTrimReplace = '$1^' + } else { + throwError(state, 'undeclared tag handle "' + tagHandle + '"'); + } -var CARET = R++ -src[CARET] = '^' + src[LONECARET] + src[XRANGEPLAIN] + '$' -var CARETLOOSE = R++ -src[CARETLOOSE] = '^' + src[LONECARET] + src[XRANGEPLAINLOOSE] + '$' + return true; +} -// A simple gt/lt/eq thing, or just "" to indicate "any version" -var COMPARATORLOOSE = R++ -src[COMPARATORLOOSE] = '^' + src[GTLT] + '\\s*(' + LOOSEPLAIN + ')$|^$' -var COMPARATOR = R++ -src[COMPARATOR] = '^' + src[GTLT] + '\\s*(' + FULLPLAIN + ')$|^$' +function readAnchorProperty(state) { + var _position, + ch; -// An expression to strip any whitespace between the gtlt and the thing -// it modifies, so that `> 1.2.3` ==> `>1.2.3` -var COMPARATORTRIM = R++ -src[COMPARATORTRIM] = '(\\s*)' + src[GTLT] + - '\\s*(' + LOOSEPLAIN + '|' + src[XRANGEPLAIN] + ')' + ch = state.input.charCodeAt(state.position); -// this one has to use the /g flag -re[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], 'g') -var comparatorTrimReplace = '$1$2$3' + if (ch !== 0x26/* & */) return false; -// Something like `1.2.3 - 1.2.4` -// Note that these all use the loose form, because they'll be -// checked against either the strict or loose comparator form -// later. -var HYPHENRANGE = R++ -src[HYPHENRANGE] = '^\\s*(' + src[XRANGEPLAIN] + ')' + - '\\s+-\\s+' + - '(' + src[XRANGEPLAIN] + ')' + - '\\s*$' + if (state.anchor !== null) { + throwError(state, 'duplication of an anchor property'); + } -var HYPHENRANGELOOSE = R++ -src[HYPHENRANGELOOSE] = '^\\s*(' + src[XRANGEPLAINLOOSE] + ')' + - '\\s+-\\s+' + - '(' + src[XRANGEPLAINLOOSE] + ')' + - '\\s*$' + ch = state.input.charCodeAt(++state.position); + _position = state.position; -// Star ranges basically just allow anything at all. -var STAR = R++ -src[STAR] = '(<|>)?=?\\s*\\*' + while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { + ch = state.input.charCodeAt(++state.position); + } -// Compile to actual regexp objects. -// All are flag-free, unless they were created above with a flag. -for (var i = 0; i < R; i++) { - debug(i, src[i]) - if (!re[i]) { - re[i] = new RegExp(src[i]) + if (state.position === _position) { + throwError(state, 'name of an anchor node must contain at least one character'); } + + state.anchor = state.input.slice(_position, state.position); + return true; } -exports.parse = parse -function parse (version, options) { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } - } +function readAlias(state) { + var _position, alias, + ch; - if (version instanceof SemVer) { - return version - } + ch = state.input.charCodeAt(state.position); - if (typeof version !== 'string') { - return null - } + if (ch !== 0x2A/* * */) return false; - if (version.length > MAX_LENGTH) { - return null + ch = state.input.charCodeAt(++state.position); + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { + ch = state.input.charCodeAt(++state.position); } - var r = options.loose ? re[LOOSE] : re[FULL] - if (!r.test(version)) { - return null + if (state.position === _position) { + throwError(state, 'name of an alias node must contain at least one character'); } - try { - return new SemVer(version, options) - } catch (er) { - return null + alias = state.input.slice(_position, state.position); + + if (!_hasOwnProperty.call(state.anchorMap, alias)) { + throwError(state, 'unidentified alias "' + alias + '"'); } -} -exports.valid = valid -function valid (version, options) { - var v = parse(version, options) - return v ? v.version : null + state.result = state.anchorMap[alias]; + skipSeparationSpace(state, true, -1); + return true; } -exports.clean = clean -function clean (version, options) { - var s = parse(version.trim().replace(/^[=v]+/, ''), options) - return s ? s.version : null -} +function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) { + var allowBlockStyles, + allowBlockScalars, + allowBlockCollections, + indentStatus = 1, // 1: this>parent, 0: this=parent, -1: this parentIndent) { + indentStatus = 1; + } else if (state.lineIndent === parentIndent) { + indentStatus = 0; + } else if (state.lineIndent < parentIndent) { + indentStatus = -1; + } } } - if (version instanceof SemVer) { - if (version.loose === options.loose) { - return version - } else { - version = version.version + + if (indentStatus === 1) { + while (readTagProperty(state) || readAnchorProperty(state)) { + if (skipSeparationSpace(state, true, -1)) { + atNewLine = true; + allowBlockCollections = allowBlockStyles; + + if (state.lineIndent > parentIndent) { + indentStatus = 1; + } else if (state.lineIndent === parentIndent) { + indentStatus = 0; + } else if (state.lineIndent < parentIndent) { + indentStatus = -1; + } + } else { + allowBlockCollections = false; + } } - } else if (typeof version !== 'string') { - throw new TypeError('Invalid Version: ' + version) } - if (version.length > MAX_LENGTH) { - throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters') + if (allowBlockCollections) { + allowBlockCollections = atNewLine || allowCompact; } - if (!(this instanceof SemVer)) { - return new SemVer(version, options) - } + if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) { + if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) { + flowIndent = parentIndent; + } else { + flowIndent = parentIndent + 1; + } - debug('SemVer', version, options) - this.options = options - this.loose = !!options.loose + blockIndent = state.position - state.lineStart; - var m = version.trim().match(options.loose ? re[LOOSE] : re[FULL]) + if (indentStatus === 1) { + if (allowBlockCollections && + (readBlockSequence(state, blockIndent) || + readBlockMapping(state, blockIndent, flowIndent)) || + readFlowCollection(state, flowIndent)) { + hasContent = true; + } else { + if ((allowBlockScalars && readBlockScalar(state, flowIndent)) || + readSingleQuotedScalar(state, flowIndent) || + readDoubleQuotedScalar(state, flowIndent)) { + hasContent = true; - if (!m) { - throw new TypeError('Invalid Version: ' + version) - } + } else if (readAlias(state)) { + hasContent = true; - this.raw = version + if (state.tag !== null || state.anchor !== null) { + throwError(state, 'alias node should not have any properties'); + } - // these are actually numbers - this.major = +m[1] - this.minor = +m[2] - this.patch = +m[3] + } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) { + hasContent = true; - if (this.major > MAX_SAFE_INTEGER || this.major < 0) { - throw new TypeError('Invalid major version') - } + if (state.tag === null) { + state.tag = '?'; + } + } - if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { - throw new TypeError('Invalid minor version') + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + } + } else if (indentStatus === 0) { + // Special case: block sequences are allowed to have same indentation level as the parent. + // http://www.yaml.org/spec/1.2/spec.html#id2799784 + hasContent = allowBlockCollections && readBlockSequence(state, blockIndent); + } } - if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { - throw new TypeError('Invalid patch version') - } + if (state.tag === null) { + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } - // numberify any prerelease numeric ids - if (!m[4]) { - this.prerelease = [] - } else { - this.prerelease = m[4].split('.').map(function (id) { - if (/^[0-9]+$/.test(id)) { - var num = +id - if (num >= 0 && num < MAX_SAFE_INTEGER) { - return num + } else if (state.tag === '?') { + // Implicit resolving is not allowed for non-scalar types, and '?' + // non-specific tag is only automatically assigned to plain scalars. + // + // We only need to check kind conformity in case user explicitly assigns '?' + // tag, for example like this: "! [0]" + // + if (state.result !== null && state.kind !== 'scalar') { + throwError(state, 'unacceptable node kind for ! tag; it should be "scalar", not "' + state.kind + '"'); + } + + for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) { + type = state.implicitTypes[typeIndex]; + + if (type.resolve(state.result)) { // `state.result` updated in resolver if matched + state.result = type.construct(state.result); + state.tag = type.tag; + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; } + break; } - return id - }) - } + } + } else if (state.tag !== '!') { + if (_hasOwnProperty.call(state.typeMap[state.kind || 'fallback'], state.tag)) { + type = state.typeMap[state.kind || 'fallback'][state.tag]; + } else { + // looking for multi type + type = null; + typeList = state.typeMap.multi[state.kind || 'fallback']; - this.build = m[5] ? m[5].split('.') : [] - this.format() -} + for (typeIndex = 0, typeQuantity = typeList.length; typeIndex < typeQuantity; typeIndex += 1) { + if (state.tag.slice(0, typeList[typeIndex].tag.length) === typeList[typeIndex].tag) { + type = typeList[typeIndex]; + break; + } + } + } -SemVer.prototype.format = function () { - this.version = this.major + '.' + this.minor + '.' + this.patch - if (this.prerelease.length) { - this.version += '-' + this.prerelease.join('.') - } - return this.version -} + if (!type) { + throwError(state, 'unknown tag !<' + state.tag + '>'); + } -SemVer.prototype.toString = function () { - return this.version -} + if (state.result !== null && type.kind !== state.kind) { + throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be "' + type.kind + '", not "' + state.kind + '"'); + } -SemVer.prototype.compare = function (other) { - debug('SemVer.compare', this.version, this.options, other) - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options) + if (!type.resolve(state.result, state.tag)) { // `state.result` updated in resolver if matched + throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag'); + } else { + state.result = type.construct(state.result, state.tag); + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + } } - return this.compareMain(other) || this.comparePre(other) + if (state.listener !== null) { + state.listener('close', state); + } + return state.tag !== null || state.anchor !== null || hasContent; } -SemVer.prototype.compareMain = function (other) { - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options) - } +function readDocument(state) { + var documentStart = state.position, + _position, + directiveName, + directiveArgs, + hasDirectives = false, + ch; - return compareIdentifiers(this.major, other.major) || - compareIdentifiers(this.minor, other.minor) || - compareIdentifiers(this.patch, other.patch) -} + state.version = null; + state.checkLineBreaks = state.legacy; + state.tagMap = Object.create(null); + state.anchorMap = Object.create(null); -SemVer.prototype.comparePre = function (other) { - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options) - } + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + skipSeparationSpace(state, true, -1); - // NOT having a prerelease is > having one - if (this.prerelease.length && !other.prerelease.length) { - return -1 - } else if (!this.prerelease.length && other.prerelease.length) { - return 1 - } else if (!this.prerelease.length && !other.prerelease.length) { - return 0 - } + ch = state.input.charCodeAt(state.position); - var i = 0 - do { - var a = this.prerelease[i] - var b = other.prerelease[i] - debug('prerelease compare', i, a, b) - if (a === undefined && b === undefined) { - return 0 - } else if (b === undefined) { - return 1 - } else if (a === undefined) { - return -1 - } else if (a === b) { - continue - } else { - return compareIdentifiers(a, b) + if (state.lineIndent > 0 || ch !== 0x25/* % */) { + break; } - } while (++i) -} -// preminor will bump the version up to the next minor release, and immediately -// down to pre-release. premajor and prepatch work the same way. -SemVer.prototype.inc = function (release, identifier) { - switch (release) { - case 'premajor': - this.prerelease.length = 0 - this.patch = 0 - this.minor = 0 - this.major++ - this.inc('pre', identifier) - break - case 'preminor': - this.prerelease.length = 0 - this.patch = 0 - this.minor++ - this.inc('pre', identifier) - break - case 'prepatch': - // If this is already a prerelease, it will bump to the next version - // drop any prereleases that might already exist, since they are not - // relevant at this point. - this.prerelease.length = 0 - this.inc('patch', identifier) - this.inc('pre', identifier) - break - // If the input is a non-prerelease version, this acts the same as - // prepatch. - case 'prerelease': - if (this.prerelease.length === 0) { - this.inc('patch', identifier) - } - this.inc('pre', identifier) - break + hasDirectives = true; + ch = state.input.charCodeAt(++state.position); + _position = state.position; - case 'major': - // If this is a pre-major version, bump up to the same major version. - // Otherwise increment major. - // 1.0.0-5 bumps to 1.0.0 - // 1.1.0 bumps to 2.0.0 - if (this.minor !== 0 || - this.patch !== 0 || - this.prerelease.length === 0) { - this.major++ - } - this.minor = 0 - this.patch = 0 - this.prerelease = [] - break - case 'minor': - // If this is a pre-minor version, bump up to the same minor version. - // Otherwise increment minor. - // 1.2.0-5 bumps to 1.2.0 - // 1.2.1 bumps to 1.3.0 - if (this.patch !== 0 || this.prerelease.length === 0) { - this.minor++ - } - this.patch = 0 - this.prerelease = [] - break - case 'patch': - // If this is not a pre-release version, it will increment the patch. - // If it is a pre-release it will bump up to the same patch version. - // 1.2.0-5 patches to 1.2.0 - // 1.2.0 patches to 1.2.1 - if (this.prerelease.length === 0) { - this.patch++ - } - this.prerelease = [] - break - // This probably shouldn't be used publicly. - // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction. - case 'pre': - if (this.prerelease.length === 0) { - this.prerelease = [0] - } else { - var i = this.prerelease.length - while (--i >= 0) { - if (typeof this.prerelease[i] === 'number') { - this.prerelease[i]++ - i = -2 - } - } - if (i === -1) { - // didn't increment anything - this.prerelease.push(0) - } + while (ch !== 0 && !is_WS_OR_EOL(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + directiveName = state.input.slice(_position, state.position); + directiveArgs = []; + + if (directiveName.length < 1) { + throwError(state, 'directive name must not be less than one character in length'); + } + + while (ch !== 0) { + while (is_WHITE_SPACE(ch)) { + ch = state.input.charCodeAt(++state.position); } - if (identifier) { - // 1.2.0-beta.1 bumps to 1.2.0-beta.2, - // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 - if (this.prerelease[0] === identifier) { - if (isNaN(this.prerelease[1])) { - this.prerelease = [identifier, 0] - } - } else { - this.prerelease = [identifier, 0] - } + + if (ch === 0x23/* # */) { + do { ch = state.input.charCodeAt(++state.position); } + while (ch !== 0 && !is_EOL(ch)); + break; } - break - default: - throw new Error('invalid increment argument: ' + release) + if (is_EOL(ch)) break; + + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + directiveArgs.push(state.input.slice(_position, state.position)); + } + + if (ch !== 0) readLineBreak(state); + + if (_hasOwnProperty.call(directiveHandlers, directiveName)) { + directiveHandlers[directiveName](state, directiveName, directiveArgs); + } else { + throwWarning(state, 'unknown document directive "' + directiveName + '"'); + } } - this.format() - this.raw = this.version - return this -} -exports.inc = inc -function inc (version, release, loose, identifier) { - if (typeof (loose) === 'string') { - identifier = loose - loose = undefined + skipSeparationSpace(state, true, -1); + + if (state.lineIndent === 0 && + state.input.charCodeAt(state.position) === 0x2D/* - */ && + state.input.charCodeAt(state.position + 1) === 0x2D/* - */ && + state.input.charCodeAt(state.position + 2) === 0x2D/* - */) { + state.position += 3; + skipSeparationSpace(state, true, -1); + + } else if (hasDirectives) { + throwError(state, 'directives end mark is expected'); } - try { - return new SemVer(version, loose).inc(release, identifier).version - } catch (er) { - return null + composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true); + skipSeparationSpace(state, true, -1); + + if (state.checkLineBreaks && + PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) { + throwWarning(state, 'non-ASCII line breaks are interpreted as content'); } -} -exports.diff = diff -function diff (version1, version2) { - if (eq(version1, version2)) { - return null + state.documents.push(state.result); + + if (state.position === state.lineStart && testDocumentSeparator(state)) { + + if (state.input.charCodeAt(state.position) === 0x2E/* . */) { + state.position += 3; + skipSeparationSpace(state, true, -1); + } + return; + } + + if (state.position < (state.length - 1)) { + throwError(state, 'end of the stream or a document separator is expected'); } else { - var v1 = parse(version1) - var v2 = parse(version2) - var prefix = '' - if (v1.prerelease.length || v2.prerelease.length) { - prefix = 'pre' - var defaultResult = 'prerelease' + return; + } +} + + +function loadDocuments(input, options) { + input = String(input); + options = options || {}; + + if (input.length !== 0) { + + // Add tailing `\n` if not exists + if (input.charCodeAt(input.length - 1) !== 0x0A/* LF */ && + input.charCodeAt(input.length - 1) !== 0x0D/* CR */) { + input += '\n'; } - for (var key in v1) { - if (key === 'major' || key === 'minor' || key === 'patch') { - if (v1[key] !== v2[key]) { - return prefix + key - } - } + + // Strip BOM + if (input.charCodeAt(0) === 0xFEFF) { + input = input.slice(1); } - return defaultResult // may be undefined } -} -exports.compareIdentifiers = compareIdentifiers + var state = new State(input, options); -var numeric = /^[0-9]+$/ -function compareIdentifiers (a, b) { - var anum = numeric.test(a) - var bnum = numeric.test(b) + var nullpos = input.indexOf('\0'); - if (anum && bnum) { - a = +a - b = +b + if (nullpos !== -1) { + state.position = nullpos; + throwError(state, 'null byte is not allowed in input'); } - return a === b ? 0 - : (anum && !bnum) ? -1 - : (bnum && !anum) ? 1 - : a < b ? -1 - : 1 -} + // Use 0 as string terminator. That significantly simplifies bounds check. + state.input += '\0'; -exports.rcompareIdentifiers = rcompareIdentifiers -function rcompareIdentifiers (a, b) { - return compareIdentifiers(b, a) -} + while (state.input.charCodeAt(state.position) === 0x20/* Space */) { + state.lineIndent += 1; + state.position += 1; + } -exports.major = major -function major (a, loose) { - return new SemVer(a, loose).major -} + while (state.position < (state.length - 1)) { + readDocument(state); + } -exports.minor = minor -function minor (a, loose) { - return new SemVer(a, loose).minor + return state.documents; } -exports.patch = patch -function patch (a, loose) { - return new SemVer(a, loose).patch -} -exports.compare = compare -function compare (a, b, loose) { - return new SemVer(a, loose).compare(new SemVer(b, loose)) -} +function loadAll(input, iterator, options) { + if (iterator !== null && typeof iterator === 'object' && typeof options === 'undefined') { + options = iterator; + iterator = null; + } -exports.compareLoose = compareLoose -function compareLoose (a, b) { - return compare(a, b, true) -} + var documents = loadDocuments(input, options); -exports.rcompare = rcompare -function rcompare (a, b, loose) { - return compare(b, a, loose) -} + if (typeof iterator !== 'function') { + return documents; + } -exports.sort = sort -function sort (list, loose) { - return list.sort(function (a, b) { - return exports.compare(a, b, loose) - }) + for (var index = 0, length = documents.length; index < length; index += 1) { + iterator(documents[index]); + } } -exports.rsort = rsort -function rsort (list, loose) { - return list.sort(function (a, b) { - return exports.rcompare(a, b, loose) - }) -} -exports.gt = gt -function gt (a, b, loose) { - return compare(a, b, loose) > 0 -} +function load(input, options) { + var documents = loadDocuments(input, options); -exports.lt = lt -function lt (a, b, loose) { - return compare(a, b, loose) < 0 + if (documents.length === 0) { + /*eslint-disable no-undefined*/ + return undefined; + } else if (documents.length === 1) { + return documents[0]; + } + throw new YAMLException('expected a single document in the stream, but found more'); } -exports.eq = eq -function eq (a, b, loose) { - return compare(a, b, loose) === 0 -} -exports.neq = neq -function neq (a, b, loose) { - return compare(a, b, loose) !== 0 -} +module.exports.loadAll = loadAll; +module.exports.load = load; -exports.gte = gte -function gte (a, b, loose) { - return compare(a, b, loose) >= 0 -} -exports.lte = lte -function lte (a, b, loose) { - return compare(a, b, loose) <= 0 -} +/***/ }), -exports.cmp = cmp -function cmp (a, op, b, loose) { - switch (op) { - case '===': - if (typeof a === 'object') - a = a.version - if (typeof b === 'object') - b = b.version - return a === b +/***/ 21082: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - case '!==': - if (typeof a === 'object') - a = a.version - if (typeof b === 'object') - b = b.version - return a !== b +"use strict"; - case '': - case '=': - case '==': - return eq(a, b, loose) - case '!=': - return neq(a, b, loose) +/*eslint-disable max-len*/ - case '>': - return gt(a, b, loose) +var YAMLException = __nccwpck_require__(68179); +var Type = __nccwpck_require__(6073); - case '>=': - return gte(a, b, loose) - case '<': - return lt(a, b, loose) +function compileList(schema, name) { + var result = []; - case '<=': - return lte(a, b, loose) + schema[name].forEach(function (currentType) { + var newIndex = result.length; - default: - throw new TypeError('Invalid operator: ' + op) - } + result.forEach(function (previousType, previousIndex) { + if (previousType.tag === currentType.tag && + previousType.kind === currentType.kind && + previousType.multi === currentType.multi) { + + newIndex = previousIndex; + } + }); + + result[newIndex] = currentType; + }); + + return result; } -exports.Comparator = Comparator -function Comparator (comp, options) { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } - } - if (comp instanceof Comparator) { - if (comp.loose === !!options.loose) { - return comp +function compileMap(/* lists... */) { + var result = { + scalar: {}, + sequence: {}, + mapping: {}, + fallback: {}, + multi: { + scalar: [], + sequence: [], + mapping: [], + fallback: [] + } + }, index, length; + + function collectType(type) { + if (type.multi) { + result.multi[type.kind].push(type); + result.multi['fallback'].push(type); } else { - comp = comp.value + result[type.kind][type.tag] = result['fallback'][type.tag] = type; } } - if (!(this instanceof Comparator)) { - return new Comparator(comp, options) + for (index = 0, length = arguments.length; index < length; index += 1) { + arguments[index].forEach(collectType); } + return result; +} - debug('comparator', comp, options) - this.options = options - this.loose = !!options.loose - this.parse(comp) - - if (this.semver === ANY) { - this.value = '' - } else { - this.value = this.operator + this.semver.version - } - debug('comp', this) +function Schema(definition) { + return this.extend(definition); } -var ANY = {} -Comparator.prototype.parse = function (comp) { - var r = this.options.loose ? re[COMPARATORLOOSE] : re[COMPARATOR] - var m = comp.match(r) - if (!m) { - throw new TypeError('Invalid comparator: ' + comp) - } +Schema.prototype.extend = function extend(definition) { + var implicit = []; + var explicit = []; - this.operator = m[1] - if (this.operator === '=') { - this.operator = '' - } + if (definition instanceof Type) { + // Schema.extend(type) + explicit.push(definition); + + } else if (Array.isArray(definition)) { + // Schema.extend([ type1, type2, ... ]) + explicit = explicit.concat(definition); + + } else if (definition && (Array.isArray(definition.implicit) || Array.isArray(definition.explicit))) { + // Schema.extend({ explicit: [ type1, type2, ... ], implicit: [ type1, type2, ... ] }) + if (definition.implicit) implicit = implicit.concat(definition.implicit); + if (definition.explicit) explicit = explicit.concat(definition.explicit); - // if it literally is just '>' or '' then allow anything. - if (!m[2]) { - this.semver = ANY } else { - this.semver = new SemVer(m[2], this.options.loose) + throw new YAMLException('Schema.extend argument should be a Type, [ Type ], ' + + 'or a schema definition ({ implicit: [...], explicit: [...] })'); } -} -Comparator.prototype.toString = function () { - return this.value -} + implicit.forEach(function (type) { + if (!(type instanceof Type)) { + throw new YAMLException('Specified list of YAML types (or a single Type object) contains a non-Type object.'); + } -Comparator.prototype.test = function (version) { - debug('Comparator.test', version, this.options.loose) + if (type.loadKind && type.loadKind !== 'scalar') { + throw new YAMLException('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.'); + } - if (this.semver === ANY) { - return true - } + if (type.multi) { + throw new YAMLException('There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.'); + } + }); - if (typeof version === 'string') { - version = new SemVer(version, this.options) - } + explicit.forEach(function (type) { + if (!(type instanceof Type)) { + throw new YAMLException('Specified list of YAML types (or a single Type object) contains a non-Type object.'); + } + }); - return cmp(version, this.operator, this.semver, this.options) -} + var result = Object.create(Schema.prototype); -Comparator.prototype.intersects = function (comp, options) { - if (!(comp instanceof Comparator)) { - throw new TypeError('a Comparator is required') - } + result.implicit = (this.implicit || []).concat(implicit); + result.explicit = (this.explicit || []).concat(explicit); - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } - } + result.compiledImplicit = compileList(result, 'implicit'); + result.compiledExplicit = compileList(result, 'explicit'); + result.compiledTypeMap = compileMap(result.compiledImplicit, result.compiledExplicit); - var rangeTmp + return result; +}; - if (this.operator === '') { - rangeTmp = new Range(comp.value, options) - return satisfies(this.value, rangeTmp, options) - } else if (comp.operator === '') { - rangeTmp = new Range(this.value, options) - return satisfies(comp.semver, rangeTmp, options) - } - var sameDirectionIncreasing = - (this.operator === '>=' || this.operator === '>') && - (comp.operator === '>=' || comp.operator === '>') - var sameDirectionDecreasing = - (this.operator === '<=' || this.operator === '<') && - (comp.operator === '<=' || comp.operator === '<') - var sameSemVer = this.semver.version === comp.semver.version - var differentDirectionsInclusive = - (this.operator === '>=' || this.operator === '<=') && - (comp.operator === '>=' || comp.operator === '<=') - var oppositeDirectionsLessThan = - cmp(this.semver, '<', comp.semver, options) && - ((this.operator === '>=' || this.operator === '>') && - (comp.operator === '<=' || comp.operator === '<')) - var oppositeDirectionsGreaterThan = - cmp(this.semver, '>', comp.semver, options) && - ((this.operator === '<=' || this.operator === '<') && - (comp.operator === '>=' || comp.operator === '>')) +module.exports = Schema; - return sameDirectionIncreasing || sameDirectionDecreasing || - (sameSemVer && differentDirectionsInclusive) || - oppositeDirectionsLessThan || oppositeDirectionsGreaterThan -} -exports.Range = Range -function Range (range, options) { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } - } +/***/ }), - if (range instanceof Range) { - if (range.loose === !!options.loose && - range.includePrerelease === !!options.includePrerelease) { - return range - } else { - return new Range(range.raw, options) - } - } +/***/ 12011: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (range instanceof Comparator) { - return new Range(range.value, options) - } +"use strict"; +// Standard YAML's Core schema. +// http://www.yaml.org/spec/1.2/spec.html#id2804923 +// +// NOTE: JS-YAML does not support schema-specific tag resolution restrictions. +// So, Core schema has no distinctions from JSON schema is JS-YAML. - if (!(this instanceof Range)) { - return new Range(range, options) - } - this.options = options - this.loose = !!options.loose - this.includePrerelease = !!options.includePrerelease - // First, split based on boolean or || - this.raw = range - this.set = range.split(/\s*\|\|\s*/).map(function (range) { - return this.parseRange(range.trim()) - }, this).filter(function (c) { - // throw out any that are not relevant for whatever reason - return c.length - }) - if (!this.set.length) { - throw new TypeError('Invalid SemVer Range: ' + range) - } - this.format() -} +module.exports = __nccwpck_require__(1035); + + +/***/ }), + +/***/ 18759: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; +// JS-YAML's default schema for `safeLoad` function. +// It is not described in the YAML specification. +// +// This schema is based on standard YAML's Core schema and includes most of +// extra types described at YAML tag repository. (http://yaml.org/type/) -Range.prototype.format = function () { - this.range = this.set.map(function (comps) { - return comps.join(' ').trim() - }).join('||').trim() - return this.range -} -Range.prototype.toString = function () { - return this.range -} -Range.prototype.parseRange = function (range) { - var loose = this.options.loose - range = range.trim() - // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` - var hr = loose ? re[HYPHENRANGELOOSE] : re[HYPHENRANGE] - range = range.replace(hr, hyphenReplace) - debug('hyphen replace', range) - // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` - range = range.replace(re[COMPARATORTRIM], comparatorTrimReplace) - debug('comparator trim', range, re[COMPARATORTRIM]) - // `~ 1.2.3` => `~1.2.3` - range = range.replace(re[TILDETRIM], tildeTrimReplace) - // `^ 1.2.3` => `^1.2.3` - range = range.replace(re[CARETTRIM], caretTrimReplace) +module.exports = (__nccwpck_require__(12011).extend)({ + implicit: [ + __nccwpck_require__(99212), + __nccwpck_require__(86104) + ], + explicit: [ + __nccwpck_require__(77900), + __nccwpck_require__(19046), + __nccwpck_require__(96860), + __nccwpck_require__(79548) + ] +}); - // normalize spaces - range = range.split(/\s+/).join(' ') - // At this point, the range is completely trimmed and - // ready to be split into comparators. +/***/ }), - var compRe = loose ? re[COMPARATORLOOSE] : re[COMPARATOR] - var set = range.split(' ').map(function (comp) { - return parseComparator(comp, this.options) - }, this).join(' ').split(/\s+/) - if (this.options.loose) { - // in loose mode, throw out any that are not valid comparators - set = set.filter(function (comp) { - return !!comp.match(compRe) - }) - } - set = set.map(function (comp) { - return new Comparator(comp, this.options) - }, this) +/***/ 28562: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return set -} +"use strict"; +// Standard YAML's Failsafe schema. +// http://www.yaml.org/spec/1.2/spec.html#id2802346 -Range.prototype.intersects = function (range, options) { - if (!(range instanceof Range)) { - throw new TypeError('a Range is required') - } - return this.set.some(function (thisComparators) { - return thisComparators.every(function (thisComparator) { - return range.set.some(function (rangeComparators) { - return rangeComparators.every(function (rangeComparator) { - return thisComparator.intersects(rangeComparator, options) - }) - }) - }) - }) -} -// Mostly just for testing and legacy API reasons -exports.toComparators = toComparators -function toComparators (range, options) { - return new Range(range, options).set.map(function (comp) { - return comp.map(function (c) { - return c.value - }).join(' ').trim().split(' ') - }) -} -// comprised of xranges, tildes, stars, and gtlt's at this point. -// already replaced the hyphen ranges -// turn into a set of JUST comparators. -function parseComparator (comp, options) { - debug('comp', comp, options) - comp = replaceCarets(comp, options) - debug('caret', comp) - comp = replaceTildes(comp, options) - debug('tildes', comp) - comp = replaceXRanges(comp, options) - debug('xrange', comp) - comp = replaceStars(comp, options) - debug('stars', comp) - return comp -} -function isX (id) { - return !id || id.toLowerCase() === 'x' || id === '*' -} +var Schema = __nccwpck_require__(21082); -// ~, ~> --> * (any, kinda silly) -// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0 -// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0 -// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0 -// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0 -// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0 -function replaceTildes (comp, options) { - return comp.trim().split(/\s+/).map(function (comp) { - return replaceTilde(comp, options) - }).join(' ') -} -function replaceTilde (comp, options) { - var r = options.loose ? re[TILDELOOSE] : re[TILDE] - return comp.replace(r, function (_, M, m, p, pr) { - debug('tilde', comp, _, M, m, p, pr) - var ret +module.exports = new Schema({ + explicit: [ + __nccwpck_require__(23619), + __nccwpck_require__(67283), + __nccwpck_require__(86150) + ] +}); - if (isX(M)) { - ret = '' - } else if (isX(m)) { - ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' - } else if (isX(p)) { - // ~1.2 == >=1.2.0 <1.3.0 - ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' - } else if (pr) { - debug('replaceTilde pr', pr) - ret = '>=' + M + '.' + m + '.' + p + '-' + pr + - ' <' + M + '.' + (+m + 1) + '.0' - } else { - // ~1.2.3 == >=1.2.3 <1.3.0 - ret = '>=' + M + '.' + m + '.' + p + - ' <' + M + '.' + (+m + 1) + '.0' - } - debug('tilde return', ret) - return ret - }) -} +/***/ }), -// ^ --> * (any, kinda silly) -// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0 -// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0 -// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0 -// ^1.2.3 --> >=1.2.3 <2.0.0 -// ^1.2.0 --> >=1.2.0 <2.0.0 -function replaceCarets (comp, options) { - return comp.trim().split(/\s+/).map(function (comp) { - return replaceCaret(comp, options) - }).join(' ') -} +/***/ 1035: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -function replaceCaret (comp, options) { - debug('caret', comp, options) - var r = options.loose ? re[CARETLOOSE] : re[CARET] - return comp.replace(r, function (_, M, m, p, pr) { - debug('caret', comp, _, M, m, p, pr) - var ret +"use strict"; +// Standard YAML's JSON schema. +// http://www.yaml.org/spec/1.2/spec.html#id2803231 +// +// NOTE: JS-YAML does not support schema-specific tag resolution restrictions. +// So, this schema is not such strict as defined in the YAML specification. +// It allows numbers in binary notaion, use `Null` and `NULL` as `null`, etc. - if (isX(M)) { - ret = '' - } else if (isX(m)) { - ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' - } else if (isX(p)) { - if (M === '0') { - ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' - } else { - ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0' - } - } else if (pr) { - debug('replaceCaret pr', pr) - if (M === '0') { - if (m === '0') { - ret = '>=' + M + '.' + m + '.' + p + '-' + pr + - ' <' + M + '.' + m + '.' + (+p + 1) - } else { - ret = '>=' + M + '.' + m + '.' + p + '-' + pr + - ' <' + M + '.' + (+m + 1) + '.0' - } - } else { - ret = '>=' + M + '.' + m + '.' + p + '-' + pr + - ' <' + (+M + 1) + '.0.0' - } - } else { - debug('no pr') - if (M === '0') { - if (m === '0') { - ret = '>=' + M + '.' + m + '.' + p + - ' <' + M + '.' + m + '.' + (+p + 1) - } else { - ret = '>=' + M + '.' + m + '.' + p + - ' <' + M + '.' + (+m + 1) + '.0' - } - } else { - ret = '>=' + M + '.' + m + '.' + p + - ' <' + (+M + 1) + '.0.0' - } - } - debug('caret return', ret) - return ret - }) -} -function replaceXRanges (comp, options) { - debug('replaceXRanges', comp, options) - return comp.split(/\s+/).map(function (comp) { - return replaceXRange(comp, options) - }).join(' ') -} -function replaceXRange (comp, options) { - comp = comp.trim() - var r = options.loose ? re[XRANGELOOSE] : re[XRANGE] - return comp.replace(r, function (ret, gtlt, M, m, p, pr) { - debug('xRange', comp, ret, gtlt, M, m, p, pr) - var xM = isX(M) - var xm = xM || isX(m) - var xp = xm || isX(p) - var anyX = xp - if (gtlt === '=' && anyX) { - gtlt = '' - } +module.exports = (__nccwpck_require__(28562).extend)({ + implicit: [ + __nccwpck_require__(20721), + __nccwpck_require__(64993), + __nccwpck_require__(11615), + __nccwpck_require__(42705) + ] +}); - if (xM) { - if (gtlt === '>' || gtlt === '<') { - // nothing is allowed - ret = '<0.0.0' - } else { - // nothing is forbidden - ret = '*' - } - } else if (gtlt && anyX) { - // we know patch is an x, because we have any x at all. - // replace X with 0 - if (xm) { - m = 0 - } - p = 0 - if (gtlt === '>') { - // >1 => >=2.0.0 - // >1.2 => >=1.3.0 - // >1.2.3 => >= 1.2.4 - gtlt = '>=' - if (xm) { - M = +M + 1 - m = 0 - p = 0 - } else { - m = +m + 1 - p = 0 - } - } else if (gtlt === '<=') { - // <=0.7.x is actually <0.8.0, since any 0.7.x should - // pass. Similarly, <=7.x is actually <8.0.0, etc. - gtlt = '<' - if (xm) { - M = +M + 1 - } else { - m = +m + 1 - } - } +/***/ }), - ret = gtlt + M + '.' + m + '.' + p - } else if (xm) { - ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' - } else if (xp) { - ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' - } +/***/ 96975: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - debug('xRange return', ret) +"use strict"; - return ret - }) -} -// Because * is AND-ed with everything else in the comparator, -// and '' means "any version", just remove the *s entirely. -function replaceStars (comp, options) { - debug('replaceStars', comp, options) - // Looseness is ignored here. star is always as loose as it gets! - return comp.trim().replace(re[STAR], '') -} -// This function is passed to string.replace(re[HYPHENRANGE]) -// M, m, patch, prerelease, build -// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 -// 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do -// 1.2 - 3.4 => >=1.2.0 <3.5.0 -function hyphenReplace ($0, - from, fM, fm, fp, fpr, fb, - to, tM, tm, tp, tpr, tb) { - if (isX(fM)) { - from = '' - } else if (isX(fm)) { - from = '>=' + fM + '.0.0' - } else if (isX(fp)) { - from = '>=' + fM + '.' + fm + '.0' - } else { - from = '>=' + from - } +var common = __nccwpck_require__(26829); - if (isX(tM)) { - to = '' - } else if (isX(tm)) { - to = '<' + (+tM + 1) + '.0.0' - } else if (isX(tp)) { - to = '<' + tM + '.' + (+tm + 1) + '.0' - } else if (tpr) { - to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr - } else { - to = '<=' + to - } - return (from + ' ' + to).trim() -} +// get snippet for a single line, respecting maxLength +function getLine(buffer, lineStart, lineEnd, position, maxLineLength) { + var head = ''; + var tail = ''; + var maxHalfLength = Math.floor(maxLineLength / 2) - 1; -// if ANY of the sets match ALL of its comparators, then pass -Range.prototype.test = function (version) { - if (!version) { - return false + if (position - lineStart > maxHalfLength) { + head = ' ... '; + lineStart = position - maxHalfLength + head.length; } - if (typeof version === 'string') { - version = new SemVer(version, this.options) + if (lineEnd - position > maxHalfLength) { + tail = ' ...'; + lineEnd = position + maxHalfLength - tail.length; } - for (var i = 0; i < this.set.length; i++) { - if (testSet(this.set[i], version, this.options)) { - return true - } - } - return false + return { + str: head + buffer.slice(lineStart, lineEnd).replace(/\t/g, '→') + tail, + pos: position - lineStart + head.length // relative position + }; } -function testSet (set, version, options) { - for (var i = 0; i < set.length; i++) { - if (!set[i].test(version)) { - return false - } - } - - if (version.prerelease.length && !options.includePrerelease) { - // Find the set of versions that are allowed to have prereleases - // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 - // That should allow `1.2.3-pr.2` to pass. - // However, `1.2.4-alpha.notready` should NOT be allowed, - // even though it's within the range set by the comparators. - for (i = 0; i < set.length; i++) { - debug(set[i].semver) - if (set[i].semver === ANY) { - continue - } - if (set[i].semver.prerelease.length > 0) { - var allowed = set[i].semver - if (allowed.major === version.major && - allowed.minor === version.minor && - allowed.patch === version.patch) { - return true - } - } - } +function padStart(string, max) { + return common.repeat(' ', max - string.length) + string; +} - // Version has a -pre, but it's not one of the ones we like. - return false - } - return true -} +function makeSnippet(mark, options) { + options = Object.create(options || null); -exports.satisfies = satisfies -function satisfies (version, range, options) { - try { - range = new Range(range, options) - } catch (er) { - return false - } - return range.test(version) -} + if (!mark.buffer) return null; -exports.maxSatisfying = maxSatisfying -function maxSatisfying (versions, range, options) { - var max = null - var maxSV = null - try { - var rangeObj = new Range(range, options) - } catch (er) { - return null - } - versions.forEach(function (v) { - if (rangeObj.test(v)) { - // satisfies(v, range, options) - if (!max || maxSV.compare(v) === -1) { - // compare(max, v, true) - max = v - maxSV = new SemVer(max, options) - } - } - }) - return max -} + if (!options.maxLength) options.maxLength = 79; + if (typeof options.indent !== 'number') options.indent = 1; + if (typeof options.linesBefore !== 'number') options.linesBefore = 3; + if (typeof options.linesAfter !== 'number') options.linesAfter = 2; -exports.minSatisfying = minSatisfying -function minSatisfying (versions, range, options) { - var min = null - var minSV = null - try { - var rangeObj = new Range(range, options) - } catch (er) { - return null - } - versions.forEach(function (v) { - if (rangeObj.test(v)) { - // satisfies(v, range, options) - if (!min || minSV.compare(v) === 1) { - // compare(min, v, true) - min = v - minSV = new SemVer(min, options) - } - } - }) - return min -} + var re = /\r?\n|\r|\0/g; + var lineStarts = [ 0 ]; + var lineEnds = []; + var match; + var foundLineNo = -1; -exports.minVersion = minVersion -function minVersion (range, loose) { - range = new Range(range, loose) + while ((match = re.exec(mark.buffer))) { + lineEnds.push(match.index); + lineStarts.push(match.index + match[0].length); - var minver = new SemVer('0.0.0') - if (range.test(minver)) { - return minver + if (mark.position <= match.index && foundLineNo < 0) { + foundLineNo = lineStarts.length - 2; + } } - minver = new SemVer('0.0.0-0') - if (range.test(minver)) { - return minver - } + if (foundLineNo < 0) foundLineNo = lineStarts.length - 1; - minver = null - for (var i = 0; i < range.set.length; ++i) { - var comparators = range.set[i] + var result = '', i, line; + var lineNoLength = Math.min(mark.line + options.linesAfter, lineEnds.length).toString().length; + var maxLineLength = options.maxLength - (options.indent + lineNoLength + 3); - comparators.forEach(function (comparator) { - // Clone to avoid manipulating the comparator's semver object. - var compver = new SemVer(comparator.semver.version) - switch (comparator.operator) { - case '>': - if (compver.prerelease.length === 0) { - compver.patch++ - } else { - compver.prerelease.push(0) - } - compver.raw = compver.format() - /* fallthrough */ - case '': - case '>=': - if (!minver || gt(minver, compver)) { - minver = compver - } - break - case '<': - case '<=': - /* Ignore maximum versions */ - break - /* istanbul ignore next */ - default: - throw new Error('Unexpected operation: ' + comparator.operator) - } - }) + for (i = 1; i <= options.linesBefore; i++) { + if (foundLineNo - i < 0) break; + line = getLine( + mark.buffer, + lineStarts[foundLineNo - i], + lineEnds[foundLineNo - i], + mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo - i]), + maxLineLength + ); + result = common.repeat(' ', options.indent) + padStart((mark.line - i + 1).toString(), lineNoLength) + + ' | ' + line.str + '\n' + result; } - if (minver && range.test(minver)) { - return minver + line = getLine(mark.buffer, lineStarts[foundLineNo], lineEnds[foundLineNo], mark.position, maxLineLength); + result += common.repeat(' ', options.indent) + padStart((mark.line + 1).toString(), lineNoLength) + + ' | ' + line.str + '\n'; + result += common.repeat('-', options.indent + lineNoLength + 3 + line.pos) + '^' + '\n'; + + for (i = 1; i <= options.linesAfter; i++) { + if (foundLineNo + i >= lineEnds.length) break; + line = getLine( + mark.buffer, + lineStarts[foundLineNo + i], + lineEnds[foundLineNo + i], + mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo + i]), + maxLineLength + ); + result += common.repeat(' ', options.indent) + padStart((mark.line + i + 1).toString(), lineNoLength) + + ' | ' + line.str + '\n'; } - return null + return result.replace(/\n$/, ''); } -exports.validRange = validRange -function validRange (range, options) { - try { - // Return '*' instead of '' so that truthiness works. - // This will throw if it's invalid anyway - return new Range(range, options).range || '*' - } catch (er) { - return null - } -} -// Determine if version is less than all the versions possible in the range -exports.ltr = ltr -function ltr (version, range, options) { - return outside(version, range, '<', options) -} +module.exports = makeSnippet; -// Determine if version is greater than all the versions possible in the range. -exports.gtr = gtr -function gtr (version, range, options) { - return outside(version, range, '>', options) -} -exports.outside = outside -function outside (version, range, hilo, options) { - version = new SemVer(version, options) - range = new Range(range, options) +/***/ }), - var gtfn, ltefn, ltfn, comp, ecomp - switch (hilo) { - case '>': - gtfn = gt - ltefn = lte - ltfn = lt - comp = '>' - ecomp = '>=' - break - case '<': - gtfn = lt - ltefn = gte - ltfn = gt - comp = '<' - ecomp = '<=' - break - default: - throw new TypeError('Must provide a hilo val of "<" or ">"') - } +/***/ 6073: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // If it satisifes the range it is not outside - if (satisfies(version, range, options)) { - return false - } +"use strict"; - // From now on, variable terms are as if we're in "gtr" mode. - // but note that everything is flipped for the "ltr" function. - for (var i = 0; i < range.set.length; ++i) { - var comparators = range.set[i] +var YAMLException = __nccwpck_require__(68179); - var high = null - var low = null +var TYPE_CONSTRUCTOR_OPTIONS = [ + 'kind', + 'multi', + 'resolve', + 'construct', + 'instanceOf', + 'predicate', + 'represent', + 'representName', + 'defaultStyle', + 'styleAliases' +]; - comparators.forEach(function (comparator) { - if (comparator.semver === ANY) { - comparator = new Comparator('>=0.0.0') - } - high = high || comparator - low = low || comparator - if (gtfn(comparator.semver, high.semver, options)) { - high = comparator - } else if (ltfn(comparator.semver, low.semver, options)) { - low = comparator - } - }) +var YAML_NODE_KINDS = [ + 'scalar', + 'sequence', + 'mapping' +]; - // If the edge version comparator has a operator then our version - // isn't outside it - if (high.operator === comp || high.operator === ecomp) { - return false - } +function compileStyleAliases(map) { + var result = {}; - // If the lowest version comparator has an operator and our version - // is less than it then it isn't higher than the range - if ((!low.operator || low.operator === comp) && - ltefn(version, low.semver)) { - return false - } else if (low.operator === ecomp && ltfn(version, low.semver)) { - return false - } + if (map !== null) { + Object.keys(map).forEach(function (style) { + map[style].forEach(function (alias) { + result[String(alias)] = style; + }); + }); } - return true -} - -exports.prerelease = prerelease -function prerelease (version, options) { - var parsed = parse(version, options) - return (parsed && parsed.prerelease.length) ? parsed.prerelease : null -} -exports.intersects = intersects -function intersects (r1, r2, options) { - r1 = new Range(r1, options) - r2 = new Range(r2, options) - return r1.intersects(r2) + return result; } -exports.coerce = coerce -function coerce (version) { - if (version instanceof SemVer) { - return version - } +function Type(tag, options) { + options = options || {}; - if (typeof version !== 'string') { - return null - } + Object.keys(options).forEach(function (name) { + if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) { + throw new YAMLException('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.'); + } + }); - var match = version.match(re[COERCE]) + // TODO: Add tag format check. + this.options = options; // keep original options in case user wants to extend this type later + this.tag = tag; + this.kind = options['kind'] || null; + this.resolve = options['resolve'] || function () { return true; }; + this.construct = options['construct'] || function (data) { return data; }; + this.instanceOf = options['instanceOf'] || null; + this.predicate = options['predicate'] || null; + this.represent = options['represent'] || null; + this.representName = options['representName'] || null; + this.defaultStyle = options['defaultStyle'] || null; + this.multi = options['multi'] || false; + this.styleAliases = compileStyleAliases(options['styleAliases'] || null); - if (match == null) { - return null + if (YAML_NODE_KINDS.indexOf(this.kind) === -1) { + throw new YAMLException('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.'); } - - return parse(match[1] + - '.' + (match[2] || '0') + - '.' + (match[3] || '0')) } +module.exports = Type; + /***/ }), -/***/ 82022: +/***/ 77900: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var timespan = __nccwpck_require__(46098); -var PS_SUPPORTED = __nccwpck_require__(59085); -var jws = __nccwpck_require__(4636); -var includes = __nccwpck_require__(17931); -var isBoolean = __nccwpck_require__(16501); -var isInteger = __nccwpck_require__(21441); -var isNumber = __nccwpck_require__(40298); -var isPlainObject = __nccwpck_require__(25723); -var isString = __nccwpck_require__(25180); -var once = __nccwpck_require__(94499); +"use strict"; -var SUPPORTED_ALGS = ['RS256', 'RS384', 'RS512', 'ES256', 'ES384', 'ES512', 'HS256', 'HS384', 'HS512', 'none'] -if (PS_SUPPORTED) { - SUPPORTED_ALGS.splice(3, 0, 'PS256', 'PS384', 'PS512'); -} -var sign_options_schema = { - expiresIn: { isValid: function(value) { return isInteger(value) || (isString(value) && value); }, message: '"expiresIn" should be a number of seconds or string representing a timespan' }, - notBefore: { isValid: function(value) { return isInteger(value) || (isString(value) && value); }, message: '"notBefore" should be a number of seconds or string representing a timespan' }, - audience: { isValid: function(value) { return isString(value) || Array.isArray(value); }, message: '"audience" must be a string or array' }, - algorithm: { isValid: includes.bind(null, SUPPORTED_ALGS), message: '"algorithm" must be a valid string enum value' }, - header: { isValid: isPlainObject, message: '"header" must be an object' }, - encoding: { isValid: isString, message: '"encoding" must be a string' }, - issuer: { isValid: isString, message: '"issuer" must be a string' }, - subject: { isValid: isString, message: '"subject" must be a string' }, - jwtid: { isValid: isString, message: '"jwtid" must be a string' }, - noTimestamp: { isValid: isBoolean, message: '"noTimestamp" must be a boolean' }, - keyid: { isValid: isString, message: '"keyid" must be a string' }, - mutatePayload: { isValid: isBoolean, message: '"mutatePayload" must be a boolean' } -}; +/*eslint-disable no-bitwise*/ -var registered_claims_schema = { - iat: { isValid: isNumber, message: '"iat" should be a number of seconds' }, - exp: { isValid: isNumber, message: '"exp" should be a number of seconds' }, - nbf: { isValid: isNumber, message: '"nbf" should be a number of seconds' } -}; -function validate(schema, allowUnknown, object, parameterName) { - if (!isPlainObject(object)) { - throw new Error('Expected "' + parameterName + '" to be a plain object.'); - } - Object.keys(object) - .forEach(function(key) { - var validator = schema[key]; - if (!validator) { - if (!allowUnknown) { - throw new Error('"' + key + '" is not allowed in "' + parameterName + '"'); - } - return; - } - if (!validator.isValid(object[key])) { - throw new Error(validator.message); - } - }); -} +var Type = __nccwpck_require__(6073); -function validateOptions(options) { - return validate(sign_options_schema, false, options, 'options'); -} -function validatePayload(payload) { - return validate(registered_claims_schema, true, payload, 'payload'); -} +// [ 64, 65, 66 ] -> [ padding, CR, LF ] +var BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r'; -var options_to_payload = { - 'audience': 'aud', - 'issuer': 'iss', - 'subject': 'sub', - 'jwtid': 'jti' -}; -var options_for_objects = [ - 'expiresIn', - 'notBefore', - 'noTimestamp', - 'audience', - 'issuer', - 'subject', - 'jwtid', -]; +function resolveYamlBinary(data) { + if (data === null) return false; -module.exports = function (payload, secretOrPrivateKey, options, callback) { - if (typeof options === 'function') { - callback = options; - options = {}; - } else { - options = options || {}; - } + var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP; - var isObjectPayload = typeof payload === 'object' && - !Buffer.isBuffer(payload); + // Convert one by one. + for (idx = 0; idx < max; idx++) { + code = map.indexOf(data.charAt(idx)); - var header = Object.assign({ - alg: options.algorithm || 'HS256', - typ: isObjectPayload ? 'JWT' : undefined, - kid: options.keyid - }, options.header); + // Skip CR/LF + if (code > 64) continue; - function failure(err) { - if (callback) { - return callback(err); - } - throw err; - } + // Fail on illegal characters + if (code < 0) return false; - if (!secretOrPrivateKey && options.algorithm !== 'none') { - return failure(new Error('secretOrPrivateKey must have a value')); + bitlen += 6; } - if (typeof payload === 'undefined') { - return failure(new Error('payload is required')); - } else if (isObjectPayload) { - try { - validatePayload(payload); - } - catch (error) { - return failure(error); - } - if (!options.mutatePayload) { - payload = Object.assign({},payload); - } - } else { - var invalid_options = options_for_objects.filter(function (opt) { - return typeof options[opt] !== 'undefined'; - }); + // If there are any bits left, source was corrupted + return (bitlen % 8) === 0; +} - if (invalid_options.length > 0) { - return failure(new Error('invalid ' + invalid_options.join(',') + ' option for ' + (typeof payload ) + ' payload')); +function constructYamlBinary(data) { + var idx, tailbits, + input = data.replace(/[\r\n=]/g, ''), // remove CR/LF & padding to simplify scan + max = input.length, + map = BASE64_MAP, + bits = 0, + result = []; + + // Collect by 6*4 bits (3 bytes) + + for (idx = 0; idx < max; idx++) { + if ((idx % 4 === 0) && idx) { + result.push((bits >> 16) & 0xFF); + result.push((bits >> 8) & 0xFF); + result.push(bits & 0xFF); } - } - if (typeof payload.exp !== 'undefined' && typeof options.expiresIn !== 'undefined') { - return failure(new Error('Bad "options.expiresIn" option the payload already has an "exp" property.')); + bits = (bits << 6) | map.indexOf(input.charAt(idx)); } - if (typeof payload.nbf !== 'undefined' && typeof options.notBefore !== 'undefined') { - return failure(new Error('Bad "options.notBefore" option the payload already has an "nbf" property.')); - } + // Dump tail - try { - validateOptions(options); - } - catch (error) { - return failure(error); + tailbits = (max % 4) * 6; + + if (tailbits === 0) { + result.push((bits >> 16) & 0xFF); + result.push((bits >> 8) & 0xFF); + result.push(bits & 0xFF); + } else if (tailbits === 18) { + result.push((bits >> 10) & 0xFF); + result.push((bits >> 2) & 0xFF); + } else if (tailbits === 12) { + result.push((bits >> 4) & 0xFF); } - var timestamp = payload.iat || Math.floor(Date.now() / 1000); + return new Uint8Array(result); +} - if (options.noTimestamp) { - delete payload.iat; - } else if (isObjectPayload) { - payload.iat = timestamp; - } +function representYamlBinary(object /*, style*/) { + var result = '', bits = 0, idx, tail, + max = object.length, + map = BASE64_MAP; - if (typeof options.notBefore !== 'undefined') { - try { - payload.nbf = timespan(options.notBefore, timestamp); - } - catch (err) { - return failure(err); - } - if (typeof payload.nbf === 'undefined') { - return failure(new Error('"notBefore" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60')); - } - } + // Convert every three bytes to 4 ASCII characters. - if (typeof options.expiresIn !== 'undefined' && typeof payload === 'object') { - try { - payload.exp = timespan(options.expiresIn, timestamp); - } - catch (err) { - return failure(err); - } - if (typeof payload.exp === 'undefined') { - return failure(new Error('"expiresIn" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60')); + for (idx = 0; idx < max; idx++) { + if ((idx % 3 === 0) && idx) { + result += map[(bits >> 18) & 0x3F]; + result += map[(bits >> 12) & 0x3F]; + result += map[(bits >> 6) & 0x3F]; + result += map[bits & 0x3F]; } - } - Object.keys(options_to_payload).forEach(function (key) { - var claim = options_to_payload[key]; - if (typeof options[key] !== 'undefined') { - if (typeof payload[claim] !== 'undefined') { - return failure(new Error('Bad "options.' + key + '" option. The payload already has an "' + claim + '" property.')); - } - payload[claim] = options[key]; - } - }); + bits = (bits << 8) + object[idx]; + } - var encoding = options.encoding || 'utf8'; + // Dump tail - if (typeof callback === 'function') { - callback = callback && once(callback); + tail = max % 3; - jws.createSign({ - header: header, - privateKey: secretOrPrivateKey, - payload: payload, - encoding: encoding - }).once('error', callback) - .once('done', function (signature) { - callback(null, signature); - }); - } else { - return jws.sign({header: header, payload: payload, secret: secretOrPrivateKey, encoding: encoding}); + if (tail === 0) { + result += map[(bits >> 18) & 0x3F]; + result += map[(bits >> 12) & 0x3F]; + result += map[(bits >> 6) & 0x3F]; + result += map[bits & 0x3F]; + } else if (tail === 2) { + result += map[(bits >> 10) & 0x3F]; + result += map[(bits >> 4) & 0x3F]; + result += map[(bits << 2) & 0x3F]; + result += map[64]; + } else if (tail === 1) { + result += map[(bits >> 2) & 0x3F]; + result += map[(bits << 4) & 0x3F]; + result += map[64]; + result += map[64]; } -}; + + return result; +} + +function isBinary(obj) { + return Object.prototype.toString.call(obj) === '[object Uint8Array]'; +} + +module.exports = new Type('tag:yaml.org,2002:binary', { + kind: 'scalar', + resolve: resolveYamlBinary, + construct: constructYamlBinary, + predicate: isBinary, + represent: representYamlBinary +}); /***/ }), -/***/ 12327: +/***/ 64993: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var JsonWebTokenError = __nccwpck_require__(405); -var NotBeforeError = __nccwpck_require__(4383); -var TokenExpiredError = __nccwpck_require__(46637); -var decode = __nccwpck_require__(53359); -var timespan = __nccwpck_require__(46098); -var PS_SUPPORTED = __nccwpck_require__(59085); -var jws = __nccwpck_require__(4636); +"use strict"; -var PUB_KEY_ALGS = ['RS256', 'RS384', 'RS512', 'ES256', 'ES384', 'ES512']; -var RSA_KEY_ALGS = ['RS256', 'RS384', 'RS512']; -var HS_ALGS = ['HS256', 'HS384', 'HS512']; -if (PS_SUPPORTED) { - PUB_KEY_ALGS.splice(3, 0, 'PS256', 'PS384', 'PS512'); - RSA_KEY_ALGS.splice(3, 0, 'PS256', 'PS384', 'PS512'); +var Type = __nccwpck_require__(6073); + +function resolveYamlBoolean(data) { + if (data === null) return false; + + var max = data.length; + + return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) || + (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE')); } -module.exports = function (jwtString, secretOrPublicKey, options, callback) { - if ((typeof options === 'function') && !callback) { - callback = options; - options = {}; - } +function constructYamlBoolean(data) { + return data === 'true' || + data === 'True' || + data === 'TRUE'; +} - if (!options) { - options = {}; - } +function isBoolean(object) { + return Object.prototype.toString.call(object) === '[object Boolean]'; +} - //clone this object since we are going to mutate it. - options = Object.assign({}, options); +module.exports = new Type('tag:yaml.org,2002:bool', { + kind: 'scalar', + resolve: resolveYamlBoolean, + construct: constructYamlBoolean, + predicate: isBoolean, + represent: { + lowercase: function (object) { return object ? 'true' : 'false'; }, + uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; }, + camelcase: function (object) { return object ? 'True' : 'False'; } + }, + defaultStyle: 'lowercase' +}); - var done; - if (callback) { - done = callback; - } else { - done = function(err, data) { - if (err) throw err; - return data; - }; - } +/***/ }), - if (options.clockTimestamp && typeof options.clockTimestamp !== 'number') { - return done(new JsonWebTokenError('clockTimestamp must be a number')); - } +/***/ 42705: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (options.nonce !== undefined && (typeof options.nonce !== 'string' || options.nonce.trim() === '')) { - return done(new JsonWebTokenError('nonce must be a non-empty string')); - } +"use strict"; - var clockTimestamp = options.clockTimestamp || Math.floor(Date.now() / 1000); - if (!jwtString){ - return done(new JsonWebTokenError('jwt must be provided')); - } +var common = __nccwpck_require__(26829); +var Type = __nccwpck_require__(6073); - if (typeof jwtString !== 'string') { - return done(new JsonWebTokenError('jwt must be a string')); - } +var YAML_FLOAT_PATTERN = new RegExp( + // 2.5e4, 2.5 and integers + '^(?:[-+]?(?:[0-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?' + + // .2e4, .2 + // special case, seems not from spec + '|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?' + + // .inf + '|[-+]?\\.(?:inf|Inf|INF)' + + // .nan + '|\\.(?:nan|NaN|NAN))$'); - var parts = jwtString.split('.'); +function resolveYamlFloat(data) { + if (data === null) return false; - if (parts.length !== 3){ - return done(new JsonWebTokenError('jwt malformed')); + if (!YAML_FLOAT_PATTERN.test(data) || + // Quick hack to not allow integers end with `_` + // Probably should update regexp & check speed + data[data.length - 1] === '_') { + return false; } - var decodedToken; + return true; +} - try { - decodedToken = decode(jwtString, { complete: true }); - } catch(err) { - return done(err); - } +function constructYamlFloat(data) { + var value, sign; - if (!decodedToken) { - return done(new JsonWebTokenError('invalid token')); - } + value = data.replace(/_/g, '').toLowerCase(); + sign = value[0] === '-' ? -1 : 1; - var header = decodedToken.header; - var getSecret; + if ('+-'.indexOf(value[0]) >= 0) { + value = value.slice(1); + } - if(typeof secretOrPublicKey === 'function') { - if(!callback) { - return done(new JsonWebTokenError('verify must be called asynchronous if secret or public key is provided as a callback')); - } + if (value === '.inf') { + return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY; - getSecret = secretOrPublicKey; - } - else { - getSecret = function(header, secretCallback) { - return secretCallback(null, secretOrPublicKey); - }; + } else if (value === '.nan') { + return NaN; } + return sign * parseFloat(value, 10); +} - return getSecret(header, function(err, secretOrPublicKey) { - if(err) { - return done(new JsonWebTokenError('error in secret or public key callback: ' + err.message)); - } - var hasSignature = parts[2].trim() !== ''; +var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/; - if (!hasSignature && secretOrPublicKey){ - return done(new JsonWebTokenError('jwt signature is required')); - } +function representYamlFloat(object, style) { + var res; - if (hasSignature && !secretOrPublicKey) { - return done(new JsonWebTokenError('secret or public key must be provided')); + if (isNaN(object)) { + switch (style) { + case 'lowercase': return '.nan'; + case 'uppercase': return '.NAN'; + case 'camelcase': return '.NaN'; } - - if (!hasSignature && !options.algorithms) { - options.algorithms = ['none']; + } else if (Number.POSITIVE_INFINITY === object) { + switch (style) { + case 'lowercase': return '.inf'; + case 'uppercase': return '.INF'; + case 'camelcase': return '.Inf'; + } + } else if (Number.NEGATIVE_INFINITY === object) { + switch (style) { + case 'lowercase': return '-.inf'; + case 'uppercase': return '-.INF'; + case 'camelcase': return '-.Inf'; } + } else if (common.isNegativeZero(object)) { + return '-0.0'; + } - if (!options.algorithms) { - options.algorithms = ~secretOrPublicKey.toString().indexOf('BEGIN CERTIFICATE') || - ~secretOrPublicKey.toString().indexOf('BEGIN PUBLIC KEY') ? PUB_KEY_ALGS : - ~secretOrPublicKey.toString().indexOf('BEGIN RSA PUBLIC KEY') ? RSA_KEY_ALGS : HS_ALGS; + res = object.toString(10); - } + // JS stringifier can build scientific format without dots: 5e-100, + // while YAML requres dot: 5.e-100. Fix it with simple hack - if (!~options.algorithms.indexOf(decodedToken.header.alg)) { - return done(new JsonWebTokenError('invalid algorithm')); - } + return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res; +} - var valid; +function isFloat(object) { + return (Object.prototype.toString.call(object) === '[object Number]') && + (object % 1 !== 0 || common.isNegativeZero(object)); +} - try { - valid = jws.verify(jwtString, decodedToken.header.alg, secretOrPublicKey); - } catch (e) { - return done(e); - } +module.exports = new Type('tag:yaml.org,2002:float', { + kind: 'scalar', + resolve: resolveYamlFloat, + construct: constructYamlFloat, + predicate: isFloat, + represent: representYamlFloat, + defaultStyle: 'lowercase' +}); - if (!valid) { - return done(new JsonWebTokenError('invalid signature')); - } - var payload = decodedToken.payload; +/***/ }), - if (typeof payload.nbf !== 'undefined' && !options.ignoreNotBefore) { - if (typeof payload.nbf !== 'number') { - return done(new JsonWebTokenError('invalid nbf value')); - } - if (payload.nbf > clockTimestamp + (options.clockTolerance || 0)) { - return done(new NotBeforeError('jwt not active', new Date(payload.nbf * 1000))); - } - } +/***/ 11615: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (typeof payload.exp !== 'undefined' && !options.ignoreExpiration) { - if (typeof payload.exp !== 'number') { - return done(new JsonWebTokenError('invalid exp value')); - } - if (clockTimestamp >= payload.exp + (options.clockTolerance || 0)) { - return done(new TokenExpiredError('jwt expired', new Date(payload.exp * 1000))); - } - } +"use strict"; - if (options.audience) { - var audiences = Array.isArray(options.audience) ? options.audience : [options.audience]; - var target = Array.isArray(payload.aud) ? payload.aud : [payload.aud]; - var match = target.some(function (targetAudience) { - return audiences.some(function (audience) { - return audience instanceof RegExp ? audience.test(targetAudience) : audience === targetAudience; - }); - }); +var common = __nccwpck_require__(26829); +var Type = __nccwpck_require__(6073); - if (!match) { - return done(new JsonWebTokenError('jwt audience invalid. expected: ' + audiences.join(' or '))); - } - } +function isHexCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) || + ((0x41/* A */ <= c) && (c <= 0x46/* F */)) || + ((0x61/* a */ <= c) && (c <= 0x66/* f */)); +} - if (options.issuer) { - var invalid_issuer = - (typeof options.issuer === 'string' && payload.iss !== options.issuer) || - (Array.isArray(options.issuer) && options.issuer.indexOf(payload.iss) === -1); +function isOctCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */)); +} - if (invalid_issuer) { - return done(new JsonWebTokenError('jwt issuer invalid. expected: ' + options.issuer)); - } - } +function isDecCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)); +} - if (options.subject) { - if (payload.sub !== options.subject) { - return done(new JsonWebTokenError('jwt subject invalid. expected: ' + options.subject)); - } - } +function resolveYamlInteger(data) { + if (data === null) return false; - if (options.jwtid) { - if (payload.jti !== options.jwtid) { - return done(new JsonWebTokenError('jwt jwtid invalid. expected: ' + options.jwtid)); - } - } + var max = data.length, + index = 0, + hasDigits = false, + ch; - if (options.nonce) { - if (payload.nonce !== options.nonce) { - return done(new JsonWebTokenError('jwt nonce invalid. expected: ' + options.nonce)); - } - } + if (!max) return false; - if (options.maxAge) { - if (typeof payload.iat !== 'number') { - return done(new JsonWebTokenError('iat required when maxAge is specified')); - } + ch = data[index]; - var maxAgeTimestamp = timespan(options.maxAge, payload.iat); - if (typeof maxAgeTimestamp === 'undefined') { - return done(new JsonWebTokenError('"maxAge" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60')); - } - if (clockTimestamp >= maxAgeTimestamp + (options.clockTolerance || 0)) { - return done(new TokenExpiredError('maxAge exceeded', new Date(maxAgeTimestamp * 1000))); - } - } + // sign + if (ch === '-' || ch === '+') { + ch = data[++index]; + } - if (options.complete === true) { - var signature = decodedToken.signature; + if (ch === '0') { + // 0 + if (index + 1 === max) return true; + ch = data[++index]; - return done(null, { - header: header, - payload: payload, - signature: signature - }); - } + // base 2, base 8, base 16 - return done(null, payload); - }); -}; + if (ch === 'b') { + // base 2 + index++; + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (ch !== '0' && ch !== '1') return false; + hasDigits = true; + } + return hasDigits && ch !== '_'; + } -/***/ }), -/***/ 96010: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (ch === 'x') { + // base 16 + index++; -var bufferEqual = __nccwpck_require__(9239); -var Buffer = (__nccwpck_require__(21867).Buffer); -var crypto = __nccwpck_require__(6113); -var formatEcdsa = __nccwpck_require__(11728); -var util = __nccwpck_require__(73837); + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (!isHexCode(data.charCodeAt(index))) return false; + hasDigits = true; + } + return hasDigits && ch !== '_'; + } -var MSG_INVALID_ALGORITHM = '"%s" is not a valid algorithm.\n Supported algorithms are:\n "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".' -var MSG_INVALID_SECRET = 'secret must be a string or buffer'; -var MSG_INVALID_VERIFIER_KEY = 'key must be a string or a buffer'; -var MSG_INVALID_SIGNER_KEY = 'key must be a string, a buffer or an object'; -var supportsKeyObjects = typeof crypto.createPublicKey === 'function'; -if (supportsKeyObjects) { - MSG_INVALID_VERIFIER_KEY += ' or a KeyObject'; - MSG_INVALID_SECRET += 'or a KeyObject'; -} + if (ch === 'o') { + // base 8 + index++; -function checkIsPublicKey(key) { - if (Buffer.isBuffer(key)) { - return; + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (!isOctCode(data.charCodeAt(index))) return false; + hasDigits = true; + } + return hasDigits && ch !== '_'; + } } - if (typeof key === 'string') { - return; - } + // base 10 (except 0) - if (!supportsKeyObjects) { - throw typeError(MSG_INVALID_VERIFIER_KEY); - } + // value should not start with `_`; + if (ch === '_') return false; - if (typeof key !== 'object') { - throw typeError(MSG_INVALID_VERIFIER_KEY); + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (!isDecCode(data.charCodeAt(index))) { + return false; + } + hasDigits = true; } - if (typeof key.type !== 'string') { - throw typeError(MSG_INVALID_VERIFIER_KEY); - } + // Should have digits and should not end with `_` + if (!hasDigits || ch === '_') return false; - if (typeof key.asymmetricKeyType !== 'string') { - throw typeError(MSG_INVALID_VERIFIER_KEY); - } + return true; +} - if (typeof key.export !== 'function') { - throw typeError(MSG_INVALID_VERIFIER_KEY); - } -}; +function constructYamlInteger(data) { + var value = data, sign = 1, ch; -function checkIsPrivateKey(key) { - if (Buffer.isBuffer(key)) { - return; + if (value.indexOf('_') !== -1) { + value = value.replace(/_/g, ''); } - if (typeof key === 'string') { - return; - } + ch = value[0]; - if (typeof key === 'object') { - return; + if (ch === '-' || ch === '+') { + if (ch === '-') sign = -1; + value = value.slice(1); + ch = value[0]; } - throw typeError(MSG_INVALID_SIGNER_KEY); -}; + if (value === '0') return 0; -function checkIsSecretKey(key) { - if (Buffer.isBuffer(key)) { - return; + if (ch === '0') { + if (value[1] === 'b') return sign * parseInt(value.slice(2), 2); + if (value[1] === 'x') return sign * parseInt(value.slice(2), 16); + if (value[1] === 'o') return sign * parseInt(value.slice(2), 8); } - if (typeof key === 'string') { - return key; - } + return sign * parseInt(value, 10); +} - if (!supportsKeyObjects) { - throw typeError(MSG_INVALID_SECRET); - } +function isInteger(object) { + return (Object.prototype.toString.call(object)) === '[object Number]' && + (object % 1 === 0 && !common.isNegativeZero(object)); +} - if (typeof key !== 'object') { - throw typeError(MSG_INVALID_SECRET); +module.exports = new Type('tag:yaml.org,2002:int', { + kind: 'scalar', + resolve: resolveYamlInteger, + construct: constructYamlInteger, + predicate: isInteger, + represent: { + binary: function (obj) { return obj >= 0 ? '0b' + obj.toString(2) : '-0b' + obj.toString(2).slice(1); }, + octal: function (obj) { return obj >= 0 ? '0o' + obj.toString(8) : '-0o' + obj.toString(8).slice(1); }, + decimal: function (obj) { return obj.toString(10); }, + /* eslint-disable max-len */ + hexadecimal: function (obj) { return obj >= 0 ? '0x' + obj.toString(16).toUpperCase() : '-0x' + obj.toString(16).toUpperCase().slice(1); } + }, + defaultStyle: 'decimal', + styleAliases: { + binary: [ 2, 'bin' ], + octal: [ 8, 'oct' ], + decimal: [ 10, 'dec' ], + hexadecimal: [ 16, 'hex' ] } +}); - if (key.type !== 'secret') { - throw typeError(MSG_INVALID_SECRET); - } - if (typeof key.export !== 'function') { - throw typeError(MSG_INVALID_SECRET); - } -} +/***/ }), -function fromBase64(base64) { - return base64 - .replace(/=/g, '') - .replace(/\+/g, '-') - .replace(/\//g, '_'); -} +/***/ 86150: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -function toBase64(base64url) { - base64url = base64url.toString(); +"use strict"; - var padding = 4 - base64url.length % 4; - if (padding !== 4) { - for (var i = 0; i < padding; ++i) { - base64url += '='; - } - } - return base64url - .replace(/\-/g, '+') - .replace(/_/g, '/'); -} +var Type = __nccwpck_require__(6073); -function typeError(template) { - var args = [].slice.call(arguments, 1); - var errMsg = util.format.bind(util, template).apply(null, args); - return new TypeError(errMsg); -} +module.exports = new Type('tag:yaml.org,2002:map', { + kind: 'mapping', + construct: function (data) { return data !== null ? data : {}; } +}); -function bufferOrString(obj) { - return Buffer.isBuffer(obj) || typeof obj === 'string'; -} -function normalizeInput(thing) { - if (!bufferOrString(thing)) - thing = JSON.stringify(thing); - return thing; -} +/***/ }), -function createHmacSigner(bits) { - return function sign(thing, secret) { - checkIsSecretKey(secret); - thing = normalizeInput(thing); - var hmac = crypto.createHmac('sha' + bits, secret); - var sig = (hmac.update(thing), hmac.digest('base64')) - return fromBase64(sig); - } -} +/***/ 86104: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -function createHmacVerifier(bits) { - return function verify(thing, signature, secret) { - var computedSig = createHmacSigner(bits)(thing, secret); - return bufferEqual(Buffer.from(signature), Buffer.from(computedSig)); - } -} +"use strict"; -function createKeySigner(bits) { - return function sign(thing, privateKey) { - checkIsPrivateKey(privateKey); - thing = normalizeInput(thing); - // Even though we are specifying "RSA" here, this works with ECDSA - // keys as well. - var signer = crypto.createSign('RSA-SHA' + bits); - var sig = (signer.update(thing), signer.sign(privateKey, 'base64')); - return fromBase64(sig); - } -} -function createKeyVerifier(bits) { - return function verify(thing, signature, publicKey) { - checkIsPublicKey(publicKey); - thing = normalizeInput(thing); - signature = toBase64(signature); - var verifier = crypto.createVerify('RSA-SHA' + bits); - verifier.update(thing); - return verifier.verify(publicKey, signature, 'base64'); - } -} +var Type = __nccwpck_require__(6073); -function createPSSKeySigner(bits) { - return function sign(thing, privateKey) { - checkIsPrivateKey(privateKey); - thing = normalizeInput(thing); - var signer = crypto.createSign('RSA-SHA' + bits); - var sig = (signer.update(thing), signer.sign({ - key: privateKey, - padding: crypto.constants.RSA_PKCS1_PSS_PADDING, - saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST - }, 'base64')); - return fromBase64(sig); - } +function resolveYamlMerge(data) { + return data === '<<' || data === null; } -function createPSSKeyVerifier(bits) { - return function verify(thing, signature, publicKey) { - checkIsPublicKey(publicKey); - thing = normalizeInput(thing); - signature = toBase64(signature); - var verifier = crypto.createVerify('RSA-SHA' + bits); - verifier.update(thing); - return verifier.verify({ - key: publicKey, - padding: crypto.constants.RSA_PKCS1_PSS_PADDING, - saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST - }, signature, 'base64'); - } -} +module.exports = new Type('tag:yaml.org,2002:merge', { + kind: 'scalar', + resolve: resolveYamlMerge +}); -function createECDSASigner(bits) { - var inner = createKeySigner(bits); - return function sign() { - var signature = inner.apply(null, arguments); - signature = formatEcdsa.derToJose(signature, 'ES' + bits); - return signature; - }; -} -function createECDSAVerifer(bits) { - var inner = createKeyVerifier(bits); - return function verify(thing, signature, publicKey) { - signature = formatEcdsa.joseToDer(signature, 'ES' + bits).toString('base64'); - var result = inner(thing, signature, publicKey); - return result; - }; -} +/***/ }), -function createNoneSigner() { - return function sign() { - return ''; - } +/***/ 20721: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var Type = __nccwpck_require__(6073); + +function resolveYamlNull(data) { + if (data === null) return true; + + var max = data.length; + + return (max === 1 && data === '~') || + (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL')); } -function createNoneVerifier() { - return function verify(thing, signature) { - return signature === ''; - } +function constructYamlNull() { + return null; } -module.exports = function jwa(algorithm) { - var signerFactories = { - hs: createHmacSigner, - rs: createKeySigner, - ps: createPSSKeySigner, - es: createECDSASigner, - none: createNoneSigner, - } - var verifierFactories = { - hs: createHmacVerifier, - rs: createKeyVerifier, - ps: createPSSKeyVerifier, - es: createECDSAVerifer, - none: createNoneVerifier, - } - var match = algorithm.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/i); - if (!match) - throw typeError(MSG_INVALID_ALGORITHM, algorithm); - var algo = (match[1] || match[3]).toLowerCase(); - var bits = match[2]; +function isNull(object) { + return object === null; +} - return { - sign: signerFactories[algo](bits), - verify: verifierFactories[algo](bits), - } -}; +module.exports = new Type('tag:yaml.org,2002:null', { + kind: 'scalar', + resolve: resolveYamlNull, + construct: constructYamlNull, + predicate: isNull, + represent: { + canonical: function () { return '~'; }, + lowercase: function () { return 'null'; }, + uppercase: function () { return 'NULL'; }, + camelcase: function () { return 'Null'; }, + empty: function () { return ''; } + }, + defaultStyle: 'lowercase' +}); /***/ }), -/***/ 4636: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 19046: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/*global exports*/ -var SignStream = __nccwpck_require__(73334); -var VerifyStream = __nccwpck_require__(5522); +"use strict"; -var ALGORITHMS = [ - 'HS256', 'HS384', 'HS512', - 'RS256', 'RS384', 'RS512', - 'PS256', 'PS384', 'PS512', - 'ES256', 'ES384', 'ES512' -]; -exports.ALGORITHMS = ALGORITHMS; -exports.sign = SignStream.sign; -exports.verify = VerifyStream.verify; -exports.decode = VerifyStream.decode; -exports.isValid = VerifyStream.isValid; -exports.createSign = function createSign(opts) { - return new SignStream(opts); -}; -exports.createVerify = function createVerify(opts) { - return new VerifyStream(opts); -}; +var Type = __nccwpck_require__(6073); +var _hasOwnProperty = Object.prototype.hasOwnProperty; +var _toString = Object.prototype.toString; -/***/ }), +function resolveYamlOmap(data) { + if (data === null) return true; -/***/ 61868: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + var objectKeys = [], index, length, pair, pairKey, pairHasKey, + object = data; -/*global module, process*/ -var Buffer = (__nccwpck_require__(21867).Buffer); -var Stream = __nccwpck_require__(12781); -var util = __nccwpck_require__(73837); + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + pairHasKey = false; -function DataStream(data) { - this.buffer = null; - this.writable = true; - this.readable = true; + if (_toString.call(pair) !== '[object Object]') return false; - // No input - if (!data) { - this.buffer = Buffer.alloc(0); - return this; - } + for (pairKey in pair) { + if (_hasOwnProperty.call(pair, pairKey)) { + if (!pairHasKey) pairHasKey = true; + else return false; + } + } - // Stream - if (typeof data.pipe === 'function') { - this.buffer = Buffer.alloc(0); - data.pipe(this); - return this; - } + if (!pairHasKey) return false; - // Buffer or String - // or Object (assumedly a passworded key) - if (data.length || typeof data === 'object') { - this.buffer = data; - this.writable = false; - process.nextTick(function () { - this.emit('end', data); - this.readable = false; - this.emit('close'); - }.bind(this)); - return this; + if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey); + else return false; } - throw new TypeError('Unexpected data type ('+ typeof data + ')'); + return true; } -util.inherits(DataStream, Stream); - -DataStream.prototype.write = function write(data) { - this.buffer = Buffer.concat([this.buffer, Buffer.from(data)]); - this.emit('data', data); -}; -DataStream.prototype.end = function end(data) { - if (data) - this.write(data); - this.emit('end', data); - this.emit('close'); - this.writable = false; - this.readable = false; -}; +function constructYamlOmap(data) { + return data !== null ? data : []; +} -module.exports = DataStream; +module.exports = new Type('tag:yaml.org,2002:omap', { + kind: 'sequence', + resolve: resolveYamlOmap, + construct: constructYamlOmap +}); /***/ }), -/***/ 73334: +/***/ 96860: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/*global module*/ -var Buffer = (__nccwpck_require__(21867).Buffer); -var DataStream = __nccwpck_require__(61868); -var jwa = __nccwpck_require__(96010); -var Stream = __nccwpck_require__(12781); -var toString = __nccwpck_require__(65292); -var util = __nccwpck_require__(73837); +"use strict"; -function base64url(string, encoding) { - return Buffer - .from(string, encoding) - .toString('base64') - .replace(/=/g, '') - .replace(/\+/g, '-') - .replace(/\//g, '_'); -} -function jwsSecuredInput(header, payload, encoding) { - encoding = encoding || 'utf8'; - var encodedHeader = base64url(toString(header), 'binary'); - var encodedPayload = base64url(toString(payload), encoding); - return util.format('%s.%s', encodedHeader, encodedPayload); -} +var Type = __nccwpck_require__(6073); -function jwsSign(opts) { - var header = opts.header; - var payload = opts.payload; - var secretOrKey = opts.secret || opts.privateKey; - var encoding = opts.encoding; - var algo = jwa(header.alg); - var securedInput = jwsSecuredInput(header, payload, encoding); - var signature = algo.sign(securedInput, secretOrKey); - return util.format('%s.%s', securedInput, signature); -} +var _toString = Object.prototype.toString; -function SignStream(opts) { - var secret = opts.secret||opts.privateKey||opts.key; - var secretStream = new DataStream(secret); - this.readable = true; - this.header = opts.header; - this.encoding = opts.encoding; - this.secret = this.privateKey = this.key = secretStream; - this.payload = new DataStream(opts.payload); - this.secret.once('close', function () { - if (!this.payload.writable && this.readable) - this.sign(); - }.bind(this)); +function resolveYamlPairs(data) { + if (data === null) return true; - this.payload.once('close', function () { - if (!this.secret.writable && this.readable) - this.sign(); - }.bind(this)); + var index, length, pair, keys, result, + object = data; + + result = new Array(object.length); + + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + + if (_toString.call(pair) !== '[object Object]') return false; + + keys = Object.keys(pair); + + if (keys.length !== 1) return false; + + result[index] = [ keys[0], pair[keys[0]] ]; + } + + return true; } -util.inherits(SignStream, Stream); -SignStream.prototype.sign = function sign() { - try { - var signature = jwsSign({ - header: this.header, - payload: this.payload.buffer, - secret: this.secret.buffer, - encoding: this.encoding - }); - this.emit('done', signature); - this.emit('data', signature); - this.emit('end'); - this.readable = false; - return signature; - } catch (e) { - this.readable = false; - this.emit('error', e); - this.emit('close'); +function constructYamlPairs(data) { + if (data === null) return []; + + var index, length, pair, keys, result, + object = data; + + result = new Array(object.length); + + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + + keys = Object.keys(pair); + + result[index] = [ keys[0], pair[keys[0]] ]; } -}; -SignStream.sign = jwsSign; + return result; +} -module.exports = SignStream; +module.exports = new Type('tag:yaml.org,2002:pairs', { + kind: 'sequence', + resolve: resolveYamlPairs, + construct: constructYamlPairs +}); /***/ }), -/***/ 65292: +/***/ 67283: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/*global module*/ -var Buffer = (__nccwpck_require__(14300).Buffer); +"use strict"; -module.exports = function toString(obj) { - if (typeof obj === 'string') - return obj; - if (typeof obj === 'number' || Buffer.isBuffer(obj)) - return obj.toString(); - return JSON.stringify(obj); -}; + +var Type = __nccwpck_require__(6073); + +module.exports = new Type('tag:yaml.org,2002:seq', { + kind: 'sequence', + construct: function (data) { return data !== null ? data : []; } +}); /***/ }), -/***/ 5522: +/***/ 79548: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/*global module*/ -var Buffer = (__nccwpck_require__(21867).Buffer); -var DataStream = __nccwpck_require__(61868); -var jwa = __nccwpck_require__(96010); -var Stream = __nccwpck_require__(12781); -var toString = __nccwpck_require__(65292); -var util = __nccwpck_require__(73837); -var JWS_REGEX = /^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/; +"use strict"; -function isObject(thing) { - return Object.prototype.toString.call(thing) === '[object Object]'; -} -function safeJsonParse(thing) { - if (isObject(thing)) - return thing; - try { return JSON.parse(thing); } - catch (e) { return undefined; } -} +var Type = __nccwpck_require__(6073); -function headerFromJWS(jwsSig) { - var encodedHeader = jwsSig.split('.', 1)[0]; - return safeJsonParse(Buffer.from(encodedHeader, 'base64').toString('binary')); -} +var _hasOwnProperty = Object.prototype.hasOwnProperty; -function securedInputFromJWS(jwsSig) { - return jwsSig.split('.', 2).join('.'); -} +function resolveYamlSet(data) { + if (data === null) return true; -function signatureFromJWS(jwsSig) { - return jwsSig.split('.')[2]; -} + var key, object = data; -function payloadFromJWS(jwsSig, encoding) { - encoding = encoding || 'utf8'; - var payload = jwsSig.split('.')[1]; - return Buffer.from(payload, 'base64').toString(encoding); -} + for (key in object) { + if (_hasOwnProperty.call(object, key)) { + if (object[key] !== null) return false; + } + } -function isValidJws(string) { - return JWS_REGEX.test(string) && !!headerFromJWS(string); + return true; } -function jwsVerify(jwsSig, algorithm, secretOrKey) { - if (!algorithm) { - var err = new Error("Missing algorithm parameter for jws.verify"); - err.code = "MISSING_ALGORITHM"; - throw err; - } - jwsSig = toString(jwsSig); - var signature = signatureFromJWS(jwsSig); - var securedInput = securedInputFromJWS(jwsSig); - var algo = jwa(algorithm); - return algo.verify(securedInput, signature, secretOrKey); +function constructYamlSet(data) { + return data !== null ? data : {}; } -function jwsDecode(jwsSig, opts) { - opts = opts || {}; - jwsSig = toString(jwsSig); - - if (!isValidJws(jwsSig)) - return null; - - var header = headerFromJWS(jwsSig); +module.exports = new Type('tag:yaml.org,2002:set', { + kind: 'mapping', + resolve: resolveYamlSet, + construct: constructYamlSet +}); - if (!header) - return null; - var payload = payloadFromJWS(jwsSig); - if (header.typ === 'JWT' || opts.json) - payload = JSON.parse(payload, opts.encoding); +/***/ }), - return { - header: header, - payload: payload, - signature: signatureFromJWS(jwsSig) - }; -} +/***/ 23619: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -function VerifyStream(opts) { - opts = opts || {}; - var secretOrKey = opts.secret||opts.publicKey||opts.key; - var secretStream = new DataStream(secretOrKey); - this.readable = true; - this.algorithm = opts.algorithm; - this.encoding = opts.encoding; - this.secret = this.publicKey = this.key = secretStream; - this.signature = new DataStream(opts.signature); - this.secret.once('close', function () { - if (!this.signature.writable && this.readable) - this.verify(); - }.bind(this)); +"use strict"; - this.signature.once('close', function () { - if (!this.secret.writable && this.readable) - this.verify(); - }.bind(this)); -} -util.inherits(VerifyStream, Stream); -VerifyStream.prototype.verify = function verify() { - try { - var valid = jwsVerify(this.signature.buffer, this.algorithm, this.key.buffer); - var obj = jwsDecode(this.signature.buffer, this.encoding); - this.emit('done', valid, obj); - this.emit('data', valid); - this.emit('end'); - this.readable = false; - return valid; - } catch (e) { - this.readable = false; - this.emit('error', e); - this.emit('close'); - } -}; -VerifyStream.decode = jwsDecode; -VerifyStream.isValid = isValidJws; -VerifyStream.verify = jwsVerify; +var Type = __nccwpck_require__(6073); -module.exports = VerifyStream; +module.exports = new Type('tag:yaml.org,2002:str', { + kind: 'scalar', + construct: function (data) { return data !== null ? data : ''; } +}); /***/ }), -/***/ 75978: +/***/ 99212: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const path = __nccwpck_require__(71017); -const fs = __nccwpck_require__(77758); -const stripBom = __nccwpck_require__(89383); -const parseJson = __nccwpck_require__(81680); -const pify = __nccwpck_require__(64810); -const parse = (data, filePath, options = {}) => { - data = stripBom(data); +var Type = __nccwpck_require__(6073); + +var YAML_DATE_REGEXP = new RegExp( + '^([0-9][0-9][0-9][0-9])' + // [1] year + '-([0-9][0-9])' + // [2] month + '-([0-9][0-9])$'); // [3] day + +var YAML_TIMESTAMP_REGEXP = new RegExp( + '^([0-9][0-9][0-9][0-9])' + // [1] year + '-([0-9][0-9]?)' + // [2] month + '-([0-9][0-9]?)' + // [3] day + '(?:[Tt]|[ \\t]+)' + // ... + '([0-9][0-9]?)' + // [4] hour + ':([0-9][0-9])' + // [5] minute + ':([0-9][0-9])' + // [6] second + '(?:\\.([0-9]*))?' + // [7] fraction + '(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour + '(?::([0-9][0-9]))?))?$'); // [11] tz_minute + +function resolveYamlTimestamp(data) { + if (data === null) return false; + if (YAML_DATE_REGEXP.exec(data) !== null) return true; + if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true; + return false; +} + +function constructYamlTimestamp(data) { + var match, year, month, day, hour, minute, second, fraction = 0, + delta = null, tz_hour, tz_minute, date; + + match = YAML_DATE_REGEXP.exec(data); + if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data); + + if (match === null) throw new Error('Date resolve error'); + + // match: [1] year [2] month [3] day + + year = +(match[1]); + month = +(match[2]) - 1; // JS month starts with 0 + day = +(match[3]); - if (typeof options.beforeParse === 'function') { - data = options.beforeParse(data); - } + if (!match[4]) { // no hour + return new Date(Date.UTC(year, month, day)); + } - return parseJson(data, options.reviver, path.relative(process.cwd(), filePath)); -}; + // match: [4] hour [5] minute [6] second [7] fraction -const loadJsonFile = (filePath, options) => pify(fs.readFile)(filePath, 'utf8').then(data => parse(data, filePath, options)); + hour = +(match[4]); + minute = +(match[5]); + second = +(match[6]); -module.exports = loadJsonFile; -// TODO: Remove this for the next major release -module.exports["default"] = loadJsonFile; -module.exports.sync = (filePath, options) => parse(fs.readFileSync(filePath, 'utf8'), filePath, options); + if (match[7]) { + fraction = match[7].slice(0, 3); + while (fraction.length < 3) { // milli-seconds + fraction += '0'; + } + fraction = +fraction; + } + // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute -/***/ }), + if (match[9]) { + tz_hour = +(match[10]); + tz_minute = +(match[11] || 0); + delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds + if (match[9] === '-') delta = -delta; + } -/***/ 81680: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction)); -"use strict"; + if (delta) date.setTime(date.getTime() - delta); -const errorEx = __nccwpck_require__(23505); -const fallback = __nccwpck_require__(55586); + return date; +} -const JSONError = errorEx('JSONError', { - fileName: errorEx.append('in %s') +function representYamlTimestamp(object /*, style*/) { + return object.toISOString(); +} + +module.exports = new Type('tag:yaml.org,2002:timestamp', { + kind: 'scalar', + resolve: resolveYamlTimestamp, + construct: constructYamlTimestamp, + instanceOf: Date, + represent: representYamlTimestamp }); -module.exports = (input, reviver, filename) => { - if (typeof reviver === 'string') { - filename = reviver; - reviver = null; - } - try { - try { - return JSON.parse(input, reviver); - } catch (err) { - fallback(input, reviver); +/***/ }), - throw err; - } - } catch (err) { - err.message = err.message.replace(/\n/g, ''); +/***/ 55586: +/***/ ((module) => { - const jsonErr = new JSONError(err); - if (filename) { - jsonErr.fileName = filename; - } +"use strict"; - throw jsonErr; - } -}; + +module.exports = parseJson +function parseJson (txt, reviver, context) { + context = context || 20 + try { + return JSON.parse(txt, reviver) + } catch (e) { + if (typeof txt !== 'string') { + const isEmptyArray = Array.isArray(txt) && txt.length === 0 + const errorMessage = 'Cannot parse ' + + (isEmptyArray ? 'an empty array' : String(txt)) + throw new TypeError(errorMessage) + } + const syntaxErr = e.message.match(/^Unexpected token.*position\s+(\d+)/i) + const errIdx = syntaxErr + ? +syntaxErr[1] + : e.message.match(/^Unexpected end of JSON.*/i) + ? txt.length - 1 + : null + if (errIdx != null) { + const start = errIdx <= context + ? 0 + : errIdx - context + const end = errIdx + context >= txt.length + ? txt.length + : errIdx + context + e.message += ` while parsing near '${ + start === 0 ? '' : '...' + }${txt.slice(start, end)}${ + end === txt.length ? '' : '...' + }'` + } else { + e.message += ` while parsing '${txt.slice(0, context * 2)}'` + } + throw e + } +} /***/ }), -/***/ 89383: -/***/ ((module) => { +/***/ 53359: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +var jws = __nccwpck_require__(4636); -module.exports = x => { - if (typeof x !== 'string') { - throw new TypeError('Expected a string, got ' + typeof x); - } +module.exports = function (jwt, options) { + options = options || {}; + var decoded = jws.decode(jwt, options); + if (!decoded) { return null; } + var payload = decoded.payload; - // Catches EFBBBF (UTF-8 BOM) because the buffer-to-string - // conversion translates it to FEFF (UTF-16 BOM) - if (x.charCodeAt(0) === 0xFEFF) { - return x.slice(1); - } + //try parse the payload + if(typeof payload === 'string') { + try { + var obj = JSON.parse(payload); + if(obj !== null && typeof obj === 'object') { + payload = obj; + } + } catch (e) { } + } - return x; + //return header if `complete` option is enabled. header includes claims + //such as `kid` and `alg` used to select the key within a JWKS needed to + //verify the signature + if (options.complete === true) { + return { + header: decoded.header, + payload: payload, + signature: decoded.signature + }; + } + return payload; }; /***/ }), -/***/ 11289: -/***/ ((module) => { - -/** - * lodash (Custom Build) - * Build: `lodash modularize exports="npm" -o ./` - * Copyright jQuery Foundation and other contributors - * Released under MIT license - * Based on Underscore.js 1.8.3 - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - */ - -/** Used as references for various `Number` constants. */ -var MAX_SAFE_INTEGER = 9007199254740991; +/***/ 77486: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** `Object#toString` result references. */ -var argsTag = '[object Arguments]', - funcTag = '[object Function]', - genTag = '[object GeneratorFunction]'; +module.exports = { + decode: __nccwpck_require__(53359), + verify: __nccwpck_require__(12327), + sign: __nccwpck_require__(82022), + JsonWebTokenError: __nccwpck_require__(405), + NotBeforeError: __nccwpck_require__(4383), + TokenExpiredError: __nccwpck_require__(46637), +}; -/** Used to detect unsigned integer values. */ -var reIsUint = /^(?:0|[1-9]\d*)$/; -/** - * A faster alternative to `Function#apply`, this function invokes `func` - * with the `this` binding of `thisArg` and the arguments of `args`. - * - * @private - * @param {Function} func The function to invoke. - * @param {*} thisArg The `this` binding of `func`. - * @param {Array} args The arguments to invoke `func` with. - * @returns {*} Returns the result of `func`. - */ -function apply(func, thisArg, args) { - switch (args.length) { - case 0: return func.call(thisArg); - case 1: return func.call(thisArg, args[0]); - case 2: return func.call(thisArg, args[0], args[1]); - case 3: return func.call(thisArg, args[0], args[1], args[2]); - } - return func.apply(thisArg, args); -} +/***/ }), -/** - * The base implementation of `_.times` without support for iteratee shorthands - * or max array length checks. - * - * @private - * @param {number} n The number of times to invoke `iteratee`. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the array of results. - */ -function baseTimes(n, iteratee) { - var index = -1, - result = Array(n); +/***/ 405: +/***/ ((module) => { - while (++index < n) { - result[index] = iteratee(index); +var JsonWebTokenError = function (message, error) { + Error.call(this, message); + if(Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); } - return result; -} + this.name = 'JsonWebTokenError'; + this.message = message; + if (error) this.inner = error; +}; -/** Used for built-in method references. */ -var objectProto = Object.prototype; +JsonWebTokenError.prototype = Object.create(Error.prototype); +JsonWebTokenError.prototype.constructor = JsonWebTokenError; -/** Used to check objects for own properties. */ -var hasOwnProperty = objectProto.hasOwnProperty; +module.exports = JsonWebTokenError; -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var objectToString = objectProto.toString; -/** Built-in value references. */ -var propertyIsEnumerable = objectProto.propertyIsEnumerable; +/***/ }), -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeMax = Math.max; +/***/ 4383: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * Creates an array of the enumerable property names of the array-like `value`. - * - * @private - * @param {*} value The value to query. - * @param {boolean} inherited Specify returning inherited property names. - * @returns {Array} Returns the array of property names. - */ -function arrayLikeKeys(value, inherited) { - // Safari 8.1 makes `arguments.callee` enumerable in strict mode. - // Safari 9 makes `arguments.length` enumerable in strict mode. - var result = (isArray(value) || isArguments(value)) - ? baseTimes(value.length, String) - : []; +var JsonWebTokenError = __nccwpck_require__(405); - var length = result.length, - skipIndexes = !!length; +var NotBeforeError = function (message, date) { + JsonWebTokenError.call(this, message); + this.name = 'NotBeforeError'; + this.date = date; +}; - for (var key in value) { - if ((inherited || hasOwnProperty.call(value, key)) && - !(skipIndexes && (key == 'length' || isIndex(key, length)))) { - result.push(key); - } - } - return result; -} +NotBeforeError.prototype = Object.create(JsonWebTokenError.prototype); -/** - * Used by `_.defaults` to customize its `_.assignIn` use. - * - * @private - * @param {*} objValue The destination value. - * @param {*} srcValue The source value. - * @param {string} key The key of the property to assign. - * @param {Object} object The parent object of `objValue`. - * @returns {*} Returns the value to assign. - */ -function assignInDefaults(objValue, srcValue, key, object) { - if (objValue === undefined || - (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) { - return srcValue; - } - return objValue; -} +NotBeforeError.prototype.constructor = NotBeforeError; -/** - * Assigns `value` to `key` of `object` if the existing value is not equivalent - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ -function assignValue(object, key, value) { - var objValue = object[key]; - if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || - (value === undefined && !(key in object))) { - object[key] = value; - } -} +module.exports = NotBeforeError; -/** - * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ -function baseKeysIn(object) { - if (!isObject(object)) { - return nativeKeysIn(object); - } - var isProto = isPrototype(object), - result = []; +/***/ }), - for (var key in object) { - if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { - result.push(key); - } - } - return result; -} +/***/ 46637: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * The base implementation of `_.rest` which doesn't validate or coerce arguments. - * - * @private - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @returns {Function} Returns the new function. - */ -function baseRest(func, start) { - start = nativeMax(start === undefined ? (func.length - 1) : start, 0); - return function() { - var args = arguments, - index = -1, - length = nativeMax(args.length - start, 0), - array = Array(length); +var JsonWebTokenError = __nccwpck_require__(405); - while (++index < length) { - array[index] = args[start + index]; - } - index = -1; - var otherArgs = Array(start + 1); - while (++index < start) { - otherArgs[index] = args[index]; - } - otherArgs[start] = array; - return apply(func, this, otherArgs); - }; -} +var TokenExpiredError = function (message, expiredAt) { + JsonWebTokenError.call(this, message); + this.name = 'TokenExpiredError'; + this.expiredAt = expiredAt; +}; -/** - * Copies properties of `source` to `object`. - * - * @private - * @param {Object} source The object to copy properties from. - * @param {Array} props The property identifiers to copy. - * @param {Object} [object={}] The object to copy properties to. - * @param {Function} [customizer] The function to customize copied values. - * @returns {Object} Returns `object`. - */ -function copyObject(source, props, object, customizer) { - object || (object = {}); +TokenExpiredError.prototype = Object.create(JsonWebTokenError.prototype); - var index = -1, - length = props.length; +TokenExpiredError.prototype.constructor = TokenExpiredError; - while (++index < length) { - var key = props[index]; +module.exports = TokenExpiredError; - var newValue = customizer - ? customizer(object[key], source[key], key, object, source) - : undefined; +/***/ }), - assignValue(object, key, newValue === undefined ? source[key] : newValue); - } - return object; -} +/***/ 59085: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * Creates a function like `_.assign`. - * - * @private - * @param {Function} assigner The function to assign values. - * @returns {Function} Returns the new assigner function. - */ -function createAssigner(assigner) { - return baseRest(function(object, sources) { - var index = -1, - length = sources.length, - customizer = length > 1 ? sources[length - 1] : undefined, - guard = length > 2 ? sources[2] : undefined; +var semver = __nccwpck_require__(27174); - customizer = (assigner.length > 3 && typeof customizer == 'function') - ? (length--, customizer) - : undefined; +module.exports = semver.satisfies(process.version, '^6.12.0 || >=8.0.0'); - if (guard && isIterateeCall(sources[0], sources[1], guard)) { - customizer = length < 3 ? undefined : customizer; - length = 1; - } - object = Object(object); - while (++index < length) { - var source = sources[index]; - if (source) { - assigner(object, source, index, customizer); - } - } - return object; - }); -} -/** - * Checks if `value` is a valid array-like index. - * - * @private - * @param {*} value The value to check. - * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. - * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. - */ -function isIndex(value, length) { - length = length == null ? MAX_SAFE_INTEGER : length; - return !!length && - (typeof value == 'number' || reIsUint.test(value)) && - (value > -1 && value % 1 == 0 && value < length); -} +/***/ }), -/** - * Checks if the given arguments are from an iteratee call. - * - * @private - * @param {*} value The potential iteratee value argument. - * @param {*} index The potential iteratee index or key argument. - * @param {*} object The potential iteratee object argument. - * @returns {boolean} Returns `true` if the arguments are from an iteratee call, - * else `false`. - */ -function isIterateeCall(value, index, object) { - if (!isObject(object)) { - return false; - } - var type = typeof index; - if (type == 'number' - ? (isArrayLike(object) && isIndex(index, object.length)) - : (type == 'string' && index in object) - ) { - return eq(object[index], value); - } - return false; -} +/***/ 46098: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * Checks if `value` is likely a prototype object. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. - */ -function isPrototype(value) { - var Ctor = value && value.constructor, - proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; +var ms = __nccwpck_require__(84098); - return value === proto; -} +module.exports = function (time, iat) { + var timestamp = iat || Math.floor(Date.now() / 1000); -/** - * This function is like - * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) - * except that it includes inherited enumerable properties. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ -function nativeKeysIn(object) { - var result = []; - if (object != null) { - for (var key in Object(object)) { - result.push(key); + if (typeof time === 'string') { + var milliseconds = ms(time); + if (typeof milliseconds === 'undefined') { + return; } + return Math.floor(timestamp + milliseconds / 1000); + } else if (typeof time === 'number') { + return timestamp + time; + } else { + return; } - return result; -} -/** - * Performs a - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * comparison between two values to determine if they are equivalent. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * var object = { 'a': 1 }; - * var other = { 'a': 1 }; - * - * _.eq(object, object); - * // => true - * - * _.eq(object, other); - * // => false - * - * _.eq('a', 'a'); - * // => true - * - * _.eq('a', Object('a')); - * // => false - * - * _.eq(NaN, NaN); - * // => true - */ -function eq(value, other) { - return value === other || (value !== value && other !== other); -} +}; -/** - * Checks if `value` is likely an `arguments` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - * else `false`. - * @example - * - * _.isArguments(function() { return arguments; }()); - * // => true - * - * _.isArguments([1, 2, 3]); - * // => false - */ -function isArguments(value) { - // Safari 8.1 makes `arguments.callee` enumerable in strict mode. - return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && - (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); -} +/***/ }), + +/***/ 84098: +/***/ ((module) => { /** - * Checks if `value` is classified as an `Array` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array, else `false`. - * @example - * - * _.isArray([1, 2, 3]); - * // => true - * - * _.isArray(document.body.children); - * // => false - * - * _.isArray('abc'); - * // => false - * - * _.isArray(_.noop); - * // => false + * Helpers. */ -var isArray = Array.isArray; + +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var w = d * 7; +var y = d * 365.25; /** - * Checks if `value` is array-like. A value is considered array-like if it's - * not a function and has a `value.length` that's an integer greater than or - * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is array-like, else `false`. - * @example - * - * _.isArrayLike([1, 2, 3]); - * // => true + * Parse or format the given `val`. * - * _.isArrayLike(document.body.children); - * // => true + * Options: * - * _.isArrayLike('abc'); - * // => true + * - `long` verbose formatting [false] * - * _.isArrayLike(_.noop); - * // => false + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public */ -function isArrayLike(value) { - return value != null && isLength(value.length) && !isFunction(value); -} + +module.exports = function (val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isFinite(val)) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); +}; /** - * This method is like `_.isArrayLike` except that it also checks if `value` - * is an object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array-like object, - * else `false`. - * @example - * - * _.isArrayLikeObject([1, 2, 3]); - * // => true - * - * _.isArrayLikeObject(document.body.children); - * // => true - * - * _.isArrayLikeObject('abc'); - * // => false + * Parse the given `str` and return milliseconds. * - * _.isArrayLikeObject(_.noop); - * // => false + * @param {String} str + * @return {Number} + * @api private */ -function isArrayLikeObject(value) { - return isObjectLike(value) && isArrayLike(value); + +function parse(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'weeks': + case 'week': + case 'w': + return n * w; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; + } } /** - * Checks if `value` is classified as a `Function` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a function, else `false`. - * @example - * - * _.isFunction(_); - * // => true + * Short format for `ms`. * - * _.isFunction(/abc/); - * // => false + * @param {Number} ms + * @return {String} + * @api private */ -function isFunction(value) { - // The use of `Object#toString` avoids issues with the `typeof` operator - // in Safari 8-9 which returns 'object' for typed array and other constructors. - var tag = isObject(value) ? objectToString.call(value) : ''; - return tag == funcTag || tag == genTag; + +function fmtShort(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return Math.round(ms / d) + 'd'; + } + if (msAbs >= h) { + return Math.round(ms / h) + 'h'; + } + if (msAbs >= m) { + return Math.round(ms / m) + 'm'; + } + if (msAbs >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; } /** - * Checks if `value` is a valid array-like length. - * - * **Note:** This method is loosely based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. - * @example - * - * _.isLength(3); - * // => true - * - * _.isLength(Number.MIN_VALUE); - * // => false - * - * _.isLength(Infinity); - * // => false + * Long format for `ms`. * - * _.isLength('3'); - * // => false + * @param {Number} ms + * @return {String} + * @api private */ -function isLength(value) { - return typeof value == 'number' && - value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; + +function fmtLong(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return plural(ms, msAbs, d, 'day'); + } + if (msAbs >= h) { + return plural(ms, msAbs, h, 'hour'); + } + if (msAbs >= m) { + return plural(ms, msAbs, m, 'minute'); + } + if (msAbs >= s) { + return plural(ms, msAbs, s, 'second'); + } + return ms + ' ms'; } /** - * Checks if `value` is the - * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) - * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false + * Pluralization helper. */ -function isObject(value) { - var type = typeof value; - return !!value && (type == 'object' || type == 'function'); + +function plural(ms, msAbs, n, name) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); } -/** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ -function isObjectLike(value) { - return !!value && typeof value == 'object'; + +/***/ }), + +/***/ 27174: +/***/ ((module, exports) => { + +exports = module.exports = SemVer + +var debug +/* istanbul ignore next */ +if (typeof process === 'object' && + process.env && + process.env.NODE_DEBUG && + /\bsemver\b/i.test(process.env.NODE_DEBUG)) { + debug = function () { + var args = Array.prototype.slice.call(arguments, 0) + args.unshift('SEMVER') + console.log.apply(console, args) + } +} else { + debug = function () {} } -/** - * This method is like `_.assignIn` except that it accepts `customizer` - * which is invoked to produce the assigned values. If `customizer` returns - * `undefined`, assignment is handled by the method instead. The `customizer` - * is invoked with five arguments: (objValue, srcValue, key, object, source). - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @alias extendWith - * @category Object - * @param {Object} object The destination object. - * @param {...Object} sources The source objects. - * @param {Function} [customizer] The function to customize assigned values. - * @returns {Object} Returns `object`. - * @see _.assignWith - * @example - * - * function customizer(objValue, srcValue) { - * return _.isUndefined(objValue) ? srcValue : objValue; - * } - * - * var defaults = _.partialRight(_.assignInWith, customizer); - * - * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); - * // => { 'a': 1, 'b': 2 } - */ -var assignInWith = createAssigner(function(object, source, srcIndex, customizer) { - copyObject(source, keysIn(source), object, customizer); -}); +// Note: this is the semver.org version of the spec that it implements +// Not necessarily the package version of this code. +exports.SEMVER_SPEC_VERSION = '2.0.0' -/** - * Assigns own and inherited enumerable string keyed properties of source - * objects to the destination object for all destination properties that - * resolve to `undefined`. Source objects are applied from left to right. - * Once a property is set, additional values of the same property are ignored. - * - * **Note:** This method mutates `object`. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. - * @see _.defaultsDeep - * @example - * - * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); - * // => { 'a': 1, 'b': 2 } - */ -var defaults = baseRest(function(args) { - args.push(undefined, assignInDefaults); - return apply(assignInWith, undefined, args); -}); +var MAX_LENGTH = 256 +var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || + /* istanbul ignore next */ 9007199254740991 + +// Max safe segment length for coercion. +var MAX_SAFE_COMPONENT_LENGTH = 16 + +// The actual regexps go on exports.re +var re = exports.re = [] +var src = exports.src = [] +var R = 0 + +// The following Regular Expressions can be used for tokenizing, +// validating, and parsing SemVer version strings. + +// ## Numeric Identifier +// A single `0`, or a non-zero digit followed by zero or more digits. + +var NUMERICIDENTIFIER = R++ +src[NUMERICIDENTIFIER] = '0|[1-9]\\d*' +var NUMERICIDENTIFIERLOOSE = R++ +src[NUMERICIDENTIFIERLOOSE] = '[0-9]+' + +// ## Non-numeric Identifier +// Zero or more digits, followed by a letter or hyphen, and then zero or +// more letters, digits, or hyphens. + +var NONNUMERICIDENTIFIER = R++ +src[NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*' + +// ## Main Version +// Three dot-separated numeric identifiers. + +var MAINVERSION = R++ +src[MAINVERSION] = '(' + src[NUMERICIDENTIFIER] + ')\\.' + + '(' + src[NUMERICIDENTIFIER] + ')\\.' + + '(' + src[NUMERICIDENTIFIER] + ')' + +var MAINVERSIONLOOSE = R++ +src[MAINVERSIONLOOSE] = '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + + '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + + '(' + src[NUMERICIDENTIFIERLOOSE] + ')' + +// ## Pre-release Version Identifier +// A numeric identifier, or a non-numeric identifier. + +var PRERELEASEIDENTIFIER = R++ +src[PRERELEASEIDENTIFIER] = '(?:' + src[NUMERICIDENTIFIER] + + '|' + src[NONNUMERICIDENTIFIER] + ')' + +var PRERELEASEIDENTIFIERLOOSE = R++ +src[PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[NUMERICIDENTIFIERLOOSE] + + '|' + src[NONNUMERICIDENTIFIER] + ')' + +// ## Pre-release Version +// Hyphen, followed by one or more dot-separated pre-release version +// identifiers. + +var PRERELEASE = R++ +src[PRERELEASE] = '(?:-(' + src[PRERELEASEIDENTIFIER] + + '(?:\\.' + src[PRERELEASEIDENTIFIER] + ')*))' -/** - * Creates an array of the own and inherited enumerable property names of `object`. - * - * **Note:** Non-object values are coerced to objects. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.keysIn(new Foo); - * // => ['a', 'b', 'c'] (iteration order is not guaranteed) - */ -function keysIn(object) { - return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); -} +var PRERELEASELOOSE = R++ +src[PRERELEASELOOSE] = '(?:-?(' + src[PRERELEASEIDENTIFIERLOOSE] + + '(?:\\.' + src[PRERELEASEIDENTIFIERLOOSE] + ')*))' -module.exports = defaults; +// ## Build Metadata Identifier +// Any combination of digits, letters, or hyphens. +var BUILDIDENTIFIER = R++ +src[BUILDIDENTIFIER] = '[0-9A-Za-z-]+' -/***/ }), +// ## Build Metadata +// Plus sign, followed by one or more period-separated build metadata +// identifiers. -/***/ 48919: -/***/ ((module) => { +var BUILD = R++ +src[BUILD] = '(?:\\+(' + src[BUILDIDENTIFIER] + + '(?:\\.' + src[BUILDIDENTIFIER] + ')*))' -/** - * lodash (Custom Build) - * Build: `lodash modularize exports="npm" -o ./` - * Copyright jQuery Foundation and other contributors - * Released under MIT license - * Based on Underscore.js 1.8.3 - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - */ +// ## Full Version String +// A main version, followed optionally by a pre-release version and +// build metadata. -/** Used as references for various `Number` constants. */ -var MAX_SAFE_INTEGER = 9007199254740991; +// Note that the only major, minor, patch, and pre-release sections of +// the version string are capturing groups. The build metadata is not a +// capturing group, because it should not ever be used in version +// comparison. -/** `Object#toString` result references. */ -var argsTag = '[object Arguments]', - funcTag = '[object Function]', - genTag = '[object GeneratorFunction]'; +var FULL = R++ +var FULLPLAIN = 'v?' + src[MAINVERSION] + + src[PRERELEASE] + '?' + + src[BUILD] + '?' -/** Detect free variable `global` from Node.js. */ -var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; +src[FULL] = '^' + FULLPLAIN + '$' -/** Detect free variable `self`. */ -var freeSelf = typeof self == 'object' && self && self.Object === Object && self; +// like full, but allows v1.2.3 and =1.2.3, which people do sometimes. +// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty +// common in the npm registry. +var LOOSEPLAIN = '[v=\\s]*' + src[MAINVERSIONLOOSE] + + src[PRERELEASELOOSE] + '?' + + src[BUILD] + '?' -/** Used as a reference to the global object. */ -var root = freeGlobal || freeSelf || Function('return this')(); +var LOOSE = R++ +src[LOOSE] = '^' + LOOSEPLAIN + '$' -/** - * Appends the elements of `values` to `array`. - * - * @private - * @param {Array} array The array to modify. - * @param {Array} values The values to append. - * @returns {Array} Returns `array`. - */ -function arrayPush(array, values) { - var index = -1, - length = values.length, - offset = array.length; +var GTLT = R++ +src[GTLT] = '((?:<|>)?=?)' - while (++index < length) { - array[offset + index] = values[index]; - } - return array; -} +// Something like "2.*" or "1.2.x". +// Note that "x.x" is a valid xRange identifer, meaning "any version" +// Only the first item is strictly required. +var XRANGEIDENTIFIERLOOSE = R++ +src[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + '|x|X|\\*' +var XRANGEIDENTIFIER = R++ +src[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + '|x|X|\\*' -/** Used for built-in method references. */ -var objectProto = Object.prototype; +var XRANGEPLAIN = R++ +src[XRANGEPLAIN] = '[v=\\s]*(' + src[XRANGEIDENTIFIER] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + + '(?:' + src[PRERELEASE] + ')?' + + src[BUILD] + '?' + + ')?)?' -/** Used to check objects for own properties. */ -var hasOwnProperty = objectProto.hasOwnProperty; +var XRANGEPLAINLOOSE = R++ +src[XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[XRANGEIDENTIFIERLOOSE] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + + '(?:' + src[PRERELEASELOOSE] + ')?' + + src[BUILD] + '?' + + ')?)?' -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var objectToString = objectProto.toString; +var XRANGE = R++ +src[XRANGE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAIN] + '$' +var XRANGELOOSE = R++ +src[XRANGELOOSE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAINLOOSE] + '$' -/** Built-in value references. */ -var Symbol = root.Symbol, - propertyIsEnumerable = objectProto.propertyIsEnumerable, - spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined; +// Coercion. +// Extract anything that could conceivably be a part of a valid semver +var COERCE = R++ +src[COERCE] = '(?:^|[^\\d])' + + '(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' + + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + + '(?:$|[^\\d])' -/** - * The base implementation of `_.flatten` with support for restricting flattening. - * - * @private - * @param {Array} array The array to flatten. - * @param {number} depth The maximum recursion depth. - * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. - * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. - * @param {Array} [result=[]] The initial result value. - * @returns {Array} Returns the new flattened array. - */ -function baseFlatten(array, depth, predicate, isStrict, result) { - var index = -1, - length = array.length; +// Tilde ranges. +// Meaning is "reasonably at or greater than" +var LONETILDE = R++ +src[LONETILDE] = '(?:~>?)' - predicate || (predicate = isFlattenable); - result || (result = []); +var TILDETRIM = R++ +src[TILDETRIM] = '(\\s*)' + src[LONETILDE] + '\\s+' +re[TILDETRIM] = new RegExp(src[TILDETRIM], 'g') +var tildeTrimReplace = '$1~' - while (++index < length) { - var value = array[index]; - if (depth > 0 && predicate(value)) { - if (depth > 1) { - // Recursively flatten arrays (susceptible to call stack limits). - baseFlatten(value, depth - 1, predicate, isStrict, result); - } else { - arrayPush(result, value); - } - } else if (!isStrict) { - result[result.length] = value; - } - } - return result; -} +var TILDE = R++ +src[TILDE] = '^' + src[LONETILDE] + src[XRANGEPLAIN] + '$' +var TILDELOOSE = R++ +src[TILDELOOSE] = '^' + src[LONETILDE] + src[XRANGEPLAINLOOSE] + '$' -/** - * Checks if `value` is a flattenable `arguments` object or array. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. - */ -function isFlattenable(value) { - return isArray(value) || isArguments(value) || - !!(spreadableSymbol && value && value[spreadableSymbol]); -} +// Caret ranges. +// Meaning is "at least and backwards compatible with" +var LONECARET = R++ +src[LONECARET] = '(?:\\^)' -/** - * Flattens `array` a single level deep. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to flatten. - * @returns {Array} Returns the new flattened array. - * @example - * - * _.flatten([1, [2, [3, [4]], 5]]); - * // => [1, 2, [3, [4]], 5] - */ -function flatten(array) { - var length = array ? array.length : 0; - return length ? baseFlatten(array, 1) : []; -} +var CARETTRIM = R++ +src[CARETTRIM] = '(\\s*)' + src[LONECARET] + '\\s+' +re[CARETTRIM] = new RegExp(src[CARETTRIM], 'g') +var caretTrimReplace = '$1^' -/** - * Checks if `value` is likely an `arguments` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - * else `false`. - * @example - * - * _.isArguments(function() { return arguments; }()); - * // => true - * - * _.isArguments([1, 2, 3]); - * // => false - */ -function isArguments(value) { - // Safari 8.1 makes `arguments.callee` enumerable in strict mode. - return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && - (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); -} +var CARET = R++ +src[CARET] = '^' + src[LONECARET] + src[XRANGEPLAIN] + '$' +var CARETLOOSE = R++ +src[CARETLOOSE] = '^' + src[LONECARET] + src[XRANGEPLAINLOOSE] + '$' -/** - * Checks if `value` is classified as an `Array` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array, else `false`. - * @example - * - * _.isArray([1, 2, 3]); - * // => true - * - * _.isArray(document.body.children); - * // => false - * - * _.isArray('abc'); - * // => false - * - * _.isArray(_.noop); - * // => false - */ -var isArray = Array.isArray; +// A simple gt/lt/eq thing, or just "" to indicate "any version" +var COMPARATORLOOSE = R++ +src[COMPARATORLOOSE] = '^' + src[GTLT] + '\\s*(' + LOOSEPLAIN + ')$|^$' +var COMPARATOR = R++ +src[COMPARATOR] = '^' + src[GTLT] + '\\s*(' + FULLPLAIN + ')$|^$' -/** - * Checks if `value` is array-like. A value is considered array-like if it's - * not a function and has a `value.length` that's an integer greater than or - * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is array-like, else `false`. - * @example - * - * _.isArrayLike([1, 2, 3]); - * // => true - * - * _.isArrayLike(document.body.children); - * // => true - * - * _.isArrayLike('abc'); - * // => true - * - * _.isArrayLike(_.noop); - * // => false - */ -function isArrayLike(value) { - return value != null && isLength(value.length) && !isFunction(value); -} +// An expression to strip any whitespace between the gtlt and the thing +// it modifies, so that `> 1.2.3` ==> `>1.2.3` +var COMPARATORTRIM = R++ +src[COMPARATORTRIM] = '(\\s*)' + src[GTLT] + + '\\s*(' + LOOSEPLAIN + '|' + src[XRANGEPLAIN] + ')' -/** - * This method is like `_.isArrayLike` except that it also checks if `value` - * is an object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array-like object, - * else `false`. - * @example - * - * _.isArrayLikeObject([1, 2, 3]); - * // => true - * - * _.isArrayLikeObject(document.body.children); - * // => true - * - * _.isArrayLikeObject('abc'); - * // => false - * - * _.isArrayLikeObject(_.noop); - * // => false - */ -function isArrayLikeObject(value) { - return isObjectLike(value) && isArrayLike(value); -} +// this one has to use the /g flag +re[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], 'g') +var comparatorTrimReplace = '$1$2$3' -/** - * Checks if `value` is classified as a `Function` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a function, else `false`. - * @example - * - * _.isFunction(_); - * // => true - * - * _.isFunction(/abc/); - * // => false - */ -function isFunction(value) { - // The use of `Object#toString` avoids issues with the `typeof` operator - // in Safari 8-9 which returns 'object' for typed array and other constructors. - var tag = isObject(value) ? objectToString.call(value) : ''; - return tag == funcTag || tag == genTag; -} +// Something like `1.2.3 - 1.2.4` +// Note that these all use the loose form, because they'll be +// checked against either the strict or loose comparator form +// later. +var HYPHENRANGE = R++ +src[HYPHENRANGE] = '^\\s*(' + src[XRANGEPLAIN] + ')' + + '\\s+-\\s+' + + '(' + src[XRANGEPLAIN] + ')' + + '\\s*$' -/** - * Checks if `value` is a valid array-like length. - * - * **Note:** This method is loosely based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. - * @example - * - * _.isLength(3); - * // => true - * - * _.isLength(Number.MIN_VALUE); - * // => false - * - * _.isLength(Infinity); - * // => false - * - * _.isLength('3'); - * // => false - */ -function isLength(value) { - return typeof value == 'number' && - value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; -} +var HYPHENRANGELOOSE = R++ +src[HYPHENRANGELOOSE] = '^\\s*(' + src[XRANGEPLAINLOOSE] + ')' + + '\\s+-\\s+' + + '(' + src[XRANGEPLAINLOOSE] + ')' + + '\\s*$' -/** - * Checks if `value` is the - * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) - * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false - */ -function isObject(value) { - var type = typeof value; - return !!value && (type == 'object' || type == 'function'); +// Star ranges basically just allow anything at all. +var STAR = R++ +src[STAR] = '(<|>)?=?\\s*\\*' + +// Compile to actual regexp objects. +// All are flag-free, unless they were created above with a flag. +for (var i = 0; i < R; i++) { + debug(i, src[i]) + if (!re[i]) { + re[i] = new RegExp(src[i]) + } } -/** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ -function isObjectLike(value) { - return !!value && typeof value == 'object'; +exports.parse = parse +function parse (version, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + + if (version instanceof SemVer) { + return version + } + + if (typeof version !== 'string') { + return null + } + + if (version.length > MAX_LENGTH) { + return null + } + + var r = options.loose ? re[LOOSE] : re[FULL] + if (!r.test(version)) { + return null + } + + try { + return new SemVer(version, options) + } catch (er) { + return null + } } -module.exports = flatten; +exports.valid = valid +function valid (version, options) { + var v = parse(version, options) + return v ? v.version : null +} +exports.clean = clean +function clean (version, options) { + var s = parse(version.trim().replace(/^[=v]+/, ''), options) + return s ? s.version : null +} -/***/ }), +exports.SemVer = SemVer -/***/ 17931: -/***/ ((module) => { +function SemVer (version, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + if (version instanceof SemVer) { + if (version.loose === options.loose) { + return version + } else { + version = version.version + } + } else if (typeof version !== 'string') { + throw new TypeError('Invalid Version: ' + version) + } -/** - * lodash (Custom Build) - * Build: `lodash modularize exports="npm" -o ./` - * Copyright jQuery Foundation and other contributors - * Released under MIT license - * Based on Underscore.js 1.8.3 - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - */ + if (version.length > MAX_LENGTH) { + throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters') + } -/** Used as references for various `Number` constants. */ -var INFINITY = 1 / 0, - MAX_SAFE_INTEGER = 9007199254740991, - MAX_INTEGER = 1.7976931348623157e+308, - NAN = 0 / 0; + if (!(this instanceof SemVer)) { + return new SemVer(version, options) + } -/** `Object#toString` result references. */ -var argsTag = '[object Arguments]', - funcTag = '[object Function]', - genTag = '[object GeneratorFunction]', - stringTag = '[object String]', - symbolTag = '[object Symbol]'; + debug('SemVer', version, options) + this.options = options + this.loose = !!options.loose -/** Used to match leading and trailing whitespace. */ -var reTrim = /^\s+|\s+$/g; + var m = version.trim().match(options.loose ? re[LOOSE] : re[FULL]) -/** Used to detect bad signed hexadecimal string values. */ -var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; + if (!m) { + throw new TypeError('Invalid Version: ' + version) + } -/** Used to detect binary string values. */ -var reIsBinary = /^0b[01]+$/i; + this.raw = version -/** Used to detect octal string values. */ -var reIsOctal = /^0o[0-7]+$/i; + // these are actually numbers + this.major = +m[1] + this.minor = +m[2] + this.patch = +m[3] -/** Used to detect unsigned integer values. */ -var reIsUint = /^(?:0|[1-9]\d*)$/; + if (this.major > MAX_SAFE_INTEGER || this.major < 0) { + throw new TypeError('Invalid major version') + } -/** Built-in method references without a dependency on `root`. */ -var freeParseInt = parseInt; + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { + throw new TypeError('Invalid minor version') + } -/** - * A specialized version of `_.map` for arrays without support for iteratee - * shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the new mapped array. - */ -function arrayMap(array, iteratee) { - var index = -1, - length = array ? array.length : 0, - result = Array(length); + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { + throw new TypeError('Invalid patch version') + } - while (++index < length) { - result[index] = iteratee(array[index], index, array); + // numberify any prerelease numeric ids + if (!m[4]) { + this.prerelease = [] + } else { + this.prerelease = m[4].split('.').map(function (id) { + if (/^[0-9]+$/.test(id)) { + var num = +id + if (num >= 0 && num < MAX_SAFE_INTEGER) { + return num + } + } + return id + }) } - return result; + + this.build = m[5] ? m[5].split('.') : [] + this.format() } -/** - * The base implementation of `_.findIndex` and `_.findLastIndex` without - * support for iteratee shorthands. - * - * @private - * @param {Array} array The array to inspect. - * @param {Function} predicate The function invoked per iteration. - * @param {number} fromIndex The index to search from. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {number} Returns the index of the matched value, else `-1`. - */ -function baseFindIndex(array, predicate, fromIndex, fromRight) { - var length = array.length, - index = fromIndex + (fromRight ? 1 : -1); +SemVer.prototype.format = function () { + this.version = this.major + '.' + this.minor + '.' + this.patch + if (this.prerelease.length) { + this.version += '-' + this.prerelease.join('.') + } + return this.version +} - while ((fromRight ? index-- : ++index < length)) { - if (predicate(array[index], index, array)) { - return index; - } +SemVer.prototype.toString = function () { + return this.version +} + +SemVer.prototype.compare = function (other) { + debug('SemVer.compare', this.version, this.options, other) + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) } - return -1; + + return this.compareMain(other) || this.comparePre(other) } -/** - * The base implementation of `_.indexOf` without `fromIndex` bounds checks. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - */ -function baseIndexOf(array, value, fromIndex) { - if (value !== value) { - return baseFindIndex(array, baseIsNaN, fromIndex); +SemVer.prototype.compareMain = function (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) } - var index = fromIndex - 1, - length = array.length; - while (++index < length) { - if (array[index] === value) { - return index; + return compareIdentifiers(this.major, other.major) || + compareIdentifiers(this.minor, other.minor) || + compareIdentifiers(this.patch, other.patch) +} + +SemVer.prototype.comparePre = function (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + // NOT having a prerelease is > having one + if (this.prerelease.length && !other.prerelease.length) { + return -1 + } else if (!this.prerelease.length && other.prerelease.length) { + return 1 + } else if (!this.prerelease.length && !other.prerelease.length) { + return 0 + } + + var i = 0 + do { + var a = this.prerelease[i] + var b = other.prerelease[i] + debug('prerelease compare', i, a, b) + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) } + } while (++i) +} + +// preminor will bump the version up to the next minor release, and immediately +// down to pre-release. premajor and prepatch work the same way. +SemVer.prototype.inc = function (release, identifier) { + switch (release) { + case 'premajor': + this.prerelease.length = 0 + this.patch = 0 + this.minor = 0 + this.major++ + this.inc('pre', identifier) + break + case 'preminor': + this.prerelease.length = 0 + this.patch = 0 + this.minor++ + this.inc('pre', identifier) + break + case 'prepatch': + // If this is already a prerelease, it will bump to the next version + // drop any prereleases that might already exist, since they are not + // relevant at this point. + this.prerelease.length = 0 + this.inc('patch', identifier) + this.inc('pre', identifier) + break + // If the input is a non-prerelease version, this acts the same as + // prepatch. + case 'prerelease': + if (this.prerelease.length === 0) { + this.inc('patch', identifier) + } + this.inc('pre', identifier) + break + + case 'major': + // If this is a pre-major version, bump up to the same major version. + // Otherwise increment major. + // 1.0.0-5 bumps to 1.0.0 + // 1.1.0 bumps to 2.0.0 + if (this.minor !== 0 || + this.patch !== 0 || + this.prerelease.length === 0) { + this.major++ + } + this.minor = 0 + this.patch = 0 + this.prerelease = [] + break + case 'minor': + // If this is a pre-minor version, bump up to the same minor version. + // Otherwise increment minor. + // 1.2.0-5 bumps to 1.2.0 + // 1.2.1 bumps to 1.3.0 + if (this.patch !== 0 || this.prerelease.length === 0) { + this.minor++ + } + this.patch = 0 + this.prerelease = [] + break + case 'patch': + // If this is not a pre-release version, it will increment the patch. + // If it is a pre-release it will bump up to the same patch version. + // 1.2.0-5 patches to 1.2.0 + // 1.2.0 patches to 1.2.1 + if (this.prerelease.length === 0) { + this.patch++ + } + this.prerelease = [] + break + // This probably shouldn't be used publicly. + // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction. + case 'pre': + if (this.prerelease.length === 0) { + this.prerelease = [0] + } else { + var i = this.prerelease.length + while (--i >= 0) { + if (typeof this.prerelease[i] === 'number') { + this.prerelease[i]++ + i = -2 + } + } + if (i === -1) { + // didn't increment anything + this.prerelease.push(0) + } + } + if (identifier) { + // 1.2.0-beta.1 bumps to 1.2.0-beta.2, + // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 + if (this.prerelease[0] === identifier) { + if (isNaN(this.prerelease[1])) { + this.prerelease = [identifier, 0] + } + } else { + this.prerelease = [identifier, 0] + } + } + break + + default: + throw new Error('invalid increment argument: ' + release) } - return -1; + this.format() + this.raw = this.version + return this } -/** - * The base implementation of `_.isNaN` without support for number objects. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. - */ -function baseIsNaN(value) { - return value !== value; +exports.inc = inc +function inc (version, release, loose, identifier) { + if (typeof (loose) === 'string') { + identifier = loose + loose = undefined + } + + try { + return new SemVer(version, loose).inc(release, identifier).version + } catch (er) { + return null + } } -/** - * The base implementation of `_.times` without support for iteratee shorthands - * or max array length checks. - * - * @private - * @param {number} n The number of times to invoke `iteratee`. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the array of results. - */ -function baseTimes(n, iteratee) { - var index = -1, - result = Array(n); +exports.diff = diff +function diff (version1, version2) { + if (eq(version1, version2)) { + return null + } else { + var v1 = parse(version1) + var v2 = parse(version2) + var prefix = '' + if (v1.prerelease.length || v2.prerelease.length) { + prefix = 'pre' + var defaultResult = 'prerelease' + } + for (var key in v1) { + if (key === 'major' || key === 'minor' || key === 'patch') { + if (v1[key] !== v2[key]) { + return prefix + key + } + } + } + return defaultResult // may be undefined + } +} - while (++index < n) { - result[index] = iteratee(index); +exports.compareIdentifiers = compareIdentifiers + +var numeric = /^[0-9]+$/ +function compareIdentifiers (a, b) { + var anum = numeric.test(a) + var bnum = numeric.test(b) + + if (anum && bnum) { + a = +a + b = +b } - return result; + + return a === b ? 0 + : (anum && !bnum) ? -1 + : (bnum && !anum) ? 1 + : a < b ? -1 + : 1 } -/** - * The base implementation of `_.values` and `_.valuesIn` which creates an - * array of `object` property values corresponding to the property names - * of `props`. - * - * @private - * @param {Object} object The object to query. - * @param {Array} props The property names to get values for. - * @returns {Object} Returns the array of property values. - */ -function baseValues(object, props) { - return arrayMap(props, function(key) { - return object[key]; - }); +exports.rcompareIdentifiers = rcompareIdentifiers +function rcompareIdentifiers (a, b) { + return compareIdentifiers(b, a) } -/** - * Creates a unary function that invokes `func` with its argument transformed. - * - * @private - * @param {Function} func The function to wrap. - * @param {Function} transform The argument transform. - * @returns {Function} Returns the new function. - */ -function overArg(func, transform) { - return function(arg) { - return func(transform(arg)); - }; +exports.major = major +function major (a, loose) { + return new SemVer(a, loose).major } -/** Used for built-in method references. */ -var objectProto = Object.prototype; +exports.minor = minor +function minor (a, loose) { + return new SemVer(a, loose).minor +} + +exports.patch = patch +function patch (a, loose) { + return new SemVer(a, loose).patch +} + +exports.compare = compare +function compare (a, b, loose) { + return new SemVer(a, loose).compare(new SemVer(b, loose)) +} + +exports.compareLoose = compareLoose +function compareLoose (a, b) { + return compare(a, b, true) +} + +exports.rcompare = rcompare +function rcompare (a, b, loose) { + return compare(b, a, loose) +} + +exports.sort = sort +function sort (list, loose) { + return list.sort(function (a, b) { + return exports.compare(a, b, loose) + }) +} + +exports.rsort = rsort +function rsort (list, loose) { + return list.sort(function (a, b) { + return exports.rcompare(a, b, loose) + }) +} + +exports.gt = gt +function gt (a, b, loose) { + return compare(a, b, loose) > 0 +} + +exports.lt = lt +function lt (a, b, loose) { + return compare(a, b, loose) < 0 +} + +exports.eq = eq +function eq (a, b, loose) { + return compare(a, b, loose) === 0 +} + +exports.neq = neq +function neq (a, b, loose) { + return compare(a, b, loose) !== 0 +} + +exports.gte = gte +function gte (a, b, loose) { + return compare(a, b, loose) >= 0 +} + +exports.lte = lte +function lte (a, b, loose) { + return compare(a, b, loose) <= 0 +} + +exports.cmp = cmp +function cmp (a, op, b, loose) { + switch (op) { + case '===': + if (typeof a === 'object') + a = a.version + if (typeof b === 'object') + b = b.version + return a === b + + case '!==': + if (typeof a === 'object') + a = a.version + if (typeof b === 'object') + b = b.version + return a !== b -/** Used to check objects for own properties. */ -var hasOwnProperty = objectProto.hasOwnProperty; + case '': + case '=': + case '==': + return eq(a, b, loose) -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var objectToString = objectProto.toString; + case '!=': + return neq(a, b, loose) -/** Built-in value references. */ -var propertyIsEnumerable = objectProto.propertyIsEnumerable; + case '>': + return gt(a, b, loose) -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeKeys = overArg(Object.keys, Object), - nativeMax = Math.max; + case '>=': + return gte(a, b, loose) -/** - * Creates an array of the enumerable property names of the array-like `value`. - * - * @private - * @param {*} value The value to query. - * @param {boolean} inherited Specify returning inherited property names. - * @returns {Array} Returns the array of property names. - */ -function arrayLikeKeys(value, inherited) { - // Safari 8.1 makes `arguments.callee` enumerable in strict mode. - // Safari 9 makes `arguments.length` enumerable in strict mode. - var result = (isArray(value) || isArguments(value)) - ? baseTimes(value.length, String) - : []; + case '<': + return lt(a, b, loose) - var length = result.length, - skipIndexes = !!length; + case '<=': + return lte(a, b, loose) - for (var key in value) { - if ((inherited || hasOwnProperty.call(value, key)) && - !(skipIndexes && (key == 'length' || isIndex(key, length)))) { - result.push(key); - } + default: + throw new TypeError('Invalid operator: ' + op) } - return result; } -/** - * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ -function baseKeys(object) { - if (!isPrototype(object)) { - return nativeKeys(object); - } - var result = []; - for (var key in Object(object)) { - if (hasOwnProperty.call(object, key) && key != 'constructor') { - result.push(key); +exports.Comparator = Comparator +function Comparator (comp, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false } } - return result; -} - -/** - * Checks if `value` is a valid array-like index. - * - * @private - * @param {*} value The value to check. - * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. - * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. - */ -function isIndex(value, length) { - length = length == null ? MAX_SAFE_INTEGER : length; - return !!length && - (typeof value == 'number' || reIsUint.test(value)) && - (value > -1 && value % 1 == 0 && value < length); -} -/** - * Checks if `value` is likely a prototype object. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. - */ -function isPrototype(value) { - var Ctor = value && value.constructor, - proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; + if (comp instanceof Comparator) { + if (comp.loose === !!options.loose) { + return comp + } else { + comp = comp.value + } + } - return value === proto; -} + if (!(this instanceof Comparator)) { + return new Comparator(comp, options) + } -/** - * Checks if `value` is in `collection`. If `collection` is a string, it's - * checked for a substring of `value`, otherwise - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * is used for equality comparisons. If `fromIndex` is negative, it's used as - * the offset from the end of `collection`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object|string} collection The collection to inspect. - * @param {*} value The value to search for. - * @param {number} [fromIndex=0] The index to search from. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. - * @returns {boolean} Returns `true` if `value` is found, else `false`. - * @example - * - * _.includes([1, 2, 3], 1); - * // => true - * - * _.includes([1, 2, 3], 1, 2); - * // => false - * - * _.includes({ 'a': 1, 'b': 2 }, 1); - * // => true - * - * _.includes('abcd', 'bc'); - * // => true - */ -function includes(collection, value, fromIndex, guard) { - collection = isArrayLike(collection) ? collection : values(collection); - fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0; + debug('comparator', comp, options) + this.options = options + this.loose = !!options.loose + this.parse(comp) - var length = collection.length; - if (fromIndex < 0) { - fromIndex = nativeMax(length + fromIndex, 0); + if (this.semver === ANY) { + this.value = '' + } else { + this.value = this.operator + this.semver.version } - return isString(collection) - ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1) - : (!!length && baseIndexOf(collection, value, fromIndex) > -1); -} -/** - * Checks if `value` is likely an `arguments` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - * else `false`. - * @example - * - * _.isArguments(function() { return arguments; }()); - * // => true - * - * _.isArguments([1, 2, 3]); - * // => false - */ -function isArguments(value) { - // Safari 8.1 makes `arguments.callee` enumerable in strict mode. - return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && - (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); + debug('comp', this) } -/** - * Checks if `value` is classified as an `Array` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array, else `false`. - * @example - * - * _.isArray([1, 2, 3]); - * // => true - * - * _.isArray(document.body.children); - * // => false - * - * _.isArray('abc'); - * // => false - * - * _.isArray(_.noop); - * // => false - */ -var isArray = Array.isArray; +var ANY = {} +Comparator.prototype.parse = function (comp) { + var r = this.options.loose ? re[COMPARATORLOOSE] : re[COMPARATOR] + var m = comp.match(r) -/** - * Checks if `value` is array-like. A value is considered array-like if it's - * not a function and has a `value.length` that's an integer greater than or - * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is array-like, else `false`. - * @example - * - * _.isArrayLike([1, 2, 3]); - * // => true - * - * _.isArrayLike(document.body.children); - * // => true - * - * _.isArrayLike('abc'); - * // => true - * - * _.isArrayLike(_.noop); - * // => false - */ -function isArrayLike(value) { - return value != null && isLength(value.length) && !isFunction(value); -} + if (!m) { + throw new TypeError('Invalid comparator: ' + comp) + } -/** - * This method is like `_.isArrayLike` except that it also checks if `value` - * is an object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array-like object, - * else `false`. - * @example - * - * _.isArrayLikeObject([1, 2, 3]); - * // => true - * - * _.isArrayLikeObject(document.body.children); - * // => true - * - * _.isArrayLikeObject('abc'); - * // => false - * - * _.isArrayLikeObject(_.noop); - * // => false - */ -function isArrayLikeObject(value) { - return isObjectLike(value) && isArrayLike(value); -} + this.operator = m[1] + if (this.operator === '=') { + this.operator = '' + } -/** - * Checks if `value` is classified as a `Function` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a function, else `false`. - * @example - * - * _.isFunction(_); - * // => true - * - * _.isFunction(/abc/); - * // => false - */ -function isFunction(value) { - // The use of `Object#toString` avoids issues with the `typeof` operator - // in Safari 8-9 which returns 'object' for typed array and other constructors. - var tag = isObject(value) ? objectToString.call(value) : ''; - return tag == funcTag || tag == genTag; + // if it literally is just '>' or '' then allow anything. + if (!m[2]) { + this.semver = ANY + } else { + this.semver = new SemVer(m[2], this.options.loose) + } } -/** - * Checks if `value` is a valid array-like length. - * - * **Note:** This method is loosely based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. - * @example - * - * _.isLength(3); - * // => true - * - * _.isLength(Number.MIN_VALUE); - * // => false - * - * _.isLength(Infinity); - * // => false - * - * _.isLength('3'); - * // => false - */ -function isLength(value) { - return typeof value == 'number' && - value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; +Comparator.prototype.toString = function () { + return this.value } -/** - * Checks if `value` is the - * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) - * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false - */ -function isObject(value) { - var type = typeof value; - return !!value && (type == 'object' || type == 'function'); -} +Comparator.prototype.test = function (version) { + debug('Comparator.test', version, this.options.loose) -/** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ -function isObjectLike(value) { - return !!value && typeof value == 'object'; -} + if (this.semver === ANY) { + return true + } -/** - * Checks if `value` is classified as a `String` primitive or object. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a string, else `false`. - * @example - * - * _.isString('abc'); - * // => true - * - * _.isString(1); - * // => false - */ -function isString(value) { - return typeof value == 'string' || - (!isArray(value) && isObjectLike(value) && objectToString.call(value) == stringTag); -} + if (typeof version === 'string') { + version = new SemVer(version, this.options) + } -/** - * Checks if `value` is classified as a `Symbol` primitive or object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. - * @example - * - * _.isSymbol(Symbol.iterator); - * // => true - * - * _.isSymbol('abc'); - * // => false - */ -function isSymbol(value) { - return typeof value == 'symbol' || - (isObjectLike(value) && objectToString.call(value) == symbolTag); + return cmp(version, this.operator, this.semver, this.options) } -/** - * Converts `value` to a finite number. - * - * @static - * @memberOf _ - * @since 4.12.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted number. - * @example - * - * _.toFinite(3.2); - * // => 3.2 - * - * _.toFinite(Number.MIN_VALUE); - * // => 5e-324 - * - * _.toFinite(Infinity); - * // => 1.7976931348623157e+308 - * - * _.toFinite('3.2'); - * // => 3.2 - */ -function toFinite(value) { - if (!value) { - return value === 0 ? value : 0; +Comparator.prototype.intersects = function (comp, options) { + if (!(comp instanceof Comparator)) { + throw new TypeError('a Comparator is required') } - value = toNumber(value); - if (value === INFINITY || value === -INFINITY) { - var sign = (value < 0 ? -1 : 1); - return sign * MAX_INTEGER; + + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } } - return value === value ? value : 0; -} -/** - * Converts `value` to an integer. - * - * **Note:** This method is loosely based on - * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted integer. - * @example - * - * _.toInteger(3.2); - * // => 3 - * - * _.toInteger(Number.MIN_VALUE); - * // => 0 - * - * _.toInteger(Infinity); - * // => 1.7976931348623157e+308 - * - * _.toInteger('3.2'); - * // => 3 - */ -function toInteger(value) { - var result = toFinite(value), - remainder = result % 1; + var rangeTmp + + if (this.operator === '') { + rangeTmp = new Range(comp.value, options) + return satisfies(this.value, rangeTmp, options) + } else if (comp.operator === '') { + rangeTmp = new Range(this.value, options) + return satisfies(comp.semver, rangeTmp, options) + } - return result === result ? (remainder ? result - remainder : result) : 0; + var sameDirectionIncreasing = + (this.operator === '>=' || this.operator === '>') && + (comp.operator === '>=' || comp.operator === '>') + var sameDirectionDecreasing = + (this.operator === '<=' || this.operator === '<') && + (comp.operator === '<=' || comp.operator === '<') + var sameSemVer = this.semver.version === comp.semver.version + var differentDirectionsInclusive = + (this.operator === '>=' || this.operator === '<=') && + (comp.operator === '>=' || comp.operator === '<=') + var oppositeDirectionsLessThan = + cmp(this.semver, '<', comp.semver, options) && + ((this.operator === '>=' || this.operator === '>') && + (comp.operator === '<=' || comp.operator === '<')) + var oppositeDirectionsGreaterThan = + cmp(this.semver, '>', comp.semver, options) && + ((this.operator === '<=' || this.operator === '<') && + (comp.operator === '>=' || comp.operator === '>')) + + return sameDirectionIncreasing || sameDirectionDecreasing || + (sameSemVer && differentDirectionsInclusive) || + oppositeDirectionsLessThan || oppositeDirectionsGreaterThan } -/** - * Converts `value` to a number. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to process. - * @returns {number} Returns the number. - * @example - * - * _.toNumber(3.2); - * // => 3.2 - * - * _.toNumber(Number.MIN_VALUE); - * // => 5e-324 - * - * _.toNumber(Infinity); - * // => Infinity - * - * _.toNumber('3.2'); - * // => 3.2 - */ -function toNumber(value) { - if (typeof value == 'number') { - return value; +exports.Range = Range +function Range (range, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } } - if (isSymbol(value)) { - return NAN; + + if (range instanceof Range) { + if (range.loose === !!options.loose && + range.includePrerelease === !!options.includePrerelease) { + return range + } else { + return new Range(range.raw, options) + } } - if (isObject(value)) { - var other = typeof value.valueOf == 'function' ? value.valueOf() : value; - value = isObject(other) ? (other + '') : other; + + if (range instanceof Comparator) { + return new Range(range.value, options) } - if (typeof value != 'string') { - return value === 0 ? value : +value; + + if (!(this instanceof Range)) { + return new Range(range, options) } - value = value.replace(reTrim, ''); - var isBinary = reIsBinary.test(value); - return (isBinary || reIsOctal.test(value)) - ? freeParseInt(value.slice(2), isBinary ? 2 : 8) - : (reIsBadHex.test(value) ? NAN : +value); -} -/** - * Creates an array of the own enumerable property names of `object`. - * - * **Note:** Non-object values are coerced to objects. See the - * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) - * for more details. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.keys(new Foo); - * // => ['a', 'b'] (iteration order is not guaranteed) - * - * _.keys('hi'); - * // => ['0', '1'] - */ -function keys(object) { - return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); -} + this.options = options + this.loose = !!options.loose + this.includePrerelease = !!options.includePrerelease -/** - * Creates an array of the own enumerable string keyed property values of `object`. - * - * **Note:** Non-object values are coerced to objects. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property values. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.values(new Foo); - * // => [1, 2] (iteration order is not guaranteed) - * - * _.values('hi'); - * // => ['h', 'i'] - */ -function values(object) { - return object ? baseValues(object, keys(object)) : []; + // First, split based on boolean or || + this.raw = range + this.set = range.split(/\s*\|\|\s*/).map(function (range) { + return this.parseRange(range.trim()) + }, this).filter(function (c) { + // throw out any that are not relevant for whatever reason + return c.length + }) + + if (!this.set.length) { + throw new TypeError('Invalid SemVer Range: ' + range) + } + + this.format() } -module.exports = includes; +Range.prototype.format = function () { + this.range = this.set.map(function (comps) { + return comps.join(' ').trim() + }).join('||').trim() + return this.range +} +Range.prototype.toString = function () { + return this.range +} -/***/ }), +Range.prototype.parseRange = function (range) { + var loose = this.options.loose + range = range.trim() + // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` + var hr = loose ? re[HYPHENRANGELOOSE] : re[HYPHENRANGE] + range = range.replace(hr, hyphenReplace) + debug('hyphen replace', range) + // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` + range = range.replace(re[COMPARATORTRIM], comparatorTrimReplace) + debug('comparator trim', range, re[COMPARATORTRIM]) -/***/ 44130: -/***/ ((module) => { + // `~ 1.2.3` => `~1.2.3` + range = range.replace(re[TILDETRIM], tildeTrimReplace) -/** - * lodash (Custom Build) - * Build: `lodash modularize exports="npm" -o ./` - * Copyright jQuery Foundation and other contributors - * Released under MIT license - * Based on Underscore.js 1.8.3 - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - */ + // `^ 1.2.3` => `^1.2.3` + range = range.replace(re[CARETTRIM], caretTrimReplace) -/** Used as references for various `Number` constants. */ -var MAX_SAFE_INTEGER = 9007199254740991; + // normalize spaces + range = range.split(/\s+/).join(' ') -/** `Object#toString` result references. */ -var argsTag = '[object Arguments]', - funcTag = '[object Function]', - genTag = '[object GeneratorFunction]'; + // At this point, the range is completely trimmed and + // ready to be split into comparators. -/** Used for built-in method references. */ -var objectProto = Object.prototype; + var compRe = loose ? re[COMPARATORLOOSE] : re[COMPARATOR] + var set = range.split(' ').map(function (comp) { + return parseComparator(comp, this.options) + }, this).join(' ').split(/\s+/) + if (this.options.loose) { + // in loose mode, throw out any that are not valid comparators + set = set.filter(function (comp) { + return !!comp.match(compRe) + }) + } + set = set.map(function (comp) { + return new Comparator(comp, this.options) + }, this) -/** Used to check objects for own properties. */ -var hasOwnProperty = objectProto.hasOwnProperty; + return set +} -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var objectToString = objectProto.toString; +Range.prototype.intersects = function (range, options) { + if (!(range instanceof Range)) { + throw new TypeError('a Range is required') + } -/** Built-in value references. */ -var propertyIsEnumerable = objectProto.propertyIsEnumerable; + return this.set.some(function (thisComparators) { + return thisComparators.every(function (thisComparator) { + return range.set.some(function (rangeComparators) { + return rangeComparators.every(function (rangeComparator) { + return thisComparator.intersects(rangeComparator, options) + }) + }) + }) + }) +} -/** - * Checks if `value` is likely an `arguments` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - * else `false`. - * @example - * - * _.isArguments(function() { return arguments; }()); - * // => true - * - * _.isArguments([1, 2, 3]); - * // => false - */ -function isArguments(value) { - // Safari 8.1 makes `arguments.callee` enumerable in strict mode. - return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && - (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); +// Mostly just for testing and legacy API reasons +exports.toComparators = toComparators +function toComparators (range, options) { + return new Range(range, options).set.map(function (comp) { + return comp.map(function (c) { + return c.value + }).join(' ').trim().split(' ') + }) } -/** - * Checks if `value` is array-like. A value is considered array-like if it's - * not a function and has a `value.length` that's an integer greater than or - * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is array-like, else `false`. - * @example - * - * _.isArrayLike([1, 2, 3]); - * // => true - * - * _.isArrayLike(document.body.children); - * // => true - * - * _.isArrayLike('abc'); - * // => true - * - * _.isArrayLike(_.noop); - * // => false - */ -function isArrayLike(value) { - return value != null && isLength(value.length) && !isFunction(value); +// comprised of xranges, tildes, stars, and gtlt's at this point. +// already replaced the hyphen ranges +// turn into a set of JUST comparators. +function parseComparator (comp, options) { + debug('comp', comp, options) + comp = replaceCarets(comp, options) + debug('caret', comp) + comp = replaceTildes(comp, options) + debug('tildes', comp) + comp = replaceXRanges(comp, options) + debug('xrange', comp) + comp = replaceStars(comp, options) + debug('stars', comp) + return comp } -/** - * This method is like `_.isArrayLike` except that it also checks if `value` - * is an object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array-like object, - * else `false`. - * @example - * - * _.isArrayLikeObject([1, 2, 3]); - * // => true - * - * _.isArrayLikeObject(document.body.children); - * // => true - * - * _.isArrayLikeObject('abc'); - * // => false - * - * _.isArrayLikeObject(_.noop); - * // => false - */ -function isArrayLikeObject(value) { - return isObjectLike(value) && isArrayLike(value); +function isX (id) { + return !id || id.toLowerCase() === 'x' || id === '*' } -/** - * Checks if `value` is classified as a `Function` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a function, else `false`. - * @example - * - * _.isFunction(_); - * // => true - * - * _.isFunction(/abc/); - * // => false - */ -function isFunction(value) { - // The use of `Object#toString` avoids issues with the `typeof` operator - // in Safari 8-9 which returns 'object' for typed array and other constructors. - var tag = isObject(value) ? objectToString.call(value) : ''; - return tag == funcTag || tag == genTag; +// ~, ~> --> * (any, kinda silly) +// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0 +// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0 +// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0 +// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0 +// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0 +function replaceTildes (comp, options) { + return comp.trim().split(/\s+/).map(function (comp) { + return replaceTilde(comp, options) + }).join(' ') } -/** - * Checks if `value` is a valid array-like length. - * - * **Note:** This method is loosely based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. - * @example - * - * _.isLength(3); - * // => true - * - * _.isLength(Number.MIN_VALUE); - * // => false - * - * _.isLength(Infinity); - * // => false - * - * _.isLength('3'); - * // => false - */ -function isLength(value) { - return typeof value == 'number' && - value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; +function replaceTilde (comp, options) { + var r = options.loose ? re[TILDELOOSE] : re[TILDE] + return comp.replace(r, function (_, M, m, p, pr) { + debug('tilde', comp, _, M, m, p, pr) + var ret + + if (isX(M)) { + ret = '' + } else if (isX(m)) { + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' + } else if (isX(p)) { + // ~1.2 == >=1.2.0 <1.3.0 + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' + } else if (pr) { + debug('replaceTilde pr', pr) + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + + ' <' + M + '.' + (+m + 1) + '.0' + } else { + // ~1.2.3 == >=1.2.3 <1.3.0 + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + (+m + 1) + '.0' + } + + debug('tilde return', ret) + return ret + }) } -/** - * Checks if `value` is the - * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) - * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false - */ -function isObject(value) { - var type = typeof value; - return !!value && (type == 'object' || type == 'function'); +// ^ --> * (any, kinda silly) +// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0 +// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0 +// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0 +// ^1.2.3 --> >=1.2.3 <2.0.0 +// ^1.2.0 --> >=1.2.0 <2.0.0 +function replaceCarets (comp, options) { + return comp.trim().split(/\s+/).map(function (comp) { + return replaceCaret(comp, options) + }).join(' ') } -/** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ -function isObjectLike(value) { - return !!value && typeof value == 'object'; +function replaceCaret (comp, options) { + debug('caret', comp, options) + var r = options.loose ? re[CARETLOOSE] : re[CARET] + return comp.replace(r, function (_, M, m, p, pr) { + debug('caret', comp, _, M, m, p, pr) + var ret + + if (isX(M)) { + ret = '' + } else if (isX(m)) { + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' + } else if (isX(p)) { + if (M === '0') { + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' + } else { + ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0' + } + } else if (pr) { + debug('replaceCaret pr', pr) + if (M === '0') { + if (m === '0') { + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + + ' <' + M + '.' + m + '.' + (+p + 1) + } else { + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + + ' <' + M + '.' + (+m + 1) + '.0' + } + } else { + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + + ' <' + (+M + 1) + '.0.0' + } + } else { + debug('no pr') + if (M === '0') { + if (m === '0') { + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + m + '.' + (+p + 1) + } else { + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + (+m + 1) + '.0' + } + } else { + ret = '>=' + M + '.' + m + '.' + p + + ' <' + (+M + 1) + '.0.0' + } + } + + debug('caret return', ret) + return ret + }) } -module.exports = isArguments; - +function replaceXRanges (comp, options) { + debug('replaceXRanges', comp, options) + return comp.split(/\s+/).map(function (comp) { + return replaceXRange(comp, options) + }).join(' ') +} -/***/ }), +function replaceXRange (comp, options) { + comp = comp.trim() + var r = options.loose ? re[XRANGELOOSE] : re[XRANGE] + return comp.replace(r, function (ret, gtlt, M, m, p, pr) { + debug('xRange', comp, ret, gtlt, M, m, p, pr) + var xM = isX(M) + var xm = xM || isX(m) + var xp = xm || isX(p) + var anyX = xp -/***/ 16501: -/***/ ((module) => { + if (gtlt === '=' && anyX) { + gtlt = '' + } -/** - * lodash 3.0.3 (Custom Build) - * Build: `lodash modularize exports="npm" -o ./` - * Copyright 2012-2016 The Dojo Foundation - * Based on Underscore.js 1.8.3 - * Copyright 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - * Available under MIT license - */ + if (xM) { + if (gtlt === '>' || gtlt === '<') { + // nothing is allowed + ret = '<0.0.0' + } else { + // nothing is forbidden + ret = '*' + } + } else if (gtlt && anyX) { + // we know patch is an x, because we have any x at all. + // replace X with 0 + if (xm) { + m = 0 + } + p = 0 -/** `Object#toString` result references. */ -var boolTag = '[object Boolean]'; + if (gtlt === '>') { + // >1 => >=2.0.0 + // >1.2 => >=1.3.0 + // >1.2.3 => >= 1.2.4 + gtlt = '>=' + if (xm) { + M = +M + 1 + m = 0 + p = 0 + } else { + m = +m + 1 + p = 0 + } + } else if (gtlt === '<=') { + // <=0.7.x is actually <0.8.0, since any 0.7.x should + // pass. Similarly, <=7.x is actually <8.0.0, etc. + gtlt = '<' + if (xm) { + M = +M + 1 + } else { + m = +m + 1 + } + } -/** Used for built-in method references. */ -var objectProto = Object.prototype; + ret = gtlt + M + '.' + m + '.' + p + } else if (xm) { + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' + } else if (xp) { + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' + } -/** - * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) - * of values. - */ -var objectToString = objectProto.toString; + debug('xRange return', ret) -/** - * Checks if `value` is classified as a boolean primitive or object. - * - * @static - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. - * @example - * - * _.isBoolean(false); - * // => true - * - * _.isBoolean(null); - * // => false - */ -function isBoolean(value) { - return value === true || value === false || - (isObjectLike(value) && objectToString.call(value) == boolTag); + return ret + }) } -/** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ -function isObjectLike(value) { - return !!value && typeof value == 'object'; +// Because * is AND-ed with everything else in the comparator, +// and '' means "any version", just remove the *s entirely. +function replaceStars (comp, options) { + debug('replaceStars', comp, options) + // Looseness is ignored here. star is always as loose as it gets! + return comp.trim().replace(re[STAR], '') } -module.exports = isBoolean; - - -/***/ }), - -/***/ 21441: -/***/ ((module) => { - -/** - * lodash (Custom Build) - * Build: `lodash modularize exports="npm" -o ./` - * Copyright jQuery Foundation and other contributors - * Released under MIT license - * Based on Underscore.js 1.8.3 - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - */ +// This function is passed to string.replace(re[HYPHENRANGE]) +// M, m, patch, prerelease, build +// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 +// 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do +// 1.2 - 3.4 => >=1.2.0 <3.5.0 +function hyphenReplace ($0, + from, fM, fm, fp, fpr, fb, + to, tM, tm, tp, tpr, tb) { + if (isX(fM)) { + from = '' + } else if (isX(fm)) { + from = '>=' + fM + '.0.0' + } else if (isX(fp)) { + from = '>=' + fM + '.' + fm + '.0' + } else { + from = '>=' + from + } -/** Used as references for various `Number` constants. */ -var INFINITY = 1 / 0, - MAX_INTEGER = 1.7976931348623157e+308, - NAN = 0 / 0; + if (isX(tM)) { + to = '' + } else if (isX(tm)) { + to = '<' + (+tM + 1) + '.0.0' + } else if (isX(tp)) { + to = '<' + tM + '.' + (+tm + 1) + '.0' + } else if (tpr) { + to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr + } else { + to = '<=' + to + } -/** `Object#toString` result references. */ -var symbolTag = '[object Symbol]'; + return (from + ' ' + to).trim() +} -/** Used to match leading and trailing whitespace. */ -var reTrim = /^\s+|\s+$/g; +// if ANY of the sets match ALL of its comparators, then pass +Range.prototype.test = function (version) { + if (!version) { + return false + } -/** Used to detect bad signed hexadecimal string values. */ -var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; + if (typeof version === 'string') { + version = new SemVer(version, this.options) + } -/** Used to detect binary string values. */ -var reIsBinary = /^0b[01]+$/i; + for (var i = 0; i < this.set.length; i++) { + if (testSet(this.set[i], version, this.options)) { + return true + } + } + return false +} -/** Used to detect octal string values. */ -var reIsOctal = /^0o[0-7]+$/i; +function testSet (set, version, options) { + for (var i = 0; i < set.length; i++) { + if (!set[i].test(version)) { + return false + } + } -/** Built-in method references without a dependency on `root`. */ -var freeParseInt = parseInt; + if (version.prerelease.length && !options.includePrerelease) { + // Find the set of versions that are allowed to have prereleases + // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 + // That should allow `1.2.3-pr.2` to pass. + // However, `1.2.4-alpha.notready` should NOT be allowed, + // even though it's within the range set by the comparators. + for (i = 0; i < set.length; i++) { + debug(set[i].semver) + if (set[i].semver === ANY) { + continue + } -/** Used for built-in method references. */ -var objectProto = Object.prototype; + if (set[i].semver.prerelease.length > 0) { + var allowed = set[i].semver + if (allowed.major === version.major && + allowed.minor === version.minor && + allowed.patch === version.patch) { + return true + } + } + } -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var objectToString = objectProto.toString; + // Version has a -pre, but it's not one of the ones we like. + return false + } -/** - * Checks if `value` is an integer. - * - * **Note:** This method is based on - * [`Number.isInteger`](https://mdn.io/Number/isInteger). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an integer, else `false`. - * @example - * - * _.isInteger(3); - * // => true - * - * _.isInteger(Number.MIN_VALUE); - * // => false - * - * _.isInteger(Infinity); - * // => false - * - * _.isInteger('3'); - * // => false - */ -function isInteger(value) { - return typeof value == 'number' && value == toInteger(value); + return true } -/** - * Checks if `value` is the - * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) - * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false - */ -function isObject(value) { - var type = typeof value; - return !!value && (type == 'object' || type == 'function'); +exports.satisfies = satisfies +function satisfies (version, range, options) { + try { + range = new Range(range, options) + } catch (er) { + return false + } + return range.test(version) } -/** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ -function isObjectLike(value) { - return !!value && typeof value == 'object'; +exports.maxSatisfying = maxSatisfying +function maxSatisfying (versions, range, options) { + var max = null + var maxSV = null + try { + var rangeObj = new Range(range, options) + } catch (er) { + return null + } + versions.forEach(function (v) { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!max || maxSV.compare(v) === -1) { + // compare(max, v, true) + max = v + maxSV = new SemVer(max, options) + } + } + }) + return max } -/** - * Checks if `value` is classified as a `Symbol` primitive or object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. - * @example - * - * _.isSymbol(Symbol.iterator); - * // => true - * - * _.isSymbol('abc'); - * // => false - */ -function isSymbol(value) { - return typeof value == 'symbol' || - (isObjectLike(value) && objectToString.call(value) == symbolTag); +exports.minSatisfying = minSatisfying +function minSatisfying (versions, range, options) { + var min = null + var minSV = null + try { + var rangeObj = new Range(range, options) + } catch (er) { + return null + } + versions.forEach(function (v) { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!min || minSV.compare(v) === 1) { + // compare(min, v, true) + min = v + minSV = new SemVer(min, options) + } + } + }) + return min } -/** - * Converts `value` to a finite number. - * - * @static - * @memberOf _ - * @since 4.12.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted number. - * @example - * - * _.toFinite(3.2); - * // => 3.2 - * - * _.toFinite(Number.MIN_VALUE); - * // => 5e-324 - * - * _.toFinite(Infinity); - * // => 1.7976931348623157e+308 - * - * _.toFinite('3.2'); - * // => 3.2 - */ -function toFinite(value) { - if (!value) { - return value === 0 ? value : 0; +exports.minVersion = minVersion +function minVersion (range, loose) { + range = new Range(range, loose) + + var minver = new SemVer('0.0.0') + if (range.test(minver)) { + return minver + } + + minver = new SemVer('0.0.0-0') + if (range.test(minver)) { + return minver + } + + minver = null + for (var i = 0; i < range.set.length; ++i) { + var comparators = range.set[i] + + comparators.forEach(function (comparator) { + // Clone to avoid manipulating the comparator's semver object. + var compver = new SemVer(comparator.semver.version) + switch (comparator.operator) { + case '>': + if (compver.prerelease.length === 0) { + compver.patch++ + } else { + compver.prerelease.push(0) + } + compver.raw = compver.format() + /* fallthrough */ + case '': + case '>=': + if (!minver || gt(minver, compver)) { + minver = compver + } + break + case '<': + case '<=': + /* Ignore maximum versions */ + break + /* istanbul ignore next */ + default: + throw new Error('Unexpected operation: ' + comparator.operator) + } + }) } - value = toNumber(value); - if (value === INFINITY || value === -INFINITY) { - var sign = (value < 0 ? -1 : 1); - return sign * MAX_INTEGER; + + if (minver && range.test(minver)) { + return minver } - return value === value ? value : 0; + + return null } -/** - * Converts `value` to an integer. - * - * **Note:** This method is loosely based on - * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted integer. - * @example - * - * _.toInteger(3.2); - * // => 3 - * - * _.toInteger(Number.MIN_VALUE); - * // => 0 - * - * _.toInteger(Infinity); - * // => 1.7976931348623157e+308 - * - * _.toInteger('3.2'); - * // => 3 - */ -function toInteger(value) { - var result = toFinite(value), - remainder = result % 1; +exports.validRange = validRange +function validRange (range, options) { + try { + // Return '*' instead of '' so that truthiness works. + // This will throw if it's invalid anyway + return new Range(range, options).range || '*' + } catch (er) { + return null + } +} - return result === result ? (remainder ? result - remainder : result) : 0; +// Determine if version is less than all the versions possible in the range +exports.ltr = ltr +function ltr (version, range, options) { + return outside(version, range, '<', options) } -/** - * Converts `value` to a number. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to process. - * @returns {number} Returns the number. - * @example - * - * _.toNumber(3.2); - * // => 3.2 - * - * _.toNumber(Number.MIN_VALUE); - * // => 5e-324 - * - * _.toNumber(Infinity); - * // => Infinity - * - * _.toNumber('3.2'); - * // => 3.2 - */ -function toNumber(value) { - if (typeof value == 'number') { - return value; - } - if (isSymbol(value)) { - return NAN; - } - if (isObject(value)) { - var other = typeof value.valueOf == 'function' ? value.valueOf() : value; - value = isObject(other) ? (other + '') : other; - } - if (typeof value != 'string') { - return value === 0 ? value : +value; - } - value = value.replace(reTrim, ''); - var isBinary = reIsBinary.test(value); - return (isBinary || reIsOctal.test(value)) - ? freeParseInt(value.slice(2), isBinary ? 2 : 8) - : (reIsBadHex.test(value) ? NAN : +value); +// Determine if version is greater than all the versions possible in the range. +exports.gtr = gtr +function gtr (version, range, options) { + return outside(version, range, '>', options) } -module.exports = isInteger; +exports.outside = outside +function outside (version, range, hilo, options) { + version = new SemVer(version, options) + range = new Range(range, options) + var gtfn, ltefn, ltfn, comp, ecomp + switch (hilo) { + case '>': + gtfn = gt + ltefn = lte + ltfn = lt + comp = '>' + ecomp = '>=' + break + case '<': + gtfn = lt + ltefn = gte + ltfn = gt + comp = '<' + ecomp = '<=' + break + default: + throw new TypeError('Must provide a hilo val of "<" or ">"') + } -/***/ }), + // If it satisifes the range it is not outside + if (satisfies(version, range, options)) { + return false + } -/***/ 40298: -/***/ ((module) => { + // From now on, variable terms are as if we're in "gtr" mode. + // but note that everything is flipped for the "ltr" function. -/** - * lodash 3.0.3 (Custom Build) - * Build: `lodash modularize exports="npm" -o ./` - * Copyright 2012-2016 The Dojo Foundation - * Based on Underscore.js 1.8.3 - * Copyright 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - * Available under MIT license - */ + for (var i = 0; i < range.set.length; ++i) { + var comparators = range.set[i] -/** `Object#toString` result references. */ -var numberTag = '[object Number]'; + var high = null + var low = null -/** Used for built-in method references. */ -var objectProto = Object.prototype; + comparators.forEach(function (comparator) { + if (comparator.semver === ANY) { + comparator = new Comparator('>=0.0.0') + } + high = high || comparator + low = low || comparator + if (gtfn(comparator.semver, high.semver, options)) { + high = comparator + } else if (ltfn(comparator.semver, low.semver, options)) { + low = comparator + } + }) -/** - * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) - * of values. - */ -var objectToString = objectProto.toString; + // If the edge version comparator has a operator then our version + // isn't outside it + if (high.operator === comp || high.operator === ecomp) { + return false + } -/** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ -function isObjectLike(value) { - return !!value && typeof value == 'object'; + // If the lowest version comparator has an operator and our version + // is less than it then it isn't higher than the range + if ((!low.operator || low.operator === comp) && + ltefn(version, low.semver)) { + return false + } else if (low.operator === ecomp && ltfn(version, low.semver)) { + return false + } + } + return true } -/** - * Checks if `value` is classified as a `Number` primitive or object. - * - * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are classified - * as numbers, use the `_.isFinite` method. - * - * @static - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. - * @example - * - * _.isNumber(3); - * // => true - * - * _.isNumber(Number.MIN_VALUE); - * // => true - * - * _.isNumber(Infinity); - * // => true - * - * _.isNumber('3'); - * // => false - */ -function isNumber(value) { - return typeof value == 'number' || - (isObjectLike(value) && objectToString.call(value) == numberTag); +exports.prerelease = prerelease +function prerelease (version, options) { + var parsed = parse(version, options) + return (parsed && parsed.prerelease.length) ? parsed.prerelease : null } -module.exports = isNumber; +exports.intersects = intersects +function intersects (r1, r2, options) { + r1 = new Range(r1, options) + r2 = new Range(r2, options) + return r1.intersects(r2) +} + +exports.coerce = coerce +function coerce (version) { + if (version instanceof SemVer) { + return version + } + + if (typeof version !== 'string') { + return null + } + + var match = version.match(re[COERCE]) + + if (match == null) { + return null + } + + return parse(match[1] + + '.' + (match[2] || '0') + + '.' + (match[3] || '0')) +} /***/ }), -/***/ 25723: -/***/ ((module) => { +/***/ 82022: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * lodash (Custom Build) - * Build: `lodash modularize exports="npm" -o ./` - * Copyright jQuery Foundation and other contributors - * Released under MIT license - * Based on Underscore.js 1.8.3 - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - */ +var timespan = __nccwpck_require__(46098); +var PS_SUPPORTED = __nccwpck_require__(59085); +var jws = __nccwpck_require__(4636); +var includes = __nccwpck_require__(17931); +var isBoolean = __nccwpck_require__(16501); +var isInteger = __nccwpck_require__(21441); +var isNumber = __nccwpck_require__(40298); +var isPlainObject = __nccwpck_require__(25723); +var isString = __nccwpck_require__(25180); +var once = __nccwpck_require__(94499); -/** `Object#toString` result references. */ -var objectTag = '[object Object]'; +var SUPPORTED_ALGS = ['RS256', 'RS384', 'RS512', 'ES256', 'ES384', 'ES512', 'HS256', 'HS384', 'HS512', 'none'] +if (PS_SUPPORTED) { + SUPPORTED_ALGS.splice(3, 0, 'PS256', 'PS384', 'PS512'); +} -/** - * Checks if `value` is a host object in IE < 9. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a host object, else `false`. - */ -function isHostObject(value) { - // Many host objects are `Object` objects that can coerce to strings - // despite having improperly defined `toString` methods. - var result = false; - if (value != null && typeof value.toString != 'function') { - try { - result = !!(value + ''); - } catch (e) {} +var sign_options_schema = { + expiresIn: { isValid: function(value) { return isInteger(value) || (isString(value) && value); }, message: '"expiresIn" should be a number of seconds or string representing a timespan' }, + notBefore: { isValid: function(value) { return isInteger(value) || (isString(value) && value); }, message: '"notBefore" should be a number of seconds or string representing a timespan' }, + audience: { isValid: function(value) { return isString(value) || Array.isArray(value); }, message: '"audience" must be a string or array' }, + algorithm: { isValid: includes.bind(null, SUPPORTED_ALGS), message: '"algorithm" must be a valid string enum value' }, + header: { isValid: isPlainObject, message: '"header" must be an object' }, + encoding: { isValid: isString, message: '"encoding" must be a string' }, + issuer: { isValid: isString, message: '"issuer" must be a string' }, + subject: { isValid: isString, message: '"subject" must be a string' }, + jwtid: { isValid: isString, message: '"jwtid" must be a string' }, + noTimestamp: { isValid: isBoolean, message: '"noTimestamp" must be a boolean' }, + keyid: { isValid: isString, message: '"keyid" must be a string' }, + mutatePayload: { isValid: isBoolean, message: '"mutatePayload" must be a boolean' } +}; + +var registered_claims_schema = { + iat: { isValid: isNumber, message: '"iat" should be a number of seconds' }, + exp: { isValid: isNumber, message: '"exp" should be a number of seconds' }, + nbf: { isValid: isNumber, message: '"nbf" should be a number of seconds' } +}; + +function validate(schema, allowUnknown, object, parameterName) { + if (!isPlainObject(object)) { + throw new Error('Expected "' + parameterName + '" to be a plain object.'); } - return result; + Object.keys(object) + .forEach(function(key) { + var validator = schema[key]; + if (!validator) { + if (!allowUnknown) { + throw new Error('"' + key + '" is not allowed in "' + parameterName + '"'); + } + return; + } + if (!validator.isValid(object[key])) { + throw new Error(validator.message); + } + }); } -/** - * Creates a unary function that invokes `func` with its argument transformed. - * - * @private - * @param {Function} func The function to wrap. - * @param {Function} transform The argument transform. - * @returns {Function} Returns the new function. - */ -function overArg(func, transform) { - return function(arg) { - return func(transform(arg)); - }; +function validateOptions(options) { + return validate(sign_options_schema, false, options, 'options'); } -/** Used for built-in method references. */ -var funcProto = Function.prototype, - objectProto = Object.prototype; +function validatePayload(payload) { + return validate(registered_claims_schema, true, payload, 'payload'); +} -/** Used to resolve the decompiled source of functions. */ -var funcToString = funcProto.toString; +var options_to_payload = { + 'audience': 'aud', + 'issuer': 'iss', + 'subject': 'sub', + 'jwtid': 'jti' +}; -/** Used to check objects for own properties. */ -var hasOwnProperty = objectProto.hasOwnProperty; +var options_for_objects = [ + 'expiresIn', + 'notBefore', + 'noTimestamp', + 'audience', + 'issuer', + 'subject', + 'jwtid', +]; -/** Used to infer the `Object` constructor. */ -var objectCtorString = funcToString.call(Object); +module.exports = function (payload, secretOrPrivateKey, options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } else { + options = options || {}; + } -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var objectToString = objectProto.toString; + var isObjectPayload = typeof payload === 'object' && + !Buffer.isBuffer(payload); -/** Built-in value references. */ -var getPrototype = overArg(Object.getPrototypeOf, Object); + var header = Object.assign({ + alg: options.algorithm || 'HS256', + typ: isObjectPayload ? 'JWT' : undefined, + kid: options.keyid + }, options.header); -/** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ -function isObjectLike(value) { - return !!value && typeof value == 'object'; -} + function failure(err) { + if (callback) { + return callback(err); + } + throw err; + } -/** - * Checks if `value` is a plain object, that is, an object created by the - * `Object` constructor or one with a `[[Prototype]]` of `null`. - * - * @static - * @memberOf _ - * @since 0.8.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. - * @example - * - * function Foo() { - * this.a = 1; - * } - * - * _.isPlainObject(new Foo); - * // => false - * - * _.isPlainObject([1, 2, 3]); - * // => false - * - * _.isPlainObject({ 'x': 0, 'y': 0 }); - * // => true - * - * _.isPlainObject(Object.create(null)); - * // => true - */ -function isPlainObject(value) { - if (!isObjectLike(value) || - objectToString.call(value) != objectTag || isHostObject(value)) { - return false; + if (!secretOrPrivateKey && options.algorithm !== 'none') { + return failure(new Error('secretOrPrivateKey must have a value')); + } + + if (typeof payload === 'undefined') { + return failure(new Error('payload is required')); + } else if (isObjectPayload) { + try { + validatePayload(payload); + } + catch (error) { + return failure(error); + } + if (!options.mutatePayload) { + payload = Object.assign({},payload); + } + } else { + var invalid_options = options_for_objects.filter(function (opt) { + return typeof options[opt] !== 'undefined'; + }); + + if (invalid_options.length > 0) { + return failure(new Error('invalid ' + invalid_options.join(',') + ' option for ' + (typeof payload ) + ' payload')); + } + } + + if (typeof payload.exp !== 'undefined' && typeof options.expiresIn !== 'undefined') { + return failure(new Error('Bad "options.expiresIn" option the payload already has an "exp" property.')); + } + + if (typeof payload.nbf !== 'undefined' && typeof options.notBefore !== 'undefined') { + return failure(new Error('Bad "options.notBefore" option the payload already has an "nbf" property.')); + } + + try { + validateOptions(options); } - var proto = getPrototype(value); - if (proto === null) { - return true; + catch (error) { + return failure(error); } - var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; - return (typeof Ctor == 'function' && - Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString); -} -module.exports = isPlainObject; + var timestamp = payload.iat || Math.floor(Date.now() / 1000); + if (options.noTimestamp) { + delete payload.iat; + } else if (isObjectPayload) { + payload.iat = timestamp; + } -/***/ }), + if (typeof options.notBefore !== 'undefined') { + try { + payload.nbf = timespan(options.notBefore, timestamp); + } + catch (err) { + return failure(err); + } + if (typeof payload.nbf === 'undefined') { + return failure(new Error('"notBefore" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60')); + } + } -/***/ 25180: -/***/ ((module) => { + if (typeof options.expiresIn !== 'undefined' && typeof payload === 'object') { + try { + payload.exp = timespan(options.expiresIn, timestamp); + } + catch (err) { + return failure(err); + } + if (typeof payload.exp === 'undefined') { + return failure(new Error('"expiresIn" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60')); + } + } -/** - * lodash 4.0.1 (Custom Build) - * Build: `lodash modularize exports="npm" -o ./` - * Copyright 2012-2016 The Dojo Foundation - * Based on Underscore.js 1.8.3 - * Copyright 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - * Available under MIT license - */ + Object.keys(options_to_payload).forEach(function (key) { + var claim = options_to_payload[key]; + if (typeof options[key] !== 'undefined') { + if (typeof payload[claim] !== 'undefined') { + return failure(new Error('Bad "options.' + key + '" option. The payload already has an "' + claim + '" property.')); + } + payload[claim] = options[key]; + } + }); -/** `Object#toString` result references. */ -var stringTag = '[object String]'; + var encoding = options.encoding || 'utf8'; -/** Used for built-in method references. */ -var objectProto = Object.prototype; + if (typeof callback === 'function') { + callback = callback && once(callback); -/** - * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) - * of values. - */ -var objectToString = objectProto.toString; + jws.createSign({ + header: header, + privateKey: secretOrPrivateKey, + payload: payload, + encoding: encoding + }).once('error', callback) + .once('done', function (signature) { + callback(null, signature); + }); + } else { + return jws.sign({header: header, payload: payload, secret: secretOrPrivateKey, encoding: encoding}); + } +}; -/** - * Checks if `value` is classified as an `Array` object. - * - * @static - * @memberOf _ - * @type Function - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. - * @example - * - * _.isArray([1, 2, 3]); - * // => true - * - * _.isArray(document.body.children); - * // => false - * - * _.isArray('abc'); - * // => false - * - * _.isArray(_.noop); - * // => false - */ -var isArray = Array.isArray; -/** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ -function isObjectLike(value) { - return !!value && typeof value == 'object'; -} +/***/ }), -/** - * Checks if `value` is classified as a `String` primitive or object. - * - * @static - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. - * @example - * - * _.isString('abc'); - * // => true - * - * _.isString(1); - * // => false - */ -function isString(value) { - return typeof value == 'string' || - (!isArray(value) && isObjectLike(value) && objectToString.call(value) == stringTag); +/***/ 12327: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var JsonWebTokenError = __nccwpck_require__(405); +var NotBeforeError = __nccwpck_require__(4383); +var TokenExpiredError = __nccwpck_require__(46637); +var decode = __nccwpck_require__(53359); +var timespan = __nccwpck_require__(46098); +var PS_SUPPORTED = __nccwpck_require__(59085); +var jws = __nccwpck_require__(4636); + +var PUB_KEY_ALGS = ['RS256', 'RS384', 'RS512', 'ES256', 'ES384', 'ES512']; +var RSA_KEY_ALGS = ['RS256', 'RS384', 'RS512']; +var HS_ALGS = ['HS256', 'HS384', 'HS512']; + +if (PS_SUPPORTED) { + PUB_KEY_ALGS.splice(3, 0, 'PS256', 'PS384', 'PS512'); + RSA_KEY_ALGS.splice(3, 0, 'PS256', 'PS384', 'PS512'); } -module.exports = isString; +module.exports = function (jwtString, secretOrPublicKey, options, callback) { + if ((typeof options === 'function') && !callback) { + callback = options; + options = {}; + } + if (!options) { + options = {}; + } -/***/ }), + //clone this object since we are going to mutate it. + options = Object.assign({}, options); -/***/ 94499: -/***/ ((module) => { + var done; -/** - * lodash (Custom Build) - * Build: `lodash modularize exports="npm" -o ./` - * Copyright jQuery Foundation and other contributors - * Released under MIT license - * Based on Underscore.js 1.8.3 - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - */ + if (callback) { + done = callback; + } else { + done = function(err, data) { + if (err) throw err; + return data; + }; + } -/** Used as the `TypeError` message for "Functions" methods. */ -var FUNC_ERROR_TEXT = 'Expected a function'; + if (options.clockTimestamp && typeof options.clockTimestamp !== 'number') { + return done(new JsonWebTokenError('clockTimestamp must be a number')); + } -/** Used as references for various `Number` constants. */ -var INFINITY = 1 / 0, - MAX_INTEGER = 1.7976931348623157e+308, - NAN = 0 / 0; + if (options.nonce !== undefined && (typeof options.nonce !== 'string' || options.nonce.trim() === '')) { + return done(new JsonWebTokenError('nonce must be a non-empty string')); + } -/** `Object#toString` result references. */ -var symbolTag = '[object Symbol]'; + var clockTimestamp = options.clockTimestamp || Math.floor(Date.now() / 1000); -/** Used to match leading and trailing whitespace. */ -var reTrim = /^\s+|\s+$/g; + if (!jwtString){ + return done(new JsonWebTokenError('jwt must be provided')); + } -/** Used to detect bad signed hexadecimal string values. */ -var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; + if (typeof jwtString !== 'string') { + return done(new JsonWebTokenError('jwt must be a string')); + } -/** Used to detect binary string values. */ -var reIsBinary = /^0b[01]+$/i; + var parts = jwtString.split('.'); -/** Used to detect octal string values. */ -var reIsOctal = /^0o[0-7]+$/i; + if (parts.length !== 3){ + return done(new JsonWebTokenError('jwt malformed')); + } -/** Built-in method references without a dependency on `root`. */ -var freeParseInt = parseInt; + var decodedToken; -/** Used for built-in method references. */ -var objectProto = Object.prototype; + try { + decodedToken = decode(jwtString, { complete: true }); + } catch(err) { + return done(err); + } -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var objectToString = objectProto.toString; + if (!decodedToken) { + return done(new JsonWebTokenError('invalid token')); + } -/** - * Creates a function that invokes `func`, with the `this` binding and arguments - * of the created function, while it's called less than `n` times. Subsequent - * calls to the created function return the result of the last `func` invocation. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Function - * @param {number} n The number of calls at which `func` is no longer invoked. - * @param {Function} func The function to restrict. - * @returns {Function} Returns the new restricted function. - * @example - * - * jQuery(element).on('click', _.before(5, addContactToList)); - * // => Allows adding up to 4 contacts to the list. - */ -function before(n, func) { - var result; - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); + var header = decodedToken.header; + var getSecret; + + if(typeof secretOrPublicKey === 'function') { + if(!callback) { + return done(new JsonWebTokenError('verify must be called asynchronous if secret or public key is provided as a callback')); + } + + getSecret = secretOrPublicKey; } - n = toInteger(n); - return function() { - if (--n > 0) { - result = func.apply(this, arguments); + else { + getSecret = function(header, secretCallback) { + return secretCallback(null, secretOrPublicKey); + }; + } + + return getSecret(header, function(err, secretOrPublicKey) { + if(err) { + return done(new JsonWebTokenError('error in secret or public key callback: ' + err.message)); } - if (n <= 1) { - func = undefined; + + var hasSignature = parts[2].trim() !== ''; + + if (!hasSignature && secretOrPublicKey){ + return done(new JsonWebTokenError('jwt signature is required')); } - return result; - }; -} -/** - * Creates a function that is restricted to invoking `func` once. Repeat calls - * to the function return the value of the first invocation. The `func` is - * invoked with the `this` binding and arguments of the created function. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to restrict. - * @returns {Function} Returns the new restricted function. - * @example - * - * var initialize = _.once(createApplication); - * initialize(); - * initialize(); - * // => `createApplication` is invoked once - */ -function once(func) { - return before(2, func); -} + if (hasSignature && !secretOrPublicKey) { + return done(new JsonWebTokenError('secret or public key must be provided')); + } -/** - * Checks if `value` is the - * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) - * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false - */ -function isObject(value) { - var type = typeof value; - return !!value && (type == 'object' || type == 'function'); -} + if (!hasSignature && !options.algorithms) { + options.algorithms = ['none']; + } -/** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ -function isObjectLike(value) { - return !!value && typeof value == 'object'; -} + if (!options.algorithms) { + options.algorithms = ~secretOrPublicKey.toString().indexOf('BEGIN CERTIFICATE') || + ~secretOrPublicKey.toString().indexOf('BEGIN PUBLIC KEY') ? PUB_KEY_ALGS : + ~secretOrPublicKey.toString().indexOf('BEGIN RSA PUBLIC KEY') ? RSA_KEY_ALGS : HS_ALGS; -/** - * Checks if `value` is classified as a `Symbol` primitive or object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. - * @example - * - * _.isSymbol(Symbol.iterator); - * // => true - * - * _.isSymbol('abc'); - * // => false - */ -function isSymbol(value) { - return typeof value == 'symbol' || - (isObjectLike(value) && objectToString.call(value) == symbolTag); -} + } -/** - * Converts `value` to a finite number. - * - * @static - * @memberOf _ - * @since 4.12.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted number. - * @example - * - * _.toFinite(3.2); - * // => 3.2 - * - * _.toFinite(Number.MIN_VALUE); - * // => 5e-324 - * - * _.toFinite(Infinity); - * // => 1.7976931348623157e+308 - * - * _.toFinite('3.2'); - * // => 3.2 - */ -function toFinite(value) { - if (!value) { - return value === 0 ? value : 0; - } - value = toNumber(value); - if (value === INFINITY || value === -INFINITY) { - var sign = (value < 0 ? -1 : 1); - return sign * MAX_INTEGER; - } - return value === value ? value : 0; -} + if (!~options.algorithms.indexOf(decodedToken.header.alg)) { + return done(new JsonWebTokenError('invalid algorithm')); + } -/** - * Converts `value` to an integer. - * - * **Note:** This method is loosely based on - * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted integer. - * @example - * - * _.toInteger(3.2); - * // => 3 - * - * _.toInteger(Number.MIN_VALUE); - * // => 0 - * - * _.toInteger(Infinity); - * // => 1.7976931348623157e+308 - * - * _.toInteger('3.2'); - * // => 3 - */ -function toInteger(value) { - var result = toFinite(value), - remainder = result % 1; + var valid; + + try { + valid = jws.verify(jwtString, decodedToken.header.alg, secretOrPublicKey); + } catch (e) { + return done(e); + } + + if (!valid) { + return done(new JsonWebTokenError('invalid signature')); + } + + var payload = decodedToken.payload; + + if (typeof payload.nbf !== 'undefined' && !options.ignoreNotBefore) { + if (typeof payload.nbf !== 'number') { + return done(new JsonWebTokenError('invalid nbf value')); + } + if (payload.nbf > clockTimestamp + (options.clockTolerance || 0)) { + return done(new NotBeforeError('jwt not active', new Date(payload.nbf * 1000))); + } + } + + if (typeof payload.exp !== 'undefined' && !options.ignoreExpiration) { + if (typeof payload.exp !== 'number') { + return done(new JsonWebTokenError('invalid exp value')); + } + if (clockTimestamp >= payload.exp + (options.clockTolerance || 0)) { + return done(new TokenExpiredError('jwt expired', new Date(payload.exp * 1000))); + } + } - return result === result ? (remainder ? result - remainder : result) : 0; -} + if (options.audience) { + var audiences = Array.isArray(options.audience) ? options.audience : [options.audience]; + var target = Array.isArray(payload.aud) ? payload.aud : [payload.aud]; -/** - * Converts `value` to a number. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to process. - * @returns {number} Returns the number. - * @example - * - * _.toNumber(3.2); - * // => 3.2 - * - * _.toNumber(Number.MIN_VALUE); - * // => 5e-324 - * - * _.toNumber(Infinity); - * // => Infinity - * - * _.toNumber('3.2'); - * // => 3.2 - */ -function toNumber(value) { - if (typeof value == 'number') { - return value; - } - if (isSymbol(value)) { - return NAN; - } - if (isObject(value)) { - var other = typeof value.valueOf == 'function' ? value.valueOf() : value; - value = isObject(other) ? (other + '') : other; - } - if (typeof value != 'string') { - return value === 0 ? value : +value; - } - value = value.replace(reTrim, ''); - var isBinary = reIsBinary.test(value); - return (isBinary || reIsOctal.test(value)) - ? freeParseInt(value.slice(2), isBinary ? 2 : 8) - : (reIsBadHex.test(value) ? NAN : +value); -} + var match = target.some(function (targetAudience) { + return audiences.some(function (audience) { + return audience instanceof RegExp ? audience.test(targetAudience) : audience === targetAudience; + }); + }); -module.exports = once; + if (!match) { + return done(new JsonWebTokenError('jwt audience invalid. expected: ' + audiences.join(' or '))); + } + } + if (options.issuer) { + var invalid_issuer = + (typeof options.issuer === 'string' && payload.iss !== options.issuer) || + (Array.isArray(options.issuer) && options.issuer.indexOf(payload.iss) === -1); -/***/ }), + if (invalid_issuer) { + return done(new JsonWebTokenError('jwt issuer invalid. expected: ' + options.issuer)); + } + } -/***/ 90250: -/***/ (function(module, exports, __nccwpck_require__) { + if (options.subject) { + if (payload.sub !== options.subject) { + return done(new JsonWebTokenError('jwt subject invalid. expected: ' + options.subject)); + } + } -/* module decorator */ module = __nccwpck_require__.nmd(module); -/** - * @license - * Lodash - * Copyright OpenJS Foundation and other contributors - * Released under MIT license - * Based on Underscore.js 1.8.3 - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - */ -;(function() { + if (options.jwtid) { + if (payload.jti !== options.jwtid) { + return done(new JsonWebTokenError('jwt jwtid invalid. expected: ' + options.jwtid)); + } + } - /** Used as a safe reference for `undefined` in pre-ES5 environments. */ - var undefined; + if (options.nonce) { + if (payload.nonce !== options.nonce) { + return done(new JsonWebTokenError('jwt nonce invalid. expected: ' + options.nonce)); + } + } - /** Used as the semantic version number. */ - var VERSION = '4.17.21'; + if (options.maxAge) { + if (typeof payload.iat !== 'number') { + return done(new JsonWebTokenError('iat required when maxAge is specified')); + } - /** Used as the size to enable large array optimizations. */ - var LARGE_ARRAY_SIZE = 200; + var maxAgeTimestamp = timespan(options.maxAge, payload.iat); + if (typeof maxAgeTimestamp === 'undefined') { + return done(new JsonWebTokenError('"maxAge" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60')); + } + if (clockTimestamp >= maxAgeTimestamp + (options.clockTolerance || 0)) { + return done(new TokenExpiredError('maxAge exceeded', new Date(maxAgeTimestamp * 1000))); + } + } - /** Error message constants. */ - var CORE_ERROR_TEXT = 'Unsupported core-js use. Try https://npms.io/search?q=ponyfill.', - FUNC_ERROR_TEXT = 'Expected a function', - INVALID_TEMPL_VAR_ERROR_TEXT = 'Invalid `variable` option passed into `_.template`'; + if (options.complete === true) { + var signature = decodedToken.signature; - /** Used to stand-in for `undefined` hash values. */ - var HASH_UNDEFINED = '__lodash_hash_undefined__'; + return done(null, { + header: header, + payload: payload, + signature: signature + }); + } - /** Used as the maximum memoize cache size. */ - var MAX_MEMOIZE_SIZE = 500; + return done(null, payload); + }); +}; - /** Used as the internal argument placeholder. */ - var PLACEHOLDER = '__lodash_placeholder__'; - /** Used to compose bitmasks for cloning. */ - var CLONE_DEEP_FLAG = 1, - CLONE_FLAT_FLAG = 2, - CLONE_SYMBOLS_FLAG = 4; +/***/ }), - /** Used to compose bitmasks for value comparisons. */ - var COMPARE_PARTIAL_FLAG = 1, - COMPARE_UNORDERED_FLAG = 2; +/***/ 96010: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /** Used to compose bitmasks for function metadata. */ - var WRAP_BIND_FLAG = 1, - WRAP_BIND_KEY_FLAG = 2, - WRAP_CURRY_BOUND_FLAG = 4, - WRAP_CURRY_FLAG = 8, - WRAP_CURRY_RIGHT_FLAG = 16, - WRAP_PARTIAL_FLAG = 32, - WRAP_PARTIAL_RIGHT_FLAG = 64, - WRAP_ARY_FLAG = 128, - WRAP_REARG_FLAG = 256, - WRAP_FLIP_FLAG = 512; +var bufferEqual = __nccwpck_require__(9239); +var Buffer = (__nccwpck_require__(21867).Buffer); +var crypto = __nccwpck_require__(6113); +var formatEcdsa = __nccwpck_require__(11728); +var util = __nccwpck_require__(73837); - /** Used as default options for `_.truncate`. */ - var DEFAULT_TRUNC_LENGTH = 30, - DEFAULT_TRUNC_OMISSION = '...'; +var MSG_INVALID_ALGORITHM = '"%s" is not a valid algorithm.\n Supported algorithms are:\n "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".' +var MSG_INVALID_SECRET = 'secret must be a string or buffer'; +var MSG_INVALID_VERIFIER_KEY = 'key must be a string or a buffer'; +var MSG_INVALID_SIGNER_KEY = 'key must be a string, a buffer or an object'; - /** Used to detect hot functions by number of calls within a span of milliseconds. */ - var HOT_COUNT = 800, - HOT_SPAN = 16; +var supportsKeyObjects = typeof crypto.createPublicKey === 'function'; +if (supportsKeyObjects) { + MSG_INVALID_VERIFIER_KEY += ' or a KeyObject'; + MSG_INVALID_SECRET += 'or a KeyObject'; +} - /** Used to indicate the type of lazy iteratees. */ - var LAZY_FILTER_FLAG = 1, - LAZY_MAP_FLAG = 2, - LAZY_WHILE_FLAG = 3; +function checkIsPublicKey(key) { + if (Buffer.isBuffer(key)) { + return; + } - /** Used as references for various `Number` constants. */ - var INFINITY = 1 / 0, - MAX_SAFE_INTEGER = 9007199254740991, - MAX_INTEGER = 1.7976931348623157e+308, - NAN = 0 / 0; + if (typeof key === 'string') { + return; + } - /** Used as references for the maximum length and index of an array. */ - var MAX_ARRAY_LENGTH = 4294967295, - MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1, - HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1; + if (!supportsKeyObjects) { + throw typeError(MSG_INVALID_VERIFIER_KEY); + } - /** Used to associate wrap methods with their bit flags. */ - var wrapFlags = [ - ['ary', WRAP_ARY_FLAG], - ['bind', WRAP_BIND_FLAG], - ['bindKey', WRAP_BIND_KEY_FLAG], - ['curry', WRAP_CURRY_FLAG], - ['curryRight', WRAP_CURRY_RIGHT_FLAG], - ['flip', WRAP_FLIP_FLAG], - ['partial', WRAP_PARTIAL_FLAG], - ['partialRight', WRAP_PARTIAL_RIGHT_FLAG], - ['rearg', WRAP_REARG_FLAG] - ]; + if (typeof key !== 'object') { + throw typeError(MSG_INVALID_VERIFIER_KEY); + } - /** `Object#toString` result references. */ - var argsTag = '[object Arguments]', - arrayTag = '[object Array]', - asyncTag = '[object AsyncFunction]', - boolTag = '[object Boolean]', - dateTag = '[object Date]', - domExcTag = '[object DOMException]', - errorTag = '[object Error]', - funcTag = '[object Function]', - genTag = '[object GeneratorFunction]', - mapTag = '[object Map]', - numberTag = '[object Number]', - nullTag = '[object Null]', - objectTag = '[object Object]', - promiseTag = '[object Promise]', - proxyTag = '[object Proxy]', - regexpTag = '[object RegExp]', - setTag = '[object Set]', - stringTag = '[object String]', - symbolTag = '[object Symbol]', - undefinedTag = '[object Undefined]', - weakMapTag = '[object WeakMap]', - weakSetTag = '[object WeakSet]'; + if (typeof key.type !== 'string') { + throw typeError(MSG_INVALID_VERIFIER_KEY); + } - var arrayBufferTag = '[object ArrayBuffer]', - dataViewTag = '[object DataView]', - float32Tag = '[object Float32Array]', - float64Tag = '[object Float64Array]', - int8Tag = '[object Int8Array]', - int16Tag = '[object Int16Array]', - int32Tag = '[object Int32Array]', - uint8Tag = '[object Uint8Array]', - uint8ClampedTag = '[object Uint8ClampedArray]', - uint16Tag = '[object Uint16Array]', - uint32Tag = '[object Uint32Array]'; + if (typeof key.asymmetricKeyType !== 'string') { + throw typeError(MSG_INVALID_VERIFIER_KEY); + } - /** Used to match empty string literals in compiled template source. */ - var reEmptyStringLeading = /\b__p \+= '';/g, - reEmptyStringMiddle = /\b(__p \+=) '' \+/g, - reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; + if (typeof key.export !== 'function') { + throw typeError(MSG_INVALID_VERIFIER_KEY); + } +}; - /** Used to match HTML entities and HTML characters. */ - var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g, - reUnescapedHtml = /[&<>"']/g, - reHasEscapedHtml = RegExp(reEscapedHtml.source), - reHasUnescapedHtml = RegExp(reUnescapedHtml.source); +function checkIsPrivateKey(key) { + if (Buffer.isBuffer(key)) { + return; + } - /** Used to match template delimiters. */ - var reEscape = /<%-([\s\S]+?)%>/g, - reEvaluate = /<%([\s\S]+?)%>/g, - reInterpolate = /<%=([\s\S]+?)%>/g; + if (typeof key === 'string') { + return; + } - /** Used to match property names within property paths. */ - var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, - reIsPlainProp = /^\w*$/, - rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; + if (typeof key === 'object') { + return; + } - /** - * Used to match `RegExp` - * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). - */ - var reRegExpChar = /[\\^$.*+?()[\]{}|]/g, - reHasRegExpChar = RegExp(reRegExpChar.source); + throw typeError(MSG_INVALID_SIGNER_KEY); +}; - /** Used to match leading whitespace. */ - var reTrimStart = /^\s+/; +function checkIsSecretKey(key) { + if (Buffer.isBuffer(key)) { + return; + } - /** Used to match a single whitespace character. */ - var reWhitespace = /\s/; + if (typeof key === 'string') { + return key; + } - /** Used to match wrap detail comments. */ - var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/, - reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/, - reSplitDetails = /,? & /; + if (!supportsKeyObjects) { + throw typeError(MSG_INVALID_SECRET); + } - /** Used to match words composed of alphanumeric characters. */ - var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g; + if (typeof key !== 'object') { + throw typeError(MSG_INVALID_SECRET); + } - /** - * Used to validate the `validate` option in `_.template` variable. - * - * Forbids characters which could potentially change the meaning of the function argument definition: - * - "()," (modification of function parameters) - * - "=" (default value) - * - "[]{}" (destructuring of function parameters) - * - "/" (beginning of a comment) - * - whitespace - */ - var reForbiddenIdentifierChars = /[()=,{}\[\]\/\s]/; + if (key.type !== 'secret') { + throw typeError(MSG_INVALID_SECRET); + } - /** Used to match backslashes in property paths. */ - var reEscapeChar = /\\(\\)?/g; + if (typeof key.export !== 'function') { + throw typeError(MSG_INVALID_SECRET); + } +} - /** - * Used to match - * [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components). - */ - var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; +function fromBase64(base64) { + return base64 + .replace(/=/g, '') + .replace(/\+/g, '-') + .replace(/\//g, '_'); +} - /** Used to match `RegExp` flags from their coerced string values. */ - var reFlags = /\w*$/; +function toBase64(base64url) { + base64url = base64url.toString(); - /** Used to detect bad signed hexadecimal string values. */ - var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; + var padding = 4 - base64url.length % 4; + if (padding !== 4) { + for (var i = 0; i < padding; ++i) { + base64url += '='; + } + } - /** Used to detect binary string values. */ - var reIsBinary = /^0b[01]+$/i; + return base64url + .replace(/\-/g, '+') + .replace(/_/g, '/'); +} - /** Used to detect host constructors (Safari). */ - var reIsHostCtor = /^\[object .+?Constructor\]$/; +function typeError(template) { + var args = [].slice.call(arguments, 1); + var errMsg = util.format.bind(util, template).apply(null, args); + return new TypeError(errMsg); +} - /** Used to detect octal string values. */ - var reIsOctal = /^0o[0-7]+$/i; +function bufferOrString(obj) { + return Buffer.isBuffer(obj) || typeof obj === 'string'; +} - /** Used to detect unsigned integer values. */ - var reIsUint = /^(?:0|[1-9]\d*)$/; +function normalizeInput(thing) { + if (!bufferOrString(thing)) + thing = JSON.stringify(thing); + return thing; +} - /** Used to match Latin Unicode letters (excluding mathematical operators). */ - var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g; +function createHmacSigner(bits) { + return function sign(thing, secret) { + checkIsSecretKey(secret); + thing = normalizeInput(thing); + var hmac = crypto.createHmac('sha' + bits, secret); + var sig = (hmac.update(thing), hmac.digest('base64')) + return fromBase64(sig); + } +} - /** Used to ensure capturing order of template delimiters. */ - var reNoMatch = /($^)/; +function createHmacVerifier(bits) { + return function verify(thing, signature, secret) { + var computedSig = createHmacSigner(bits)(thing, secret); + return bufferEqual(Buffer.from(signature), Buffer.from(computedSig)); + } +} - /** Used to match unescaped characters in compiled string literals. */ - var reUnescapedString = /['\n\r\u2028\u2029\\]/g; +function createKeySigner(bits) { + return function sign(thing, privateKey) { + checkIsPrivateKey(privateKey); + thing = normalizeInput(thing); + // Even though we are specifying "RSA" here, this works with ECDSA + // keys as well. + var signer = crypto.createSign('RSA-SHA' + bits); + var sig = (signer.update(thing), signer.sign(privateKey, 'base64')); + return fromBase64(sig); + } +} - /** Used to compose unicode character classes. */ - var rsAstralRange = '\\ud800-\\udfff', - rsComboMarksRange = '\\u0300-\\u036f', - reComboHalfMarksRange = '\\ufe20-\\ufe2f', - rsComboSymbolsRange = '\\u20d0-\\u20ff', - rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, - rsDingbatRange = '\\u2700-\\u27bf', - rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff', - rsMathOpRange = '\\xac\\xb1\\xd7\\xf7', - rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf', - rsPunctuationRange = '\\u2000-\\u206f', - rsSpaceRange = ' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000', - rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde', - rsVarRange = '\\ufe0e\\ufe0f', - rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange; +function createKeyVerifier(bits) { + return function verify(thing, signature, publicKey) { + checkIsPublicKey(publicKey); + thing = normalizeInput(thing); + signature = toBase64(signature); + var verifier = crypto.createVerify('RSA-SHA' + bits); + verifier.update(thing); + return verifier.verify(publicKey, signature, 'base64'); + } +} - /** Used to compose unicode capture groups. */ - var rsApos = "['\u2019]", - rsAstral = '[' + rsAstralRange + ']', - rsBreak = '[' + rsBreakRange + ']', - rsCombo = '[' + rsComboRange + ']', - rsDigits = '\\d+', - rsDingbat = '[' + rsDingbatRange + ']', - rsLower = '[' + rsLowerRange + ']', - rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']', - rsFitz = '\\ud83c[\\udffb-\\udfff]', - rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', - rsNonAstral = '[^' + rsAstralRange + ']', - rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', - rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', - rsUpper = '[' + rsUpperRange + ']', - rsZWJ = '\\u200d'; +function createPSSKeySigner(bits) { + return function sign(thing, privateKey) { + checkIsPrivateKey(privateKey); + thing = normalizeInput(thing); + var signer = crypto.createSign('RSA-SHA' + bits); + var sig = (signer.update(thing), signer.sign({ + key: privateKey, + padding: crypto.constants.RSA_PKCS1_PSS_PADDING, + saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST + }, 'base64')); + return fromBase64(sig); + } +} - /** Used to compose unicode regexes. */ - var rsMiscLower = '(?:' + rsLower + '|' + rsMisc + ')', - rsMiscUpper = '(?:' + rsUpper + '|' + rsMisc + ')', - rsOptContrLower = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?', - rsOptContrUpper = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?', - reOptMod = rsModifier + '?', - rsOptVar = '[' + rsVarRange + ']?', - rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', - rsOrdLower = '\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])', - rsOrdUpper = '\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])', - rsSeq = rsOptVar + reOptMod + rsOptJoin, - rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq, - rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; +function createPSSKeyVerifier(bits) { + return function verify(thing, signature, publicKey) { + checkIsPublicKey(publicKey); + thing = normalizeInput(thing); + signature = toBase64(signature); + var verifier = crypto.createVerify('RSA-SHA' + bits); + verifier.update(thing); + return verifier.verify({ + key: publicKey, + padding: crypto.constants.RSA_PKCS1_PSS_PADDING, + saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST + }, signature, 'base64'); + } +} + +function createECDSASigner(bits) { + var inner = createKeySigner(bits); + return function sign() { + var signature = inner.apply(null, arguments); + signature = formatEcdsa.derToJose(signature, 'ES' + bits); + return signature; + }; +} + +function createECDSAVerifer(bits) { + var inner = createKeyVerifier(bits); + return function verify(thing, signature, publicKey) { + signature = formatEcdsa.joseToDer(signature, 'ES' + bits).toString('base64'); + var result = inner(thing, signature, publicKey); + return result; + }; +} - /** Used to match apostrophes. */ - var reApos = RegExp(rsApos, 'g'); +function createNoneSigner() { + return function sign() { + return ''; + } +} - /** - * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and - * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols). - */ - var reComboMark = RegExp(rsCombo, 'g'); +function createNoneVerifier() { + return function verify(thing, signature) { + return signature === ''; + } +} - /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ - var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); +module.exports = function jwa(algorithm) { + var signerFactories = { + hs: createHmacSigner, + rs: createKeySigner, + ps: createPSSKeySigner, + es: createECDSASigner, + none: createNoneSigner, + } + var verifierFactories = { + hs: createHmacVerifier, + rs: createKeyVerifier, + ps: createPSSKeyVerifier, + es: createECDSAVerifer, + none: createNoneVerifier, + } + var match = algorithm.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/i); + if (!match) + throw typeError(MSG_INVALID_ALGORITHM, algorithm); + var algo = (match[1] || match[3]).toLowerCase(); + var bits = match[2]; - /** Used to match complex or compound words. */ - var reUnicodeWord = RegExp([ - rsUpper + '?' + rsLower + '+' + rsOptContrLower + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')', - rsMiscUpper + '+' + rsOptContrUpper + '(?=' + [rsBreak, rsUpper + rsMiscLower, '$'].join('|') + ')', - rsUpper + '?' + rsMiscLower + '+' + rsOptContrLower, - rsUpper + '+' + rsOptContrUpper, - rsOrdUpper, - rsOrdLower, - rsDigits, - rsEmoji - ].join('|'), 'g'); + return { + sign: signerFactories[algo](bits), + verify: verifierFactories[algo](bits), + } +}; - /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ - var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']'); - /** Used to detect strings that need a more robust regexp to match words. */ - var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/; +/***/ }), - /** Used to assign default `context` object properties. */ - var contextProps = [ - 'Array', 'Buffer', 'DataView', 'Date', 'Error', 'Float32Array', 'Float64Array', - 'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Map', 'Math', 'Object', - 'Promise', 'RegExp', 'Set', 'String', 'Symbol', 'TypeError', 'Uint8Array', - 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap', - '_', 'clearTimeout', 'isFinite', 'parseInt', 'setTimeout' - ]; +/***/ 4636: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - /** Used to make template sourceURLs easier to identify. */ - var templateCounter = -1; +/*global exports*/ +var SignStream = __nccwpck_require__(73334); +var VerifyStream = __nccwpck_require__(5522); - /** Used to identify `toStringTag` values of typed arrays. */ - var typedArrayTags = {}; - typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = - typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = - typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = - typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = - typedArrayTags[uint32Tag] = true; - typedArrayTags[argsTag] = typedArrayTags[arrayTag] = - typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = - typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = - typedArrayTags[errorTag] = typedArrayTags[funcTag] = - typedArrayTags[mapTag] = typedArrayTags[numberTag] = - typedArrayTags[objectTag] = typedArrayTags[regexpTag] = - typedArrayTags[setTag] = typedArrayTags[stringTag] = - typedArrayTags[weakMapTag] = false; +var ALGORITHMS = [ + 'HS256', 'HS384', 'HS512', + 'RS256', 'RS384', 'RS512', + 'PS256', 'PS384', 'PS512', + 'ES256', 'ES384', 'ES512' +]; - /** Used to identify `toStringTag` values supported by `_.clone`. */ - var cloneableTags = {}; - cloneableTags[argsTag] = cloneableTags[arrayTag] = - cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = - cloneableTags[boolTag] = cloneableTags[dateTag] = - cloneableTags[float32Tag] = cloneableTags[float64Tag] = - cloneableTags[int8Tag] = cloneableTags[int16Tag] = - cloneableTags[int32Tag] = cloneableTags[mapTag] = - cloneableTags[numberTag] = cloneableTags[objectTag] = - cloneableTags[regexpTag] = cloneableTags[setTag] = - cloneableTags[stringTag] = cloneableTags[symbolTag] = - cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = - cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; - cloneableTags[errorTag] = cloneableTags[funcTag] = - cloneableTags[weakMapTag] = false; +exports.ALGORITHMS = ALGORITHMS; +exports.sign = SignStream.sign; +exports.verify = VerifyStream.verify; +exports.decode = VerifyStream.decode; +exports.isValid = VerifyStream.isValid; +exports.createSign = function createSign(opts) { + return new SignStream(opts); +}; +exports.createVerify = function createVerify(opts) { + return new VerifyStream(opts); +}; - /** Used to map Latin Unicode letters to basic Latin letters. */ - var deburredLetters = { - // Latin-1 Supplement block. - '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A', - '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a', - '\xc7': 'C', '\xe7': 'c', - '\xd0': 'D', '\xf0': 'd', - '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E', - '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e', - '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I', - '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i', - '\xd1': 'N', '\xf1': 'n', - '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O', - '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o', - '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U', - '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u', - '\xdd': 'Y', '\xfd': 'y', '\xff': 'y', - '\xc6': 'Ae', '\xe6': 'ae', - '\xde': 'Th', '\xfe': 'th', - '\xdf': 'ss', - // Latin Extended-A block. - '\u0100': 'A', '\u0102': 'A', '\u0104': 'A', - '\u0101': 'a', '\u0103': 'a', '\u0105': 'a', - '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C', - '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c', - '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd', - '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E', - '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e', - '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G', - '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g', - '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h', - '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I', - '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i', - '\u0134': 'J', '\u0135': 'j', - '\u0136': 'K', '\u0137': 'k', '\u0138': 'k', - '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L', - '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l', - '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N', - '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n', - '\u014c': 'O', '\u014e': 'O', '\u0150': 'O', - '\u014d': 'o', '\u014f': 'o', '\u0151': 'o', - '\u0154': 'R', '\u0156': 'R', '\u0158': 'R', - '\u0155': 'r', '\u0157': 'r', '\u0159': 'r', - '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S', - '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's', - '\u0162': 'T', '\u0164': 'T', '\u0166': 'T', - '\u0163': 't', '\u0165': 't', '\u0167': 't', - '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U', - '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u', - '\u0174': 'W', '\u0175': 'w', - '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y', - '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z', - '\u017a': 'z', '\u017c': 'z', '\u017e': 'z', - '\u0132': 'IJ', '\u0133': 'ij', - '\u0152': 'Oe', '\u0153': 'oe', - '\u0149': "'n", '\u017f': 's' - }; - /** Used to map characters to HTML entities. */ - var htmlEscapes = { - '&': '&', - '<': '<', - '>': '>', - '"': '"', - "'": ''' - }; +/***/ }), - /** Used to map HTML entities to characters. */ - var htmlUnescapes = { - '&': '&', - '<': '<', - '>': '>', - '"': '"', - ''': "'" - }; +/***/ 61868: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /** Used to escape characters for inclusion in compiled string literals. */ - var stringEscapes = { - '\\': '\\', - "'": "'", - '\n': 'n', - '\r': 'r', - '\u2028': 'u2028', - '\u2029': 'u2029' - }; +/*global module, process*/ +var Buffer = (__nccwpck_require__(21867).Buffer); +var Stream = __nccwpck_require__(12781); +var util = __nccwpck_require__(73837); - /** Built-in method references without a dependency on `root`. */ - var freeParseFloat = parseFloat, - freeParseInt = parseInt; +function DataStream(data) { + this.buffer = null; + this.writable = true; + this.readable = true; - /** Detect free variable `global` from Node.js. */ - var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; + // No input + if (!data) { + this.buffer = Buffer.alloc(0); + return this; + } - /** Detect free variable `self`. */ - var freeSelf = typeof self == 'object' && self && self.Object === Object && self; + // Stream + if (typeof data.pipe === 'function') { + this.buffer = Buffer.alloc(0); + data.pipe(this); + return this; + } - /** Used as a reference to the global object. */ - var root = freeGlobal || freeSelf || Function('return this')(); + // Buffer or String + // or Object (assumedly a passworded key) + if (data.length || typeof data === 'object') { + this.buffer = data; + this.writable = false; + process.nextTick(function () { + this.emit('end', data); + this.readable = false; + this.emit('close'); + }.bind(this)); + return this; + } - /** Detect free variable `exports`. */ - var freeExports = true && exports && !exports.nodeType && exports; + throw new TypeError('Unexpected data type ('+ typeof data + ')'); +} +util.inherits(DataStream, Stream); - /** Detect free variable `module`. */ - var freeModule = freeExports && "object" == 'object' && module && !module.nodeType && module; +DataStream.prototype.write = function write(data) { + this.buffer = Buffer.concat([this.buffer, Buffer.from(data)]); + this.emit('data', data); +}; - /** Detect the popular CommonJS extension `module.exports`. */ - var moduleExports = freeModule && freeModule.exports === freeExports; +DataStream.prototype.end = function end(data) { + if (data) + this.write(data); + this.emit('end', data); + this.emit('close'); + this.writable = false; + this.readable = false; +}; - /** Detect free variable `process` from Node.js. */ - var freeProcess = moduleExports && freeGlobal.process; +module.exports = DataStream; - /** Used to access faster Node.js helpers. */ - var nodeUtil = (function() { - try { - // Use `util.types` for Node.js 10+. - var types = freeModule && freeModule.require && freeModule.require('util').types; - if (types) { - return types; - } +/***/ }), - // Legacy `process.binding('util')` for Node.js < 10. - return freeProcess && freeProcess.binding && freeProcess.binding('util'); - } catch (e) {} - }()); +/***/ 73334: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /* Node.js helper references. */ - var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer, - nodeIsDate = nodeUtil && nodeUtil.isDate, - nodeIsMap = nodeUtil && nodeUtil.isMap, - nodeIsRegExp = nodeUtil && nodeUtil.isRegExp, - nodeIsSet = nodeUtil && nodeUtil.isSet, - nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; +/*global module*/ +var Buffer = (__nccwpck_require__(21867).Buffer); +var DataStream = __nccwpck_require__(61868); +var jwa = __nccwpck_require__(96010); +var Stream = __nccwpck_require__(12781); +var toString = __nccwpck_require__(65292); +var util = __nccwpck_require__(73837); - /*--------------------------------------------------------------------------*/ +function base64url(string, encoding) { + return Buffer + .from(string, encoding) + .toString('base64') + .replace(/=/g, '') + .replace(/\+/g, '-') + .replace(/\//g, '_'); +} - /** - * A faster alternative to `Function#apply`, this function invokes `func` - * with the `this` binding of `thisArg` and the arguments of `args`. - * - * @private - * @param {Function} func The function to invoke. - * @param {*} thisArg The `this` binding of `func`. - * @param {Array} args The arguments to invoke `func` with. - * @returns {*} Returns the result of `func`. - */ - function apply(func, thisArg, args) { - switch (args.length) { - case 0: return func.call(thisArg); - case 1: return func.call(thisArg, args[0]); - case 2: return func.call(thisArg, args[0], args[1]); - case 3: return func.call(thisArg, args[0], args[1], args[2]); - } - return func.apply(thisArg, args); - } +function jwsSecuredInput(header, payload, encoding) { + encoding = encoding || 'utf8'; + var encodedHeader = base64url(toString(header), 'binary'); + var encodedPayload = base64url(toString(payload), encoding); + return util.format('%s.%s', encodedHeader, encodedPayload); +} - /** - * A specialized version of `baseAggregator` for arrays. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} setter The function to set `accumulator` values. - * @param {Function} iteratee The iteratee to transform keys. - * @param {Object} accumulator The initial aggregated object. - * @returns {Function} Returns `accumulator`. - */ - function arrayAggregator(array, setter, iteratee, accumulator) { - var index = -1, - length = array == null ? 0 : array.length; +function jwsSign(opts) { + var header = opts.header; + var payload = opts.payload; + var secretOrKey = opts.secret || opts.privateKey; + var encoding = opts.encoding; + var algo = jwa(header.alg); + var securedInput = jwsSecuredInput(header, payload, encoding); + var signature = algo.sign(securedInput, secretOrKey); + return util.format('%s.%s', securedInput, signature); +} - while (++index < length) { - var value = array[index]; - setter(accumulator, value, iteratee(value), array); - } - return accumulator; - } +function SignStream(opts) { + var secret = opts.secret||opts.privateKey||opts.key; + var secretStream = new DataStream(secret); + this.readable = true; + this.header = opts.header; + this.encoding = opts.encoding; + this.secret = this.privateKey = this.key = secretStream; + this.payload = new DataStream(opts.payload); + this.secret.once('close', function () { + if (!this.payload.writable && this.readable) + this.sign(); + }.bind(this)); - /** - * A specialized version of `_.forEach` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns `array`. - */ - function arrayEach(array, iteratee) { - var index = -1, - length = array == null ? 0 : array.length; + this.payload.once('close', function () { + if (!this.secret.writable && this.readable) + this.sign(); + }.bind(this)); +} +util.inherits(SignStream, Stream); - while (++index < length) { - if (iteratee(array[index], index, array) === false) { - break; - } - } - return array; +SignStream.prototype.sign = function sign() { + try { + var signature = jwsSign({ + header: this.header, + payload: this.payload.buffer, + secret: this.secret.buffer, + encoding: this.encoding + }); + this.emit('done', signature); + this.emit('data', signature); + this.emit('end'); + this.readable = false; + return signature; + } catch (e) { + this.readable = false; + this.emit('error', e); + this.emit('close'); } +}; - /** - * A specialized version of `_.forEachRight` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns `array`. - */ - function arrayEachRight(array, iteratee) { - var length = array == null ? 0 : array.length; +SignStream.sign = jwsSign; - while (length--) { - if (iteratee(array[length], length, array) === false) { - break; - } - } - return array; - } +module.exports = SignStream; - /** - * A specialized version of `_.every` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {boolean} Returns `true` if all elements pass the predicate check, - * else `false`. - */ - function arrayEvery(array, predicate) { - var index = -1, - length = array == null ? 0 : array.length; - while (++index < length) { - if (!predicate(array[index], index, array)) { - return false; - } - } - return true; - } +/***/ }), - /** - * A specialized version of `_.filter` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {Array} Returns the new filtered array. - */ - function arrayFilter(array, predicate) { - var index = -1, - length = array == null ? 0 : array.length, - resIndex = 0, - result = []; +/***/ 65292: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - while (++index < length) { - var value = array[index]; - if (predicate(value, index, array)) { - result[resIndex++] = value; - } - } - return result; - } +/*global module*/ +var Buffer = (__nccwpck_require__(14300).Buffer); - /** - * A specialized version of `_.includes` for arrays without support for - * specifying an index to search from. - * - * @private - * @param {Array} [array] The array to inspect. - * @param {*} target The value to search for. - * @returns {boolean} Returns `true` if `target` is found, else `false`. - */ - function arrayIncludes(array, value) { - var length = array == null ? 0 : array.length; - return !!length && baseIndexOf(array, value, 0) > -1; - } +module.exports = function toString(obj) { + if (typeof obj === 'string') + return obj; + if (typeof obj === 'number' || Buffer.isBuffer(obj)) + return obj.toString(); + return JSON.stringify(obj); +}; + + +/***/ }), + +/***/ 5522: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /** - * This function is like `arrayIncludes` except that it accepts a comparator. - * - * @private - * @param {Array} [array] The array to inspect. - * @param {*} target The value to search for. - * @param {Function} comparator The comparator invoked per element. - * @returns {boolean} Returns `true` if `target` is found, else `false`. - */ - function arrayIncludesWith(array, value, comparator) { - var index = -1, - length = array == null ? 0 : array.length; +/*global module*/ +var Buffer = (__nccwpck_require__(21867).Buffer); +var DataStream = __nccwpck_require__(61868); +var jwa = __nccwpck_require__(96010); +var Stream = __nccwpck_require__(12781); +var toString = __nccwpck_require__(65292); +var util = __nccwpck_require__(73837); +var JWS_REGEX = /^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/; - while (++index < length) { - if (comparator(value, array[index])) { - return true; - } - } - return false; - } +function isObject(thing) { + return Object.prototype.toString.call(thing) === '[object Object]'; +} - /** - * A specialized version of `_.map` for arrays without support for iteratee - * shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the new mapped array. - */ - function arrayMap(array, iteratee) { - var index = -1, - length = array == null ? 0 : array.length, - result = Array(length); +function safeJsonParse(thing) { + if (isObject(thing)) + return thing; + try { return JSON.parse(thing); } + catch (e) { return undefined; } +} - while (++index < length) { - result[index] = iteratee(array[index], index, array); - } - return result; - } +function headerFromJWS(jwsSig) { + var encodedHeader = jwsSig.split('.', 1)[0]; + return safeJsonParse(Buffer.from(encodedHeader, 'base64').toString('binary')); +} - /** - * Appends the elements of `values` to `array`. - * - * @private - * @param {Array} array The array to modify. - * @param {Array} values The values to append. - * @returns {Array} Returns `array`. - */ - function arrayPush(array, values) { - var index = -1, - length = values.length, - offset = array.length; +function securedInputFromJWS(jwsSig) { + return jwsSig.split('.', 2).join('.'); +} - while (++index < length) { - array[offset + index] = values[index]; - } - return array; - } +function signatureFromJWS(jwsSig) { + return jwsSig.split('.')[2]; +} - /** - * A specialized version of `_.reduce` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {*} [accumulator] The initial value. - * @param {boolean} [initAccum] Specify using the first element of `array` as - * the initial value. - * @returns {*} Returns the accumulated value. - */ - function arrayReduce(array, iteratee, accumulator, initAccum) { - var index = -1, - length = array == null ? 0 : array.length; +function payloadFromJWS(jwsSig, encoding) { + encoding = encoding || 'utf8'; + var payload = jwsSig.split('.')[1]; + return Buffer.from(payload, 'base64').toString(encoding); +} - if (initAccum && length) { - accumulator = array[++index]; - } - while (++index < length) { - accumulator = iteratee(accumulator, array[index], index, array); - } - return accumulator; - } +function isValidJws(string) { + return JWS_REGEX.test(string) && !!headerFromJWS(string); +} - /** - * A specialized version of `_.reduceRight` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {*} [accumulator] The initial value. - * @param {boolean} [initAccum] Specify using the last element of `array` as - * the initial value. - * @returns {*} Returns the accumulated value. - */ - function arrayReduceRight(array, iteratee, accumulator, initAccum) { - var length = array == null ? 0 : array.length; - if (initAccum && length) { - accumulator = array[--length]; - } - while (length--) { - accumulator = iteratee(accumulator, array[length], length, array); - } - return accumulator; +function jwsVerify(jwsSig, algorithm, secretOrKey) { + if (!algorithm) { + var err = new Error("Missing algorithm parameter for jws.verify"); + err.code = "MISSING_ALGORITHM"; + throw err; } + jwsSig = toString(jwsSig); + var signature = signatureFromJWS(jwsSig); + var securedInput = securedInputFromJWS(jwsSig); + var algo = jwa(algorithm); + return algo.verify(securedInput, signature, secretOrKey); +} - /** - * A specialized version of `_.some` for arrays without support for iteratee - * shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {boolean} Returns `true` if any element passes the predicate check, - * else `false`. - */ - function arraySome(array, predicate) { - var index = -1, - length = array == null ? 0 : array.length; +function jwsDecode(jwsSig, opts) { + opts = opts || {}; + jwsSig = toString(jwsSig); - while (++index < length) { - if (predicate(array[index], index, array)) { - return true; - } - } - return false; - } + if (!isValidJws(jwsSig)) + return null; - /** - * Gets the size of an ASCII `string`. - * - * @private - * @param {string} string The string inspect. - * @returns {number} Returns the string size. - */ - var asciiSize = baseProperty('length'); + var header = headerFromJWS(jwsSig); - /** - * Converts an ASCII `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ - function asciiToArray(string) { - return string.split(''); - } + if (!header) + return null; - /** - * Splits an ASCII `string` into an array of its words. - * - * @private - * @param {string} The string to inspect. - * @returns {Array} Returns the words of `string`. - */ - function asciiWords(string) { - return string.match(reAsciiWord) || []; - } + var payload = payloadFromJWS(jwsSig); + if (header.typ === 'JWT' || opts.json) + payload = JSON.parse(payload, opts.encoding); - /** - * The base implementation of methods like `_.findKey` and `_.findLastKey`, - * without support for iteratee shorthands, which iterates over `collection` - * using `eachFunc`. - * - * @private - * @param {Array|Object} collection The collection to inspect. - * @param {Function} predicate The function invoked per iteration. - * @param {Function} eachFunc The function to iterate over `collection`. - * @returns {*} Returns the found element or its key, else `undefined`. - */ - function baseFindKey(collection, predicate, eachFunc) { - var result; - eachFunc(collection, function(value, key, collection) { - if (predicate(value, key, collection)) { - result = key; - return false; - } - }); - return result; - } + return { + header: header, + payload: payload, + signature: signatureFromJWS(jwsSig) + }; +} - /** - * The base implementation of `_.findIndex` and `_.findLastIndex` without - * support for iteratee shorthands. - * - * @private - * @param {Array} array The array to inspect. - * @param {Function} predicate The function invoked per iteration. - * @param {number} fromIndex The index to search from. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function baseFindIndex(array, predicate, fromIndex, fromRight) { - var length = array.length, - index = fromIndex + (fromRight ? 1 : -1); +function VerifyStream(opts) { + opts = opts || {}; + var secretOrKey = opts.secret||opts.publicKey||opts.key; + var secretStream = new DataStream(secretOrKey); + this.readable = true; + this.algorithm = opts.algorithm; + this.encoding = opts.encoding; + this.secret = this.publicKey = this.key = secretStream; + this.signature = new DataStream(opts.signature); + this.secret.once('close', function () { + if (!this.signature.writable && this.readable) + this.verify(); + }.bind(this)); - while ((fromRight ? index-- : ++index < length)) { - if (predicate(array[index], index, array)) { - return index; - } - } - return -1; + this.signature.once('close', function () { + if (!this.secret.writable && this.readable) + this.verify(); + }.bind(this)); +} +util.inherits(VerifyStream, Stream); +VerifyStream.prototype.verify = function verify() { + try { + var valid = jwsVerify(this.signature.buffer, this.algorithm, this.key.buffer); + var obj = jwsDecode(this.signature.buffer, this.encoding); + this.emit('done', valid, obj); + this.emit('data', valid); + this.emit('end'); + this.readable = false; + return valid; + } catch (e) { + this.readable = false; + this.emit('error', e); + this.emit('close'); } +}; - /** - * The base implementation of `_.indexOf` without `fromIndex` bounds checks. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function baseIndexOf(array, value, fromIndex) { - return value === value - ? strictIndexOf(array, value, fromIndex) - : baseFindIndex(array, baseIsNaN, fromIndex); - } +VerifyStream.decode = jwsDecode; +VerifyStream.isValid = isValidJws; +VerifyStream.verify = jwsVerify; - /** - * This function is like `baseIndexOf` except that it accepts a comparator. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @param {Function} comparator The comparator invoked per element. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function baseIndexOfWith(array, value, fromIndex, comparator) { - var index = fromIndex - 1, - length = array.length; +module.exports = VerifyStream; - while (++index < length) { - if (comparator(array[index], value)) { - return index; - } - } - return -1; - } - /** - * The base implementation of `_.isNaN` without support for number objects. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. - */ - function baseIsNaN(value) { - return value !== value; - } +/***/ }), - /** - * The base implementation of `_.mean` and `_.meanBy` without support for - * iteratee shorthands. - * - * @private - * @param {Array} array The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {number} Returns the mean. - */ - function baseMean(array, iteratee) { - var length = array == null ? 0 : array.length; - return length ? (baseSum(array, iteratee) / length) : NAN; - } +/***/ 75978: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /** - * The base implementation of `_.property` without support for deep paths. - * - * @private - * @param {string} key The key of the property to get. - * @returns {Function} Returns the new accessor function. - */ - function baseProperty(key) { - return function(object) { - return object == null ? undefined : object[key]; - }; - } +"use strict"; - /** - * The base implementation of `_.propertyOf` without support for deep paths. - * - * @private - * @param {Object} object The object to query. - * @returns {Function} Returns the new accessor function. - */ - function basePropertyOf(object) { - return function(key) { - return object == null ? undefined : object[key]; - }; - } +const path = __nccwpck_require__(71017); +const fs = __nccwpck_require__(77758); +const stripBom = __nccwpck_require__(88551); +const parseJson = __nccwpck_require__(81680); +const pify = __nccwpck_require__(64810); - /** - * The base implementation of `_.reduce` and `_.reduceRight`, without support - * for iteratee shorthands, which iterates over `collection` using `eachFunc`. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {*} accumulator The initial value. - * @param {boolean} initAccum Specify using the first or last element of - * `collection` as the initial value. - * @param {Function} eachFunc The function to iterate over `collection`. - * @returns {*} Returns the accumulated value. - */ - function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { - eachFunc(collection, function(value, index, collection) { - accumulator = initAccum - ? (initAccum = false, value) - : iteratee(accumulator, value, index, collection); - }); - return accumulator; - } +const parse = (data, filePath, options = {}) => { + data = stripBom(data); - /** - * The base implementation of `_.sortBy` which uses `comparer` to define the - * sort order of `array` and replaces criteria objects with their corresponding - * values. - * - * @private - * @param {Array} array The array to sort. - * @param {Function} comparer The function to define sort order. - * @returns {Array} Returns `array`. - */ - function baseSortBy(array, comparer) { - var length = array.length; + if (typeof options.beforeParse === 'function') { + data = options.beforeParse(data); + } - array.sort(comparer); - while (length--) { - array[length] = array[length].value; - } - return array; - } + return parseJson(data, options.reviver, path.relative(process.cwd(), filePath)); +}; - /** - * The base implementation of `_.sum` and `_.sumBy` without support for - * iteratee shorthands. - * - * @private - * @param {Array} array The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {number} Returns the sum. - */ - function baseSum(array, iteratee) { - var result, - index = -1, - length = array.length; +const loadJsonFile = (filePath, options) => pify(fs.readFile)(filePath, 'utf8').then(data => parse(data, filePath, options)); - while (++index < length) { - var current = iteratee(array[index]); - if (current !== undefined) { - result = result === undefined ? current : (result + current); - } - } - return result; - } +module.exports = loadJsonFile; +// TODO: Remove this for the next major release +module.exports["default"] = loadJsonFile; +module.exports.sync = (filePath, options) => parse(fs.readFileSync(filePath, 'utf8'), filePath, options); - /** - * The base implementation of `_.times` without support for iteratee shorthands - * or max array length checks. - * - * @private - * @param {number} n The number of times to invoke `iteratee`. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the array of results. - */ - function baseTimes(n, iteratee) { - var index = -1, - result = Array(n); - while (++index < n) { - result[index] = iteratee(index); - } - return result; - } +/***/ }), - /** - * The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array - * of key-value pairs for `object` corresponding to the property names of `props`. - * - * @private - * @param {Object} object The object to query. - * @param {Array} props The property names to get values for. - * @returns {Object} Returns the key-value pairs. - */ - function baseToPairs(object, props) { - return arrayMap(props, function(key) { - return [key, object[key]]; - }); - } +/***/ 81680: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /** - * The base implementation of `_.trim`. - * - * @private - * @param {string} string The string to trim. - * @returns {string} Returns the trimmed string. - */ - function baseTrim(string) { - return string - ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, '') - : string; - } +"use strict"; - /** - * The base implementation of `_.unary` without support for storing metadata. - * - * @private - * @param {Function} func The function to cap arguments for. - * @returns {Function} Returns the new capped function. - */ - function baseUnary(func) { - return function(value) { - return func(value); - }; - } +const errorEx = __nccwpck_require__(23505); +const fallback = __nccwpck_require__(55586); + +const JSONError = errorEx('JSONError', { + fileName: errorEx.append('in %s') +}); - /** - * The base implementation of `_.values` and `_.valuesIn` which creates an - * array of `object` property values corresponding to the property names - * of `props`. - * - * @private - * @param {Object} object The object to query. - * @param {Array} props The property names to get values for. - * @returns {Object} Returns the array of property values. - */ - function baseValues(object, props) { - return arrayMap(props, function(key) { - return object[key]; - }); - } +module.exports = (input, reviver, filename) => { + if (typeof reviver === 'string') { + filename = reviver; + reviver = null; + } - /** - * Checks if a `cache` value for `key` exists. - * - * @private - * @param {Object} cache The cache to query. - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function cacheHas(cache, key) { - return cache.has(key); - } + try { + try { + return JSON.parse(input, reviver); + } catch (err) { + fallback(input, reviver); - /** - * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol - * that is not found in the character symbols. - * - * @private - * @param {Array} strSymbols The string symbols to inspect. - * @param {Array} chrSymbols The character symbols to find. - * @returns {number} Returns the index of the first unmatched string symbol. - */ - function charsStartIndex(strSymbols, chrSymbols) { - var index = -1, - length = strSymbols.length; + throw err; + } + } catch (err) { + err.message = err.message.replace(/\n/g, ''); - while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} - return index; - } + const jsonErr = new JSONError(err); + if (filename) { + jsonErr.fileName = filename; + } - /** - * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol - * that is not found in the character symbols. - * - * @private - * @param {Array} strSymbols The string symbols to inspect. - * @param {Array} chrSymbols The character symbols to find. - * @returns {number} Returns the index of the last unmatched string symbol. - */ - function charsEndIndex(strSymbols, chrSymbols) { - var index = strSymbols.length; + throw jsonErr; + } +}; - while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} - return index; - } - /** - * Gets the number of `placeholder` occurrences in `array`. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} placeholder The placeholder to search for. - * @returns {number} Returns the placeholder count. - */ - function countHolders(array, placeholder) { - var length = array.length, - result = 0; +/***/ }), - while (length--) { - if (array[length] === placeholder) { - ++result; - } - } - return result; - } +/***/ 11289: +/***/ ((module) => { - /** - * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A - * letters to basic Latin letters. - * - * @private - * @param {string} letter The matched letter to deburr. - * @returns {string} Returns the deburred letter. - */ - var deburrLetter = basePropertyOf(deburredLetters); +/** + * lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright jQuery Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ - /** - * Used by `_.escape` to convert characters to HTML entities. - * - * @private - * @param {string} chr The matched character to escape. - * @returns {string} Returns the escaped character. - */ - var escapeHtmlChar = basePropertyOf(htmlEscapes); +/** Used as references for various `Number` constants. */ +var MAX_SAFE_INTEGER = 9007199254740991; - /** - * Used by `_.template` to escape characters for inclusion in compiled string literals. - * - * @private - * @param {string} chr The matched character to escape. - * @returns {string} Returns the escaped character. - */ - function escapeStringChar(chr) { - return '\\' + stringEscapes[chr]; - } +/** `Object#toString` result references. */ +var argsTag = '[object Arguments]', + funcTag = '[object Function]', + genTag = '[object GeneratorFunction]'; - /** - * Gets the value at `key` of `object`. - * - * @private - * @param {Object} [object] The object to query. - * @param {string} key The key of the property to get. - * @returns {*} Returns the property value. - */ - function getValue(object, key) { - return object == null ? undefined : object[key]; - } +/** Used to detect unsigned integer values. */ +var reIsUint = /^(?:0|[1-9]\d*)$/; - /** - * Checks if `string` contains Unicode symbols. - * - * @private - * @param {string} string The string to inspect. - * @returns {boolean} Returns `true` if a symbol is found, else `false`. - */ - function hasUnicode(string) { - return reHasUnicode.test(string); +/** + * A faster alternative to `Function#apply`, this function invokes `func` + * with the `this` binding of `thisArg` and the arguments of `args`. + * + * @private + * @param {Function} func The function to invoke. + * @param {*} thisArg The `this` binding of `func`. + * @param {Array} args The arguments to invoke `func` with. + * @returns {*} Returns the result of `func`. + */ +function apply(func, thisArg, args) { + switch (args.length) { + case 0: return func.call(thisArg); + case 1: return func.call(thisArg, args[0]); + case 2: return func.call(thisArg, args[0], args[1]); + case 3: return func.call(thisArg, args[0], args[1], args[2]); } + return func.apply(thisArg, args); +} - /** - * Checks if `string` contains a word composed of Unicode symbols. - * - * @private - * @param {string} string The string to inspect. - * @returns {boolean} Returns `true` if a word is found, else `false`. - */ - function hasUnicodeWord(string) { - return reHasUnicodeWord.test(string); +/** + * The base implementation of `_.times` without support for iteratee shorthands + * or max array length checks. + * + * @private + * @param {number} n The number of times to invoke `iteratee`. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the array of results. + */ +function baseTimes(n, iteratee) { + var index = -1, + result = Array(n); + + while (++index < n) { + result[index] = iteratee(index); } + return result; +} - /** - * Converts `iterator` to an array. - * - * @private - * @param {Object} iterator The iterator to convert. - * @returns {Array} Returns the converted array. - */ - function iteratorToArray(iterator) { - var data, - result = []; +/** Used for built-in method references. */ +var objectProto = Object.prototype; - while (!(data = iterator.next()).done) { - result.push(data.value); - } - return result; - } +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; - /** - * Converts `map` to its key-value pairs. - * - * @private - * @param {Object} map The map to convert. - * @returns {Array} Returns the key-value pairs. - */ - function mapToArray(map) { - var index = -1, - result = Array(map.size); +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; - map.forEach(function(value, key) { - result[++index] = [key, value]; - }); - return result; - } +/** Built-in value references. */ +var propertyIsEnumerable = objectProto.propertyIsEnumerable; - /** - * Creates a unary function that invokes `func` with its argument transformed. - * - * @private - * @param {Function} func The function to wrap. - * @param {Function} transform The argument transform. - * @returns {Function} Returns the new function. - */ - function overArg(func, transform) { - return function(arg) { - return func(transform(arg)); - }; - } +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max; - /** - * Replaces all `placeholder` elements in `array` with an internal placeholder - * and returns an array of their indexes. - * - * @private - * @param {Array} array The array to modify. - * @param {*} placeholder The placeholder to replace. - * @returns {Array} Returns the new array of placeholder indexes. - */ - function replaceHolders(array, placeholder) { - var index = -1, - length = array.length, - resIndex = 0, - result = []; +/** + * Creates an array of the enumerable property names of the array-like `value`. + * + * @private + * @param {*} value The value to query. + * @param {boolean} inherited Specify returning inherited property names. + * @returns {Array} Returns the array of property names. + */ +function arrayLikeKeys(value, inherited) { + // Safari 8.1 makes `arguments.callee` enumerable in strict mode. + // Safari 9 makes `arguments.length` enumerable in strict mode. + var result = (isArray(value) || isArguments(value)) + ? baseTimes(value.length, String) + : []; - while (++index < length) { - var value = array[index]; - if (value === placeholder || value === PLACEHOLDER) { - array[index] = PLACEHOLDER; - result[resIndex++] = index; - } + var length = result.length, + skipIndexes = !!length; + + for (var key in value) { + if ((inherited || hasOwnProperty.call(value, key)) && + !(skipIndexes && (key == 'length' || isIndex(key, length)))) { + result.push(key); } - return result; } + return result; +} - /** - * Converts `set` to an array of its values. - * - * @private - * @param {Object} set The set to convert. - * @returns {Array} Returns the values. - */ - function setToArray(set) { - var index = -1, - result = Array(set.size); +/** + * Used by `_.defaults` to customize its `_.assignIn` use. + * + * @private + * @param {*} objValue The destination value. + * @param {*} srcValue The source value. + * @param {string} key The key of the property to assign. + * @param {Object} object The parent object of `objValue`. + * @returns {*} Returns the value to assign. + */ +function assignInDefaults(objValue, srcValue, key, object) { + if (objValue === undefined || + (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) { + return srcValue; + } + return objValue; +} - set.forEach(function(value) { - result[++index] = value; - }); - return result; +/** + * Assigns `value` to `key` of `object` if the existing value is not equivalent + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ +function assignValue(object, key, value) { + var objValue = object[key]; + if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || + (value === undefined && !(key in object))) { + object[key] = value; } +} - /** - * Converts `set` to its value-value pairs. - * - * @private - * @param {Object} set The set to convert. - * @returns {Array} Returns the value-value pairs. - */ - function setToPairs(set) { - var index = -1, - result = Array(set.size); +/** + * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ +function baseKeysIn(object) { + if (!isObject(object)) { + return nativeKeysIn(object); + } + var isProto = isPrototype(object), + result = []; - set.forEach(function(value) { - result[++index] = [value, value]; - }); - return result; + for (var key in object) { + if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { + result.push(key); + } } + return result; +} - /** - * A specialized version of `_.indexOf` which performs strict equality - * comparisons of values, i.e. `===`. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function strictIndexOf(array, value, fromIndex) { - var index = fromIndex - 1, - length = array.length; +/** + * The base implementation of `_.rest` which doesn't validate or coerce arguments. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. + */ +function baseRest(func, start) { + start = nativeMax(start === undefined ? (func.length - 1) : start, 0); + return function() { + var args = arguments, + index = -1, + length = nativeMax(args.length - start, 0), + array = Array(length); while (++index < length) { - if (array[index] === value) { - return index; - } + array[index] = args[start + index]; } - return -1; - } - - /** - * A specialized version of `_.lastIndexOf` which performs strict equality - * comparisons of values, i.e. `===`. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function strictLastIndexOf(array, value, fromIndex) { - var index = fromIndex + 1; - while (index--) { - if (array[index] === value) { - return index; - } + index = -1; + var otherArgs = Array(start + 1); + while (++index < start) { + otherArgs[index] = args[index]; } - return index; - } + otherArgs[start] = array; + return apply(func, this, otherArgs); + }; +} - /** - * Gets the number of symbols in `string`. - * - * @private - * @param {string} string The string to inspect. - * @returns {number} Returns the string size. - */ - function stringSize(string) { - return hasUnicode(string) - ? unicodeSize(string) - : asciiSize(string); - } +/** + * Copies properties of `source` to `object`. + * + * @private + * @param {Object} source The object to copy properties from. + * @param {Array} props The property identifiers to copy. + * @param {Object} [object={}] The object to copy properties to. + * @param {Function} [customizer] The function to customize copied values. + * @returns {Object} Returns `object`. + */ +function copyObject(source, props, object, customizer) { + object || (object = {}); - /** - * Converts `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ - function stringToArray(string) { - return hasUnicode(string) - ? unicodeToArray(string) - : asciiToArray(string); - } + var index = -1, + length = props.length; - /** - * Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace - * character of `string`. - * - * @private - * @param {string} string The string to inspect. - * @returns {number} Returns the index of the last non-whitespace character. - */ - function trimmedEndIndex(string) { - var index = string.length; + while (++index < length) { + var key = props[index]; - while (index-- && reWhitespace.test(string.charAt(index))) {} - return index; + var newValue = customizer + ? customizer(object[key], source[key], key, object, source) + : undefined; + + assignValue(object, key, newValue === undefined ? source[key] : newValue); } + return object; +} + +/** + * Creates a function like `_.assign`. + * + * @private + * @param {Function} assigner The function to assign values. + * @returns {Function} Returns the new assigner function. + */ +function createAssigner(assigner) { + return baseRest(function(object, sources) { + var index = -1, + length = sources.length, + customizer = length > 1 ? sources[length - 1] : undefined, + guard = length > 2 ? sources[2] : undefined; - /** - * Used by `_.unescape` to convert HTML entities to characters. - * - * @private - * @param {string} chr The matched character to unescape. - * @returns {string} Returns the unescaped character. - */ - var unescapeHtmlChar = basePropertyOf(htmlUnescapes); + customizer = (assigner.length > 3 && typeof customizer == 'function') + ? (length--, customizer) + : undefined; - /** - * Gets the size of a Unicode `string`. - * - * @private - * @param {string} string The string inspect. - * @returns {number} Returns the string size. - */ - function unicodeSize(string) { - var result = reUnicode.lastIndex = 0; - while (reUnicode.test(string)) { - ++result; + if (guard && isIterateeCall(sources[0], sources[1], guard)) { + customizer = length < 3 ? undefined : customizer; + length = 1; } - return result; - } + object = Object(object); + while (++index < length) { + var source = sources[index]; + if (source) { + assigner(object, source, index, customizer); + } + } + return object; + }); +} - /** - * Converts a Unicode `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ - function unicodeToArray(string) { - return string.match(reUnicode) || []; - } +/** + * Checks if `value` is a valid array-like index. + * + * @private + * @param {*} value The value to check. + * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. + * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + */ +function isIndex(value, length) { + length = length == null ? MAX_SAFE_INTEGER : length; + return !!length && + (typeof value == 'number' || reIsUint.test(value)) && + (value > -1 && value % 1 == 0 && value < length); +} - /** - * Splits a Unicode `string` into an array of its words. - * - * @private - * @param {string} The string to inspect. - * @returns {Array} Returns the words of `string`. - */ - function unicodeWords(string) { - return string.match(reUnicodeWord) || []; +/** + * Checks if the given arguments are from an iteratee call. + * + * @private + * @param {*} value The potential iteratee value argument. + * @param {*} index The potential iteratee index or key argument. + * @param {*} object The potential iteratee object argument. + * @returns {boolean} Returns `true` if the arguments are from an iteratee call, + * else `false`. + */ +function isIterateeCall(value, index, object) { + if (!isObject(object)) { + return false; + } + var type = typeof index; + if (type == 'number' + ? (isArrayLike(object) && isIndex(index, object.length)) + : (type == 'string' && index in object) + ) { + return eq(object[index], value); } + return false; +} - /*--------------------------------------------------------------------------*/ +/** + * Checks if `value` is likely a prototype object. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. + */ +function isPrototype(value) { + var Ctor = value && value.constructor, + proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; - /** - * Create a new pristine `lodash` function using the `context` object. - * - * @static - * @memberOf _ - * @since 1.1.0 - * @category Util - * @param {Object} [context=root] The context object. - * @returns {Function} Returns a new `lodash` function. - * @example - * - * _.mixin({ 'foo': _.constant('foo') }); - * - * var lodash = _.runInContext(); - * lodash.mixin({ 'bar': lodash.constant('bar') }); - * - * _.isFunction(_.foo); - * // => true - * _.isFunction(_.bar); - * // => false - * - * lodash.isFunction(lodash.foo); - * // => false - * lodash.isFunction(lodash.bar); - * // => true - * - * // Create a suped-up `defer` in Node.js. - * var defer = _.runInContext({ 'setTimeout': setImmediate }).defer; - */ - var runInContext = (function runInContext(context) { - context = context == null ? root : _.defaults(root.Object(), context, _.pick(root, contextProps)); + return value === proto; +} - /** Built-in constructor references. */ - var Array = context.Array, - Date = context.Date, - Error = context.Error, - Function = context.Function, - Math = context.Math, - Object = context.Object, - RegExp = context.RegExp, - String = context.String, - TypeError = context.TypeError; +/** + * This function is like + * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * except that it includes inherited enumerable properties. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ +function nativeKeysIn(object) { + var result = []; + if (object != null) { + for (var key in Object(object)) { + result.push(key); + } + } + return result; +} - /** Used for built-in method references. */ - var arrayProto = Array.prototype, - funcProto = Function.prototype, - objectProto = Object.prototype; +/** + * Performs a + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * comparison between two values to determine if they are equivalent. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.eq(object, object); + * // => true + * + * _.eq(object, other); + * // => false + * + * _.eq('a', 'a'); + * // => true + * + * _.eq('a', Object('a')); + * // => false + * + * _.eq(NaN, NaN); + * // => true + */ +function eq(value, other) { + return value === other || (value !== value && other !== other); +} - /** Used to detect overreaching core-js shims. */ - var coreJsData = context['__core-js_shared__']; +/** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ +function isArguments(value) { + // Safari 8.1 makes `arguments.callee` enumerable in strict mode. + return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && + (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); +} - /** Used to resolve the decompiled source of functions. */ - var funcToString = funcProto.toString; +/** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ +var isArray = Array.isArray; - /** Used to check objects for own properties. */ - var hasOwnProperty = objectProto.hasOwnProperty; +/** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ +function isArrayLike(value) { + return value != null && isLength(value.length) && !isFunction(value); +} - /** Used to generate unique IDs. */ - var idCounter = 0; +/** + * This method is like `_.isArrayLike` except that it also checks if `value` + * is an object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array-like object, + * else `false`. + * @example + * + * _.isArrayLikeObject([1, 2, 3]); + * // => true + * + * _.isArrayLikeObject(document.body.children); + * // => true + * + * _.isArrayLikeObject('abc'); + * // => false + * + * _.isArrayLikeObject(_.noop); + * // => false + */ +function isArrayLikeObject(value) { + return isObjectLike(value) && isArrayLike(value); +} - /** Used to detect methods masquerading as native. */ - var maskSrcKey = (function() { - var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); - return uid ? ('Symbol(src)_1.' + uid) : ''; - }()); +/** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ +function isFunction(value) { + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 8-9 which returns 'object' for typed array and other constructors. + var tag = isObject(value) ? objectToString.call(value) : ''; + return tag == funcTag || tag == genTag; +} - /** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ - var nativeObjectToString = objectProto.toString; +/** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ +function isLength(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; +} - /** Used to infer the `Object` constructor. */ - var objectCtorString = funcToString.call(Object); +/** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ +function isObject(value) { + var type = typeof value; + return !!value && (type == 'object' || type == 'function'); +} - /** Used to restore the original `_` reference in `_.noConflict`. */ - var oldDash = root._; +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} - /** Used to detect if a method is native. */ - var reIsNative = RegExp('^' + - funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') - .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' - ); +/** + * This method is like `_.assignIn` except that it accepts `customizer` + * which is invoked to produce the assigned values. If `customizer` returns + * `undefined`, assignment is handled by the method instead. The `customizer` + * is invoked with five arguments: (objValue, srcValue, key, object, source). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @alias extendWith + * @category Object + * @param {Object} object The destination object. + * @param {...Object} sources The source objects. + * @param {Function} [customizer] The function to customize assigned values. + * @returns {Object} Returns `object`. + * @see _.assignWith + * @example + * + * function customizer(objValue, srcValue) { + * return _.isUndefined(objValue) ? srcValue : objValue; + * } + * + * var defaults = _.partialRight(_.assignInWith, customizer); + * + * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); + * // => { 'a': 1, 'b': 2 } + */ +var assignInWith = createAssigner(function(object, source, srcIndex, customizer) { + copyObject(source, keysIn(source), object, customizer); +}); - /** Built-in value references. */ - var Buffer = moduleExports ? context.Buffer : undefined, - Symbol = context.Symbol, - Uint8Array = context.Uint8Array, - allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined, - getPrototype = overArg(Object.getPrototypeOf, Object), - objectCreate = Object.create, - propertyIsEnumerable = objectProto.propertyIsEnumerable, - splice = arrayProto.splice, - spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined, - symIterator = Symbol ? Symbol.iterator : undefined, - symToStringTag = Symbol ? Symbol.toStringTag : undefined; +/** + * Assigns own and inherited enumerable string keyed properties of source + * objects to the destination object for all destination properties that + * resolve to `undefined`. Source objects are applied from left to right. + * Once a property is set, additional values of the same property are ignored. + * + * **Note:** This method mutates `object`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.defaultsDeep + * @example + * + * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); + * // => { 'a': 1, 'b': 2 } + */ +var defaults = baseRest(function(args) { + args.push(undefined, assignInDefaults); + return apply(assignInWith, undefined, args); +}); - var defineProperty = (function() { - try { - var func = getNative(Object, 'defineProperty'); - func({}, '', {}); - return func; - } catch (e) {} - }()); +/** + * Creates an array of the own and inherited enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keysIn(new Foo); + * // => ['a', 'b', 'c'] (iteration order is not guaranteed) + */ +function keysIn(object) { + return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); +} - /** Mocked built-ins. */ - var ctxClearTimeout = context.clearTimeout !== root.clearTimeout && context.clearTimeout, - ctxNow = Date && Date.now !== root.Date.now && Date.now, - ctxSetTimeout = context.setTimeout !== root.setTimeout && context.setTimeout; +module.exports = defaults; - /* Built-in method references for those with the same name as other `lodash` methods. */ - var nativeCeil = Math.ceil, - nativeFloor = Math.floor, - nativeGetSymbols = Object.getOwnPropertySymbols, - nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined, - nativeIsFinite = context.isFinite, - nativeJoin = arrayProto.join, - nativeKeys = overArg(Object.keys, Object), - nativeMax = Math.max, - nativeMin = Math.min, - nativeNow = Date.now, - nativeParseInt = context.parseInt, - nativeRandom = Math.random, - nativeReverse = arrayProto.reverse; - /* Built-in method references that are verified to be native. */ - var DataView = getNative(context, 'DataView'), - Map = getNative(context, 'Map'), - Promise = getNative(context, 'Promise'), - Set = getNative(context, 'Set'), - WeakMap = getNative(context, 'WeakMap'), - nativeCreate = getNative(Object, 'create'); +/***/ }), - /** Used to store function metadata. */ - var metaMap = WeakMap && new WeakMap; +/***/ 48919: +/***/ ((module) => { - /** Used to lookup unminified function names. */ - var realNames = {}; +/** + * lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright jQuery Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ - /** Used to detect maps, sets, and weakmaps. */ - var dataViewCtorString = toSource(DataView), - mapCtorString = toSource(Map), - promiseCtorString = toSource(Promise), - setCtorString = toSource(Set), - weakMapCtorString = toSource(WeakMap); +/** Used as references for various `Number` constants. */ +var MAX_SAFE_INTEGER = 9007199254740991; - /** Used to convert symbols to primitives and strings. */ - var symbolProto = Symbol ? Symbol.prototype : undefined, - symbolValueOf = symbolProto ? symbolProto.valueOf : undefined, - symbolToString = symbolProto ? symbolProto.toString : undefined; +/** `Object#toString` result references. */ +var argsTag = '[object Arguments]', + funcTag = '[object Function]', + genTag = '[object GeneratorFunction]'; - /*------------------------------------------------------------------------*/ +/** Detect free variable `global` from Node.js. */ +var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; - /** - * Creates a `lodash` object which wraps `value` to enable implicit method - * chain sequences. Methods that operate on and return arrays, collections, - * and functions can be chained together. Methods that retrieve a single value - * or may return a primitive value will automatically end the chain sequence - * and return the unwrapped value. Otherwise, the value must be unwrapped - * with `_#value`. - * - * Explicit chain sequences, which must be unwrapped with `_#value`, may be - * enabled using `_.chain`. - * - * The execution of chained methods is lazy, that is, it's deferred until - * `_#value` is implicitly or explicitly called. - * - * Lazy evaluation allows several methods to support shortcut fusion. - * Shortcut fusion is an optimization to merge iteratee calls; this avoids - * the creation of intermediate arrays and can greatly reduce the number of - * iteratee executions. Sections of a chain sequence qualify for shortcut - * fusion if the section is applied to an array and iteratees accept only - * one argument. The heuristic for whether a section qualifies for shortcut - * fusion is subject to change. - * - * Chaining is supported in custom builds as long as the `_#value` method is - * directly or indirectly included in the build. - * - * In addition to lodash methods, wrappers have `Array` and `String` methods. - * - * The wrapper `Array` methods are: - * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift` - * - * The wrapper `String` methods are: - * `replace` and `split` - * - * The wrapper methods that support shortcut fusion are: - * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`, - * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`, - * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray` - * - * The chainable wrapper methods are: - * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`, - * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`, - * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`, - * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`, - * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`, - * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`, - * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`, - * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`, - * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`, - * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`, - * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`, - * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`, - * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`, - * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`, - * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`, - * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`, - * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`, - * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`, - * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`, - * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`, - * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`, - * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`, - * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`, - * `zipObject`, `zipObjectDeep`, and `zipWith` - * - * The wrapper methods that are **not** chainable by default are: - * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`, - * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`, - * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`, - * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`, - * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`, - * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`, - * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`, - * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`, - * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`, - * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`, - * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`, - * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`, - * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`, - * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`, - * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`, - * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`, - * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`, - * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`, - * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`, - * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`, - * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`, - * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`, - * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`, - * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`, - * `upperFirst`, `value`, and `words` - * - * @name _ - * @constructor - * @category Seq - * @param {*} value The value to wrap in a `lodash` instance. - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example - * - * function square(n) { - * return n * n; - * } - * - * var wrapped = _([1, 2, 3]); - * - * // Returns an unwrapped value. - * wrapped.reduce(_.add); - * // => 6 - * - * // Returns a wrapped value. - * var squares = wrapped.map(square); - * - * _.isArray(squares); - * // => false - * - * _.isArray(squares.value()); - * // => true - */ - function lodash(value) { - if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) { - if (value instanceof LodashWrapper) { - return value; - } - if (hasOwnProperty.call(value, '__wrapped__')) { - return wrapperClone(value); - } - } - return new LodashWrapper(value); - } +/** Detect free variable `self`. */ +var freeSelf = typeof self == 'object' && self && self.Object === Object && self; - /** - * The base implementation of `_.create` without support for assigning - * properties to the created object. - * - * @private - * @param {Object} proto The object to inherit from. - * @returns {Object} Returns the new object. - */ - var baseCreate = (function() { - function object() {} - return function(proto) { - if (!isObject(proto)) { - return {}; - } - if (objectCreate) { - return objectCreate(proto); - } - object.prototype = proto; - var result = new object; - object.prototype = undefined; - return result; - }; - }()); +/** Used as a reference to the global object. */ +var root = freeGlobal || freeSelf || Function('return this')(); - /** - * The function whose prototype chain sequence wrappers inherit from. - * - * @private - */ - function baseLodash() { - // No operation performed. - } +/** + * Appends the elements of `values` to `array`. + * + * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to append. + * @returns {Array} Returns `array`. + */ +function arrayPush(array, values) { + var index = -1, + length = values.length, + offset = array.length; - /** - * The base constructor for creating `lodash` wrapper objects. - * - * @private - * @param {*} value The value to wrap. - * @param {boolean} [chainAll] Enable explicit method chain sequences. - */ - function LodashWrapper(value, chainAll) { - this.__wrapped__ = value; - this.__actions__ = []; - this.__chain__ = !!chainAll; - this.__index__ = 0; - this.__values__ = undefined; - } + while (++index < length) { + array[offset + index] = values[index]; + } + return array; +} - /** - * By default, the template delimiters used by lodash are like those in - * embedded Ruby (ERB) as well as ES2015 template strings. Change the - * following template settings to use alternative delimiters. - * - * @static - * @memberOf _ - * @type {Object} - */ - lodash.templateSettings = { +/** Used for built-in method references. */ +var objectProto = Object.prototype; - /** - * Used to detect `data` property values to be HTML-escaped. - * - * @memberOf _.templateSettings - * @type {RegExp} - */ - 'escape': reEscape, +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; - /** - * Used to detect code to be evaluated. - * - * @memberOf _.templateSettings - * @type {RegExp} - */ - 'evaluate': reEvaluate, +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; - /** - * Used to detect `data` property values to inject. - * - * @memberOf _.templateSettings - * @type {RegExp} - */ - 'interpolate': reInterpolate, +/** Built-in value references. */ +var Symbol = root.Symbol, + propertyIsEnumerable = objectProto.propertyIsEnumerable, + spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined; - /** - * Used to reference the data object in the template text. - * - * @memberOf _.templateSettings - * @type {string} - */ - 'variable': '', +/** + * The base implementation of `_.flatten` with support for restricting flattening. + * + * @private + * @param {Array} array The array to flatten. + * @param {number} depth The maximum recursion depth. + * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. + * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. + * @param {Array} [result=[]] The initial result value. + * @returns {Array} Returns the new flattened array. + */ +function baseFlatten(array, depth, predicate, isStrict, result) { + var index = -1, + length = array.length; - /** - * Used to import variables into the compiled template. - * - * @memberOf _.templateSettings - * @type {Object} - */ - 'imports': { + predicate || (predicate = isFlattenable); + result || (result = []); - /** - * A reference to the `lodash` function. - * - * @memberOf _.templateSettings.imports - * @type {Function} - */ - '_': lodash + while (++index < length) { + var value = array[index]; + if (depth > 0 && predicate(value)) { + if (depth > 1) { + // Recursively flatten arrays (susceptible to call stack limits). + baseFlatten(value, depth - 1, predicate, isStrict, result); + } else { + arrayPush(result, value); } - }; + } else if (!isStrict) { + result[result.length] = value; + } + } + return result; +} - // Ensure wrappers are instances of `baseLodash`. - lodash.prototype = baseLodash.prototype; - lodash.prototype.constructor = lodash; +/** + * Checks if `value` is a flattenable `arguments` object or array. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. + */ +function isFlattenable(value) { + return isArray(value) || isArguments(value) || + !!(spreadableSymbol && value && value[spreadableSymbol]); +} - LodashWrapper.prototype = baseCreate(baseLodash.prototype); - LodashWrapper.prototype.constructor = LodashWrapper; +/** + * Flattens `array` a single level deep. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to flatten. + * @returns {Array} Returns the new flattened array. + * @example + * + * _.flatten([1, [2, [3, [4]], 5]]); + * // => [1, 2, [3, [4]], 5] + */ +function flatten(array) { + var length = array ? array.length : 0; + return length ? baseFlatten(array, 1) : []; +} - /*------------------------------------------------------------------------*/ +/** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ +function isArguments(value) { + // Safari 8.1 makes `arguments.callee` enumerable in strict mode. + return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && + (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); +} - /** - * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation. - * - * @private - * @constructor - * @param {*} value The value to wrap. - */ - function LazyWrapper(value) { - this.__wrapped__ = value; - this.__actions__ = []; - this.__dir__ = 1; - this.__filtered__ = false; - this.__iteratees__ = []; - this.__takeCount__ = MAX_ARRAY_LENGTH; - this.__views__ = []; - } +/** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ +var isArray = Array.isArray; + +/** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ +function isArrayLike(value) { + return value != null && isLength(value.length) && !isFunction(value); +} - /** - * Creates a clone of the lazy wrapper object. - * - * @private - * @name clone - * @memberOf LazyWrapper - * @returns {Object} Returns the cloned `LazyWrapper` object. - */ - function lazyClone() { - var result = new LazyWrapper(this.__wrapped__); - result.__actions__ = copyArray(this.__actions__); - result.__dir__ = this.__dir__; - result.__filtered__ = this.__filtered__; - result.__iteratees__ = copyArray(this.__iteratees__); - result.__takeCount__ = this.__takeCount__; - result.__views__ = copyArray(this.__views__); - return result; - } +/** + * This method is like `_.isArrayLike` except that it also checks if `value` + * is an object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array-like object, + * else `false`. + * @example + * + * _.isArrayLikeObject([1, 2, 3]); + * // => true + * + * _.isArrayLikeObject(document.body.children); + * // => true + * + * _.isArrayLikeObject('abc'); + * // => false + * + * _.isArrayLikeObject(_.noop); + * // => false + */ +function isArrayLikeObject(value) { + return isObjectLike(value) && isArrayLike(value); +} - /** - * Reverses the direction of lazy iteration. - * - * @private - * @name reverse - * @memberOf LazyWrapper - * @returns {Object} Returns the new reversed `LazyWrapper` object. - */ - function lazyReverse() { - if (this.__filtered__) { - var result = new LazyWrapper(this); - result.__dir__ = -1; - result.__filtered__ = true; - } else { - result = this.clone(); - result.__dir__ *= -1; - } - return result; - } +/** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ +function isFunction(value) { + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 8-9 which returns 'object' for typed array and other constructors. + var tag = isObject(value) ? objectToString.call(value) : ''; + return tag == funcTag || tag == genTag; +} - /** - * Extracts the unwrapped value from its lazy wrapper. - * - * @private - * @name value - * @memberOf LazyWrapper - * @returns {*} Returns the unwrapped value. - */ - function lazyValue() { - var array = this.__wrapped__.value(), - dir = this.__dir__, - isArr = isArray(array), - isRight = dir < 0, - arrLength = isArr ? array.length : 0, - view = getView(0, arrLength, this.__views__), - start = view.start, - end = view.end, - length = end - start, - index = isRight ? end : (start - 1), - iteratees = this.__iteratees__, - iterLength = iteratees.length, - resIndex = 0, - takeCount = nativeMin(length, this.__takeCount__); +/** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ +function isLength(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; +} - if (!isArr || (!isRight && arrLength == length && takeCount == length)) { - return baseWrapperValue(array, this.__actions__); - } - var result = []; +/** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ +function isObject(value) { + var type = typeof value; + return !!value && (type == 'object' || type == 'function'); +} - outer: - while (length-- && resIndex < takeCount) { - index += dir; +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} - var iterIndex = -1, - value = array[index]; +module.exports = flatten; - while (++iterIndex < iterLength) { - var data = iteratees[iterIndex], - iteratee = data.iteratee, - type = data.type, - computed = iteratee(value); - if (type == LAZY_MAP_FLAG) { - value = computed; - } else if (!computed) { - if (type == LAZY_FILTER_FLAG) { - continue outer; - } else { - break outer; - } - } - } - result[resIndex++] = value; - } - return result; - } +/***/ }), - // Ensure `LazyWrapper` is an instance of `baseLodash`. - LazyWrapper.prototype = baseCreate(baseLodash.prototype); - LazyWrapper.prototype.constructor = LazyWrapper; +/***/ 17931: +/***/ ((module) => { - /*------------------------------------------------------------------------*/ +/** + * lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright jQuery Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ - /** - * Creates a hash object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function Hash(entries) { - var index = -1, - length = entries == null ? 0 : entries.length; +/** Used as references for various `Number` constants. */ +var INFINITY = 1 / 0, + MAX_SAFE_INTEGER = 9007199254740991, + MAX_INTEGER = 1.7976931348623157e+308, + NAN = 0 / 0; - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } +/** `Object#toString` result references. */ +var argsTag = '[object Arguments]', + funcTag = '[object Function]', + genTag = '[object GeneratorFunction]', + stringTag = '[object String]', + symbolTag = '[object Symbol]'; - /** - * Removes all key-value entries from the hash. - * - * @private - * @name clear - * @memberOf Hash - */ - function hashClear() { - this.__data__ = nativeCreate ? nativeCreate(null) : {}; - this.size = 0; - } +/** Used to match leading and trailing whitespace. */ +var reTrim = /^\s+|\s+$/g; - /** - * Removes `key` and its value from the hash. - * - * @private - * @name delete - * @memberOf Hash - * @param {Object} hash The hash to modify. - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function hashDelete(key) { - var result = this.has(key) && delete this.__data__[key]; - this.size -= result ? 1 : 0; - return result; - } +/** Used to detect bad signed hexadecimal string values. */ +var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; - /** - * Gets the hash value for `key`. - * - * @private - * @name get - * @memberOf Hash - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function hashGet(key) { - var data = this.__data__; - if (nativeCreate) { - var result = data[key]; - return result === HASH_UNDEFINED ? undefined : result; - } - return hasOwnProperty.call(data, key) ? data[key] : undefined; - } +/** Used to detect binary string values. */ +var reIsBinary = /^0b[01]+$/i; - /** - * Checks if a hash value for `key` exists. - * - * @private - * @name has - * @memberOf Hash - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function hashHas(key) { - var data = this.__data__; - return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key); - } +/** Used to detect octal string values. */ +var reIsOctal = /^0o[0-7]+$/i; - /** - * Sets the hash `key` to `value`. - * - * @private - * @name set - * @memberOf Hash - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the hash instance. - */ - function hashSet(key, value) { - var data = this.__data__; - this.size += this.has(key) ? 0 : 1; - data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; - return this; - } +/** Used to detect unsigned integer values. */ +var reIsUint = /^(?:0|[1-9]\d*)$/; - // Add methods to `Hash`. - Hash.prototype.clear = hashClear; - Hash.prototype['delete'] = hashDelete; - Hash.prototype.get = hashGet; - Hash.prototype.has = hashHas; - Hash.prototype.set = hashSet; +/** Built-in method references without a dependency on `root`. */ +var freeParseInt = parseInt; - /*------------------------------------------------------------------------*/ +/** + * A specialized version of `_.map` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + */ +function arrayMap(array, iteratee) { + var index = -1, + length = array ? array.length : 0, + result = Array(length); - /** - * Creates an list cache object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function ListCache(entries) { - var index = -1, - length = entries == null ? 0 : entries.length; + while (++index < length) { + result[index] = iteratee(array[index], index, array); + } + return result; +} - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } +/** + * The base implementation of `_.findIndex` and `_.findLastIndex` without + * support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} predicate The function invoked per iteration. + * @param {number} fromIndex The index to search from. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function baseFindIndex(array, predicate, fromIndex, fromRight) { + var length = array.length, + index = fromIndex + (fromRight ? 1 : -1); - /** - * Removes all key-value entries from the list cache. - * - * @private - * @name clear - * @memberOf ListCache - */ - function listCacheClear() { - this.__data__ = []; - this.size = 0; + while ((fromRight ? index-- : ++index < length)) { + if (predicate(array[index], index, array)) { + return index; } + } + return -1; +} - /** - * Removes `key` and its value from the list cache. - * - * @private - * @name delete - * @memberOf ListCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function listCacheDelete(key) { - var data = this.__data__, - index = assocIndexOf(data, key); +/** + * The base implementation of `_.indexOf` without `fromIndex` bounds checks. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function baseIndexOf(array, value, fromIndex) { + if (value !== value) { + return baseFindIndex(array, baseIsNaN, fromIndex); + } + var index = fromIndex - 1, + length = array.length; - if (index < 0) { - return false; - } - var lastIndex = data.length - 1; - if (index == lastIndex) { - data.pop(); - } else { - splice.call(data, index, 1); - } - --this.size; - return true; + while (++index < length) { + if (array[index] === value) { + return index; } + } + return -1; +} - /** - * Gets the list cache value for `key`. - * - * @private - * @name get - * @memberOf ListCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function listCacheGet(key) { - var data = this.__data__, - index = assocIndexOf(data, key); +/** + * The base implementation of `_.isNaN` without support for number objects. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. + */ +function baseIsNaN(value) { + return value !== value; +} - return index < 0 ? undefined : data[index][1]; - } +/** + * The base implementation of `_.times` without support for iteratee shorthands + * or max array length checks. + * + * @private + * @param {number} n The number of times to invoke `iteratee`. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the array of results. + */ +function baseTimes(n, iteratee) { + var index = -1, + result = Array(n); + + while (++index < n) { + result[index] = iteratee(index); + } + return result; +} - /** - * Checks if a list cache value for `key` exists. - * - * @private - * @name has - * @memberOf ListCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function listCacheHas(key) { - return assocIndexOf(this.__data__, key) > -1; - } +/** + * The base implementation of `_.values` and `_.valuesIn` which creates an + * array of `object` property values corresponding to the property names + * of `props`. + * + * @private + * @param {Object} object The object to query. + * @param {Array} props The property names to get values for. + * @returns {Object} Returns the array of property values. + */ +function baseValues(object, props) { + return arrayMap(props, function(key) { + return object[key]; + }); +} - /** - * Sets the list cache `key` to `value`. - * - * @private - * @name set - * @memberOf ListCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the list cache instance. - */ - function listCacheSet(key, value) { - var data = this.__data__, - index = assocIndexOf(data, key); +/** + * Creates a unary function that invokes `func` with its argument transformed. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ +function overArg(func, transform) { + return function(arg) { + return func(transform(arg)); + }; +} - if (index < 0) { - ++this.size; - data.push([key, value]); - } else { - data[index][1] = value; - } - return this; - } +/** Used for built-in method references. */ +var objectProto = Object.prototype; - // Add methods to `ListCache`. - ListCache.prototype.clear = listCacheClear; - ListCache.prototype['delete'] = listCacheDelete; - ListCache.prototype.get = listCacheGet; - ListCache.prototype.has = listCacheHas; - ListCache.prototype.set = listCacheSet; +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; - /*------------------------------------------------------------------------*/ +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; - /** - * Creates a map cache object to store key-value pairs. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function MapCache(entries) { - var index = -1, - length = entries == null ? 0 : entries.length; +/** Built-in value references. */ +var propertyIsEnumerable = objectProto.propertyIsEnumerable; - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeKeys = overArg(Object.keys, Object), + nativeMax = Math.max; - /** - * Removes all key-value entries from the map. - * - * @private - * @name clear - * @memberOf MapCache - */ - function mapCacheClear() { - this.size = 0; - this.__data__ = { - 'hash': new Hash, - 'map': new (Map || ListCache), - 'string': new Hash - }; - } +/** + * Creates an array of the enumerable property names of the array-like `value`. + * + * @private + * @param {*} value The value to query. + * @param {boolean} inherited Specify returning inherited property names. + * @returns {Array} Returns the array of property names. + */ +function arrayLikeKeys(value, inherited) { + // Safari 8.1 makes `arguments.callee` enumerable in strict mode. + // Safari 9 makes `arguments.length` enumerable in strict mode. + var result = (isArray(value) || isArguments(value)) + ? baseTimes(value.length, String) + : []; - /** - * Removes `key` and its value from the map. - * - * @private - * @name delete - * @memberOf MapCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function mapCacheDelete(key) { - var result = getMapData(this, key)['delete'](key); - this.size -= result ? 1 : 0; - return result; - } + var length = result.length, + skipIndexes = !!length; - /** - * Gets the map value for `key`. - * - * @private - * @name get - * @memberOf MapCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function mapCacheGet(key) { - return getMapData(this, key).get(key); + for (var key in value) { + if ((inherited || hasOwnProperty.call(value, key)) && + !(skipIndexes && (key == 'length' || isIndex(key, length)))) { + result.push(key); } + } + return result; +} - /** - * Checks if a map value for `key` exists. - * - * @private - * @name has - * @memberOf MapCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function mapCacheHas(key) { - return getMapData(this, key).has(key); +/** + * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ +function baseKeys(object) { + if (!isPrototype(object)) { + return nativeKeys(object); + } + var result = []; + for (var key in Object(object)) { + if (hasOwnProperty.call(object, key) && key != 'constructor') { + result.push(key); } + } + return result; +} - /** - * Sets the map `key` to `value`. - * - * @private - * @name set - * @memberOf MapCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the map cache instance. - */ - function mapCacheSet(key, value) { - var data = getMapData(this, key), - size = data.size; +/** + * Checks if `value` is a valid array-like index. + * + * @private + * @param {*} value The value to check. + * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. + * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + */ +function isIndex(value, length) { + length = length == null ? MAX_SAFE_INTEGER : length; + return !!length && + (typeof value == 'number' || reIsUint.test(value)) && + (value > -1 && value % 1 == 0 && value < length); +} - data.set(key, value); - this.size += data.size == size ? 0 : 1; - return this; - } +/** + * Checks if `value` is likely a prototype object. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. + */ +function isPrototype(value) { + var Ctor = value && value.constructor, + proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; - // Add methods to `MapCache`. - MapCache.prototype.clear = mapCacheClear; - MapCache.prototype['delete'] = mapCacheDelete; - MapCache.prototype.get = mapCacheGet; - MapCache.prototype.has = mapCacheHas; - MapCache.prototype.set = mapCacheSet; + return value === proto; +} - /*------------------------------------------------------------------------*/ +/** + * Checks if `value` is in `collection`. If `collection` is a string, it's + * checked for a substring of `value`, otherwise + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * is used for equality comparisons. If `fromIndex` is negative, it's used as + * the offset from the end of `collection`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object|string} collection The collection to inspect. + * @param {*} value The value to search for. + * @param {number} [fromIndex=0] The index to search from. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. + * @returns {boolean} Returns `true` if `value` is found, else `false`. + * @example + * + * _.includes([1, 2, 3], 1); + * // => true + * + * _.includes([1, 2, 3], 1, 2); + * // => false + * + * _.includes({ 'a': 1, 'b': 2 }, 1); + * // => true + * + * _.includes('abcd', 'bc'); + * // => true + */ +function includes(collection, value, fromIndex, guard) { + collection = isArrayLike(collection) ? collection : values(collection); + fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0; - /** - * - * Creates an array cache object to store unique values. - * - * @private - * @constructor - * @param {Array} [values] The values to cache. - */ - function SetCache(values) { - var index = -1, - length = values == null ? 0 : values.length; + var length = collection.length; + if (fromIndex < 0) { + fromIndex = nativeMax(length + fromIndex, 0); + } + return isString(collection) + ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1) + : (!!length && baseIndexOf(collection, value, fromIndex) > -1); +} - this.__data__ = new MapCache; - while (++index < length) { - this.add(values[index]); - } - } +/** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ +function isArguments(value) { + // Safari 8.1 makes `arguments.callee` enumerable in strict mode. + return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && + (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); +} - /** - * Adds `value` to the array cache. - * - * @private - * @name add - * @memberOf SetCache - * @alias push - * @param {*} value The value to cache. - * @returns {Object} Returns the cache instance. - */ - function setCacheAdd(value) { - this.__data__.set(value, HASH_UNDEFINED); - return this; - } +/** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ +var isArray = Array.isArray; - /** - * Checks if `value` is in the array cache. - * - * @private - * @name has - * @memberOf SetCache - * @param {*} value The value to search for. - * @returns {number} Returns `true` if `value` is found, else `false`. - */ - function setCacheHas(value) { - return this.__data__.has(value); - } +/** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ +function isArrayLike(value) { + return value != null && isLength(value.length) && !isFunction(value); +} - // Add methods to `SetCache`. - SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; - SetCache.prototype.has = setCacheHas; +/** + * This method is like `_.isArrayLike` except that it also checks if `value` + * is an object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array-like object, + * else `false`. + * @example + * + * _.isArrayLikeObject([1, 2, 3]); + * // => true + * + * _.isArrayLikeObject(document.body.children); + * // => true + * + * _.isArrayLikeObject('abc'); + * // => false + * + * _.isArrayLikeObject(_.noop); + * // => false + */ +function isArrayLikeObject(value) { + return isObjectLike(value) && isArrayLike(value); +} - /*------------------------------------------------------------------------*/ +/** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ +function isFunction(value) { + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 8-9 which returns 'object' for typed array and other constructors. + var tag = isObject(value) ? objectToString.call(value) : ''; + return tag == funcTag || tag == genTag; +} - /** - * Creates a stack cache object to store key-value pairs. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function Stack(entries) { - var data = this.__data__ = new ListCache(entries); - this.size = data.size; - } +/** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ +function isLength(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; +} - /** - * Removes all key-value entries from the stack. - * - * @private - * @name clear - * @memberOf Stack - */ - function stackClear() { - this.__data__ = new ListCache; - this.size = 0; - } +/** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ +function isObject(value) { + var type = typeof value; + return !!value && (type == 'object' || type == 'function'); +} - /** - * Removes `key` and its value from the stack. - * - * @private - * @name delete - * @memberOf Stack - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function stackDelete(key) { - var data = this.__data__, - result = data['delete'](key); +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} - this.size = data.size; - return result; - } +/** + * Checks if `value` is classified as a `String` primitive or object. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a string, else `false`. + * @example + * + * _.isString('abc'); + * // => true + * + * _.isString(1); + * // => false + */ +function isString(value) { + return typeof value == 'string' || + (!isArray(value) && isObjectLike(value) && objectToString.call(value) == stringTag); +} - /** - * Gets the stack value for `key`. - * - * @private - * @name get - * @memberOf Stack - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function stackGet(key) { - return this.__data__.get(key); - } +/** + * Checks if `value` is classified as a `Symbol` primitive or object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. + * @example + * + * _.isSymbol(Symbol.iterator); + * // => true + * + * _.isSymbol('abc'); + * // => false + */ +function isSymbol(value) { + return typeof value == 'symbol' || + (isObjectLike(value) && objectToString.call(value) == symbolTag); +} - /** - * Checks if a stack value for `key` exists. - * - * @private - * @name has - * @memberOf Stack - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function stackHas(key) { - return this.__data__.has(key); - } +/** + * Converts `value` to a finite number. + * + * @static + * @memberOf _ + * @since 4.12.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted number. + * @example + * + * _.toFinite(3.2); + * // => 3.2 + * + * _.toFinite(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toFinite(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toFinite('3.2'); + * // => 3.2 + */ +function toFinite(value) { + if (!value) { + return value === 0 ? value : 0; + } + value = toNumber(value); + if (value === INFINITY || value === -INFINITY) { + var sign = (value < 0 ? -1 : 1); + return sign * MAX_INTEGER; + } + return value === value ? value : 0; +} - /** - * Sets the stack `key` to `value`. - * - * @private - * @name set - * @memberOf Stack - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the stack cache instance. - */ - function stackSet(key, value) { - var data = this.__data__; - if (data instanceof ListCache) { - var pairs = data.__data__; - if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { - pairs.push([key, value]); - this.size = ++data.size; - return this; - } - data = this.__data__ = new MapCache(pairs); - } - data.set(key, value); - this.size = data.size; - return this; - } +/** + * Converts `value` to an integer. + * + * **Note:** This method is loosely based on + * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. + * @example + * + * _.toInteger(3.2); + * // => 3 + * + * _.toInteger(Number.MIN_VALUE); + * // => 0 + * + * _.toInteger(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toInteger('3.2'); + * // => 3 + */ +function toInteger(value) { + var result = toFinite(value), + remainder = result % 1; - // Add methods to `Stack`. - Stack.prototype.clear = stackClear; - Stack.prototype['delete'] = stackDelete; - Stack.prototype.get = stackGet; - Stack.prototype.has = stackHas; - Stack.prototype.set = stackSet; + return result === result ? (remainder ? result - remainder : result) : 0; +} - /*------------------------------------------------------------------------*/ +/** + * Converts `value` to a number. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to process. + * @returns {number} Returns the number. + * @example + * + * _.toNumber(3.2); + * // => 3.2 + * + * _.toNumber(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toNumber(Infinity); + * // => Infinity + * + * _.toNumber('3.2'); + * // => 3.2 + */ +function toNumber(value) { + if (typeof value == 'number') { + return value; + } + if (isSymbol(value)) { + return NAN; + } + if (isObject(value)) { + var other = typeof value.valueOf == 'function' ? value.valueOf() : value; + value = isObject(other) ? (other + '') : other; + } + if (typeof value != 'string') { + return value === 0 ? value : +value; + } + value = value.replace(reTrim, ''); + var isBinary = reIsBinary.test(value); + return (isBinary || reIsOctal.test(value)) + ? freeParseInt(value.slice(2), isBinary ? 2 : 8) + : (reIsBadHex.test(value) ? NAN : +value); +} - /** - * Creates an array of the enumerable property names of the array-like `value`. - * - * @private - * @param {*} value The value to query. - * @param {boolean} inherited Specify returning inherited property names. - * @returns {Array} Returns the array of property names. - */ - function arrayLikeKeys(value, inherited) { - var isArr = isArray(value), - isArg = !isArr && isArguments(value), - isBuff = !isArr && !isArg && isBuffer(value), - isType = !isArr && !isArg && !isBuff && isTypedArray(value), - skipIndexes = isArr || isArg || isBuff || isType, - result = skipIndexes ? baseTimes(value.length, String) : [], - length = result.length; +/** + * Creates an array of the own enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. See the + * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * for more details. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keys(new Foo); + * // => ['a', 'b'] (iteration order is not guaranteed) + * + * _.keys('hi'); + * // => ['0', '1'] + */ +function keys(object) { + return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); +} - for (var key in value) { - if ((inherited || hasOwnProperty.call(value, key)) && - !(skipIndexes && ( - // Safari 9 has enumerable `arguments.length` in strict mode. - key == 'length' || - // Node.js 0.10 has enumerable non-index properties on buffers. - (isBuff && (key == 'offset' || key == 'parent')) || - // PhantomJS 2 has enumerable non-index properties on typed arrays. - (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || - // Skip index properties. - isIndex(key, length) - ))) { - result.push(key); - } - } - return result; - } +/** + * Creates an array of the own enumerable string keyed property values of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property values. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.values(new Foo); + * // => [1, 2] (iteration order is not guaranteed) + * + * _.values('hi'); + * // => ['h', 'i'] + */ +function values(object) { + return object ? baseValues(object, keys(object)) : []; +} - /** - * A specialized version of `_.sample` for arrays. - * - * @private - * @param {Array} array The array to sample. - * @returns {*} Returns the random element. - */ - function arraySample(array) { - var length = array.length; - return length ? array[baseRandom(0, length - 1)] : undefined; - } +module.exports = includes; - /** - * A specialized version of `_.sampleSize` for arrays. - * - * @private - * @param {Array} array The array to sample. - * @param {number} n The number of elements to sample. - * @returns {Array} Returns the random elements. - */ - function arraySampleSize(array, n) { - return shuffleSelf(copyArray(array), baseClamp(n, 0, array.length)); - } - /** - * A specialized version of `_.shuffle` for arrays. - * - * @private - * @param {Array} array The array to shuffle. - * @returns {Array} Returns the new shuffled array. - */ - function arrayShuffle(array) { - return shuffleSelf(copyArray(array)); - } +/***/ }), - /** - * This function is like `assignValue` except that it doesn't assign - * `undefined` values. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ - function assignMergeValue(object, key, value) { - if ((value !== undefined && !eq(object[key], value)) || - (value === undefined && !(key in object))) { - baseAssignValue(object, key, value); - } - } +/***/ 44130: +/***/ ((module) => { - /** - * Assigns `value` to `key` of `object` if the existing value is not equivalent - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ - function assignValue(object, key, value) { - var objValue = object[key]; - if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || - (value === undefined && !(key in object))) { - baseAssignValue(object, key, value); - } - } +/** + * lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright jQuery Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ - /** - * Gets the index at which the `key` is found in `array` of key-value pairs. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} key The key to search for. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function assocIndexOf(array, key) { - var length = array.length; - while (length--) { - if (eq(array[length][0], key)) { - return length; - } - } - return -1; - } +/** Used as references for various `Number` constants. */ +var MAX_SAFE_INTEGER = 9007199254740991; - /** - * Aggregates elements of `collection` on `accumulator` with keys transformed - * by `iteratee` and values set by `setter`. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} setter The function to set `accumulator` values. - * @param {Function} iteratee The iteratee to transform keys. - * @param {Object} accumulator The initial aggregated object. - * @returns {Function} Returns `accumulator`. - */ - function baseAggregator(collection, setter, iteratee, accumulator) { - baseEach(collection, function(value, key, collection) { - setter(accumulator, value, iteratee(value), collection); - }); - return accumulator; - } +/** `Object#toString` result references. */ +var argsTag = '[object Arguments]', + funcTag = '[object Function]', + genTag = '[object GeneratorFunction]'; - /** - * The base implementation of `_.assign` without support for multiple sources - * or `customizer` functions. - * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @returns {Object} Returns `object`. - */ - function baseAssign(object, source) { - return object && copyObject(source, keys(source), object); - } +/** Used for built-in method references. */ +var objectProto = Object.prototype; - /** - * The base implementation of `_.assignIn` without support for multiple sources - * or `customizer` functions. - * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @returns {Object} Returns `object`. - */ - function baseAssignIn(object, source) { - return object && copyObject(source, keysIn(source), object); - } +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; - /** - * The base implementation of `assignValue` and `assignMergeValue` without - * value checks. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ - function baseAssignValue(object, key, value) { - if (key == '__proto__' && defineProperty) { - defineProperty(object, key, { - 'configurable': true, - 'enumerable': true, - 'value': value, - 'writable': true - }); - } else { - object[key] = value; - } - } +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; - /** - * The base implementation of `_.at` without support for individual paths. - * - * @private - * @param {Object} object The object to iterate over. - * @param {string[]} paths The property paths to pick. - * @returns {Array} Returns the picked elements. - */ - function baseAt(object, paths) { - var index = -1, - length = paths.length, - result = Array(length), - skip = object == null; +/** Built-in value references. */ +var propertyIsEnumerable = objectProto.propertyIsEnumerable; - while (++index < length) { - result[index] = skip ? undefined : get(object, paths[index]); - } - return result; - } +/** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ +function isArguments(value) { + // Safari 8.1 makes `arguments.callee` enumerable in strict mode. + return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && + (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); +} - /** - * The base implementation of `_.clamp` which doesn't coerce arguments. - * - * @private - * @param {number} number The number to clamp. - * @param {number} [lower] The lower bound. - * @param {number} upper The upper bound. - * @returns {number} Returns the clamped number. - */ - function baseClamp(number, lower, upper) { - if (number === number) { - if (upper !== undefined) { - number = number <= upper ? number : upper; - } - if (lower !== undefined) { - number = number >= lower ? number : lower; - } - } - return number; - } +/** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ +function isArrayLike(value) { + return value != null && isLength(value.length) && !isFunction(value); +} - /** - * The base implementation of `_.clone` and `_.cloneDeep` which tracks - * traversed objects. - * - * @private - * @param {*} value The value to clone. - * @param {boolean} bitmask The bitmask flags. - * 1 - Deep clone - * 2 - Flatten inherited properties - * 4 - Clone symbols - * @param {Function} [customizer] The function to customize cloning. - * @param {string} [key] The key of `value`. - * @param {Object} [object] The parent object of `value`. - * @param {Object} [stack] Tracks traversed objects and their clone counterparts. - * @returns {*} Returns the cloned value. - */ - function baseClone(value, bitmask, customizer, key, object, stack) { - var result, - isDeep = bitmask & CLONE_DEEP_FLAG, - isFlat = bitmask & CLONE_FLAT_FLAG, - isFull = bitmask & CLONE_SYMBOLS_FLAG; +/** + * This method is like `_.isArrayLike` except that it also checks if `value` + * is an object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array-like object, + * else `false`. + * @example + * + * _.isArrayLikeObject([1, 2, 3]); + * // => true + * + * _.isArrayLikeObject(document.body.children); + * // => true + * + * _.isArrayLikeObject('abc'); + * // => false + * + * _.isArrayLikeObject(_.noop); + * // => false + */ +function isArrayLikeObject(value) { + return isObjectLike(value) && isArrayLike(value); +} - if (customizer) { - result = object ? customizer(value, key, object, stack) : customizer(value); - } - if (result !== undefined) { - return result; - } - if (!isObject(value)) { - return value; - } - var isArr = isArray(value); - if (isArr) { - result = initCloneArray(value); - if (!isDeep) { - return copyArray(value, result); - } - } else { - var tag = getTag(value), - isFunc = tag == funcTag || tag == genTag; +/** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ +function isFunction(value) { + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 8-9 which returns 'object' for typed array and other constructors. + var tag = isObject(value) ? objectToString.call(value) : ''; + return tag == funcTag || tag == genTag; +} - if (isBuffer(value)) { - return cloneBuffer(value, isDeep); - } - if (tag == objectTag || tag == argsTag || (isFunc && !object)) { - result = (isFlat || isFunc) ? {} : initCloneObject(value); - if (!isDeep) { - return isFlat - ? copySymbolsIn(value, baseAssignIn(result, value)) - : copySymbols(value, baseAssign(result, value)); - } - } else { - if (!cloneableTags[tag]) { - return object ? value : {}; - } - result = initCloneByTag(value, tag, isDeep); - } - } - // Check for circular references and return its corresponding clone. - stack || (stack = new Stack); - var stacked = stack.get(value); - if (stacked) { - return stacked; - } - stack.set(value, result); +/** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ +function isLength(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; +} - if (isSet(value)) { - value.forEach(function(subValue) { - result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack)); - }); - } else if (isMap(value)) { - value.forEach(function(subValue, key) { - result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack)); - }); - } +/** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ +function isObject(value) { + var type = typeof value; + return !!value && (type == 'object' || type == 'function'); +} - var keysFunc = isFull - ? (isFlat ? getAllKeysIn : getAllKeys) - : (isFlat ? keysIn : keys); +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} - var props = isArr ? undefined : keysFunc(value); - arrayEach(props || value, function(subValue, key) { - if (props) { - key = subValue; - subValue = value[key]; - } - // Recursively populate clone (susceptible to call stack limits). - assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack)); - }); - return result; - } +module.exports = isArguments; - /** - * The base implementation of `_.conforms` which doesn't clone `source`. - * - * @private - * @param {Object} source The object of property predicates to conform to. - * @returns {Function} Returns the new spec function. - */ - function baseConforms(source) { - var props = keys(source); - return function(object) { - return baseConformsTo(object, source, props); - }; - } - /** - * The base implementation of `_.conformsTo` which accepts `props` to check. - * - * @private - * @param {Object} object The object to inspect. - * @param {Object} source The object of property predicates to conform to. - * @returns {boolean} Returns `true` if `object` conforms, else `false`. - */ - function baseConformsTo(object, source, props) { - var length = props.length; - if (object == null) { - return !length; - } - object = Object(object); - while (length--) { - var key = props[length], - predicate = source[key], - value = object[key]; +/***/ }), - if ((value === undefined && !(key in object)) || !predicate(value)) { - return false; - } - } - return true; - } +/***/ 16501: +/***/ ((module) => { - /** - * The base implementation of `_.delay` and `_.defer` which accepts `args` - * to provide to `func`. - * - * @private - * @param {Function} func The function to delay. - * @param {number} wait The number of milliseconds to delay invocation. - * @param {Array} args The arguments to provide to `func`. - * @returns {number|Object} Returns the timer id or timeout object. - */ - function baseDelay(func, wait, args) { - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - return setTimeout(function() { func.apply(undefined, args); }, wait); - } +/** + * lodash 3.0.3 (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright 2012-2016 The Dojo Foundation + * Based on Underscore.js 1.8.3 + * Copyright 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + * Available under MIT license + */ - /** - * The base implementation of methods like `_.difference` without support - * for excluding multiple arrays or iteratee shorthands. - * - * @private - * @param {Array} array The array to inspect. - * @param {Array} values The values to exclude. - * @param {Function} [iteratee] The iteratee invoked per element. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of filtered values. - */ - function baseDifference(array, values, iteratee, comparator) { - var index = -1, - includes = arrayIncludes, - isCommon = true, - length = array.length, - result = [], - valuesLength = values.length; +/** `Object#toString` result references. */ +var boolTag = '[object Boolean]'; - if (!length) { - return result; - } - if (iteratee) { - values = arrayMap(values, baseUnary(iteratee)); - } - if (comparator) { - includes = arrayIncludesWith; - isCommon = false; - } - else if (values.length >= LARGE_ARRAY_SIZE) { - includes = cacheHas; - isCommon = false; - values = new SetCache(values); - } - outer: - while (++index < length) { - var value = array[index], - computed = iteratee == null ? value : iteratee(value); +/** Used for built-in method references. */ +var objectProto = Object.prototype; - value = (comparator || value !== 0) ? value : 0; - if (isCommon && computed === computed) { - var valuesIndex = valuesLength; - while (valuesIndex--) { - if (values[valuesIndex] === computed) { - continue outer; - } - } - result.push(value); - } - else if (!includes(values, computed, comparator)) { - result.push(value); - } - } - return result; - } +/** + * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; + +/** + * Checks if `value` is classified as a boolean primitive or object. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. + * @example + * + * _.isBoolean(false); + * // => true + * + * _.isBoolean(null); + * // => false + */ +function isBoolean(value) { + return value === true || value === false || + (isObjectLike(value) && objectToString.call(value) == boolTag); +} + +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} - /** - * The base implementation of `_.forEach` without support for iteratee shorthands. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array|Object} Returns `collection`. - */ - var baseEach = createBaseEach(baseForOwn); +module.exports = isBoolean; - /** - * The base implementation of `_.forEachRight` without support for iteratee shorthands. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array|Object} Returns `collection`. - */ - var baseEachRight = createBaseEach(baseForOwnRight, true); - /** - * The base implementation of `_.every` without support for iteratee shorthands. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {boolean} Returns `true` if all elements pass the predicate check, - * else `false` - */ - function baseEvery(collection, predicate) { - var result = true; - baseEach(collection, function(value, index, collection) { - result = !!predicate(value, index, collection); - return result; - }); - return result; - } +/***/ }), - /** - * The base implementation of methods like `_.max` and `_.min` which accepts a - * `comparator` to determine the extremum value. - * - * @private - * @param {Array} array The array to iterate over. - * @param {Function} iteratee The iteratee invoked per iteration. - * @param {Function} comparator The comparator used to compare values. - * @returns {*} Returns the extremum value. - */ - function baseExtremum(array, iteratee, comparator) { - var index = -1, - length = array.length; +/***/ 21441: +/***/ ((module) => { - while (++index < length) { - var value = array[index], - current = iteratee(value); +/** + * lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright jQuery Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ - if (current != null && (computed === undefined - ? (current === current && !isSymbol(current)) - : comparator(current, computed) - )) { - var computed = current, - result = value; - } - } - return result; - } +/** Used as references for various `Number` constants. */ +var INFINITY = 1 / 0, + MAX_INTEGER = 1.7976931348623157e+308, + NAN = 0 / 0; - /** - * The base implementation of `_.fill` without an iteratee call guard. - * - * @private - * @param {Array} array The array to fill. - * @param {*} value The value to fill `array` with. - * @param {number} [start=0] The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns `array`. - */ - function baseFill(array, value, start, end) { - var length = array.length; +/** `Object#toString` result references. */ +var symbolTag = '[object Symbol]'; - start = toInteger(start); - if (start < 0) { - start = -start > length ? 0 : (length + start); - } - end = (end === undefined || end > length) ? length : toInteger(end); - if (end < 0) { - end += length; - } - end = start > end ? 0 : toLength(end); - while (start < end) { - array[start++] = value; - } - return array; - } +/** Used to match leading and trailing whitespace. */ +var reTrim = /^\s+|\s+$/g; - /** - * The base implementation of `_.filter` without support for iteratee shorthands. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {Array} Returns the new filtered array. - */ - function baseFilter(collection, predicate) { - var result = []; - baseEach(collection, function(value, index, collection) { - if (predicate(value, index, collection)) { - result.push(value); - } - }); - return result; - } +/** Used to detect bad signed hexadecimal string values. */ +var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; - /** - * The base implementation of `_.flatten` with support for restricting flattening. - * - * @private - * @param {Array} array The array to flatten. - * @param {number} depth The maximum recursion depth. - * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. - * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. - * @param {Array} [result=[]] The initial result value. - * @returns {Array} Returns the new flattened array. - */ - function baseFlatten(array, depth, predicate, isStrict, result) { - var index = -1, - length = array.length; +/** Used to detect binary string values. */ +var reIsBinary = /^0b[01]+$/i; - predicate || (predicate = isFlattenable); - result || (result = []); +/** Used to detect octal string values. */ +var reIsOctal = /^0o[0-7]+$/i; - while (++index < length) { - var value = array[index]; - if (depth > 0 && predicate(value)) { - if (depth > 1) { - // Recursively flatten arrays (susceptible to call stack limits). - baseFlatten(value, depth - 1, predicate, isStrict, result); - } else { - arrayPush(result, value); - } - } else if (!isStrict) { - result[result.length] = value; - } - } - return result; - } +/** Built-in method references without a dependency on `root`. */ +var freeParseInt = parseInt; - /** - * The base implementation of `baseForOwn` which iterates over `object` - * properties returned by `keysFunc` and invokes `iteratee` for each property. - * Iteratee functions may exit iteration early by explicitly returning `false`. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {Function} keysFunc The function to get the keys of `object`. - * @returns {Object} Returns `object`. - */ - var baseFor = createBaseFor(); +/** Used for built-in method references. */ +var objectProto = Object.prototype; - /** - * This function is like `baseFor` except that it iterates over properties - * in the opposite order. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {Function} keysFunc The function to get the keys of `object`. - * @returns {Object} Returns `object`. - */ - var baseForRight = createBaseFor(true); +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; - /** - * The base implementation of `_.forOwn` without support for iteratee shorthands. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Object} Returns `object`. - */ - function baseForOwn(object, iteratee) { - return object && baseFor(object, iteratee, keys); - } +/** + * Checks if `value` is an integer. + * + * **Note:** This method is based on + * [`Number.isInteger`](https://mdn.io/Number/isInteger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an integer, else `false`. + * @example + * + * _.isInteger(3); + * // => true + * + * _.isInteger(Number.MIN_VALUE); + * // => false + * + * _.isInteger(Infinity); + * // => false + * + * _.isInteger('3'); + * // => false + */ +function isInteger(value) { + return typeof value == 'number' && value == toInteger(value); +} - /** - * The base implementation of `_.forOwnRight` without support for iteratee shorthands. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Object} Returns `object`. - */ - function baseForOwnRight(object, iteratee) { - return object && baseForRight(object, iteratee, keys); - } +/** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ +function isObject(value) { + var type = typeof value; + return !!value && (type == 'object' || type == 'function'); +} - /** - * The base implementation of `_.functions` which creates an array of - * `object` function property names filtered from `props`. - * - * @private - * @param {Object} object The object to inspect. - * @param {Array} props The property names to filter. - * @returns {Array} Returns the function names. - */ - function baseFunctions(object, props) { - return arrayFilter(props, function(key) { - return isFunction(object[key]); - }); - } +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} - /** - * The base implementation of `_.get` without support for default values. - * - * @private - * @param {Object} object The object to query. - * @param {Array|string} path The path of the property to get. - * @returns {*} Returns the resolved value. - */ - function baseGet(object, path) { - path = castPath(path, object); +/** + * Checks if `value` is classified as a `Symbol` primitive or object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. + * @example + * + * _.isSymbol(Symbol.iterator); + * // => true + * + * _.isSymbol('abc'); + * // => false + */ +function isSymbol(value) { + return typeof value == 'symbol' || + (isObjectLike(value) && objectToString.call(value) == symbolTag); +} - var index = 0, - length = path.length; +/** + * Converts `value` to a finite number. + * + * @static + * @memberOf _ + * @since 4.12.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted number. + * @example + * + * _.toFinite(3.2); + * // => 3.2 + * + * _.toFinite(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toFinite(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toFinite('3.2'); + * // => 3.2 + */ +function toFinite(value) { + if (!value) { + return value === 0 ? value : 0; + } + value = toNumber(value); + if (value === INFINITY || value === -INFINITY) { + var sign = (value < 0 ? -1 : 1); + return sign * MAX_INTEGER; + } + return value === value ? value : 0; +} - while (object != null && index < length) { - object = object[toKey(path[index++])]; - } - return (index && index == length) ? object : undefined; - } +/** + * Converts `value` to an integer. + * + * **Note:** This method is loosely based on + * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. + * @example + * + * _.toInteger(3.2); + * // => 3 + * + * _.toInteger(Number.MIN_VALUE); + * // => 0 + * + * _.toInteger(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toInteger('3.2'); + * // => 3 + */ +function toInteger(value) { + var result = toFinite(value), + remainder = result % 1; - /** - * The base implementation of `getAllKeys` and `getAllKeysIn` which uses - * `keysFunc` and `symbolsFunc` to get the enumerable property names and - * symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @param {Function} keysFunc The function to get the keys of `object`. - * @param {Function} symbolsFunc The function to get the symbols of `object`. - * @returns {Array} Returns the array of property names and symbols. - */ - function baseGetAllKeys(object, keysFunc, symbolsFunc) { - var result = keysFunc(object); - return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); - } + return result === result ? (remainder ? result - remainder : result) : 0; +} - /** - * The base implementation of `getTag` without fallbacks for buggy environments. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the `toStringTag`. - */ - function baseGetTag(value) { - if (value == null) { - return value === undefined ? undefinedTag : nullTag; - } - return (symToStringTag && symToStringTag in Object(value)) - ? getRawTag(value) - : objectToString(value); - } +/** + * Converts `value` to a number. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to process. + * @returns {number} Returns the number. + * @example + * + * _.toNumber(3.2); + * // => 3.2 + * + * _.toNumber(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toNumber(Infinity); + * // => Infinity + * + * _.toNumber('3.2'); + * // => 3.2 + */ +function toNumber(value) { + if (typeof value == 'number') { + return value; + } + if (isSymbol(value)) { + return NAN; + } + if (isObject(value)) { + var other = typeof value.valueOf == 'function' ? value.valueOf() : value; + value = isObject(other) ? (other + '') : other; + } + if (typeof value != 'string') { + return value === 0 ? value : +value; + } + value = value.replace(reTrim, ''); + var isBinary = reIsBinary.test(value); + return (isBinary || reIsOctal.test(value)) + ? freeParseInt(value.slice(2), isBinary ? 2 : 8) + : (reIsBadHex.test(value) ? NAN : +value); +} + +module.exports = isInteger; + + +/***/ }), + +/***/ 40298: +/***/ ((module) => { + +/** + * lodash 3.0.3 (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright 2012-2016 The Dojo Foundation + * Based on Underscore.js 1.8.3 + * Copyright 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + * Available under MIT license + */ - /** - * The base implementation of `_.gt` which doesn't coerce arguments. - * - * @private - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if `value` is greater than `other`, - * else `false`. - */ - function baseGt(value, other) { - return value > other; - } +/** `Object#toString` result references. */ +var numberTag = '[object Number]'; - /** - * The base implementation of `_.has` without support for deep paths. - * - * @private - * @param {Object} [object] The object to query. - * @param {Array|string} key The key to check. - * @returns {boolean} Returns `true` if `key` exists, else `false`. - */ - function baseHas(object, key) { - return object != null && hasOwnProperty.call(object, key); - } +/** Used for built-in method references. */ +var objectProto = Object.prototype; - /** - * The base implementation of `_.hasIn` without support for deep paths. - * - * @private - * @param {Object} [object] The object to query. - * @param {Array|string} key The key to check. - * @returns {boolean} Returns `true` if `key` exists, else `false`. - */ - function baseHasIn(object, key) { - return object != null && key in Object(object); - } +/** + * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; - /** - * The base implementation of `_.inRange` which doesn't coerce arguments. - * - * @private - * @param {number} number The number to check. - * @param {number} start The start of the range. - * @param {number} end The end of the range. - * @returns {boolean} Returns `true` if `number` is in the range, else `false`. - */ - function baseInRange(number, start, end) { - return number >= nativeMin(start, end) && number < nativeMax(start, end); - } +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} - /** - * The base implementation of methods like `_.intersection`, without support - * for iteratee shorthands, that accepts an array of arrays to inspect. - * - * @private - * @param {Array} arrays The arrays to inspect. - * @param {Function} [iteratee] The iteratee invoked per element. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of shared values. - */ - function baseIntersection(arrays, iteratee, comparator) { - var includes = comparator ? arrayIncludesWith : arrayIncludes, - length = arrays[0].length, - othLength = arrays.length, - othIndex = othLength, - caches = Array(othLength), - maxLength = Infinity, - result = []; +/** + * Checks if `value` is classified as a `Number` primitive or object. + * + * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are classified + * as numbers, use the `_.isFinite` method. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. + * @example + * + * _.isNumber(3); + * // => true + * + * _.isNumber(Number.MIN_VALUE); + * // => true + * + * _.isNumber(Infinity); + * // => true + * + * _.isNumber('3'); + * // => false + */ +function isNumber(value) { + return typeof value == 'number' || + (isObjectLike(value) && objectToString.call(value) == numberTag); +} - while (othIndex--) { - var array = arrays[othIndex]; - if (othIndex && iteratee) { - array = arrayMap(array, baseUnary(iteratee)); - } - maxLength = nativeMin(array.length, maxLength); - caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120)) - ? new SetCache(othIndex && array) - : undefined; - } - array = arrays[0]; +module.exports = isNumber; - var index = -1, - seen = caches[0]; - outer: - while (++index < length && result.length < maxLength) { - var value = array[index], - computed = iteratee ? iteratee(value) : value; +/***/ }), - value = (comparator || value !== 0) ? value : 0; - if (!(seen - ? cacheHas(seen, computed) - : includes(result, computed, comparator) - )) { - othIndex = othLength; - while (--othIndex) { - var cache = caches[othIndex]; - if (!(cache - ? cacheHas(cache, computed) - : includes(arrays[othIndex], computed, comparator)) - ) { - continue outer; - } - } - if (seen) { - seen.push(computed); - } - result.push(value); - } - } - return result; - } +/***/ 25723: +/***/ ((module) => { - /** - * The base implementation of `_.invert` and `_.invertBy` which inverts - * `object` with values transformed by `iteratee` and set by `setter`. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} setter The function to set `accumulator` values. - * @param {Function} iteratee The iteratee to transform values. - * @param {Object} accumulator The initial inverted object. - * @returns {Function} Returns `accumulator`. - */ - function baseInverter(object, setter, iteratee, accumulator) { - baseForOwn(object, function(value, key, object) { - setter(accumulator, iteratee(value), key, object); - }); - return accumulator; - } +/** + * lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright jQuery Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ - /** - * The base implementation of `_.invoke` without support for individual - * method arguments. - * - * @private - * @param {Object} object The object to query. - * @param {Array|string} path The path of the method to invoke. - * @param {Array} args The arguments to invoke the method with. - * @returns {*} Returns the result of the invoked method. - */ - function baseInvoke(object, path, args) { - path = castPath(path, object); - object = parent(object, path); - var func = object == null ? object : object[toKey(last(path))]; - return func == null ? undefined : apply(func, object, args); - } +/** `Object#toString` result references. */ +var objectTag = '[object Object]'; - /** - * The base implementation of `_.isArguments`. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - */ - function baseIsArguments(value) { - return isObjectLike(value) && baseGetTag(value) == argsTag; - } +/** + * Checks if `value` is a host object in IE < 9. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a host object, else `false`. + */ +function isHostObject(value) { + // Many host objects are `Object` objects that can coerce to strings + // despite having improperly defined `toString` methods. + var result = false; + if (value != null && typeof value.toString != 'function') { + try { + result = !!(value + ''); + } catch (e) {} + } + return result; +} - /** - * The base implementation of `_.isArrayBuffer` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. - */ - function baseIsArrayBuffer(value) { - return isObjectLike(value) && baseGetTag(value) == arrayBufferTag; - } +/** + * Creates a unary function that invokes `func` with its argument transformed. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ +function overArg(func, transform) { + return function(arg) { + return func(transform(arg)); + }; +} - /** - * The base implementation of `_.isDate` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a date object, else `false`. - */ - function baseIsDate(value) { - return isObjectLike(value) && baseGetTag(value) == dateTag; - } +/** Used for built-in method references. */ +var funcProto = Function.prototype, + objectProto = Object.prototype; - /** - * The base implementation of `_.isEqual` which supports partial comparisons - * and tracks traversed objects. - * - * @private - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @param {boolean} bitmask The bitmask flags. - * 1 - Unordered comparison - * 2 - Partial comparison - * @param {Function} [customizer] The function to customize comparisons. - * @param {Object} [stack] Tracks traversed `value` and `other` objects. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - */ - function baseIsEqual(value, other, bitmask, customizer, stack) { - if (value === other) { - return true; - } - if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) { - return value !== value && other !== other; - } - return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); - } +/** Used to resolve the decompiled source of functions. */ +var funcToString = funcProto.toString; - /** - * A specialized version of `baseIsEqual` for arrays and objects which performs - * deep comparisons and tracks traversed objects enabling objects with circular - * references to be compared. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} [stack] Tracks traversed `object` and `other` objects. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. - */ - function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { - var objIsArr = isArray(object), - othIsArr = isArray(other), - objTag = objIsArr ? arrayTag : getTag(object), - othTag = othIsArr ? arrayTag : getTag(other); +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; - objTag = objTag == argsTag ? objectTag : objTag; - othTag = othTag == argsTag ? objectTag : othTag; +/** Used to infer the `Object` constructor. */ +var objectCtorString = funcToString.call(Object); - var objIsObj = objTag == objectTag, - othIsObj = othTag == objectTag, - isSameTag = objTag == othTag; +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; - if (isSameTag && isBuffer(object)) { - if (!isBuffer(other)) { - return false; - } - objIsArr = true; - objIsObj = false; - } - if (isSameTag && !objIsObj) { - stack || (stack = new Stack); - return (objIsArr || isTypedArray(object)) - ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) - : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); - } - if (!(bitmask & COMPARE_PARTIAL_FLAG)) { - var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), - othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); +/** Built-in value references. */ +var getPrototype = overArg(Object.getPrototypeOf, Object); - if (objIsWrapped || othIsWrapped) { - var objUnwrapped = objIsWrapped ? object.value() : object, - othUnwrapped = othIsWrapped ? other.value() : other; +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} - stack || (stack = new Stack); - return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); - } - } - if (!isSameTag) { - return false; - } - stack || (stack = new Stack); - return equalObjects(object, other, bitmask, customizer, equalFunc, stack); - } +/** + * Checks if `value` is a plain object, that is, an object created by the + * `Object` constructor or one with a `[[Prototype]]` of `null`. + * + * @static + * @memberOf _ + * @since 0.8.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * _.isPlainObject(new Foo); + * // => false + * + * _.isPlainObject([1, 2, 3]); + * // => false + * + * _.isPlainObject({ 'x': 0, 'y': 0 }); + * // => true + * + * _.isPlainObject(Object.create(null)); + * // => true + */ +function isPlainObject(value) { + if (!isObjectLike(value) || + objectToString.call(value) != objectTag || isHostObject(value)) { + return false; + } + var proto = getPrototype(value); + if (proto === null) { + return true; + } + var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; + return (typeof Ctor == 'function' && + Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString); +} - /** - * The base implementation of `_.isMap` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a map, else `false`. - */ - function baseIsMap(value) { - return isObjectLike(value) && getTag(value) == mapTag; - } +module.exports = isPlainObject; - /** - * The base implementation of `_.isMatch` without support for iteratee shorthands. - * - * @private - * @param {Object} object The object to inspect. - * @param {Object} source The object of property values to match. - * @param {Array} matchData The property names, values, and compare flags to match. - * @param {Function} [customizer] The function to customize comparisons. - * @returns {boolean} Returns `true` if `object` is a match, else `false`. - */ - function baseIsMatch(object, source, matchData, customizer) { - var index = matchData.length, - length = index, - noCustomizer = !customizer; - if (object == null) { - return !length; - } - object = Object(object); - while (index--) { - var data = matchData[index]; - if ((noCustomizer && data[2]) - ? data[1] !== object[data[0]] - : !(data[0] in object) - ) { - return false; - } - } - while (++index < length) { - data = matchData[index]; - var key = data[0], - objValue = object[key], - srcValue = data[1]; +/***/ }), - if (noCustomizer && data[2]) { - if (objValue === undefined && !(key in object)) { - return false; - } - } else { - var stack = new Stack; - if (customizer) { - var result = customizer(objValue, srcValue, key, object, source, stack); - } - if (!(result === undefined - ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack) - : result - )) { - return false; - } - } - } - return true; - } +/***/ 25180: +/***/ ((module) => { + +/** + * lodash 4.0.1 (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright 2012-2016 The Dojo Foundation + * Based on Underscore.js 1.8.3 + * Copyright 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + * Available under MIT license + */ - /** - * The base implementation of `_.isNative` without bad shim checks. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a native function, - * else `false`. - */ - function baseIsNative(value) { - if (!isObject(value) || isMasked(value)) { - return false; - } - var pattern = isFunction(value) ? reIsNative : reIsHostCtor; - return pattern.test(toSource(value)); - } +/** `Object#toString` result references. */ +var stringTag = '[object String]'; - /** - * The base implementation of `_.isRegExp` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. - */ - function baseIsRegExp(value) { - return isObjectLike(value) && baseGetTag(value) == regexpTag; - } +/** Used for built-in method references. */ +var objectProto = Object.prototype; - /** - * The base implementation of `_.isSet` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a set, else `false`. - */ - function baseIsSet(value) { - return isObjectLike(value) && getTag(value) == setTag; - } +/** + * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; - /** - * The base implementation of `_.isTypedArray` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. - */ - function baseIsTypedArray(value) { - return isObjectLike(value) && - isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; - } +/** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @type Function + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ +var isArray = Array.isArray; - /** - * The base implementation of `_.iteratee`. - * - * @private - * @param {*} [value=_.identity] The value to convert to an iteratee. - * @returns {Function} Returns the iteratee. - */ - function baseIteratee(value) { - // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. - // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. - if (typeof value == 'function') { - return value; - } - if (value == null) { - return identity; - } - if (typeof value == 'object') { - return isArray(value) - ? baseMatchesProperty(value[0], value[1]) - : baseMatches(value); - } - return property(value); - } +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} - /** - * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ - function baseKeys(object) { - if (!isPrototype(object)) { - return nativeKeys(object); - } - var result = []; - for (var key in Object(object)) { - if (hasOwnProperty.call(object, key) && key != 'constructor') { - result.push(key); - } - } - return result; - } +/** + * Checks if `value` is classified as a `String` primitive or object. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. + * @example + * + * _.isString('abc'); + * // => true + * + * _.isString(1); + * // => false + */ +function isString(value) { + return typeof value == 'string' || + (!isArray(value) && isObjectLike(value) && objectToString.call(value) == stringTag); +} - /** - * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ - function baseKeysIn(object) { - if (!isObject(object)) { - return nativeKeysIn(object); - } - var isProto = isPrototype(object), - result = []; +module.exports = isString; - for (var key in object) { - if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { - result.push(key); - } - } - return result; - } - /** - * The base implementation of `_.lt` which doesn't coerce arguments. - * - * @private - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if `value` is less than `other`, - * else `false`. - */ - function baseLt(value, other) { - return value < other; - } +/***/ }), - /** - * The base implementation of `_.map` without support for iteratee shorthands. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the new mapped array. - */ - function baseMap(collection, iteratee) { - var index = -1, - result = isArrayLike(collection) ? Array(collection.length) : []; +/***/ 94499: +/***/ ((module) => { - baseEach(collection, function(value, key, collection) { - result[++index] = iteratee(value, key, collection); - }); - return result; - } +/** + * lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright jQuery Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ - /** - * The base implementation of `_.matches` which doesn't clone `source`. - * - * @private - * @param {Object} source The object of property values to match. - * @returns {Function} Returns the new spec function. - */ - function baseMatches(source) { - var matchData = getMatchData(source); - if (matchData.length == 1 && matchData[0][2]) { - return matchesStrictComparable(matchData[0][0], matchData[0][1]); - } - return function(object) { - return object === source || baseIsMatch(object, source, matchData); - }; - } +/** Used as the `TypeError` message for "Functions" methods. */ +var FUNC_ERROR_TEXT = 'Expected a function'; - /** - * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. - * - * @private - * @param {string} path The path of the property to get. - * @param {*} srcValue The value to match. - * @returns {Function} Returns the new spec function. - */ - function baseMatchesProperty(path, srcValue) { - if (isKey(path) && isStrictComparable(srcValue)) { - return matchesStrictComparable(toKey(path), srcValue); - } - return function(object) { - var objValue = get(object, path); - return (objValue === undefined && objValue === srcValue) - ? hasIn(object, path) - : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG); - }; - } +/** Used as references for various `Number` constants. */ +var INFINITY = 1 / 0, + MAX_INTEGER = 1.7976931348623157e+308, + NAN = 0 / 0; - /** - * The base implementation of `_.merge` without support for multiple sources. - * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @param {number} srcIndex The index of `source`. - * @param {Function} [customizer] The function to customize merged values. - * @param {Object} [stack] Tracks traversed source values and their merged - * counterparts. - */ - function baseMerge(object, source, srcIndex, customizer, stack) { - if (object === source) { - return; - } - baseFor(source, function(srcValue, key) { - stack || (stack = new Stack); - if (isObject(srcValue)) { - baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); - } - else { - var newValue = customizer - ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack) - : undefined; +/** `Object#toString` result references. */ +var symbolTag = '[object Symbol]'; - if (newValue === undefined) { - newValue = srcValue; - } - assignMergeValue(object, key, newValue); - } - }, keysIn); - } +/** Used to match leading and trailing whitespace. */ +var reTrim = /^\s+|\s+$/g; - /** - * A specialized version of `baseMerge` for arrays and objects which performs - * deep merges and tracks traversed objects enabling objects with circular - * references to be merged. - * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @param {string} key The key of the value to merge. - * @param {number} srcIndex The index of `source`. - * @param {Function} mergeFunc The function to merge values. - * @param {Function} [customizer] The function to customize assigned values. - * @param {Object} [stack] Tracks traversed source values and their merged - * counterparts. - */ - function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { - var objValue = safeGet(object, key), - srcValue = safeGet(source, key), - stacked = stack.get(srcValue); +/** Used to detect bad signed hexadecimal string values. */ +var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; - if (stacked) { - assignMergeValue(object, key, stacked); - return; - } - var newValue = customizer - ? customizer(objValue, srcValue, (key + ''), object, source, stack) - : undefined; +/** Used to detect binary string values. */ +var reIsBinary = /^0b[01]+$/i; - var isCommon = newValue === undefined; +/** Used to detect octal string values. */ +var reIsOctal = /^0o[0-7]+$/i; - if (isCommon) { - var isArr = isArray(srcValue), - isBuff = !isArr && isBuffer(srcValue), - isTyped = !isArr && !isBuff && isTypedArray(srcValue); +/** Built-in method references without a dependency on `root`. */ +var freeParseInt = parseInt; - newValue = srcValue; - if (isArr || isBuff || isTyped) { - if (isArray(objValue)) { - newValue = objValue; - } - else if (isArrayLikeObject(objValue)) { - newValue = copyArray(objValue); - } - else if (isBuff) { - isCommon = false; - newValue = cloneBuffer(srcValue, true); - } - else if (isTyped) { - isCommon = false; - newValue = cloneTypedArray(srcValue, true); - } - else { - newValue = []; - } - } - else if (isPlainObject(srcValue) || isArguments(srcValue)) { - newValue = objValue; - if (isArguments(objValue)) { - newValue = toPlainObject(objValue); - } - else if (!isObject(objValue) || isFunction(objValue)) { - newValue = initCloneObject(srcValue); - } - } - else { - isCommon = false; - } - } - if (isCommon) { - // Recursively merge objects and arrays (susceptible to call stack limits). - stack.set(srcValue, newValue); - mergeFunc(newValue, srcValue, srcIndex, customizer, stack); - stack['delete'](srcValue); - } - assignMergeValue(object, key, newValue); - } +/** Used for built-in method references. */ +var objectProto = Object.prototype; - /** - * The base implementation of `_.nth` which doesn't coerce arguments. - * - * @private - * @param {Array} array The array to query. - * @param {number} n The index of the element to return. - * @returns {*} Returns the nth element of `array`. - */ - function baseNth(array, n) { - var length = array.length; - if (!length) { - return; - } - n += n < 0 ? length : 0; - return isIndex(n, length) ? array[n] : undefined; +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; + +/** + * Creates a function that invokes `func`, with the `this` binding and arguments + * of the created function, while it's called less than `n` times. Subsequent + * calls to the created function return the result of the last `func` invocation. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {number} n The number of calls at which `func` is no longer invoked. + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * jQuery(element).on('click', _.before(5, addContactToList)); + * // => Allows adding up to 4 contacts to the list. + */ +function before(n, func) { + var result; + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + n = toInteger(n); + return function() { + if (--n > 0) { + result = func.apply(this, arguments); + } + if (n <= 1) { + func = undefined; } + return result; + }; +} - /** - * The base implementation of `_.orderBy` without param guards. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by. - * @param {string[]} orders The sort orders of `iteratees`. - * @returns {Array} Returns the new sorted array. - */ - function baseOrderBy(collection, iteratees, orders) { - if (iteratees.length) { - iteratees = arrayMap(iteratees, function(iteratee) { - if (isArray(iteratee)) { - return function(value) { - return baseGet(value, iteratee.length === 1 ? iteratee[0] : iteratee); - } - } - return iteratee; - }); - } else { - iteratees = [identity]; - } +/** + * Creates a function that is restricted to invoking `func` once. Repeat calls + * to the function return the value of the first invocation. The `func` is + * invoked with the `this` binding and arguments of the created function. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * var initialize = _.once(createApplication); + * initialize(); + * initialize(); + * // => `createApplication` is invoked once + */ +function once(func) { + return before(2, func); +} - var index = -1; - iteratees = arrayMap(iteratees, baseUnary(getIteratee())); +/** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ +function isObject(value) { + var type = typeof value; + return !!value && (type == 'object' || type == 'function'); +} - var result = baseMap(collection, function(value, key, collection) { - var criteria = arrayMap(iteratees, function(iteratee) { - return iteratee(value); - }); - return { 'criteria': criteria, 'index': ++index, 'value': value }; - }); +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} - return baseSortBy(result, function(object, other) { - return compareMultiple(object, other, orders); - }); - } +/** + * Checks if `value` is classified as a `Symbol` primitive or object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. + * @example + * + * _.isSymbol(Symbol.iterator); + * // => true + * + * _.isSymbol('abc'); + * // => false + */ +function isSymbol(value) { + return typeof value == 'symbol' || + (isObjectLike(value) && objectToString.call(value) == symbolTag); +} - /** - * The base implementation of `_.pick` without support for individual - * property identifiers. - * - * @private - * @param {Object} object The source object. - * @param {string[]} paths The property paths to pick. - * @returns {Object} Returns the new object. - */ - function basePick(object, paths) { - return basePickBy(object, paths, function(value, path) { - return hasIn(object, path); - }); - } +/** + * Converts `value` to a finite number. + * + * @static + * @memberOf _ + * @since 4.12.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted number. + * @example + * + * _.toFinite(3.2); + * // => 3.2 + * + * _.toFinite(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toFinite(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toFinite('3.2'); + * // => 3.2 + */ +function toFinite(value) { + if (!value) { + return value === 0 ? value : 0; + } + value = toNumber(value); + if (value === INFINITY || value === -INFINITY) { + var sign = (value < 0 ? -1 : 1); + return sign * MAX_INTEGER; + } + return value === value ? value : 0; +} - /** - * The base implementation of `_.pickBy` without support for iteratee shorthands. - * - * @private - * @param {Object} object The source object. - * @param {string[]} paths The property paths to pick. - * @param {Function} predicate The function invoked per property. - * @returns {Object} Returns the new object. - */ - function basePickBy(object, paths, predicate) { - var index = -1, - length = paths.length, - result = {}; +/** + * Converts `value` to an integer. + * + * **Note:** This method is loosely based on + * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. + * @example + * + * _.toInteger(3.2); + * // => 3 + * + * _.toInteger(Number.MIN_VALUE); + * // => 0 + * + * _.toInteger(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toInteger('3.2'); + * // => 3 + */ +function toInteger(value) { + var result = toFinite(value), + remainder = result % 1; - while (++index < length) { - var path = paths[index], - value = baseGet(object, path); + return result === result ? (remainder ? result - remainder : result) : 0; +} - if (predicate(value, path)) { - baseSet(result, castPath(path, object), value); - } - } - return result; - } +/** + * Converts `value` to a number. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to process. + * @returns {number} Returns the number. + * @example + * + * _.toNumber(3.2); + * // => 3.2 + * + * _.toNumber(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toNumber(Infinity); + * // => Infinity + * + * _.toNumber('3.2'); + * // => 3.2 + */ +function toNumber(value) { + if (typeof value == 'number') { + return value; + } + if (isSymbol(value)) { + return NAN; + } + if (isObject(value)) { + var other = typeof value.valueOf == 'function' ? value.valueOf() : value; + value = isObject(other) ? (other + '') : other; + } + if (typeof value != 'string') { + return value === 0 ? value : +value; + } + value = value.replace(reTrim, ''); + var isBinary = reIsBinary.test(value); + return (isBinary || reIsOctal.test(value)) + ? freeParseInt(value.slice(2), isBinary ? 2 : 8) + : (reIsBadHex.test(value) ? NAN : +value); +} - /** - * A specialized version of `baseProperty` which supports deep paths. - * - * @private - * @param {Array|string} path The path of the property to get. - * @returns {Function} Returns the new accessor function. - */ - function basePropertyDeep(path) { - return function(object) { - return baseGet(object, path); - }; - } +module.exports = once; - /** - * The base implementation of `_.pullAllBy` without support for iteratee - * shorthands. - * - * @private - * @param {Array} array The array to modify. - * @param {Array} values The values to remove. - * @param {Function} [iteratee] The iteratee invoked per element. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns `array`. - */ - function basePullAll(array, values, iteratee, comparator) { - var indexOf = comparator ? baseIndexOfWith : baseIndexOf, - index = -1, - length = values.length, - seen = array; - if (array === values) { - values = copyArray(values); - } - if (iteratee) { - seen = arrayMap(array, baseUnary(iteratee)); - } - while (++index < length) { - var fromIndex = 0, - value = values[index], - computed = iteratee ? iteratee(value) : value; +/***/ }), - while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) { - if (seen !== array) { - splice.call(seen, fromIndex, 1); - } - splice.call(array, fromIndex, 1); - } - } - return array; - } +/***/ 90250: +/***/ (function(module, exports, __nccwpck_require__) { - /** - * The base implementation of `_.pullAt` without support for individual - * indexes or capturing the removed elements. - * - * @private - * @param {Array} array The array to modify. - * @param {number[]} indexes The indexes of elements to remove. - * @returns {Array} Returns `array`. - */ - function basePullAt(array, indexes) { - var length = array ? indexes.length : 0, - lastIndex = length - 1; +/* module decorator */ module = __nccwpck_require__.nmd(module); +/** + * @license + * Lodash + * Copyright OpenJS Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ +;(function() { - while (length--) { - var index = indexes[length]; - if (length == lastIndex || index !== previous) { - var previous = index; - if (isIndex(index)) { - splice.call(array, index, 1); - } else { - baseUnset(array, index); - } - } - } - return array; - } + /** Used as a safe reference for `undefined` in pre-ES5 environments. */ + var undefined; - /** - * The base implementation of `_.random` without support for returning - * floating-point numbers. - * - * @private - * @param {number} lower The lower bound. - * @param {number} upper The upper bound. - * @returns {number} Returns the random number. - */ - function baseRandom(lower, upper) { - return lower + nativeFloor(nativeRandom() * (upper - lower + 1)); - } + /** Used as the semantic version number. */ + var VERSION = '4.17.21'; - /** - * The base implementation of `_.range` and `_.rangeRight` which doesn't - * coerce arguments. - * - * @private - * @param {number} start The start of the range. - * @param {number} end The end of the range. - * @param {number} step The value to increment or decrement by. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Array} Returns the range of numbers. - */ - function baseRange(start, end, step, fromRight) { - var index = -1, - length = nativeMax(nativeCeil((end - start) / (step || 1)), 0), - result = Array(length); + /** Used as the size to enable large array optimizations. */ + var LARGE_ARRAY_SIZE = 200; - while (length--) { - result[fromRight ? length : ++index] = start; - start += step; - } - return result; - } + /** Error message constants. */ + var CORE_ERROR_TEXT = 'Unsupported core-js use. Try https://npms.io/search?q=ponyfill.', + FUNC_ERROR_TEXT = 'Expected a function', + INVALID_TEMPL_VAR_ERROR_TEXT = 'Invalid `variable` option passed into `_.template`'; - /** - * The base implementation of `_.repeat` which doesn't coerce arguments. - * - * @private - * @param {string} string The string to repeat. - * @param {number} n The number of times to repeat the string. - * @returns {string} Returns the repeated string. - */ - function baseRepeat(string, n) { - var result = ''; - if (!string || n < 1 || n > MAX_SAFE_INTEGER) { - return result; - } - // Leverage the exponentiation by squaring algorithm for a faster repeat. - // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details. - do { - if (n % 2) { - result += string; - } - n = nativeFloor(n / 2); - if (n) { - string += string; - } - } while (n); + /** Used to stand-in for `undefined` hash values. */ + var HASH_UNDEFINED = '__lodash_hash_undefined__'; - return result; - } + /** Used as the maximum memoize cache size. */ + var MAX_MEMOIZE_SIZE = 500; - /** - * The base implementation of `_.rest` which doesn't validate or coerce arguments. - * - * @private - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @returns {Function} Returns the new function. - */ - function baseRest(func, start) { - return setToString(overRest(func, start, identity), func + ''); - } + /** Used as the internal argument placeholder. */ + var PLACEHOLDER = '__lodash_placeholder__'; - /** - * The base implementation of `_.sample`. - * - * @private - * @param {Array|Object} collection The collection to sample. - * @returns {*} Returns the random element. - */ - function baseSample(collection) { - return arraySample(values(collection)); - } + /** Used to compose bitmasks for cloning. */ + var CLONE_DEEP_FLAG = 1, + CLONE_FLAT_FLAG = 2, + CLONE_SYMBOLS_FLAG = 4; - /** - * The base implementation of `_.sampleSize` without param guards. - * - * @private - * @param {Array|Object} collection The collection to sample. - * @param {number} n The number of elements to sample. - * @returns {Array} Returns the random elements. - */ - function baseSampleSize(collection, n) { - var array = values(collection); - return shuffleSelf(array, baseClamp(n, 0, array.length)); - } + /** Used to compose bitmasks for value comparisons. */ + var COMPARE_PARTIAL_FLAG = 1, + COMPARE_UNORDERED_FLAG = 2; - /** - * The base implementation of `_.set`. - * - * @private - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to set. - * @param {*} value The value to set. - * @param {Function} [customizer] The function to customize path creation. - * @returns {Object} Returns `object`. - */ - function baseSet(object, path, value, customizer) { - if (!isObject(object)) { - return object; - } - path = castPath(path, object); + /** Used to compose bitmasks for function metadata. */ + var WRAP_BIND_FLAG = 1, + WRAP_BIND_KEY_FLAG = 2, + WRAP_CURRY_BOUND_FLAG = 4, + WRAP_CURRY_FLAG = 8, + WRAP_CURRY_RIGHT_FLAG = 16, + WRAP_PARTIAL_FLAG = 32, + WRAP_PARTIAL_RIGHT_FLAG = 64, + WRAP_ARY_FLAG = 128, + WRAP_REARG_FLAG = 256, + WRAP_FLIP_FLAG = 512; - var index = -1, - length = path.length, - lastIndex = length - 1, - nested = object; + /** Used as default options for `_.truncate`. */ + var DEFAULT_TRUNC_LENGTH = 30, + DEFAULT_TRUNC_OMISSION = '...'; - while (nested != null && ++index < length) { - var key = toKey(path[index]), - newValue = value; + /** Used to detect hot functions by number of calls within a span of milliseconds. */ + var HOT_COUNT = 800, + HOT_SPAN = 16; - if (key === '__proto__' || key === 'constructor' || key === 'prototype') { - return object; - } + /** Used to indicate the type of lazy iteratees. */ + var LAZY_FILTER_FLAG = 1, + LAZY_MAP_FLAG = 2, + LAZY_WHILE_FLAG = 3; - if (index != lastIndex) { - var objValue = nested[key]; - newValue = customizer ? customizer(objValue, key, nested) : undefined; - if (newValue === undefined) { - newValue = isObject(objValue) - ? objValue - : (isIndex(path[index + 1]) ? [] : {}); - } - } - assignValue(nested, key, newValue); - nested = nested[key]; - } - return object; - } + /** Used as references for various `Number` constants. */ + var INFINITY = 1 / 0, + MAX_SAFE_INTEGER = 9007199254740991, + MAX_INTEGER = 1.7976931348623157e+308, + NAN = 0 / 0; - /** - * The base implementation of `setData` without support for hot loop shorting. - * - * @private - * @param {Function} func The function to associate metadata with. - * @param {*} data The metadata. - * @returns {Function} Returns `func`. - */ - var baseSetData = !metaMap ? identity : function(func, data) { - metaMap.set(func, data); - return func; - }; + /** Used as references for the maximum length and index of an array. */ + var MAX_ARRAY_LENGTH = 4294967295, + MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1, + HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1; - /** - * The base implementation of `setToString` without support for hot loop shorting. - * - * @private - * @param {Function} func The function to modify. - * @param {Function} string The `toString` result. - * @returns {Function} Returns `func`. - */ - var baseSetToString = !defineProperty ? identity : function(func, string) { - return defineProperty(func, 'toString', { - 'configurable': true, - 'enumerable': false, - 'value': constant(string), - 'writable': true - }); - }; + /** Used to associate wrap methods with their bit flags. */ + var wrapFlags = [ + ['ary', WRAP_ARY_FLAG], + ['bind', WRAP_BIND_FLAG], + ['bindKey', WRAP_BIND_KEY_FLAG], + ['curry', WRAP_CURRY_FLAG], + ['curryRight', WRAP_CURRY_RIGHT_FLAG], + ['flip', WRAP_FLIP_FLAG], + ['partial', WRAP_PARTIAL_FLAG], + ['partialRight', WRAP_PARTIAL_RIGHT_FLAG], + ['rearg', WRAP_REARG_FLAG] + ]; - /** - * The base implementation of `_.shuffle`. - * - * @private - * @param {Array|Object} collection The collection to shuffle. - * @returns {Array} Returns the new shuffled array. - */ - function baseShuffle(collection) { - return shuffleSelf(values(collection)); - } + /** `Object#toString` result references. */ + var argsTag = '[object Arguments]', + arrayTag = '[object Array]', + asyncTag = '[object AsyncFunction]', + boolTag = '[object Boolean]', + dateTag = '[object Date]', + domExcTag = '[object DOMException]', + errorTag = '[object Error]', + funcTag = '[object Function]', + genTag = '[object GeneratorFunction]', + mapTag = '[object Map]', + numberTag = '[object Number]', + nullTag = '[object Null]', + objectTag = '[object Object]', + promiseTag = '[object Promise]', + proxyTag = '[object Proxy]', + regexpTag = '[object RegExp]', + setTag = '[object Set]', + stringTag = '[object String]', + symbolTag = '[object Symbol]', + undefinedTag = '[object Undefined]', + weakMapTag = '[object WeakMap]', + weakSetTag = '[object WeakSet]'; - /** - * The base implementation of `_.slice` without an iteratee call guard. - * - * @private - * @param {Array} array The array to slice. - * @param {number} [start=0] The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns the slice of `array`. - */ - function baseSlice(array, start, end) { - var index = -1, - length = array.length; + var arrayBufferTag = '[object ArrayBuffer]', + dataViewTag = '[object DataView]', + float32Tag = '[object Float32Array]', + float64Tag = '[object Float64Array]', + int8Tag = '[object Int8Array]', + int16Tag = '[object Int16Array]', + int32Tag = '[object Int32Array]', + uint8Tag = '[object Uint8Array]', + uint8ClampedTag = '[object Uint8ClampedArray]', + uint16Tag = '[object Uint16Array]', + uint32Tag = '[object Uint32Array]'; - if (start < 0) { - start = -start > length ? 0 : (length + start); - } - end = end > length ? length : end; - if (end < 0) { - end += length; - } - length = start > end ? 0 : ((end - start) >>> 0); - start >>>= 0; + /** Used to match empty string literals in compiled template source. */ + var reEmptyStringLeading = /\b__p \+= '';/g, + reEmptyStringMiddle = /\b(__p \+=) '' \+/g, + reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; - var result = Array(length); - while (++index < length) { - result[index] = array[index + start]; - } - return result; - } + /** Used to match HTML entities and HTML characters. */ + var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g, + reUnescapedHtml = /[&<>"']/g, + reHasEscapedHtml = RegExp(reEscapedHtml.source), + reHasUnescapedHtml = RegExp(reUnescapedHtml.source); - /** - * The base implementation of `_.some` without support for iteratee shorthands. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {boolean} Returns `true` if any element passes the predicate check, - * else `false`. - */ - function baseSome(collection, predicate) { - var result; + /** Used to match template delimiters. */ + var reEscape = /<%-([\s\S]+?)%>/g, + reEvaluate = /<%([\s\S]+?)%>/g, + reInterpolate = /<%=([\s\S]+?)%>/g; - baseEach(collection, function(value, index, collection) { - result = predicate(value, index, collection); - return !result; - }); - return !!result; - } + /** Used to match property names within property paths. */ + var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, + reIsPlainProp = /^\w*$/, + rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; - /** - * The base implementation of `_.sortedIndex` and `_.sortedLastIndex` which - * performs a binary search of `array` to determine the index at which `value` - * should be inserted into `array` in order to maintain its sort order. - * - * @private - * @param {Array} array The sorted array to inspect. - * @param {*} value The value to evaluate. - * @param {boolean} [retHighest] Specify returning the highest qualified index. - * @returns {number} Returns the index at which `value` should be inserted - * into `array`. - */ - function baseSortedIndex(array, value, retHighest) { - var low = 0, - high = array == null ? low : array.length; + /** + * Used to match `RegExp` + * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). + */ + var reRegExpChar = /[\\^$.*+?()[\]{}|]/g, + reHasRegExpChar = RegExp(reRegExpChar.source); - if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) { - while (low < high) { - var mid = (low + high) >>> 1, - computed = array[mid]; + /** Used to match leading whitespace. */ + var reTrimStart = /^\s+/; - if (computed !== null && !isSymbol(computed) && - (retHighest ? (computed <= value) : (computed < value))) { - low = mid + 1; - } else { - high = mid; - } - } - return high; - } - return baseSortedIndexBy(array, value, identity, retHighest); - } + /** Used to match a single whitespace character. */ + var reWhitespace = /\s/; - /** - * The base implementation of `_.sortedIndexBy` and `_.sortedLastIndexBy` - * which invokes `iteratee` for `value` and each element of `array` to compute - * their sort ranking. The iteratee is invoked with one argument; (value). - * - * @private - * @param {Array} array The sorted array to inspect. - * @param {*} value The value to evaluate. - * @param {Function} iteratee The iteratee invoked per element. - * @param {boolean} [retHighest] Specify returning the highest qualified index. - * @returns {number} Returns the index at which `value` should be inserted - * into `array`. - */ - function baseSortedIndexBy(array, value, iteratee, retHighest) { - var low = 0, - high = array == null ? 0 : array.length; - if (high === 0) { - return 0; - } + /** Used to match wrap detail comments. */ + var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/, + reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/, + reSplitDetails = /,? & /; - value = iteratee(value); - var valIsNaN = value !== value, - valIsNull = value === null, - valIsSymbol = isSymbol(value), - valIsUndefined = value === undefined; + /** Used to match words composed of alphanumeric characters. */ + var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g; - while (low < high) { - var mid = nativeFloor((low + high) / 2), - computed = iteratee(array[mid]), - othIsDefined = computed !== undefined, - othIsNull = computed === null, - othIsReflexive = computed === computed, - othIsSymbol = isSymbol(computed); + /** + * Used to validate the `validate` option in `_.template` variable. + * + * Forbids characters which could potentially change the meaning of the function argument definition: + * - "()," (modification of function parameters) + * - "=" (default value) + * - "[]{}" (destructuring of function parameters) + * - "/" (beginning of a comment) + * - whitespace + */ + var reForbiddenIdentifierChars = /[()=,{}\[\]\/\s]/; - if (valIsNaN) { - var setLow = retHighest || othIsReflexive; - } else if (valIsUndefined) { - setLow = othIsReflexive && (retHighest || othIsDefined); - } else if (valIsNull) { - setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull); - } else if (valIsSymbol) { - setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol); - } else if (othIsNull || othIsSymbol) { - setLow = false; - } else { - setLow = retHighest ? (computed <= value) : (computed < value); - } - if (setLow) { - low = mid + 1; - } else { - high = mid; - } - } - return nativeMin(high, MAX_ARRAY_INDEX); - } + /** Used to match backslashes in property paths. */ + var reEscapeChar = /\\(\\)?/g; - /** - * The base implementation of `_.sortedUniq` and `_.sortedUniqBy` without - * support for iteratee shorthands. - * - * @private - * @param {Array} array The array to inspect. - * @param {Function} [iteratee] The iteratee invoked per element. - * @returns {Array} Returns the new duplicate free array. - */ - function baseSortedUniq(array, iteratee) { - var index = -1, - length = array.length, - resIndex = 0, - result = []; + /** + * Used to match + * [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components). + */ + var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; - while (++index < length) { - var value = array[index], - computed = iteratee ? iteratee(value) : value; + /** Used to match `RegExp` flags from their coerced string values. */ + var reFlags = /\w*$/; - if (!index || !eq(computed, seen)) { - var seen = computed; - result[resIndex++] = value === 0 ? 0 : value; - } - } - return result; - } + /** Used to detect bad signed hexadecimal string values. */ + var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; - /** - * The base implementation of `_.toNumber` which doesn't ensure correct - * conversions of binary, hexadecimal, or octal string values. - * - * @private - * @param {*} value The value to process. - * @returns {number} Returns the number. - */ - function baseToNumber(value) { - if (typeof value == 'number') { - return value; - } - if (isSymbol(value)) { - return NAN; - } - return +value; - } + /** Used to detect binary string values. */ + var reIsBinary = /^0b[01]+$/i; - /** - * The base implementation of `_.toString` which doesn't convert nullish - * values to empty strings. - * - * @private - * @param {*} value The value to process. - * @returns {string} Returns the string. - */ - function baseToString(value) { - // Exit early for strings to avoid a performance hit in some environments. - if (typeof value == 'string') { - return value; - } - if (isArray(value)) { - // Recursively convert values (susceptible to call stack limits). - return arrayMap(value, baseToString) + ''; - } - if (isSymbol(value)) { - return symbolToString ? symbolToString.call(value) : ''; - } - var result = (value + ''); - return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; - } + /** Used to detect host constructors (Safari). */ + var reIsHostCtor = /^\[object .+?Constructor\]$/; - /** - * The base implementation of `_.uniqBy` without support for iteratee shorthands. - * - * @private - * @param {Array} array The array to inspect. - * @param {Function} [iteratee] The iteratee invoked per element. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new duplicate free array. - */ - function baseUniq(array, iteratee, comparator) { - var index = -1, - includes = arrayIncludes, - length = array.length, - isCommon = true, - result = [], - seen = result; + /** Used to detect octal string values. */ + var reIsOctal = /^0o[0-7]+$/i; - if (comparator) { - isCommon = false; - includes = arrayIncludesWith; - } - else if (length >= LARGE_ARRAY_SIZE) { - var set = iteratee ? null : createSet(array); - if (set) { - return setToArray(set); - } - isCommon = false; - includes = cacheHas; - seen = new SetCache; - } - else { - seen = iteratee ? [] : result; - } - outer: - while (++index < length) { - var value = array[index], - computed = iteratee ? iteratee(value) : value; + /** Used to detect unsigned integer values. */ + var reIsUint = /^(?:0|[1-9]\d*)$/; - value = (comparator || value !== 0) ? value : 0; - if (isCommon && computed === computed) { - var seenIndex = seen.length; - while (seenIndex--) { - if (seen[seenIndex] === computed) { - continue outer; - } - } - if (iteratee) { - seen.push(computed); - } - result.push(value); - } - else if (!includes(seen, computed, comparator)) { - if (seen !== result) { - seen.push(computed); - } - result.push(value); - } - } - return result; - } + /** Used to match Latin Unicode letters (excluding mathematical operators). */ + var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g; - /** - * The base implementation of `_.unset`. - * - * @private - * @param {Object} object The object to modify. - * @param {Array|string} path The property path to unset. - * @returns {boolean} Returns `true` if the property is deleted, else `false`. - */ - function baseUnset(object, path) { - path = castPath(path, object); - object = parent(object, path); - return object == null || delete object[toKey(last(path))]; - } + /** Used to ensure capturing order of template delimiters. */ + var reNoMatch = /($^)/; - /** - * The base implementation of `_.update`. - * - * @private - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to update. - * @param {Function} updater The function to produce the updated value. - * @param {Function} [customizer] The function to customize path creation. - * @returns {Object} Returns `object`. - */ - function baseUpdate(object, path, updater, customizer) { - return baseSet(object, path, updater(baseGet(object, path)), customizer); - } + /** Used to match unescaped characters in compiled string literals. */ + var reUnescapedString = /['\n\r\u2028\u2029\\]/g; - /** - * The base implementation of methods like `_.dropWhile` and `_.takeWhile` - * without support for iteratee shorthands. - * - * @private - * @param {Array} array The array to query. - * @param {Function} predicate The function invoked per iteration. - * @param {boolean} [isDrop] Specify dropping elements instead of taking them. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Array} Returns the slice of `array`. - */ - function baseWhile(array, predicate, isDrop, fromRight) { - var length = array.length, - index = fromRight ? length : -1; + /** Used to compose unicode character classes. */ + var rsAstralRange = '\\ud800-\\udfff', + rsComboMarksRange = '\\u0300-\\u036f', + reComboHalfMarksRange = '\\ufe20-\\ufe2f', + rsComboSymbolsRange = '\\u20d0-\\u20ff', + rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, + rsDingbatRange = '\\u2700-\\u27bf', + rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff', + rsMathOpRange = '\\xac\\xb1\\xd7\\xf7', + rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf', + rsPunctuationRange = '\\u2000-\\u206f', + rsSpaceRange = ' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000', + rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde', + rsVarRange = '\\ufe0e\\ufe0f', + rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange; - while ((fromRight ? index-- : ++index < length) && - predicate(array[index], index, array)) {} + /** Used to compose unicode capture groups. */ + var rsApos = "['\u2019]", + rsAstral = '[' + rsAstralRange + ']', + rsBreak = '[' + rsBreakRange + ']', + rsCombo = '[' + rsComboRange + ']', + rsDigits = '\\d+', + rsDingbat = '[' + rsDingbatRange + ']', + rsLower = '[' + rsLowerRange + ']', + rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']', + rsFitz = '\\ud83c[\\udffb-\\udfff]', + rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', + rsNonAstral = '[^' + rsAstralRange + ']', + rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', + rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', + rsUpper = '[' + rsUpperRange + ']', + rsZWJ = '\\u200d'; - return isDrop - ? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length)) - : baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index)); - } + /** Used to compose unicode regexes. */ + var rsMiscLower = '(?:' + rsLower + '|' + rsMisc + ')', + rsMiscUpper = '(?:' + rsUpper + '|' + rsMisc + ')', + rsOptContrLower = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?', + rsOptContrUpper = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?', + reOptMod = rsModifier + '?', + rsOptVar = '[' + rsVarRange + ']?', + rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', + rsOrdLower = '\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])', + rsOrdUpper = '\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])', + rsSeq = rsOptVar + reOptMod + rsOptJoin, + rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq, + rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; - /** - * The base implementation of `wrapperValue` which returns the result of - * performing a sequence of actions on the unwrapped `value`, where each - * successive action is supplied the return value of the previous. - * - * @private - * @param {*} value The unwrapped value. - * @param {Array} actions Actions to perform to resolve the unwrapped value. - * @returns {*} Returns the resolved value. - */ - function baseWrapperValue(value, actions) { - var result = value; - if (result instanceof LazyWrapper) { - result = result.value(); - } - return arrayReduce(actions, function(result, action) { - return action.func.apply(action.thisArg, arrayPush([result], action.args)); - }, result); - } + /** Used to match apostrophes. */ + var reApos = RegExp(rsApos, 'g'); - /** - * The base implementation of methods like `_.xor`, without support for - * iteratee shorthands, that accepts an array of arrays to inspect. - * - * @private - * @param {Array} arrays The arrays to inspect. - * @param {Function} [iteratee] The iteratee invoked per element. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of values. - */ - function baseXor(arrays, iteratee, comparator) { - var length = arrays.length; - if (length < 2) { - return length ? baseUniq(arrays[0]) : []; - } - var index = -1, - result = Array(length); + /** + * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and + * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols). + */ + var reComboMark = RegExp(rsCombo, 'g'); - while (++index < length) { - var array = arrays[index], - othIndex = -1; + /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ + var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); - while (++othIndex < length) { - if (othIndex != index) { - result[index] = baseDifference(result[index] || array, arrays[othIndex], iteratee, comparator); - } - } - } - return baseUniq(baseFlatten(result, 1), iteratee, comparator); - } + /** Used to match complex or compound words. */ + var reUnicodeWord = RegExp([ + rsUpper + '?' + rsLower + '+' + rsOptContrLower + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')', + rsMiscUpper + '+' + rsOptContrUpper + '(?=' + [rsBreak, rsUpper + rsMiscLower, '$'].join('|') + ')', + rsUpper + '?' + rsMiscLower + '+' + rsOptContrLower, + rsUpper + '+' + rsOptContrUpper, + rsOrdUpper, + rsOrdLower, + rsDigits, + rsEmoji + ].join('|'), 'g'); - /** - * This base implementation of `_.zipObject` which assigns values using `assignFunc`. - * - * @private - * @param {Array} props The property identifiers. - * @param {Array} values The property values. - * @param {Function} assignFunc The function to assign values. - * @returns {Object} Returns the new object. - */ - function baseZipObject(props, values, assignFunc) { - var index = -1, - length = props.length, - valsLength = values.length, - result = {}; + /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ + var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']'); - while (++index < length) { - var value = index < valsLength ? values[index] : undefined; - assignFunc(result, props[index], value); - } - return result; - } + /** Used to detect strings that need a more robust regexp to match words. */ + var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/; - /** - * Casts `value` to an empty array if it's not an array like object. - * - * @private - * @param {*} value The value to inspect. - * @returns {Array|Object} Returns the cast array-like object. - */ - function castArrayLikeObject(value) { - return isArrayLikeObject(value) ? value : []; - } + /** Used to assign default `context` object properties. */ + var contextProps = [ + 'Array', 'Buffer', 'DataView', 'Date', 'Error', 'Float32Array', 'Float64Array', + 'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Map', 'Math', 'Object', + 'Promise', 'RegExp', 'Set', 'String', 'Symbol', 'TypeError', 'Uint8Array', + 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap', + '_', 'clearTimeout', 'isFinite', 'parseInt', 'setTimeout' + ]; - /** - * Casts `value` to `identity` if it's not a function. - * - * @private - * @param {*} value The value to inspect. - * @returns {Function} Returns cast function. - */ - function castFunction(value) { - return typeof value == 'function' ? value : identity; - } + /** Used to make template sourceURLs easier to identify. */ + var templateCounter = -1; - /** - * Casts `value` to a path array if it's not one. - * - * @private - * @param {*} value The value to inspect. - * @param {Object} [object] The object to query keys on. - * @returns {Array} Returns the cast property path array. - */ - function castPath(value, object) { - if (isArray(value)) { - return value; - } - return isKey(value, object) ? [value] : stringToPath(toString(value)); - } + /** Used to identify `toStringTag` values of typed arrays. */ + var typedArrayTags = {}; + typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = + typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = + typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = + typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = + typedArrayTags[uint32Tag] = true; + typedArrayTags[argsTag] = typedArrayTags[arrayTag] = + typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = + typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = + typedArrayTags[errorTag] = typedArrayTags[funcTag] = + typedArrayTags[mapTag] = typedArrayTags[numberTag] = + typedArrayTags[objectTag] = typedArrayTags[regexpTag] = + typedArrayTags[setTag] = typedArrayTags[stringTag] = + typedArrayTags[weakMapTag] = false; - /** - * A `baseRest` alias which can be replaced with `identity` by module - * replacement plugins. - * - * @private - * @type {Function} - * @param {Function} func The function to apply a rest parameter to. - * @returns {Function} Returns the new function. - */ - var castRest = baseRest; + /** Used to identify `toStringTag` values supported by `_.clone`. */ + var cloneableTags = {}; + cloneableTags[argsTag] = cloneableTags[arrayTag] = + cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = + cloneableTags[boolTag] = cloneableTags[dateTag] = + cloneableTags[float32Tag] = cloneableTags[float64Tag] = + cloneableTags[int8Tag] = cloneableTags[int16Tag] = + cloneableTags[int32Tag] = cloneableTags[mapTag] = + cloneableTags[numberTag] = cloneableTags[objectTag] = + cloneableTags[regexpTag] = cloneableTags[setTag] = + cloneableTags[stringTag] = cloneableTags[symbolTag] = + cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = + cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; + cloneableTags[errorTag] = cloneableTags[funcTag] = + cloneableTags[weakMapTag] = false; - /** - * Casts `array` to a slice if it's needed. - * - * @private - * @param {Array} array The array to inspect. - * @param {number} start The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns the cast slice. - */ - function castSlice(array, start, end) { - var length = array.length; - end = end === undefined ? length : end; - return (!start && end >= length) ? array : baseSlice(array, start, end); - } + /** Used to map Latin Unicode letters to basic Latin letters. */ + var deburredLetters = { + // Latin-1 Supplement block. + '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A', + '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a', + '\xc7': 'C', '\xe7': 'c', + '\xd0': 'D', '\xf0': 'd', + '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E', + '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e', + '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I', + '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i', + '\xd1': 'N', '\xf1': 'n', + '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O', + '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o', + '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U', + '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u', + '\xdd': 'Y', '\xfd': 'y', '\xff': 'y', + '\xc6': 'Ae', '\xe6': 'ae', + '\xde': 'Th', '\xfe': 'th', + '\xdf': 'ss', + // Latin Extended-A block. + '\u0100': 'A', '\u0102': 'A', '\u0104': 'A', + '\u0101': 'a', '\u0103': 'a', '\u0105': 'a', + '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C', + '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c', + '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd', + '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E', + '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e', + '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G', + '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g', + '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h', + '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I', + '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i', + '\u0134': 'J', '\u0135': 'j', + '\u0136': 'K', '\u0137': 'k', '\u0138': 'k', + '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L', + '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l', + '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N', + '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n', + '\u014c': 'O', '\u014e': 'O', '\u0150': 'O', + '\u014d': 'o', '\u014f': 'o', '\u0151': 'o', + '\u0154': 'R', '\u0156': 'R', '\u0158': 'R', + '\u0155': 'r', '\u0157': 'r', '\u0159': 'r', + '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S', + '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's', + '\u0162': 'T', '\u0164': 'T', '\u0166': 'T', + '\u0163': 't', '\u0165': 't', '\u0167': 't', + '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U', + '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u', + '\u0174': 'W', '\u0175': 'w', + '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y', + '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z', + '\u017a': 'z', '\u017c': 'z', '\u017e': 'z', + '\u0132': 'IJ', '\u0133': 'ij', + '\u0152': 'Oe', '\u0153': 'oe', + '\u0149': "'n", '\u017f': 's' + }; - /** - * A simple wrapper around the global [`clearTimeout`](https://mdn.io/clearTimeout). - * - * @private - * @param {number|Object} id The timer id or timeout object of the timer to clear. - */ - var clearTimeout = ctxClearTimeout || function(id) { - return root.clearTimeout(id); - }; + /** Used to map characters to HTML entities. */ + var htmlEscapes = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''' + }; - /** - * Creates a clone of `buffer`. - * - * @private - * @param {Buffer} buffer The buffer to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Buffer} Returns the cloned buffer. - */ - function cloneBuffer(buffer, isDeep) { - if (isDeep) { - return buffer.slice(); - } - var length = buffer.length, - result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); + /** Used to map HTML entities to characters. */ + var htmlUnescapes = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + ''': "'" + }; - buffer.copy(result); - return result; - } + /** Used to escape characters for inclusion in compiled string literals. */ + var stringEscapes = { + '\\': '\\', + "'": "'", + '\n': 'n', + '\r': 'r', + '\u2028': 'u2028', + '\u2029': 'u2029' + }; - /** - * Creates a clone of `arrayBuffer`. - * - * @private - * @param {ArrayBuffer} arrayBuffer The array buffer to clone. - * @returns {ArrayBuffer} Returns the cloned array buffer. - */ - function cloneArrayBuffer(arrayBuffer) { - var result = new arrayBuffer.constructor(arrayBuffer.byteLength); - new Uint8Array(result).set(new Uint8Array(arrayBuffer)); - return result; - } + /** Built-in method references without a dependency on `root`. */ + var freeParseFloat = parseFloat, + freeParseInt = parseInt; - /** - * Creates a clone of `dataView`. - * - * @private - * @param {Object} dataView The data view to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the cloned data view. - */ - function cloneDataView(dataView, isDeep) { - var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer; - return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); - } + /** Detect free variable `global` from Node.js. */ + var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; - /** - * Creates a clone of `regexp`. - * - * @private - * @param {Object} regexp The regexp to clone. - * @returns {Object} Returns the cloned regexp. - */ - function cloneRegExp(regexp) { - var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); - result.lastIndex = regexp.lastIndex; - return result; - } + /** Detect free variable `self`. */ + var freeSelf = typeof self == 'object' && self && self.Object === Object && self; - /** - * Creates a clone of the `symbol` object. - * - * @private - * @param {Object} symbol The symbol object to clone. - * @returns {Object} Returns the cloned symbol object. - */ - function cloneSymbol(symbol) { - return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {}; - } + /** Used as a reference to the global object. */ + var root = freeGlobal || freeSelf || Function('return this')(); - /** - * Creates a clone of `typedArray`. - * - * @private - * @param {Object} typedArray The typed array to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the cloned typed array. - */ - function cloneTypedArray(typedArray, isDeep) { - var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; - return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); - } + /** Detect free variable `exports`. */ + var freeExports = true && exports && !exports.nodeType && exports; - /** - * Compares values to sort them in ascending order. - * - * @private - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {number} Returns the sort order indicator for `value`. - */ - function compareAscending(value, other) { - if (value !== other) { - var valIsDefined = value !== undefined, - valIsNull = value === null, - valIsReflexive = value === value, - valIsSymbol = isSymbol(value); + /** Detect free variable `module`. */ + var freeModule = freeExports && "object" == 'object' && module && !module.nodeType && module; - var othIsDefined = other !== undefined, - othIsNull = other === null, - othIsReflexive = other === other, - othIsSymbol = isSymbol(other); + /** Detect the popular CommonJS extension `module.exports`. */ + var moduleExports = freeModule && freeModule.exports === freeExports; - if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) || - (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) || - (valIsNull && othIsDefined && othIsReflexive) || - (!valIsDefined && othIsReflexive) || - !valIsReflexive) { - return 1; - } - if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) || - (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) || - (othIsNull && valIsDefined && valIsReflexive) || - (!othIsDefined && valIsReflexive) || - !othIsReflexive) { - return -1; - } - } - return 0; - } + /** Detect free variable `process` from Node.js. */ + var freeProcess = moduleExports && freeGlobal.process; - /** - * Used by `_.orderBy` to compare multiple properties of a value to another - * and stable sort them. - * - * If `orders` is unspecified, all values are sorted in ascending order. Otherwise, - * specify an order of "desc" for descending or "asc" for ascending sort order - * of corresponding values. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {boolean[]|string[]} orders The order to sort by for each property. - * @returns {number} Returns the sort order indicator for `object`. - */ - function compareMultiple(object, other, orders) { - var index = -1, - objCriteria = object.criteria, - othCriteria = other.criteria, - length = objCriteria.length, - ordersLength = orders.length; + /** Used to access faster Node.js helpers. */ + var nodeUtil = (function() { + try { + // Use `util.types` for Node.js 10+. + var types = freeModule && freeModule.require && freeModule.require('util').types; - while (++index < length) { - var result = compareAscending(objCriteria[index], othCriteria[index]); - if (result) { - if (index >= ordersLength) { - return result; - } - var order = orders[index]; - return result * (order == 'desc' ? -1 : 1); - } + if (types) { + return types; } - // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications - // that causes it, under certain circumstances, to provide the same value for - // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247 - // for more details. - // - // This also ensures a stable sort in V8 and other engines. - // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details. - return object.index - other.index; - } - /** - * Creates an array that is the composition of partially applied arguments, - * placeholders, and provided arguments into a single array of arguments. - * - * @private - * @param {Array} args The provided arguments. - * @param {Array} partials The arguments to prepend to those provided. - * @param {Array} holders The `partials` placeholder indexes. - * @params {boolean} [isCurried] Specify composing for a curried function. - * @returns {Array} Returns the new array of composed arguments. - */ - function composeArgs(args, partials, holders, isCurried) { - var argsIndex = -1, - argsLength = args.length, - holdersLength = holders.length, - leftIndex = -1, - leftLength = partials.length, - rangeLength = nativeMax(argsLength - holdersLength, 0), - result = Array(leftLength + rangeLength), - isUncurried = !isCurried; + // Legacy `process.binding('util')` for Node.js < 10. + return freeProcess && freeProcess.binding && freeProcess.binding('util'); + } catch (e) {} + }()); - while (++leftIndex < leftLength) { - result[leftIndex] = partials[leftIndex]; - } - while (++argsIndex < holdersLength) { - if (isUncurried || argsIndex < argsLength) { - result[holders[argsIndex]] = args[argsIndex]; - } - } - while (rangeLength--) { - result[leftIndex++] = args[argsIndex++]; - } - return result; - } + /* Node.js helper references. */ + var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer, + nodeIsDate = nodeUtil && nodeUtil.isDate, + nodeIsMap = nodeUtil && nodeUtil.isMap, + nodeIsRegExp = nodeUtil && nodeUtil.isRegExp, + nodeIsSet = nodeUtil && nodeUtil.isSet, + nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; - /** - * This function is like `composeArgs` except that the arguments composition - * is tailored for `_.partialRight`. - * - * @private - * @param {Array} args The provided arguments. - * @param {Array} partials The arguments to append to those provided. - * @param {Array} holders The `partials` placeholder indexes. - * @params {boolean} [isCurried] Specify composing for a curried function. - * @returns {Array} Returns the new array of composed arguments. - */ - function composeArgsRight(args, partials, holders, isCurried) { - var argsIndex = -1, - argsLength = args.length, - holdersIndex = -1, - holdersLength = holders.length, - rightIndex = -1, - rightLength = partials.length, - rangeLength = nativeMax(argsLength - holdersLength, 0), - result = Array(rangeLength + rightLength), - isUncurried = !isCurried; + /*--------------------------------------------------------------------------*/ - while (++argsIndex < rangeLength) { - result[argsIndex] = args[argsIndex]; - } - var offset = argsIndex; - while (++rightIndex < rightLength) { - result[offset + rightIndex] = partials[rightIndex]; - } - while (++holdersIndex < holdersLength) { - if (isUncurried || argsIndex < argsLength) { - result[offset + holders[holdersIndex]] = args[argsIndex++]; - } - } - return result; + /** + * A faster alternative to `Function#apply`, this function invokes `func` + * with the `this` binding of `thisArg` and the arguments of `args`. + * + * @private + * @param {Function} func The function to invoke. + * @param {*} thisArg The `this` binding of `func`. + * @param {Array} args The arguments to invoke `func` with. + * @returns {*} Returns the result of `func`. + */ + function apply(func, thisArg, args) { + switch (args.length) { + case 0: return func.call(thisArg); + case 1: return func.call(thisArg, args[0]); + case 2: return func.call(thisArg, args[0], args[1]); + case 3: return func.call(thisArg, args[0], args[1], args[2]); } + return func.apply(thisArg, args); + } - /** - * Copies the values of `source` to `array`. - * - * @private - * @param {Array} source The array to copy values from. - * @param {Array} [array=[]] The array to copy values to. - * @returns {Array} Returns `array`. - */ - function copyArray(source, array) { - var index = -1, - length = source.length; + /** + * A specialized version of `baseAggregator` for arrays. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} setter The function to set `accumulator` values. + * @param {Function} iteratee The iteratee to transform keys. + * @param {Object} accumulator The initial aggregated object. + * @returns {Function} Returns `accumulator`. + */ + function arrayAggregator(array, setter, iteratee, accumulator) { + var index = -1, + length = array == null ? 0 : array.length; - array || (array = Array(length)); - while (++index < length) { - array[index] = source[index]; - } - return array; + while (++index < length) { + var value = array[index]; + setter(accumulator, value, iteratee(value), array); } + return accumulator; + } - /** - * Copies properties of `source` to `object`. - * - * @private - * @param {Object} source The object to copy properties from. - * @param {Array} props The property identifiers to copy. - * @param {Object} [object={}] The object to copy properties to. - * @param {Function} [customizer] The function to customize copied values. - * @returns {Object} Returns `object`. - */ - function copyObject(source, props, object, customizer) { - var isNew = !object; - object || (object = {}); - - var index = -1, - length = props.length; + /** + * A specialized version of `_.forEach` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns `array`. + */ + function arrayEach(array, iteratee) { + var index = -1, + length = array == null ? 0 : array.length; - while (++index < length) { - var key = props[index]; + while (++index < length) { + if (iteratee(array[index], index, array) === false) { + break; + } + } + return array; + } - var newValue = customizer - ? customizer(object[key], source[key], key, object, source) - : undefined; + /** + * A specialized version of `_.forEachRight` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns `array`. + */ + function arrayEachRight(array, iteratee) { + var length = array == null ? 0 : array.length; - if (newValue === undefined) { - newValue = source[key]; - } - if (isNew) { - baseAssignValue(object, key, newValue); - } else { - assignValue(object, key, newValue); - } + while (length--) { + if (iteratee(array[length], length, array) === false) { + break; } - return object; } + return array; + } - /** - * Copies own symbols of `source` to `object`. - * - * @private - * @param {Object} source The object to copy symbols from. - * @param {Object} [object={}] The object to copy symbols to. - * @returns {Object} Returns `object`. - */ - function copySymbols(source, object) { - return copyObject(source, getSymbols(source), object); - } + /** + * A specialized version of `_.every` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false`. + */ + function arrayEvery(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length; - /** - * Copies own and inherited symbols of `source` to `object`. - * - * @private - * @param {Object} source The object to copy symbols from. - * @param {Object} [object={}] The object to copy symbols to. - * @returns {Object} Returns `object`. - */ - function copySymbolsIn(source, object) { - return copyObject(source, getSymbolsIn(source), object); + while (++index < length) { + if (!predicate(array[index], index, array)) { + return false; + } } + return true; + } - /** - * Creates a function like `_.groupBy`. - * - * @private - * @param {Function} setter The function to set accumulator values. - * @param {Function} [initializer] The accumulator object initializer. - * @returns {Function} Returns the new aggregator function. - */ - function createAggregator(setter, initializer) { - return function(collection, iteratee) { - var func = isArray(collection) ? arrayAggregator : baseAggregator, - accumulator = initializer ? initializer() : {}; + /** + * A specialized version of `_.filter` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + */ + function arrayFilter(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length, + resIndex = 0, + result = []; - return func(collection, setter, getIteratee(iteratee, 2), accumulator); - }; + while (++index < length) { + var value = array[index]; + if (predicate(value, index, array)) { + result[resIndex++] = value; + } } + return result; + } - /** - * Creates a function like `_.assign`. - * - * @private - * @param {Function} assigner The function to assign values. - * @returns {Function} Returns the new assigner function. - */ - function createAssigner(assigner) { - return baseRest(function(object, sources) { - var index = -1, - length = sources.length, - customizer = length > 1 ? sources[length - 1] : undefined, - guard = length > 2 ? sources[2] : undefined; + /** + * A specialized version of `_.includes` for arrays without support for + * specifying an index to search from. + * + * @private + * @param {Array} [array] The array to inspect. + * @param {*} target The value to search for. + * @returns {boolean} Returns `true` if `target` is found, else `false`. + */ + function arrayIncludes(array, value) { + var length = array == null ? 0 : array.length; + return !!length && baseIndexOf(array, value, 0) > -1; + } - customizer = (assigner.length > 3 && typeof customizer == 'function') - ? (length--, customizer) - : undefined; + /** + * This function is like `arrayIncludes` except that it accepts a comparator. + * + * @private + * @param {Array} [array] The array to inspect. + * @param {*} target The value to search for. + * @param {Function} comparator The comparator invoked per element. + * @returns {boolean} Returns `true` if `target` is found, else `false`. + */ + function arrayIncludesWith(array, value, comparator) { + var index = -1, + length = array == null ? 0 : array.length; - if (guard && isIterateeCall(sources[0], sources[1], guard)) { - customizer = length < 3 ? undefined : customizer; - length = 1; - } - object = Object(object); - while (++index < length) { - var source = sources[index]; - if (source) { - assigner(object, source, index, customizer); - } - } - return object; - }); + while (++index < length) { + if (comparator(value, array[index])) { + return true; + } } + return false; + } - /** - * Creates a `baseEach` or `baseEachRight` function. - * - * @private - * @param {Function} eachFunc The function to iterate over a collection. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Function} Returns the new base function. - */ - function createBaseEach(eachFunc, fromRight) { - return function(collection, iteratee) { - if (collection == null) { - return collection; - } - if (!isArrayLike(collection)) { - return eachFunc(collection, iteratee); - } - var length = collection.length, - index = fromRight ? length : -1, - iterable = Object(collection); + /** + * A specialized version of `_.map` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + */ + function arrayMap(array, iteratee) { + var index = -1, + length = array == null ? 0 : array.length, + result = Array(length); - while ((fromRight ? index-- : ++index < length)) { - if (iteratee(iterable[index], index, iterable) === false) { - break; - } - } - return collection; - }; + while (++index < length) { + result[index] = iteratee(array[index], index, array); } + return result; + } - /** - * Creates a base function for methods like `_.forIn` and `_.forOwn`. - * - * @private - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Function} Returns the new base function. - */ - function createBaseFor(fromRight) { - return function(object, iteratee, keysFunc) { - var index = -1, - iterable = Object(object), - props = keysFunc(object), - length = props.length; + /** + * Appends the elements of `values` to `array`. + * + * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to append. + * @returns {Array} Returns `array`. + */ + function arrayPush(array, values) { + var index = -1, + length = values.length, + offset = array.length; - while (length--) { - var key = props[fromRight ? length : ++index]; - if (iteratee(iterable[key], key, iterable) === false) { - break; - } - } - return object; - }; + while (++index < length) { + array[offset + index] = values[index]; } + return array; + } - /** - * Creates a function that wraps `func` to invoke it with the optional `this` - * binding of `thisArg`. - * - * @private - * @param {Function} func The function to wrap. - * @param {number} bitmask The bitmask flags. See `createWrap` for more details. - * @param {*} [thisArg] The `this` binding of `func`. - * @returns {Function} Returns the new wrapped function. - */ - function createBind(func, bitmask, thisArg) { - var isBind = bitmask & WRAP_BIND_FLAG, - Ctor = createCtor(func); + /** + * A specialized version of `_.reduce` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @param {boolean} [initAccum] Specify using the first element of `array` as + * the initial value. + * @returns {*} Returns the accumulated value. + */ + function arrayReduce(array, iteratee, accumulator, initAccum) { + var index = -1, + length = array == null ? 0 : array.length; - function wrapper() { - var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; - return fn.apply(isBind ? thisArg : this, arguments); - } - return wrapper; + if (initAccum && length) { + accumulator = array[++index]; + } + while (++index < length) { + accumulator = iteratee(accumulator, array[index], index, array); } + return accumulator; + } - /** - * Creates a function like `_.lowerFirst`. - * - * @private - * @param {string} methodName The name of the `String` case method to use. - * @returns {Function} Returns the new case function. - */ - function createCaseFirst(methodName) { - return function(string) { - string = toString(string); + /** + * A specialized version of `_.reduceRight` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @param {boolean} [initAccum] Specify using the last element of `array` as + * the initial value. + * @returns {*} Returns the accumulated value. + */ + function arrayReduceRight(array, iteratee, accumulator, initAccum) { + var length = array == null ? 0 : array.length; + if (initAccum && length) { + accumulator = array[--length]; + } + while (length--) { + accumulator = iteratee(accumulator, array[length], length, array); + } + return accumulator; + } - var strSymbols = hasUnicode(string) - ? stringToArray(string) - : undefined; + /** + * A specialized version of `_.some` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + */ + function arraySome(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length; - var chr = strSymbols - ? strSymbols[0] - : string.charAt(0); + while (++index < length) { + if (predicate(array[index], index, array)) { + return true; + } + } + return false; + } - var trailing = strSymbols - ? castSlice(strSymbols, 1).join('') - : string.slice(1); + /** + * Gets the size of an ASCII `string`. + * + * @private + * @param {string} string The string inspect. + * @returns {number} Returns the string size. + */ + var asciiSize = baseProperty('length'); - return chr[methodName]() + trailing; - }; - } + /** + * Converts an ASCII `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ + function asciiToArray(string) { + return string.split(''); + } - /** - * Creates a function like `_.camelCase`. - * - * @private - * @param {Function} callback The function to combine each word. - * @returns {Function} Returns the new compounder function. - */ - function createCompounder(callback) { - return function(string) { - return arrayReduce(words(deburr(string).replace(reApos, '')), callback, ''); - }; - } + /** + * Splits an ASCII `string` into an array of its words. + * + * @private + * @param {string} The string to inspect. + * @returns {Array} Returns the words of `string`. + */ + function asciiWords(string) { + return string.match(reAsciiWord) || []; + } - /** - * Creates a function that produces an instance of `Ctor` regardless of - * whether it was invoked as part of a `new` expression or by `call` or `apply`. - * - * @private - * @param {Function} Ctor The constructor to wrap. - * @returns {Function} Returns the new wrapped function. - */ - function createCtor(Ctor) { - return function() { - // Use a `switch` statement to work with class constructors. See - // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist - // for more details. - var args = arguments; - switch (args.length) { - case 0: return new Ctor; - case 1: return new Ctor(args[0]); - case 2: return new Ctor(args[0], args[1]); - case 3: return new Ctor(args[0], args[1], args[2]); - case 4: return new Ctor(args[0], args[1], args[2], args[3]); - case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]); - case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]); - case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); - } - var thisBinding = baseCreate(Ctor.prototype), - result = Ctor.apply(thisBinding, args); + /** + * The base implementation of methods like `_.findKey` and `_.findLastKey`, + * without support for iteratee shorthands, which iterates over `collection` + * using `eachFunc`. + * + * @private + * @param {Array|Object} collection The collection to inspect. + * @param {Function} predicate The function invoked per iteration. + * @param {Function} eachFunc The function to iterate over `collection`. + * @returns {*} Returns the found element or its key, else `undefined`. + */ + function baseFindKey(collection, predicate, eachFunc) { + var result; + eachFunc(collection, function(value, key, collection) { + if (predicate(value, key, collection)) { + result = key; + return false; + } + }); + return result; + } - // Mimic the constructor's `return` behavior. - // See https://es5.github.io/#x13.2.2 for more details. - return isObject(result) ? result : thisBinding; - }; - } + /** + * The base implementation of `_.findIndex` and `_.findLastIndex` without + * support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} predicate The function invoked per iteration. + * @param {number} fromIndex The index to search from. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function baseFindIndex(array, predicate, fromIndex, fromRight) { + var length = array.length, + index = fromIndex + (fromRight ? 1 : -1); - /** - * Creates a function that wraps `func` to enable currying. - * - * @private - * @param {Function} func The function to wrap. - * @param {number} bitmask The bitmask flags. See `createWrap` for more details. - * @param {number} arity The arity of `func`. - * @returns {Function} Returns the new wrapped function. - */ - function createCurry(func, bitmask, arity) { - var Ctor = createCtor(func); + while ((fromRight ? index-- : ++index < length)) { + if (predicate(array[index], index, array)) { + return index; + } + } + return -1; + } - function wrapper() { - var length = arguments.length, - args = Array(length), - index = length, - placeholder = getHolder(wrapper); + /** + * The base implementation of `_.indexOf` without `fromIndex` bounds checks. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function baseIndexOf(array, value, fromIndex) { + return value === value + ? strictIndexOf(array, value, fromIndex) + : baseFindIndex(array, baseIsNaN, fromIndex); + } - while (index--) { - args[index] = arguments[index]; - } - var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder) - ? [] - : replaceHolders(args, placeholder); + /** + * This function is like `baseIndexOf` except that it accepts a comparator. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @param {Function} comparator The comparator invoked per element. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function baseIndexOfWith(array, value, fromIndex, comparator) { + var index = fromIndex - 1, + length = array.length; - length -= holders.length; - if (length < arity) { - return createRecurry( - func, bitmask, createHybrid, wrapper.placeholder, undefined, - args, holders, undefined, undefined, arity - length); - } - var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; - return apply(fn, this, args); + while (++index < length) { + if (comparator(array[index], value)) { + return index; } - return wrapper; } + return -1; + } - /** - * Creates a `_.find` or `_.findLast` function. - * - * @private - * @param {Function} findIndexFunc The function to find the collection index. - * @returns {Function} Returns the new find function. - */ - function createFind(findIndexFunc) { - return function(collection, predicate, fromIndex) { - var iterable = Object(collection); - if (!isArrayLike(collection)) { - var iteratee = getIteratee(predicate, 3); - collection = keys(collection); - predicate = function(key) { return iteratee(iterable[key], key, iterable); }; - } - var index = findIndexFunc(collection, predicate, fromIndex); - return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined; - }; - } + /** + * The base implementation of `_.isNaN` without support for number objects. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. + */ + function baseIsNaN(value) { + return value !== value; + } - /** - * Creates a `_.flow` or `_.flowRight` function. - * - * @private - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Function} Returns the new flow function. - */ - function createFlow(fromRight) { - return flatRest(function(funcs) { - var length = funcs.length, - index = length, - prereq = LodashWrapper.prototype.thru; + /** + * The base implementation of `_.mean` and `_.meanBy` without support for + * iteratee shorthands. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {number} Returns the mean. + */ + function baseMean(array, iteratee) { + var length = array == null ? 0 : array.length; + return length ? (baseSum(array, iteratee) / length) : NAN; + } - if (fromRight) { - funcs.reverse(); - } - while (index--) { - var func = funcs[index]; - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - if (prereq && !wrapper && getFuncName(func) == 'wrapper') { - var wrapper = new LodashWrapper([], true); - } - } - index = wrapper ? index : length; - while (++index < length) { - func = funcs[index]; + /** + * The base implementation of `_.property` without support for deep paths. + * + * @private + * @param {string} key The key of the property to get. + * @returns {Function} Returns the new accessor function. + */ + function baseProperty(key) { + return function(object) { + return object == null ? undefined : object[key]; + }; + } - var funcName = getFuncName(func), - data = funcName == 'wrapper' ? getData(func) : undefined; + /** + * The base implementation of `_.propertyOf` without support for deep paths. + * + * @private + * @param {Object} object The object to query. + * @returns {Function} Returns the new accessor function. + */ + function basePropertyOf(object) { + return function(key) { + return object == null ? undefined : object[key]; + }; + } - if (data && isLaziable(data[0]) && - data[1] == (WRAP_ARY_FLAG | WRAP_CURRY_FLAG | WRAP_PARTIAL_FLAG | WRAP_REARG_FLAG) && - !data[4].length && data[9] == 1 - ) { - wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]); - } else { - wrapper = (func.length == 1 && isLaziable(func)) - ? wrapper[funcName]() - : wrapper.thru(func); - } - } - return function() { - var args = arguments, - value = args[0]; + /** + * The base implementation of `_.reduce` and `_.reduceRight`, without support + * for iteratee shorthands, which iterates over `collection` using `eachFunc`. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} accumulator The initial value. + * @param {boolean} initAccum Specify using the first or last element of + * `collection` as the initial value. + * @param {Function} eachFunc The function to iterate over `collection`. + * @returns {*} Returns the accumulated value. + */ + function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { + eachFunc(collection, function(value, index, collection) { + accumulator = initAccum + ? (initAccum = false, value) + : iteratee(accumulator, value, index, collection); + }); + return accumulator; + } - if (wrapper && args.length == 1 && isArray(value)) { - return wrapper.plant(value).value(); - } - var index = 0, - result = length ? funcs[index].apply(this, args) : value; + /** + * The base implementation of `_.sortBy` which uses `comparer` to define the + * sort order of `array` and replaces criteria objects with their corresponding + * values. + * + * @private + * @param {Array} array The array to sort. + * @param {Function} comparer The function to define sort order. + * @returns {Array} Returns `array`. + */ + function baseSortBy(array, comparer) { + var length = array.length; - while (++index < length) { - result = funcs[index].call(this, result); - } - return result; - }; - }); + array.sort(comparer); + while (length--) { + array[length] = array[length].value; } + return array; + } - /** - * Creates a function that wraps `func` to invoke it with optional `this` - * binding of `thisArg`, partial application, and currying. - * - * @private - * @param {Function|string} func The function or method name to wrap. - * @param {number} bitmask The bitmask flags. See `createWrap` for more details. - * @param {*} [thisArg] The `this` binding of `func`. - * @param {Array} [partials] The arguments to prepend to those provided to - * the new function. - * @param {Array} [holders] The `partials` placeholder indexes. - * @param {Array} [partialsRight] The arguments to append to those provided - * to the new function. - * @param {Array} [holdersRight] The `partialsRight` placeholder indexes. - * @param {Array} [argPos] The argument positions of the new function. - * @param {number} [ary] The arity cap of `func`. - * @param {number} [arity] The arity of `func`. - * @returns {Function} Returns the new wrapped function. - */ - function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) { - var isAry = bitmask & WRAP_ARY_FLAG, - isBind = bitmask & WRAP_BIND_FLAG, - isBindKey = bitmask & WRAP_BIND_KEY_FLAG, - isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG), - isFlip = bitmask & WRAP_FLIP_FLAG, - Ctor = isBindKey ? undefined : createCtor(func); - - function wrapper() { - var length = arguments.length, - args = Array(length), - index = length; - - while (index--) { - args[index] = arguments[index]; - } - if (isCurried) { - var placeholder = getHolder(wrapper), - holdersCount = countHolders(args, placeholder); - } - if (partials) { - args = composeArgs(args, partials, holders, isCurried); - } - if (partialsRight) { - args = composeArgsRight(args, partialsRight, holdersRight, isCurried); - } - length -= holdersCount; - if (isCurried && length < arity) { - var newHolders = replaceHolders(args, placeholder); - return createRecurry( - func, bitmask, createHybrid, wrapper.placeholder, thisArg, - args, newHolders, argPos, ary, arity - length - ); - } - var thisBinding = isBind ? thisArg : this, - fn = isBindKey ? thisBinding[func] : func; + /** + * The base implementation of `_.sum` and `_.sumBy` without support for + * iteratee shorthands. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {number} Returns the sum. + */ + function baseSum(array, iteratee) { + var result, + index = -1, + length = array.length; - length = args.length; - if (argPos) { - args = reorder(args, argPos); - } else if (isFlip && length > 1) { - args.reverse(); - } - if (isAry && ary < length) { - args.length = ary; - } - if (this && this !== root && this instanceof wrapper) { - fn = Ctor || createCtor(fn); - } - return fn.apply(thisBinding, args); + while (++index < length) { + var current = iteratee(array[index]); + if (current !== undefined) { + result = result === undefined ? current : (result + current); } - return wrapper; } + return result; + } - /** - * Creates a function like `_.invertBy`. - * - * @private - * @param {Function} setter The function to set accumulator values. - * @param {Function} toIteratee The function to resolve iteratees. - * @returns {Function} Returns the new inverter function. - */ - function createInverter(setter, toIteratee) { - return function(object, iteratee) { - return baseInverter(object, setter, toIteratee(iteratee), {}); - }; - } + /** + * The base implementation of `_.times` without support for iteratee shorthands + * or max array length checks. + * + * @private + * @param {number} n The number of times to invoke `iteratee`. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the array of results. + */ + function baseTimes(n, iteratee) { + var index = -1, + result = Array(n); - /** - * Creates a function that performs a mathematical operation on two values. - * - * @private - * @param {Function} operator The function to perform the operation. - * @param {number} [defaultValue] The value used for `undefined` arguments. - * @returns {Function} Returns the new mathematical operation function. - */ - function createMathOperation(operator, defaultValue) { - return function(value, other) { - var result; - if (value === undefined && other === undefined) { - return defaultValue; - } - if (value !== undefined) { - result = value; - } - if (other !== undefined) { - if (result === undefined) { - return other; - } - if (typeof value == 'string' || typeof other == 'string') { - value = baseToString(value); - other = baseToString(other); - } else { - value = baseToNumber(value); - other = baseToNumber(other); - } - result = operator(value, other); - } - return result; - }; + while (++index < n) { + result[index] = iteratee(index); } + return result; + } - /** - * Creates a function like `_.over`. - * - * @private - * @param {Function} arrayFunc The function to iterate over iteratees. - * @returns {Function} Returns the new over function. - */ - function createOver(arrayFunc) { - return flatRest(function(iteratees) { - iteratees = arrayMap(iteratees, baseUnary(getIteratee())); - return baseRest(function(args) { - var thisArg = this; - return arrayFunc(iteratees, function(iteratee) { - return apply(iteratee, thisArg, args); - }); - }); - }); - } + /** + * The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array + * of key-value pairs for `object` corresponding to the property names of `props`. + * + * @private + * @param {Object} object The object to query. + * @param {Array} props The property names to get values for. + * @returns {Object} Returns the key-value pairs. + */ + function baseToPairs(object, props) { + return arrayMap(props, function(key) { + return [key, object[key]]; + }); + } - /** - * Creates the padding for `string` based on `length`. The `chars` string - * is truncated if the number of characters exceeds `length`. - * - * @private - * @param {number} length The padding length. - * @param {string} [chars=' '] The string used as padding. - * @returns {string} Returns the padding for `string`. - */ - function createPadding(length, chars) { - chars = chars === undefined ? ' ' : baseToString(chars); + /** + * The base implementation of `_.trim`. + * + * @private + * @param {string} string The string to trim. + * @returns {string} Returns the trimmed string. + */ + function baseTrim(string) { + return string + ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, '') + : string; + } - var charsLength = chars.length; - if (charsLength < 2) { - return charsLength ? baseRepeat(chars, length) : chars; - } - var result = baseRepeat(chars, nativeCeil(length / stringSize(chars))); - return hasUnicode(chars) - ? castSlice(stringToArray(result), 0, length).join('') - : result.slice(0, length); - } + /** + * The base implementation of `_.unary` without support for storing metadata. + * + * @private + * @param {Function} func The function to cap arguments for. + * @returns {Function} Returns the new capped function. + */ + function baseUnary(func) { + return function(value) { + return func(value); + }; + } - /** - * Creates a function that wraps `func` to invoke it with the `this` binding - * of `thisArg` and `partials` prepended to the arguments it receives. - * - * @private - * @param {Function} func The function to wrap. - * @param {number} bitmask The bitmask flags. See `createWrap` for more details. - * @param {*} thisArg The `this` binding of `func`. - * @param {Array} partials The arguments to prepend to those provided to - * the new function. - * @returns {Function} Returns the new wrapped function. - */ - function createPartial(func, bitmask, thisArg, partials) { - var isBind = bitmask & WRAP_BIND_FLAG, - Ctor = createCtor(func); + /** + * The base implementation of `_.values` and `_.valuesIn` which creates an + * array of `object` property values corresponding to the property names + * of `props`. + * + * @private + * @param {Object} object The object to query. + * @param {Array} props The property names to get values for. + * @returns {Object} Returns the array of property values. + */ + function baseValues(object, props) { + return arrayMap(props, function(key) { + return object[key]; + }); + } + + /** + * Checks if a `cache` value for `key` exists. + * + * @private + * @param {Object} cache The cache to query. + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function cacheHas(cache, key) { + return cache.has(key); + } + + /** + * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol + * that is not found in the character symbols. + * + * @private + * @param {Array} strSymbols The string symbols to inspect. + * @param {Array} chrSymbols The character symbols to find. + * @returns {number} Returns the index of the first unmatched string symbol. + */ + function charsStartIndex(strSymbols, chrSymbols) { + var index = -1, + length = strSymbols.length; + + while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} + return index; + } + + /** + * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol + * that is not found in the character symbols. + * + * @private + * @param {Array} strSymbols The string symbols to inspect. + * @param {Array} chrSymbols The character symbols to find. + * @returns {number} Returns the index of the last unmatched string symbol. + */ + function charsEndIndex(strSymbols, chrSymbols) { + var index = strSymbols.length; - function wrapper() { - var argsIndex = -1, - argsLength = arguments.length, - leftIndex = -1, - leftLength = partials.length, - args = Array(leftLength + argsLength), - fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; + while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} + return index; + } - while (++leftIndex < leftLength) { - args[leftIndex] = partials[leftIndex]; - } - while (argsLength--) { - args[leftIndex++] = arguments[++argsIndex]; - } - return apply(fn, isBind ? thisArg : this, args); + /** + * Gets the number of `placeholder` occurrences in `array`. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} placeholder The placeholder to search for. + * @returns {number} Returns the placeholder count. + */ + function countHolders(array, placeholder) { + var length = array.length, + result = 0; + + while (length--) { + if (array[length] === placeholder) { + ++result; } - return wrapper; } + return result; + } - /** - * Creates a `_.range` or `_.rangeRight` function. - * - * @private - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Function} Returns the new range function. - */ - function createRange(fromRight) { - return function(start, end, step) { - if (step && typeof step != 'number' && isIterateeCall(start, end, step)) { - end = step = undefined; - } - // Ensure the sign of `-0` is preserved. - start = toFinite(start); - if (end === undefined) { - end = start; - start = 0; - } else { - end = toFinite(end); - } - step = step === undefined ? (start < end ? 1 : -1) : toFinite(step); - return baseRange(start, end, step, fromRight); - }; - } + /** + * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A + * letters to basic Latin letters. + * + * @private + * @param {string} letter The matched letter to deburr. + * @returns {string} Returns the deburred letter. + */ + var deburrLetter = basePropertyOf(deburredLetters); - /** - * Creates a function that performs a relational operation on two values. - * - * @private - * @param {Function} operator The function to perform the operation. - * @returns {Function} Returns the new relational operation function. - */ - function createRelationalOperation(operator) { - return function(value, other) { - if (!(typeof value == 'string' && typeof other == 'string')) { - value = toNumber(value); - other = toNumber(other); - } - return operator(value, other); - }; - } + /** + * Used by `_.escape` to convert characters to HTML entities. + * + * @private + * @param {string} chr The matched character to escape. + * @returns {string} Returns the escaped character. + */ + var escapeHtmlChar = basePropertyOf(htmlEscapes); - /** - * Creates a function that wraps `func` to continue currying. - * - * @private - * @param {Function} func The function to wrap. - * @param {number} bitmask The bitmask flags. See `createWrap` for more details. - * @param {Function} wrapFunc The function to create the `func` wrapper. - * @param {*} placeholder The placeholder value. - * @param {*} [thisArg] The `this` binding of `func`. - * @param {Array} [partials] The arguments to prepend to those provided to - * the new function. - * @param {Array} [holders] The `partials` placeholder indexes. - * @param {Array} [argPos] The argument positions of the new function. - * @param {number} [ary] The arity cap of `func`. - * @param {number} [arity] The arity of `func`. - * @returns {Function} Returns the new wrapped function. - */ - function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) { - var isCurry = bitmask & WRAP_CURRY_FLAG, - newHolders = isCurry ? holders : undefined, - newHoldersRight = isCurry ? undefined : holders, - newPartials = isCurry ? partials : undefined, - newPartialsRight = isCurry ? undefined : partials; + /** + * Used by `_.template` to escape characters for inclusion in compiled string literals. + * + * @private + * @param {string} chr The matched character to escape. + * @returns {string} Returns the escaped character. + */ + function escapeStringChar(chr) { + return '\\' + stringEscapes[chr]; + } - bitmask |= (isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG); - bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG); + /** + * Gets the value at `key` of `object`. + * + * @private + * @param {Object} [object] The object to query. + * @param {string} key The key of the property to get. + * @returns {*} Returns the property value. + */ + function getValue(object, key) { + return object == null ? undefined : object[key]; + } - if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) { - bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG); - } - var newData = [ - func, bitmask, thisArg, newPartials, newHolders, newPartialsRight, - newHoldersRight, argPos, ary, arity - ]; + /** + * Checks if `string` contains Unicode symbols. + * + * @private + * @param {string} string The string to inspect. + * @returns {boolean} Returns `true` if a symbol is found, else `false`. + */ + function hasUnicode(string) { + return reHasUnicode.test(string); + } - var result = wrapFunc.apply(undefined, newData); - if (isLaziable(func)) { - setData(result, newData); - } - result.placeholder = placeholder; - return setWrapToString(result, func, bitmask); - } + /** + * Checks if `string` contains a word composed of Unicode symbols. + * + * @private + * @param {string} string The string to inspect. + * @returns {boolean} Returns `true` if a word is found, else `false`. + */ + function hasUnicodeWord(string) { + return reHasUnicodeWord.test(string); + } - /** - * Creates a function like `_.round`. - * - * @private - * @param {string} methodName The name of the `Math` method to use when rounding. - * @returns {Function} Returns the new round function. - */ - function createRound(methodName) { - var func = Math[methodName]; - return function(number, precision) { - number = toNumber(number); - precision = precision == null ? 0 : nativeMin(toInteger(precision), 292); - if (precision && nativeIsFinite(number)) { - // Shift with exponential notation to avoid floating-point issues. - // See [MDN](https://mdn.io/round#Examples) for more details. - var pair = (toString(number) + 'e').split('e'), - value = func(pair[0] + 'e' + (+pair[1] + precision)); + /** + * Converts `iterator` to an array. + * + * @private + * @param {Object} iterator The iterator to convert. + * @returns {Array} Returns the converted array. + */ + function iteratorToArray(iterator) { + var data, + result = []; - pair = (toString(value) + 'e').split('e'); - return +(pair[0] + 'e' + (+pair[1] - precision)); - } - return func(number); - }; + while (!(data = iterator.next()).done) { + result.push(data.value); } + return result; + } - /** - * Creates a set object of `values`. - * - * @private - * @param {Array} values The values to add to the set. - * @returns {Object} Returns the new set. - */ - var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) { - return new Set(values); + /** + * Converts `map` to its key-value pairs. + * + * @private + * @param {Object} map The map to convert. + * @returns {Array} Returns the key-value pairs. + */ + function mapToArray(map) { + var index = -1, + result = Array(map.size); + + map.forEach(function(value, key) { + result[++index] = [key, value]; + }); + return result; + } + + /** + * Creates a unary function that invokes `func` with its argument transformed. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ + function overArg(func, transform) { + return function(arg) { + return func(transform(arg)); }; + } - /** - * Creates a `_.toPairs` or `_.toPairsIn` function. - * - * @private - * @param {Function} keysFunc The function to get the keys of a given object. - * @returns {Function} Returns the new pairs function. - */ - function createToPairs(keysFunc) { - return function(object) { - var tag = getTag(object); - if (tag == mapTag) { - return mapToArray(object); - } - if (tag == setTag) { - return setToPairs(object); - } - return baseToPairs(object, keysFunc(object)); - }; - } + /** + * Replaces all `placeholder` elements in `array` with an internal placeholder + * and returns an array of their indexes. + * + * @private + * @param {Array} array The array to modify. + * @param {*} placeholder The placeholder to replace. + * @returns {Array} Returns the new array of placeholder indexes. + */ + function replaceHolders(array, placeholder) { + var index = -1, + length = array.length, + resIndex = 0, + result = []; - /** - * Creates a function that either curries or invokes `func` with optional - * `this` binding and partially applied arguments. - * - * @private - * @param {Function|string} func The function or method name to wrap. - * @param {number} bitmask The bitmask flags. - * 1 - `_.bind` - * 2 - `_.bindKey` - * 4 - `_.curry` or `_.curryRight` of a bound function - * 8 - `_.curry` - * 16 - `_.curryRight` - * 32 - `_.partial` - * 64 - `_.partialRight` - * 128 - `_.rearg` - * 256 - `_.ary` - * 512 - `_.flip` - * @param {*} [thisArg] The `this` binding of `func`. - * @param {Array} [partials] The arguments to be partially applied. - * @param {Array} [holders] The `partials` placeholder indexes. - * @param {Array} [argPos] The argument positions of the new function. - * @param {number} [ary] The arity cap of `func`. - * @param {number} [arity] The arity of `func`. - * @returns {Function} Returns the new wrapped function. - */ - function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) { - var isBindKey = bitmask & WRAP_BIND_KEY_FLAG; - if (!isBindKey && typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - var length = partials ? partials.length : 0; - if (!length) { - bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG); - partials = holders = undefined; + while (++index < length) { + var value = array[index]; + if (value === placeholder || value === PLACEHOLDER) { + array[index] = PLACEHOLDER; + result[resIndex++] = index; } - ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0); - arity = arity === undefined ? arity : toInteger(arity); - length -= holders ? holders.length : 0; + } + return result; + } - if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) { - var partialsRight = partials, - holdersRight = holders; + /** + * Converts `set` to an array of its values. + * + * @private + * @param {Object} set The set to convert. + * @returns {Array} Returns the values. + */ + function setToArray(set) { + var index = -1, + result = Array(set.size); - partials = holders = undefined; - } - var data = isBindKey ? undefined : getData(func); + set.forEach(function(value) { + result[++index] = value; + }); + return result; + } - var newData = [ - func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, - argPos, ary, arity - ]; + /** + * Converts `set` to its value-value pairs. + * + * @private + * @param {Object} set The set to convert. + * @returns {Array} Returns the value-value pairs. + */ + function setToPairs(set) { + var index = -1, + result = Array(set.size); - if (data) { - mergeData(newData, data); - } - func = newData[0]; - bitmask = newData[1]; - thisArg = newData[2]; - partials = newData[3]; - holders = newData[4]; - arity = newData[9] = newData[9] === undefined - ? (isBindKey ? 0 : func.length) - : nativeMax(newData[9] - length, 0); + set.forEach(function(value) { + result[++index] = [value, value]; + }); + return result; + } - if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) { - bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG); - } - if (!bitmask || bitmask == WRAP_BIND_FLAG) { - var result = createBind(func, bitmask, thisArg); - } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) { - result = createCurry(func, bitmask, arity); - } else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) { - result = createPartial(func, bitmask, thisArg, partials); - } else { - result = createHybrid.apply(undefined, newData); - } - var setter = data ? baseSetData : setData; - return setWrapToString(setter(result, newData), func, bitmask); - } + /** + * A specialized version of `_.indexOf` which performs strict equality + * comparisons of values, i.e. `===`. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function strictIndexOf(array, value, fromIndex) { + var index = fromIndex - 1, + length = array.length; - /** - * Used by `_.defaults` to customize its `_.assignIn` use to assign properties - * of source objects to the destination object for all destination properties - * that resolve to `undefined`. - * - * @private - * @param {*} objValue The destination value. - * @param {*} srcValue The source value. - * @param {string} key The key of the property to assign. - * @param {Object} object The parent object of `objValue`. - * @returns {*} Returns the value to assign. - */ - function customDefaultsAssignIn(objValue, srcValue, key, object) { - if (objValue === undefined || - (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) { - return srcValue; + while (++index < length) { + if (array[index] === value) { + return index; } - return objValue; } + return -1; + } - /** - * Used by `_.defaultsDeep` to customize its `_.merge` use to merge source - * objects into destination objects that are passed thru. - * - * @private - * @param {*} objValue The destination value. - * @param {*} srcValue The source value. - * @param {string} key The key of the property to merge. - * @param {Object} object The parent object of `objValue`. - * @param {Object} source The parent object of `srcValue`. - * @param {Object} [stack] Tracks traversed source values and their merged - * counterparts. - * @returns {*} Returns the value to assign. - */ - function customDefaultsMerge(objValue, srcValue, key, object, source, stack) { - if (isObject(objValue) && isObject(srcValue)) { - // Recursively merge objects and arrays (susceptible to call stack limits). - stack.set(srcValue, objValue); - baseMerge(objValue, srcValue, undefined, customDefaultsMerge, stack); - stack['delete'](srcValue); + /** + * A specialized version of `_.lastIndexOf` which performs strict equality + * comparisons of values, i.e. `===`. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function strictLastIndexOf(array, value, fromIndex) { + var index = fromIndex + 1; + while (index--) { + if (array[index] === value) { + return index; } - return objValue; } + return index; + } + + /** + * Gets the number of symbols in `string`. + * + * @private + * @param {string} string The string to inspect. + * @returns {number} Returns the string size. + */ + function stringSize(string) { + return hasUnicode(string) + ? unicodeSize(string) + : asciiSize(string); + } + + /** + * Converts `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ + function stringToArray(string) { + return hasUnicode(string) + ? unicodeToArray(string) + : asciiToArray(string); + } + + /** + * Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace + * character of `string`. + * + * @private + * @param {string} string The string to inspect. + * @returns {number} Returns the index of the last non-whitespace character. + */ + function trimmedEndIndex(string) { + var index = string.length; + + while (index-- && reWhitespace.test(string.charAt(index))) {} + return index; + } + + /** + * Used by `_.unescape` to convert HTML entities to characters. + * + * @private + * @param {string} chr The matched character to unescape. + * @returns {string} Returns the unescaped character. + */ + var unescapeHtmlChar = basePropertyOf(htmlUnescapes); - /** - * Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain - * objects. - * - * @private - * @param {*} value The value to inspect. - * @param {string} key The key of the property to inspect. - * @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`. - */ - function customOmitClone(value) { - return isPlainObject(value) ? undefined : value; + /** + * Gets the size of a Unicode `string`. + * + * @private + * @param {string} string The string inspect. + * @returns {number} Returns the string size. + */ + function unicodeSize(string) { + var result = reUnicode.lastIndex = 0; + while (reUnicode.test(string)) { + ++result; } + return result; + } - /** - * A specialized version of `baseIsEqualDeep` for arrays with support for - * partial deep comparisons. - * - * @private - * @param {Array} array The array to compare. - * @param {Array} other The other array to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} stack Tracks traversed `array` and `other` objects. - * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. - */ - function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { - var isPartial = bitmask & COMPARE_PARTIAL_FLAG, - arrLength = array.length, - othLength = other.length; + /** + * Converts a Unicode `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ + function unicodeToArray(string) { + return string.match(reUnicode) || []; + } - if (arrLength != othLength && !(isPartial && othLength > arrLength)) { - return false; - } - // Check that cyclic values are equal. - var arrStacked = stack.get(array); - var othStacked = stack.get(other); - if (arrStacked && othStacked) { - return arrStacked == other && othStacked == array; - } - var index = -1, - result = true, - seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined; + /** + * Splits a Unicode `string` into an array of its words. + * + * @private + * @param {string} The string to inspect. + * @returns {Array} Returns the words of `string`. + */ + function unicodeWords(string) { + return string.match(reUnicodeWord) || []; + } - stack.set(array, other); - stack.set(other, array); + /*--------------------------------------------------------------------------*/ - // Ignore non-index properties. - while (++index < arrLength) { - var arrValue = array[index], - othValue = other[index]; + /** + * Create a new pristine `lodash` function using the `context` object. + * + * @static + * @memberOf _ + * @since 1.1.0 + * @category Util + * @param {Object} [context=root] The context object. + * @returns {Function} Returns a new `lodash` function. + * @example + * + * _.mixin({ 'foo': _.constant('foo') }); + * + * var lodash = _.runInContext(); + * lodash.mixin({ 'bar': lodash.constant('bar') }); + * + * _.isFunction(_.foo); + * // => true + * _.isFunction(_.bar); + * // => false + * + * lodash.isFunction(lodash.foo); + * // => false + * lodash.isFunction(lodash.bar); + * // => true + * + * // Create a suped-up `defer` in Node.js. + * var defer = _.runInContext({ 'setTimeout': setImmediate }).defer; + */ + var runInContext = (function runInContext(context) { + context = context == null ? root : _.defaults(root.Object(), context, _.pick(root, contextProps)); - if (customizer) { - var compared = isPartial - ? customizer(othValue, arrValue, index, other, array, stack) - : customizer(arrValue, othValue, index, array, other, stack); - } - if (compared !== undefined) { - if (compared) { - continue; - } - result = false; - break; - } - // Recursively compare arrays (susceptible to call stack limits). - if (seen) { - if (!arraySome(other, function(othValue, othIndex) { - if (!cacheHas(seen, othIndex) && - (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { - return seen.push(othIndex); - } - })) { - result = false; - break; - } - } else if (!( - arrValue === othValue || - equalFunc(arrValue, othValue, bitmask, customizer, stack) - )) { - result = false; - break; - } - } - stack['delete'](array); - stack['delete'](other); - return result; - } + /** Built-in constructor references. */ + var Array = context.Array, + Date = context.Date, + Error = context.Error, + Function = context.Function, + Math = context.Math, + Object = context.Object, + RegExp = context.RegExp, + String = context.String, + TypeError = context.TypeError; + + /** Used for built-in method references. */ + var arrayProto = Array.prototype, + funcProto = Function.prototype, + objectProto = Object.prototype; + + /** Used to detect overreaching core-js shims. */ + var coreJsData = context['__core-js_shared__']; + + /** Used to resolve the decompiled source of functions. */ + var funcToString = funcProto.toString; + + /** Used to check objects for own properties. */ + var hasOwnProperty = objectProto.hasOwnProperty; + + /** Used to generate unique IDs. */ + var idCounter = 0; + + /** Used to detect methods masquerading as native. */ + var maskSrcKey = (function() { + var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); + return uid ? ('Symbol(src)_1.' + uid) : ''; + }()); /** - * A specialized version of `baseIsEqualDeep` for comparing objects of - * the same `toStringTag`. - * - * **Note:** This function only supports comparing values with tags of - * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {string} tag The `toStringTag` of the objects to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} stack Tracks traversed `object` and `other` objects. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. */ - function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { - switch (tag) { - case dataViewTag: - if ((object.byteLength != other.byteLength) || - (object.byteOffset != other.byteOffset)) { - return false; - } - object = object.buffer; - other = other.buffer; - - case arrayBufferTag: - if ((object.byteLength != other.byteLength) || - !equalFunc(new Uint8Array(object), new Uint8Array(other))) { - return false; - } - return true; + var nativeObjectToString = objectProto.toString; - case boolTag: - case dateTag: - case numberTag: - // Coerce booleans to `1` or `0` and dates to milliseconds. - // Invalid dates are coerced to `NaN`. - return eq(+object, +other); + /** Used to infer the `Object` constructor. */ + var objectCtorString = funcToString.call(Object); - case errorTag: - return object.name == other.name && object.message == other.message; + /** Used to restore the original `_` reference in `_.noConflict`. */ + var oldDash = root._; - case regexpTag: - case stringTag: - // Coerce regexes to strings and treat strings, primitives and objects, - // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring - // for more details. - return object == (other + ''); + /** Used to detect if a method is native. */ + var reIsNative = RegExp('^' + + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') + .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' + ); - case mapTag: - var convert = mapToArray; + /** Built-in value references. */ + var Buffer = moduleExports ? context.Buffer : undefined, + Symbol = context.Symbol, + Uint8Array = context.Uint8Array, + allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined, + getPrototype = overArg(Object.getPrototypeOf, Object), + objectCreate = Object.create, + propertyIsEnumerable = objectProto.propertyIsEnumerable, + splice = arrayProto.splice, + spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined, + symIterator = Symbol ? Symbol.iterator : undefined, + symToStringTag = Symbol ? Symbol.toStringTag : undefined; - case setTag: - var isPartial = bitmask & COMPARE_PARTIAL_FLAG; - convert || (convert = setToArray); + var defineProperty = (function() { + try { + var func = getNative(Object, 'defineProperty'); + func({}, '', {}); + return func; + } catch (e) {} + }()); - if (object.size != other.size && !isPartial) { - return false; - } - // Assume cyclic values are equal. - var stacked = stack.get(object); - if (stacked) { - return stacked == other; - } - bitmask |= COMPARE_UNORDERED_FLAG; + /** Mocked built-ins. */ + var ctxClearTimeout = context.clearTimeout !== root.clearTimeout && context.clearTimeout, + ctxNow = Date && Date.now !== root.Date.now && Date.now, + ctxSetTimeout = context.setTimeout !== root.setTimeout && context.setTimeout; - // Recursively compare objects (susceptible to call stack limits). - stack.set(object, other); - var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); - stack['delete'](object); - return result; + /* Built-in method references for those with the same name as other `lodash` methods. */ + var nativeCeil = Math.ceil, + nativeFloor = Math.floor, + nativeGetSymbols = Object.getOwnPropertySymbols, + nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined, + nativeIsFinite = context.isFinite, + nativeJoin = arrayProto.join, + nativeKeys = overArg(Object.keys, Object), + nativeMax = Math.max, + nativeMin = Math.min, + nativeNow = Date.now, + nativeParseInt = context.parseInt, + nativeRandom = Math.random, + nativeReverse = arrayProto.reverse; - case symbolTag: - if (symbolValueOf) { - return symbolValueOf.call(object) == symbolValueOf.call(other); - } - } - return false; - } + /* Built-in method references that are verified to be native. */ + var DataView = getNative(context, 'DataView'), + Map = getNative(context, 'Map'), + Promise = getNative(context, 'Promise'), + Set = getNative(context, 'Set'), + WeakMap = getNative(context, 'WeakMap'), + nativeCreate = getNative(Object, 'create'); - /** - * A specialized version of `baseIsEqualDeep` for objects with support for - * partial deep comparisons. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} stack Tracks traversed `object` and `other` objects. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. - */ - function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { - var isPartial = bitmask & COMPARE_PARTIAL_FLAG, - objProps = getAllKeys(object), - objLength = objProps.length, - othProps = getAllKeys(other), - othLength = othProps.length; + /** Used to store function metadata. */ + var metaMap = WeakMap && new WeakMap; - if (objLength != othLength && !isPartial) { - return false; - } - var index = objLength; - while (index--) { - var key = objProps[index]; - if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { - return false; - } - } - // Check that cyclic values are equal. - var objStacked = stack.get(object); - var othStacked = stack.get(other); - if (objStacked && othStacked) { - return objStacked == other && othStacked == object; - } - var result = true; - stack.set(object, other); - stack.set(other, object); + /** Used to lookup unminified function names. */ + var realNames = {}; - var skipCtor = isPartial; - while (++index < objLength) { - key = objProps[index]; - var objValue = object[key], - othValue = other[key]; + /** Used to detect maps, sets, and weakmaps. */ + var dataViewCtorString = toSource(DataView), + mapCtorString = toSource(Map), + promiseCtorString = toSource(Promise), + setCtorString = toSource(Set), + weakMapCtorString = toSource(WeakMap); - if (customizer) { - var compared = isPartial - ? customizer(othValue, objValue, key, other, object, stack) - : customizer(objValue, othValue, key, object, other, stack); - } - // Recursively compare objects (susceptible to call stack limits). - if (!(compared === undefined - ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) - : compared - )) { - result = false; - break; - } - skipCtor || (skipCtor = key == 'constructor'); - } - if (result && !skipCtor) { - var objCtor = object.constructor, - othCtor = other.constructor; + /** Used to convert symbols to primitives and strings. */ + var symbolProto = Symbol ? Symbol.prototype : undefined, + symbolValueOf = symbolProto ? symbolProto.valueOf : undefined, + symbolToString = symbolProto ? symbolProto.toString : undefined; - // Non `Object` object instances with different constructors are not equal. - if (objCtor != othCtor && - ('constructor' in object && 'constructor' in other) && - !(typeof objCtor == 'function' && objCtor instanceof objCtor && - typeof othCtor == 'function' && othCtor instanceof othCtor)) { - result = false; - } - } - stack['delete'](object); - stack['delete'](other); - return result; - } + /*------------------------------------------------------------------------*/ /** - * A specialized version of `baseRest` which flattens the rest array. + * Creates a `lodash` object which wraps `value` to enable implicit method + * chain sequences. Methods that operate on and return arrays, collections, + * and functions can be chained together. Methods that retrieve a single value + * or may return a primitive value will automatically end the chain sequence + * and return the unwrapped value. Otherwise, the value must be unwrapped + * with `_#value`. * - * @private - * @param {Function} func The function to apply a rest parameter to. - * @returns {Function} Returns the new function. - */ - function flatRest(func) { - return setToString(overRest(func, undefined, flatten), func + ''); - } - - /** - * Creates an array of own enumerable property names and symbols of `object`. + * Explicit chain sequences, which must be unwrapped with `_#value`, may be + * enabled using `_.chain`. * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names and symbols. - */ - function getAllKeys(object) { - return baseGetAllKeys(object, keys, getSymbols); - } - - /** - * Creates an array of own and inherited enumerable property names and - * symbols of `object`. + * The execution of chained methods is lazy, that is, it's deferred until + * `_#value` is implicitly or explicitly called. + * + * Lazy evaluation allows several methods to support shortcut fusion. + * Shortcut fusion is an optimization to merge iteratee calls; this avoids + * the creation of intermediate arrays and can greatly reduce the number of + * iteratee executions. Sections of a chain sequence qualify for shortcut + * fusion if the section is applied to an array and iteratees accept only + * one argument. The heuristic for whether a section qualifies for shortcut + * fusion is subject to change. + * + * Chaining is supported in custom builds as long as the `_#value` method is + * directly or indirectly included in the build. + * + * In addition to lodash methods, wrappers have `Array` and `String` methods. + * + * The wrapper `Array` methods are: + * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift` + * + * The wrapper `String` methods are: + * `replace` and `split` + * + * The wrapper methods that support shortcut fusion are: + * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`, + * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`, + * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray` + * + * The chainable wrapper methods are: + * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`, + * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`, + * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`, + * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`, + * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`, + * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`, + * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`, + * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`, + * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`, + * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`, + * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`, + * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`, + * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`, + * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`, + * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`, + * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`, + * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`, + * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`, + * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`, + * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`, + * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`, + * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`, + * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`, + * `zipObject`, `zipObjectDeep`, and `zipWith` + * + * The wrapper methods that are **not** chainable by default are: + * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`, + * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`, + * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`, + * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`, + * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`, + * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`, + * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`, + * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`, + * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`, + * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`, + * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`, + * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`, + * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`, + * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`, + * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`, + * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`, + * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`, + * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`, + * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`, + * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`, + * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`, + * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`, + * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`, + * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`, + * `upperFirst`, `value`, and `words` + * + * @name _ + * @constructor + * @category Seq + * @param {*} value The value to wrap in a `lodash` instance. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names and symbols. - */ - function getAllKeysIn(object) { - return baseGetAllKeys(object, keysIn, getSymbolsIn); - } - - /** - * Gets metadata for `func`. + * function square(n) { + * return n * n; + * } * - * @private - * @param {Function} func The function to query. - * @returns {*} Returns the metadata for `func`. - */ - var getData = !metaMap ? noop : function(func) { - return metaMap.get(func); - }; - - /** - * Gets the name of `func`. + * var wrapped = _([1, 2, 3]); * - * @private - * @param {Function} func The function to query. - * @returns {string} Returns the function name. + * // Returns an unwrapped value. + * wrapped.reduce(_.add); + * // => 6 + * + * // Returns a wrapped value. + * var squares = wrapped.map(square); + * + * _.isArray(squares); + * // => false + * + * _.isArray(squares.value()); + * // => true */ - function getFuncName(func) { - var result = (func.name + ''), - array = realNames[result], - length = hasOwnProperty.call(realNames, result) ? array.length : 0; - - while (length--) { - var data = array[length], - otherFunc = data.func; - if (otherFunc == null || otherFunc == func) { - return data.name; + function lodash(value) { + if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) { + if (value instanceof LodashWrapper) { + return value; + } + if (hasOwnProperty.call(value, '__wrapped__')) { + return wrapperClone(value); } } - return result; + return new LodashWrapper(value); } /** - * Gets the argument placeholder value for `func`. + * The base implementation of `_.create` without support for assigning + * properties to the created object. * * @private - * @param {Function} func The function to inspect. - * @returns {*} Returns the placeholder value. + * @param {Object} proto The object to inherit from. + * @returns {Object} Returns the new object. */ - function getHolder(func) { - var object = hasOwnProperty.call(lodash, 'placeholder') ? lodash : func; - return object.placeholder; - } + var baseCreate = (function() { + function object() {} + return function(proto) { + if (!isObject(proto)) { + return {}; + } + if (objectCreate) { + return objectCreate(proto); + } + object.prototype = proto; + var result = new object; + object.prototype = undefined; + return result; + }; + }()); /** - * Gets the appropriate "iteratee" function. If `_.iteratee` is customized, - * this function returns the custom method, otherwise it returns `baseIteratee`. - * If arguments are provided, the chosen function is invoked with them and - * its result is returned. + * The function whose prototype chain sequence wrappers inherit from. * * @private - * @param {*} [value] The value to convert to an iteratee. - * @param {number} [arity] The arity of the created iteratee. - * @returns {Function} Returns the chosen function or its result. */ - function getIteratee() { - var result = lodash.iteratee || iteratee; - result = result === iteratee ? baseIteratee : result; - return arguments.length ? result(arguments[0], arguments[1]) : result; + function baseLodash() { + // No operation performed. } /** - * Gets the data for `map`. + * The base constructor for creating `lodash` wrapper objects. * * @private - * @param {Object} map The map to query. - * @param {string} key The reference key. - * @returns {*} Returns the map data. + * @param {*} value The value to wrap. + * @param {boolean} [chainAll] Enable explicit method chain sequences. */ - function getMapData(map, key) { - var data = map.__data__; - return isKeyable(key) - ? data[typeof key == 'string' ? 'string' : 'hash'] - : data.map; + function LodashWrapper(value, chainAll) { + this.__wrapped__ = value; + this.__actions__ = []; + this.__chain__ = !!chainAll; + this.__index__ = 0; + this.__values__ = undefined; } /** - * Gets the property names, values, and compare flags of `object`. + * By default, the template delimiters used by lodash are like those in + * embedded Ruby (ERB) as well as ES2015 template strings. Change the + * following template settings to use alternative delimiters. * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the match data of `object`. + * @static + * @memberOf _ + * @type {Object} */ - function getMatchData(object) { - var result = keys(object), - length = result.length; - - while (length--) { - var key = result[length], - value = object[key]; - - result[length] = [key, value, isStrictComparable(value)]; - } - return result; - } + lodash.templateSettings = { - /** - * Gets the native function at `key` of `object`. - * - * @private - * @param {Object} object The object to query. - * @param {string} key The key of the method to get. - * @returns {*} Returns the function if it's native, else `undefined`. - */ - function getNative(object, key) { - var value = getValue(object, key); - return baseIsNative(value) ? value : undefined; - } + /** + * Used to detect `data` property values to be HTML-escaped. + * + * @memberOf _.templateSettings + * @type {RegExp} + */ + 'escape': reEscape, - /** - * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the raw `toStringTag`. - */ - function getRawTag(value) { - var isOwn = hasOwnProperty.call(value, symToStringTag), - tag = value[symToStringTag]; + /** + * Used to detect code to be evaluated. + * + * @memberOf _.templateSettings + * @type {RegExp} + */ + 'evaluate': reEvaluate, - try { - value[symToStringTag] = undefined; - var unmasked = true; - } catch (e) {} + /** + * Used to detect `data` property values to inject. + * + * @memberOf _.templateSettings + * @type {RegExp} + */ + 'interpolate': reInterpolate, - var result = nativeObjectToString.call(value); - if (unmasked) { - if (isOwn) { - value[symToStringTag] = tag; - } else { - delete value[symToStringTag]; - } - } - return result; - } + /** + * Used to reference the data object in the template text. + * + * @memberOf _.templateSettings + * @type {string} + */ + 'variable': '', - /** - * Creates an array of the own enumerable symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of symbols. - */ - var getSymbols = !nativeGetSymbols ? stubArray : function(object) { - if (object == null) { - return []; - } - object = Object(object); - return arrayFilter(nativeGetSymbols(object), function(symbol) { - return propertyIsEnumerable.call(object, symbol); - }); - }; + /** + * Used to import variables into the compiled template. + * + * @memberOf _.templateSettings + * @type {Object} + */ + 'imports': { - /** - * Creates an array of the own and inherited enumerable symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of symbols. - */ - var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) { - var result = []; - while (object) { - arrayPush(result, getSymbols(object)); - object = getPrototype(object); + /** + * A reference to the `lodash` function. + * + * @memberOf _.templateSettings.imports + * @type {Function} + */ + '_': lodash } - return result; }; - /** - * Gets the `toStringTag` of `value`. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the `toStringTag`. - */ - var getTag = baseGetTag; - - // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. - if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || - (Map && getTag(new Map) != mapTag) || - (Promise && getTag(Promise.resolve()) != promiseTag) || - (Set && getTag(new Set) != setTag) || - (WeakMap && getTag(new WeakMap) != weakMapTag)) { - getTag = function(value) { - var result = baseGetTag(value), - Ctor = result == objectTag ? value.constructor : undefined, - ctorString = Ctor ? toSource(Ctor) : ''; - - if (ctorString) { - switch (ctorString) { - case dataViewCtorString: return dataViewTag; - case mapCtorString: return mapTag; - case promiseCtorString: return promiseTag; - case setCtorString: return setTag; - case weakMapCtorString: return weakMapTag; - } - } - return result; - }; - } - - /** - * Gets the view, applying any `transforms` to the `start` and `end` positions. - * - * @private - * @param {number} start The start of the view. - * @param {number} end The end of the view. - * @param {Array} transforms The transformations to apply to the view. - * @returns {Object} Returns an object containing the `start` and `end` - * positions of the view. - */ - function getView(start, end, transforms) { - var index = -1, - length = transforms.length; + // Ensure wrappers are instances of `baseLodash`. + lodash.prototype = baseLodash.prototype; + lodash.prototype.constructor = lodash; - while (++index < length) { - var data = transforms[index], - size = data.size; + LodashWrapper.prototype = baseCreate(baseLodash.prototype); + LodashWrapper.prototype.constructor = LodashWrapper; - switch (data.type) { - case 'drop': start += size; break; - case 'dropRight': end -= size; break; - case 'take': end = nativeMin(end, start + size); break; - case 'takeRight': start = nativeMax(start, end - size); break; - } - } - return { 'start': start, 'end': end }; - } + /*------------------------------------------------------------------------*/ /** - * Extracts wrapper details from the `source` body comment. + * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation. * * @private - * @param {string} source The source to inspect. - * @returns {Array} Returns the wrapper details. + * @constructor + * @param {*} value The value to wrap. */ - function getWrapDetails(source) { - var match = source.match(reWrapDetails); - return match ? match[1].split(reSplitDetails) : []; + function LazyWrapper(value) { + this.__wrapped__ = value; + this.__actions__ = []; + this.__dir__ = 1; + this.__filtered__ = false; + this.__iteratees__ = []; + this.__takeCount__ = MAX_ARRAY_LENGTH; + this.__views__ = []; } /** - * Checks if `path` exists on `object`. + * Creates a clone of the lazy wrapper object. * * @private - * @param {Object} object The object to query. - * @param {Array|string} path The path to check. - * @param {Function} hasFunc The function to check properties. - * @returns {boolean} Returns `true` if `path` exists, else `false`. + * @name clone + * @memberOf LazyWrapper + * @returns {Object} Returns the cloned `LazyWrapper` object. */ - function hasPath(object, path, hasFunc) { - path = castPath(path, object); - - var index = -1, - length = path.length, - result = false; - - while (++index < length) { - var key = toKey(path[index]); - if (!(result = object != null && hasFunc(object, key))) { - break; - } - object = object[key]; - } - if (result || ++index != length) { - return result; - } - length = object == null ? 0 : object.length; - return !!length && isLength(length) && isIndex(key, length) && - (isArray(object) || isArguments(object)); + function lazyClone() { + var result = new LazyWrapper(this.__wrapped__); + result.__actions__ = copyArray(this.__actions__); + result.__dir__ = this.__dir__; + result.__filtered__ = this.__filtered__; + result.__iteratees__ = copyArray(this.__iteratees__); + result.__takeCount__ = this.__takeCount__; + result.__views__ = copyArray(this.__views__); + return result; } /** - * Initializes an array clone. + * Reverses the direction of lazy iteration. * * @private - * @param {Array} array The array to clone. - * @returns {Array} Returns the initialized clone. + * @name reverse + * @memberOf LazyWrapper + * @returns {Object} Returns the new reversed `LazyWrapper` object. */ - function initCloneArray(array) { - var length = array.length, - result = new array.constructor(length); - - // Add properties assigned by `RegExp#exec`. - if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) { - result.index = array.index; - result.input = array.input; + function lazyReverse() { + if (this.__filtered__) { + var result = new LazyWrapper(this); + result.__dir__ = -1; + result.__filtered__ = true; + } else { + result = this.clone(); + result.__dir__ *= -1; } return result; } /** - * Initializes an object clone. - * - * @private - * @param {Object} object The object to clone. - * @returns {Object} Returns the initialized clone. - */ - function initCloneObject(object) { - return (typeof object.constructor == 'function' && !isPrototype(object)) - ? baseCreate(getPrototype(object)) - : {}; - } - - /** - * Initializes an object clone based on its `toStringTag`. - * - * **Note:** This function only supports cloning values with tags of - * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`. + * Extracts the unwrapped value from its lazy wrapper. * * @private - * @param {Object} object The object to clone. - * @param {string} tag The `toStringTag` of the object to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the initialized clone. + * @name value + * @memberOf LazyWrapper + * @returns {*} Returns the unwrapped value. */ - function initCloneByTag(object, tag, isDeep) { - var Ctor = object.constructor; - switch (tag) { - case arrayBufferTag: - return cloneArrayBuffer(object); - - case boolTag: - case dateTag: - return new Ctor(+object); - - case dataViewTag: - return cloneDataView(object, isDeep); - - case float32Tag: case float64Tag: - case int8Tag: case int16Tag: case int32Tag: - case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag: - return cloneTypedArray(object, isDeep); + function lazyValue() { + var array = this.__wrapped__.value(), + dir = this.__dir__, + isArr = isArray(array), + isRight = dir < 0, + arrLength = isArr ? array.length : 0, + view = getView(0, arrLength, this.__views__), + start = view.start, + end = view.end, + length = end - start, + index = isRight ? end : (start - 1), + iteratees = this.__iteratees__, + iterLength = iteratees.length, + resIndex = 0, + takeCount = nativeMin(length, this.__takeCount__); - case mapTag: - return new Ctor; + if (!isArr || (!isRight && arrLength == length && takeCount == length)) { + return baseWrapperValue(array, this.__actions__); + } + var result = []; - case numberTag: - case stringTag: - return new Ctor(object); + outer: + while (length-- && resIndex < takeCount) { + index += dir; - case regexpTag: - return cloneRegExp(object); + var iterIndex = -1, + value = array[index]; - case setTag: - return new Ctor; + while (++iterIndex < iterLength) { + var data = iteratees[iterIndex], + iteratee = data.iteratee, + type = data.type, + computed = iteratee(value); - case symbolTag: - return cloneSymbol(object); + if (type == LAZY_MAP_FLAG) { + value = computed; + } else if (!computed) { + if (type == LAZY_FILTER_FLAG) { + continue outer; + } else { + break outer; + } + } + } + result[resIndex++] = value; } + return result; } + // Ensure `LazyWrapper` is an instance of `baseLodash`. + LazyWrapper.prototype = baseCreate(baseLodash.prototype); + LazyWrapper.prototype.constructor = LazyWrapper; + + /*------------------------------------------------------------------------*/ + /** - * Inserts wrapper `details` in a comment at the top of the `source` body. + * Creates a hash object. * * @private - * @param {string} source The source to modify. - * @returns {Array} details The details to insert. - * @returns {string} Returns the modified source. + * @constructor + * @param {Array} [entries] The key-value pairs to cache. */ - function insertWrapDetails(source, details) { - var length = details.length; - if (!length) { - return source; - } - var lastIndex = length - 1; - details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex]; - details = details.join(length > 2 ? ', ' : ' '); - return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n'); + function Hash(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } } /** - * Checks if `value` is a flattenable `arguments` object or array. + * Removes all key-value entries from the hash. * * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. + * @name clear + * @memberOf Hash */ - function isFlattenable(value) { - return isArray(value) || isArguments(value) || - !!(spreadableSymbol && value && value[spreadableSymbol]); + function hashClear() { + this.__data__ = nativeCreate ? nativeCreate(null) : {}; + this.size = 0; } /** - * Checks if `value` is a valid array-like index. + * Removes `key` and its value from the hash. * * @private - * @param {*} value The value to check. - * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. - * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + * @name delete + * @memberOf Hash + * @param {Object} hash The hash to modify. + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ - function isIndex(value, length) { - var type = typeof value; - length = length == null ? MAX_SAFE_INTEGER : length; - - return !!length && - (type == 'number' || - (type != 'symbol' && reIsUint.test(value))) && - (value > -1 && value % 1 == 0 && value < length); + function hashDelete(key) { + var result = this.has(key) && delete this.__data__[key]; + this.size -= result ? 1 : 0; + return result; } /** - * Checks if the given arguments are from an iteratee call. + * Gets the hash value for `key`. * * @private - * @param {*} value The potential iteratee value argument. - * @param {*} index The potential iteratee index or key argument. - * @param {*} object The potential iteratee object argument. - * @returns {boolean} Returns `true` if the arguments are from an iteratee call, - * else `false`. + * @name get + * @memberOf Hash + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. */ - function isIterateeCall(value, index, object) { - if (!isObject(object)) { - return false; - } - var type = typeof index; - if (type == 'number' - ? (isArrayLike(object) && isIndex(index, object.length)) - : (type == 'string' && index in object) - ) { - return eq(object[index], value); + function hashGet(key) { + var data = this.__data__; + if (nativeCreate) { + var result = data[key]; + return result === HASH_UNDEFINED ? undefined : result; } - return false; + return hasOwnProperty.call(data, key) ? data[key] : undefined; } /** - * Checks if `value` is a property name and not a property path. + * Checks if a hash value for `key` exists. * * @private - * @param {*} value The value to check. - * @param {Object} [object] The object to query keys on. - * @returns {boolean} Returns `true` if `value` is a property name, else `false`. + * @name has + * @memberOf Hash + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ - function isKey(value, object) { - if (isArray(value)) { - return false; - } - var type = typeof value; - if (type == 'number' || type == 'symbol' || type == 'boolean' || - value == null || isSymbol(value)) { - return true; - } - return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || - (object != null && value in Object(object)); + function hashHas(key) { + var data = this.__data__; + return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key); } /** - * Checks if `value` is suitable for use as unique object key. + * Sets the hash `key` to `value`. * * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is suitable, else `false`. + * @name set + * @memberOf Hash + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the hash instance. */ - function isKeyable(value) { - var type = typeof value; - return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') - ? (value !== '__proto__') - : (value === null); + function hashSet(key, value) { + var data = this.__data__; + this.size += this.has(key) ? 0 : 1; + data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; + return this; } + // Add methods to `Hash`. + Hash.prototype.clear = hashClear; + Hash.prototype['delete'] = hashDelete; + Hash.prototype.get = hashGet; + Hash.prototype.has = hashHas; + Hash.prototype.set = hashSet; + + /*------------------------------------------------------------------------*/ + /** - * Checks if `func` has a lazy counterpart. + * Creates an list cache object. * * @private - * @param {Function} func The function to check. - * @returns {boolean} Returns `true` if `func` has a lazy counterpart, - * else `false`. + * @constructor + * @param {Array} [entries] The key-value pairs to cache. */ - function isLaziable(func) { - var funcName = getFuncName(func), - other = lodash[funcName]; + function ListCache(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; - if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) { - return false; - } - if (func === other) { - return true; + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); } - var data = getData(other); - return !!data && func === data[0]; } /** - * Checks if `func` has its source masked. + * Removes all key-value entries from the list cache. * * @private - * @param {Function} func The function to check. - * @returns {boolean} Returns `true` if `func` is masked, else `false`. + * @name clear + * @memberOf ListCache */ - function isMasked(func) { - return !!maskSrcKey && (maskSrcKey in func); + function listCacheClear() { + this.__data__ = []; + this.size = 0; } /** - * Checks if `func` is capable of being masked. + * Removes `key` and its value from the list cache. * * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `func` is maskable, else `false`. + * @name delete + * @memberOf ListCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ - var isMaskable = coreJsData ? isFunction : stubFalse; + function listCacheDelete(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + return false; + } + var lastIndex = data.length - 1; + if (index == lastIndex) { + data.pop(); + } else { + splice.call(data, index, 1); + } + --this.size; + return true; + } /** - * Checks if `value` is likely a prototype object. + * Gets the list cache value for `key`. * * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. + * @name get + * @memberOf ListCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. */ - function isPrototype(value) { - var Ctor = value && value.constructor, - proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; + function listCacheGet(key) { + var data = this.__data__, + index = assocIndexOf(data, key); - return value === proto; + return index < 0 ? undefined : data[index][1]; } /** - * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. + * Checks if a list cache value for `key` exists. * * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` if suitable for strict - * equality comparisons, else `false`. + * @name has + * @memberOf ListCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ - function isStrictComparable(value) { - return value === value && !isObject(value); + function listCacheHas(key) { + return assocIndexOf(this.__data__, key) > -1; } /** - * A specialized version of `matchesProperty` for source values suitable - * for strict equality comparisons, i.e. `===`. + * Sets the list cache `key` to `value`. * * @private - * @param {string} key The key of the property to get. - * @param {*} srcValue The value to match. - * @returns {Function} Returns the new spec function. + * @name set + * @memberOf ListCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the list cache instance. */ - function matchesStrictComparable(key, srcValue) { - return function(object) { - if (object == null) { - return false; - } - return object[key] === srcValue && - (srcValue !== undefined || (key in Object(object))); - }; + function listCacheSet(key, value) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + ++this.size; + data.push([key, value]); + } else { + data[index][1] = value; + } + return this; } + // Add methods to `ListCache`. + ListCache.prototype.clear = listCacheClear; + ListCache.prototype['delete'] = listCacheDelete; + ListCache.prototype.get = listCacheGet; + ListCache.prototype.has = listCacheHas; + ListCache.prototype.set = listCacheSet; + + /*------------------------------------------------------------------------*/ + /** - * A specialized version of `_.memoize` which clears the memoized function's - * cache when it exceeds `MAX_MEMOIZE_SIZE`. + * Creates a map cache object to store key-value pairs. * * @private - * @param {Function} func The function to have its output memoized. - * @returns {Function} Returns the new memoized function. + * @constructor + * @param {Array} [entries] The key-value pairs to cache. */ - function memoizeCapped(func) { - var result = memoize(func, function(key) { - if (cache.size === MAX_MEMOIZE_SIZE) { - cache.clear(); - } - return key; - }); + function MapCache(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; - var cache = result.cache; - return result; + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } } /** - * Merges the function metadata of `source` into `data`. - * - * Merging metadata reduces the number of wrappers used to invoke a function. - * This is possible because methods like `_.bind`, `_.curry`, and `_.partial` - * may be applied regardless of execution order. Methods like `_.ary` and - * `_.rearg` modify function arguments, making the order in which they are - * executed important, preventing the merging of metadata. However, we make - * an exception for a safe combined case where curried functions have `_.ary` - * and or `_.rearg` applied. + * Removes all key-value entries from the map. * * @private - * @param {Array} data The destination metadata. - * @param {Array} source The source metadata. - * @returns {Array} Returns `data`. + * @name clear + * @memberOf MapCache */ - function mergeData(data, source) { - var bitmask = data[1], - srcBitmask = source[1], - newBitmask = bitmask | srcBitmask, - isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG); - - var isCombo = - ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_CURRY_FLAG)) || - ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_REARG_FLAG) && (data[7].length <= source[8])) || - ((srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG)); - - // Exit early if metadata can't be merged. - if (!(isCommon || isCombo)) { - return data; - } - // Use source `thisArg` if available. - if (srcBitmask & WRAP_BIND_FLAG) { - data[2] = source[2]; - // Set when currying a bound function. - newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG; - } - // Compose partial arguments. - var value = source[3]; - if (value) { - var partials = data[3]; - data[3] = partials ? composeArgs(partials, value, source[4]) : value; - data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4]; - } - // Compose partial right arguments. - value = source[5]; - if (value) { - partials = data[5]; - data[5] = partials ? composeArgsRight(partials, value, source[6]) : value; - data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6]; - } - // Use source `argPos` if available. - value = source[7]; - if (value) { - data[7] = value; - } - // Use source `ary` if it's smaller. - if (srcBitmask & WRAP_ARY_FLAG) { - data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]); - } - // Use source `arity` if one is not provided. - if (data[9] == null) { - data[9] = source[9]; - } - // Use source `func` and merge bitmasks. - data[0] = source[0]; - data[1] = newBitmask; - - return data; + function mapCacheClear() { + this.size = 0; + this.__data__ = { + 'hash': new Hash, + 'map': new (Map || ListCache), + 'string': new Hash + }; } /** - * This function is like - * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) - * except that it includes inherited enumerable properties. + * Removes `key` and its value from the map. * * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. + * @name delete + * @memberOf MapCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ - function nativeKeysIn(object) { - var result = []; - if (object != null) { - for (var key in Object(object)) { - result.push(key); - } - } + function mapCacheDelete(key) { + var result = getMapData(this, key)['delete'](key); + this.size -= result ? 1 : 0; return result; } /** - * Converts `value` to a string using `Object.prototype.toString`. + * Gets the map value for `key`. * * @private - * @param {*} value The value to convert. - * @returns {string} Returns the converted string. + * @name get + * @memberOf MapCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. */ - function objectToString(value) { - return nativeObjectToString.call(value); + function mapCacheGet(key) { + return getMapData(this, key).get(key); } /** - * A specialized version of `baseRest` which transforms the rest array. + * Checks if a map value for `key` exists. * * @private - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @param {Function} transform The rest array transform. - * @returns {Function} Returns the new function. + * @name has + * @memberOf MapCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ - function overRest(func, start, transform) { - start = nativeMax(start === undefined ? (func.length - 1) : start, 0); - return function() { - var args = arguments, - index = -1, - length = nativeMax(args.length - start, 0), - array = Array(length); - - while (++index < length) { - array[index] = args[start + index]; - } - index = -1; - var otherArgs = Array(start + 1); - while (++index < start) { - otherArgs[index] = args[index]; - } - otherArgs[start] = transform(array); - return apply(func, this, otherArgs); - }; + function mapCacheHas(key) { + return getMapData(this, key).has(key); } /** - * Gets the parent value at `path` of `object`. + * Sets the map `key` to `value`. * * @private - * @param {Object} object The object to query. - * @param {Array} path The path to get the parent value of. - * @returns {*} Returns the parent value. + * @name set + * @memberOf MapCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the map cache instance. */ - function parent(object, path) { - return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1)); + function mapCacheSet(key, value) { + var data = getMapData(this, key), + size = data.size; + + data.set(key, value); + this.size += data.size == size ? 0 : 1; + return this; } + // Add methods to `MapCache`. + MapCache.prototype.clear = mapCacheClear; + MapCache.prototype['delete'] = mapCacheDelete; + MapCache.prototype.get = mapCacheGet; + MapCache.prototype.has = mapCacheHas; + MapCache.prototype.set = mapCacheSet; + + /*------------------------------------------------------------------------*/ + /** - * Reorder `array` according to the specified indexes where the element at - * the first index is assigned as the first element, the element at - * the second index is assigned as the second element, and so on. + * + * Creates an array cache object to store unique values. * * @private - * @param {Array} array The array to reorder. - * @param {Array} indexes The arranged array indexes. - * @returns {Array} Returns `array`. + * @constructor + * @param {Array} [values] The values to cache. */ - function reorder(array, indexes) { - var arrLength = array.length, - length = nativeMin(indexes.length, arrLength), - oldArray = copyArray(array); + function SetCache(values) { + var index = -1, + length = values == null ? 0 : values.length; - while (length--) { - var index = indexes[length]; - array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined; + this.__data__ = new MapCache; + while (++index < length) { + this.add(values[index]); } - return array; } /** - * Gets the value at `key`, unless `key` is "__proto__" or "constructor". + * Adds `value` to the array cache. * * @private - * @param {Object} object The object to query. - * @param {string} key The key of the property to get. - * @returns {*} Returns the property value. + * @name add + * @memberOf SetCache + * @alias push + * @param {*} value The value to cache. + * @returns {Object} Returns the cache instance. */ - function safeGet(object, key) { - if (key === 'constructor' && typeof object[key] === 'function') { - return; - } - - if (key == '__proto__') { - return; - } - - return object[key]; + function setCacheAdd(value) { + this.__data__.set(value, HASH_UNDEFINED); + return this; } /** - * Sets metadata for `func`. + * Checks if `value` is in the array cache. * - * **Note:** If this function becomes hot, i.e. is invoked a lot in a short - * period of time, it will trip its breaker and transition to an identity - * function to avoid garbage collection pauses in V8. See - * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070) - * for more details. + * @private + * @name has + * @memberOf SetCache + * @param {*} value The value to search for. + * @returns {number} Returns `true` if `value` is found, else `false`. + */ + function setCacheHas(value) { + return this.__data__.has(value); + } + + // Add methods to `SetCache`. + SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; + SetCache.prototype.has = setCacheHas; + + /*------------------------------------------------------------------------*/ + + /** + * Creates a stack cache object to store key-value pairs. * * @private - * @param {Function} func The function to associate metadata with. - * @param {*} data The metadata. - * @returns {Function} Returns `func`. + * @constructor + * @param {Array} [entries] The key-value pairs to cache. */ - var setData = shortOut(baseSetData); + function Stack(entries) { + var data = this.__data__ = new ListCache(entries); + this.size = data.size; + } /** - * A simple wrapper around the global [`setTimeout`](https://mdn.io/setTimeout). + * Removes all key-value entries from the stack. * * @private - * @param {Function} func The function to delay. - * @param {number} wait The number of milliseconds to delay invocation. - * @returns {number|Object} Returns the timer id or timeout object. + * @name clear + * @memberOf Stack */ - var setTimeout = ctxSetTimeout || function(func, wait) { - return root.setTimeout(func, wait); - }; + function stackClear() { + this.__data__ = new ListCache; + this.size = 0; + } /** - * Sets the `toString` method of `func` to return `string`. + * Removes `key` and its value from the stack. * * @private - * @param {Function} func The function to modify. - * @param {Function} string The `toString` result. - * @returns {Function} Returns `func`. + * @name delete + * @memberOf Stack + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ - var setToString = shortOut(baseSetToString); + function stackDelete(key) { + var data = this.__data__, + result = data['delete'](key); + + this.size = data.size; + return result; + } /** - * Sets the `toString` method of `wrapper` to mimic the source of `reference` - * with wrapper details in a comment at the top of the source body. + * Gets the stack value for `key`. * * @private - * @param {Function} wrapper The function to modify. - * @param {Function} reference The reference function. - * @param {number} bitmask The bitmask flags. See `createWrap` for more details. - * @returns {Function} Returns `wrapper`. + * @name get + * @memberOf Stack + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. */ - function setWrapToString(wrapper, reference, bitmask) { - var source = (reference + ''); - return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask))); + function stackGet(key) { + return this.__data__.get(key); } /** - * Creates a function that'll short out and invoke `identity` instead - * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` - * milliseconds. + * Checks if a stack value for `key` exists. * * @private - * @param {Function} func The function to restrict. - * @returns {Function} Returns the new shortable function. + * @name has + * @memberOf Stack + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ - function shortOut(func) { - var count = 0, - lastCalled = 0; - - return function() { - var stamp = nativeNow(), - remaining = HOT_SPAN - (stamp - lastCalled); - - lastCalled = stamp; - if (remaining > 0) { - if (++count >= HOT_COUNT) { - return arguments[0]; - } - } else { - count = 0; - } - return func.apply(undefined, arguments); - }; + function stackHas(key) { + return this.__data__.has(key); } /** - * A specialized version of `_.shuffle` which mutates and sets the size of `array`. + * Sets the stack `key` to `value`. * * @private - * @param {Array} array The array to shuffle. - * @param {number} [size=array.length] The size of `array`. - * @returns {Array} Returns `array`. + * @name set + * @memberOf Stack + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the stack cache instance. */ - function shuffleSelf(array, size) { - var index = -1, - length = array.length, - lastIndex = length - 1; - - size = size === undefined ? length : size; - while (++index < size) { - var rand = baseRandom(index, lastIndex), - value = array[rand]; - - array[rand] = array[index]; - array[index] = value; + function stackSet(key, value) { + var data = this.__data__; + if (data instanceof ListCache) { + var pairs = data.__data__; + if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { + pairs.push([key, value]); + this.size = ++data.size; + return this; + } + data = this.__data__ = new MapCache(pairs); } - array.length = size; - return array; + data.set(key, value); + this.size = data.size; + return this; } + // Add methods to `Stack`. + Stack.prototype.clear = stackClear; + Stack.prototype['delete'] = stackDelete; + Stack.prototype.get = stackGet; + Stack.prototype.has = stackHas; + Stack.prototype.set = stackSet; + + /*------------------------------------------------------------------------*/ + /** - * Converts `string` to a property path array. + * Creates an array of the enumerable property names of the array-like `value`. * * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the property path array. + * @param {*} value The value to query. + * @param {boolean} inherited Specify returning inherited property names. + * @returns {Array} Returns the array of property names. */ - var stringToPath = memoizeCapped(function(string) { - var result = []; - if (string.charCodeAt(0) === 46 /* . */) { - result.push(''); + function arrayLikeKeys(value, inherited) { + var isArr = isArray(value), + isArg = !isArr && isArguments(value), + isBuff = !isArr && !isArg && isBuffer(value), + isType = !isArr && !isArg && !isBuff && isTypedArray(value), + skipIndexes = isArr || isArg || isBuff || isType, + result = skipIndexes ? baseTimes(value.length, String) : [], + length = result.length; + + for (var key in value) { + if ((inherited || hasOwnProperty.call(value, key)) && + !(skipIndexes && ( + // Safari 9 has enumerable `arguments.length` in strict mode. + key == 'length' || + // Node.js 0.10 has enumerable non-index properties on buffers. + (isBuff && (key == 'offset' || key == 'parent')) || + // PhantomJS 2 has enumerable non-index properties on typed arrays. + (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || + // Skip index properties. + isIndex(key, length) + ))) { + result.push(key); + } } - string.replace(rePropName, function(match, number, quote, subString) { - result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match)); - }); return result; - }); + } /** - * Converts `value` to a string key if it's not a string or symbol. + * A specialized version of `_.sample` for arrays. * * @private - * @param {*} value The value to inspect. - * @returns {string|symbol} Returns the key. + * @param {Array} array The array to sample. + * @returns {*} Returns the random element. */ - function toKey(value) { - if (typeof value == 'string' || isSymbol(value)) { - return value; - } - var result = (value + ''); - return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; + function arraySample(array) { + var length = array.length; + return length ? array[baseRandom(0, length - 1)] : undefined; } /** - * Converts `func` to its source code. + * A specialized version of `_.sampleSize` for arrays. * * @private - * @param {Function} func The function to convert. - * @returns {string} Returns the source code. + * @param {Array} array The array to sample. + * @param {number} n The number of elements to sample. + * @returns {Array} Returns the random elements. */ - function toSource(func) { - if (func != null) { - try { - return funcToString.call(func); - } catch (e) {} - try { - return (func + ''); - } catch (e) {} - } - return ''; + function arraySampleSize(array, n) { + return shuffleSelf(copyArray(array), baseClamp(n, 0, array.length)); } /** - * Updates wrapper `details` based on `bitmask` flags. + * A specialized version of `_.shuffle` for arrays. * * @private - * @returns {Array} details The details to modify. - * @param {number} bitmask The bitmask flags. See `createWrap` for more details. - * @returns {Array} Returns `details`. + * @param {Array} array The array to shuffle. + * @returns {Array} Returns the new shuffled array. */ - function updateWrapDetails(details, bitmask) { - arrayEach(wrapFlags, function(pair) { - var value = '_.' + pair[0]; - if ((bitmask & pair[1]) && !arrayIncludes(details, value)) { - details.push(value); - } - }); - return details.sort(); + function arrayShuffle(array) { + return shuffleSelf(copyArray(array)); } /** - * Creates a clone of `wrapper`. + * This function is like `assignValue` except that it doesn't assign + * `undefined` values. * * @private - * @param {Object} wrapper The wrapper to clone. - * @returns {Object} Returns the cloned wrapper. + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. */ - function wrapperClone(wrapper) { - if (wrapper instanceof LazyWrapper) { - return wrapper.clone(); + function assignMergeValue(object, key, value) { + if ((value !== undefined && !eq(object[key], value)) || + (value === undefined && !(key in object))) { + baseAssignValue(object, key, value); } - var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__); - result.__actions__ = copyArray(wrapper.__actions__); - result.__index__ = wrapper.__index__; - result.__values__ = wrapper.__values__; - return result; } - /*------------------------------------------------------------------------*/ - /** - * Creates an array of elements split into groups the length of `size`. - * If `array` can't be split evenly, the final chunk will be the remaining - * elements. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to process. - * @param {number} [size=1] The length of each chunk - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Array} Returns the new array of chunks. - * @example - * - * _.chunk(['a', 'b', 'c', 'd'], 2); - * // => [['a', 'b'], ['c', 'd']] + * Assigns `value` to `key` of `object` if the existing value is not equivalent + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. * - * _.chunk(['a', 'b', 'c', 'd'], 3); - * // => [['a', 'b', 'c'], ['d']] + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. */ - function chunk(array, size, guard) { - if ((guard ? isIterateeCall(array, size, guard) : size === undefined)) { - size = 1; - } else { - size = nativeMax(toInteger(size), 0); - } - var length = array == null ? 0 : array.length; - if (!length || size < 1) { - return []; - } - var index = 0, - resIndex = 0, - result = Array(nativeCeil(length / size)); - - while (index < length) { - result[resIndex++] = baseSlice(array, index, (index += size)); + function assignValue(object, key, value) { + var objValue = object[key]; + if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || + (value === undefined && !(key in object))) { + baseAssignValue(object, key, value); } - return result; } /** - * Creates an array with all falsey values removed. The values `false`, `null`, - * `0`, `""`, `undefined`, and `NaN` are falsey. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to compact. - * @returns {Array} Returns the new array of filtered values. - * @example + * Gets the index at which the `key` is found in `array` of key-value pairs. * - * _.compact([0, 1, false, 2, '', 3]); - * // => [1, 2, 3] + * @private + * @param {Array} array The array to inspect. + * @param {*} key The key to search for. + * @returns {number} Returns the index of the matched value, else `-1`. */ - function compact(array) { - var index = -1, - length = array == null ? 0 : array.length, - resIndex = 0, - result = []; - - while (++index < length) { - var value = array[index]; - if (value) { - result[resIndex++] = value; + function assocIndexOf(array, key) { + var length = array.length; + while (length--) { + if (eq(array[length][0], key)) { + return length; } } - return result; + return -1; } /** - * Creates a new array concatenating `array` with any additional arrays - * and/or values. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to concatenate. - * @param {...*} [values] The values to concatenate. - * @returns {Array} Returns the new concatenated array. - * @example - * - * var array = [1]; - * var other = _.concat(array, 2, [3], [[4]]); - * - * console.log(other); - * // => [1, 2, 3, [4]] + * Aggregates elements of `collection` on `accumulator` with keys transformed + * by `iteratee` and values set by `setter`. * - * console.log(array); - * // => [1] + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} setter The function to set `accumulator` values. + * @param {Function} iteratee The iteratee to transform keys. + * @param {Object} accumulator The initial aggregated object. + * @returns {Function} Returns `accumulator`. */ - function concat() { - var length = arguments.length; - if (!length) { - return []; - } - var args = Array(length - 1), - array = arguments[0], - index = length; - - while (index--) { - args[index - 1] = arguments[index]; - } - return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1)); + function baseAggregator(collection, setter, iteratee, accumulator) { + baseEach(collection, function(value, key, collection) { + setter(accumulator, value, iteratee(value), collection); + }); + return accumulator; } /** - * Creates an array of `array` values not included in the other given arrays - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. The order and references of result values are - * determined by the first array. - * - * **Note:** Unlike `_.pullAll`, this method returns a new array. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {...Array} [values] The values to exclude. - * @returns {Array} Returns the new array of filtered values. - * @see _.without, _.xor - * @example - * - * _.difference([2, 1], [2, 3]); - * // => [1] - */ - var difference = baseRest(function(array, values) { - return isArrayLikeObject(array) - ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true)) - : []; - }); - - /** - * This method is like `_.difference` except that it accepts `iteratee` which - * is invoked for each element of `array` and `values` to generate the criterion - * by which they're compared. The order and references of result values are - * determined by the first array. The iteratee is invoked with one argument: - * (value). - * - * **Note:** Unlike `_.pullAllBy`, this method returns a new array. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {...Array} [values] The values to exclude. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {Array} Returns the new array of filtered values. - * @example - * - * _.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); - * // => [1.2] + * The base implementation of `_.assign` without support for multiple sources + * or `customizer` functions. * - * // The `_.property` iteratee shorthand. - * _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x'); - * // => [{ 'x': 2 }] + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @returns {Object} Returns `object`. */ - var differenceBy = baseRest(function(array, values) { - var iteratee = last(values); - if (isArrayLikeObject(iteratee)) { - iteratee = undefined; - } - return isArrayLikeObject(array) - ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)) - : []; - }); + function baseAssign(object, source) { + return object && copyObject(source, keys(source), object); + } /** - * This method is like `_.difference` except that it accepts `comparator` - * which is invoked to compare elements of `array` to `values`. The order and - * references of result values are determined by the first array. The comparator - * is invoked with two arguments: (arrVal, othVal). - * - * **Note:** Unlike `_.pullAllWith`, this method returns a new array. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {...Array} [values] The values to exclude. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of filtered values. - * @example - * - * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * The base implementation of `_.assignIn` without support for multiple sources + * or `customizer` functions. * - * _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual); - * // => [{ 'x': 2, 'y': 1 }] + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @returns {Object} Returns `object`. */ - var differenceWith = baseRest(function(array, values) { - var comparator = last(values); - if (isArrayLikeObject(comparator)) { - comparator = undefined; - } - return isArrayLikeObject(array) - ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), undefined, comparator) - : []; - }); + function baseAssignIn(object, source) { + return object && copyObject(source, keysIn(source), object); + } /** - * Creates a slice of `array` with `n` elements dropped from the beginning. - * - * @static - * @memberOf _ - * @since 0.5.0 - * @category Array - * @param {Array} array The array to query. - * @param {number} [n=1] The number of elements to drop. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Array} Returns the slice of `array`. - * @example - * - * _.drop([1, 2, 3]); - * // => [2, 3] - * - * _.drop([1, 2, 3], 2); - * // => [3] - * - * _.drop([1, 2, 3], 5); - * // => [] + * The base implementation of `assignValue` and `assignMergeValue` without + * value checks. * - * _.drop([1, 2, 3], 0); - * // => [1, 2, 3] + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. */ - function drop(array, n, guard) { - var length = array == null ? 0 : array.length; - if (!length) { - return []; + function baseAssignValue(object, key, value) { + if (key == '__proto__' && defineProperty) { + defineProperty(object, key, { + 'configurable': true, + 'enumerable': true, + 'value': value, + 'writable': true + }); + } else { + object[key] = value; } - n = (guard || n === undefined) ? 1 : toInteger(n); - return baseSlice(array, n < 0 ? 0 : n, length); } /** - * Creates a slice of `array` with `n` elements dropped from the end. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to query. - * @param {number} [n=1] The number of elements to drop. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Array} Returns the slice of `array`. - * @example - * - * _.dropRight([1, 2, 3]); - * // => [1, 2] - * - * _.dropRight([1, 2, 3], 2); - * // => [1] - * - * _.dropRight([1, 2, 3], 5); - * // => [] + * The base implementation of `_.at` without support for individual paths. * - * _.dropRight([1, 2, 3], 0); - * // => [1, 2, 3] + * @private + * @param {Object} object The object to iterate over. + * @param {string[]} paths The property paths to pick. + * @returns {Array} Returns the picked elements. */ - function dropRight(array, n, guard) { - var length = array == null ? 0 : array.length; - if (!length) { - return []; + function baseAt(object, paths) { + var index = -1, + length = paths.length, + result = Array(length), + skip = object == null; + + while (++index < length) { + result[index] = skip ? undefined : get(object, paths[index]); } - n = (guard || n === undefined) ? 1 : toInteger(n); - n = length - n; - return baseSlice(array, 0, n < 0 ? 0 : n); + return result; } /** - * Creates a slice of `array` excluding elements dropped from the end. - * Elements are dropped until `predicate` returns falsey. The predicate is - * invoked with three arguments: (value, index, array). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to query. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the slice of `array`. - * @example - * - * var users = [ - * { 'user': 'barney', 'active': true }, - * { 'user': 'fred', 'active': false }, - * { 'user': 'pebbles', 'active': false } - * ]; - * - * _.dropRightWhile(users, function(o) { return !o.active; }); - * // => objects for ['barney'] - * - * // The `_.matches` iteratee shorthand. - * _.dropRightWhile(users, { 'user': 'pebbles', 'active': false }); - * // => objects for ['barney', 'fred'] - * - * // The `_.matchesProperty` iteratee shorthand. - * _.dropRightWhile(users, ['active', false]); - * // => objects for ['barney'] + * The base implementation of `_.clamp` which doesn't coerce arguments. * - * // The `_.property` iteratee shorthand. - * _.dropRightWhile(users, 'active'); - * // => objects for ['barney', 'fred', 'pebbles'] + * @private + * @param {number} number The number to clamp. + * @param {number} [lower] The lower bound. + * @param {number} upper The upper bound. + * @returns {number} Returns the clamped number. */ - function dropRightWhile(array, predicate) { - return (array && array.length) - ? baseWhile(array, getIteratee(predicate, 3), true, true) - : []; + function baseClamp(number, lower, upper) { + if (number === number) { + if (upper !== undefined) { + number = number <= upper ? number : upper; + } + if (lower !== undefined) { + number = number >= lower ? number : lower; + } + } + return number; } /** - * Creates a slice of `array` excluding elements dropped from the beginning. - * Elements are dropped until `predicate` returns falsey. The predicate is - * invoked with three arguments: (value, index, array). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to query. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the slice of `array`. - * @example - * - * var users = [ - * { 'user': 'barney', 'active': false }, - * { 'user': 'fred', 'active': false }, - * { 'user': 'pebbles', 'active': true } - * ]; - * - * _.dropWhile(users, function(o) { return !o.active; }); - * // => objects for ['pebbles'] - * - * // The `_.matches` iteratee shorthand. - * _.dropWhile(users, { 'user': 'barney', 'active': false }); - * // => objects for ['fred', 'pebbles'] - * - * // The `_.matchesProperty` iteratee shorthand. - * _.dropWhile(users, ['active', false]); - * // => objects for ['pebbles'] + * The base implementation of `_.clone` and `_.cloneDeep` which tracks + * traversed objects. * - * // The `_.property` iteratee shorthand. - * _.dropWhile(users, 'active'); - * // => objects for ['barney', 'fred', 'pebbles'] + * @private + * @param {*} value The value to clone. + * @param {boolean} bitmask The bitmask flags. + * 1 - Deep clone + * 2 - Flatten inherited properties + * 4 - Clone symbols + * @param {Function} [customizer] The function to customize cloning. + * @param {string} [key] The key of `value`. + * @param {Object} [object] The parent object of `value`. + * @param {Object} [stack] Tracks traversed objects and their clone counterparts. + * @returns {*} Returns the cloned value. */ - function dropWhile(array, predicate) { - return (array && array.length) - ? baseWhile(array, getIteratee(predicate, 3), true) - : []; + function baseClone(value, bitmask, customizer, key, object, stack) { + var result, + isDeep = bitmask & CLONE_DEEP_FLAG, + isFlat = bitmask & CLONE_FLAT_FLAG, + isFull = bitmask & CLONE_SYMBOLS_FLAG; + + if (customizer) { + result = object ? customizer(value, key, object, stack) : customizer(value); + } + if (result !== undefined) { + return result; + } + if (!isObject(value)) { + return value; + } + var isArr = isArray(value); + if (isArr) { + result = initCloneArray(value); + if (!isDeep) { + return copyArray(value, result); + } + } else { + var tag = getTag(value), + isFunc = tag == funcTag || tag == genTag; + + if (isBuffer(value)) { + return cloneBuffer(value, isDeep); + } + if (tag == objectTag || tag == argsTag || (isFunc && !object)) { + result = (isFlat || isFunc) ? {} : initCloneObject(value); + if (!isDeep) { + return isFlat + ? copySymbolsIn(value, baseAssignIn(result, value)) + : copySymbols(value, baseAssign(result, value)); + } + } else { + if (!cloneableTags[tag]) { + return object ? value : {}; + } + result = initCloneByTag(value, tag, isDeep); + } + } + // Check for circular references and return its corresponding clone. + stack || (stack = new Stack); + var stacked = stack.get(value); + if (stacked) { + return stacked; + } + stack.set(value, result); + + if (isSet(value)) { + value.forEach(function(subValue) { + result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack)); + }); + } else if (isMap(value)) { + value.forEach(function(subValue, key) { + result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack)); + }); + } + + var keysFunc = isFull + ? (isFlat ? getAllKeysIn : getAllKeys) + : (isFlat ? keysIn : keys); + + var props = isArr ? undefined : keysFunc(value); + arrayEach(props || value, function(subValue, key) { + if (props) { + key = subValue; + subValue = value[key]; + } + // Recursively populate clone (susceptible to call stack limits). + assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack)); + }); + return result; } /** - * Fills elements of `array` with `value` from `start` up to, but not - * including, `end`. - * - * **Note:** This method mutates `array`. - * - * @static - * @memberOf _ - * @since 3.2.0 - * @category Array - * @param {Array} array The array to fill. - * @param {*} value The value to fill `array` with. - * @param {number} [start=0] The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns `array`. - * @example - * - * var array = [1, 2, 3]; - * - * _.fill(array, 'a'); - * console.log(array); - * // => ['a', 'a', 'a'] + * The base implementation of `_.conforms` which doesn't clone `source`. * - * _.fill(Array(3), 2); - * // => [2, 2, 2] + * @private + * @param {Object} source The object of property predicates to conform to. + * @returns {Function} Returns the new spec function. + */ + function baseConforms(source) { + var props = keys(source); + return function(object) { + return baseConformsTo(object, source, props); + }; + } + + /** + * The base implementation of `_.conformsTo` which accepts `props` to check. * - * _.fill([4, 6, 8, 10], '*', 1, 3); - * // => [4, '*', '*', 10] + * @private + * @param {Object} object The object to inspect. + * @param {Object} source The object of property predicates to conform to. + * @returns {boolean} Returns `true` if `object` conforms, else `false`. */ - function fill(array, value, start, end) { - var length = array == null ? 0 : array.length; - if (!length) { - return []; + function baseConformsTo(object, source, props) { + var length = props.length; + if (object == null) { + return !length; } - if (start && typeof start != 'number' && isIterateeCall(array, value, start)) { - start = 0; - end = length; + object = Object(object); + while (length--) { + var key = props[length], + predicate = source[key], + value = object[key]; + + if ((value === undefined && !(key in object)) || !predicate(value)) { + return false; + } } - return baseFill(array, value, start, end); + return true; } /** - * This method is like `_.find` except that it returns the index of the first - * element `predicate` returns truthy for instead of the element itself. - * - * @static - * @memberOf _ - * @since 1.1.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @param {number} [fromIndex=0] The index to search from. - * @returns {number} Returns the index of the found element, else `-1`. - * @example - * - * var users = [ - * { 'user': 'barney', 'active': false }, - * { 'user': 'fred', 'active': false }, - * { 'user': 'pebbles', 'active': true } - * ]; - * - * _.findIndex(users, function(o) { return o.user == 'barney'; }); - * // => 0 - * - * // The `_.matches` iteratee shorthand. - * _.findIndex(users, { 'user': 'fred', 'active': false }); - * // => 1 - * - * // The `_.matchesProperty` iteratee shorthand. - * _.findIndex(users, ['active', false]); - * // => 0 + * The base implementation of `_.delay` and `_.defer` which accepts `args` + * to provide to `func`. * - * // The `_.property` iteratee shorthand. - * _.findIndex(users, 'active'); - * // => 2 + * @private + * @param {Function} func The function to delay. + * @param {number} wait The number of milliseconds to delay invocation. + * @param {Array} args The arguments to provide to `func`. + * @returns {number|Object} Returns the timer id or timeout object. */ - function findIndex(array, predicate, fromIndex) { - var length = array == null ? 0 : array.length; - if (!length) { - return -1; - } - var index = fromIndex == null ? 0 : toInteger(fromIndex); - if (index < 0) { - index = nativeMax(length + index, 0); + function baseDelay(func, wait, args) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); } - return baseFindIndex(array, getIteratee(predicate, 3), index); + return setTimeout(function() { func.apply(undefined, args); }, wait); } /** - * This method is like `_.findIndex` except that it iterates over elements - * of `collection` from right to left. + * The base implementation of methods like `_.difference` without support + * for excluding multiple arrays or iteratee shorthands. * - * @static - * @memberOf _ - * @since 2.0.0 - * @category Array + * @private * @param {Array} array The array to inspect. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @param {number} [fromIndex=array.length-1] The index to search from. - * @returns {number} Returns the index of the found element, else `-1`. - * @example - * - * var users = [ - * { 'user': 'barney', 'active': true }, - * { 'user': 'fred', 'active': false }, - * { 'user': 'pebbles', 'active': false } - * ]; - * - * _.findLastIndex(users, function(o) { return o.user == 'pebbles'; }); - * // => 2 - * - * // The `_.matches` iteratee shorthand. - * _.findLastIndex(users, { 'user': 'barney', 'active': true }); - * // => 0 - * - * // The `_.matchesProperty` iteratee shorthand. - * _.findLastIndex(users, ['active', false]); - * // => 2 - * - * // The `_.property` iteratee shorthand. - * _.findLastIndex(users, 'active'); - * // => 0 + * @param {Array} values The values to exclude. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of filtered values. */ - function findLastIndex(array, predicate, fromIndex) { - var length = array == null ? 0 : array.length; + function baseDifference(array, values, iteratee, comparator) { + var index = -1, + includes = arrayIncludes, + isCommon = true, + length = array.length, + result = [], + valuesLength = values.length; + if (!length) { - return -1; + return result; } - var index = length - 1; - if (fromIndex !== undefined) { - index = toInteger(fromIndex); - index = fromIndex < 0 - ? nativeMax(length + index, 0) - : nativeMin(index, length - 1); + if (iteratee) { + values = arrayMap(values, baseUnary(iteratee)); } - return baseFindIndex(array, getIteratee(predicate, 3), index, true); - } + if (comparator) { + includes = arrayIncludesWith; + isCommon = false; + } + else if (values.length >= LARGE_ARRAY_SIZE) { + includes = cacheHas; + isCommon = false; + values = new SetCache(values); + } + outer: + while (++index < length) { + var value = array[index], + computed = iteratee == null ? value : iteratee(value); - /** - * Flattens `array` a single level deep. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to flatten. - * @returns {Array} Returns the new flattened array. - * @example - * - * _.flatten([1, [2, [3, [4]], 5]]); - * // => [1, 2, [3, [4]], 5] - */ - function flatten(array) { - var length = array == null ? 0 : array.length; - return length ? baseFlatten(array, 1) : []; + value = (comparator || value !== 0) ? value : 0; + if (isCommon && computed === computed) { + var valuesIndex = valuesLength; + while (valuesIndex--) { + if (values[valuesIndex] === computed) { + continue outer; + } + } + result.push(value); + } + else if (!includes(values, computed, comparator)) { + result.push(value); + } + } + return result; } /** - * Recursively flattens `array`. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to flatten. - * @returns {Array} Returns the new flattened array. - * @example + * The base implementation of `_.forEach` without support for iteratee shorthands. * - * _.flattenDeep([1, [2, [3, [4]], 5]]); - * // => [1, 2, 3, 4, 5] + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. */ - function flattenDeep(array) { - var length = array == null ? 0 : array.length; - return length ? baseFlatten(array, INFINITY) : []; - } + var baseEach = createBaseEach(baseForOwn); /** - * Recursively flatten `array` up to `depth` times. - * - * @static - * @memberOf _ - * @since 4.4.0 - * @category Array - * @param {Array} array The array to flatten. - * @param {number} [depth=1] The maximum recursion depth. - * @returns {Array} Returns the new flattened array. - * @example - * - * var array = [1, [2, [3, [4]], 5]]; - * - * _.flattenDepth(array, 1); - * // => [1, 2, [3, [4]], 5] + * The base implementation of `_.forEachRight` without support for iteratee shorthands. * - * _.flattenDepth(array, 2); - * // => [1, 2, 3, [4], 5] + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. */ - function flattenDepth(array, depth) { - var length = array == null ? 0 : array.length; - if (!length) { - return []; - } - depth = depth === undefined ? 1 : toInteger(depth); - return baseFlatten(array, depth); - } + var baseEachRight = createBaseEach(baseForOwnRight, true); /** - * The inverse of `_.toPairs`; this method returns an object composed - * from key-value `pairs`. + * The base implementation of `_.every` without support for iteratee shorthands. * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} pairs The key-value pairs. - * @returns {Object} Returns the new object. - * @example + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false` + */ + function baseEvery(collection, predicate) { + var result = true; + baseEach(collection, function(value, index, collection) { + result = !!predicate(value, index, collection); + return result; + }); + return result; + } + + /** + * The base implementation of methods like `_.max` and `_.min` which accepts a + * `comparator` to determine the extremum value. * - * _.fromPairs([['a', 1], ['b', 2]]); - * // => { 'a': 1, 'b': 2 } + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The iteratee invoked per iteration. + * @param {Function} comparator The comparator used to compare values. + * @returns {*} Returns the extremum value. */ - function fromPairs(pairs) { + function baseExtremum(array, iteratee, comparator) { var index = -1, - length = pairs == null ? 0 : pairs.length, - result = {}; + length = array.length; while (++index < length) { - var pair = pairs[index]; - result[pair[0]] = pair[1]; + var value = array[index], + current = iteratee(value); + + if (current != null && (computed === undefined + ? (current === current && !isSymbol(current)) + : comparator(current, computed) + )) { + var computed = current, + result = value; + } } return result; } /** - * Gets the first element of `array`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @alias first - * @category Array - * @param {Array} array The array to query. - * @returns {*} Returns the first element of `array`. - * @example - * - * _.head([1, 2, 3]); - * // => 1 + * The base implementation of `_.fill` without an iteratee call guard. * - * _.head([]); - * // => undefined + * @private + * @param {Array} array The array to fill. + * @param {*} value The value to fill `array` with. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns `array`. */ - function head(array) { - return (array && array.length) ? array[0] : undefined; + function baseFill(array, value, start, end) { + var length = array.length; + + start = toInteger(start); + if (start < 0) { + start = -start > length ? 0 : (length + start); + } + end = (end === undefined || end > length) ? length : toInteger(end); + if (end < 0) { + end += length; + } + end = start > end ? 0 : toLength(end); + while (start < end) { + array[start++] = value; + } + return array; } /** - * Gets the index at which the first occurrence of `value` is found in `array` - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. If `fromIndex` is negative, it's used as the - * offset from the end of `array`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} [fromIndex=0] The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - * @example - * - * _.indexOf([1, 2, 1, 2], 2); - * // => 1 + * The base implementation of `_.filter` without support for iteratee shorthands. * - * // Search from the `fromIndex`. - * _.indexOf([1, 2, 1, 2], 2, 2); - * // => 3 + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {Array} Returns the new filtered array. */ - function indexOf(array, value, fromIndex) { - var length = array == null ? 0 : array.length; - if (!length) { - return -1; - } - var index = fromIndex == null ? 0 : toInteger(fromIndex); - if (index < 0) { - index = nativeMax(length + index, 0); - } - return baseIndexOf(array, value, index); + function baseFilter(collection, predicate) { + var result = []; + baseEach(collection, function(value, index, collection) { + if (predicate(value, index, collection)) { + result.push(value); + } + }); + return result; } /** - * Gets all but the last element of `array`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to query. - * @returns {Array} Returns the slice of `array`. - * @example + * The base implementation of `_.flatten` with support for restricting flattening. * - * _.initial([1, 2, 3]); - * // => [1, 2] + * @private + * @param {Array} array The array to flatten. + * @param {number} depth The maximum recursion depth. + * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. + * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. + * @param {Array} [result=[]] The initial result value. + * @returns {Array} Returns the new flattened array. */ - function initial(array) { - var length = array == null ? 0 : array.length; - return length ? baseSlice(array, 0, -1) : []; + function baseFlatten(array, depth, predicate, isStrict, result) { + var index = -1, + length = array.length; + + predicate || (predicate = isFlattenable); + result || (result = []); + + while (++index < length) { + var value = array[index]; + if (depth > 0 && predicate(value)) { + if (depth > 1) { + // Recursively flatten arrays (susceptible to call stack limits). + baseFlatten(value, depth - 1, predicate, isStrict, result); + } else { + arrayPush(result, value); + } + } else if (!isStrict) { + result[result.length] = value; + } + } + return result; } /** - * Creates an array of unique values that are included in all given arrays - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. The order and references of result values are - * determined by the first array. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @returns {Array} Returns the new array of intersecting values. - * @example + * The base implementation of `baseForOwn` which iterates over `object` + * properties returned by `keysFunc` and invokes `iteratee` for each property. + * Iteratee functions may exit iteration early by explicitly returning `false`. * - * _.intersection([2, 1], [2, 3]); - * // => [2] + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {Function} keysFunc The function to get the keys of `object`. + * @returns {Object} Returns `object`. */ - var intersection = baseRest(function(arrays) { - var mapped = arrayMap(arrays, castArrayLikeObject); - return (mapped.length && mapped[0] === arrays[0]) - ? baseIntersection(mapped) - : []; - }); + var baseFor = createBaseFor(); /** - * This method is like `_.intersection` except that it accepts `iteratee` - * which is invoked for each element of each `arrays` to generate the criterion - * by which they're compared. The order and references of result values are - * determined by the first array. The iteratee is invoked with one argument: - * (value). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {Array} Returns the new array of intersecting values. - * @example - * - * _.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor); - * // => [2.1] + * This function is like `baseFor` except that it iterates over properties + * in the opposite order. * - * // The `_.property` iteratee shorthand. - * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); - * // => [{ 'x': 1 }] + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {Function} keysFunc The function to get the keys of `object`. + * @returns {Object} Returns `object`. */ - var intersectionBy = baseRest(function(arrays) { - var iteratee = last(arrays), - mapped = arrayMap(arrays, castArrayLikeObject); - - if (iteratee === last(mapped)) { - iteratee = undefined; - } else { - mapped.pop(); - } - return (mapped.length && mapped[0] === arrays[0]) - ? baseIntersection(mapped, getIteratee(iteratee, 2)) - : []; - }); + var baseForRight = createBaseFor(true); /** - * This method is like `_.intersection` except that it accepts `comparator` - * which is invoked to compare elements of `arrays`. The order and references - * of result values are determined by the first array. The comparator is - * invoked with two arguments: (arrVal, othVal). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of intersecting values. - * @example - * - * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; - * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * The base implementation of `_.forOwn` without support for iteratee shorthands. * - * _.intersectionWith(objects, others, _.isEqual); - * // => [{ 'x': 1, 'y': 2 }] + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Object} Returns `object`. */ - var intersectionWith = baseRest(function(arrays) { - var comparator = last(arrays), - mapped = arrayMap(arrays, castArrayLikeObject); - - comparator = typeof comparator == 'function' ? comparator : undefined; - if (comparator) { - mapped.pop(); - } - return (mapped.length && mapped[0] === arrays[0]) - ? baseIntersection(mapped, undefined, comparator) - : []; - }); + function baseForOwn(object, iteratee) { + return object && baseFor(object, iteratee, keys); + } /** - * Converts all elements in `array` into a string separated by `separator`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to convert. - * @param {string} [separator=','] The element separator. - * @returns {string} Returns the joined string. - * @example + * The base implementation of `_.forOwnRight` without support for iteratee shorthands. * - * _.join(['a', 'b', 'c'], '~'); - * // => 'a~b~c' + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Object} Returns `object`. */ - function join(array, separator) { - return array == null ? '' : nativeJoin.call(array, separator); + function baseForOwnRight(object, iteratee) { + return object && baseForRight(object, iteratee, keys); } /** - * Gets the last element of `array`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to query. - * @returns {*} Returns the last element of `array`. - * @example + * The base implementation of `_.functions` which creates an array of + * `object` function property names filtered from `props`. * - * _.last([1, 2, 3]); - * // => 3 + * @private + * @param {Object} object The object to inspect. + * @param {Array} props The property names to filter. + * @returns {Array} Returns the function names. */ - function last(array) { - var length = array == null ? 0 : array.length; - return length ? array[length - 1] : undefined; + function baseFunctions(object, props) { + return arrayFilter(props, function(key) { + return isFunction(object[key]); + }); } /** - * This method is like `_.indexOf` except that it iterates over elements of - * `array` from right to left. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} [fromIndex=array.length-1] The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - * @example - * - * _.lastIndexOf([1, 2, 1, 2], 2); - * // => 3 + * The base implementation of `_.get` without support for default values. * - * // Search from the `fromIndex`. - * _.lastIndexOf([1, 2, 1, 2], 2, 2); - * // => 1 + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @returns {*} Returns the resolved value. */ - function lastIndexOf(array, value, fromIndex) { - var length = array == null ? 0 : array.length; - if (!length) { - return -1; - } - var index = length; - if (fromIndex !== undefined) { - index = toInteger(fromIndex); - index = index < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1); + function baseGet(object, path) { + path = castPath(path, object); + + var index = 0, + length = path.length; + + while (object != null && index < length) { + object = object[toKey(path[index++])]; } - return value === value - ? strictLastIndexOf(array, value, index) - : baseFindIndex(array, baseIsNaN, index, true); + return (index && index == length) ? object : undefined; } /** - * Gets the element at index `n` of `array`. If `n` is negative, the nth - * element from the end is returned. - * - * @static - * @memberOf _ - * @since 4.11.0 - * @category Array - * @param {Array} array The array to query. - * @param {number} [n=0] The index of the element to return. - * @returns {*} Returns the nth element of `array`. - * @example - * - * var array = ['a', 'b', 'c', 'd']; - * - * _.nth(array, 1); - * // => 'b' + * The base implementation of `getAllKeys` and `getAllKeysIn` which uses + * `keysFunc` and `symbolsFunc` to get the enumerable property names and + * symbols of `object`. * - * _.nth(array, -2); - * // => 'c'; + * @private + * @param {Object} object The object to query. + * @param {Function} keysFunc The function to get the keys of `object`. + * @param {Function} symbolsFunc The function to get the symbols of `object`. + * @returns {Array} Returns the array of property names and symbols. */ - function nth(array, n) { - return (array && array.length) ? baseNth(array, toInteger(n)) : undefined; + function baseGetAllKeys(object, keysFunc, symbolsFunc) { + var result = keysFunc(object); + return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); } /** - * Removes all given values from `array` using - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. - * - * **Note:** Unlike `_.without`, this method mutates `array`. Use `_.remove` - * to remove elements from an array by predicate. - * - * @static - * @memberOf _ - * @since 2.0.0 - * @category Array - * @param {Array} array The array to modify. - * @param {...*} [values] The values to remove. - * @returns {Array} Returns `array`. - * @example - * - * var array = ['a', 'b', 'c', 'a', 'b', 'c']; + * The base implementation of `getTag` without fallbacks for buggy environments. * - * _.pull(array, 'a', 'c'); - * console.log(array); - * // => ['b', 'b'] + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. */ - var pull = baseRest(pullAll); + function baseGetTag(value) { + if (value == null) { + return value === undefined ? undefinedTag : nullTag; + } + return (symToStringTag && symToStringTag in Object(value)) + ? getRawTag(value) + : objectToString(value); + } /** - * This method is like `_.pull` except that it accepts an array of values to remove. - * - * **Note:** Unlike `_.difference`, this method mutates `array`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to modify. - * @param {Array} values The values to remove. - * @returns {Array} Returns `array`. - * @example - * - * var array = ['a', 'b', 'c', 'a', 'b', 'c']; + * The base implementation of `_.gt` which doesn't coerce arguments. * - * _.pullAll(array, ['a', 'c']); - * console.log(array); - * // => ['b', 'b'] + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is greater than `other`, + * else `false`. */ - function pullAll(array, values) { - return (array && array.length && values && values.length) - ? basePullAll(array, values) - : array; + function baseGt(value, other) { + return value > other; } /** - * This method is like `_.pullAll` except that it accepts `iteratee` which is - * invoked for each element of `array` and `values` to generate the criterion - * by which they're compared. The iteratee is invoked with one argument: (value). - * - * **Note:** Unlike `_.differenceBy`, this method mutates `array`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to modify. - * @param {Array} values The values to remove. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {Array} Returns `array`. - * @example - * - * var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }]; + * The base implementation of `_.has` without support for deep paths. * - * _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x'); - * console.log(array); - * // => [{ 'x': 2 }] + * @private + * @param {Object} [object] The object to query. + * @param {Array|string} key The key to check. + * @returns {boolean} Returns `true` if `key` exists, else `false`. */ - function pullAllBy(array, values, iteratee) { - return (array && array.length && values && values.length) - ? basePullAll(array, values, getIteratee(iteratee, 2)) - : array; + function baseHas(object, key) { + return object != null && hasOwnProperty.call(object, key); } /** - * This method is like `_.pullAll` except that it accepts `comparator` which - * is invoked to compare elements of `array` to `values`. The comparator is - * invoked with two arguments: (arrVal, othVal). - * - * **Note:** Unlike `_.differenceWith`, this method mutates `array`. - * - * @static - * @memberOf _ - * @since 4.6.0 - * @category Array - * @param {Array} array The array to modify. - * @param {Array} values The values to remove. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns `array`. - * @example - * - * var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }]; + * The base implementation of `_.hasIn` without support for deep paths. * - * _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual); - * console.log(array); - * // => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }] + * @private + * @param {Object} [object] The object to query. + * @param {Array|string} key The key to check. + * @returns {boolean} Returns `true` if `key` exists, else `false`. */ - function pullAllWith(array, values, comparator) { - return (array && array.length && values && values.length) - ? basePullAll(array, values, undefined, comparator) - : array; + function baseHasIn(object, key) { + return object != null && key in Object(object); } /** - * Removes elements from `array` corresponding to `indexes` and returns an - * array of removed elements. - * - * **Note:** Unlike `_.at`, this method mutates `array`. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to modify. - * @param {...(number|number[])} [indexes] The indexes of elements to remove. - * @returns {Array} Returns the new array of removed elements. - * @example - * - * var array = ['a', 'b', 'c', 'd']; - * var pulled = _.pullAt(array, [1, 3]); - * - * console.log(array); - * // => ['a', 'c'] + * The base implementation of `_.inRange` which doesn't coerce arguments. * - * console.log(pulled); - * // => ['b', 'd'] + * @private + * @param {number} number The number to check. + * @param {number} start The start of the range. + * @param {number} end The end of the range. + * @returns {boolean} Returns `true` if `number` is in the range, else `false`. */ - var pullAt = flatRest(function(array, indexes) { - var length = array == null ? 0 : array.length, - result = baseAt(array, indexes); - - basePullAt(array, arrayMap(indexes, function(index) { - return isIndex(index, length) ? +index : index; - }).sort(compareAscending)); - - return result; - }); + function baseInRange(number, start, end) { + return number >= nativeMin(start, end) && number < nativeMax(start, end); + } /** - * Removes all elements from `array` that `predicate` returns truthy for - * and returns an array of the removed elements. The predicate is invoked - * with three arguments: (value, index, array). - * - * **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull` - * to pull elements from an array by value. - * - * @static - * @memberOf _ - * @since 2.0.0 - * @category Array - * @param {Array} array The array to modify. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the new array of removed elements. - * @example - * - * var array = [1, 2, 3, 4]; - * var evens = _.remove(array, function(n) { - * return n % 2 == 0; - * }); - * - * console.log(array); - * // => [1, 3] + * The base implementation of methods like `_.intersection`, without support + * for iteratee shorthands, that accepts an array of arrays to inspect. * - * console.log(evens); - * // => [2, 4] + * @private + * @param {Array} arrays The arrays to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of shared values. */ - function remove(array, predicate) { - var result = []; - if (!(array && array.length)) { - return result; + function baseIntersection(arrays, iteratee, comparator) { + var includes = comparator ? arrayIncludesWith : arrayIncludes, + length = arrays[0].length, + othLength = arrays.length, + othIndex = othLength, + caches = Array(othLength), + maxLength = Infinity, + result = []; + + while (othIndex--) { + var array = arrays[othIndex]; + if (othIndex && iteratee) { + array = arrayMap(array, baseUnary(iteratee)); + } + maxLength = nativeMin(array.length, maxLength); + caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120)) + ? new SetCache(othIndex && array) + : undefined; } + array = arrays[0]; + var index = -1, - indexes = [], - length = array.length; + seen = caches[0]; - predicate = getIteratee(predicate, 3); - while (++index < length) { - var value = array[index]; - if (predicate(value, index, array)) { + outer: + while (++index < length && result.length < maxLength) { + var value = array[index], + computed = iteratee ? iteratee(value) : value; + + value = (comparator || value !== 0) ? value : 0; + if (!(seen + ? cacheHas(seen, computed) + : includes(result, computed, comparator) + )) { + othIndex = othLength; + while (--othIndex) { + var cache = caches[othIndex]; + if (!(cache + ? cacheHas(cache, computed) + : includes(arrays[othIndex], computed, comparator)) + ) { + continue outer; + } + } + if (seen) { + seen.push(computed); + } result.push(value); - indexes.push(index); } } - basePullAt(array, indexes); return result; } /** - * Reverses `array` so that the first element becomes the last, the second - * element becomes the second to last, and so on. - * - * **Note:** This method mutates `array` and is based on - * [`Array#reverse`](https://mdn.io/Array/reverse). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to modify. - * @returns {Array} Returns `array`. - * @example - * - * var array = [1, 2, 3]; - * - * _.reverse(array); - * // => [3, 2, 1] + * The base implementation of `_.invert` and `_.invertBy` which inverts + * `object` with values transformed by `iteratee` and set by `setter`. * - * console.log(array); - * // => [3, 2, 1] + * @private + * @param {Object} object The object to iterate over. + * @param {Function} setter The function to set `accumulator` values. + * @param {Function} iteratee The iteratee to transform values. + * @param {Object} accumulator The initial inverted object. + * @returns {Function} Returns `accumulator`. */ - function reverse(array) { - return array == null ? array : nativeReverse.call(array); + function baseInverter(object, setter, iteratee, accumulator) { + baseForOwn(object, function(value, key, object) { + setter(accumulator, iteratee(value), key, object); + }); + return accumulator; } /** - * Creates a slice of `array` from `start` up to, but not including, `end`. - * - * **Note:** This method is used instead of - * [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are - * returned. + * The base implementation of `_.invoke` without support for individual + * method arguments. * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to slice. - * @param {number} [start=0] The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns the slice of `array`. + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path of the method to invoke. + * @param {Array} args The arguments to invoke the method with. + * @returns {*} Returns the result of the invoked method. */ - function slice(array, start, end) { - var length = array == null ? 0 : array.length; - if (!length) { - return []; - } - if (end && typeof end != 'number' && isIterateeCall(array, start, end)) { - start = 0; - end = length; - } - else { - start = start == null ? 0 : toInteger(start); - end = end === undefined ? length : toInteger(end); - } - return baseSlice(array, start, end); + function baseInvoke(object, path, args) { + path = castPath(path, object); + object = parent(object, path); + var func = object == null ? object : object[toKey(last(path))]; + return func == null ? undefined : apply(func, object, args); } /** - * Uses a binary search to determine the lowest index at which `value` - * should be inserted into `array` in order to maintain its sort order. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The sorted array to inspect. - * @param {*} value The value to evaluate. - * @returns {number} Returns the index at which `value` should be inserted - * into `array`. - * @example + * The base implementation of `_.isArguments`. * - * _.sortedIndex([30, 50], 40); - * // => 1 + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, */ - function sortedIndex(array, value) { - return baseSortedIndex(array, value); + function baseIsArguments(value) { + return isObjectLike(value) && baseGetTag(value) == argsTag; } /** - * This method is like `_.sortedIndex` except that it accepts `iteratee` - * which is invoked for `value` and each element of `array` to compute their - * sort ranking. The iteratee is invoked with one argument: (value). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The sorted array to inspect. - * @param {*} value The value to evaluate. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {number} Returns the index at which `value` should be inserted - * into `array`. - * @example - * - * var objects = [{ 'x': 4 }, { 'x': 5 }]; - * - * _.sortedIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); - * // => 0 + * The base implementation of `_.isArrayBuffer` without Node.js optimizations. * - * // The `_.property` iteratee shorthand. - * _.sortedIndexBy(objects, { 'x': 4 }, 'x'); - * // => 0 + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. */ - function sortedIndexBy(array, value, iteratee) { - return baseSortedIndexBy(array, value, getIteratee(iteratee, 2)); + function baseIsArrayBuffer(value) { + return isObjectLike(value) && baseGetTag(value) == arrayBufferTag; } /** - * This method is like `_.indexOf` except that it performs a binary - * search on a sorted `array`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @returns {number} Returns the index of the matched value, else `-1`. - * @example + * The base implementation of `_.isDate` without Node.js optimizations. * - * _.sortedIndexOf([4, 5, 5, 5, 6], 5); - * // => 1 + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a date object, else `false`. */ - function sortedIndexOf(array, value) { - var length = array == null ? 0 : array.length; - if (length) { - var index = baseSortedIndex(array, value); - if (index < length && eq(array[index], value)) { - return index; - } - } - return -1; + function baseIsDate(value) { + return isObjectLike(value) && baseGetTag(value) == dateTag; } /** - * This method is like `_.sortedIndex` except that it returns the highest - * index at which `value` should be inserted into `array` in order to - * maintain its sort order. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The sorted array to inspect. - * @param {*} value The value to evaluate. - * @returns {number} Returns the index at which `value` should be inserted - * into `array`. - * @example + * The base implementation of `_.isEqual` which supports partial comparisons + * and tracks traversed objects. * - * _.sortedLastIndex([4, 5, 5, 5, 6], 5); - * // => 4 + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @param {boolean} bitmask The bitmask flags. + * 1 - Unordered comparison + * 2 - Partial comparison + * @param {Function} [customizer] The function to customize comparisons. + * @param {Object} [stack] Tracks traversed `value` and `other` objects. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. */ - function sortedLastIndex(array, value) { - return baseSortedIndex(array, value, true); + function baseIsEqual(value, other, bitmask, customizer, stack) { + if (value === other) { + return true; + } + if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) { + return value !== value && other !== other; + } + return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); } /** - * This method is like `_.sortedLastIndex` except that it accepts `iteratee` - * which is invoked for `value` and each element of `array` to compute their - * sort ranking. The iteratee is invoked with one argument: (value). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The sorted array to inspect. - * @param {*} value The value to evaluate. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {number} Returns the index at which `value` should be inserted - * into `array`. - * @example - * - * var objects = [{ 'x': 4 }, { 'x': 5 }]; - * - * _.sortedLastIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); - * // => 1 + * A specialized version of `baseIsEqual` for arrays and objects which performs + * deep comparisons and tracks traversed objects enabling objects with circular + * references to be compared. * - * // The `_.property` iteratee shorthand. - * _.sortedLastIndexBy(objects, { 'x': 4 }, 'x'); - * // => 1 + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} [stack] Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ - function sortedLastIndexBy(array, value, iteratee) { - return baseSortedIndexBy(array, value, getIteratee(iteratee, 2), true); + function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { + var objIsArr = isArray(object), + othIsArr = isArray(other), + objTag = objIsArr ? arrayTag : getTag(object), + othTag = othIsArr ? arrayTag : getTag(other); + + objTag = objTag == argsTag ? objectTag : objTag; + othTag = othTag == argsTag ? objectTag : othTag; + + var objIsObj = objTag == objectTag, + othIsObj = othTag == objectTag, + isSameTag = objTag == othTag; + + if (isSameTag && isBuffer(object)) { + if (!isBuffer(other)) { + return false; + } + objIsArr = true; + objIsObj = false; + } + if (isSameTag && !objIsObj) { + stack || (stack = new Stack); + return (objIsArr || isTypedArray(object)) + ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) + : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); + } + if (!(bitmask & COMPARE_PARTIAL_FLAG)) { + var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), + othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); + + if (objIsWrapped || othIsWrapped) { + var objUnwrapped = objIsWrapped ? object.value() : object, + othUnwrapped = othIsWrapped ? other.value() : other; + + stack || (stack = new Stack); + return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); + } + } + if (!isSameTag) { + return false; + } + stack || (stack = new Stack); + return equalObjects(object, other, bitmask, customizer, equalFunc, stack); } /** - * This method is like `_.lastIndexOf` except that it performs a binary - * search on a sorted `array`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @returns {number} Returns the index of the matched value, else `-1`. - * @example + * The base implementation of `_.isMap` without Node.js optimizations. * - * _.sortedLastIndexOf([4, 5, 5, 5, 6], 5); - * // => 3 + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a map, else `false`. */ - function sortedLastIndexOf(array, value) { - var length = array == null ? 0 : array.length; - if (length) { - var index = baseSortedIndex(array, value, true) - 1; - if (eq(array[index], value)) { - return index; - } - } - return -1; + function baseIsMap(value) { + return isObjectLike(value) && getTag(value) == mapTag; } /** - * This method is like `_.uniq` except that it's designed and optimized - * for sorted arrays. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @returns {Array} Returns the new duplicate free array. - * @example + * The base implementation of `_.isMatch` without support for iteratee shorthands. * - * _.sortedUniq([1, 1, 2]); - * // => [1, 2] + * @private + * @param {Object} object The object to inspect. + * @param {Object} source The object of property values to match. + * @param {Array} matchData The property names, values, and compare flags to match. + * @param {Function} [customizer] The function to customize comparisons. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. */ - function sortedUniq(array) { - return (array && array.length) - ? baseSortedUniq(array) - : []; + function baseIsMatch(object, source, matchData, customizer) { + var index = matchData.length, + length = index, + noCustomizer = !customizer; + + if (object == null) { + return !length; + } + object = Object(object); + while (index--) { + var data = matchData[index]; + if ((noCustomizer && data[2]) + ? data[1] !== object[data[0]] + : !(data[0] in object) + ) { + return false; + } + } + while (++index < length) { + data = matchData[index]; + var key = data[0], + objValue = object[key], + srcValue = data[1]; + + if (noCustomizer && data[2]) { + if (objValue === undefined && !(key in object)) { + return false; + } + } else { + var stack = new Stack; + if (customizer) { + var result = customizer(objValue, srcValue, key, object, source, stack); + } + if (!(result === undefined + ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack) + : result + )) { + return false; + } + } + } + return true; } /** - * This method is like `_.uniqBy` except that it's designed and optimized - * for sorted arrays. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {Function} [iteratee] The iteratee invoked per element. - * @returns {Array} Returns the new duplicate free array. - * @example + * The base implementation of `_.isNative` without bad shim checks. * - * _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor); - * // => [1.1, 2.3] + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, + * else `false`. */ - function sortedUniqBy(array, iteratee) { - return (array && array.length) - ? baseSortedUniq(array, getIteratee(iteratee, 2)) - : []; + function baseIsNative(value) { + if (!isObject(value) || isMasked(value)) { + return false; + } + var pattern = isFunction(value) ? reIsNative : reIsHostCtor; + return pattern.test(toSource(value)); } /** - * Gets all but the first element of `array`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to query. - * @returns {Array} Returns the slice of `array`. - * @example + * The base implementation of `_.isRegExp` without Node.js optimizations. * - * _.tail([1, 2, 3]); - * // => [2, 3] + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. */ - function tail(array) { - var length = array == null ? 0 : array.length; - return length ? baseSlice(array, 1, length) : []; + function baseIsRegExp(value) { + return isObjectLike(value) && baseGetTag(value) == regexpTag; } /** - * Creates a slice of `array` with `n` elements taken from the beginning. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to query. - * @param {number} [n=1] The number of elements to take. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Array} Returns the slice of `array`. - * @example - * - * _.take([1, 2, 3]); - * // => [1] - * - * _.take([1, 2, 3], 2); - * // => [1, 2] - * - * _.take([1, 2, 3], 5); - * // => [1, 2, 3] + * The base implementation of `_.isSet` without Node.js optimizations. * - * _.take([1, 2, 3], 0); - * // => [] + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a set, else `false`. */ - function take(array, n, guard) { - if (!(array && array.length)) { - return []; - } - n = (guard || n === undefined) ? 1 : toInteger(n); - return baseSlice(array, 0, n < 0 ? 0 : n); + function baseIsSet(value) { + return isObjectLike(value) && getTag(value) == setTag; } /** - * Creates a slice of `array` with `n` elements taken from the end. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to query. - * @param {number} [n=1] The number of elements to take. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Array} Returns the slice of `array`. - * @example - * - * _.takeRight([1, 2, 3]); - * // => [3] - * - * _.takeRight([1, 2, 3], 2); - * // => [2, 3] - * - * _.takeRight([1, 2, 3], 5); - * // => [1, 2, 3] + * The base implementation of `_.isTypedArray` without Node.js optimizations. * - * _.takeRight([1, 2, 3], 0); - * // => [] + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. */ - function takeRight(array, n, guard) { - var length = array == null ? 0 : array.length; - if (!length) { - return []; - } - n = (guard || n === undefined) ? 1 : toInteger(n); - n = length - n; - return baseSlice(array, n < 0 ? 0 : n, length); + function baseIsTypedArray(value) { + return isObjectLike(value) && + isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; } /** - * Creates a slice of `array` with elements taken from the end. Elements are - * taken until `predicate` returns falsey. The predicate is invoked with - * three arguments: (value, index, array). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to query. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the slice of `array`. - * @example - * - * var users = [ - * { 'user': 'barney', 'active': true }, - * { 'user': 'fred', 'active': false }, - * { 'user': 'pebbles', 'active': false } - * ]; - * - * _.takeRightWhile(users, function(o) { return !o.active; }); - * // => objects for ['fred', 'pebbles'] - * - * // The `_.matches` iteratee shorthand. - * _.takeRightWhile(users, { 'user': 'pebbles', 'active': false }); - * // => objects for ['pebbles'] - * - * // The `_.matchesProperty` iteratee shorthand. - * _.takeRightWhile(users, ['active', false]); - * // => objects for ['fred', 'pebbles'] + * The base implementation of `_.iteratee`. * - * // The `_.property` iteratee shorthand. - * _.takeRightWhile(users, 'active'); - * // => [] + * @private + * @param {*} [value=_.identity] The value to convert to an iteratee. + * @returns {Function} Returns the iteratee. */ - function takeRightWhile(array, predicate) { - return (array && array.length) - ? baseWhile(array, getIteratee(predicate, 3), false, true) - : []; + function baseIteratee(value) { + // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. + // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. + if (typeof value == 'function') { + return value; + } + if (value == null) { + return identity; + } + if (typeof value == 'object') { + return isArray(value) + ? baseMatchesProperty(value[0], value[1]) + : baseMatches(value); + } + return property(value); } /** - * Creates a slice of `array` with elements taken from the beginning. Elements - * are taken until `predicate` returns falsey. The predicate is invoked with - * three arguments: (value, index, array). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to query. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the slice of `array`. - * @example - * - * var users = [ - * { 'user': 'barney', 'active': false }, - * { 'user': 'fred', 'active': false }, - * { 'user': 'pebbles', 'active': true } - * ]; - * - * _.takeWhile(users, function(o) { return !o.active; }); - * // => objects for ['barney', 'fred'] - * - * // The `_.matches` iteratee shorthand. - * _.takeWhile(users, { 'user': 'barney', 'active': false }); - * // => objects for ['barney'] - * - * // The `_.matchesProperty` iteratee shorthand. - * _.takeWhile(users, ['active', false]); - * // => objects for ['barney', 'fred'] + * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. * - * // The `_.property` iteratee shorthand. - * _.takeWhile(users, 'active'); - * // => [] + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. */ - function takeWhile(array, predicate) { - return (array && array.length) - ? baseWhile(array, getIteratee(predicate, 3)) - : []; + function baseKeys(object) { + if (!isPrototype(object)) { + return nativeKeys(object); + } + var result = []; + for (var key in Object(object)) { + if (hasOwnProperty.call(object, key) && key != 'constructor') { + result.push(key); + } + } + return result; } /** - * Creates an array of unique values, in order, from all given arrays using - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @returns {Array} Returns the new array of combined values. - * @example + * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. * - * _.union([2], [1, 2]); - * // => [2, 1] + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. */ - var union = baseRest(function(arrays) { - return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true)); - }); + function baseKeysIn(object) { + if (!isObject(object)) { + return nativeKeysIn(object); + } + var isProto = isPrototype(object), + result = []; + + for (var key in object) { + if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { + result.push(key); + } + } + return result; + } /** - * This method is like `_.union` except that it accepts `iteratee` which is - * invoked for each element of each `arrays` to generate the criterion by - * which uniqueness is computed. Result values are chosen from the first - * array in which the value occurs. The iteratee is invoked with one argument: - * (value). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {Array} Returns the new array of combined values. - * @example - * - * _.unionBy([2.1], [1.2, 2.3], Math.floor); - * // => [2.1, 1.2] + * The base implementation of `_.lt` which doesn't coerce arguments. * - * // The `_.property` iteratee shorthand. - * _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); - * // => [{ 'x': 1 }, { 'x': 2 }] + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is less than `other`, + * else `false`. */ - var unionBy = baseRest(function(arrays) { - var iteratee = last(arrays); - if (isArrayLikeObject(iteratee)) { - iteratee = undefined; - } - return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)); - }); + function baseLt(value, other) { + return value < other; + } /** - * This method is like `_.union` except that it accepts `comparator` which - * is invoked to compare elements of `arrays`. Result values are chosen from - * the first array in which the value occurs. The comparator is invoked - * with two arguments: (arrVal, othVal). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of combined values. - * @example - * - * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; - * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * The base implementation of `_.map` without support for iteratee shorthands. * - * _.unionWith(objects, others, _.isEqual); - * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. */ - var unionWith = baseRest(function(arrays) { - var comparator = last(arrays); - comparator = typeof comparator == 'function' ? comparator : undefined; - return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), undefined, comparator); - }); + function baseMap(collection, iteratee) { + var index = -1, + result = isArrayLike(collection) ? Array(collection.length) : []; + + baseEach(collection, function(value, key, collection) { + result[++index] = iteratee(value, key, collection); + }); + return result; + } /** - * Creates a duplicate-free version of an array, using - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons, in which only the first occurrence of each element - * is kept. The order of result values is determined by the order they occur - * in the array. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to inspect. - * @returns {Array} Returns the new duplicate free array. - * @example + * The base implementation of `_.matches` which doesn't clone `source`. * - * _.uniq([2, 1, 2]); - * // => [2, 1] + * @private + * @param {Object} source The object of property values to match. + * @returns {Function} Returns the new spec function. */ - function uniq(array) { - return (array && array.length) ? baseUniq(array) : []; + function baseMatches(source) { + var matchData = getMatchData(source); + if (matchData.length == 1 && matchData[0][2]) { + return matchesStrictComparable(matchData[0][0], matchData[0][1]); + } + return function(object) { + return object === source || baseIsMatch(object, source, matchData); + }; } /** - * This method is like `_.uniq` except that it accepts `iteratee` which is - * invoked for each element in `array` to generate the criterion by which - * uniqueness is computed. The order of result values is determined by the - * order they occur in the array. The iteratee is invoked with one argument: - * (value). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {Array} Returns the new duplicate free array. - * @example - * - * _.uniqBy([2.1, 1.2, 2.3], Math.floor); - * // => [2.1, 1.2] + * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. * - * // The `_.property` iteratee shorthand. - * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); - * // => [{ 'x': 1 }, { 'x': 2 }] + * @private + * @param {string} path The path of the property to get. + * @param {*} srcValue The value to match. + * @returns {Function} Returns the new spec function. */ - function uniqBy(array, iteratee) { - return (array && array.length) ? baseUniq(array, getIteratee(iteratee, 2)) : []; + function baseMatchesProperty(path, srcValue) { + if (isKey(path) && isStrictComparable(srcValue)) { + return matchesStrictComparable(toKey(path), srcValue); + } + return function(object) { + var objValue = get(object, path); + return (objValue === undefined && objValue === srcValue) + ? hasIn(object, path) + : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG); + }; } /** - * This method is like `_.uniq` except that it accepts `comparator` which - * is invoked to compare elements of `array`. The order of result values is - * determined by the order they occur in the array.The comparator is invoked - * with two arguments: (arrVal, othVal). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new duplicate free array. - * @example - * - * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * The base implementation of `_.merge` without support for multiple sources. * - * _.uniqWith(objects, _.isEqual); - * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }] + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @param {number} srcIndex The index of `source`. + * @param {Function} [customizer] The function to customize merged values. + * @param {Object} [stack] Tracks traversed source values and their merged + * counterparts. */ - function uniqWith(array, comparator) { - comparator = typeof comparator == 'function' ? comparator : undefined; - return (array && array.length) ? baseUniq(array, undefined, comparator) : []; + function baseMerge(object, source, srcIndex, customizer, stack) { + if (object === source) { + return; + } + baseFor(source, function(srcValue, key) { + stack || (stack = new Stack); + if (isObject(srcValue)) { + baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); + } + else { + var newValue = customizer + ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack) + : undefined; + + if (newValue === undefined) { + newValue = srcValue; + } + assignMergeValue(object, key, newValue); + } + }, keysIn); } /** - * This method is like `_.zip` except that it accepts an array of grouped - * elements and creates an array regrouping the elements to their pre-zip - * configuration. - * - * @static - * @memberOf _ - * @since 1.2.0 - * @category Array - * @param {Array} array The array of grouped elements to process. - * @returns {Array} Returns the new array of regrouped elements. - * @example - * - * var zipped = _.zip(['a', 'b'], [1, 2], [true, false]); - * // => [['a', 1, true], ['b', 2, false]] + * A specialized version of `baseMerge` for arrays and objects which performs + * deep merges and tracks traversed objects enabling objects with circular + * references to be merged. * - * _.unzip(zipped); - * // => [['a', 'b'], [1, 2], [true, false]] + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @param {string} key The key of the value to merge. + * @param {number} srcIndex The index of `source`. + * @param {Function} mergeFunc The function to merge values. + * @param {Function} [customizer] The function to customize assigned values. + * @param {Object} [stack] Tracks traversed source values and their merged + * counterparts. */ - function unzip(array) { - if (!(array && array.length)) { - return []; + function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { + var objValue = safeGet(object, key), + srcValue = safeGet(source, key), + stacked = stack.get(srcValue); + + if (stacked) { + assignMergeValue(object, key, stacked); + return; } - var length = 0; - array = arrayFilter(array, function(group) { - if (isArrayLikeObject(group)) { - length = nativeMax(group.length, length); - return true; + var newValue = customizer + ? customizer(objValue, srcValue, (key + ''), object, source, stack) + : undefined; + + var isCommon = newValue === undefined; + + if (isCommon) { + var isArr = isArray(srcValue), + isBuff = !isArr && isBuffer(srcValue), + isTyped = !isArr && !isBuff && isTypedArray(srcValue); + + newValue = srcValue; + if (isArr || isBuff || isTyped) { + if (isArray(objValue)) { + newValue = objValue; + } + else if (isArrayLikeObject(objValue)) { + newValue = copyArray(objValue); + } + else if (isBuff) { + isCommon = false; + newValue = cloneBuffer(srcValue, true); + } + else if (isTyped) { + isCommon = false; + newValue = cloneTypedArray(srcValue, true); + } + else { + newValue = []; + } } - }); - return baseTimes(length, function(index) { - return arrayMap(array, baseProperty(index)); - }); + else if (isPlainObject(srcValue) || isArguments(srcValue)) { + newValue = objValue; + if (isArguments(objValue)) { + newValue = toPlainObject(objValue); + } + else if (!isObject(objValue) || isFunction(objValue)) { + newValue = initCloneObject(srcValue); + } + } + else { + isCommon = false; + } + } + if (isCommon) { + // Recursively merge objects and arrays (susceptible to call stack limits). + stack.set(srcValue, newValue); + mergeFunc(newValue, srcValue, srcIndex, customizer, stack); + stack['delete'](srcValue); + } + assignMergeValue(object, key, newValue); } /** - * This method is like `_.unzip` except that it accepts `iteratee` to specify - * how regrouped values should be combined. The iteratee is invoked with the - * elements of each group: (...group). - * - * @static - * @memberOf _ - * @since 3.8.0 - * @category Array - * @param {Array} array The array of grouped elements to process. - * @param {Function} [iteratee=_.identity] The function to combine - * regrouped values. - * @returns {Array} Returns the new array of regrouped elements. - * @example - * - * var zipped = _.zip([1, 2], [10, 20], [100, 200]); - * // => [[1, 10, 100], [2, 20, 200]] + * The base implementation of `_.nth` which doesn't coerce arguments. * - * _.unzipWith(zipped, _.add); - * // => [3, 30, 300] + * @private + * @param {Array} array The array to query. + * @param {number} n The index of the element to return. + * @returns {*} Returns the nth element of `array`. */ - function unzipWith(array, iteratee) { - if (!(array && array.length)) { - return []; - } - var result = unzip(array); - if (iteratee == null) { - return result; + function baseNth(array, n) { + var length = array.length; + if (!length) { + return; } - return arrayMap(result, function(group) { - return apply(iteratee, undefined, group); - }); + n += n < 0 ? length : 0; + return isIndex(n, length) ? array[n] : undefined; } /** - * Creates an array excluding all given values using - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. - * - * **Note:** Unlike `_.pull`, this method returns a new array. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {...*} [values] The values to exclude. - * @returns {Array} Returns the new array of filtered values. - * @see _.difference, _.xor - * @example + * The base implementation of `_.orderBy` without param guards. * - * _.without([2, 1, 2, 3], 1, 2); - * // => [3] + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by. + * @param {string[]} orders The sort orders of `iteratees`. + * @returns {Array} Returns the new sorted array. */ - var without = baseRest(function(array, values) { - return isArrayLikeObject(array) - ? baseDifference(array, values) - : []; - }); + function baseOrderBy(collection, iteratees, orders) { + if (iteratees.length) { + iteratees = arrayMap(iteratees, function(iteratee) { + if (isArray(iteratee)) { + return function(value) { + return baseGet(value, iteratee.length === 1 ? iteratee[0] : iteratee); + } + } + return iteratee; + }); + } else { + iteratees = [identity]; + } - /** - * Creates an array of unique values that is the - * [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference) - * of the given arrays. The order of result values is determined by the order - * they occur in the arrays. - * - * @static - * @memberOf _ - * @since 2.4.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @returns {Array} Returns the new array of filtered values. - * @see _.difference, _.without - * @example - * - * _.xor([2, 1], [2, 3]); - * // => [1, 3] - */ - var xor = baseRest(function(arrays) { - return baseXor(arrayFilter(arrays, isArrayLikeObject)); - }); + var index = -1; + iteratees = arrayMap(iteratees, baseUnary(getIteratee())); - /** - * This method is like `_.xor` except that it accepts `iteratee` which is - * invoked for each element of each `arrays` to generate the criterion by - * which by which they're compared. The order of result values is determined - * by the order they occur in the arrays. The iteratee is invoked with one - * argument: (value). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {Array} Returns the new array of filtered values. - * @example - * - * _.xorBy([2.1, 1.2], [2.3, 3.4], Math.floor); - * // => [1.2, 3.4] - * - * // The `_.property` iteratee shorthand. - * _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); - * // => [{ 'x': 2 }] - */ - var xorBy = baseRest(function(arrays) { - var iteratee = last(arrays); - if (isArrayLikeObject(iteratee)) { - iteratee = undefined; - } - return baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee, 2)); - }); + var result = baseMap(collection, function(value, key, collection) { + var criteria = arrayMap(iteratees, function(iteratee) { + return iteratee(value); + }); + return { 'criteria': criteria, 'index': ++index, 'value': value }; + }); - /** - * This method is like `_.xor` except that it accepts `comparator` which is - * invoked to compare elements of `arrays`. The order of result values is - * determined by the order they occur in the arrays. The comparator is invoked - * with two arguments: (arrVal, othVal). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of filtered values. - * @example - * - * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; - * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; - * - * _.xorWith(objects, others, _.isEqual); - * // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] - */ - var xorWith = baseRest(function(arrays) { - var comparator = last(arrays); - comparator = typeof comparator == 'function' ? comparator : undefined; - return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined, comparator); - }); + return baseSortBy(result, function(object, other) { + return compareMultiple(object, other, orders); + }); + } /** - * Creates an array of grouped elements, the first of which contains the - * first elements of the given arrays, the second of which contains the - * second elements of the given arrays, and so on. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {...Array} [arrays] The arrays to process. - * @returns {Array} Returns the new array of grouped elements. - * @example + * The base implementation of `_.pick` without support for individual + * property identifiers. * - * _.zip(['a', 'b'], [1, 2], [true, false]); - * // => [['a', 1, true], ['b', 2, false]] + * @private + * @param {Object} object The source object. + * @param {string[]} paths The property paths to pick. + * @returns {Object} Returns the new object. */ - var zip = baseRest(unzip); + function basePick(object, paths) { + return basePickBy(object, paths, function(value, path) { + return hasIn(object, path); + }); + } /** - * This method is like `_.fromPairs` except that it accepts two arrays, - * one of property identifiers and one of corresponding values. + * The base implementation of `_.pickBy` without support for iteratee shorthands. * - * @static - * @memberOf _ - * @since 0.4.0 - * @category Array - * @param {Array} [props=[]] The property identifiers. - * @param {Array} [values=[]] The property values. + * @private + * @param {Object} object The source object. + * @param {string[]} paths The property paths to pick. + * @param {Function} predicate The function invoked per property. * @returns {Object} Returns the new object. - * @example - * - * _.zipObject(['a', 'b'], [1, 2]); - * // => { 'a': 1, 'b': 2 } */ - function zipObject(props, values) { - return baseZipObject(props || [], values || [], assignValue); + function basePickBy(object, paths, predicate) { + var index = -1, + length = paths.length, + result = {}; + + while (++index < length) { + var path = paths[index], + value = baseGet(object, path); + + if (predicate(value, path)) { + baseSet(result, castPath(path, object), value); + } + } + return result; } /** - * This method is like `_.zipObject` except that it supports property paths. - * - * @static - * @memberOf _ - * @since 4.1.0 - * @category Array - * @param {Array} [props=[]] The property identifiers. - * @param {Array} [values=[]] The property values. - * @returns {Object} Returns the new object. - * @example + * A specialized version of `baseProperty` which supports deep paths. * - * _.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]); - * // => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } } + * @private + * @param {Array|string} path The path of the property to get. + * @returns {Function} Returns the new accessor function. */ - function zipObjectDeep(props, values) { - return baseZipObject(props || [], values || [], baseSet); + function basePropertyDeep(path) { + return function(object) { + return baseGet(object, path); + }; } /** - * This method is like `_.zip` except that it accepts `iteratee` to specify - * how grouped values should be combined. The iteratee is invoked with the - * elements of each group: (...group). - * - * @static - * @memberOf _ - * @since 3.8.0 - * @category Array - * @param {...Array} [arrays] The arrays to process. - * @param {Function} [iteratee=_.identity] The function to combine - * grouped values. - * @returns {Array} Returns the new array of grouped elements. - * @example + * The base implementation of `_.pullAllBy` without support for iteratee + * shorthands. * - * _.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) { - * return a + b + c; - * }); - * // => [111, 222] + * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns `array`. */ - var zipWith = baseRest(function(arrays) { - var length = arrays.length, - iteratee = length > 1 ? arrays[length - 1] : undefined; - - iteratee = typeof iteratee == 'function' ? (arrays.pop(), iteratee) : undefined; - return unzipWith(arrays, iteratee); - }); + function basePullAll(array, values, iteratee, comparator) { + var indexOf = comparator ? baseIndexOfWith : baseIndexOf, + index = -1, + length = values.length, + seen = array; - /*------------------------------------------------------------------------*/ + if (array === values) { + values = copyArray(values); + } + if (iteratee) { + seen = arrayMap(array, baseUnary(iteratee)); + } + while (++index < length) { + var fromIndex = 0, + value = values[index], + computed = iteratee ? iteratee(value) : value; - /** - * Creates a `lodash` wrapper instance that wraps `value` with explicit method - * chain sequences enabled. The result of such sequences must be unwrapped - * with `_#value`. - * - * @static - * @memberOf _ - * @since 1.3.0 - * @category Seq - * @param {*} value The value to wrap. - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example - * - * var users = [ - * { 'user': 'barney', 'age': 36 }, - * { 'user': 'fred', 'age': 40 }, - * { 'user': 'pebbles', 'age': 1 } - * ]; - * - * var youngest = _ - * .chain(users) - * .sortBy('age') - * .map(function(o) { - * return o.user + ' is ' + o.age; - * }) - * .head() - * .value(); - * // => 'pebbles is 1' - */ - function chain(value) { - var result = lodash(value); - result.__chain__ = true; - return result; + while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) { + if (seen !== array) { + splice.call(seen, fromIndex, 1); + } + splice.call(array, fromIndex, 1); + } + } + return array; } /** - * This method invokes `interceptor` and returns `value`. The interceptor - * is invoked with one argument; (value). The purpose of this method is to - * "tap into" a method chain sequence in order to modify intermediate results. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Seq - * @param {*} value The value to provide to `interceptor`. - * @param {Function} interceptor The function to invoke. - * @returns {*} Returns `value`. - * @example + * The base implementation of `_.pullAt` without support for individual + * indexes or capturing the removed elements. * - * _([1, 2, 3]) - * .tap(function(array) { - * // Mutate input array. - * array.pop(); - * }) - * .reverse() - * .value(); - * // => [2, 1] + * @private + * @param {Array} array The array to modify. + * @param {number[]} indexes The indexes of elements to remove. + * @returns {Array} Returns `array`. */ - function tap(value, interceptor) { - interceptor(value); - return value; + function basePullAt(array, indexes) { + var length = array ? indexes.length : 0, + lastIndex = length - 1; + + while (length--) { + var index = indexes[length]; + if (length == lastIndex || index !== previous) { + var previous = index; + if (isIndex(index)) { + splice.call(array, index, 1); + } else { + baseUnset(array, index); + } + } + } + return array; } /** - * This method is like `_.tap` except that it returns the result of `interceptor`. - * The purpose of this method is to "pass thru" values replacing intermediate - * results in a method chain sequence. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Seq - * @param {*} value The value to provide to `interceptor`. - * @param {Function} interceptor The function to invoke. - * @returns {*} Returns the result of `interceptor`. - * @example + * The base implementation of `_.random` without support for returning + * floating-point numbers. * - * _(' abc ') - * .chain() - * .trim() - * .thru(function(value) { - * return [value]; - * }) - * .value(); - * // => ['abc'] + * @private + * @param {number} lower The lower bound. + * @param {number} upper The upper bound. + * @returns {number} Returns the random number. */ - function thru(value, interceptor) { - return interceptor(value); + function baseRandom(lower, upper) { + return lower + nativeFloor(nativeRandom() * (upper - lower + 1)); } /** - * This method is the wrapper version of `_.at`. - * - * @name at - * @memberOf _ - * @since 1.0.0 - * @category Seq - * @param {...(string|string[])} [paths] The property paths to pick. - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example - * - * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; + * The base implementation of `_.range` and `_.rangeRight` which doesn't + * coerce arguments. * - * _(object).at(['a[0].b.c', 'a[1]']).value(); - * // => [3, 4] + * @private + * @param {number} start The start of the range. + * @param {number} end The end of the range. + * @param {number} step The value to increment or decrement by. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Array} Returns the range of numbers. */ - var wrapperAt = flatRest(function(paths) { - var length = paths.length, - start = length ? paths[0] : 0, - value = this.__wrapped__, - interceptor = function(object) { return baseAt(object, paths); }; + function baseRange(start, end, step, fromRight) { + var index = -1, + length = nativeMax(nativeCeil((end - start) / (step || 1)), 0), + result = Array(length); - if (length > 1 || this.__actions__.length || - !(value instanceof LazyWrapper) || !isIndex(start)) { - return this.thru(interceptor); + while (length--) { + result[fromRight ? length : ++index] = start; + start += step; } - value = value.slice(start, +start + (length ? 1 : 0)); - value.__actions__.push({ - 'func': thru, - 'args': [interceptor], - 'thisArg': undefined - }); - return new LodashWrapper(value, this.__chain__).thru(function(array) { - if (length && !array.length) { - array.push(undefined); - } - return array; - }); - }); + return result; + } /** - * Creates a `lodash` wrapper instance with explicit method chain sequences enabled. - * - * @name chain - * @memberOf _ - * @since 0.1.0 - * @category Seq - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example - * - * var users = [ - * { 'user': 'barney', 'age': 36 }, - * { 'user': 'fred', 'age': 40 } - * ]; - * - * // A sequence without explicit chaining. - * _(users).head(); - * // => { 'user': 'barney', 'age': 36 } + * The base implementation of `_.repeat` which doesn't coerce arguments. * - * // A sequence with explicit chaining. - * _(users) - * .chain() - * .head() - * .pick('user') - * .value(); - * // => { 'user': 'barney' } + * @private + * @param {string} string The string to repeat. + * @param {number} n The number of times to repeat the string. + * @returns {string} Returns the repeated string. */ - function wrapperChain() { - return chain(this); + function baseRepeat(string, n) { + var result = ''; + if (!string || n < 1 || n > MAX_SAFE_INTEGER) { + return result; + } + // Leverage the exponentiation by squaring algorithm for a faster repeat. + // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details. + do { + if (n % 2) { + result += string; + } + n = nativeFloor(n / 2); + if (n) { + string += string; + } + } while (n); + + return result; } /** - * Executes the chain sequence and returns the wrapped result. - * - * @name commit - * @memberOf _ - * @since 3.2.0 - * @category Seq - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example - * - * var array = [1, 2]; - * var wrapped = _(array).push(3); - * - * console.log(array); - * // => [1, 2] - * - * wrapped = wrapped.commit(); - * console.log(array); - * // => [1, 2, 3] - * - * wrapped.last(); - * // => 3 + * The base implementation of `_.rest` which doesn't validate or coerce arguments. * - * console.log(array); - * // => [1, 2, 3] + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. */ - function wrapperCommit() { - return new LodashWrapper(this.value(), this.__chain__); + function baseRest(func, start) { + return setToString(overRest(func, start, identity), func + ''); } /** - * Gets the next value on a wrapped object following the - * [iterator protocol](https://mdn.io/iteration_protocols#iterator). - * - * @name next - * @memberOf _ - * @since 4.0.0 - * @category Seq - * @returns {Object} Returns the next iterator value. - * @example - * - * var wrapped = _([1, 2]); - * - * wrapped.next(); - * // => { 'done': false, 'value': 1 } - * - * wrapped.next(); - * // => { 'done': false, 'value': 2 } + * The base implementation of `_.sample`. * - * wrapped.next(); - * // => { 'done': true, 'value': undefined } + * @private + * @param {Array|Object} collection The collection to sample. + * @returns {*} Returns the random element. */ - function wrapperNext() { - if (this.__values__ === undefined) { - this.__values__ = toArray(this.value()); - } - var done = this.__index__ >= this.__values__.length, - value = done ? undefined : this.__values__[this.__index__++]; - - return { 'done': done, 'value': value }; + function baseSample(collection) { + return arraySample(values(collection)); } /** - * Enables the wrapper to be iterable. - * - * @name Symbol.iterator - * @memberOf _ - * @since 4.0.0 - * @category Seq - * @returns {Object} Returns the wrapper object. - * @example - * - * var wrapped = _([1, 2]); - * - * wrapped[Symbol.iterator]() === wrapped; - * // => true + * The base implementation of `_.sampleSize` without param guards. * - * Array.from(wrapped); - * // => [1, 2] + * @private + * @param {Array|Object} collection The collection to sample. + * @param {number} n The number of elements to sample. + * @returns {Array} Returns the random elements. */ - function wrapperToIterator() { - return this; + function baseSampleSize(collection, n) { + var array = values(collection); + return shuffleSelf(array, baseClamp(n, 0, array.length)); } /** - * Creates a clone of the chain sequence planting `value` as the wrapped value. - * - * @name plant - * @memberOf _ - * @since 3.2.0 - * @category Seq - * @param {*} value The value to plant. - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example - * - * function square(n) { - * return n * n; - * } - * - * var wrapped = _([1, 2]).map(square); - * var other = wrapped.plant([3, 4]); - * - * other.value(); - * // => [9, 16] + * The base implementation of `_.set`. * - * wrapped.value(); - * // => [1, 4] + * @private + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {*} value The value to set. + * @param {Function} [customizer] The function to customize path creation. + * @returns {Object} Returns `object`. */ - function wrapperPlant(value) { - var result, - parent = this; + function baseSet(object, path, value, customizer) { + if (!isObject(object)) { + return object; + } + path = castPath(path, object); - while (parent instanceof baseLodash) { - var clone = wrapperClone(parent); - clone.__index__ = 0; - clone.__values__ = undefined; - if (result) { - previous.__wrapped__ = clone; - } else { - result = clone; + var index = -1, + length = path.length, + lastIndex = length - 1, + nested = object; + + while (nested != null && ++index < length) { + var key = toKey(path[index]), + newValue = value; + + if (key === '__proto__' || key === 'constructor' || key === 'prototype') { + return object; } - var previous = clone; - parent = parent.__wrapped__; + + if (index != lastIndex) { + var objValue = nested[key]; + newValue = customizer ? customizer(objValue, key, nested) : undefined; + if (newValue === undefined) { + newValue = isObject(objValue) + ? objValue + : (isIndex(path[index + 1]) ? [] : {}); + } + } + assignValue(nested, key, newValue); + nested = nested[key]; } - previous.__wrapped__ = value; - return result; + return object; } /** - * This method is the wrapper version of `_.reverse`. - * - * **Note:** This method mutates the wrapped array. - * - * @name reverse - * @memberOf _ - * @since 0.1.0 - * @category Seq - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example - * - * var array = [1, 2, 3]; - * - * _(array).reverse().value() - * // => [3, 2, 1] + * The base implementation of `setData` without support for hot loop shorting. * - * console.log(array); - * // => [3, 2, 1] + * @private + * @param {Function} func The function to associate metadata with. + * @param {*} data The metadata. + * @returns {Function} Returns `func`. */ - function wrapperReverse() { - var value = this.__wrapped__; - if (value instanceof LazyWrapper) { - var wrapped = value; - if (this.__actions__.length) { - wrapped = new LazyWrapper(this); - } - wrapped = wrapped.reverse(); - wrapped.__actions__.push({ - 'func': thru, - 'args': [reverse], - 'thisArg': undefined - }); - return new LodashWrapper(wrapped, this.__chain__); - } - return this.thru(reverse); - } + var baseSetData = !metaMap ? identity : function(func, data) { + metaMap.set(func, data); + return func; + }; /** - * Executes the chain sequence to resolve the unwrapped value. + * The base implementation of `setToString` without support for hot loop shorting. * - * @name value - * @memberOf _ - * @since 0.1.0 - * @alias toJSON, valueOf - * @category Seq - * @returns {*} Returns the resolved unwrapped value. - * @example + * @private + * @param {Function} func The function to modify. + * @param {Function} string The `toString` result. + * @returns {Function} Returns `func`. + */ + var baseSetToString = !defineProperty ? identity : function(func, string) { + return defineProperty(func, 'toString', { + 'configurable': true, + 'enumerable': false, + 'value': constant(string), + 'writable': true + }); + }; + + /** + * The base implementation of `_.shuffle`. * - * _([1, 2, 3]).value(); - * // => [1, 2, 3] + * @private + * @param {Array|Object} collection The collection to shuffle. + * @returns {Array} Returns the new shuffled array. */ - function wrapperValue() { - return baseWrapperValue(this.__wrapped__, this.__actions__); + function baseShuffle(collection) { + return shuffleSelf(values(collection)); } - /*------------------------------------------------------------------------*/ - /** - * Creates an object composed of keys generated from the results of running - * each element of `collection` thru `iteratee`. The corresponding value of - * each key is the number of times the key was returned by `iteratee`. The - * iteratee is invoked with one argument: (value). - * - * @static - * @memberOf _ - * @since 0.5.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The iteratee to transform keys. - * @returns {Object} Returns the composed aggregate object. - * @example - * - * _.countBy([6.1, 4.2, 6.3], Math.floor); - * // => { '4': 1, '6': 2 } + * The base implementation of `_.slice` without an iteratee call guard. * - * // The `_.property` iteratee shorthand. - * _.countBy(['one', 'two', 'three'], 'length'); - * // => { '3': 2, '5': 1 } + * @private + * @param {Array} array The array to slice. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the slice of `array`. */ - var countBy = createAggregator(function(result, value, key) { - if (hasOwnProperty.call(result, key)) { - ++result[key]; - } else { - baseAssignValue(result, key, 1); + function baseSlice(array, start, end) { + var index = -1, + length = array.length; + + if (start < 0) { + start = -start > length ? 0 : (length + start); } - }); + end = end > length ? length : end; + if (end < 0) { + end += length; + } + length = start > end ? 0 : ((end - start) >>> 0); + start >>>= 0; + + var result = Array(length); + while (++index < length) { + result[index] = array[index + start]; + } + return result; + } /** - * Checks if `predicate` returns truthy for **all** elements of `collection`. - * Iteration is stopped once `predicate` returns falsey. The predicate is - * invoked with three arguments: (value, index|key, collection). - * - * **Note:** This method returns `true` for - * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because - * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of - * elements of empty collections. + * The base implementation of `_.some` without support for iteratee shorthands. * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection + * @private * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {boolean} Returns `true` if all elements pass the predicate check, + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. - * @example - * - * _.every([true, 1, null, 'yes'], Boolean); - * // => false - * - * var users = [ - * { 'user': 'barney', 'age': 36, 'active': false }, - * { 'user': 'fred', 'age': 40, 'active': false } - * ]; - * - * // The `_.matches` iteratee shorthand. - * _.every(users, { 'user': 'barney', 'active': false }); - * // => false - * - * // The `_.matchesProperty` iteratee shorthand. - * _.every(users, ['active', false]); - * // => true + */ + function baseSome(collection, predicate) { + var result; + + baseEach(collection, function(value, index, collection) { + result = predicate(value, index, collection); + return !result; + }); + return !!result; + } + + /** + * The base implementation of `_.sortedIndex` and `_.sortedLastIndex` which + * performs a binary search of `array` to determine the index at which `value` + * should be inserted into `array` in order to maintain its sort order. * - * // The `_.property` iteratee shorthand. - * _.every(users, 'active'); - * // => false + * @private + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {boolean} [retHighest] Specify returning the highest qualified index. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. */ - function every(collection, predicate, guard) { - var func = isArray(collection) ? arrayEvery : baseEvery; - if (guard && isIterateeCall(collection, predicate, guard)) { - predicate = undefined; + function baseSortedIndex(array, value, retHighest) { + var low = 0, + high = array == null ? low : array.length; + + if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) { + while (low < high) { + var mid = (low + high) >>> 1, + computed = array[mid]; + + if (computed !== null && !isSymbol(computed) && + (retHighest ? (computed <= value) : (computed < value))) { + low = mid + 1; + } else { + high = mid; + } + } + return high; } - return func(collection, getIteratee(predicate, 3)); + return baseSortedIndexBy(array, value, identity, retHighest); } /** - * Iterates over elements of `collection`, returning an array of all elements - * `predicate` returns truthy for. The predicate is invoked with three - * arguments: (value, index|key, collection). - * - * **Note:** Unlike `_.remove`, this method returns a new array. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the new filtered array. - * @see _.reject - * @example - * - * var users = [ - * { 'user': 'barney', 'age': 36, 'active': true }, - * { 'user': 'fred', 'age': 40, 'active': false } - * ]; - * - * _.filter(users, function(o) { return !o.active; }); - * // => objects for ['fred'] - * - * // The `_.matches` iteratee shorthand. - * _.filter(users, { 'age': 36, 'active': true }); - * // => objects for ['barney'] - * - * // The `_.matchesProperty` iteratee shorthand. - * _.filter(users, ['active', false]); - * // => objects for ['fred'] - * - * // The `_.property` iteratee shorthand. - * _.filter(users, 'active'); - * // => objects for ['barney'] + * The base implementation of `_.sortedIndexBy` and `_.sortedLastIndexBy` + * which invokes `iteratee` for `value` and each element of `array` to compute + * their sort ranking. The iteratee is invoked with one argument; (value). * - * // Combining several predicates using `_.overEvery` or `_.overSome`. - * _.filter(users, _.overSome([{ 'age': 36 }, ['age', 40]])); - * // => objects for ['fred', 'barney'] + * @private + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {Function} iteratee The iteratee invoked per element. + * @param {boolean} [retHighest] Specify returning the highest qualified index. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. */ - function filter(collection, predicate) { - var func = isArray(collection) ? arrayFilter : baseFilter; - return func(collection, getIteratee(predicate, 3)); + function baseSortedIndexBy(array, value, iteratee, retHighest) { + var low = 0, + high = array == null ? 0 : array.length; + if (high === 0) { + return 0; + } + + value = iteratee(value); + var valIsNaN = value !== value, + valIsNull = value === null, + valIsSymbol = isSymbol(value), + valIsUndefined = value === undefined; + + while (low < high) { + var mid = nativeFloor((low + high) / 2), + computed = iteratee(array[mid]), + othIsDefined = computed !== undefined, + othIsNull = computed === null, + othIsReflexive = computed === computed, + othIsSymbol = isSymbol(computed); + + if (valIsNaN) { + var setLow = retHighest || othIsReflexive; + } else if (valIsUndefined) { + setLow = othIsReflexive && (retHighest || othIsDefined); + } else if (valIsNull) { + setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull); + } else if (valIsSymbol) { + setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol); + } else if (othIsNull || othIsSymbol) { + setLow = false; + } else { + setLow = retHighest ? (computed <= value) : (computed < value); + } + if (setLow) { + low = mid + 1; + } else { + high = mid; + } + } + return nativeMin(high, MAX_ARRAY_INDEX); } /** - * Iterates over elements of `collection`, returning the first element - * `predicate` returns truthy for. The predicate is invoked with three - * arguments: (value, index|key, collection). - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to inspect. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @param {number} [fromIndex=0] The index to search from. - * @returns {*} Returns the matched element, else `undefined`. - * @example - * - * var users = [ - * { 'user': 'barney', 'age': 36, 'active': true }, - * { 'user': 'fred', 'age': 40, 'active': false }, - * { 'user': 'pebbles', 'age': 1, 'active': true } - * ]; - * - * _.find(users, function(o) { return o.age < 40; }); - * // => object for 'barney' - * - * // The `_.matches` iteratee shorthand. - * _.find(users, { 'age': 1, 'active': true }); - * // => object for 'pebbles' - * - * // The `_.matchesProperty` iteratee shorthand. - * _.find(users, ['active', false]); - * // => object for 'fred' - * - * // The `_.property` iteratee shorthand. - * _.find(users, 'active'); - * // => object for 'barney' + * The base implementation of `_.sortedUniq` and `_.sortedUniqBy` without + * support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @returns {Array} Returns the new duplicate free array. */ - var find = createFind(findIndex); + function baseSortedUniq(array, iteratee) { + var index = -1, + length = array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index], + computed = iteratee ? iteratee(value) : value; + + if (!index || !eq(computed, seen)) { + var seen = computed; + result[resIndex++] = value === 0 ? 0 : value; + } + } + return result; + } /** - * This method is like `_.find` except that it iterates over elements of - * `collection` from right to left. - * - * @static - * @memberOf _ - * @since 2.0.0 - * @category Collection - * @param {Array|Object} collection The collection to inspect. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @param {number} [fromIndex=collection.length-1] The index to search from. - * @returns {*} Returns the matched element, else `undefined`. - * @example + * The base implementation of `_.toNumber` which doesn't ensure correct + * conversions of binary, hexadecimal, or octal string values. * - * _.findLast([1, 2, 3, 4], function(n) { - * return n % 2 == 1; - * }); - * // => 3 + * @private + * @param {*} value The value to process. + * @returns {number} Returns the number. */ - var findLast = createFind(findLastIndex); + function baseToNumber(value) { + if (typeof value == 'number') { + return value; + } + if (isSymbol(value)) { + return NAN; + } + return +value; + } /** - * Creates a flattened array of values by running each element in `collection` - * thru `iteratee` and flattening the mapped results. The iteratee is invoked - * with three arguments: (value, index|key, collection). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Array} Returns the new flattened array. - * @example - * - * function duplicate(n) { - * return [n, n]; - * } + * The base implementation of `_.toString` which doesn't convert nullish + * values to empty strings. * - * _.flatMap([1, 2], duplicate); - * // => [1, 1, 2, 2] + * @private + * @param {*} value The value to process. + * @returns {string} Returns the string. */ - function flatMap(collection, iteratee) { - return baseFlatten(map(collection, iteratee), 1); + function baseToString(value) { + // Exit early for strings to avoid a performance hit in some environments. + if (typeof value == 'string') { + return value; + } + if (isArray(value)) { + // Recursively convert values (susceptible to call stack limits). + return arrayMap(value, baseToString) + ''; + } + if (isSymbol(value)) { + return symbolToString ? symbolToString.call(value) : ''; + } + var result = (value + ''); + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } /** - * This method is like `_.flatMap` except that it recursively flattens the - * mapped results. - * - * @static - * @memberOf _ - * @since 4.7.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Array} Returns the new flattened array. - * @example - * - * function duplicate(n) { - * return [[[n, n]]]; - * } + * The base implementation of `_.uniqBy` without support for iteratee shorthands. * - * _.flatMapDeep([1, 2], duplicate); - * // => [1, 1, 2, 2] + * @private + * @param {Array} array The array to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new duplicate free array. */ - function flatMapDeep(collection, iteratee) { - return baseFlatten(map(collection, iteratee), INFINITY); + function baseUniq(array, iteratee, comparator) { + var index = -1, + includes = arrayIncludes, + length = array.length, + isCommon = true, + result = [], + seen = result; + + if (comparator) { + isCommon = false; + includes = arrayIncludesWith; + } + else if (length >= LARGE_ARRAY_SIZE) { + var set = iteratee ? null : createSet(array); + if (set) { + return setToArray(set); + } + isCommon = false; + includes = cacheHas; + seen = new SetCache; + } + else { + seen = iteratee ? [] : result; + } + outer: + while (++index < length) { + var value = array[index], + computed = iteratee ? iteratee(value) : value; + + value = (comparator || value !== 0) ? value : 0; + if (isCommon && computed === computed) { + var seenIndex = seen.length; + while (seenIndex--) { + if (seen[seenIndex] === computed) { + continue outer; + } + } + if (iteratee) { + seen.push(computed); + } + result.push(value); + } + else if (!includes(seen, computed, comparator)) { + if (seen !== result) { + seen.push(computed); + } + result.push(value); + } + } + return result; } /** - * This method is like `_.flatMap` except that it recursively flattens the - * mapped results up to `depth` times. - * - * @static - * @memberOf _ - * @since 4.7.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @param {number} [depth=1] The maximum recursion depth. - * @returns {Array} Returns the new flattened array. - * @example - * - * function duplicate(n) { - * return [[[n, n]]]; - * } + * The base implementation of `_.unset`. * - * _.flatMapDepth([1, 2], duplicate, 2); - * // => [[1, 1], [2, 2]] + * @private + * @param {Object} object The object to modify. + * @param {Array|string} path The property path to unset. + * @returns {boolean} Returns `true` if the property is deleted, else `false`. */ - function flatMapDepth(collection, iteratee, depth) { - depth = depth === undefined ? 1 : toInteger(depth); - return baseFlatten(map(collection, iteratee), depth); + function baseUnset(object, path) { + path = castPath(path, object); + object = parent(object, path); + return object == null || delete object[toKey(last(path))]; } /** - * Iterates over elements of `collection` and invokes `iteratee` for each element. - * The iteratee is invoked with three arguments: (value, index|key, collection). - * Iteratee functions may exit iteration early by explicitly returning `false`. - * - * **Note:** As with other "Collections" methods, objects with a "length" - * property are iterated like arrays. To avoid this behavior use `_.forIn` - * or `_.forOwn` for object iteration. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @alias each - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Array|Object} Returns `collection`. - * @see _.forEachRight - * @example - * - * _.forEach([1, 2], function(value) { - * console.log(value); - * }); - * // => Logs `1` then `2`. + * The base implementation of `_.update`. * - * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) { - * console.log(key); - * }); - * // => Logs 'a' then 'b' (iteration order is not guaranteed). + * @private + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to update. + * @param {Function} updater The function to produce the updated value. + * @param {Function} [customizer] The function to customize path creation. + * @returns {Object} Returns `object`. */ - function forEach(collection, iteratee) { - var func = isArray(collection) ? arrayEach : baseEach; - return func(collection, getIteratee(iteratee, 3)); + function baseUpdate(object, path, updater, customizer) { + return baseSet(object, path, updater(baseGet(object, path)), customizer); } /** - * This method is like `_.forEach` except that it iterates over elements of - * `collection` from right to left. - * - * @static - * @memberOf _ - * @since 2.0.0 - * @alias eachRight - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Array|Object} Returns `collection`. - * @see _.forEach - * @example + * The base implementation of methods like `_.dropWhile` and `_.takeWhile` + * without support for iteratee shorthands. * - * _.forEachRight([1, 2], function(value) { - * console.log(value); - * }); - * // => Logs `2` then `1`. + * @private + * @param {Array} array The array to query. + * @param {Function} predicate The function invoked per iteration. + * @param {boolean} [isDrop] Specify dropping elements instead of taking them. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Array} Returns the slice of `array`. */ - function forEachRight(collection, iteratee) { - var func = isArray(collection) ? arrayEachRight : baseEachRight; - return func(collection, getIteratee(iteratee, 3)); + function baseWhile(array, predicate, isDrop, fromRight) { + var length = array.length, + index = fromRight ? length : -1; + + while ((fromRight ? index-- : ++index < length) && + predicate(array[index], index, array)) {} + + return isDrop + ? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length)) + : baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index)); } /** - * Creates an object composed of keys generated from the results of running - * each element of `collection` thru `iteratee`. The order of grouped values - * is determined by the order they occur in `collection`. The corresponding - * value of each key is an array of elements responsible for generating the - * key. The iteratee is invoked with one argument: (value). - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The iteratee to transform keys. - * @returns {Object} Returns the composed aggregate object. - * @example - * - * _.groupBy([6.1, 4.2, 6.3], Math.floor); - * // => { '4': [4.2], '6': [6.1, 6.3] } + * The base implementation of `wrapperValue` which returns the result of + * performing a sequence of actions on the unwrapped `value`, where each + * successive action is supplied the return value of the previous. * - * // The `_.property` iteratee shorthand. - * _.groupBy(['one', 'two', 'three'], 'length'); - * // => { '3': ['one', 'two'], '5': ['three'] } + * @private + * @param {*} value The unwrapped value. + * @param {Array} actions Actions to perform to resolve the unwrapped value. + * @returns {*} Returns the resolved value. */ - var groupBy = createAggregator(function(result, value, key) { - if (hasOwnProperty.call(result, key)) { - result[key].push(value); - } else { - baseAssignValue(result, key, [value]); + function baseWrapperValue(value, actions) { + var result = value; + if (result instanceof LazyWrapper) { + result = result.value(); } - }); + return arrayReduce(actions, function(result, action) { + return action.func.apply(action.thisArg, arrayPush([result], action.args)); + }, result); + } /** - * Checks if `value` is in `collection`. If `collection` is a string, it's - * checked for a substring of `value`, otherwise - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * is used for equality comparisons. If `fromIndex` is negative, it's used as - * the offset from the end of `collection`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object|string} collection The collection to inspect. - * @param {*} value The value to search for. - * @param {number} [fromIndex=0] The index to search from. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. - * @returns {boolean} Returns `true` if `value` is found, else `false`. - * @example - * - * _.includes([1, 2, 3], 1); - * // => true - * - * _.includes([1, 2, 3], 1, 2); - * // => false - * - * _.includes({ 'a': 1, 'b': 2 }, 1); - * // => true + * The base implementation of methods like `_.xor`, without support for + * iteratee shorthands, that accepts an array of arrays to inspect. * - * _.includes('abcd', 'bc'); - * // => true + * @private + * @param {Array} arrays The arrays to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of values. */ - function includes(collection, value, fromIndex, guard) { - collection = isArrayLike(collection) ? collection : values(collection); - fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0; + function baseXor(arrays, iteratee, comparator) { + var length = arrays.length; + if (length < 2) { + return length ? baseUniq(arrays[0]) : []; + } + var index = -1, + result = Array(length); - var length = collection.length; - if (fromIndex < 0) { - fromIndex = nativeMax(length + fromIndex, 0); + while (++index < length) { + var array = arrays[index], + othIndex = -1; + + while (++othIndex < length) { + if (othIndex != index) { + result[index] = baseDifference(result[index] || array, arrays[othIndex], iteratee, comparator); + } + } } - return isString(collection) - ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1) - : (!!length && baseIndexOf(collection, value, fromIndex) > -1); + return baseUniq(baseFlatten(result, 1), iteratee, comparator); } /** - * Invokes the method at `path` of each element in `collection`, returning - * an array of the results of each invoked method. Any additional arguments - * are provided to each invoked method. If `path` is a function, it's invoked - * for, and `this` bound to, each element in `collection`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Array|Function|string} path The path of the method to invoke or - * the function invoked per iteration. - * @param {...*} [args] The arguments to invoke each method with. - * @returns {Array} Returns the array of results. - * @example - * - * _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort'); - * // => [[1, 5, 7], [1, 2, 3]] + * This base implementation of `_.zipObject` which assigns values using `assignFunc`. * - * _.invokeMap([123, 456], String.prototype.split, ''); - * // => [['1', '2', '3'], ['4', '5', '6']] + * @private + * @param {Array} props The property identifiers. + * @param {Array} values The property values. + * @param {Function} assignFunc The function to assign values. + * @returns {Object} Returns the new object. */ - var invokeMap = baseRest(function(collection, path, args) { + function baseZipObject(props, values, assignFunc) { var index = -1, - isFunc = typeof path == 'function', - result = isArrayLike(collection) ? Array(collection.length) : []; + length = props.length, + valsLength = values.length, + result = {}; - baseEach(collection, function(value) { - result[++index] = isFunc ? apply(path, value, args) : baseInvoke(value, path, args); - }); + while (++index < length) { + var value = index < valsLength ? values[index] : undefined; + assignFunc(result, props[index], value); + } return result; - }); + } /** - * Creates an object composed of keys generated from the results of running - * each element of `collection` thru `iteratee`. The corresponding value of - * each key is the last element responsible for generating the key. The - * iteratee is invoked with one argument: (value). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The iteratee to transform keys. - * @returns {Object} Returns the composed aggregate object. - * @example - * - * var array = [ - * { 'dir': 'left', 'code': 97 }, - * { 'dir': 'right', 'code': 100 } - * ]; - * - * _.keyBy(array, function(o) { - * return String.fromCharCode(o.code); - * }); - * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } + * Casts `value` to an empty array if it's not an array like object. * - * _.keyBy(array, 'dir'); - * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } } + * @private + * @param {*} value The value to inspect. + * @returns {Array|Object} Returns the cast array-like object. */ - var keyBy = createAggregator(function(result, value, key) { - baseAssignValue(result, key, value); - }); + function castArrayLikeObject(value) { + return isArrayLikeObject(value) ? value : []; + } /** - * Creates an array of values by running each element in `collection` thru - * `iteratee`. The iteratee is invoked with three arguments: - * (value, index|key, collection). - * - * Many lodash methods are guarded to work as iteratees for methods like - * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. - * - * The guarded methods are: - * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`, - * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`, - * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`, - * `template`, `trim`, `trimEnd`, `trimStart`, and `words` - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Array} Returns the new mapped array. - * @example - * - * function square(n) { - * return n * n; - * } + * Casts `value` to `identity` if it's not a function. * - * _.map([4, 8], square); - * // => [16, 64] + * @private + * @param {*} value The value to inspect. + * @returns {Function} Returns cast function. + */ + function castFunction(value) { + return typeof value == 'function' ? value : identity; + } + + /** + * Casts `value` to a path array if it's not one. * - * _.map({ 'a': 4, 'b': 8 }, square); - * // => [16, 64] (iteration order is not guaranteed) + * @private + * @param {*} value The value to inspect. + * @param {Object} [object] The object to query keys on. + * @returns {Array} Returns the cast property path array. + */ + function castPath(value, object) { + if (isArray(value)) { + return value; + } + return isKey(value, object) ? [value] : stringToPath(toString(value)); + } + + /** + * A `baseRest` alias which can be replaced with `identity` by module + * replacement plugins. * - * var users = [ - * { 'user': 'barney' }, - * { 'user': 'fred' } - * ]; + * @private + * @type {Function} + * @param {Function} func The function to apply a rest parameter to. + * @returns {Function} Returns the new function. + */ + var castRest = baseRest; + + /** + * Casts `array` to a slice if it's needed. * - * // The `_.property` iteratee shorthand. - * _.map(users, 'user'); - * // => ['barney', 'fred'] + * @private + * @param {Array} array The array to inspect. + * @param {number} start The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the cast slice. */ - function map(collection, iteratee) { - var func = isArray(collection) ? arrayMap : baseMap; - return func(collection, getIteratee(iteratee, 3)); + function castSlice(array, start, end) { + var length = array.length; + end = end === undefined ? length : end; + return (!start && end >= length) ? array : baseSlice(array, start, end); } /** - * This method is like `_.sortBy` except that it allows specifying the sort - * orders of the iteratees to sort by. If `orders` is unspecified, all values - * are sorted in ascending order. Otherwise, specify an order of "desc" for - * descending or "asc" for ascending sort order of corresponding values. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]] - * The iteratees to sort by. - * @param {string[]} [orders] The sort orders of `iteratees`. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. - * @returns {Array} Returns the new sorted array. - * @example + * A simple wrapper around the global [`clearTimeout`](https://mdn.io/clearTimeout). * - * var users = [ - * { 'user': 'fred', 'age': 48 }, - * { 'user': 'barney', 'age': 34 }, - * { 'user': 'fred', 'age': 40 }, - * { 'user': 'barney', 'age': 36 } - * ]; + * @private + * @param {number|Object} id The timer id or timeout object of the timer to clear. + */ + var clearTimeout = ctxClearTimeout || function(id) { + return root.clearTimeout(id); + }; + + /** + * Creates a clone of `buffer`. * - * // Sort by `user` in ascending order and by `age` in descending order. - * _.orderBy(users, ['user', 'age'], ['asc', 'desc']); - * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] + * @private + * @param {Buffer} buffer The buffer to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Buffer} Returns the cloned buffer. */ - function orderBy(collection, iteratees, orders, guard) { - if (collection == null) { - return []; - } - if (!isArray(iteratees)) { - iteratees = iteratees == null ? [] : [iteratees]; - } - orders = guard ? undefined : orders; - if (!isArray(orders)) { - orders = orders == null ? [] : [orders]; + function cloneBuffer(buffer, isDeep) { + if (isDeep) { + return buffer.slice(); } - return baseOrderBy(collection, iteratees, orders); + var length = buffer.length, + result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); + + buffer.copy(result); + return result; } /** - * Creates an array of elements split into two groups, the first of which - * contains elements `predicate` returns truthy for, the second of which - * contains elements `predicate` returns falsey for. The predicate is - * invoked with one argument: (value). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the array of grouped elements. - * @example - * - * var users = [ - * { 'user': 'barney', 'age': 36, 'active': false }, - * { 'user': 'fred', 'age': 40, 'active': true }, - * { 'user': 'pebbles', 'age': 1, 'active': false } - * ]; - * - * _.partition(users, function(o) { return o.active; }); - * // => objects for [['fred'], ['barney', 'pebbles']] - * - * // The `_.matches` iteratee shorthand. - * _.partition(users, { 'age': 1, 'active': false }); - * // => objects for [['pebbles'], ['barney', 'fred']] - * - * // The `_.matchesProperty` iteratee shorthand. - * _.partition(users, ['active', false]); - * // => objects for [['barney', 'pebbles'], ['fred']] + * Creates a clone of `arrayBuffer`. * - * // The `_.property` iteratee shorthand. - * _.partition(users, 'active'); - * // => objects for [['fred'], ['barney', 'pebbles']] + * @private + * @param {ArrayBuffer} arrayBuffer The array buffer to clone. + * @returns {ArrayBuffer} Returns the cloned array buffer. */ - var partition = createAggregator(function(result, value, key) { - result[key ? 0 : 1].push(value); - }, function() { return [[], []]; }); + function cloneArrayBuffer(arrayBuffer) { + var result = new arrayBuffer.constructor(arrayBuffer.byteLength); + new Uint8Array(result).set(new Uint8Array(arrayBuffer)); + return result; + } /** - * Reduces `collection` to a value which is the accumulated result of running - * each element in `collection` thru `iteratee`, where each successive - * invocation is supplied the return value of the previous. If `accumulator` - * is not given, the first element of `collection` is used as the initial - * value. The iteratee is invoked with four arguments: - * (accumulator, value, index|key, collection). - * - * Many lodash methods are guarded to work as iteratees for methods like - * `_.reduce`, `_.reduceRight`, and `_.transform`. - * - * The guarded methods are: - * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`, - * and `sortBy` - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @param {*} [accumulator] The initial value. - * @returns {*} Returns the accumulated value. - * @see _.reduceRight - * @example - * - * _.reduce([1, 2], function(sum, n) { - * return sum + n; - * }, 0); - * // => 3 + * Creates a clone of `dataView`. * - * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { - * (result[value] || (result[value] = [])).push(key); - * return result; - * }, {}); - * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed) + * @private + * @param {Object} dataView The data view to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned data view. */ - function reduce(collection, iteratee, accumulator) { - var func = isArray(collection) ? arrayReduce : baseReduce, - initAccum = arguments.length < 3; + function cloneDataView(dataView, isDeep) { + var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer; + return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); + } - return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEach); + /** + * Creates a clone of `regexp`. + * + * @private + * @param {Object} regexp The regexp to clone. + * @returns {Object} Returns the cloned regexp. + */ + function cloneRegExp(regexp) { + var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); + result.lastIndex = regexp.lastIndex; + return result; } /** - * This method is like `_.reduce` except that it iterates over elements of - * `collection` from right to left. + * Creates a clone of the `symbol` object. * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @param {*} [accumulator] The initial value. - * @returns {*} Returns the accumulated value. - * @see _.reduce - * @example + * @private + * @param {Object} symbol The symbol object to clone. + * @returns {Object} Returns the cloned symbol object. + */ + function cloneSymbol(symbol) { + return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {}; + } + + /** + * Creates a clone of `typedArray`. * - * var array = [[0, 1], [2, 3], [4, 5]]; + * @private + * @param {Object} typedArray The typed array to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned typed array. + */ + function cloneTypedArray(typedArray, isDeep) { + var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; + return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); + } + + /** + * Compares values to sort them in ascending order. * - * _.reduceRight(array, function(flattened, other) { - * return flattened.concat(other); - * }, []); - * // => [4, 5, 2, 3, 0, 1] + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {number} Returns the sort order indicator for `value`. */ - function reduceRight(collection, iteratee, accumulator) { - var func = isArray(collection) ? arrayReduceRight : baseReduce, - initAccum = arguments.length < 3; + function compareAscending(value, other) { + if (value !== other) { + var valIsDefined = value !== undefined, + valIsNull = value === null, + valIsReflexive = value === value, + valIsSymbol = isSymbol(value); - return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEachRight); + var othIsDefined = other !== undefined, + othIsNull = other === null, + othIsReflexive = other === other, + othIsSymbol = isSymbol(other); + + if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) || + (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) || + (valIsNull && othIsDefined && othIsReflexive) || + (!valIsDefined && othIsReflexive) || + !valIsReflexive) { + return 1; + } + if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) || + (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) || + (othIsNull && valIsDefined && valIsReflexive) || + (!othIsDefined && valIsReflexive) || + !othIsReflexive) { + return -1; + } + } + return 0; } /** - * The opposite of `_.filter`; this method returns the elements of `collection` - * that `predicate` does **not** return truthy for. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the new filtered array. - * @see _.filter - * @example - * - * var users = [ - * { 'user': 'barney', 'age': 36, 'active': false }, - * { 'user': 'fred', 'age': 40, 'active': true } - * ]; - * - * _.reject(users, function(o) { return !o.active; }); - * // => objects for ['fred'] - * - * // The `_.matches` iteratee shorthand. - * _.reject(users, { 'age': 40, 'active': true }); - * // => objects for ['barney'] + * Used by `_.orderBy` to compare multiple properties of a value to another + * and stable sort them. * - * // The `_.matchesProperty` iteratee shorthand. - * _.reject(users, ['active', false]); - * // => objects for ['fred'] + * If `orders` is unspecified, all values are sorted in ascending order. Otherwise, + * specify an order of "desc" for descending or "asc" for ascending sort order + * of corresponding values. * - * // The `_.property` iteratee shorthand. - * _.reject(users, 'active'); - * // => objects for ['barney'] + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {boolean[]|string[]} orders The order to sort by for each property. + * @returns {number} Returns the sort order indicator for `object`. */ - function reject(collection, predicate) { - var func = isArray(collection) ? arrayFilter : baseFilter; - return func(collection, negate(getIteratee(predicate, 3))); + function compareMultiple(object, other, orders) { + var index = -1, + objCriteria = object.criteria, + othCriteria = other.criteria, + length = objCriteria.length, + ordersLength = orders.length; + + while (++index < length) { + var result = compareAscending(objCriteria[index], othCriteria[index]); + if (result) { + if (index >= ordersLength) { + return result; + } + var order = orders[index]; + return result * (order == 'desc' ? -1 : 1); + } + } + // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications + // that causes it, under certain circumstances, to provide the same value for + // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247 + // for more details. + // + // This also ensures a stable sort in V8 and other engines. + // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details. + return object.index - other.index; } /** - * Gets a random element from `collection`. - * - * @static - * @memberOf _ - * @since 2.0.0 - * @category Collection - * @param {Array|Object} collection The collection to sample. - * @returns {*} Returns the random element. - * @example + * Creates an array that is the composition of partially applied arguments, + * placeholders, and provided arguments into a single array of arguments. * - * _.sample([1, 2, 3, 4]); - * // => 2 + * @private + * @param {Array} args The provided arguments. + * @param {Array} partials The arguments to prepend to those provided. + * @param {Array} holders The `partials` placeholder indexes. + * @params {boolean} [isCurried] Specify composing for a curried function. + * @returns {Array} Returns the new array of composed arguments. */ - function sample(collection) { - var func = isArray(collection) ? arraySample : baseSample; - return func(collection); + function composeArgs(args, partials, holders, isCurried) { + var argsIndex = -1, + argsLength = args.length, + holdersLength = holders.length, + leftIndex = -1, + leftLength = partials.length, + rangeLength = nativeMax(argsLength - holdersLength, 0), + result = Array(leftLength + rangeLength), + isUncurried = !isCurried; + + while (++leftIndex < leftLength) { + result[leftIndex] = partials[leftIndex]; + } + while (++argsIndex < holdersLength) { + if (isUncurried || argsIndex < argsLength) { + result[holders[argsIndex]] = args[argsIndex]; + } + } + while (rangeLength--) { + result[leftIndex++] = args[argsIndex++]; + } + return result; } /** - * Gets `n` random elements at unique keys from `collection` up to the - * size of `collection`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Collection - * @param {Array|Object} collection The collection to sample. - * @param {number} [n=1] The number of elements to sample. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Array} Returns the random elements. - * @example - * - * _.sampleSize([1, 2, 3], 2); - * // => [3, 1] + * This function is like `composeArgs` except that the arguments composition + * is tailored for `_.partialRight`. * - * _.sampleSize([1, 2, 3], 4); - * // => [2, 3, 1] + * @private + * @param {Array} args The provided arguments. + * @param {Array} partials The arguments to append to those provided. + * @param {Array} holders The `partials` placeholder indexes. + * @params {boolean} [isCurried] Specify composing for a curried function. + * @returns {Array} Returns the new array of composed arguments. */ - function sampleSize(collection, n, guard) { - if ((guard ? isIterateeCall(collection, n, guard) : n === undefined)) { - n = 1; - } else { - n = toInteger(n); + function composeArgsRight(args, partials, holders, isCurried) { + var argsIndex = -1, + argsLength = args.length, + holdersIndex = -1, + holdersLength = holders.length, + rightIndex = -1, + rightLength = partials.length, + rangeLength = nativeMax(argsLength - holdersLength, 0), + result = Array(rangeLength + rightLength), + isUncurried = !isCurried; + + while (++argsIndex < rangeLength) { + result[argsIndex] = args[argsIndex]; } - var func = isArray(collection) ? arraySampleSize : baseSampleSize; - return func(collection, n); + var offset = argsIndex; + while (++rightIndex < rightLength) { + result[offset + rightIndex] = partials[rightIndex]; + } + while (++holdersIndex < holdersLength) { + if (isUncurried || argsIndex < argsLength) { + result[offset + holders[holdersIndex]] = args[argsIndex++]; + } + } + return result; } /** - * Creates an array of shuffled values, using a version of the - * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle). - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to shuffle. - * @returns {Array} Returns the new shuffled array. - * @example + * Copies the values of `source` to `array`. * - * _.shuffle([1, 2, 3, 4]); - * // => [4, 1, 3, 2] + * @private + * @param {Array} source The array to copy values from. + * @param {Array} [array=[]] The array to copy values to. + * @returns {Array} Returns `array`. */ - function shuffle(collection) { - var func = isArray(collection) ? arrayShuffle : baseShuffle; - return func(collection); + function copyArray(source, array) { + var index = -1, + length = source.length; + + array || (array = Array(length)); + while (++index < length) { + array[index] = source[index]; + } + return array; } /** - * Gets the size of `collection` by returning its length for array-like - * values or the number of own enumerable string keyed properties for objects. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object|string} collection The collection to inspect. - * @returns {number} Returns the collection size. - * @example - * - * _.size([1, 2, 3]); - * // => 3 - * - * _.size({ 'a': 1, 'b': 2 }); - * // => 2 + * Copies properties of `source` to `object`. * - * _.size('pebbles'); - * // => 7 + * @private + * @param {Object} source The object to copy properties from. + * @param {Array} props The property identifiers to copy. + * @param {Object} [object={}] The object to copy properties to. + * @param {Function} [customizer] The function to customize copied values. + * @returns {Object} Returns `object`. */ - function size(collection) { - if (collection == null) { - return 0; - } - if (isArrayLike(collection)) { - return isString(collection) ? stringSize(collection) : collection.length; - } - var tag = getTag(collection); - if (tag == mapTag || tag == setTag) { - return collection.size; + function copyObject(source, props, object, customizer) { + var isNew = !object; + object || (object = {}); + + var index = -1, + length = props.length; + + while (++index < length) { + var key = props[index]; + + var newValue = customizer + ? customizer(object[key], source[key], key, object, source) + : undefined; + + if (newValue === undefined) { + newValue = source[key]; + } + if (isNew) { + baseAssignValue(object, key, newValue); + } else { + assignValue(object, key, newValue); + } } - return baseKeys(collection).length; + return object; } /** - * Checks if `predicate` returns truthy for **any** element of `collection`. - * Iteration is stopped once `predicate` returns truthy. The predicate is - * invoked with three arguments: (value, index|key, collection). - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {boolean} Returns `true` if any element passes the predicate check, - * else `false`. - * @example - * - * _.some([null, 0, 'yes', false], Boolean); - * // => true - * - * var users = [ - * { 'user': 'barney', 'active': true }, - * { 'user': 'fred', 'active': false } - * ]; - * - * // The `_.matches` iteratee shorthand. - * _.some(users, { 'user': 'barney', 'active': false }); - * // => false - * - * // The `_.matchesProperty` iteratee shorthand. - * _.some(users, ['active', false]); - * // => true + * Copies own symbols of `source` to `object`. * - * // The `_.property` iteratee shorthand. - * _.some(users, 'active'); - * // => true + * @private + * @param {Object} source The object to copy symbols from. + * @param {Object} [object={}] The object to copy symbols to. + * @returns {Object} Returns `object`. */ - function some(collection, predicate, guard) { - var func = isArray(collection) ? arraySome : baseSome; - if (guard && isIterateeCall(collection, predicate, guard)) { - predicate = undefined; - } - return func(collection, getIteratee(predicate, 3)); + function copySymbols(source, object) { + return copyObject(source, getSymbols(source), object); } /** - * Creates an array of elements, sorted in ascending order by the results of - * running each element in a collection thru each iteratee. This method - * performs a stable sort, that is, it preserves the original sort order of - * equal elements. The iteratees are invoked with one argument: (value). - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {...(Function|Function[])} [iteratees=[_.identity]] - * The iteratees to sort by. - * @returns {Array} Returns the new sorted array. - * @example - * - * var users = [ - * { 'user': 'fred', 'age': 48 }, - * { 'user': 'barney', 'age': 36 }, - * { 'user': 'fred', 'age': 30 }, - * { 'user': 'barney', 'age': 34 } - * ]; - * - * _.sortBy(users, [function(o) { return o.user; }]); - * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 30]] + * Copies own and inherited symbols of `source` to `object`. * - * _.sortBy(users, ['user', 'age']); - * // => objects for [['barney', 34], ['barney', 36], ['fred', 30], ['fred', 48]] + * @private + * @param {Object} source The object to copy symbols from. + * @param {Object} [object={}] The object to copy symbols to. + * @returns {Object} Returns `object`. */ - var sortBy = baseRest(function(collection, iteratees) { - if (collection == null) { - return []; - } - var length = iteratees.length; - if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) { - iteratees = []; - } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) { - iteratees = [iteratees[0]]; - } - return baseOrderBy(collection, baseFlatten(iteratees, 1), []); - }); - - /*------------------------------------------------------------------------*/ + function copySymbolsIn(source, object) { + return copyObject(source, getSymbolsIn(source), object); + } /** - * Gets the timestamp of the number of milliseconds that have elapsed since - * the Unix epoch (1 January 1970 00:00:00 UTC). - * - * @static - * @memberOf _ - * @since 2.4.0 - * @category Date - * @returns {number} Returns the timestamp. - * @example + * Creates a function like `_.groupBy`. * - * _.defer(function(stamp) { - * console.log(_.now() - stamp); - * }, _.now()); - * // => Logs the number of milliseconds it took for the deferred invocation. + * @private + * @param {Function} setter The function to set accumulator values. + * @param {Function} [initializer] The accumulator object initializer. + * @returns {Function} Returns the new aggregator function. */ - var now = ctxNow || function() { - return root.Date.now(); - }; + function createAggregator(setter, initializer) { + return function(collection, iteratee) { + var func = isArray(collection) ? arrayAggregator : baseAggregator, + accumulator = initializer ? initializer() : {}; - /*------------------------------------------------------------------------*/ + return func(collection, setter, getIteratee(iteratee, 2), accumulator); + }; + } /** - * The opposite of `_.before`; this method creates a function that invokes - * `func` once it's called `n` or more times. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {number} n The number of calls before `func` is invoked. - * @param {Function} func The function to restrict. - * @returns {Function} Returns the new restricted function. - * @example - * - * var saves = ['profile', 'settings']; - * - * var done = _.after(saves.length, function() { - * console.log('done saving!'); - * }); + * Creates a function like `_.assign`. * - * _.forEach(saves, function(type) { - * asyncSave({ 'type': type, 'complete': done }); - * }); - * // => Logs 'done saving!' after the two async saves have completed. + * @private + * @param {Function} assigner The function to assign values. + * @returns {Function} Returns the new assigner function. */ - function after(n, func) { - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - n = toInteger(n); - return function() { - if (--n < 1) { - return func.apply(this, arguments); + function createAssigner(assigner) { + return baseRest(function(object, sources) { + var index = -1, + length = sources.length, + customizer = length > 1 ? sources[length - 1] : undefined, + guard = length > 2 ? sources[2] : undefined; + + customizer = (assigner.length > 3 && typeof customizer == 'function') + ? (length--, customizer) + : undefined; + + if (guard && isIterateeCall(sources[0], sources[1], guard)) { + customizer = length < 3 ? undefined : customizer; + length = 1; } - }; + object = Object(object); + while (++index < length) { + var source = sources[index]; + if (source) { + assigner(object, source, index, customizer); + } + } + return object; + }); } /** - * Creates a function that invokes `func`, with up to `n` arguments, - * ignoring any additional arguments. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Function - * @param {Function} func The function to cap arguments for. - * @param {number} [n=func.length] The arity cap. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Function} Returns the new capped function. - * @example + * Creates a `baseEach` or `baseEachRight` function. * - * _.map(['6', '8', '10'], _.ary(parseInt, 1)); - * // => [6, 8, 10] + * @private + * @param {Function} eachFunc The function to iterate over a collection. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. */ - function ary(func, n, guard) { - n = guard ? undefined : n; - n = (func && n == null) ? func.length : n; - return createWrap(func, WRAP_ARY_FLAG, undefined, undefined, undefined, undefined, n); + function createBaseEach(eachFunc, fromRight) { + return function(collection, iteratee) { + if (collection == null) { + return collection; + } + if (!isArrayLike(collection)) { + return eachFunc(collection, iteratee); + } + var length = collection.length, + index = fromRight ? length : -1, + iterable = Object(collection); + + while ((fromRight ? index-- : ++index < length)) { + if (iteratee(iterable[index], index, iterable) === false) { + break; + } + } + return collection; + }; } /** - * Creates a function that invokes `func`, with the `this` binding and arguments - * of the created function, while it's called less than `n` times. Subsequent - * calls to the created function return the result of the last `func` invocation. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Function - * @param {number} n The number of calls at which `func` is no longer invoked. - * @param {Function} func The function to restrict. - * @returns {Function} Returns the new restricted function. - * @example + * Creates a base function for methods like `_.forIn` and `_.forOwn`. * - * jQuery(element).on('click', _.before(5, addContactToList)); - * // => Allows adding up to 4 contacts to the list. + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. */ - function before(n, func) { - var result; - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - n = toInteger(n); - return function() { - if (--n > 0) { - result = func.apply(this, arguments); - } - if (n <= 1) { - func = undefined; + function createBaseFor(fromRight) { + return function(object, iteratee, keysFunc) { + var index = -1, + iterable = Object(object), + props = keysFunc(object), + length = props.length; + + while (length--) { + var key = props[fromRight ? length : ++index]; + if (iteratee(iterable[key], key, iterable) === false) { + break; + } } - return result; + return object; }; } /** - * Creates a function that invokes `func` with the `this` binding of `thisArg` - * and `partials` prepended to the arguments it receives. - * - * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds, - * may be used as a placeholder for partially applied arguments. - * - * **Note:** Unlike native `Function#bind`, this method doesn't set the "length" - * property of bound functions. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to bind. - * @param {*} thisArg The `this` binding of `func`. - * @param {...*} [partials] The arguments to be partially applied. - * @returns {Function} Returns the new bound function. - * @example - * - * function greet(greeting, punctuation) { - * return greeting + ' ' + this.user + punctuation; - * } - * - * var object = { 'user': 'fred' }; - * - * var bound = _.bind(greet, object, 'hi'); - * bound('!'); - * // => 'hi fred!' + * Creates a function that wraps `func` to invoke it with the optional `this` + * binding of `thisArg`. * - * // Bound with placeholders. - * var bound = _.bind(greet, object, _, '!'); - * bound('hi'); - * // => 'hi fred!' + * @private + * @param {Function} func The function to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {*} [thisArg] The `this` binding of `func`. + * @returns {Function} Returns the new wrapped function. */ - var bind = baseRest(function(func, thisArg, partials) { - var bitmask = WRAP_BIND_FLAG; - if (partials.length) { - var holders = replaceHolders(partials, getHolder(bind)); - bitmask |= WRAP_PARTIAL_FLAG; + function createBind(func, bitmask, thisArg) { + var isBind = bitmask & WRAP_BIND_FLAG, + Ctor = createCtor(func); + + function wrapper() { + var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; + return fn.apply(isBind ? thisArg : this, arguments); } - return createWrap(func, bitmask, thisArg, partials, holders); - }); + return wrapper; + } /** - * Creates a function that invokes the method at `object[key]` with `partials` - * prepended to the arguments it receives. - * - * This method differs from `_.bind` by allowing bound functions to reference - * methods that may be redefined or don't yet exist. See - * [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern) - * for more details. - * - * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic - * builds, may be used as a placeholder for partially applied arguments. - * - * @static - * @memberOf _ - * @since 0.10.0 - * @category Function - * @param {Object} object The object to invoke the method on. - * @param {string} key The key of the method. - * @param {...*} [partials] The arguments to be partially applied. - * @returns {Function} Returns the new bound function. - * @example - * - * var object = { - * 'user': 'fred', - * 'greet': function(greeting, punctuation) { - * return greeting + ' ' + this.user + punctuation; - * } - * }; - * - * var bound = _.bindKey(object, 'greet', 'hi'); - * bound('!'); - * // => 'hi fred!' - * - * object.greet = function(greeting, punctuation) { - * return greeting + 'ya ' + this.user + punctuation; - * }; - * - * bound('!'); - * // => 'hiya fred!' + * Creates a function like `_.lowerFirst`. * - * // Bound with placeholders. - * var bound = _.bindKey(object, 'greet', _, '!'); - * bound('hi'); - * // => 'hiya fred!' + * @private + * @param {string} methodName The name of the `String` case method to use. + * @returns {Function} Returns the new case function. */ - var bindKey = baseRest(function(object, key, partials) { - var bitmask = WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG; - if (partials.length) { - var holders = replaceHolders(partials, getHolder(bindKey)); - bitmask |= WRAP_PARTIAL_FLAG; - } - return createWrap(key, bitmask, object, partials, holders); - }); + function createCaseFirst(methodName) { + return function(string) { + string = toString(string); + + var strSymbols = hasUnicode(string) + ? stringToArray(string) + : undefined; + + var chr = strSymbols + ? strSymbols[0] + : string.charAt(0); + + var trailing = strSymbols + ? castSlice(strSymbols, 1).join('') + : string.slice(1); + + return chr[methodName]() + trailing; + }; + } /** - * Creates a function that accepts arguments of `func` and either invokes - * `func` returning its result, if at least `arity` number of arguments have - * been provided, or returns a function that accepts the remaining `func` - * arguments, and so on. The arity of `func` may be specified if `func.length` - * is not sufficient. - * - * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds, - * may be used as a placeholder for provided arguments. - * - * **Note:** This method doesn't set the "length" property of curried functions. - * - * @static - * @memberOf _ - * @since 2.0.0 - * @category Function - * @param {Function} func The function to curry. - * @param {number} [arity=func.length] The arity of `func`. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Function} Returns the new curried function. - * @example - * - * var abc = function(a, b, c) { - * return [a, b, c]; - * }; - * - * var curried = _.curry(abc); - * - * curried(1)(2)(3); - * // => [1, 2, 3] + * Creates a function like `_.camelCase`. * - * curried(1, 2)(3); - * // => [1, 2, 3] + * @private + * @param {Function} callback The function to combine each word. + * @returns {Function} Returns the new compounder function. + */ + function createCompounder(callback) { + return function(string) { + return arrayReduce(words(deburr(string).replace(reApos, '')), callback, ''); + }; + } + + /** + * Creates a function that produces an instance of `Ctor` regardless of + * whether it was invoked as part of a `new` expression or by `call` or `apply`. * - * curried(1, 2, 3); - * // => [1, 2, 3] + * @private + * @param {Function} Ctor The constructor to wrap. + * @returns {Function} Returns the new wrapped function. + */ + function createCtor(Ctor) { + return function() { + // Use a `switch` statement to work with class constructors. See + // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist + // for more details. + var args = arguments; + switch (args.length) { + case 0: return new Ctor; + case 1: return new Ctor(args[0]); + case 2: return new Ctor(args[0], args[1]); + case 3: return new Ctor(args[0], args[1], args[2]); + case 4: return new Ctor(args[0], args[1], args[2], args[3]); + case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]); + case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]); + case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); + } + var thisBinding = baseCreate(Ctor.prototype), + result = Ctor.apply(thisBinding, args); + + // Mimic the constructor's `return` behavior. + // See https://es5.github.io/#x13.2.2 for more details. + return isObject(result) ? result : thisBinding; + }; + } + + /** + * Creates a function that wraps `func` to enable currying. * - * // Curried with placeholders. - * curried(1)(_, 3)(2); - * // => [1, 2, 3] + * @private + * @param {Function} func The function to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {number} arity The arity of `func`. + * @returns {Function} Returns the new wrapped function. */ - function curry(func, arity, guard) { - arity = guard ? undefined : arity; - var result = createWrap(func, WRAP_CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity); - result.placeholder = curry.placeholder; - return result; + function createCurry(func, bitmask, arity) { + var Ctor = createCtor(func); + + function wrapper() { + var length = arguments.length, + args = Array(length), + index = length, + placeholder = getHolder(wrapper); + + while (index--) { + args[index] = arguments[index]; + } + var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder) + ? [] + : replaceHolders(args, placeholder); + + length -= holders.length; + if (length < arity) { + return createRecurry( + func, bitmask, createHybrid, wrapper.placeholder, undefined, + args, holders, undefined, undefined, arity - length); + } + var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; + return apply(fn, this, args); + } + return wrapper; } /** - * This method is like `_.curry` except that arguments are applied to `func` - * in the manner of `_.partialRight` instead of `_.partial`. - * - * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic - * builds, may be used as a placeholder for provided arguments. - * - * **Note:** This method doesn't set the "length" property of curried functions. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Function - * @param {Function} func The function to curry. - * @param {number} [arity=func.length] The arity of `func`. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Function} Returns the new curried function. - * @example - * - * var abc = function(a, b, c) { - * return [a, b, c]; - * }; - * - * var curried = _.curryRight(abc); - * - * curried(3)(2)(1); - * // => [1, 2, 3] - * - * curried(2, 3)(1); - * // => [1, 2, 3] - * - * curried(1, 2, 3); - * // => [1, 2, 3] + * Creates a `_.find` or `_.findLast` function. * - * // Curried with placeholders. - * curried(3)(1, _)(2); - * // => [1, 2, 3] + * @private + * @param {Function} findIndexFunc The function to find the collection index. + * @returns {Function} Returns the new find function. */ - function curryRight(func, arity, guard) { - arity = guard ? undefined : arity; - var result = createWrap(func, WRAP_CURRY_RIGHT_FLAG, undefined, undefined, undefined, undefined, undefined, arity); - result.placeholder = curryRight.placeholder; - return result; + function createFind(findIndexFunc) { + return function(collection, predicate, fromIndex) { + var iterable = Object(collection); + if (!isArrayLike(collection)) { + var iteratee = getIteratee(predicate, 3); + collection = keys(collection); + predicate = function(key) { return iteratee(iterable[key], key, iterable); }; + } + var index = findIndexFunc(collection, predicate, fromIndex); + return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined; + }; } /** - * Creates a debounced function that delays invoking `func` until after `wait` - * milliseconds have elapsed since the last time the debounced function was - * invoked. The debounced function comes with a `cancel` method to cancel - * delayed `func` invocations and a `flush` method to immediately invoke them. - * Provide `options` to indicate whether `func` should be invoked on the - * leading and/or trailing edge of the `wait` timeout. The `func` is invoked - * with the last arguments provided to the debounced function. Subsequent - * calls to the debounced function return the result of the last `func` - * invocation. - * - * **Note:** If `leading` and `trailing` options are `true`, `func` is - * invoked on the trailing edge of the timeout only if the debounced function - * is invoked more than once during the `wait` timeout. - * - * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred - * until to the next tick, similar to `setTimeout` with a timeout of `0`. - * - * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) - * for details over the differences between `_.debounce` and `_.throttle`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to debounce. - * @param {number} [wait=0] The number of milliseconds to delay. - * @param {Object} [options={}] The options object. - * @param {boolean} [options.leading=false] - * Specify invoking on the leading edge of the timeout. - * @param {number} [options.maxWait] - * The maximum time `func` is allowed to be delayed before it's invoked. - * @param {boolean} [options.trailing=true] - * Specify invoking on the trailing edge of the timeout. - * @returns {Function} Returns the new debounced function. - * @example - * - * // Avoid costly calculations while the window size is in flux. - * jQuery(window).on('resize', _.debounce(calculateLayout, 150)); - * - * // Invoke `sendMail` when clicked, debouncing subsequent calls. - * jQuery(element).on('click', _.debounce(sendMail, 300, { - * 'leading': true, - * 'trailing': false - * })); - * - * // Ensure `batchLog` is invoked once after 1 second of debounced calls. - * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 }); - * var source = new EventSource('/stream'); - * jQuery(source).on('message', debounced); + * Creates a `_.flow` or `_.flowRight` function. * - * // Cancel the trailing debounced invocation. - * jQuery(window).on('popstate', debounced.cancel); + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new flow function. */ - function debounce(func, wait, options) { - var lastArgs, - lastThis, - maxWait, - result, - timerId, - lastCallTime, - lastInvokeTime = 0, - leading = false, - maxing = false, - trailing = true; - - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - wait = toNumber(wait) || 0; - if (isObject(options)) { - leading = !!options.leading; - maxing = 'maxWait' in options; - maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait; - trailing = 'trailing' in options ? !!options.trailing : trailing; - } + function createFlow(fromRight) { + return flatRest(function(funcs) { + var length = funcs.length, + index = length, + prereq = LodashWrapper.prototype.thru; - function invokeFunc(time) { - var args = lastArgs, - thisArg = lastThis; + if (fromRight) { + funcs.reverse(); + } + while (index--) { + var func = funcs[index]; + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + if (prereq && !wrapper && getFuncName(func) == 'wrapper') { + var wrapper = new LodashWrapper([], true); + } + } + index = wrapper ? index : length; + while (++index < length) { + func = funcs[index]; - lastArgs = lastThis = undefined; - lastInvokeTime = time; - result = func.apply(thisArg, args); - return result; - } + var funcName = getFuncName(func), + data = funcName == 'wrapper' ? getData(func) : undefined; - function leadingEdge(time) { - // Reset any `maxWait` timer. - lastInvokeTime = time; - // Start the timer for the trailing edge. - timerId = setTimeout(timerExpired, wait); - // Invoke the leading edge. - return leading ? invokeFunc(time) : result; - } + if (data && isLaziable(data[0]) && + data[1] == (WRAP_ARY_FLAG | WRAP_CURRY_FLAG | WRAP_PARTIAL_FLAG | WRAP_REARG_FLAG) && + !data[4].length && data[9] == 1 + ) { + wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]); + } else { + wrapper = (func.length == 1 && isLaziable(func)) + ? wrapper[funcName]() + : wrapper.thru(func); + } + } + return function() { + var args = arguments, + value = args[0]; - function remainingWait(time) { - var timeSinceLastCall = time - lastCallTime, - timeSinceLastInvoke = time - lastInvokeTime, - timeWaiting = wait - timeSinceLastCall; + if (wrapper && args.length == 1 && isArray(value)) { + return wrapper.plant(value).value(); + } + var index = 0, + result = length ? funcs[index].apply(this, args) : value; - return maxing - ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke) - : timeWaiting; - } + while (++index < length) { + result = funcs[index].call(this, result); + } + return result; + }; + }); + } - function shouldInvoke(time) { - var timeSinceLastCall = time - lastCallTime, - timeSinceLastInvoke = time - lastInvokeTime; + /** + * Creates a function that wraps `func` to invoke it with optional `this` + * binding of `thisArg`, partial application, and currying. + * + * @private + * @param {Function|string} func The function or method name to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {*} [thisArg] The `this` binding of `func`. + * @param {Array} [partials] The arguments to prepend to those provided to + * the new function. + * @param {Array} [holders] The `partials` placeholder indexes. + * @param {Array} [partialsRight] The arguments to append to those provided + * to the new function. + * @param {Array} [holdersRight] The `partialsRight` placeholder indexes. + * @param {Array} [argPos] The argument positions of the new function. + * @param {number} [ary] The arity cap of `func`. + * @param {number} [arity] The arity of `func`. + * @returns {Function} Returns the new wrapped function. + */ + function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) { + var isAry = bitmask & WRAP_ARY_FLAG, + isBind = bitmask & WRAP_BIND_FLAG, + isBindKey = bitmask & WRAP_BIND_KEY_FLAG, + isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG), + isFlip = bitmask & WRAP_FLIP_FLAG, + Ctor = isBindKey ? undefined : createCtor(func); - // Either this is the first call, activity has stopped and we're at the - // trailing edge, the system time has gone backwards and we're treating - // it as the trailing edge, or we've hit the `maxWait` limit. - return (lastCallTime === undefined || (timeSinceLastCall >= wait) || - (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait)); - } + function wrapper() { + var length = arguments.length, + args = Array(length), + index = length; - function timerExpired() { - var time = now(); - if (shouldInvoke(time)) { - return trailingEdge(time); + while (index--) { + args[index] = arguments[index]; } - // Restart the timer. - timerId = setTimeout(timerExpired, remainingWait(time)); - } - - function trailingEdge(time) { - timerId = undefined; - - // Only invoke if we have `lastArgs` which means `func` has been - // debounced at least once. - if (trailing && lastArgs) { - return invokeFunc(time); + if (isCurried) { + var placeholder = getHolder(wrapper), + holdersCount = countHolders(args, placeholder); } - lastArgs = lastThis = undefined; - return result; - } - - function cancel() { - if (timerId !== undefined) { - clearTimeout(timerId); + if (partials) { + args = composeArgs(args, partials, holders, isCurried); } - lastInvokeTime = 0; - lastArgs = lastCallTime = lastThis = timerId = undefined; - } + if (partialsRight) { + args = composeArgsRight(args, partialsRight, holdersRight, isCurried); + } + length -= holdersCount; + if (isCurried && length < arity) { + var newHolders = replaceHolders(args, placeholder); + return createRecurry( + func, bitmask, createHybrid, wrapper.placeholder, thisArg, + args, newHolders, argPos, ary, arity - length + ); + } + var thisBinding = isBind ? thisArg : this, + fn = isBindKey ? thisBinding[func] : func; - function flush() { - return timerId === undefined ? result : trailingEdge(now()); + length = args.length; + if (argPos) { + args = reorder(args, argPos); + } else if (isFlip && length > 1) { + args.reverse(); + } + if (isAry && ary < length) { + args.length = ary; + } + if (this && this !== root && this instanceof wrapper) { + fn = Ctor || createCtor(fn); + } + return fn.apply(thisBinding, args); } + return wrapper; + } - function debounced() { - var time = now(), - isInvoking = shouldInvoke(time); - - lastArgs = arguments; - lastThis = this; - lastCallTime = time; + /** + * Creates a function like `_.invertBy`. + * + * @private + * @param {Function} setter The function to set accumulator values. + * @param {Function} toIteratee The function to resolve iteratees. + * @returns {Function} Returns the new inverter function. + */ + function createInverter(setter, toIteratee) { + return function(object, iteratee) { + return baseInverter(object, setter, toIteratee(iteratee), {}); + }; + } - if (isInvoking) { - if (timerId === undefined) { - return leadingEdge(lastCallTime); + /** + * Creates a function that performs a mathematical operation on two values. + * + * @private + * @param {Function} operator The function to perform the operation. + * @param {number} [defaultValue] The value used for `undefined` arguments. + * @returns {Function} Returns the new mathematical operation function. + */ + function createMathOperation(operator, defaultValue) { + return function(value, other) { + var result; + if (value === undefined && other === undefined) { + return defaultValue; + } + if (value !== undefined) { + result = value; + } + if (other !== undefined) { + if (result === undefined) { + return other; } - if (maxing) { - // Handle invocations in a tight loop. - clearTimeout(timerId); - timerId = setTimeout(timerExpired, wait); - return invokeFunc(lastCallTime); + if (typeof value == 'string' || typeof other == 'string') { + value = baseToString(value); + other = baseToString(other); + } else { + value = baseToNumber(value); + other = baseToNumber(other); } - } - if (timerId === undefined) { - timerId = setTimeout(timerExpired, wait); + result = operator(value, other); } return result; - } - debounced.cancel = cancel; - debounced.flush = flush; - return debounced; + }; } /** - * Defers invoking the `func` until the current call stack has cleared. Any - * additional arguments are provided to `func` when it's invoked. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to defer. - * @param {...*} [args] The arguments to invoke `func` with. - * @returns {number} Returns the timer id. - * @example + * Creates a function like `_.over`. * - * _.defer(function(text) { - * console.log(text); - * }, 'deferred'); - * // => Logs 'deferred' after one millisecond. + * @private + * @param {Function} arrayFunc The function to iterate over iteratees. + * @returns {Function} Returns the new over function. */ - var defer = baseRest(function(func, args) { - return baseDelay(func, 1, args); - }); + function createOver(arrayFunc) { + return flatRest(function(iteratees) { + iteratees = arrayMap(iteratees, baseUnary(getIteratee())); + return baseRest(function(args) { + var thisArg = this; + return arrayFunc(iteratees, function(iteratee) { + return apply(iteratee, thisArg, args); + }); + }); + }); + } /** - * Invokes `func` after `wait` milliseconds. Any additional arguments are - * provided to `func` when it's invoked. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to delay. - * @param {number} wait The number of milliseconds to delay invocation. - * @param {...*} [args] The arguments to invoke `func` with. - * @returns {number} Returns the timer id. - * @example + * Creates the padding for `string` based on `length`. The `chars` string + * is truncated if the number of characters exceeds `length`. * - * _.delay(function(text) { - * console.log(text); - * }, 1000, 'later'); - * // => Logs 'later' after one second. + * @private + * @param {number} length The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padding for `string`. */ - var delay = baseRest(function(func, wait, args) { - return baseDelay(func, toNumber(wait) || 0, args); - }); + function createPadding(length, chars) { + chars = chars === undefined ? ' ' : baseToString(chars); + + var charsLength = chars.length; + if (charsLength < 2) { + return charsLength ? baseRepeat(chars, length) : chars; + } + var result = baseRepeat(chars, nativeCeil(length / stringSize(chars))); + return hasUnicode(chars) + ? castSlice(stringToArray(result), 0, length).join('') + : result.slice(0, length); + } /** - * Creates a function that invokes `func` with arguments reversed. + * Creates a function that wraps `func` to invoke it with the `this` binding + * of `thisArg` and `partials` prepended to the arguments it receives. * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Function - * @param {Function} func The function to flip arguments for. - * @returns {Function} Returns the new flipped function. - * @example + * @private + * @param {Function} func The function to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {*} thisArg The `this` binding of `func`. + * @param {Array} partials The arguments to prepend to those provided to + * the new function. + * @returns {Function} Returns the new wrapped function. + */ + function createPartial(func, bitmask, thisArg, partials) { + var isBind = bitmask & WRAP_BIND_FLAG, + Ctor = createCtor(func); + + function wrapper() { + var argsIndex = -1, + argsLength = arguments.length, + leftIndex = -1, + leftLength = partials.length, + args = Array(leftLength + argsLength), + fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; + + while (++leftIndex < leftLength) { + args[leftIndex] = partials[leftIndex]; + } + while (argsLength--) { + args[leftIndex++] = arguments[++argsIndex]; + } + return apply(fn, isBind ? thisArg : this, args); + } + return wrapper; + } + + /** + * Creates a `_.range` or `_.rangeRight` function. * - * var flipped = _.flip(function() { - * return _.toArray(arguments); - * }); + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new range function. + */ + function createRange(fromRight) { + return function(start, end, step) { + if (step && typeof step != 'number' && isIterateeCall(start, end, step)) { + end = step = undefined; + } + // Ensure the sign of `-0` is preserved. + start = toFinite(start); + if (end === undefined) { + end = start; + start = 0; + } else { + end = toFinite(end); + } + step = step === undefined ? (start < end ? 1 : -1) : toFinite(step); + return baseRange(start, end, step, fromRight); + }; + } + + /** + * Creates a function that performs a relational operation on two values. * - * flipped('a', 'b', 'c', 'd'); - * // => ['d', 'c', 'b', 'a'] + * @private + * @param {Function} operator The function to perform the operation. + * @returns {Function} Returns the new relational operation function. */ - function flip(func) { - return createWrap(func, WRAP_FLIP_FLAG); + function createRelationalOperation(operator) { + return function(value, other) { + if (!(typeof value == 'string' && typeof other == 'string')) { + value = toNumber(value); + other = toNumber(other); + } + return operator(value, other); + }; } /** - * Creates a function that memoizes the result of `func`. If `resolver` is - * provided, it determines the cache key for storing the result based on the - * arguments provided to the memoized function. By default, the first argument - * provided to the memoized function is used as the map cache key. The `func` - * is invoked with the `this` binding of the memoized function. - * - * **Note:** The cache is exposed as the `cache` property on the memoized - * function. Its creation may be customized by replacing the `_.memoize.Cache` - * constructor with one whose instances implement the - * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) - * method interface of `clear`, `delete`, `get`, `has`, and `set`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to have its output memoized. - * @param {Function} [resolver] The function to resolve the cache key. - * @returns {Function} Returns the new memoized function. - * @example - * - * var object = { 'a': 1, 'b': 2 }; - * var other = { 'c': 3, 'd': 4 }; - * - * var values = _.memoize(_.values); - * values(object); - * // => [1, 2] - * - * values(other); - * // => [3, 4] - * - * object.a = 2; - * values(object); - * // => [1, 2] - * - * // Modify the result cache. - * values.cache.set(object, ['a', 'b']); - * values(object); - * // => ['a', 'b'] + * Creates a function that wraps `func` to continue currying. * - * // Replace `_.memoize.Cache`. - * _.memoize.Cache = WeakMap; + * @private + * @param {Function} func The function to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {Function} wrapFunc The function to create the `func` wrapper. + * @param {*} placeholder The placeholder value. + * @param {*} [thisArg] The `this` binding of `func`. + * @param {Array} [partials] The arguments to prepend to those provided to + * the new function. + * @param {Array} [holders] The `partials` placeholder indexes. + * @param {Array} [argPos] The argument positions of the new function. + * @param {number} [ary] The arity cap of `func`. + * @param {number} [arity] The arity of `func`. + * @returns {Function} Returns the new wrapped function. */ - function memoize(func, resolver) { - if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { - throw new TypeError(FUNC_ERROR_TEXT); + function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) { + var isCurry = bitmask & WRAP_CURRY_FLAG, + newHolders = isCurry ? holders : undefined, + newHoldersRight = isCurry ? undefined : holders, + newPartials = isCurry ? partials : undefined, + newPartialsRight = isCurry ? undefined : partials; + + bitmask |= (isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG); + bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG); + + if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) { + bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG); } - var memoized = function() { - var args = arguments, - key = resolver ? resolver.apply(this, args) : args[0], - cache = memoized.cache; + var newData = [ + func, bitmask, thisArg, newPartials, newHolders, newPartialsRight, + newHoldersRight, argPos, ary, arity + ]; - if (cache.has(key)) { - return cache.get(key); - } - var result = func.apply(this, args); - memoized.cache = cache.set(key, result) || cache; - return result; - }; - memoized.cache = new (memoize.Cache || MapCache); - return memoized; + var result = wrapFunc.apply(undefined, newData); + if (isLaziable(func)) { + setData(result, newData); + } + result.placeholder = placeholder; + return setWrapToString(result, func, bitmask); } - // Expose `MapCache`. - memoize.Cache = MapCache; - /** - * Creates a function that negates the result of the predicate `func`. The - * `func` predicate is invoked with the `this` binding and arguments of the - * created function. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Function - * @param {Function} predicate The predicate to negate. - * @returns {Function} Returns the new negated function. - * @example - * - * function isEven(n) { - * return n % 2 == 0; - * } + * Creates a function like `_.round`. * - * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven)); - * // => [1, 3, 5] + * @private + * @param {string} methodName The name of the `Math` method to use when rounding. + * @returns {Function} Returns the new round function. */ - function negate(predicate) { - if (typeof predicate != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - return function() { - var args = arguments; - switch (args.length) { - case 0: return !predicate.call(this); - case 1: return !predicate.call(this, args[0]); - case 2: return !predicate.call(this, args[0], args[1]); - case 3: return !predicate.call(this, args[0], args[1], args[2]); + function createRound(methodName) { + var func = Math[methodName]; + return function(number, precision) { + number = toNumber(number); + precision = precision == null ? 0 : nativeMin(toInteger(precision), 292); + if (precision && nativeIsFinite(number)) { + // Shift with exponential notation to avoid floating-point issues. + // See [MDN](https://mdn.io/round#Examples) for more details. + var pair = (toString(number) + 'e').split('e'), + value = func(pair[0] + 'e' + (+pair[1] + precision)); + + pair = (toString(value) + 'e').split('e'); + return +(pair[0] + 'e' + (+pair[1] - precision)); } - return !predicate.apply(this, args); + return func(number); }; } /** - * Creates a function that is restricted to invoking `func` once. Repeat calls - * to the function return the value of the first invocation. The `func` is - * invoked with the `this` binding and arguments of the created function. + * Creates a set object of `values`. * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to restrict. - * @returns {Function} Returns the new restricted function. - * @example + * @private + * @param {Array} values The values to add to the set. + * @returns {Object} Returns the new set. + */ + var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) { + return new Set(values); + }; + + /** + * Creates a `_.toPairs` or `_.toPairsIn` function. * - * var initialize = _.once(createApplication); - * initialize(); - * initialize(); - * // => `createApplication` is invoked once + * @private + * @param {Function} keysFunc The function to get the keys of a given object. + * @returns {Function} Returns the new pairs function. */ - function once(func) { - return before(2, func); + function createToPairs(keysFunc) { + return function(object) { + var tag = getTag(object); + if (tag == mapTag) { + return mapToArray(object); + } + if (tag == setTag) { + return setToPairs(object); + } + return baseToPairs(object, keysFunc(object)); + }; } /** - * Creates a function that invokes `func` with its arguments transformed. - * - * @static - * @since 4.0.0 - * @memberOf _ - * @category Function - * @param {Function} func The function to wrap. - * @param {...(Function|Function[])} [transforms=[_.identity]] - * The argument transforms. - * @returns {Function} Returns the new function. - * @example - * - * function doubled(n) { - * return n * 2; - * } - * - * function square(n) { - * return n * n; - * } - * - * var func = _.overArgs(function(x, y) { - * return [x, y]; - * }, [square, doubled]); - * - * func(9, 3); - * // => [81, 6] + * Creates a function that either curries or invokes `func` with optional + * `this` binding and partially applied arguments. * - * func(10, 5); - * // => [100, 10] + * @private + * @param {Function|string} func The function or method name to wrap. + * @param {number} bitmask The bitmask flags. + * 1 - `_.bind` + * 2 - `_.bindKey` + * 4 - `_.curry` or `_.curryRight` of a bound function + * 8 - `_.curry` + * 16 - `_.curryRight` + * 32 - `_.partial` + * 64 - `_.partialRight` + * 128 - `_.rearg` + * 256 - `_.ary` + * 512 - `_.flip` + * @param {*} [thisArg] The `this` binding of `func`. + * @param {Array} [partials] The arguments to be partially applied. + * @param {Array} [holders] The `partials` placeholder indexes. + * @param {Array} [argPos] The argument positions of the new function. + * @param {number} [ary] The arity cap of `func`. + * @param {number} [arity] The arity of `func`. + * @returns {Function} Returns the new wrapped function. */ - var overArgs = castRest(function(func, transforms) { - transforms = (transforms.length == 1 && isArray(transforms[0])) - ? arrayMap(transforms[0], baseUnary(getIteratee())) - : arrayMap(baseFlatten(transforms, 1), baseUnary(getIteratee())); + function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) { + var isBindKey = bitmask & WRAP_BIND_KEY_FLAG; + if (!isBindKey && typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + var length = partials ? partials.length : 0; + if (!length) { + bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG); + partials = holders = undefined; + } + ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0); + arity = arity === undefined ? arity : toInteger(arity); + length -= holders ? holders.length : 0; - var funcsLength = transforms.length; - return baseRest(function(args) { - var index = -1, - length = nativeMin(args.length, funcsLength); + if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) { + var partialsRight = partials, + holdersRight = holders; - while (++index < length) { - args[index] = transforms[index].call(this, args[index]); - } - return apply(func, this, args); - }); - }); + partials = holders = undefined; + } + var data = isBindKey ? undefined : getData(func); + + var newData = [ + func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, + argPos, ary, arity + ]; + + if (data) { + mergeData(newData, data); + } + func = newData[0]; + bitmask = newData[1]; + thisArg = newData[2]; + partials = newData[3]; + holders = newData[4]; + arity = newData[9] = newData[9] === undefined + ? (isBindKey ? 0 : func.length) + : nativeMax(newData[9] - length, 0); + + if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) { + bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG); + } + if (!bitmask || bitmask == WRAP_BIND_FLAG) { + var result = createBind(func, bitmask, thisArg); + } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) { + result = createCurry(func, bitmask, arity); + } else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) { + result = createPartial(func, bitmask, thisArg, partials); + } else { + result = createHybrid.apply(undefined, newData); + } + var setter = data ? baseSetData : setData; + return setWrapToString(setter(result, newData), func, bitmask); + } /** - * Creates a function that invokes `func` with `partials` prepended to the - * arguments it receives. This method is like `_.bind` except it does **not** - * alter the `this` binding. - * - * The `_.partial.placeholder` value, which defaults to `_` in monolithic - * builds, may be used as a placeholder for partially applied arguments. - * - * **Note:** This method doesn't set the "length" property of partially - * applied functions. - * - * @static - * @memberOf _ - * @since 0.2.0 - * @category Function - * @param {Function} func The function to partially apply arguments to. - * @param {...*} [partials] The arguments to be partially applied. - * @returns {Function} Returns the new partially applied function. - * @example - * - * function greet(greeting, name) { - * return greeting + ' ' + name; - * } - * - * var sayHelloTo = _.partial(greet, 'hello'); - * sayHelloTo('fred'); - * // => 'hello fred' + * Used by `_.defaults` to customize its `_.assignIn` use to assign properties + * of source objects to the destination object for all destination properties + * that resolve to `undefined`. * - * // Partially applied with placeholders. - * var greetFred = _.partial(greet, _, 'fred'); - * greetFred('hi'); - * // => 'hi fred' + * @private + * @param {*} objValue The destination value. + * @param {*} srcValue The source value. + * @param {string} key The key of the property to assign. + * @param {Object} object The parent object of `objValue`. + * @returns {*} Returns the value to assign. */ - var partial = baseRest(function(func, partials) { - var holders = replaceHolders(partials, getHolder(partial)); - return createWrap(func, WRAP_PARTIAL_FLAG, undefined, partials, holders); - }); + function customDefaultsAssignIn(objValue, srcValue, key, object) { + if (objValue === undefined || + (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) { + return srcValue; + } + return objValue; + } /** - * This method is like `_.partial` except that partially applied arguments - * are appended to the arguments it receives. - * - * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic - * builds, may be used as a placeholder for partially applied arguments. - * - * **Note:** This method doesn't set the "length" property of partially - * applied functions. - * - * @static - * @memberOf _ - * @since 1.0.0 - * @category Function - * @param {Function} func The function to partially apply arguments to. - * @param {...*} [partials] The arguments to be partially applied. - * @returns {Function} Returns the new partially applied function. - * @example - * - * function greet(greeting, name) { - * return greeting + ' ' + name; - * } - * - * var greetFred = _.partialRight(greet, 'fred'); - * greetFred('hi'); - * // => 'hi fred' + * Used by `_.defaultsDeep` to customize its `_.merge` use to merge source + * objects into destination objects that are passed thru. * - * // Partially applied with placeholders. - * var sayHelloTo = _.partialRight(greet, 'hello', _); - * sayHelloTo('fred'); - * // => 'hello fred' + * @private + * @param {*} objValue The destination value. + * @param {*} srcValue The source value. + * @param {string} key The key of the property to merge. + * @param {Object} object The parent object of `objValue`. + * @param {Object} source The parent object of `srcValue`. + * @param {Object} [stack] Tracks traversed source values and their merged + * counterparts. + * @returns {*} Returns the value to assign. */ - var partialRight = baseRest(function(func, partials) { - var holders = replaceHolders(partials, getHolder(partialRight)); - return createWrap(func, WRAP_PARTIAL_RIGHT_FLAG, undefined, partials, holders); - }); + function customDefaultsMerge(objValue, srcValue, key, object, source, stack) { + if (isObject(objValue) && isObject(srcValue)) { + // Recursively merge objects and arrays (susceptible to call stack limits). + stack.set(srcValue, objValue); + baseMerge(objValue, srcValue, undefined, customDefaultsMerge, stack); + stack['delete'](srcValue); + } + return objValue; + } /** - * Creates a function that invokes `func` with arguments arranged according - * to the specified `indexes` where the argument value at the first index is - * provided as the first argument, the argument value at the second index is - * provided as the second argument, and so on. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Function - * @param {Function} func The function to rearrange arguments for. - * @param {...(number|number[])} indexes The arranged argument indexes. - * @returns {Function} Returns the new function. - * @example + * Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain + * objects. * - * var rearged = _.rearg(function(a, b, c) { - * return [a, b, c]; - * }, [2, 0, 1]); + * @private + * @param {*} value The value to inspect. + * @param {string} key The key of the property to inspect. + * @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`. + */ + function customOmitClone(value) { + return isPlainObject(value) ? undefined : value; + } + + /** + * A specialized version of `baseIsEqualDeep` for arrays with support for + * partial deep comparisons. * - * rearged('b', 'c', 'a') - * // => ['a', 'b', 'c'] + * @private + * @param {Array} array The array to compare. + * @param {Array} other The other array to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `array` and `other` objects. + * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. */ - var rearg = flatRest(function(func, indexes) { - return createWrap(func, WRAP_REARG_FLAG, undefined, undefined, undefined, indexes); - }); + function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG, + arrLength = array.length, + othLength = other.length; + + if (arrLength != othLength && !(isPartial && othLength > arrLength)) { + return false; + } + // Check that cyclic values are equal. + var arrStacked = stack.get(array); + var othStacked = stack.get(other); + if (arrStacked && othStacked) { + return arrStacked == other && othStacked == array; + } + var index = -1, + result = true, + seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined; + + stack.set(array, other); + stack.set(other, array); + + // Ignore non-index properties. + while (++index < arrLength) { + var arrValue = array[index], + othValue = other[index]; + + if (customizer) { + var compared = isPartial + ? customizer(othValue, arrValue, index, other, array, stack) + : customizer(arrValue, othValue, index, array, other, stack); + } + if (compared !== undefined) { + if (compared) { + continue; + } + result = false; + break; + } + // Recursively compare arrays (susceptible to call stack limits). + if (seen) { + if (!arraySome(other, function(othValue, othIndex) { + if (!cacheHas(seen, othIndex) && + (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { + return seen.push(othIndex); + } + })) { + result = false; + break; + } + } else if (!( + arrValue === othValue || + equalFunc(arrValue, othValue, bitmask, customizer, stack) + )) { + result = false; + break; + } + } + stack['delete'](array); + stack['delete'](other); + return result; + } /** - * Creates a function that invokes `func` with the `this` binding of the - * created function and arguments from `start` and beyond provided as - * an array. - * - * **Note:** This method is based on the - * [rest parameter](https://mdn.io/rest_parameters). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Function - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @returns {Function} Returns the new function. - * @example + * A specialized version of `baseIsEqualDeep` for comparing objects of + * the same `toStringTag`. * - * var say = _.rest(function(what, names) { - * return what + ' ' + _.initial(names).join(', ') + - * (_.size(names) > 1 ? ', & ' : '') + _.last(names); - * }); + * **Note:** This function only supports comparing values with tags of + * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. * - * say('hello', 'fred', 'barney', 'pebbles'); - * // => 'hello fred, barney, & pebbles' + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {string} tag The `toStringTag` of the objects to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ - function rest(func, start) { - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); + function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { + switch (tag) { + case dataViewTag: + if ((object.byteLength != other.byteLength) || + (object.byteOffset != other.byteOffset)) { + return false; + } + object = object.buffer; + other = other.buffer; + + case arrayBufferTag: + if ((object.byteLength != other.byteLength) || + !equalFunc(new Uint8Array(object), new Uint8Array(other))) { + return false; + } + return true; + + case boolTag: + case dateTag: + case numberTag: + // Coerce booleans to `1` or `0` and dates to milliseconds. + // Invalid dates are coerced to `NaN`. + return eq(+object, +other); + + case errorTag: + return object.name == other.name && object.message == other.message; + + case regexpTag: + case stringTag: + // Coerce regexes to strings and treat strings, primitives and objects, + // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring + // for more details. + return object == (other + ''); + + case mapTag: + var convert = mapToArray; + + case setTag: + var isPartial = bitmask & COMPARE_PARTIAL_FLAG; + convert || (convert = setToArray); + + if (object.size != other.size && !isPartial) { + return false; + } + // Assume cyclic values are equal. + var stacked = stack.get(object); + if (stacked) { + return stacked == other; + } + bitmask |= COMPARE_UNORDERED_FLAG; + + // Recursively compare objects (susceptible to call stack limits). + stack.set(object, other); + var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); + stack['delete'](object); + return result; + + case symbolTag: + if (symbolValueOf) { + return symbolValueOf.call(object) == symbolValueOf.call(other); + } } - start = start === undefined ? start : toInteger(start); - return baseRest(func, start); + return false; } /** - * Creates a function that invokes `func` with the `this` binding of the - * create function and an array of arguments much like - * [`Function#apply`](http://www.ecma-international.org/ecma-262/7.0/#sec-function.prototype.apply). - * - * **Note:** This method is based on the - * [spread operator](https://mdn.io/spread_operator). - * - * @static - * @memberOf _ - * @since 3.2.0 - * @category Function - * @param {Function} func The function to spread arguments over. - * @param {number} [start=0] The start position of the spread. - * @returns {Function} Returns the new function. - * @example - * - * var say = _.spread(function(who, what) { - * return who + ' says ' + what; - * }); - * - * say(['fred', 'hello']); - * // => 'fred says hello' - * - * var numbers = Promise.all([ - * Promise.resolve(40), - * Promise.resolve(36) - * ]); + * A specialized version of `baseIsEqualDeep` for objects with support for + * partial deep comparisons. * - * numbers.then(_.spread(function(x, y) { - * return x + y; - * })); - * // => a Promise of 76 + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ - function spread(func, start) { - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - start = start == null ? 0 : nativeMax(toInteger(start), 0); - return baseRest(function(args) { - var array = args[start], - otherArgs = castSlice(args, 0, start); + function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG, + objProps = getAllKeys(object), + objLength = objProps.length, + othProps = getAllKeys(other), + othLength = othProps.length; - if (array) { - arrayPush(otherArgs, array); + if (objLength != othLength && !isPartial) { + return false; + } + var index = objLength; + while (index--) { + var key = objProps[index]; + if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { + return false; } - return apply(func, this, otherArgs); - }); - } + } + // Check that cyclic values are equal. + var objStacked = stack.get(object); + var othStacked = stack.get(other); + if (objStacked && othStacked) { + return objStacked == other && othStacked == object; + } + var result = true; + stack.set(object, other); + stack.set(other, object); - /** - * Creates a throttled function that only invokes `func` at most once per - * every `wait` milliseconds. The throttled function comes with a `cancel` - * method to cancel delayed `func` invocations and a `flush` method to - * immediately invoke them. Provide `options` to indicate whether `func` - * should be invoked on the leading and/or trailing edge of the `wait` - * timeout. The `func` is invoked with the last arguments provided to the - * throttled function. Subsequent calls to the throttled function return the - * result of the last `func` invocation. - * - * **Note:** If `leading` and `trailing` options are `true`, `func` is - * invoked on the trailing edge of the timeout only if the throttled function - * is invoked more than once during the `wait` timeout. - * - * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred - * until to the next tick, similar to `setTimeout` with a timeout of `0`. - * - * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) - * for details over the differences between `_.throttle` and `_.debounce`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to throttle. - * @param {number} [wait=0] The number of milliseconds to throttle invocations to. - * @param {Object} [options={}] The options object. - * @param {boolean} [options.leading=true] - * Specify invoking on the leading edge of the timeout. - * @param {boolean} [options.trailing=true] - * Specify invoking on the trailing edge of the timeout. - * @returns {Function} Returns the new throttled function. - * @example - * - * // Avoid excessively updating the position while scrolling. - * jQuery(window).on('scroll', _.throttle(updatePosition, 100)); - * - * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes. - * var throttled = _.throttle(renewToken, 300000, { 'trailing': false }); - * jQuery(element).on('click', throttled); - * - * // Cancel the trailing throttled invocation. - * jQuery(window).on('popstate', throttled.cancel); - */ - function throttle(func, wait, options) { - var leading = true, - trailing = true; + var skipCtor = isPartial; + while (++index < objLength) { + key = objProps[index]; + var objValue = object[key], + othValue = other[key]; - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); + if (customizer) { + var compared = isPartial + ? customizer(othValue, objValue, key, other, object, stack) + : customizer(objValue, othValue, key, object, other, stack); + } + // Recursively compare objects (susceptible to call stack limits). + if (!(compared === undefined + ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) + : compared + )) { + result = false; + break; + } + skipCtor || (skipCtor = key == 'constructor'); } - if (isObject(options)) { - leading = 'leading' in options ? !!options.leading : leading; - trailing = 'trailing' in options ? !!options.trailing : trailing; + if (result && !skipCtor) { + var objCtor = object.constructor, + othCtor = other.constructor; + + // Non `Object` object instances with different constructors are not equal. + if (objCtor != othCtor && + ('constructor' in object && 'constructor' in other) && + !(typeof objCtor == 'function' && objCtor instanceof objCtor && + typeof othCtor == 'function' && othCtor instanceof othCtor)) { + result = false; + } } - return debounce(func, wait, { - 'leading': leading, - 'maxWait': wait, - 'trailing': trailing - }); + stack['delete'](object); + stack['delete'](other); + return result; } /** - * Creates a function that accepts up to one argument, ignoring any - * additional arguments. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Function - * @param {Function} func The function to cap arguments for. - * @returns {Function} Returns the new capped function. - * @example + * A specialized version of `baseRest` which flattens the rest array. * - * _.map(['6', '8', '10'], _.unary(parseInt)); - * // => [6, 8, 10] + * @private + * @param {Function} func The function to apply a rest parameter to. + * @returns {Function} Returns the new function. */ - function unary(func) { - return ary(func, 1); + function flatRest(func) { + return setToString(overRest(func, undefined, flatten), func + ''); } /** - * Creates a function that provides `value` to `wrapper` as its first - * argument. Any additional arguments provided to the function are appended - * to those provided to the `wrapper`. The wrapper is invoked with the `this` - * binding of the created function. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {*} value The value to wrap. - * @param {Function} [wrapper=identity] The wrapper function. - * @returns {Function} Returns the new function. - * @example - * - * var p = _.wrap(_.escape, function(func, text) { - * return '

' + func(text) + '

'; - * }); + * Creates an array of own enumerable property names and symbols of `object`. * - * p('fred, barney, & pebbles'); - * // => '

fred, barney, & pebbles

' + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names and symbols. */ - function wrap(value, wrapper) { - return partial(castFunction(wrapper), value); + function getAllKeys(object) { + return baseGetAllKeys(object, keys, getSymbols); } - /*------------------------------------------------------------------------*/ - /** - * Casts `value` as an array if it's not one. - * - * @static - * @memberOf _ - * @since 4.4.0 - * @category Lang - * @param {*} value The value to inspect. - * @returns {Array} Returns the cast array. - * @example - * - * _.castArray(1); - * // => [1] - * - * _.castArray({ 'a': 1 }); - * // => [{ 'a': 1 }] - * - * _.castArray('abc'); - * // => ['abc'] - * - * _.castArray(null); - * // => [null] - * - * _.castArray(undefined); - * // => [undefined] - * - * _.castArray(); - * // => [] + * Creates an array of own and inherited enumerable property names and + * symbols of `object`. * - * var array = [1, 2, 3]; - * console.log(_.castArray(array) === array); - * // => true + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names and symbols. */ - function castArray() { - if (!arguments.length) { - return []; - } - var value = arguments[0]; - return isArray(value) ? value : [value]; + function getAllKeysIn(object) { + return baseGetAllKeys(object, keysIn, getSymbolsIn); } /** - * Creates a shallow clone of `value`. - * - * **Note:** This method is loosely based on the - * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm) - * and supports cloning arrays, array buffers, booleans, date objects, maps, - * numbers, `Object` objects, regexes, sets, strings, symbols, and typed - * arrays. The own enumerable properties of `arguments` objects are cloned - * as plain objects. An empty object is returned for uncloneable values such - * as error objects, functions, DOM nodes, and WeakMaps. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to clone. - * @returns {*} Returns the cloned value. - * @see _.cloneDeep - * @example - * - * var objects = [{ 'a': 1 }, { 'b': 2 }]; + * Gets metadata for `func`. * - * var shallow = _.clone(objects); - * console.log(shallow[0] === objects[0]); - * // => true + * @private + * @param {Function} func The function to query. + * @returns {*} Returns the metadata for `func`. */ - function clone(value) { - return baseClone(value, CLONE_SYMBOLS_FLAG); - } + var getData = !metaMap ? noop : function(func) { + return metaMap.get(func); + }; /** - * This method is like `_.clone` except that it accepts `customizer` which - * is invoked to produce the cloned value. If `customizer` returns `undefined`, - * cloning is handled by the method instead. The `customizer` is invoked with - * up to four arguments; (value [, index|key, object, stack]). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to clone. - * @param {Function} [customizer] The function to customize cloning. - * @returns {*} Returns the cloned value. - * @see _.cloneDeepWith - * @example - * - * function customizer(value) { - * if (_.isElement(value)) { - * return value.cloneNode(false); - * } - * } - * - * var el = _.cloneWith(document.body, customizer); + * Gets the name of `func`. * - * console.log(el === document.body); - * // => false - * console.log(el.nodeName); - * // => 'BODY' - * console.log(el.childNodes.length); - * // => 0 + * @private + * @param {Function} func The function to query. + * @returns {string} Returns the function name. */ - function cloneWith(value, customizer) { - customizer = typeof customizer == 'function' ? customizer : undefined; - return baseClone(value, CLONE_SYMBOLS_FLAG, customizer); + function getFuncName(func) { + var result = (func.name + ''), + array = realNames[result], + length = hasOwnProperty.call(realNames, result) ? array.length : 0; + + while (length--) { + var data = array[length], + otherFunc = data.func; + if (otherFunc == null || otherFunc == func) { + return data.name; + } + } + return result; } /** - * This method is like `_.clone` except that it recursively clones `value`. - * - * @static - * @memberOf _ - * @since 1.0.0 - * @category Lang - * @param {*} value The value to recursively clone. - * @returns {*} Returns the deep cloned value. - * @see _.clone - * @example - * - * var objects = [{ 'a': 1 }, { 'b': 2 }]; + * Gets the argument placeholder value for `func`. * - * var deep = _.cloneDeep(objects); - * console.log(deep[0] === objects[0]); - * // => false + * @private + * @param {Function} func The function to inspect. + * @returns {*} Returns the placeholder value. */ - function cloneDeep(value) { - return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG); + function getHolder(func) { + var object = hasOwnProperty.call(lodash, 'placeholder') ? lodash : func; + return object.placeholder; } /** - * This method is like `_.cloneWith` except that it recursively clones `value`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to recursively clone. - * @param {Function} [customizer] The function to customize cloning. - * @returns {*} Returns the deep cloned value. - * @see _.cloneWith - * @example - * - * function customizer(value) { - * if (_.isElement(value)) { - * return value.cloneNode(true); - * } - * } - * - * var el = _.cloneDeepWith(document.body, customizer); + * Gets the appropriate "iteratee" function. If `_.iteratee` is customized, + * this function returns the custom method, otherwise it returns `baseIteratee`. + * If arguments are provided, the chosen function is invoked with them and + * its result is returned. * - * console.log(el === document.body); - * // => false - * console.log(el.nodeName); - * // => 'BODY' - * console.log(el.childNodes.length); - * // => 20 + * @private + * @param {*} [value] The value to convert to an iteratee. + * @param {number} [arity] The arity of the created iteratee. + * @returns {Function} Returns the chosen function or its result. */ - function cloneDeepWith(value, customizer) { - customizer = typeof customizer == 'function' ? customizer : undefined; - return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG, customizer); + function getIteratee() { + var result = lodash.iteratee || iteratee; + result = result === iteratee ? baseIteratee : result; + return arguments.length ? result(arguments[0], arguments[1]) : result; } /** - * Checks if `object` conforms to `source` by invoking the predicate - * properties of `source` with the corresponding property values of `object`. - * - * **Note:** This method is equivalent to `_.conforms` when `source` is - * partially applied. - * - * @static - * @memberOf _ - * @since 4.14.0 - * @category Lang - * @param {Object} object The object to inspect. - * @param {Object} source The object of property predicates to conform to. - * @returns {boolean} Returns `true` if `object` conforms, else `false`. - * @example - * - * var object = { 'a': 1, 'b': 2 }; - * - * _.conformsTo(object, { 'b': function(n) { return n > 1; } }); - * // => true + * Gets the data for `map`. * - * _.conformsTo(object, { 'b': function(n) { return n > 2; } }); - * // => false + * @private + * @param {Object} map The map to query. + * @param {string} key The reference key. + * @returns {*} Returns the map data. */ - function conformsTo(object, source) { - return source == null || baseConformsTo(object, source, keys(source)); + function getMapData(map, key) { + var data = map.__data__; + return isKeyable(key) + ? data[typeof key == 'string' ? 'string' : 'hash'] + : data.map; } /** - * Performs a - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * comparison between two values to determine if they are equivalent. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * var object = { 'a': 1 }; - * var other = { 'a': 1 }; - * - * _.eq(object, object); - * // => true - * - * _.eq(object, other); - * // => false - * - * _.eq('a', 'a'); - * // => true - * - * _.eq('a', Object('a')); - * // => false + * Gets the property names, values, and compare flags of `object`. * - * _.eq(NaN, NaN); - * // => true + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the match data of `object`. */ - function eq(value, other) { - return value === other || (value !== value && other !== other); + function getMatchData(object) { + var result = keys(object), + length = result.length; + + while (length--) { + var key = result[length], + value = object[key]; + + result[length] = [key, value, isStrictComparable(value)]; + } + return result; } /** - * Checks if `value` is greater than `other`. - * - * @static - * @memberOf _ - * @since 3.9.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if `value` is greater than `other`, - * else `false`. - * @see _.lt - * @example - * - * _.gt(3, 1); - * // => true - * - * _.gt(3, 3); - * // => false + * Gets the native function at `key` of `object`. * - * _.gt(1, 3); - * // => false + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the method to get. + * @returns {*} Returns the function if it's native, else `undefined`. */ - var gt = createRelationalOperation(baseGt); + function getNative(object, key) { + var value = getValue(object, key); + return baseIsNative(value) ? value : undefined; + } /** - * Checks if `value` is greater than or equal to `other`. - * - * @static - * @memberOf _ - * @since 3.9.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if `value` is greater than or equal to - * `other`, else `false`. - * @see _.lte - * @example - * - * _.gte(3, 1); - * // => true - * - * _.gte(3, 3); - * // => true + * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. * - * _.gte(1, 3); - * // => false + * @private + * @param {*} value The value to query. + * @returns {string} Returns the raw `toStringTag`. */ - var gte = createRelationalOperation(function(value, other) { - return value >= other; - }); + function getRawTag(value) { + var isOwn = hasOwnProperty.call(value, symToStringTag), + tag = value[symToStringTag]; + + try { + value[symToStringTag] = undefined; + var unmasked = true; + } catch (e) {} + + var result = nativeObjectToString.call(value); + if (unmasked) { + if (isOwn) { + value[symToStringTag] = tag; + } else { + delete value[symToStringTag]; + } + } + return result; + } /** - * Checks if `value` is likely an `arguments` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - * else `false`. - * @example - * - * _.isArguments(function() { return arguments; }()); - * // => true + * Creates an array of the own enumerable symbols of `object`. * - * _.isArguments([1, 2, 3]); - * // => false + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of symbols. */ - var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { - return isObjectLike(value) && hasOwnProperty.call(value, 'callee') && - !propertyIsEnumerable.call(value, 'callee'); + var getSymbols = !nativeGetSymbols ? stubArray : function(object) { + if (object == null) { + return []; + } + object = Object(object); + return arrayFilter(nativeGetSymbols(object), function(symbol) { + return propertyIsEnumerable.call(object, symbol); + }); }; /** - * Checks if `value` is classified as an `Array` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array, else `false`. - * @example - * - * _.isArray([1, 2, 3]); - * // => true - * - * _.isArray(document.body.children); - * // => false - * - * _.isArray('abc'); - * // => false + * Creates an array of the own and inherited enumerable symbols of `object`. * - * _.isArray(_.noop); - * // => false + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of symbols. */ - var isArray = Array.isArray; + var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) { + var result = []; + while (object) { + arrayPush(result, getSymbols(object)); + object = getPrototype(object); + } + return result; + }; /** - * Checks if `value` is classified as an `ArrayBuffer` object. - * - * @static - * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. - * @example - * - * _.isArrayBuffer(new ArrayBuffer(2)); - * // => true + * Gets the `toStringTag` of `value`. * - * _.isArrayBuffer(new Array(2)); - * // => false + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. */ - var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer; + var getTag = baseGetTag; + + // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. + if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || + (Map && getTag(new Map) != mapTag) || + (Promise && getTag(Promise.resolve()) != promiseTag) || + (Set && getTag(new Set) != setTag) || + (WeakMap && getTag(new WeakMap) != weakMapTag)) { + getTag = function(value) { + var result = baseGetTag(value), + Ctor = result == objectTag ? value.constructor : undefined, + ctorString = Ctor ? toSource(Ctor) : ''; + + if (ctorString) { + switch (ctorString) { + case dataViewCtorString: return dataViewTag; + case mapCtorString: return mapTag; + case promiseCtorString: return promiseTag; + case setCtorString: return setTag; + case weakMapCtorString: return weakMapTag; + } + } + return result; + }; + } /** - * Checks if `value` is array-like. A value is considered array-like if it's - * not a function and has a `value.length` that's an integer greater than or - * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is array-like, else `false`. - * @example - * - * _.isArrayLike([1, 2, 3]); - * // => true - * - * _.isArrayLike(document.body.children); - * // => true - * - * _.isArrayLike('abc'); - * // => true + * Gets the view, applying any `transforms` to the `start` and `end` positions. * - * _.isArrayLike(_.noop); - * // => false + * @private + * @param {number} start The start of the view. + * @param {number} end The end of the view. + * @param {Array} transforms The transformations to apply to the view. + * @returns {Object} Returns an object containing the `start` and `end` + * positions of the view. */ - function isArrayLike(value) { - return value != null && isLength(value.length) && !isFunction(value); + function getView(start, end, transforms) { + var index = -1, + length = transforms.length; + + while (++index < length) { + var data = transforms[index], + size = data.size; + + switch (data.type) { + case 'drop': start += size; break; + case 'dropRight': end -= size; break; + case 'take': end = nativeMin(end, start + size); break; + case 'takeRight': start = nativeMax(start, end - size); break; + } + } + return { 'start': start, 'end': end }; } /** - * This method is like `_.isArrayLike` except that it also checks if `value` - * is an object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array-like object, - * else `false`. - * @example - * - * _.isArrayLikeObject([1, 2, 3]); - * // => true - * - * _.isArrayLikeObject(document.body.children); - * // => true - * - * _.isArrayLikeObject('abc'); - * // => false + * Extracts wrapper details from the `source` body comment. * - * _.isArrayLikeObject(_.noop); - * // => false + * @private + * @param {string} source The source to inspect. + * @returns {Array} Returns the wrapper details. */ - function isArrayLikeObject(value) { - return isObjectLike(value) && isArrayLike(value); + function getWrapDetails(source) { + var match = source.match(reWrapDetails); + return match ? match[1].split(reSplitDetails) : []; } /** - * Checks if `value` is classified as a boolean primitive or object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a boolean, else `false`. - * @example - * - * _.isBoolean(false); - * // => true + * Checks if `path` exists on `object`. * - * _.isBoolean(null); - * // => false + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @param {Function} hasFunc The function to check properties. + * @returns {boolean} Returns `true` if `path` exists, else `false`. */ - function isBoolean(value) { - return value === true || value === false || - (isObjectLike(value) && baseGetTag(value) == boolTag); + function hasPath(object, path, hasFunc) { + path = castPath(path, object); + + var index = -1, + length = path.length, + result = false; + + while (++index < length) { + var key = toKey(path[index]); + if (!(result = object != null && hasFunc(object, key))) { + break; + } + object = object[key]; + } + if (result || ++index != length) { + return result; + } + length = object == null ? 0 : object.length; + return !!length && isLength(length) && isIndex(key, length) && + (isArray(object) || isArguments(object)); } /** - * Checks if `value` is a buffer. - * - * @static - * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. - * @example - * - * _.isBuffer(new Buffer(2)); - * // => true + * Initializes an array clone. * - * _.isBuffer(new Uint8Array(2)); - * // => false + * @private + * @param {Array} array The array to clone. + * @returns {Array} Returns the initialized clone. */ - var isBuffer = nativeIsBuffer || stubFalse; + function initCloneArray(array) { + var length = array.length, + result = new array.constructor(length); + + // Add properties assigned by `RegExp#exec`. + if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) { + result.index = array.index; + result.input = array.input; + } + return result; + } /** - * Checks if `value` is classified as a `Date` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a date object, else `false`. - * @example - * - * _.isDate(new Date); - * // => true + * Initializes an object clone. * - * _.isDate('Mon April 23 2012'); - * // => false + * @private + * @param {Object} object The object to clone. + * @returns {Object} Returns the initialized clone. */ - var isDate = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate; + function initCloneObject(object) { + return (typeof object.constructor == 'function' && !isPrototype(object)) + ? baseCreate(getPrototype(object)) + : {}; + } /** - * Checks if `value` is likely a DOM element. + * Initializes an object clone based on its `toStringTag`. * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`. - * @example + * **Note:** This function only supports cloning values with tags of + * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`. * - * _.isElement(document.body); - * // => true + * @private + * @param {Object} object The object to clone. + * @param {string} tag The `toStringTag` of the object to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the initialized clone. + */ + function initCloneByTag(object, tag, isDeep) { + var Ctor = object.constructor; + switch (tag) { + case arrayBufferTag: + return cloneArrayBuffer(object); + + case boolTag: + case dateTag: + return new Ctor(+object); + + case dataViewTag: + return cloneDataView(object, isDeep); + + case float32Tag: case float64Tag: + case int8Tag: case int16Tag: case int32Tag: + case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag: + return cloneTypedArray(object, isDeep); + + case mapTag: + return new Ctor; + + case numberTag: + case stringTag: + return new Ctor(object); + + case regexpTag: + return cloneRegExp(object); + + case setTag: + return new Ctor; + + case symbolTag: + return cloneSymbol(object); + } + } + + /** + * Inserts wrapper `details` in a comment at the top of the `source` body. * - * _.isElement(''); - * // => false + * @private + * @param {string} source The source to modify. + * @returns {Array} details The details to insert. + * @returns {string} Returns the modified source. */ - function isElement(value) { - return isObjectLike(value) && value.nodeType === 1 && !isPlainObject(value); + function insertWrapDetails(source, details) { + var length = details.length; + if (!length) { + return source; + } + var lastIndex = length - 1; + details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex]; + details = details.join(length > 2 ? ', ' : ' '); + return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n'); } /** - * Checks if `value` is an empty object, collection, map, or set. - * - * Objects are considered empty if they have no own enumerable string keyed - * properties. - * - * Array-like values such as `arguments` objects, arrays, buffers, strings, or - * jQuery-like collections are considered empty if they have a `length` of `0`. - * Similarly, maps and sets are considered empty if they have a `size` of `0`. + * Checks if `value` is a flattenable `arguments` object or array. * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang + * @private * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is empty, else `false`. - * @example - * - * _.isEmpty(null); - * // => true - * - * _.isEmpty(true); - * // => true - * - * _.isEmpty(1); - * // => true - * - * _.isEmpty([1, 2, 3]); - * // => false - * - * _.isEmpty({ 'a': 1 }); - * // => false + * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. */ - function isEmpty(value) { - if (value == null) { - return true; - } - if (isArrayLike(value) && - (isArray(value) || typeof value == 'string' || typeof value.splice == 'function' || - isBuffer(value) || isTypedArray(value) || isArguments(value))) { - return !value.length; - } - var tag = getTag(value); - if (tag == mapTag || tag == setTag) { - return !value.size; - } - if (isPrototype(value)) { - return !baseKeys(value).length; - } - for (var key in value) { - if (hasOwnProperty.call(value, key)) { - return false; - } - } - return true; + function isFlattenable(value) { + return isArray(value) || isArguments(value) || + !!(spreadableSymbol && value && value[spreadableSymbol]); } /** - * Performs a deep comparison between two values to determine if they are - * equivalent. - * - * **Note:** This method supports comparing arrays, array buffers, booleans, - * date objects, error objects, maps, numbers, `Object` objects, regexes, - * sets, strings, symbols, and typed arrays. `Object` objects are compared - * by their own, not inherited, enumerable properties. Functions and DOM - * nodes are compared by strict equality, i.e. `===`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * var object = { 'a': 1 }; - * var other = { 'a': 1 }; - * - * _.isEqual(object, other); - * // => true + * Checks if `value` is a valid array-like index. * - * object === other; - * // => false + * @private + * @param {*} value The value to check. + * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. + * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. */ - function isEqual(value, other) { - return baseIsEqual(value, other); + function isIndex(value, length) { + var type = typeof value; + length = length == null ? MAX_SAFE_INTEGER : length; + + return !!length && + (type == 'number' || + (type != 'symbol' && reIsUint.test(value))) && + (value > -1 && value % 1 == 0 && value < length); } /** - * This method is like `_.isEqual` except that it accepts `customizer` which - * is invoked to compare values. If `customizer` returns `undefined`, comparisons - * are handled by the method instead. The `customizer` is invoked with up to - * six arguments: (objValue, othValue [, index|key, object, other, stack]). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @param {Function} [customizer] The function to customize comparisons. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * function isGreeting(value) { - * return /^h(?:i|ello)$/.test(value); - * } - * - * function customizer(objValue, othValue) { - * if (isGreeting(objValue) && isGreeting(othValue)) { - * return true; - * } - * } - * - * var array = ['hello', 'goodbye']; - * var other = ['hi', 'goodbye']; + * Checks if the given arguments are from an iteratee call. * - * _.isEqualWith(array, other, customizer); - * // => true + * @private + * @param {*} value The potential iteratee value argument. + * @param {*} index The potential iteratee index or key argument. + * @param {*} object The potential iteratee object argument. + * @returns {boolean} Returns `true` if the arguments are from an iteratee call, + * else `false`. */ - function isEqualWith(value, other, customizer) { - customizer = typeof customizer == 'function' ? customizer : undefined; - var result = customizer ? customizer(value, other) : undefined; - return result === undefined ? baseIsEqual(value, other, undefined, customizer) : !!result; + function isIterateeCall(value, index, object) { + if (!isObject(object)) { + return false; + } + var type = typeof index; + if (type == 'number' + ? (isArrayLike(object) && isIndex(index, object.length)) + : (type == 'string' && index in object) + ) { + return eq(object[index], value); + } + return false; } /** - * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`, - * `SyntaxError`, `TypeError`, or `URIError` object. + * Checks if `value` is a property name and not a property path. * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Lang + * @private * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an error object, else `false`. - * @example - * - * _.isError(new Error); - * // => true - * - * _.isError(Error); - * // => false + * @param {Object} [object] The object to query keys on. + * @returns {boolean} Returns `true` if `value` is a property name, else `false`. */ - function isError(value) { - if (!isObjectLike(value)) { + function isKey(value, object) { + if (isArray(value)) { return false; } - var tag = baseGetTag(value); - return tag == errorTag || tag == domExcTag || - (typeof value.message == 'string' && typeof value.name == 'string' && !isPlainObject(value)); + var type = typeof value; + if (type == 'number' || type == 'symbol' || type == 'boolean' || + value == null || isSymbol(value)) { + return true; + } + return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || + (object != null && value in Object(object)); } /** - * Checks if `value` is a finite primitive number. - * - * **Note:** This method is based on - * [`Number.isFinite`](https://mdn.io/Number/isFinite). + * Checks if `value` is suitable for use as unique object key. * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang + * @private * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a finite number, else `false`. - * @example - * - * _.isFinite(3); - * // => true - * - * _.isFinite(Number.MIN_VALUE); - * // => true - * - * _.isFinite(Infinity); - * // => false - * - * _.isFinite('3'); - * // => false + * @returns {boolean} Returns `true` if `value` is suitable, else `false`. */ - function isFinite(value) { - return typeof value == 'number' && nativeIsFinite(value); + function isKeyable(value) { + var type = typeof value; + return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') + ? (value !== '__proto__') + : (value === null); } /** - * Checks if `value` is classified as a `Function` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a function, else `false`. - * @example - * - * _.isFunction(_); - * // => true + * Checks if `func` has a lazy counterpart. * - * _.isFunction(/abc/); - * // => false + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` has a lazy counterpart, + * else `false`. */ - function isFunction(value) { - if (!isObject(value)) { + function isLaziable(func) { + var funcName = getFuncName(func), + other = lodash[funcName]; + + if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) { return false; } - // The use of `Object#toString` avoids issues with the `typeof` operator - // in Safari 9 which returns 'object' for typed arrays and other constructors. - var tag = baseGetTag(value); - return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; + if (func === other) { + return true; + } + var data = getData(other); + return !!data && func === data[0]; } /** - * Checks if `value` is an integer. - * - * **Note:** This method is based on - * [`Number.isInteger`](https://mdn.io/Number/isInteger). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an integer, else `false`. - * @example - * - * _.isInteger(3); - * // => true - * - * _.isInteger(Number.MIN_VALUE); - * // => false - * - * _.isInteger(Infinity); - * // => false + * Checks if `func` has its source masked. * - * _.isInteger('3'); - * // => false + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` is masked, else `false`. */ - function isInteger(value) { - return typeof value == 'number' && value == toInteger(value); + function isMasked(func) { + return !!maskSrcKey && (maskSrcKey in func); } /** - * Checks if `value` is a valid array-like length. - * - * **Note:** This method is loosely based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * Checks if `func` is capable of being masked. * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang + * @private * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. - * @example - * - * _.isLength(3); - * // => true - * - * _.isLength(Number.MIN_VALUE); - * // => false - * - * _.isLength(Infinity); - * // => false - * - * _.isLength('3'); - * // => false + * @returns {boolean} Returns `true` if `func` is maskable, else `false`. */ - function isLength(value) { - return typeof value == 'number' && - value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; - } + var isMaskable = coreJsData ? isFunction : stubFalse; /** - * Checks if `value` is the - * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) - * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * Checks if `value` is likely a prototype object. * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang + * @private * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false + * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. */ - function isObject(value) { - var type = typeof value; - return value != null && (type == 'object' || type == 'function'); + function isPrototype(value) { + var Ctor = value && value.constructor, + proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; + + return value === proto; } /** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". + * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang + * @private * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false + * @returns {boolean} Returns `true` if `value` if suitable for strict + * equality comparisons, else `false`. */ - function isObjectLike(value) { - return value != null && typeof value == 'object'; + function isStrictComparable(value) { + return value === value && !isObject(value); } /** - * Checks if `value` is classified as a `Map` object. - * - * @static - * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a map, else `false`. - * @example - * - * _.isMap(new Map); - * // => true + * A specialized version of `matchesProperty` for source values suitable + * for strict equality comparisons, i.e. `===`. * - * _.isMap(new WeakMap); - * // => false + * @private + * @param {string} key The key of the property to get. + * @param {*} srcValue The value to match. + * @returns {Function} Returns the new spec function. */ - var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap; + function matchesStrictComparable(key, srcValue) { + return function(object) { + if (object == null) { + return false; + } + return object[key] === srcValue && + (srcValue !== undefined || (key in Object(object))); + }; + } /** - * Performs a partial deep comparison between `object` and `source` to - * determine if `object` contains equivalent property values. - * - * **Note:** This method is equivalent to `_.matches` when `source` is - * partially applied. - * - * Partial comparisons will match empty array and empty object `source` - * values against any array or object value, respectively. See `_.isEqual` - * for a list of supported value comparisons. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Lang - * @param {Object} object The object to inspect. - * @param {Object} source The object of property values to match. - * @returns {boolean} Returns `true` if `object` is a match, else `false`. - * @example - * - * var object = { 'a': 1, 'b': 2 }; - * - * _.isMatch(object, { 'b': 2 }); - * // => true + * A specialized version of `_.memoize` which clears the memoized function's + * cache when it exceeds `MAX_MEMOIZE_SIZE`. * - * _.isMatch(object, { 'b': 1 }); - * // => false + * @private + * @param {Function} func The function to have its output memoized. + * @returns {Function} Returns the new memoized function. */ - function isMatch(object, source) { - return object === source || baseIsMatch(object, source, getMatchData(source)); + function memoizeCapped(func) { + var result = memoize(func, function(key) { + if (cache.size === MAX_MEMOIZE_SIZE) { + cache.clear(); + } + return key; + }); + + var cache = result.cache; + return result; } /** - * This method is like `_.isMatch` except that it accepts `customizer` which - * is invoked to compare values. If `customizer` returns `undefined`, comparisons - * are handled by the method instead. The `customizer` is invoked with five - * arguments: (objValue, srcValue, index|key, object, source). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {Object} object The object to inspect. - * @param {Object} source The object of property values to match. - * @param {Function} [customizer] The function to customize comparisons. - * @returns {boolean} Returns `true` if `object` is a match, else `false`. - * @example - * - * function isGreeting(value) { - * return /^h(?:i|ello)$/.test(value); - * } - * - * function customizer(objValue, srcValue) { - * if (isGreeting(objValue) && isGreeting(srcValue)) { - * return true; - * } - * } + * Merges the function metadata of `source` into `data`. * - * var object = { 'greeting': 'hello' }; - * var source = { 'greeting': 'hi' }; + * Merging metadata reduces the number of wrappers used to invoke a function. + * This is possible because methods like `_.bind`, `_.curry`, and `_.partial` + * may be applied regardless of execution order. Methods like `_.ary` and + * `_.rearg` modify function arguments, making the order in which they are + * executed important, preventing the merging of metadata. However, we make + * an exception for a safe combined case where curried functions have `_.ary` + * and or `_.rearg` applied. * - * _.isMatchWith(object, source, customizer); - * // => true + * @private + * @param {Array} data The destination metadata. + * @param {Array} source The source metadata. + * @returns {Array} Returns `data`. */ - function isMatchWith(object, source, customizer) { - customizer = typeof customizer == 'function' ? customizer : undefined; - return baseIsMatch(object, source, getMatchData(source), customizer); + function mergeData(data, source) { + var bitmask = data[1], + srcBitmask = source[1], + newBitmask = bitmask | srcBitmask, + isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG); + + var isCombo = + ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_CURRY_FLAG)) || + ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_REARG_FLAG) && (data[7].length <= source[8])) || + ((srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG)); + + // Exit early if metadata can't be merged. + if (!(isCommon || isCombo)) { + return data; + } + // Use source `thisArg` if available. + if (srcBitmask & WRAP_BIND_FLAG) { + data[2] = source[2]; + // Set when currying a bound function. + newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG; + } + // Compose partial arguments. + var value = source[3]; + if (value) { + var partials = data[3]; + data[3] = partials ? composeArgs(partials, value, source[4]) : value; + data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4]; + } + // Compose partial right arguments. + value = source[5]; + if (value) { + partials = data[5]; + data[5] = partials ? composeArgsRight(partials, value, source[6]) : value; + data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6]; + } + // Use source `argPos` if available. + value = source[7]; + if (value) { + data[7] = value; + } + // Use source `ary` if it's smaller. + if (srcBitmask & WRAP_ARY_FLAG) { + data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]); + } + // Use source `arity` if one is not provided. + if (data[9] == null) { + data[9] = source[9]; + } + // Use source `func` and merge bitmasks. + data[0] = source[0]; + data[1] = newBitmask; + + return data; } /** - * Checks if `value` is `NaN`. - * - * **Note:** This method is based on - * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as - * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for - * `undefined` and other non-number values. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. - * @example - * - * _.isNaN(NaN); - * // => true - * - * _.isNaN(new Number(NaN)); - * // => true - * - * isNaN(undefined); - * // => true + * This function is like + * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * except that it includes inherited enumerable properties. * - * _.isNaN(undefined); - * // => false + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. */ - function isNaN(value) { - // An `NaN` primitive is the only value that is not equal to itself. - // Perform the `toStringTag` check first to avoid errors with some - // ActiveX objects in IE. - return isNumber(value) && value != +value; + function nativeKeysIn(object) { + var result = []; + if (object != null) { + for (var key in Object(object)) { + result.push(key); + } + } + return result; } /** - * Checks if `value` is a pristine native function. - * - * **Note:** This method can't reliably detect native functions in the presence - * of the core-js package because core-js circumvents this kind of detection. - * Despite multiple requests, the core-js maintainer has made it clear: any - * attempt to fix the detection will be obstructed. As a result, we're left - * with little choice but to throw an error. Unfortunately, this also affects - * packages, like [babel-polyfill](https://www.npmjs.com/package/babel-polyfill), - * which rely on core-js. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a native function, - * else `false`. - * @example - * - * _.isNative(Array.prototype.push); - * // => true + * Converts `value` to a string using `Object.prototype.toString`. * - * _.isNative(_); - * // => false + * @private + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. */ - function isNative(value) { - if (isMaskable(value)) { - throw new Error(CORE_ERROR_TEXT); - } - return baseIsNative(value); + function objectToString(value) { + return nativeObjectToString.call(value); } /** - * Checks if `value` is `null`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `null`, else `false`. - * @example - * - * _.isNull(null); - * // => true + * A specialized version of `baseRest` which transforms the rest array. * - * _.isNull(void 0); - * // => false + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @param {Function} transform The rest array transform. + * @returns {Function} Returns the new function. */ - function isNull(value) { - return value === null; + function overRest(func, start, transform) { + start = nativeMax(start === undefined ? (func.length - 1) : start, 0); + return function() { + var args = arguments, + index = -1, + length = nativeMax(args.length - start, 0), + array = Array(length); + + while (++index < length) { + array[index] = args[start + index]; + } + index = -1; + var otherArgs = Array(start + 1); + while (++index < start) { + otherArgs[index] = args[index]; + } + otherArgs[start] = transform(array); + return apply(func, this, otherArgs); + }; } /** - * Checks if `value` is `null` or `undefined`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is nullish, else `false`. - * @example - * - * _.isNil(null); - * // => true - * - * _.isNil(void 0); - * // => true + * Gets the parent value at `path` of `object`. * - * _.isNil(NaN); - * // => false + * @private + * @param {Object} object The object to query. + * @param {Array} path The path to get the parent value of. + * @returns {*} Returns the parent value. */ - function isNil(value) { - return value == null; + function parent(object, path) { + return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1)); } /** - * Checks if `value` is classified as a `Number` primitive or object. - * - * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are - * classified as numbers, use the `_.isFinite` method. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a number, else `false`. - * @example - * - * _.isNumber(3); - * // => true - * - * _.isNumber(Number.MIN_VALUE); - * // => true - * - * _.isNumber(Infinity); - * // => true + * Reorder `array` according to the specified indexes where the element at + * the first index is assigned as the first element, the element at + * the second index is assigned as the second element, and so on. * - * _.isNumber('3'); - * // => false + * @private + * @param {Array} array The array to reorder. + * @param {Array} indexes The arranged array indexes. + * @returns {Array} Returns `array`. */ - function isNumber(value) { - return typeof value == 'number' || - (isObjectLike(value) && baseGetTag(value) == numberTag); + function reorder(array, indexes) { + var arrLength = array.length, + length = nativeMin(indexes.length, arrLength), + oldArray = copyArray(array); + + while (length--) { + var index = indexes[length]; + array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined; + } + return array; } /** - * Checks if `value` is a plain object, that is, an object created by the - * `Object` constructor or one with a `[[Prototype]]` of `null`. - * - * @static - * @memberOf _ - * @since 0.8.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. - * @example - * - * function Foo() { - * this.a = 1; - * } - * - * _.isPlainObject(new Foo); - * // => false - * - * _.isPlainObject([1, 2, 3]); - * // => false - * - * _.isPlainObject({ 'x': 0, 'y': 0 }); - * // => true + * Gets the value at `key`, unless `key` is "__proto__" or "constructor". * - * _.isPlainObject(Object.create(null)); - * // => true + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the property to get. + * @returns {*} Returns the property value. */ - function isPlainObject(value) { - if (!isObjectLike(value) || baseGetTag(value) != objectTag) { - return false; + function safeGet(object, key) { + if (key === 'constructor' && typeof object[key] === 'function') { + return; } - var proto = getPrototype(value); - if (proto === null) { - return true; + + if (key == '__proto__') { + return; } - var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; - return typeof Ctor == 'function' && Ctor instanceof Ctor && - funcToString.call(Ctor) == objectCtorString; + + return object[key]; } /** - * Checks if `value` is classified as a `RegExp` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. - * @example + * Sets metadata for `func`. * - * _.isRegExp(/abc/); - * // => true + * **Note:** If this function becomes hot, i.e. is invoked a lot in a short + * period of time, it will trip its breaker and transition to an identity + * function to avoid garbage collection pauses in V8. See + * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070) + * for more details. * - * _.isRegExp('/abc/'); - * // => false + * @private + * @param {Function} func The function to associate metadata with. + * @param {*} data The metadata. + * @returns {Function} Returns `func`. */ - var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp; + var setData = shortOut(baseSetData); /** - * Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754 - * double precision number which isn't the result of a rounded unsafe integer. - * - * **Note:** This method is based on - * [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a safe integer, else `false`. - * @example - * - * _.isSafeInteger(3); - * // => true + * A simple wrapper around the global [`setTimeout`](https://mdn.io/setTimeout). * - * _.isSafeInteger(Number.MIN_VALUE); - * // => false + * @private + * @param {Function} func The function to delay. + * @param {number} wait The number of milliseconds to delay invocation. + * @returns {number|Object} Returns the timer id or timeout object. + */ + var setTimeout = ctxSetTimeout || function(func, wait) { + return root.setTimeout(func, wait); + }; + + /** + * Sets the `toString` method of `func` to return `string`. * - * _.isSafeInteger(Infinity); - * // => false + * @private + * @param {Function} func The function to modify. + * @param {Function} string The `toString` result. + * @returns {Function} Returns `func`. + */ + var setToString = shortOut(baseSetToString); + + /** + * Sets the `toString` method of `wrapper` to mimic the source of `reference` + * with wrapper details in a comment at the top of the source body. * - * _.isSafeInteger('3'); - * // => false + * @private + * @param {Function} wrapper The function to modify. + * @param {Function} reference The reference function. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @returns {Function} Returns `wrapper`. */ - function isSafeInteger(value) { - return isInteger(value) && value >= -MAX_SAFE_INTEGER && value <= MAX_SAFE_INTEGER; + function setWrapToString(wrapper, reference, bitmask) { + var source = (reference + ''); + return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask))); } /** - * Checks if `value` is classified as a `Set` object. - * - * @static - * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a set, else `false`. - * @example - * - * _.isSet(new Set); - * // => true + * Creates a function that'll short out and invoke `identity` instead + * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` + * milliseconds. * - * _.isSet(new WeakSet); - * // => false + * @private + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new shortable function. */ - var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet; + function shortOut(func) { + var count = 0, + lastCalled = 0; + + return function() { + var stamp = nativeNow(), + remaining = HOT_SPAN - (stamp - lastCalled); + + lastCalled = stamp; + if (remaining > 0) { + if (++count >= HOT_COUNT) { + return arguments[0]; + } + } else { + count = 0; + } + return func.apply(undefined, arguments); + }; + } /** - * Checks if `value` is classified as a `String` primitive or object. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a string, else `false`. - * @example - * - * _.isString('abc'); - * // => true + * A specialized version of `_.shuffle` which mutates and sets the size of `array`. * - * _.isString(1); - * // => false + * @private + * @param {Array} array The array to shuffle. + * @param {number} [size=array.length] The size of `array`. + * @returns {Array} Returns `array`. */ - function isString(value) { - return typeof value == 'string' || - (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag); + function shuffleSelf(array, size) { + var index = -1, + length = array.length, + lastIndex = length - 1; + + size = size === undefined ? length : size; + while (++index < size) { + var rand = baseRandom(index, lastIndex), + value = array[rand]; + + array[rand] = array[index]; + array[index] = value; + } + array.length = size; + return array; } /** - * Checks if `value` is classified as a `Symbol` primitive or object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. - * @example + * Converts `string` to a property path array. * - * _.isSymbol(Symbol.iterator); - * // => true + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the property path array. + */ + var stringToPath = memoizeCapped(function(string) { + var result = []; + if (string.charCodeAt(0) === 46 /* . */) { + result.push(''); + } + string.replace(rePropName, function(match, number, quote, subString) { + result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match)); + }); + return result; + }); + + /** + * Converts `value` to a string key if it's not a string or symbol. * - * _.isSymbol('abc'); - * // => false + * @private + * @param {*} value The value to inspect. + * @returns {string|symbol} Returns the key. */ - function isSymbol(value) { - return typeof value == 'symbol' || - (isObjectLike(value) && baseGetTag(value) == symbolTag); + function toKey(value) { + if (typeof value == 'string' || isSymbol(value)) { + return value; + } + var result = (value + ''); + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } /** - * Checks if `value` is classified as a typed array. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. - * @example - * - * _.isTypedArray(new Uint8Array); - * // => true + * Converts `func` to its source code. * - * _.isTypedArray([]); - * // => false + * @private + * @param {Function} func The function to convert. + * @returns {string} Returns the source code. */ - var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; + function toSource(func) { + if (func != null) { + try { + return funcToString.call(func); + } catch (e) {} + try { + return (func + ''); + } catch (e) {} + } + return ''; + } /** - * Checks if `value` is `undefined`. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. - * @example + * Updates wrapper `details` based on `bitmask` flags. * - * _.isUndefined(void 0); - * // => true + * @private + * @returns {Array} details The details to modify. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @returns {Array} Returns `details`. + */ + function updateWrapDetails(details, bitmask) { + arrayEach(wrapFlags, function(pair) { + var value = '_.' + pair[0]; + if ((bitmask & pair[1]) && !arrayIncludes(details, value)) { + details.push(value); + } + }); + return details.sort(); + } + + /** + * Creates a clone of `wrapper`. * - * _.isUndefined(null); - * // => false + * @private + * @param {Object} wrapper The wrapper to clone. + * @returns {Object} Returns the cloned wrapper. */ - function isUndefined(value) { - return value === undefined; + function wrapperClone(wrapper) { + if (wrapper instanceof LazyWrapper) { + return wrapper.clone(); + } + var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__); + result.__actions__ = copyArray(wrapper.__actions__); + result.__index__ = wrapper.__index__; + result.__values__ = wrapper.__values__; + return result; } + /*------------------------------------------------------------------------*/ + /** - * Checks if `value` is classified as a `WeakMap` object. + * Creates an array of elements split into groups the length of `size`. + * If `array` can't be split evenly, the final chunk will be the remaining + * elements. * * @static * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a weak map, else `false`. + * @since 3.0.0 + * @category Array + * @param {Array} array The array to process. + * @param {number} [size=1] The length of each chunk + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the new array of chunks. * @example * - * _.isWeakMap(new WeakMap); - * // => true + * _.chunk(['a', 'b', 'c', 'd'], 2); + * // => [['a', 'b'], ['c', 'd']] * - * _.isWeakMap(new Map); - * // => false + * _.chunk(['a', 'b', 'c', 'd'], 3); + * // => [['a', 'b', 'c'], ['d']] */ - function isWeakMap(value) { - return isObjectLike(value) && getTag(value) == weakMapTag; + function chunk(array, size, guard) { + if ((guard ? isIterateeCall(array, size, guard) : size === undefined)) { + size = 1; + } else { + size = nativeMax(toInteger(size), 0); + } + var length = array == null ? 0 : array.length; + if (!length || size < 1) { + return []; + } + var index = 0, + resIndex = 0, + result = Array(nativeCeil(length / size)); + + while (index < length) { + result[resIndex++] = baseSlice(array, index, (index += size)); + } + return result; } /** - * Checks if `value` is classified as a `WeakSet` object. + * Creates an array with all falsey values removed. The values `false`, `null`, + * `0`, `""`, `undefined`, and `NaN` are falsey. * * @static * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a weak set, else `false`. + * @since 0.1.0 + * @category Array + * @param {Array} array The array to compact. + * @returns {Array} Returns the new array of filtered values. * @example * - * _.isWeakSet(new WeakSet); - * // => true - * - * _.isWeakSet(new Set); - * // => false + * _.compact([0, 1, false, 2, '', 3]); + * // => [1, 2, 3] */ - function isWeakSet(value) { - return isObjectLike(value) && baseGetTag(value) == weakSetTag; + function compact(array) { + var index = -1, + length = array == null ? 0 : array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index]; + if (value) { + result[resIndex++] = value; + } + } + return result; } /** - * Checks if `value` is less than `other`. + * Creates a new array concatenating `array` with any additional arrays + * and/or values. * * @static * @memberOf _ - * @since 3.9.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if `value` is less than `other`, - * else `false`. - * @see _.gt + * @since 4.0.0 + * @category Array + * @param {Array} array The array to concatenate. + * @param {...*} [values] The values to concatenate. + * @returns {Array} Returns the new concatenated array. * @example * - * _.lt(1, 3); - * // => true + * var array = [1]; + * var other = _.concat(array, 2, [3], [[4]]); * - * _.lt(3, 3); - * // => false + * console.log(other); + * // => [1, 2, 3, [4]] * - * _.lt(3, 1); - * // => false + * console.log(array); + * // => [1] */ - var lt = createRelationalOperation(baseLt); + function concat() { + var length = arguments.length; + if (!length) { + return []; + } + var args = Array(length - 1), + array = arguments[0], + index = length; + + while (index--) { + args[index - 1] = arguments[index]; + } + return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1)); + } /** - * Checks if `value` is less than or equal to `other`. + * Creates an array of `array` values not included in the other given arrays + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. The order and references of result values are + * determined by the first array. + * + * **Note:** Unlike `_.pullAll`, this method returns a new array. * * @static * @memberOf _ - * @since 3.9.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if `value` is less than or equal to - * `other`, else `false`. - * @see _.gte + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...Array} [values] The values to exclude. + * @returns {Array} Returns the new array of filtered values. + * @see _.without, _.xor * @example * - * _.lte(1, 3); - * // => true - * - * _.lte(3, 3); - * // => true - * - * _.lte(3, 1); - * // => false + * _.difference([2, 1], [2, 3]); + * // => [1] */ - var lte = createRelationalOperation(function(value, other) { - return value <= other; + var difference = baseRest(function(array, values) { + return isArrayLikeObject(array) + ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true)) + : []; }); /** - * Converts `value` to an array. + * This method is like `_.difference` except that it accepts `iteratee` which + * is invoked for each element of `array` and `values` to generate the criterion + * by which they're compared. The order and references of result values are + * determined by the first array. The iteratee is invoked with one argument: + * (value). + * + * **Note:** Unlike `_.pullAllBy`, this method returns a new array. * * @static - * @since 0.1.0 * @memberOf _ - * @category Lang - * @param {*} value The value to convert. - * @returns {Array} Returns the converted array. + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...Array} [values] The values to exclude. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new array of filtered values. * @example * - * _.toArray({ 'a': 1, 'b': 2 }); - * // => [1, 2] - * - * _.toArray('abc'); - * // => ['a', 'b', 'c'] - * - * _.toArray(1); - * // => [] + * _.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); + * // => [1.2] * - * _.toArray(null); - * // => [] + * // The `_.property` iteratee shorthand. + * _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x'); + * // => [{ 'x': 2 }] */ - function toArray(value) { - if (!value) { - return []; - } - if (isArrayLike(value)) { - return isString(value) ? stringToArray(value) : copyArray(value); - } - if (symIterator && value[symIterator]) { - return iteratorToArray(value[symIterator]()); + var differenceBy = baseRest(function(array, values) { + var iteratee = last(values); + if (isArrayLikeObject(iteratee)) { + iteratee = undefined; } - var tag = getTag(value), - func = tag == mapTag ? mapToArray : (tag == setTag ? setToArray : values); - - return func(value); - } + return isArrayLikeObject(array) + ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)) + : []; + }); /** - * Converts `value` to a finite number. + * This method is like `_.difference` except that it accepts `comparator` + * which is invoked to compare elements of `array` to `values`. The order and + * references of result values are determined by the first array. The comparator + * is invoked with two arguments: (arrVal, othVal). + * + * **Note:** Unlike `_.pullAllWith`, this method returns a new array. * * @static * @memberOf _ - * @since 4.12.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted number. + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...Array} [values] The values to exclude. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of filtered values. * @example * - * _.toFinite(3.2); - * // => 3.2 - * - * _.toFinite(Number.MIN_VALUE); - * // => 5e-324 - * - * _.toFinite(Infinity); - * // => 1.7976931348623157e+308 + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; * - * _.toFinite('3.2'); - * // => 3.2 + * _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual); + * // => [{ 'x': 2, 'y': 1 }] */ - function toFinite(value) { - if (!value) { - return value === 0 ? value : 0; - } - value = toNumber(value); - if (value === INFINITY || value === -INFINITY) { - var sign = (value < 0 ? -1 : 1); - return sign * MAX_INTEGER; + var differenceWith = baseRest(function(array, values) { + var comparator = last(values); + if (isArrayLikeObject(comparator)) { + comparator = undefined; } - return value === value ? value : 0; - } + return isArrayLikeObject(array) + ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), undefined, comparator) + : []; + }); /** - * Converts `value` to an integer. - * - * **Note:** This method is loosely based on - * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). + * Creates a slice of `array` with `n` elements dropped from the beginning. * * @static * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted integer. + * @since 0.5.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to drop. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. * @example * - * _.toInteger(3.2); - * // => 3 + * _.drop([1, 2, 3]); + * // => [2, 3] * - * _.toInteger(Number.MIN_VALUE); - * // => 0 + * _.drop([1, 2, 3], 2); + * // => [3] * - * _.toInteger(Infinity); - * // => 1.7976931348623157e+308 + * _.drop([1, 2, 3], 5); + * // => [] * - * _.toInteger('3.2'); - * // => 3 + * _.drop([1, 2, 3], 0); + * // => [1, 2, 3] */ - function toInteger(value) { - var result = toFinite(value), - remainder = result % 1; - - return result === result ? (remainder ? result - remainder : result) : 0; + function drop(array, n, guard) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + n = (guard || n === undefined) ? 1 : toInteger(n); + return baseSlice(array, n < 0 ? 0 : n, length); } /** - * Converts `value` to an integer suitable for use as the length of an - * array-like object. - * - * **Note:** This method is based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * Creates a slice of `array` with `n` elements dropped from the end. * * @static * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted integer. + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to drop. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. * @example * - * _.toLength(3.2); - * // => 3 + * _.dropRight([1, 2, 3]); + * // => [1, 2] * - * _.toLength(Number.MIN_VALUE); - * // => 0 + * _.dropRight([1, 2, 3], 2); + * // => [1] * - * _.toLength(Infinity); - * // => 4294967295 + * _.dropRight([1, 2, 3], 5); + * // => [] * - * _.toLength('3.2'); - * // => 3 + * _.dropRight([1, 2, 3], 0); + * // => [1, 2, 3] */ - function toLength(value) { - return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0; + function dropRight(array, n, guard) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + n = (guard || n === undefined) ? 1 : toInteger(n); + n = length - n; + return baseSlice(array, 0, n < 0 ? 0 : n); } /** - * Converts `value` to a number. + * Creates a slice of `array` excluding elements dropped from the end. + * Elements are dropped until `predicate` returns falsey. The predicate is + * invoked with three arguments: (value, index, array). * * @static * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to process. - * @returns {number} Returns the number. + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. * @example * - * _.toNumber(3.2); - * // => 3.2 + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; * - * _.toNumber(Number.MIN_VALUE); - * // => 5e-324 + * _.dropRightWhile(users, function(o) { return !o.active; }); + * // => objects for ['barney'] * - * _.toNumber(Infinity); - * // => Infinity + * // The `_.matches` iteratee shorthand. + * _.dropRightWhile(users, { 'user': 'pebbles', 'active': false }); + * // => objects for ['barney', 'fred'] * - * _.toNumber('3.2'); - * // => 3.2 + * // The `_.matchesProperty` iteratee shorthand. + * _.dropRightWhile(users, ['active', false]); + * // => objects for ['barney'] + * + * // The `_.property` iteratee shorthand. + * _.dropRightWhile(users, 'active'); + * // => objects for ['barney', 'fred', 'pebbles'] */ - function toNumber(value) { - if (typeof value == 'number') { - return value; - } - if (isSymbol(value)) { - return NAN; - } - if (isObject(value)) { - var other = typeof value.valueOf == 'function' ? value.valueOf() : value; - value = isObject(other) ? (other + '') : other; - } - if (typeof value != 'string') { - return value === 0 ? value : +value; - } - value = baseTrim(value); - var isBinary = reIsBinary.test(value); - return (isBinary || reIsOctal.test(value)) - ? freeParseInt(value.slice(2), isBinary ? 2 : 8) - : (reIsBadHex.test(value) ? NAN : +value); + function dropRightWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, getIteratee(predicate, 3), true, true) + : []; } /** - * Converts `value` to a plain object flattening inherited enumerable string - * keyed properties of `value` to own properties of the plain object. + * Creates a slice of `array` excluding elements dropped from the beginning. + * Elements are dropped until `predicate` returns falsey. The predicate is + * invoked with three arguments: (value, index, array). * * @static * @memberOf _ * @since 3.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {Object} Returns the converted plain object. + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. * @example * - * function Foo() { - * this.b = 2; - * } + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; * - * Foo.prototype.c = 3; + * _.dropWhile(users, function(o) { return !o.active; }); + * // => objects for ['pebbles'] * - * _.assign({ 'a': 1 }, new Foo); - * // => { 'a': 1, 'b': 2 } + * // The `_.matches` iteratee shorthand. + * _.dropWhile(users, { 'user': 'barney', 'active': false }); + * // => objects for ['fred', 'pebbles'] * - * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); - * // => { 'a': 1, 'b': 2, 'c': 3 } + * // The `_.matchesProperty` iteratee shorthand. + * _.dropWhile(users, ['active', false]); + * // => objects for ['pebbles'] + * + * // The `_.property` iteratee shorthand. + * _.dropWhile(users, 'active'); + * // => objects for ['barney', 'fred', 'pebbles'] */ - function toPlainObject(value) { - return copyObject(value, keysIn(value)); + function dropWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, getIteratee(predicate, 3), true) + : []; } /** - * Converts `value` to a safe integer. A safe integer can be compared and - * represented correctly. + * Fills elements of `array` with `value` from `start` up to, but not + * including, `end`. + * + * **Note:** This method mutates `array`. * * @static * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted integer. + * @since 3.2.0 + * @category Array + * @param {Array} array The array to fill. + * @param {*} value The value to fill `array` with. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns `array`. * @example * - * _.toSafeInteger(3.2); - * // => 3 + * var array = [1, 2, 3]; * - * _.toSafeInteger(Number.MIN_VALUE); - * // => 0 + * _.fill(array, 'a'); + * console.log(array); + * // => ['a', 'a', 'a'] * - * _.toSafeInteger(Infinity); - * // => 9007199254740991 + * _.fill(Array(3), 2); + * // => [2, 2, 2] * - * _.toSafeInteger('3.2'); - * // => 3 + * _.fill([4, 6, 8, 10], '*', 1, 3); + * // => [4, '*', '*', 10] */ - function toSafeInteger(value) { - return value - ? baseClamp(toInteger(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER) - : (value === 0 ? value : 0); + function fill(array, value, start, end) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + if (start && typeof start != 'number' && isIterateeCall(array, value, start)) { + start = 0; + end = length; + } + return baseFill(array, value, start, end); } /** - * Converts `value` to a string. An empty string is returned for `null` - * and `undefined` values. The sign of `-0` is preserved. + * This method is like `_.find` except that it returns the index of the first + * element `predicate` returns truthy for instead of the element itself. * * @static * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {string} Returns the converted string. + * @since 1.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param {number} [fromIndex=0] The index to search from. + * @returns {number} Returns the index of the found element, else `-1`. * @example * - * _.toString(null); - * // => '' + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; * - * _.toString(-0); - * // => '-0' + * _.findIndex(users, function(o) { return o.user == 'barney'; }); + * // => 0 * - * _.toString([1, 2, 3]); - * // => '1,2,3' + * // The `_.matches` iteratee shorthand. + * _.findIndex(users, { 'user': 'fred', 'active': false }); + * // => 1 + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findIndex(users, ['active', false]); + * // => 0 + * + * // The `_.property` iteratee shorthand. + * _.findIndex(users, 'active'); + * // => 2 */ - function toString(value) { - return value == null ? '' : baseToString(value); + function findIndex(array, predicate, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; + } + var index = fromIndex == null ? 0 : toInteger(fromIndex); + if (index < 0) { + index = nativeMax(length + index, 0); + } + return baseFindIndex(array, getIteratee(predicate, 3), index); } - /*------------------------------------------------------------------------*/ - /** - * Assigns own enumerable string keyed properties of source objects to the - * destination object. Source objects are applied from left to right. - * Subsequent sources overwrite property assignments of previous sources. - * - * **Note:** This method mutates `object` and is loosely based on - * [`Object.assign`](https://mdn.io/Object/assign). + * This method is like `_.findIndex` except that it iterates over elements + * of `collection` from right to left. * * @static * @memberOf _ - * @since 0.10.0 - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. - * @see _.assignIn + * @since 2.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param {number} [fromIndex=array.length-1] The index to search from. + * @returns {number} Returns the index of the found element, else `-1`. * @example * - * function Foo() { - * this.a = 1; - * } + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; * - * function Bar() { - * this.c = 3; - * } + * _.findLastIndex(users, function(o) { return o.user == 'pebbles'; }); + * // => 2 * - * Foo.prototype.b = 2; - * Bar.prototype.d = 4; + * // The `_.matches` iteratee shorthand. + * _.findLastIndex(users, { 'user': 'barney', 'active': true }); + * // => 0 * - * _.assign({ 'a': 0 }, new Foo, new Bar); - * // => { 'a': 1, 'c': 3 } + * // The `_.matchesProperty` iteratee shorthand. + * _.findLastIndex(users, ['active', false]); + * // => 2 + * + * // The `_.property` iteratee shorthand. + * _.findLastIndex(users, 'active'); + * // => 0 */ - var assign = createAssigner(function(object, source) { - if (isPrototype(source) || isArrayLike(source)) { - copyObject(source, keys(source), object); - return; + function findLastIndex(array, predicate, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; } - for (var key in source) { - if (hasOwnProperty.call(source, key)) { - assignValue(object, key, source[key]); - } + var index = length - 1; + if (fromIndex !== undefined) { + index = toInteger(fromIndex); + index = fromIndex < 0 + ? nativeMax(length + index, 0) + : nativeMin(index, length - 1); } - }); + return baseFindIndex(array, getIteratee(predicate, 3), index, true); + } /** - * This method is like `_.assign` except that it iterates over own and - * inherited source properties. - * - * **Note:** This method mutates `object`. + * Flattens `array` a single level deep. * * @static * @memberOf _ - * @since 4.0.0 - * @alias extend - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. - * @see _.assign + * @since 0.1.0 + * @category Array + * @param {Array} array The array to flatten. + * @returns {Array} Returns the new flattened array. * @example * - * function Foo() { - * this.a = 1; - * } - * - * function Bar() { - * this.c = 3; - * } - * - * Foo.prototype.b = 2; - * Bar.prototype.d = 4; - * - * _.assignIn({ 'a': 0 }, new Foo, new Bar); - * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 } + * _.flatten([1, [2, [3, [4]], 5]]); + * // => [1, 2, [3, [4]], 5] */ - var assignIn = createAssigner(function(object, source) { - copyObject(source, keysIn(source), object); - }); + function flatten(array) { + var length = array == null ? 0 : array.length; + return length ? baseFlatten(array, 1) : []; + } /** - * This method is like `_.assignIn` except that it accepts `customizer` - * which is invoked to produce the assigned values. If `customizer` returns - * `undefined`, assignment is handled by the method instead. The `customizer` - * is invoked with five arguments: (objValue, srcValue, key, object, source). - * - * **Note:** This method mutates `object`. + * Recursively flattens `array`. * * @static * @memberOf _ - * @since 4.0.0 - * @alias extendWith - * @category Object - * @param {Object} object The destination object. - * @param {...Object} sources The source objects. - * @param {Function} [customizer] The function to customize assigned values. - * @returns {Object} Returns `object`. - * @see _.assignWith + * @since 3.0.0 + * @category Array + * @param {Array} array The array to flatten. + * @returns {Array} Returns the new flattened array. * @example * - * function customizer(objValue, srcValue) { - * return _.isUndefined(objValue) ? srcValue : objValue; - * } - * - * var defaults = _.partialRight(_.assignInWith, customizer); - * - * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); - * // => { 'a': 1, 'b': 2 } + * _.flattenDeep([1, [2, [3, [4]], 5]]); + * // => [1, 2, 3, 4, 5] */ - var assignInWith = createAssigner(function(object, source, srcIndex, customizer) { - copyObject(source, keysIn(source), object, customizer); - }); + function flattenDeep(array) { + var length = array == null ? 0 : array.length; + return length ? baseFlatten(array, INFINITY) : []; + } /** - * This method is like `_.assign` except that it accepts `customizer` - * which is invoked to produce the assigned values. If `customizer` returns - * `undefined`, assignment is handled by the method instead. The `customizer` - * is invoked with five arguments: (objValue, srcValue, key, object, source). - * - * **Note:** This method mutates `object`. + * Recursively flatten `array` up to `depth` times. * * @static * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The destination object. - * @param {...Object} sources The source objects. - * @param {Function} [customizer] The function to customize assigned values. - * @returns {Object} Returns `object`. - * @see _.assignInWith + * @since 4.4.0 + * @category Array + * @param {Array} array The array to flatten. + * @param {number} [depth=1] The maximum recursion depth. + * @returns {Array} Returns the new flattened array. * @example * - * function customizer(objValue, srcValue) { - * return _.isUndefined(objValue) ? srcValue : objValue; - * } + * var array = [1, [2, [3, [4]], 5]]; * - * var defaults = _.partialRight(_.assignWith, customizer); + * _.flattenDepth(array, 1); + * // => [1, 2, [3, [4]], 5] * - * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); - * // => { 'a': 1, 'b': 2 } + * _.flattenDepth(array, 2); + * // => [1, 2, 3, [4], 5] */ - var assignWith = createAssigner(function(object, source, srcIndex, customizer) { - copyObject(source, keys(source), object, customizer); - }); + function flattenDepth(array, depth) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + depth = depth === undefined ? 1 : toInteger(depth); + return baseFlatten(array, depth); + } /** - * Creates an array of values corresponding to `paths` of `object`. + * The inverse of `_.toPairs`; this method returns an object composed + * from key-value `pairs`. * * @static * @memberOf _ - * @since 1.0.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {...(string|string[])} [paths] The property paths to pick. - * @returns {Array} Returns the picked values. + * @since 4.0.0 + * @category Array + * @param {Array} pairs The key-value pairs. + * @returns {Object} Returns the new object. * @example * - * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; - * - * _.at(object, ['a[0].b.c', 'a[1]']); - * // => [3, 4] + * _.fromPairs([['a', 1], ['b', 2]]); + * // => { 'a': 1, 'b': 2 } */ - var at = flatRest(baseAt); + function fromPairs(pairs) { + var index = -1, + length = pairs == null ? 0 : pairs.length, + result = {}; + + while (++index < length) { + var pair = pairs[index]; + result[pair[0]] = pair[1]; + } + return result; + } /** - * Creates an object that inherits from the `prototype` object. If a - * `properties` object is given, its own enumerable string keyed properties - * are assigned to the created object. + * Gets the first element of `array`. * * @static * @memberOf _ - * @since 2.3.0 - * @category Object - * @param {Object} prototype The object to inherit from. - * @param {Object} [properties] The properties to assign to the object. - * @returns {Object} Returns the new object. + * @since 0.1.0 + * @alias first + * @category Array + * @param {Array} array The array to query. + * @returns {*} Returns the first element of `array`. * @example * - * function Shape() { - * this.x = 0; - * this.y = 0; - * } - * - * function Circle() { - * Shape.call(this); - * } - * - * Circle.prototype = _.create(Shape.prototype, { - * 'constructor': Circle - * }); - * - * var circle = new Circle; - * circle instanceof Circle; - * // => true + * _.head([1, 2, 3]); + * // => 1 * - * circle instanceof Shape; - * // => true + * _.head([]); + * // => undefined */ - function create(prototype, properties) { - var result = baseCreate(prototype); - return properties == null ? result : baseAssign(result, properties); + function head(array) { + return (array && array.length) ? array[0] : undefined; } /** - * Assigns own and inherited enumerable string keyed properties of source - * objects to the destination object for all destination properties that - * resolve to `undefined`. Source objects are applied from left to right. - * Once a property is set, additional values of the same property are ignored. - * - * **Note:** This method mutates `object`. + * Gets the index at which the first occurrence of `value` is found in `array` + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. If `fromIndex` is negative, it's used as the + * offset from the end of `array`. * * @static - * @since 0.1.0 * @memberOf _ - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. - * @see _.defaultsDeep + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} [fromIndex=0] The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. * @example * - * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); - * // => { 'a': 1, 'b': 2 } + * _.indexOf([1, 2, 1, 2], 2); + * // => 1 + * + * // Search from the `fromIndex`. + * _.indexOf([1, 2, 1, 2], 2, 2); + * // => 3 */ - var defaults = baseRest(function(object, sources) { - object = Object(object); - - var index = -1; - var length = sources.length; - var guard = length > 2 ? sources[2] : undefined; - - if (guard && isIterateeCall(sources[0], sources[1], guard)) { - length = 1; + function indexOf(array, value, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; } - - while (++index < length) { - var source = sources[index]; - var props = keysIn(source); - var propsIndex = -1; - var propsLength = props.length; - - while (++propsIndex < propsLength) { - var key = props[propsIndex]; - var value = object[key]; - - if (value === undefined || - (eq(value, objectProto[key]) && !hasOwnProperty.call(object, key))) { - object[key] = source[key]; - } - } + var index = fromIndex == null ? 0 : toInteger(fromIndex); + if (index < 0) { + index = nativeMax(length + index, 0); } - - return object; - }); + return baseIndexOf(array, value, index); + } /** - * This method is like `_.defaults` except that it recursively assigns - * default properties. - * - * **Note:** This method mutates `object`. + * Gets all but the last element of `array`. * * @static * @memberOf _ - * @since 3.10.0 - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. - * @see _.defaults + * @since 0.1.0 + * @category Array + * @param {Array} array The array to query. + * @returns {Array} Returns the slice of `array`. * @example * - * _.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } }); - * // => { 'a': { 'b': 2, 'c': 3 } } + * _.initial([1, 2, 3]); + * // => [1, 2] */ - var defaultsDeep = baseRest(function(args) { - args.push(undefined, customDefaultsMerge); - return apply(mergeWith, undefined, args); - }); + function initial(array) { + var length = array == null ? 0 : array.length; + return length ? baseSlice(array, 0, -1) : []; + } /** - * This method is like `_.find` except that it returns the key of the first - * element `predicate` returns truthy for instead of the element itself. + * Creates an array of unique values that are included in all given arrays + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. The order and references of result values are + * determined by the first array. * * @static * @memberOf _ - * @since 1.1.0 - * @category Object - * @param {Object} object The object to inspect. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {string|undefined} Returns the key of the matched element, - * else `undefined`. + * @since 0.1.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of intersecting values. * @example * - * var users = { - * 'barney': { 'age': 36, 'active': true }, - * 'fred': { 'age': 40, 'active': false }, - * 'pebbles': { 'age': 1, 'active': true } - * }; - * - * _.findKey(users, function(o) { return o.age < 40; }); - * // => 'barney' (iteration order is not guaranteed) - * - * // The `_.matches` iteratee shorthand. - * _.findKey(users, { 'age': 1, 'active': true }); - * // => 'pebbles' - * - * // The `_.matchesProperty` iteratee shorthand. - * _.findKey(users, ['active', false]); - * // => 'fred' - * - * // The `_.property` iteratee shorthand. - * _.findKey(users, 'active'); - * // => 'barney' + * _.intersection([2, 1], [2, 3]); + * // => [2] */ - function findKey(object, predicate) { - return baseFindKey(object, getIteratee(predicate, 3), baseForOwn); - } + var intersection = baseRest(function(arrays) { + var mapped = arrayMap(arrays, castArrayLikeObject); + return (mapped.length && mapped[0] === arrays[0]) + ? baseIntersection(mapped) + : []; + }); /** - * This method is like `_.findKey` except that it iterates over elements of - * a collection in the opposite order. + * This method is like `_.intersection` except that it accepts `iteratee` + * which is invoked for each element of each `arrays` to generate the criterion + * by which they're compared. The order and references of result values are + * determined by the first array. The iteratee is invoked with one argument: + * (value). * * @static * @memberOf _ - * @since 2.0.0 - * @category Object - * @param {Object} object The object to inspect. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {string|undefined} Returns the key of the matched element, - * else `undefined`. + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new array of intersecting values. * @example * - * var users = { - * 'barney': { 'age': 36, 'active': true }, - * 'fred': { 'age': 40, 'active': false }, - * 'pebbles': { 'age': 1, 'active': true } - * }; - * - * _.findLastKey(users, function(o) { return o.age < 40; }); - * // => returns 'pebbles' assuming `_.findKey` returns 'barney' - * - * // The `_.matches` iteratee shorthand. - * _.findLastKey(users, { 'age': 36, 'active': true }); - * // => 'barney' - * - * // The `_.matchesProperty` iteratee shorthand. - * _.findLastKey(users, ['active', false]); - * // => 'fred' + * _.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor); + * // => [2.1] * * // The `_.property` iteratee shorthand. - * _.findLastKey(users, 'active'); - * // => 'pebbles' + * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 1 }] */ - function findLastKey(object, predicate) { - return baseFindKey(object, getIteratee(predicate, 3), baseForOwnRight); - } + var intersectionBy = baseRest(function(arrays) { + var iteratee = last(arrays), + mapped = arrayMap(arrays, castArrayLikeObject); - /** - * Iterates over own and inherited enumerable string keyed properties of an - * object and invokes `iteratee` for each property. The iteratee is invoked - * with three arguments: (value, key, object). Iteratee functions may exit - * iteration early by explicitly returning `false`. + if (iteratee === last(mapped)) { + iteratee = undefined; + } else { + mapped.pop(); + } + return (mapped.length && mapped[0] === arrays[0]) + ? baseIntersection(mapped, getIteratee(iteratee, 2)) + : []; + }); + + /** + * This method is like `_.intersection` except that it accepts `comparator` + * which is invoked to compare elements of `arrays`. The order and references + * of result values are determined by the first array. The comparator is + * invoked with two arguments: (arrVal, othVal). * * @static * @memberOf _ - * @since 0.3.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Object} Returns `object`. - * @see _.forInRight + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of intersecting values. * @example * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; * - * _.forIn(new Foo, function(value, key) { - * console.log(key); - * }); - * // => Logs 'a', 'b', then 'c' (iteration order is not guaranteed). + * _.intersectionWith(objects, others, _.isEqual); + * // => [{ 'x': 1, 'y': 2 }] */ - function forIn(object, iteratee) { - return object == null - ? object - : baseFor(object, getIteratee(iteratee, 3), keysIn); - } + var intersectionWith = baseRest(function(arrays) { + var comparator = last(arrays), + mapped = arrayMap(arrays, castArrayLikeObject); + + comparator = typeof comparator == 'function' ? comparator : undefined; + if (comparator) { + mapped.pop(); + } + return (mapped.length && mapped[0] === arrays[0]) + ? baseIntersection(mapped, undefined, comparator) + : []; + }); /** - * This method is like `_.forIn` except that it iterates over properties of - * `object` in the opposite order. + * Converts all elements in `array` into a string separated by `separator`. * * @static * @memberOf _ - * @since 2.0.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Object} Returns `object`. - * @see _.forIn + * @since 4.0.0 + * @category Array + * @param {Array} array The array to convert. + * @param {string} [separator=','] The element separator. + * @returns {string} Returns the joined string. * @example * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.forInRight(new Foo, function(value, key) { - * console.log(key); - * }); - * // => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'. + * _.join(['a', 'b', 'c'], '~'); + * // => 'a~b~c' */ - function forInRight(object, iteratee) { - return object == null - ? object - : baseForRight(object, getIteratee(iteratee, 3), keysIn); + function join(array, separator) { + return array == null ? '' : nativeJoin.call(array, separator); } /** - * Iterates over own enumerable string keyed properties of an object and - * invokes `iteratee` for each property. The iteratee is invoked with three - * arguments: (value, key, object). Iteratee functions may exit iteration - * early by explicitly returning `false`. + * Gets the last element of `array`. * * @static * @memberOf _ - * @since 0.3.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Object} Returns `object`. - * @see _.forOwnRight + * @since 0.1.0 + * @category Array + * @param {Array} array The array to query. + * @returns {*} Returns the last element of `array`. * @example * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.forOwn(new Foo, function(value, key) { - * console.log(key); - * }); - * // => Logs 'a' then 'b' (iteration order is not guaranteed). + * _.last([1, 2, 3]); + * // => 3 */ - function forOwn(object, iteratee) { - return object && baseForOwn(object, getIteratee(iteratee, 3)); + function last(array) { + var length = array == null ? 0 : array.length; + return length ? array[length - 1] : undefined; } /** - * This method is like `_.forOwn` except that it iterates over properties of - * `object` in the opposite order. + * This method is like `_.indexOf` except that it iterates over elements of + * `array` from right to left. * * @static * @memberOf _ - * @since 2.0.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Object} Returns `object`. - * @see _.forOwn + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} [fromIndex=array.length-1] The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. * @example * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; + * _.lastIndexOf([1, 2, 1, 2], 2); + * // => 3 * - * _.forOwnRight(new Foo, function(value, key) { - * console.log(key); - * }); - * // => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'. + * // Search from the `fromIndex`. + * _.lastIndexOf([1, 2, 1, 2], 2, 2); + * // => 1 */ - function forOwnRight(object, iteratee) { - return object && baseForOwnRight(object, getIteratee(iteratee, 3)); + function lastIndexOf(array, value, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; + } + var index = length; + if (fromIndex !== undefined) { + index = toInteger(fromIndex); + index = index < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1); + } + return value === value + ? strictLastIndexOf(array, value, index) + : baseFindIndex(array, baseIsNaN, index, true); } /** - * Creates an array of function property names from own enumerable properties - * of `object`. + * Gets the element at index `n` of `array`. If `n` is negative, the nth + * element from the end is returned. * * @static - * @since 0.1.0 * @memberOf _ - * @category Object - * @param {Object} object The object to inspect. - * @returns {Array} Returns the function names. - * @see _.functionsIn + * @since 4.11.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=0] The index of the element to return. + * @returns {*} Returns the nth element of `array`. * @example * - * function Foo() { - * this.a = _.constant('a'); - * this.b = _.constant('b'); - * } + * var array = ['a', 'b', 'c', 'd']; * - * Foo.prototype.c = _.constant('c'); + * _.nth(array, 1); + * // => 'b' * - * _.functions(new Foo); - * // => ['a', 'b'] + * _.nth(array, -2); + * // => 'c'; */ - function functions(object) { - return object == null ? [] : baseFunctions(object, keys(object)); + function nth(array, n) { + return (array && array.length) ? baseNth(array, toInteger(n)) : undefined; } /** - * Creates an array of function property names from own and inherited - * enumerable properties of `object`. + * Removes all given values from `array` using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * **Note:** Unlike `_.without`, this method mutates `array`. Use `_.remove` + * to remove elements from an array by predicate. * * @static * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The object to inspect. - * @returns {Array} Returns the function names. - * @see _.functions + * @since 2.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {...*} [values] The values to remove. + * @returns {Array} Returns `array`. * @example * - * function Foo() { - * this.a = _.constant('a'); - * this.b = _.constant('b'); - * } - * - * Foo.prototype.c = _.constant('c'); + * var array = ['a', 'b', 'c', 'a', 'b', 'c']; * - * _.functionsIn(new Foo); - * // => ['a', 'b', 'c'] + * _.pull(array, 'a', 'c'); + * console.log(array); + * // => ['b', 'b'] */ - function functionsIn(object) { - return object == null ? [] : baseFunctions(object, keysIn(object)); - } + var pull = baseRest(pullAll); /** - * Gets the value at `path` of `object`. If the resolved value is - * `undefined`, the `defaultValue` is returned in its place. + * This method is like `_.pull` except that it accepts an array of values to remove. + * + * **Note:** Unlike `_.difference`, this method mutates `array`. * * @static * @memberOf _ - * @since 3.7.0 - * @category Object - * @param {Object} object The object to query. - * @param {Array|string} path The path of the property to get. - * @param {*} [defaultValue] The value returned for `undefined` resolved values. - * @returns {*} Returns the resolved value. + * @since 4.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @returns {Array} Returns `array`. * @example * - * var object = { 'a': [{ 'b': { 'c': 3 } }] }; - * - * _.get(object, 'a[0].b.c'); - * // => 3 - * - * _.get(object, ['a', '0', 'b', 'c']); - * // => 3 + * var array = ['a', 'b', 'c', 'a', 'b', 'c']; * - * _.get(object, 'a.b.c', 'default'); - * // => 'default' + * _.pullAll(array, ['a', 'c']); + * console.log(array); + * // => ['b', 'b'] */ - function get(object, path, defaultValue) { - var result = object == null ? undefined : baseGet(object, path); - return result === undefined ? defaultValue : result; + function pullAll(array, values) { + return (array && array.length && values && values.length) + ? basePullAll(array, values) + : array; } /** - * Checks if `path` is a direct property of `object`. + * This method is like `_.pullAll` except that it accepts `iteratee` which is + * invoked for each element of `array` and `values` to generate the criterion + * by which they're compared. The iteratee is invoked with one argument: (value). + * + * **Note:** Unlike `_.differenceBy`, this method mutates `array`. * * @static - * @since 0.1.0 * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @param {Array|string} path The path to check. - * @returns {boolean} Returns `true` if `path` exists, else `false`. + * @since 4.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns `array`. * @example * - * var object = { 'a': { 'b': 2 } }; - * var other = _.create({ 'a': _.create({ 'b': 2 }) }); - * - * _.has(object, 'a'); - * // => true - * - * _.has(object, 'a.b'); - * // => true - * - * _.has(object, ['a', 'b']); - * // => true + * var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }]; * - * _.has(other, 'a'); - * // => false + * _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x'); + * console.log(array); + * // => [{ 'x': 2 }] */ - function has(object, path) { - return object != null && hasPath(object, path, baseHas); + function pullAllBy(array, values, iteratee) { + return (array && array.length && values && values.length) + ? basePullAll(array, values, getIteratee(iteratee, 2)) + : array; } /** - * Checks if `path` is a direct or inherited property of `object`. + * This method is like `_.pullAll` except that it accepts `comparator` which + * is invoked to compare elements of `array` to `values`. The comparator is + * invoked with two arguments: (arrVal, othVal). + * + * **Note:** Unlike `_.differenceWith`, this method mutates `array`. * * @static * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The object to query. - * @param {Array|string} path The path to check. - * @returns {boolean} Returns `true` if `path` exists, else `false`. + * @since 4.6.0 + * @category Array + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns `array`. * @example * - * var object = _.create({ 'a': _.create({ 'b': 2 }) }); - * - * _.hasIn(object, 'a'); - * // => true - * - * _.hasIn(object, 'a.b'); - * // => true - * - * _.hasIn(object, ['a', 'b']); - * // => true + * var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }]; * - * _.hasIn(object, 'b'); - * // => false + * _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual); + * console.log(array); + * // => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }] */ - function hasIn(object, path) { - return object != null && hasPath(object, path, baseHasIn); + function pullAllWith(array, values, comparator) { + return (array && array.length && values && values.length) + ? basePullAll(array, values, undefined, comparator) + : array; } /** - * Creates an object composed of the inverted keys and values of `object`. - * If `object` contains duplicate values, subsequent values overwrite - * property assignments of previous values. + * Removes elements from `array` corresponding to `indexes` and returns an + * array of removed elements. + * + * **Note:** Unlike `_.at`, this method mutates `array`. * * @static * @memberOf _ - * @since 0.7.0 - * @category Object - * @param {Object} object The object to invert. - * @returns {Object} Returns the new inverted object. + * @since 3.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {...(number|number[])} [indexes] The indexes of elements to remove. + * @returns {Array} Returns the new array of removed elements. * @example * - * var object = { 'a': 1, 'b': 2, 'c': 1 }; + * var array = ['a', 'b', 'c', 'd']; + * var pulled = _.pullAt(array, [1, 3]); * - * _.invert(object); - * // => { '1': 'c', '2': 'b' } + * console.log(array); + * // => ['a', 'c'] + * + * console.log(pulled); + * // => ['b', 'd'] */ - var invert = createInverter(function(result, value, key) { - if (value != null && - typeof value.toString != 'function') { - value = nativeObjectToString.call(value); - } + var pullAt = flatRest(function(array, indexes) { + var length = array == null ? 0 : array.length, + result = baseAt(array, indexes); - result[value] = key; - }, constant(identity)); + basePullAt(array, arrayMap(indexes, function(index) { + return isIndex(index, length) ? +index : index; + }).sort(compareAscending)); + + return result; + }); /** - * This method is like `_.invert` except that the inverted object is generated - * from the results of running each element of `object` thru `iteratee`. The - * corresponding inverted value of each inverted key is an array of keys - * responsible for generating the inverted value. The iteratee is invoked - * with one argument: (value). + * Removes all elements from `array` that `predicate` returns truthy for + * and returns an array of the removed elements. The predicate is invoked + * with three arguments: (value, index, array). + * + * **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull` + * to pull elements from an array by value. * * @static * @memberOf _ - * @since 4.1.0 - * @category Object - * @param {Object} object The object to invert. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {Object} Returns the new inverted object. + * @since 2.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new array of removed elements. * @example * - * var object = { 'a': 1, 'b': 2, 'c': 1 }; + * var array = [1, 2, 3, 4]; + * var evens = _.remove(array, function(n) { + * return n % 2 == 0; + * }); * - * _.invertBy(object); - * // => { '1': ['a', 'c'], '2': ['b'] } + * console.log(array); + * // => [1, 3] * - * _.invertBy(object, function(value) { - * return 'group' + value; - * }); - * // => { 'group1': ['a', 'c'], 'group2': ['b'] } + * console.log(evens); + * // => [2, 4] */ - var invertBy = createInverter(function(result, value, key) { - if (value != null && - typeof value.toString != 'function') { - value = nativeObjectToString.call(value); + function remove(array, predicate) { + var result = []; + if (!(array && array.length)) { + return result; } + var index = -1, + indexes = [], + length = array.length; - if (hasOwnProperty.call(result, value)) { - result[value].push(key); - } else { - result[value] = [key]; + predicate = getIteratee(predicate, 3); + while (++index < length) { + var value = array[index]; + if (predicate(value, index, array)) { + result.push(value); + indexes.push(index); + } } - }, getIteratee); + basePullAt(array, indexes); + return result; + } /** - * Invokes the method at `path` of `object`. + * Reverses `array` so that the first element becomes the last, the second + * element becomes the second to last, and so on. + * + * **Note:** This method mutates `array` and is based on + * [`Array#reverse`](https://mdn.io/Array/reverse). * * @static * @memberOf _ * @since 4.0.0 - * @category Object - * @param {Object} object The object to query. - * @param {Array|string} path The path of the method to invoke. - * @param {...*} [args] The arguments to invoke the method with. - * @returns {*} Returns the result of the invoked method. + * @category Array + * @param {Array} array The array to modify. + * @returns {Array} Returns `array`. * @example * - * var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] }; + * var array = [1, 2, 3]; * - * _.invoke(object, 'a[0].b.c.slice', 1, 3); - * // => [2, 3] + * _.reverse(array); + * // => [3, 2, 1] + * + * console.log(array); + * // => [3, 2, 1] */ - var invoke = baseRest(baseInvoke); + function reverse(array) { + return array == null ? array : nativeReverse.call(array); + } /** - * Creates an array of the own enumerable property names of `object`. + * Creates a slice of `array` from `start` up to, but not including, `end`. * - * **Note:** Non-object values are coerced to objects. See the - * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) - * for more details. + * **Note:** This method is used instead of + * [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are + * returned. * * @static - * @since 0.1.0 * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.keys(new Foo); - * // => ['a', 'b'] (iteration order is not guaranteed) - * - * _.keys('hi'); - * // => ['0', '1'] + * @since 3.0.0 + * @category Array + * @param {Array} array The array to slice. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the slice of `array`. */ - function keys(object) { - return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); + function slice(array, start, end) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + if (end && typeof end != 'number' && isIterateeCall(array, start, end)) { + start = 0; + end = length; + } + else { + start = start == null ? 0 : toInteger(start); + end = end === undefined ? length : toInteger(end); + } + return baseSlice(array, start, end); } /** - * Creates an array of the own and inherited enumerable property names of `object`. - * - * **Note:** Non-object values are coerced to objects. + * Uses a binary search to determine the lowest index at which `value` + * should be inserted into `array` in order to maintain its sort order. * * @static * @memberOf _ - * @since 3.0.0 - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. + * @since 0.1.0 + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. * @example * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.keysIn(new Foo); - * // => ['a', 'b', 'c'] (iteration order is not guaranteed) + * _.sortedIndex([30, 50], 40); + * // => 1 */ - function keysIn(object) { - return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); + function sortedIndex(array, value) { + return baseSortedIndex(array, value); } /** - * The opposite of `_.mapValues`; this method creates an object with the - * same values as `object` and keys generated by running each own enumerable - * string keyed property of `object` thru `iteratee`. The iteratee is invoked - * with three arguments: (value, key, object). + * This method is like `_.sortedIndex` except that it accepts `iteratee` + * which is invoked for `value` and each element of `array` to compute their + * sort ranking. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ - * @since 3.8.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Object} Returns the new mapped object. - * @see _.mapValues + * @since 4.0.0 + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. * @example * - * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) { - * return key + value; - * }); - * // => { 'a1': 1, 'b2': 2 } + * var objects = [{ 'x': 4 }, { 'x': 5 }]; + * + * _.sortedIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); + * // => 0 + * + * // The `_.property` iteratee shorthand. + * _.sortedIndexBy(objects, { 'x': 4 }, 'x'); + * // => 0 */ - function mapKeys(object, iteratee) { - var result = {}; - iteratee = getIteratee(iteratee, 3); - - baseForOwn(object, function(value, key, object) { - baseAssignValue(result, iteratee(value, key, object), value); - }); - return result; + function sortedIndexBy(array, value, iteratee) { + return baseSortedIndexBy(array, value, getIteratee(iteratee, 2)); } /** - * Creates an object with the same keys as `object` and values generated - * by running each own enumerable string keyed property of `object` thru - * `iteratee`. The iteratee is invoked with three arguments: - * (value, key, object). + * This method is like `_.indexOf` except that it performs a binary + * search on a sorted `array`. * * @static * @memberOf _ - * @since 2.4.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Object} Returns the new mapped object. - * @see _.mapKeys + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @returns {number} Returns the index of the matched value, else `-1`. * @example * - * var users = { - * 'fred': { 'user': 'fred', 'age': 40 }, - * 'pebbles': { 'user': 'pebbles', 'age': 1 } - * }; - * - * _.mapValues(users, function(o) { return o.age; }); - * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) - * - * // The `_.property` iteratee shorthand. - * _.mapValues(users, 'age'); - * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) + * _.sortedIndexOf([4, 5, 5, 5, 6], 5); + * // => 1 */ - function mapValues(object, iteratee) { - var result = {}; - iteratee = getIteratee(iteratee, 3); - - baseForOwn(object, function(value, key, object) { - baseAssignValue(result, key, iteratee(value, key, object)); - }); - return result; + function sortedIndexOf(array, value) { + var length = array == null ? 0 : array.length; + if (length) { + var index = baseSortedIndex(array, value); + if (index < length && eq(array[index], value)) { + return index; + } + } + return -1; } /** - * This method is like `_.assign` except that it recursively merges own and - * inherited enumerable string keyed properties of source objects into the - * destination object. Source properties that resolve to `undefined` are - * skipped if a destination value exists. Array and plain object properties - * are merged recursively. Other objects and value types are overridden by - * assignment. Source objects are applied from left to right. Subsequent - * sources overwrite property assignments of previous sources. - * - * **Note:** This method mutates `object`. + * This method is like `_.sortedIndex` except that it returns the highest + * index at which `value` should be inserted into `array` in order to + * maintain its sort order. * * @static * @memberOf _ - * @since 0.5.0 - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. + * @since 3.0.0 + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. * @example * - * var object = { - * 'a': [{ 'b': 2 }, { 'd': 4 }] - * }; - * - * var other = { - * 'a': [{ 'c': 3 }, { 'e': 5 }] - * }; - * - * _.merge(object, other); - * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } + * _.sortedLastIndex([4, 5, 5, 5, 6], 5); + * // => 4 */ - var merge = createAssigner(function(object, source, srcIndex) { - baseMerge(object, source, srcIndex); - }); + function sortedLastIndex(array, value) { + return baseSortedIndex(array, value, true); + } /** - * This method is like `_.merge` except that it accepts `customizer` which - * is invoked to produce the merged values of the destination and source - * properties. If `customizer` returns `undefined`, merging is handled by the - * method instead. The `customizer` is invoked with six arguments: - * (objValue, srcValue, key, object, source, stack). - * - * **Note:** This method mutates `object`. + * This method is like `_.sortedLastIndex` except that it accepts `iteratee` + * which is invoked for `value` and each element of `array` to compute their + * sort ranking. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 - * @category Object - * @param {Object} object The destination object. - * @param {...Object} sources The source objects. - * @param {Function} customizer The function to customize assigned values. - * @returns {Object} Returns `object`. + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. * @example * - * function customizer(objValue, srcValue) { - * if (_.isArray(objValue)) { - * return objValue.concat(srcValue); - * } - * } + * var objects = [{ 'x': 4 }, { 'x': 5 }]; * - * var object = { 'a': [1], 'b': [2] }; - * var other = { 'a': [3], 'b': [4] }; + * _.sortedLastIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); + * // => 1 * - * _.mergeWith(object, other, customizer); - * // => { 'a': [1, 3], 'b': [2, 4] } + * // The `_.property` iteratee shorthand. + * _.sortedLastIndexBy(objects, { 'x': 4 }, 'x'); + * // => 1 */ - var mergeWith = createAssigner(function(object, source, srcIndex, customizer) { - baseMerge(object, source, srcIndex, customizer); - }); + function sortedLastIndexBy(array, value, iteratee) { + return baseSortedIndexBy(array, value, getIteratee(iteratee, 2), true); + } /** - * The opposite of `_.pick`; this method creates an object composed of the - * own and inherited enumerable property paths of `object` that are not omitted. - * - * **Note:** This method is considerably slower than `_.pick`. + * This method is like `_.lastIndexOf` except that it performs a binary + * search on a sorted `array`. * * @static - * @since 0.1.0 * @memberOf _ - * @category Object - * @param {Object} object The source object. - * @param {...(string|string[])} [paths] The property paths to omit. - * @returns {Object} Returns the new object. + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @returns {number} Returns the index of the matched value, else `-1`. * @example * - * var object = { 'a': 1, 'b': '2', 'c': 3 }; - * - * _.omit(object, ['a', 'c']); - * // => { 'b': '2' } + * _.sortedLastIndexOf([4, 5, 5, 5, 6], 5); + * // => 3 */ - var omit = flatRest(function(object, paths) { - var result = {}; - if (object == null) { - return result; - } - var isDeep = false; - paths = arrayMap(paths, function(path) { - path = castPath(path, object); - isDeep || (isDeep = path.length > 1); - return path; - }); - copyObject(object, getAllKeysIn(object), result); - if (isDeep) { - result = baseClone(result, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, customOmitClone); - } - var length = paths.length; - while (length--) { - baseUnset(result, paths[length]); + function sortedLastIndexOf(array, value) { + var length = array == null ? 0 : array.length; + if (length) { + var index = baseSortedIndex(array, value, true) - 1; + if (eq(array[index], value)) { + return index; + } } - return result; - }); + return -1; + } /** - * The opposite of `_.pickBy`; this method creates an object composed of - * the own and inherited enumerable string keyed properties of `object` that - * `predicate` doesn't return truthy for. The predicate is invoked with two - * arguments: (value, key). + * This method is like `_.uniq` except that it's designed and optimized + * for sorted arrays. * * @static * @memberOf _ * @since 4.0.0 - * @category Object - * @param {Object} object The source object. - * @param {Function} [predicate=_.identity] The function invoked per property. - * @returns {Object} Returns the new object. + * @category Array + * @param {Array} array The array to inspect. + * @returns {Array} Returns the new duplicate free array. * @example * - * var object = { 'a': 1, 'b': '2', 'c': 3 }; - * - * _.omitBy(object, _.isNumber); - * // => { 'b': '2' } + * _.sortedUniq([1, 1, 2]); + * // => [1, 2] */ - function omitBy(object, predicate) { - return pickBy(object, negate(getIteratee(predicate))); + function sortedUniq(array) { + return (array && array.length) + ? baseSortedUniq(array) + : []; } /** - * Creates an object composed of the picked `object` properties. + * This method is like `_.uniqBy` except that it's designed and optimized + * for sorted arrays. * * @static - * @since 0.1.0 * @memberOf _ - * @category Object - * @param {Object} object The source object. - * @param {...(string|string[])} [paths] The property paths to pick. - * @returns {Object} Returns the new object. + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @returns {Array} Returns the new duplicate free array. * @example * - * var object = { 'a': 1, 'b': '2', 'c': 3 }; - * - * _.pick(object, ['a', 'c']); - * // => { 'a': 1, 'c': 3 } + * _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor); + * // => [1.1, 2.3] */ - var pick = flatRest(function(object, paths) { - return object == null ? {} : basePick(object, paths); - }); + function sortedUniqBy(array, iteratee) { + return (array && array.length) + ? baseSortedUniq(array, getIteratee(iteratee, 2)) + : []; + } /** - * Creates an object composed of the `object` properties `predicate` returns - * truthy for. The predicate is invoked with two arguments: (value, key). + * Gets all but the first element of `array`. * * @static * @memberOf _ * @since 4.0.0 - * @category Object - * @param {Object} object The source object. - * @param {Function} [predicate=_.identity] The function invoked per property. - * @returns {Object} Returns the new object. + * @category Array + * @param {Array} array The array to query. + * @returns {Array} Returns the slice of `array`. * @example * - * var object = { 'a': 1, 'b': '2', 'c': 3 }; - * - * _.pickBy(object, _.isNumber); - * // => { 'a': 1, 'c': 3 } + * _.tail([1, 2, 3]); + * // => [2, 3] */ - function pickBy(object, predicate) { - if (object == null) { - return {}; - } - var props = arrayMap(getAllKeysIn(object), function(prop) { - return [prop]; - }); - predicate = getIteratee(predicate); - return basePickBy(object, props, function(value, path) { - return predicate(value, path[0]); - }); + function tail(array) { + var length = array == null ? 0 : array.length; + return length ? baseSlice(array, 1, length) : []; } /** - * This method is like `_.get` except that if the resolved value is a - * function it's invoked with the `this` binding of its parent object and - * its result is returned. + * Creates a slice of `array` with `n` elements taken from the beginning. * * @static - * @since 0.1.0 * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @param {Array|string} path The path of the property to resolve. - * @param {*} [defaultValue] The value returned for `undefined` resolved values. - * @returns {*} Returns the resolved value. + * @since 0.1.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to take. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. * @example * - * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] }; - * - * _.result(object, 'a[0].b.c1'); - * // => 3 + * _.take([1, 2, 3]); + * // => [1] * - * _.result(object, 'a[0].b.c2'); - * // => 4 + * _.take([1, 2, 3], 2); + * // => [1, 2] * - * _.result(object, 'a[0].b.c3', 'default'); - * // => 'default' + * _.take([1, 2, 3], 5); + * // => [1, 2, 3] * - * _.result(object, 'a[0].b.c3', _.constant('default')); - * // => 'default' + * _.take([1, 2, 3], 0); + * // => [] */ - function result(object, path, defaultValue) { - path = castPath(path, object); - - var index = -1, - length = path.length; - - // Ensure the loop is entered when path is empty. - if (!length) { - length = 1; - object = undefined; - } - while (++index < length) { - var value = object == null ? undefined : object[toKey(path[index])]; - if (value === undefined) { - index = length; - value = defaultValue; - } - object = isFunction(value) ? value.call(object) : value; + function take(array, n, guard) { + if (!(array && array.length)) { + return []; } - return object; + n = (guard || n === undefined) ? 1 : toInteger(n); + return baseSlice(array, 0, n < 0 ? 0 : n); } /** - * Sets the value at `path` of `object`. If a portion of `path` doesn't exist, - * it's created. Arrays are created for missing index properties while objects - * are created for all other missing properties. Use `_.setWith` to customize - * `path` creation. - * - * **Note:** This method mutates `object`. + * Creates a slice of `array` with `n` elements taken from the end. * * @static * @memberOf _ - * @since 3.7.0 - * @category Object - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to set. - * @param {*} value The value to set. - * @returns {Object} Returns `object`. + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to take. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. * @example * - * var object = { 'a': [{ 'b': { 'c': 3 } }] }; + * _.takeRight([1, 2, 3]); + * // => [3] * - * _.set(object, 'a[0].b.c', 4); - * console.log(object.a[0].b.c); - * // => 4 + * _.takeRight([1, 2, 3], 2); + * // => [2, 3] * - * _.set(object, ['x', '0', 'y', 'z'], 5); - * console.log(object.x[0].y.z); - * // => 5 + * _.takeRight([1, 2, 3], 5); + * // => [1, 2, 3] + * + * _.takeRight([1, 2, 3], 0); + * // => [] */ - function set(object, path, value) { - return object == null ? object : baseSet(object, path, value); + function takeRight(array, n, guard) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + n = (guard || n === undefined) ? 1 : toInteger(n); + n = length - n; + return baseSlice(array, n < 0 ? 0 : n, length); } /** - * This method is like `_.set` except that it accepts `customizer` which is - * invoked to produce the objects of `path`. If `customizer` returns `undefined` - * path creation is handled by the method instead. The `customizer` is invoked - * with three arguments: (nsValue, key, nsObject). - * - * **Note:** This method mutates `object`. + * Creates a slice of `array` with elements taken from the end. Elements are + * taken until `predicate` returns falsey. The predicate is invoked with + * three arguments: (value, index, array). * * @static * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to set. - * @param {*} value The value to set. - * @param {Function} [customizer] The function to customize assigned values. - * @returns {Object} Returns `object`. + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. * @example * - * var object = {}; - * - * _.setWith(object, '[0][1]', 'a', Object); - * // => { '0': { '1': 'a' } } - */ - function setWith(object, path, value, customizer) { - customizer = typeof customizer == 'function' ? customizer : undefined; - return object == null ? object : baseSet(object, path, value, customizer); - } - - /** - * Creates an array of own enumerable string keyed-value pairs for `object` - * which can be consumed by `_.fromPairs`. If `object` is a map or set, its - * entries are returned. + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; * - * @static - * @memberOf _ - * @since 4.0.0 - * @alias entries - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the key-value pairs. - * @example + * _.takeRightWhile(users, function(o) { return !o.active; }); + * // => objects for ['fred', 'pebbles'] * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } + * // The `_.matches` iteratee shorthand. + * _.takeRightWhile(users, { 'user': 'pebbles', 'active': false }); + * // => objects for ['pebbles'] * - * Foo.prototype.c = 3; + * // The `_.matchesProperty` iteratee shorthand. + * _.takeRightWhile(users, ['active', false]); + * // => objects for ['fred', 'pebbles'] * - * _.toPairs(new Foo); - * // => [['a', 1], ['b', 2]] (iteration order is not guaranteed) + * // The `_.property` iteratee shorthand. + * _.takeRightWhile(users, 'active'); + * // => [] */ - var toPairs = createToPairs(keys); + function takeRightWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, getIteratee(predicate, 3), false, true) + : []; + } /** - * Creates an array of own and inherited enumerable string keyed-value pairs - * for `object` which can be consumed by `_.fromPairs`. If `object` is a map - * or set, its entries are returned. + * Creates a slice of `array` with elements taken from the beginning. Elements + * are taken until `predicate` returns falsey. The predicate is invoked with + * three arguments: (value, index, array). * * @static * @memberOf _ - * @since 4.0.0 - * @alias entriesIn - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the key-value pairs. + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. * @example * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; * - * Foo.prototype.c = 3; + * _.takeWhile(users, function(o) { return !o.active; }); + * // => objects for ['barney', 'fred'] * - * _.toPairsIn(new Foo); - * // => [['a', 1], ['b', 2], ['c', 3]] (iteration order is not guaranteed) + * // The `_.matches` iteratee shorthand. + * _.takeWhile(users, { 'user': 'barney', 'active': false }); + * // => objects for ['barney'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.takeWhile(users, ['active', false]); + * // => objects for ['barney', 'fred'] + * + * // The `_.property` iteratee shorthand. + * _.takeWhile(users, 'active'); + * // => [] */ - var toPairsIn = createToPairs(keysIn); + function takeWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, getIteratee(predicate, 3)) + : []; + } /** - * An alternative to `_.reduce`; this method transforms `object` to a new - * `accumulator` object which is the result of running each of its own - * enumerable string keyed properties thru `iteratee`, with each invocation - * potentially mutating the `accumulator` object. If `accumulator` is not - * provided, a new object with the same `[[Prototype]]` will be used. The - * iteratee is invoked with four arguments: (accumulator, value, key, object). - * Iteratee functions may exit iteration early by explicitly returning `false`. + * Creates an array of unique values, in order, from all given arrays using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. * * @static * @memberOf _ - * @since 1.3.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @param {*} [accumulator] The custom accumulator value. - * @returns {*} Returns the accumulated value. + * @since 0.1.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of combined values. * @example * - * _.transform([2, 3, 4], function(result, n) { - * result.push(n *= n); - * return n % 2 == 0; - * }, []); - * // => [4, 9] - * - * _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { - * (result[value] || (result[value] = [])).push(key); - * }, {}); - * // => { '1': ['a', 'c'], '2': ['b'] } + * _.union([2], [1, 2]); + * // => [2, 1] */ - function transform(object, iteratee, accumulator) { - var isArr = isArray(object), - isArrLike = isArr || isBuffer(object) || isTypedArray(object); - - iteratee = getIteratee(iteratee, 4); - if (accumulator == null) { - var Ctor = object && object.constructor; - if (isArrLike) { - accumulator = isArr ? new Ctor : []; - } - else if (isObject(object)) { - accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {}; - } - else { - accumulator = {}; - } - } - (isArrLike ? arrayEach : baseForOwn)(object, function(value, index, object) { - return iteratee(accumulator, value, index, object); - }); - return accumulator; - } + var union = baseRest(function(arrays) { + return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true)); + }); /** - * Removes the property at `path` of `object`. - * - * **Note:** This method mutates `object`. + * This method is like `_.union` except that it accepts `iteratee` which is + * invoked for each element of each `arrays` to generate the criterion by + * which uniqueness is computed. Result values are chosen from the first + * array in which the value occurs. The iteratee is invoked with one argument: + * (value). * * @static * @memberOf _ * @since 4.0.0 - * @category Object - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to unset. - * @returns {boolean} Returns `true` if the property is deleted, else `false`. + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new array of combined values. * @example * - * var object = { 'a': [{ 'b': { 'c': 7 } }] }; - * _.unset(object, 'a[0].b.c'); - * // => true - * - * console.log(object); - * // => { 'a': [{ 'b': {} }] }; - * - * _.unset(object, ['a', '0', 'b', 'c']); - * // => true + * _.unionBy([2.1], [1.2, 2.3], Math.floor); + * // => [2.1, 1.2] * - * console.log(object); - * // => { 'a': [{ 'b': {} }] }; + * // The `_.property` iteratee shorthand. + * _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 1 }, { 'x': 2 }] */ - function unset(object, path) { - return object == null ? true : baseUnset(object, path); - } + var unionBy = baseRest(function(arrays) { + var iteratee = last(arrays); + if (isArrayLikeObject(iteratee)) { + iteratee = undefined; + } + return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)); + }); /** - * This method is like `_.set` except that accepts `updater` to produce the - * value to set. Use `_.updateWith` to customize `path` creation. The `updater` - * is invoked with one argument: (value). - * - * **Note:** This method mutates `object`. + * This method is like `_.union` except that it accepts `comparator` which + * is invoked to compare elements of `arrays`. Result values are chosen from + * the first array in which the value occurs. The comparator is invoked + * with two arguments: (arrVal, othVal). * * @static * @memberOf _ - * @since 4.6.0 - * @category Object - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to set. - * @param {Function} updater The function to produce the updated value. - * @returns {Object} Returns `object`. + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of combined values. * @example * - * var object = { 'a': [{ 'b': { 'c': 3 } }] }; - * - * _.update(object, 'a[0].b.c', function(n) { return n * n; }); - * console.log(object.a[0].b.c); - * // => 9 + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; * - * _.update(object, 'x[0].y.z', function(n) { return n ? n + 1 : 0; }); - * console.log(object.x[0].y.z); - * // => 0 + * _.unionWith(objects, others, _.isEqual); + * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] */ - function update(object, path, updater) { - return object == null ? object : baseUpdate(object, path, castFunction(updater)); - } + var unionWith = baseRest(function(arrays) { + var comparator = last(arrays); + comparator = typeof comparator == 'function' ? comparator : undefined; + return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), undefined, comparator); + }); /** - * This method is like `_.update` except that it accepts `customizer` which is - * invoked to produce the objects of `path`. If `customizer` returns `undefined` - * path creation is handled by the method instead. The `customizer` is invoked - * with three arguments: (nsValue, key, nsObject). - * - * **Note:** This method mutates `object`. + * Creates a duplicate-free version of an array, using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons, in which only the first occurrence of each element + * is kept. The order of result values is determined by the order they occur + * in the array. * * @static * @memberOf _ - * @since 4.6.0 - * @category Object - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to set. - * @param {Function} updater The function to produce the updated value. - * @param {Function} [customizer] The function to customize assigned values. - * @returns {Object} Returns `object`. + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @returns {Array} Returns the new duplicate free array. * @example * - * var object = {}; - * - * _.updateWith(object, '[0][1]', _.constant('a'), Object); - * // => { '0': { '1': 'a' } } + * _.uniq([2, 1, 2]); + * // => [2, 1] */ - function updateWith(object, path, updater, customizer) { - customizer = typeof customizer == 'function' ? customizer : undefined; - return object == null ? object : baseUpdate(object, path, castFunction(updater), customizer); + function uniq(array) { + return (array && array.length) ? baseUniq(array) : []; } /** - * Creates an array of the own enumerable string keyed property values of `object`. - * - * **Note:** Non-object values are coerced to objects. + * This method is like `_.uniq` except that it accepts `iteratee` which is + * invoked for each element in `array` to generate the criterion by which + * uniqueness is computed. The order of result values is determined by the + * order they occur in the array. The iteratee is invoked with one argument: + * (value). * * @static - * @since 0.1.0 * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property values. + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new duplicate free array. * @example * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.values(new Foo); - * // => [1, 2] (iteration order is not guaranteed) + * _.uniqBy([2.1, 1.2, 2.3], Math.floor); + * // => [2.1, 1.2] * - * _.values('hi'); - * // => ['h', 'i'] + * // The `_.property` iteratee shorthand. + * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 1 }, { 'x': 2 }] */ - function values(object) { - return object == null ? [] : baseValues(object, keys(object)); + function uniqBy(array, iteratee) { + return (array && array.length) ? baseUniq(array, getIteratee(iteratee, 2)) : []; } /** - * Creates an array of the own and inherited enumerable string keyed property - * values of `object`. - * - * **Note:** Non-object values are coerced to objects. + * This method is like `_.uniq` except that it accepts `comparator` which + * is invoked to compare elements of `array`. The order of result values is + * determined by the order they occur in the array.The comparator is invoked + * with two arguments: (arrVal, othVal). * * @static * @memberOf _ - * @since 3.0.0 - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property values. + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new duplicate free array. * @example * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }]; * - * _.valuesIn(new Foo); - * // => [1, 2, 3] (iteration order is not guaranteed) + * _.uniqWith(objects, _.isEqual); + * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }] */ - function valuesIn(object) { - return object == null ? [] : baseValues(object, keysIn(object)); + function uniqWith(array, comparator) { + comparator = typeof comparator == 'function' ? comparator : undefined; + return (array && array.length) ? baseUniq(array, undefined, comparator) : []; } - /*------------------------------------------------------------------------*/ - /** - * Clamps `number` within the inclusive `lower` and `upper` bounds. + * This method is like `_.zip` except that it accepts an array of grouped + * elements and creates an array regrouping the elements to their pre-zip + * configuration. * * @static * @memberOf _ - * @since 4.0.0 - * @category Number - * @param {number} number The number to clamp. - * @param {number} [lower] The lower bound. - * @param {number} upper The upper bound. - * @returns {number} Returns the clamped number. + * @since 1.2.0 + * @category Array + * @param {Array} array The array of grouped elements to process. + * @returns {Array} Returns the new array of regrouped elements. * @example * - * _.clamp(-10, -5, 5); - * // => -5 + * var zipped = _.zip(['a', 'b'], [1, 2], [true, false]); + * // => [['a', 1, true], ['b', 2, false]] * - * _.clamp(10, -5, 5); - * // => 5 + * _.unzip(zipped); + * // => [['a', 'b'], [1, 2], [true, false]] */ - function clamp(number, lower, upper) { - if (upper === undefined) { - upper = lower; - lower = undefined; - } - if (upper !== undefined) { - upper = toNumber(upper); - upper = upper === upper ? upper : 0; - } - if (lower !== undefined) { - lower = toNumber(lower); - lower = lower === lower ? lower : 0; + function unzip(array) { + if (!(array && array.length)) { + return []; } - return baseClamp(toNumber(number), lower, upper); + var length = 0; + array = arrayFilter(array, function(group) { + if (isArrayLikeObject(group)) { + length = nativeMax(group.length, length); + return true; + } + }); + return baseTimes(length, function(index) { + return arrayMap(array, baseProperty(index)); + }); } /** - * Checks if `n` is between `start` and up to, but not including, `end`. If - * `end` is not specified, it's set to `start` with `start` then set to `0`. - * If `start` is greater than `end` the params are swapped to support - * negative ranges. + * This method is like `_.unzip` except that it accepts `iteratee` to specify + * how regrouped values should be combined. The iteratee is invoked with the + * elements of each group: (...group). * * @static * @memberOf _ - * @since 3.3.0 - * @category Number - * @param {number} number The number to check. - * @param {number} [start=0] The start of the range. - * @param {number} end The end of the range. - * @returns {boolean} Returns `true` if `number` is in the range, else `false`. - * @see _.range, _.rangeRight + * @since 3.8.0 + * @category Array + * @param {Array} array The array of grouped elements to process. + * @param {Function} [iteratee=_.identity] The function to combine + * regrouped values. + * @returns {Array} Returns the new array of regrouped elements. * @example * - * _.inRange(3, 2, 4); - * // => true - * - * _.inRange(4, 8); - * // => true - * - * _.inRange(4, 2); - * // => false - * - * _.inRange(2, 2); - * // => false - * - * _.inRange(1.2, 2); - * // => true - * - * _.inRange(5.2, 4); - * // => false + * var zipped = _.zip([1, 2], [10, 20], [100, 200]); + * // => [[1, 10, 100], [2, 20, 200]] * - * _.inRange(-3, -2, -6); - * // => true + * _.unzipWith(zipped, _.add); + * // => [3, 30, 300] */ - function inRange(number, start, end) { - start = toFinite(start); - if (end === undefined) { - end = start; - start = 0; - } else { - end = toFinite(end); + function unzipWith(array, iteratee) { + if (!(array && array.length)) { + return []; } - number = toNumber(number); - return baseInRange(number, start, end); + var result = unzip(array); + if (iteratee == null) { + return result; + } + return arrayMap(result, function(group) { + return apply(iteratee, undefined, group); + }); } /** - * Produces a random number between the inclusive `lower` and `upper` bounds. - * If only one argument is provided a number between `0` and the given number - * is returned. If `floating` is `true`, or either `lower` or `upper` are - * floats, a floating-point number is returned instead of an integer. + * Creates an array excluding all given values using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. * - * **Note:** JavaScript follows the IEEE-754 standard for resolving - * floating-point values which can produce unexpected results. + * **Note:** Unlike `_.pull`, this method returns a new array. * * @static * @memberOf _ - * @since 0.7.0 - * @category Number - * @param {number} [lower=0] The lower bound. - * @param {number} [upper=1] The upper bound. - * @param {boolean} [floating] Specify returning a floating-point number. - * @returns {number} Returns the random number. + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...*} [values] The values to exclude. + * @returns {Array} Returns the new array of filtered values. + * @see _.difference, _.xor * @example * - * _.random(0, 5); - * // => an integer between 0 and 5 - * - * _.random(5); - * // => also an integer between 0 and 5 - * - * _.random(5, true); - * // => a floating-point number between 0 and 5 - * - * _.random(1.2, 5.2); - * // => a floating-point number between 1.2 and 5.2 + * _.without([2, 1, 2, 3], 1, 2); + * // => [3] */ - function random(lower, upper, floating) { - if (floating && typeof floating != 'boolean' && isIterateeCall(lower, upper, floating)) { - upper = floating = undefined; - } - if (floating === undefined) { - if (typeof upper == 'boolean') { - floating = upper; - upper = undefined; - } - else if (typeof lower == 'boolean') { - floating = lower; - lower = undefined; - } - } - if (lower === undefined && upper === undefined) { - lower = 0; - upper = 1; - } - else { - lower = toFinite(lower); - if (upper === undefined) { - upper = lower; - lower = 0; - } else { - upper = toFinite(upper); - } - } - if (lower > upper) { - var temp = lower; - lower = upper; - upper = temp; - } - if (floating || lower % 1 || upper % 1) { - var rand = nativeRandom(); - return nativeMin(lower + (rand * (upper - lower + freeParseFloat('1e-' + ((rand + '').length - 1)))), upper); - } - return baseRandom(lower, upper); - } - - /*------------------------------------------------------------------------*/ + var without = baseRest(function(array, values) { + return isArrayLikeObject(array) + ? baseDifference(array, values) + : []; + }); /** - * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase). + * Creates an array of unique values that is the + * [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference) + * of the given arrays. The order of result values is determined by the order + * they occur in the arrays. * * @static * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the camel cased string. + * @since 2.4.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of filtered values. + * @see _.difference, _.without * @example * - * _.camelCase('Foo Bar'); - * // => 'fooBar' - * - * _.camelCase('--foo-bar--'); - * // => 'fooBar' - * - * _.camelCase('__FOO_BAR__'); - * // => 'fooBar' + * _.xor([2, 1], [2, 3]); + * // => [1, 3] */ - var camelCase = createCompounder(function(result, word, index) { - word = word.toLowerCase(); - return result + (index ? capitalize(word) : word); + var xor = baseRest(function(arrays) { + return baseXor(arrayFilter(arrays, isArrayLikeObject)); }); /** - * Converts the first character of `string` to upper case and the remaining - * to lower case. + * This method is like `_.xor` except that it accepts `iteratee` which is + * invoked for each element of each `arrays` to generate the criterion by + * which by which they're compared. The order of result values is determined + * by the order they occur in the arrays. The iteratee is invoked with one + * argument: (value). * * @static * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to capitalize. - * @returns {string} Returns the capitalized string. + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new array of filtered values. * @example * - * _.capitalize('FRED'); - * // => 'Fred' + * _.xorBy([2.1, 1.2], [2.3, 3.4], Math.floor); + * // => [1.2, 3.4] + * + * // The `_.property` iteratee shorthand. + * _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 2 }] */ - function capitalize(string) { - return upperFirst(toString(string).toLowerCase()); - } + var xorBy = baseRest(function(arrays) { + var iteratee = last(arrays); + if (isArrayLikeObject(iteratee)) { + iteratee = undefined; + } + return baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee, 2)); + }); /** - * Deburrs `string` by converting - * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table) - * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A) - * letters to basic Latin letters and removing - * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). + * This method is like `_.xor` except that it accepts `comparator` which is + * invoked to compare elements of `arrays`. The order of result values is + * determined by the order they occur in the arrays. The comparator is invoked + * with two arguments: (arrVal, othVal). * * @static * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to deburr. - * @returns {string} Returns the deburred string. + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of filtered values. * @example * - * _.deburr('déjà vu'); - * // => 'deja vu' + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * + * _.xorWith(objects, others, _.isEqual); + * // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] */ - function deburr(string) { - string = toString(string); - return string && string.replace(reLatin, deburrLetter).replace(reComboMark, ''); - } + var xorWith = baseRest(function(arrays) { + var comparator = last(arrays); + comparator = typeof comparator == 'function' ? comparator : undefined; + return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined, comparator); + }); /** - * Checks if `string` ends with the given target string. + * Creates an array of grouped elements, the first of which contains the + * first elements of the given arrays, the second of which contains the + * second elements of the given arrays, and so on. * * @static * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to inspect. - * @param {string} [target] The string to search for. - * @param {number} [position=string.length] The position to search up to. - * @returns {boolean} Returns `true` if `string` ends with `target`, - * else `false`. + * @since 0.1.0 + * @category Array + * @param {...Array} [arrays] The arrays to process. + * @returns {Array} Returns the new array of grouped elements. * @example * - * _.endsWith('abc', 'c'); - * // => true - * - * _.endsWith('abc', 'b'); - * // => false - * - * _.endsWith('abc', 'b', 2); - * // => true + * _.zip(['a', 'b'], [1, 2], [true, false]); + * // => [['a', 1, true], ['b', 2, false]] */ - function endsWith(string, target, position) { - string = toString(string); - target = baseToString(target); - - var length = string.length; - position = position === undefined - ? length - : baseClamp(toInteger(position), 0, length); - - var end = position; - position -= target.length; - return position >= 0 && string.slice(position, end) == target; - } + var zip = baseRest(unzip); /** - * Converts the characters "&", "<", ">", '"', and "'" in `string` to their - * corresponding HTML entities. - * - * **Note:** No other characters are escaped. To escape additional - * characters use a third-party library like [_he_](https://mths.be/he). - * - * Though the ">" character is escaped for symmetry, characters like - * ">" and "/" don't need escaping in HTML and have no special meaning - * unless they're part of a tag or unquoted attribute value. See - * [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands) - * (under "semi-related fun fact") for more details. - * - * When working with HTML you should always - * [quote attribute values](http://wonko.com/post/html-escaping) to reduce - * XSS vectors. + * This method is like `_.fromPairs` except that it accepts two arrays, + * one of property identifiers and one of corresponding values. * * @static - * @since 0.1.0 * @memberOf _ - * @category String - * @param {string} [string=''] The string to escape. - * @returns {string} Returns the escaped string. + * @since 0.4.0 + * @category Array + * @param {Array} [props=[]] The property identifiers. + * @param {Array} [values=[]] The property values. + * @returns {Object} Returns the new object. * @example * - * _.escape('fred, barney, & pebbles'); - * // => 'fred, barney, & pebbles' + * _.zipObject(['a', 'b'], [1, 2]); + * // => { 'a': 1, 'b': 2 } */ - function escape(string) { - string = toString(string); - return (string && reHasUnescapedHtml.test(string)) - ? string.replace(reUnescapedHtml, escapeHtmlChar) - : string; + function zipObject(props, values) { + return baseZipObject(props || [], values || [], assignValue); } /** - * Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+", - * "?", "(", ")", "[", "]", "{", "}", and "|" in `string`. + * This method is like `_.zipObject` except that it supports property paths. * * @static * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to escape. - * @returns {string} Returns the escaped string. + * @since 4.1.0 + * @category Array + * @param {Array} [props=[]] The property identifiers. + * @param {Array} [values=[]] The property values. + * @returns {Object} Returns the new object. * @example * - * _.escapeRegExp('[lodash](https://lodash.com/)'); - * // => '\[lodash\]\(https://lodash\.com/\)' + * _.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]); + * // => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } } */ - function escapeRegExp(string) { - string = toString(string); - return (string && reHasRegExpChar.test(string)) - ? string.replace(reRegExpChar, '\\$&') - : string; + function zipObjectDeep(props, values) { + return baseZipObject(props || [], values || [], baseSet); } /** - * Converts `string` to - * [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles). + * This method is like `_.zip` except that it accepts `iteratee` to specify + * how grouped values should be combined. The iteratee is invoked with the + * elements of each group: (...group). * * @static * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the kebab cased string. + * @since 3.8.0 + * @category Array + * @param {...Array} [arrays] The arrays to process. + * @param {Function} [iteratee=_.identity] The function to combine + * grouped values. + * @returns {Array} Returns the new array of grouped elements. * @example * - * _.kebabCase('Foo Bar'); - * // => 'foo-bar' - * - * _.kebabCase('fooBar'); - * // => 'foo-bar' - * - * _.kebabCase('__FOO_BAR__'); - * // => 'foo-bar' + * _.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) { + * return a + b + c; + * }); + * // => [111, 222] */ - var kebabCase = createCompounder(function(result, word, index) { - return result + (index ? '-' : '') + word.toLowerCase(); + var zipWith = baseRest(function(arrays) { + var length = arrays.length, + iteratee = length > 1 ? arrays[length - 1] : undefined; + + iteratee = typeof iteratee == 'function' ? (arrays.pop(), iteratee) : undefined; + return unzipWith(arrays, iteratee); }); + /*------------------------------------------------------------------------*/ + /** - * Converts `string`, as space separated words, to lower case. + * Creates a `lodash` wrapper instance that wraps `value` with explicit method + * chain sequences enabled. The result of such sequences must be unwrapped + * with `_#value`. * * @static * @memberOf _ - * @since 4.0.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the lower cased string. + * @since 1.3.0 + * @category Seq + * @param {*} value The value to wrap. + * @returns {Object} Returns the new `lodash` wrapper instance. * @example * - * _.lowerCase('--Foo-Bar--'); - * // => 'foo bar' - * - * _.lowerCase('fooBar'); - * // => 'foo bar' + * var users = [ + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 }, + * { 'user': 'pebbles', 'age': 1 } + * ]; * - * _.lowerCase('__FOO_BAR__'); - * // => 'foo bar' + * var youngest = _ + * .chain(users) + * .sortBy('age') + * .map(function(o) { + * return o.user + ' is ' + o.age; + * }) + * .head() + * .value(); + * // => 'pebbles is 1' */ - var lowerCase = createCompounder(function(result, word, index) { - return result + (index ? ' ' : '') + word.toLowerCase(); - }); + function chain(value) { + var result = lodash(value); + result.__chain__ = true; + return result; + } /** - * Converts the first character of `string` to lower case. + * This method invokes `interceptor` and returns `value`. The interceptor + * is invoked with one argument; (value). The purpose of this method is to + * "tap into" a method chain sequence in order to modify intermediate results. * * @static * @memberOf _ - * @since 4.0.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the converted string. + * @since 0.1.0 + * @category Seq + * @param {*} value The value to provide to `interceptor`. + * @param {Function} interceptor The function to invoke. + * @returns {*} Returns `value`. * @example * - * _.lowerFirst('Fred'); - * // => 'fred' - * - * _.lowerFirst('FRED'); - * // => 'fRED' + * _([1, 2, 3]) + * .tap(function(array) { + * // Mutate input array. + * array.pop(); + * }) + * .reverse() + * .value(); + * // => [2, 1] */ - var lowerFirst = createCaseFirst('toLowerCase'); + function tap(value, interceptor) { + interceptor(value); + return value; + } /** - * Pads `string` on the left and right sides if it's shorter than `length`. - * Padding characters are truncated if they can't be evenly divided by `length`. + * This method is like `_.tap` except that it returns the result of `interceptor`. + * The purpose of this method is to "pass thru" values replacing intermediate + * results in a method chain sequence. * * @static * @memberOf _ * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to pad. - * @param {number} [length=0] The padding length. - * @param {string} [chars=' '] The string used as padding. - * @returns {string} Returns the padded string. + * @category Seq + * @param {*} value The value to provide to `interceptor`. + * @param {Function} interceptor The function to invoke. + * @returns {*} Returns the result of `interceptor`. * @example * - * _.pad('abc', 8); - * // => ' abc ' + * _(' abc ') + * .chain() + * .trim() + * .thru(function(value) { + * return [value]; + * }) + * .value(); + * // => ['abc'] + */ + function thru(value, interceptor) { + return interceptor(value); + } + + /** + * This method is the wrapper version of `_.at`. * - * _.pad('abc', 8, '_-'); - * // => '_-abc_-_' + * @name at + * @memberOf _ + * @since 1.0.0 + * @category Seq + * @param {...(string|string[])} [paths] The property paths to pick. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example * - * _.pad('abc', 3); - * // => 'abc' + * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; + * + * _(object).at(['a[0].b.c', 'a[1]']).value(); + * // => [3, 4] */ - function pad(string, length, chars) { - string = toString(string); - length = toInteger(length); + var wrapperAt = flatRest(function(paths) { + var length = paths.length, + start = length ? paths[0] : 0, + value = this.__wrapped__, + interceptor = function(object) { return baseAt(object, paths); }; - var strLength = length ? stringSize(string) : 0; - if (!length || strLength >= length) { - return string; + if (length > 1 || this.__actions__.length || + !(value instanceof LazyWrapper) || !isIndex(start)) { + return this.thru(interceptor); } - var mid = (length - strLength) / 2; - return ( - createPadding(nativeFloor(mid), chars) + - string + - createPadding(nativeCeil(mid), chars) - ); - } + value = value.slice(start, +start + (length ? 1 : 0)); + value.__actions__.push({ + 'func': thru, + 'args': [interceptor], + 'thisArg': undefined + }); + return new LodashWrapper(value, this.__chain__).thru(function(array) { + if (length && !array.length) { + array.push(undefined); + } + return array; + }); + }); /** - * Pads `string` on the right side if it's shorter than `length`. Padding - * characters are truncated if they exceed `length`. + * Creates a `lodash` wrapper instance with explicit method chain sequences enabled. * - * @static + * @name chain * @memberOf _ - * @since 4.0.0 - * @category String - * @param {string} [string=''] The string to pad. - * @param {number} [length=0] The padding length. - * @param {string} [chars=' '] The string used as padding. - * @returns {string} Returns the padded string. + * @since 0.1.0 + * @category Seq + * @returns {Object} Returns the new `lodash` wrapper instance. * @example * - * _.padEnd('abc', 6); - * // => 'abc ' + * var users = [ + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 } + * ]; * - * _.padEnd('abc', 6, '_-'); - * // => 'abc_-_' + * // A sequence without explicit chaining. + * _(users).head(); + * // => { 'user': 'barney', 'age': 36 } * - * _.padEnd('abc', 3); - * // => 'abc' + * // A sequence with explicit chaining. + * _(users) + * .chain() + * .head() + * .pick('user') + * .value(); + * // => { 'user': 'barney' } */ - function padEnd(string, length, chars) { - string = toString(string); - length = toInteger(length); - - var strLength = length ? stringSize(string) : 0; - return (length && strLength < length) - ? (string + createPadding(length - strLength, chars)) - : string; + function wrapperChain() { + return chain(this); } /** - * Pads `string` on the left side if it's shorter than `length`. Padding - * characters are truncated if they exceed `length`. + * Executes the chain sequence and returns the wrapped result. * - * @static + * @name commit * @memberOf _ - * @since 4.0.0 - * @category String - * @param {string} [string=''] The string to pad. - * @param {number} [length=0] The padding length. - * @param {string} [chars=' '] The string used as padding. - * @returns {string} Returns the padded string. + * @since 3.2.0 + * @category Seq + * @returns {Object} Returns the new `lodash` wrapper instance. * @example * - * _.padStart('abc', 6); - * // => ' abc' + * var array = [1, 2]; + * var wrapped = _(array).push(3); * - * _.padStart('abc', 6, '_-'); - * // => '_-_abc' + * console.log(array); + * // => [1, 2] * - * _.padStart('abc', 3); - * // => 'abc' + * wrapped = wrapped.commit(); + * console.log(array); + * // => [1, 2, 3] + * + * wrapped.last(); + * // => 3 + * + * console.log(array); + * // => [1, 2, 3] */ - function padStart(string, length, chars) { - string = toString(string); - length = toInteger(length); - - var strLength = length ? stringSize(string) : 0; - return (length && strLength < length) - ? (createPadding(length - strLength, chars) + string) - : string; + function wrapperCommit() { + return new LodashWrapper(this.value(), this.__chain__); } /** - * Converts `string` to an integer of the specified radix. If `radix` is - * `undefined` or `0`, a `radix` of `10` is used unless `value` is a - * hexadecimal, in which case a `radix` of `16` is used. - * - * **Note:** This method aligns with the - * [ES5 implementation](https://es5.github.io/#x15.1.2.2) of `parseInt`. + * Gets the next value on a wrapped object following the + * [iterator protocol](https://mdn.io/iteration_protocols#iterator). * - * @static + * @name next * @memberOf _ - * @since 1.1.0 - * @category String - * @param {string} string The string to convert. - * @param {number} [radix=10] The radix to interpret `value` by. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {number} Returns the converted integer. + * @since 4.0.0 + * @category Seq + * @returns {Object} Returns the next iterator value. * @example * - * _.parseInt('08'); - * // => 8 + * var wrapped = _([1, 2]); * - * _.map(['6', '08', '10'], _.parseInt); - * // => [6, 8, 10] + * wrapped.next(); + * // => { 'done': false, 'value': 1 } + * + * wrapped.next(); + * // => { 'done': false, 'value': 2 } + * + * wrapped.next(); + * // => { 'done': true, 'value': undefined } */ - function parseInt(string, radix, guard) { - if (guard || radix == null) { - radix = 0; - } else if (radix) { - radix = +radix; + function wrapperNext() { + if (this.__values__ === undefined) { + this.__values__ = toArray(this.value()); } - return nativeParseInt(toString(string).replace(reTrimStart, ''), radix || 0); + var done = this.__index__ >= this.__values__.length, + value = done ? undefined : this.__values__[this.__index__++]; + + return { 'done': done, 'value': value }; } /** - * Repeats the given string `n` times. + * Enables the wrapper to be iterable. * - * @static + * @name Symbol.iterator * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to repeat. - * @param {number} [n=1] The number of times to repeat the string. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {string} Returns the repeated string. + * @since 4.0.0 + * @category Seq + * @returns {Object} Returns the wrapper object. * @example * - * _.repeat('*', 3); - * // => '***' + * var wrapped = _([1, 2]); * - * _.repeat('abc', 2); - * // => 'abcabc' + * wrapped[Symbol.iterator]() === wrapped; + * // => true * - * _.repeat('abc', 0); - * // => '' + * Array.from(wrapped); + * // => [1, 2] */ - function repeat(string, n, guard) { - if ((guard ? isIterateeCall(string, n, guard) : n === undefined)) { - n = 1; - } else { - n = toInteger(n); - } - return baseRepeat(toString(string), n); + function wrapperToIterator() { + return this; } /** - * Replaces matches for `pattern` in `string` with `replacement`. - * - * **Note:** This method is based on - * [`String#replace`](https://mdn.io/String/replace). + * Creates a clone of the chain sequence planting `value` as the wrapped value. * - * @static + * @name plant * @memberOf _ - * @since 4.0.0 - * @category String - * @param {string} [string=''] The string to modify. - * @param {RegExp|string} pattern The pattern to replace. - * @param {Function|string} replacement The match replacement. - * @returns {string} Returns the modified string. + * @since 3.2.0 + * @category Seq + * @param {*} value The value to plant. + * @returns {Object} Returns the new `lodash` wrapper instance. * @example * - * _.replace('Hi Fred', 'Fred', 'Barney'); - * // => 'Hi Barney' + * function square(n) { + * return n * n; + * } + * + * var wrapped = _([1, 2]).map(square); + * var other = wrapped.plant([3, 4]); + * + * other.value(); + * // => [9, 16] + * + * wrapped.value(); + * // => [1, 4] */ - function replace() { - var args = arguments, - string = toString(args[0]); + function wrapperPlant(value) { + var result, + parent = this; - return args.length < 3 ? string : string.replace(args[1], args[2]); + while (parent instanceof baseLodash) { + var clone = wrapperClone(parent); + clone.__index__ = 0; + clone.__values__ = undefined; + if (result) { + previous.__wrapped__ = clone; + } else { + result = clone; + } + var previous = clone; + parent = parent.__wrapped__; + } + previous.__wrapped__ = value; + return result; } /** - * Converts `string` to - * [snake case](https://en.wikipedia.org/wiki/Snake_case). + * This method is the wrapper version of `_.reverse`. * - * @static + * **Note:** This method mutates the wrapped array. + * + * @name reverse * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the snake cased string. + * @since 0.1.0 + * @category Seq + * @returns {Object} Returns the new `lodash` wrapper instance. * @example * - * _.snakeCase('Foo Bar'); - * // => 'foo_bar' + * var array = [1, 2, 3]; * - * _.snakeCase('fooBar'); - * // => 'foo_bar' + * _(array).reverse().value() + * // => [3, 2, 1] * - * _.snakeCase('--FOO-BAR--'); - * // => 'foo_bar' + * console.log(array); + * // => [3, 2, 1] */ - var snakeCase = createCompounder(function(result, word, index) { - return result + (index ? '_' : '') + word.toLowerCase(); - }); + function wrapperReverse() { + var value = this.__wrapped__; + if (value instanceof LazyWrapper) { + var wrapped = value; + if (this.__actions__.length) { + wrapped = new LazyWrapper(this); + } + wrapped = wrapped.reverse(); + wrapped.__actions__.push({ + 'func': thru, + 'args': [reverse], + 'thisArg': undefined + }); + return new LodashWrapper(wrapped, this.__chain__); + } + return this.thru(reverse); + } /** - * Splits `string` by `separator`. - * - * **Note:** This method is based on - * [`String#split`](https://mdn.io/String/split). + * Executes the chain sequence to resolve the unwrapped value. * - * @static + * @name value * @memberOf _ - * @since 4.0.0 - * @category String - * @param {string} [string=''] The string to split. - * @param {RegExp|string} separator The separator pattern to split by. - * @param {number} [limit] The length to truncate results to. - * @returns {Array} Returns the string segments. + * @since 0.1.0 + * @alias toJSON, valueOf + * @category Seq + * @returns {*} Returns the resolved unwrapped value. * @example * - * _.split('a-b-c', '-', 2); - * // => ['a', 'b'] + * _([1, 2, 3]).value(); + * // => [1, 2, 3] */ - function split(string, separator, limit) { - if (limit && typeof limit != 'number' && isIterateeCall(string, separator, limit)) { - separator = limit = undefined; - } - limit = limit === undefined ? MAX_ARRAY_LENGTH : limit >>> 0; - if (!limit) { - return []; - } - string = toString(string); - if (string && ( - typeof separator == 'string' || - (separator != null && !isRegExp(separator)) - )) { - separator = baseToString(separator); - if (!separator && hasUnicode(string)) { - return castSlice(stringToArray(string), 0, limit); - } - } - return string.split(separator, limit); + function wrapperValue() { + return baseWrapperValue(this.__wrapped__, this.__actions__); } + /*------------------------------------------------------------------------*/ + /** - * Converts `string` to - * [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage). + * Creates an object composed of keys generated from the results of running + * each element of `collection` thru `iteratee`. The corresponding value of + * each key is the number of times the key was returned by `iteratee`. The + * iteratee is invoked with one argument: (value). * * @static * @memberOf _ - * @since 3.1.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the start cased string. + * @since 0.5.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The iteratee to transform keys. + * @returns {Object} Returns the composed aggregate object. * @example * - * _.startCase('--foo-bar--'); - * // => 'Foo Bar' - * - * _.startCase('fooBar'); - * // => 'Foo Bar' + * _.countBy([6.1, 4.2, 6.3], Math.floor); + * // => { '4': 1, '6': 2 } * - * _.startCase('__FOO_BAR__'); - * // => 'FOO BAR' + * // The `_.property` iteratee shorthand. + * _.countBy(['one', 'two', 'three'], 'length'); + * // => { '3': 2, '5': 1 } */ - var startCase = createCompounder(function(result, word, index) { - return result + (index ? ' ' : '') + upperFirst(word); + var countBy = createAggregator(function(result, value, key) { + if (hasOwnProperty.call(result, key)) { + ++result[key]; + } else { + baseAssignValue(result, key, 1); + } }); /** - * Checks if `string` starts with the given target string. + * Checks if `predicate` returns truthy for **all** elements of `collection`. + * Iteration is stopped once `predicate` returns falsey. The predicate is + * invoked with three arguments: (value, index|key, collection). + * + * **Note:** This method returns `true` for + * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because + * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of + * elements of empty collections. * * @static * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to inspect. - * @param {string} [target] The string to search for. - * @param {number} [position=0] The position to search from. - * @returns {boolean} Returns `true` if `string` starts with `target`, + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {boolean} Returns `true` if all elements pass the predicate check, * else `false`. * @example * - * _.startsWith('abc', 'a'); - * // => true + * _.every([true, 1, null, 'yes'], Boolean); + * // => false * - * _.startsWith('abc', 'b'); + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false }, + * { 'user': 'fred', 'age': 40, 'active': false } + * ]; + * + * // The `_.matches` iteratee shorthand. + * _.every(users, { 'user': 'barney', 'active': false }); * // => false * - * _.startsWith('abc', 'b', 1); + * // The `_.matchesProperty` iteratee shorthand. + * _.every(users, ['active', false]); * // => true + * + * // The `_.property` iteratee shorthand. + * _.every(users, 'active'); + * // => false */ - function startsWith(string, target, position) { - string = toString(string); - position = position == null - ? 0 - : baseClamp(toInteger(position), 0, string.length); - - target = baseToString(target); - return string.slice(position, position + target.length) == target; + function every(collection, predicate, guard) { + var func = isArray(collection) ? arrayEvery : baseEvery; + if (guard && isIterateeCall(collection, predicate, guard)) { + predicate = undefined; + } + return func(collection, getIteratee(predicate, 3)); } /** - * Creates a compiled template function that can interpolate data properties - * in "interpolate" delimiters, HTML-escape interpolated data properties in - * "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data - * properties may be accessed as free variables in the template. If a setting - * object is given, it takes precedence over `_.templateSettings` values. - * - * **Note:** In the development build `_.template` utilizes - * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl) - * for easier debugging. - * - * For more information on precompiling templates see - * [lodash's custom builds documentation](https://lodash.com/custom-builds). + * Iterates over elements of `collection`, returning an array of all elements + * `predicate` returns truthy for. The predicate is invoked with three + * arguments: (value, index|key, collection). * - * For more information on Chrome extension sandboxes see - * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval). + * **Note:** Unlike `_.remove`, this method returns a new array. * * @static - * @since 0.1.0 * @memberOf _ - * @category String - * @param {string} [string=''] The template string. - * @param {Object} [options={}] The options object. - * @param {RegExp} [options.escape=_.templateSettings.escape] - * The HTML "escape" delimiter. - * @param {RegExp} [options.evaluate=_.templateSettings.evaluate] - * The "evaluate" delimiter. - * @param {Object} [options.imports=_.templateSettings.imports] - * An object to import into the template as free variables. - * @param {RegExp} [options.interpolate=_.templateSettings.interpolate] - * The "interpolate" delimiter. - * @param {string} [options.sourceURL='lodash.templateSources[n]'] - * The sourceURL of the compiled template. - * @param {string} [options.variable='obj'] - * The data object variable name. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Function} Returns the compiled template function. + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + * @see _.reject * @example * - * // Use the "interpolate" delimiter to create a compiled template. - * var compiled = _.template('hello <%= user %>!'); - * compiled({ 'user': 'fred' }); - * // => 'hello fred!' + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': true }, + * { 'user': 'fred', 'age': 40, 'active': false } + * ]; * - * // Use the HTML "escape" delimiter to escape data property values. - * var compiled = _.template('<%- value %>'); - * compiled({ 'value': '