diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 52d6bb47e..ff9f20ba0 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -12,15 +12,6 @@ updates: open-pull-requests-limit: 10 labels: - 'type: dependencies' - ignore: - - dependency-name: '@hapi/joi' - versions: - - '>= 16.a' - - '< 18' - - dependency-name: '@types/hapi__joi' - versions: - - '>= 16.a' - - '< 18' - package-ecosystem: 'github-actions' directory: '/' schedule: diff --git a/bin/generate-schema.js b/bin/generate-schema.js index 498ef8bcd..6bfe6622e 100644 --- a/bin/generate-schema.js +++ b/bin/generate-schema.js @@ -1,5 +1,5 @@ // joi-to-json-schema currently does not support v16 of Joi (https://github.com/lightsofapollo/joi-to-json-schema/issues/57) -const convert = require('joi-to-json-schema') +const { convert } = require('@koa-lite/joi-schema') const fs = require('fs') const { schema } = require('../lib/schema') const inputArguments = process.argv.slice(2) || [] diff --git a/dist/index.js b/dist/index.js index e58b152d4..8b4d32249 100644 --- a/dist/index.js +++ b/dist/index.js @@ -1275,10304 +1275,2060 @@ exports.checkBypass = checkBypass; /***/ }), -/***/ 95541: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 97174: +/***/ ((__unused_webpack_module, exports) => { "use strict"; -const Url = __nccwpck_require__(57310); - const internals = { - minDomainSegments: 2, - nonAsciiRx: /[^\x00-\x7f]/, - domainControlRx: /[\x00-\x20@\:\/]/, // Control + space + separators - tldSegmentRx: /^[a-zA-Z](?:[a-zA-Z0-9\-]*[a-zA-Z0-9])?$/, - domainSegmentRx: /^[a-zA-Z0-9](?:[a-zA-Z0-9\-]*[a-zA-Z0-9])?$/, - URL: Url.URL || URL // $lab:coverage:ignore$ + suspectRx: /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*\:/ }; -exports.analyze = function (domain, options = {}) { +exports.parse = function (text, ...args) { - if (typeof domain !== 'string') { - throw new Error('Invalid input: domain must be a string'); + // Normalize arguments + + const firstOptions = typeof args[0] === 'object' && args[0]; + const reviver = args.length > 1 || !firstOptions ? args[0] : undefined; + const options = (args.length > 1 && args[1]) || firstOptions || {}; + + // Parse normally, allowing exceptions + + const obj = JSON.parse(text, reviver); + + // options.protoAction: 'error' (default) / 'remove' / 'ignore' + + if (options.protoAction === 'ignore') { + return obj; } - if (!domain) { - return { error: 'Domain must be a non-empty string' }; + // Ignore null and non-objects + + if (!obj || + typeof obj !== 'object') { + + return obj; } - if (domain.length > 256) { - return { error: 'Domain too long' }; + // Check original string for potential exploit + + if (!text.match(internals.suspectRx)) { + return obj; } - const ascii = !internals.nonAsciiRx.test(domain); - if (!ascii) { - if (options.allowUnicode === false) { // Defaults to true - return { error: 'Domain contains forbidden Unicode characters' }; - } + // Scan result for proto keys - domain = domain.normalize('NFC'); + exports.scan(obj, options); + + return obj; +}; + + +exports.scan = function (obj, options = {}) { + + let next = [obj]; + + while (next.length) { + const nodes = next; + next = []; + + for (const node of nodes) { + if (Object.prototype.hasOwnProperty.call(node, '__proto__')) { // Avoid calling node.hasOwnProperty directly + if (options.protoAction !== 'remove') { + throw new SyntaxError('Object contains forbidden prototype property'); + } + + delete node.__proto__; + } + + for (const key in node) { + const value = node[key]; + if (value && + typeof value === 'object') { + + next.push(node[key]); + } + } + } } +}; - if (internals.domainControlRx.test(domain)) { - return { error: 'Domain contains invalid character' }; + +exports.safeParse = function (text, reviver) { + + try { + return exports.parse(text, reviver); + } + catch (ignoreError) { + return null; } +}; - domain = internals.punycode(domain); - // https://tools.ietf.org/html/rfc1035 section 2.3.1 +/***/ }), - const minDomainSegments = options.minDomainSegments || internals.minDomainSegments; +/***/ 85545: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - const segments = domain.split('.'); - if (segments.length < minDomainSegments) { - return { error: 'Domain lacks the minimum required number of segments' }; +"use strict"; + + +const Assert = __nccwpck_require__(32718); +const Clone = __nccwpck_require__(85578); +const Merge = __nccwpck_require__(60445); +const Reach = __nccwpck_require__(18891); + + +const internals = {}; + + +module.exports = function (defaults, source, options = {}) { + + Assert(defaults && typeof defaults === 'object', 'Invalid defaults value: must be an object'); + Assert(!source || source === true || typeof source === 'object', 'Invalid source value: must be true, falsy or an object'); + Assert(typeof options === 'object', 'Invalid options: must be an object'); + + if (!source) { // If no source, return null + return null; } - const tlds = options.tlds; - if (tlds) { - const tld = segments[segments.length - 1].toLowerCase(); - if (tlds.deny && tlds.deny.has(tld) || - tlds.allow && !tlds.allow.has(tld)) { + if (options.shallow) { + return internals.applyToDefaultsWithShallow(defaults, source, options); + } - return { error: 'Domain uses forbidden TLD' }; - } + const copy = Clone(defaults); + + if (source === true) { // If source is set to true, use defaults + return copy; } - for (let i = 0; i < segments.length; ++i) { - const segment = segments[i]; + const nullOverride = options.nullOverride !== undefined ? options.nullOverride : false; + return Merge(copy, source, { nullOverride, mergeArrays: false }); +}; - if (!segment.length) { - return { error: 'Domain contains empty dot-separated segment' }; - } - if (segment.length > 63) { - return { error: 'Domain contains dot-separated segment that is too long' }; - } +internals.applyToDefaultsWithShallow = function (defaults, source, options) { - if (i < segments.length - 1) { - if (!internals.domainSegmentRx.test(segment)) { - return { error: 'Domain contains invalid character' }; - } + const keys = options.shallow; + Assert(Array.isArray(keys), 'Invalid keys'); + + const seen = new Map(); + const merge = source === true ? null : new Set(); + + for (let key of keys) { + key = Array.isArray(key) ? key : key.split('.'); // Pre-split optimization + + const ref = Reach(defaults, key); + if (ref && + typeof ref === 'object') { + + seen.set(ref, merge && Reach(source, key) || ref); } - else { - if (!internals.tldSegmentRx.test(segment)) { - return { error: 'Domain contains invalid tld character' }; - } + else if (merge) { + merge.add(key); } } -}; + const copy = Clone(defaults, {}, seen); -exports.isValid = function (domain, options) { + if (!merge) { + return copy; + } - return !exports.analyze(domain, options); + for (const key of merge) { + internals.reachCopy(copy, source, key); + } + + const nullOverride = options.nullOverride !== undefined ? options.nullOverride : false; + return Merge(copy, source, { nullOverride, mergeArrays: false }); }; -internals.punycode = function (domain) { +internals.reachCopy = function (dst, src, path) { - try { - return new internals.URL(`http://${domain}`).host; + for (const segment of path) { + if (!(segment in src)) { + return; + } + + const val = src[segment]; + + if (typeof val !== 'object' || val === null) { + return; + } + + src = val; } - catch (err) { - return domain; + + const value = src; + let ref = dst; + for (let i = 0; i < path.length - 1; ++i) { + const segment = path[i]; + if (typeof ref[segment] !== 'object') { + ref[segment] = {}; + } + + ref = ref[segment]; } + + ref[path[path.length - 1]] = value; }; /***/ }), -/***/ 67318: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 32718: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const Util = __nccwpck_require__(73837); +const AssertError = __nccwpck_require__(35563); -const Domain = __nccwpck_require__(95541); +const internals = {}; -const internals = { - nonAsciiRx: /[^\x00-\x7f]/, - encoder: new (Util.TextEncoder || TextEncoder)() // $lab:coverage:ignore$ -}; +module.exports = function (condition, ...args) { + + if (condition) { + return; + } + if (args.length === 1 && + args[0] instanceof Error) { -exports.analyze = function (email, options) { + throw args[0]; + } - return internals.email(email, options); + throw new AssertError(args); }; -exports.isValid = function (email, options) { +/***/ }), - return !internals.email(email, options); +/***/ 85578: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const Reach = __nccwpck_require__(18891); +const Types = __nccwpck_require__(84340); +const Utils = __nccwpck_require__(30417); + + +const internals = { + needsProtoHack: new Set([Types.set, Types.map, Types.weakSet, Types.weakMap]) }; -internals.email = function (email, options = {}) { +module.exports = internals.clone = function (obj, options = {}, _seen = null) { - if (typeof email !== 'string') { - throw new Error('Invalid input: email must be a string'); - } + if (typeof obj !== 'object' || + obj === null) { - if (!email) { - return { error: 'Address must be a non-empty string' }; + return obj; } - // Unicode + let clone = internals.clone; + let seen = _seen; - const ascii = !internals.nonAsciiRx.test(email); - if (!ascii) { - if (options.allowUnicode === false) { // Defaults to true - return { error: 'Address contains forbidden Unicode characters' }; + if (options.shallow) { + if (options.shallow !== true) { + return internals.cloneWithShallow(obj, options); } - email = email.normalize('NFC'); + clone = (value) => value; } - - // Basic structure - - const parts = email.split('@'); - if (parts.length !== 2) { - return { error: parts.length > 2 ? 'Address cannot contain more than one @ character' : 'Address must contain one @ character' }; + else if (seen) { + const lookup = seen.get(obj); + if (lookup) { + return lookup; + } + } + else { + seen = new Map(); } - const [local, domain] = parts; + // Built-in object types - if (!local) { - return { error: 'Address local part cannot be empty' }; + const baseProto = Types.getInternalProto(obj); + if (baseProto === Types.buffer) { + return Buffer && Buffer.from(obj); // $lab:coverage:ignore$ } - if (!options.ignoreLength) { - if (email.length > 254) { // http://tools.ietf.org/html/rfc5321#section-4.5.3.1.3 - return { error: 'Address too long' }; - } + if (baseProto === Types.date) { + return new Date(obj.getTime()); + } - if (internals.encoder.encode(local).length > 64) { // http://tools.ietf.org/html/rfc5321#section-4.5.3.1.1 - return { error: 'Address local part too long' }; - } + if (baseProto === Types.regex) { + return new RegExp(obj); } - // Validate parts + // Generic objects - return internals.local(local, ascii) || Domain.analyze(domain, options); -}; + const newObj = internals.base(obj, baseProto, options); + if (newObj === obj) { + return obj; + } + if (seen) { + seen.set(obj, newObj); // Set seen, since obj could recurse + } -internals.local = function (local, ascii) { + if (baseProto === Types.set) { + for (const value of obj) { + newObj.add(clone(value, options, seen)); + } + } + else if (baseProto === Types.map) { + for (const [key, value] of obj) { + newObj.set(key, clone(value, options, seen)); + } + } - const segments = local.split('.'); - for (const segment of segments) { - if (!segment.length) { - return { error: 'Address local part contains empty dot-separated segment' }; + const keys = Utils.keys(obj, options); + for (const key of keys) { + if (key === '__proto__') { + continue; } - if (ascii) { - if (!internals.atextRx.test(segment)) { - return { error: 'Address local part contains invalid character' }; - } + if (baseProto === Types.array && + key === 'length') { + newObj.length = obj.length; continue; } - for (const char of segment) { - if (internals.atextRx.test(char)) { - continue; - } + const descriptor = Object.getOwnPropertyDescriptor(obj, key); + if (descriptor) { + if (descriptor.get || + descriptor.set) { - const binary = internals.binary(char); - if (!internals.atomRx.test(binary)) { - return { error: 'Address local part contains invalid character' }; + Object.defineProperty(newObj, key, descriptor); + } + else if (descriptor.enumerable) { + newObj[key] = clone(obj[key], options, seen); } + else { + Object.defineProperty(newObj, key, { enumerable: false, writable: true, configurable: true, value: clone(obj[key], options, seen) }); + } + } + else { + Object.defineProperty(newObj, key, { + enumerable: true, + writable: true, + configurable: true, + value: clone(obj[key], options, seen) + }); } } -}; - -internals.binary = function (char) { - - return Array.from(internals.encoder.encode(char)).map((v) => String.fromCharCode(v)).join(''); + return newObj; }; -/* - From RFC 5321: - - Mailbox = Local-part "@" ( Domain / address-literal ) - - Local-part = Dot-string / Quoted-string - Dot-string = Atom *("." Atom) - Atom = 1*atext - atext = ALPHA / DIGIT / "!" / "#" / "$" / "%" / "&" / "'" / "*" / "+" / "-" / "/" / "=" / "?" / "^" / "_" / "`" / "{" / "|" / "}" / "~" - - Domain = sub-domain *("." sub-domain) - sub-domain = Let-dig [Ldh-str] - Let-dig = ALPHA / DIGIT - Ldh-str = *( ALPHA / DIGIT / "-" ) Let-dig +internals.cloneWithShallow = function (source, options) { - ALPHA = %x41-5A / %x61-7A ; a-z, A-Z - DIGIT = %x30-39 ; 0-9 + const keys = options.shallow; + options = Object.assign({}, options); + options.shallow = false; - From RFC 6531: + const seen = new Map(); - sub-domain =/ U-label - atext =/ UTF8-non-ascii + for (const key of keys) { + const ref = Reach(source, key); + if (typeof ref === 'object' || + typeof ref === 'function') { - UTF8-non-ascii = UTF8-2 / UTF8-3 / UTF8-4 + seen.set(ref, ref); + } + } - UTF8-2 = %xC2-DF UTF8-tail - UTF8-3 = %xE0 %xA0-BF UTF8-tail / - %xE1-EC 2( UTF8-tail ) / - %xED %x80-9F UTF8-tail / - %xEE-EF 2( UTF8-tail ) - UTF8-4 = %xF0 %x90-BF 2( UTF8-tail ) / - %xF1-F3 3( UTF8-tail ) / - %xF4 %x80-8F 2( UTF8-tail ) + return internals.clone(source, options, seen); +}; - UTF8-tail = %x80-BF - Note: The following are not supported: +internals.base = function (obj, baseProto, options) { - RFC 5321: address-literal, Quoted-string - RFC 5322: obs-*, CFWS -*/ + if (options.prototype === false) { // Defaults to true + if (internals.needsProtoHack.has(baseProto)) { + return new baseProto.constructor(); + } + return baseProto === Types.array ? [] : {}; + } -internals.atextRx = /^[\w!#\$%&'\*\+\-/=\?\^`\{\|\}~]+$/; // _ included in \w + const proto = Object.getPrototypeOf(obj); + if (proto && + proto.isImmutable) { + return obj; + } -internals.atomRx = new RegExp([ + if (baseProto === Types.array) { + const newObj = []; + if (proto !== baseProto) { + Object.setPrototypeOf(newObj, proto); + } - // %xC2-DF UTF8-tail - '(?:[\\xc2-\\xdf][\\x80-\\xbf])', + return newObj; + } - // %xE0 %xA0-BF UTF8-tail %xE1-EC 2( UTF8-tail ) %xED %x80-9F UTF8-tail %xEE-EF 2( UTF8-tail ) - '(?:\\xe0[\\xa0-\\xbf][\\x80-\\xbf])|(?:[\\xe1-\\xec][\\x80-\\xbf]{2})|(?:\\xed[\\x80-\\x9f][\\x80-\\xbf])|(?:[\\xee-\\xef][\\x80-\\xbf]{2})', + if (internals.needsProtoHack.has(baseProto)) { + const newObj = new proto.constructor(); + if (proto !== baseProto) { + Object.setPrototypeOf(newObj, proto); + } - // %xF0 %x90-BF 2( UTF8-tail ) %xF1-F3 3( UTF8-tail ) %xF4 %x80-8F 2( UTF8-tail ) - '(?:\\xf0[\\x90-\\xbf][\\x80-\\xbf]{2})|(?:[\\xf1-\\xf3][\\x80-\\xbf]{3})|(?:\\xf4[\\x80-\\x8f][\\x80-\\xbf]{2})' + return newObj; + } -].join('|')); + return Object.create(proto); +}; /***/ }), -/***/ 9491: +/***/ 55801: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const Domain = __nccwpck_require__(95541); -const Email = __nccwpck_require__(67318); -const Tlds = __nccwpck_require__(5026); +const Types = __nccwpck_require__(84340); const internals = { - defaultTlds: { allow: Tlds, deny: null } + mismatched: null }; -module.exports = { - domain: { - analyze(domain, options) { - - options = internals.options(options); - return Domain.analyze(domain, options); - }, +module.exports = function (obj, ref, options) { - isValid(domain, options) { + options = Object.assign({ prototype: true }, options); - options = internals.options(options); - return Domain.isValid(domain, options); - } - }, - email: { - analyze(email, options) { + return !!internals.isDeepEqual(obj, ref, options, []); +}; - options = internals.options(options); - return Email.analyze(email, options); - }, - isValid(email, options) { +internals.isDeepEqual = function (obj, ref, options, seen) { - options = internals.options(options); - return Email.isValid(email, options); - } + if (obj === ref) { // Copied from Deep-eql, copyright(c) 2013 Jake Luer, jake@alogicalparadox.com, MIT Licensed, https://github.com/chaijs/deep-eql + return obj !== 0 || 1 / obj === 1 / ref; } -}; - -internals.options = function (options) { + const type = typeof obj; - if (!options) { - return { tlds: internals.defaultTlds }; + if (type !== typeof ref) { + return false; } - if (options.tlds === false) { // Defaults to true - return options; + if (obj === null || + ref === null) { + + return false; } - if (!options.tlds || - options.tlds === true) { + if (type === 'function') { + if (!options.deepFunction || + obj.toString() !== ref.toString()) { + + return false; + } - return Object.assign({}, options, { tlds: internals.defaultTlds }); + // Continue as object + } + else if (type !== 'object') { + return obj !== obj && ref !== ref; // NaN } - if (typeof options.tlds !== 'object') { - throw new Error('Invalid options: tlds must be a boolean or an object'); + const instanceType = internals.getSharedType(obj, ref, !!options.prototype); + switch (instanceType) { + case Types.buffer: + return Buffer && Buffer.prototype.equals.call(obj, ref); // $lab:coverage:ignore$ + case Types.promise: + return obj === ref; + case Types.regex: + return obj.toString() === ref.toString(); + case internals.mismatched: + return false; } - if (options.tlds.deny) { - if (options.tlds.deny instanceof Set === false) { - throw new Error('Invalid options: tlds.deny must be a Set object'); + for (let i = seen.length - 1; i >= 0; --i) { + if (seen[i].isSame(obj, ref)) { + return true; // If previous comparison failed, it would have stopped execution } + } + + seen.push(new internals.SeenEntry(obj, ref)); + + try { + return !!internals.isDeepEqualObj(instanceType, obj, ref, options, seen); + } + finally { + seen.pop(); + } +}; + - if (options.tlds.allow) { - throw new Error('Invalid options: cannot specify both tlds.allow and tlds.deny lists'); +internals.getSharedType = function (obj, ref, checkPrototype) { + + if (checkPrototype) { + if (Object.getPrototypeOf(obj) !== Object.getPrototypeOf(ref)) { + return internals.mismatched; } - return options; + return Types.getInternalProto(obj); } - if (options.tlds.allow === true) { - return Object.assign({}, options, { tlds: internals.defaultTlds }); + const type = Types.getInternalProto(obj); + if (type !== Types.getInternalProto(ref)) { + return internals.mismatched; } - if (options.tlds.allow instanceof Set === false) { - throw new Error('Invalid options: tlds.allow must be a Set object or true'); + return type; +}; + + +internals.valueOf = function (obj) { + + const objValueOf = obj.valueOf; + if (objValueOf === undefined) { + return obj; } - return options; + try { + return objValueOf.call(obj); + } + catch (err) { + return err; + } }; -/***/ }), +internals.hasOwnEnumerableProperty = function (obj, key) { -/***/ 5026: -/***/ ((module) => { + return Object.prototype.propertyIsEnumerable.call(obj, key); +}; -"use strict"; +internals.isSetSimpleEqual = function (obj, ref) { -const internals = {}; + for (const entry of Set.prototype.values.call(obj)) { + if (!Set.prototype.has.call(ref, entry)) { + return false; + } + } + return true; +}; -// http://data.iana.org/TLD/tlds-alpha-by-domain.txt -// # Version 2019091902, Last Updated Fri Sep 20 07: 07: 02 2019 UTC +internals.isDeepEqualObj = function (instanceType, obj, ref, options, seen) { -internals.tlds = [ - 'AAA', - 'AARP', - 'ABARTH', - 'ABB', - 'ABBOTT', - 'ABBVIE', - 'ABC', - 'ABLE', - 'ABOGADO', - 'ABUDHABI', - 'AC', - 'ACADEMY', - 'ACCENTURE', - 'ACCOUNTANT', - 'ACCOUNTANTS', - 'ACO', - 'ACTOR', - 'AD', - 'ADAC', - 'ADS', - 'ADULT', - 'AE', - 'AEG', - 'AERO', - 'AETNA', - 'AF', - 'AFAMILYCOMPANY', - 'AFL', - 'AFRICA', - 'AG', - 'AGAKHAN', - 'AGENCY', - 'AI', - 'AIG', - 'AIGO', - 'AIRBUS', - 'AIRFORCE', - 'AIRTEL', - 'AKDN', - 'AL', - 'ALFAROMEO', - 'ALIBABA', - 'ALIPAY', - 'ALLFINANZ', - 'ALLSTATE', - 'ALLY', - 'ALSACE', - 'ALSTOM', - 'AM', - 'AMERICANEXPRESS', - 'AMERICANFAMILY', - 'AMEX', - 'AMFAM', - 'AMICA', - 'AMSTERDAM', - 'ANALYTICS', - 'ANDROID', - 'ANQUAN', - 'ANZ', - 'AO', - 'AOL', - 'APARTMENTS', - 'APP', - 'APPLE', - 'AQ', - 'AQUARELLE', - 'AR', - 'ARAB', - 'ARAMCO', - 'ARCHI', - 'ARMY', - 'ARPA', - 'ART', - 'ARTE', - 'AS', - 'ASDA', - 'ASIA', - 'ASSOCIATES', - 'AT', - 'ATHLETA', - 'ATTORNEY', - 'AU', - 'AUCTION', - 'AUDI', - 'AUDIBLE', - 'AUDIO', - 'AUSPOST', - 'AUTHOR', - 'AUTO', - 'AUTOS', - 'AVIANCA', - 'AW', - 'AWS', - 'AX', - 'AXA', - 'AZ', - 'AZURE', - 'BA', - 'BABY', - 'BAIDU', - 'BANAMEX', - 'BANANAREPUBLIC', - 'BAND', - 'BANK', - 'BAR', - 'BARCELONA', - 'BARCLAYCARD', - 'BARCLAYS', - 'BAREFOOT', - 'BARGAINS', - 'BASEBALL', - 'BASKETBALL', - 'BAUHAUS', - 'BAYERN', - 'BB', - 'BBC', - 'BBT', - 'BBVA', - 'BCG', - 'BCN', - 'BD', - 'BE', - 'BEATS', - 'BEAUTY', - 'BEER', - 'BENTLEY', - 'BERLIN', - 'BEST', - 'BESTBUY', - 'BET', - 'BF', - 'BG', - 'BH', - 'BHARTI', - 'BI', - 'BIBLE', - 'BID', - 'BIKE', - 'BING', - 'BINGO', - 'BIO', - 'BIZ', - 'BJ', - 'BLACK', - 'BLACKFRIDAY', - 'BLOCKBUSTER', - 'BLOG', - 'BLOOMBERG', - 'BLUE', - 'BM', - 'BMS', - 'BMW', - 'BN', - 'BNPPARIBAS', - 'BO', - 'BOATS', - 'BOEHRINGER', - 'BOFA', - 'BOM', - 'BOND', - 'BOO', - 'BOOK', - 'BOOKING', - 'BOSCH', - 'BOSTIK', - 'BOSTON', - 'BOT', - 'BOUTIQUE', - 'BOX', - 'BR', - 'BRADESCO', - 'BRIDGESTONE', - 'BROADWAY', - 'BROKER', - 'BROTHER', - 'BRUSSELS', - 'BS', - 'BT', - 'BUDAPEST', - 'BUGATTI', - 'BUILD', - 'BUILDERS', - 'BUSINESS', - 'BUY', - 'BUZZ', - 'BV', - 'BW', - 'BY', - 'BZ', - 'BZH', - 'CA', - 'CAB', - 'CAFE', - 'CAL', - 'CALL', - 'CALVINKLEIN', - 'CAM', - 'CAMERA', - 'CAMP', - 'CANCERRESEARCH', - 'CANON', - 'CAPETOWN', - 'CAPITAL', - 'CAPITALONE', - 'CAR', - 'CARAVAN', - 'CARDS', - 'CARE', - 'CAREER', - 'CAREERS', - 'CARS', - 'CARTIER', - 'CASA', - 'CASE', - 'CASEIH', - 'CASH', - 'CASINO', - 'CAT', - 'CATERING', - 'CATHOLIC', - 'CBA', - 'CBN', - 'CBRE', - 'CBS', - 'CC', - 'CD', - 'CEB', - 'CENTER', - 'CEO', - 'CERN', - 'CF', - 'CFA', - 'CFD', - 'CG', - 'CH', - 'CHANEL', - 'CHANNEL', - 'CHARITY', - 'CHASE', - 'CHAT', - 'CHEAP', - 'CHINTAI', - 'CHRISTMAS', - 'CHROME', - 'CHRYSLER', - 'CHURCH', - 'CI', - 'CIPRIANI', - 'CIRCLE', - 'CISCO', - 'CITADEL', - 'CITI', - 'CITIC', - 'CITY', - 'CITYEATS', - 'CK', - 'CL', - 'CLAIMS', - 'CLEANING', - 'CLICK', - 'CLINIC', - 'CLINIQUE', - 'CLOTHING', - 'CLOUD', - 'CLUB', - 'CLUBMED', - 'CM', - 'CN', - 'CO', - 'COACH', - 'CODES', - 'COFFEE', - 'COLLEGE', - 'COLOGNE', - 'COM', - 'COMCAST', - 'COMMBANK', - 'COMMUNITY', - 'COMPANY', - 'COMPARE', - 'COMPUTER', - 'COMSEC', - 'CONDOS', - 'CONSTRUCTION', - 'CONSULTING', - 'CONTACT', - 'CONTRACTORS', - 'COOKING', - 'COOKINGCHANNEL', - 'COOL', - 'COOP', - 'CORSICA', - 'COUNTRY', - 'COUPON', - 'COUPONS', - 'COURSES', - 'CR', - 'CREDIT', - 'CREDITCARD', - 'CREDITUNION', - 'CRICKET', - 'CROWN', - 'CRS', - 'CRUISE', - 'CRUISES', - 'CSC', - 'CU', - 'CUISINELLA', - 'CV', - 'CW', - 'CX', - 'CY', - 'CYMRU', - 'CYOU', - 'CZ', - 'DABUR', - 'DAD', - 'DANCE', - 'DATA', - 'DATE', - 'DATING', - 'DATSUN', - 'DAY', - 'DCLK', - 'DDS', - 'DE', - 'DEAL', - 'DEALER', - 'DEALS', - 'DEGREE', - 'DELIVERY', - 'DELL', - 'DELOITTE', - 'DELTA', - 'DEMOCRAT', - 'DENTAL', - 'DENTIST', - 'DESI', - 'DESIGN', - 'DEV', - 'DHL', - 'DIAMONDS', - 'DIET', - 'DIGITAL', - 'DIRECT', - 'DIRECTORY', - 'DISCOUNT', - 'DISCOVER', - 'DISH', - 'DIY', - 'DJ', - 'DK', - 'DM', - 'DNP', - 'DO', - 'DOCS', - 'DOCTOR', - 'DODGE', - 'DOG', - 'DOMAINS', - 'DOT', - 'DOWNLOAD', - 'DRIVE', - 'DTV', - 'DUBAI', - 'DUCK', - 'DUNLOP', - 'DUPONT', - 'DURBAN', - 'DVAG', - 'DVR', - 'DZ', - 'EARTH', - 'EAT', - 'EC', - 'ECO', - 'EDEKA', - 'EDU', - 'EDUCATION', - 'EE', - 'EG', - 'EMAIL', - 'EMERCK', - 'ENERGY', - 'ENGINEER', - 'ENGINEERING', - 'ENTERPRISES', - 'EPSON', - 'EQUIPMENT', - 'ER', - 'ERICSSON', - 'ERNI', - 'ES', - 'ESQ', - 'ESTATE', - 'ESURANCE', - 'ET', - 'ETISALAT', - 'EU', - 'EUROVISION', - 'EUS', - 'EVENTS', - 'EVERBANK', - 'EXCHANGE', - 'EXPERT', - 'EXPOSED', - 'EXPRESS', - 'EXTRASPACE', - 'FAGE', - 'FAIL', - 'FAIRWINDS', - 'FAITH', - 'FAMILY', - 'FAN', - 'FANS', - 'FARM', - 'FARMERS', - 'FASHION', - 'FAST', - 'FEDEX', - 'FEEDBACK', - 'FERRARI', - 'FERRERO', - 'FI', - 'FIAT', - 'FIDELITY', - 'FIDO', - 'FILM', - 'FINAL', - 'FINANCE', - 'FINANCIAL', - 'FIRE', - 'FIRESTONE', - 'FIRMDALE', - 'FISH', - 'FISHING', - 'FIT', - 'FITNESS', - 'FJ', - 'FK', - 'FLICKR', - 'FLIGHTS', - 'FLIR', - 'FLORIST', - 'FLOWERS', - 'FLY', - 'FM', - 'FO', - 'FOO', - 'FOOD', - 'FOODNETWORK', - 'FOOTBALL', - 'FORD', - 'FOREX', - 'FORSALE', - 'FORUM', - 'FOUNDATION', - 'FOX', - 'FR', - 'FREE', - 'FRESENIUS', - 'FRL', - 'FROGANS', - 'FRONTDOOR', - 'FRONTIER', - 'FTR', - 'FUJITSU', - 'FUJIXEROX', - 'FUN', - 'FUND', - 'FURNITURE', - 'FUTBOL', - 'FYI', - 'GA', - 'GAL', - 'GALLERY', - 'GALLO', - 'GALLUP', - 'GAME', - 'GAMES', - 'GAP', - 'GARDEN', - 'GAY', - 'GB', - 'GBIZ', - 'GD', - 'GDN', - 'GE', - 'GEA', - 'GENT', - 'GENTING', - 'GEORGE', - 'GF', - 'GG', - 'GGEE', - 'GH', - 'GI', - 'GIFT', - 'GIFTS', - 'GIVES', - 'GIVING', - 'GL', - 'GLADE', - 'GLASS', - 'GLE', - 'GLOBAL', - 'GLOBO', - 'GM', - 'GMAIL', - 'GMBH', - 'GMO', - 'GMX', - 'GN', - 'GODADDY', - 'GOLD', - 'GOLDPOINT', - 'GOLF', - 'GOO', - 'GOODYEAR', - 'GOOG', - 'GOOGLE', - 'GOP', - 'GOT', - 'GOV', - 'GP', - 'GQ', - 'GR', - 'GRAINGER', - 'GRAPHICS', - 'GRATIS', - 'GREEN', - 'GRIPE', - 'GROCERY', - 'GROUP', - 'GS', - 'GT', - 'GU', - 'GUARDIAN', - 'GUCCI', - 'GUGE', - 'GUIDE', - 'GUITARS', - 'GURU', - 'GW', - 'GY', - 'HAIR', - 'HAMBURG', - 'HANGOUT', - 'HAUS', - 'HBO', - 'HDFC', - 'HDFCBANK', - 'HEALTH', - 'HEALTHCARE', - 'HELP', - 'HELSINKI', - 'HERE', - 'HERMES', - 'HGTV', - 'HIPHOP', - 'HISAMITSU', - 'HITACHI', - 'HIV', - 'HK', - 'HKT', - 'HM', - 'HN', - 'HOCKEY', - 'HOLDINGS', - 'HOLIDAY', - 'HOMEDEPOT', - 'HOMEGOODS', - 'HOMES', - 'HOMESENSE', - 'HONDA', - 'HORSE', - 'HOSPITAL', - 'HOST', - 'HOSTING', - 'HOT', - 'HOTELES', - 'HOTELS', - 'HOTMAIL', - 'HOUSE', - 'HOW', - 'HR', - 'HSBC', - 'HT', - 'HU', - 'HUGHES', - 'HYATT', - 'HYUNDAI', - 'IBM', - 'ICBC', - 'ICE', - 'ICU', - 'ID', - 'IE', - 'IEEE', - 'IFM', - 'IKANO', - 'IL', - 'IM', - 'IMAMAT', - 'IMDB', - 'IMMO', - 'IMMOBILIEN', - 'IN', - 'INC', - 'INDUSTRIES', - 'INFINITI', - 'INFO', - 'ING', - 'INK', - 'INSTITUTE', - 'INSURANCE', - 'INSURE', - 'INT', - 'INTEL', - 'INTERNATIONAL', - 'INTUIT', - 'INVESTMENTS', - 'IO', - 'IPIRANGA', - 'IQ', - 'IR', - 'IRISH', - 'IS', - 'ISMAILI', - 'IST', - 'ISTANBUL', - 'IT', - 'ITAU', - 'ITV', - 'IVECO', - 'JAGUAR', - 'JAVA', - 'JCB', - 'JCP', - 'JE', - 'JEEP', - 'JETZT', - 'JEWELRY', - 'JIO', - 'JLL', - 'JM', - 'JMP', - 'JNJ', - 'JO', - 'JOBS', - 'JOBURG', - 'JOT', - 'JOY', - 'JP', - 'JPMORGAN', - 'JPRS', - 'JUEGOS', - 'JUNIPER', - 'KAUFEN', - 'KDDI', - 'KE', - 'KERRYHOTELS', - 'KERRYLOGISTICS', - 'KERRYPROPERTIES', - 'KFH', - 'KG', - 'KH', - 'KI', - 'KIA', - 'KIM', - 'KINDER', - 'KINDLE', - 'KITCHEN', - 'KIWI', - 'KM', - 'KN', - 'KOELN', - 'KOMATSU', - 'KOSHER', - 'KP', - 'KPMG', - 'KPN', - 'KR', - 'KRD', - 'KRED', - 'KUOKGROUP', - 'KW', - 'KY', - 'KYOTO', - 'KZ', - 'LA', - 'LACAIXA', - 'LADBROKES', - 'LAMBORGHINI', - 'LAMER', - 'LANCASTER', - 'LANCIA', - 'LANCOME', - 'LAND', - 'LANDROVER', - 'LANXESS', - 'LASALLE', - 'LAT', - 'LATINO', - 'LATROBE', - 'LAW', - 'LAWYER', - 'LB', - 'LC', - 'LDS', - 'LEASE', - 'LECLERC', - 'LEFRAK', - 'LEGAL', - 'LEGO', - 'LEXUS', - 'LGBT', - 'LI', - 'LIAISON', - 'LIDL', - 'LIFE', - 'LIFEINSURANCE', - 'LIFESTYLE', - 'LIGHTING', - 'LIKE', - 'LILLY', - 'LIMITED', - 'LIMO', - 'LINCOLN', - 'LINDE', - 'LINK', - 'LIPSY', - 'LIVE', - 'LIVING', - 'LIXIL', - 'LK', - 'LLC', - 'LOAN', - 'LOANS', - 'LOCKER', - 'LOCUS', - 'LOFT', - 'LOL', - 'LONDON', - 'LOTTE', - 'LOTTO', - 'LOVE', - 'LPL', - 'LPLFINANCIAL', - 'LR', - 'LS', - 'LT', - 'LTD', - 'LTDA', - 'LU', - 'LUNDBECK', - 'LUPIN', - 'LUXE', - 'LUXURY', - 'LV', - 'LY', - 'MA', - 'MACYS', - 'MADRID', - 'MAIF', - 'MAISON', - 'MAKEUP', - 'MAN', - 'MANAGEMENT', - 'MANGO', - 'MAP', - 'MARKET', - 'MARKETING', - 'MARKETS', - 'MARRIOTT', - 'MARSHALLS', - 'MASERATI', - 'MATTEL', - 'MBA', - 'MC', - 'MCKINSEY', - 'MD', - 'ME', - 'MED', - 'MEDIA', - 'MEET', - 'MELBOURNE', - 'MEME', - 'MEMORIAL', - 'MEN', - 'MENU', - 'MERCKMSD', - 'METLIFE', - 'MG', - 'MH', - 'MIAMI', - 'MICROSOFT', - 'MIL', - 'MINI', - 'MINT', - 'MIT', - 'MITSUBISHI', - 'MK', - 'ML', - 'MLB', - 'MLS', - 'MM', - 'MMA', - 'MN', - 'MO', - 'MOBI', - 'MOBILE', - 'MODA', - 'MOE', - 'MOI', - 'MOM', - 'MONASH', - 'MONEY', - 'MONSTER', - 'MOPAR', - 'MORMON', - 'MORTGAGE', - 'MOSCOW', - 'MOTO', - 'MOTORCYCLES', - 'MOV', - 'MOVIE', - 'MOVISTAR', - 'MP', - 'MQ', - 'MR', - 'MS', - 'MSD', - 'MT', - 'MTN', - 'MTR', - 'MU', - 'MUSEUM', - 'MUTUAL', - 'MV', - 'MW', - 'MX', - 'MY', - 'MZ', - 'NA', - 'NAB', - 'NADEX', - 'NAGOYA', - 'NAME', - 'NATIONWIDE', - 'NATURA', - 'NAVY', - 'NBA', - 'NC', - 'NE', - 'NEC', - 'NET', - 'NETBANK', - 'NETFLIX', - 'NETWORK', - 'NEUSTAR', - 'NEW', - 'NEWHOLLAND', - 'NEWS', - 'NEXT', - 'NEXTDIRECT', - 'NEXUS', - 'NF', - 'NFL', - 'NG', - 'NGO', - 'NHK', - 'NI', - 'NICO', - 'NIKE', - 'NIKON', - 'NINJA', - 'NISSAN', - 'NISSAY', - 'NL', - 'NO', - 'NOKIA', - 'NORTHWESTERNMUTUAL', - 'NORTON', - 'NOW', - 'NOWRUZ', - 'NOWTV', - 'NP', - 'NR', - 'NRA', - 'NRW', - 'NTT', - 'NU', - 'NYC', - 'NZ', - 'OBI', - 'OBSERVER', - 'OFF', - 'OFFICE', - 'OKINAWA', - 'OLAYAN', - 'OLAYANGROUP', - 'OLDNAVY', - 'OLLO', - 'OM', - 'OMEGA', - 'ONE', - 'ONG', - 'ONL', - 'ONLINE', - 'ONYOURSIDE', - 'OOO', - 'OPEN', - 'ORACLE', - 'ORANGE', - 'ORG', - 'ORGANIC', - 'ORIGINS', - 'OSAKA', - 'OTSUKA', - 'OTT', - 'OVH', - 'PA', - 'PAGE', - 'PANASONIC', - 'PARIS', - 'PARS', - 'PARTNERS', - 'PARTS', - 'PARTY', - 'PASSAGENS', - 'PAY', - 'PCCW', - 'PE', - 'PET', - 'PF', - 'PFIZER', - 'PG', - 'PH', - 'PHARMACY', - 'PHD', - 'PHILIPS', - 'PHONE', - 'PHOTO', - 'PHOTOGRAPHY', - 'PHOTOS', - 'PHYSIO', - 'PIAGET', - 'PICS', - 'PICTET', - 'PICTURES', - 'PID', - 'PIN', - 'PING', - 'PINK', - 'PIONEER', - 'PIZZA', - 'PK', - 'PL', - 'PLACE', - 'PLAY', - 'PLAYSTATION', - 'PLUMBING', - 'PLUS', - 'PM', - 'PN', - 'PNC', - 'POHL', - 'POKER', - 'POLITIE', - 'PORN', - 'POST', - 'PR', - 'PRAMERICA', - 'PRAXI', - 'PRESS', - 'PRIME', - 'PRO', - 'PROD', - 'PRODUCTIONS', - 'PROF', - 'PROGRESSIVE', - 'PROMO', - 'PROPERTIES', - 'PROPERTY', - 'PROTECTION', - 'PRU', - 'PRUDENTIAL', - 'PS', - 'PT', - 'PUB', - 'PW', - 'PWC', - 'PY', - 'QA', - 'QPON', - 'QUEBEC', - 'QUEST', - 'QVC', - 'RACING', - 'RADIO', - 'RAID', - 'RE', - 'READ', - 'REALESTATE', - 'REALTOR', - 'REALTY', - 'RECIPES', - 'RED', - 'REDSTONE', - 'REDUMBRELLA', - 'REHAB', - 'REISE', - 'REISEN', - 'REIT', - 'RELIANCE', - 'REN', - 'RENT', - 'RENTALS', - 'REPAIR', - 'REPORT', - 'REPUBLICAN', - 'REST', - 'RESTAURANT', - 'REVIEW', - 'REVIEWS', - 'REXROTH', - 'RICH', - 'RICHARDLI', - 'RICOH', - 'RIGHTATHOME', - 'RIL', - 'RIO', - 'RIP', - 'RMIT', - 'RO', - 'ROCHER', - 'ROCKS', - 'RODEO', - 'ROGERS', - 'ROOM', - 'RS', - 'RSVP', - 'RU', - 'RUGBY', - 'RUHR', - 'RUN', - 'RW', - 'RWE', - 'RYUKYU', - 'SA', - 'SAARLAND', - 'SAFE', - 'SAFETY', - 'SAKURA', - 'SALE', - 'SALON', - 'SAMSCLUB', - 'SAMSUNG', - 'SANDVIK', - 'SANDVIKCOROMANT', - 'SANOFI', - 'SAP', - 'SARL', - 'SAS', - 'SAVE', - 'SAXO', - 'SB', - 'SBI', - 'SBS', - 'SC', - 'SCA', - 'SCB', - 'SCHAEFFLER', - 'SCHMIDT', - 'SCHOLARSHIPS', - 'SCHOOL', - 'SCHULE', - 'SCHWARZ', - 'SCIENCE', - 'SCJOHNSON', - 'SCOR', - 'SCOT', - 'SD', - 'SE', - 'SEARCH', - 'SEAT', - 'SECURE', - 'SECURITY', - 'SEEK', - 'SELECT', - 'SENER', - 'SERVICES', - 'SES', - 'SEVEN', - 'SEW', - 'SEX', - 'SEXY', - 'SFR', - 'SG', - 'SH', - 'SHANGRILA', - 'SHARP', - 'SHAW', - 'SHELL', - 'SHIA', - 'SHIKSHA', - 'SHOES', - 'SHOP', - 'SHOPPING', - 'SHOUJI', - 'SHOW', - 'SHOWTIME', - 'SHRIRAM', - 'SI', - 'SILK', - 'SINA', - 'SINGLES', - 'SITE', - 'SJ', - 'SK', - 'SKI', - 'SKIN', - 'SKY', - 'SKYPE', - 'SL', - 'SLING', - 'SM', - 'SMART', - 'SMILE', - 'SN', - 'SNCF', - 'SO', - 'SOCCER', - 'SOCIAL', - 'SOFTBANK', - 'SOFTWARE', - 'SOHU', - 'SOLAR', - 'SOLUTIONS', - 'SONG', - 'SONY', - 'SOY', - 'SPACE', - 'SPORT', - 'SPOT', - 'SPREADBETTING', - 'SR', - 'SRL', - 'SRT', - 'SS', - 'ST', - 'STADA', - 'STAPLES', - 'STAR', - 'STATEBANK', - 'STATEFARM', - 'STC', - 'STCGROUP', - 'STOCKHOLM', - 'STORAGE', - 'STORE', - 'STREAM', - 'STUDIO', - 'STUDY', - 'STYLE', - 'SU', - 'SUCKS', - 'SUPPLIES', - 'SUPPLY', - 'SUPPORT', - 'SURF', - 'SURGERY', - 'SUZUKI', - 'SV', - 'SWATCH', - 'SWIFTCOVER', - 'SWISS', - 'SX', - 'SY', - 'SYDNEY', - 'SYMANTEC', - 'SYSTEMS', - 'SZ', - 'TAB', - 'TAIPEI', - 'TALK', - 'TAOBAO', - 'TARGET', - 'TATAMOTORS', - 'TATAR', - 'TATTOO', - 'TAX', - 'TAXI', - 'TC', - 'TCI', - 'TD', - 'TDK', - 'TEAM', - 'TECH', - 'TECHNOLOGY', - 'TEL', - 'TELEFONICA', - 'TEMASEK', - 'TENNIS', - 'TEVA', - 'TF', - 'TG', - 'TH', - 'THD', - 'THEATER', - 'THEATRE', - 'TIAA', - 'TICKETS', - 'TIENDA', - 'TIFFANY', - 'TIPS', - 'TIRES', - 'TIROL', - 'TJ', - 'TJMAXX', - 'TJX', - 'TK', - 'TKMAXX', - 'TL', - 'TM', - 'TMALL', - 'TN', - 'TO', - 'TODAY', - 'TOKYO', - 'TOOLS', - 'TOP', - 'TORAY', - 'TOSHIBA', - 'TOTAL', - 'TOURS', - 'TOWN', - 'TOYOTA', - 'TOYS', - 'TR', - 'TRADE', - 'TRADING', - 'TRAINING', - 'TRAVEL', - 'TRAVELCHANNEL', - 'TRAVELERS', - 'TRAVELERSINSURANCE', - 'TRUST', - 'TRV', - 'TT', - 'TUBE', - 'TUI', - 'TUNES', - 'TUSHU', - 'TV', - 'TVS', - 'TW', - 'TZ', - 'UA', - 'UBANK', - 'UBS', - 'UCONNECT', - 'UG', - 'UK', - 'UNICOM', - 'UNIVERSITY', - 'UNO', - 'UOL', - 'UPS', - 'US', - 'UY', - 'UZ', - 'VA', - 'VACATIONS', - 'VANA', - 'VANGUARD', - 'VC', - 'VE', - 'VEGAS', - 'VENTURES', - 'VERISIGN', - 'VERSICHERUNG', - 'VET', - 'VG', - 'VI', - 'VIAJES', - 'VIDEO', - 'VIG', - 'VIKING', - 'VILLAS', - 'VIN', - 'VIP', - 'VIRGIN', - 'VISA', - 'VISION', - 'VISTAPRINT', - 'VIVA', - 'VIVO', - 'VLAANDEREN', - 'VN', - 'VODKA', - 'VOLKSWAGEN', - 'VOLVO', - 'VOTE', - 'VOTING', - 'VOTO', - 'VOYAGE', - 'VU', - 'VUELOS', - 'WALES', - 'WALMART', - 'WALTER', - 'WANG', - 'WANGGOU', - 'WARMAN', - 'WATCH', - 'WATCHES', - 'WEATHER', - 'WEATHERCHANNEL', - 'WEBCAM', - 'WEBER', - 'WEBSITE', - 'WED', - 'WEDDING', - 'WEIBO', - 'WEIR', - 'WF', - 'WHOSWHO', - 'WIEN', - 'WIKI', - 'WILLIAMHILL', - 'WIN', - 'WINDOWS', - 'WINE', - 'WINNERS', - 'WME', - 'WOLTERSKLUWER', - 'WOODSIDE', - 'WORK', - 'WORKS', - 'WORLD', - 'WOW', - 'WS', - 'WTC', - 'WTF', - 'XBOX', - 'XEROX', - 'XFINITY', - 'XIHUAN', - 'XIN', - 'XN--11B4C3D', - 'XN--1CK2E1B', - 'XN--1QQW23A', - 'XN--2SCRJ9C', - 'XN--30RR7Y', - 'XN--3BST00M', - 'XN--3DS443G', - 'XN--3E0B707E', - 'XN--3HCRJ9C', - 'XN--3OQ18VL8PN36A', - 'XN--3PXU8K', - 'XN--42C2D9A', - 'XN--45BR5CYL', - 'XN--45BRJ9C', - 'XN--45Q11C', - 'XN--4GBRIM', - 'XN--54B7FTA0CC', - 'XN--55QW42G', - 'XN--55QX5D', - 'XN--5SU34J936BGSG', - 'XN--5TZM5G', - 'XN--6FRZ82G', - 'XN--6QQ986B3XL', - 'XN--80ADXHKS', - 'XN--80AO21A', - 'XN--80AQECDR1A', - 'XN--80ASEHDB', - 'XN--80ASWG', - 'XN--8Y0A063A', - 'XN--90A3AC', - 'XN--90AE', - 'XN--90AIS', - 'XN--9DBQ2A', - 'XN--9ET52U', - 'XN--9KRT00A', - 'XN--B4W605FERD', - 'XN--BCK1B9A5DRE4C', - 'XN--C1AVG', - 'XN--C2BR7G', - 'XN--CCK2B3B', - 'XN--CG4BKI', - 'XN--CLCHC0EA0B2G2A9GCD', - 'XN--CZR694B', - 'XN--CZRS0T', - 'XN--CZRU2D', - 'XN--D1ACJ3B', - 'XN--D1ALF', - 'XN--E1A4C', - 'XN--ECKVDTC9D', - 'XN--EFVY88H', - 'XN--ESTV75G', - 'XN--FCT429K', - 'XN--FHBEI', - 'XN--FIQ228C5HS', - 'XN--FIQ64B', - 'XN--FIQS8S', - 'XN--FIQZ9S', - 'XN--FJQ720A', - 'XN--FLW351E', - 'XN--FPCRJ9C3D', - 'XN--FZC2C9E2C', - 'XN--FZYS8D69UVGM', - 'XN--G2XX48C', - 'XN--GCKR3F0F', - 'XN--GECRJ9C', - 'XN--GK3AT1E', - 'XN--H2BREG3EVE', - 'XN--H2BRJ9C', - 'XN--H2BRJ9C8C', - 'XN--HXT814E', - 'XN--I1B6B1A6A2E', - 'XN--IMR513N', - 'XN--IO0A7I', - 'XN--J1AEF', - 'XN--J1AMH', - 'XN--J6W193G', - 'XN--JLQ61U9W7B', - 'XN--JVR189M', - 'XN--KCRX77D1X4A', - 'XN--KPRW13D', - 'XN--KPRY57D', - 'XN--KPU716F', - 'XN--KPUT3I', - 'XN--L1ACC', - 'XN--LGBBAT1AD8J', - 'XN--MGB9AWBF', - 'XN--MGBA3A3EJT', - 'XN--MGBA3A4F16A', - 'XN--MGBA7C0BBN0A', - 'XN--MGBAAKC7DVF', - 'XN--MGBAAM7A8H', - 'XN--MGBAB2BD', - 'XN--MGBAH1A3HJKRD', - 'XN--MGBAI9AZGQP6J', - 'XN--MGBAYH7GPA', - 'XN--MGBBH1A', - 'XN--MGBBH1A71E', - 'XN--MGBC0A9AZCG', - 'XN--MGBCA7DZDO', - 'XN--MGBERP4A5D4AR', - 'XN--MGBGU82A', - 'XN--MGBI4ECEXP', - 'XN--MGBPL2FH', - 'XN--MGBT3DHD', - 'XN--MGBTX2B', - 'XN--MGBX4CD0AB', - 'XN--MIX891F', - 'XN--MK1BU44C', - 'XN--MXTQ1M', - 'XN--NGBC5AZD', - 'XN--NGBE9E0A', - 'XN--NGBRX', - 'XN--NODE', - 'XN--NQV7F', - 'XN--NQV7FS00EMA', - 'XN--NYQY26A', - 'XN--O3CW4H', - 'XN--OGBPF8FL', - 'XN--OTU796D', - 'XN--P1ACF', - 'XN--P1AI', - 'XN--PBT977C', - 'XN--PGBS0DH', - 'XN--PSSY2U', - 'XN--Q9JYB4C', - 'XN--QCKA1PMC', - 'XN--QXA6A', - 'XN--QXAM', - 'XN--RHQV96G', - 'XN--ROVU88B', - 'XN--RVC1E0AM3E', - 'XN--S9BRJ9C', - 'XN--SES554G', - 'XN--T60B56A', - 'XN--TCKWE', - 'XN--TIQ49XQYJ', - 'XN--UNUP4Y', - 'XN--VERMGENSBERATER-CTB', - 'XN--VERMGENSBERATUNG-PWB', - 'XN--VHQUV', - 'XN--VUQ861B', - 'XN--W4R85EL8FHU5DNRA', - 'XN--W4RS40L', - 'XN--WGBH1C', - 'XN--WGBL6A', - 'XN--XHQ521B', - 'XN--XKC2AL3HYE2A', - 'XN--XKC2DL3A5EE0H', - 'XN--Y9A3AQ', - 'XN--YFRO4I67O', - 'XN--YGBI2AMMX', - 'XN--ZFR164B', - 'XXX', - 'XYZ', - 'YACHTS', - 'YAHOO', - 'YAMAXUN', - 'YANDEX', - 'YE', - 'YODOBASHI', - 'YOGA', - 'YOKOHAMA', - 'YOU', - 'YOUTUBE', - 'YT', - 'YUN', - 'ZA', - 'ZAPPOS', - 'ZARA', - 'ZERO', - 'ZIP', - 'ZM', - 'ZONE', - 'ZUERICH', - 'ZW' -]; - - -// Keep as upper-case to make updating from source easier - -module.exports = new Set(internals.tlds.map((tld) => tld.toLowerCase())); - - -/***/ }), - -/***/ 97174: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - - -const internals = { - suspectRx: /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*\:/ -}; - - -exports.parse = function (text, reviver, options) { - - // Normalize arguments - - if (!options) { - if (reviver && - typeof reviver === 'object') { - - options = reviver; - reviver = undefined; - } - else { - options = {}; - } - } - - // Parse normally, allowing exceptions - - const obj = JSON.parse(text, reviver); - - // options.protoAction: 'error' (default) / 'remove' / 'ignore' - - if (options.protoAction === 'ignore') { - return obj; - } - - // Ignore null and non-objects - - if (!obj || - typeof obj !== 'object') { - - return obj; - } - - // Check original string for potential exploit - - if (!text.match(internals.suspectRx)) { - return obj; - } - - // Scan result for proto keys - - exports.scan(obj, options); - - return obj; -}; - - -exports.scan = function (obj, options) { - - options = options || {}; - - let next = [obj]; - - while (next.length) { - const nodes = next; - next = []; - - for (const node of nodes) { - if (Object.prototype.hasOwnProperty.call(node, '__proto__')) { // Avoid calling node.hasOwnProperty directly - if (options.protoAction !== 'remove') { - throw new SyntaxError('Object contains forbidden prototype property'); - } - - delete node.__proto__; - } - - for (const key in node) { - const value = node[key]; - if (value && - typeof value === 'object') { - - next.push(node[key]); - } - } - } - } -}; - - -exports.safeParse = function (text, reviver) { - - try { - return exports.parse(text, reviver); - } - catch (ignoreError) { - return null; - } -}; - - -/***/ }), - -/***/ 85545: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const Assert = __nccwpck_require__(32718); -const Clone = __nccwpck_require__(85578); -const Merge = __nccwpck_require__(60445); -const Utils = __nccwpck_require__(30417); - - -const internals = {}; - - -module.exports = function (defaults, source, options = {}) { - - Assert(defaults && typeof defaults === 'object', 'Invalid defaults value: must be an object'); - Assert(!source || source === true || typeof source === 'object', 'Invalid source value: must be true, falsy or an object'); - Assert(typeof options === 'object', 'Invalid options: must be an object'); - - if (!source) { // If no source, return null - return null; - } - - if (options.shallow) { - return internals.applyToDefaultsWithShallow(defaults, source, options); - } - - const copy = Clone(defaults); - - if (source === true) { // If source is set to true, use defaults - return copy; - } - - const nullOverride = options.nullOverride !== undefined ? options.nullOverride : false; - return Merge(copy, source, { nullOverride, mergeArrays: false }); -}; - - -internals.applyToDefaultsWithShallow = function (defaults, source, options) { - - const keys = options.shallow; - Assert(Array.isArray(keys), 'Invalid keys'); - - options = Object.assign({}, options); - options.shallow = false; - - const copy = Clone(defaults, { shallow: keys }); - - if (source === true) { // If source is set to true, use defaults - return copy; - } - - const storage = Utils.store(source, keys); // Move shallow copy items to storage - Merge(copy, source, { mergeArrays: false, nullOverride: false }); // Deep copy the rest - Utils.restore(copy, source, storage); // Shallow copy the stored items and restore - return copy; -}; - - -/***/ }), - -/***/ 32718: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const AssertError = __nccwpck_require__(35563); - -const internals = {}; - - -module.exports = function (condition, ...args) { - - if (condition) { - return; - } - - if (args.length === 1 && - args[0] instanceof Error) { - - throw args[0]; - } - - throw new AssertError(args); -}; - - -/***/ }), - -/***/ 86999: -/***/ ((module) => { - -"use strict"; - - -const internals = {}; - - -module.exports = internals.Bench = class { - - constructor() { - - this.ts = 0; - this.reset(); - } - - reset() { - - this.ts = internals.Bench.now(); - } - - elapsed() { - - return internals.Bench.now() - this.ts; - } - - static now() { - - const ts = process.hrtime(); - return (ts[0] * 1e3) + (ts[1] / 1e6); - } -}; - - -/***/ }), - -/***/ 77820: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const Ignore = __nccwpck_require__(12887); - - -const internals = {}; - - -module.exports = function () { - - return new Promise(Ignore); // $lab:coverage:ignore$ -}; - - -/***/ }), - -/***/ 85578: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const Types = __nccwpck_require__(84340); -const Utils = __nccwpck_require__(30417); - - -const internals = { - needsProtoHack: new Set([Types.set, Types.map, Types.weakSet, Types.weakMap]) -}; - - -module.exports = internals.clone = function (obj, options = {}, _seen = null) { - - if (typeof obj !== 'object' || - obj === null) { - - return obj; - } - - let clone = internals.clone; - let seen = _seen; - - if (options.shallow) { - if (options.shallow !== true) { - return internals.cloneWithShallow(obj, options); - } - - clone = (value) => value; - } - else { - seen = seen || new Map(); - - const lookup = seen.get(obj); - if (lookup) { - return lookup; - } - } - - // Built-in object types - - const baseProto = Types.getInternalProto(obj); - if (baseProto === Types.buffer) { - return Buffer && Buffer.from(obj); // $lab:coverage:ignore$ - } - - if (baseProto === Types.date) { - return new Date(obj.getTime()); - } - - if (baseProto === Types.regex) { - return new RegExp(obj); - } - - // Generic objects - - const newObj = internals.base(obj, baseProto, options); - if (newObj === obj) { - return obj; - } - - if (seen) { - seen.set(obj, newObj); // Set seen, since obj could recurse - } - - if (baseProto === Types.set) { - for (const value of obj) { - newObj.add(clone(value, options, seen)); - } - } - else if (baseProto === Types.map) { - for (const [key, value] of obj) { - newObj.set(key, clone(value, options, seen)); - } - } - - const keys = Utils.keys(obj, options); - for (const key of keys) { - if (baseProto === Types.array && - key === 'length') { - - newObj.length = obj.length; - continue; - } - - const descriptor = Object.getOwnPropertyDescriptor(obj, key); - if (descriptor) { - if (descriptor.get || - descriptor.set) { - - Object.defineProperty(newObj, key, descriptor); - } - else if (descriptor.enumerable) { - newObj[key] = clone(obj[key], options, seen); - } - else { - Object.defineProperty(newObj, key, { enumerable: false, writable: true, configurable: true, value: clone(obj[key], options, seen) }); - } - } - else { - Object.defineProperty(newObj, key, { - enumerable: true, - writable: true, - configurable: true, - value: clone(obj[key], options, seen) - }); - } - } - - return newObj; -}; - - -internals.cloneWithShallow = function (source, options) { - - const keys = options.shallow; - options = Object.assign({}, options); - options.shallow = false; - - const storage = Utils.store(source, keys); // Move shallow copy items to storage - const copy = internals.clone(source, options); // Deep copy the rest - Utils.restore(copy, source, storage); // Shallow copy the stored items and restore - return copy; -}; - - -internals.base = function (obj, baseProto, options) { - - if (baseProto === Types.array) { - return []; - } - - if (options.prototype === false) { // Defaults to true - if (internals.needsProtoHack.has(baseProto)) { - return new baseProto.constructor(); - } - - return {}; - } - - const proto = Object.getPrototypeOf(obj); - if (proto && - proto.isImmutable) { - - return obj; - } - - if (internals.needsProtoHack.has(baseProto)) { - const newObj = new proto.constructor(); - if (proto !== baseProto) { - Object.setPrototypeOf(newObj, proto); - } - - return newObj; - } - - return Object.create(proto); -}; - - -/***/ }), - -/***/ 39157: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const Assert = __nccwpck_require__(32718); -const DeepEqual = __nccwpck_require__(55801); -const EscapeRegex = __nccwpck_require__(91965); -const Utils = __nccwpck_require__(30417); - - -const internals = {}; - - -module.exports = function (ref, values, options = {}) { // options: { deep, once, only, part, symbols } - - /* - string -> string(s) - array -> item(s) - object -> key(s) - object -> object (key:value) - */ - - if (typeof values !== 'object') { - values = [values]; - } - - Assert(!Array.isArray(values) || values.length, 'Values array cannot be empty'); - - // String - - if (typeof ref === 'string') { - return internals.string(ref, values, options); - } - - // Array - - if (Array.isArray(ref)) { - return internals.array(ref, values, options); - } - - // Object - - Assert(typeof ref === 'object', 'Reference must be string or an object'); - return internals.object(ref, values, options); -}; - - -internals.array = function (ref, values, options) { - - if (!Array.isArray(values)) { - values = [values]; - } - - if (!ref.length) { - return false; - } - - if (options.only && - options.once && - ref.length !== values.length) { - - return false; - } - - let compare; - - // Map values - - const map = new Map(); - for (const value of values) { - if (!options.deep || - !value || - typeof value !== 'object') { - - const existing = map.get(value); - if (existing) { - ++existing.allowed; - } - else { - map.set(value, { allowed: 1, hits: 0 }); - } - } - else { - compare = compare || internals.compare(options); - - let found = false; - for (const [key, existing] of map.entries()) { - if (compare(key, value)) { - ++existing.allowed; - found = true; - break; - } - } - - if (!found) { - map.set(value, { allowed: 1, hits: 0 }); - } - } - } - - // Lookup values - - let hits = 0; - for (const item of ref) { - let match; - if (!options.deep || - !item || - typeof item !== 'object') { - - match = map.get(item); - } - else { - for (const [key, existing] of map.entries()) { - if (compare(key, item)) { - match = existing; - break; - } - } - } - - if (match) { - ++match.hits; - ++hits; - - if (options.once && - match.hits > match.allowed) { - - return false; - } - } - } - - // Validate results - - if (options.only && - hits !== ref.length) { - - return false; - } - - for (const match of map.values()) { - if (match.hits === match.allowed) { - continue; - } - - if (match.hits < match.allowed && - !options.part) { - - return false; - } - } - - return !!hits; -}; - - -internals.object = function (ref, values, options) { - - Assert(options.once === undefined, 'Cannot use option once with object'); - - const keys = Utils.keys(ref, options); - if (!keys.length) { - return false; - } - - // Keys list - - if (Array.isArray(values)) { - return internals.array(keys, values, options); - } - - // Key value pairs - - const symbols = Object.getOwnPropertySymbols(values).filter((sym) => values.propertyIsEnumerable(sym)); - const targets = [...Object.keys(values), ...symbols]; - - const compare = internals.compare(options); - const set = new Set(targets); - - for (const key of keys) { - if (!set.has(key)) { - if (options.only) { - return false; - } - - continue; - } - - if (!compare(values[key], ref[key])) { - return false; - } - - set.delete(key); - } - - if (set.size) { - return options.part ? set.size < targets.length : false; - } - - return true; -}; - - -internals.string = function (ref, values, options) { - - // Empty string - - if (ref === '') { - return values.length === 1 && values[0] === '' || // '' contains '' - !options.once && !values.some((v) => v !== ''); // '' contains multiple '' if !once - } - - // Map values - - const map = new Map(); - const patterns = []; - - for (const value of values) { - Assert(typeof value === 'string', 'Cannot compare string reference to non-string value'); - - if (value) { - const existing = map.get(value); - if (existing) { - ++existing.allowed; - } - else { - map.set(value, { allowed: 1, hits: 0 }); - patterns.push(EscapeRegex(value)); - } - } - else if (options.once || - options.only) { - - return false; - } - } - - if (!patterns.length) { // Non-empty string contains unlimited empty string - return true; - } - - // Match patterns - - const regex = new RegExp(`(${patterns.join('|')})`, 'g'); - const leftovers = ref.replace(regex, ($0, $1) => { - - ++map.get($1).hits; - return ''; // Remove from string - }); - - // Validate results - - if (options.only && - leftovers) { - - return false; - } - - let any = false; - for (const match of map.values()) { - if (match.hits) { - any = true; - } - - if (match.hits === match.allowed) { - continue; - } - - if (match.hits < match.allowed && - !options.part) { - - return false; - } - - // match.hits > match.allowed - - if (options.once) { - return false; - } - } - - return !!any; -}; - - -internals.compare = function (options) { - - if (!options.deep) { - return internals.shallow; - } - - const hasOnly = options.only !== undefined; - const hasPart = options.part !== undefined; - - const flags = { - prototype: hasOnly ? options.only : hasPart ? !options.part : false, - part: hasOnly ? !options.only : hasPart ? options.part : false - }; - - return (a, b) => DeepEqual(a, b, flags); -}; - - -internals.shallow = function (a, b) { - - return a === b; -}; - - -/***/ }), - -/***/ 55801: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const Types = __nccwpck_require__(84340); - - -const internals = { - mismatched: null -}; - - -module.exports = function (obj, ref, options) { - - options = Object.assign({ prototype: true }, options); - - return !!internals.isDeepEqual(obj, ref, options, []); -}; - - -internals.isDeepEqual = function (obj, ref, options, seen) { - - if (obj === ref) { // Copied from Deep-eql, copyright(c) 2013 Jake Luer, jake@alogicalparadox.com, MIT Licensed, https://github.com/chaijs/deep-eql - return obj !== 0 || 1 / obj === 1 / ref; - } - - const type = typeof obj; - - if (type !== typeof ref) { - return false; - } - - if (obj === null || - ref === null) { - - return false; - } - - if (type === 'function') { - if (!options.deepFunction || - obj.toString() !== ref.toString()) { - - return false; - } - - // Continue as object - } - else if (type !== 'object') { - return obj !== obj && ref !== ref; // NaN - } - - const instanceType = internals.getSharedType(obj, ref, !!options.prototype); - switch (instanceType) { - case Types.buffer: - return Buffer && Buffer.prototype.equals.call(obj, ref); // $lab:coverage:ignore$ - case Types.promise: - return obj === ref; - case Types.regex: - return obj.toString() === ref.toString(); - case internals.mismatched: - return false; - } - - for (let i = seen.length - 1; i >= 0; --i) { - if (seen[i].isSame(obj, ref)) { - return true; // If previous comparison failed, it would have stopped execution - } - } - - seen.push(new internals.SeenEntry(obj, ref)); - - try { - return !!internals.isDeepEqualObj(instanceType, obj, ref, options, seen); - } - finally { - seen.pop(); - } -}; - - -internals.getSharedType = function (obj, ref, checkPrototype) { - - if (checkPrototype) { - if (Object.getPrototypeOf(obj) !== Object.getPrototypeOf(ref)) { - return internals.mismatched; - } - - return Types.getInternalProto(obj); - } - - const type = Types.getInternalProto(obj); - if (type !== Types.getInternalProto(ref)) { - return internals.mismatched; - } - - return type; -}; - - -internals.valueOf = function (obj) { - - const objValueOf = obj.valueOf; - if (objValueOf === undefined) { - return obj; - } - - try { - return objValueOf.call(obj); - } - catch (err) { - return err; - } -}; - - -internals.hasOwnEnumerableProperty = function (obj, key) { - - return Object.prototype.propertyIsEnumerable.call(obj, key); -}; - - -internals.isSetSimpleEqual = function (obj, ref) { - - for (const entry of obj) { - if (!ref.has(entry)) { - return false; - } - } - - return true; -}; - - -internals.isDeepEqualObj = function (instanceType, obj, ref, options, seen) { - - const { isDeepEqual, valueOf, hasOwnEnumerableProperty } = internals; - const { keys, getOwnPropertySymbols } = Object; - - if (instanceType === Types.array) { - if (options.part) { - - // Check if any index match any other index - - for (const objValue of obj) { - for (const refValue of ref) { - if (isDeepEqual(objValue, refValue, options, seen)) { - return true; - } - } - } - } - else { - if (obj.length !== ref.length) { - return false; - } - - for (let i = 0; i < obj.length; ++i) { - if (!isDeepEqual(obj[i], ref[i], options, seen)) { - return false; - } - } - - return true; - } - } - else if (instanceType === Types.set) { - if (obj.size !== ref.size) { - return false; - } - - if (!internals.isSetSimpleEqual(obj, ref)) { - - // Check for deep equality - - const ref2 = new Set(ref); - for (const objEntry of obj) { - if (ref2.delete(objEntry)) { - continue; - } - - let found = false; - for (const refEntry of ref2) { - if (isDeepEqual(objEntry, refEntry, options, seen)) { - ref2.delete(refEntry); - found = true; - break; - } - } - - if (!found) { - return false; - } - } - } - } - else if (instanceType === Types.map) { - if (obj.size !== ref.size) { - return false; - } - - for (const [key, value] of obj) { - if (value === undefined && !ref.has(key)) { - return false; - } - - if (!isDeepEqual(value, ref.get(key), options, seen)) { - return false; - } - } - } - else if (instanceType === Types.error) { - - // Always check name and message - - if (obj.name !== ref.name || - obj.message !== ref.message) { - - return false; - } - } - - // Check .valueOf() - - const valueOfObj = valueOf(obj); - const valueOfRef = valueOf(ref); - if ((obj !== valueOfObj || ref !== valueOfRef) && - !isDeepEqual(valueOfObj, valueOfRef, options, seen)) { - - return false; - } - - // Check properties - - const objKeys = keys(obj); - if (!options.part && - objKeys.length !== keys(ref).length && - !options.skip) { - - return false; - } - - let skipped = 0; - for (const key of objKeys) { - if (options.skip && - options.skip.includes(key)) { - - if (ref[key] === undefined) { - ++skipped; - } - - continue; - } - - if (!hasOwnEnumerableProperty(ref, key)) { - return false; - } - - if (!isDeepEqual(obj[key], ref[key], options, seen)) { - return false; - } - } - - if (!options.part && - objKeys.length - skipped !== keys(ref).length) { - - return false; - } - - // Check symbols - - if (options.symbols !== false) { // Defaults to true - const objSymbols = getOwnPropertySymbols(obj); - const refSymbols = new Set(getOwnPropertySymbols(ref)); - - for (const key of objSymbols) { - if (!options.skip || - !options.skip.includes(key)) { - - if (hasOwnEnumerableProperty(obj, key)) { - if (!hasOwnEnumerableProperty(ref, key)) { - return false; - } - - if (!isDeepEqual(obj[key], ref[key], options, seen)) { - return false; - } - } - else if (hasOwnEnumerableProperty(ref, key)) { - return false; - } - } - - refSymbols.delete(key); - } - - for (const key of refSymbols) { - if (hasOwnEnumerableProperty(ref, key)) { - return false; - } - } - } - - return true; -}; - - -internals.SeenEntry = class { - - constructor(obj, ref) { - - this.obj = obj; - this.ref = ref; - } - - isSame(obj, ref) { - - return this.obj === obj && this.ref === ref; - } -}; - - -/***/ }), - -/***/ 35563: -/***/ ((module, exports, __nccwpck_require__) => { - -"use strict"; - - -const Stringify = __nccwpck_require__(37577); - - -const internals = {}; - - -module.exports = class extends Error { - - constructor(args) { - - const msgs = args - .filter((arg) => arg !== '') - .map((arg) => { - - return typeof arg === 'string' ? arg : arg instanceof Error ? arg.message : Stringify(arg); - }); - - super(msgs.join(' ') || 'Unknown error'); - - if (typeof Error.captureStackTrace === 'function') { // $lab:coverage:ignore$ - Error.captureStackTrace(this, exports.assert); - } - } -}; - - -/***/ }), - -/***/ 199: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const Assert = __nccwpck_require__(32718); - - -const internals = {}; - - -module.exports = function (attribute) { - - // Allowed value characters: !#$%&'()*+,-./:;<=>?@[]^_`{|}~ and space, a-z, A-Z, 0-9, \, " - - Assert(/^[ \w\!#\$%&'\(\)\*\+,\-\.\/\:;<\=>\?@\[\]\^`\{\|\}~\"\\]*$/.test(attribute), 'Bad attribute value (' + attribute + ')'); - - return attribute.replace(/\\/g, '\\\\').replace(/\"/g, '\\"'); // Escape quotes and slash -}; - - -/***/ }), - -/***/ 24752: -/***/ ((module) => { - -"use strict"; - - -const internals = {}; - - -module.exports = function (input) { - - if (!input) { - return ''; - } - - let escaped = ''; - - for (let i = 0; i < input.length; ++i) { - - const charCode = input.charCodeAt(i); - - if (internals.isSafe(charCode)) { - escaped += input[i]; - } - else { - escaped += internals.escapeHtmlChar(charCode); - } - } - - return escaped; -}; - - -internals.escapeHtmlChar = function (charCode) { - - const namedEscape = internals.namedHtml[charCode]; - if (typeof namedEscape !== 'undefined') { - return namedEscape; - } - - if (charCode >= 256) { - return '&#' + charCode + ';'; - } - - const hexValue = charCode.toString(16).padStart(2, '0'); - return `&#x${hexValue};`; -}; - - -internals.isSafe = function (charCode) { - - return (typeof internals.safeCharCodes[charCode] !== 'undefined'); -}; - - -internals.namedHtml = { - '38': '&', - '60': '<', - '62': '>', - '34': '"', - '160': ' ', - '162': '¢', - '163': '£', - '164': '¤', - '169': '©', - '174': '®' -}; - - -internals.safeCharCodes = (function () { - - const safe = {}; - - for (let i = 32; i < 123; ++i) { - - if ((i >= 97) || // a-z - (i >= 65 && i <= 90) || // A-Z - (i >= 48 && i <= 57) || // 0-9 - i === 32 || // space - i === 46 || // . - i === 44 || // , - i === 45 || // - - i === 58 || // : - i === 95) { // _ - - safe[i] = null; - } - } - - return safe; -}()); - - -/***/ }), - -/***/ 30112: -/***/ ((module) => { - -"use strict"; - - -const internals = {}; - - -module.exports = function (input) { - - if (!input) { - return ''; - } - - const lessThan = 0x3C; - const greaterThan = 0x3E; - const andSymbol = 0x26; - const lineSeperator = 0x2028; - - // replace method - let charCode; - return input.replace(/[<>&\u2028\u2029]/g, (match) => { - - charCode = match.charCodeAt(0); - - if (charCode === lessThan) { - return '\\u003c'; - } - - if (charCode === greaterThan) { - return '\\u003e'; - } - - if (charCode === andSymbol) { - return '\\u0026'; - } - - if (charCode === lineSeperator) { - return '\\u2028'; - } - - return '\\u2029'; - }); -}; - - -/***/ }), - -/***/ 91965: -/***/ ((module) => { - -"use strict"; - - -const internals = {}; - - -module.exports = function (string) { - - // Escape ^$.*+-?=!:|\/()[]{}, - - return string.replace(/[\^\$\.\*\+\-\?\=\!\:\|\\\/\(\)\[\]\{\}\,]/g, '\\$&'); -}; - - -/***/ }), - -/***/ 69666: -/***/ ((module) => { - -"use strict"; - - -const internals = {}; - - -module.exports = internals.flatten = function (array, target) { - - const result = target || []; - - for (let i = 0; i < array.length; ++i) { - if (Array.isArray(array[i])) { - internals.flatten(array[i], result); - } - else { - result.push(array[i]); - } - } - - return result; -}; - - -/***/ }), - -/***/ 12887: -/***/ ((module) => { - -"use strict"; - - -const internals = {}; - - -module.exports = function () { }; - - -/***/ }), - -/***/ 10904: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const internals = {}; - - -module.exports = { - applyToDefaults: __nccwpck_require__(85545), - assert: __nccwpck_require__(32718), - Bench: __nccwpck_require__(86999), - block: __nccwpck_require__(77820), - clone: __nccwpck_require__(85578), - contain: __nccwpck_require__(39157), - deepEqual: __nccwpck_require__(55801), - Error: __nccwpck_require__(35563), - escapeHeaderAttribute: __nccwpck_require__(199), - escapeHtml: __nccwpck_require__(24752), - escapeJson: __nccwpck_require__(30112), - escapeRegex: __nccwpck_require__(91965), - flatten: __nccwpck_require__(69666), - ignore: __nccwpck_require__(12887), - intersect: __nccwpck_require__(43221), - isPromise: __nccwpck_require__(14193), - merge: __nccwpck_require__(60445), - once: __nccwpck_require__(98926), - reach: __nccwpck_require__(18891), - reachTemplate: __nccwpck_require__(15517), - stringify: __nccwpck_require__(37577), - wait: __nccwpck_require__(69497) -}; - - -/***/ }), - -/***/ 43221: -/***/ ((module) => { - -"use strict"; - - -const internals = {}; - - -module.exports = function (array1, array2, options = {}) { - - if (!array1 || - !array2) { - - return (options.first ? null : []); - } - - const common = []; - const hash = (Array.isArray(array1) ? new Set(array1) : array1); - const found = new Set(); - for (const value of array2) { - if (internals.has(hash, value) && - !found.has(value)) { - - if (options.first) { - return value; - } - - common.push(value); - found.add(value); - } - } - - return (options.first ? null : common); -}; - - -internals.has = function (ref, key) { - - if (typeof ref.has === 'function') { - return ref.has(key); - } - - return ref[key] !== undefined; -}; - - -/***/ }), - -/***/ 14193: -/***/ ((module) => { - -"use strict"; - - -const internals = {}; - - -module.exports = function (promise) { - - return !!promise && typeof promise.then === 'function'; -}; - - -/***/ }), - -/***/ 60445: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const Assert = __nccwpck_require__(32718); -const Clone = __nccwpck_require__(85578); -const Utils = __nccwpck_require__(30417); - - -const internals = {}; - - -module.exports = internals.merge = function (target, source, options) { - - Assert(target && typeof target === 'object', 'Invalid target value: must be an object'); - Assert(source === null || source === undefined || typeof source === 'object', 'Invalid source value: must be null, undefined, or an object'); - - if (!source) { - return target; - } - - options = Object.assign({ nullOverride: true, mergeArrays: true }, options); - - if (Array.isArray(source)) { - Assert(Array.isArray(target), 'Cannot merge array onto an object'); - if (!options.mergeArrays) { - target.length = 0; // Must not change target assignment - } - - for (let i = 0; i < source.length; ++i) { - target.push(Clone(source[i], { symbols: options.symbols })); - } - - return target; - } - - const keys = Utils.keys(source, options); - for (let i = 0; i < keys.length; ++i) { - const key = keys[i]; - if (key === '__proto__' || - !Object.prototype.propertyIsEnumerable.call(source, key)) { - - continue; - } - - const value = source[key]; - if (value && - typeof value === 'object') { - - if (!target[key] || - typeof target[key] !== 'object' || - (Array.isArray(target[key]) !== Array.isArray(value)) || - value instanceof Date || - (Buffer && Buffer.isBuffer(value)) || // $lab:coverage:ignore$ - value instanceof RegExp) { - - target[key] = Clone(value, { symbols: options.symbols }); - } - else { - internals.merge(target[key], value, options); - } - } - else { - if (value !== null && - value !== undefined) { // Explicit to preserve empty strings - - target[key] = value; - } - else if (options.nullOverride) { - target[key] = value; - } - } - } - - return target; -}; - - -/***/ }), - -/***/ 98926: -/***/ ((module) => { - -"use strict"; - - -const internals = {}; - - -module.exports = function (method) { - - if (method._hoekOnce) { - return method; - } - - let once = false; - const wrapped = function (...args) { - - if (!once) { - once = true; - method(...args); - } - }; - - wrapped._hoekOnce = true; - return wrapped; -}; - - -/***/ }), - -/***/ 18891: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const Assert = __nccwpck_require__(32718); - - -const internals = {}; - - -module.exports = function (obj, chain, options) { - - if (chain === false || - chain === null || - chain === undefined) { - - return obj; - } - - options = options || {}; - if (typeof options === 'string') { - options = { separator: options }; - } - - const isChainArray = Array.isArray(chain); - - Assert(!isChainArray || !options.separator, 'Separator option no valid for array-based chain'); - - const path = isChainArray ? chain : chain.split(options.separator || '.'); - let ref = obj; - for (let i = 0; i < path.length; ++i) { - let key = path[i]; - const type = options.iterables && internals.iterables(ref); - - if (Array.isArray(ref) || - type === 'set') { - - const number = Number(key); - if (Number.isInteger(number)) { - key = number < 0 ? ref.length + number : number; - } - } - - if (!ref || - typeof ref === 'function' && options.functions === false || // Defaults to true - !type && ref[key] === undefined) { - - Assert(!options.strict || i + 1 === path.length, 'Missing segment', key, 'in reach path ', chain); - Assert(typeof ref === 'object' || options.functions === true || typeof ref !== 'function', 'Invalid segment', key, 'in reach path ', chain); - ref = options.default; - break; - } - - if (!type) { - ref = ref[key]; - } - else if (type === 'set') { - ref = [...ref][key]; - } - else { // type === 'map' - ref = ref.get(key); - } - } - - return ref; -}; - - -internals.iterables = function (ref) { - - if (ref instanceof Set) { - return 'set'; - } - - if (ref instanceof Map) { - return 'map'; - } -}; - - -/***/ }), - -/***/ 15517: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const Reach = __nccwpck_require__(18891); - - -const internals = {}; - - -module.exports = function (obj, template, options) { - - return template.replace(/{([^}]+)}/g, ($0, chain) => { - - const value = Reach(obj, chain, options); - return (value === undefined || value === null ? '' : value); - }); -}; - - -/***/ }), - -/***/ 37577: -/***/ ((module) => { - -"use strict"; - - -const internals = {}; - - -module.exports = function (...args) { - - try { - return JSON.stringify.apply(null, args); - } - catch (err) { - return '[Cannot display object: ' + err.message + ']'; - } -}; - - -/***/ }), - -/***/ 84340: -/***/ ((module, exports) => { - -"use strict"; - - -const internals = {}; - - -exports = module.exports = { - array: Array.prototype, - buffer: Buffer && Buffer.prototype, // $lab:coverage:ignore$ - date: Date.prototype, - error: Error.prototype, - generic: Object.prototype, - map: Map.prototype, - promise: Promise.prototype, - regex: RegExp.prototype, - set: Set.prototype, - weakMap: WeakMap.prototype, - weakSet: WeakSet.prototype -}; - - -internals.typeMap = new Map([ - ['[object Error]', exports.error], - ['[object Map]', exports.map], - ['[object Promise]', exports.promise], - ['[object Set]', exports.set], - ['[object WeakMap]', exports.weakMap], - ['[object WeakSet]', exports.weakSet] -]); - - -exports.getInternalProto = function (obj) { - - if (Array.isArray(obj)) { - return exports.array; - } - - if (Buffer && obj instanceof Buffer) { // $lab:coverage:ignore$ - return exports.buffer; - } - - if (obj instanceof Date) { - return exports.date; - } - - if (obj instanceof RegExp) { - return exports.regex; - } - - if (obj instanceof Error) { - return exports.error; - } - - const objName = Object.prototype.toString.call(obj); - return internals.typeMap.get(objName) || exports.generic; -}; - - -/***/ }), - -/***/ 30417: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -const Reach = __nccwpck_require__(18891); - - -const internals = {}; - - -exports.keys = function (obj, options = {}) { - - return options.symbols !== false ? Reflect.ownKeys(obj) : Object.getOwnPropertyNames(obj); // Defaults to true -}; - - -exports.store = function (source, keys) { - - const storage = new Map(); - for (let i = 0; i < keys.length; ++i) { - const key = keys[i]; - const value = Reach(source, key); - if (typeof value === 'object' || - typeof value === 'function') { - - storage.set(key, value); - internals.reachSet(source, key, undefined); - } - } - - return storage; -}; - - -exports.restore = function (copy, source, storage) { - - for (const [key, value] of storage) { - internals.reachSet(copy, key, value); - internals.reachSet(source, key, value); - } -}; - - -internals.reachSet = function (obj, key, value) { - - const path = Array.isArray(key) ? key : key.split('.'); - let ref = obj; - for (let i = 0; i < path.length; ++i) { - const segment = path[i]; - if (i + 1 === path.length) { - ref[segment] = value; - } - - ref = ref[segment]; - } -}; - - -/***/ }), - -/***/ 69497: -/***/ ((module) => { - -"use strict"; - - -const internals = {}; - - -module.exports = function (timeout) { - - return new Promise((resolve) => setTimeout(resolve, timeout)); -}; - - -/***/ }), - -/***/ 16415: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -const Hoek = __nccwpck_require__(10904); - -const Ref = __nccwpck_require__(71802); - - -const internals = {}; - - -exports.schema = function (Joi, config) { - - if (config !== undefined && config !== null && typeof config === 'object') { - - if (config.isJoi) { - return config; - } - - if (Array.isArray(config)) { - return Joi.alternatives().try(config); - } - - if (config instanceof RegExp) { - return Joi.string().regex(config); - } - - if (config instanceof Date) { - return Joi.date().valid(config); - } - - return Joi.object().keys(config); - } - - if (typeof config === 'string') { - return Joi.string().valid(config); - } - - if (typeof config === 'number') { - return Joi.number().valid(config); - } - - if (typeof config === 'boolean') { - return Joi.boolean().valid(config); - } - - if (Ref.isRef(config)) { - return Joi.valid(config); - } - - Hoek.assert(config === null, 'Invalid schema content:', config); - - return Joi.valid(null); -}; - - -exports.ref = function (id) { - - return Ref.isRef(id) ? id : Ref.create(id); -}; - - -/***/ }), - -/***/ 32150: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -const Hoek = __nccwpck_require__(10904); - -const Language = __nccwpck_require__(43910); - - -const internals = { - annotations: Symbol('joi-annotations') -}; - - -internals.stringify = function (value, wrapArrays) { - - const type = typeof value; - - if (value === null) { - return 'null'; - } - - if (type === 'string') { - return value; - } - - if (value instanceof exports.Err || type === 'function' || type === 'symbol') { - return value.toString(); - } - - if (type === 'object') { - if (Array.isArray(value)) { - let partial = ''; - - for (let i = 0; i < value.length; ++i) { - partial = partial + (partial.length ? ', ' : '') + internals.stringify(value[i], wrapArrays); - } - - return wrapArrays ? '[' + partial + ']' : partial; - } - - return value.toString(); - } - - return JSON.stringify(value); -}; - - -exports.Err = class { - - constructor(type, context, state, options, flags, message, template) { - - this.isJoi = true; - this.type = type; - this.context = context || {}; - this.context.key = state.path[state.path.length - 1]; - this.context.label = state.key; - this.path = state.path; - this.options = options; - this.flags = flags; - this.message = message; - this.template = template; - - const localized = this.options.language; - - if (this.flags.label) { - this.context.label = this.flags.label; - } - else if (localized && // language can be null for arrays exclusion check - (this.context.label === '' || - this.context.label === null)) { - this.context.label = localized.root || Language.errors.root; - } - } - - toString() { - - if (this.message) { - return this.message; - } - - let format; - - if (this.template) { - format = this.template; - } - - const localized = this.options.language; - - format = format || Hoek.reach(localized, this.type) || Hoek.reach(Language.errors, this.type); - - if (format === undefined) { - return `Error code "${this.type}" is not defined, your custom type is missing the correct language definition`; - } - - let wrapArrays = Hoek.reach(localized, 'messages.wrapArrays'); - if (typeof wrapArrays !== 'boolean') { - wrapArrays = Language.errors.messages.wrapArrays; - } - - if (format === null) { - const childrenString = internals.stringify(this.context.reason, wrapArrays); - if (wrapArrays) { - return childrenString.slice(1, -1); - } - - return childrenString; - } - - const hasKey = /{{!?label}}/.test(format); - const skipKey = format.length > 2 && format[0] === '!' && format[1] === '!'; - - if (skipKey) { - format = format.slice(2); - } - - if (!hasKey && !skipKey) { - const localizedKey = Hoek.reach(localized, 'key'); - if (typeof localizedKey === 'string') { - format = localizedKey + format; - } - else { - format = Hoek.reach(Language.errors, 'key') + format; - } - } - - const message = format.replace(/{{(!?)([^}]+)}}/g, ($0, isSecure, name) => { - - const value = Hoek.reach(this.context, name); - const normalized = internals.stringify(value, wrapArrays); - return (isSecure && this.options.escapeHtml ? Hoek.escapeHtml(normalized) : normalized); - }); - - this.toString = () => message; // Persist result of last toString call, it won't change - - return message; - } - -}; - - -exports.create = function (type, context, state, options, flags, message, template) { - - return new exports.Err(type, context, state, options, flags, message, template); -}; - - -exports.process = function (errors, object) { - - if (!errors) { - return null; - } - - // Construct error - - let message = ''; - const details = []; - - const processErrors = function (localErrors, parent, overrideMessage) { - - for (let i = 0; i < localErrors.length; ++i) { - const item = localErrors[i]; - - if (item instanceof Error) { - return item; - } - - if (item.flags.error && typeof item.flags.error !== 'function') { - if (!item.flags.selfError || !item.context.reason) { - return item.flags.error; - } - } - - let itemMessage; - if (parent === undefined) { - itemMessage = item.toString(); - message = message + (message ? '. ' : '') + itemMessage; - } - - // Do not push intermediate errors, we're only interested in leafs - - if (item.context.reason) { - const override = processErrors(item.context.reason, item.path, item.type === 'override' ? item.message : null); - if (override) { - return override; - } - } - else { - details.push({ - message: overrideMessage || itemMessage || item.toString(), - path: item.path, - type: item.type, - context: item.context - }); - } - } - }; - - const override = processErrors(errors); - if (override) { - return override; - } - - const error = new Error(message); - error.isJoi = true; - error.name = 'ValidationError'; - error.details = details; - error._object = object; - error.annotate = internals.annotate; - return error; -}; - - -// Inspired by json-stringify-safe - -internals.safeStringify = function (obj, spaces) { - - return JSON.stringify(obj, internals.serializer(), spaces); -}; - - -internals.serializer = function () { - - const keys = []; - const stack = []; - - const cycleReplacer = (key, value) => { - - if (stack[0] === value) { - return '[Circular ~]'; - } - - return '[Circular ~.' + keys.slice(0, stack.indexOf(value)).join('.') + ']'; - }; - - 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); - } - - if (~stack.indexOf(value)) { - value = cycleReplacer.call(this, key, value); - } - } - else { - stack.push(value); - } - - 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$_`); - } - - annotated.push(value[i]); - } - - value = annotated; - } - else { - const errorKeys = Object.keys(annotations.errors); - for (let i = 0; i < errorKeys.length; ++i) { - const errorKey = errorKeys[i]; - value[`${errorKey}_$key$_${annotations.errors[errorKey].sort().join(', ')}_$end$_`] = value[errorKey]; - value[errorKey] = undefined; - } - - const missingKeys = Object.keys(annotations.missing); - for (let i = 0; i < missingKeys.length; ++i) { - const missingKey = missingKeys[i]; - value[`_$miss$_${missingKey}|${annotations.missing[missingKey]}_$end$_`] = '__missing__'; - } - } - - return value; - } - } - - if (value === Infinity || value === -Infinity || Number.isNaN(value) || - typeof value === 'function' || typeof value === 'symbol') { - return '[' + value.toString() + ']'; - } - - return value; - }; -}; - - -internals.annotate = function (stripColorCodes) { - - const redFgEscape = stripColorCodes ? '' : '\u001b[31m'; - const redBgEscape = stripColorCodes ? '' : '\u001b[41m'; - const endColor = stripColorCodes ? '' : '\u001b[0m'; - - if (typeof this._object !== 'object') { - return this.details[0].message; - } - - const obj = Hoek.clone(this._object || {}); - - 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 ref = obj; - for (let j = 0; ; ++j) { - const seg = path[j]; - - if (ref.isImmutable) { - ref = ref.clone(); // joi schemas are not cloned by hoek, we have to take this extra step - } - - if (j + 1 < path.length && - ref[seg] && - typeof ref[seg] !== 'string') { - - ref = ref[seg]; - } - else { - const refAnnotations = ref[internals.annotations] = ref[internals.annotations] || { errors: {}, missing: {} }; - const value = ref[seg]; - const cacheKey = seg || error.context.label; - - if (value !== undefined) { - refAnnotations.errors[cacheKey] = refAnnotations.errors[cacheKey] || []; - refAnnotations.errors[cacheKey].push(pos); - } - else { - refAnnotations.missing[cacheKey] = pos; - } - - 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 - }; - - 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; -}; - - -/***/ }), - -/***/ 44010: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const Hoek = __nccwpck_require__(10904); - -const Any = __nccwpck_require__(77641); -const Cast = __nccwpck_require__(16415); -const Errors = __nccwpck_require__(32150); -const Lazy = __nccwpck_require__(92187); -const Ref = __nccwpck_require__(71802); - - -const internals = { - alternatives: __nccwpck_require__(32797), - array: __nccwpck_require__(81500), - boolean: __nccwpck_require__(78578), - binary: __nccwpck_require__(2608), - date: __nccwpck_require__(46254), - func: __nccwpck_require__(28710), - number: __nccwpck_require__(18668), - object: __nccwpck_require__(38395), - string: __nccwpck_require__(67769), - symbol: __nccwpck_require__(62462) -}; - - -internals.callWithDefaults = function (schema, args) { - - Hoek.assert(this, 'Must be invoked on a Joi instance.'); - - if (this._defaults) { - schema = this._defaults(schema); - } - - schema._currentJoi = this; - - return schema._init(...args); -}; - - -internals.root = function () { - - const any = new Any(); - - const root = any.clone(); - Any.prototype._currentJoi = root; - root._currentJoi = root; - root._binds = new Set(['any', 'alternatives', 'alt', 'array', 'bool', 'boolean', 'binary', 'date', 'func', 'number', 'object', 'string', 'symbol', 'validate', 'describe', 'compile', 'assert', 'attempt', 'lazy', 'defaults', 'extend', 'allow', 'valid', 'only', 'equal', 'invalid', 'disallow', 'not', 'required', 'exist', 'optional', 'forbidden', 'strip', 'when', 'empty', 'default']); - - root.any = function (...args) { - - Hoek.assert(args.length === 0, 'Joi.any() does not allow arguments.'); - - return internals.callWithDefaults.call(this, any, args); - }; - - root.alternatives = root.alt = function (...args) { - - return internals.callWithDefaults.call(this, internals.alternatives, args); - }; - - root.array = function (...args) { - - Hoek.assert(args.length === 0, 'Joi.array() does not allow arguments.'); - - return internals.callWithDefaults.call(this, internals.array, args); - }; - - root.boolean = root.bool = function (...args) { - - Hoek.assert(args.length === 0, 'Joi.boolean() does not allow arguments.'); - - return internals.callWithDefaults.call(this, internals.boolean, args); - }; - - root.binary = function (...args) { - - Hoek.assert(args.length === 0, 'Joi.binary() does not allow arguments.'); - - return internals.callWithDefaults.call(this, internals.binary, args); - }; - - root.date = function (...args) { - - Hoek.assert(args.length === 0, 'Joi.date() does not allow arguments.'); - - return internals.callWithDefaults.call(this, internals.date, args); - }; - - root.func = function (...args) { - - Hoek.assert(args.length === 0, 'Joi.func() does not allow arguments.'); - - return internals.callWithDefaults.call(this, internals.func, args); - }; - - root.number = function (...args) { - - Hoek.assert(args.length === 0, 'Joi.number() does not allow arguments.'); - - return internals.callWithDefaults.call(this, internals.number, args); - }; - - root.object = function (...args) { - - return internals.callWithDefaults.call(this, internals.object, args); - }; - - root.string = function (...args) { - - Hoek.assert(args.length === 0, 'Joi.string() does not allow arguments.'); - - return internals.callWithDefaults.call(this, internals.string, args); - }; - - root.symbol = function (...args) { - - Hoek.assert(args.length === 0, 'Joi.symbol() does not allow arguments.'); - - return internals.callWithDefaults.call(this, internals.symbol, args); - }; - - root.ref = function (...args) { - - return Ref.create(...args); - }; - - root.isRef = function (ref) { - - return Ref.isRef(ref); - }; - - root.validate = function (value, ...args /*, [schema], [options], callback */) { - - const last = args[args.length - 1]; - const callback = typeof last === 'function' ? last : null; - - const count = args.length - (callback ? 1 : 0); - if (count === 0) { - return any.validate(value, callback); - } - - const options = count === 2 ? args[1] : undefined; - const schema = this.compile(args[0]); - - return schema._validateWithOptions(value, options, callback); - }; - - root.describe = function (...args) { - - const schema = args.length ? this.compile(args[0]) : any; - return schema.describe(); - }; - - root.compile = function (schema) { - - try { - return Cast.schema(this, schema); - } - catch (err) { - if (err.hasOwnProperty('path')) { - err.message = err.message + '(' + err.path + ')'; - } - - throw err; - } - }; - - root.assert = function (value, schema, message) { - - this.attempt(value, schema, message); - }; - - root.attempt = function (value, schema, message) { - - const result = this.validate(value, schema); - const error = result.error; - if (error) { - if (!message) { - if (typeof error.annotate === 'function') { - error.message = error.annotate(); - } - - throw error; - } - - if (!(message instanceof Error)) { - if (typeof error.annotate === 'function') { - error.message = `${message} ${error.annotate()}`; - } - - throw error; - } - - throw message; - } - - return result.value; - }; - - root.reach = function (schema, path) { - - Hoek.assert(schema && schema instanceof Any, 'you must provide a joi schema'); - Hoek.assert(Array.isArray(path) || typeof path === 'string', 'path must be a string or an array of strings'); - - const reach = (sourceSchema, schemaPath) => { - - if (!schemaPath.length) { - return sourceSchema; - } - - const children = sourceSchema._inner.children; - if (!children) { - return; - } - - const key = schemaPath.shift(); - for (let i = 0; i < children.length; ++i) { - const child = children[i]; - if (child.key === key) { - return reach(child.schema, schemaPath); - } - } - }; - - const schemaPath = typeof path === 'string' ? (path ? path.split('.') : []) : path.slice(); - - return reach(schema, schemaPath); - }; - - root.lazy = function (...args) { - - return internals.callWithDefaults.call(this, Lazy, args); - }; - - root.defaults = function (fn) { - - Hoek.assert(typeof fn === 'function', 'Defaults must be a function'); - - let joi = Object.create(this.any()); - joi = fn(joi); - - Hoek.assert(joi && joi instanceof this.constructor, 'defaults() must return a schema'); - - Object.assign(joi, this, joi.clone()); // Re-add the types from `this` but also keep the settings from joi's potential new defaults - - joi._defaults = (schema) => { - - if (this._defaults) { - schema = this._defaults(schema); - Hoek.assert(schema instanceof this.constructor, 'defaults() must return a schema'); - } - - schema = fn(schema); - Hoek.assert(schema instanceof this.constructor, 'defaults() must return a schema'); - return schema; - }; - - return joi; - }; - - root.bind = function () { - - const joi = Object.create(this); - - joi._binds.forEach((bind) => { - - joi[bind] = joi[bind].bind(joi); - }); - - return joi; - }; - - root.extend = function (...args) { - - const extensions = Hoek.flatten(args); - Hoek.assert(extensions.length > 0, 'You need to provide at least one extension'); - - this.assert(extensions, root.extensionsSchema); - - const joi = Object.create(this.any()); - Object.assign(joi, this); - joi._currentJoi = joi; - joi._binds = new Set(joi._binds); - - for (let i = 0; i < extensions.length; ++i) { - let extension = extensions[i]; - - if (typeof extension === 'function') { - extension = extension(joi); - } - - this.assert(extension, root.extensionSchema); - - const base = (extension.base || this.any()).clone(); // Cloning because we're going to override language afterwards - const ctor = base.constructor; - const type = class extends ctor { // eslint-disable-line no-loop-func - - constructor() { - - super(); - if (extension.base) { - Object.assign(this, base); - } - - this._type = extension.name; - } - - }; - - if (extension.language) { - const lang = { - [extension.name]: extension.language - }; - type.prototype._language = Hoek.applyToDefaults(type.prototype._language || (base._settings && base._settings.language) || {}, lang); - } - - - if (extension.coerce) { - type.prototype._coerce = function (value, state, options) { - - if (ctor.prototype._coerce) { - const baseRet = ctor.prototype._coerce.call(this, value, state, options); - - if (baseRet.errors) { - return baseRet; - } - - value = baseRet.value; - } - - const ret = extension.coerce.call(this, value, state, options); - if (ret instanceof Errors.Err) { - return { value, errors: ret }; - } - - return { value: ret }; - }; - } - - if (extension.pre) { - type.prototype._base = function (value, state, options) { - - if (ctor.prototype._base) { - const baseRet = ctor.prototype._base.call(this, value, state, options); - - if (baseRet.errors) { - return baseRet; - } - - value = baseRet.value; - } - - const ret = extension.pre.call(this, value, state, options); - if (ret instanceof Errors.Err) { - return { value, errors: ret }; - } - - return { value: ret }; - }; - } - - if (extension.rules) { - for (let j = 0; j < extension.rules.length; ++j) { - const rule = extension.rules[j]; - const ruleArgs = rule.params ? - (rule.params instanceof Any ? rule.params._inner.children.map((k) => k.key) : Object.keys(rule.params)) : - []; - const validateArgs = rule.params ? Cast.schema(this, rule.params) : null; - - type.prototype[rule.name] = function (...rArgs) { // eslint-disable-line no-loop-func - - if (rArgs.length > ruleArgs.length) { - throw new Error('Unexpected number of arguments'); - } - - let hasRef = false; - let arg = {}; - - for (let k = 0; k < ruleArgs.length; ++k) { - arg[ruleArgs[k]] = rArgs[k]; - if (!hasRef && Ref.isRef(rArgs[k])) { - hasRef = true; - } - } - - if (validateArgs) { - arg = joi.attempt(arg, validateArgs); - } - - let schema; - if (rule.validate && !rule.setup) { - const validate = function (value, state, options) { - - return rule.validate.call(this, arg, value, state, options); - }; - - schema = this._test(rule.name, arg, validate, { - description: rule.description, - hasRef - }); - } - else { - schema = this.clone(); - } - - if (rule.setup) { - const newSchema = rule.setup.call(schema, arg); - if (newSchema !== undefined) { - Hoek.assert(newSchema instanceof Any, `Setup of extension Joi.${this._type}().${rule.name}() must return undefined or a Joi object`); - schema = newSchema; - } - - if (rule.validate) { - const validate = function (value, state, options) { - - return rule.validate.call(this, arg, value, state, options); - }; - - schema = schema._test(rule.name, arg, validate, { - description: rule.description, - hasRef - }); - } - } - - return schema; - }; - } - } - - if (extension.describe) { - type.prototype.describe = function () { - - const description = ctor.prototype.describe.call(this); - return extension.describe.call(this, description); - }; - } - - const instance = new type(); - joi[extension.name] = function (...extArgs) { - - return internals.callWithDefaults.call(this, instance, extArgs); - }; - - joi._binds.add(extension.name); - } - - return joi; - }; - - root.extensionSchema = internals.object.keys({ - base: internals.object.type(Any, 'Joi object'), - name: internals.string.required(), - coerce: internals.func.arity(3), - pre: internals.func.arity(3), - language: internals.object, - describe: internals.func.arity(1), - rules: internals.array.items(internals.object.keys({ - name: internals.string.required(), - setup: internals.func.arity(1), - validate: internals.func.arity(4), - params: [ - internals.object.pattern(/.*/, internals.object.type(Any, 'Joi object')), - internals.object.type(internals.object.constructor, 'Joi object') - ], - description: [internals.string, internals.func.arity(1)] - }).or('setup', 'validate')) - }).strict(); - - root.extensionsSchema = internals.array.items([internals.object, internals.func.arity(1)]).strict(); - - root.version = (__nccwpck_require__(86251).version); - - return root; -}; - - -module.exports = internals.root(); - - -/***/ }), - -/***/ 43910: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - -const internals = {}; - - -exports.errors = { - root: 'value', - key: '"{{!label}}" ', - messages: { - wrapArrays: true - }, - any: { - unknown: 'is not allowed', - invalid: 'contains an invalid value', - empty: 'is not allowed to be empty', - required: 'is required', - allowOnly: 'must be one of {{valids}}', - default: 'threw an error when running default method' - }, - alternatives: { - base: 'not matching any of the allowed alternatives', - child: null - }, - array: { - base: 'must be an array', - includes: 'at position {{pos}} does not match any of the allowed types', - includesSingle: 'single value of "{{!label}}" does not match any of the allowed types', - includesOne: 'at position {{pos}} fails because {{reason}}', - includesOneSingle: 'single value of "{{!label}}" fails because {{reason}}', - includesRequiredUnknowns: 'does not contain {{unknownMisses}} required value(s)', - includesRequiredKnowns: 'does not contain {{knownMisses}}', - includesRequiredBoth: 'does not contain {{knownMisses}} and {{unknownMisses}} other required value(s)', - excludes: 'at position {{pos}} contains an excluded value', - excludesSingle: 'single value of "{{!label}}" contains an excluded value', - hasKnown: 'does not contain at least one required match for type "{{!patternLabel}}"', - hasUnknown: 'does not contain at least one required match', - min: 'must contain at least {{limit}} items', - max: 'must contain less than or equal to {{limit}} items', - length: 'must contain {{limit}} items', - ordered: 'at position {{pos}} fails because {{reason}}', - orderedLength: 'at position {{pos}} fails because array must contain at most {{limit}} items', - ref: 'references "{{ref}}" which is not a positive integer', - sparse: 'must not be a sparse array', - unique: 'position {{pos}} contains a duplicate value' - }, - boolean: { - base: 'must be a boolean' - }, - binary: { - base: 'must be a buffer or a string', - min: 'must be at least {{limit}} bytes', - max: 'must be less than or equal to {{limit}} bytes', - length: 'must be {{limit}} bytes' - }, - date: { - base: 'must be a number of milliseconds or valid date string', - strict: 'must be a valid date', - min: 'must be larger than or equal to "{{limit}}"', - max: 'must be less than or equal to "{{limit}}"', - less: 'must be less than "{{limit}}"', - greater: 'must be greater than "{{limit}}"', - isoDate: 'must be a valid ISO 8601 date', - timestamp: { - javascript: 'must be a valid timestamp or number of milliseconds', - unix: 'must be a valid timestamp or number of seconds' - }, - ref: 'references "{{ref}}" which is not a date' - }, - function: { - base: 'must be a Function', - arity: 'must have an arity of {{n}}', - minArity: 'must have an arity greater or equal to {{n}}', - maxArity: 'must have an arity lesser or equal to {{n}}', - ref: 'must be a Joi reference', - class: 'must be a class' - }, - lazy: { - base: '!!schema error: lazy schema must be set', - schema: '!!schema error: lazy schema function must return a schema' - }, - object: { - base: 'must be an object', - child: '!!child "{{!child}}" fails because {{reason}}', - min: 'must have at least {{limit}} children', - max: 'must have less than or equal to {{limit}} children', - length: 'must have {{limit}} children', - allowUnknown: '!!"{{!child}}" is not allowed', - with: '!!"{{mainWithLabel}}" missing required peer "{{peerWithLabel}}"', - without: '!!"{{mainWithLabel}}" conflict with forbidden peer "{{peerWithLabel}}"', - missing: 'must contain at least one of {{peersWithLabels}}', - xor: 'contains a conflict between exclusive peers {{peersWithLabels}}', - oxor: 'contains a conflict between optional exclusive peers {{peersWithLabels}}', - and: 'contains {{presentWithLabels}} without its required peers {{missingWithLabels}}', - nand: '!!"{{mainWithLabel}}" must not exist simultaneously with {{peersWithLabels}}', - assert: '!!"{{ref}}" validation failed because "{{ref}}" failed to {{message}}', - rename: { - multiple: 'cannot rename child "{{from}}" because multiple renames are disabled and another key was already renamed to "{{to}}"', - override: 'cannot rename child "{{from}}" because override is disabled and target "{{to}}" exists', - regex: { - multiple: 'cannot rename children {{from}} because multiple renames are disabled and another key was already renamed to "{{to}}"', - override: 'cannot rename children {{from}} because override is disabled and target "{{to}}" exists' - } - }, - type: 'must be an instance of "{{type}}"', - schema: 'must be a Joi instance' - }, - number: { - base: 'must be a number', - unsafe: 'must be a safe number', - min: 'must be larger than or equal to {{limit}}', - max: 'must be less than or equal to {{limit}}', - less: 'must be less than {{limit}}', - greater: 'must be greater than {{limit}}', - integer: 'must be an integer', - negative: 'must be a negative number', - positive: 'must be a positive number', - precision: 'must have no more than {{limit}} decimal places', - ref: 'references "{{ref}}" which is not a number', - multiple: 'must be a multiple of {{multiple}}', - port: 'must be a valid port' - }, - string: { - base: 'must be a string', - min: 'length must be at least {{limit}} characters long', - max: 'length must be less than or equal to {{limit}} characters long', - length: 'length must be {{limit}} characters long', - alphanum: 'must only contain alpha-numeric characters', - token: 'must only contain alpha-numeric and underscore characters', - regex: { - base: 'with value "{{!value}}" fails to match the required pattern: {{pattern}}', - name: 'with value "{{!value}}" fails to match the {{name}} pattern', - invert: { - base: 'with value "{{!value}}" matches the inverted pattern: {{pattern}}', - name: 'with value "{{!value}}" matches the inverted {{name}} pattern' - } - }, - email: 'must be a valid email', - uri: 'must be a valid uri', - uriRelativeOnly: 'must be a valid relative uri', - uriCustomScheme: 'must be a valid uri with a scheme matching the {{scheme}} pattern', - isoDate: 'must be a valid ISO 8601 date', - guid: 'must be a valid GUID', - hex: 'must only contain hexadecimal characters', - hexAlign: 'hex decoded representation must be byte aligned', - base64: 'must be a valid base64 string', - dataUri: 'must be a valid dataUri string', - hostname: 'must be a valid hostname', - normalize: 'must be unicode normalized in the {{form}} form', - lowercase: 'must only contain lowercase characters', - uppercase: 'must only contain uppercase characters', - trim: 'must not have leading or trailing whitespace', - creditCard: 'must be a credit card', - ref: 'references "{{ref}}" which is not a number', - ip: 'must be a valid ip address with a {{cidr}} CIDR', - ipVersion: 'must be a valid ip address of one of the following versions {{version}} with a {{cidr}} CIDR' - }, - symbol: { - base: 'must be a symbol', - map: 'must be one of {{map}}' - } -}; - - -/***/ }), - -/***/ 71802: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -const Hoek = __nccwpck_require__(10904); - - -const internals = {}; - - -exports.create = function (key, options) { - - Hoek.assert(typeof key === 'string', 'Invalid reference key:', key); - - const settings = Hoek.clone(options); // options can be reused and modified - - const ref = function (value, validationOptions) { - - return Hoek.reach(ref.isContext ? validationOptions.context : value, ref.key, settings); - }; - - ref.isContext = (key[0] === ((settings && settings.contextPrefix) || '$')); - ref.key = (ref.isContext ? key.slice(1) : key); - ref.path = ref.key.split((settings && settings.separator) || '.'); - ref.depth = ref.path.length; - ref.root = ref.path[0]; - ref.isJoi = true; - - ref.toString = function () { - - return (ref.isContext ? 'context:' : 'ref:') + ref.key; - }; - - return ref; -}; - - -exports.isRef = function (ref) { - - return typeof ref === 'function' && ref.isJoi; -}; - - -exports.push = function (array, ref) { - - if (exports.isRef(ref) && - !ref.isContext) { - - array.push(ref.root); - } -}; - - -/***/ }), - -/***/ 13723: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -const Joi = __nccwpck_require__(44010); - - -const internals = {}; - - -exports.options = Joi.object({ - abortEarly: Joi.boolean(), - convert: Joi.boolean(), - allowUnknown: Joi.boolean(), - skipFunctions: Joi.boolean(), - stripUnknown: [Joi.boolean(), Joi.object({ arrays: Joi.boolean(), objects: Joi.boolean() }).or('arrays', 'objects')], - language: Joi.object(), - presence: Joi.string().only('required', 'optional', 'forbidden', 'ignore'), - context: Joi.object(), - noDefaults: Joi.boolean(), - escapeHtml: Joi.boolean() -}).strict(); - - -/***/ }), - -/***/ 39417: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const Ref = __nccwpck_require__(71802); - - -const internals = {}; - - -internals.extendedCheckForValue = function (value, insensitive) { - - const valueType = typeof value; - - if (valueType === 'object') { - if (value instanceof Date) { - return (item) => { - - return item instanceof Date && value.getTime() === item.getTime(); - }; - } - - if (Buffer.isBuffer(value)) { - return (item) => { - - return Buffer.isBuffer(item) && value.length === item.length && value.toString('binary') === item.toString('binary'); - }; - } - } - else if (insensitive && valueType === 'string') { - const lowercaseValue = value.toLowerCase(); - return (item) => { - - return typeof item === 'string' && lowercaseValue === item.toLowerCase(); - }; - } - - return null; -}; - - -module.exports = class InternalSet { - - constructor(from) { - - this._set = new Set(from); - this._hasRef = false; - } - - add(value, refs) { - - const isRef = Ref.isRef(value); - if (!isRef && this.has(value, null, null, false)) { - - return this; - } - - if (refs !== undefined) { // If it's a merge, we don't have any refs - Ref.push(refs, value); - } - - this._set.add(value); - - this._hasRef |= isRef; - - return this; - } - - merge(add, remove) { - - for (const item of add._set) { - this.add(item); - } - - for (const item of remove._set) { - this.remove(item); - } - - return this; - } - - remove(value) { - - this._set.delete(value); - return this; - } - - has(value, state, options, insensitive) { - - return !!this.get(value, state, options, insensitive); - } - - get(value, state, options, insensitive) { - - if (!this._set.size) { - return false; - } - - const hasValue = this._set.has(value); - if (hasValue) { - return { value }; - } - - const extendedCheck = internals.extendedCheckForValue(value, insensitive); - if (!extendedCheck) { - if (state && this._hasRef) { - for (let item of this._set) { - if (Ref.isRef(item)) { - item = [].concat(item(state.reference || state.parent, options)); - const found = item.indexOf(value); - if (found >= 0) { - return { value: item[found] }; - } - } - } - } - - return false; - } - - return this._has(value, state, options, extendedCheck); - } - - _has(value, state, options, check) { - - const checkRef = !!(state && this._hasRef); - - const isReallyEqual = function (item) { - - if (value === item) { - return true; - } - - return check(item); - }; - - for (let item of this._set) { - if (checkRef && Ref.isRef(item)) { // Only resolve references if there is a state, otherwise it's a merge - item = item(state.reference || state.parent, options); - - if (Array.isArray(item)) { - const found = item.findIndex(isReallyEqual); - if (found >= 0) { - return { - value: item[found] - }; - } - - continue; - } - } - - if (isReallyEqual(item)) { - return { - value: item - }; - } - } - - return false; - } - - values(options) { - - if (options && options.stripUndefined) { - const values = []; - - for (const item of this._set) { - if (item !== undefined) { - values.push(item); - } - } - - return values; - } - - return Array.from(this._set); - } - - slice() { - - const set = new InternalSet(this._set); - set._hasRef = this._hasRef; - return set; - } - - concat(source) { - - const set = new InternalSet([...this._set, ...source._set]); - set._hasRef = !!(this._hasRef | source._hasRef); - return set; - } -}; - - -/***/ }), - -/***/ 32797: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const Hoek = __nccwpck_require__(10904); - -const Any = __nccwpck_require__(77641); -const Cast = __nccwpck_require__(16415); -const Ref = __nccwpck_require__(71802); - - -const internals = {}; - - -internals.Alternatives = class extends Any { - - constructor() { - - super(); - this._type = 'alternatives'; - this._invalids.remove(null); - this._inner.matches = []; - } - - _init(...args) { - - return args.length ? this.try(...args) : this; - } - - _base(value, state, options) { - - const errors = []; - const il = this._inner.matches.length; - const baseType = this._baseType; - - for (let i = 0; i < il; ++i) { - const item = this._inner.matches[i]; - if (!item.schema) { - const schema = item.peek || item.is; - const input = item.is ? item.ref(state.reference || state.parent, options) : value; - const failed = schema._validate(input, null, options, state.parent).errors; - - if (failed) { - if (item.otherwise) { - return item.otherwise._validate(value, state, options); - } - } - else if (item.then) { - return item.then._validate(value, state, options); - } - - if (i === (il - 1) && baseType) { - return baseType._validate(value, state, options); - } - - continue; - } - - const result = item.schema._validate(value, state, options); - if (!result.errors) { // Found a valid match - return result; - } - - errors.push(...result.errors); - } - - if (errors.length) { - return { errors: this.createError('alternatives.child', { reason: errors }, state, options) }; - } - - return { errors: this.createError('alternatives.base', null, state, options) }; - } - - try(...schemas) { - - schemas = Hoek.flatten(schemas); - Hoek.assert(schemas.length, 'Cannot add other alternatives without at least one schema'); - - const obj = this.clone(); - - for (let i = 0; i < schemas.length; ++i) { - const cast = Cast.schema(this._currentJoi, schemas[i]); - if (cast._refs.length) { - obj._refs.push(...cast._refs); - } - - obj._inner.matches.push({ schema: cast }); - } - - return obj; - } - - when(condition, options) { - - let schemaCondition = false; - Hoek.assert(Ref.isRef(condition) || typeof condition === 'string' || (schemaCondition = condition instanceof Any), 'Invalid condition:', condition); - Hoek.assert(options, 'Missing options'); - Hoek.assert(typeof options === 'object', 'Invalid options'); - if (schemaCondition) { - Hoek.assert(!options.hasOwnProperty('is'), '"is" can not be used with a schema condition'); - } - else { - Hoek.assert(options.hasOwnProperty('is'), 'Missing "is" directive'); - } - - Hoek.assert(options.then !== undefined || options.otherwise !== undefined, 'options must have at least one of "then" or "otherwise"'); - - const obj = this.clone(); - let is; - if (!schemaCondition) { - is = Cast.schema(this._currentJoi, options.is); - - if (options.is === null || !(Ref.isRef(options.is) || options.is instanceof Any)) { - - // Only apply required if this wasn't already a schema or a ref, we'll suppose people know what they're doing - is = is.required(); - } - } - - const item = { - ref: schemaCondition ? null : Cast.ref(condition), - peek: schemaCondition ? condition : null, - is, - then: options.then !== undefined ? Cast.schema(this._currentJoi, options.then) : undefined, - otherwise: options.otherwise !== undefined ? Cast.schema(this._currentJoi, options.otherwise) : undefined - }; - - if (obj._baseType) { - - item.then = item.then && obj._baseType.concat(item.then); - item.otherwise = item.otherwise && obj._baseType.concat(item.otherwise); - } - - if (!schemaCondition) { - Ref.push(obj._refs, item.ref); - obj._refs.push(...item.is._refs); - } - - if (item.then && item.then._refs.length) { - obj._refs.push(...item.then._refs); - } - - if (item.otherwise && item.otherwise._refs.length) { - obj._refs.push(...item.otherwise._refs); - } - - obj._inner.matches.push(item); - - return obj; - } - - label(name) { - - const obj = super.label(name); - obj._inner.matches = obj._inner.matches.map((match) => { - - if (match.schema) { - return { schema: match.schema.label(name) }; - } - - match = Object.assign({}, match); - if (match.then) { - match.then = match.then.label(name); - } - - if (match.otherwise) { - match.otherwise = match.otherwise.label(name); - } - - return match; - }); - return obj; - } - - describe() { - - const description = super.describe(); - const alternatives = []; - for (let i = 0; i < this._inner.matches.length; ++i) { - const item = this._inner.matches[i]; - if (item.schema) { - - // try() - - alternatives.push(item.schema.describe()); - } - else { - - // when() - - const when = item.is ? { - ref: item.ref.toString(), - is: item.is.describe() - } : { - peek: item.peek.describe() - }; - - if (item.then) { - when.then = item.then.describe(); - } - - if (item.otherwise) { - when.otherwise = item.otherwise.describe(); - } - - alternatives.push(when); - } - } - - description.alternatives = alternatives; - return description; - } - -}; - - -module.exports = new internals.Alternatives(); - - -/***/ }), - -/***/ 77641: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const Hoek = __nccwpck_require__(10904); - -const Cast = __nccwpck_require__(16415); -const Settings = __nccwpck_require__(29804); -const Ref = __nccwpck_require__(71802); -const Errors = __nccwpck_require__(32150); -const State = __nccwpck_require__(13538); -const Symbols = __nccwpck_require__(52252); - -const Pkg = __nccwpck_require__(86251); - -let Alternatives = null; // Delay-loaded to prevent circular dependencies -let Schemas = null; - - -const internals = { - Set: __nccwpck_require__(39417), - symbol: Symbol.for('@hapi/joi/schema') -}; - - -internals.defaults = { - abortEarly: true, - convert: true, - allowUnknown: false, - skipFunctions: false, - stripUnknown: false, - language: {}, - presence: 'optional', - noDefaults: false, - escapeHtml: false - - // context: null -}; - - -module.exports = internals.Any = class { - - constructor() { - - this.isJoi = true; - this._type = 'any'; - this._settings = null; - this._valids = new internals.Set(); - this._invalids = new internals.Set(); - this._tests = []; - this._refs = []; - this._flags = { - /* - presence: 'optional', // optional, required, forbidden, ignore - allowOnly: false, - allowUnknown: undefined, - default: undefined, - forbidden: false, - encoding: undefined, - insensitive: false, - trim: false, - normalize: undefined, // NFC, NFD, NFKC, NFKD - case: undefined, // upper, lower - empty: undefined, - func: false, - raw: false - */ - }; - - this._description = null; - this._unit = null; - this._notes = []; - this._tags = []; - this._examples = []; - this._meta = []; - - this._inner = {}; // Hash of arrays of immutable objects - } - - _init() { - - return this; - } - - get schemaType() { - - return this._type; - } - - createError(type, context, state, options, flags = this._flags) { - - return Errors.create(type, context, state, options, flags); - } - - createOverrideError(type, context, state, options, message, template) { - - return Errors.create(type, context, state, options, this._flags, message, template); - } - - checkOptions(options) { - - Schemas = Schemas || __nccwpck_require__(13723); - - const result = Schemas.options.validate(options); - - if (result.error) { - throw new Error(result.error.details[0].message); - } - } - - clone() { - - const obj = Object.create(Object.getPrototypeOf(this)); - - obj.isJoi = true; - obj._currentJoi = this._currentJoi; - obj._type = this._type; - obj._settings = this._settings; - obj._baseType = this._baseType; - obj._valids = this._valids.slice(); - obj._invalids = this._invalids.slice(); - obj._tests = this._tests.slice(); - obj._refs = this._refs.slice(); - obj._flags = Hoek.clone(this._flags); - - obj._description = this._description; - obj._unit = this._unit; - obj._notes = this._notes.slice(); - obj._tags = this._tags.slice(); - obj._examples = this._examples.slice(); - obj._meta = this._meta.slice(); - - obj._inner = {}; - const inners = Object.keys(this._inner); - for (let i = 0; i < inners.length; ++i) { - const key = inners[i]; - obj._inner[key] = this._inner[key] ? this._inner[key].slice() : null; - } - - return obj; - } - - concat(schema) { - - Hoek.assert(schema instanceof internals.Any, 'Invalid schema object'); - Hoek.assert(this._type === 'any' || schema._type === 'any' || schema._type === this._type, 'Cannot merge type', this._type, 'with another type:', schema._type); - - let obj = this.clone(); - - if (this._type === 'any' && schema._type !== 'any') { - - // Reset values as if we were "this" - const tmpObj = schema.clone(); - const keysToRestore = ['_settings', '_valids', '_invalids', '_tests', '_refs', '_flags', '_description', '_unit', - '_notes', '_tags', '_examples', '_meta', '_inner']; - - for (let i = 0; i < keysToRestore.length; ++i) { - tmpObj[keysToRestore[i]] = obj[keysToRestore[i]]; - } - - obj = tmpObj; - } - - obj._settings = obj._settings ? Settings.concat(obj._settings, schema._settings) : schema._settings; - obj._valids.merge(schema._valids, schema._invalids); - obj._invalids.merge(schema._invalids, schema._valids); - obj._tests.push(...schema._tests); - obj._refs.push(...schema._refs); - if (obj._flags.empty && schema._flags.empty) { - obj._flags.empty = obj._flags.empty.concat(schema._flags.empty); - const flags = Object.assign({}, schema._flags); - delete flags.empty; - Hoek.merge(obj._flags, flags); - } - else if (schema._flags.empty) { - obj._flags.empty = schema._flags.empty; - const flags = Object.assign({}, schema._flags); - delete flags.empty; - Hoek.merge(obj._flags, flags); - } - else { - Hoek.merge(obj._flags, schema._flags); - } - - obj._description = schema._description || obj._description; - obj._unit = schema._unit || obj._unit; - obj._notes.push(...schema._notes); - obj._tags.push(...schema._tags); - obj._examples.push(...schema._examples); - obj._meta.push(...schema._meta); - - const inners = Object.keys(schema._inner); - const isObject = obj._type === 'object'; - for (let i = 0; i < inners.length; ++i) { - const key = inners[i]; - const source = schema._inner[key]; - if (source) { - const target = obj._inner[key]; - if (target) { - if (isObject && key === 'children') { - const keys = {}; - - for (let j = 0; j < target.length; ++j) { - keys[target[j].key] = j; - } - - for (let j = 0; j < source.length; ++j) { - const sourceKey = source[j].key; - if (keys[sourceKey] >= 0) { - target[keys[sourceKey]] = { - key: sourceKey, - schema: target[keys[sourceKey]].schema.concat(source[j].schema) - }; - } - else { - target.push(source[j]); - } - } - } - else { - obj._inner[key] = obj._inner[key].concat(source); - } - } - else { - obj._inner[key] = source.slice(); - } - } - } - - return obj; - } - - _test(name, arg, func, options) { - - const obj = this.clone(); - obj._tests.push({ func, name, arg, options }); - return obj; - } - - _testUnique(name, arg, func, options) { - - const obj = this.clone(); - obj._tests = obj._tests.filter((test) => test.name !== name); - obj._tests.push({ func, name, arg, options }); - return obj; - } - - options(options) { - - Hoek.assert(!options.context, 'Cannot override context'); - this.checkOptions(options); - - const obj = this.clone(); - obj._settings = Settings.concat(obj._settings, options); - return obj; - } - - strict(isStrict) { - - const obj = this.clone(); - - const convert = isStrict === undefined ? false : !isStrict; - obj._settings = Settings.concat(obj._settings, { convert }); - return obj; - } - - raw(isRaw) { - - const value = isRaw === undefined ? true : isRaw; - - if (this._flags.raw === value) { - return this; - } - - const obj = this.clone(); - obj._flags.raw = value; - return obj; - } - - error(err, options = { self: false }) { - - Hoek.assert(err && (err instanceof Error || typeof err === 'function'), 'Must provide a valid Error object or a function'); - - const unknownKeys = Object.keys(options).filter((k) => !['self'].includes(k)); - Hoek.assert(unknownKeys.length === 0, `Options ${unknownKeys} are unknown`); - - const obj = this.clone(); - obj._flags.error = err; - - if (options.self) { - obj._flags.selfError = true; - } - - return obj; - } - - allow(...values) { - - const obj = this.clone(); - values = Hoek.flatten(values); - for (let i = 0; i < values.length; ++i) { - const value = values[i]; - - Hoek.assert(value !== undefined, 'Cannot call allow/valid/invalid with undefined'); - obj._invalids.remove(value); - obj._valids.add(value, obj._refs); - } - - return obj; - } - - valid(...values) { - - const obj = this.allow(...values); - obj._flags.allowOnly = true; - return obj; - } - - invalid(...values) { - - const obj = this.clone(); - values = Hoek.flatten(values); - for (let i = 0; i < values.length; ++i) { - const value = values[i]; - - Hoek.assert(value !== undefined, 'Cannot call allow/valid/invalid with undefined'); - obj._valids.remove(value); - obj._invalids.add(value, obj._refs); - } - - return obj; - } - - required() { - - if (this._flags.presence === 'required') { - return this; - } - - const obj = this.clone(); - obj._flags.presence = 'required'; - return obj; - } - - optional() { - - if (this._flags.presence === 'optional') { - return this; - } - - const obj = this.clone(); - obj._flags.presence = 'optional'; - return obj; - } - - - forbidden() { - - if (this._flags.presence === 'forbidden') { - return this; - } - - const obj = this.clone(); - obj._flags.presence = 'forbidden'; - return obj; - } - - - strip() { - - if (this._flags.strip) { - return this; - } - - const obj = this.clone(); - obj._flags.strip = true; - return obj; - } - - applyFunctionToChildren(children, fn, args = [], root) { - - children = [].concat(children); - - if (children.length !== 1 || children[0] !== '') { - root = root ? (root + '.') : ''; - - const extraChildren = (children[0] === '' ? children.slice(1) : children).map((child) => { - - return root + child; - }); - - throw new Error('unknown key(s) ' + extraChildren.join(', ')); - } - - return this[fn](...args); - } - - default(value, description) { - - if (typeof value === 'function' && - !Ref.isRef(value)) { - - if (!value.description && - description) { - - value.description = description; - } - - if (!this._flags.func) { - Hoek.assert(typeof value.description === 'string' && value.description.length > 0, 'description must be provided when default value is a function'); - } - } - - const obj = this.clone(); - obj._flags.default = value; - Ref.push(obj._refs, value); - return obj; - } - - empty(schema) { - - const obj = this.clone(); - if (schema === undefined) { - delete obj._flags.empty; - } - else { - obj._flags.empty = Cast.schema(this._currentJoi, schema); - } - - return obj; - } - - when(condition, options) { - - Hoek.assert(options && typeof options === 'object', 'Invalid options'); - Hoek.assert(options.then !== undefined || options.otherwise !== undefined, 'options must have at least one of "then" or "otherwise"'); - - const then = options.hasOwnProperty('then') ? this.concat(Cast.schema(this._currentJoi, options.then)) : undefined; - const otherwise = options.hasOwnProperty('otherwise') ? this.concat(Cast.schema(this._currentJoi, options.otherwise)) : undefined; - - Alternatives = Alternatives || __nccwpck_require__(32797); - - const alternativeOptions = { then, otherwise }; - if (Object.prototype.hasOwnProperty.call(options, 'is')) { - alternativeOptions.is = options.is; - } - - const obj = Alternatives.when(condition, alternativeOptions); - obj._flags.presence = 'ignore'; - obj._baseType = this; - - return obj; - } - - description(desc) { - - Hoek.assert(desc && typeof desc === 'string', 'Description must be a non-empty string'); - - const obj = this.clone(); - obj._description = desc; - return obj; - } - - notes(notes) { - - Hoek.assert(notes && (typeof notes === 'string' || Array.isArray(notes)), 'Notes must be a non-empty string or array'); - - const obj = this.clone(); - obj._notes = obj._notes.concat(notes); - return obj; - } - - tags(tags) { - - Hoek.assert(tags && (typeof tags === 'string' || Array.isArray(tags)), 'Tags must be a non-empty string or array'); - - const obj = this.clone(); - obj._tags = obj._tags.concat(tags); - return obj; - } - - meta(meta) { - - Hoek.assert(meta !== undefined, 'Meta cannot be undefined'); - - const obj = this.clone(); - obj._meta = obj._meta.concat(meta); - return obj; - } - - example(...examples) { - - Hoek.assert(examples.length > 0, 'Missing examples'); - - const processed = []; - for (let i = 0; i < examples.length; ++i) { - const example = [].concat(examples[i]); - Hoek.assert(example.length <= 2, `Bad example format at index ${i}`); - - const value = example[0]; - let options = example[1]; - if (options !== undefined) { - Hoek.assert(options && typeof options === 'object', `Options for example at index ${i} must be an object`); - const unknownOptions = Object.keys(options).filter((option) => !['parent', 'context'].includes(option)); - Hoek.assert(unknownOptions.length === 0, `Unknown example options ${unknownOptions} at index ${i}`); - } - else { - options = {}; - } - - const localState = new State('', [], options.parent || null); - const result = this._validate(value, localState, Settings.concat(internals.defaults, options.context ? { context: options.context } : null)); - Hoek.assert(!result.errors, `Bad example at index ${i}:`, result.errors && Errors.process(result.errors, value)); - - const ex = { value }; - if (Object.keys(options).length) { - ex.options = options; - } - - processed.push(ex); - } - - const obj = this.clone(); - obj._examples = processed; - return obj; - } - - unit(name) { - - Hoek.assert(name && typeof name === 'string', 'Unit name must be a non-empty string'); - - const obj = this.clone(); - obj._unit = name; - return obj; - } - - _prepareEmptyValue(value) { - - if (typeof value === 'string' && this._flags.trim) { - return value.trim(); - } - - return value; - } - - _validate(value, state, options, reference) { - - const originalValue = value; - - // Setup state and settings - - state = state || new State('', [], null, reference); - - if (this._settings) { - const isDefaultOptions = options === internals.defaults; - if (isDefaultOptions && this._settings[Symbols.settingsCache]) { - options = this._settings[Symbols.settingsCache]; - } - else { - options = Settings.concat(this._language ? Settings.concat({ language: this._language }, options) : options, this._settings); - if (isDefaultOptions) { - this._settings[Symbols.settingsCache] = options; - } - } - } - else if (this._language) { - options = Settings.concat({ language: this._language }, options); - } - - let errors = []; - - if (this._coerce) { - const coerced = this._coerce(value, state, options); - if (coerced.errors) { - value = coerced.value; - errors = errors.concat(coerced.errors); - return this._finalizeValue(value, originalValue, errors, state, options); // Coerced error always aborts early - } - - value = coerced.value; - } - - if (this._flags.empty && !this._flags.empty._validate(this._prepareEmptyValue(value), null, internals.defaults).errors) { - value = undefined; - } - - // Check presence requirements - - const presence = this._flags.presence || options.presence; - if (presence === 'optional') { - if (value === undefined) { - const isDeepDefault = this._flags.hasOwnProperty('default') && this._flags.default === undefined; - if (isDeepDefault && this._type === 'object') { - value = {}; - } - else { - return this._finalizeValue(value, originalValue, errors, state, options); - } - } - } - else if (presence === 'required' && - value === undefined) { - - errors.push(this.createError('any.required', null, state, options)); - return this._finalizeValue(value, originalValue, errors, state, options); - } - else if (presence === 'forbidden') { - if (value === undefined) { - return this._finalizeValue(value, originalValue, errors, state, options); - } - - errors.push(this.createError('any.unknown', null, state, options)); - return this._finalizeValue(value, originalValue, errors, state, options); - } - - // Check allowed and denied values using the original value - - let match = this._valids.get(value, state, options, this._flags.insensitive); - if (match) { - if (options.convert) { - value = match.value; - } - - return this._finalizeValue(value, originalValue, errors, state, options); - } - - if (this._invalids.has(value, state, options, this._flags.insensitive)) { - errors.push(this.createError(value === '' ? 'any.empty' : 'any.invalid', { value, invalids: this._invalids.values({ stripUndefined: true }) }, state, options)); - if (options.abortEarly) { - - return this._finalizeValue(value, originalValue, errors, state, options); - } - } - - // Convert value and validate type - - if (this._base) { - const base = this._base(value, state, options); - if (base.errors) { - value = base.value; - errors = errors.concat(base.errors); - return this._finalizeValue(value, originalValue, errors, state, options); // Base error always aborts early - } - - if (base.value !== value) { - value = base.value; - - // Check allowed and denied values using the converted value - - match = this._valids.get(value, state, options, this._flags.insensitive); - if (match) { - value = match.value; - return this._finalizeValue(value, originalValue, errors, state, options); - } - - if (this._invalids.has(value, state, options, this._flags.insensitive)) { - errors.push(this.createError(value === '' ? 'any.empty' : 'any.invalid', { value, invalids: this._invalids.values({ stripUndefined: true }) }, state, options)); - if (options.abortEarly) { - return this._finalizeValue(value, originalValue, errors, state, options); - } - } - } - } - - // Required values did not match - - if (this._flags.allowOnly) { - errors.push(this.createError('any.allowOnly', { value, valids: this._valids.values({ stripUndefined: true }) }, state, options)); - if (options.abortEarly) { - return this._finalizeValue(value, originalValue, errors, state, options); - } - } - - // Validate tests - - for (let i = 0; i < this._tests.length; ++i) { - const test = this._tests[i]; - const ret = test.func.call(this, value, state, options); - if (ret instanceof Errors.Err) { - errors.push(ret); - if (options.abortEarly) { - return this._finalizeValue(value, originalValue, errors, state, options); - } - } - else { - value = ret; - } - } - - return this._finalizeValue(value, originalValue, errors, state, options); - } - - _finalizeValue(value, originalValue, errors, state, options) { - - let finalValue; - - if (value !== undefined) { - finalValue = this._flags.raw ? originalValue : value; - } - else if (options.noDefaults) { - finalValue = value; - } - else if (Ref.isRef(this._flags.default)) { - finalValue = this._flags.default(state.parent, options); - } - else if (typeof this._flags.default === 'function' && - !(this._flags.func && !this._flags.default.description)) { - - let args; - - if (state.parent !== null && - this._flags.default.length > 0) { - - args = [Hoek.clone(state.parent), options]; - } - - const defaultValue = internals._try(this._flags.default, args); - finalValue = defaultValue.value; - if (defaultValue.error) { - errors.push(this.createError('any.default', { error: defaultValue.error }, state, options)); - } - } - else { - finalValue = Hoek.clone(this._flags.default); - } - - if (errors.length && - typeof this._flags.error === 'function' && - ( - !this._flags.selfError || - errors.some((e) => state.path.length === e.path.length) - ) - ) { - const change = this._flags.error.call(this, errors); - - if (typeof change === 'string') { - errors = [this.createOverrideError('override', { reason: errors }, state, options, change)]; - } - else { - errors = [].concat(change) - .map((err) => { - - return err instanceof Error ? - err : - this.createOverrideError(err.type || 'override', err.context, state, options, err.message, err.template); - }); - } - } - - return { - value: this._flags.strip ? undefined : finalValue, - finalValue, - errors: errors.length ? errors : null - }; - } - - _validateWithOptions(value, options, callback) { - - if (options) { - this.checkOptions(options); - } - - const settings = Settings.concat(internals.defaults, options); - const result = this._validate(value, null, settings); - const errors = Errors.process(result.errors, value); - - if (callback) { - return callback(errors, result.value); - } - - return { - error: errors, - value: result.value, - then(resolve, reject) { - - if (errors) { - return Promise.reject(errors).catch(reject); - } - - return Promise.resolve(result.value).then(resolve); - }, - catch(reject) { - - if (errors) { - return Promise.reject(errors).catch(reject); - } - - return Promise.resolve(result.value); - } - }; - } - - validate(value, options, callback) { - - if (typeof options === 'function') { - return this._validateWithOptions(value, null, options); - } - - return this._validateWithOptions(value, options, callback); - } - - describe() { - - const description = { - type: this._type - }; - - const flags = Object.keys(this._flags); - if (flags.length) { - if (['empty', 'default', 'lazy', 'label'].some((flag) => this._flags.hasOwnProperty(flag))) { - description.flags = {}; - for (let i = 0; i < flags.length; ++i) { - const flag = flags[i]; - if (flag === 'empty') { - description.flags[flag] = this._flags[flag].describe(); - } - else if (flag === 'default') { - if (Ref.isRef(this._flags[flag])) { - description.flags[flag] = this._flags[flag].toString(); - } - else if (typeof this._flags[flag] === 'function') { - description.flags[flag] = { - description: this._flags[flag].description, - function : this._flags[flag] - }; - } - else { - description.flags[flag] = this._flags[flag]; - } - } - else if (flag === 'lazy' || flag === 'label') { - // We don't want it in the description - } - else { - description.flags[flag] = this._flags[flag]; - } - } - } - else { - description.flags = this._flags; - } - } - - if (this._settings) { - description.options = Hoek.clone(this._settings); - } - - if (this._baseType) { - description.base = this._baseType.describe(); - } - - if (this._description) { - description.description = this._description; - } - - if (this._notes.length) { - description.notes = this._notes; - } - - if (this._tags.length) { - description.tags = this._tags; - } - - if (this._meta.length) { - description.meta = this._meta; - } - - if (this._examples.length) { - description.examples = this._examples; - } - - if (this._unit) { - description.unit = this._unit; - } - - const valids = this._valids.values(); - if (valids.length) { - description.valids = valids.map((v) => { - - return Ref.isRef(v) ? v.toString() : v; - }); - } - - const invalids = this._invalids.values(); - if (invalids.length) { - description.invalids = invalids.map((v) => { - - return Ref.isRef(v) ? v.toString() : v; - }); - } - - description.rules = []; - - for (let i = 0; i < this._tests.length; ++i) { - const validator = this._tests[i]; - const item = { name: validator.name }; - - if (validator.arg !== void 0) { - item.arg = Ref.isRef(validator.arg) ? validator.arg.toString() : validator.arg; - } - - const options = validator.options; - if (options) { - if (options.hasRef) { - item.arg = {}; - const keys = Object.keys(validator.arg); - for (let j = 0; j < keys.length; ++j) { - const key = keys[j]; - const value = validator.arg[key]; - item.arg[key] = Ref.isRef(value) ? value.toString() : value; - } - } - - if (typeof options.description === 'string') { - item.description = options.description; - } - else if (typeof options.description === 'function') { - item.description = options.description(item.arg); - } - } - - description.rules.push(item); - } - - if (!description.rules.length) { - delete description.rules; - } - - const label = this._getLabel(); - if (label) { - description.label = label; - } - - return description; - } - - label(name) { - - Hoek.assert(name && typeof name === 'string', 'Label name must be a non-empty string'); - - const obj = this.clone(); - obj._flags.label = name; - return obj; - } - - _getLabel(def) { - - return this._flags.label || def; - } - -}; - - -internals.Any.prototype.isImmutable = true; // Prevents Hoek from deep cloning schema objects - -// Aliases - -internals.Any.prototype.only = internals.Any.prototype.equal = internals.Any.prototype.valid; -internals.Any.prototype.disallow = internals.Any.prototype.not = internals.Any.prototype.invalid; -internals.Any.prototype.exist = internals.Any.prototype.required; - - -internals.Any.prototype[internals.symbol] = { - version: Pkg.version, - compile: Cast.schema, - root: '_currentJoi' -}; - - -internals._try = function (fn, args = []) { - - let err; - let result; - - try { - result = fn(...args); - } - catch (e) { - err = e; - } - - return { - value: result, - error: err - }; -}; - - -/***/ }), - -/***/ 29804: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -const Hoek = __nccwpck_require__(10904); - -const Symbols = __nccwpck_require__(52252); - - -const internals = {}; - - -exports.concat = function (target, source) { - - if (!source) { - return target; - } - - const obj = Object.assign({}, target); - - const language = source.language; - - Object.assign(obj, source); - - if (language && target && target.language) { - obj.language = Hoek.applyToDefaults(target.language, language); - } - - if (obj[Symbols.settingsCache]) { - delete obj[Symbols.settingsCache]; - } - - return obj; -}; - - -/***/ }), - -/***/ 81500: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const Bourne = __nccwpck_require__(97174); -const Hoek = __nccwpck_require__(10904); - -const Any = __nccwpck_require__(77641); -const Cast = __nccwpck_require__(16415); -const Ref = __nccwpck_require__(71802); -const State = __nccwpck_require__(13538); - - -const internals = {}; - - -internals.fastSplice = function (arr, i) { - - let pos = i; - while (pos < arr.length) { - arr[pos++] = arr[pos]; - } - - --arr.length; -}; - - -internals.Array = class extends Any { - - constructor() { - - super(); - this._type = 'array'; - this._inner.items = []; - this._inner.ordereds = []; - this._inner.inclusions = []; - this._inner.exclusions = []; - this._inner.requireds = []; - this._flags.sparse = false; - } - - _base(value, state, options) { - - const result = { - value - }; - - if (typeof value === 'string' && - options.convert) { - - if (value.length > 1 && - (value[0] === '[' || /^\s*\[/.test(value))) { - - try { - result.value = Bourne.parse(value); - } - catch (e) { } - } - } - - let isArray = Array.isArray(result.value); - const wasArray = isArray; - if (options.convert && this._flags.single && !isArray) { - result.value = [result.value]; - isArray = true; - } - - if (!isArray) { - result.errors = this.createError('array.base', null, state, options); - return result; - } - - if (this._inner.inclusions.length || - this._inner.exclusions.length || - this._inner.requireds.length || - this._inner.ordereds.length || - !this._flags.sparse) { - - // Clone the array so that we don't modify the original - if (wasArray) { - result.value = result.value.slice(0); - } - - result.errors = this._checkItems(result.value, wasArray, state, options); - - if (result.errors && wasArray && options.convert && this._flags.single) { - - // Attempt a 2nd pass by putting the array inside one. - const previousErrors = result.errors; - - result.value = [result.value]; - result.errors = this._checkItems(result.value, wasArray, state, options); - - if (result.errors) { - - // Restore previous errors and value since this didn't validate either. - result.errors = previousErrors; - result.value = result.value[0]; - } - } - } - - return result; - } - - _checkItems(items, wasArray, state, options) { - - const errors = []; - let errored; - - const requireds = this._inner.requireds.slice(); - const ordereds = this._inner.ordereds.slice(); - const inclusions = [...this._inner.inclusions, ...requireds]; - - let il = items.length; - for (let i = 0; i < il; ++i) { - errored = false; - const item = items[i]; - let isValid = false; - const key = wasArray ? i : state.key; - const path = wasArray ? [...state.path, i] : state.path; - const localState = new State(key, path, state.parent, state.reference); - let res; - - // Sparse - - if (!this._flags.sparse && item === undefined) { - errors.push(this.createError('array.sparse', null, { key: state.key, path: localState.path, pos: i }, options)); - - if (options.abortEarly) { - return errors; - } - - ordereds.shift(); - - continue; - } - - // Exclusions - - for (let j = 0; j < this._inner.exclusions.length; ++j) { - res = this._inner.exclusions[j]._validate(item, localState, {}); // Not passing options to use defaults - - if (!res.errors) { - errors.push(this.createError(wasArray ? 'array.excludes' : 'array.excludesSingle', { pos: i, value: item }, { key: state.key, path: localState.path }, options)); - errored = true; - - if (options.abortEarly) { - return errors; - } - - ordereds.shift(); - - break; - } - } - - if (errored) { - continue; - } - - // Ordered - if (this._inner.ordereds.length) { - if (ordereds.length > 0) { - const ordered = ordereds.shift(); - res = ordered._validate(item, localState, options); - if (!res.errors) { - if (ordered._flags.strip) { - internals.fastSplice(items, i); - --i; - --il; - } - else if (!this._flags.sparse && res.value === undefined) { - errors.push(this.createError('array.sparse', null, { key: state.key, path: localState.path, pos: i }, options)); - - if (options.abortEarly) { - return errors; - } - - continue; - } - else { - items[i] = res.value; - } - } - else { - errors.push(this.createError('array.ordered', { pos: i, reason: res.errors, value: item }, { key: state.key, path: localState.path }, options)); - if (options.abortEarly) { - return errors; - } - } - - continue; - } - else if (!this._inner.items.length) { - errors.push(this.createError('array.orderedLength', { pos: i, limit: this._inner.ordereds.length }, { key: state.key, path: localState.path }, options)); - if (options.abortEarly) { - return errors; - } - - continue; - } - } - - // Requireds - - const requiredChecks = []; - let jl = requireds.length; - for (let j = 0; j < jl; ++j) { - res = requiredChecks[j] = requireds[j]._validate(item, localState, options); - if (!res.errors) { - items[i] = res.value; - isValid = true; - internals.fastSplice(requireds, j); - --j; - --jl; - - if (!this._flags.sparse && res.value === undefined) { - errors.push(this.createError('array.sparse', null, { key: state.key, path: localState.path, pos: i }, options)); - - if (options.abortEarly) { - return errors; - } - } - - break; - } - } - - if (isValid) { - continue; - } - - // Inclusions - - const stripUnknown = options.stripUnknown && !!options.stripUnknown.arrays || false; - - jl = inclusions.length; - for (let j = 0; j < jl; ++j) { - const inclusion = inclusions[j]; - - // Avoid re-running requireds that already didn't match in the previous loop - const previousCheck = requireds.indexOf(inclusion); - if (previousCheck !== -1) { - res = requiredChecks[previousCheck]; - } - else { - res = inclusion._validate(item, localState, options); - - if (!res.errors) { - if (inclusion._flags.strip) { - internals.fastSplice(items, i); - --i; - --il; - } - else if (!this._flags.sparse && res.value === undefined) { - errors.push(this.createError('array.sparse', null, { key: state.key, path: localState.path, pos: i }, options)); - errored = true; - } - else { - items[i] = res.value; - } - - isValid = true; - break; - } - } - - // Return the actual error if only one inclusion defined - if (jl === 1) { - if (stripUnknown) { - internals.fastSplice(items, i); - --i; - --il; - isValid = true; - break; - } - - errors.push(this.createError(wasArray ? 'array.includesOne' : 'array.includesOneSingle', { pos: i, reason: res.errors, value: item }, { key: state.key, path: localState.path }, options)); - errored = true; - - if (options.abortEarly) { - return errors; - } - - break; - } - } - - if (errored) { - continue; - } - - if (this._inner.inclusions.length && !isValid) { - if (stripUnknown) { - internals.fastSplice(items, i); - --i; - --il; - continue; - } - - errors.push(this.createError(wasArray ? 'array.includes' : 'array.includesSingle', { pos: i, value: item }, { key: state.key, path: localState.path }, options)); - - if (options.abortEarly) { - return errors; - } - } - } - - if (requireds.length) { - this._fillMissedErrors(errors, requireds, state, options); - } - - if (ordereds.length) { - this._fillOrderedErrors(errors, ordereds, state, options); - } - - return errors.length ? errors : null; - } - - describe() { - - const description = super.describe(); - - if (this._inner.ordereds.length) { - description.orderedItems = []; - - for (let i = 0; i < this._inner.ordereds.length; ++i) { - description.orderedItems.push(this._inner.ordereds[i].describe()); - } - } - - if (this._inner.items.length) { - description.items = []; - - for (let i = 0; i < this._inner.items.length; ++i) { - description.items.push(this._inner.items[i].describe()); - } - } - - if (description.rules) { - for (let i = 0; i < description.rules.length; ++i) { - const rule = description.rules[i]; - if (rule.name === 'has') { - rule.arg = rule.arg.describe(); - } - } - } - - return description; - } - - items(...schemas) { - - const obj = this.clone(); - - Hoek.flatten(schemas).forEach((type, index) => { - - try { - type = Cast.schema(this._currentJoi, type); - } - catch (castErr) { - if (castErr.hasOwnProperty('path')) { - castErr.path = index + '.' + castErr.path; - } - else { - castErr.path = index; - } - - castErr.message = `${castErr.message}(${castErr.path})`; - throw castErr; - } - - obj._inner.items.push(type); - - if (type._flags.presence === 'required') { - obj._inner.requireds.push(type); - } - else if (type._flags.presence === 'forbidden') { - obj._inner.exclusions.push(type.optional()); - } - else { - obj._inner.inclusions.push(type); - } - }); - - return obj; - } - - ordered(...schemas) { - - const obj = this.clone(); - - Hoek.flatten(schemas).forEach((type, index) => { - - try { - type = Cast.schema(this._currentJoi, type); - } - catch (castErr) { - if (castErr.hasOwnProperty('path')) { - castErr.path = index + '.' + castErr.path; - } - else { - castErr.path = index; - } - - castErr.message = `${castErr.message}(${castErr.path})`; - throw castErr; - } - - obj._inner.ordereds.push(type); - }); - - return obj; - } - - min(limit) { - - const isRef = Ref.isRef(limit); - - Hoek.assert((Number.isSafeInteger(limit) && limit >= 0) || isRef, 'limit must be a positive integer or reference'); - - return this._testUnique('min', limit, function (value, state, options) { - - let compareTo; - if (isRef) { - compareTo = limit(state.reference || state.parent, options); - - if (!(Number.isSafeInteger(compareTo) && compareTo >= 0)) { - return this.createError('array.ref', { ref: limit, value: compareTo }, state, options); - } - } - else { - compareTo = limit; - } - - if (value.length >= compareTo) { - return value; - } - - return this.createError('array.min', { limit, value }, state, options); - }); - } - - max(limit) { - - const isRef = Ref.isRef(limit); - - Hoek.assert((Number.isSafeInteger(limit) && limit >= 0) || isRef, 'limit must be a positive integer or reference'); - - return this._testUnique('max', limit, function (value, state, options) { - - let compareTo; - if (isRef) { - compareTo = limit(state.reference || state.parent, options); - - if (!(Number.isSafeInteger(compareTo) && compareTo >= 0)) { - return this.createError('array.ref', { ref: limit.key }, state, options); - } - } - else { - compareTo = limit; - } - - if (value.length <= compareTo) { - return value; - } - - return this.createError('array.max', { limit, value }, state, options); - }); - } - - length(limit) { - - const isRef = Ref.isRef(limit); - - Hoek.assert((Number.isSafeInteger(limit) && limit >= 0) || isRef, 'limit must be a positive integer or reference'); - - return this._testUnique('length', limit, function (value, state, options) { - - let compareTo; - if (isRef) { - compareTo = limit(state.reference || state.parent, options); - - if (!(Number.isSafeInteger(compareTo) && compareTo >= 0)) { - return this.createError('array.ref', { ref: limit.key }, state, options); - } - } - else { - compareTo = limit; - } - - if (value.length === compareTo) { - return value; - } - - return this.createError('array.length', { limit, value }, state, options); - }); - } - - has(schema) { - - try { - schema = Cast.schema(this._currentJoi, schema); - } - catch (castErr) { - if (castErr.hasOwnProperty('path')) { - castErr.message = `${castErr.message}(${castErr.path})`; - } - - throw castErr; - } - - return this._test('has', schema, function (value, state, options) { - - const isValid = value.some((item, idx) => { - - const localState = new State(idx, [...state.path, idx], state.key, state.reference); - return !schema._validate(item, localState, options).errors; - }); - - if (isValid) { - return value; - } - - const patternLabel = schema._getLabel(); - if (patternLabel) { - return this.createError('array.hasKnown', { patternLabel }, state, options); - } - - return this.createError('array.hasUnknown', null, state, options); - }); - } - - unique(comparator, configs) { - - Hoek.assert(comparator === undefined || - typeof comparator === 'function' || - typeof comparator === 'string', 'comparator must be a function or a string'); - - Hoek.assert(configs === undefined || - typeof configs === 'object', 'configs must be an object'); - - const settings = { - ignoreUndefined: (configs && configs.ignoreUndefined) || false - }; - - - if (typeof comparator === 'string') { - settings.path = comparator; - } - else if (typeof comparator === 'function') { - settings.comparator = comparator; - } - - return this._test('unique', settings, function (value, state, options) { - - 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 compare = settings.comparator || Hoek.deepEqual; - const ignoreUndefined = settings.ignoreUndefined; - - for (let i = 0; i < value.length; ++i) { - const item = settings.path ? Hoek.reach(value[i], settings.path) : value[i]; - const records = settings.comparator ? found.custom : found[typeof item]; - - // All available types are supported, so it's not possible to reach 100% coverage without ignoring this line. - // I still want to keep the test for future js versions with new types (eg. Symbol). - if (/* $lab:coverage:off$ */ records /* $lab:coverage:on$ */) { - if (records instanceof Map) { - const entries = records.entries(); - let current; - while (!(current = entries.next()).done) { - if (compare(current.value[0], item)) { - const localState = new State(state.key, [...state.path, i], state.parent, state.reference); - const context = { - pos: i, - value: value[i], - dupePos: current.value[1], - dupeValue: value[current.value[1]] - }; - - if (settings.path) { - context.path = settings.path; - } - - return this.createError('array.unique', context, localState, options); - } - } - - records.set(item, i); - } - else { - if ((!ignoreUndefined || item !== undefined) && records[item] !== undefined) { - const localState = new State(state.key, [...state.path, i], state.parent, state.reference); - - const context = { - pos: i, - value: value[i], - dupePos: records[item], - dupeValue: value[records[item]] - }; - - if (settings.path) { - context.path = settings.path; - } - - return this.createError('array.unique', context, localState, options); - } - - records[item] = i; - } - } - } - - return value; - }); - } - - sparse(enabled) { - - const value = enabled === undefined ? true : !!enabled; - - if (this._flags.sparse === value) { - return this; - } - - const obj = this.clone(); - obj._flags.sparse = value; - return obj; - } - - single(enabled) { - - const value = enabled === undefined ? true : !!enabled; - - if (this._flags.single === value) { - return this; - } - - const obj = this.clone(); - obj._flags.single = value; - return obj; - } - - _fillMissedErrors(errors, requireds, state, options) { - - const knownMisses = []; - let unknownMisses = 0; - for (let i = 0; i < requireds.length; ++i) { - const label = requireds[i]._getLabel(); - if (label) { - knownMisses.push(label); - } - else { - ++unknownMisses; - } - } - - if (knownMisses.length) { - if (unknownMisses) { - errors.push(this.createError('array.includesRequiredBoth', { knownMisses, unknownMisses }, { key: state.key, path: state.path }, options)); - } - else { - errors.push(this.createError('array.includesRequiredKnowns', { knownMisses }, { key: state.key, path: state.path }, options)); - } - } - else { - errors.push(this.createError('array.includesRequiredUnknowns', { unknownMisses }, { key: state.key, path: state.path }, options)); - } - } - - - _fillOrderedErrors(errors, ordereds, state, options) { - - const requiredOrdereds = []; - - for (let i = 0; i < ordereds.length; ++i) { - const presence = Hoek.reach(ordereds[i], '_flags.presence'); - if (presence === 'required') { - requiredOrdereds.push(ordereds[i]); - } - } - - if (requiredOrdereds.length) { - this._fillMissedErrors(errors, requiredOrdereds, state, options); - } - } - -}; - - -module.exports = new internals.Array(); - - -/***/ }), - -/***/ 2608: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const Hoek = __nccwpck_require__(10904); - -const Any = __nccwpck_require__(77641); - - -const internals = {}; - - -internals.Binary = class extends Any { - - constructor() { - - super(); - this._type = 'binary'; - } - - _base(value, state, options) { - - const result = { - value - }; - - if (typeof value === 'string' && - options.convert) { - - try { - result.value = Buffer.from(value, this._flags.encoding); - } - catch (e) { } - } - - result.errors = Buffer.isBuffer(result.value) ? null : this.createError('binary.base', null, state, options); - return result; - } - - encoding(encoding) { - - Hoek.assert(Buffer.isEncoding(encoding), 'Invalid encoding:', encoding); - - if (this._flags.encoding === encoding) { - return this; - } - - const obj = this.clone(); - obj._flags.encoding = encoding; - return obj; - } - - min(limit) { - - Hoek.assert(Number.isSafeInteger(limit) && limit >= 0, 'limit must be a positive integer'); - - return this._test('min', limit, function (value, state, options) { - - if (value.length >= limit) { - return value; - } - - return this.createError('binary.min', { limit, value }, state, options); - }); - } - - max(limit) { - - Hoek.assert(Number.isSafeInteger(limit) && limit >= 0, 'limit must be a positive integer'); - - return this._test('max', limit, function (value, state, options) { - - if (value.length <= limit) { - return value; - } - - return this.createError('binary.max', { limit, value }, state, options); - }); - } - - length(limit) { - - Hoek.assert(Number.isSafeInteger(limit) && limit >= 0, 'limit must be a positive integer'); - - return this._test('length', limit, function (value, state, options) { - - if (value.length === limit) { - return value; - } - - return this.createError('binary.length', { limit, value }, state, options); - }); - } - -}; - - -module.exports = new internals.Binary(); - - -/***/ }), - -/***/ 78578: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const Hoek = __nccwpck_require__(10904); - -const Any = __nccwpck_require__(77641); - - -const internals = { - Set: __nccwpck_require__(39417) -}; - - -internals.Boolean = class extends Any { - constructor() { - - super(); - this._type = 'boolean'; - this._flags.insensitive = true; - this._inner.truthySet = new internals.Set(); - this._inner.falsySet = new internals.Set(); - } - - _base(value, state, options) { - - const result = { - value - }; - - if (typeof value === 'string' && - options.convert) { - - const normalized = this._flags.insensitive ? value.toLowerCase() : value; - result.value = (normalized === 'true' ? true - : (normalized === 'false' ? false : value)); - } - - if (typeof result.value !== 'boolean') { - result.value = (this._inner.truthySet.has(value, null, null, this._flags.insensitive) ? true - : (this._inner.falsySet.has(value, null, null, this._flags.insensitive) ? false : value)); - } - - result.errors = (typeof result.value === 'boolean') ? null : this.createError('boolean.base', { value }, state, options); - return result; - } - - truthy(...values) { - - const obj = this.clone(); - values = Hoek.flatten(values); - for (let i = 0; i < values.length; ++i) { - const value = values[i]; - - Hoek.assert(value !== undefined, 'Cannot call truthy with undefined'); - obj._inner.truthySet.add(value); - } - - return obj; - } - - falsy(...values) { - - const obj = this.clone(); - values = Hoek.flatten(values); - for (let i = 0; i < values.length; ++i) { - const value = values[i]; - - Hoek.assert(value !== undefined, 'Cannot call falsy with undefined'); - obj._inner.falsySet.add(value); - } - - return obj; - } - - insensitive(enabled) { - - const insensitive = enabled === undefined ? true : !!enabled; - - if (this._flags.insensitive === insensitive) { - return this; - } - - const obj = this.clone(); - obj._flags.insensitive = insensitive; - return obj; - } - - describe() { - - const description = super.describe(); - description.truthy = [true, ...this._inner.truthySet.values()]; - description.falsy = [false, ...this._inner.falsySet.values()]; - return description; - } -}; - - -module.exports = new internals.Boolean(); - - -/***/ }), - -/***/ 46254: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const Hoek = __nccwpck_require__(10904); - -const Any = __nccwpck_require__(77641); -const Ref = __nccwpck_require__(71802); - - -const internals = {}; - -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)?)?)?)?$/; -internals.invalidDate = new Date(''); -internals.isIsoDate = (() => { - - const isoString = internals.isoDate.toString(); - - return (date) => { - - return date && (date.toString() === isoString); - }; -})(); - -internals.Date = class extends Any { - - constructor() { - - super(); - this._type = 'date'; - } - - _base(value, state, options) { - - const result = { - value: (options.convert && internals.Date.toDate(value, this._flags.format, this._flags.timestamp, this._flags.multiplier)) || value - }; - - if (result.value instanceof Date && !isNaN(result.value.getTime())) { - result.errors = null; - } - else if (!options.convert) { - result.errors = this.createError('date.strict', { value }, state, options); - } - else { - let type; - if (internals.isIsoDate(this._flags.format)) { - type = 'isoDate'; - } - else if (this._flags.timestamp) { - type = `timestamp.${this._flags.timestamp}`; - } - else { - type = 'base'; - } - - result.errors = this.createError(`date.${type}`, { value }, state, options); - } - - return result; - } - - static toDate(value, format, timestamp, multiplier) { - - if (value instanceof Date) { - return value; - } - - if (typeof value === 'string' || - (typeof value === 'number' && !isNaN(value) && isFinite(value))) { - - const isIsoDate = format && internals.isIsoDate(format); - if (!isIsoDate && - typeof value === 'string' && - /^[+-]?\d+(\.\d+)?$/.test(value)) { - - value = parseFloat(value); - } - - let date; - if (isIsoDate) { - date = format.test(value) ? new Date(value.toString()) : internals.invalidDate; - } - else if (timestamp) { - date = /^\s*$/.test(value) ? internals.invalidDate : new Date(value * multiplier); - } - else { - date = new Date(value); - } - - if (!isNaN(date.getTime())) { - return date; - } - } - - return null; - } - - iso() { - - if (this._flags.format === internals.isoDate) { - return this; - } - - const obj = this.clone(); - obj._flags.format = internals.isoDate; - return obj; - } - - timestamp(type = 'javascript') { - - const allowed = ['javascript', 'unix']; - Hoek.assert(allowed.includes(type), '"type" must be one of "' + allowed.join('", "') + '"'); - - if (this._flags.timestamp === type) { - return this; - } - - const obj = this.clone(); - obj._flags.timestamp = type; - obj._flags.multiplier = type === 'unix' ? 1000 : 1; - return obj; - } - - _isIsoDate(value) { - - return internals.isoDate.test(value); - } - -}; - -internals.compare = function (type, compare) { - - return function (date) { - - const isNow = date === 'now'; - const isRef = Ref.isRef(date); - - if (!isNow && !isRef) { - date = internals.Date.toDate(date); - } - - Hoek.assert(date, 'Invalid date format'); - - return this._test(type, date, function (value, state, options) { - - let compareTo; - if (isNow) { - compareTo = Date.now(); - } - else if (isRef) { - const refValue = date(state.reference || state.parent, options); - compareTo = internals.Date.toDate(refValue); - - if (!compareTo) { - return this.createError('date.ref', { ref: date, value: refValue }, state, options); - } - - compareTo = compareTo.getTime(); - } - else { - compareTo = date.getTime(); - } - - if (compare(value.getTime(), compareTo)) { - return value; - } - - return this.createError('date.' + type, { limit: new Date(compareTo), value }, state, options); - }); - }; -}; - - -internals.Date.prototype.min = internals.compare('min', (value, date) => value >= date); -internals.Date.prototype.max = internals.compare('max', (value, date) => value <= date); -internals.Date.prototype.greater = internals.compare('greater', (value, date) => value > date); -internals.Date.prototype.less = internals.compare('less', (value, date) => value < date); - - -module.exports = new internals.Date(); - - -/***/ }), - -/***/ 28710: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const Hoek = __nccwpck_require__(10904); - -const ObjectType = __nccwpck_require__(38395); -const Ref = __nccwpck_require__(71802); - - -const internals = {}; - - -internals.Func = class extends ObjectType.constructor { - - constructor() { - - super(); - this._flags.func = true; - } - - arity(n) { - - Hoek.assert(Number.isSafeInteger(n) && n >= 0, 'n must be a positive integer'); - - return this._test('arity', n, function (value, state, options) { - - if (value.length === n) { - return value; - } - - return this.createError('function.arity', { n }, state, options); - }); - } - - minArity(n) { - - Hoek.assert(Number.isSafeInteger(n) && n > 0, 'n must be a strict positive integer'); - - return this._test('minArity', n, function (value, state, options) { - - if (value.length >= n) { - return value; - } - - return this.createError('function.minArity', { n }, state, options); - }); - } - - maxArity(n) { - - Hoek.assert(Number.isSafeInteger(n) && n >= 0, 'n must be a positive integer'); - - return this._test('maxArity', n, function (value, state, options) { - - if (value.length <= n) { - return value; - } - - return this.createError('function.maxArity', { n }, state, options); - }); - } - - ref() { - - return this._test('ref', null, function (value, state, options) { - - if (Ref.isRef(value)) { - return value; - } - - return this.createError('function.ref', { value }, state, options); - }); - } - - class() { - - return this._test('class', null, function (value, state, options) { - - if ((/^\s*class\s/).test(value.toString())) { - return value; - } - - return this.createError('function.class', { value }, state, options); - }); - } -}; - -module.exports = new internals.Func(); - - -/***/ }), - -/***/ 92187: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const Hoek = __nccwpck_require__(10904); - -const Any = __nccwpck_require__(77641); - - -const internals = {}; - - -internals.Lazy = class extends Any { - - constructor() { - - super(); - this._type = 'lazy'; - this._flags.once = true; - this._cache = null; - } - - _init(fn, options) { - - return this.set(fn, options); - } - - _base(value, state, options) { - - let schema; - if (this._cache) { - schema = this._cache; - } - else { - const result = { value }; - const lazy = this._flags.lazy; - - if (!lazy) { - result.errors = this.createError('lazy.base', null, state, options); - return result; - } - - schema = lazy(); - - if (!(schema instanceof Any)) { - result.errors = this.createError('lazy.schema', { schema }, state, options); - return result; - } - - if (this._flags.once) { - this._cache = schema; - } - } - - return schema._validate(value, state, options); - } - - set(fn, options) { - - Hoek.assert(typeof fn === 'function', 'You must provide a function as first argument'); - Hoek.assert(options === undefined || (options && typeof options === 'object' && !Array.isArray(options)), `Options must be an object`); - - if (options) { - const unknownOptions = Object.keys(options).filter((key) => !['once'].includes(key)); - Hoek.assert(unknownOptions.length === 0, `Options contain unknown keys: ${unknownOptions}`); - Hoek.assert(options.once === undefined || typeof options.once === 'boolean', 'Option "once" must be a boolean'); - } - - const obj = this.clone(); - obj._flags.lazy = fn; - - if (options && options.once !== obj._flags.once) { - obj._flags.once = options.once; - } - - return obj; - } - -}; - -module.exports = new internals.Lazy(); - - -/***/ }), - -/***/ 18668: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const Hoek = __nccwpck_require__(10904); - -const Any = __nccwpck_require__(77641); -const Ref = __nccwpck_require__(71802); - - -const internals = { - precisionRx: /(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/, - normalizeExponent(str) { - - return str - .replace(/\.?0+e/, 'e') - .replace(/e\+/, 'e') - .replace(/^\+/, '') - .replace(/^(-?)0+([1-9])/, '$1$2'); - }, - normalizeDecimal(str) { - - str = str - .replace(/^\+/, '') - .replace(/\.0+$/, '') - .replace(/^(-?)0+([1-9])/, '$1$2'); - - if (str.includes('.') && str.endsWith('0')) { - str = str.replace(/0+$/, ''); - } - - return str; - } -}; - - -internals.Number = class extends Any { - - constructor() { - - super(); - this._type = 'number'; - this._flags.unsafe = false; - this._invalids.add(Infinity); - this._invalids.add(-Infinity); - } - - _base(value, state, options) { - - const result = { - errors: null, - value - }; - - if (typeof value === 'string' && - options.convert) { - - const matches = value.match(/^\s*[+-]?\d+(?:\.\d+)?(?:e([+-]?\d+))?\s*$/i); - if (matches) { - - value = value.trim(); - result.value = parseFloat(value); - - if (!this._flags.unsafe) { - if (value.includes('e')) { - if (internals.normalizeExponent(`${result.value / Math.pow(10, matches[1])}e${matches[1]}`) !== internals.normalizeExponent(value)) { - result.errors = this.createError('number.unsafe', { value }, state, options); - return result; - } - } - else { - if (result.value.toString() !== internals.normalizeDecimal(value)) { - result.errors = this.createError('number.unsafe', { value }, state, options); - return result; - } - } - } - } - } - - const isNumber = typeof result.value === 'number' && !isNaN(result.value); - - if (options.convert && 'precision' in this._flags && isNumber) { - - // This is conceptually equivalent to using toFixed but it should be much faster - const precision = Math.pow(10, this._flags.precision); - result.value = Math.round(result.value * precision) / precision; - } - - if (isNumber) { - if (!this._flags.unsafe && - (value > Number.MAX_SAFE_INTEGER || value < Number.MIN_SAFE_INTEGER)) { - result.errors = this.createError('number.unsafe', { value }, state, options); - } - } - else { - result.errors = this.createError('number.base', { value }, state, options); - } - - return result; - } - - multiple(base) { - - const isRef = Ref.isRef(base); - - if (!isRef) { - Hoek.assert(typeof base === 'number' && isFinite(base), 'multiple must be a number'); - Hoek.assert(base > 0, 'multiple must be greater than 0'); - } - - return this._test('multiple', base, function (value, state, options) { - - const divisor = isRef ? base(state.reference || state.parent, options) : base; - - if (isRef && (typeof divisor !== 'number' || !isFinite(divisor))) { - return this.createError('number.ref', { ref: base.key }, state, options); - } - - if (value % divisor === 0) { - return value; - } - - return this.createError('number.multiple', { multiple: base, value }, state, options); - }); - } - - integer() { - - return this._test('integer', undefined, function (value, state, options) { - - return Math.trunc(value) - value === 0 ? value : this.createError('number.integer', { value }, state, options); - }); - } - - unsafe(enabled = true) { - - Hoek.assert(typeof enabled === 'boolean', 'enabled must be a boolean'); - - if (this._flags.unsafe === enabled) { - return this; - } - - const obj = this.clone(); - obj._flags.unsafe = enabled; - return obj; - } - - negative() { - - return this._test('negative', undefined, function (value, state, options) { - - if (value < 0) { - return value; - } - - return this.createError('number.negative', { value }, state, options); - }); - } - - positive() { - - return this._test('positive', undefined, function (value, state, options) { - - if (value > 0) { - return value; - } - - return this.createError('number.positive', { value }, state, options); - }); - } - - precision(limit) { - - Hoek.assert(Number.isSafeInteger(limit), 'limit must be an integer'); - Hoek.assert(!('precision' in this._flags), 'precision already set'); - - const obj = this._test('precision', limit, function (value, state, options) { - - 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; - } - - return this.createError('number.precision', { limit, value }, state, options); - }); - - obj._flags.precision = limit; - return obj; - } - - port() { - - return this._test('port', undefined, function (value, state, options) { - - if (!Number.isSafeInteger(value) || value < 0 || value > 65535) { - return this.createError('number.port', { value }, state, options); - } - - return value; - }); - } - -}; - - -internals.compare = function (type, compare) { - - return function (limit) { - - const isRef = Ref.isRef(limit); - const isNumber = typeof limit === 'number' && !isNaN(limit); - - Hoek.assert(isNumber || isRef, 'limit must be a number or reference'); - - return this._test(type, limit, function (value, state, options) { - - let compareTo; - if (isRef) { - compareTo = limit(state.reference || state.parent, options); - - if (!(typeof compareTo === 'number' && !isNaN(compareTo))) { - return this.createError('number.ref', { ref: limit.key }, state, options); - } - } - else { - compareTo = limit; - } - - if (compare(value, compareTo)) { - return value; - } - - return this.createError('number.' + type, { limit: compareTo, value }, state, options); - }); - }; -}; - - -internals.Number.prototype.min = internals.compare('min', (value, limit) => value >= limit); -internals.Number.prototype.max = internals.compare('max', (value, limit) => value <= limit); -internals.Number.prototype.greater = internals.compare('greater', (value, limit) => value > limit); -internals.Number.prototype.less = internals.compare('less', (value, limit) => value < limit); - - -module.exports = new internals.Number(); - - -/***/ }), - -/***/ 38395: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const Bourne = __nccwpck_require__(97174); -const Hoek = __nccwpck_require__(10904); -const Topo = __nccwpck_require__(88392); - -const Any = __nccwpck_require__(77641); -const Errors = __nccwpck_require__(32150); -const Cast = __nccwpck_require__(16415); -const State = __nccwpck_require__(13538); - - -const internals = {}; - - -internals.Object = class extends Any { - - constructor() { - - super(); - this._type = 'object'; - this._inner.children = null; - this._inner.renames = []; - this._inner.dependencies = []; - this._inner.patterns = []; - } - - _init(...args) { - - return args.length ? this.keys(...args) : this; - } - - _base(value, state, options) { - - let target = value; - const errors = []; - const finish = () => { - - return { - value: target, - errors: errors.length ? errors : null - }; - }; - - if (typeof value === 'string' && - options.convert) { - - if (value.length > 1 && - (value[0] === '{' || /^\s*\{/.test(value))) { - - try { - value = Bourne.parse(value); - } - catch (e) { } - } - } - - const type = this._flags.func ? 'function' : 'object'; - if (!value || - typeof value !== type || - Array.isArray(value)) { - - errors.push(this.createError(type + '.base', { value }, state, options)); - return finish(); - } - - // Skip if there are no other rules to test - - if (!this._inner.renames.length && - !this._inner.dependencies.length && - !this._inner.children && // null allows any keys - !this._inner.patterns.length) { - - target = value; - return finish(); - } - - // Ensure target is a local copy (parsed) or shallow copy - - if (target === value) { - if (type === 'object') { - target = Object.create(Object.getPrototypeOf(value)); - } - else { - target = function (...args) { - - return value.apply(this, args); - }; - - target.prototype = Hoek.clone(value.prototype); - } - - const valueKeys = Object.keys(value); - for (let i = 0; i < valueKeys.length; ++i) { - target[valueKeys[i]] = value[valueKeys[i]]; - } - } - else { - target = value; - } - - // Rename keys - - const renamed = {}; - for (let i = 0; i < this._inner.renames.length; ++i) { - const rename = this._inner.renames[i]; - - if (rename.isRegExp) { - const targetKeys = Object.keys(target); - const matchedTargetKeys = []; - - for (let j = 0; j < targetKeys.length; ++j) { - if (rename.from.test(targetKeys[j])) { - matchedTargetKeys.push(targetKeys[j]); - } - } - - const allUndefined = matchedTargetKeys.every((key) => target[key] === undefined); - if (rename.options.ignoreUndefined && allUndefined) { - continue; - } - - if (!rename.options.multiple && - renamed[rename.to]) { - - errors.push(this.createError('object.rename.regex.multiple', { from: matchedTargetKeys, to: rename.to }, state, options)); - if (options.abortEarly) { - return finish(); - } - } - - if (Object.prototype.hasOwnProperty.call(target, rename.to) && - !rename.options.override && - !renamed[rename.to]) { - - errors.push(this.createError('object.rename.regex.override', { from: matchedTargetKeys, to: rename.to }, state, options)); - if (options.abortEarly) { - return finish(); - } - } - - if (allUndefined) { - delete target[rename.to]; - } - else { - target[rename.to] = target[matchedTargetKeys[matchedTargetKeys.length - 1]]; - } - - renamed[rename.to] = true; - - if (!rename.options.alias) { - for (let j = 0; j < matchedTargetKeys.length; ++j) { - delete target[matchedTargetKeys[j]]; - } - } - } - else { - if (rename.options.ignoreUndefined && target[rename.from] === undefined) { - continue; - } - - if (!rename.options.multiple && - renamed[rename.to]) { - - errors.push(this.createError('object.rename.multiple', { from: rename.from, to: rename.to }, state, options)); - if (options.abortEarly) { - return finish(); - } - } - - if (Object.prototype.hasOwnProperty.call(target, rename.to) && - !rename.options.override && - !renamed[rename.to]) { - - errors.push(this.createError('object.rename.override', { from: rename.from, to: rename.to }, state, options)); - if (options.abortEarly) { - return finish(); - } - } - - if (target[rename.from] === undefined) { - delete target[rename.to]; - } - else { - target[rename.to] = target[rename.from]; - } - - renamed[rename.to] = true; - - if (!rename.options.alias) { - delete target[rename.from]; - } - } - } - - // Validate schema - - if (!this._inner.children && // null allows any keys - !this._inner.patterns.length && - !this._inner.dependencies.length) { - - return finish(); - } - - const unprocessed = new Set(Object.keys(target)); - - if (this._inner.children) { - const stripProps = []; - - for (let i = 0; i < this._inner.children.length; ++i) { - const child = this._inner.children[i]; - const key = child.key; - const item = target[key]; - - unprocessed.delete(key); - - const localState = new State(key, [...state.path, key], target, state.reference); - const result = child.schema._validate(item, localState, options); - if (result.errors) { - errors.push(this.createError('object.child', { key, child: child.schema._getLabel(key), reason: result.errors }, localState, options)); - - if (options.abortEarly) { - return finish(); - } - } - else { - if (child.schema._flags.strip || (result.value === undefined && result.value !== item)) { - stripProps.push(key); - target[key] = result.finalValue; - } - else if (result.value !== undefined) { - target[key] = result.value; - } - } - } - - for (let i = 0; i < stripProps.length; ++i) { - delete target[stripProps[i]]; - } - } - - // Unknown keys - - if (unprocessed.size && this._inner.patterns.length) { - - for (const key of unprocessed) { - const localState = new State(key, [...state.path, key], target, state.reference); - const item = target[key]; - - for (let i = 0; i < this._inner.patterns.length; ++i) { - const pattern = this._inner.patterns[i]; - - if (pattern.regex ? - pattern.regex.test(key) : - !pattern.schema._validate(key, state, { ...options, abortEarly:true }).errors) { - - unprocessed.delete(key); - - const result = pattern.rule._validate(item, localState, options); - if (result.errors) { - errors.push(this.createError('object.child', { - key, - child: pattern.rule._getLabel(key), - reason: result.errors - }, localState, options)); - - if (options.abortEarly) { - return finish(); - } - } - - target[key] = result.value; - } - } - } - } - - if (unprocessed.size && (this._inner.children || this._inner.patterns.length)) { - if ((options.stripUnknown && this._flags.allowUnknown !== true) || - options.skipFunctions) { - - const stripUnknown = options.stripUnknown - ? (options.stripUnknown === true ? true : !!options.stripUnknown.objects) - : false; - - - for (const key of unprocessed) { - if (stripUnknown) { - delete target[key]; - unprocessed.delete(key); - } - else if (typeof target[key] === 'function') { - unprocessed.delete(key); - } - } - } - - if ((this._flags.allowUnknown !== undefined ? !this._flags.allowUnknown : !options.allowUnknown)) { - - for (const unprocessedKey of unprocessed) { - errors.push(this.createError('object.allowUnknown', { child: unprocessedKey, value: target[unprocessedKey] }, { - key: unprocessedKey, - path: [...state.path, unprocessedKey] - }, options, {})); - } - } - } - - // Validate dependencies - - for (let i = 0; i < this._inner.dependencies.length; ++i) { - const dep = this._inner.dependencies[i]; - const hasKey = dep.key !== null; - const splitKey = hasKey && dep.key.split('.'); - const localState = hasKey ? new State(splitKey[splitKey.length - 1], [...state.path, ...splitKey]) : new State(null, state.path); - const err = internals[dep.type].call(this, dep.key, hasKey && Hoek.reach(target, dep.key, { functions: true }), dep.peers, target, localState, options); - if (err instanceof Errors.Err) { - errors.push(err); - if (options.abortEarly) { - return finish(); - } - } - } - - return finish(); - } - - keys(schema) { - - Hoek.assert(schema === null || schema === undefined || typeof schema === 'object', 'Object schema must be a valid object'); - Hoek.assert(!schema || !(schema instanceof Any), 'Object schema cannot be a joi schema'); - - const obj = this.clone(); - - if (!schema) { - obj._inner.children = null; - return obj; - } - - const children = Object.keys(schema); - - if (!children.length) { - obj._inner.children = []; - return obj; - } - - const topo = new Topo(); - if (obj._inner.children) { - for (let i = 0; i < obj._inner.children.length; ++i) { - const child = obj._inner.children[i]; - - // Only add the key if we are not going to replace it later - if (!children.includes(child.key)) { - topo.add(child, { after: child._refs, group: child.key }); - } - } - } - - for (let i = 0; i < children.length; ++i) { - const key = children[i]; - const child = schema[key]; - try { - const cast = Cast.schema(this._currentJoi, child); - topo.add({ key, schema: cast }, { after: cast._refs, group: key }); - } - catch (castErr) { - if (castErr.hasOwnProperty('path')) { - castErr.path = key + '.' + castErr.path; - } - else { - castErr.path = key; - } - - throw castErr; - } - } - - obj._inner.children = topo.nodes; - - return obj; - } - - append(schema) { - // Skip any changes - if (schema === null || schema === undefined || Object.keys(schema).length === 0) { - return this; - } - - return this.keys(schema); - } - - unknown(allow) { - - const value = allow !== false; - - if (this._flags.allowUnknown === value) { - return this; - } - - const obj = this.clone(); - obj._flags.allowUnknown = value; - return obj; - } - - length(limit) { - - Hoek.assert(Number.isSafeInteger(limit) && limit >= 0, 'limit must be a positive integer'); - - return this._test('length', limit, function (value, state, options) { - - if (Object.keys(value).length === limit) { - return value; - } - - return this.createError('object.length', { limit, value }, state, options); - }); - } - - min(limit) { - - Hoek.assert(Number.isSafeInteger(limit) && limit >= 0, 'limit must be a positive integer'); - - return this._test('min', limit, function (value, state, options) { - - if (Object.keys(value).length >= limit) { - return value; - } - - return this.createError('object.min', { limit, value }, state, options); - }); - } - - max(limit) { - - Hoek.assert(Number.isSafeInteger(limit) && limit >= 0, 'limit must be a positive integer'); - - return this._test('max', limit, function (value, state, options) { - - if (Object.keys(value).length <= limit) { - return value; - } - - return this.createError('object.max', { limit, value }, state, options); - }); - } - - pattern(pattern, schema) { - - const isRegExp = pattern instanceof RegExp; - Hoek.assert(isRegExp || pattern instanceof Any, 'pattern must be a regex or schema'); - Hoek.assert(schema !== undefined, 'Invalid rule'); - - if (isRegExp) { - Hoek.assert(!pattern.flags.includes('g') && !pattern.flags.includes('y'), 'pattern should not use global or sticky mode'); - } - - try { - schema = Cast.schema(this._currentJoi, schema); - } - catch (castErr) { - if (castErr.hasOwnProperty('path')) { - castErr.message = `${castErr.message}(${castErr.path})`; - } - - throw castErr; - } - - const obj = this.clone(); - if (isRegExp) { - obj._inner.patterns.push({ regex: pattern, rule: schema }); - } - else { - obj._inner.patterns.push({ schema: pattern, rule: schema }); - } - - return obj; - } - - schema() { - - return this._test('schema', null, function (value, state, options) { - - if (value instanceof Any) { - return value; - } - - return this.createError('object.schema', null, state, options); - }); - } - - with(key, peers) { - - Hoek.assert(arguments.length === 2, 'Invalid number of arguments, expected 2.'); - - return this._dependency('with', key, peers); - } - - without(key, peers) { - - Hoek.assert(arguments.length === 2, 'Invalid number of arguments, expected 2.'); - - return this._dependency('without', key, peers); - } - - xor(...peers) { - - peers = Hoek.flatten(peers); - return this._dependency('xor', null, peers); - } - - oxor(...peers) { - - return this._dependency('oxor', null, peers); - } - - or(...peers) { - - peers = Hoek.flatten(peers); - return this._dependency('or', null, peers); - } - - and(...peers) { - - peers = Hoek.flatten(peers); - return this._dependency('and', null, peers); - } - - nand(...peers) { - - peers = Hoek.flatten(peers); - return this._dependency('nand', null, peers); - } - - requiredKeys(...children) { - - children = Hoek.flatten(children); - return this.applyFunctionToChildren(children, 'required'); - } - - optionalKeys(...children) { - - children = Hoek.flatten(children); - return this.applyFunctionToChildren(children, 'optional'); - } - - forbiddenKeys(...children) { - - children = Hoek.flatten(children); - return this.applyFunctionToChildren(children, 'forbidden'); - } - - rename(from, to, options) { - - Hoek.assert(typeof from === 'string' || from instanceof RegExp, 'Rename missing the from argument'); - Hoek.assert(typeof to === 'string', 'Rename missing the to argument'); - Hoek.assert(to !== from, 'Cannot rename key to same name:', from); - - for (let i = 0; i < this._inner.renames.length; ++i) { - Hoek.assert(this._inner.renames[i].from !== from, 'Cannot rename the same key multiple times'); - } - - const obj = this.clone(); - - obj._inner.renames.push({ - from, - to, - options: Hoek.applyToDefaults(internals.renameDefaults, options || {}), - isRegExp: from instanceof RegExp - }); - - return obj; - } - - applyFunctionToChildren(children, fn, args = [], root) { + const { isDeepEqual, valueOf, hasOwnEnumerableProperty } = internals; + const { keys, getOwnPropertySymbols } = Object; - children = [].concat(children); - Hoek.assert(children.length > 0, 'expected at least one children'); + if (instanceType === Types.array) { + if (options.part) { - const groupedChildren = internals.groupChildren(children); - let obj; + // Check if any index match any other index - if ('' in groupedChildren) { - obj = this[fn](...args); - delete groupedChildren['']; + for (const objValue of obj) { + for (const refValue of ref) { + if (isDeepEqual(objValue, refValue, options, seen)) { + return true; + } + } + } } else { - obj = this.clone(); - } - - if (obj._inner.children) { - root = root ? (root + '.') : ''; - - for (let i = 0; i < obj._inner.children.length; ++i) { - const child = obj._inner.children[i]; - const group = groupedChildren[child.key]; - - if (group) { - obj._inner.children[i] = { - key: child.key, - _refs: child._refs, - schema: child.schema.applyFunctionToChildren(group, fn, args, root + child.key) - }; + if (obj.length !== ref.length) { + return false; + } - delete groupedChildren[child.key]; + for (let i = 0; i < obj.length; ++i) { + if (!isDeepEqual(obj[i], ref[i], options, seen)) { + return false; } } - } - - const remaining = Object.keys(groupedChildren); - Hoek.assert(remaining.length === 0, 'unknown key(s)', remaining.join(', ')); - - return obj; - } - _dependency(type, key, peers) { - - peers = [].concat(peers); - for (let i = 0; i < peers.length; ++i) { - Hoek.assert(typeof peers[i] === 'string', type, 'peers must be a string or array of strings'); + return true; } - - const obj = this.clone(); - obj._inner.dependencies.push({ type, key, peers }); - return obj; } - - describe(shallow) { - - const description = super.describe(); - - if (description.rules) { - for (let i = 0; i < description.rules.length; ++i) { - const rule = description.rules[i]; - // Coverage off for future-proof descriptions, only object().assert() is use right now - if (/* $lab:coverage:off$ */rule.arg && - typeof rule.arg === 'object' && - rule.arg.schema && - rule.arg.ref /* $lab:coverage:on$ */) { - rule.arg = { - schema: rule.arg.schema.describe(), - ref: rule.arg.ref.toString() - }; - } - } + else if (instanceType === Types.set) { + if (obj.size !== ref.size) { + return false; } - if (this._inner.children && - !shallow) { - - description.children = {}; - for (let i = 0; i < this._inner.children.length; ++i) { - const child = this._inner.children[i]; - description.children[child.key] = child.schema.describe(); - } - } + if (!internals.isSetSimpleEqual(obj, ref)) { - if (this._inner.dependencies.length) { - description.dependencies = Hoek.clone(this._inner.dependencies); - } + // Check for deep equality - if (this._inner.patterns.length) { - description.patterns = []; + const ref2 = new Set(Set.prototype.values.call(ref)); + for (const objEntry of Set.prototype.values.call(obj)) { + if (ref2.delete(objEntry)) { + continue; + } - for (let i = 0; i < this._inner.patterns.length; ++i) { - const pattern = this._inner.patterns[i]; - if (pattern.regex) { - description.patterns.push({ regex: pattern.regex.toString(), rule: pattern.rule.describe() }); + let found = false; + for (const refEntry of ref2) { + if (isDeepEqual(objEntry, refEntry, options, seen)) { + ref2.delete(refEntry); + found = true; + break; + } } - else { - description.patterns.push({ schema: pattern.schema.describe(), rule: pattern.rule.describe() }); + + if (!found) { + return false; } } } - - if (this._inner.renames.length > 0) { - description.renames = Hoek.clone(this._inner.renames); - } - - return description; } - - assert(ref, schema, message) { - - ref = Cast.ref(ref); - Hoek.assert(ref.isContext || ref.depth > 1, 'Cannot use assertions for root level references - use direct key rules instead'); - message = message || 'pass the assertion test'; - Hoek.assert(typeof message === 'string', 'Message must be a string'); - - try { - schema = Cast.schema(this._currentJoi, schema); - } - catch (castErr) { - if (castErr.hasOwnProperty('path')) { - castErr.message = `${castErr.message}(${castErr.path})`; - } - - throw castErr; + else if (instanceType === Types.map) { + if (obj.size !== ref.size) { + return false; } - const key = ref.path[ref.path.length - 1]; - const path = ref.path.join('.'); - - return this._test('assert', { schema, ref }, function (value, state, options) { - - const result = schema._validate(ref(value), null, options, value); - if (!result.errors) { - return value; + for (const [key, value] of Map.prototype.entries.call(obj)) { + if (value === undefined && !Map.prototype.has.call(ref, key)) { + return false; } - const localState = new State(key, ref.path, state.parent, state.reference); - return this.createError('object.assert', { ref: path, message }, localState, options); - }); - } - - type(constructor, name = constructor.name) { - - Hoek.assert(typeof constructor === 'function', 'type must be a constructor function'); - const typeData = { - name, - ctor: constructor - }; - - return this._test('type', typeData, function (value, state, options) { - - if (value instanceof constructor) { - return value; + if (!isDeepEqual(value, Map.prototype.get.call(ref, key), options, seen)) { + return false; } - - return this.createError('object.type', { type: typeData.name, value }, state, options); - }); - } -}; - - -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 -}; - - -internals.groupChildren = function (children) { - - children.sort(); - - const grouped = {}; - - for (let i = 0; i < children.length; ++i) { - const child = children[i]; - Hoek.assert(typeof child === 'string', 'children must be strings'); - const group = child.split('.')[0]; - const childGroup = grouped[group] = (grouped[group] || []); - childGroup.push(child.substring(group.length + 1)); + } } + else if (instanceType === Types.error) { - return grouped; -}; - - -internals.keysToLabels = function (schema, keys) { + // Always check name and message - const children = schema._inner.children; + if (obj.name !== ref.name || + obj.message !== ref.message) { - if (!children) { - return keys; + return false; + } } - const findLabel = function (key) { + // Check .valueOf() - const matchingChild = schema._currentJoi.reach(schema, key); - return matchingChild ? matchingChild._getLabel(key) : key; - }; + const valueOfObj = valueOf(obj); + const valueOfRef = valueOf(ref); + if ((obj !== valueOfObj || ref !== valueOfRef) && + !isDeepEqual(valueOfObj, valueOfRef, options, seen)) { - if (Array.isArray(keys)) { - return keys.map(findLabel); + return false; } - return findLabel(keys); -}; - + // Check properties -internals.with = function (key, value, peers, parent, state, options) { + const objKeys = keys(obj); + if (!options.part && + objKeys.length !== keys(ref).length && + !options.skip) { - if (value === undefined) { - return; + return false; } - for (let i = 0; i < peers.length; ++i) { + let skipped = 0; + for (const key of objKeys) { + if (options.skip && + options.skip.includes(key)) { - const peer = peers[i]; - const keysExist = Hoek.reach(parent, peer, { functions: true }); - if (keysExist === undefined) { + if (ref[key] === undefined) { + ++skipped; + } - return this.createError('object.with', { - main: key, - mainWithLabel: internals.keysToLabels(this, key), - peer, - peerWithLabel: internals.keysToLabels(this, peer) - }, state, options); + continue; } - } -}; - -internals.without = function (key, value, peers, parent, state, options) { - - if (value === undefined) { - return; - } - - for (let i = 0; i < peers.length; ++i) { - const peer = peers[i]; - const keysExist = Hoek.reach(parent, peer, { functions: true }); - if (keysExist !== undefined) { - - return this.createError('object.without', { - main: key, - mainWithLabel: internals.keysToLabels(this, key), - peer, - peerWithLabel: internals.keysToLabels(this, peer) - }, state, options); + if (!hasOwnEnumerableProperty(ref, key)) { + return false; } - } -}; - -internals.xor = function (key, value, peers, parent, state, options) { - - const present = []; - for (let i = 0; i < peers.length; ++i) { - const peer = peers[i]; - const keysExist = Hoek.reach(parent, peer, { functions: true }); - if (keysExist !== undefined) { - present.push(peer); + if (!isDeepEqual(obj[key], ref[key], options, seen)) { + return false; } } - if (present.length === 1) { - return; - } - - const context = { peers, peersWithLabels: internals.keysToLabels(this, peers) }; - - if (present.length === 0) { - return this.createError('object.missing', context, state, options); - } - - context.present = present; - context.presentWithLabels = internals.keysToLabels(this, present); - - return this.createError('object.xor', context, state, options); -}; - - -internals.oxor = function (key, value, peers, parent, state, options) { + if (!options.part && + objKeys.length - skipped !== keys(ref).length) { - const present = []; - for (let i = 0; i < peers.length; ++i) { - const peer = peers[i]; - const keysExist = Hoek.reach(parent, peer, { functions: true }); - if (keysExist !== undefined) { - present.push(peer); - } + return false; } - if (!present.length || - present.length === 1) { - - return; - } + // Check symbols - const context = { peers, peersWithLabels: internals.keysToLabels(this, peers) }; - context.present = present; - context.presentWithLabels = internals.keysToLabels(this, present); + if (options.symbols !== false) { // Defaults to true + const objSymbols = getOwnPropertySymbols(obj); + const refSymbols = new Set(getOwnPropertySymbols(ref)); - return this.createError('object.oxor', context, state, options); -}; + for (const key of objSymbols) { + if (!options.skip || + !options.skip.includes(key)) { + if (hasOwnEnumerableProperty(obj, key)) { + if (!hasOwnEnumerableProperty(ref, key)) { + return false; + } -internals.or = function (key, value, peers, parent, state, options) { + if (!isDeepEqual(obj[key], ref[key], options, seen)) { + return false; + } + } + else if (hasOwnEnumerableProperty(ref, key)) { + return false; + } + } - for (let i = 0; i < peers.length; ++i) { - const peer = peers[i]; - const keysExist = Hoek.reach(parent, peer, { functions: true }); - if (keysExist !== undefined) { - return; + refSymbols.delete(key); } - } - - return this.createError('object.missing', { - peers, - peersWithLabels: internals.keysToLabels(this, peers) - }, state, options); -}; - - -internals.and = function (key, value, peers, parent, state, options) { - - const missing = []; - const present = []; - const count = peers.length; - for (let i = 0; i < count; ++i) { - const peer = peers[i]; - const keysExist = Hoek.reach(parent, peer, { functions: true }); - if (keysExist === undefined) { - missing.push(peer); - } - else { - present.push(peer); + for (const key of refSymbols) { + if (hasOwnEnumerableProperty(ref, key)) { + return false; + } } } - const aon = (missing.length === count || present.length === count); - - if (!aon) { - - return this.createError('object.and', { - present, - presentWithLabels: internals.keysToLabels(this, present), - missing, - missingWithLabels: internals.keysToLabels(this, missing) - }, state, options); - } + return true; }; -internals.nand = function (key, value, peers, parent, state, options) { +internals.SeenEntry = class { - const present = []; - for (let i = 0; i < peers.length; ++i) { - const peer = peers[i]; - const keysExist = Hoek.reach(parent, peer, { functions: true }); - if (keysExist !== undefined) { + constructor(obj, ref) { - present.push(peer); - } + this.obj = obj; + this.ref = ref; } - const main = peers[0]; - const values = peers.slice(1); - const allPresent = (present.length === peers.length); - return allPresent ? this.createError('object.nand', { - main, - mainWithLabel: internals.keysToLabels(this, main), - peers: values, - peersWithLabels: internals.keysToLabels(this, values) - }, state, options) : null; -}; - - -module.exports = new internals.Object(); - - -/***/ }), - -/***/ 13538: -/***/ ((module) => { - -"use strict"; - - -const internals = {}; - - -module.exports = class { - constructor(key, path, parent, reference) { + isSame(obj, ref) { - this.key = key; - this.path = path; - this.parent = parent; - this.reference = reference; + return this.obj === obj && this.ref === ref; } }; /***/ }), -/***/ 67769: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 35563: +/***/ ((module, exports, __nccwpck_require__) => { "use strict"; -const Net = __nccwpck_require__(41808); - -const Address = __nccwpck_require__(9491); -const Hoek = __nccwpck_require__(10904); - -const Any = __nccwpck_require__(77641); -const Ref = __nccwpck_require__(71802); -const JoiDate = __nccwpck_require__(46254); - -const Uri = __nccwpck_require__(30018); -const Ip = __nccwpck_require__(8751); - - -const internals = { - uriRegex: Uri.createUriRegex(), - ipRegex: Ip.createIpRegex(['ipv4', 'ipv6', 'ipvfuture'], 'optional'), - guidBrackets: { - '{': '}', '[': ']', '(': ')', '': '' - }, - guidVersions: { - uuidv1: '1', - uuidv2: '2', - uuidv3: '3', - uuidv4: '4', - uuidv5: '5' - }, - cidrPresences: ['required', 'optional', 'forbidden'], - normalizationForms: ['NFC', 'NFD', 'NFKC', 'NFKD'] -}; - - -internals.String = class extends Any { - - constructor() { - - super(); - this._type = 'string'; - this._invalids.add(''); - } - - _base(value, state, options) { - - if (typeof value === 'string' && - options.convert) { - - if (this._flags.normalize) { - value = value.normalize(this._flags.normalize); - } - - if (this._flags.case) { - value = (this._flags.case === 'upper' ? value.toLocaleUpperCase() : value.toLocaleLowerCase()); - } - - if (this._flags.trim) { - value = value.trim(); - } - - if (this._inner.replacements) { - - for (let i = 0; i < this._inner.replacements.length; ++i) { - const replacement = this._inner.replacements[i]; - value = value.replace(replacement.pattern, replacement.replacement); - } - } - - if (this._flags.truncate) { - for (let i = 0; i < this._tests.length; ++i) { - const test = this._tests[i]; - if (test.name === 'max') { - value = value.slice(0, test.arg); - break; - } - } - } - - if (this._flags.byteAligned && value.length % 2 !== 0) { - value = `0${value}`; - } - } - - return { - value, - errors: (typeof value === 'string') ? null : this.createError('string.base', { value }, state, options) - }; - } - - insensitive() { - - if (this._flags.insensitive) { - return this; - } - - const obj = this.clone(); - obj._flags.insensitive = true; - return obj; - } - - creditCard() { +const Stringify = __nccwpck_require__(37577); - return this._test('creditCard', undefined, function (value, state, options) { - let i = value.length; - let sum = 0; - let mul = 1; +const internals = {}; - while (i--) { - const char = value.charAt(i) * mul; - sum = sum + (char - (char > 9) * 9); - mul = mul ^ 3; - } - const check = (sum % 10 === 0) && (sum > 0); - return check ? value : this.createError('string.creditCard', { value }, state, options); - }); - } +module.exports = class extends Error { - regex(pattern, patternOptions) { + constructor(args) { - Hoek.assert(pattern instanceof RegExp, 'pattern must be a RegExp'); - Hoek.assert(!pattern.flags.includes('g') && !pattern.flags.includes('y'), 'pattern should not use global or sticky mode'); + const msgs = args + .filter((arg) => arg !== '') + .map((arg) => { - const patternObject = { pattern }; + return typeof arg === 'string' ? arg : arg instanceof Error ? arg.message : Stringify(arg); + }); - if (typeof patternOptions === 'string') { - patternObject.name = patternOptions; - } - else if (typeof patternOptions === 'object') { - patternObject.invert = !!patternOptions.invert; + super(msgs.join(' ') || 'Unknown error'); - if (patternOptions.name) { - patternObject.name = patternOptions.name; - } + if (typeof Error.captureStackTrace === 'function') { // $lab:coverage:ignore$ + Error.captureStackTrace(this, exports.assert); } - - const errorCode = ['string.regex', patternObject.invert ? '.invert' : '', patternObject.name ? '.name' : '.base'].join(''); - - return this._test('regex', patternObject, function (value, state, options) { - - const patternMatch = patternObject.pattern.test(value); - - if (patternMatch ^ patternObject.invert) { - return value; - } - - return this.createError(errorCode, { name: patternObject.name, pattern: patternObject.pattern, value }, state, options); - }); } +}; - alphanum() { - - return this._test('alphanum', undefined, function (value, state, options) { - - if (/^[a-zA-Z0-9]+$/.test(value)) { - return value; - } - - return this.createError('string.alphanum', { value }, state, options); - }); - } - - token() { - - return this._test('token', undefined, function (value, state, options) { - - if (/^\w+$/.test(value)) { - return value; - } - - return this.createError('string.token', { value }, state, options); - }); - } - - email(validationOptions) { - - if (validationOptions) { - Hoek.assert(typeof validationOptions === 'object', 'email options must be an object'); - - // Migration validation for unsupported options - - Hoek.assert(validationOptions.checkDNS === undefined, 'checkDNS option is not supported'); - Hoek.assert(validationOptions.errorLevel === undefined, 'errorLevel option is not supported'); - Hoek.assert(validationOptions.minDomainAtoms === undefined, 'minDomainAtoms option is not supported, use minDomainSegments instead'); - Hoek.assert(validationOptions.tldBlacklist === undefined, 'tldBlacklist option is not supported, use tlds.deny instead'); - Hoek.assert(validationOptions.tldWhitelist === undefined, 'tldWhitelist option is not supported, use tlds.allow instead'); - - // Validate options - - if (validationOptions.tlds && - typeof validationOptions.tlds === 'object') { - - Hoek.assert(validationOptions.tlds.allow === undefined || - validationOptions.tlds.allow === false || - validationOptions.tlds.allow === true || - Array.isArray(validationOptions.tlds.allow) || - validationOptions.tlds.allow instanceof Set, 'tlds.allow must be an array, Set, or boolean'); - - Hoek.assert(validationOptions.tlds.deny === undefined || - Array.isArray(validationOptions.tlds.deny) || - validationOptions.tlds.deny instanceof Set, 'tlds.deny must be an array or Set'); - - const normalizeTable = (table) => { - if (table === undefined || - typeof table === 'boolean' || - table instanceof Set) { +/***/ }), - return table; - } +/***/ 24752: +/***/ ((module) => { - return new Set(table); - }; +"use strict"; - validationOptions = Object.assign({}, validationOptions); // Shallow cloned - validationOptions.tlds = { - allow: normalizeTable(validationOptions.tlds.allow), - deny: normalizeTable(validationOptions.tlds.deny) - }; - } - Hoek.assert(validationOptions.minDomainSegments === undefined || - Number.isSafeInteger(validationOptions.minDomainSegments) && validationOptions.minDomainSegments > 0, 'minDomainSegments must be a positive integer'); - } +const internals = {}; - return this._test('email', validationOptions, function (value, state, options) { - if (Address.email.isValid(value, validationOptions)) { - return value; - } +module.exports = function (input) { - return this.createError('string.email', { value }, state, options); - }); + if (!input) { + return ''; } - ip(ipOptions = {}) { - - let regex = internals.ipRegex; - Hoek.assert(typeof ipOptions === 'object', 'options must be an object'); + let escaped = ''; - if (ipOptions.cidr) { - Hoek.assert(typeof ipOptions.cidr === 'string', 'cidr must be a string'); - ipOptions.cidr = ipOptions.cidr.toLowerCase(); + for (let i = 0; i < input.length; ++i) { - Hoek.assert(Hoek.contain(internals.cidrPresences, ipOptions.cidr), 'cidr must be one of ' + internals.cidrPresences.join(', ')); + const charCode = input.charCodeAt(i); - // If we only received a `cidr` setting, create a regex for it. But we don't need to create one if `cidr` is "optional" since that is the default - if (!ipOptions.version && ipOptions.cidr !== 'optional') { - regex = Ip.createIpRegex(['ipv4', 'ipv6', 'ipvfuture'], ipOptions.cidr); - } + if (internals.isSafe(charCode)) { + escaped += input[i]; } else { - - // Set our default cidr strategy - ipOptions.cidr = 'optional'; - } - - let versions; - if (ipOptions.version) { - if (!Array.isArray(ipOptions.version)) { - ipOptions.version = [ipOptions.version]; - } - - Hoek.assert(ipOptions.version.length >= 1, 'version must have at least 1 version specified'); - - versions = []; - for (let i = 0; i < ipOptions.version.length; ++i) { - let version = ipOptions.version[i]; - Hoek.assert(typeof version === 'string', 'version at position ' + i + ' must be a string'); - version = version.toLowerCase(); - Hoek.assert(Ip.versions[version], 'version at position ' + i + ' must be one of ' + Object.keys(Ip.versions).join(', ')); - versions.push(version); - } - - // Make sure we have a set of versions - versions = Array.from(new Set(versions)); - - regex = Ip.createIpRegex(versions, ipOptions.cidr); + escaped += internals.escapeHtmlChar(charCode); } + } - return this._test('ip', ipOptions, function (value, state, options) { + return escaped; +}; - if (regex.test(value)) { - return value; - } - if (versions) { - return this.createError('string.ipVersion', { value, cidr: ipOptions.cidr, version: versions }, state, options); - } +internals.escapeHtmlChar = function (charCode) { - return this.createError('string.ip', { value, cidr: ipOptions.cidr }, state, options); - }); + const namedEscape = internals.namedHtml[charCode]; + if (typeof namedEscape !== 'undefined') { + return namedEscape; } - uri(uriOptions) { - - let customScheme = ''; - let allowRelative = false; - let relativeOnly = false; - let allowQuerySquareBrackets = false; - let regex = internals.uriRegex; + if (charCode >= 256) { + return '&#' + charCode + ';'; + } - if (uriOptions) { - Hoek.assert(typeof uriOptions === 'object', 'options must be an object'); + const hexValue = charCode.toString(16).padStart(2, '0'); + return `&#x${hexValue};`; +}; - const unknownOptions = Object.keys(uriOptions).filter((key) => !['scheme', 'allowRelative', 'relativeOnly', 'allowQuerySquareBrackets'].includes(key)); - Hoek.assert(unknownOptions.length === 0, `options contain unknown keys: ${unknownOptions}`); - if (uriOptions.scheme) { - Hoek.assert(uriOptions.scheme instanceof RegExp || typeof uriOptions.scheme === 'string' || Array.isArray(uriOptions.scheme), 'scheme must be a RegExp, String, or Array'); +internals.isSafe = function (charCode) { - if (!Array.isArray(uriOptions.scheme)) { - uriOptions.scheme = [uriOptions.scheme]; - } + return (typeof internals.safeCharCodes[charCode] !== 'undefined'); +}; - Hoek.assert(uriOptions.scheme.length >= 1, 'scheme must have at least 1 scheme specified'); - // Flatten the array into a string to be used to match the schemes. - for (let i = 0; i < uriOptions.scheme.length; ++i) { - const scheme = uriOptions.scheme[i]; - Hoek.assert(scheme instanceof RegExp || typeof scheme === 'string', 'scheme at position ' + i + ' must be a RegExp or String'); +internals.namedHtml = { + '38': '&', + '60': '<', + '62': '>', + '34': '"', + '160': ' ', + '162': '¢', + '163': '£', + '164': '¤', + '169': '©', + '174': '®' +}; - // Add OR separators if a value already exists - customScheme = customScheme + (customScheme ? '|' : ''); - // If someone wants to match HTTP or HTTPS for example then we need to support both RegExp and String so we don't escape their pattern unknowingly. - if (scheme instanceof RegExp) { - customScheme = customScheme + scheme.source; - } - else { - Hoek.assert(/[a-zA-Z][a-zA-Z0-9+-\.]*/.test(scheme), 'scheme at position ' + i + ' must be a valid scheme'); - customScheme = customScheme + Hoek.escapeRegex(scheme); - } - } - } +internals.safeCharCodes = (function () { - if (uriOptions.allowRelative) { - allowRelative = true; - } + const safe = {}; - if (uriOptions.relativeOnly) { - relativeOnly = true; - } + for (let i = 32; i < 123; ++i) { - if (uriOptions.allowQuerySquareBrackets) { - allowQuerySquareBrackets = true; - } - } + if ((i >= 97) || // a-z + (i >= 65 && i <= 90) || // A-Z + (i >= 48 && i <= 57) || // 0-9 + i === 32 || // space + i === 46 || // . + i === 44 || // , + i === 45 || // - + i === 58 || // : + i === 95) { // _ - if (customScheme || allowRelative || relativeOnly || allowQuerySquareBrackets) { - regex = Uri.createUriRegex(customScheme, allowRelative, relativeOnly, allowQuerySquareBrackets); + safe[i] = null; } - - return this._test('uri', uriOptions, function (value, state, options) { - - if (regex.test(value)) { - return value; - } - - if (relativeOnly) { - return this.createError('string.uriRelativeOnly', { value }, state, options); - } - - if (customScheme) { - return this.createError('string.uriCustomScheme', { scheme: customScheme, value }, state, options); - } - - return this.createError('string.uri', { value }, state, options); - }); - } - - isoDate() { - - return this._test('isoDate', undefined, function (value, state, options) { - - if (JoiDate._isIsoDate(value)) { - if (!options.convert) { - return value; - } - - const d = new Date(value); - if (!isNaN(d.getTime())) { - return d.toISOString(); - } - } - - return this.createError('string.isoDate', { value }, state, options); - }); } - guid(guidOptions) { - - let versionNumbers = ''; - - if (guidOptions && guidOptions.version) { - if (!Array.isArray(guidOptions.version)) { - guidOptions.version = [guidOptions.version]; - } - - Hoek.assert(guidOptions.version.length >= 1, 'version must have at least 1 valid version specified'); - const versions = new Set(); + return safe; +}()); - for (let i = 0; i < guidOptions.version.length; ++i) { - let version = guidOptions.version[i]; - Hoek.assert(typeof version === 'string', 'version at position ' + i + ' must be a string'); - version = version.toLowerCase(); - const versionNumber = internals.guidVersions[version]; - Hoek.assert(versionNumber, 'version at position ' + i + ' must be one of ' + Object.keys(internals.guidVersions).join(', ')); - Hoek.assert(!(versions.has(versionNumber)), 'version at position ' + i + ' must not be a duplicate.'); - versionNumbers += versionNumber; - versions.add(versionNumber); - } - } +/***/ }), - const guidRegex = new RegExp(`^([\\[{\\(]?)[0-9A-F]{8}([:-]?)[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'); +/***/ 91965: +/***/ ((module) => { - return this._test('guid', guidOptions, function (value, state, options) { +"use strict"; - const results = guidRegex.exec(value); - if (!results) { - return this.createError('string.guid', { value }, state, options); - } +const internals = {}; - // Matching braces - if (internals.guidBrackets[results[1]] !== results[results.length - 1]) { - return this.createError('string.guid', { value }, state, options); - } - return value; - }); - } +module.exports = function (string) { - hex(hexOptions = {}) { + // Escape ^$.*+-?=!:|\/()[]{}, - Hoek.assert(typeof hexOptions === 'object', 'hex options must be an object'); - Hoek.assert(typeof hexOptions.byteAligned === 'undefined' || typeof hexOptions.byteAligned === 'boolean', - 'byteAligned must be boolean'); + return string.replace(/[\^\$\.\*\+\-\?\=\!\:\|\\\/\(\)\[\]\{\}\,]/g, '\\$&'); +}; - const byteAligned = hexOptions.byteAligned === true; - const regex = /^[a-f0-9]+$/i; - const obj = this._test('hex', regex, function (value, state, options) { +/***/ }), - if (regex.test(value)) { - if (byteAligned && value.length % 2 !== 0) { - return this.createError('string.hexAlign', { value }, state, options); - } +/***/ 12887: +/***/ ((module) => { - return value; - } +"use strict"; - return this.createError('string.hex', { value }, state, options); - }); - if (byteAligned) { - obj._flags.byteAligned = true; - } +const internals = {}; - return obj; - } - base64(base64Options = {}) { +module.exports = function () { }; - // Validation. - Hoek.assert(typeof base64Options === 'object', 'base64 options must be an object'); - Hoek.assert(typeof base64Options.paddingRequired === 'undefined' || typeof base64Options.paddingRequired === 'boolean', - 'paddingRequired must be boolean'); - // Determine if padding is required. - const paddingRequired = base64Options.paddingRequired === false ? - base64Options.paddingRequired - : base64Options.paddingRequired || true; +/***/ }), - // Set validation based on preference. - const regex = paddingRequired ? - // Padding is required. - /^(?:[A-Za-z0-9+\/]{2}[A-Za-z0-9+\/]{2})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/ - // Padding is optional. - : /^(?:[A-Za-z0-9+\/]{2}[A-Za-z0-9+\/]{2})*(?:[A-Za-z0-9+\/]{2}(==)?|[A-Za-z0-9+\/]{3}=?)?$/; +/***/ 60445: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return this._test('base64', regex, function (value, state, options) { +"use strict"; - if (regex.test(value)) { - return value; - } - return this.createError('string.base64', { value }, state, options); - }); - } +const Assert = __nccwpck_require__(32718); +const Clone = __nccwpck_require__(85578); +const Utils = __nccwpck_require__(30417); - dataUri(dataUriOptions = {}) { - const regex = /^data:[\w+.-]+\/[\w+.-]+;((charset=[\w-]+|base64),)?(.*)$/; +const internals = {}; - // Determine if padding is required. - const paddingRequired = dataUriOptions.paddingRequired === false ? - dataUriOptions.paddingRequired - : dataUriOptions.paddingRequired || true; - const base64regex = paddingRequired ? - /^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/ - : /^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}(==)?|[A-Za-z0-9+\/]{3}=?)?$/; +module.exports = internals.merge = function (target, source, options) { - return this._test('dataUri', regex, function (value, state, options) { + Assert(target && typeof target === 'object', 'Invalid target value: must be an object'); + Assert(source === null || source === undefined || typeof source === 'object', 'Invalid source value: must be null, undefined, or an object'); - const matches = value.match(regex); + if (!source) { + return target; + } - if (matches) { - if (!matches[2]) { - return value; - } + options = Object.assign({ nullOverride: true, mergeArrays: true }, options); - if (matches[2] !== 'base64') { - return value; - } + if (Array.isArray(source)) { + Assert(Array.isArray(target), 'Cannot merge array onto an object'); + if (!options.mergeArrays) { + target.length = 0; // Must not change target assignment + } - if (base64regex.test(matches[3])) { - return value; - } - } + for (let i = 0; i < source.length; ++i) { + target.push(Clone(source[i], { symbols: options.symbols })); + } - return this.createError('string.dataUri', { value }, state, options); - }); + return target; } - hostname() { + const keys = Utils.keys(source, options); + for (let i = 0; i < keys.length; ++i) { + const key = keys[i]; + if (key === '__proto__' || + !Object.prototype.propertyIsEnumerable.call(source, key)) { - const regex = /^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$/; + continue; + } - return this._test('hostname', undefined, function (value, state, options) { + const value = source[key]; + if (value && + typeof value === 'object') { - if ((value.length <= 255 && regex.test(value)) || - Net.isIPv6(value)) { + if (target[key] === value) { + continue; // Can occur for shallow merges + } - return value; + if (!target[key] || + typeof target[key] !== 'object' || + (Array.isArray(target[key]) !== Array.isArray(value)) || + value instanceof Date || + (Buffer && Buffer.isBuffer(value)) || // $lab:coverage:ignore$ + value instanceof RegExp) { + + target[key] = Clone(value, { symbols: options.symbols }); + } + else { + internals.merge(target[key], value, options); } + } + else { + if (value !== null && + value !== undefined) { // Explicit to preserve empty strings - return this.createError('string.hostname', { value }, state, options); - }); + target[key] = value; + } + else if (options.nullOverride) { + target[key] = value; + } + } } - normalize(form = 'NFC') { + return target; +}; - Hoek.assert(Hoek.contain(internals.normalizationForms, form), 'normalization form must be one of ' + internals.normalizationForms.join(', ')); - const obj = this._test('normalize', form, function (value, state, options) { +/***/ }), - if (options.convert || - value === value.normalize(form)) { +/***/ 18891: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return value; - } +"use strict"; - return this.createError('string.normalize', { value, form }, state, options); - }); - obj._flags.normalize = form; - return obj; - } +const Assert = __nccwpck_require__(32718); - lowercase() { - const obj = this._test('lowercase', undefined, function (value, state, options) { +const internals = {}; - if (options.convert || - value === value.toLocaleLowerCase()) { - return value; - } +module.exports = function (obj, chain, options) { - return this.createError('string.lowercase', { value }, state, options); - }); + if (chain === false || + chain === null || + chain === undefined) { - obj._flags.case = 'lower'; return obj; } - uppercase() { + options = options || {}; + if (typeof options === 'string') { + options = { separator: options }; + } - const obj = this._test('uppercase', undefined, function (value, state, options) { + const isChainArray = Array.isArray(chain); - if (options.convert || - value === value.toLocaleUpperCase()) { + Assert(!isChainArray || !options.separator, 'Separator option no valid for array-based chain'); - return value; - } + const path = isChainArray ? chain : chain.split(options.separator || '.'); + let ref = obj; + for (let i = 0; i < path.length; ++i) { + let key = path[i]; + const type = options.iterables && internals.iterables(ref); - return this.createError('string.uppercase', { value }, state, options); - }); + if (Array.isArray(ref) || + type === 'set') { - obj._flags.case = 'upper'; - return obj; - } + const number = Number(key); + if (Number.isInteger(number)) { + key = number < 0 ? ref.length + number : number; + } + } - trim(enabled = true) { + if (!ref || + typeof ref === 'function' && options.functions === false || // Defaults to true + !type && ref[key] === undefined) { - Hoek.assert(typeof enabled === 'boolean', 'option must be a boolean'); + Assert(!options.strict || i + 1 === path.length, 'Missing segment', key, 'in reach path ', chain); + Assert(typeof ref === 'object' || options.functions === true || typeof ref !== 'function', 'Invalid segment', key, 'in reach path ', chain); + ref = options.default; + break; + } - if ((this._flags.trim && enabled) || (!this._flags.trim && !enabled)) { - return this; + if (!type) { + ref = ref[key]; + } + else if (type === 'set') { + ref = [...ref][key]; + } + else { // type === 'map' + ref = ref.get(key); } + } - let obj; - if (enabled) { - obj = this._test('trim', undefined, function (value, state, options) { + return ref; +}; - if (options.convert || - value === value.trim()) { - return value; - } +internals.iterables = function (ref) { - return this.createError('string.trim', { value }, state, options); - }); - } - else { - obj = this.clone(); - obj._tests = obj._tests.filter((test) => test.name !== 'trim'); - } + if (ref instanceof Set) { + return 'set'; + } - obj._flags.trim = enabled; - return obj; + if (ref instanceof Map) { + return 'map'; } +}; - replace(pattern, replacement) { - if (typeof pattern === 'string') { - pattern = new RegExp(Hoek.escapeRegex(pattern), 'g'); - } +/***/ }), - Hoek.assert(pattern instanceof RegExp, 'pattern must be a RegExp'); - Hoek.assert(typeof replacement === 'string', 'replacement must be a String'); +/***/ 37577: +/***/ ((module) => { - // This can not be considere a test like trim, we can't "reject" - // anything from this rule, so just clone the current object - const obj = this.clone(); +"use strict"; - if (!obj._inner.replacements) { - obj._inner.replacements = []; - } - obj._inner.replacements.push({ - pattern, - replacement - }); +const internals = {}; - return obj; + +module.exports = function (...args) { + + try { + return JSON.stringify.apply(null, args); + } + catch (err) { + return '[Cannot display object: ' + err.message + ']'; } +}; - truncate(enabled) { - const value = enabled === undefined ? true : !!enabled; +/***/ }), - if (this._flags.truncate === value) { - return this; - } +/***/ 84340: +/***/ ((module, exports) => { - const obj = this.clone(); - obj._flags.truncate = value; - return obj; - } +"use strict"; -}; -internals.compare = function (type, compare) { +const internals = {}; + - return function (limit, encoding) { +exports = module.exports = { + array: Array.prototype, + buffer: Buffer && Buffer.prototype, // $lab:coverage:ignore$ + date: Date.prototype, + error: Error.prototype, + generic: Object.prototype, + map: Map.prototype, + promise: Promise.prototype, + regex: RegExp.prototype, + set: Set.prototype, + weakMap: WeakMap.prototype, + weakSet: WeakSet.prototype +}; - const isRef = Ref.isRef(limit); - Hoek.assert((Number.isSafeInteger(limit) && limit >= 0) || isRef, 'limit must be a positive integer or reference'); - Hoek.assert(!encoding || Buffer.isEncoding(encoding), 'Invalid encoding:', encoding); +internals.typeMap = new Map([ + ['[object Error]', exports.error], + ['[object Map]', exports.map], + ['[object Promise]', exports.promise], + ['[object Set]', exports.set], + ['[object WeakMap]', exports.weakMap], + ['[object WeakSet]', exports.weakSet] +]); - return this._test(type, limit, function (value, state, options) { - let compareTo; - if (isRef) { - compareTo = limit(state.reference || state.parent, options); +exports.getInternalProto = function (obj) { - if (!Number.isSafeInteger(compareTo)) { - return this.createError('string.ref', { ref: limit, value: compareTo }, state, options); - } - } - else { - compareTo = limit; - } + if (Array.isArray(obj)) { + return exports.array; + } - if (compare(value, compareTo, encoding)) { - return value; - } + if (Buffer && obj instanceof Buffer) { // $lab:coverage:ignore$ + return exports.buffer; + } - return this.createError('string.' + type, { limit: compareTo, value, encoding }, state, options); - }); - }; -}; + if (obj instanceof Date) { + return exports.date; + } + if (obj instanceof RegExp) { + return exports.regex; + } -internals.String.prototype.min = internals.compare('min', (value, limit, encoding) => { + if (obj instanceof Error) { + return exports.error; + } - const length = encoding ? Buffer.byteLength(value, encoding) : value.length; - return length >= limit; -}); + const objName = Object.prototype.toString.call(obj); + return internals.typeMap.get(objName) || exports.generic; +}; -internals.String.prototype.max = internals.compare('max', (value, limit, encoding) => { +/***/ }), - const length = encoding ? Buffer.byteLength(value, encoding) : value.length; - return length <= limit; -}); +/***/ 30417: +/***/ ((__unused_webpack_module, exports) => { +"use strict"; -internals.String.prototype.length = internals.compare('length', (value, limit, encoding) => { - const length = encoding ? Buffer.byteLength(value, encoding) : value.length; - return length === limit; -}); +const internals = {}; -// Aliases -internals.String.prototype.uuid = internals.String.prototype.guid; +exports.keys = function (obj, options = {}) { -module.exports = new internals.String(); + return options.symbols !== false ? Reflect.ownKeys(obj) : Object.getOwnPropertyNames(obj); // Defaults to true +}; /***/ }), -/***/ 8751: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 88392: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -const RFC3986 = __nccwpck_require__(49954); +const Assert = __nccwpck_require__(32718); -const internals = { - Ip: { - cidrs: { - ipv4: { - required: '\\/(?:' + RFC3986.ipv4Cidr + ')', - optional: '(?:\\/(?:' + RFC3986.ipv4Cidr + '))?', - forbidden: '' - }, - ipv6: { - required: '\\/' + RFC3986.ipv6Cidr, - optional: '(?:\\/' + RFC3986.ipv6Cidr + ')?', - forbidden: '' - }, - ipvfuture: { - required: '\\/' + RFC3986.ipv6Cidr, - optional: '(?:\\/' + RFC3986.ipv6Cidr + ')?', - forbidden: '' - } - }, - versions: { - ipv4: RFC3986.IPv4address, - ipv6: RFC3986.IPv6address, - ipvfuture: RFC3986.IPvFuture - } - } -}; +const internals = {}; -internals.Ip.createIpRegex = function (versions, cidr) { +exports.Sorter = class { - let regex; - for (let i = 0; i < versions.length; ++i) { - const version = versions[i]; - if (!regex) { - regex = '^(?:' + internals.Ip.versions[version] + internals.Ip.cidrs[version][cidr]; - } - else { - regex += '|' + internals.Ip.versions[version] + internals.Ip.cidrs[version][cidr]; - } - } + constructor() { - return new RegExp(regex + ')$'); -}; + this._items = []; + this.nodes = []; + } -module.exports = internals.Ip; + add(nodes, options) { + options = options || {}; -/***/ }), + // Validate rules -/***/ 49954: -/***/ ((module) => { + const before = [].concat(options.before || []); + const after = [].concat(options.after || []); + const group = options.group || '?'; + const sort = options.sort || 0; // Used for merging only -"use strict"; + Assert(!before.includes(group), `Item cannot come before itself: ${group}`); + Assert(!before.includes('?'), 'Item cannot come before unassociated items'); + Assert(!after.includes(group), `Item cannot come after itself: ${group}`); + Assert(!after.includes('?'), 'Item cannot come after unassociated items'); + if (!Array.isArray(nodes)) { + nodes = [nodes]; + } -const internals = { - rfc3986: {} -}; + for (const node of nodes) { + const item = { + seq: this._items.length, + sort, + before, + after, + group, + node + }; + this._items.push(item); + } -internals.generate = function () { + // Insert event - /** - * elements separated by forward slash ("/") are alternatives. - */ - const or = '|'; + if (!options.manual) { + const valid = this._sort(); + Assert(valid, 'item', group !== '?' ? `added into group ${group}` : '', 'created a dependencies error'); + } - /** - * Rule to support zero-padded addresses. - */ - const zeroPad = '0?'; + return this.nodes; + } - /** - * DIGIT = %x30-39 ; 0-9 - */ - const digit = '0-9'; - const digitOnly = '[' + digit + ']'; + merge(others) { - /** - * ALPHA = %x41-5A / %x61-7A ; A-Z / a-z - */ - const alpha = 'a-zA-Z'; - const alphaOnly = '[' + alpha + ']'; + if (!Array.isArray(others)) { + others = [others]; + } - /** - * IPv4 - * cidr = DIGIT ; 0-9 - * / %x31-32 DIGIT ; 10-29 - * / "3" %x30-32 ; 30-32 - */ - internals.rfc3986.ipv4Cidr = digitOnly + or + '[1-2]' + digitOnly + or + '3' + '[0-2]'; + for (const other of others) { + if (other) { + for (const item of other._items) { + this._items.push(Object.assign({}, item)); // Shallow cloned + } + } + } - /** - * IPv6 - * cidr = DIGIT ; 0-9 - * / %x31-39 DIGIT ; 10-99 - * / "1" %x0-1 DIGIT ; 100-119 - * / "12" %x0-8 ; 120-128 - */ - internals.rfc3986.ipv6Cidr = '(?:' + zeroPad + zeroPad + digitOnly + or + zeroPad + '[1-9]' + digitOnly + or + '1' + '[01]' + digitOnly + or + '12[0-8])'; + // Sort items - /** - * HEXDIG = DIGIT / "A" / "B" / "C" / "D" / "E" / "F" - */ - const hexDigit = digit + 'A-Fa-f'; - const hexDigitOnly = '[' + hexDigit + ']'; + this._items.sort(internals.mergeSort); + for (let i = 0; i < this._items.length; ++i) { + this._items[i].seq = i; + } - /** - * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" - */ - const unreserved = alpha + digit + '-\\._~'; + const valid = this._sort(); + Assert(valid, 'merge created a dependencies error'); - /** - * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "=" - */ - const subDelims = '!\\$&\'\\(\\)\\*\\+,;='; + return this.nodes; + } - /** - * pct-encoded = "%" HEXDIG HEXDIG - */ - const pctEncoded = '%' + hexDigit; + sort() { - /** - * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" - */ - const pchar = unreserved + pctEncoded + subDelims + ':@'; - const pcharOnly = '[' + pchar + ']'; + const valid = this._sort(); + Assert(valid, 'sort created a dependencies error'); - /** - * squareBrackets example: [] - */ - const squareBrackets = '\\[\\]'; + return this.nodes; + } - /** - * dec-octet = DIGIT ; 0-9 - * / %x31-39 DIGIT ; 10-99 - * / "1" 2DIGIT ; 100-199 - * / "2" %x30-34 DIGIT ; 200-249 - * / "25" %x30-35 ; 250-255 - */ - const decOctect = '(?:' + zeroPad + zeroPad + digitOnly + or + zeroPad + '[1-9]' + digitOnly + or + '1' + digitOnly + digitOnly + or + '2' + '[0-4]' + digitOnly + or + '25' + '[0-5])'; + _sort() { - /** - * IPv4address = dec-octet "." dec-octet "." dec-octet "." dec-octet - */ - internals.rfc3986.IPv4address = '(?:' + decOctect + '\\.){3}' + decOctect; + // Construct graph - /** - * h16 = 1*4HEXDIG ; 16 bits of address represented in hexadecimal - * ls32 = ( h16 ":" h16 ) / IPv4address ; least-significant 32 bits of address - * IPv6address = 6( h16 ":" ) ls32 - * / "::" 5( h16 ":" ) ls32 - * / [ h16 ] "::" 4( h16 ":" ) ls32 - * / [ *1( h16 ":" ) h16 ] "::" 3( h16 ":" ) ls32 - * / [ *2( h16 ":" ) h16 ] "::" 2( h16 ":" ) ls32 - * / [ *3( h16 ":" ) h16 ] "::" h16 ":" ls32 - * / [ *4( h16 ":" ) h16 ] "::" ls32 - * / [ *5( h16 ":" ) h16 ] "::" h16 - * / [ *6( h16 ":" ) h16 ] "::" - */ - const h16 = hexDigitOnly + '{1,4}'; - const ls32 = '(?:' + h16 + ':' + h16 + '|' + internals.rfc3986.IPv4address + ')'; - const IPv6SixHex = '(?:' + h16 + ':){6}' + ls32; - const IPv6FiveHex = '::(?:' + h16 + ':){5}' + ls32; - const IPv6FourHex = '(?:' + h16 + ')?::(?:' + h16 + ':){4}' + ls32; - const IPv6ThreeHex = '(?:(?:' + h16 + ':){0,1}' + h16 + ')?::(?:' + h16 + ':){3}' + ls32; - const IPv6TwoHex = '(?:(?:' + h16 + ':){0,2}' + h16 + ')?::(?:' + h16 + ':){2}' + ls32; - const IPv6OneHex = '(?:(?:' + h16 + ':){0,3}' + h16 + ')?::' + h16 + ':' + ls32; - const IPv6NoneHex = '(?:(?:' + h16 + ':){0,4}' + h16 + ')?::' + ls32; - const IPv6NoneHex2 = '(?:(?:' + h16 + ':){0,5}' + h16 + ')?::' + h16; - const IPv6NoneHex3 = '(?:(?:' + h16 + ':){0,6}' + h16 + ')?::'; - internals.rfc3986.IPv6address = '(?:' + IPv6SixHex + or + IPv6FiveHex + or + IPv6FourHex + or + IPv6ThreeHex + or + IPv6TwoHex + or + IPv6OneHex + or + IPv6NoneHex + or + IPv6NoneHex2 + or + IPv6NoneHex3 + ')'; + const graph = {}; + const graphAfters = Object.create(null); // A prototype can bungle lookups w/ false positives + const groups = Object.create(null); - /** - * IPvFuture = "v" 1*HEXDIG "." 1*( unreserved / sub-delims / ":" ) - */ - internals.rfc3986.IPvFuture = 'v' + hexDigitOnly + '+\\.[' + unreserved + subDelims + ':]+'; + for (const item of this._items) { + const seq = item.seq; // Unique across all items + const group = item.group; - /** - * scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) - */ - internals.rfc3986.scheme = alphaOnly + '[' + alpha + digit + '+-\\.]*'; + // Determine Groups - /** - * userinfo = *( unreserved / pct-encoded / sub-delims / ":" ) - */ - const userinfo = '[' + unreserved + pctEncoded + subDelims + ':]*'; + groups[group] = groups[group] || []; + groups[group].push(seq); - /** - * IP-literal = "[" ( IPv6address / IPvFuture ) "]" - */ - const IPLiteral = '\\[(?:' + internals.rfc3986.IPv6address + or + internals.rfc3986.IPvFuture + ')\\]'; + // Build intermediary graph using 'before' - /** - * reg-name = *( unreserved / pct-encoded / sub-delims ) - */ - const regName = '[' + unreserved + pctEncoded + subDelims + ']{0,255}'; + graph[seq] = item.before; - /** - * host = IP-literal / IPv4address / reg-name - */ - const host = '(?:' + IPLiteral + or + internals.rfc3986.IPv4address + or + regName + ')'; + // Build second intermediary graph with 'after' - /** - * port = *DIGIT - */ - const port = digitOnly + '*'; + for (const after of item.after) { + graphAfters[after] = graphAfters[after] || []; + graphAfters[after].push(seq); + } + } - /** - * authority = [ userinfo "@" ] host [ ":" port ] - */ - const authority = '(?:' + userinfo + '@)?' + host + '(?::' + port + ')?'; + // Expand intermediary graph - /** - * segment = *pchar - * segment-nz = 1*pchar - * path = path-abempty ; begins with "/" or is empty - * / path-absolute ; begins with "/" but not "//" - * / path-noscheme ; begins with a non-colon segment - * / path-rootless ; begins with a segment - * / path-empty ; zero characters - * path-abempty = *( "/" segment ) - * path-absolute = "/" [ segment-nz *( "/" segment ) ] - * path-rootless = segment-nz *( "/" segment ) - */ - const segment = pcharOnly + '*'; - const segmentNz = pcharOnly + '+'; - const segmentNzNc = '[' + unreserved + pctEncoded + subDelims + '@' + ']+'; - const pathEmpty = ''; - const pathAbEmpty = '(?:\\/' + segment + ')*'; - const pathAbsolute = '\\/(?:' + segmentNz + pathAbEmpty + ')?'; - const pathRootless = segmentNz + pathAbEmpty; - const pathNoScheme = segmentNzNc + pathAbEmpty; + for (const node in graph) { + const expandedGroups = []; - /** - * hier-part = "//" authority path - */ - internals.rfc3986.hierPart = '(?:' + '(?:\\/\\/' + authority + pathAbEmpty + ')' + or + pathAbsolute + or + pathRootless + ')'; + for (const graphNodeItem in graph[node]) { + const group = graph[node][graphNodeItem]; + groups[group] = groups[group] || []; + expandedGroups.push(...groups[group]); + } - /** - * relative-part = "//" authority path-abempty - * / path-absolute - * / path-noscheme - * / path-empty - */ - internals.rfc3986.relativeRef = '(?:' + '(?:\\/\\/' + authority + pathAbEmpty + ')' + or + pathAbsolute + or + pathNoScheme + or + pathEmpty + ')'; + graph[node] = expandedGroups; + } - /** - * query = *( pchar / "/" / "?" ) - */ - internals.rfc3986.query = '[' + pchar + '\\/\\?]*(?=#|$)'; //Finish matching either at the fragment part or end of the line. + // Merge intermediary graph using graphAfters into final graph - /** - * query = *( pchar / "[" / "]" / "/" / "?" ) - */ - internals.rfc3986.queryWithSquareBrackets = '[' + pchar + squareBrackets + '\\/\\?]*(?=#|$)'; //Finish matching either at the fragment part or end of the line. + for (const group in graphAfters) { + if (groups[group]) { + for (const node of groups[group]) { + graph[node].push(...graphAfters[group]); + } + } + } - /** - * fragment = *( pchar / "/" / "?" ) - */ - internals.rfc3986.fragment = '[' + pchar + '\\/\\?]*'; -}; + // Compile ancestors + const ancestors = {}; + for (const node in graph) { + const children = graph[node]; + for (const child of children) { + ancestors[child] = ancestors[child] || []; + ancestors[child].push(node); + } + } -internals.generate(); + // Topo sort -module.exports = internals.rfc3986; + const visited = {}; + const sorted = []; + for (let i = 0; i < this._items.length; ++i) { // Looping through item.seq values out of order + let next = i; -/***/ }), + if (ancestors[i]) { + next = null; + for (let j = 0; j < this._items.length; ++j) { // As above, these are item.seq values + if (visited[j] === true) { + continue; + } -/***/ 30018: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (!ancestors[j]) { + ancestors[j] = []; + } -"use strict"; + const shouldSeeCount = ancestors[j].length; + let seenCount = 0; + for (let k = 0; k < shouldSeeCount; ++k) { + if (visited[ancestors[j][k]]) { + ++seenCount; + } + } + if (seenCount === shouldSeeCount) { + next = j; + break; + } + } + } -const RFC3986 = __nccwpck_require__(49954); + if (next !== null) { + visited[next] = true; + sorted.push(next); + } + } + if (sorted.length !== this._items.length) { + return false; + } -const internals = { - Uri: { - createUriRegex: function (optionalScheme, allowRelative, relativeOnly, allowQuerySquareBrackets) { + const seqIndex = {}; + for (const item of this._items) { + seqIndex[item.seq] = item; + } - let scheme = RFC3986.scheme; - let prefix; + this._items = []; + this.nodes = []; - if (relativeOnly) { - prefix = '(?:' + RFC3986.relativeRef + ')'; - } - else { - // If we were passed a scheme, use it instead of the generic one - if (optionalScheme) { + for (const value of sorted) { + const sortedItem = seqIndex[value]; + this.nodes.push(sortedItem.node); + this._items.push(sortedItem); + } - // Have to put this in a non-capturing group to handle the OR statements - scheme = '(?:' + optionalScheme + ')'; - } + return true; + } +}; - const withScheme = '(?:' + scheme + ':' + RFC3986.hierPart + ')'; - prefix = allowRelative ? '(?:' + withScheme + '|' + RFC3986.relativeRef + ')' : withScheme; - } +internals.mergeSort = (a, b) => { - /** - * URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ] - * - * OR - * - * relative-ref = relative-part [ "?" query ] [ "#" fragment ] - */ - return new RegExp('^' + prefix + '(?:\\?' + (allowQuerySquareBrackets ? RFC3986.queryWithSquareBrackets : RFC3986.query) + ')?' + '(?:#' + RFC3986.fragment + ')?$'); - } - } + return a.sort === b.sort ? 0 : (a.sort < b.sort ? -1 : 1); }; -module.exports = internals.Uri; - /***/ }), -/***/ 62462: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 47541: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -const Util = __nccwpck_require__(73837); +Object.defineProperty(exports, "__esModule", ({ value: true })); -const Hoek = __nccwpck_require__(10904); +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } -const Any = __nccwpck_require__(77641); +var universalUserAgent = __nccwpck_require__(45030); +var request = __nccwpck_require__(36234); +var deprecation = __nccwpck_require__(58932); +var universalGithubAppJwt = __nccwpck_require__(84419); +var LRU = _interopDefault(__nccwpck_require__(7129)); +var requestError = __nccwpck_require__(10537); +async function getAppAuthentication({ + appId, + privateKey, + timeDifference +}) { + const appAuthentication = await universalGithubAppJwt.githubAppJwt({ + id: +appId, + privateKey, + now: timeDifference && Math.floor(Date.now() / 1000) + timeDifference + }); + return { + type: "app", + token: appAuthentication.token, + appId: appAuthentication.appId, + expiresAt: new Date(appAuthentication.expiration * 1000).toISOString() + }; +} -const internals = {}; +function _defineProperty(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + return obj; +} -internals.Map = class extends Map { +function ownKeys(object, enumerableOnly) { + var keys = Object.keys(object); - slice() { + if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(object); + if (enumerableOnly) symbols = symbols.filter(function (sym) { + return Object.getOwnPropertyDescriptor(object, sym).enumerable; + }); + keys.push.apply(keys, symbols); + } - return new internals.Map(this); - } + return keys; +} - toString() { +function _objectSpread2(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i] != null ? arguments[i] : {}; - return Util.inspect(this); + if (i % 2) { + ownKeys(Object(source), true).forEach(function (key) { + _defineProperty(target, key, source[key]); + }); + } else if (Object.getOwnPropertyDescriptors) { + Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); + } else { + ownKeys(Object(source)).forEach(function (key) { + Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); + }); } -}; + } + return target; +} -internals.Symbol = class extends Any { +function _objectWithoutPropertiesLoose(source, excluded) { + if (source == null) return {}; + var target = {}; + var sourceKeys = Object.keys(source); + var key, i; - constructor() { + for (i = 0; i < sourceKeys.length; i++) { + key = sourceKeys[i]; + if (excluded.indexOf(key) >= 0) continue; + target[key] = source[key]; + } - super(); - this._type = 'symbol'; - this._inner.map = new internals.Map(); + return target; +} + +function _objectWithoutProperties(source, excluded) { + if (source == null) return {}; + + var target = _objectWithoutPropertiesLoose(source, excluded); + + var key, i; + + if (Object.getOwnPropertySymbols) { + var sourceSymbolKeys = Object.getOwnPropertySymbols(source); + + for (i = 0; i < sourceSymbolKeys.length; i++) { + key = sourceSymbolKeys[i]; + if (excluded.indexOf(key) >= 0) continue; + if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; + target[key] = source[key]; } + } - _base(value, state, options) { + return target; +} - if (options.convert) { - const lookup = this._inner.map.get(value); - if (lookup) { - value = lookup; - } +// https://github.com/isaacs/node-lru-cache#readme +function getCache() { + return new LRU({ + // 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 + }); +} +async function get(cache, options) { + const cacheKey = optionsToCacheKey(options); + const result = await cache.get(cacheKey); - if (this._flags.allowOnly) { - return { - value, - errors: (typeof value === 'symbol') ? null : this.createError('symbol.map', { value, map: this._inner.map }, state, options) - }; - } - } + if (!result) { + return; + } - return { - value, - errors: (typeof value === 'symbol') ? null : this.createError('symbol.base', { value }, state, options) - }; + const [token, createdAt, expiresAt, repositorySelection, permissionsString, singleFileName] = result.split("|"); + const permissions = options.permissions || permissionsString.split(/,/).reduce((permissions, string) => { + if (/!$/.test(string)) { + permissions[string.slice(0, -1)] = "write"; + } else { + permissions[string] = "read"; } - map(iterable) { + return permissions; + }, {}); + return { + token, + createdAt, + expiresAt, + permissions, + repositoryIds: options.repositoryIds, + singleFileName, + repositorySelection: repositorySelection + }; +} +async function set(cache, options, data) { + const key = optionsToCacheKey(options); + const permissionsString = options.permissions ? "" : Object.keys(data.permissions).map(name => `${name}${data.permissions[name] === "write" ? "!" : ""}`).join(","); + const value = [data.token, data.createdAt, data.expiresAt, data.repositorySelection, permissionsString, data.singleFileName].join("|"); + await cache.set(key, value); +} - if (iterable && !iterable[Symbol.iterator] && typeof iterable === 'object') { - iterable = Object.entries(iterable); - } +function optionsToCacheKey({ + installationId, + permissions = {}, + repositoryIds = [] +}) { + const permissionsString = Object.keys(permissions).sort().map(name => permissions[name] === "read" ? name : `${name}!`).join(","); + const repositoryIdsString = repositoryIds.sort().join(","); + return [installationId, repositoryIdsString, permissionsString].filter(Boolean).join("|"); +} - Hoek.assert(iterable && iterable[Symbol.iterator], 'Iterable must be an iterable or object'); - const obj = this.clone(); +function toTokenAuthentication({ + installationId, + token, + createdAt, + expiresAt, + repositorySelection, + permissions, + repositoryIds, + singleFileName +}) { + return Object.assign({ + type: "token", + tokenType: "installation", + token, + installationId, + permissions, + createdAt, + expiresAt, + repositorySelection + }, repositoryIds ? { + repositoryIds + } : null, singleFileName ? { + singleFileName + } : null); +} - const symbols = []; - for (const entry of iterable) { - Hoek.assert(entry && entry[Symbol.iterator], 'Entry must be an iterable'); - const [key, value] = entry; +async function getInstallationAuthentication(state, options, customRequest) { + const installationId = Number(options.installationId || state.installationId); - Hoek.assert(typeof key !== 'object' && typeof key !== 'function' && typeof key !== 'symbol', 'Key must not be an object, function, or Symbol'); - Hoek.assert(typeof value === 'symbol', 'Value must be a Symbol'); - obj._inner.map.set(key, value); - symbols.push(value); - } + if (!installationId) { + throw new Error("[@octokit/auth-app] installationId option is required for installation authentication."); + } - return obj.valid(...symbols); - } + if (options.factory) { + const { + type, + factory + } = options, + factoryAuthOptions = _objectWithoutProperties(options, ["type", "factory"]); // @ts-ignore if `options.factory` is set, the return type for `auth()` should be `Promise>` - describe() { - const description = super.describe(); - description.map = new Map(this._inner.map); - return description; - } -}; + return factory(Object.assign({}, state, factoryAuthOptions)); + } + const optionsWithInstallationTokenFromState = Object.assign({ + installationId + }, options); -module.exports = new internals.Symbol(); + if (!options.refresh) { + const result = await get(state.cache, optionsWithInstallationTokenFromState); + if (result) { + const { + token, + createdAt, + expiresAt, + permissions, + repositoryIds, + singleFileName, + repositorySelection + } = result; + return toTokenAuthentication({ + installationId, + token, + createdAt, + expiresAt, + permissions, + repositorySelection, + repositoryIds, + singleFileName + }); + } + } -/***/ }), + const appAuthentication = await getAppAuthentication(state); + const request = customRequest || state.request; + const { + data: { + token, + expires_at: expiresAt, + repositories, + permissions, + // @ts-ignore + repository_selection: repositorySelection, + // @ts-ignore + single_file: singleFileName + } + } = await request("POST /app/installations/{installation_id}/access_tokens", { + installation_id: installationId, + repository_ids: options.repositoryIds, + permissions: options.permissions, + mediaType: { + previews: ["machine-man"] + }, + headers: { + authorization: `bearer ${appAuthentication.token}` + } + }); + const repositoryIds = repositories ? repositories.map(r => r.id) : void 0; + const createdAt = new Date().toISOString(); + await set(state.cache, optionsWithInstallationTokenFromState, { + token, + createdAt, + expiresAt, + repositorySelection, + permissions, + repositoryIds, + singleFileName + }); + return toTokenAuthentication({ + installationId, + token, + createdAt, + expiresAt, + repositorySelection, + permissions, + repositoryIds, + singleFileName + }); +} -/***/ 52252: -/***/ ((module) => { +async function getOAuthAuthentication(state, options, customRequest) { + const request = customRequest || state.request; // The "/login/oauth/access_token" is not part of the REST API hosted on api.github.com, + // instead it’s using the github.com domain. -"use strict"; + const route = /^https:\/\/(api\.)?github\.com$/.test(state.request.endpoint.DEFAULTS.baseUrl) ? "POST https://github.com/login/oauth/access_token" : `POST ${state.request.endpoint.DEFAULTS.baseUrl.replace("/api/v3", "/login/oauth/access_token")}`; + const parameters = { + headers: { + accept: `application/json` + }, + client_id: state.clientId, + client_secret: state.clientSecret, + code: options.code, + state: options.state, + redirect_uri: options.redirectUrl + }; + const response = await request(route, parameters); + if (response.data.error !== undefined) { + throw new requestError.RequestError(`${response.data.error_description} (${response.data.error})`, response.status, { + headers: response.headers, + request: request.endpoint(route, parameters) + }); + } -const internals = {}; + const { + data: { + access_token: token, + scope + } + } = response; + return { + type: "token", + tokenType: "oauth", + token, + scopes: scope.split(/,\s*/).filter(Boolean) + }; +} +async function auth(state, options) { + if (options.type === "app") { + return getAppAuthentication(state); + } -module.exports = { - settingsCache: Symbol('settingsCache') -}; + if (options.type === "installation") { + return getInstallationAuthentication(state, options); + } + return getOAuthAuthentication(state, options); +} -/***/ }), +const PATHS = ["/app", "/app/hook/config", "/app/installations", "/app/installations/{installation_id}", "/app/installations/{installation_id}/access_tokens", "/app/installations/{installation_id}/suspended", "/marketplace_listing/accounts/{account_id}", "/marketplace_listing/plan", "/marketplace_listing/plans", "/marketplace_listing/plans/{plan_id}/accounts", "/marketplace_listing/stubbed/accounts/{account_id}", "/marketplace_listing/stubbed/plan", "/marketplace_listing/stubbed/plans", "/marketplace_listing/stubbed/plans/{plan_id}/accounts", "/orgs/{org}/installation", "/repos/{owner}/{repo}/installation", "/users/{username}/installation"]; // CREDIT: Simon Grondin (https://github.com/SGrondin) +// https://github.com/octokit/plugin-throttling.js/blob/45c5d7f13b8af448a9dbca468d9c9150a73b3948/lib/route-matcher.js -/***/ 88392: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +function routeMatcher(paths) { + // EXAMPLE. For the following paths: -"use strict"; + /* [ + "/orgs/{org}/invitations", + "/repos/{owner}/{repo}/collaborators/{username}" + ] */ + const regexes = paths.map(p => p.split("/").map(c => c.startsWith("{") ? "(?:.+?)" : c).join("/")); // 'regexes' would contain: + /* [ + '/orgs/(?:.+?)/invitations', + '/repos/(?:.+?)/(?:.+?)/collaborators/(?:.+?)' + ] */ -const Assert = __nccwpck_require__(32718); + const regex = `^(?:${regexes.map(r => `(?:${r})`).join("|")})[^/]*$`; // 'regex' would contain: + /* + ^(?:(?:\/orgs\/(?:.+?)\/invitations)|(?:\/repos\/(?:.+?)\/(?:.+?)\/collaborators\/(?:.+?)))[^\/]*$ + It may look scary, but paste it into https://www.debuggex.com/ + and it will make a lot more sense! + */ -const internals = {}; + return new RegExp(regex, "i"); +} +const REGEX = routeMatcher(PATHS); +function requiresAppAuth(url) { + return !!url && REGEX.test(url); +} -module.exports = class Topo { +const FIVE_SECONDS_IN_MS = 5 * 1000; - constructor() { +function isNotTimeSkewError(error) { + return !(error.message.match(/'Expiration time' claim \('exp'\) must be a numeric value representing the future time at which the assertion expires/) || error.message.match(/'Issued at' claim \('iat'\) must be an Integer representing the time that the assertion was issued/)); +} - this._items = []; - this.nodes = []; - } +async function hook(state, request, route, parameters) { + let endpoint = request.endpoint.merge(route, parameters); - add(nodes, options) { + if (requiresAppAuth(endpoint.url.replace(request.endpoint.DEFAULTS.baseUrl, ""))) { + const { + token + } = await getAppAuthentication(state); + endpoint.headers.authorization = `bearer ${token}`; + let response; - options = options || {}; + try { + response = await request(endpoint); + } catch (error) { + // If there's an issue with the expiration, regenerate the token and try again. + // Otherwise rethrow the error for upstream handling. + if (isNotTimeSkewError(error)) { + throw error; + } // If the date header is missing, we can't correct the system time skew. + // Throw the error to be handled upstream. - // Validate rules - const before = [].concat(options.before || []); - const after = [].concat(options.after || []); - const group = options.group || '?'; - const sort = options.sort || 0; // Used for merging only + if (typeof error.headers.date === "undefined") { + throw error; + } - Assert(!before.includes(group), `Item cannot come before itself: ${group}`); - Assert(!before.includes('?'), 'Item cannot come before unassociated items'); - Assert(!after.includes(group), `Item cannot come after itself: ${group}`); - Assert(!after.includes('?'), 'Item cannot come after unassociated items'); + const diff = Math.floor((Date.parse(error.headers.date) - Date.parse(new Date().toString())) / 1000); + state.log.warn(error.message); + state.log.warn(`[@octokit/auth-app] GitHub API time and system time are different by ${diff} seconds. Retrying request with the difference accounted for.`); + const { + token + } = await getAppAuthentication(_objectSpread2(_objectSpread2({}, state), {}, { + timeDifference: diff + })); + endpoint.headers.authorization = `bearer ${token}`; + return request(endpoint); + } - if (!Array.isArray(nodes)) { - nodes = [nodes]; - } + return response; + } - for (const node of nodes) { - const item = { - seq: this._items.length, - sort, - before, - after, - group, - node - }; + const { + token, + createdAt + } = await getInstallationAuthentication(state, {}, request); + endpoint.headers.authorization = `token ${token}`; + return sendRequestWithRetries(state, request, endpoint, createdAt); +} +/** + * Newly created tokens might not be accessible immediately after creation. + * In case of a 401 response, we retry with an exponential delay until more + * than five seconds pass since the creation of the token. + * + * @see https://github.com/octokit/auth-app.js/issues/65 + */ - this._items.push(item); - } +async function sendRequestWithRetries(state, request, options, createdAt, retries = 0) { + const timeSinceTokenCreationInMs = +new Date() - +new Date(createdAt); - // Insert event + try { + return await request(options); + } catch (error) { + if (error.status !== 401) { + throw error; + } - const valid = this._sort(); - Assert(valid, 'item', group !== '?' ? `added into group ${group}` : '', 'created a dependencies error'); + if (timeSinceTokenCreationInMs >= FIVE_SECONDS_IN_MS) { + if (retries > 0) { + error.message = `After ${retries} retries within ${timeSinceTokenCreationInMs / 1000}s of creating the installation access token, the response remains 401. At this point, the cause may be an authentication problem or a system outage. Please check https://www.githubstatus.com for status information`; + } - return this.nodes; + throw error; } - merge(others) { + ++retries; + const awaitTime = retries * 1000; + state.log.warn(`[@octokit/auth-app] Retrying after 401 response to account for token replication delay (retry: ${retries}, wait: ${awaitTime / 1000}s)`); + await new Promise(resolve => setTimeout(resolve, awaitTime)); + return sendRequestWithRetries(state, request, options, createdAt, retries); + } +} - if (!Array.isArray(others)) { - others = [others]; - } +const VERSION = "2.10.5"; - for (const other of others) { - if (other) { - for (const item of other._items) { - this._items.push(Object.assign({}, item)); // Shallow cloned - } - } - } +const createAppAuth = function createAppAuth(options) { + const log = Object.assign({ + warn: console.warn.bind(console) + }, options.log); - // Sort items + if ("id" in options) { + log.warn(new deprecation.Deprecation('[@octokit/auth-app] "createAppAuth({ id })" is deprecated, use "createAppAuth({ appId })" instead')); + } - this._items.sort(internals.mergeSort); - for (let i = 0; i < this._items.length; ++i) { - this._items[i].seq = i; - } + const state = Object.assign({ + request: request.request.defaults({ + headers: { + "user-agent": `octokit-auth-app.js/${VERSION} ${universalUserAgent.getUserAgent()}` + } + }), + cache: getCache() + }, options, { + appId: Number("appId" in options ? options.appId : options.id) + }, options.installationId ? { + installationId: Number(options.installationId) + } : {}, { + log + }); + return Object.assign(auth.bind(null, state), { + hook: hook.bind(null, state) + }); +}; - const valid = this._sort(); - Assert(valid, 'merge created a dependencies error'); +exports.createAppAuth = createAppAuth; +//# sourceMappingURL=index.js.map - return this.nodes; - } - _sort() { +/***/ }), - // Construct graph +/***/ 40334: +/***/ ((__unused_webpack_module, exports) => { - const graph = {}; - const graphAfters = Object.create(null); // A prototype can bungle lookups w/ false positives - const groups = Object.create(null); +"use strict"; - for (const item of this._items) { - const seq = item.seq; // Unique across all items - const group = item.group; - // Determine Groups +Object.defineProperty(exports, "__esModule", ({ value: true })); - groups[group] = groups[group] || []; - groups[group].push(seq); +async function auth(token) { + const tokenType = token.split(/\./).length === 3 ? "app" : /^v\d+\./.test(token) ? "installation" : "oauth"; + return { + type: "token", + token: token, + tokenType + }; +} - // Build intermediary graph using 'before' +/** + * Prefix token for usage in the Authorization header + * + * @param token OAuth token or JSON Web Token + */ +function withAuthorizationPrefix(token) { + if (token.split(/\./).length === 3) { + return `bearer ${token}`; + } - graph[seq] = item.before; + return `token ${token}`; +} - // Build second intermediary graph with 'after' +async function hook(token, request, route, parameters) { + const endpoint = request.endpoint.merge(route, parameters); + endpoint.headers.authorization = withAuthorizationPrefix(token); + return request(endpoint); +} - for (const after of item.after) { - graphAfters[after] = graphAfters[after] || []; - graphAfters[after].push(seq); - } - } +const createTokenAuth = function createTokenAuth(token) { + if (!token) { + throw new Error("[@octokit/auth-token] No token passed to createTokenAuth"); + } - // Expand intermediary graph + if (typeof token !== "string") { + throw new Error("[@octokit/auth-token] Token passed to createTokenAuth is not a string"); + } - for (const node in graph) { - const expandedGroups = []; + token = token.replace(/^(token|bearer) +/i, ""); + return Object.assign(auth.bind(null, token), { + hook: hook.bind(null, token) + }); +}; - for (const graphNodeItem in graph[node]) { - const group = graph[node][graphNodeItem]; - groups[group] = groups[group] || []; - expandedGroups.push(...groups[group]); - } +exports.createTokenAuth = createTokenAuth; +//# sourceMappingURL=index.js.map - graph[node] = expandedGroups; - } - // Merge intermediary graph using graphAfters into final graph +/***/ }), - for (const group in graphAfters) { - if (groups[group]) { - for (const node of groups[group]) { - graph[node].push(...graphAfters[group]); - } - } - } +/***/ 79567: +/***/ ((__unused_webpack_module, exports) => { - // Compile ancestors +"use strict"; - const ancestors = {}; - for (const node in graph) { - const children = graph[node]; - for (const child of children) { - ancestors[child] = ancestors[child] || []; - ancestors[child].push(node); - } - } - // Topo sort +Object.defineProperty(exports, "__esModule", ({ value: true })); - const visited = {}; - const sorted = []; +async function auth(reason) { + return { + type: "unauthenticated", + reason + }; +} - for (let i = 0; i < this._items.length; ++i) { // Looping through item.seq values out of order - let next = i; +function isRateLimitError(error) { + if (error.status !== 403) { + return false; + } + /* istanbul ignore if */ - if (ancestors[i]) { - next = null; - for (let j = 0; j < this._items.length; ++j) { // As above, these are item.seq values - if (visited[j] === true) { - continue; - } - if (!ancestors[j]) { - ancestors[j] = []; - } + if (!error.headers) { + return false; + } - const shouldSeeCount = ancestors[j].length; - let seenCount = 0; - for (let k = 0; k < shouldSeeCount; ++k) { - if (visited[ancestors[j][k]]) { - ++seenCount; - } - } + return error.headers["x-ratelimit-remaining"] === "0"; +} - if (seenCount === shouldSeeCount) { - next = j; - break; - } - } - } +const REGEX_ABUSE_LIMIT_MESSAGE = /\babuse\b/i; +function isAbuseLimitError(error) { + if (error.status !== 403) { + return false; + } - if (next !== null) { - visited[next] = true; - sorted.push(next); - } - } + return REGEX_ABUSE_LIMIT_MESSAGE.test(error.message); +} - if (sorted.length !== this._items.length) { - return false; - } +async function hook(reason, request, route, parameters) { + const endpoint = request.endpoint.merge(route, parameters); + return request(endpoint).catch(error => { + if (error.status === 404) { + error.message = `Not found. May be due to lack of authentication. Reason: ${reason}`; + throw error; + } - const seqIndex = {}; - for (const item of this._items) { - seqIndex[item.seq] = item; - } + if (isRateLimitError(error)) { + error.message = `API rate limit exceeded. This maybe caused by the lack of authentication. Reason: ${reason}`; + throw error; + } - this._items = []; - this.nodes = []; + if (isAbuseLimitError(error)) { + error.message = `You have triggered an abuse detection mechanism. This maybe caused by the lack of authentication. Reason: ${reason}`; + throw error; + } - for (const value of sorted) { - const sortedItem = seqIndex[value]; - this.nodes.push(sortedItem.node); - this._items.push(sortedItem); - } + if (error.status === 401) { + error.message = `Unauthorized. "${endpoint.method} ${endpoint.url}" failed most likely due to lack of authentication. Reason: ${reason}`; + throw error; + } - return true; + if (error.status >= 400 && error.status < 500) { + error.message = error.message.replace(/\.?$/, `. May be caused by lack of authentication (${reason}).`); } -}; + throw error; + }); +} -internals.mergeSort = (a, b) => { +const createUnauthenticatedAuth = function createUnauthenticatedAuth(options) { + if (!options || !options.reason) { + throw new Error("[@octokit/auth-unauthenticated] No reason passed to createUnauthenticatedAuth"); + } - return a.sort === b.sort ? 0 : (a.sort < b.sort ? -1 : 1); + return Object.assign(auth.bind(null, options.reason), { + hook: hook.bind(null, options.reason) + }); }; +exports.createUnauthenticatedAuth = createUnauthenticatedAuth; +//# sourceMappingURL=index.js.map + /***/ }), -/***/ 47541: +/***/ 76762: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -11580,81 +3336,11 @@ internals.mergeSort = (a, b) => { Object.defineProperty(exports, "__esModule", ({ value: true })); -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - var universalUserAgent = __nccwpck_require__(45030); +var beforeAfterHook = __nccwpck_require__(83682); var request = __nccwpck_require__(36234); -var deprecation = __nccwpck_require__(58932); -var universalGithubAppJwt = __nccwpck_require__(84419); -var LRU = _interopDefault(__nccwpck_require__(7129)); -var requestError = __nccwpck_require__(10537); - -async function getAppAuthentication({ - appId, - privateKey, - timeDifference -}) { - const appAuthentication = await universalGithubAppJwt.githubAppJwt({ - id: +appId, - privateKey, - now: timeDifference && Math.floor(Date.now() / 1000) + timeDifference - }); - return { - type: "app", - token: appAuthentication.token, - appId: appAuthentication.appId, - expiresAt: new Date(appAuthentication.expiration * 1000).toISOString() - }; -} - -function _defineProperty(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; - } - - return obj; -} - -function ownKeys(object, enumerableOnly) { - var keys = Object.keys(object); - - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(object); - if (enumerableOnly) symbols = symbols.filter(function (sym) { - return Object.getOwnPropertyDescriptor(object, sym).enumerable; - }); - keys.push.apply(keys, symbols); - } - - return keys; -} - -function _objectSpread2(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? arguments[i] : {}; - - if (i % 2) { - ownKeys(Object(source), true).forEach(function (key) { - _defineProperty(target, key, source[key]); - }); - } else if (Object.getOwnPropertyDescriptors) { - Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); - } else { - ownKeys(Object(source)).forEach(function (key) { - Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); - }); - } - } - - return target; -} +var graphql = __nccwpck_require__(88467); +var authToken = __nccwpck_require__(40334); function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; @@ -11692,530 +3378,653 @@ function _objectWithoutProperties(source, excluded) { return target; } -// https://github.com/isaacs/node-lru-cache#readme -function getCache() { - return new LRU({ - // 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 - }); -} -async function get(cache, options) { - const cacheKey = optionsToCacheKey(options); - const result = await cache.get(cacheKey); +const VERSION = "3.2.4"; - if (!result) { - return; - } +class Octokit { + constructor(options = {}) { + const hook = new beforeAfterHook.Collection(); + const requestDefaults = { + baseUrl: request.request.endpoint.DEFAULTS.baseUrl, + headers: {}, + request: Object.assign({}, options.request, { + hook: hook.bind(null, "request") + }), + mediaType: { + previews: [], + format: "" + } + }; // prepend default user agent with `options.userAgent` if set - const [token, createdAt, expiresAt, repositorySelection, permissionsString, singleFileName] = result.split("|"); - const permissions = options.permissions || permissionsString.split(/,/).reduce((permissions, string) => { - if (/!$/.test(string)) { - permissions[string.slice(0, -1)] = "write"; - } else { - permissions[string] = "read"; + requestDefaults.headers["user-agent"] = [options.userAgent, `octokit-core.js/${VERSION} ${universalUserAgent.getUserAgent()}`].filter(Boolean).join(" "); + + if (options.baseUrl) { + requestDefaults.baseUrl = options.baseUrl; } - return permissions; - }, {}); - return { - token, - createdAt, - expiresAt, - permissions, - repositoryIds: options.repositoryIds, - singleFileName, - repositorySelection: repositorySelection - }; -} -async function set(cache, options, data) { - const key = optionsToCacheKey(options); - const permissionsString = options.permissions ? "" : Object.keys(data.permissions).map(name => `${name}${data.permissions[name] === "write" ? "!" : ""}`).join(","); - const value = [data.token, data.createdAt, data.expiresAt, data.repositorySelection, permissionsString, data.singleFileName].join("|"); - await cache.set(key, value); + if (options.previews) { + requestDefaults.mediaType.previews = options.previews; + } + + if (options.timeZone) { + requestDefaults.headers["time-zone"] = options.timeZone; + } + + this.request = request.request.defaults(requestDefaults); + this.graphql = graphql.withCustomRequest(this.request).defaults(requestDefaults); + this.log = Object.assign({ + debug: () => {}, + info: () => {}, + warn: console.warn.bind(console), + error: console.error.bind(console) + }, options.log); + this.hook = hook; // (1) If neither `options.authStrategy` nor `options.auth` are set, the `octokit` instance + // is unauthenticated. The `this.auth()` method is a no-op and no request hook is registered. + // (2) If only `options.auth` is set, use the default token authentication strategy. + // (3) If `options.authStrategy` is set then use it and pass in `options.auth`. Always pass own request as many strategies accept a custom request instance. + // TODO: type `options.auth` based on `options.authStrategy`. + + if (!options.authStrategy) { + if (!options.auth) { + // (1) + this.auth = async () => ({ + type: "unauthenticated" + }); + } else { + // (2) + const auth = authToken.createTokenAuth(options.auth); // @ts-ignore ¯\_(ツ)_/¯ + + hook.wrap("request", auth.hook); + this.auth = auth; + } + } else { + const { + authStrategy + } = options, + otherOptions = _objectWithoutProperties(options, ["authStrategy"]); + + const auth = authStrategy(Object.assign({ + request: this.request, + log: this.log, + // we pass the current octokit instance as well as its constructor options + // to allow for authentication strategies that return a new octokit instance + // that shares the same internal state as the current one. The original + // requirement for this was the "event-octokit" authentication strategy + // of https://github.com/probot/octokit-auth-probot. + octokit: this, + octokitOptions: otherOptions + }, options.auth)); // @ts-ignore ¯\_(ツ)_/¯ + + hook.wrap("request", auth.hook); + this.auth = auth; + } // apply plugins + // https://stackoverflow.com/a/16345172 + + + const classConstructor = this.constructor; + classConstructor.plugins.forEach(plugin => { + Object.assign(this, plugin(this, options)); + }); + } + + static defaults(defaults) { + const OctokitWithDefaults = class extends this { + constructor(...args) { + const options = args[0] || {}; + + if (typeof defaults === "function") { + super(defaults(options)); + return; + } + + super(Object.assign({}, defaults, options, options.userAgent && defaults.userAgent ? { + userAgent: `${options.userAgent} ${defaults.userAgent}` + } : null)); + } + + }; + return OctokitWithDefaults; + } + /** + * Attach a plugin (or many) to your Octokit instance. + * + * @example + * const API = Octokit.plugin(plugin1, plugin2, plugin3, ...) + */ + + + static plugin(...newPlugins) { + var _a; + + const currentPlugins = this.plugins; + const NewOctokit = (_a = class extends this {}, _a.plugins = currentPlugins.concat(newPlugins.filter(plugin => !currentPlugins.includes(plugin))), _a); + return NewOctokit; + } + } +Octokit.VERSION = VERSION; +Octokit.plugins = []; -function optionsToCacheKey({ - installationId, - permissions = {}, - repositoryIds = [] -}) { - const permissionsString = Object.keys(permissions).sort().map(name => permissions[name] === "read" ? name : `${name}!`).join(","); - const repositoryIdsString = repositoryIds.sort().join(","); - return [installationId, repositoryIdsString, permissionsString].filter(Boolean).join("|"); +exports.Octokit = Octokit; +//# sourceMappingURL=index.js.map + + +/***/ }), + +/***/ 59440: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +var isPlainObject = __nccwpck_require__(63287); +var universalUserAgent = __nccwpck_require__(45030); + +function lowercaseKeys(object) { + if (!object) { + return {}; + } + + return Object.keys(object).reduce((newObj, key) => { + newObj[key.toLowerCase()] = object[key]; + return newObj; + }, {}); } -function toTokenAuthentication({ - installationId, - token, - createdAt, - expiresAt, - repositorySelection, - permissions, - repositoryIds, - singleFileName -}) { - return Object.assign({ - type: "token", - tokenType: "installation", - token, - installationId, - permissions, - createdAt, - expiresAt, - repositorySelection - }, repositoryIds ? { - repositoryIds - } : null, singleFileName ? { - singleFileName - } : null); +function mergeDeep(defaults, options) { + const result = Object.assign({}, defaults); + Object.keys(options).forEach(key => { + if (isPlainObject.isPlainObject(options[key])) { + if (!(key in defaults)) Object.assign(result, { + [key]: options[key] + });else result[key] = mergeDeep(defaults[key], options[key]); + } else { + Object.assign(result, { + [key]: options[key] + }); + } + }); + return result; } -async function getInstallationAuthentication(state, options, customRequest) { - const installationId = Number(options.installationId || state.installationId); - - if (!installationId) { - throw new Error("[@octokit/auth-app] installationId option is required for installation authentication."); +function removeUndefinedProperties(obj) { + for (const key in obj) { + if (obj[key] === undefined) { + delete obj[key]; + } } - if (options.factory) { - const { - type, - factory - } = options, - factoryAuthOptions = _objectWithoutProperties(options, ["type", "factory"]); // @ts-ignore if `options.factory` is set, the return type for `auth()` should be `Promise>` + return obj; +} +function merge(defaults, route, options) { + if (typeof route === "string") { + let [method, url] = route.split(" "); + options = Object.assign(url ? { + method, + url + } : { + url: method + }, options); + } else { + options = Object.assign({}, route); + } // lowercase header names before merging with defaults to avoid duplicates - return factory(Object.assign({}, state, factoryAuthOptions)); - } - const optionsWithInstallationTokenFromState = Object.assign({ - installationId - }, options); + options.headers = lowercaseKeys(options.headers); // remove properties with undefined values before merging - if (!options.refresh) { - const result = await get(state.cache, optionsWithInstallationTokenFromState); + removeUndefinedProperties(options); + removeUndefinedProperties(options.headers); + const mergedOptions = mergeDeep(defaults || {}, options); // mediaType.previews arrays are merged, instead of overwritten - if (result) { - const { - token, - createdAt, - expiresAt, - permissions, - repositoryIds, - singleFileName, - repositorySelection - } = result; - return toTokenAuthentication({ - installationId, - token, - createdAt, - expiresAt, - permissions, - repositorySelection, - repositoryIds, - singleFileName - }); - } + if (defaults && defaults.mediaType.previews.length) { + mergedOptions.mediaType.previews = defaults.mediaType.previews.filter(preview => !mergedOptions.mediaType.previews.includes(preview)).concat(mergedOptions.mediaType.previews); } - const appAuthentication = await getAppAuthentication(state); - const request = customRequest || state.request; - const { - data: { - token, - expires_at: expiresAt, - repositories, - permissions, - // @ts-ignore - repository_selection: repositorySelection, - // @ts-ignore - single_file: singleFileName - } - } = await request("POST /app/installations/{installation_id}/access_tokens", { - installation_id: installationId, - repository_ids: options.repositoryIds, - permissions: options.permissions, - mediaType: { - previews: ["machine-man"] - }, - headers: { - authorization: `bearer ${appAuthentication.token}` - } - }); - const repositoryIds = repositories ? repositories.map(r => r.id) : void 0; - const createdAt = new Date().toISOString(); - await set(state.cache, optionsWithInstallationTokenFromState, { - token, - createdAt, - expiresAt, - repositorySelection, - permissions, - repositoryIds, - singleFileName - }); - return toTokenAuthentication({ - installationId, - token, - createdAt, - expiresAt, - repositorySelection, - permissions, - repositoryIds, - singleFileName - }); + mergedOptions.mediaType.previews = mergedOptions.mediaType.previews.map(preview => preview.replace(/-preview/, "")); + return mergedOptions; } -async function getOAuthAuthentication(state, options, customRequest) { - const request = customRequest || state.request; // The "/login/oauth/access_token" is not part of the REST API hosted on api.github.com, - // instead it’s using the github.com domain. - - const route = /^https:\/\/(api\.)?github\.com$/.test(state.request.endpoint.DEFAULTS.baseUrl) ? "POST https://github.com/login/oauth/access_token" : `POST ${state.request.endpoint.DEFAULTS.baseUrl.replace("/api/v3", "/login/oauth/access_token")}`; - const parameters = { - headers: { - accept: `application/json` - }, - client_id: state.clientId, - client_secret: state.clientSecret, - code: options.code, - state: options.state, - redirect_uri: options.redirectUrl - }; - const response = await request(route, parameters); +function addQueryParameters(url, parameters) { + const separator = /\?/.test(url) ? "&" : "?"; + const names = Object.keys(parameters); - if (response.data.error !== undefined) { - throw new requestError.RequestError(`${response.data.error_description} (${response.data.error})`, response.status, { - headers: response.headers, - request: request.endpoint(route, parameters) - }); + if (names.length === 0) { + return url; } - const { - data: { - access_token: token, - scope + return url + separator + names.map(name => { + if (name === "q") { + return "q=" + parameters.q.split("+").map(encodeURIComponent).join("+"); } - } = response; - return { - type: "token", - tokenType: "oauth", - token, - scopes: scope.split(/,\s*/).filter(Boolean) - }; -} -async function auth(state, options) { - if (options.type === "app") { - return getAppAuthentication(state); - } + return `${name}=${encodeURIComponent(parameters[name])}`; + }).join("&"); +} - if (options.type === "installation") { - return getInstallationAuthentication(state, options); - } +const urlVariableRegex = /\{[^}]+\}/g; - return getOAuthAuthentication(state, options); +function removeNonChars(variableName) { + return variableName.replace(/^\W+|\W+$/g, "").split(/,/); } -const PATHS = ["/app", "/app/hook/config", "/app/installations", "/app/installations/{installation_id}", "/app/installations/{installation_id}/access_tokens", "/app/installations/{installation_id}/suspended", "/marketplace_listing/accounts/{account_id}", "/marketplace_listing/plan", "/marketplace_listing/plans", "/marketplace_listing/plans/{plan_id}/accounts", "/marketplace_listing/stubbed/accounts/{account_id}", "/marketplace_listing/stubbed/plan", "/marketplace_listing/stubbed/plans", "/marketplace_listing/stubbed/plans/{plan_id}/accounts", "/orgs/{org}/installation", "/repos/{owner}/{repo}/installation", "/users/{username}/installation"]; // CREDIT: Simon Grondin (https://github.com/SGrondin) -// https://github.com/octokit/plugin-throttling.js/blob/45c5d7f13b8af448a9dbca468d9c9150a73b3948/lib/route-matcher.js +function extractUrlVariableNames(url) { + const matches = url.match(urlVariableRegex); -function routeMatcher(paths) { - // EXAMPLE. For the following paths: + if (!matches) { + return []; + } - /* [ - "/orgs/{org}/invitations", - "/repos/{owner}/{repo}/collaborators/{username}" - ] */ - const regexes = paths.map(p => p.split("/").map(c => c.startsWith("{") ? "(?:.+?)" : c).join("/")); // 'regexes' would contain: + return matches.map(removeNonChars).reduce((a, b) => a.concat(b), []); +} - /* [ - '/orgs/(?:.+?)/invitations', - '/repos/(?:.+?)/(?:.+?)/collaborators/(?:.+?)' - ] */ +function omit(object, keysToOmit) { + return Object.keys(object).filter(option => !keysToOmit.includes(option)).reduce((obj, key) => { + obj[key] = object[key]; + return obj; + }, {}); +} - const regex = `^(?:${regexes.map(r => `(?:${r})`).join("|")})[^/]*$`; // 'regex' would contain: +// Based on https://github.com/bramstein/url-template, licensed under BSD +// TODO: create separate package. +// +// Copyright (c) 2012-2014, Bram Stein +// All rights reserved. +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// 1. Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// 2. Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// 3. The name of the author may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED +// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO +// EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, +// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, +// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - /* - ^(?:(?:\/orgs\/(?:.+?)\/invitations)|(?:\/repos\/(?:.+?)\/(?:.+?)\/collaborators\/(?:.+?)))[^\/]*$ - It may look scary, but paste it into https://www.debuggex.com/ - and it will make a lot more sense! - */ +/* istanbul ignore file */ +function encodeReserved(str) { + return str.split(/(%[0-9A-Fa-f]{2})/g).map(function (part) { + if (!/%[0-9A-Fa-f]/.test(part)) { + part = encodeURI(part).replace(/%5B/g, "[").replace(/%5D/g, "]"); + } - return new RegExp(regex, "i"); + return part; + }).join(""); } -const REGEX = routeMatcher(PATHS); -function requiresAppAuth(url) { - return !!url && REGEX.test(url); +function encodeUnreserved(str) { + return encodeURIComponent(str).replace(/[!'()*]/g, function (c) { + return "%" + c.charCodeAt(0).toString(16).toUpperCase(); + }); } -const FIVE_SECONDS_IN_MS = 5 * 1000; +function encodeValue(operator, value, key) { + value = operator === "+" || operator === "#" ? encodeReserved(value) : encodeUnreserved(value); -function isNotTimeSkewError(error) { - return !(error.message.match(/'Expiration time' claim \('exp'\) must be a numeric value representing the future time at which the assertion expires/) || error.message.match(/'Issued at' claim \('iat'\) must be an Integer representing the time that the assertion was issued/)); + if (key) { + return encodeUnreserved(key) + "=" + value; + } else { + return value; + } } -async function hook(state, request, route, parameters) { - let endpoint = request.endpoint.merge(route, parameters); +function isDefined(value) { + return value !== undefined && value !== null; +} - if (requiresAppAuth(endpoint.url.replace(request.endpoint.DEFAULTS.baseUrl, ""))) { - const { - token - } = await getAppAuthentication(state); - endpoint.headers.authorization = `bearer ${token}`; - let response; +function isKeyOperator(operator) { + return operator === ";" || operator === "&" || operator === "?"; +} - try { - response = await request(endpoint); - } catch (error) { - // If there's an issue with the expiration, regenerate the token and try again. - // Otherwise rethrow the error for upstream handling. - if (isNotTimeSkewError(error)) { - throw error; - } // If the date header is missing, we can't correct the system time skew. - // Throw the error to be handled upstream. +function getValues(context, operator, key, modifier) { + var value = context[key], + result = []; + if (isDefined(value) && value !== "") { + if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") { + value = value.toString(); - if (typeof error.headers.date === "undefined") { - throw error; + if (modifier && modifier !== "*") { + value = value.substring(0, parseInt(modifier, 10)); } - const diff = Math.floor((Date.parse(error.headers.date) - Date.parse(new Date().toString())) / 1000); - state.log.warn(error.message); - state.log.warn(`[@octokit/auth-app] GitHub API time and system time are different by ${diff} seconds. Retrying request with the difference accounted for.`); - const { - token - } = await getAppAuthentication(_objectSpread2(_objectSpread2({}, state), {}, { - timeDifference: diff - })); - endpoint.headers.authorization = `bearer ${token}`; - return request(endpoint); - } + result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : "")); + } else { + if (modifier === "*") { + if (Array.isArray(value)) { + value.filter(isDefined).forEach(function (value) { + result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : "")); + }); + } else { + Object.keys(value).forEach(function (k) { + if (isDefined(value[k])) { + result.push(encodeValue(operator, value[k], k)); + } + }); + } + } else { + const tmp = []; - return response; + if (Array.isArray(value)) { + value.filter(isDefined).forEach(function (value) { + tmp.push(encodeValue(operator, value)); + }); + } else { + Object.keys(value).forEach(function (k) { + if (isDefined(value[k])) { + tmp.push(encodeUnreserved(k)); + tmp.push(encodeValue(operator, value[k].toString())); + } + }); + } + + if (isKeyOperator(operator)) { + result.push(encodeUnreserved(key) + "=" + tmp.join(",")); + } else if (tmp.length !== 0) { + result.push(tmp.join(",")); + } + } + } + } else { + if (operator === ";") { + if (isDefined(value)) { + result.push(encodeUnreserved(key)); + } + } else if (value === "" && (operator === "&" || operator === "?")) { + result.push(encodeUnreserved(key) + "="); + } else if (value === "") { + result.push(""); + } } - const { - token, - createdAt - } = await getInstallationAuthentication(state, {}, request); - endpoint.headers.authorization = `token ${token}`; - return sendRequestWithRetries(state, request, endpoint, createdAt); + return result; } -/** - * Newly created tokens might not be accessible immediately after creation. - * In case of a 401 response, we retry with an exponential delay until more - * than five seconds pass since the creation of the token. - * - * @see https://github.com/octokit/auth-app.js/issues/65 - */ -async function sendRequestWithRetries(state, request, options, createdAt, retries = 0) { - const timeSinceTokenCreationInMs = +new Date() - +new Date(createdAt); +function parseUrl(template) { + return { + expand: expand.bind(null, template) + }; +} - try { - return await request(options); - } catch (error) { - if (error.status !== 401) { - throw error; - } +function expand(template, context) { + var operators = ["+", "#", ".", "/", ";", "?", "&"]; + return template.replace(/\{([^\{\}]+)\}|([^\{\}]+)/g, function (_, expression, literal) { + if (expression) { + let operator = ""; + const values = []; - if (timeSinceTokenCreationInMs >= FIVE_SECONDS_IN_MS) { - if (retries > 0) { - error.message = `After ${retries} retries within ${timeSinceTokenCreationInMs / 1000}s of creating the installation access token, the response remains 401. At this point, the cause may be an authentication problem or a system outage. Please check https://www.githubstatus.com for status information`; + if (operators.indexOf(expression.charAt(0)) !== -1) { + operator = expression.charAt(0); + expression = expression.substr(1); } - throw error; - } + expression.split(/,/g).forEach(function (variable) { + var tmp = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable); + values.push(getValues(context, operator, tmp[1], tmp[2] || tmp[3])); + }); - ++retries; - const awaitTime = retries * 1000; - state.log.warn(`[@octokit/auth-app] Retrying after 401 response to account for token replication delay (retry: ${retries}, wait: ${awaitTime / 1000}s)`); - await new Promise(resolve => setTimeout(resolve, awaitTime)); - return sendRequestWithRetries(state, request, options, createdAt, retries); - } + if (operator && operator !== "+") { + var separator = ","; + + if (operator === "?") { + separator = "&"; + } else if (operator !== "#") { + separator = operator; + } + + return (values.length !== 0 ? operator : "") + values.join(separator); + } else { + return values.join(","); + } + } else { + return encodeReserved(literal); + } + }); } -const VERSION = "2.10.5"; +function parse(options) { + // https://fetch.spec.whatwg.org/#methods + let method = options.method.toUpperCase(); // replace :varname with {varname} to make it RFC 6570 compatible -const createAppAuth = function createAppAuth(options) { - const log = Object.assign({ - warn: console.warn.bind(console) - }, options.log); + let url = (options.url || "/").replace(/:([a-z]\w+)/g, "{$1}"); + let headers = Object.assign({}, options.headers); + let body; + let parameters = omit(options, ["method", "baseUrl", "url", "headers", "request", "mediaType"]); // extract variable names from URL to calculate remaining variables later - if ("id" in options) { - log.warn(new deprecation.Deprecation('[@octokit/auth-app] "createAppAuth({ id })" is deprecated, use "createAppAuth({ appId })" instead')); + const urlVariableNames = extractUrlVariableNames(url); + url = parseUrl(url).expand(parameters); + + if (!/^http/.test(url)) { + url = options.baseUrl + url; } - const state = Object.assign({ - request: request.request.defaults({ - headers: { - "user-agent": `octokit-auth-app.js/${VERSION} ${universalUserAgent.getUserAgent()}` - } - }), - cache: getCache() - }, options, { - appId: Number("appId" in options ? options.appId : options.id) - }, options.installationId ? { - installationId: Number(options.installationId) - } : {}, { - log - }); - return Object.assign(auth.bind(null, state), { - hook: hook.bind(null, state) - }); -}; + const omittedParameters = Object.keys(options).filter(option => urlVariableNames.includes(option)).concat("baseUrl"); + const remainingParameters = omit(parameters, omittedParameters); + const isBinaryRequest = /application\/octet-stream/i.test(headers.accept); -exports.createAppAuth = createAppAuth; -//# sourceMappingURL=index.js.map + if (!isBinaryRequest) { + if (options.mediaType.format) { + // e.g. application/vnd.github.v3+json => application/vnd.github.v3.raw + headers.accept = headers.accept.split(/,/).map(preview => preview.replace(/application\/vnd(\.\w+)(\.v3)?(\.\w+)?(\+json)?$/, `application/vnd$1$2.${options.mediaType.format}`)).join(","); + } + if (options.mediaType.previews.length) { + const previewsFromAcceptHeader = headers.accept.match(/[\w-]+(?=-preview)/g) || []; + headers.accept = previewsFromAcceptHeader.concat(options.mediaType.previews).map(preview => { + const format = options.mediaType.format ? `.${options.mediaType.format}` : "+json"; + return `application/vnd.github.${preview}-preview${format}`; + }).join(","); + } + } // for GET/HEAD requests, set URL query parameters from remaining parameters + // for PATCH/POST/PUT/DELETE requests, set request body from remaining parameters -/***/ }), -/***/ 40334: -/***/ ((__unused_webpack_module, exports) => { + if (["GET", "HEAD"].includes(method)) { + url = addQueryParameters(url, remainingParameters); + } else { + if ("data" in remainingParameters) { + body = remainingParameters.data; + } else { + if (Object.keys(remainingParameters).length) { + body = remainingParameters; + } else { + headers["content-length"] = 0; + } + } + } // default content-type for JSON if body is set -"use strict"; + if (!headers["content-type"] && typeof body !== "undefined") { + headers["content-type"] = "application/json; charset=utf-8"; + } // GitHub expects 'content-length: 0' header for PUT/PATCH requests without body. + // fetch does not allow to set `content-length` header, but we can set body to an empty string -Object.defineProperty(exports, "__esModule", ({ value: true })); -async function auth(token) { - const tokenType = token.split(/\./).length === 3 ? "app" : /^v\d+\./.test(token) ? "installation" : "oauth"; - return { - type: "token", - token: token, - tokenType - }; + if (["PATCH", "PUT"].includes(method) && typeof body === "undefined") { + body = ""; + } // Only return body/request keys if present + + + return Object.assign({ + method, + url, + headers + }, typeof body !== "undefined" ? { + body + } : null, options.request ? { + request: options.request + } : null); } -/** - * Prefix token for usage in the Authorization header - * - * @param token OAuth token or JSON Web Token - */ -function withAuthorizationPrefix(token) { - if (token.split(/\./).length === 3) { - return `bearer ${token}`; - } - - return `token ${token}`; +function endpointWithDefaults(defaults, route, options) { + return parse(merge(defaults, route, options)); } -async function hook(token, request, route, parameters) { - const endpoint = request.endpoint.merge(route, parameters); - endpoint.headers.authorization = withAuthorizationPrefix(token); - return request(endpoint); +function withDefaults(oldDefaults, newDefaults) { + const DEFAULTS = merge(oldDefaults, newDefaults); + const endpoint = endpointWithDefaults.bind(null, DEFAULTS); + return Object.assign(endpoint, { + DEFAULTS, + defaults: withDefaults.bind(null, DEFAULTS), + merge: merge.bind(null, DEFAULTS), + parse + }); } -const createTokenAuth = function createTokenAuth(token) { - if (!token) { - throw new Error("[@octokit/auth-token] No token passed to createTokenAuth"); - } +const VERSION = "6.0.10"; - if (typeof token !== "string") { - throw new Error("[@octokit/auth-token] Token passed to createTokenAuth is not a string"); - } +const userAgent = `octokit-endpoint.js/${VERSION} ${universalUserAgent.getUserAgent()}`; // DEFAULTS has all properties set that EndpointOptions has, except url. +// So we use RequestParameters and add method as additional required property. - token = token.replace(/^(token|bearer) +/i, ""); - return Object.assign(auth.bind(null, token), { - hook: hook.bind(null, token) - }); +const DEFAULTS = { + method: "GET", + baseUrl: "https://api.github.com", + headers: { + accept: "application/vnd.github.v3+json", + "user-agent": userAgent + }, + mediaType: { + format: "", + previews: [] + } }; -exports.createTokenAuth = createTokenAuth; +const endpoint = withDefaults(null, DEFAULTS); + +exports.endpoint = endpoint; //# sourceMappingURL=index.js.map /***/ }), -/***/ 79567: -/***/ ((__unused_webpack_module, exports) => { +/***/ 88467: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -async function auth(reason) { - return { - type: "unauthenticated", - reason - }; -} +var request = __nccwpck_require__(36234); +var universalUserAgent = __nccwpck_require__(45030); -function isRateLimitError(error) { - if (error.status !== 403) { - return false; - } - /* istanbul ignore if */ +const VERSION = "4.5.8"; + +class GraphqlError extends Error { + constructor(request, response) { + const message = response.data.errors[0].message; + super(message); + Object.assign(this, response.data); + Object.assign(this, { + headers: response.headers + }); + this.name = "GraphqlError"; + this.request = request; // Maintains proper stack trace (only available on V8) + /* istanbul ignore next */ - if (!error.headers) { - return false; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } } - return error.headers["x-ratelimit-remaining"] === "0"; } -const REGEX_ABUSE_LIMIT_MESSAGE = /\babuse\b/i; -function isAbuseLimitError(error) { - if (error.status !== 403) { - return false; +const NON_VARIABLE_OPTIONS = ["method", "baseUrl", "url", "headers", "request", "query", "mediaType"]; +const GHES_V3_SUFFIX_REGEX = /\/api\/v3\/?$/; +function graphql(request, query, options) { + if (typeof query === "string" && options && "query" in options) { + return Promise.reject(new Error(`[@octokit/graphql] "query" cannot be used as variable name`)); } - return REGEX_ABUSE_LIMIT_MESSAGE.test(error.message); -} - -async function hook(reason, request, route, parameters) { - const endpoint = request.endpoint.merge(route, parameters); - return request(endpoint).catch(error => { - if (error.status === 404) { - error.message = `Not found. May be due to lack of authentication. Reason: ${reason}`; - throw error; + const parsedOptions = typeof query === "string" ? Object.assign({ + query + }, options) : query; + const requestOptions = Object.keys(parsedOptions).reduce((result, key) => { + if (NON_VARIABLE_OPTIONS.includes(key)) { + result[key] = parsedOptions[key]; + return result; } - if (isRateLimitError(error)) { - error.message = `API rate limit exceeded. This maybe caused by the lack of authentication. Reason: ${reason}`; - throw error; + if (!result.variables) { + result.variables = {}; } - if (isAbuseLimitError(error)) { - error.message = `You have triggered an abuse detection mechanism. This maybe caused by the lack of authentication. Reason: ${reason}`; - throw error; - } + result.variables[key] = parsedOptions[key]; + return result; + }, {}); // workaround for GitHub Enterprise baseUrl set with /api/v3 suffix + // https://github.com/octokit/auth-app.js/issues/111#issuecomment-657610451 - if (error.status === 401) { - error.message = `Unauthorized. "${endpoint.method} ${endpoint.url}" failed most likely due to lack of authentication. Reason: ${reason}`; - throw error; - } + const baseUrl = parsedOptions.baseUrl || request.endpoint.DEFAULTS.baseUrl; - if (error.status >= 400 && error.status < 500) { - error.message = error.message.replace(/\.?$/, `. May be caused by lack of authentication (${reason}).`); + if (GHES_V3_SUFFIX_REGEX.test(baseUrl)) { + requestOptions.url = baseUrl.replace(GHES_V3_SUFFIX_REGEX, "/api/graphql"); + } + + return request(requestOptions).then(response => { + if (response.data.errors) { + const headers = {}; + + for (const key of Object.keys(response.headers)) { + headers[key] = response.headers[key]; + } + + throw new GraphqlError(requestOptions, { + headers, + data: response.data + }); } - throw error; + return response.data.data; }); } -const createUnauthenticatedAuth = function createUnauthenticatedAuth(options) { - if (!options || !options.reason) { - throw new Error("[@octokit/auth-unauthenticated] No reason passed to createUnauthenticatedAuth"); - } +function withDefaults(request$1, newDefaults) { + const newRequest = request$1.defaults(newDefaults); - return Object.assign(auth.bind(null, options.reason), { - hook: hook.bind(null, options.reason) + const newApi = (query, options) => { + return graphql(newRequest, query, options); + }; + + return Object.assign(newApi, { + defaults: withDefaults.bind(null, newRequest), + endpoint: request.request.endpoint }); -}; +} -exports.createUnauthenticatedAuth = createUnauthenticatedAuth; +const graphql$1 = withDefaults(request.request, { + headers: { + "user-agent": `octokit-graphql.js/${VERSION} ${universalUserAgent.getUserAgent()}` + }, + method: "POST", + url: "/graphql" +}); +function withCustomRequest(customRequest) { + return withDefaults(customRequest, { + method: "POST", + url: "/graphql" + }); +} + +exports.graphql = graphql$1; +exports.withCustomRequest = withCustomRequest; //# sourceMappingURL=index.js.map /***/ }), -/***/ 76762: +/***/ 25823: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -12223,929 +4032,1364 @@ exports.createUnauthenticatedAuth = createUnauthenticatedAuth; Object.defineProperty(exports, "__esModule", ({ value: true })); -var universalUserAgent = __nccwpck_require__(45030); -var beforeAfterHook = __nccwpck_require__(83682); -var request = __nccwpck_require__(36234); -var graphql = __nccwpck_require__(88467); -var authToken = __nccwpck_require__(40334); +var requestError = __nccwpck_require__(10537); -function _objectWithoutPropertiesLoose(source, excluded) { - if (source == null) return {}; - var target = {}; - var sourceKeys = Object.keys(source); - var key, i; +const VERSION = "1.2.8"; - for (i = 0; i < sourceKeys.length; i++) { - key = sourceKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - target[key] = source[key]; +function isIssueLabelsUpdateOrReplace({ + method, + url +}) { + if (!["POST", "PUT"].includes(method)) { + return false; } - return target; -} - -function _objectWithoutProperties(source, excluded) { - if (source == null) return {}; - - var target = _objectWithoutPropertiesLoose(source, excluded); - - var key, i; - - if (Object.getOwnPropertySymbols) { - var sourceSymbolKeys = Object.getOwnPropertySymbols(source); - - for (i = 0; i < sourceSymbolKeys.length; i++) { - key = sourceSymbolKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; - target[key] = source[key]; - } + if (!/\/repos\/[^/]+\/[^/]+\/issues\/[^/]+\/labels/.test(url)) { + return false; } - return target; + return true; } -const VERSION = "3.2.4"; - -class Octokit { - constructor(options = {}) { - const hook = new beforeAfterHook.Collection(); - const requestDefaults = { - baseUrl: request.request.endpoint.DEFAULTS.baseUrl, - headers: {}, - request: Object.assign({}, options.request, { - hook: hook.bind(null, "request") - }), - mediaType: { - previews: [], - format: "" - } - }; // prepend default user agent with `options.userAgent` if set - - requestDefaults.headers["user-agent"] = [options.userAgent, `octokit-core.js/${VERSION} ${universalUserAgent.getUserAgent()}`].filter(Boolean).join(" "); - - if (options.baseUrl) { - requestDefaults.baseUrl = options.baseUrl; - } - - if (options.previews) { - requestDefaults.mediaType.previews = options.previews; - } - - if (options.timeZone) { - requestDefaults.headers["time-zone"] = options.timeZone; - } - - this.request = request.request.defaults(requestDefaults); - this.graphql = graphql.withCustomRequest(this.request).defaults(requestDefaults); - this.log = Object.assign({ - debug: () => {}, - info: () => {}, - warn: console.warn.bind(console), - error: console.error.bind(console) - }, options.log); - this.hook = hook; // (1) If neither `options.authStrategy` nor `options.auth` are set, the `octokit` instance - // is unauthenticated. The `this.auth()` method is a no-op and no request hook is registered. - // (2) If only `options.auth` is set, use the default token authentication strategy. - // (3) If `options.authStrategy` is set then use it and pass in `options.auth`. Always pass own request as many strategies accept a custom request instance. - // TODO: type `options.auth` based on `options.authStrategy`. +function enterpriseCompatibility(octokit) { + octokit.hook.wrap("request", async (request, options) => { + // see https://github.com/octokit/rest.js/blob/15.x/lib/routes.json#L3046-L3068 + if (isIssueLabelsUpdateOrReplace(options)) { + options.data = options.labels; + delete options.labels; // for @octokit/rest v16.x, remove validation of labels option - if (!options.authStrategy) { - if (!options.auth) { - // (1) - this.auth = async () => ({ - type: "unauthenticated" - }); - } else { - // (2) - const auth = authToken.createTokenAuth(options.auth); // @ts-ignore ¯\_(ツ)_/¯ + /* istanbul ignore if */ - hook.wrap("request", auth.hook); - this.auth = auth; + if (options.request.validate) { + delete options.request.validate.labels; } - } else { - const { - authStrategy - } = options, - otherOptions = _objectWithoutProperties(options, ["authStrategy"]); - - const auth = authStrategy(Object.assign({ - request: this.request, - log: this.log, - // we pass the current octokit instance as well as its constructor options - // to allow for authentication strategies that return a new octokit instance - // that shares the same internal state as the current one. The original - // requirement for this was the "event-octokit" authentication strategy - // of https://github.com/probot/octokit-auth-probot. - octokit: this, - octokitOptions: otherOptions - }, options.auth)); // @ts-ignore ¯\_(ツ)_/¯ - - hook.wrap("request", auth.hook); - this.auth = auth; - } // apply plugins - // https://stackoverflow.com/a/16345172 + return request(options); + } // TODO: implement fix for #62 here + // https://github.com/octokit/plugin-enterprise-compatibility.js/issues/60 - const classConstructor = this.constructor; - classConstructor.plugins.forEach(plugin => { - Object.assign(this, plugin(this, options)); - }); - } - static defaults(defaults) { - const OctokitWithDefaults = class extends this { - constructor(...args) { - const options = args[0] || {}; + if (/\/orgs\/[^/]+\/teams/.test(options.url)) { + try { + return await request(options); + } catch (error) { + if (error.status !== 404) { + throw error; + } - if (typeof defaults === "function") { - super(defaults(options)); - return; + if (!error.headers || !error.headers["x-github-enterprise-version"]) { + throw error; } - super(Object.assign({}, defaults, options, options.userAgent && defaults.userAgent ? { - userAgent: `${options.userAgent} ${defaults.userAgent}` - } : null)); + const deprecatedUrl = options.url.replace(/\/orgs\/[^/]+\/teams\/[^/]+/, "/teams/{team_id}"); + throw new requestError.RequestError(`"${options.method} ${options.url}" is not supported in your GitHub Enterprise Server version. Please replace with octokit.request("${options.method} ${deprecatedUrl}", { team_id })`, 404, { + request: options + }); } + } - }; - return OctokitWithDefaults; - } - /** - * Attach a plugin (or many) to your Octokit instance. - * - * @example - * const API = Octokit.plugin(plugin1, plugin2, plugin3, ...) - */ - - - static plugin(...newPlugins) { - var _a; - - const currentPlugins = this.plugins; - const NewOctokit = (_a = class extends this {}, _a.plugins = currentPlugins.concat(newPlugins.filter(plugin => !currentPlugins.includes(plugin))), _a); - return NewOctokit; - } - + return request(options); + }); } -Octokit.VERSION = VERSION; -Octokit.plugins = []; +enterpriseCompatibility.VERSION = VERSION; -exports.Octokit = Octokit; +exports.enterpriseCompatibility = enterpriseCompatibility; //# sourceMappingURL=index.js.map /***/ }), -/***/ 59440: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 64193: +/***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -var isPlainObject = __nccwpck_require__(63287); -var universalUserAgent = __nccwpck_require__(45030); +const VERSION = "2.6.2"; -function lowercaseKeys(object) { - if (!object) { - return {}; - } +/** + * Some “list” response that can be paginated have a different response structure + * + * They have a `total_count` key in the response (search also has `incomplete_results`, + * /installation/repositories also has `repository_selection`), as well as a key with + * the list of the items which name varies from endpoint to endpoint. + * + * Octokit normalizes these responses so that paginated results are always returned following + * the same structure. One challenge is that if the list response has only one page, no Link + * header is provided, so this header alone is not sufficient to check wether a response is + * paginated or not. + * + * We check if a "total_count" key is present in the response data, but also make sure that + * a "url" property is not, as the "Get the combined status for a specific ref" endpoint would + * otherwise match: https://developer.github.com/v3/repos/statuses/#get-the-combined-status-for-a-specific-ref + */ +function normalizePaginatedListResponse(response) { + const responseNeedsNormalization = "total_count" in response.data && !("url" in response.data); + if (!responseNeedsNormalization) return response; // keep the additional properties intact as there is currently no other way + // to retrieve the same information. - return Object.keys(object).reduce((newObj, key) => { - newObj[key.toLowerCase()] = object[key]; - return newObj; - }, {}); -} + const incompleteResults = response.data.incomplete_results; + const repositorySelection = response.data.repository_selection; + const totalCount = response.data.total_count; + delete response.data.incomplete_results; + delete response.data.repository_selection; + delete response.data.total_count; + const namespaceKey = Object.keys(response.data)[0]; + const data = response.data[namespaceKey]; + response.data = data; -function mergeDeep(defaults, options) { - const result = Object.assign({}, defaults); - Object.keys(options).forEach(key => { - if (isPlainObject.isPlainObject(options[key])) { - if (!(key in defaults)) Object.assign(result, { - [key]: options[key] - });else result[key] = mergeDeep(defaults[key], options[key]); - } else { - Object.assign(result, { - [key]: options[key] - }); - } - }); - return result; -} + if (typeof incompleteResults !== "undefined") { + response.data.incomplete_results = incompleteResults; + } -function removeUndefinedProperties(obj) { - for (const key in obj) { - if (obj[key] === undefined) { - delete obj[key]; - } + if (typeof repositorySelection !== "undefined") { + response.data.repository_selection = repositorySelection; } - return obj; + response.data.total_count = totalCount; + return response; } -function merge(defaults, route, options) { - if (typeof route === "string") { - let [method, url] = route.split(" "); - options = Object.assign(url ? { - method, - url - } : { - url: method - }, options); - } else { - options = Object.assign({}, route); - } // lowercase header names before merging with defaults to avoid duplicates - +function iterator(octokit, route, parameters) { + const options = typeof route === "function" ? route.endpoint(parameters) : octokit.request.endpoint(route, parameters); + const requestMethod = typeof route === "function" ? route : octokit.request; + const method = options.method; + const headers = options.headers; + let url = options.url; + return { + [Symbol.asyncIterator]: () => ({ + async next() { + if (!url) return { + done: true + }; + const response = await requestMethod({ + method, + url, + headers + }); + const normalizedResponse = normalizePaginatedListResponse(response); // `response.headers.link` format: + // '; rel="next", ; rel="last"' + // sets `url` to undefined if "next" URL is not present or `link` header is not set - options.headers = lowercaseKeys(options.headers); // remove properties with undefined values before merging + url = ((normalizedResponse.headers.link || "").match(/<([^>]+)>;\s*rel="next"/) || [])[1]; + return { + value: normalizedResponse + }; + } - removeUndefinedProperties(options); - removeUndefinedProperties(options.headers); - const mergedOptions = mergeDeep(defaults || {}, options); // mediaType.previews arrays are merged, instead of overwritten + }) + }; +} - if (defaults && defaults.mediaType.previews.length) { - mergedOptions.mediaType.previews = defaults.mediaType.previews.filter(preview => !mergedOptions.mediaType.previews.includes(preview)).concat(mergedOptions.mediaType.previews); +function paginate(octokit, route, parameters, mapFn) { + if (typeof parameters === "function") { + mapFn = parameters; + parameters = undefined; } - mergedOptions.mediaType.previews = mergedOptions.mediaType.previews.map(preview => preview.replace(/-preview/, "")); - return mergedOptions; -} + return gather(octokit, [], iterator(octokit, route, parameters)[Symbol.asyncIterator](), mapFn); +} + +function gather(octokit, results, iterator, mapFn) { + return iterator.next().then(result => { + if (result.done) { + return results; + } + + let earlyExit = false; -function addQueryParameters(url, parameters) { - const separator = /\?/.test(url) ? "&" : "?"; - const names = Object.keys(parameters); + function done() { + earlyExit = true; + } - if (names.length === 0) { - return url; - } + results = results.concat(mapFn ? mapFn(result.value, done) : result.value.data); - return url + separator + names.map(name => { - if (name === "q") { - return "q=" + parameters.q.split("+").map(encodeURIComponent).join("+"); + if (earlyExit) { + return results; } - return `${name}=${encodeURIComponent(parameters[name])}`; - }).join("&"); + return gather(octokit, results, iterator, mapFn); + }); } -const urlVariableRegex = /\{[^}]+\}/g; +const composePaginateRest = Object.assign(paginate, { + iterator +}); -function removeNonChars(variableName) { - return variableName.replace(/^\W+|\W+$/g, "").split(/,/); +/** + * @param octokit Octokit instance + * @param options Options passed to Octokit constructor + */ + +function paginateRest(octokit) { + return { + paginate: Object.assign(paginate.bind(null, octokit), { + iterator: iterator.bind(null, octokit) + }) + }; } +paginateRest.VERSION = VERSION; -function extractUrlVariableNames(url) { - const matches = url.match(urlVariableRegex); +exports.composePaginateRest = composePaginateRest; +exports.paginateRest = paginateRest; +//# sourceMappingURL=index.js.map - if (!matches) { - return []; - } - return matches.map(removeNonChars).reduce((a, b) => a.concat(b), []); -} +/***/ }), -function omit(object, keysToOmit) { - return Object.keys(object).filter(option => !keysToOmit.includes(option)).reduce((obj, key) => { - obj[key] = object[key]; - return obj; - }, {}); -} +/***/ 83044: +/***/ ((__unused_webpack_module, exports) => { -// Based on https://github.com/bramstein/url-template, licensed under BSD -// TODO: create separate package. -// -// Copyright (c) 2012-2014, Bram Stein -// All rights reserved. -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions -// are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. The name of the author may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED -// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO -// EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, -// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, -// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY -// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, -// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +"use strict"; -/* istanbul ignore file */ -function encodeReserved(str) { - return str.split(/(%[0-9A-Fa-f]{2})/g).map(function (part) { - if (!/%[0-9A-Fa-f]/.test(part)) { - part = encodeURI(part).replace(/%5B/g, "[").replace(/%5D/g, "]"); - } - return part; - }).join(""); -} +Object.defineProperty(exports, "__esModule", ({ value: true })); -function encodeUnreserved(str) { - return encodeURIComponent(str).replace(/[!'()*]/g, function (c) { - return "%" + c.charCodeAt(0).toString(16).toUpperCase(); - }); -} +function ownKeys(object, enumerableOnly) { + var keys = Object.keys(object); -function encodeValue(operator, value, key) { - value = operator === "+" || operator === "#" ? encodeReserved(value) : encodeUnreserved(value); + if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(object); - if (key) { - return encodeUnreserved(key) + "=" + value; - } else { - return value; - } -} + if (enumerableOnly) { + symbols = symbols.filter(function (sym) { + return Object.getOwnPropertyDescriptor(object, sym).enumerable; + }); + } -function isDefined(value) { - return value !== undefined && value !== null; -} + keys.push.apply(keys, symbols); + } -function isKeyOperator(operator) { - return operator === ";" || operator === "&" || operator === "?"; + return keys; } -function getValues(context, operator, key, modifier) { - var value = context[key], - result = []; +function _objectSpread2(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i] != null ? arguments[i] : {}; - if (isDefined(value) && value !== "") { - if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") { - value = value.toString(); + if (i % 2) { + ownKeys(Object(source), true).forEach(function (key) { + _defineProperty(target, key, source[key]); + }); + } else if (Object.getOwnPropertyDescriptors) { + Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); + } else { + ownKeys(Object(source)).forEach(function (key) { + Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); + }); + } + } - if (modifier && modifier !== "*") { - value = value.substring(0, parseInt(modifier, 10)); - } + return target; +} - result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : "")); - } else { - if (modifier === "*") { - if (Array.isArray(value)) { - value.filter(isDefined).forEach(function (value) { - result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : "")); - }); - } else { - Object.keys(value).forEach(function (k) { - if (isDefined(value[k])) { - result.push(encodeValue(operator, value[k], k)); - } - }); - } - } else { - const tmp = []; +function _defineProperty(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } - if (Array.isArray(value)) { - value.filter(isDefined).forEach(function (value) { - tmp.push(encodeValue(operator, value)); - }); - } else { - Object.keys(value).forEach(function (k) { - if (isDefined(value[k])) { - tmp.push(encodeUnreserved(k)); - tmp.push(encodeValue(operator, value[k].toString())); - } - }); - } + return obj; +} - if (isKeyOperator(operator)) { - result.push(encodeUnreserved(key) + "=" + tmp.join(",")); - } else if (tmp.length !== 0) { - result.push(tmp.join(",")); - } +const Endpoints = { + actions: { + addSelectedRepoToOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}"], + approveWorkflowRun: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/approve"], + cancelWorkflowRun: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/cancel"], + createOrUpdateEnvironmentSecret: ["PUT /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}"], + createOrUpdateOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}"], + createOrUpdateRepoSecret: ["PUT /repos/{owner}/{repo}/actions/secrets/{secret_name}"], + createRegistrationTokenForOrg: ["POST /orgs/{org}/actions/runners/registration-token"], + createRegistrationTokenForRepo: ["POST /repos/{owner}/{repo}/actions/runners/registration-token"], + createRemoveTokenForOrg: ["POST /orgs/{org}/actions/runners/remove-token"], + createRemoveTokenForRepo: ["POST /repos/{owner}/{repo}/actions/runners/remove-token"], + createWorkflowDispatch: ["POST /repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches"], + deleteArtifact: ["DELETE /repos/{owner}/{repo}/actions/artifacts/{artifact_id}"], + deleteEnvironmentSecret: ["DELETE /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}"], + deleteOrgSecret: ["DELETE /orgs/{org}/actions/secrets/{secret_name}"], + deleteRepoSecret: ["DELETE /repos/{owner}/{repo}/actions/secrets/{secret_name}"], + deleteSelfHostedRunnerFromOrg: ["DELETE /orgs/{org}/actions/runners/{runner_id}"], + deleteSelfHostedRunnerFromRepo: ["DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}"], + deleteWorkflowRun: ["DELETE /repos/{owner}/{repo}/actions/runs/{run_id}"], + deleteWorkflowRunLogs: ["DELETE /repos/{owner}/{repo}/actions/runs/{run_id}/logs"], + disableSelectedRepositoryGithubActionsOrganization: ["DELETE /orgs/{org}/actions/permissions/repositories/{repository_id}"], + disableWorkflow: ["PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/disable"], + downloadArtifact: ["GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}/{archive_format}"], + downloadJobLogsForWorkflowRun: ["GET /repos/{owner}/{repo}/actions/jobs/{job_id}/logs"], + downloadWorkflowRunAttemptLogs: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/logs"], + downloadWorkflowRunLogs: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/logs"], + enableSelectedRepositoryGithubActionsOrganization: ["PUT /orgs/{org}/actions/permissions/repositories/{repository_id}"], + enableWorkflow: ["PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/enable"], + getAllowedActionsOrganization: ["GET /orgs/{org}/actions/permissions/selected-actions"], + getAllowedActionsRepository: ["GET /repos/{owner}/{repo}/actions/permissions/selected-actions"], + getArtifact: ["GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}"], + getEnvironmentPublicKey: ["GET /repositories/{repository_id}/environments/{environment_name}/secrets/public-key"], + getEnvironmentSecret: ["GET /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}"], + getGithubActionsPermissionsOrganization: ["GET /orgs/{org}/actions/permissions"], + getGithubActionsPermissionsRepository: ["GET /repos/{owner}/{repo}/actions/permissions"], + getJobForWorkflowRun: ["GET /repos/{owner}/{repo}/actions/jobs/{job_id}"], + getOrgPublicKey: ["GET /orgs/{org}/actions/secrets/public-key"], + getOrgSecret: ["GET /orgs/{org}/actions/secrets/{secret_name}"], + getPendingDeploymentsForRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments"], + getRepoPermissions: ["GET /repos/{owner}/{repo}/actions/permissions", {}, { + renamed: ["actions", "getGithubActionsPermissionsRepository"] + }], + getRepoPublicKey: ["GET /repos/{owner}/{repo}/actions/secrets/public-key"], + getRepoSecret: ["GET /repos/{owner}/{repo}/actions/secrets/{secret_name}"], + getReviewsForRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/approvals"], + getSelfHostedRunnerForOrg: ["GET /orgs/{org}/actions/runners/{runner_id}"], + getSelfHostedRunnerForRepo: ["GET /repos/{owner}/{repo}/actions/runners/{runner_id}"], + getWorkflow: ["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}"], + getWorkflowRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}"], + getWorkflowRunAttempt: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}"], + getWorkflowRunUsage: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/timing"], + getWorkflowUsage: ["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/timing"], + listArtifactsForRepo: ["GET /repos/{owner}/{repo}/actions/artifacts"], + listEnvironmentSecrets: ["GET /repositories/{repository_id}/environments/{environment_name}/secrets"], + listJobsForWorkflowRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs"], + listJobsForWorkflowRunAttempt: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs"], + listOrgSecrets: ["GET /orgs/{org}/actions/secrets"], + listRepoSecrets: ["GET /repos/{owner}/{repo}/actions/secrets"], + listRepoWorkflows: ["GET /repos/{owner}/{repo}/actions/workflows"], + listRunnerApplicationsForOrg: ["GET /orgs/{org}/actions/runners/downloads"], + listRunnerApplicationsForRepo: ["GET /repos/{owner}/{repo}/actions/runners/downloads"], + listSelectedReposForOrgSecret: ["GET /orgs/{org}/actions/secrets/{secret_name}/repositories"], + listSelectedRepositoriesEnabledGithubActionsOrganization: ["GET /orgs/{org}/actions/permissions/repositories"], + listSelfHostedRunnersForOrg: ["GET /orgs/{org}/actions/runners"], + listSelfHostedRunnersForRepo: ["GET /repos/{owner}/{repo}/actions/runners"], + listWorkflowRunArtifacts: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts"], + listWorkflowRuns: ["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs"], + listWorkflowRunsForRepo: ["GET /repos/{owner}/{repo}/actions/runs"], + removeSelectedRepoFromOrgSecret: ["DELETE /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}"], + reviewPendingDeploymentsForRun: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments"], + setAllowedActionsOrganization: ["PUT /orgs/{org}/actions/permissions/selected-actions"], + setAllowedActionsRepository: ["PUT /repos/{owner}/{repo}/actions/permissions/selected-actions"], + setGithubActionsPermissionsOrganization: ["PUT /orgs/{org}/actions/permissions"], + setGithubActionsPermissionsRepository: ["PUT /repos/{owner}/{repo}/actions/permissions"], + setSelectedReposForOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}/repositories"], + setSelectedRepositoriesEnabledGithubActionsOrganization: ["PUT /orgs/{org}/actions/permissions/repositories"] + }, + activity: { + checkRepoIsStarredByAuthenticatedUser: ["GET /user/starred/{owner}/{repo}"], + deleteRepoSubscription: ["DELETE /repos/{owner}/{repo}/subscription"], + deleteThreadSubscription: ["DELETE /notifications/threads/{thread_id}/subscription"], + getFeeds: ["GET /feeds"], + getRepoSubscription: ["GET /repos/{owner}/{repo}/subscription"], + getThread: ["GET /notifications/threads/{thread_id}"], + getThreadSubscriptionForAuthenticatedUser: ["GET /notifications/threads/{thread_id}/subscription"], + listEventsForAuthenticatedUser: ["GET /users/{username}/events"], + listNotificationsForAuthenticatedUser: ["GET /notifications"], + listOrgEventsForAuthenticatedUser: ["GET /users/{username}/events/orgs/{org}"], + listPublicEvents: ["GET /events"], + listPublicEventsForRepoNetwork: ["GET /networks/{owner}/{repo}/events"], + listPublicEventsForUser: ["GET /users/{username}/events/public"], + listPublicOrgEvents: ["GET /orgs/{org}/events"], + listReceivedEventsForUser: ["GET /users/{username}/received_events"], + listReceivedPublicEventsForUser: ["GET /users/{username}/received_events/public"], + listRepoEvents: ["GET /repos/{owner}/{repo}/events"], + listRepoNotificationsForAuthenticatedUser: ["GET /repos/{owner}/{repo}/notifications"], + listReposStarredByAuthenticatedUser: ["GET /user/starred"], + listReposStarredByUser: ["GET /users/{username}/starred"], + listReposWatchedByUser: ["GET /users/{username}/subscriptions"], + listStargazersForRepo: ["GET /repos/{owner}/{repo}/stargazers"], + listWatchedReposForAuthenticatedUser: ["GET /user/subscriptions"], + listWatchersForRepo: ["GET /repos/{owner}/{repo}/subscribers"], + markNotificationsAsRead: ["PUT /notifications"], + markRepoNotificationsAsRead: ["PUT /repos/{owner}/{repo}/notifications"], + markThreadAsRead: ["PATCH /notifications/threads/{thread_id}"], + setRepoSubscription: ["PUT /repos/{owner}/{repo}/subscription"], + setThreadSubscription: ["PUT /notifications/threads/{thread_id}/subscription"], + starRepoForAuthenticatedUser: ["PUT /user/starred/{owner}/{repo}"], + unstarRepoForAuthenticatedUser: ["DELETE /user/starred/{owner}/{repo}"] + }, + apps: { + addRepoToInstallation: ["PUT /user/installations/{installation_id}/repositories/{repository_id}", {}, { + renamed: ["apps", "addRepoToInstallationForAuthenticatedUser"] + }], + addRepoToInstallationForAuthenticatedUser: ["PUT /user/installations/{installation_id}/repositories/{repository_id}"], + checkToken: ["POST /applications/{client_id}/token"], + createContentAttachment: ["POST /content_references/{content_reference_id}/attachments", { + mediaType: { + previews: ["corsair"] } - } - } else { - if (operator === ";") { - if (isDefined(value)) { - result.push(encodeUnreserved(key)); + }], + createContentAttachmentForRepo: ["POST /repos/{owner}/{repo}/content_references/{content_reference_id}/attachments", { + mediaType: { + previews: ["corsair"] + } + }], + createFromManifest: ["POST /app-manifests/{code}/conversions"], + createInstallationAccessToken: ["POST /app/installations/{installation_id}/access_tokens"], + deleteAuthorization: ["DELETE /applications/{client_id}/grant"], + deleteInstallation: ["DELETE /app/installations/{installation_id}"], + deleteToken: ["DELETE /applications/{client_id}/token"], + getAuthenticated: ["GET /app"], + getBySlug: ["GET /apps/{app_slug}"], + getInstallation: ["GET /app/installations/{installation_id}"], + getOrgInstallation: ["GET /orgs/{org}/installation"], + getRepoInstallation: ["GET /repos/{owner}/{repo}/installation"], + getSubscriptionPlanForAccount: ["GET /marketplace_listing/accounts/{account_id}"], + getSubscriptionPlanForAccountStubbed: ["GET /marketplace_listing/stubbed/accounts/{account_id}"], + getUserInstallation: ["GET /users/{username}/installation"], + getWebhookConfigForApp: ["GET /app/hook/config"], + getWebhookDelivery: ["GET /app/hook/deliveries/{delivery_id}"], + listAccountsForPlan: ["GET /marketplace_listing/plans/{plan_id}/accounts"], + listAccountsForPlanStubbed: ["GET /marketplace_listing/stubbed/plans/{plan_id}/accounts"], + listInstallationReposForAuthenticatedUser: ["GET /user/installations/{installation_id}/repositories"], + listInstallations: ["GET /app/installations"], + listInstallationsForAuthenticatedUser: ["GET /user/installations"], + listPlans: ["GET /marketplace_listing/plans"], + listPlansStubbed: ["GET /marketplace_listing/stubbed/plans"], + listReposAccessibleToInstallation: ["GET /installation/repositories"], + listSubscriptionsForAuthenticatedUser: ["GET /user/marketplace_purchases"], + listSubscriptionsForAuthenticatedUserStubbed: ["GET /user/marketplace_purchases/stubbed"], + listWebhookDeliveries: ["GET /app/hook/deliveries"], + redeliverWebhookDelivery: ["POST /app/hook/deliveries/{delivery_id}/attempts"], + removeRepoFromInstallation: ["DELETE /user/installations/{installation_id}/repositories/{repository_id}", {}, { + renamed: ["apps", "removeRepoFromInstallationForAuthenticatedUser"] + }], + removeRepoFromInstallationForAuthenticatedUser: ["DELETE /user/installations/{installation_id}/repositories/{repository_id}"], + resetToken: ["PATCH /applications/{client_id}/token"], + revokeInstallationAccessToken: ["DELETE /installation/token"], + scopeToken: ["POST /applications/{client_id}/token/scoped"], + suspendInstallation: ["PUT /app/installations/{installation_id}/suspended"], + unsuspendInstallation: ["DELETE /app/installations/{installation_id}/suspended"], + updateWebhookConfigForApp: ["PATCH /app/hook/config"] + }, + billing: { + getGithubActionsBillingOrg: ["GET /orgs/{org}/settings/billing/actions"], + getGithubActionsBillingUser: ["GET /users/{username}/settings/billing/actions"], + getGithubPackagesBillingOrg: ["GET /orgs/{org}/settings/billing/packages"], + getGithubPackagesBillingUser: ["GET /users/{username}/settings/billing/packages"], + getSharedStorageBillingOrg: ["GET /orgs/{org}/settings/billing/shared-storage"], + getSharedStorageBillingUser: ["GET /users/{username}/settings/billing/shared-storage"] + }, + checks: { + create: ["POST /repos/{owner}/{repo}/check-runs"], + createSuite: ["POST /repos/{owner}/{repo}/check-suites"], + get: ["GET /repos/{owner}/{repo}/check-runs/{check_run_id}"], + getSuite: ["GET /repos/{owner}/{repo}/check-suites/{check_suite_id}"], + listAnnotations: ["GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations"], + listForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-runs"], + listForSuite: ["GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs"], + listSuitesForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-suites"], + rerequestRun: ["POST /repos/{owner}/{repo}/check-runs/{check_run_id}/rerequest"], + rerequestSuite: ["POST /repos/{owner}/{repo}/check-suites/{check_suite_id}/rerequest"], + setSuitesPreferences: ["PATCH /repos/{owner}/{repo}/check-suites/preferences"], + update: ["PATCH /repos/{owner}/{repo}/check-runs/{check_run_id}"] + }, + codeScanning: { + deleteAnalysis: ["DELETE /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}{?confirm_delete}"], + getAlert: ["GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}", {}, { + renamedParameters: { + alert_id: "alert_number" + } + }], + getAnalysis: ["GET /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}"], + getSarif: ["GET /repos/{owner}/{repo}/code-scanning/sarifs/{sarif_id}"], + listAlertInstances: ["GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances"], + listAlertsForRepo: ["GET /repos/{owner}/{repo}/code-scanning/alerts"], + listAlertsInstances: ["GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances", {}, { + renamed: ["codeScanning", "listAlertInstances"] + }], + listRecentAnalyses: ["GET /repos/{owner}/{repo}/code-scanning/analyses"], + updateAlert: ["PATCH /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}"], + uploadSarif: ["POST /repos/{owner}/{repo}/code-scanning/sarifs"] + }, + codesOfConduct: { + getAllCodesOfConduct: ["GET /codes_of_conduct"], + getConductCode: ["GET /codes_of_conduct/{key}"] + }, + emojis: { + get: ["GET /emojis"] + }, + enterpriseAdmin: { + disableSelectedOrganizationGithubActionsEnterprise: ["DELETE /enterprises/{enterprise}/actions/permissions/organizations/{org_id}"], + enableSelectedOrganizationGithubActionsEnterprise: ["PUT /enterprises/{enterprise}/actions/permissions/organizations/{org_id}"], + getAllowedActionsEnterprise: ["GET /enterprises/{enterprise}/actions/permissions/selected-actions"], + getGithubActionsPermissionsEnterprise: ["GET /enterprises/{enterprise}/actions/permissions"], + listSelectedOrganizationsEnabledGithubActionsEnterprise: ["GET /enterprises/{enterprise}/actions/permissions/organizations"], + setAllowedActionsEnterprise: ["PUT /enterprises/{enterprise}/actions/permissions/selected-actions"], + setGithubActionsPermissionsEnterprise: ["PUT /enterprises/{enterprise}/actions/permissions"], + setSelectedOrganizationsEnabledGithubActionsEnterprise: ["PUT /enterprises/{enterprise}/actions/permissions/organizations"] + }, + gists: { + checkIsStarred: ["GET /gists/{gist_id}/star"], + create: ["POST /gists"], + createComment: ["POST /gists/{gist_id}/comments"], + delete: ["DELETE /gists/{gist_id}"], + deleteComment: ["DELETE /gists/{gist_id}/comments/{comment_id}"], + fork: ["POST /gists/{gist_id}/forks"], + get: ["GET /gists/{gist_id}"], + getComment: ["GET /gists/{gist_id}/comments/{comment_id}"], + getRevision: ["GET /gists/{gist_id}/{sha}"], + list: ["GET /gists"], + listComments: ["GET /gists/{gist_id}/comments"], + listCommits: ["GET /gists/{gist_id}/commits"], + listForUser: ["GET /users/{username}/gists"], + listForks: ["GET /gists/{gist_id}/forks"], + listPublic: ["GET /gists/public"], + listStarred: ["GET /gists/starred"], + star: ["PUT /gists/{gist_id}/star"], + unstar: ["DELETE /gists/{gist_id}/star"], + update: ["PATCH /gists/{gist_id}"], + updateComment: ["PATCH /gists/{gist_id}/comments/{comment_id}"] + }, + git: { + createBlob: ["POST /repos/{owner}/{repo}/git/blobs"], + createCommit: ["POST /repos/{owner}/{repo}/git/commits"], + createRef: ["POST /repos/{owner}/{repo}/git/refs"], + createTag: ["POST /repos/{owner}/{repo}/git/tags"], + createTree: ["POST /repos/{owner}/{repo}/git/trees"], + deleteRef: ["DELETE /repos/{owner}/{repo}/git/refs/{ref}"], + getBlob: ["GET /repos/{owner}/{repo}/git/blobs/{file_sha}"], + getCommit: ["GET /repos/{owner}/{repo}/git/commits/{commit_sha}"], + getRef: ["GET /repos/{owner}/{repo}/git/ref/{ref}"], + getTag: ["GET /repos/{owner}/{repo}/git/tags/{tag_sha}"], + getTree: ["GET /repos/{owner}/{repo}/git/trees/{tree_sha}"], + listMatchingRefs: ["GET /repos/{owner}/{repo}/git/matching-refs/{ref}"], + updateRef: ["PATCH /repos/{owner}/{repo}/git/refs/{ref}"] + }, + gitignore: { + getAllTemplates: ["GET /gitignore/templates"], + getTemplate: ["GET /gitignore/templates/{name}"] + }, + interactions: { + getRestrictionsForAuthenticatedUser: ["GET /user/interaction-limits"], + getRestrictionsForOrg: ["GET /orgs/{org}/interaction-limits"], + getRestrictionsForRepo: ["GET /repos/{owner}/{repo}/interaction-limits"], + getRestrictionsForYourPublicRepos: ["GET /user/interaction-limits", {}, { + renamed: ["interactions", "getRestrictionsForAuthenticatedUser"] + }], + removeRestrictionsForAuthenticatedUser: ["DELETE /user/interaction-limits"], + removeRestrictionsForOrg: ["DELETE /orgs/{org}/interaction-limits"], + removeRestrictionsForRepo: ["DELETE /repos/{owner}/{repo}/interaction-limits"], + removeRestrictionsForYourPublicRepos: ["DELETE /user/interaction-limits", {}, { + renamed: ["interactions", "removeRestrictionsForAuthenticatedUser"] + }], + setRestrictionsForAuthenticatedUser: ["PUT /user/interaction-limits"], + setRestrictionsForOrg: ["PUT /orgs/{org}/interaction-limits"], + setRestrictionsForRepo: ["PUT /repos/{owner}/{repo}/interaction-limits"], + setRestrictionsForYourPublicRepos: ["PUT /user/interaction-limits", {}, { + renamed: ["interactions", "setRestrictionsForAuthenticatedUser"] + }] + }, + issues: { + addAssignees: ["POST /repos/{owner}/{repo}/issues/{issue_number}/assignees"], + addLabels: ["POST /repos/{owner}/{repo}/issues/{issue_number}/labels"], + checkUserCanBeAssigned: ["GET /repos/{owner}/{repo}/assignees/{assignee}"], + create: ["POST /repos/{owner}/{repo}/issues"], + createComment: ["POST /repos/{owner}/{repo}/issues/{issue_number}/comments"], + createLabel: ["POST /repos/{owner}/{repo}/labels"], + createMilestone: ["POST /repos/{owner}/{repo}/milestones"], + deleteComment: ["DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}"], + deleteLabel: ["DELETE /repos/{owner}/{repo}/labels/{name}"], + deleteMilestone: ["DELETE /repos/{owner}/{repo}/milestones/{milestone_number}"], + get: ["GET /repos/{owner}/{repo}/issues/{issue_number}"], + getComment: ["GET /repos/{owner}/{repo}/issues/comments/{comment_id}"], + getEvent: ["GET /repos/{owner}/{repo}/issues/events/{event_id}"], + getLabel: ["GET /repos/{owner}/{repo}/labels/{name}"], + getMilestone: ["GET /repos/{owner}/{repo}/milestones/{milestone_number}"], + list: ["GET /issues"], + listAssignees: ["GET /repos/{owner}/{repo}/assignees"], + listComments: ["GET /repos/{owner}/{repo}/issues/{issue_number}/comments"], + listCommentsForRepo: ["GET /repos/{owner}/{repo}/issues/comments"], + listEvents: ["GET /repos/{owner}/{repo}/issues/{issue_number}/events"], + listEventsForRepo: ["GET /repos/{owner}/{repo}/issues/events"], + listEventsForTimeline: ["GET /repos/{owner}/{repo}/issues/{issue_number}/timeline"], + listForAuthenticatedUser: ["GET /user/issues"], + listForOrg: ["GET /orgs/{org}/issues"], + listForRepo: ["GET /repos/{owner}/{repo}/issues"], + listLabelsForMilestone: ["GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels"], + listLabelsForRepo: ["GET /repos/{owner}/{repo}/labels"], + listLabelsOnIssue: ["GET /repos/{owner}/{repo}/issues/{issue_number}/labels"], + listMilestones: ["GET /repos/{owner}/{repo}/milestones"], + lock: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/lock"], + removeAllLabels: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels"], + removeAssignees: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/assignees"], + removeLabel: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels/{name}"], + setLabels: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/labels"], + unlock: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/lock"], + update: ["PATCH /repos/{owner}/{repo}/issues/{issue_number}"], + updateComment: ["PATCH /repos/{owner}/{repo}/issues/comments/{comment_id}"], + updateLabel: ["PATCH /repos/{owner}/{repo}/labels/{name}"], + updateMilestone: ["PATCH /repos/{owner}/{repo}/milestones/{milestone_number}"] + }, + licenses: { + get: ["GET /licenses/{license}"], + getAllCommonlyUsed: ["GET /licenses"], + getForRepo: ["GET /repos/{owner}/{repo}/license"] + }, + markdown: { + render: ["POST /markdown"], + renderRaw: ["POST /markdown/raw", { + headers: { + "content-type": "text/plain; charset=utf-8" } - } else if (value === "" && (operator === "&" || operator === "?")) { - result.push(encodeUnreserved(key) + "="); - } else if (value === "") { - result.push(""); - } - } - - return result; -} - -function parseUrl(template) { - return { - expand: expand.bind(null, template) - }; -} - -function expand(template, context) { - var operators = ["+", "#", ".", "/", ";", "?", "&"]; - return template.replace(/\{([^\{\}]+)\}|([^\{\}]+)/g, function (_, expression, literal) { - if (expression) { - let operator = ""; - const values = []; - - if (operators.indexOf(expression.charAt(0)) !== -1) { - operator = expression.charAt(0); - expression = expression.substr(1); + }] + }, + meta: { + get: ["GET /meta"], + getOctocat: ["GET /octocat"], + getZen: ["GET /zen"], + root: ["GET /"] + }, + migrations: { + cancelImport: ["DELETE /repos/{owner}/{repo}/import"], + deleteArchiveForAuthenticatedUser: ["DELETE /user/migrations/{migration_id}/archive"], + deleteArchiveForOrg: ["DELETE /orgs/{org}/migrations/{migration_id}/archive"], + downloadArchiveForOrg: ["GET /orgs/{org}/migrations/{migration_id}/archive"], + getArchiveForAuthenticatedUser: ["GET /user/migrations/{migration_id}/archive"], + getCommitAuthors: ["GET /repos/{owner}/{repo}/import/authors"], + getImportStatus: ["GET /repos/{owner}/{repo}/import"], + getLargeFiles: ["GET /repos/{owner}/{repo}/import/large_files"], + getStatusForAuthenticatedUser: ["GET /user/migrations/{migration_id}"], + getStatusForOrg: ["GET /orgs/{org}/migrations/{migration_id}"], + listForAuthenticatedUser: ["GET /user/migrations"], + listForOrg: ["GET /orgs/{org}/migrations"], + listReposForAuthenticatedUser: ["GET /user/migrations/{migration_id}/repositories"], + listReposForOrg: ["GET /orgs/{org}/migrations/{migration_id}/repositories"], + listReposForUser: ["GET /user/migrations/{migration_id}/repositories", {}, { + renamed: ["migrations", "listReposForAuthenticatedUser"] + }], + mapCommitAuthor: ["PATCH /repos/{owner}/{repo}/import/authors/{author_id}"], + setLfsPreference: ["PATCH /repos/{owner}/{repo}/import/lfs"], + startForAuthenticatedUser: ["POST /user/migrations"], + startForOrg: ["POST /orgs/{org}/migrations"], + startImport: ["PUT /repos/{owner}/{repo}/import"], + unlockRepoForAuthenticatedUser: ["DELETE /user/migrations/{migration_id}/repos/{repo_name}/lock"], + unlockRepoForOrg: ["DELETE /orgs/{org}/migrations/{migration_id}/repos/{repo_name}/lock"], + updateImport: ["PATCH /repos/{owner}/{repo}/import"] + }, + orgs: { + blockUser: ["PUT /orgs/{org}/blocks/{username}"], + cancelInvitation: ["DELETE /orgs/{org}/invitations/{invitation_id}"], + checkBlockedUser: ["GET /orgs/{org}/blocks/{username}"], + checkMembershipForUser: ["GET /orgs/{org}/members/{username}"], + checkPublicMembershipForUser: ["GET /orgs/{org}/public_members/{username}"], + convertMemberToOutsideCollaborator: ["PUT /orgs/{org}/outside_collaborators/{username}"], + createInvitation: ["POST /orgs/{org}/invitations"], + createWebhook: ["POST /orgs/{org}/hooks"], + deleteWebhook: ["DELETE /orgs/{org}/hooks/{hook_id}"], + get: ["GET /orgs/{org}"], + getMembershipForAuthenticatedUser: ["GET /user/memberships/orgs/{org}"], + getMembershipForUser: ["GET /orgs/{org}/memberships/{username}"], + getWebhook: ["GET /orgs/{org}/hooks/{hook_id}"], + getWebhookConfigForOrg: ["GET /orgs/{org}/hooks/{hook_id}/config"], + getWebhookDelivery: ["GET /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}"], + list: ["GET /organizations"], + listAppInstallations: ["GET /orgs/{org}/installations"], + listBlockedUsers: ["GET /orgs/{org}/blocks"], + listFailedInvitations: ["GET /orgs/{org}/failed_invitations"], + listForAuthenticatedUser: ["GET /user/orgs"], + listForUser: ["GET /users/{username}/orgs"], + listInvitationTeams: ["GET /orgs/{org}/invitations/{invitation_id}/teams"], + listMembers: ["GET /orgs/{org}/members"], + listMembershipsForAuthenticatedUser: ["GET /user/memberships/orgs"], + listOutsideCollaborators: ["GET /orgs/{org}/outside_collaborators"], + listPendingInvitations: ["GET /orgs/{org}/invitations"], + listPublicMembers: ["GET /orgs/{org}/public_members"], + listWebhookDeliveries: ["GET /orgs/{org}/hooks/{hook_id}/deliveries"], + listWebhooks: ["GET /orgs/{org}/hooks"], + pingWebhook: ["POST /orgs/{org}/hooks/{hook_id}/pings"], + redeliverWebhookDelivery: ["POST /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}/attempts"], + removeMember: ["DELETE /orgs/{org}/members/{username}"], + removeMembershipForUser: ["DELETE /orgs/{org}/memberships/{username}"], + removeOutsideCollaborator: ["DELETE /orgs/{org}/outside_collaborators/{username}"], + removePublicMembershipForAuthenticatedUser: ["DELETE /orgs/{org}/public_members/{username}"], + setMembershipForUser: ["PUT /orgs/{org}/memberships/{username}"], + setPublicMembershipForAuthenticatedUser: ["PUT /orgs/{org}/public_members/{username}"], + unblockUser: ["DELETE /orgs/{org}/blocks/{username}"], + update: ["PATCH /orgs/{org}"], + updateMembershipForAuthenticatedUser: ["PATCH /user/memberships/orgs/{org}"], + updateWebhook: ["PATCH /orgs/{org}/hooks/{hook_id}"], + updateWebhookConfigForOrg: ["PATCH /orgs/{org}/hooks/{hook_id}/config"] + }, + packages: { + deletePackageForAuthenticatedUser: ["DELETE /user/packages/{package_type}/{package_name}"], + deletePackageForOrg: ["DELETE /orgs/{org}/packages/{package_type}/{package_name}"], + deletePackageForUser: ["DELETE /users/{username}/packages/{package_type}/{package_name}"], + deletePackageVersionForAuthenticatedUser: ["DELETE /user/packages/{package_type}/{package_name}/versions/{package_version_id}"], + deletePackageVersionForOrg: ["DELETE /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}"], + deletePackageVersionForUser: ["DELETE /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}"], + getAllPackageVersionsForAPackageOwnedByAnOrg: ["GET /orgs/{org}/packages/{package_type}/{package_name}/versions", {}, { + renamed: ["packages", "getAllPackageVersionsForPackageOwnedByOrg"] + }], + getAllPackageVersionsForAPackageOwnedByTheAuthenticatedUser: ["GET /user/packages/{package_type}/{package_name}/versions", {}, { + renamed: ["packages", "getAllPackageVersionsForPackageOwnedByAuthenticatedUser"] + }], + getAllPackageVersionsForPackageOwnedByAuthenticatedUser: ["GET /user/packages/{package_type}/{package_name}/versions"], + getAllPackageVersionsForPackageOwnedByOrg: ["GET /orgs/{org}/packages/{package_type}/{package_name}/versions"], + getAllPackageVersionsForPackageOwnedByUser: ["GET /users/{username}/packages/{package_type}/{package_name}/versions"], + getPackageForAuthenticatedUser: ["GET /user/packages/{package_type}/{package_name}"], + getPackageForOrganization: ["GET /orgs/{org}/packages/{package_type}/{package_name}"], + getPackageForUser: ["GET /users/{username}/packages/{package_type}/{package_name}"], + getPackageVersionForAuthenticatedUser: ["GET /user/packages/{package_type}/{package_name}/versions/{package_version_id}"], + getPackageVersionForOrganization: ["GET /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}"], + getPackageVersionForUser: ["GET /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}"], + listPackagesForAuthenticatedUser: ["GET /user/packages"], + listPackagesForOrganization: ["GET /orgs/{org}/packages"], + listPackagesForUser: ["GET /users/{username}/packages"], + restorePackageForAuthenticatedUser: ["POST /user/packages/{package_type}/{package_name}/restore{?token}"], + restorePackageForOrg: ["POST /orgs/{org}/packages/{package_type}/{package_name}/restore{?token}"], + restorePackageForUser: ["POST /users/{username}/packages/{package_type}/{package_name}/restore{?token}"], + restorePackageVersionForAuthenticatedUser: ["POST /user/packages/{package_type}/{package_name}/versions/{package_version_id}/restore"], + restorePackageVersionForOrg: ["POST /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore"], + restorePackageVersionForUser: ["POST /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore"] + }, + projects: { + addCollaborator: ["PUT /projects/{project_id}/collaborators/{username}"], + createCard: ["POST /projects/columns/{column_id}/cards"], + createColumn: ["POST /projects/{project_id}/columns"], + createForAuthenticatedUser: ["POST /user/projects"], + createForOrg: ["POST /orgs/{org}/projects"], + createForRepo: ["POST /repos/{owner}/{repo}/projects"], + delete: ["DELETE /projects/{project_id}"], + deleteCard: ["DELETE /projects/columns/cards/{card_id}"], + deleteColumn: ["DELETE /projects/columns/{column_id}"], + get: ["GET /projects/{project_id}"], + getCard: ["GET /projects/columns/cards/{card_id}"], + getColumn: ["GET /projects/columns/{column_id}"], + getPermissionForUser: ["GET /projects/{project_id}/collaborators/{username}/permission"], + listCards: ["GET /projects/columns/{column_id}/cards"], + listCollaborators: ["GET /projects/{project_id}/collaborators"], + listColumns: ["GET /projects/{project_id}/columns"], + listForOrg: ["GET /orgs/{org}/projects"], + listForRepo: ["GET /repos/{owner}/{repo}/projects"], + listForUser: ["GET /users/{username}/projects"], + moveCard: ["POST /projects/columns/cards/{card_id}/moves"], + moveColumn: ["POST /projects/columns/{column_id}/moves"], + removeCollaborator: ["DELETE /projects/{project_id}/collaborators/{username}"], + update: ["PATCH /projects/{project_id}"], + updateCard: ["PATCH /projects/columns/cards/{card_id}"], + updateColumn: ["PATCH /projects/columns/{column_id}"] + }, + pulls: { + checkIfMerged: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/merge"], + create: ["POST /repos/{owner}/{repo}/pulls"], + createReplyForReviewComment: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies"], + createReview: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews"], + createReviewComment: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/comments"], + deletePendingReview: ["DELETE /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}"], + deleteReviewComment: ["DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}"], + dismissReview: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/dismissals"], + get: ["GET /repos/{owner}/{repo}/pulls/{pull_number}"], + getReview: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}"], + getReviewComment: ["GET /repos/{owner}/{repo}/pulls/comments/{comment_id}"], + list: ["GET /repos/{owner}/{repo}/pulls"], + listCommentsForReview: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments"], + listCommits: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/commits"], + listFiles: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/files"], + listRequestedReviewers: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers"], + listReviewComments: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/comments"], + listReviewCommentsForRepo: ["GET /repos/{owner}/{repo}/pulls/comments"], + listReviews: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews"], + merge: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/merge"], + removeRequestedReviewers: ["DELETE /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers"], + requestReviewers: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers"], + submitReview: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/events"], + update: ["PATCH /repos/{owner}/{repo}/pulls/{pull_number}"], + updateBranch: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/update-branch"], + updateReview: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}"], + updateReviewComment: ["PATCH /repos/{owner}/{repo}/pulls/comments/{comment_id}"] + }, + rateLimit: { + get: ["GET /rate_limit"] + }, + reactions: { + createForCommitComment: ["POST /repos/{owner}/{repo}/comments/{comment_id}/reactions"], + createForIssue: ["POST /repos/{owner}/{repo}/issues/{issue_number}/reactions"], + createForIssueComment: ["POST /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions"], + createForPullRequestReviewComment: ["POST /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions"], + createForRelease: ["POST /repos/{owner}/{repo}/releases/{release_id}/reactions"], + createForTeamDiscussionCommentInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions"], + createForTeamDiscussionInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions"], + deleteForCommitComment: ["DELETE /repos/{owner}/{repo}/comments/{comment_id}/reactions/{reaction_id}"], + deleteForIssue: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/reactions/{reaction_id}"], + deleteForIssueComment: ["DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions/{reaction_id}"], + deleteForPullRequestComment: ["DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions/{reaction_id}"], + deleteForTeamDiscussion: ["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions/{reaction_id}"], + deleteForTeamDiscussionComment: ["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions/{reaction_id}"], + listForCommitComment: ["GET /repos/{owner}/{repo}/comments/{comment_id}/reactions"], + listForIssue: ["GET /repos/{owner}/{repo}/issues/{issue_number}/reactions"], + listForIssueComment: ["GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions"], + listForPullRequestReviewComment: ["GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions"], + listForTeamDiscussionCommentInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions"], + listForTeamDiscussionInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions"] + }, + repos: { + acceptInvitation: ["PATCH /user/repository_invitations/{invitation_id}", {}, { + renamed: ["repos", "acceptInvitationForAuthenticatedUser"] + }], + acceptInvitationForAuthenticatedUser: ["PATCH /user/repository_invitations/{invitation_id}"], + addAppAccessRestrictions: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", {}, { + mapToData: "apps" + }], + addCollaborator: ["PUT /repos/{owner}/{repo}/collaborators/{username}"], + addStatusCheckContexts: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", {}, { + mapToData: "contexts" + }], + addTeamAccessRestrictions: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", {}, { + mapToData: "teams" + }], + addUserAccessRestrictions: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", {}, { + mapToData: "users" + }], + checkCollaborator: ["GET /repos/{owner}/{repo}/collaborators/{username}"], + checkVulnerabilityAlerts: ["GET /repos/{owner}/{repo}/vulnerability-alerts"], + compareCommits: ["GET /repos/{owner}/{repo}/compare/{base}...{head}"], + compareCommitsWithBasehead: ["GET /repos/{owner}/{repo}/compare/{basehead}"], + createAutolink: ["POST /repos/{owner}/{repo}/autolinks"], + createCommitComment: ["POST /repos/{owner}/{repo}/commits/{commit_sha}/comments"], + createCommitSignatureProtection: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures"], + createCommitStatus: ["POST /repos/{owner}/{repo}/statuses/{sha}"], + createDeployKey: ["POST /repos/{owner}/{repo}/keys"], + createDeployment: ["POST /repos/{owner}/{repo}/deployments"], + createDeploymentStatus: ["POST /repos/{owner}/{repo}/deployments/{deployment_id}/statuses"], + createDispatchEvent: ["POST /repos/{owner}/{repo}/dispatches"], + createForAuthenticatedUser: ["POST /user/repos"], + createFork: ["POST /repos/{owner}/{repo}/forks"], + createInOrg: ["POST /orgs/{org}/repos"], + createOrUpdateEnvironment: ["PUT /repos/{owner}/{repo}/environments/{environment_name}"], + createOrUpdateFileContents: ["PUT /repos/{owner}/{repo}/contents/{path}"], + createPagesSite: ["POST /repos/{owner}/{repo}/pages"], + createRelease: ["POST /repos/{owner}/{repo}/releases"], + createUsingTemplate: ["POST /repos/{template_owner}/{template_repo}/generate"], + createWebhook: ["POST /repos/{owner}/{repo}/hooks"], + declineInvitation: ["DELETE /user/repository_invitations/{invitation_id}", {}, { + renamed: ["repos", "declineInvitationForAuthenticatedUser"] + }], + declineInvitationForAuthenticatedUser: ["DELETE /user/repository_invitations/{invitation_id}"], + delete: ["DELETE /repos/{owner}/{repo}"], + deleteAccessRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions"], + deleteAdminBranchProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins"], + deleteAnEnvironment: ["DELETE /repos/{owner}/{repo}/environments/{environment_name}"], + deleteAutolink: ["DELETE /repos/{owner}/{repo}/autolinks/{autolink_id}"], + deleteBranchProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection"], + deleteCommitComment: ["DELETE /repos/{owner}/{repo}/comments/{comment_id}"], + deleteCommitSignatureProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures"], + deleteDeployKey: ["DELETE /repos/{owner}/{repo}/keys/{key_id}"], + deleteDeployment: ["DELETE /repos/{owner}/{repo}/deployments/{deployment_id}"], + deleteFile: ["DELETE /repos/{owner}/{repo}/contents/{path}"], + deleteInvitation: ["DELETE /repos/{owner}/{repo}/invitations/{invitation_id}"], + deletePagesSite: ["DELETE /repos/{owner}/{repo}/pages"], + deletePullRequestReviewProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews"], + deleteRelease: ["DELETE /repos/{owner}/{repo}/releases/{release_id}"], + deleteReleaseAsset: ["DELETE /repos/{owner}/{repo}/releases/assets/{asset_id}"], + deleteWebhook: ["DELETE /repos/{owner}/{repo}/hooks/{hook_id}"], + disableAutomatedSecurityFixes: ["DELETE /repos/{owner}/{repo}/automated-security-fixes"], + disableLfsForRepo: ["DELETE /repos/{owner}/{repo}/lfs"], + disableVulnerabilityAlerts: ["DELETE /repos/{owner}/{repo}/vulnerability-alerts"], + downloadArchive: ["GET /repos/{owner}/{repo}/zipball/{ref}", {}, { + renamed: ["repos", "downloadZipballArchive"] + }], + downloadTarballArchive: ["GET /repos/{owner}/{repo}/tarball/{ref}"], + downloadZipballArchive: ["GET /repos/{owner}/{repo}/zipball/{ref}"], + enableAutomatedSecurityFixes: ["PUT /repos/{owner}/{repo}/automated-security-fixes"], + enableLfsForRepo: ["PUT /repos/{owner}/{repo}/lfs"], + enableVulnerabilityAlerts: ["PUT /repos/{owner}/{repo}/vulnerability-alerts"], + generateReleaseNotes: ["POST /repos/{owner}/{repo}/releases/generate-notes"], + get: ["GET /repos/{owner}/{repo}"], + getAccessRestrictions: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions"], + getAdminBranchProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins"], + getAllEnvironments: ["GET /repos/{owner}/{repo}/environments"], + getAllStatusCheckContexts: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts"], + getAllTopics: ["GET /repos/{owner}/{repo}/topics", { + mediaType: { + previews: ["mercy"] } - - expression.split(/,/g).forEach(function (variable) { - var tmp = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable); - values.push(getValues(context, operator, tmp[1], tmp[2] || tmp[3])); - }); - - if (operator && operator !== "+") { - var separator = ","; - - if (operator === "?") { - separator = "&"; - } else if (operator !== "#") { - separator = operator; - } - - return (values.length !== 0 ? operator : "") + values.join(separator); - } else { - return values.join(","); + }], + getAppsWithAccessToProtectedBranch: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps"], + getAutolink: ["GET /repos/{owner}/{repo}/autolinks/{autolink_id}"], + getBranch: ["GET /repos/{owner}/{repo}/branches/{branch}"], + getBranchProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection"], + getClones: ["GET /repos/{owner}/{repo}/traffic/clones"], + getCodeFrequencyStats: ["GET /repos/{owner}/{repo}/stats/code_frequency"], + getCollaboratorPermissionLevel: ["GET /repos/{owner}/{repo}/collaborators/{username}/permission"], + getCombinedStatusForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/status"], + getCommit: ["GET /repos/{owner}/{repo}/commits/{ref}"], + getCommitActivityStats: ["GET /repos/{owner}/{repo}/stats/commit_activity"], + getCommitComment: ["GET /repos/{owner}/{repo}/comments/{comment_id}"], + getCommitSignatureProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures"], + getCommunityProfileMetrics: ["GET /repos/{owner}/{repo}/community/profile"], + getContent: ["GET /repos/{owner}/{repo}/contents/{path}"], + getContributorsStats: ["GET /repos/{owner}/{repo}/stats/contributors"], + getDeployKey: ["GET /repos/{owner}/{repo}/keys/{key_id}"], + getDeployment: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}"], + getDeploymentStatus: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses/{status_id}"], + getEnvironment: ["GET /repos/{owner}/{repo}/environments/{environment_name}"], + getLatestPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/latest"], + getLatestRelease: ["GET /repos/{owner}/{repo}/releases/latest"], + getPages: ["GET /repos/{owner}/{repo}/pages"], + getPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/{build_id}"], + getPagesHealthCheck: ["GET /repos/{owner}/{repo}/pages/health"], + getParticipationStats: ["GET /repos/{owner}/{repo}/stats/participation"], + getPullRequestReviewProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews"], + getPunchCardStats: ["GET /repos/{owner}/{repo}/stats/punch_card"], + getReadme: ["GET /repos/{owner}/{repo}/readme"], + getReadmeInDirectory: ["GET /repos/{owner}/{repo}/readme/{dir}"], + getRelease: ["GET /repos/{owner}/{repo}/releases/{release_id}"], + getReleaseAsset: ["GET /repos/{owner}/{repo}/releases/assets/{asset_id}"], + getReleaseByTag: ["GET /repos/{owner}/{repo}/releases/tags/{tag}"], + getStatusChecksProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks"], + getTeamsWithAccessToProtectedBranch: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams"], + getTopPaths: ["GET /repos/{owner}/{repo}/traffic/popular/paths"], + getTopReferrers: ["GET /repos/{owner}/{repo}/traffic/popular/referrers"], + getUsersWithAccessToProtectedBranch: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users"], + getViews: ["GET /repos/{owner}/{repo}/traffic/views"], + getWebhook: ["GET /repos/{owner}/{repo}/hooks/{hook_id}"], + getWebhookConfigForRepo: ["GET /repos/{owner}/{repo}/hooks/{hook_id}/config"], + getWebhookDelivery: ["GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}"], + listAutolinks: ["GET /repos/{owner}/{repo}/autolinks"], + listBranches: ["GET /repos/{owner}/{repo}/branches"], + listBranchesForHeadCommit: ["GET /repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head"], + listCollaborators: ["GET /repos/{owner}/{repo}/collaborators"], + listCommentsForCommit: ["GET /repos/{owner}/{repo}/commits/{commit_sha}/comments"], + listCommitCommentsForRepo: ["GET /repos/{owner}/{repo}/comments"], + listCommitStatusesForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/statuses"], + listCommits: ["GET /repos/{owner}/{repo}/commits"], + listContributors: ["GET /repos/{owner}/{repo}/contributors"], + listDeployKeys: ["GET /repos/{owner}/{repo}/keys"], + listDeploymentStatuses: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses"], + listDeployments: ["GET /repos/{owner}/{repo}/deployments"], + listForAuthenticatedUser: ["GET /user/repos"], + listForOrg: ["GET /orgs/{org}/repos"], + listForUser: ["GET /users/{username}/repos"], + listForks: ["GET /repos/{owner}/{repo}/forks"], + listInvitations: ["GET /repos/{owner}/{repo}/invitations"], + listInvitationsForAuthenticatedUser: ["GET /user/repository_invitations"], + listLanguages: ["GET /repos/{owner}/{repo}/languages"], + listPagesBuilds: ["GET /repos/{owner}/{repo}/pages/builds"], + listPublic: ["GET /repositories"], + listPullRequestsAssociatedWithCommit: ["GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls"], + listReleaseAssets: ["GET /repos/{owner}/{repo}/releases/{release_id}/assets"], + listReleases: ["GET /repos/{owner}/{repo}/releases"], + listTags: ["GET /repos/{owner}/{repo}/tags"], + listTeams: ["GET /repos/{owner}/{repo}/teams"], + listWebhookDeliveries: ["GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries"], + listWebhooks: ["GET /repos/{owner}/{repo}/hooks"], + merge: ["POST /repos/{owner}/{repo}/merges"], + mergeUpstream: ["POST /repos/{owner}/{repo}/merge-upstream"], + pingWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/pings"], + redeliverWebhookDelivery: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}/attempts"], + removeAppAccessRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", {}, { + mapToData: "apps" + }], + removeCollaborator: ["DELETE /repos/{owner}/{repo}/collaborators/{username}"], + removeStatusCheckContexts: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", {}, { + mapToData: "contexts" + }], + removeStatusCheckProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks"], + removeTeamAccessRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", {}, { + mapToData: "teams" + }], + removeUserAccessRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", {}, { + mapToData: "users" + }], + renameBranch: ["POST /repos/{owner}/{repo}/branches/{branch}/rename"], + replaceAllTopics: ["PUT /repos/{owner}/{repo}/topics", { + mediaType: { + previews: ["mercy"] } - } else { - return encodeReserved(literal); - } - }); -} - -function parse(options) { - // https://fetch.spec.whatwg.org/#methods - let method = options.method.toUpperCase(); // replace :varname with {varname} to make it RFC 6570 compatible - - let url = (options.url || "/").replace(/:([a-z]\w+)/g, "{$1}"); - let headers = Object.assign({}, options.headers); - let body; - let parameters = omit(options, ["method", "baseUrl", "url", "headers", "request", "mediaType"]); // extract variable names from URL to calculate remaining variables later - - const urlVariableNames = extractUrlVariableNames(url); - url = parseUrl(url).expand(parameters); - - if (!/^http/.test(url)) { - url = options.baseUrl + url; - } - - const omittedParameters = Object.keys(options).filter(option => urlVariableNames.includes(option)).concat("baseUrl"); - const remainingParameters = omit(parameters, omittedParameters); - const isBinaryRequest = /application\/octet-stream/i.test(headers.accept); - - if (!isBinaryRequest) { - if (options.mediaType.format) { - // e.g. application/vnd.github.v3+json => application/vnd.github.v3.raw - headers.accept = headers.accept.split(/,/).map(preview => preview.replace(/application\/vnd(\.\w+)(\.v3)?(\.\w+)?(\+json)?$/, `application/vnd$1$2.${options.mediaType.format}`)).join(","); - } - - if (options.mediaType.previews.length) { - const previewsFromAcceptHeader = headers.accept.match(/[\w-]+(?=-preview)/g) || []; - headers.accept = previewsFromAcceptHeader.concat(options.mediaType.previews).map(preview => { - const format = options.mediaType.format ? `.${options.mediaType.format}` : "+json"; - return `application/vnd.github.${preview}-preview${format}`; - }).join(","); - } - } // for GET/HEAD requests, set URL query parameters from remaining parameters - // for PATCH/POST/PUT/DELETE requests, set request body from remaining parameters - - - if (["GET", "HEAD"].includes(method)) { - url = addQueryParameters(url, remainingParameters); - } else { - if ("data" in remainingParameters) { - body = remainingParameters.data; - } else { - if (Object.keys(remainingParameters).length) { - body = remainingParameters; - } else { - headers["content-length"] = 0; + }], + requestPagesBuild: ["POST /repos/{owner}/{repo}/pages/builds"], + setAdminBranchProtection: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins"], + setAppAccessRestrictions: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", {}, { + mapToData: "apps" + }], + setStatusCheckContexts: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", {}, { + mapToData: "contexts" + }], + setTeamAccessRestrictions: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", {}, { + mapToData: "teams" + }], + setUserAccessRestrictions: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", {}, { + mapToData: "users" + }], + testPushWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/tests"], + transfer: ["POST /repos/{owner}/{repo}/transfer"], + update: ["PATCH /repos/{owner}/{repo}"], + updateBranchProtection: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection"], + updateCommitComment: ["PATCH /repos/{owner}/{repo}/comments/{comment_id}"], + updateInformationAboutPagesSite: ["PUT /repos/{owner}/{repo}/pages"], + updateInvitation: ["PATCH /repos/{owner}/{repo}/invitations/{invitation_id}"], + updatePullRequestReviewProtection: ["PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews"], + updateRelease: ["PATCH /repos/{owner}/{repo}/releases/{release_id}"], + updateReleaseAsset: ["PATCH /repos/{owner}/{repo}/releases/assets/{asset_id}"], + updateStatusCheckPotection: ["PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks", {}, { + renamed: ["repos", "updateStatusCheckProtection"] + }], + updateStatusCheckProtection: ["PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks"], + updateWebhook: ["PATCH /repos/{owner}/{repo}/hooks/{hook_id}"], + updateWebhookConfigForRepo: ["PATCH /repos/{owner}/{repo}/hooks/{hook_id}/config"], + uploadReleaseAsset: ["POST /repos/{owner}/{repo}/releases/{release_id}/assets{?name,label}", { + baseUrl: "https://uploads.github.com" + }] + }, + search: { + code: ["GET /search/code"], + commits: ["GET /search/commits"], + issuesAndPullRequests: ["GET /search/issues"], + labels: ["GET /search/labels"], + repos: ["GET /search/repositories"], + topics: ["GET /search/topics", { + mediaType: { + previews: ["mercy"] } - } - } // default content-type for JSON if body is set - - - if (!headers["content-type"] && typeof body !== "undefined") { - headers["content-type"] = "application/json; charset=utf-8"; - } // GitHub expects 'content-length: 0' header for PUT/PATCH requests without body. - // fetch does not allow to set `content-length` header, but we can set body to an empty string - - - if (["PATCH", "PUT"].includes(method) && typeof body === "undefined") { - body = ""; - } // Only return body/request keys if present - - - return Object.assign({ - method, - url, - headers - }, typeof body !== "undefined" ? { - body - } : null, options.request ? { - request: options.request - } : null); -} - -function endpointWithDefaults(defaults, route, options) { - return parse(merge(defaults, route, options)); -} - -function withDefaults(oldDefaults, newDefaults) { - const DEFAULTS = merge(oldDefaults, newDefaults); - const endpoint = endpointWithDefaults.bind(null, DEFAULTS); - return Object.assign(endpoint, { - DEFAULTS, - defaults: withDefaults.bind(null, DEFAULTS), - merge: merge.bind(null, DEFAULTS), - parse - }); -} - -const VERSION = "6.0.10"; - -const userAgent = `octokit-endpoint.js/${VERSION} ${universalUserAgent.getUserAgent()}`; // DEFAULTS has all properties set that EndpointOptions has, except url. -// So we use RequestParameters and add method as additional required property. - -const DEFAULTS = { - method: "GET", - baseUrl: "https://api.github.com", - headers: { - accept: "application/vnd.github.v3+json", - "user-agent": userAgent + }], + users: ["GET /search/users"] }, - mediaType: { - format: "", - previews: [] + secretScanning: { + getAlert: ["GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}"], + listAlertsForOrg: ["GET /orgs/{org}/secret-scanning/alerts"], + listAlertsForRepo: ["GET /repos/{owner}/{repo}/secret-scanning/alerts"], + updateAlert: ["PATCH /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}"] + }, + teams: { + addOrUpdateMembershipForUserInOrg: ["PUT /orgs/{org}/teams/{team_slug}/memberships/{username}"], + addOrUpdateProjectPermissionsInOrg: ["PUT /orgs/{org}/teams/{team_slug}/projects/{project_id}"], + addOrUpdateRepoPermissionsInOrg: ["PUT /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}"], + checkPermissionsForProjectInOrg: ["GET /orgs/{org}/teams/{team_slug}/projects/{project_id}"], + checkPermissionsForRepoInOrg: ["GET /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}"], + create: ["POST /orgs/{org}/teams"], + createDiscussionCommentInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments"], + createDiscussionInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions"], + deleteDiscussionCommentInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}"], + deleteDiscussionInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}"], + deleteInOrg: ["DELETE /orgs/{org}/teams/{team_slug}"], + getByName: ["GET /orgs/{org}/teams/{team_slug}"], + getDiscussionCommentInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}"], + getDiscussionInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}"], + getMembershipForUserInOrg: ["GET /orgs/{org}/teams/{team_slug}/memberships/{username}"], + list: ["GET /orgs/{org}/teams"], + listChildInOrg: ["GET /orgs/{org}/teams/{team_slug}/teams"], + listDiscussionCommentsInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments"], + listDiscussionsInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions"], + listForAuthenticatedUser: ["GET /user/teams"], + listMembersInOrg: ["GET /orgs/{org}/teams/{team_slug}/members"], + listPendingInvitationsInOrg: ["GET /orgs/{org}/teams/{team_slug}/invitations"], + listProjectsInOrg: ["GET /orgs/{org}/teams/{team_slug}/projects"], + listReposInOrg: ["GET /orgs/{org}/teams/{team_slug}/repos"], + removeMembershipForUserInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/memberships/{username}"], + removeProjectInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/projects/{project_id}"], + removeRepoInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}"], + updateDiscussionCommentInOrg: ["PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}"], + updateDiscussionInOrg: ["PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}"], + updateInOrg: ["PATCH /orgs/{org}/teams/{team_slug}"] + }, + users: { + addEmailForAuthenticated: ["POST /user/emails", {}, { + renamed: ["users", "addEmailForAuthenticatedUser"] + }], + addEmailForAuthenticatedUser: ["POST /user/emails"], + block: ["PUT /user/blocks/{username}"], + checkBlocked: ["GET /user/blocks/{username}"], + checkFollowingForUser: ["GET /users/{username}/following/{target_user}"], + checkPersonIsFollowedByAuthenticated: ["GET /user/following/{username}"], + createGpgKeyForAuthenticated: ["POST /user/gpg_keys", {}, { + renamed: ["users", "createGpgKeyForAuthenticatedUser"] + }], + createGpgKeyForAuthenticatedUser: ["POST /user/gpg_keys"], + createPublicSshKeyForAuthenticated: ["POST /user/keys", {}, { + renamed: ["users", "createPublicSshKeyForAuthenticatedUser"] + }], + createPublicSshKeyForAuthenticatedUser: ["POST /user/keys"], + deleteEmailForAuthenticated: ["DELETE /user/emails", {}, { + renamed: ["users", "deleteEmailForAuthenticatedUser"] + }], + deleteEmailForAuthenticatedUser: ["DELETE /user/emails"], + deleteGpgKeyForAuthenticated: ["DELETE /user/gpg_keys/{gpg_key_id}", {}, { + renamed: ["users", "deleteGpgKeyForAuthenticatedUser"] + }], + deleteGpgKeyForAuthenticatedUser: ["DELETE /user/gpg_keys/{gpg_key_id}"], + deletePublicSshKeyForAuthenticated: ["DELETE /user/keys/{key_id}", {}, { + renamed: ["users", "deletePublicSshKeyForAuthenticatedUser"] + }], + deletePublicSshKeyForAuthenticatedUser: ["DELETE /user/keys/{key_id}"], + follow: ["PUT /user/following/{username}"], + getAuthenticated: ["GET /user"], + getByUsername: ["GET /users/{username}"], + getContextForUser: ["GET /users/{username}/hovercard"], + getGpgKeyForAuthenticated: ["GET /user/gpg_keys/{gpg_key_id}", {}, { + renamed: ["users", "getGpgKeyForAuthenticatedUser"] + }], + getGpgKeyForAuthenticatedUser: ["GET /user/gpg_keys/{gpg_key_id}"], + getPublicSshKeyForAuthenticated: ["GET /user/keys/{key_id}", {}, { + renamed: ["users", "getPublicSshKeyForAuthenticatedUser"] + }], + getPublicSshKeyForAuthenticatedUser: ["GET /user/keys/{key_id}"], + list: ["GET /users"], + listBlockedByAuthenticated: ["GET /user/blocks", {}, { + renamed: ["users", "listBlockedByAuthenticatedUser"] + }], + listBlockedByAuthenticatedUser: ["GET /user/blocks"], + listEmailsForAuthenticated: ["GET /user/emails", {}, { + renamed: ["users", "listEmailsForAuthenticatedUser"] + }], + listEmailsForAuthenticatedUser: ["GET /user/emails"], + listFollowedByAuthenticated: ["GET /user/following", {}, { + renamed: ["users", "listFollowedByAuthenticatedUser"] + }], + listFollowedByAuthenticatedUser: ["GET /user/following"], + listFollowersForAuthenticatedUser: ["GET /user/followers"], + listFollowersForUser: ["GET /users/{username}/followers"], + listFollowingForUser: ["GET /users/{username}/following"], + listGpgKeysForAuthenticated: ["GET /user/gpg_keys", {}, { + renamed: ["users", "listGpgKeysForAuthenticatedUser"] + }], + listGpgKeysForAuthenticatedUser: ["GET /user/gpg_keys"], + listGpgKeysForUser: ["GET /users/{username}/gpg_keys"], + listPublicEmailsForAuthenticated: ["GET /user/public_emails", {}, { + renamed: ["users", "listPublicEmailsForAuthenticatedUser"] + }], + listPublicEmailsForAuthenticatedUser: ["GET /user/public_emails"], + listPublicKeysForUser: ["GET /users/{username}/keys"], + listPublicSshKeysForAuthenticated: ["GET /user/keys", {}, { + renamed: ["users", "listPublicSshKeysForAuthenticatedUser"] + }], + listPublicSshKeysForAuthenticatedUser: ["GET /user/keys"], + setPrimaryEmailVisibilityForAuthenticated: ["PATCH /user/email/visibility", {}, { + renamed: ["users", "setPrimaryEmailVisibilityForAuthenticatedUser"] + }], + setPrimaryEmailVisibilityForAuthenticatedUser: ["PATCH /user/email/visibility"], + unblock: ["DELETE /user/blocks/{username}"], + unfollow: ["DELETE /user/following/{username}"], + updateAuthenticated: ["PATCH /user"] } }; -const endpoint = withDefaults(null, DEFAULTS); - -exports.endpoint = endpoint; -//# sourceMappingURL=index.js.map - - -/***/ }), - -/***/ 88467: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - +const VERSION = "5.13.0"; -Object.defineProperty(exports, "__esModule", ({ value: true })); +function endpointsToMethods(octokit, endpointsMap) { + const newMethods = {}; -var request = __nccwpck_require__(36234); -var universalUserAgent = __nccwpck_require__(45030); + for (const [scope, endpoints] of Object.entries(endpointsMap)) { + for (const [methodName, endpoint] of Object.entries(endpoints)) { + const [route, defaults, decorations] = endpoint; + const [method, url] = route.split(/ /); + const endpointDefaults = Object.assign({ + method, + url + }, defaults); -const VERSION = "4.5.8"; + if (!newMethods[scope]) { + newMethods[scope] = {}; + } -class GraphqlError extends Error { - constructor(request, response) { - const message = response.data.errors[0].message; - super(message); - Object.assign(this, response.data); - Object.assign(this, { - headers: response.headers - }); - this.name = "GraphqlError"; - this.request = request; // Maintains proper stack trace (only available on V8) + const scopeMethods = newMethods[scope]; - /* istanbul ignore next */ + if (decorations) { + scopeMethods[methodName] = decorate(octokit, scope, methodName, endpointDefaults, decorations); + continue; + } - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); + scopeMethods[methodName] = octokit.request.defaults(endpointDefaults); } } + return newMethods; } -const NON_VARIABLE_OPTIONS = ["method", "baseUrl", "url", "headers", "request", "query", "mediaType"]; -const GHES_V3_SUFFIX_REGEX = /\/api\/v3\/?$/; -function graphql(request, query, options) { - if (typeof query === "string" && options && "query" in options) { - return Promise.reject(new Error(`[@octokit/graphql] "query" cannot be used as variable name`)); - } - - const parsedOptions = typeof query === "string" ? Object.assign({ - query - }, options) : query; - const requestOptions = Object.keys(parsedOptions).reduce((result, key) => { - if (NON_VARIABLE_OPTIONS.includes(key)) { - result[key] = parsedOptions[key]; - return result; - } - - if (!result.variables) { - result.variables = {}; - } - - result.variables[key] = parsedOptions[key]; - return result; - }, {}); // workaround for GitHub Enterprise baseUrl set with /api/v3 suffix - // https://github.com/octokit/auth-app.js/issues/111#issuecomment-657610451 - - const baseUrl = parsedOptions.baseUrl || request.endpoint.DEFAULTS.baseUrl; - - if (GHES_V3_SUFFIX_REGEX.test(baseUrl)) { - requestOptions.url = baseUrl.replace(GHES_V3_SUFFIX_REGEX, "/api/graphql"); - } - - return request(requestOptions).then(response => { - if (response.data.errors) { - const headers = {}; +function decorate(octokit, scope, methodName, defaults, decorations) { + const requestWithDefaults = octokit.request.defaults(defaults); + /* istanbul ignore next */ - for (const key of Object.keys(response.headers)) { - headers[key] = response.headers[key]; - } + function withDecorations(...args) { + // @ts-ignore https://github.com/microsoft/TypeScript/issues/25488 + let options = requestWithDefaults.endpoint.merge(...args); // There are currently no other decorations than `.mapToData` - throw new GraphqlError(requestOptions, { - headers, - data: response.data + if (decorations.mapToData) { + options = Object.assign({}, options, { + data: options[decorations.mapToData], + [decorations.mapToData]: undefined }); + return requestWithDefaults(options); } - return response.data.data; - }); -} - -function withDefaults(request$1, newDefaults) { - const newRequest = request$1.defaults(newDefaults); - - const newApi = (query, options) => { - return graphql(newRequest, query, options); - }; - - return Object.assign(newApi, { - defaults: withDefaults.bind(null, newRequest), - endpoint: request.request.endpoint - }); -} - -const graphql$1 = withDefaults(request.request, { - headers: { - "user-agent": `octokit-graphql.js/${VERSION} ${universalUserAgent.getUserAgent()}` - }, - method: "POST", - url: "/graphql" -}); -function withCustomRequest(customRequest) { - return withDefaults(customRequest, { - method: "POST", - url: "/graphql" - }); -} - -exports.graphql = graphql$1; -exports.withCustomRequest = withCustomRequest; -//# sourceMappingURL=index.js.map - - -/***/ }), + if (decorations.renamed) { + const [newScope, newMethodName] = decorations.renamed; + octokit.log.warn(`octokit.${scope}.${methodName}() has been renamed to octokit.${newScope}.${newMethodName}()`); + } -/***/ 25823: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + if (decorations.deprecated) { + octokit.log.warn(decorations.deprecated); + } -"use strict"; + if (decorations.renamedParameters) { + // @ts-ignore https://github.com/microsoft/TypeScript/issues/25488 + const options = requestWithDefaults.endpoint.merge(...args); + for (const [name, alias] of Object.entries(decorations.renamedParameters)) { + if (name in options) { + octokit.log.warn(`"${name}" parameter is deprecated for "octokit.${scope}.${methodName}()". Use "${alias}" instead`); -Object.defineProperty(exports, "__esModule", ({ value: true })); + if (!(alias in options)) { + options[alias] = options[name]; + } -var requestError = __nccwpck_require__(10537); + delete options[name]; + } + } -const VERSION = "1.2.8"; + return requestWithDefaults(options); + } // @ts-ignore https://github.com/microsoft/TypeScript/issues/25488 -function isIssueLabelsUpdateOrReplace({ - method, - url -}) { - if (!["POST", "PUT"].includes(method)) { - return false; - } - if (!/\/repos\/[^/]+\/[^/]+\/issues\/[^/]+\/labels/.test(url)) { - return false; + return requestWithDefaults(...args); } - return true; + return Object.assign(withDecorations, requestWithDefaults); } -function enterpriseCompatibility(octokit) { - octokit.hook.wrap("request", async (request, options) => { - // see https://github.com/octokit/rest.js/blob/15.x/lib/routes.json#L3046-L3068 - if (isIssueLabelsUpdateOrReplace(options)) { - options.data = options.labels; - delete options.labels; // for @octokit/rest v16.x, remove validation of labels option - - /* istanbul ignore if */ - - if (options.request.validate) { - delete options.request.validate.labels; - } - - return request(options); - } // TODO: implement fix for #62 here - // https://github.com/octokit/plugin-enterprise-compatibility.js/issues/60 - - - if (/\/orgs\/[^/]+\/teams/.test(options.url)) { - try { - return await request(options); - } catch (error) { - if (error.status !== 404) { - throw error; - } - - if (!error.headers || !error.headers["x-github-enterprise-version"]) { - throw error; - } - - const deprecatedUrl = options.url.replace(/\/orgs\/[^/]+\/teams\/[^/]+/, "/teams/{team_id}"); - throw new requestError.RequestError(`"${options.method} ${options.url}" is not supported in your GitHub Enterprise Server version. Please replace with octokit.request("${options.method} ${deprecatedUrl}", { team_id })`, 404, { - request: options - }); - } - } - - return request(options); +function restEndpointMethods(octokit) { + const api = endpointsToMethods(octokit, Endpoints); + return { + rest: api + }; +} +restEndpointMethods.VERSION = VERSION; +function legacyRestEndpointMethods(octokit) { + const api = endpointsToMethods(octokit, Endpoints); + return _objectSpread2(_objectSpread2({}, api), {}, { + rest: api }); } -enterpriseCompatibility.VERSION = VERSION; +legacyRestEndpointMethods.VERSION = VERSION; -exports.enterpriseCompatibility = enterpriseCompatibility; +exports.legacyRestEndpointMethods = legacyRestEndpointMethods; +exports.restEndpointMethods = restEndpointMethods; //# sourceMappingURL=index.js.map /***/ }), -/***/ 64193: -/***/ ((__unused_webpack_module, exports) => { +/***/ 86298: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -const VERSION = "2.6.2"; - -/** - * Some “list” response that can be paginated have a different response structure - * - * They have a `total_count` key in the response (search also has `incomplete_results`, - * /installation/repositories also has `repository_selection`), as well as a key with - * the list of the items which name varies from endpoint to endpoint. - * - * Octokit normalizes these responses so that paginated results are always returned following - * the same structure. One challenge is that if the list response has only one page, no Link - * header is provided, so this header alone is not sufficient to check wether a response is - * paginated or not. - * - * We check if a "total_count" key is present in the response data, but also make sure that - * a "url" property is not, as the "Get the combined status for a specific ref" endpoint would - * otherwise match: https://developer.github.com/v3/repos/statuses/#get-the-combined-status-for-a-specific-ref - */ -function normalizePaginatedListResponse(response) { - const responseNeedsNormalization = "total_count" in response.data && !("url" in response.data); - if (!responseNeedsNormalization) return response; // keep the additional properties intact as there is currently no other way - // to retrieve the same information. - - const incompleteResults = response.data.incomplete_results; - const repositorySelection = response.data.repository_selection; - const totalCount = response.data.total_count; - delete response.data.incomplete_results; - delete response.data.repository_selection; - delete response.data.total_count; - const namespaceKey = Object.keys(response.data)[0]; - const data = response.data[namespaceKey]; - response.data = data; - - if (typeof incompleteResults !== "undefined") { - response.data.incomplete_results = incompleteResults; - } - - if (typeof repositorySelection !== "undefined") { - response.data.repository_selection = repositorySelection; - } +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - response.data.total_count = totalCount; - return response; -} +var Bottleneck = _interopDefault(__nccwpck_require__(11174)); -function iterator(octokit, route, parameters) { - const options = typeof route === "function" ? route.endpoint(parameters) : octokit.request.endpoint(route, parameters); - const requestMethod = typeof route === "function" ? route : octokit.request; - const method = options.method; - const headers = options.headers; - let url = options.url; - return { - [Symbol.asyncIterator]: () => ({ - async next() { - if (!url) return { - done: true - }; - const response = await requestMethod({ - method, - url, - headers - }); - const normalizedResponse = normalizePaginatedListResponse(response); // `response.headers.link` format: - // '; rel="next", ; rel="last"' - // sets `url` to undefined if "next" URL is not present or `link` header is not set +// @ts-ignore +async function errorRequest(octokit, state, error, options) { + if (!error.request || !error.request.request) { + // address https://github.com/octokit/plugin-retry.js/issues/8 + throw error; + } // retry all >= 400 && not doNotRetry - url = ((normalizedResponse.headers.link || "").match(/<([^>]+)>;\s*rel="next"/) || [])[1]; - return { - value: normalizedResponse - }; - } - }) - }; -} + if (error.status >= 400 && !state.doNotRetry.includes(error.status)) { + const retries = options.request.retries != null ? options.request.retries : state.retries; + const retryAfter = Math.pow((options.request.retryCount || 0) + 1, 2); + throw octokit.retry.retryRequest(error, retries, retryAfter); + } // Maybe eventually there will be more cases here -function paginate(octokit, route, parameters, mapFn) { - if (typeof parameters === "function") { - mapFn = parameters; - parameters = undefined; - } - return gather(octokit, [], iterator(octokit, route, parameters)[Symbol.asyncIterator](), mapFn); + throw error; } -function gather(octokit, results, iterator, mapFn) { - return iterator.next().then(result => { - if (result.done) { - return results; - } - - let earlyExit = false; +// @ts-ignore - function done() { - earlyExit = true; - } +async function wrapRequest(state, request, options) { + const limiter = new Bottleneck(); // @ts-ignore - results = results.concat(mapFn ? mapFn(result.value, done) : result.value.data); + limiter.on("failed", function (error, info) { + const maxRetries = ~~error.request.request.retries; + const after = ~~error.request.request.retryAfter; + options.request.retryCount = info.retryCount + 1; - if (earlyExit) { - return results; + if (maxRetries > info.retryCount) { + // Returning a number instructs the limiter to retry + // the request after that number of milliseconds have passed + return after * state.retryAfterBaseValue; } - - return gather(octokit, results, iterator, mapFn); }); + return limiter.schedule(request, options); } -const composePaginateRest = Object.assign(paginate, { - iterator -}); +const VERSION = "3.0.6"; +function retry(octokit, octokitOptions = {}) { + const state = Object.assign({ + enabled: true, + retryAfterBaseValue: 1000, + doNotRetry: [400, 401, 403, 404, 422], + retries: 3 + }, octokitOptions.retry); + octokit.retry = { + retryRequest: (error, retries, retryAfter) => { + error.request.request = Object.assign({}, error.request.request, { + retries: retries, + retryAfter: retryAfter + }); + return error; + } + }; -/** - * @param octokit Octokit instance - * @param options Options passed to Octokit constructor - */ + if (!state.enabled) { + return; + } -function paginateRest(octokit) { - return { - paginate: Object.assign(paginate.bind(null, octokit), { - iterator: iterator.bind(null, octokit) - }) - }; + octokit.hook.error("request", errorRequest.bind(null, octokit, state)); + octokit.hook.wrap("request", wrapRequest.bind(null, state)); } -paginateRest.VERSION = VERSION; +retry.VERSION = VERSION; -exports.composePaginateRest = composePaginateRest; -exports.paginateRest = paginateRest; +exports.VERSION = VERSION; +exports.retry = retry; //# sourceMappingURL=index.js.map /***/ }), -/***/ 83044: -/***/ ((__unused_webpack_module, exports) => { +/***/ 9968: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } + +var BottleneckLight = _interopDefault(__nccwpck_require__(11174)); + +function _defineProperty(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + + return obj; +} + function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); - - if (enumerableOnly) { - symbols = symbols.filter(function (sym) { - return Object.getOwnPropertyDescriptor(object, sym).enumerable; - }); - } - + if (enumerableOnly) symbols = symbols.filter(function (sym) { + return Object.getOwnPropertyDescriptor(object, sym).enumerable; + }); keys.push.apply(keys, symbols); } @@ -13172,31519 +5416,39790 @@ function _objectSpread2(target) { return target; } -function _defineProperty(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; +const VERSION = "3.3.4"; + +const noop = () => Promise.resolve(); // @ts-ignore + + +function wrapRequest(state, request, options) { + return state.retryLimiter.schedule(doRequest, state, request, options); +} // @ts-ignore + +async function doRequest(state, request, options) { + const isWrite = options.method !== "GET" && options.method !== "HEAD"; + const isSearch = options.method === "GET" && options.url.startsWith("/search/"); + const isGraphQL = options.url.startsWith("/graphql"); + const retryCount = ~~options.request.retryCount; + const jobOptions = retryCount > 0 ? { + priority: 0, + weight: 0 + } : {}; + + if (state.clustering) { + // Remove a job from Redis if it has not completed or failed within 60s + // Examples: Node process terminated, client disconnected, etc. + // @ts-ignore + jobOptions.expiration = 1000 * 60; + } // Guarantee at least 1000ms between writes + // GraphQL can also trigger writes + + + if (isWrite || isGraphQL) { + await state.write.key(state.id).schedule(jobOptions, noop); + } // Guarantee at least 3000ms between requests that trigger notifications + + + if (isWrite && state.triggersNotification(options.url)) { + await state.notifications.key(state.id).schedule(jobOptions, noop); + } // Guarantee at least 2000ms between search requests + + + if (isSearch) { + await state.search.key(state.id).schedule(jobOptions, noop); } - return obj; + const req = state.global.key(state.id).schedule(jobOptions, request, options); + + if (isGraphQL) { + const res = await req; + + if (res.data.errors != null && // @ts-ignore + res.data.errors.some(error => error.type === "RATE_LIMITED")) { + const error = Object.assign(new Error("GraphQL Rate Limit Exceeded"), { + headers: res.headers, + data: res.data + }); + throw error; + } + } + + return req; } -const Endpoints = { - actions: { - addSelectedRepoToOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}"], - approveWorkflowRun: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/approve"], - cancelWorkflowRun: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/cancel"], - createOrUpdateEnvironmentSecret: ["PUT /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}"], - createOrUpdateOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}"], - createOrUpdateRepoSecret: ["PUT /repos/{owner}/{repo}/actions/secrets/{secret_name}"], - createRegistrationTokenForOrg: ["POST /orgs/{org}/actions/runners/registration-token"], - createRegistrationTokenForRepo: ["POST /repos/{owner}/{repo}/actions/runners/registration-token"], - createRemoveTokenForOrg: ["POST /orgs/{org}/actions/runners/remove-token"], - createRemoveTokenForRepo: ["POST /repos/{owner}/{repo}/actions/runners/remove-token"], - createWorkflowDispatch: ["POST /repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches"], - deleteArtifact: ["DELETE /repos/{owner}/{repo}/actions/artifacts/{artifact_id}"], - deleteEnvironmentSecret: ["DELETE /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}"], - deleteOrgSecret: ["DELETE /orgs/{org}/actions/secrets/{secret_name}"], - deleteRepoSecret: ["DELETE /repos/{owner}/{repo}/actions/secrets/{secret_name}"], - deleteSelfHostedRunnerFromOrg: ["DELETE /orgs/{org}/actions/runners/{runner_id}"], - deleteSelfHostedRunnerFromRepo: ["DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}"], - deleteWorkflowRun: ["DELETE /repos/{owner}/{repo}/actions/runs/{run_id}"], - deleteWorkflowRunLogs: ["DELETE /repos/{owner}/{repo}/actions/runs/{run_id}/logs"], - disableSelectedRepositoryGithubActionsOrganization: ["DELETE /orgs/{org}/actions/permissions/repositories/{repository_id}"], - disableWorkflow: ["PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/disable"], - downloadArtifact: ["GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}/{archive_format}"], - downloadJobLogsForWorkflowRun: ["GET /repos/{owner}/{repo}/actions/jobs/{job_id}/logs"], - downloadWorkflowRunAttemptLogs: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/logs"], - downloadWorkflowRunLogs: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/logs"], - enableSelectedRepositoryGithubActionsOrganization: ["PUT /orgs/{org}/actions/permissions/repositories/{repository_id}"], - enableWorkflow: ["PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/enable"], - getAllowedActionsOrganization: ["GET /orgs/{org}/actions/permissions/selected-actions"], - getAllowedActionsRepository: ["GET /repos/{owner}/{repo}/actions/permissions/selected-actions"], - getArtifact: ["GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}"], - getEnvironmentPublicKey: ["GET /repositories/{repository_id}/environments/{environment_name}/secrets/public-key"], - getEnvironmentSecret: ["GET /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}"], - getGithubActionsPermissionsOrganization: ["GET /orgs/{org}/actions/permissions"], - getGithubActionsPermissionsRepository: ["GET /repos/{owner}/{repo}/actions/permissions"], - getJobForWorkflowRun: ["GET /repos/{owner}/{repo}/actions/jobs/{job_id}"], - getOrgPublicKey: ["GET /orgs/{org}/actions/secrets/public-key"], - getOrgSecret: ["GET /orgs/{org}/actions/secrets/{secret_name}"], - getPendingDeploymentsForRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments"], - getRepoPermissions: ["GET /repos/{owner}/{repo}/actions/permissions", {}, { - renamed: ["actions", "getGithubActionsPermissionsRepository"] - }], - getRepoPublicKey: ["GET /repos/{owner}/{repo}/actions/secrets/public-key"], - getRepoSecret: ["GET /repos/{owner}/{repo}/actions/secrets/{secret_name}"], - getReviewsForRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/approvals"], - getSelfHostedRunnerForOrg: ["GET /orgs/{org}/actions/runners/{runner_id}"], - getSelfHostedRunnerForRepo: ["GET /repos/{owner}/{repo}/actions/runners/{runner_id}"], - getWorkflow: ["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}"], - getWorkflowRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}"], - getWorkflowRunAttempt: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}"], - getWorkflowRunUsage: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/timing"], - getWorkflowUsage: ["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/timing"], - listArtifactsForRepo: ["GET /repos/{owner}/{repo}/actions/artifacts"], - listEnvironmentSecrets: ["GET /repositories/{repository_id}/environments/{environment_name}/secrets"], - listJobsForWorkflowRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs"], - listJobsForWorkflowRunAttempt: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs"], - listOrgSecrets: ["GET /orgs/{org}/actions/secrets"], - listRepoSecrets: ["GET /repos/{owner}/{repo}/actions/secrets"], - listRepoWorkflows: ["GET /repos/{owner}/{repo}/actions/workflows"], - listRunnerApplicationsForOrg: ["GET /orgs/{org}/actions/runners/downloads"], - listRunnerApplicationsForRepo: ["GET /repos/{owner}/{repo}/actions/runners/downloads"], - listSelectedReposForOrgSecret: ["GET /orgs/{org}/actions/secrets/{secret_name}/repositories"], - listSelectedRepositoriesEnabledGithubActionsOrganization: ["GET /orgs/{org}/actions/permissions/repositories"], - listSelfHostedRunnersForOrg: ["GET /orgs/{org}/actions/runners"], - listSelfHostedRunnersForRepo: ["GET /repos/{owner}/{repo}/actions/runners"], - listWorkflowRunArtifacts: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts"], - listWorkflowRuns: ["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs"], - listWorkflowRunsForRepo: ["GET /repos/{owner}/{repo}/actions/runs"], - removeSelectedRepoFromOrgSecret: ["DELETE /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}"], - reviewPendingDeploymentsForRun: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments"], - setAllowedActionsOrganization: ["PUT /orgs/{org}/actions/permissions/selected-actions"], - setAllowedActionsRepository: ["PUT /repos/{owner}/{repo}/actions/permissions/selected-actions"], - setGithubActionsPermissionsOrganization: ["PUT /orgs/{org}/actions/permissions"], - setGithubActionsPermissionsRepository: ["PUT /repos/{owner}/{repo}/actions/permissions"], - setSelectedReposForOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}/repositories"], - setSelectedRepositoriesEnabledGithubActionsOrganization: ["PUT /orgs/{org}/actions/permissions/repositories"] - }, - activity: { - checkRepoIsStarredByAuthenticatedUser: ["GET /user/starred/{owner}/{repo}"], - deleteRepoSubscription: ["DELETE /repos/{owner}/{repo}/subscription"], - deleteThreadSubscription: ["DELETE /notifications/threads/{thread_id}/subscription"], - getFeeds: ["GET /feeds"], - getRepoSubscription: ["GET /repos/{owner}/{repo}/subscription"], - getThread: ["GET /notifications/threads/{thread_id}"], - getThreadSubscriptionForAuthenticatedUser: ["GET /notifications/threads/{thread_id}/subscription"], - listEventsForAuthenticatedUser: ["GET /users/{username}/events"], - listNotificationsForAuthenticatedUser: ["GET /notifications"], - listOrgEventsForAuthenticatedUser: ["GET /users/{username}/events/orgs/{org}"], - listPublicEvents: ["GET /events"], - listPublicEventsForRepoNetwork: ["GET /networks/{owner}/{repo}/events"], - listPublicEventsForUser: ["GET /users/{username}/events/public"], - listPublicOrgEvents: ["GET /orgs/{org}/events"], - listReceivedEventsForUser: ["GET /users/{username}/received_events"], - listReceivedPublicEventsForUser: ["GET /users/{username}/received_events/public"], - listRepoEvents: ["GET /repos/{owner}/{repo}/events"], - listRepoNotificationsForAuthenticatedUser: ["GET /repos/{owner}/{repo}/notifications"], - listReposStarredByAuthenticatedUser: ["GET /user/starred"], - listReposStarredByUser: ["GET /users/{username}/starred"], - listReposWatchedByUser: ["GET /users/{username}/subscriptions"], - listStargazersForRepo: ["GET /repos/{owner}/{repo}/stargazers"], - listWatchedReposForAuthenticatedUser: ["GET /user/subscriptions"], - listWatchersForRepo: ["GET /repos/{owner}/{repo}/subscribers"], - markNotificationsAsRead: ["PUT /notifications"], - markRepoNotificationsAsRead: ["PUT /repos/{owner}/{repo}/notifications"], - markThreadAsRead: ["PATCH /notifications/threads/{thread_id}"], - setRepoSubscription: ["PUT /repos/{owner}/{repo}/subscription"], - setThreadSubscription: ["PUT /notifications/threads/{thread_id}/subscription"], - starRepoForAuthenticatedUser: ["PUT /user/starred/{owner}/{repo}"], - unstarRepoForAuthenticatedUser: ["DELETE /user/starred/{owner}/{repo}"] - }, - apps: { - addRepoToInstallation: ["PUT /user/installations/{installation_id}/repositories/{repository_id}", {}, { - renamed: ["apps", "addRepoToInstallationForAuthenticatedUser"] - }], - addRepoToInstallationForAuthenticatedUser: ["PUT /user/installations/{installation_id}/repositories/{repository_id}"], - checkToken: ["POST /applications/{client_id}/token"], - createContentAttachment: ["POST /content_references/{content_reference_id}/attachments", { - mediaType: { - previews: ["corsair"] - } - }], - createContentAttachmentForRepo: ["POST /repos/{owner}/{repo}/content_references/{content_reference_id}/attachments", { - mediaType: { - previews: ["corsair"] +var triggersNotificationPaths = ["/orgs/{org}/invitations", "/orgs/{org}/teams/{team_slug}/discussions", "/orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments", "/repos/{owner}/{repo}/collaborators/{username}", "/repos/{owner}/{repo}/commits/{commit_sha}/comments", "/repos/{owner}/{repo}/issues", "/repos/{owner}/{repo}/issues/{issue_number}/comments", "/repos/{owner}/{repo}/pulls", "/repos/{owner}/{repo}/pulls/{pull_number}/comments", "/repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies", "/repos/{owner}/{repo}/pulls/{pull_number}/merge", "/repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers", "/repos/{owner}/{repo}/pulls/{pull_number}/reviews", "/repos/{owner}/{repo}/releases", "/teams/{team_id}/discussions", "/teams/{team_id}/discussions/{discussion_number}/comments"]; + +// @ts-ignore +function routeMatcher(paths) { + // EXAMPLE. For the following paths: + + /* [ + "/orgs/:org/invitations", + "/repos/:owner/:repo/collaborators/:username" + ] */ + // @ts-ignore + const regexes = paths.map(path => path.split("/") // @ts-ignore + .map(c => c.startsWith("{") ? "(?:.+?)" : c).join("/")); // 'regexes' would contain: + + /* [ + '/orgs/(?:.+?)/invitations', + '/repos/(?:.+?)/(?:.+?)/collaborators/(?:.+?)' + ] */ + // @ts-ignore + + const regex = `^(?:${regexes.map(r => `(?:${r})`).join("|")})[^/]*$`; // 'regex' would contain: + + /* + ^(?:(?:\/orgs\/(?:.+?)\/invitations)|(?:\/repos\/(?:.+?)\/(?:.+?)\/collaborators\/(?:.+?)))[^\/]*$ + It may look scary, but paste it into https://www.debuggex.com/ + and it will make a lot more sense! + */ + + return new RegExp(regex, "i"); +} + +const regex = routeMatcher(triggersNotificationPaths); +const triggersNotification = regex.test.bind(regex); +const groups = {}; // @ts-ignore + +const createGroups = function (Bottleneck, common) { + // @ts-ignore + groups.global = new Bottleneck.Group(_objectSpread2({ + id: "octokit-global", + maxConcurrent: 10 + }, common)); // @ts-ignore + + groups.search = new Bottleneck.Group(_objectSpread2({ + id: "octokit-search", + maxConcurrent: 1, + minTime: 2000 + }, common)); // @ts-ignore + + groups.write = new Bottleneck.Group(_objectSpread2({ + id: "octokit-write", + maxConcurrent: 1, + minTime: 1000 + }, common)); // @ts-ignore + + groups.notifications = new Bottleneck.Group(_objectSpread2({ + id: "octokit-notifications", + maxConcurrent: 1, + minTime: 3000 + }, common)); +}; + +function throttling(octokit, octokitOptions = {}) { + const { + enabled = true, + Bottleneck = BottleneckLight, + id = "no-id", + timeout = 1000 * 60 * 2, + // Redis TTL: 2 minutes + connection + } = octokitOptions.throttle || {}; + + if (!enabled) { + return; + } + + const common = { + connection, + timeout + }; // @ts-ignore + + if (groups.global == null) { + createGroups(Bottleneck, common); + } + + const state = Object.assign(_objectSpread2({ + clustering: connection != null, + triggersNotification, + minimumAbuseRetryAfter: 5, + retryAfterBaseValue: 1000, + retryLimiter: new Bottleneck(), + id + }, groups), // @ts-ignore + octokitOptions.throttle); + + if (typeof state.onAbuseLimit !== "function" || typeof state.onRateLimit !== "function") { + throw new Error(`octokit/plugin-throttling error: + You must pass the onAbuseLimit and onRateLimit error handlers. + See https://github.com/octokit/rest.js#throttling + + const octokit = new Octokit({ + throttle: { + onAbuseLimit: (retryAfter, options) => {/* ... */}, + onRateLimit: (retryAfter, options) => {/* ... */} + } + }) + `); + } + + const events = {}; + const emitter = new Bottleneck.Events(events); // @ts-ignore + + events.on("abuse-limit", state.onAbuseLimit); // @ts-ignore + + events.on("rate-limit", state.onRateLimit); // @ts-ignore + + events.on("error", e => console.warn("Error in throttling-plugin limit handler", e)); // @ts-ignore + + state.retryLimiter.on("failed", async function (error, info) { + const options = info.args[info.args.length - 1]; + const shouldRetryGraphQL = options.url.startsWith("/graphql") && error.status !== 401; + + if (!(shouldRetryGraphQL || error.status === 403)) { + return; + } + + const retryCount = ~~options.request.retryCount; + options.request.retryCount = retryCount; + const { + wantRetry, + retryAfter + } = await async function () { + if (/\babuse\b/i.test(error.message)) { + // The user has hit the abuse rate limit. (REST and GraphQL) + // https://docs.github.com/en/rest/overview/resources-in-the-rest-api#abuse-rate-limits + // The Retry-After header can sometimes be blank when hitting an abuse limit, + // but is always present after 2-3s, so make sure to set `retryAfter` to at least 5s by default. + const retryAfter = Math.max(~~error.headers["retry-after"], state.minimumAbuseRetryAfter); + const wantRetry = await emitter.trigger("abuse-limit", retryAfter, options, octokit); + return { + wantRetry, + retryAfter + }; } - }], - createFromManifest: ["POST /app-manifests/{code}/conversions"], - createInstallationAccessToken: ["POST /app/installations/{installation_id}/access_tokens"], - deleteAuthorization: ["DELETE /applications/{client_id}/grant"], - deleteInstallation: ["DELETE /app/installations/{installation_id}"], - deleteToken: ["DELETE /applications/{client_id}/token"], - getAuthenticated: ["GET /app"], - getBySlug: ["GET /apps/{app_slug}"], - getInstallation: ["GET /app/installations/{installation_id}"], - getOrgInstallation: ["GET /orgs/{org}/installation"], - getRepoInstallation: ["GET /repos/{owner}/{repo}/installation"], - getSubscriptionPlanForAccount: ["GET /marketplace_listing/accounts/{account_id}"], - getSubscriptionPlanForAccountStubbed: ["GET /marketplace_listing/stubbed/accounts/{account_id}"], - getUserInstallation: ["GET /users/{username}/installation"], - getWebhookConfigForApp: ["GET /app/hook/config"], - getWebhookDelivery: ["GET /app/hook/deliveries/{delivery_id}"], - listAccountsForPlan: ["GET /marketplace_listing/plans/{plan_id}/accounts"], - listAccountsForPlanStubbed: ["GET /marketplace_listing/stubbed/plans/{plan_id}/accounts"], - listInstallationReposForAuthenticatedUser: ["GET /user/installations/{installation_id}/repositories"], - listInstallations: ["GET /app/installations"], - listInstallationsForAuthenticatedUser: ["GET /user/installations"], - listPlans: ["GET /marketplace_listing/plans"], - listPlansStubbed: ["GET /marketplace_listing/stubbed/plans"], - listReposAccessibleToInstallation: ["GET /installation/repositories"], - listSubscriptionsForAuthenticatedUser: ["GET /user/marketplace_purchases"], - listSubscriptionsForAuthenticatedUserStubbed: ["GET /user/marketplace_purchases/stubbed"], - listWebhookDeliveries: ["GET /app/hook/deliveries"], - redeliverWebhookDelivery: ["POST /app/hook/deliveries/{delivery_id}/attempts"], - removeRepoFromInstallation: ["DELETE /user/installations/{installation_id}/repositories/{repository_id}", {}, { - renamed: ["apps", "removeRepoFromInstallationForAuthenticatedUser"] - }], - removeRepoFromInstallationForAuthenticatedUser: ["DELETE /user/installations/{installation_id}/repositories/{repository_id}"], - resetToken: ["PATCH /applications/{client_id}/token"], - revokeInstallationAccessToken: ["DELETE /installation/token"], - scopeToken: ["POST /applications/{client_id}/token/scoped"], - suspendInstallation: ["PUT /app/installations/{installation_id}/suspended"], - unsuspendInstallation: ["DELETE /app/installations/{installation_id}/suspended"], - updateWebhookConfigForApp: ["PATCH /app/hook/config"] - }, - billing: { - getGithubActionsBillingOrg: ["GET /orgs/{org}/settings/billing/actions"], - getGithubActionsBillingUser: ["GET /users/{username}/settings/billing/actions"], - getGithubPackagesBillingOrg: ["GET /orgs/{org}/settings/billing/packages"], - getGithubPackagesBillingUser: ["GET /users/{username}/settings/billing/packages"], - getSharedStorageBillingOrg: ["GET /orgs/{org}/settings/billing/shared-storage"], - getSharedStorageBillingUser: ["GET /users/{username}/settings/billing/shared-storage"] - }, - checks: { - create: ["POST /repos/{owner}/{repo}/check-runs"], - createSuite: ["POST /repos/{owner}/{repo}/check-suites"], - get: ["GET /repos/{owner}/{repo}/check-runs/{check_run_id}"], - getSuite: ["GET /repos/{owner}/{repo}/check-suites/{check_suite_id}"], - listAnnotations: ["GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations"], - listForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-runs"], - listForSuite: ["GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs"], - listSuitesForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-suites"], - rerequestRun: ["POST /repos/{owner}/{repo}/check-runs/{check_run_id}/rerequest"], - rerequestSuite: ["POST /repos/{owner}/{repo}/check-suites/{check_suite_id}/rerequest"], - setSuitesPreferences: ["PATCH /repos/{owner}/{repo}/check-suites/preferences"], - update: ["PATCH /repos/{owner}/{repo}/check-runs/{check_run_id}"] - }, - codeScanning: { - deleteAnalysis: ["DELETE /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}{?confirm_delete}"], - getAlert: ["GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}", {}, { - renamedParameters: { - alert_id: "alert_number" + + if (error.headers != null && error.headers["x-ratelimit-remaining"] === "0") { + // The user has used all their allowed calls for the current time period (REST and GraphQL) + // https://docs.github.com/en/rest/reference/rate-limit (REST) + // https://docs.github.com/en/graphql/overview/resource-limitations#rate-limit (GraphQL) + const rateLimitReset = new Date(~~error.headers["x-ratelimit-reset"] * 1000).getTime(); + const retryAfter = Math.max(Math.ceil((rateLimitReset - Date.now()) / 1000), 0); + const wantRetry = await emitter.trigger("rate-limit", retryAfter, options, octokit); + return { + wantRetry, + retryAfter + }; } - }], - getAnalysis: ["GET /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}"], - getSarif: ["GET /repos/{owner}/{repo}/code-scanning/sarifs/{sarif_id}"], - listAlertInstances: ["GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances"], - listAlertsForRepo: ["GET /repos/{owner}/{repo}/code-scanning/alerts"], - listAlertsInstances: ["GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances", {}, { - renamed: ["codeScanning", "listAlertInstances"] - }], - listRecentAnalyses: ["GET /repos/{owner}/{repo}/code-scanning/analyses"], - updateAlert: ["PATCH /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}"], - uploadSarif: ["POST /repos/{owner}/{repo}/code-scanning/sarifs"] - }, - codesOfConduct: { - getAllCodesOfConduct: ["GET /codes_of_conduct"], - getConductCode: ["GET /codes_of_conduct/{key}"] - }, - emojis: { - get: ["GET /emojis"] - }, - enterpriseAdmin: { - disableSelectedOrganizationGithubActionsEnterprise: ["DELETE /enterprises/{enterprise}/actions/permissions/organizations/{org_id}"], - enableSelectedOrganizationGithubActionsEnterprise: ["PUT /enterprises/{enterprise}/actions/permissions/organizations/{org_id}"], - getAllowedActionsEnterprise: ["GET /enterprises/{enterprise}/actions/permissions/selected-actions"], - getGithubActionsPermissionsEnterprise: ["GET /enterprises/{enterprise}/actions/permissions"], - listSelectedOrganizationsEnabledGithubActionsEnterprise: ["GET /enterprises/{enterprise}/actions/permissions/organizations"], - setAllowedActionsEnterprise: ["PUT /enterprises/{enterprise}/actions/permissions/selected-actions"], - setGithubActionsPermissionsEnterprise: ["PUT /enterprises/{enterprise}/actions/permissions"], - setSelectedOrganizationsEnabledGithubActionsEnterprise: ["PUT /enterprises/{enterprise}/actions/permissions/organizations"] - }, - gists: { - checkIsStarred: ["GET /gists/{gist_id}/star"], - create: ["POST /gists"], - createComment: ["POST /gists/{gist_id}/comments"], - delete: ["DELETE /gists/{gist_id}"], - deleteComment: ["DELETE /gists/{gist_id}/comments/{comment_id}"], - fork: ["POST /gists/{gist_id}/forks"], - get: ["GET /gists/{gist_id}"], - getComment: ["GET /gists/{gist_id}/comments/{comment_id}"], - getRevision: ["GET /gists/{gist_id}/{sha}"], - list: ["GET /gists"], - listComments: ["GET /gists/{gist_id}/comments"], - listCommits: ["GET /gists/{gist_id}/commits"], - listForUser: ["GET /users/{username}/gists"], - listForks: ["GET /gists/{gist_id}/forks"], - listPublic: ["GET /gists/public"], - listStarred: ["GET /gists/starred"], - star: ["PUT /gists/{gist_id}/star"], - unstar: ["DELETE /gists/{gist_id}/star"], - update: ["PATCH /gists/{gist_id}"], - updateComment: ["PATCH /gists/{gist_id}/comments/{comment_id}"] - }, - git: { - createBlob: ["POST /repos/{owner}/{repo}/git/blobs"], - createCommit: ["POST /repos/{owner}/{repo}/git/commits"], - createRef: ["POST /repos/{owner}/{repo}/git/refs"], - createTag: ["POST /repos/{owner}/{repo}/git/tags"], - createTree: ["POST /repos/{owner}/{repo}/git/trees"], - deleteRef: ["DELETE /repos/{owner}/{repo}/git/refs/{ref}"], - getBlob: ["GET /repos/{owner}/{repo}/git/blobs/{file_sha}"], - getCommit: ["GET /repos/{owner}/{repo}/git/commits/{commit_sha}"], - getRef: ["GET /repos/{owner}/{repo}/git/ref/{ref}"], - getTag: ["GET /repos/{owner}/{repo}/git/tags/{tag_sha}"], - getTree: ["GET /repos/{owner}/{repo}/git/trees/{tree_sha}"], - listMatchingRefs: ["GET /repos/{owner}/{repo}/git/matching-refs/{ref}"], - updateRef: ["PATCH /repos/{owner}/{repo}/git/refs/{ref}"] - }, - gitignore: { - getAllTemplates: ["GET /gitignore/templates"], - getTemplate: ["GET /gitignore/templates/{name}"] - }, - interactions: { - getRestrictionsForAuthenticatedUser: ["GET /user/interaction-limits"], - getRestrictionsForOrg: ["GET /orgs/{org}/interaction-limits"], - getRestrictionsForRepo: ["GET /repos/{owner}/{repo}/interaction-limits"], - getRestrictionsForYourPublicRepos: ["GET /user/interaction-limits", {}, { - renamed: ["interactions", "getRestrictionsForAuthenticatedUser"] - }], - removeRestrictionsForAuthenticatedUser: ["DELETE /user/interaction-limits"], - removeRestrictionsForOrg: ["DELETE /orgs/{org}/interaction-limits"], - removeRestrictionsForRepo: ["DELETE /repos/{owner}/{repo}/interaction-limits"], - removeRestrictionsForYourPublicRepos: ["DELETE /user/interaction-limits", {}, { - renamed: ["interactions", "removeRestrictionsForAuthenticatedUser"] - }], - setRestrictionsForAuthenticatedUser: ["PUT /user/interaction-limits"], - setRestrictionsForOrg: ["PUT /orgs/{org}/interaction-limits"], - setRestrictionsForRepo: ["PUT /repos/{owner}/{repo}/interaction-limits"], - setRestrictionsForYourPublicRepos: ["PUT /user/interaction-limits", {}, { - renamed: ["interactions", "setRestrictionsForAuthenticatedUser"] - }] - }, - issues: { - addAssignees: ["POST /repos/{owner}/{repo}/issues/{issue_number}/assignees"], - addLabels: ["POST /repos/{owner}/{repo}/issues/{issue_number}/labels"], - checkUserCanBeAssigned: ["GET /repos/{owner}/{repo}/assignees/{assignee}"], - create: ["POST /repos/{owner}/{repo}/issues"], - createComment: ["POST /repos/{owner}/{repo}/issues/{issue_number}/comments"], - createLabel: ["POST /repos/{owner}/{repo}/labels"], - createMilestone: ["POST /repos/{owner}/{repo}/milestones"], - deleteComment: ["DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}"], - deleteLabel: ["DELETE /repos/{owner}/{repo}/labels/{name}"], - deleteMilestone: ["DELETE /repos/{owner}/{repo}/milestones/{milestone_number}"], - get: ["GET /repos/{owner}/{repo}/issues/{issue_number}"], - getComment: ["GET /repos/{owner}/{repo}/issues/comments/{comment_id}"], - getEvent: ["GET /repos/{owner}/{repo}/issues/events/{event_id}"], - getLabel: ["GET /repos/{owner}/{repo}/labels/{name}"], - getMilestone: ["GET /repos/{owner}/{repo}/milestones/{milestone_number}"], - list: ["GET /issues"], - listAssignees: ["GET /repos/{owner}/{repo}/assignees"], - listComments: ["GET /repos/{owner}/{repo}/issues/{issue_number}/comments"], - listCommentsForRepo: ["GET /repos/{owner}/{repo}/issues/comments"], - listEvents: ["GET /repos/{owner}/{repo}/issues/{issue_number}/events"], - listEventsForRepo: ["GET /repos/{owner}/{repo}/issues/events"], - listEventsForTimeline: ["GET /repos/{owner}/{repo}/issues/{issue_number}/timeline"], - listForAuthenticatedUser: ["GET /user/issues"], - listForOrg: ["GET /orgs/{org}/issues"], - listForRepo: ["GET /repos/{owner}/{repo}/issues"], - listLabelsForMilestone: ["GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels"], - listLabelsForRepo: ["GET /repos/{owner}/{repo}/labels"], - listLabelsOnIssue: ["GET /repos/{owner}/{repo}/issues/{issue_number}/labels"], - listMilestones: ["GET /repos/{owner}/{repo}/milestones"], - lock: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/lock"], - removeAllLabels: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels"], - removeAssignees: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/assignees"], - removeLabel: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels/{name}"], - setLabels: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/labels"], - unlock: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/lock"], - update: ["PATCH /repos/{owner}/{repo}/issues/{issue_number}"], - updateComment: ["PATCH /repos/{owner}/{repo}/issues/comments/{comment_id}"], - updateLabel: ["PATCH /repos/{owner}/{repo}/labels/{name}"], - updateMilestone: ["PATCH /repos/{owner}/{repo}/milestones/{milestone_number}"] - }, - licenses: { - get: ["GET /licenses/{license}"], - getAllCommonlyUsed: ["GET /licenses"], - getForRepo: ["GET /repos/{owner}/{repo}/license"] - }, - markdown: { - render: ["POST /markdown"], - renderRaw: ["POST /markdown/raw", { - headers: { - "content-type": "text/plain; charset=utf-8" + + return {}; + }(); + + if (wantRetry) { + options.request.retryCount++; // @ts-ignore + + return retryAfter * state.retryAfterBaseValue; + } + }); + octokit.hook.wrap("request", wrapRequest.bind(null, state)); +} +throttling.VERSION = VERSION; +throttling.triggersNotification = triggersNotification; + +exports.throttling = throttling; +//# sourceMappingURL=index.js.map + + +/***/ }), + +/***/ 10537: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } + +var deprecation = __nccwpck_require__(58932); +var once = _interopDefault(__nccwpck_require__(1223)); + +const logOnce = once(deprecation => console.warn(deprecation)); +/** + * Error with extra properties to help with debugging + */ + +class RequestError extends Error { + constructor(message, statusCode, options) { + super(message); // Maintains proper stack trace (only available on V8) + + /* istanbul ignore next */ + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + + this.name = "HttpError"; + this.status = statusCode; + Object.defineProperty(this, "code", { + get() { + logOnce(new deprecation.Deprecation("[@octokit/request-error] `error.code` is deprecated, use `error.status`.")); + return statusCode; } - }] - }, - meta: { - get: ["GET /meta"], - getOctocat: ["GET /octocat"], - getZen: ["GET /zen"], - root: ["GET /"] - }, - migrations: { - cancelImport: ["DELETE /repos/{owner}/{repo}/import"], - deleteArchiveForAuthenticatedUser: ["DELETE /user/migrations/{migration_id}/archive"], - deleteArchiveForOrg: ["DELETE /orgs/{org}/migrations/{migration_id}/archive"], - downloadArchiveForOrg: ["GET /orgs/{org}/migrations/{migration_id}/archive"], - getArchiveForAuthenticatedUser: ["GET /user/migrations/{migration_id}/archive"], - getCommitAuthors: ["GET /repos/{owner}/{repo}/import/authors"], - getImportStatus: ["GET /repos/{owner}/{repo}/import"], - getLargeFiles: ["GET /repos/{owner}/{repo}/import/large_files"], - getStatusForAuthenticatedUser: ["GET /user/migrations/{migration_id}"], - getStatusForOrg: ["GET /orgs/{org}/migrations/{migration_id}"], - listForAuthenticatedUser: ["GET /user/migrations"], - listForOrg: ["GET /orgs/{org}/migrations"], - listReposForAuthenticatedUser: ["GET /user/migrations/{migration_id}/repositories"], - listReposForOrg: ["GET /orgs/{org}/migrations/{migration_id}/repositories"], - listReposForUser: ["GET /user/migrations/{migration_id}/repositories", {}, { - renamed: ["migrations", "listReposForAuthenticatedUser"] - }], - mapCommitAuthor: ["PATCH /repos/{owner}/{repo}/import/authors/{author_id}"], - setLfsPreference: ["PATCH /repos/{owner}/{repo}/import/lfs"], - startForAuthenticatedUser: ["POST /user/migrations"], - startForOrg: ["POST /orgs/{org}/migrations"], - startImport: ["PUT /repos/{owner}/{repo}/import"], - unlockRepoForAuthenticatedUser: ["DELETE /user/migrations/{migration_id}/repos/{repo_name}/lock"], - unlockRepoForOrg: ["DELETE /orgs/{org}/migrations/{migration_id}/repos/{repo_name}/lock"], - updateImport: ["PATCH /repos/{owner}/{repo}/import"] - }, - orgs: { - blockUser: ["PUT /orgs/{org}/blocks/{username}"], - cancelInvitation: ["DELETE /orgs/{org}/invitations/{invitation_id}"], - checkBlockedUser: ["GET /orgs/{org}/blocks/{username}"], - checkMembershipForUser: ["GET /orgs/{org}/members/{username}"], - checkPublicMembershipForUser: ["GET /orgs/{org}/public_members/{username}"], - convertMemberToOutsideCollaborator: ["PUT /orgs/{org}/outside_collaborators/{username}"], - createInvitation: ["POST /orgs/{org}/invitations"], - createWebhook: ["POST /orgs/{org}/hooks"], - deleteWebhook: ["DELETE /orgs/{org}/hooks/{hook_id}"], - get: ["GET /orgs/{org}"], - getMembershipForAuthenticatedUser: ["GET /user/memberships/orgs/{org}"], - getMembershipForUser: ["GET /orgs/{org}/memberships/{username}"], - getWebhook: ["GET /orgs/{org}/hooks/{hook_id}"], - getWebhookConfigForOrg: ["GET /orgs/{org}/hooks/{hook_id}/config"], - getWebhookDelivery: ["GET /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}"], - list: ["GET /organizations"], - listAppInstallations: ["GET /orgs/{org}/installations"], - listBlockedUsers: ["GET /orgs/{org}/blocks"], - listFailedInvitations: ["GET /orgs/{org}/failed_invitations"], - listForAuthenticatedUser: ["GET /user/orgs"], - listForUser: ["GET /users/{username}/orgs"], - listInvitationTeams: ["GET /orgs/{org}/invitations/{invitation_id}/teams"], - listMembers: ["GET /orgs/{org}/members"], - listMembershipsForAuthenticatedUser: ["GET /user/memberships/orgs"], - listOutsideCollaborators: ["GET /orgs/{org}/outside_collaborators"], - listPendingInvitations: ["GET /orgs/{org}/invitations"], - listPublicMembers: ["GET /orgs/{org}/public_members"], - listWebhookDeliveries: ["GET /orgs/{org}/hooks/{hook_id}/deliveries"], - listWebhooks: ["GET /orgs/{org}/hooks"], - pingWebhook: ["POST /orgs/{org}/hooks/{hook_id}/pings"], - redeliverWebhookDelivery: ["POST /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}/attempts"], - removeMember: ["DELETE /orgs/{org}/members/{username}"], - removeMembershipForUser: ["DELETE /orgs/{org}/memberships/{username}"], - removeOutsideCollaborator: ["DELETE /orgs/{org}/outside_collaborators/{username}"], - removePublicMembershipForAuthenticatedUser: ["DELETE /orgs/{org}/public_members/{username}"], - setMembershipForUser: ["PUT /orgs/{org}/memberships/{username}"], - setPublicMembershipForAuthenticatedUser: ["PUT /orgs/{org}/public_members/{username}"], - unblockUser: ["DELETE /orgs/{org}/blocks/{username}"], - update: ["PATCH /orgs/{org}"], - updateMembershipForAuthenticatedUser: ["PATCH /user/memberships/orgs/{org}"], - updateWebhook: ["PATCH /orgs/{org}/hooks/{hook_id}"], - updateWebhookConfigForOrg: ["PATCH /orgs/{org}/hooks/{hook_id}/config"] - }, - packages: { - deletePackageForAuthenticatedUser: ["DELETE /user/packages/{package_type}/{package_name}"], - deletePackageForOrg: ["DELETE /orgs/{org}/packages/{package_type}/{package_name}"], - deletePackageForUser: ["DELETE /users/{username}/packages/{package_type}/{package_name}"], - deletePackageVersionForAuthenticatedUser: ["DELETE /user/packages/{package_type}/{package_name}/versions/{package_version_id}"], - deletePackageVersionForOrg: ["DELETE /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}"], - deletePackageVersionForUser: ["DELETE /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}"], - getAllPackageVersionsForAPackageOwnedByAnOrg: ["GET /orgs/{org}/packages/{package_type}/{package_name}/versions", {}, { - renamed: ["packages", "getAllPackageVersionsForPackageOwnedByOrg"] - }], - getAllPackageVersionsForAPackageOwnedByTheAuthenticatedUser: ["GET /user/packages/{package_type}/{package_name}/versions", {}, { - renamed: ["packages", "getAllPackageVersionsForPackageOwnedByAuthenticatedUser"] - }], - getAllPackageVersionsForPackageOwnedByAuthenticatedUser: ["GET /user/packages/{package_type}/{package_name}/versions"], - getAllPackageVersionsForPackageOwnedByOrg: ["GET /orgs/{org}/packages/{package_type}/{package_name}/versions"], - getAllPackageVersionsForPackageOwnedByUser: ["GET /users/{username}/packages/{package_type}/{package_name}/versions"], - getPackageForAuthenticatedUser: ["GET /user/packages/{package_type}/{package_name}"], - getPackageForOrganization: ["GET /orgs/{org}/packages/{package_type}/{package_name}"], - getPackageForUser: ["GET /users/{username}/packages/{package_type}/{package_name}"], - getPackageVersionForAuthenticatedUser: ["GET /user/packages/{package_type}/{package_name}/versions/{package_version_id}"], - getPackageVersionForOrganization: ["GET /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}"], - getPackageVersionForUser: ["GET /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}"], - listPackagesForAuthenticatedUser: ["GET /user/packages"], - listPackagesForOrganization: ["GET /orgs/{org}/packages"], - listPackagesForUser: ["GET /users/{username}/packages"], - restorePackageForAuthenticatedUser: ["POST /user/packages/{package_type}/{package_name}/restore{?token}"], - restorePackageForOrg: ["POST /orgs/{org}/packages/{package_type}/{package_name}/restore{?token}"], - restorePackageForUser: ["POST /users/{username}/packages/{package_type}/{package_name}/restore{?token}"], - restorePackageVersionForAuthenticatedUser: ["POST /user/packages/{package_type}/{package_name}/versions/{package_version_id}/restore"], - restorePackageVersionForOrg: ["POST /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore"], - restorePackageVersionForUser: ["POST /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore"] - }, - projects: { - addCollaborator: ["PUT /projects/{project_id}/collaborators/{username}"], - createCard: ["POST /projects/columns/{column_id}/cards"], - createColumn: ["POST /projects/{project_id}/columns"], - createForAuthenticatedUser: ["POST /user/projects"], - createForOrg: ["POST /orgs/{org}/projects"], - createForRepo: ["POST /repos/{owner}/{repo}/projects"], - delete: ["DELETE /projects/{project_id}"], - deleteCard: ["DELETE /projects/columns/cards/{card_id}"], - deleteColumn: ["DELETE /projects/columns/{column_id}"], - get: ["GET /projects/{project_id}"], - getCard: ["GET /projects/columns/cards/{card_id}"], - getColumn: ["GET /projects/columns/{column_id}"], - getPermissionForUser: ["GET /projects/{project_id}/collaborators/{username}/permission"], - listCards: ["GET /projects/columns/{column_id}/cards"], - listCollaborators: ["GET /projects/{project_id}/collaborators"], - listColumns: ["GET /projects/{project_id}/columns"], - listForOrg: ["GET /orgs/{org}/projects"], - listForRepo: ["GET /repos/{owner}/{repo}/projects"], - listForUser: ["GET /users/{username}/projects"], - moveCard: ["POST /projects/columns/cards/{card_id}/moves"], - moveColumn: ["POST /projects/columns/{column_id}/moves"], - removeCollaborator: ["DELETE /projects/{project_id}/collaborators/{username}"], - update: ["PATCH /projects/{project_id}"], - updateCard: ["PATCH /projects/columns/cards/{card_id}"], - updateColumn: ["PATCH /projects/columns/{column_id}"] - }, - pulls: { - checkIfMerged: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/merge"], - create: ["POST /repos/{owner}/{repo}/pulls"], - createReplyForReviewComment: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies"], - createReview: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews"], - createReviewComment: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/comments"], - deletePendingReview: ["DELETE /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}"], - deleteReviewComment: ["DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}"], - dismissReview: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/dismissals"], - get: ["GET /repos/{owner}/{repo}/pulls/{pull_number}"], - getReview: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}"], - getReviewComment: ["GET /repos/{owner}/{repo}/pulls/comments/{comment_id}"], - list: ["GET /repos/{owner}/{repo}/pulls"], - listCommentsForReview: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments"], - listCommits: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/commits"], - listFiles: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/files"], - listRequestedReviewers: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers"], - listReviewComments: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/comments"], - listReviewCommentsForRepo: ["GET /repos/{owner}/{repo}/pulls/comments"], - listReviews: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews"], - merge: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/merge"], - removeRequestedReviewers: ["DELETE /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers"], - requestReviewers: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers"], - submitReview: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/events"], - update: ["PATCH /repos/{owner}/{repo}/pulls/{pull_number}"], - updateBranch: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/update-branch"], - updateReview: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}"], - updateReviewComment: ["PATCH /repos/{owner}/{repo}/pulls/comments/{comment_id}"] - }, - rateLimit: { - get: ["GET /rate_limit"] - }, - reactions: { - createForCommitComment: ["POST /repos/{owner}/{repo}/comments/{comment_id}/reactions"], - createForIssue: ["POST /repos/{owner}/{repo}/issues/{issue_number}/reactions"], - createForIssueComment: ["POST /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions"], - createForPullRequestReviewComment: ["POST /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions"], - createForRelease: ["POST /repos/{owner}/{repo}/releases/{release_id}/reactions"], - createForTeamDiscussionCommentInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions"], - createForTeamDiscussionInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions"], - deleteForCommitComment: ["DELETE /repos/{owner}/{repo}/comments/{comment_id}/reactions/{reaction_id}"], - deleteForIssue: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/reactions/{reaction_id}"], - deleteForIssueComment: ["DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions/{reaction_id}"], - deleteForPullRequestComment: ["DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions/{reaction_id}"], - deleteForTeamDiscussion: ["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions/{reaction_id}"], - deleteForTeamDiscussionComment: ["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions/{reaction_id}"], - listForCommitComment: ["GET /repos/{owner}/{repo}/comments/{comment_id}/reactions"], - listForIssue: ["GET /repos/{owner}/{repo}/issues/{issue_number}/reactions"], - listForIssueComment: ["GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions"], - listForPullRequestReviewComment: ["GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions"], - listForTeamDiscussionCommentInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions"], - listForTeamDiscussionInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions"] - }, - repos: { - acceptInvitation: ["PATCH /user/repository_invitations/{invitation_id}", {}, { - renamed: ["repos", "acceptInvitationForAuthenticatedUser"] - }], - acceptInvitationForAuthenticatedUser: ["PATCH /user/repository_invitations/{invitation_id}"], - addAppAccessRestrictions: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", {}, { - mapToData: "apps" - }], - addCollaborator: ["PUT /repos/{owner}/{repo}/collaborators/{username}"], - addStatusCheckContexts: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", {}, { - mapToData: "contexts" - }], - addTeamAccessRestrictions: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", {}, { - mapToData: "teams" - }], - addUserAccessRestrictions: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", {}, { - mapToData: "users" - }], - checkCollaborator: ["GET /repos/{owner}/{repo}/collaborators/{username}"], - checkVulnerabilityAlerts: ["GET /repos/{owner}/{repo}/vulnerability-alerts"], - compareCommits: ["GET /repos/{owner}/{repo}/compare/{base}...{head}"], - compareCommitsWithBasehead: ["GET /repos/{owner}/{repo}/compare/{basehead}"], - createAutolink: ["POST /repos/{owner}/{repo}/autolinks"], - createCommitComment: ["POST /repos/{owner}/{repo}/commits/{commit_sha}/comments"], - createCommitSignatureProtection: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures"], - createCommitStatus: ["POST /repos/{owner}/{repo}/statuses/{sha}"], - createDeployKey: ["POST /repos/{owner}/{repo}/keys"], - createDeployment: ["POST /repos/{owner}/{repo}/deployments"], - createDeploymentStatus: ["POST /repos/{owner}/{repo}/deployments/{deployment_id}/statuses"], - createDispatchEvent: ["POST /repos/{owner}/{repo}/dispatches"], - createForAuthenticatedUser: ["POST /user/repos"], - createFork: ["POST /repos/{owner}/{repo}/forks"], - createInOrg: ["POST /orgs/{org}/repos"], - createOrUpdateEnvironment: ["PUT /repos/{owner}/{repo}/environments/{environment_name}"], - createOrUpdateFileContents: ["PUT /repos/{owner}/{repo}/contents/{path}"], - createPagesSite: ["POST /repos/{owner}/{repo}/pages"], - createRelease: ["POST /repos/{owner}/{repo}/releases"], - createUsingTemplate: ["POST /repos/{template_owner}/{template_repo}/generate"], - createWebhook: ["POST /repos/{owner}/{repo}/hooks"], - declineInvitation: ["DELETE /user/repository_invitations/{invitation_id}", {}, { - renamed: ["repos", "declineInvitationForAuthenticatedUser"] - }], - declineInvitationForAuthenticatedUser: ["DELETE /user/repository_invitations/{invitation_id}"], - delete: ["DELETE /repos/{owner}/{repo}"], - deleteAccessRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions"], - deleteAdminBranchProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins"], - deleteAnEnvironment: ["DELETE /repos/{owner}/{repo}/environments/{environment_name}"], - deleteAutolink: ["DELETE /repos/{owner}/{repo}/autolinks/{autolink_id}"], - deleteBranchProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection"], - deleteCommitComment: ["DELETE /repos/{owner}/{repo}/comments/{comment_id}"], - deleteCommitSignatureProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures"], - deleteDeployKey: ["DELETE /repos/{owner}/{repo}/keys/{key_id}"], - deleteDeployment: ["DELETE /repos/{owner}/{repo}/deployments/{deployment_id}"], - deleteFile: ["DELETE /repos/{owner}/{repo}/contents/{path}"], - deleteInvitation: ["DELETE /repos/{owner}/{repo}/invitations/{invitation_id}"], - deletePagesSite: ["DELETE /repos/{owner}/{repo}/pages"], - deletePullRequestReviewProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews"], - deleteRelease: ["DELETE /repos/{owner}/{repo}/releases/{release_id}"], - deleteReleaseAsset: ["DELETE /repos/{owner}/{repo}/releases/assets/{asset_id}"], - deleteWebhook: ["DELETE /repos/{owner}/{repo}/hooks/{hook_id}"], - disableAutomatedSecurityFixes: ["DELETE /repos/{owner}/{repo}/automated-security-fixes"], - disableLfsForRepo: ["DELETE /repos/{owner}/{repo}/lfs"], - disableVulnerabilityAlerts: ["DELETE /repos/{owner}/{repo}/vulnerability-alerts"], - downloadArchive: ["GET /repos/{owner}/{repo}/zipball/{ref}", {}, { - renamed: ["repos", "downloadZipballArchive"] - }], - downloadTarballArchive: ["GET /repos/{owner}/{repo}/tarball/{ref}"], - downloadZipballArchive: ["GET /repos/{owner}/{repo}/zipball/{ref}"], - enableAutomatedSecurityFixes: ["PUT /repos/{owner}/{repo}/automated-security-fixes"], - enableLfsForRepo: ["PUT /repos/{owner}/{repo}/lfs"], - enableVulnerabilityAlerts: ["PUT /repos/{owner}/{repo}/vulnerability-alerts"], - generateReleaseNotes: ["POST /repos/{owner}/{repo}/releases/generate-notes"], - get: ["GET /repos/{owner}/{repo}"], - getAccessRestrictions: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions"], - getAdminBranchProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins"], - getAllEnvironments: ["GET /repos/{owner}/{repo}/environments"], - getAllStatusCheckContexts: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts"], - getAllTopics: ["GET /repos/{owner}/{repo}/topics", { - mediaType: { - previews: ["mercy"] + + }); + this.headers = options.headers || {}; // redact request credentials without mutating original request options + + const requestCopy = Object.assign({}, options.request); + + if (options.request.headers.authorization) { + requestCopy.headers = Object.assign({}, options.request.headers, { + authorization: options.request.headers.authorization.replace(/ .*$/, " [REDACTED]") + }); + } + + requestCopy.url = requestCopy.url // client_id & client_secret can be passed as URL query parameters to increase rate limit + // see https://developer.github.com/v3/#increasing-the-unauthenticated-rate-limit-for-oauth-applications + .replace(/\bclient_secret=\w+/g, "client_secret=[REDACTED]") // OAuth tokens can be passed as URL query parameters, although it is not recommended + // see https://developer.github.com/v3/#oauth2-token-sent-in-a-header + .replace(/\baccess_token=\w+/g, "access_token=[REDACTED]"); + this.request = requestCopy; + } + +} + +exports.RequestError = RequestError; +//# sourceMappingURL=index.js.map + + +/***/ }), + +/***/ 36234: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } + +var endpoint = __nccwpck_require__(59440); +var universalUserAgent = __nccwpck_require__(45030); +var isPlainObject = __nccwpck_require__(63287); +var nodeFetch = _interopDefault(__nccwpck_require__(81768)); +var requestError = __nccwpck_require__(10537); + +const VERSION = "5.4.12"; + +function getBufferResponse(response) { + return response.arrayBuffer(); +} + +function fetchWrapper(requestOptions) { + if (isPlainObject.isPlainObject(requestOptions.body) || Array.isArray(requestOptions.body)) { + requestOptions.body = JSON.stringify(requestOptions.body); + } + + let headers = {}; + let status; + let url; + const fetch = requestOptions.request && requestOptions.request.fetch || nodeFetch; + return fetch(requestOptions.url, Object.assign({ + method: requestOptions.method, + body: requestOptions.body, + headers: requestOptions.headers, + redirect: requestOptions.redirect + }, requestOptions.request)).then(response => { + url = response.url; + status = response.status; + + for (const keyAndValue of response.headers) { + headers[keyAndValue[0]] = keyAndValue[1]; + } + + if (status === 204 || status === 205) { + return; + } // GitHub API returns 200 for HEAD requests + + + if (requestOptions.method === "HEAD") { + if (status < 400) { + return; } - }], - getAppsWithAccessToProtectedBranch: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps"], - getAutolink: ["GET /repos/{owner}/{repo}/autolinks/{autolink_id}"], - getBranch: ["GET /repos/{owner}/{repo}/branches/{branch}"], - getBranchProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection"], - getClones: ["GET /repos/{owner}/{repo}/traffic/clones"], - getCodeFrequencyStats: ["GET /repos/{owner}/{repo}/stats/code_frequency"], - getCollaboratorPermissionLevel: ["GET /repos/{owner}/{repo}/collaborators/{username}/permission"], - getCombinedStatusForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/status"], - getCommit: ["GET /repos/{owner}/{repo}/commits/{ref}"], - getCommitActivityStats: ["GET /repos/{owner}/{repo}/stats/commit_activity"], - getCommitComment: ["GET /repos/{owner}/{repo}/comments/{comment_id}"], - getCommitSignatureProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures"], - getCommunityProfileMetrics: ["GET /repos/{owner}/{repo}/community/profile"], - getContent: ["GET /repos/{owner}/{repo}/contents/{path}"], - getContributorsStats: ["GET /repos/{owner}/{repo}/stats/contributors"], - getDeployKey: ["GET /repos/{owner}/{repo}/keys/{key_id}"], - getDeployment: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}"], - getDeploymentStatus: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses/{status_id}"], - getEnvironment: ["GET /repos/{owner}/{repo}/environments/{environment_name}"], - getLatestPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/latest"], - getLatestRelease: ["GET /repos/{owner}/{repo}/releases/latest"], - getPages: ["GET /repos/{owner}/{repo}/pages"], - getPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/{build_id}"], - getPagesHealthCheck: ["GET /repos/{owner}/{repo}/pages/health"], - getParticipationStats: ["GET /repos/{owner}/{repo}/stats/participation"], - getPullRequestReviewProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews"], - getPunchCardStats: ["GET /repos/{owner}/{repo}/stats/punch_card"], - getReadme: ["GET /repos/{owner}/{repo}/readme"], - getReadmeInDirectory: ["GET /repos/{owner}/{repo}/readme/{dir}"], - getRelease: ["GET /repos/{owner}/{repo}/releases/{release_id}"], - getReleaseAsset: ["GET /repos/{owner}/{repo}/releases/assets/{asset_id}"], - getReleaseByTag: ["GET /repos/{owner}/{repo}/releases/tags/{tag}"], - getStatusChecksProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks"], - getTeamsWithAccessToProtectedBranch: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams"], - getTopPaths: ["GET /repos/{owner}/{repo}/traffic/popular/paths"], - getTopReferrers: ["GET /repos/{owner}/{repo}/traffic/popular/referrers"], - getUsersWithAccessToProtectedBranch: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users"], - getViews: ["GET /repos/{owner}/{repo}/traffic/views"], - getWebhook: ["GET /repos/{owner}/{repo}/hooks/{hook_id}"], - getWebhookConfigForRepo: ["GET /repos/{owner}/{repo}/hooks/{hook_id}/config"], - getWebhookDelivery: ["GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}"], - listAutolinks: ["GET /repos/{owner}/{repo}/autolinks"], - listBranches: ["GET /repos/{owner}/{repo}/branches"], - listBranchesForHeadCommit: ["GET /repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head"], - listCollaborators: ["GET /repos/{owner}/{repo}/collaborators"], - listCommentsForCommit: ["GET /repos/{owner}/{repo}/commits/{commit_sha}/comments"], - listCommitCommentsForRepo: ["GET /repos/{owner}/{repo}/comments"], - listCommitStatusesForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/statuses"], - listCommits: ["GET /repos/{owner}/{repo}/commits"], - listContributors: ["GET /repos/{owner}/{repo}/contributors"], - listDeployKeys: ["GET /repos/{owner}/{repo}/keys"], - listDeploymentStatuses: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses"], - listDeployments: ["GET /repos/{owner}/{repo}/deployments"], - listForAuthenticatedUser: ["GET /user/repos"], - listForOrg: ["GET /orgs/{org}/repos"], - listForUser: ["GET /users/{username}/repos"], - listForks: ["GET /repos/{owner}/{repo}/forks"], - listInvitations: ["GET /repos/{owner}/{repo}/invitations"], - listInvitationsForAuthenticatedUser: ["GET /user/repository_invitations"], - listLanguages: ["GET /repos/{owner}/{repo}/languages"], - listPagesBuilds: ["GET /repos/{owner}/{repo}/pages/builds"], - listPublic: ["GET /repositories"], - listPullRequestsAssociatedWithCommit: ["GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls"], - listReleaseAssets: ["GET /repos/{owner}/{repo}/releases/{release_id}/assets"], - listReleases: ["GET /repos/{owner}/{repo}/releases"], - listTags: ["GET /repos/{owner}/{repo}/tags"], - listTeams: ["GET /repos/{owner}/{repo}/teams"], - listWebhookDeliveries: ["GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries"], - listWebhooks: ["GET /repos/{owner}/{repo}/hooks"], - merge: ["POST /repos/{owner}/{repo}/merges"], - mergeUpstream: ["POST /repos/{owner}/{repo}/merge-upstream"], - pingWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/pings"], - redeliverWebhookDelivery: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}/attempts"], - removeAppAccessRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", {}, { - mapToData: "apps" - }], - removeCollaborator: ["DELETE /repos/{owner}/{repo}/collaborators/{username}"], - removeStatusCheckContexts: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", {}, { - mapToData: "contexts" - }], - removeStatusCheckProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks"], - removeTeamAccessRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", {}, { - mapToData: "teams" - }], - removeUserAccessRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", {}, { - mapToData: "users" - }], - renameBranch: ["POST /repos/{owner}/{repo}/branches/{branch}/rename"], - replaceAllTopics: ["PUT /repos/{owner}/{repo}/topics", { - mediaType: { - previews: ["mercy"] + + throw new requestError.RequestError(response.statusText, status, { + headers, + request: requestOptions + }); + } + + if (status === 304) { + throw new requestError.RequestError("Not modified", status, { + headers, + request: requestOptions + }); + } + + if (status >= 400) { + return response.text().then(message => { + const error = new requestError.RequestError(message, status, { + headers, + request: requestOptions + }); + + try { + let responseBody = JSON.parse(error.message); + Object.assign(error, responseBody); + let errors = responseBody.errors; // Assumption `errors` would always be in Array format + + error.message = error.message + ": " + errors.map(JSON.stringify).join(", "); + } catch (e) {// ignore, see octokit/rest.js#684 + } + + throw error; + }); + } + + const contentType = response.headers.get("content-type"); + + if (/application\/json/.test(contentType)) { + return response.json(); + } + + if (!contentType || /^text\/|charset=utf-8$/.test(contentType)) { + return response.text(); + } + + return getBufferResponse(response); + }).then(data => { + return { + status, + url, + headers, + data + }; + }).catch(error => { + if (error instanceof requestError.RequestError) { + throw error; + } + + throw new requestError.RequestError(error.message, 500, { + headers, + request: requestOptions + }); + }); +} + +function withDefaults(oldEndpoint, newDefaults) { + const endpoint = oldEndpoint.defaults(newDefaults); + + const newApi = function (route, parameters) { + const endpointOptions = endpoint.merge(route, parameters); + + if (!endpointOptions.request || !endpointOptions.request.hook) { + return fetchWrapper(endpoint.parse(endpointOptions)); + } + + const request = (route, parameters) => { + return fetchWrapper(endpoint.parse(endpoint.merge(route, parameters))); + }; + + Object.assign(request, { + endpoint, + defaults: withDefaults.bind(null, endpoint) + }); + return endpointOptions.request.hook(request, endpointOptions); + }; + + return Object.assign(newApi, { + endpoint, + defaults: withDefaults.bind(null, endpoint) + }); +} + +const request = withDefaults(endpoint.endpoint, { + headers: { + "user-agent": `octokit-request.js/${VERSION} ${universalUserAgent.getUserAgent()}` + } +}); + +exports.request = request; +//# sourceMappingURL=index.js.map + + +/***/ }), + +/***/ 81768: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } + +var Stream = _interopDefault(__nccwpck_require__(12781)); +var http = _interopDefault(__nccwpck_require__(13685)); +var Url = _interopDefault(__nccwpck_require__(57310)); +var https = _interopDefault(__nccwpck_require__(95687)); +var zlib = _interopDefault(__nccwpck_require__(59796)); + +// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js + +// fix for "Readable" isn't a named export issue +const Readable = Stream.Readable; + +const BUFFER = Symbol('buffer'); +const TYPE = Symbol('type'); + +class Blob { + constructor() { + this[TYPE] = ''; + + const blobParts = arguments[0]; + const options = arguments[1]; + + const buffers = []; + let size = 0; + + if (blobParts) { + const a = blobParts; + const length = Number(a.length); + for (let i = 0; i < length; i++) { + const element = a[i]; + let buffer; + if (element instanceof Buffer) { + buffer = element; + } else if (ArrayBuffer.isView(element)) { + buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength); + } else if (element instanceof ArrayBuffer) { + buffer = Buffer.from(element); + } else if (element instanceof Blob) { + buffer = element[BUFFER]; + } else { + buffer = Buffer.from(typeof element === 'string' ? element : String(element)); + } + size += buffer.length; + buffers.push(buffer); + } + } + + this[BUFFER] = Buffer.concat(buffers); + + let type = options && options.type !== undefined && String(options.type).toLowerCase(); + if (type && !/[^\u0020-\u007E]/.test(type)) { + this[TYPE] = type; + } + } + get size() { + return this[BUFFER].length; + } + get type() { + return this[TYPE]; + } + text() { + return Promise.resolve(this[BUFFER].toString()); + } + arrayBuffer() { + const buf = this[BUFFER]; + const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + return Promise.resolve(ab); + } + stream() { + const readable = new Readable(); + readable._read = function () {}; + readable.push(this[BUFFER]); + readable.push(null); + return readable; + } + toString() { + return '[object Blob]'; + } + slice() { + const size = this.size; + + const start = arguments[0]; + const end = arguments[1]; + let relativeStart, relativeEnd; + if (start === undefined) { + relativeStart = 0; + } else if (start < 0) { + relativeStart = Math.max(size + start, 0); + } else { + relativeStart = Math.min(start, size); + } + if (end === undefined) { + relativeEnd = size; + } else if (end < 0) { + relativeEnd = Math.max(size + end, 0); + } else { + relativeEnd = Math.min(end, size); + } + const span = Math.max(relativeEnd - relativeStart, 0); + + const buffer = this[BUFFER]; + const slicedBuffer = buffer.slice(relativeStart, relativeStart + span); + const blob = new Blob([], { type: arguments[2] }); + blob[BUFFER] = slicedBuffer; + return blob; + } +} + +Object.defineProperties(Blob.prototype, { + size: { enumerable: true }, + type: { enumerable: true }, + slice: { enumerable: true } +}); + +Object.defineProperty(Blob.prototype, Symbol.toStringTag, { + value: 'Blob', + writable: false, + enumerable: false, + configurable: true +}); + +/** + * fetch-error.js + * + * FetchError interface for operational errors + */ + +/** + * Create FetchError instance + * + * @param String message Error message for human + * @param String type Error type for machine + * @param String systemError For Node.js system error + * @return FetchError + */ +function FetchError(message, type, systemError) { + Error.call(this, message); + + this.message = message; + this.type = type; + + // when err.type is `system`, err.code contains system error code + if (systemError) { + this.code = this.errno = systemError.code; + } + + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} + +FetchError.prototype = Object.create(Error.prototype); +FetchError.prototype.constructor = FetchError; +FetchError.prototype.name = 'FetchError'; + +let convert; +try { + convert = (__nccwpck_require__(22877).convert); +} catch (e) {} + +const INTERNALS = Symbol('Body internals'); + +// fix an issue where "PassThrough" isn't a named export for node <10 +const PassThrough = Stream.PassThrough; + +/** + * Body mixin + * + * Ref: https://fetch.spec.whatwg.org/#body + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +function Body(body) { + var _this = this; + + var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, + _ref$size = _ref.size; + + let size = _ref$size === undefined ? 0 : _ref$size; + var _ref$timeout = _ref.timeout; + let timeout = _ref$timeout === undefined ? 0 : _ref$timeout; + + if (body == null) { + // body is undefined or null + body = null; + } else if (isURLSearchParams(body)) { + // body is a URLSearchParams + body = Buffer.from(body.toString()); + } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') { + // body is ArrayBuffer + body = Buffer.from(body); + } else if (ArrayBuffer.isView(body)) { + // body is ArrayBufferView + body = Buffer.from(body.buffer, body.byteOffset, body.byteLength); + } else if (body instanceof Stream) ; else { + // none of the above + // coerce to string then buffer + body = Buffer.from(String(body)); + } + this[INTERNALS] = { + body, + disturbed: false, + error: null + }; + this.size = size; + this.timeout = timeout; + + if (body instanceof Stream) { + body.on('error', function (err) { + const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err); + _this[INTERNALS].error = error; + }); + } +} + +Body.prototype = { + get body() { + return this[INTERNALS].body; + }, + + get bodyUsed() { + return this[INTERNALS].disturbed; + }, + + /** + * Decode response as ArrayBuffer + * + * @return Promise + */ + arrayBuffer() { + return consumeBody.call(this).then(function (buf) { + return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + }); + }, + + /** + * Return raw response as Blob + * + * @return Promise + */ + blob() { + let ct = this.headers && this.headers.get('content-type') || ''; + return consumeBody.call(this).then(function (buf) { + return Object.assign( + // Prevent copying + new Blob([], { + type: ct.toLowerCase() + }), { + [BUFFER]: buf + }); + }); + }, + + /** + * Decode response as json + * + * @return Promise + */ + json() { + var _this2 = this; + + return consumeBody.call(this).then(function (buffer) { + try { + return JSON.parse(buffer.toString()); + } catch (err) { + return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json')); + } + }); + }, + + /** + * Decode response as text + * + * @return Promise + */ + text() { + return consumeBody.call(this).then(function (buffer) { + return buffer.toString(); + }); + }, + + /** + * Decode response as buffer (non-spec api) + * + * @return Promise + */ + buffer() { + return consumeBody.call(this); + }, + + /** + * Decode response as text, while automatically detecting the encoding and + * trying to decode to UTF-8 (non-spec api) + * + * @return Promise + */ + textConverted() { + var _this3 = this; + + return consumeBody.call(this).then(function (buffer) { + return convertBody(buffer, _this3.headers); + }); + } +}; + +// In browsers, all properties are enumerable. +Object.defineProperties(Body.prototype, { + body: { enumerable: true }, + bodyUsed: { enumerable: true }, + arrayBuffer: { enumerable: true }, + blob: { enumerable: true }, + json: { enumerable: true }, + text: { enumerable: true } +}); + +Body.mixIn = function (proto) { + for (const name of Object.getOwnPropertyNames(Body.prototype)) { + // istanbul ignore else: future proof + if (!(name in proto)) { + const desc = Object.getOwnPropertyDescriptor(Body.prototype, name); + Object.defineProperty(proto, name, desc); + } + } +}; + +/** + * Consume and convert an entire Body to a Buffer. + * + * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body + * + * @return Promise + */ +function consumeBody() { + var _this4 = this; + + if (this[INTERNALS].disturbed) { + return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`)); + } + + this[INTERNALS].disturbed = true; + + if (this[INTERNALS].error) { + return Body.Promise.reject(this[INTERNALS].error); + } + + let body = this.body; + + // body is null + if (body === null) { + return Body.Promise.resolve(Buffer.alloc(0)); + } + + // body is blob + if (isBlob(body)) { + body = body.stream(); + } + + // body is buffer + if (Buffer.isBuffer(body)) { + return Body.Promise.resolve(body); + } + + // istanbul ignore if: should never happen + if (!(body instanceof Stream)) { + return Body.Promise.resolve(Buffer.alloc(0)); + } + + // body is stream + // get ready to actually consume the body + let accum = []; + let accumBytes = 0; + let abort = false; + + return new Body.Promise(function (resolve, reject) { + let resTimeout; + + // allow timeout on slow response body + if (_this4.timeout) { + resTimeout = setTimeout(function () { + abort = true; + reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout')); + }, _this4.timeout); + } + + // handle stream errors + body.on('error', function (err) { + if (err.name === 'AbortError') { + // if the request was aborted, reject with this Error + abort = true; + reject(err); + } else { + // other errors, such as incorrect content-encoding + reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + + body.on('data', function (chunk) { + if (abort || chunk === null) { + return; + } + + if (_this4.size && accumBytes + chunk.length > _this4.size) { + abort = true; + reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size')); + return; + } + + accumBytes += chunk.length; + accum.push(chunk); + }); + + body.on('end', function () { + if (abort) { + return; + } + + clearTimeout(resTimeout); + + try { + resolve(Buffer.concat(accum, accumBytes)); + } catch (err) { + // handle streams that have accumulated too much data (issue #414) + reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + }); +} + +/** + * Detect buffer encoding and convert to target encoding + * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding + * + * @param Buffer buffer Incoming buffer + * @param String encoding Target encoding + * @return String + */ +function convertBody(buffer, headers) { + if (typeof convert !== 'function') { + throw new Error('The package `encoding` must be installed to use the textConverted() function'); + } + + const ct = headers.get('content-type'); + let charset = 'utf-8'; + let res, str; + + // header + if (ct) { + res = /charset=([^;]*)/i.exec(ct); + } + + // no charset in content type, peek at response body for at most 1024 bytes + str = buffer.slice(0, 1024).toString(); + + // html5 + if (!res && str) { + res = / 0 && arguments[0] !== undefined ? arguments[0] : undefined; + + this[MAP] = Object.create(null); + + if (init instanceof Headers) { + const rawHeaders = init.raw(); + const headerNames = Object.keys(rawHeaders); + + for (const headerName of headerNames) { + for (const value of rawHeaders[headerName]) { + this.append(headerName, value); + } + } + + return; + } + + // We don't worry about converting prop to ByteString here as append() + // will handle it. + if (init == null) ; else if (typeof init === 'object') { + const method = init[Symbol.iterator]; + if (method != null) { + if (typeof method !== 'function') { + throw new TypeError('Header pairs must be iterable'); + } + + // sequence> + // Note: per spec we have to first exhaust the lists then process them + const pairs = []; + for (const pair of init) { + if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') { + throw new TypeError('Each header pair must be iterable'); + } + pairs.push(Array.from(pair)); + } + + for (const pair of pairs) { + if (pair.length !== 2) { + throw new TypeError('Each header pair must be a name/value tuple'); + } + this.append(pair[0], pair[1]); + } + } else { + // record + for (const key of Object.keys(init)) { + const value = init[key]; + this.append(key, value); + } + } + } else { + throw new TypeError('Provided initializer must be an object'); + } + } + + /** + * Return combined header value given name + * + * @param String name Header name + * @return Mixed + */ + get(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key === undefined) { + return null; + } + + return this[MAP][key].join(', '); + } + + /** + * Iterate over all headers + * + * @param Function callback Executed for each item with parameters (value, name, thisArg) + * @param Boolean thisArg `this` context for callback function + * @return Void + */ + forEach(callback) { + let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; + + let pairs = getHeaders(this); + let i = 0; + while (i < pairs.length) { + var _pairs$i = pairs[i]; + const name = _pairs$i[0], + value = _pairs$i[1]; + + callback.call(thisArg, value, name, this); + pairs = getHeaders(this); + i++; + } + } + + /** + * Overwrite header values given name + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + set(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + this[MAP][key !== undefined ? key : name] = [value]; + } + + /** + * Append a value onto existing header + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + append(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + if (key !== undefined) { + this[MAP][key].push(value); + } else { + this[MAP][name] = [value]; + } + } + + /** + * Check for header name existence + * + * @param String name Header name + * @return Boolean + */ + has(name) { + name = `${name}`; + validateName(name); + return find(this[MAP], name) !== undefined; + } + + /** + * Delete all header values given name + * + * @param String name Header name + * @return Void + */ + delete(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key !== undefined) { + delete this[MAP][key]; + } + } + + /** + * Return raw headers (non-spec api) + * + * @return Object + */ + raw() { + return this[MAP]; + } + + /** + * Get an iterator on keys. + * + * @return Iterator + */ + keys() { + return createHeadersIterator(this, 'key'); + } + + /** + * Get an iterator on values. + * + * @return Iterator + */ + values() { + return createHeadersIterator(this, 'value'); + } + + /** + * Get an iterator on entries. + * + * This is the default iterator of the Headers object. + * + * @return Iterator + */ + [Symbol.iterator]() { + return createHeadersIterator(this, 'key+value'); + } +} +Headers.prototype.entries = Headers.prototype[Symbol.iterator]; + +Object.defineProperty(Headers.prototype, Symbol.toStringTag, { + value: 'Headers', + writable: false, + enumerable: false, + configurable: true +}); + +Object.defineProperties(Headers.prototype, { + get: { enumerable: true }, + forEach: { enumerable: true }, + set: { enumerable: true }, + append: { enumerable: true }, + has: { enumerable: true }, + delete: { enumerable: true }, + keys: { enumerable: true }, + values: { enumerable: true }, + entries: { enumerable: true } +}); + +function getHeaders(headers) { + let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value'; + + const keys = Object.keys(headers[MAP]).sort(); + return keys.map(kind === 'key' ? function (k) { + return k.toLowerCase(); + } : kind === 'value' ? function (k) { + return headers[MAP][k].join(', '); + } : function (k) { + return [k.toLowerCase(), headers[MAP][k].join(', ')]; + }); +} + +const INTERNAL = Symbol('internal'); + +function createHeadersIterator(target, kind) { + const iterator = Object.create(HeadersIteratorPrototype); + iterator[INTERNAL] = { + target, + kind, + index: 0 + }; + return iterator; +} + +const HeadersIteratorPrototype = Object.setPrototypeOf({ + next() { + // istanbul ignore if + if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) { + throw new TypeError('Value of `this` is not a HeadersIterator'); + } + + var _INTERNAL = this[INTERNAL]; + const target = _INTERNAL.target, + kind = _INTERNAL.kind, + index = _INTERNAL.index; + + const values = getHeaders(target, kind); + const len = values.length; + if (index >= len) { + return { + value: undefined, + done: true + }; + } + + this[INTERNAL].index = index + 1; + + return { + value: values[index], + done: false + }; + } +}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))); + +Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, { + value: 'HeadersIterator', + writable: false, + enumerable: false, + configurable: true +}); + +/** + * Export the Headers object in a form that Node.js can consume. + * + * @param Headers headers + * @return Object + */ +function exportNodeCompatibleHeaders(headers) { + const obj = Object.assign({ __proto__: null }, headers[MAP]); + + // http.request() only supports string as Host header. This hack makes + // specifying custom Host header possible. + const hostHeaderKey = find(headers[MAP], 'Host'); + if (hostHeaderKey !== undefined) { + obj[hostHeaderKey] = obj[hostHeaderKey][0]; + } + + return obj; +} + +/** + * Create a Headers object from an object of headers, ignoring those that do + * not conform to HTTP grammar productions. + * + * @param Object obj Object of headers + * @return Headers + */ +function createHeadersLenient(obj) { + const headers = new Headers(); + for (const name of Object.keys(obj)) { + if (invalidTokenRegex.test(name)) { + continue; + } + if (Array.isArray(obj[name])) { + for (const val of obj[name]) { + if (invalidHeaderCharRegex.test(val)) { + continue; + } + if (headers[MAP][name] === undefined) { + headers[MAP][name] = [val]; + } else { + headers[MAP][name].push(val); + } + } + } else if (!invalidHeaderCharRegex.test(obj[name])) { + headers[MAP][name] = [obj[name]]; + } + } + return headers; +} + +const INTERNALS$1 = Symbol('Response internals'); + +// fix an issue where "STATUS_CODES" aren't a named export for node <10 +const STATUS_CODES = http.STATUS_CODES; + +/** + * Response class + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +class Response { + constructor() { + let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + Body.call(this, body, opts); + + const status = opts.status || 200; + const headers = new Headers(opts.headers); + + if (body != null && !headers.has('Content-Type')) { + const contentType = extractContentType(body); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + this[INTERNALS$1] = { + url: opts.url, + status, + statusText: opts.statusText || STATUS_CODES[status], + headers, + counter: opts.counter + }; + } + + get url() { + return this[INTERNALS$1].url || ''; + } + + get status() { + return this[INTERNALS$1].status; + } + + /** + * Convenience property representing if the request ended normally + */ + get ok() { + return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300; + } + + get redirected() { + return this[INTERNALS$1].counter > 0; + } + + get statusText() { + return this[INTERNALS$1].statusText; + } + + get headers() { + return this[INTERNALS$1].headers; + } + + /** + * Clone this response + * + * @return Response + */ + clone() { + return new Response(clone(this), { + url: this.url, + status: this.status, + statusText: this.statusText, + headers: this.headers, + ok: this.ok, + redirected: this.redirected + }); + } +} + +Body.mixIn(Response.prototype); + +Object.defineProperties(Response.prototype, { + url: { enumerable: true }, + status: { enumerable: true }, + ok: { enumerable: true }, + redirected: { enumerable: true }, + statusText: { enumerable: true }, + headers: { enumerable: true }, + clone: { enumerable: true } +}); + +Object.defineProperty(Response.prototype, Symbol.toStringTag, { + value: 'Response', + writable: false, + enumerable: false, + configurable: true +}); + +const INTERNALS$2 = Symbol('Request internals'); + +// fix an issue where "format", "parse" aren't a named export for node <10 +const parse_url = Url.parse; +const format_url = Url.format; + +const streamDestructionSupported = 'destroy' in Stream.Readable.prototype; + +/** + * Check if a value is an instance of Request. + * + * @param Mixed input + * @return Boolean + */ +function isRequest(input) { + return typeof input === 'object' && typeof input[INTERNALS$2] === 'object'; +} + +function isAbortSignal(signal) { + const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal); + return !!(proto && proto.constructor.name === 'AbortSignal'); +} + +/** + * Request class + * + * @param Mixed input Url or Request instance + * @param Object init Custom options + * @return Void + */ +class Request { + constructor(input) { + let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + let parsedURL; + + // normalize input + if (!isRequest(input)) { + if (input && input.href) { + // in order to support Node.js' Url objects; though WHATWG's URL objects + // will fall into this branch also (since their `toString()` will return + // `href` property anyway) + parsedURL = parse_url(input.href); + } else { + // coerce input to a string before attempting to parse + parsedURL = parse_url(`${input}`); + } + input = {}; + } else { + parsedURL = parse_url(input.url); + } + + let method = init.method || input.method || 'GET'; + method = method.toUpperCase(); + + if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) { + throw new TypeError('Request with GET/HEAD method cannot have body'); + } + + let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null; + + Body.call(this, inputBody, { + timeout: init.timeout || input.timeout || 0, + size: init.size || input.size || 0 + }); + + const headers = new Headers(init.headers || input.headers || {}); + + if (inputBody != null && !headers.has('Content-Type')) { + const contentType = extractContentType(inputBody); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + let signal = isRequest(input) ? input.signal : null; + if ('signal' in init) signal = init.signal; + + if (signal != null && !isAbortSignal(signal)) { + throw new TypeError('Expected signal to be an instanceof AbortSignal'); + } + + this[INTERNALS$2] = { + method, + redirect: init.redirect || input.redirect || 'follow', + headers, + parsedURL, + signal + }; + + // node-fetch-only options + this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20; + this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true; + this.counter = init.counter || input.counter || 0; + this.agent = init.agent || input.agent; + } + + get method() { + return this[INTERNALS$2].method; + } + + get url() { + return format_url(this[INTERNALS$2].parsedURL); + } + + get headers() { + return this[INTERNALS$2].headers; + } + + get redirect() { + return this[INTERNALS$2].redirect; + } + + get signal() { + return this[INTERNALS$2].signal; + } + + /** + * Clone this request + * + * @return Request + */ + clone() { + return new Request(this); + } +} + +Body.mixIn(Request.prototype); + +Object.defineProperty(Request.prototype, Symbol.toStringTag, { + value: 'Request', + writable: false, + enumerable: false, + configurable: true +}); + +Object.defineProperties(Request.prototype, { + method: { enumerable: true }, + url: { enumerable: true }, + headers: { enumerable: true }, + redirect: { enumerable: true }, + clone: { enumerable: true }, + signal: { enumerable: true } +}); + +/** + * Convert a Request to Node.js http request options. + * + * @param Request A Request instance + * @return Object The options object to be passed to http.request + */ +function getNodeRequestOptions(request) { + const parsedURL = request[INTERNALS$2].parsedURL; + const headers = new Headers(request[INTERNALS$2].headers); + + // fetch step 1.3 + if (!headers.has('Accept')) { + headers.set('Accept', '*/*'); + } + + // Basic fetch + if (!parsedURL.protocol || !parsedURL.hostname) { + throw new TypeError('Only absolute URLs are supported'); + } + + if (!/^https?:$/.test(parsedURL.protocol)) { + throw new TypeError('Only HTTP(S) protocols are supported'); + } + + if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) { + throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8'); + } + + // HTTP-network-or-cache fetch steps 2.4-2.7 + let contentLengthValue = null; + if (request.body == null && /^(POST|PUT)$/i.test(request.method)) { + contentLengthValue = '0'; + } + if (request.body != null) { + const totalBytes = getTotalBytes(request); + if (typeof totalBytes === 'number') { + contentLengthValue = String(totalBytes); + } + } + if (contentLengthValue) { + headers.set('Content-Length', contentLengthValue); + } + + // HTTP-network-or-cache fetch step 2.11 + if (!headers.has('User-Agent')) { + headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)'); + } + + // HTTP-network-or-cache fetch step 2.15 + if (request.compress && !headers.has('Accept-Encoding')) { + headers.set('Accept-Encoding', 'gzip,deflate'); + } + + let agent = request.agent; + if (typeof agent === 'function') { + agent = agent(parsedURL); + } + + if (!headers.has('Connection') && !agent) { + headers.set('Connection', 'close'); + } + + // HTTP-network fetch step 4.2 + // chunked encoding is handled by Node.js + + return Object.assign({}, parsedURL, { + method: request.method, + headers: exportNodeCompatibleHeaders(headers), + agent + }); +} + +/** + * abort-error.js + * + * AbortError interface for cancelled requests + */ + +/** + * Create AbortError instance + * + * @param String message Error message for human + * @return AbortError + */ +function AbortError(message) { + Error.call(this, message); + + this.type = 'aborted'; + this.message = message; + + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} + +AbortError.prototype = Object.create(Error.prototype); +AbortError.prototype.constructor = AbortError; +AbortError.prototype.name = 'AbortError'; + +// fix an issue where "PassThrough", "resolve" aren't a named export for node <10 +const PassThrough$1 = Stream.PassThrough; +const resolve_url = Url.resolve; + +/** + * Fetch function + * + * @param Mixed url Absolute url or Request instance + * @param Object opts Fetch options + * @return Promise + */ +function fetch(url, opts) { + + // allow custom promise + if (!fetch.Promise) { + throw new Error('native promise missing, set fetch.Promise to your favorite alternative'); + } + + Body.Promise = fetch.Promise; + + // wrap http.request into fetch + return new fetch.Promise(function (resolve, reject) { + // build request object + const request = new Request(url, opts); + const options = getNodeRequestOptions(request); + + const send = (options.protocol === 'https:' ? https : http).request; + const signal = request.signal; + + let response = null; + + const abort = function abort() { + let error = new AbortError('The user aborted a request.'); + reject(error); + if (request.body && request.body instanceof Stream.Readable) { + request.body.destroy(error); + } + if (!response || !response.body) return; + response.body.emit('error', error); + }; + + if (signal && signal.aborted) { + abort(); + return; + } + + const abortAndFinalize = function abortAndFinalize() { + abort(); + finalize(); + }; + + // send request + const req = send(options); + let reqTimeout; + + if (signal) { + signal.addEventListener('abort', abortAndFinalize); + } + + function finalize() { + req.abort(); + if (signal) signal.removeEventListener('abort', abortAndFinalize); + clearTimeout(reqTimeout); + } + + if (request.timeout) { + req.once('socket', function (socket) { + reqTimeout = setTimeout(function () { + reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout')); + finalize(); + }, request.timeout); + }); + } + + req.on('error', function (err) { + reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err)); + finalize(); + }); + + req.on('response', function (res) { + clearTimeout(reqTimeout); + + const headers = createHeadersLenient(res.headers); + + // HTTP fetch step 5 + if (fetch.isRedirect(res.statusCode)) { + // HTTP fetch step 5.2 + const location = headers.get('Location'); + + // HTTP fetch step 5.3 + const locationURL = location === null ? null : resolve_url(request.url, location); + + // HTTP fetch step 5.5 + switch (request.redirect) { + case 'error': + reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect')); + finalize(); + return; + case 'manual': + // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL. + if (locationURL !== null) { + // handle corrupted header + try { + headers.set('Location', locationURL); + } catch (err) { + // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request + reject(err); + } + } + break; + case 'follow': + // HTTP-redirect fetch step 2 + if (locationURL === null) { + break; + } + + // HTTP-redirect fetch step 5 + if (request.counter >= request.follow) { + reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 6 (counter increment) + // Create a new Request object. + const requestOpts = { + headers: new Headers(request.headers), + follow: request.follow, + counter: request.counter + 1, + agent: request.agent, + compress: request.compress, + method: request.method, + body: request.body, + signal: request.signal, + timeout: request.timeout, + size: request.size + }; + + // HTTP-redirect fetch step 9 + if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) { + reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 11 + if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') { + requestOpts.method = 'GET'; + requestOpts.body = undefined; + requestOpts.headers.delete('content-length'); + } + + // HTTP-redirect fetch step 15 + resolve(fetch(new Request(locationURL, requestOpts))); + finalize(); + return; + } + } + + // prepare response + res.once('end', function () { + if (signal) signal.removeEventListener('abort', abortAndFinalize); + }); + let body = res.pipe(new PassThrough$1()); + + const response_options = { + url: request.url, + status: res.statusCode, + statusText: res.statusMessage, + headers: headers, + size: request.size, + timeout: request.timeout, + counter: request.counter + }; + + // HTTP-network fetch step 12.1.1.3 + const codings = headers.get('Content-Encoding'); + + // HTTP-network fetch step 12.1.1.4: handle content codings + + // in following scenarios we ignore compression support + // 1. compression support is disabled + // 2. HEAD request + // 3. no Content-Encoding header + // 4. no content response (204) + // 5. content not modified response (304) + if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) { + response = new Response(body, response_options); + resolve(response); + return; + } + + // For Node v6+ + // Be less strict when decoding compressed responses, since sometimes + // servers send slightly invalid responses that are still accepted + // by common browsers. + // Always using Z_SYNC_FLUSH is what cURL does. + const zlibOptions = { + flush: zlib.Z_SYNC_FLUSH, + finishFlush: zlib.Z_SYNC_FLUSH + }; + + // for gzip + if (codings == 'gzip' || codings == 'x-gzip') { + body = body.pipe(zlib.createGunzip(zlibOptions)); + response = new Response(body, response_options); + resolve(response); + return; + } + + // for deflate + if (codings == 'deflate' || codings == 'x-deflate') { + // handle the infamous raw deflate response from old servers + // a hack for old IIS and Apache servers + const raw = res.pipe(new PassThrough$1()); + raw.once('data', function (chunk) { + // see http://stackoverflow.com/questions/37519828 + if ((chunk[0] & 0x0F) === 0x08) { + body = body.pipe(zlib.createInflate()); + } else { + body = body.pipe(zlib.createInflateRaw()); + } + response = new Response(body, response_options); + resolve(response); + }); + return; + } + + // for br + if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') { + body = body.pipe(zlib.createBrotliDecompress()); + response = new Response(body, response_options); + resolve(response); + return; + } + + // otherwise, use response as-is + response = new Response(body, response_options); + resolve(response); + }); + + writeToStream(req, request); + }); +} +/** + * Redirect code matching + * + * @param Number code Status code + * @return Boolean + */ +fetch.isRedirect = function (code) { + return code === 301 || code === 302 || code === 303 || code === 307 || code === 308; +}; + +// expose Promise +fetch.Promise = global.Promise; + +module.exports = exports = fetch; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports["default"] = exports; +exports.Headers = Headers; +exports.Request = Request; +exports.Response = Response; +exports.FetchError = FetchError; + + +/***/ }), + +/***/ 49768: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +var crypto = __nccwpck_require__(6113); +var buffer = __nccwpck_require__(14300); + +const VERSION = "2.0.0"; + +var Algorithm; + +(function (Algorithm) { + Algorithm["SHA1"] = "sha1"; + Algorithm["SHA256"] = "sha256"; +})(Algorithm || (Algorithm = {})); + +async function sign(options, payload) { + const { + secret, + algorithm + } = typeof options === "object" ? { + secret: options.secret, + algorithm: options.algorithm || Algorithm.SHA256 + } : { + secret: options, + algorithm: Algorithm.SHA256 + }; + + if (!secret || !payload) { + throw new TypeError("[@octokit/webhooks-methods] secret & payload required for sign()"); + } + + if (!Object.values(Algorithm).includes(algorithm)) { + throw new TypeError(`[@octokit/webhooks] Algorithm ${algorithm} is not supported. Must be 'sha1' or 'sha256'`); + } + + return `${algorithm}=${crypto.createHmac(algorithm, secret).update(payload).digest("hex")}`; +} +sign.VERSION = VERSION; + +const getAlgorithm = signature => { + return signature.startsWith("sha256=") ? "sha256" : "sha1"; +}; + +async function verify(secret, eventPayload, signature) { + if (!secret || !eventPayload || !signature) { + throw new TypeError("[@octokit/webhooks-methods] secret, eventPayload & signature required"); + } + + const signatureBuffer = buffer.Buffer.from(signature); + const algorithm = getAlgorithm(signature); + const verificationBuffer = buffer.Buffer.from(await sign({ + secret, + algorithm + }, eventPayload)); + + if (signatureBuffer.length !== verificationBuffer.length) { + return false; + } // constant time comparison to prevent timing attachs + // https://stackoverflow.com/a/31096242/206879 + // https://en.wikipedia.org/wiki/Timing_attack + + + return crypto.timingSafeEqual(signatureBuffer, verificationBuffer); +} +verify.VERSION = VERSION; + +exports.sign = sign; +exports.verify = verify; +//# sourceMappingURL=index.js.map + + +/***/ }), + +/***/ 18513: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } + +var AggregateError = _interopDefault(__nccwpck_require__(61231)); +var webhooksMethods = __nccwpck_require__(49768); + +function ownKeys(object, enumerableOnly) { + var keys = Object.keys(object); + + if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(object); + + if (enumerableOnly) { + symbols = symbols.filter(function (sym) { + return Object.getOwnPropertyDescriptor(object, sym).enumerable; + }); + } + + keys.push.apply(keys, symbols); + } + + return keys; +} + +function _objectSpread2(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i] != null ? arguments[i] : {}; + + if (i % 2) { + ownKeys(Object(source), true).forEach(function (key) { + _defineProperty(target, key, source[key]); + }); + } else if (Object.getOwnPropertyDescriptors) { + Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); + } else { + ownKeys(Object(source)).forEach(function (key) { + Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); + }); + } + } + + return target; +} + +function _defineProperty(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + + return obj; +} + +const createLogger = logger => _objectSpread2({ + debug: () => {}, + info: () => {}, + warn: console.warn.bind(console), + error: console.error.bind(console) +}, logger); + +// THIS FILE IS GENERATED - DO NOT EDIT DIRECTLY +// make edits in scripts/generate-types.ts +const emitterEventNames = ["branch_protection_rule", "branch_protection_rule.created", "branch_protection_rule.deleted", "branch_protection_rule.edited", "check_run", "check_run.completed", "check_run.created", "check_run.requested_action", "check_run.rerequested", "check_suite", "check_suite.completed", "check_suite.requested", "check_suite.rerequested", "code_scanning_alert", "code_scanning_alert.appeared_in_branch", "code_scanning_alert.closed_by_user", "code_scanning_alert.created", "code_scanning_alert.fixed", "code_scanning_alert.reopened", "code_scanning_alert.reopened_by_user", "commit_comment", "commit_comment.created", "create", "delete", "deploy_key", "deploy_key.created", "deploy_key.deleted", "deployment", "deployment.created", "deployment_status", "deployment_status.created", "discussion", "discussion.answered", "discussion.category_changed", "discussion.created", "discussion.deleted", "discussion.edited", "discussion.labeled", "discussion.locked", "discussion.pinned", "discussion.transferred", "discussion.unanswered", "discussion.unlabeled", "discussion.unlocked", "discussion.unpinned", "discussion_comment", "discussion_comment.created", "discussion_comment.deleted", "discussion_comment.edited", "fork", "github_app_authorization", "github_app_authorization.revoked", "gollum", "installation", "installation.created", "installation.deleted", "installation.new_permissions_accepted", "installation.suspend", "installation.unsuspend", "installation_repositories", "installation_repositories.added", "installation_repositories.removed", "issue_comment", "issue_comment.created", "issue_comment.deleted", "issue_comment.edited", "issues", "issues.assigned", "issues.closed", "issues.deleted", "issues.demilestoned", "issues.edited", "issues.labeled", "issues.locked", "issues.milestoned", "issues.opened", "issues.pinned", "issues.reopened", "issues.transferred", "issues.unassigned", "issues.unlabeled", "issues.unlocked", "issues.unpinned", "label", "label.created", "label.deleted", "label.edited", "marketplace_purchase", "marketplace_purchase.cancelled", "marketplace_purchase.changed", "marketplace_purchase.pending_change", "marketplace_purchase.pending_change_cancelled", "marketplace_purchase.purchased", "member", "member.added", "member.edited", "member.removed", "membership", "membership.added", "membership.removed", "meta", "meta.deleted", "milestone", "milestone.closed", "milestone.created", "milestone.deleted", "milestone.edited", "milestone.opened", "org_block", "org_block.blocked", "org_block.unblocked", "organization", "organization.deleted", "organization.member_added", "organization.member_invited", "organization.member_removed", "organization.renamed", "package", "package.published", "package.updated", "page_build", "ping", "project", "project.closed", "project.created", "project.deleted", "project.edited", "project.reopened", "project_card", "project_card.converted", "project_card.created", "project_card.deleted", "project_card.edited", "project_card.moved", "project_column", "project_column.created", "project_column.deleted", "project_column.edited", "project_column.moved", "public", "pull_request", "pull_request.assigned", "pull_request.auto_merge_disabled", "pull_request.auto_merge_enabled", "pull_request.closed", "pull_request.converted_to_draft", "pull_request.edited", "pull_request.labeled", "pull_request.locked", "pull_request.opened", "pull_request.ready_for_review", "pull_request.reopened", "pull_request.review_request_removed", "pull_request.review_requested", "pull_request.synchronize", "pull_request.unassigned", "pull_request.unlabeled", "pull_request.unlocked", "pull_request_review", "pull_request_review.dismissed", "pull_request_review.edited", "pull_request_review.submitted", "pull_request_review_comment", "pull_request_review_comment.created", "pull_request_review_comment.deleted", "pull_request_review_comment.edited", "pull_request_review_thread", "pull_request_review_thread.resolved", "pull_request_review_thread.unresolved", "push", "release", "release.created", "release.deleted", "release.edited", "release.prereleased", "release.published", "release.released", "release.unpublished", "repository", "repository.archived", "repository.created", "repository.deleted", "repository.edited", "repository.privatized", "repository.publicized", "repository.renamed", "repository.transferred", "repository.unarchived", "repository_dispatch", "repository_import", "repository_vulnerability_alert", "repository_vulnerability_alert.create", "repository_vulnerability_alert.dismiss", "repository_vulnerability_alert.resolve", "secret_scanning_alert", "secret_scanning_alert.created", "secret_scanning_alert.reopened", "secret_scanning_alert.resolved", "security_advisory", "security_advisory.performed", "security_advisory.published", "security_advisory.updated", "security_advisory.withdrawn", "sponsorship", "sponsorship.cancelled", "sponsorship.created", "sponsorship.edited", "sponsorship.pending_cancellation", "sponsorship.pending_tier_change", "sponsorship.tier_changed", "star", "star.created", "star.deleted", "status", "team", "team.added_to_repository", "team.created", "team.deleted", "team.edited", "team.removed_from_repository", "team_add", "watch", "watch.started", "workflow_dispatch", "workflow_job", "workflow_job.completed", "workflow_job.in_progress", "workflow_job.queued", "workflow_job.started", "workflow_run", "workflow_run.completed", "workflow_run.requested"]; + +function handleEventHandlers(state, webhookName, handler) { + if (!state.hooks[webhookName]) { + state.hooks[webhookName] = []; + } + + state.hooks[webhookName].push(handler); +} + +function receiverOn(state, webhookNameOrNames, handler) { + if (Array.isArray(webhookNameOrNames)) { + webhookNameOrNames.forEach(webhookName => receiverOn(state, webhookName, handler)); + return; + } + + if (["*", "error"].includes(webhookNameOrNames)) { + const webhookName = webhookNameOrNames === "*" ? "any" : webhookNameOrNames; + const message = `Using the "${webhookNameOrNames}" event with the regular Webhooks.on() function is not supported. Please use the Webhooks.on${webhookName.charAt(0).toUpperCase() + webhookName.slice(1)}() method instead`; + throw new Error(message); + } + + if (!emitterEventNames.includes(webhookNameOrNames)) { + state.log.warn(`"${webhookNameOrNames}" is not a known webhook name (https://developer.github.com/v3/activity/events/types/)`); + } + + handleEventHandlers(state, webhookNameOrNames, handler); +} +function receiverOnAny(state, handler) { + handleEventHandlers(state, "*", handler); +} +function receiverOnError(state, handler) { + handleEventHandlers(state, "error", handler); +} + +// Errors thrown or rejected Promises in "error" event handlers are not handled +// as they are in the webhook event handlers. If errors occur, we log a +// "Fatal: Error occurred" message to stdout +function wrapErrorHandler(handler, error) { + let returnValue; + + try { + returnValue = handler(error); + } catch (error) { + console.log('FATAL: Error occurred in "error" event handler'); + console.log(error); + } + + if (returnValue && returnValue.catch) { + returnValue.catch(error => { + console.log('FATAL: Error occurred in "error" event handler'); + console.log(error); + }); + } +} + +// @ts-ignore to address #245 + +function getHooks(state, eventPayloadAction, eventName) { + const hooks = [state.hooks[eventName], state.hooks["*"]]; + + if (eventPayloadAction) { + hooks.unshift(state.hooks[`${eventName}.${eventPayloadAction}`]); + } + + return [].concat(...hooks.filter(Boolean)); +} // main handler function + + +function receiverHandle(state, event) { + const errorHandlers = state.hooks.error || []; + + if (event instanceof Error) { + const error = Object.assign(new AggregateError([event]), { + event, + errors: [event] + }); + errorHandlers.forEach(handler => wrapErrorHandler(handler, error)); + return Promise.reject(error); + } + + if (!event || !event.name) { + throw new AggregateError(["Event name not passed"]); + } + + if (!event.payload) { + throw new AggregateError(["Event payload not passed"]); + } // flatten arrays of event listeners and remove undefined values + + + const hooks = getHooks(state, "action" in event.payload ? event.payload.action : null, event.name); + + if (hooks.length === 0) { + return Promise.resolve(); + } + + const errors = []; + const promises = hooks.map(handler => { + let promise = Promise.resolve(event); + + if (state.transform) { + promise = promise.then(state.transform); + } + + return promise.then(event => { + return handler(event); + }).catch(error => errors.push(Object.assign(error, { + event + }))); + }); + return Promise.all(promises).then(() => { + if (errors.length === 0) { + return; + } + + const error = new AggregateError(errors); + Object.assign(error, { + event, + errors + }); + errorHandlers.forEach(handler => wrapErrorHandler(handler, error)); + throw error; + }); +} + +function removeListener(state, webhookNameOrNames, handler) { + if (Array.isArray(webhookNameOrNames)) { + webhookNameOrNames.forEach(webhookName => removeListener(state, webhookName, handler)); + return; + } + + if (!state.hooks[webhookNameOrNames]) { + return; + } // remove last hook that has been added, that way + // it behaves the same as removeListener + + + for (let i = state.hooks[webhookNameOrNames].length - 1; i >= 0; i--) { + if (state.hooks[webhookNameOrNames][i] === handler) { + state.hooks[webhookNameOrNames].splice(i, 1); + return; + } + } +} + +function createEventHandler(options) { + const state = { + hooks: {}, + log: createLogger(options && options.log) + }; + + if (options && options.transform) { + state.transform = options.transform; + } + + return { + on: receiverOn.bind(null, state), + onAny: receiverOnAny.bind(null, state), + onError: receiverOnError.bind(null, state), + removeListener: removeListener.bind(null, state), + receive: receiverHandle.bind(null, state) + }; +} + +/** + * GitHub sends its JSON with an indentation of 2 spaces and a line break at the end + */ +function toNormalizedJsonString(payload) { + const payloadString = JSON.stringify(payload); + return payloadString.replace(/[^\\]\\u[\da-f]{4}/g, s => { + return s.substr(0, 3) + s.substr(3).toUpperCase(); + }); +} + +async function sign(secret, payload) { + return webhooksMethods.sign(secret, typeof payload === "string" ? payload : toNormalizedJsonString(payload)); +} + +async function verify(secret, payload, signature) { + return webhooksMethods.verify(secret, typeof payload === "string" ? payload : toNormalizedJsonString(payload), signature); +} + +async function verifyAndReceive(state, event) { + // verify will validate that the secret is not undefined + const matchesSignature = await webhooksMethods.verify(state.secret, typeof event.payload === "object" ? toNormalizedJsonString(event.payload) : event.payload, event.signature); + + if (!matchesSignature) { + const error = new Error("[@octokit/webhooks] signature does not match event payload and secret"); + return state.eventHandler.receive(Object.assign(error, { + event, + status: 400 + })); + } + + return state.eventHandler.receive({ + id: event.id, + name: event.name, + payload: typeof event.payload === "string" ? JSON.parse(event.payload) : event.payload + }); +} + +const WEBHOOK_HEADERS = ["x-github-event", "x-hub-signature-256", "x-github-delivery"]; // https://docs.github.com/en/developers/webhooks-and-events/webhook-events-and-payloads#delivery-headers + +function getMissingHeaders(request) { + return WEBHOOK_HEADERS.filter(header => !(header in request.headers)); +} + +// @ts-ignore to address #245 +function getPayload(request) { + // If request.body already exists we can stop here + // See https://github.com/octokit/webhooks.js/pull/23 + if (request.body) return Promise.resolve(request.body); + return new Promise((resolve, reject) => { + let data = ""; + request.setEncoding("utf8"); // istanbul ignore next + + request.on("error", error => reject(new AggregateError([error]))); + request.on("data", chunk => data += chunk); + request.on("end", () => { + try { + resolve(JSON.parse(data)); + } catch (error) { + error.message = "Invalid JSON"; + error.status = 400; + reject(new AggregateError([error])); } - }], - requestPagesBuild: ["POST /repos/{owner}/{repo}/pages/builds"], - setAdminBranchProtection: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins"], - setAppAccessRestrictions: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", {}, { - mapToData: "apps" - }], - setStatusCheckContexts: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", {}, { - mapToData: "contexts" - }], - setTeamAccessRestrictions: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", {}, { - mapToData: "teams" - }], - setUserAccessRestrictions: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", {}, { - mapToData: "users" - }], - testPushWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/tests"], - transfer: ["POST /repos/{owner}/{repo}/transfer"], - update: ["PATCH /repos/{owner}/{repo}"], - updateBranchProtection: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection"], - updateCommitComment: ["PATCH /repos/{owner}/{repo}/comments/{comment_id}"], - updateInformationAboutPagesSite: ["PUT /repos/{owner}/{repo}/pages"], - updateInvitation: ["PATCH /repos/{owner}/{repo}/invitations/{invitation_id}"], - updatePullRequestReviewProtection: ["PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews"], - updateRelease: ["PATCH /repos/{owner}/{repo}/releases/{release_id}"], - updateReleaseAsset: ["PATCH /repos/{owner}/{repo}/releases/assets/{asset_id}"], - updateStatusCheckPotection: ["PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks", {}, { - renamed: ["repos", "updateStatusCheckProtection"] - }], - updateStatusCheckProtection: ["PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks"], - updateWebhook: ["PATCH /repos/{owner}/{repo}/hooks/{hook_id}"], - updateWebhookConfigForRepo: ["PATCH /repos/{owner}/{repo}/hooks/{hook_id}/config"], - uploadReleaseAsset: ["POST /repos/{owner}/{repo}/releases/{release_id}/assets{?name,label}", { - baseUrl: "https://uploads.github.com" - }] - }, - search: { - code: ["GET /search/code"], - commits: ["GET /search/commits"], - issuesAndPullRequests: ["GET /search/issues"], - labels: ["GET /search/labels"], - repos: ["GET /search/repositories"], - topics: ["GET /search/topics", { - mediaType: { - previews: ["mercy"] + }); + }); +} + +async function middleware(webhooks, options, request, response, next) { + let pathname; + + try { + pathname = new URL(request.url, "http://localhost").pathname; + } catch (error) { + response.writeHead(422, { + "content-type": "application/json" + }); + response.end(JSON.stringify({ + error: `Request URL could not be parsed: ${request.url}` + })); + return; + } + + const isUnknownRoute = request.method !== "POST" || pathname !== options.path; + const isExpressMiddleware = typeof next === "function"; + + if (isUnknownRoute) { + if (isExpressMiddleware) { + return next(); + } else { + return options.onUnhandledRequest(request, response); + } + } + + const missingHeaders = getMissingHeaders(request).join(", "); + + if (missingHeaders) { + response.writeHead(400, { + "content-type": "application/json" + }); + response.end(JSON.stringify({ + error: `Required headers missing: ${missingHeaders}` + })); + return; + } + + const eventName = request.headers["x-github-event"]; + const signatureSHA256 = request.headers["x-hub-signature-256"]; + const id = request.headers["x-github-delivery"]; + options.log.debug(`${eventName} event received (id: ${id})`); // GitHub will abort the request if it does not receive a response within 10s + // See https://github.com/octokit/webhooks.js/issues/185 + + let didTimeout = false; + const timeout = setTimeout(() => { + didTimeout = true; + response.statusCode = 202; + response.end("still processing\n"); + }, 9000).unref(); + + try { + const payload = await getPayload(request); + await webhooks.verifyAndReceive({ + id: id, + name: eventName, + payload: payload, + signature: signatureSHA256 + }); + clearTimeout(timeout); + if (didTimeout) return; + response.end("ok\n"); + } catch (error) { + clearTimeout(timeout); + if (didTimeout) return; + const statusCode = Array.from(error)[0].status; + response.statusCode = typeof statusCode !== "undefined" ? statusCode : 500; + response.end(String(error)); + } +} + +function onUnhandledRequestDefault(request, response) { + response.writeHead(404, { + "content-type": "application/json" + }); + response.end(JSON.stringify({ + error: `Unknown route: ${request.method} ${request.url}` + })); +} + +function createNodeMiddleware(webhooks, { + path = "/api/github/webhooks", + onUnhandledRequest = onUnhandledRequestDefault, + log = createLogger() +} = {}) { + return middleware.bind(null, webhooks, { + path, + onUnhandledRequest, + log + }); +} + +class Webhooks { + constructor(options) { + if (!options || !options.secret) { + throw new Error("[@octokit/webhooks] options.secret required"); + } + + const state = { + eventHandler: createEventHandler(options), + secret: options.secret, + hooks: {}, + log: createLogger(options.log) + }; + this.sign = sign.bind(null, options.secret); + this.verify = verify.bind(null, options.secret); + this.on = state.eventHandler.on; + this.onAny = state.eventHandler.onAny; + this.onError = state.eventHandler.onError; + this.removeListener = state.eventHandler.removeListener; + this.receive = state.eventHandler.receive; + this.verifyAndReceive = verifyAndReceive.bind(null, state); + } + +} + +exports.Webhooks = Webhooks; +exports.createEventHandler = createEventHandler; +exports.createNodeMiddleware = createNodeMiddleware; +exports.emitterEventNames = emitterEventNames; +//# sourceMappingURL=index.js.map + + +/***/ }), + +/***/ 93159: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +const ProbotExports = __nccwpck_require__(93181); +const pino = __nccwpck_require__(79608); + +const { transport } = __nccwpck_require__(96645); + +module.exports = { ...ProbotExports, run }; + +async function run(app) { + const log = pino({}, transport); + + const githubToken = + process.env.GITHUB_TOKEN || + process.env.INPUT_GITHUB_TOKEN || + process.env.INPUT_TOKEN; + + if (!githubToken) { + log.error( + "[probot/adapter-github-actions] a token must be passed as `env.GITHUB_TOKEN` or `with.GITHUB_TOKEN` or `with.token`, see https://github.com/probot/adapter-github-actions#usage" + ); + return; + } + + const envVariablesMissing = [ + "GITHUB_RUN_ID", + "GITHUB_EVENT_NAME", + "GITHUB_EVENT_PATH", + ].filter((name) => !process.env[name]); + + if (envVariablesMissing.length) { + log.error( + `[probot/adapter-github-actions] GitHub Action default environment variables missing: ${envVariablesMissing.join( + ", " + )}. See https://docs.github.com/en/free-pro-team@latest/actions/reference/environment-variables#default-environment-variables` + ); + return; + } + + const probot = ProbotExports.createProbot({ + overrides: { + githubToken, + log, + }, + }); + + await probot.load(app); + + return probot + .receive({ + id: process.env.GITHUB_RUN_ID, + name: process.env.GITHUB_EVENT_NAME, + payload: require(process.env.GITHUB_EVENT_PATH), + }) + .catch((error) => { + probot.log.error(error); + }); +} + + +/***/ }), + +/***/ 18915: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const os = __importStar(__nccwpck_require__(22037)); +const utils_1 = __nccwpck_require__(53322); +/** + * Commands + * + * Command Format: + * ::name key=value,key=value::message + * + * Examples: + * ::warning::This is the message + * ::set-env name=MY_VAR::some value + */ +function issueCommand(command, properties, message) { + const cmd = new Command(command, properties, message); + process.stdout.write(cmd.toString() + os.EOL); +} +exports.issueCommand = issueCommand; +function issue(name, message = '') { + issueCommand(name, {}, message); +} +exports.issue = issue; +const CMD_STRING = '::'; +class Command { + constructor(command, properties, message) { + if (!command) { + command = 'missing.command'; + } + this.command = command; + this.properties = properties; + this.message = message; + } + toString() { + let cmdStr = CMD_STRING + this.command; + if (this.properties && Object.keys(this.properties).length > 0) { + cmdStr += ' '; + let first = true; + for (const key in this.properties) { + if (this.properties.hasOwnProperty(key)) { + const val = this.properties[key]; + if (val) { + if (first) { + first = false; + } + else { + cmdStr += ','; + } + cmdStr += `${key}=${escapeProperty(val)}`; + } + } + } + } + cmdStr += `${CMD_STRING}${escapeData(this.message)}`; + return cmdStr; + } +} +function escapeData(s) { + return utils_1.toCommandValue(s) + .replace(/%/g, '%25') + .replace(/\r/g, '%0D') + .replace(/\n/g, '%0A'); +} +function escapeProperty(s) { + return utils_1.toCommandValue(s) + .replace(/%/g, '%25') + .replace(/\r/g, '%0D') + .replace(/\n/g, '%0A') + .replace(/:/g, '%3A') + .replace(/,/g, '%2C'); +} +//# sourceMappingURL=command.js.map + +/***/ }), + +/***/ 68648: +/***/ (function(__unused_webpack_module, 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()); + }); +}; +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const command_1 = __nccwpck_require__(18915); +const file_command_1 = __nccwpck_require__(20); +const utils_1 = __nccwpck_require__(53322); +const os = __importStar(__nccwpck_require__(22037)); +const path = __importStar(__nccwpck_require__(71017)); +/** + * The code to exit an action + */ +var ExitCode; +(function (ExitCode) { + /** + * A code indicating that the action was successful + */ + ExitCode[ExitCode["Success"] = 0] = "Success"; + /** + * A code indicating that the action was a failure + */ + ExitCode[ExitCode["Failure"] = 1] = "Failure"; +})(ExitCode = exports.ExitCode || (exports.ExitCode = {})); +//----------------------------------------------------------------------- +// Variables +//----------------------------------------------------------------------- +/** + * Sets env variable for this action and future actions in the job + * @param name the name of the variable to set + * @param val the value of the variable. Non-string values will be converted to a string via JSON.stringify + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function exportVariable(name, val) { + const convertedVal = utils_1.toCommandValue(val); + process.env[name] = convertedVal; + const filePath = process.env['GITHUB_ENV'] || ''; + if (filePath) { + const delimiter = '_GitHubActionsFileCommandDelimeter_'; + const commandValue = `${name}<<${delimiter}${os.EOL}${convertedVal}${os.EOL}${delimiter}`; + file_command_1.issueCommand('ENV', commandValue); + } + else { + command_1.issueCommand('set-env', { name }, convertedVal); + } +} +exports.exportVariable = exportVariable; +/** + * Registers a secret which will get masked from logs + * @param secret value of the secret + */ +function setSecret(secret) { + command_1.issueCommand('add-mask', {}, secret); +} +exports.setSecret = setSecret; +/** + * Prepends inputPath to the PATH (for this action and future actions) + * @param inputPath + */ +function addPath(inputPath) { + const filePath = process.env['GITHUB_PATH'] || ''; + if (filePath) { + file_command_1.issueCommand('PATH', inputPath); + } + else { + command_1.issueCommand('add-path', {}, inputPath); + } + process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`; +} +exports.addPath = addPath; +/** + * Gets the value of an input. The value is also trimmed. + * + * @param name name of the input to get + * @param options optional. See InputOptions. + * @returns string + */ +function getInput(name, options) { + const val = process.env[`INPUT_${name.replace(/ /g, '_').toUpperCase()}`] || ''; + if (options && options.required && !val) { + throw new Error(`Input required and not supplied: ${name}`); + } + return val.trim(); +} +exports.getInput = getInput; +/** + * Sets the value of an output. + * + * @param name name of the output to set + * @param value value to store. Non-string values will be converted to a string via JSON.stringify + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function setOutput(name, value) { + command_1.issueCommand('set-output', { name }, value); +} +exports.setOutput = setOutput; +/** + * Enables or disables the echoing of commands into stdout for the rest of the step. + * Echoing is disabled by default if ACTIONS_STEP_DEBUG is not set. + * + */ +function setCommandEcho(enabled) { + command_1.issue('echo', enabled ? 'on' : 'off'); +} +exports.setCommandEcho = setCommandEcho; +//----------------------------------------------------------------------- +// Results +//----------------------------------------------------------------------- +/** + * Sets the action status to failed. + * When the action exits it will be with an exit code of 1 + * @param message add error issue message + */ +function setFailed(message) { + process.exitCode = ExitCode.Failure; + error(message); +} +exports.setFailed = setFailed; +//----------------------------------------------------------------------- +// Logging Commands +//----------------------------------------------------------------------- +/** + * Gets whether Actions Step Debug is on or not + */ +function isDebug() { + return process.env['RUNNER_DEBUG'] === '1'; +} +exports.isDebug = isDebug; +/** + * Writes debug message to user log + * @param message debug message + */ +function debug(message) { + command_1.issueCommand('debug', {}, message); +} +exports.debug = debug; +/** + * Adds an error issue + * @param message error issue message. Errors will be converted to string via toString() + */ +function error(message) { + command_1.issue('error', message instanceof Error ? message.toString() : message); +} +exports.error = error; +/** + * Adds an warning issue + * @param message warning issue message. Errors will be converted to string via toString() + */ +function warning(message) { + command_1.issue('warning', message instanceof Error ? message.toString() : message); +} +exports.warning = warning; +/** + * Writes info to log with console.log. + * @param message info message + */ +function info(message) { + process.stdout.write(message + os.EOL); +} +exports.info = info; +/** + * Begin an output group. + * + * Output until the next `groupEnd` will be foldable in this group + * + * @param name The name of the output group + */ +function startGroup(name) { + command_1.issue('group', name); +} +exports.startGroup = startGroup; +/** + * End an output group. + */ +function endGroup() { + command_1.issue('endgroup'); +} +exports.endGroup = endGroup; +/** + * Wrap an asynchronous function call in a group. + * + * Returns the same type as the function itself. + * + * @param name The name of the group + * @param fn The function to wrap in the group + */ +function group(name, fn) { + return __awaiter(this, void 0, void 0, function* () { + startGroup(name); + let result; + try { + result = yield fn(); + } + finally { + endGroup(); + } + return result; + }); +} +exports.group = group; +//----------------------------------------------------------------------- +// Wrapper action state +//----------------------------------------------------------------------- +/** + * Saves state for current action, the state can only be retrieved by this action's post job execution. + * + * @param name name of the state to store + * @param value value to store. Non-string values will be converted to a string via JSON.stringify + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function saveState(name, value) { + command_1.issueCommand('save-state', { name }, value); +} +exports.saveState = saveState; +/** + * Gets the value of an state set by this action's main execution. + * + * @param name name of the state to get + * @returns string + */ +function getState(name) { + return process.env[`STATE_${name}`] || ''; +} +exports.getState = getState; +//# sourceMappingURL=core.js.map + +/***/ }), + +/***/ 20: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +// For internal use, subject to change. +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +// We use any as a valid input type +/* eslint-disable @typescript-eslint/no-explicit-any */ +const fs = __importStar(__nccwpck_require__(57147)); +const os = __importStar(__nccwpck_require__(22037)); +const utils_1 = __nccwpck_require__(53322); +function issueCommand(command, message) { + const filePath = process.env[`GITHUB_${command}`]; + if (!filePath) { + throw new Error(`Unable to find environment variable for file command ${command}`); + } + if (!fs.existsSync(filePath)) { + throw new Error(`Missing file at path: ${filePath}`); + } + fs.appendFileSync(filePath, `${utils_1.toCommandValue(message)}${os.EOL}`, { + encoding: 'utf8' + }); +} +exports.issueCommand = issueCommand; +//# sourceMappingURL=file-command.js.map + +/***/ }), + +/***/ 53322: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +// We use any as a valid input type +/* eslint-disable @typescript-eslint/no-explicit-any */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +/** + * Sanitizes an input into a string so it can be passed into issueCommand safely + * @param input input to sanitize into a string + */ +function toCommandValue(input) { + if (input === null || input === undefined) { + return ''; + } + else if (typeof input === 'string' || input instanceof String) { + return input; + } + return JSON.stringify(input); +} +exports.toCommandValue = toCommandValue; +//# sourceMappingURL=utils.js.map + +/***/ }), + +/***/ 3598: +/***/ (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.defaultApp = void 0; +const path_1 = __importDefault(__nccwpck_require__(71017)); +function defaultApp(app, { getRouter }) { + if (!getRouter) { + throw new Error("getRouter() is required for defaultApp"); + } + const router = getRouter(); + router.get("/probot", (req, res) => { + let pkg; + try { + pkg = require(path_1.default.join(process.cwd(), "package.json")); + } + catch (e) { + pkg = {}; + } + res.render("probot.hbs", pkg); + }); + router.get("/", (req, res, next) => res.redirect("/probot")); +} +exports.defaultApp = defaultApp; +//# sourceMappingURL=default.js.map + +/***/ }), + +/***/ 36769: +/***/ (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.setupAppFactory = void 0; +const body_parser_1 = __importDefault(__nccwpck_require__(97076)); +const child_process_1 = __nccwpck_require__(32081); +const update_dotenv_1 = __importDefault(__nccwpck_require__(51023)); +const manifest_creation_1 = __nccwpck_require__(18785); +const logging_middleware_1 = __nccwpck_require__(24631); +const is_production_1 = __nccwpck_require__(75381); +const setupAppFactory = (host, port) => async function setupApp(app, { getRouter }) { + const setup = new manifest_creation_1.ManifestCreation(); + // If not on Glitch or Production, create a smee URL + if (!is_production_1.isProduction() && + !(process.env.PROJECT_DOMAIN || + process.env.WEBHOOK_PROXY_URL || + process.env.NO_SMEE_SETUP === "true")) { + await setup.createWebhookChannel(); + } + if (!getRouter) { + throw new Error("getRouter is required to use the setup app"); + } + const route = getRouter(); + route.use(logging_middleware_1.getLoggingMiddleware(app.log)); + printWelcomeMessage(app, host, port); + route.get("/probot", async (req, res) => { + const baseUrl = getBaseUrl(req); + const pkg = setup.pkg; + const manifest = setup.getManifest(pkg, baseUrl); + const createAppUrl = setup.createAppUrl; + // Pass the manifest to be POST'd + res.render("setup.hbs", { pkg, createAppUrl, manifest }); + }); + route.get("/probot/setup", async (req, res) => { + const { code } = req.query; + const response = await setup.createAppFromCode(code); + // If using glitch, restart the app + if (process.env.PROJECT_DOMAIN) { + child_process_1.exec("refresh", (error) => { + if (error) { + app.log.error(error); + } + }); + } + else { + printRestartMessage(app); + } + res.redirect(`${response}/installations/new`); + }); + route.get("/probot/import", async (_req, res) => { + const { WEBHOOK_PROXY_URL, GHE_HOST } = process.env; + const GH_HOST = `https://${GHE_HOST !== null && GHE_HOST !== void 0 ? GHE_HOST : "github.com"}`; + res.render("import.hbs", { WEBHOOK_PROXY_URL, GH_HOST }); + }); + route.post("/probot/import", body_parser_1.default.json(), async (req, res) => { + const { appId, pem, webhook_secret } = req.body; + if (!appId || !pem || !webhook_secret) { + res.status(400).send("appId and/or pem and/or webhook_secret missing"); + return; + } + update_dotenv_1.default({ + APP_ID: appId, + PRIVATE_KEY: `"${pem}"`, + WEBHOOK_SECRET: webhook_secret, + }); + res.end(); + printRestartMessage(app); + }); + route.get("/probot/success", async (req, res) => { + res.render("success.hbs"); + }); + route.get("/", (req, res, next) => res.redirect("/probot")); +}; +exports.setupAppFactory = setupAppFactory; +function printWelcomeMessage(app, host, port) { + // use glitch env to get correct domain welcome message + // https://glitch.com/help/project/ + const domain = process.env.PROJECT_DOMAIN || + `http://${host !== null && host !== void 0 ? host : "localhost"}:${port || 3000}`; + [ + ``, + `Welcome to Probot!`, + `Probot is in setup mode, webhooks cannot be received and`, + `custom routes will not work until APP_ID and PRIVATE_KEY`, + `are configured in .env.`, + `Please follow the instructions at ${domain} to configure .env.`, + `Once you are done, restart the server.`, + ``, + ].forEach((line) => { + app.log.info(line); + }); +} +function printRestartMessage(app) { + app.log.info(""); + app.log.info("Probot has been set up, please restart the server!"); + app.log.info(""); +} +function getBaseUrl(req) { + const protocols = req.headers["x-forwarded-proto"] || req.protocol; + const protocol = typeof protocols === "string" ? protocols.split(",")[0] : protocols[0]; + const host = req.headers["x-forwarded-host"] || req.get("host"); + const baseUrl = `${protocol}://${host}`; + return baseUrl; +} +//# sourceMappingURL=setup.js.map + +/***/ }), + +/***/ 81084: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.auth = void 0; +const get_authenticated_octokit_1 = __nccwpck_require__(53535); +/** + * Authenticate and get a GitHub client that can be used to make API calls. + * + * You'll probably want to use `context.octokit` instead. + * + * **Note**: `app.auth` is asynchronous, so it needs to be prefixed with a + * [`await`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await) + * to wait for the magic to happen. + * + * ```js + * module.exports = (app) => { + * app.on('issues.opened', async context => { + * const octokit = await app.auth(); + * }); + * }; + * ``` + * + * @param id - ID of the installation, which can be extracted from + * `context.payload.installation.id`. If called without this parameter, the + * client wil authenticate [as the app](https://docs.github.com/en/developers/apps/authenticating-with-github-apps#authenticating-as-a-github-app) + * instead of as a specific installation, which means it can only be used for + * [app APIs](https://docs.github.com/apps/). + * + * @returns An authenticated GitHub API client + */ +async function auth(state, installationId, log) { + return get_authenticated_octokit_1.getAuthenticatedOctokit(Object.assign({}, state, log ? { log } : null), installationId); +} +exports.auth = auth; +//# sourceMappingURL=auth.js.map + +/***/ }), + +/***/ 57767: +/***/ (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.readCliOptions = void 0; +const commander_1 = __importDefault(__nccwpck_require__(61904)); +const get_private_key_1 = __nccwpck_require__(97743); +function readCliOptions(argv) { + commander_1.default + .usage("[options] ") + .option("-p, --port ", "Port to start the server on", String(process.env.PORT || 3000)) + .option("-H --host ", "Host to start the server on", process.env.HOST) + .option("-W, --webhook-proxy ", "URL of the webhook proxy service.`", process.env.WEBHOOK_PROXY_URL) + .option("-w, --webhook-path ", "URL path which receives webhooks. Ex: `/webhook`", process.env.WEBHOOK_PATH) + .option("-a, --app ", "ID of the GitHub App", process.env.APP_ID) + .option("-s, --secret ", "Webhook secret of the GitHub App", process.env.WEBHOOK_SECRET) + .option("-P, --private-key ", "Path to private key file (.pem) for the GitHub App", process.env.PRIVATE_KEY_PATH) + .option("-L, --log-level ", 'One of: "trace" | "debug" | "info" | "warn" | "error" | "fatal"', process.env.LOG_LEVEL || "info") + .option("--log-format ", 'One of: "pretty", "json"', process.env.LOG_FORMAT) + .option("--log-level-in-string", "Set to log levels (trace, debug, info, ...) as words instead of numbers (10, 20, 30, ...)", process.env.LOG_LEVEL_IN_STRING === "true") + .option("--sentry-dsn ", 'Set to your Sentry DSN, e.g. "https://1234abcd@sentry.io/12345"', process.env.SENTRY_DSN) + .option("--redis-url ", 'Set to a "redis://" url in order to enable cluster support for request throttling. Example: "redis://:secret@redis-123.redislabs.com:12345/0"', process.env.REDIS_URL) + .option("--base-url ", 'GitHub API base URL. If you use GitHub Enterprise Server, and your hostname is "https://github.acme-inc.com", then the root URL is "https://github.acme-inc.com/api/v3"', process.env.GHE_HOST + ? `${process.env.GHE_PROTOCOL || "https"}://${process.env.GHE_HOST}/api/v3` + : "https://api.github.com") + .parse(argv); + const { app: appId, privateKey: privateKeyPath, redisUrl, ...options } = commander_1.default; + return { + privateKey: get_private_key_1.getPrivateKey({ filepath: privateKeyPath }) || undefined, + appId, + redisConfig: redisUrl, + ...options, + }; +} +exports.readCliOptions = readCliOptions; +//# sourceMappingURL=read-cli-options.js.map + +/***/ }), + +/***/ 74420: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.readEnvOptions = void 0; +const get_private_key_1 = __nccwpck_require__(97743); +function readEnvOptions(env = process.env) { + const privateKey = get_private_key_1.getPrivateKey({ env }); + const logFormat = env.LOG_FORMAT || (env.NODE_ENV === "production" ? "json" : "pretty"); + return { + args: [], + privateKey: (privateKey && privateKey.toString()) || undefined, + appId: Number(env.APP_ID), + port: Number(env.PORT) || 3000, + host: env.HOST, + secret: env.WEBHOOK_SECRET, + webhookPath: env.WEBHOOK_PATH, + webhookProxy: env.WEBHOOK_PROXY_URL, + logLevel: env.LOG_LEVEL, + logFormat: logFormat, + logLevelInString: env.LOG_LEVEL_IN_STRING === "true", + logMessageKey: env.LOG_MESSAGE_KEY, + sentryDsn: env.SENTRY_DSN, + redisConfig: env.REDIS_URL, + baseUrl: env.GHE_HOST + ? `${env.GHE_PROTOCOL || "https"}://${env.GHE_HOST}/api/v3` + : "https://api.github.com", + }; +} +exports.readEnvOptions = readEnvOptions; +//# sourceMappingURL=read-env-options.js.map + +/***/ }), + +/***/ 45006: +/***/ (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.Context = void 0; +const path_1 = __importDefault(__nccwpck_require__(71017)); +const deepmerge_1 = __importDefault(__nccwpck_require__(56323)); +const alias_log_1 = __nccwpck_require__(19752); +/** + * The context of the event that was triggered, including the payload and + * helpers for extracting information can be passed to GitHub API calls. + * + * ```js + * module.exports = app => { + * app.on('push', context => { + * context.log.info('Code was pushed to the repo, what should we do with it?'); + * }); + * }; + * ``` + * + * @property {octokit} octokit - An Octokit instance + * @property {payload} payload - The webhook event payload + * @property {log} log - A pino instance + */ +class Context { + constructor(event, octokit, log) { + this.name = event.name; + this.id = event.id; + this.payload = event.payload; + this.octokit = octokit; + this.log = alias_log_1.aliasLog(log); + } + /** + * Return the `owner` and `repo` params for making API requests against a + * repository. + * + * ```js + * const params = context.repo({path: '.github/config.yml'}) + * // Returns: {owner: 'username', repo: 'reponame', path: '.github/config.yml'} + * ``` + * + * @param object - Params to be merged with the repo params. + * + */ + repo(object) { + // @ts-ignore `repository` is not always present in this.payload + const repo = this.payload.repository; + if (!repo) { + throw new Error("context.repo() is not supported for this webhook event."); + } + return Object.assign({ + owner: repo.owner.login, + repo: repo.name, + }, object); + } + /** + * Return the `owner`, `repo`, and `issue_number` params for making API requests + * against an issue. The object passed in will be merged with the repo params. + * + * + * ```js + * const params = context.issue({body: 'Hello World!'}) + * // Returns: {owner: 'username', repo: 'reponame', issue_number: 123, body: 'Hello World!'} + * ``` + * + * @param object - Params to be merged with the issue params. + */ + issue(object) { + return Object.assign({ + issue_number: + // @ts-ignore - this.payload may not have `issue` or `pull_request` keys + (this.payload.issue || this.payload.pull_request || this.payload) + .number, + }, this.repo(object)); + } + /** + * Return the `owner`, `repo`, and `pull_number` params for making API requests + * against a pull request. The object passed in will be merged with the repo params. + * + * + * ```js + * const params = context.pullRequest({body: 'Hello World!'}) + * // Returns: {owner: 'username', repo: 'reponame', pull_number: 123, body: 'Hello World!'} + * ``` + * + * @param object - Params to be merged with the pull request params. + */ + pullRequest(object) { + const payload = this.payload; + return Object.assign({ + // @ts-ignore - this.payload may not have `issue` or `pull_request` keys + pull_number: (payload.issue || payload.pull_request || payload).number, + }, this.repo(object)); + } + /** + * Returns a boolean if the actor on the event was a bot. + * @type {boolean} + */ + get isBot() { + // @ts-expect-error - `sender` key is currently not present in all events + // see https://github.com/octokit/webhooks/issues/510 + return this.payload.sender.type === "Bot"; + } + /** + * Reads the app configuration from the given YAML file in the `.github` + * directory of the repository. + * + * For example, given a file named `.github/config.yml`: + * + * ```yml + * close: true + * comment: Check the specs on the rotary girder. + * ``` + * + * Your app can read that file from the target repository: + * + * ```js + * // Load config from .github/config.yml in the repository + * const config = await context.config('config.yml') + * + * if (config.close) { + * context.octokit.issues.comment(context.issue({body: config.comment})) + * context.octokit.issues.edit(context.issue({state: 'closed'})) + * } + * ``` + * + * You can also use a `defaultConfig` object: + * + * ```js + * // Load config from .github/config.yml in the repository and combine with default config + * const config = await context.config('config.yml', {comment: 'Make sure to check all the specs.'}) + * + * if (config.close) { + * context.octokit.issues.comment(context.issue({body: config.comment})); + * context.octokit.issues.edit(context.issue({state: 'closed'})) + * } + * ``` + * + * Config files can also specify a base that they extend. `deepMergeOptions` can be used + * to configure how the target config, extended base, and default configs are merged. + * + * For security reasons, configuration is only loaded from the repository's default branch, + * changes made in pull requests from different branches or forks are ignored. + * + * If you need more lower-level control over reading and merging configuration files, + * you can `context.octokit.config.get(options)`, see https://github.com/probot/octokit-plugin-config. + * + * @param fileName - Name of the YAML file in the `.github` directory + * @param defaultConfig - An object of default config options + * @param deepMergeOptions - Controls merging configs (from the [deepmerge](https://github.com/TehShrike/deepmerge) module) + * @return Configuration object read from the file + */ + async config(fileName, defaultConfig, deepMergeOptions) { + const params = this.repo({ + path: path_1.default.posix.join(".github", fileName), + defaults(configs) { + const result = deepmerge_1.default.all([defaultConfig || {}, ...configs], deepMergeOptions); + return result; + }, + }); + // @ts-ignore + const { config, files } = await this.octokit.config.get(params); + // if no default config is set, and no config files are found, return null + if (!defaultConfig && !files.find((file) => file.config !== null)) { + return null; + } + return config; + } +} +exports.Context = Context; +//# sourceMappingURL=context.js.map + +/***/ }), + +/***/ 44488: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.createNodeMiddleware = void 0; +const webhooks_1 = __nccwpck_require__(18513); +function createNodeMiddleware(appFn, { probot, webhooksPath }) { + probot.load(appFn); + return webhooks_1.createNodeMiddleware(probot.webhooks, { + path: webhooksPath || "/", + }); +} +exports.createNodeMiddleware = createNodeMiddleware; +//# sourceMappingURL=create-node-middleware.js.map + +/***/ }), + +/***/ 52728: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.createProbot = void 0; +const get_private_key_1 = __nccwpck_require__(97743); +const get_log_1 = __nccwpck_require__(90751); +const probot_1 = __nccwpck_require__(22357); +const DEFAULTS = { + APP_ID: "", + WEBHOOK_SECRET: "", + GHE_HOST: "", + GHE_PROTOCOL: "", + LOG_FORMAT: "", + LOG_LEVEL: "warn", + LOG_LEVEL_IN_STRING: "", + LOG_MESSAGE_KEY: "msg", + REDIS_URL: "", + SENTRY_DSN: "", +}; +/** + * Merges configuration from defaults/environment variables/overrides and returns + * a Probot instance. Finds private key using [`@probot/get-private-key`](https://github.com/probot/get-private-key). + * + * @see https://probot.github.io/docs/configuration/ + * @param defaults default Options, will be overwritten if according environment variable is set + * @param overrides overwrites defaults and according environment variables + * @param env defaults to process.env + */ +function createProbot({ overrides = {}, defaults = {}, env = process.env, } = {}) { + const privateKey = get_private_key_1.getPrivateKey({ env }); + const envWithDefaults = { ...DEFAULTS, ...env }; + const envOptions = { + logLevel: envWithDefaults.LOG_LEVEL, + appId: Number(envWithDefaults.APP_ID), + privateKey: (privateKey && privateKey.toString()) || undefined, + secret: envWithDefaults.WEBHOOK_SECRET, + redisConfig: envWithDefaults.REDIS_URL, + baseUrl: envWithDefaults.GHE_HOST + ? `${envWithDefaults.GHE_PROTOCOL || "https"}://${envWithDefaults.GHE_HOST}/api/v3` + : "https://api.github.com", + }; + const probotOptions = { + ...defaults, + ...envOptions, + ...overrides, + }; + const logOptions = { + level: probotOptions.logLevel, + logFormat: envWithDefaults.LOG_FORMAT, + logLevelInString: envWithDefaults.LOG_LEVEL_IN_STRING === "true", + logMessageKey: envWithDefaults.LOG_MESSAGE_KEY, + sentryDsn: envWithDefaults.SENTRY_DSN, + }; + const log = get_log_1.getLog(logOptions).child({ name: "server" }); + return new probot_1.Probot({ + log: log.child({ name: "probot" }), + ...probotOptions, + }); +} +exports.createProbot = createProbot; +//# sourceMappingURL=create-probot.js.map + +/***/ }), + +/***/ 19752: +/***/ ((__unused_webpack_module, exports) => { + +"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 + +/***/ }), + +/***/ 5789: +/***/ ((__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 + +/***/ }), + +/***/ 90751: +/***/ (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 + +/***/ }), + +/***/ 75381: +/***/ ((__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 + +/***/ }), + +/***/ 33208: +/***/ (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 + +/***/ }), + +/***/ 66217: +/***/ ((__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 + +/***/ }), + +/***/ 93181: +/***/ ((__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__(45006); +Object.defineProperty(exports, "Context", ({ enumerable: true, get: function () { return context_1.Context; } })); +const probot_1 = __nccwpck_require__(22357); +Object.defineProperty(exports, "Probot", ({ enumerable: true, get: function () { return probot_1.Probot; } })); +const server_1 = __nccwpck_require__(83148); +Object.defineProperty(exports, "Server", ({ enumerable: true, get: function () { return server_1.Server; } })); +const probot_octokit_1 = __nccwpck_require__(97268); +Object.defineProperty(exports, "ProbotOctokit", ({ enumerable: true, get: function () { return probot_octokit_1.ProbotOctokit; } })); +const run_1 = __nccwpck_require__(57124); +Object.defineProperty(exports, "run", ({ enumerable: true, get: function () { return run_1.run; } })); +const create_node_middleware_1 = __nccwpck_require__(44488); +Object.defineProperty(exports, "createNodeMiddleware", ({ enumerable: true, get: function () { return create_node_middleware_1.createNodeMiddleware; } })); +const create_probot_1 = __nccwpck_require__(52728); +Object.defineProperty(exports, "createProbot", ({ enumerable: true, get: function () { return create_probot_1.createProbot; } })); +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 18785: +/***/ (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__(21917)); +const path_1 = __importDefault(__nccwpck_require__(71017)); +const update_dotenv_1 = __importDefault(__nccwpck_require__(51023)); +const probot_octokit_1 = __nccwpck_require__(97268); +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}/settings/apps/new`; + } +} +exports.ManifestCreation = ManifestCreation; +//# sourceMappingURL=manifest-creation.js.map + +/***/ }), + +/***/ 53535: +/***/ ((__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 + +/***/ }), + +/***/ 51729: +/***/ (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 + +/***/ }), + +/***/ 1330: +/***/ ((__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__(51729); +/** + * 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 + +/***/ }), + +/***/ 879: +/***/ ((__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__(5789); +const octokit_webhooks_transform_1 = __nccwpck_require__(16973); +// 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 + +/***/ }), + +/***/ 7828: +/***/ ((__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 + +/***/ }), + +/***/ 16973: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.webhookTransform = void 0; +const context_1 = __nccwpck_require__(45006); +/** + * 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 + +/***/ }), + +/***/ 97268: +/***/ ((__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__(7828); +const version_1 = __nccwpck_require__(1403); +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 + +/***/ }), + +/***/ 22357: +/***/ (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__(19752); +const auth_1 = __nccwpck_require__(81084); +const get_log_1 = __nccwpck_require__(90751); +const get_probot_octokit_with_defaults_1 = __nccwpck_require__(1330); +const get_webhooks_1 = __nccwpck_require__(879); +const probot_octokit_1 = __nccwpck_require__(97268); +const version_1 = __nccwpck_require__(1403); +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 + +/***/ }), + +/***/ 57124: +/***/ (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__(93181); +const setup_1 = __nccwpck_require__(36769); +const get_log_1 = __nccwpck_require__(90751); +const read_cli_options_1 = __nccwpck_require__(57767); +const read_env_options_1 = __nccwpck_require__(74420); +const server_1 = __nccwpck_require__(83148); +const default_1 = __nccwpck_require__(3598); +const resolve_app_function_1 = __nccwpck_require__(33208); +const is_production_1 = __nccwpck_require__(75381); +/** + * + * @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 + +/***/ }), + +/***/ 24631: +/***/ (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 + +/***/ }), + +/***/ 83148: +/***/ (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__(90751); +const logging_middleware_1 = __nccwpck_require__(24631); +const webhook_proxy_1 = __nccwpck_require__(66217); +const version_1 = __nccwpck_require__(1403); +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 + +/***/ }), + +/***/ 1403: +/***/ ((__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.1.4"; +//# sourceMappingURL=version.js.map + +/***/ }), + +/***/ 96645: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +const { inspect } = __nccwpck_require__(73837); + +const through = __nccwpck_require__(18180); +const core = __nccwpck_require__(68648); +const pino = __nccwpck_require__(79608); + +const LEVEL_TO_ACTIONS_CORE_LOG_METHOD = { + trace: "debug", + debug: "debug", + info: "info", + warn: "warning", + error: "error", + fatal: "error", +}; + +const transport = through.obj(function (chunk, enc, cb) { + const { level, hostname, pid, msg, time, ...meta } = JSON.parse(chunk); + const levelLabel = pino.levels.labels[level] || level; + const logMethodName = LEVEL_TO_ACTIONS_CORE_LOG_METHOD[levelLabel]; + + const output = [ + msg, + Object.keys(meta).length ? inspect(meta, { depth: Infinity }) : "", + ] + .join("\n") + .trim(); + + if (logMethodName in core) { + core[logMethodName](output); + } else { + core.error(`"${level}" is not a known log level - ${output}`); + } + + cb(); +}); + +module.exports = { transport }; + + +/***/ }), + +/***/ 97743: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } + +var path = __nccwpck_require__(71017); +var fs = __nccwpck_require__(57147); +var isBase64 = _interopDefault(__nccwpck_require__(31310)); + +const VERSION = "0.0.0-development"; + +function getPrivateKey(options = {}) { + const env = options.env || process.env; + const cwd = options.cwd || process.cwd(); + + if (options.filepath) { + return fs.readFileSync(path.resolve(cwd, options.filepath), "utf-8"); + } + + if (env.PRIVATE_KEY) { + let privateKey = env.PRIVATE_KEY; + + if (isBase64(privateKey)) { + // Decode base64-encoded certificate + privateKey = Buffer.from(privateKey, "base64").toString(); + } + + const begin = "-----BEGIN RSA PRIVATE KEY-----"; + const end = "-----END RSA PRIVATE KEY-----"; + + if (privateKey.includes(begin) && privateKey.includes(end)) { + // Full key with new lines + return privateKey.replace(/\\n/g, "\n"); + } + + throw new Error(`[@probot/get-private-key] The contents of "env.PRIVATE_KEY" could not be validated. Please check to ensure you have copied the contents of the .pem file correctly.`); + } + + if (env.PRIVATE_KEY_PATH) { + const filepath = path.resolve(cwd, env.PRIVATE_KEY_PATH); + + if (fs.existsSync(filepath)) { + return fs.readFileSync(filepath, "utf-8"); + } else { + throw new Error(`[@probot/get-private-key] Private key does not exists at path: "${env.PRIVATE_KEY_PATH}". Please check to ensure that "env.PRIVATE_KEY_PATH" is correct.`); + } + } + + const pemFiles = fs.readdirSync(cwd).filter(path => path.endsWith(".pem")); + + if (pemFiles.length > 1) { + const paths = pemFiles.join(", "); + throw new Error(`[@probot/get-private-key] More than one file found: "${paths}". Set { filepath } option or set one of the environment variables: PRIVATE_KEY, PRIVATE_KEY_PATH`); + } else if (pemFiles[0]) { + return getPrivateKey({ + filepath: pemFiles[0], + cwd + }); + } + + return null; +} +getPrivateKey.VERSION = VERSION; + +exports.getPrivateKey = getPrivateKey; +//# sourceMappingURL=index.js.map + + +/***/ }), + +/***/ 59326: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } + +var yaml = _interopDefault(__nccwpck_require__(21917)); + +const VERSION = "1.0.1"; + +function _defineProperty(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + + return obj; +} + +function ownKeys(object, enumerableOnly) { + var keys = Object.keys(object); + + if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(object); + if (enumerableOnly) symbols = symbols.filter(function (sym) { + return Object.getOwnPropertyDescriptor(object, sym).enumerable; + }); + keys.push.apply(keys, symbols); + } + + return keys; +} + +function _objectSpread2(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i] != null ? arguments[i] : {}; + + if (i % 2) { + ownKeys(Object(source), true).forEach(function (key) { + _defineProperty(target, key, source[key]); + }); + } else if (Object.getOwnPropertyDescriptors) { + Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); + } else { + ownKeys(Object(source)).forEach(function (key) { + Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); + }); + } + } + + return target; +} + +const SUPPORTED_FILE_EXTENSIONS = ["json", "yml", "yaml"]; +/** + * Load configuration from a given repository and path. + * + * @param octokit Octokit instance + * @param options + */ + +async function getConfigFile(octokit, { + owner, + repo, + path, + ref +}) { + const fileExtension = path.split(".").pop().toLowerCase(); + + if (!SUPPORTED_FILE_EXTENSIONS.includes(fileExtension)) { + throw new Error(`[@probot/octokit-plugin-config] .${fileExtension} extension is not support for configuration (path: "${path}")`); + } // https://docs.github.com/en/rest/reference/repos#get-repository-content + + + const requestOptions = await octokit.request.endpoint("GET /repos/{owner}/{repo}/contents/{path}", _objectSpread2({ + owner, + repo, + path, + mediaType: { + format: "raw" + } + }, ref ? { + ref + } : {})); + const emptyConfigResult = { + owner, + repo, + path, + url: requestOptions.url, + config: null + }; + + try { + const { + data, + headers + } = await octokit.request(requestOptions); // If path is a submodule, or a folder, then a JSON string is returned with + // the "Content-Type" header set to "application/json; charset=utf-8". + // + // - https://docs.github.com/en/rest/reference/repos#if-the-content-is-a-submodule + // - https://docs.github.com/en/rest/reference/repos#if-the-content-is-a-directory + // + // symlinks just return the content of the linked file when requesting the raw formt, + // so we are fine + + if (headers["content-type"] === "application/json; charset=utf-8") { + throw new Error(`[@probot/octokit-plugin-config] ${requestOptions.url} exists, but is either a directory or a submodule. Ignoring.`); + } + + if (fileExtension === "json") { + if (typeof data === "string") { + throw new Error(`[@probot/octokit-plugin-config] Configuration could not be parsed from ${requestOptions.url} (invalid JSON)`); } - }], - users: ["GET /search/users"] - }, - secretScanning: { - getAlert: ["GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}"], - listAlertsForOrg: ["GET /orgs/{org}/secret-scanning/alerts"], - listAlertsForRepo: ["GET /repos/{owner}/{repo}/secret-scanning/alerts"], - updateAlert: ["PATCH /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}"] - }, - teams: { - addOrUpdateMembershipForUserInOrg: ["PUT /orgs/{org}/teams/{team_slug}/memberships/{username}"], - addOrUpdateProjectPermissionsInOrg: ["PUT /orgs/{org}/teams/{team_slug}/projects/{project_id}"], - addOrUpdateRepoPermissionsInOrg: ["PUT /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}"], - checkPermissionsForProjectInOrg: ["GET /orgs/{org}/teams/{team_slug}/projects/{project_id}"], - checkPermissionsForRepoInOrg: ["GET /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}"], - create: ["POST /orgs/{org}/teams"], - createDiscussionCommentInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments"], - createDiscussionInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions"], - deleteDiscussionCommentInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}"], - deleteDiscussionInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}"], - deleteInOrg: ["DELETE /orgs/{org}/teams/{team_slug}"], - getByName: ["GET /orgs/{org}/teams/{team_slug}"], - getDiscussionCommentInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}"], - getDiscussionInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}"], - getMembershipForUserInOrg: ["GET /orgs/{org}/teams/{team_slug}/memberships/{username}"], - list: ["GET /orgs/{org}/teams"], - listChildInOrg: ["GET /orgs/{org}/teams/{team_slug}/teams"], - listDiscussionCommentsInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments"], - listDiscussionsInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions"], - listForAuthenticatedUser: ["GET /user/teams"], - listMembersInOrg: ["GET /orgs/{org}/teams/{team_slug}/members"], - listPendingInvitationsInOrg: ["GET /orgs/{org}/teams/{team_slug}/invitations"], - listProjectsInOrg: ["GET /orgs/{org}/teams/{team_slug}/projects"], - listReposInOrg: ["GET /orgs/{org}/teams/{team_slug}/repos"], - removeMembershipForUserInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/memberships/{username}"], - removeProjectInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/projects/{project_id}"], - removeRepoInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}"], - updateDiscussionCommentInOrg: ["PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}"], - updateDiscussionInOrg: ["PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}"], - updateInOrg: ["PATCH /orgs/{org}/teams/{team_slug}"] - }, - users: { - addEmailForAuthenticated: ["POST /user/emails", {}, { - renamed: ["users", "addEmailForAuthenticatedUser"] - }], - addEmailForAuthenticatedUser: ["POST /user/emails"], - block: ["PUT /user/blocks/{username}"], - checkBlocked: ["GET /user/blocks/{username}"], - checkFollowingForUser: ["GET /users/{username}/following/{target_user}"], - checkPersonIsFollowedByAuthenticated: ["GET /user/following/{username}"], - createGpgKeyForAuthenticated: ["POST /user/gpg_keys", {}, { - renamed: ["users", "createGpgKeyForAuthenticatedUser"] - }], - createGpgKeyForAuthenticatedUser: ["POST /user/gpg_keys"], - createPublicSshKeyForAuthenticated: ["POST /user/keys", {}, { - renamed: ["users", "createPublicSshKeyForAuthenticatedUser"] - }], - createPublicSshKeyForAuthenticatedUser: ["POST /user/keys"], - deleteEmailForAuthenticated: ["DELETE /user/emails", {}, { - renamed: ["users", "deleteEmailForAuthenticatedUser"] - }], - deleteEmailForAuthenticatedUser: ["DELETE /user/emails"], - deleteGpgKeyForAuthenticated: ["DELETE /user/gpg_keys/{gpg_key_id}", {}, { - renamed: ["users", "deleteGpgKeyForAuthenticatedUser"] - }], - deleteGpgKeyForAuthenticatedUser: ["DELETE /user/gpg_keys/{gpg_key_id}"], - deletePublicSshKeyForAuthenticated: ["DELETE /user/keys/{key_id}", {}, { - renamed: ["users", "deletePublicSshKeyForAuthenticatedUser"] - }], - deletePublicSshKeyForAuthenticatedUser: ["DELETE /user/keys/{key_id}"], - follow: ["PUT /user/following/{username}"], - getAuthenticated: ["GET /user"], - getByUsername: ["GET /users/{username}"], - getContextForUser: ["GET /users/{username}/hovercard"], - getGpgKeyForAuthenticated: ["GET /user/gpg_keys/{gpg_key_id}", {}, { - renamed: ["users", "getGpgKeyForAuthenticatedUser"] - }], - getGpgKeyForAuthenticatedUser: ["GET /user/gpg_keys/{gpg_key_id}"], - getPublicSshKeyForAuthenticated: ["GET /user/keys/{key_id}", {}, { - renamed: ["users", "getPublicSshKeyForAuthenticatedUser"] - }], - getPublicSshKeyForAuthenticatedUser: ["GET /user/keys/{key_id}"], - list: ["GET /users"], - listBlockedByAuthenticated: ["GET /user/blocks", {}, { - renamed: ["users", "listBlockedByAuthenticatedUser"] - }], - listBlockedByAuthenticatedUser: ["GET /user/blocks"], - listEmailsForAuthenticated: ["GET /user/emails", {}, { - renamed: ["users", "listEmailsForAuthenticatedUser"] - }], - listEmailsForAuthenticatedUser: ["GET /user/emails"], - listFollowedByAuthenticated: ["GET /user/following", {}, { - renamed: ["users", "listFollowedByAuthenticatedUser"] - }], - listFollowedByAuthenticatedUser: ["GET /user/following"], - listFollowersForAuthenticatedUser: ["GET /user/followers"], - listFollowersForUser: ["GET /users/{username}/followers"], - listFollowingForUser: ["GET /users/{username}/following"], - listGpgKeysForAuthenticated: ["GET /user/gpg_keys", {}, { - renamed: ["users", "listGpgKeysForAuthenticatedUser"] - }], - listGpgKeysForAuthenticatedUser: ["GET /user/gpg_keys"], - listGpgKeysForUser: ["GET /users/{username}/gpg_keys"], - listPublicEmailsForAuthenticated: ["GET /user/public_emails", {}, { - renamed: ["users", "listPublicEmailsForAuthenticatedUser"] - }], - listPublicEmailsForAuthenticatedUser: ["GET /user/public_emails"], - listPublicKeysForUser: ["GET /users/{username}/keys"], - listPublicSshKeysForAuthenticated: ["GET /user/keys", {}, { - renamed: ["users", "listPublicSshKeysForAuthenticatedUser"] - }], - listPublicSshKeysForAuthenticatedUser: ["GET /user/keys"], - setPrimaryEmailVisibilityForAuthenticated: ["PATCH /user/email/visibility", {}, { - renamed: ["users", "setPrimaryEmailVisibilityForAuthenticatedUser"] - }], - setPrimaryEmailVisibilityForAuthenticatedUser: ["PATCH /user/email/visibility"], - unblock: ["DELETE /user/blocks/{username}"], - unfollow: ["DELETE /user/following/{username}"], - updateAuthenticated: ["PATCH /user"] + + return _objectSpread2(_objectSpread2({}, emptyConfigResult), {}, { + config: data + }); + } + + const config = yaml.safeLoad(data) || {}; + + if (typeof config === "string") { + throw new Error(`[@probot/octokit-plugin-config] Configuration could not be parsed from ${requestOptions.url} (YAML is not an object)`); + } + + return _objectSpread2(_objectSpread2({}, emptyConfigResult), {}, { + config + }); + } catch (error) { + if (error.status === 404) { + return emptyConfigResult; + } + + if (error.name === "YAMLException") { + const reason = /unknown tag/.test(error.message) ? "unsafe YAML" : "invalid YAML"; + throw new Error(`[@probot/octokit-plugin-config] Configuration could not be parsed from ${requestOptions.url} (${reason})`); + } + + throw error; + } +} + +const EXTENDS_REGEX = new RegExp("^" + "(?:([a-z\\d](?:[a-z\\d]|-(?=[a-z\\d])){0,38})/)?" + // org +"([-_.\\w\\d]+)" + // project +"(?::([-_./\\w\\d]+\\.ya?ml))?" + // filename +"$", "i"); +/** + * Computes parameters to retrieve the configuration file specified in _extends + * + * Base can either be the name of a repository in the same organization or + * a full slug "organization/repo". + * + * @param options + * @return The params needed to retrieve a configuration file + */ + +function extendsToGetContentParams({ + owner, + path, + url, + extendsValue +}) { + if (typeof extendsValue !== "string") { + throw new Error(`[@probot/octokit-plugin-config] Invalid value ${JSON.stringify(extendsValue)} for _extends in ${url}`); + } + + const match = extendsValue.match(EXTENDS_REGEX); + + if (match === null) { + throw new Error(`[@probot/octokit-plugin-config] Invalid value "${extendsValue}" for _extends in ${url}`); } + + return { + owner: match[1] || owner, + repo: match[2], + path: match[3] || path + }; +} + +/** + * Load configuration from selected repository file. If the file does not exist + * it loads configuration from the owners `.github` repository. + * + * If the repository file configuration includes an `_extends` key, that file + * is loaded. Same with the target file until no `_extends` key is present. + * + * @param octokit Octokit instance + * @param options + */ + +async function getConfigFiles(octokit, { + owner, + repo, + path, + branch +}) { + const requestedRepoFile = await getConfigFile(octokit, { + owner, + repo, + path, + ref: branch + }); // if no configuration file present in selected repository, + // try to load it from the `.github` repository + + if (!requestedRepoFile.config) { + if (repo === ".github") { + return [requestedRepoFile]; + } + + const defaultRepoConfig = await getConfigFile(octokit, { + owner, + repo: ".github", + path + }); + return [requestedRepoFile, defaultRepoConfig]; + } // if the configuration has no `_extends` key, we are done here. + + + if (!requestedRepoFile.config._extends) { + return [requestedRepoFile]; + } // parse the value of `_extends` into request parameters to + // retrieve the new configuration file + + + let extendConfigOptions = extendsToGetContentParams({ + owner, + path, + url: requestedRepoFile.url, + extendsValue: requestedRepoFile.config._extends + }); // remove the `_extends` key from the configuration that is returned + + delete requestedRepoFile.config._extends; + const files = [requestedRepoFile]; // now load the configuration linked from the `_extends` key. If that + // configuration also includes an `_extends` key, then load that configuration + // as well, until the target configuration has no `_extends` key + + do { + const extendRepoConfig = await getConfigFile(octokit, extendConfigOptions); + files.push(extendRepoConfig); + + if (!extendRepoConfig.config || !extendRepoConfig.config._extends) { + return files; + } + + extendConfigOptions = extendsToGetContentParams({ + owner, + path, + url: extendRepoConfig.url, + extendsValue: extendRepoConfig.config._extends + }); + delete extendRepoConfig.config._extends; // Avoid loops + + const alreadyLoaded = files.find(file => file.owner === extendConfigOptions.owner && file.repo === extendConfigOptions.repo && file.path === extendConfigOptions.path); + + if (alreadyLoaded) { + throw new Error(`[@probot/octokit-plugin-config] Recursion detected. Ignoring "_extends: ${extendRepoConfig.config._extends}" from ${extendRepoConfig.url} because ${alreadyLoaded.url} was already loaded.`); + } + } while (true); +} + +/** + * Loads configuration from one or multiple files and resolves with + * the combined configuration as well as the list of files the configuration + * was loaded from + * + * @param octokit Octokit instance + * @param options + */ + +async function composeConfigGet(octokit, { + owner, + repo, + defaults, + path, + branch +}) { + const files = await getConfigFiles(octokit, { + owner, + repo, + path, + branch + }); + const configs = files.map(file => file.config).reverse().filter(Boolean); + return { + files, + config: typeof defaults === "function" ? defaults(configs) : Object.assign({}, defaults, ...configs) + }; +} + +/** + * @param octokit Octokit instance + */ + +function config(octokit) { + return { + config: { + async get(options) { + return composeConfigGet(octokit, options); + } + + } + }; +} +config.VERSION = VERSION; + +exports.composeConfigGet = composeConfigGet; +exports.config = config; +//# sourceMappingURL=index.js.map + + +/***/ }), + +/***/ 39662: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +module.exports = { getTransformStream }; + +const { Transform } = __nccwpck_require__(51642); + +const prettyFactory = __nccwpck_require__(31691); +const Sentry = __nccwpck_require__(22783); + +const LEVEL_MAP = { + 10: "trace", + 20: "debug", + 30: "info", + 40: "warn", + 50: "error", + 60: "fatal", }; -const VERSION = "5.13.0"; +/** + * Implements Probot's default logging formatting and error captionaing using Sentry. + * + * @param {import("./").Options} options + * @returns Transform + * @see https://getpino.io/#/docs/transports + */ +function getTransformStream(options = {}) { + const formattingEnabled = options.logFormat !== "json"; + const levelAsString = options.logLevelInString === "true"; + const sentryEnabled = !!options.sentryDsn; + + if (sentryEnabled) { + Sentry.init({ + dsn: options.sentryDsn, + // See https://github.com/getsentry/sentry-javascript/issues/1964#issuecomment-688482615 + // 6 is enough to serialize the deepest property across all GitHub Event payloads + normalizeDepth: 6, + }); + } + + const pretty = prettyFactory({ + ignore: [ + // default pino keys + "time", + "pid", + "hostname", + // remove keys from pino-http + "req", + "res", + "responseTime", + ].join(","), + errorProps: ["event", "status", "headers", "request"].join(","), + }); + + return new Transform({ + objectMode: true, + transform(chunk, enc, cb) { + const line = chunk.toString().trim(); + + /* istanbul ignore if */ + if (line === undefined) return cb(); + + const data = sentryEnabled ? JSON.parse(line) : null; + + if (sentryEnabled && data.level >= 50) { + Sentry.withScope(function (scope) { + const sentryLevelName = + data.level === 50 ? Sentry.Severity.Error : Sentry.Severity.Fatal; + scope.setLevel(sentryLevelName); + + for (const extra of ["event", "headers", "request", "status"]) { + if (!data[extra]) continue; + + scope.setExtra(extra, data[extra]); + } + + // set user id and username to installation ID and account login + if (data.event && data.event.payload) { + const { + // When GitHub App is installed organization wide + installation: { id, account: { login: account } = {} } = {}, + + // When the repository belongs to an organization + organization: { login: organization } = {}, + // When the repository belongs to a user + repository: { owner: { login: owner } = {} } = {}, + } = data.event.payload; + + scope.setUser({ + id: id, + username: account || organization || owner, + }); + } + + Sentry.captureException(toSentryError(data)); + }); + } + + if (formattingEnabled) { + return cb(null, pretty(data || line)); + } + + if (levelAsString) { + return cb(null, stringifyLogLevel(data || JSON.parse(line))); + } + + cb(null, line + "\n"); + }, + }); +} + +function stringifyLogLevel(data) { + data.level = LEVEL_MAP[data.level]; + return JSON.stringify(data) + "\n"; +} + +function toSentryError(data) { + const error = new Error(data.msg); + error.name = data.type; + error.stack = data.stack; + return error; +} + + +/***/ }), + +/***/ 90785: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); +var utils_1 = __nccwpck_require__(1620); +var SENTRY_API_VERSION = '7'; +/** Helper class to provide urls to different Sentry endpoints. */ +var API = /** @class */ (function () { + /** Create a new instance of API */ + function API(dsn) { + this.dsn = dsn; + this._dsnObject = new utils_1.Dsn(dsn); + } + /** Returns the Dsn object. */ + API.prototype.getDsn = function () { + return this._dsnObject; + }; + /** Returns the prefix to construct Sentry ingestion API endpoints. */ + API.prototype.getBaseApiEndpoint = function () { + var dsn = this._dsnObject; + var protocol = dsn.protocol ? dsn.protocol + ":" : ''; + var port = dsn.port ? ":" + dsn.port : ''; + return protocol + "//" + dsn.host + port + (dsn.path ? "/" + dsn.path : '') + "/api/"; + }; + /** Returns the store endpoint URL. */ + API.prototype.getStoreEndpoint = function () { + return this._getIngestEndpoint('store'); + }; + /** + * Returns the store endpoint URL with auth in the query string. + * + * Sending auth as part of the query string and not as custom HTTP headers avoids CORS preflight requests. + */ + API.prototype.getStoreEndpointWithUrlEncodedAuth = function () { + return this.getStoreEndpoint() + "?" + this._encodedAuth(); + }; + /** + * Returns the envelope endpoint URL with auth in the query string. + * + * Sending auth as part of the query string and not as custom HTTP headers avoids CORS preflight requests. + */ + API.prototype.getEnvelopeEndpointWithUrlEncodedAuth = function () { + return this._getEnvelopeEndpoint() + "?" + this._encodedAuth(); + }; + /** Returns only the path component for the store endpoint. */ + API.prototype.getStoreEndpointPath = function () { + var dsn = this._dsnObject; + return (dsn.path ? "/" + dsn.path : '') + "/api/" + dsn.projectId + "/store/"; + }; + /** + * Returns an object that can be used in request headers. + * This is needed for node and the old /store endpoint in sentry + */ + API.prototype.getRequestHeaders = function (clientName, clientVersion) { + var dsn = this._dsnObject; + var header = ["Sentry sentry_version=" + SENTRY_API_VERSION]; + header.push("sentry_client=" + clientName + "/" + clientVersion); + header.push("sentry_key=" + dsn.user); + if (dsn.pass) { + header.push("sentry_secret=" + dsn.pass); + } + return { + 'Content-Type': 'application/json', + 'X-Sentry-Auth': header.join(', '), + }; + }; + /** Returns the url to the report dialog endpoint. */ + API.prototype.getReportDialogEndpoint = function (dialogOptions) { + if (dialogOptions === void 0) { dialogOptions = {}; } + var dsn = this._dsnObject; + var endpoint = this.getBaseApiEndpoint() + "embed/error-page/"; + var encodedOptions = []; + encodedOptions.push("dsn=" + dsn.toString()); + for (var key in dialogOptions) { + if (key === 'dsn') { + continue; + } + if (key === 'user') { + if (!dialogOptions.user) { + continue; + } + if (dialogOptions.user.name) { + encodedOptions.push("name=" + encodeURIComponent(dialogOptions.user.name)); + } + if (dialogOptions.user.email) { + encodedOptions.push("email=" + encodeURIComponent(dialogOptions.user.email)); + } + } + else { + encodedOptions.push(encodeURIComponent(key) + "=" + encodeURIComponent(dialogOptions[key])); + } + } + if (encodedOptions.length) { + return endpoint + "?" + encodedOptions.join('&'); + } + return endpoint; + }; + /** Returns the envelope endpoint URL. */ + API.prototype._getEnvelopeEndpoint = function () { + return this._getIngestEndpoint('envelope'); + }; + /** Returns the ingest API endpoint for target. */ + API.prototype._getIngestEndpoint = function (target) { + var base = this.getBaseApiEndpoint(); + var dsn = this._dsnObject; + return "" + base + dsn.projectId + "/" + target + "/"; + }; + /** Returns a URL-encoded string with auth config suitable for a query string. */ + API.prototype._encodedAuth = function () { + var dsn = this._dsnObject; + var auth = { + // We send only the minimum set of required information. See + // https://github.com/getsentry/sentry-javascript/issues/2572. + sentry_key: dsn.user, + sentry_version: SENTRY_API_VERSION, + }; + return utils_1.urlEncode(auth); + }; + return API; +}()); +exports.API = API; +//# sourceMappingURL=api.js.map + +/***/ }), + +/***/ 25886: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); +var utils_1 = __nccwpck_require__(1620); +var noop_1 = __nccwpck_require__(68641); +/** + * This is the base implemention of a Backend. + * @hidden + */ +var BaseBackend = /** @class */ (function () { + /** Creates a new backend instance. */ + function BaseBackend(options) { + this._options = options; + if (!this._options.dsn) { + utils_1.logger.warn('No DSN provided, backend will not do anything.'); + } + this._transport = this._setupTransport(); + } + /** + * @inheritDoc + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types + BaseBackend.prototype.eventFromException = function (_exception, _hint) { + throw new utils_1.SentryError('Backend has to implement `eventFromException` method'); + }; + /** + * @inheritDoc + */ + BaseBackend.prototype.eventFromMessage = function (_message, _level, _hint) { + throw new utils_1.SentryError('Backend has to implement `eventFromMessage` method'); + }; + /** + * @inheritDoc + */ + BaseBackend.prototype.sendEvent = function (event) { + this._transport.sendEvent(event).then(null, function (reason) { + utils_1.logger.error("Error while sending event: " + reason); + }); + }; + /** + * @inheritDoc + */ + BaseBackend.prototype.sendSession = function (session) { + if (!this._transport.sendSession) { + utils_1.logger.warn("Dropping session because custom transport doesn't implement sendSession"); + return; + } + this._transport.sendSession(session).then(null, function (reason) { + utils_1.logger.error("Error while sending session: " + reason); + }); + }; + /** + * @inheritDoc + */ + BaseBackend.prototype.getTransport = function () { + return this._transport; + }; + /** + * Sets up the transport so it can be used later to send requests. + */ + BaseBackend.prototype._setupTransport = function () { + return new noop_1.NoopTransport(); + }; + return BaseBackend; +}()); +exports.BaseBackend = BaseBackend; +//# sourceMappingURL=basebackend.js.map + +/***/ }), + +/***/ 25684: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __nccwpck_require__(4351); +/* eslint-disable max-lines */ +var hub_1 = __nccwpck_require__(6393); +var types_1 = __nccwpck_require__(83789); +var utils_1 = __nccwpck_require__(1620); +var integration_1 = __nccwpck_require__(58500); +/** + * Base implementation for all JavaScript SDK clients. + * + * Call the constructor with the corresponding backend constructor and options + * specific to the client subclass. To access these options later, use + * {@link Client.getOptions}. Also, the Backend instance is available via + * {@link Client.getBackend}. + * + * If a Dsn is specified in the options, it will be parsed and stored. Use + * {@link Client.getDsn} to retrieve the Dsn at any moment. In case the Dsn is + * invalid, the constructor will throw a {@link SentryException}. Note that + * without a valid Dsn, the SDK will not send any events to Sentry. + * + * Before sending an event via the backend, it is passed through + * {@link BaseClient.prepareEvent} to add SDK information and scope data + * (breadcrumbs and context). To add more custom information, override this + * method and extend the resulting prepared event. + * + * To issue automatically created events (e.g. via instrumentation), use + * {@link Client.captureEvent}. It will prepare the event and pass it through + * the callback lifecycle. To issue auto-breadcrumbs, use + * {@link Client.addBreadcrumb}. + * + * @example + * class NodeClient extends BaseClient { + * public constructor(options: NodeOptions) { + * super(NodeBackend, options); + * } + * + * // ... + * } + */ +var BaseClient = /** @class */ (function () { + /** + * Initializes this client instance. + * + * @param backendClass A constructor function to create the backend. + * @param options Options for the client. + */ + function BaseClient(backendClass, options) { + /** Array of used integrations. */ + this._integrations = {}; + /** Number of call being processed */ + this._processing = 0; + this._backend = new backendClass(options); + this._options = options; + if (options.dsn) { + this._dsn = new utils_1.Dsn(options.dsn); + } + } + /** + * @inheritDoc + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types + BaseClient.prototype.captureException = function (exception, hint, scope) { + var _this = this; + var eventId = hint && hint.event_id; + this._process(this._getBackend() + .eventFromException(exception, hint) + .then(function (event) { return _this._captureEvent(event, hint, scope); }) + .then(function (result) { + eventId = result; + })); + return eventId; + }; + /** + * @inheritDoc + */ + BaseClient.prototype.captureMessage = function (message, level, hint, scope) { + var _this = this; + var eventId = hint && hint.event_id; + var promisedEvent = utils_1.isPrimitive(message) + ? this._getBackend().eventFromMessage(String(message), level, hint) + : this._getBackend().eventFromException(message, hint); + this._process(promisedEvent + .then(function (event) { return _this._captureEvent(event, hint, scope); }) + .then(function (result) { + eventId = result; + })); + return eventId; + }; + /** + * @inheritDoc + */ + BaseClient.prototype.captureEvent = function (event, hint, scope) { + var eventId = hint && hint.event_id; + this._process(this._captureEvent(event, hint, scope).then(function (result) { + eventId = result; + })); + return eventId; + }; + /** + * @inheritDoc + */ + BaseClient.prototype.captureSession = function (session) { + if (!session.release) { + utils_1.logger.warn('Discarded session because of missing release'); + } + else { + this._sendSession(session); + } + }; + /** + * @inheritDoc + */ + BaseClient.prototype.getDsn = function () { + return this._dsn; + }; + /** + * @inheritDoc + */ + BaseClient.prototype.getOptions = function () { + return this._options; + }; + /** + * @inheritDoc + */ + BaseClient.prototype.flush = function (timeout) { + var _this = this; + return this._isClientProcessing(timeout).then(function (ready) { + return _this._getBackend() + .getTransport() + .close(timeout) + .then(function (transportFlushed) { return ready && transportFlushed; }); + }); + }; + /** + * @inheritDoc + */ + BaseClient.prototype.close = function (timeout) { + var _this = this; + return this.flush(timeout).then(function (result) { + _this.getOptions().enabled = false; + return result; + }); + }; + /** + * Sets up the integrations + */ + BaseClient.prototype.setupIntegrations = function () { + if (this._isEnabled()) { + this._integrations = integration_1.setupIntegrations(this._options); + } + }; + /** + * @inheritDoc + */ + BaseClient.prototype.getIntegration = function (integration) { + try { + return this._integrations[integration.id] || null; + } + catch (_oO) { + utils_1.logger.warn("Cannot retrieve integration " + integration.id + " from the current Client"); + return null; + } + }; + /** Updates existing session based on the provided event */ + BaseClient.prototype._updateSessionFromEvent = function (session, event) { + var e_1, _a; + var crashed = false; + var errored = false; + var userAgent; + var exceptions = event.exception && event.exception.values; + if (exceptions) { + errored = true; + try { + for (var exceptions_1 = tslib_1.__values(exceptions), exceptions_1_1 = exceptions_1.next(); !exceptions_1_1.done; exceptions_1_1 = exceptions_1.next()) { + var ex = exceptions_1_1.value; + var mechanism = ex.mechanism; + if (mechanism && mechanism.handled === false) { + crashed = true; + break; + } + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (exceptions_1_1 && !exceptions_1_1.done && (_a = exceptions_1.return)) _a.call(exceptions_1); + } + finally { if (e_1) throw e_1.error; } + } + } + var user = event.user; + if (!session.userAgent) { + var headers = event.request ? event.request.headers : {}; + for (var key in headers) { + if (key.toLowerCase() === 'user-agent') { + userAgent = headers[key]; + break; + } + } + } + session.update(tslib_1.__assign(tslib_1.__assign({}, (crashed && { status: types_1.SessionStatus.Crashed })), { user: user, + userAgent: userAgent, errors: session.errors + Number(errored || crashed) })); + }; + /** Deliver captured session to Sentry */ + BaseClient.prototype._sendSession = function (session) { + this._getBackend().sendSession(session); + }; + /** Waits for the client to be done with processing. */ + BaseClient.prototype._isClientProcessing = function (timeout) { + var _this = this; + return new utils_1.SyncPromise(function (resolve) { + var ticked = 0; + var tick = 1; + var interval = setInterval(function () { + if (_this._processing == 0) { + clearInterval(interval); + resolve(true); + } + else { + ticked += tick; + if (timeout && ticked >= timeout) { + clearInterval(interval); + resolve(false); + } + } + }, tick); + }); + }; + /** Returns the current backend. */ + BaseClient.prototype._getBackend = function () { + return this._backend; + }; + /** Determines whether this SDK is enabled and a valid Dsn is present. */ + BaseClient.prototype._isEnabled = function () { + return this.getOptions().enabled !== false && this._dsn !== undefined; + }; + /** + * Adds common information to events. + * + * The information includes release and environment from `options`, + * breadcrumbs and context (extra, tags and user) from the scope. + * + * Information that is already present in the event is never overwritten. For + * nested objects, such as the context, keys are merged. + * + * @param event The original event. + * @param hint May contain additional information about the original exception. + * @param scope A scope containing event metadata. + * @returns A new event with more information. + */ + BaseClient.prototype._prepareEvent = function (event, scope, hint) { + var _this = this; + var _a = this.getOptions().normalizeDepth, normalizeDepth = _a === void 0 ? 3 : _a; + var prepared = tslib_1.__assign(tslib_1.__assign({}, event), { event_id: event.event_id || (hint && hint.event_id ? hint.event_id : utils_1.uuid4()), timestamp: event.timestamp || utils_1.dateTimestampInSeconds() }); + this._applyClientOptions(prepared); + this._applyIntegrationsMetadata(prepared); + // If we have scope given to us, use it as the base for further modifications. + // This allows us to prevent unnecessary copying of data if `captureContext` is not provided. + var finalScope = scope; + if (hint && hint.captureContext) { + finalScope = hub_1.Scope.clone(finalScope).update(hint.captureContext); + } + // We prepare the result here with a resolved Event. + var result = utils_1.SyncPromise.resolve(prepared); + // This should be the last thing called, since we want that + // {@link Hub.addEventProcessor} gets the finished prepared event. + if (finalScope) { + // In case we have a hub we reassign it. + result = finalScope.applyToEvent(prepared, hint); + } + return result.then(function (evt) { + if (typeof normalizeDepth === 'number' && normalizeDepth > 0) { + return _this._normalizeEvent(evt, normalizeDepth); + } + return evt; + }); + }; + /** + * Applies `normalize` function on necessary `Event` attributes to make them safe for serialization. + * Normalized keys: + * - `breadcrumbs.data` + * - `user` + * - `contexts` + * - `extra` + * @param event Event + * @returns Normalized event + */ + BaseClient.prototype._normalizeEvent = function (event, depth) { + if (!event) { + return null; + } + var normalized = tslib_1.__assign(tslib_1.__assign(tslib_1.__assign(tslib_1.__assign(tslib_1.__assign({}, event), (event.breadcrumbs && { + breadcrumbs: event.breadcrumbs.map(function (b) { return (tslib_1.__assign(tslib_1.__assign({}, b), (b.data && { + data: utils_1.normalize(b.data, depth), + }))); }), + })), (event.user && { + user: utils_1.normalize(event.user, depth), + })), (event.contexts && { + contexts: utils_1.normalize(event.contexts, depth), + })), (event.extra && { + extra: utils_1.normalize(event.extra, depth), + })); + // event.contexts.trace stores information about a Transaction. Similarly, + // event.spans[] stores information about child Spans. Given that a + // Transaction is conceptually a Span, normalization should apply to both + // Transactions and Spans consistently. + // For now the decision is to skip normalization of Transactions and Spans, + // so this block overwrites the normalized event to add back the original + // Transaction information prior to normalization. + if (event.contexts && event.contexts.trace) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + normalized.contexts.trace = event.contexts.trace; + } + return normalized; + }; + /** + * Enhances event using the client configuration. + * It takes care of all "static" values like environment, release and `dist`, + * as well as truncating overly long values. + * @param event event instance to be enhanced + */ + BaseClient.prototype._applyClientOptions = function (event) { + var options = this.getOptions(); + var environment = options.environment, release = options.release, dist = options.dist, _a = options.maxValueLength, maxValueLength = _a === void 0 ? 250 : _a; + if (!('environment' in event)) { + event.environment = 'environment' in options ? environment : 'production'; + } + if (event.release === undefined && release !== undefined) { + event.release = release; + } + if (event.dist === undefined && dist !== undefined) { + event.dist = dist; + } + if (event.message) { + event.message = utils_1.truncate(event.message, maxValueLength); + } + var exception = event.exception && event.exception.values && event.exception.values[0]; + if (exception && exception.value) { + exception.value = utils_1.truncate(exception.value, maxValueLength); + } + var request = event.request; + if (request && request.url) { + request.url = utils_1.truncate(request.url, maxValueLength); + } + }; + /** + * This function adds all used integrations to the SDK info in the event. + * @param sdkInfo The sdkInfo of the event that will be filled with all integrations. + */ + BaseClient.prototype._applyIntegrationsMetadata = function (event) { + var sdkInfo = event.sdk; + var integrationsArray = Object.keys(this._integrations); + if (sdkInfo && integrationsArray.length > 0) { + sdkInfo.integrations = integrationsArray; + } + }; + /** + * Tells the backend to send this event + * @param event The Sentry event to send + */ + BaseClient.prototype._sendEvent = function (event) { + this._getBackend().sendEvent(event); + }; + /** + * Processes the event and logs an error in case of rejection + * @param event + * @param hint + * @param scope + */ + BaseClient.prototype._captureEvent = function (event, hint, scope) { + return this._processEvent(event, hint, scope).then(function (finalEvent) { + return finalEvent.event_id; + }, function (reason) { + utils_1.logger.error(reason); + return undefined; + }); + }; + /** + * Processes an event (either error or message) and sends it to Sentry. + * + * This also adds breadcrumbs and context information to the event. However, + * platform specific meta data (such as the User's IP address) must be added + * by the SDK implementor. + * + * + * @param event The event to send to Sentry. + * @param hint May contain additional information about the original exception. + * @param scope A scope containing event metadata. + * @returns A SyncPromise that resolves with the event or rejects in case event was/will not be send. + */ + BaseClient.prototype._processEvent = function (event, hint, scope) { + var _this = this; + // eslint-disable-next-line @typescript-eslint/unbound-method + var _a = this.getOptions(), beforeSend = _a.beforeSend, sampleRate = _a.sampleRate; + if (!this._isEnabled()) { + return utils_1.SyncPromise.reject(new utils_1.SentryError('SDK not enabled, will not send event.')); + } + var isTransaction = event.type === 'transaction'; + // 1.0 === 100% events are sent + // 0.0 === 0% events are sent + // Sampling for transaction happens somewhere else + if (!isTransaction && typeof sampleRate === 'number' && Math.random() > sampleRate) { + return utils_1.SyncPromise.reject(new utils_1.SentryError('This event has been sampled, will not send event.')); + } + return this._prepareEvent(event, scope, hint) + .then(function (prepared) { + if (prepared === null) { + throw new utils_1.SentryError('An event processor returned null, will not send event.'); + } + var isInternalException = hint && hint.data && hint.data.__sentry__ === true; + if (isInternalException || isTransaction || !beforeSend) { + return prepared; + } + var beforeSendResult = beforeSend(prepared, hint); + if (typeof beforeSendResult === 'undefined') { + throw new utils_1.SentryError('`beforeSend` method has to return `null` or a valid event.'); + } + else if (utils_1.isThenable(beforeSendResult)) { + return beforeSendResult.then(function (event) { return event; }, function (e) { + throw new utils_1.SentryError("beforeSend rejected with " + e); + }); + } + return beforeSendResult; + }) + .then(function (processedEvent) { + if (processedEvent === null) { + throw new utils_1.SentryError('`beforeSend` returned `null`, will not send event.'); + } + var session = scope && scope.getSession && scope.getSession(); + if (!isTransaction && session) { + _this._updateSessionFromEvent(session, processedEvent); + } + _this._sendEvent(processedEvent); + return processedEvent; + }) + .then(null, function (reason) { + if (reason instanceof utils_1.SentryError) { + throw reason; + } + _this.captureException(reason, { + data: { + __sentry__: true, + }, + originalException: reason, + }); + throw new utils_1.SentryError("Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.\nReason: " + reason); + }); + }; + /** + * Occupies the client with processing and event + */ + BaseClient.prototype._process = function (promise) { + var _this = this; + this._processing += 1; + promise.then(function (value) { + _this._processing -= 1; + return value; + }, function (reason) { + _this._processing -= 1; + return reason; + }); + }; + return BaseClient; +}()); +exports.BaseClient = BaseClient; +//# sourceMappingURL=baseclient.js.map + +/***/ }), -function endpointsToMethods(octokit, endpointsMap) { - const newMethods = {}; +/***/ 79212: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - for (const [scope, endpoints] of Object.entries(endpointsMap)) { - for (const [methodName, endpoint] of Object.entries(endpoints)) { - const [route, defaults, decorations] = endpoint; - const [method, url] = route.split(/ /); - const endpointDefaults = Object.assign({ - method, - url - }, defaults); +Object.defineProperty(exports, "__esModule", ({ value: true })); +var minimal_1 = __nccwpck_require__(88455); +exports.addBreadcrumb = minimal_1.addBreadcrumb; +exports.captureException = minimal_1.captureException; +exports.captureEvent = minimal_1.captureEvent; +exports.captureMessage = minimal_1.captureMessage; +exports.configureScope = minimal_1.configureScope; +exports.startTransaction = minimal_1.startTransaction; +exports.setContext = minimal_1.setContext; +exports.setExtra = minimal_1.setExtra; +exports.setExtras = minimal_1.setExtras; +exports.setTag = minimal_1.setTag; +exports.setTags = minimal_1.setTags; +exports.setUser = minimal_1.setUser; +exports.withScope = minimal_1.withScope; +var hub_1 = __nccwpck_require__(6393); +exports.addGlobalEventProcessor = hub_1.addGlobalEventProcessor; +exports.getCurrentHub = hub_1.getCurrentHub; +exports.getHubFromCarrier = hub_1.getHubFromCarrier; +exports.Hub = hub_1.Hub; +exports.makeMain = hub_1.makeMain; +exports.Scope = hub_1.Scope; +var api_1 = __nccwpck_require__(90785); +exports.API = api_1.API; +var baseclient_1 = __nccwpck_require__(25684); +exports.BaseClient = baseclient_1.BaseClient; +var basebackend_1 = __nccwpck_require__(25886); +exports.BaseBackend = basebackend_1.BaseBackend; +var request_1 = __nccwpck_require__(1553); +exports.eventToSentryRequest = request_1.eventToSentryRequest; +exports.sessionToSentryRequest = request_1.sessionToSentryRequest; +var sdk_1 = __nccwpck_require__(46406); +exports.initAndBind = sdk_1.initAndBind; +var noop_1 = __nccwpck_require__(68641); +exports.NoopTransport = noop_1.NoopTransport; +var Integrations = __nccwpck_require__(96727); +exports.Integrations = Integrations; +//# sourceMappingURL=index.js.map - if (!newMethods[scope]) { - newMethods[scope] = {}; - } +/***/ }), + +/***/ 58500: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __nccwpck_require__(4351); +var hub_1 = __nccwpck_require__(6393); +var utils_1 = __nccwpck_require__(1620); +exports.installedIntegrations = []; +/** Gets integration to install */ +function getIntegrationsToSetup(options) { + var defaultIntegrations = (options.defaultIntegrations && tslib_1.__spread(options.defaultIntegrations)) || []; + var userIntegrations = options.integrations; + var integrations = []; + if (Array.isArray(userIntegrations)) { + var userIntegrationsNames_1 = userIntegrations.map(function (i) { return i.name; }); + var pickedIntegrationsNames_1 = []; + // Leave only unique default integrations, that were not overridden with provided user integrations + defaultIntegrations.forEach(function (defaultIntegration) { + if (userIntegrationsNames_1.indexOf(defaultIntegration.name) === -1 && + pickedIntegrationsNames_1.indexOf(defaultIntegration.name) === -1) { + integrations.push(defaultIntegration); + pickedIntegrationsNames_1.push(defaultIntegration.name); + } + }); + // Don't add same user integration twice + userIntegrations.forEach(function (userIntegration) { + if (pickedIntegrationsNames_1.indexOf(userIntegration.name) === -1) { + integrations.push(userIntegration); + pickedIntegrationsNames_1.push(userIntegration.name); + } + }); + } + else if (typeof userIntegrations === 'function') { + integrations = userIntegrations(defaultIntegrations); + integrations = Array.isArray(integrations) ? integrations : [integrations]; + } + else { + integrations = tslib_1.__spread(defaultIntegrations); + } + // Make sure that if present, `Debug` integration will always run last + var integrationsNames = integrations.map(function (i) { return i.name; }); + var alwaysLastToRun = 'Debug'; + if (integrationsNames.indexOf(alwaysLastToRun) !== -1) { + integrations.push.apply(integrations, tslib_1.__spread(integrations.splice(integrationsNames.indexOf(alwaysLastToRun), 1))); + } + return integrations; +} +exports.getIntegrationsToSetup = getIntegrationsToSetup; +/** Setup given integration */ +function setupIntegration(integration) { + if (exports.installedIntegrations.indexOf(integration.name) !== -1) { + return; + } + integration.setupOnce(hub_1.addGlobalEventProcessor, hub_1.getCurrentHub); + exports.installedIntegrations.push(integration.name); + utils_1.logger.log("Integration installed: " + integration.name); +} +exports.setupIntegration = setupIntegration; +/** + * Given a list of integration instances this installs them all. When `withDefaults` is set to `true` then all default + * integrations are added unless they were already provided before. + * @param integrations array of integration instances + * @param withDefault should enable default integrations + */ +function setupIntegrations(options) { + var integrations = {}; + getIntegrationsToSetup(options).forEach(function (integration) { + integrations[integration.name] = integration; + setupIntegration(integration); + }); + return integrations; +} +exports.setupIntegrations = setupIntegrations; +//# sourceMappingURL=integration.js.map + +/***/ }), + +/***/ 87349: +/***/ ((__unused_webpack_module, exports) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); +var originalFunctionToString; +/** Patch toString calls to return proper name for wrapped functions */ +var FunctionToString = /** @class */ (function () { + function FunctionToString() { + /** + * @inheritDoc + */ + this.name = FunctionToString.id; + } + /** + * @inheritDoc + */ + FunctionToString.prototype.setupOnce = function () { + // eslint-disable-next-line @typescript-eslint/unbound-method + originalFunctionToString = Function.prototype.toString; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + Function.prototype.toString = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + var context = this.__sentry_original__ || this; + return originalFunctionToString.apply(context, args); + }; + }; + /** + * @inheritDoc + */ + FunctionToString.id = 'FunctionToString'; + return FunctionToString; +}()); +exports.FunctionToString = FunctionToString; +//# sourceMappingURL=functiontostring.js.map + +/***/ }), + +/***/ 54838: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __nccwpck_require__(4351); +var hub_1 = __nccwpck_require__(6393); +var utils_1 = __nccwpck_require__(1620); +// "Script error." is hard coded into browsers for errors that it can't read. +// this is the result of a script being pulled in from an external domain and CORS. +var DEFAULT_IGNORE_ERRORS = [/^Script error\.?$/, /^Javascript error: Script error\.? on line 0$/]; +/** Inbound filters configurable by the user */ +var InboundFilters = /** @class */ (function () { + function InboundFilters(_options) { + if (_options === void 0) { _options = {}; } + this._options = _options; + /** + * @inheritDoc + */ + this.name = InboundFilters.id; + } + /** + * @inheritDoc + */ + InboundFilters.prototype.setupOnce = function () { + hub_1.addGlobalEventProcessor(function (event) { + var hub = hub_1.getCurrentHub(); + if (!hub) { + return event; + } + var self = hub.getIntegration(InboundFilters); + if (self) { + var client = hub.getClient(); + var clientOptions = client ? client.getOptions() : {}; + var options = self._mergeOptions(clientOptions); + if (self._shouldDropEvent(event, options)) { + return null; + } + } + return event; + }); + }; + /** JSDoc */ + InboundFilters.prototype._shouldDropEvent = function (event, options) { + if (this._isSentryError(event, options)) { + utils_1.logger.warn("Event dropped due to being internal Sentry Error.\nEvent: " + utils_1.getEventDescription(event)); + return true; + } + if (this._isIgnoredError(event, options)) { + utils_1.logger.warn("Event dropped due to being matched by `ignoreErrors` option.\nEvent: " + utils_1.getEventDescription(event)); + return true; + } + if (this._isDeniedUrl(event, options)) { + utils_1.logger.warn("Event dropped due to being matched by `denyUrls` option.\nEvent: " + utils_1.getEventDescription(event) + ".\nUrl: " + this._getEventFilterUrl(event)); + return true; + } + if (!this._isAllowedUrl(event, options)) { + utils_1.logger.warn("Event dropped due to not being matched by `allowUrls` option.\nEvent: " + utils_1.getEventDescription(event) + ".\nUrl: " + this._getEventFilterUrl(event)); + return true; + } + return false; + }; + /** JSDoc */ + InboundFilters.prototype._isSentryError = function (event, options) { + if (!options.ignoreInternal) { + return false; + } + try { + return ((event && + event.exception && + event.exception.values && + event.exception.values[0] && + event.exception.values[0].type === 'SentryError') || + false); + } + catch (_oO) { + return false; + } + }; + /** JSDoc */ + InboundFilters.prototype._isIgnoredError = function (event, options) { + if (!options.ignoreErrors || !options.ignoreErrors.length) { + return false; + } + return this._getPossibleEventMessages(event).some(function (message) { + // Not sure why TypeScript complains here... + return options.ignoreErrors.some(function (pattern) { return utils_1.isMatchingPattern(message, pattern); }); + }); + }; + /** JSDoc */ + InboundFilters.prototype._isDeniedUrl = function (event, options) { + // TODO: Use Glob instead? + if (!options.denyUrls || !options.denyUrls.length) { + return false; + } + var url = this._getEventFilterUrl(event); + return !url ? false : options.denyUrls.some(function (pattern) { return utils_1.isMatchingPattern(url, pattern); }); + }; + /** JSDoc */ + InboundFilters.prototype._isAllowedUrl = function (event, options) { + // TODO: Use Glob instead? + if (!options.allowUrls || !options.allowUrls.length) { + return true; + } + var url = this._getEventFilterUrl(event); + return !url ? true : options.allowUrls.some(function (pattern) { return utils_1.isMatchingPattern(url, pattern); }); + }; + /** JSDoc */ + InboundFilters.prototype._mergeOptions = function (clientOptions) { + if (clientOptions === void 0) { clientOptions = {}; } + return { + allowUrls: tslib_1.__spread((this._options.whitelistUrls || []), (this._options.allowUrls || []), (clientOptions.whitelistUrls || []), (clientOptions.allowUrls || [])), + denyUrls: tslib_1.__spread((this._options.blacklistUrls || []), (this._options.denyUrls || []), (clientOptions.blacklistUrls || []), (clientOptions.denyUrls || [])), + ignoreErrors: tslib_1.__spread((this._options.ignoreErrors || []), (clientOptions.ignoreErrors || []), DEFAULT_IGNORE_ERRORS), + ignoreInternal: typeof this._options.ignoreInternal !== 'undefined' ? this._options.ignoreInternal : true, + }; + }; + /** JSDoc */ + InboundFilters.prototype._getPossibleEventMessages = function (event) { + if (event.message) { + return [event.message]; + } + if (event.exception) { + try { + var _a = (event.exception.values && event.exception.values[0]) || {}, _b = _a.type, type = _b === void 0 ? '' : _b, _c = _a.value, value = _c === void 0 ? '' : _c; + return ["" + value, type + ": " + value]; + } + catch (oO) { + utils_1.logger.error("Cannot extract message for event " + utils_1.getEventDescription(event)); + return []; + } + } + return []; + }; + /** JSDoc */ + InboundFilters.prototype._getEventFilterUrl = function (event) { + try { + if (event.stacktrace) { + var frames_1 = event.stacktrace.frames; + return (frames_1 && frames_1[frames_1.length - 1].filename) || null; + } + if (event.exception) { + var frames_2 = event.exception.values && event.exception.values[0].stacktrace && event.exception.values[0].stacktrace.frames; + return (frames_2 && frames_2[frames_2.length - 1].filename) || null; + } + return null; + } + catch (oO) { + utils_1.logger.error("Cannot extract url for event " + utils_1.getEventDescription(event)); + return null; + } + }; + /** + * @inheritDoc + */ + InboundFilters.id = 'InboundFilters'; + return InboundFilters; +}()); +exports.InboundFilters = InboundFilters; +//# sourceMappingURL=inboundfilters.js.map + +/***/ }), + +/***/ 96727: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); +var functiontostring_1 = __nccwpck_require__(87349); +exports.FunctionToString = functiontostring_1.FunctionToString; +var inboundfilters_1 = __nccwpck_require__(54838); +exports.InboundFilters = inboundfilters_1.InboundFilters; +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 1553: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __nccwpck_require__(4351); +/** Creates a SentryRequest from an event. */ +function sessionToSentryRequest(session, api) { + var envelopeHeaders = JSON.stringify({ + sent_at: new Date().toISOString(), + }); + var itemHeaders = JSON.stringify({ + type: 'session', + }); + return { + body: envelopeHeaders + "\n" + itemHeaders + "\n" + JSON.stringify(session), + type: 'session', + url: api.getEnvelopeEndpointWithUrlEncodedAuth(), + }; +} +exports.sessionToSentryRequest = sessionToSentryRequest; +/** Creates a SentryRequest from an event. */ +function eventToSentryRequest(event, api) { + // since JS has no Object.prototype.pop() + var _a = event.tags || {}, samplingMethod = _a.__sentry_samplingMethod, sampleRate = _a.__sentry_sampleRate, otherTags = tslib_1.__rest(_a, ["__sentry_samplingMethod", "__sentry_sampleRate"]); + event.tags = otherTags; + var useEnvelope = event.type === 'transaction'; + var req = { + body: JSON.stringify(event), + type: event.type || 'event', + url: useEnvelope ? api.getEnvelopeEndpointWithUrlEncodedAuth() : api.getStoreEndpointWithUrlEncodedAuth(), + }; + // https://develop.sentry.dev/sdk/envelopes/ + // Since we don't need to manipulate envelopes nor store them, there is no + // exported concept of an Envelope with operations including serialization and + // deserialization. Instead, we only implement a minimal subset of the spec to + // serialize events inline here. + if (useEnvelope) { + var envelopeHeaders = JSON.stringify({ + event_id: event.event_id, + sent_at: new Date().toISOString(), + }); + var itemHeaders = JSON.stringify({ + type: event.type, + // TODO: Right now, sampleRate may or may not be defined (it won't be in the cases of inheritance and + // explicitly-set sampling decisions). Are we good with that? + sample_rates: [{ id: samplingMethod, rate: sampleRate }], + }); + // The trailing newline is optional. We intentionally don't send it to avoid + // sending unnecessary bytes. + // + // const envelope = `${envelopeHeaders}\n${itemHeaders}\n${req.body}\n`; + var envelope = envelopeHeaders + "\n" + itemHeaders + "\n" + req.body; + req.body = envelope; + } + return req; +} +exports.eventToSentryRequest = eventToSentryRequest; +//# sourceMappingURL=request.js.map - const scopeMethods = newMethods[scope]; +/***/ }), - if (decorations) { - scopeMethods[methodName] = decorate(octokit, scope, methodName, endpointDefaults, decorations); - continue; - } +/***/ 46406: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - scopeMethods[methodName] = octokit.request.defaults(endpointDefaults); +Object.defineProperty(exports, "__esModule", ({ value: true })); +var hub_1 = __nccwpck_require__(6393); +var utils_1 = __nccwpck_require__(1620); +/** + * Internal function to create a new SDK client instance. The client is + * installed and then bound to the current scope. + * + * @param clientClass The client class to instantiate. + * @param options Options to pass to the client. + */ +function initAndBind(clientClass, options) { + if (options.debug === true) { + utils_1.logger.enable(); } - } - - return newMethods; + var hub = hub_1.getCurrentHub(); + var client = new clientClass(options); + hub.bindClient(client); } +exports.initAndBind = initAndBind; +//# sourceMappingURL=sdk.js.map -function decorate(octokit, scope, methodName, defaults, decorations) { - const requestWithDefaults = octokit.request.defaults(defaults); - /* istanbul ignore next */ +/***/ }), - function withDecorations(...args) { - // @ts-ignore https://github.com/microsoft/TypeScript/issues/25488 - let options = requestWithDefaults.endpoint.merge(...args); // There are currently no other decorations than `.mapToData` +/***/ 68641: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (decorations.mapToData) { - options = Object.assign({}, options, { - data: options[decorations.mapToData], - [decorations.mapToData]: undefined - }); - return requestWithDefaults(options); +Object.defineProperty(exports, "__esModule", ({ value: true })); +var types_1 = __nccwpck_require__(83789); +var utils_1 = __nccwpck_require__(1620); +/** Noop transport */ +var NoopTransport = /** @class */ (function () { + function NoopTransport() { } + /** + * @inheritDoc + */ + NoopTransport.prototype.sendEvent = function (_) { + return utils_1.SyncPromise.resolve({ + reason: "NoopTransport: Event has been skipped because no Dsn is configured.", + status: types_1.Status.Skipped, + }); + }; + /** + * @inheritDoc + */ + NoopTransport.prototype.close = function (_) { + return utils_1.SyncPromise.resolve(true); + }; + return NoopTransport; +}()); +exports.NoopTransport = NoopTransport; +//# sourceMappingURL=noop.js.map - if (decorations.renamed) { - const [newScope, newMethodName] = decorations.renamed; - octokit.log.warn(`octokit.${scope}.${methodName}() has been renamed to octokit.${newScope}.${newMethodName}()`); +/***/ }), + +/***/ 53536: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __nccwpck_require__(4351); +var utils_1 = __nccwpck_require__(1620); +var scope_1 = __nccwpck_require__(4213); +var session_1 = __nccwpck_require__(12474); +/** + * API compatibility version of this hub. + * + * WARNING: This number should only be increased when the global interface + * changes and new methods are introduced. + * + * @hidden + */ +exports.API_VERSION = 3; +/** + * Default maximum number of breadcrumbs added to an event. Can be overwritten + * with {@link Options.maxBreadcrumbs}. + */ +var DEFAULT_BREADCRUMBS = 100; +/** + * Absolute maximum number of breadcrumbs added to an event. The + * `maxBreadcrumbs` option cannot be higher than this value. + */ +var MAX_BREADCRUMBS = 100; +/** + * @inheritDoc + */ +var Hub = /** @class */ (function () { + /** + * Creates a new instance of the hub, will push one {@link Layer} into the + * internal stack on creation. + * + * @param client bound to the hub. + * @param scope bound to the hub. + * @param version number, higher number means higher priority. + */ + function Hub(client, scope, _version) { + if (scope === void 0) { scope = new scope_1.Scope(); } + if (_version === void 0) { _version = exports.API_VERSION; } + this._version = _version; + /** Is a {@link Layer}[] containing the client and scope */ + this._stack = [{}]; + this.getStackTop().scope = scope; + this.bindClient(client); + } + /** + * @inheritDoc + */ + Hub.prototype.isOlderThan = function (version) { + return this._version < version; + }; + /** + * @inheritDoc + */ + Hub.prototype.bindClient = function (client) { + var top = this.getStackTop(); + top.client = client; + if (client && client.setupIntegrations) { + client.setupIntegrations(); + } + }; + /** + * @inheritDoc + */ + Hub.prototype.pushScope = function () { + // We want to clone the content of prev scope + var scope = scope_1.Scope.clone(this.getScope()); + this.getStack().push({ + client: this.getClient(), + scope: scope, + }); + return scope; + }; + /** + * @inheritDoc + */ + Hub.prototype.popScope = function () { + if (this.getStack().length <= 1) + return false; + return !!this.getStack().pop(); + }; + /** + * @inheritDoc + */ + Hub.prototype.withScope = function (callback) { + var scope = this.pushScope(); + try { + callback(scope); + } + finally { + this.popScope(); + } + }; + /** + * @inheritDoc + */ + Hub.prototype.getClient = function () { + return this.getStackTop().client; + }; + /** Returns the scope of the top stack. */ + Hub.prototype.getScope = function () { + return this.getStackTop().scope; + }; + /** Returns the scope stack for domains or the process. */ + Hub.prototype.getStack = function () { + return this._stack; + }; + /** Returns the topmost scope layer in the order domain > local > process. */ + Hub.prototype.getStackTop = function () { + return this._stack[this._stack.length - 1]; + }; + /** + * @inheritDoc + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types + Hub.prototype.captureException = function (exception, hint) { + var eventId = (this._lastEventId = utils_1.uuid4()); + var finalHint = hint; + // If there's no explicit hint provided, mimick the same thing that would happen + // in the minimal itself to create a consistent behavior. + // We don't do this in the client, as it's the lowest level API, and doing this, + // would prevent user from having full control over direct calls. + if (!hint) { + var syntheticException = void 0; + try { + throw new Error('Sentry syntheticException'); + } + catch (exception) { + syntheticException = exception; + } + finalHint = { + originalException: exception, + syntheticException: syntheticException, + }; + } + this._invokeClient('captureException', exception, tslib_1.__assign(tslib_1.__assign({}, finalHint), { event_id: eventId })); + return eventId; + }; + /** + * @inheritDoc + */ + Hub.prototype.captureMessage = function (message, level, hint) { + var eventId = (this._lastEventId = utils_1.uuid4()); + var finalHint = hint; + // If there's no explicit hint provided, mimick the same thing that would happen + // in the minimal itself to create a consistent behavior. + // We don't do this in the client, as it's the lowest level API, and doing this, + // would prevent user from having full control over direct calls. + if (!hint) { + var syntheticException = void 0; + try { + throw new Error(message); + } + catch (exception) { + syntheticException = exception; + } + finalHint = { + originalException: message, + syntheticException: syntheticException, + }; + } + this._invokeClient('captureMessage', message, level, tslib_1.__assign(tslib_1.__assign({}, finalHint), { event_id: eventId })); + return eventId; + }; + /** + * @inheritDoc + */ + Hub.prototype.captureEvent = function (event, hint) { + var eventId = (this._lastEventId = utils_1.uuid4()); + this._invokeClient('captureEvent', event, tslib_1.__assign(tslib_1.__assign({}, hint), { event_id: eventId })); + return eventId; + }; + /** + * @inheritDoc + */ + Hub.prototype.lastEventId = function () { + return this._lastEventId; + }; + /** + * @inheritDoc + */ + Hub.prototype.addBreadcrumb = function (breadcrumb, hint) { + var _a = this.getStackTop(), scope = _a.scope, client = _a.client; + if (!scope || !client) + return; + // eslint-disable-next-line @typescript-eslint/unbound-method + var _b = (client.getOptions && client.getOptions()) || {}, _c = _b.beforeBreadcrumb, beforeBreadcrumb = _c === void 0 ? null : _c, _d = _b.maxBreadcrumbs, maxBreadcrumbs = _d === void 0 ? DEFAULT_BREADCRUMBS : _d; + if (maxBreadcrumbs <= 0) + return; + var timestamp = utils_1.dateTimestampInSeconds(); + var mergedBreadcrumb = tslib_1.__assign({ timestamp: timestamp }, breadcrumb); + var finalBreadcrumb = beforeBreadcrumb + ? utils_1.consoleSandbox(function () { return beforeBreadcrumb(mergedBreadcrumb, hint); }) + : mergedBreadcrumb; + if (finalBreadcrumb === null) + return; + scope.addBreadcrumb(finalBreadcrumb, Math.min(maxBreadcrumbs, MAX_BREADCRUMBS)); + }; + /** + * @inheritDoc + */ + Hub.prototype.setUser = function (user) { + var scope = this.getScope(); + if (scope) + scope.setUser(user); + }; + /** + * @inheritDoc + */ + Hub.prototype.setTags = function (tags) { + var scope = this.getScope(); + if (scope) + scope.setTags(tags); + }; + /** + * @inheritDoc + */ + Hub.prototype.setExtras = function (extras) { + var scope = this.getScope(); + if (scope) + scope.setExtras(extras); + }; + /** + * @inheritDoc + */ + Hub.prototype.setTag = function (key, value) { + var scope = this.getScope(); + if (scope) + scope.setTag(key, value); + }; + /** + * @inheritDoc + */ + Hub.prototype.setExtra = function (key, extra) { + var scope = this.getScope(); + if (scope) + scope.setExtra(key, extra); + }; + /** + * @inheritDoc + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + Hub.prototype.setContext = function (name, context) { + var scope = this.getScope(); + if (scope) + scope.setContext(name, context); + }; + /** + * @inheritDoc + */ + Hub.prototype.configureScope = function (callback) { + var _a = this.getStackTop(), scope = _a.scope, client = _a.client; + if (scope && client) { + callback(scope); + } + }; + /** + * @inheritDoc + */ + Hub.prototype.run = function (callback) { + var oldHub = makeMain(this); + try { + callback(this); + } + finally { + makeMain(oldHub); + } + }; + /** + * @inheritDoc + */ + Hub.prototype.getIntegration = function (integration) { + var client = this.getClient(); + if (!client) + return null; + try { + return client.getIntegration(integration); + } + catch (_oO) { + utils_1.logger.warn("Cannot retrieve integration " + integration.id + " from the current Hub"); + return null; + } + }; + /** + * @inheritDoc + */ + Hub.prototype.startSpan = function (context) { + return this._callExtensionMethod('startSpan', context); + }; + /** + * @inheritDoc + */ + Hub.prototype.startTransaction = function (context, customSamplingContext) { + return this._callExtensionMethod('startTransaction', context, customSamplingContext); + }; + /** + * @inheritDoc + */ + Hub.prototype.traceHeaders = function () { + return this._callExtensionMethod('traceHeaders'); + }; + /** + * @inheritDoc + */ + Hub.prototype.startSession = function (context) { + // End existing session if there's one + this.endSession(); + var _a = this.getStackTop(), scope = _a.scope, client = _a.client; + var _b = (client && client.getOptions()) || {}, release = _b.release, environment = _b.environment; + var session = new session_1.Session(tslib_1.__assign(tslib_1.__assign({ release: release, + environment: environment }, (scope && { user: scope.getUser() })), context)); + if (scope) { + scope.setSession(session); + } + return session; + }; + /** + * @inheritDoc + */ + Hub.prototype.endSession = function () { + var _a = this.getStackTop(), scope = _a.scope, client = _a.client; + if (!scope) + return; + var session = scope.getSession && scope.getSession(); + if (session) { + session.close(); + if (client && client.captureSession) { + client.captureSession(session); + } + scope.setSession(); + } + }; + /** + * Internal helper function to call a method on the top client if it exists. + * + * @param method The method to call on the client. + * @param args Arguments to pass to the client function. + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + Hub.prototype._invokeClient = function (method) { + var _a; + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + var _b = this.getStackTop(), scope = _b.scope, client = _b.client; + if (client && client[method]) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any + (_a = client)[method].apply(_a, tslib_1.__spread(args, [scope])); + } + }; + /** + * Calls global extension method and binding current instance to the function call + */ + // @ts-ignore Function lacks ending return statement and return type does not include 'undefined'. ts(2366) + // eslint-disable-next-line @typescript-eslint/no-explicit-any + Hub.prototype._callExtensionMethod = function (method) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + var carrier = getMainCarrier(); + var sentry = carrier.__SENTRY__; + if (sentry && sentry.extensions && typeof sentry.extensions[method] === 'function') { + return sentry.extensions[method].apply(this, args); + } + utils_1.logger.warn("Extension method " + method + " couldn't be found, doing nothing."); + }; + return Hub; +}()); +exports.Hub = Hub; +/** Returns the global shim registry. */ +function getMainCarrier() { + var carrier = utils_1.getGlobalObject(); + carrier.__SENTRY__ = carrier.__SENTRY__ || { + extensions: {}, + hub: undefined, + }; + return carrier; +} +exports.getMainCarrier = getMainCarrier; +/** + * Replaces the current main hub with the passed one on the global object + * + * @returns The old replaced hub + */ +function makeMain(hub) { + var registry = getMainCarrier(); + var oldHub = getHubFromCarrier(registry); + setHubOnCarrier(registry, hub); + return oldHub; +} +exports.makeMain = makeMain; +/** + * Returns the default hub instance. + * + * If a hub is already registered in the global carrier but this module + * contains a more recent version, it replaces the registered version. + * Otherwise, the currently registered hub will be returned. + */ +function getCurrentHub() { + // Get main carrier (global for every environment) + var registry = getMainCarrier(); + // If there's no hub, or its an old API, assign a new one + if (!hasHubOnCarrier(registry) || getHubFromCarrier(registry).isOlderThan(exports.API_VERSION)) { + setHubOnCarrier(registry, new Hub()); + } + // Prefer domains over global if they are there (applicable only to Node environment) + if (utils_1.isNodeEnv()) { + return getHubFromActiveDomain(registry); + } + // Return hub that lives on a global object + return getHubFromCarrier(registry); +} +exports.getCurrentHub = getCurrentHub; +/** + * Returns the active domain, if one exists + * + * @returns The domain, or undefined if there is no active domain + */ +function getActiveDomain() { + var sentry = getMainCarrier().__SENTRY__; + return sentry && sentry.extensions && sentry.extensions.domain && sentry.extensions.domain.active; +} +exports.getActiveDomain = getActiveDomain; +/** + * Try to read the hub from an active domain, and fallback to the registry if one doesn't exist + * @returns discovered hub + */ +function getHubFromActiveDomain(registry) { + try { + var activeDomain = getActiveDomain(); + // If there's no active domain, just return global hub + if (!activeDomain) { + return getHubFromCarrier(registry); + } + // If there's no hub on current domain, or it's an old API, assign a new one + if (!hasHubOnCarrier(activeDomain) || getHubFromCarrier(activeDomain).isOlderThan(exports.API_VERSION)) { + var registryHubTopStack = getHubFromCarrier(registry).getStackTop(); + setHubOnCarrier(activeDomain, new Hub(registryHubTopStack.client, scope_1.Scope.clone(registryHubTopStack.scope))); + } + // Return hub that lives on a domain + return getHubFromCarrier(activeDomain); } - - if (decorations.deprecated) { - octokit.log.warn(decorations.deprecated); + catch (_Oo) { + // Return hub that lives on a global object + return getHubFromCarrier(registry); } - - if (decorations.renamedParameters) { - // @ts-ignore https://github.com/microsoft/TypeScript/issues/25488 - const options = requestWithDefaults.endpoint.merge(...args); - - for (const [name, alias] of Object.entries(decorations.renamedParameters)) { - if (name in options) { - octokit.log.warn(`"${name}" parameter is deprecated for "octokit.${scope}.${methodName}()". Use "${alias}" instead`); - - if (!(alias in options)) { - options[alias] = options[name]; - } - - delete options[name]; - } - } - - return requestWithDefaults(options); - } // @ts-ignore https://github.com/microsoft/TypeScript/issues/25488 - - - return requestWithDefaults(...args); - } - - return Object.assign(withDecorations, requestWithDefaults); } - -function restEndpointMethods(octokit) { - const api = endpointsToMethods(octokit, Endpoints); - return { - rest: api - }; +/** + * This will tell whether a carrier has a hub on it or not + * @param carrier object + */ +function hasHubOnCarrier(carrier) { + return !!(carrier && carrier.__SENTRY__ && carrier.__SENTRY__.hub); } -restEndpointMethods.VERSION = VERSION; -function legacyRestEndpointMethods(octokit) { - const api = endpointsToMethods(octokit, Endpoints); - return _objectSpread2(_objectSpread2({}, api), {}, { - rest: api - }); +/** + * This will create a new {@link Hub} and add to the passed object on + * __SENTRY__.hub. + * @param carrier object + * @hidden + */ +function getHubFromCarrier(carrier) { + if (carrier && carrier.__SENTRY__ && carrier.__SENTRY__.hub) + return carrier.__SENTRY__.hub; + carrier.__SENTRY__ = carrier.__SENTRY__ || {}; + carrier.__SENTRY__.hub = new Hub(); + return carrier.__SENTRY__.hub; } -legacyRestEndpointMethods.VERSION = VERSION; - -exports.legacyRestEndpointMethods = legacyRestEndpointMethods; -exports.restEndpointMethods = restEndpointMethods; -//# sourceMappingURL=index.js.map - +exports.getHubFromCarrier = getHubFromCarrier; +/** + * This will set passed {@link Hub} on the passed object's __SENTRY__.hub attribute + * @param carrier object + * @param hub Hub + */ +function setHubOnCarrier(carrier, hub) { + if (!carrier) + return false; + carrier.__SENTRY__ = carrier.__SENTRY__ || {}; + carrier.__SENTRY__.hub = hub; + return true; +} +exports.setHubOnCarrier = setHubOnCarrier; +//# sourceMappingURL=hub.js.map /***/ }), -/***/ 86298: +/***/ 6393: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; - - Object.defineProperty(exports, "__esModule", ({ value: true })); - -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - -var Bottleneck = _interopDefault(__nccwpck_require__(11174)); - -// @ts-ignore -async function errorRequest(octokit, state, error, options) { - if (!error.request || !error.request.request) { - // address https://github.com/octokit/plugin-retry.js/issues/8 - throw error; - } // retry all >= 400 && not doNotRetry - - - if (error.status >= 400 && !state.doNotRetry.includes(error.status)) { - const retries = options.request.retries != null ? options.request.retries : state.retries; - const retryAfter = Math.pow((options.request.retryCount || 0) + 1, 2); - throw octokit.retry.retryRequest(error, retries, retryAfter); - } // Maybe eventually there will be more cases here - - - throw error; -} - -// @ts-ignore - -async function wrapRequest(state, request, options) { - const limiter = new Bottleneck(); // @ts-ignore - - limiter.on("failed", function (error, info) { - const maxRetries = ~~error.request.request.retries; - const after = ~~error.request.request.retryAfter; - options.request.retryCount = info.retryCount + 1; - - if (maxRetries > info.retryCount) { - // Returning a number instructs the limiter to retry - // the request after that number of milliseconds have passed - return after * state.retryAfterBaseValue; - } - }); - return limiter.schedule(request, options); -} - -const VERSION = "3.0.6"; -function retry(octokit, octokitOptions = {}) { - const state = Object.assign({ - enabled: true, - retryAfterBaseValue: 1000, - doNotRetry: [400, 401, 403, 404, 422], - retries: 3 - }, octokitOptions.retry); - octokit.retry = { - retryRequest: (error, retries, retryAfter) => { - error.request.request = Object.assign({}, error.request.request, { - retries: retries, - retryAfter: retryAfter - }); - return error; - } - }; - - if (!state.enabled) { - return; - } - - octokit.hook.error("request", errorRequest.bind(null, octokit, state)); - octokit.hook.wrap("request", wrapRequest.bind(null, state)); -} -retry.VERSION = VERSION; - -exports.VERSION = VERSION; -exports.retry = retry; +var scope_1 = __nccwpck_require__(4213); +exports.addGlobalEventProcessor = scope_1.addGlobalEventProcessor; +exports.Scope = scope_1.Scope; +var session_1 = __nccwpck_require__(12474); +exports.Session = session_1.Session; +var hub_1 = __nccwpck_require__(53536); +exports.getActiveDomain = hub_1.getActiveDomain; +exports.getCurrentHub = hub_1.getCurrentHub; +exports.getHubFromCarrier = hub_1.getHubFromCarrier; +exports.getMainCarrier = hub_1.getMainCarrier; +exports.Hub = hub_1.Hub; +exports.makeMain = hub_1.makeMain; +exports.setHubOnCarrier = hub_1.setHubOnCarrier; //# sourceMappingURL=index.js.map - /***/ }), -/***/ 9968: +/***/ 4213: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; - - Object.defineProperty(exports, "__esModule", ({ value: true })); - -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - -var BottleneckLight = _interopDefault(__nccwpck_require__(11174)); - -function _defineProperty(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; - } - - return obj; -} - -function ownKeys(object, enumerableOnly) { - var keys = Object.keys(object); - - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(object); - if (enumerableOnly) symbols = symbols.filter(function (sym) { - return Object.getOwnPropertyDescriptor(object, sym).enumerable; - }); - keys.push.apply(keys, symbols); - } - - return keys; -} - -function _objectSpread2(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? arguments[i] : {}; - - if (i % 2) { - ownKeys(Object(source), true).forEach(function (key) { - _defineProperty(target, key, source[key]); - }); - } else if (Object.getOwnPropertyDescriptors) { - Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); - } else { - ownKeys(Object(source)).forEach(function (key) { - Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); - }); - } - } - - return target; -} - -const VERSION = "3.3.4"; - -const noop = () => Promise.resolve(); // @ts-ignore - - -function wrapRequest(state, request, options) { - return state.retryLimiter.schedule(doRequest, state, request, options); -} // @ts-ignore - -async function doRequest(state, request, options) { - const isWrite = options.method !== "GET" && options.method !== "HEAD"; - const isSearch = options.method === "GET" && options.url.startsWith("/search/"); - const isGraphQL = options.url.startsWith("/graphql"); - const retryCount = ~~options.request.retryCount; - const jobOptions = retryCount > 0 ? { - priority: 0, - weight: 0 - } : {}; - - if (state.clustering) { - // Remove a job from Redis if it has not completed or failed within 60s - // Examples: Node process terminated, client disconnected, etc. - // @ts-ignore - jobOptions.expiration = 1000 * 60; - } // Guarantee at least 1000ms between writes - // GraphQL can also trigger writes - - - if (isWrite || isGraphQL) { - await state.write.key(state.id).schedule(jobOptions, noop); - } // Guarantee at least 3000ms between requests that trigger notifications - - - if (isWrite && state.triggersNotification(options.url)) { - await state.notifications.key(state.id).schedule(jobOptions, noop); - } // Guarantee at least 2000ms between search requests - - - if (isSearch) { - await state.search.key(state.id).schedule(jobOptions, noop); - } - - const req = state.global.key(state.id).schedule(jobOptions, request, options); - - if (isGraphQL) { - const res = await req; - - if (res.data.errors != null && // @ts-ignore - res.data.errors.some(error => error.type === "RATE_LIMITED")) { - const error = Object.assign(new Error("GraphQL Rate Limit Exceeded"), { - headers: res.headers, - data: res.data - }); - throw error; +var tslib_1 = __nccwpck_require__(4351); +var utils_1 = __nccwpck_require__(1620); +/** + * Holds additional event information. {@link Scope.applyToEvent} will be + * called by the client before an event will be sent. + */ +var Scope = /** @class */ (function () { + function Scope() { + /** Flag if notifiying is happening. */ + this._notifyingListeners = false; + /** Callback for client to receive scope changes. */ + this._scopeListeners = []; + /** Callback list that will be called after {@link applyToEvent}. */ + this._eventProcessors = []; + /** Array of breadcrumbs. */ + this._breadcrumbs = []; + /** User */ + this._user = {}; + /** Tags */ + this._tags = {}; + /** Extra */ + this._extra = {}; + /** Contexts */ + this._contexts = {}; } - } - - return req; -} - -var triggersNotificationPaths = ["/orgs/{org}/invitations", "/orgs/{org}/teams/{team_slug}/discussions", "/orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments", "/repos/{owner}/{repo}/collaborators/{username}", "/repos/{owner}/{repo}/commits/{commit_sha}/comments", "/repos/{owner}/{repo}/issues", "/repos/{owner}/{repo}/issues/{issue_number}/comments", "/repos/{owner}/{repo}/pulls", "/repos/{owner}/{repo}/pulls/{pull_number}/comments", "/repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies", "/repos/{owner}/{repo}/pulls/{pull_number}/merge", "/repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers", "/repos/{owner}/{repo}/pulls/{pull_number}/reviews", "/repos/{owner}/{repo}/releases", "/teams/{team_id}/discussions", "/teams/{team_id}/discussions/{discussion_number}/comments"]; - -// @ts-ignore -function routeMatcher(paths) { - // EXAMPLE. For the following paths: - - /* [ - "/orgs/:org/invitations", - "/repos/:owner/:repo/collaborators/:username" - ] */ - // @ts-ignore - const regexes = paths.map(path => path.split("/") // @ts-ignore - .map(c => c.startsWith("{") ? "(?:.+?)" : c).join("/")); // 'regexes' would contain: - - /* [ - '/orgs/(?:.+?)/invitations', - '/repos/(?:.+?)/(?:.+?)/collaborators/(?:.+?)' - ] */ - // @ts-ignore - - const regex = `^(?:${regexes.map(r => `(?:${r})`).join("|")})[^/]*$`; // 'regex' would contain: - - /* - ^(?:(?:\/orgs\/(?:.+?)\/invitations)|(?:\/repos\/(?:.+?)\/(?:.+?)\/collaborators\/(?:.+?)))[^\/]*$ - It may look scary, but paste it into https://www.debuggex.com/ - and it will make a lot more sense! - */ - - return new RegExp(regex, "i"); + /** + * Inherit values from the parent scope. + * @param scope to clone. + */ + Scope.clone = function (scope) { + var newScope = new Scope(); + if (scope) { + newScope._breadcrumbs = tslib_1.__spread(scope._breadcrumbs); + newScope._tags = tslib_1.__assign({}, scope._tags); + newScope._extra = tslib_1.__assign({}, scope._extra); + newScope._contexts = tslib_1.__assign({}, scope._contexts); + newScope._user = scope._user; + newScope._level = scope._level; + newScope._span = scope._span; + newScope._session = scope._session; + newScope._transactionName = scope._transactionName; + newScope._fingerprint = scope._fingerprint; + newScope._eventProcessors = tslib_1.__spread(scope._eventProcessors); + } + return newScope; + }; + /** + * Add internal on change listener. Used for sub SDKs that need to store the scope. + * @hidden + */ + Scope.prototype.addScopeListener = function (callback) { + this._scopeListeners.push(callback); + }; + /** + * @inheritDoc + */ + Scope.prototype.addEventProcessor = function (callback) { + this._eventProcessors.push(callback); + return this; + }; + /** + * @inheritDoc + */ + Scope.prototype.setUser = function (user) { + this._user = user || {}; + if (this._session) { + this._session.update({ user: user }); + } + this._notifyScopeListeners(); + return this; + }; + /** + * @inheritDoc + */ + Scope.prototype.getUser = function () { + return this._user; + }; + /** + * @inheritDoc + */ + Scope.prototype.setTags = function (tags) { + this._tags = tslib_1.__assign(tslib_1.__assign({}, this._tags), tags); + this._notifyScopeListeners(); + return this; + }; + /** + * @inheritDoc + */ + Scope.prototype.setTag = function (key, value) { + var _a; + this._tags = tslib_1.__assign(tslib_1.__assign({}, this._tags), (_a = {}, _a[key] = value, _a)); + this._notifyScopeListeners(); + return this; + }; + /** + * @inheritDoc + */ + Scope.prototype.setExtras = function (extras) { + this._extra = tslib_1.__assign(tslib_1.__assign({}, this._extra), extras); + this._notifyScopeListeners(); + return this; + }; + /** + * @inheritDoc + */ + Scope.prototype.setExtra = function (key, extra) { + var _a; + this._extra = tslib_1.__assign(tslib_1.__assign({}, this._extra), (_a = {}, _a[key] = extra, _a)); + this._notifyScopeListeners(); + return this; + }; + /** + * @inheritDoc + */ + Scope.prototype.setFingerprint = function (fingerprint) { + this._fingerprint = fingerprint; + this._notifyScopeListeners(); + return this; + }; + /** + * @inheritDoc + */ + Scope.prototype.setLevel = function (level) { + this._level = level; + this._notifyScopeListeners(); + return this; + }; + /** + * @inheritDoc + */ + Scope.prototype.setTransactionName = function (name) { + this._transactionName = name; + this._notifyScopeListeners(); + return this; + }; + /** + * Can be removed in major version. + * @deprecated in favor of {@link this.setTransactionName} + */ + Scope.prototype.setTransaction = function (name) { + return this.setTransactionName(name); + }; + /** + * @inheritDoc + */ + Scope.prototype.setContext = function (key, context) { + var _a; + if (context === null) { + // eslint-disable-next-line @typescript-eslint/no-dynamic-delete + delete this._contexts[key]; + } + else { + this._contexts = tslib_1.__assign(tslib_1.__assign({}, this._contexts), (_a = {}, _a[key] = context, _a)); + } + this._notifyScopeListeners(); + return this; + }; + /** + * @inheritDoc + */ + Scope.prototype.setSpan = function (span) { + this._span = span; + this._notifyScopeListeners(); + return this; + }; + /** + * @inheritDoc + */ + Scope.prototype.getSpan = function () { + return this._span; + }; + /** + * @inheritDoc + */ + Scope.prototype.getTransaction = function () { + var _a, _b, _c, _d; + // often, this span will be a transaction, but it's not guaranteed to be + var span = this.getSpan(); + // try it the new way first + if ((_a = span) === null || _a === void 0 ? void 0 : _a.transaction) { + return (_b = span) === null || _b === void 0 ? void 0 : _b.transaction; + } + // fallback to the old way (known bug: this only finds transactions with sampled = true) + if ((_d = (_c = span) === null || _c === void 0 ? void 0 : _c.spanRecorder) === null || _d === void 0 ? void 0 : _d.spans[0]) { + return span.spanRecorder.spans[0]; + } + // neither way found a transaction + return undefined; + }; + /** + * @inheritDoc + */ + Scope.prototype.setSession = function (session) { + if (!session) { + delete this._session; + } + else { + this._session = session; + } + this._notifyScopeListeners(); + return this; + }; + /** + * @inheritDoc + */ + Scope.prototype.getSession = function () { + return this._session; + }; + /** + * @inheritDoc + */ + Scope.prototype.update = function (captureContext) { + if (!captureContext) { + return this; + } + if (typeof captureContext === 'function') { + var updatedScope = captureContext(this); + return updatedScope instanceof Scope ? updatedScope : this; + } + if (captureContext instanceof Scope) { + this._tags = tslib_1.__assign(tslib_1.__assign({}, this._tags), captureContext._tags); + this._extra = tslib_1.__assign(tslib_1.__assign({}, this._extra), captureContext._extra); + this._contexts = tslib_1.__assign(tslib_1.__assign({}, this._contexts), captureContext._contexts); + if (captureContext._user && Object.keys(captureContext._user).length) { + this._user = captureContext._user; + } + if (captureContext._level) { + this._level = captureContext._level; + } + if (captureContext._fingerprint) { + this._fingerprint = captureContext._fingerprint; + } + } + else if (utils_1.isPlainObject(captureContext)) { + // eslint-disable-next-line no-param-reassign + captureContext = captureContext; + this._tags = tslib_1.__assign(tslib_1.__assign({}, this._tags), captureContext.tags); + this._extra = tslib_1.__assign(tslib_1.__assign({}, this._extra), captureContext.extra); + this._contexts = tslib_1.__assign(tslib_1.__assign({}, this._contexts), captureContext.contexts); + if (captureContext.user) { + this._user = captureContext.user; + } + if (captureContext.level) { + this._level = captureContext.level; + } + if (captureContext.fingerprint) { + this._fingerprint = captureContext.fingerprint; + } + } + return this; + }; + /** + * @inheritDoc + */ + Scope.prototype.clear = function () { + this._breadcrumbs = []; + this._tags = {}; + this._extra = {}; + this._user = {}; + this._contexts = {}; + this._level = undefined; + this._transactionName = undefined; + this._fingerprint = undefined; + this._span = undefined; + this._session = undefined; + this._notifyScopeListeners(); + return this; + }; + /** + * @inheritDoc + */ + Scope.prototype.addBreadcrumb = function (breadcrumb, maxBreadcrumbs) { + var mergedBreadcrumb = tslib_1.__assign({ timestamp: utils_1.dateTimestampInSeconds() }, breadcrumb); + this._breadcrumbs = + maxBreadcrumbs !== undefined && maxBreadcrumbs >= 0 + ? tslib_1.__spread(this._breadcrumbs, [mergedBreadcrumb]).slice(-maxBreadcrumbs) + : tslib_1.__spread(this._breadcrumbs, [mergedBreadcrumb]); + this._notifyScopeListeners(); + return this; + }; + /** + * @inheritDoc + */ + Scope.prototype.clearBreadcrumbs = function () { + this._breadcrumbs = []; + this._notifyScopeListeners(); + return this; + }; + /** + * Applies the current context and fingerprint to the event. + * Note that breadcrumbs will be added by the client. + * Also if the event has already breadcrumbs on it, we do not merge them. + * @param event Event + * @param hint May contain additional informartion about the original exception. + * @hidden + */ + Scope.prototype.applyToEvent = function (event, hint) { + var _a; + if (this._extra && Object.keys(this._extra).length) { + event.extra = tslib_1.__assign(tslib_1.__assign({}, this._extra), event.extra); + } + if (this._tags && Object.keys(this._tags).length) { + event.tags = tslib_1.__assign(tslib_1.__assign({}, this._tags), event.tags); + } + if (this._user && Object.keys(this._user).length) { + event.user = tslib_1.__assign(tslib_1.__assign({}, this._user), event.user); + } + if (this._contexts && Object.keys(this._contexts).length) { + event.contexts = tslib_1.__assign(tslib_1.__assign({}, this._contexts), event.contexts); + } + if (this._level) { + event.level = this._level; + } + if (this._transactionName) { + event.transaction = this._transactionName; + } + // We want to set the trace context for normal events only if there isn't already + // a trace context on the event. There is a product feature in place where we link + // errors with transaction and it relys on that. + if (this._span) { + event.contexts = tslib_1.__assign({ trace: this._span.getTraceContext() }, event.contexts); + var transactionName = (_a = this._span.transaction) === null || _a === void 0 ? void 0 : _a.name; + if (transactionName) { + event.tags = tslib_1.__assign({ transaction: transactionName }, event.tags); + } + } + this._applyFingerprint(event); + event.breadcrumbs = tslib_1.__spread((event.breadcrumbs || []), this._breadcrumbs); + event.breadcrumbs = event.breadcrumbs.length > 0 ? event.breadcrumbs : undefined; + return this._notifyEventProcessors(tslib_1.__spread(getGlobalEventProcessors(), this._eventProcessors), event, hint); + }; + /** + * This will be called after {@link applyToEvent} is finished. + */ + Scope.prototype._notifyEventProcessors = function (processors, event, hint, index) { + var _this = this; + if (index === void 0) { index = 0; } + return new utils_1.SyncPromise(function (resolve, reject) { + var processor = processors[index]; + if (event === null || typeof processor !== 'function') { + resolve(event); + } + else { + var result = processor(tslib_1.__assign({}, event), hint); + if (utils_1.isThenable(result)) { + result + .then(function (final) { return _this._notifyEventProcessors(processors, final, hint, index + 1).then(resolve); }) + .then(null, reject); + } + else { + _this._notifyEventProcessors(processors, result, hint, index + 1) + .then(resolve) + .then(null, reject); + } + } + }); + }; + /** + * This will be called on every set call. + */ + Scope.prototype._notifyScopeListeners = function () { + var _this = this; + // We need this check for this._notifyingListeners to be able to work on scope during updates + // If this check is not here we'll produce endless recursion when something is done with the scope + // during the callback. + if (!this._notifyingListeners) { + this._notifyingListeners = true; + this._scopeListeners.forEach(function (callback) { + callback(_this); + }); + this._notifyingListeners = false; + } + }; + /** + * Applies fingerprint from the scope to the event if there's one, + * uses message if there's one instead or get rid of empty fingerprint + */ + Scope.prototype._applyFingerprint = function (event) { + // Make sure it's an array first and we actually have something in place + event.fingerprint = event.fingerprint + ? Array.isArray(event.fingerprint) + ? event.fingerprint + : [event.fingerprint] + : []; + // If we have something on the scope, then merge it with event + if (this._fingerprint) { + event.fingerprint = event.fingerprint.concat(this._fingerprint); + } + // If we have no data at all, remove empty array default + if (event.fingerprint && !event.fingerprint.length) { + delete event.fingerprint; + } + }; + return Scope; +}()); +exports.Scope = Scope; +/** + * Retruns the global event processors. + */ +function getGlobalEventProcessors() { + /* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access */ + var global = utils_1.getGlobalObject(); + global.__SENTRY__ = global.__SENTRY__ || {}; + global.__SENTRY__.globalEventProcessors = global.__SENTRY__.globalEventProcessors || []; + return global.__SENTRY__.globalEventProcessors; + /* eslint-enable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access */ } - -const regex = routeMatcher(triggersNotificationPaths); -const triggersNotification = regex.test.bind(regex); -const groups = {}; // @ts-ignore - -const createGroups = function (Bottleneck, common) { - // @ts-ignore - groups.global = new Bottleneck.Group(_objectSpread2({ - id: "octokit-global", - maxConcurrent: 10 - }, common)); // @ts-ignore - - groups.search = new Bottleneck.Group(_objectSpread2({ - id: "octokit-search", - maxConcurrent: 1, - minTime: 2000 - }, common)); // @ts-ignore - - groups.write = new Bottleneck.Group(_objectSpread2({ - id: "octokit-write", - maxConcurrent: 1, - minTime: 1000 - }, common)); // @ts-ignore - - groups.notifications = new Bottleneck.Group(_objectSpread2({ - id: "octokit-notifications", - maxConcurrent: 1, - minTime: 3000 - }, common)); -}; - -function throttling(octokit, octokitOptions = {}) { - const { - enabled = true, - Bottleneck = BottleneckLight, - id = "no-id", - timeout = 1000 * 60 * 2, - // Redis TTL: 2 minutes - connection - } = octokitOptions.throttle || {}; - - if (!enabled) { - return; - } - - const common = { - connection, - timeout - }; // @ts-ignore - - if (groups.global == null) { - createGroups(Bottleneck, common); - } - - const state = Object.assign(_objectSpread2({ - clustering: connection != null, - triggersNotification, - minimumAbuseRetryAfter: 5, - retryAfterBaseValue: 1000, - retryLimiter: new Bottleneck(), - id - }, groups), // @ts-ignore - octokitOptions.throttle); - - if (typeof state.onAbuseLimit !== "function" || typeof state.onRateLimit !== "function") { - throw new Error(`octokit/plugin-throttling error: - You must pass the onAbuseLimit and onRateLimit error handlers. - See https://github.com/octokit/rest.js#throttling - - const octokit = new Octokit({ - throttle: { - onAbuseLimit: (retryAfter, options) => {/* ... */}, - onRateLimit: (retryAfter, options) => {/* ... */} - } - }) - `); - } - - const events = {}; - const emitter = new Bottleneck.Events(events); // @ts-ignore - - events.on("abuse-limit", state.onAbuseLimit); // @ts-ignore - - events.on("rate-limit", state.onRateLimit); // @ts-ignore - - events.on("error", e => console.warn("Error in throttling-plugin limit handler", e)); // @ts-ignore - - state.retryLimiter.on("failed", async function (error, info) { - const options = info.args[info.args.length - 1]; - const shouldRetryGraphQL = options.url.startsWith("/graphql") && error.status !== 401; - - if (!(shouldRetryGraphQL || error.status === 403)) { - return; - } - - const retryCount = ~~options.request.retryCount; - options.request.retryCount = retryCount; - const { - wantRetry, - retryAfter - } = await async function () { - if (/\babuse\b/i.test(error.message)) { - // The user has hit the abuse rate limit. (REST and GraphQL) - // https://docs.github.com/en/rest/overview/resources-in-the-rest-api#abuse-rate-limits - // The Retry-After header can sometimes be blank when hitting an abuse limit, - // but is always present after 2-3s, so make sure to set `retryAfter` to at least 5s by default. - const retryAfter = Math.max(~~error.headers["retry-after"], state.minimumAbuseRetryAfter); - const wantRetry = await emitter.trigger("abuse-limit", retryAfter, options, octokit); - return { - wantRetry, - retryAfter - }; - } - - if (error.headers != null && error.headers["x-ratelimit-remaining"] === "0") { - // The user has used all their allowed calls for the current time period (REST and GraphQL) - // https://docs.github.com/en/rest/reference/rate-limit (REST) - // https://docs.github.com/en/graphql/overview/resource-limitations#rate-limit (GraphQL) - const rateLimitReset = new Date(~~error.headers["x-ratelimit-reset"] * 1000).getTime(); - const retryAfter = Math.max(Math.ceil((rateLimitReset - Date.now()) / 1000), 0); - const wantRetry = await emitter.trigger("rate-limit", retryAfter, options, octokit); - return { - wantRetry, - retryAfter - }; - } - - return {}; - }(); - - if (wantRetry) { - options.request.retryCount++; // @ts-ignore - - return retryAfter * state.retryAfterBaseValue; - } - }); - octokit.hook.wrap("request", wrapRequest.bind(null, state)); +/** + * Add a EventProcessor to be kept globally. + * @param callback EventProcessor to add + */ +function addGlobalEventProcessor(callback) { + getGlobalEventProcessors().push(callback); } -throttling.VERSION = VERSION; -throttling.triggersNotification = triggersNotification; - -exports.throttling = throttling; -//# sourceMappingURL=index.js.map - +exports.addGlobalEventProcessor = addGlobalEventProcessor; +//# sourceMappingURL=scope.js.map /***/ }), -/***/ 10537: +/***/ 12474: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; - - Object.defineProperty(exports, "__esModule", ({ value: true })); - -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - -var deprecation = __nccwpck_require__(58932); -var once = _interopDefault(__nccwpck_require__(1223)); - -const logOnce = once(deprecation => console.warn(deprecation)); +var types_1 = __nccwpck_require__(83789); +var utils_1 = __nccwpck_require__(1620); /** - * Error with extra properties to help with debugging + * @inheritdoc */ - -class RequestError extends Error { - constructor(message, statusCode, options) { - super(message); // Maintains proper stack trace (only available on V8) - - /* istanbul ignore next */ - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } - - this.name = "HttpError"; - this.status = statusCode; - Object.defineProperty(this, "code", { - get() { - logOnce(new deprecation.Deprecation("[@octokit/request-error] `error.code` is deprecated, use `error.status`.")); - return statusCode; - } - - }); - this.headers = options.headers || {}; // redact request credentials without mutating original request options - - const requestCopy = Object.assign({}, options.request); - - if (options.request.headers.authorization) { - requestCopy.headers = Object.assign({}, options.request.headers, { - authorization: options.request.headers.authorization.replace(/ .*$/, " [REDACTED]") - }); +var Session = /** @class */ (function () { + function Session(context) { + this.errors = 0; + this.sid = utils_1.uuid4(); + this.timestamp = Date.now(); + this.started = Date.now(); + this.duration = 0; + this.status = types_1.SessionStatus.Ok; + if (context) { + this.update(context); + } } - - requestCopy.url = requestCopy.url // client_id & client_secret can be passed as URL query parameters to increase rate limit - // see https://developer.github.com/v3/#increasing-the-unauthenticated-rate-limit-for-oauth-applications - .replace(/\bclient_secret=\w+/g, "client_secret=[REDACTED]") // OAuth tokens can be passed as URL query parameters, although it is not recommended - // see https://developer.github.com/v3/#oauth2-token-sent-in-a-header - .replace(/\baccess_token=\w+/g, "access_token=[REDACTED]"); - this.request = requestCopy; - } - -} - -exports.RequestError = RequestError; -//# sourceMappingURL=index.js.map - + /** JSDoc */ + // eslint-disable-next-line complexity + Session.prototype.update = function (context) { + if (context === void 0) { context = {}; } + if (context.user) { + if (context.user.ip_address) { + this.ipAddress = context.user.ip_address; + } + if (!context.did) { + this.did = context.user.id || context.user.email || context.user.username; + } + } + this.timestamp = context.timestamp || Date.now(); + if (context.sid) { + // Good enough uuid validation. — Kamil + this.sid = context.sid.length === 32 ? context.sid : utils_1.uuid4(); + } + if (context.did) { + this.did = "" + context.did; + } + if (typeof context.started === 'number') { + this.started = context.started; + } + if (typeof context.duration === 'number') { + this.duration = context.duration; + } + else { + this.duration = this.timestamp - this.started; + } + if (context.release) { + this.release = context.release; + } + if (context.environment) { + this.environment = context.environment; + } + if (context.ipAddress) { + this.ipAddress = context.ipAddress; + } + if (context.userAgent) { + this.userAgent = context.userAgent; + } + if (typeof context.errors === 'number') { + this.errors = context.errors; + } + if (context.status) { + this.status = context.status; + } + }; + /** JSDoc */ + Session.prototype.close = function (status) { + if (status) { + this.update({ status: status }); + } + else if (this.status === types_1.SessionStatus.Ok) { + this.update({ status: types_1.SessionStatus.Exited }); + } + else { + this.update(); + } + }; + /** JSDoc */ + Session.prototype.toJSON = function () { + return utils_1.dropUndefinedKeys({ + sid: "" + this.sid, + init: true, + started: new Date(this.started).toISOString(), + timestamp: new Date(this.timestamp).toISOString(), + status: this.status, + errors: this.errors, + did: typeof this.did === 'number' || typeof this.did === 'string' ? "" + this.did : undefined, + duration: this.duration, + attrs: utils_1.dropUndefinedKeys({ + release: this.release, + environment: this.environment, + ip_address: this.ipAddress, + user_agent: this.userAgent, + }), + }); + }; + return Session; +}()); +exports.Session = Session; +//# sourceMappingURL=session.js.map /***/ }), -/***/ 36234: +/***/ 88455: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; - - Object.defineProperty(exports, "__esModule", ({ value: true })); - -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - -var endpoint = __nccwpck_require__(59440); -var universalUserAgent = __nccwpck_require__(45030); -var isPlainObject = __nccwpck_require__(63287); -var nodeFetch = _interopDefault(__nccwpck_require__(81768)); -var requestError = __nccwpck_require__(10537); - -const VERSION = "5.4.12"; - -function getBufferResponse(response) { - return response.arrayBuffer(); -} - -function fetchWrapper(requestOptions) { - if (isPlainObject.isPlainObject(requestOptions.body) || Array.isArray(requestOptions.body)) { - requestOptions.body = JSON.stringify(requestOptions.body); - } - - let headers = {}; - let status; - let url; - const fetch = requestOptions.request && requestOptions.request.fetch || nodeFetch; - return fetch(requestOptions.url, Object.assign({ - method: requestOptions.method, - body: requestOptions.body, - headers: requestOptions.headers, - redirect: requestOptions.redirect - }, requestOptions.request)).then(response => { - url = response.url; - status = response.status; - - for (const keyAndValue of response.headers) { - headers[keyAndValue[0]] = keyAndValue[1]; - } - - if (status === 204 || status === 205) { - return; - } // GitHub API returns 200 for HEAD requests - - - if (requestOptions.method === "HEAD") { - if (status < 400) { - return; - } - - throw new requestError.RequestError(response.statusText, status, { - headers, - request: requestOptions - }); +var tslib_1 = __nccwpck_require__(4351); +var hub_1 = __nccwpck_require__(6393); +/** + * This calls a function on the current hub. + * @param method function to call on hub. + * @param args to pass to function. + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function callOnHub(method) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; } - - if (status === 304) { - throw new requestError.RequestError("Not modified", status, { - headers, - request: requestOptions - }); + var hub = hub_1.getCurrentHub(); + if (hub && hub[method]) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return hub[method].apply(hub, tslib_1.__spread(args)); } - - if (status >= 400) { - return response.text().then(message => { - const error = new requestError.RequestError(message, status, { - headers, - request: requestOptions - }); - - try { - let responseBody = JSON.parse(error.message); - Object.assign(error, responseBody); - let errors = responseBody.errors; // Assumption `errors` would always be in Array format - - error.message = error.message + ": " + errors.map(JSON.stringify).join(", "); - } catch (e) {// ignore, see octokit/rest.js#684 - } - - throw error; - }); + throw new Error("No hub defined or " + method + " was not found on the hub, please open a bug report."); +} +/** + * Captures an exception event and sends it to Sentry. + * + * @param exception An exception-like object. + * @returns The generated eventId. + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types +function captureException(exception, captureContext) { + var syntheticException; + try { + throw new Error('Sentry syntheticException'); } - - const contentType = response.headers.get("content-type"); - - if (/application\/json/.test(contentType)) { - return response.json(); + catch (exception) { + syntheticException = exception; } - - if (!contentType || /^text\/|charset=utf-8$/.test(contentType)) { - return response.text(); + return callOnHub('captureException', exception, { + captureContext: captureContext, + originalException: exception, + syntheticException: syntheticException, + }); +} +exports.captureException = captureException; +/** + * Captures a message event and sends it to Sentry. + * + * @param message The message to send to Sentry. + * @param level Define the level of the message. + * @returns The generated eventId. + */ +function captureMessage(message, captureContext) { + var syntheticException; + try { + throw new Error(message); } - - return getBufferResponse(response); - }).then(data => { - return { - status, - url, - headers, - data - }; - }).catch(error => { - if (error instanceof requestError.RequestError) { - throw error; + catch (exception) { + syntheticException = exception; } - - throw new requestError.RequestError(error.message, 500, { - headers, - request: requestOptions - }); - }); + // This is necessary to provide explicit scopes upgrade, without changing the original + // arity of the `captureMessage(message, level)` method. + var level = typeof captureContext === 'string' ? captureContext : undefined; + var context = typeof captureContext !== 'string' ? { captureContext: captureContext } : undefined; + return callOnHub('captureMessage', message, level, tslib_1.__assign({ originalException: message, syntheticException: syntheticException }, context)); } - -function withDefaults(oldEndpoint, newDefaults) { - const endpoint = oldEndpoint.defaults(newDefaults); - - const newApi = function (route, parameters) { - const endpointOptions = endpoint.merge(route, parameters); - - if (!endpointOptions.request || !endpointOptions.request.hook) { - return fetchWrapper(endpoint.parse(endpointOptions)); +exports.captureMessage = captureMessage; +/** + * Captures a manually created event and sends it to Sentry. + * + * @param event The event to send to Sentry. + * @returns The generated eventId. + */ +function captureEvent(event) { + return callOnHub('captureEvent', event); +} +exports.captureEvent = captureEvent; +/** + * Callback to set context information onto the scope. + * @param callback Callback function that receives Scope. + */ +function configureScope(callback) { + callOnHub('configureScope', callback); +} +exports.configureScope = configureScope; +/** + * Records a new breadcrumb which will be attached to future events. + * + * Breadcrumbs will be added to subsequent events to provide more context on + * user's actions prior to an error or crash. + * + * @param breadcrumb The breadcrumb to record. + */ +function addBreadcrumb(breadcrumb) { + callOnHub('addBreadcrumb', breadcrumb); +} +exports.addBreadcrumb = addBreadcrumb; +/** + * Sets context data with the given name. + * @param name of the context + * @param context Any kind of data. This data will be normalized. + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function setContext(name, context) { + callOnHub('setContext', name, context); +} +exports.setContext = setContext; +/** + * Set an object that will be merged sent as extra data with the event. + * @param extras Extras object to merge into current context. + */ +function setExtras(extras) { + callOnHub('setExtras', extras); +} +exports.setExtras = setExtras; +/** + * Set an object that will be merged sent as tags data with the event. + * @param tags Tags context object to merge into current context. + */ +function setTags(tags) { + callOnHub('setTags', tags); +} +exports.setTags = setTags; +/** + * Set key:value that will be sent as extra data with the event. + * @param key String of extra + * @param extra Any kind of data. This data will be normalized. + */ +function setExtra(key, extra) { + callOnHub('setExtra', key, extra); +} +exports.setExtra = setExtra; +/** + * Set key:value that will be sent as tags data with the event. + * + * Can also be used to unset a tag, by passing `undefined`. + * + * @param key String key of tag + * @param value Value of tag + */ +function setTag(key, value) { + callOnHub('setTag', key, value); +} +exports.setTag = setTag; +/** + * Updates user context information for future events. + * + * @param user User context object to be set in the current context. Pass `null` to unset the user. + */ +function setUser(user) { + callOnHub('setUser', user); +} +exports.setUser = setUser; +/** + * Creates a new scope with and executes the given operation within. + * The scope is automatically removed once the operation + * finishes or throws. + * + * This is essentially a convenience function for: + * + * pushScope(); + * callback(); + * popScope(); + * + * @param callback that will be enclosed into push/popScope. + */ +function withScope(callback) { + callOnHub('withScope', callback); +} +exports.withScope = withScope; +/** + * Calls a function on the latest client. Use this with caution, it's meant as + * in "internal" helper so we don't need to expose every possible function in + * the shim. It is not guaranteed that the client actually implements the + * function. + * + * @param method The method to call on the client/client. + * @param args Arguments to pass to the client/fontend. + * @hidden + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function _callOnClient(method) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; } - - const request = (route, parameters) => { - return fetchWrapper(endpoint.parse(endpoint.merge(route, parameters))); - }; - - Object.assign(request, { - endpoint, - defaults: withDefaults.bind(null, endpoint) - }); - return endpointOptions.request.hook(request, endpointOptions); - }; - - return Object.assign(newApi, { - endpoint, - defaults: withDefaults.bind(null, endpoint) - }); + callOnHub.apply(void 0, tslib_1.__spread(['_invokeClient', method], args)); } - -const request = withDefaults(endpoint.endpoint, { - headers: { - "user-agent": `octokit-request.js/${VERSION} ${universalUserAgent.getUserAgent()}` - } -}); - -exports.request = request; +exports._callOnClient = _callOnClient; +/** + * Starts a new `Transaction` and returns it. This is the entry point to manual tracing instrumentation. + * + * A tree structure can be built by adding child spans to the transaction, and child spans to other spans. To start a + * new child span within the transaction or any span, call the respective `.startChild()` method. + * + * Every child span must be finished before the transaction is finished, otherwise the unfinished spans are discarded. + * + * The transaction must be finished with a call to its `.finish()` method, at which point the transaction with all its + * finished child spans will be sent to Sentry. + * + * @param context Properties of the new `Transaction`. + * @param customSamplingContext Information given to the transaction sampling function (along with context-dependent + * default values). See {@link Options.tracesSampler}. + * + * @returns The transaction which was just started + */ +function startTransaction(context, customSamplingContext) { + return callOnHub('startTransaction', tslib_1.__assign({}, context), customSamplingContext); +} +exports.startTransaction = startTransaction; //# sourceMappingURL=index.js.map - /***/ }), -/***/ 81768: -/***/ ((module, exports, __nccwpck_require__) => { - -"use strict"; - +/***/ 40508: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __nccwpck_require__(4351); +var core_1 = __nccwpck_require__(79212); +var types_1 = __nccwpck_require__(83789); +var utils_1 = __nccwpck_require__(1620); +var parsers_1 = __nccwpck_require__(19090); +var transports_1 = __nccwpck_require__(21437); +/** + * The Sentry Node SDK Backend. + * @hidden + */ +var NodeBackend = /** @class */ (function (_super) { + tslib_1.__extends(NodeBackend, _super); + function NodeBackend() { + return _super !== null && _super.apply(this, arguments) || this; + } + /** + * @inheritDoc + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types + NodeBackend.prototype.eventFromException = function (exception, hint) { + var _this = this; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + var ex = exception; + var mechanism = { + handled: true, + type: 'generic', + }; + if (!utils_1.isError(exception)) { + if (utils_1.isPlainObject(exception)) { + // This will allow us to group events based on top-level keys + // which is much better than creating new group when any key/value change + var message = "Non-Error exception captured with keys: " + utils_1.extractExceptionKeysForMessage(exception); + core_1.getCurrentHub().configureScope(function (scope) { + scope.setExtra('__serialized__', utils_1.normalizeToSize(exception)); + }); + ex = (hint && hint.syntheticException) || new Error(message); + ex.message = message; + } + else { + // This handles when someone does: `throw "something awesome";` + // We use synthesized Error here so we can extract a (rough) stack trace. + ex = (hint && hint.syntheticException) || new Error(exception); + ex.message = exception; + } + mechanism.synthetic = true; + } + return new utils_1.SyncPromise(function (resolve, reject) { + return parsers_1.parseError(ex, _this._options) + .then(function (event) { + utils_1.addExceptionTypeValue(event, undefined, undefined); + utils_1.addExceptionMechanism(event, mechanism); + resolve(tslib_1.__assign(tslib_1.__assign({}, event), { event_id: hint && hint.event_id })); + }) + .then(null, reject); + }); + }; + /** + * @inheritDoc + */ + NodeBackend.prototype.eventFromMessage = function (message, level, hint) { + var _this = this; + if (level === void 0) { level = types_1.Severity.Info; } + var event = { + event_id: hint && hint.event_id, + level: level, + message: message, + }; + return new utils_1.SyncPromise(function (resolve) { + if (_this._options.attachStacktrace && hint && hint.syntheticException) { + var stack = hint.syntheticException ? parsers_1.extractStackFromError(hint.syntheticException) : []; + parsers_1.parseStack(stack, _this._options) + .then(function (frames) { + event.stacktrace = { + frames: parsers_1.prepareFramesForEvent(frames), + }; + resolve(event); + }) + .then(null, function () { + resolve(event); + }); + } + else { + resolve(event); + } + }); + }; + /** + * @inheritDoc + */ + NodeBackend.prototype._setupTransport = function () { + if (!this._options.dsn) { + // We return the noop transport here in case there is no Dsn. + return _super.prototype._setupTransport.call(this); + } + var dsn = new utils_1.Dsn(this._options.dsn); + var transportOptions = tslib_1.__assign(tslib_1.__assign(tslib_1.__assign(tslib_1.__assign(tslib_1.__assign({}, this._options.transportOptions), (this._options.httpProxy && { httpProxy: this._options.httpProxy })), (this._options.httpsProxy && { httpsProxy: this._options.httpsProxy })), (this._options.caCerts && { caCerts: this._options.caCerts })), { dsn: this._options.dsn }); + if (this._options.transport) { + return new this._options.transport(transportOptions); + } + if (dsn.protocol === 'http') { + return new transports_1.HTTPTransport(transportOptions); + } + return new transports_1.HTTPSTransport(transportOptions); + }; + return NodeBackend; +}(core_1.BaseBackend)); +exports.NodeBackend = NodeBackend; +//# sourceMappingURL=backend.js.map -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - -var Stream = _interopDefault(__nccwpck_require__(12781)); -var http = _interopDefault(__nccwpck_require__(13685)); -var Url = _interopDefault(__nccwpck_require__(57310)); -var https = _interopDefault(__nccwpck_require__(95687)); -var zlib = _interopDefault(__nccwpck_require__(59796)); - -// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js - -// fix for "Readable" isn't a named export issue -const Readable = Stream.Readable; - -const BUFFER = Symbol('buffer'); -const TYPE = Symbol('type'); - -class Blob { - constructor() { - this[TYPE] = ''; - - const blobParts = arguments[0]; - const options = arguments[1]; - - const buffers = []; - let size = 0; - - if (blobParts) { - const a = blobParts; - const length = Number(a.length); - for (let i = 0; i < length; i++) { - const element = a[i]; - let buffer; - if (element instanceof Buffer) { - buffer = element; - } else if (ArrayBuffer.isView(element)) { - buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength); - } else if (element instanceof ArrayBuffer) { - buffer = Buffer.from(element); - } else if (element instanceof Blob) { - buffer = element[BUFFER]; - } else { - buffer = Buffer.from(typeof element === 'string' ? element : String(element)); - } - size += buffer.length; - buffers.push(buffer); - } - } - - this[BUFFER] = Buffer.concat(buffers); - - let type = options && options.type !== undefined && String(options.type).toLowerCase(); - if (type && !/[^\u0020-\u007E]/.test(type)) { - this[TYPE] = type; - } - } - get size() { - return this[BUFFER].length; - } - get type() { - return this[TYPE]; - } - text() { - return Promise.resolve(this[BUFFER].toString()); - } - arrayBuffer() { - const buf = this[BUFFER]; - const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); - return Promise.resolve(ab); - } - stream() { - const readable = new Readable(); - readable._read = function () {}; - readable.push(this[BUFFER]); - readable.push(null); - return readable; - } - toString() { - return '[object Blob]'; - } - slice() { - const size = this.size; +/***/ }), - const start = arguments[0]; - const end = arguments[1]; - let relativeStart, relativeEnd; - if (start === undefined) { - relativeStart = 0; - } else if (start < 0) { - relativeStart = Math.max(size + start, 0); - } else { - relativeStart = Math.min(start, size); - } - if (end === undefined) { - relativeEnd = size; - } else if (end < 0) { - relativeEnd = Math.max(size + end, 0); - } else { - relativeEnd = Math.min(end, size); - } - const span = Math.max(relativeEnd - relativeStart, 0); +/***/ 86147: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - const buffer = this[BUFFER]; - const slicedBuffer = buffer.slice(relativeStart, relativeStart + span); - const blob = new Blob([], { type: arguments[2] }); - blob[BUFFER] = slicedBuffer; - return blob; - } -} +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __nccwpck_require__(4351); +var core_1 = __nccwpck_require__(79212); +var backend_1 = __nccwpck_require__(40508); +var version_1 = __nccwpck_require__(31271); +/** + * The Sentry Node SDK Client. + * + * @see NodeOptions for documentation on configuration options. + * @see SentryClient for usage documentation. + */ +var NodeClient = /** @class */ (function (_super) { + tslib_1.__extends(NodeClient, _super); + /** + * Creates a new Node SDK instance. + * @param options Configuration options for this SDK. + */ + function NodeClient(options) { + return _super.call(this, backend_1.NodeBackend, options) || this; + } + /** + * @inheritDoc + */ + NodeClient.prototype._prepareEvent = function (event, scope, hint) { + event.platform = event.platform || 'node'; + event.sdk = tslib_1.__assign(tslib_1.__assign({}, event.sdk), { name: version_1.SDK_NAME, packages: tslib_1.__spread(((event.sdk && event.sdk.packages) || []), [ + { + name: 'npm:@sentry/node', + version: version_1.SDK_VERSION, + }, + ]), version: version_1.SDK_VERSION }); + if (this.getOptions().serverName) { + event.server_name = this.getOptions().serverName; + } + return _super.prototype._prepareEvent.call(this, event, scope, hint); + }; + return NodeClient; +}(core_1.BaseClient)); +exports.NodeClient = NodeClient; +//# sourceMappingURL=client.js.map -Object.defineProperties(Blob.prototype, { - size: { enumerable: true }, - type: { enumerable: true }, - slice: { enumerable: true } -}); +/***/ }), -Object.defineProperty(Blob.prototype, Symbol.toStringTag, { - value: 'Blob', - writable: false, - enumerable: false, - configurable: true -}); +/***/ 45400: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __nccwpck_require__(4351); +/* eslint-disable max-lines */ +/* eslint-disable @typescript-eslint/no-explicit-any */ +var core_1 = __nccwpck_require__(79212); +var tracing_1 = __nccwpck_require__(64358); +var utils_1 = __nccwpck_require__(1620); +var domain = __nccwpck_require__(13639); +var os = __nccwpck_require__(22037); +var sdk_1 = __nccwpck_require__(38836); +var DEFAULT_SHUTDOWN_TIMEOUT = 2000; /** - * fetch-error.js - * - * FetchError interface for operational errors + * Express-compatible tracing handler. + * @see Exposed as `Handlers.tracingHandler` */ - +function tracingHandler() { + return function sentryTracingMiddleware(req, res, next) { + // If there is a trace header set, we extract the data from it (parentSpanId, traceId, and sampling decision) + var traceparentData; + if (req.headers && utils_1.isString(req.headers['sentry-trace'])) { + traceparentData = tracing_1.extractTraceparentData(req.headers['sentry-trace']); + } + var transaction = core_1.startTransaction(tslib_1.__assign({ name: extractExpressTransactionName(req, { path: true, method: true }), op: 'http.server' }, traceparentData)); + // We put the transaction on the scope so users can attach children to it + core_1.getCurrentHub().configureScope(function (scope) { + scope.setSpan(transaction); + }); + // We also set __sentry_transaction on the response so people can grab the transaction there to add + // spans to it later. + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + res.__sentry_transaction = transaction; + res.once('finish', function () { + // Push `transaction.finish` to the next event loop so open spans have a chance to finish before the transaction + // closes + setImmediate(function () { + addExpressReqToTransaction(transaction, req); + transaction.setHttpStatus(res.statusCode); + transaction.finish(); + }); + }); + next(); + }; +} +exports.tracingHandler = tracingHandler; /** - * Create FetchError instance - * - * @param String message Error message for human - * @param String type Error type for machine - * @param String systemError For Node.js system error - * @return FetchError + * Set parameterized as transaction name e.g.: `GET /users/:id` + * Also adds more context data on the transaction from the request */ -function FetchError(message, type, systemError) { - Error.call(this, message); - - this.message = message; - this.type = type; - - // when err.type is `system`, err.code contains system error code - if (systemError) { - this.code = this.errno = systemError.code; - } - - // hide custom error implementation details from end-users - Error.captureStackTrace(this, this.constructor); +function addExpressReqToTransaction(transaction, req) { + if (!transaction) + return; + transaction.name = extractExpressTransactionName(req, { path: true, method: true }); + transaction.setData('url', req.originalUrl); + transaction.setData('baseUrl', req.baseUrl); + transaction.setData('query', req.query); } - -FetchError.prototype = Object.create(Error.prototype); -FetchError.prototype.constructor = FetchError; -FetchError.prototype.name = 'FetchError'; - -let convert; -try { - convert = (__nccwpck_require__(22877).convert); -} catch (e) {} - -const INTERNALS = Symbol('Body internals'); - -// fix an issue where "PassThrough" isn't a named export for node <10 -const PassThrough = Stream.PassThrough; - /** - * Body mixin + * Extracts complete generalized path from the request object and uses it to construct transaction name. * - * Ref: https://fetch.spec.whatwg.org/#body + * eg. GET /mountpoint/user/:id * - * @param Stream body Readable stream - * @param Object opts Response options - * @return Void + * @param req The ExpressRequest object + * @param options What to include in the transaction name (method, path, or both) + * + * @returns The fully constructed transaction name */ -function Body(body) { - var _this = this; - - var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, - _ref$size = _ref.size; - - let size = _ref$size === undefined ? 0 : _ref$size; - var _ref$timeout = _ref.timeout; - let timeout = _ref$timeout === undefined ? 0 : _ref$timeout; - - if (body == null) { - // body is undefined or null - body = null; - } else if (isURLSearchParams(body)) { - // body is a URLSearchParams - body = Buffer.from(body.toString()); - } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') { - // body is ArrayBuffer - body = Buffer.from(body); - } else if (ArrayBuffer.isView(body)) { - // body is ArrayBufferView - body = Buffer.from(body.buffer, body.byteOffset, body.byteLength); - } else if (body instanceof Stream) ; else { - // none of the above - // coerce to string then buffer - body = Buffer.from(String(body)); - } - this[INTERNALS] = { - body, - disturbed: false, - error: null - }; - this.size = size; - this.timeout = timeout; - - if (body instanceof Stream) { - body.on('error', function (err) { - const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err); - _this[INTERNALS].error = error; - }); - } +function extractExpressTransactionName(req, options) { + if (options === void 0) { options = {}; } + var _a; + var method = (_a = req.method) === null || _a === void 0 ? void 0 : _a.toUpperCase(); + var path = ''; + if (req.route) { + // if the mountpoint is `/`, req.baseUrl is '' (not undefined), so it's safe to include it here + // see https://github.com/expressjs/express/blob/508936853a6e311099c9985d4c11a4b1b8f6af07/test/req.baseUrl.js#L7 + path = "" + req.baseUrl + req.route.path; + } + else if (req.originalUrl || req.url) { + path = utils_1.stripUrlQueryAndFragment(req.originalUrl || req.url || ''); + } + var info = ''; + if (options.method && method) { + info += method; + } + if (options.method && options.path) { + info += " "; + } + if (options.path && path) { + info += path; + } + return info; +} +/** JSDoc */ +function extractTransaction(req, type) { + var _a; + switch (type) { + case 'path': { + return extractExpressTransactionName(req, { path: true }); + } + case 'handler': { + return ((_a = req.route) === null || _a === void 0 ? void 0 : _a.stack[0].name) || ''; + } + case 'methodPath': + default: { + return extractExpressTransactionName(req, { path: true, method: true }); + } + } +} +/** Default user keys that'll be used to extract data from the request */ +var DEFAULT_USER_KEYS = ['id', 'username', 'email']; +/** JSDoc */ +function extractUserData(user, keys) { + var extractedUser = {}; + var attributes = Array.isArray(keys) ? keys : DEFAULT_USER_KEYS; + attributes.forEach(function (key) { + if (user && key in user) { + extractedUser[key] = user[key]; + } + }); + return extractedUser; +} +/** + * Enriches passed event with request data. + * + * @param event Will be mutated and enriched with req data + * @param req Request object + * @param options object containing flags to enable functionality + * @hidden + */ +function parseRequest(event, req, options) { + // eslint-disable-next-line no-param-reassign + options = tslib_1.__assign({ ip: false, request: true, serverName: true, transaction: true, user: true, version: true }, options); + if (options.version) { + event.contexts = tslib_1.__assign(tslib_1.__assign({}, event.contexts), { runtime: { + name: 'node', + version: global.process.version, + } }); + } + if (options.request) { + // if the option value is `true`, use the default set of keys by not passing anything to `extractNodeRequestData()` + var extractedRequestData = Array.isArray(options.request) + ? utils_1.extractNodeRequestData(req, options.request) + : utils_1.extractNodeRequestData(req); + event.request = tslib_1.__assign(tslib_1.__assign({}, event.request), extractedRequestData); + } + if (options.serverName && !event.server_name) { + event.server_name = global.process.env.SENTRY_NAME || os.hostname(); + } + if (options.user) { + var extractedUser = req.user && utils_1.isPlainObject(req.user) ? extractUserData(req.user, options.user) : {}; + if (Object.keys(extractedUser)) { + event.user = tslib_1.__assign(tslib_1.__assign({}, event.user), extractedUser); + } + } + // client ip: + // node: req.connection.remoteAddress + // express, koa: req.ip + if (options.ip) { + var ip = req.ip || (req.connection && req.connection.remoteAddress); + if (ip) { + event.user = tslib_1.__assign(tslib_1.__assign({}, event.user), { ip_address: ip }); + } + } + if (options.transaction && !event.transaction) { + event.transaction = extractTransaction(req, options.transaction); + } + return event; +} +exports.parseRequest = parseRequest; +/** + * Express compatible request handler. + * @see Exposed as `Handlers.requestHandler` + */ +function requestHandler(options) { + return function sentryRequestMiddleware(req, res, next) { + if (options && options.flushTimeout && options.flushTimeout > 0) { + // eslint-disable-next-line @typescript-eslint/unbound-method + var _end_1 = res.end; + res.end = function (chunk, encoding, cb) { + var _this = this; + sdk_1.flush(options.flushTimeout) + .then(function () { + _end_1.call(_this, chunk, encoding, cb); + }) + .then(null, function (e) { + utils_1.logger.error(e); + }); + }; + } + var local = domain.create(); + local.add(req); + local.add(res); + local.on('error', next); + local.run(function () { + core_1.getCurrentHub().configureScope(function (scope) { + return scope.addEventProcessor(function (event) { return parseRequest(event, req, options); }); + }); + next(); + }); + }; +} +exports.requestHandler = requestHandler; +/** JSDoc */ +function getStatusCodeFromResponse(error) { + var statusCode = error.status || error.statusCode || error.status_code || (error.output && error.output.statusCode); + return statusCode ? parseInt(statusCode, 10) : 500; +} +/** Returns true if response code is internal server error */ +function defaultShouldHandleError(error) { + var status = getStatusCodeFromResponse(error); + return status >= 500; } - -Body.prototype = { - get body() { - return this[INTERNALS].body; - }, - - get bodyUsed() { - return this[INTERNALS].disturbed; - }, - - /** - * Decode response as ArrayBuffer - * - * @return Promise - */ - arrayBuffer() { - return consumeBody.call(this).then(function (buf) { - return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); - }); - }, - - /** - * Return raw response as Blob - * - * @return Promise - */ - blob() { - let ct = this.headers && this.headers.get('content-type') || ''; - return consumeBody.call(this).then(function (buf) { - return Object.assign( - // Prevent copying - new Blob([], { - type: ct.toLowerCase() - }), { - [BUFFER]: buf - }); - }); - }, - - /** - * Decode response as json - * - * @return Promise - */ - json() { - var _this2 = this; - - return consumeBody.call(this).then(function (buffer) { - try { - return JSON.parse(buffer.toString()); - } catch (err) { - return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json')); - } - }); - }, - - /** - * Decode response as text - * - * @return Promise - */ - text() { - return consumeBody.call(this).then(function (buffer) { - return buffer.toString(); - }); - }, - - /** - * Decode response as buffer (non-spec api) - * - * @return Promise - */ - buffer() { - return consumeBody.call(this); - }, - - /** - * Decode response as text, while automatically detecting the encoding and - * trying to decode to UTF-8 (non-spec api) - * - * @return Promise - */ - textConverted() { - var _this3 = this; - - return consumeBody.call(this).then(function (buffer) { - return convertBody(buffer, _this3.headers); - }); - } -}; - -// In browsers, all properties are enumerable. -Object.defineProperties(Body.prototype, { - body: { enumerable: true }, - bodyUsed: { enumerable: true }, - arrayBuffer: { enumerable: true }, - blob: { enumerable: true }, - json: { enumerable: true }, - text: { enumerable: true } -}); - -Body.mixIn = function (proto) { - for (const name of Object.getOwnPropertyNames(Body.prototype)) { - // istanbul ignore else: future proof - if (!(name in proto)) { - const desc = Object.getOwnPropertyDescriptor(Body.prototype, name); - Object.defineProperty(proto, name, desc); - } - } -}; - /** - * Consume and convert an entire Body to a Buffer. - * - * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body - * - * @return Promise + * Express compatible error handler. + * @see Exposed as `Handlers.errorHandler` */ -function consumeBody() { - var _this4 = this; +function errorHandler(options) { + return function sentryErrorMiddleware(error, _req, res, next) { + // eslint-disable-next-line @typescript-eslint/unbound-method + var shouldHandleError = (options && options.shouldHandleError) || defaultShouldHandleError; + if (shouldHandleError(error)) { + core_1.withScope(function (_scope) { + // For some reason we need to set the transaction on the scope again + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + var transaction = res.__sentry_transaction; + if (transaction && _scope.getSpan() === undefined) { + _scope.setSpan(transaction); + } + var eventId = core_1.captureException(error); + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + res.sentry = eventId; + next(error); + }); + return; + } + next(error); + }; +} +exports.errorHandler = errorHandler; +/** + * @hidden + */ +function logAndExitProcess(error) { + // eslint-disable-next-line no-console + console.error(error && error.stack ? error.stack : error); + var client = core_1.getCurrentHub().getClient(); + if (client === undefined) { + utils_1.logger.warn('No NodeClient was defined, we are exiting the process now.'); + global.process.exit(1); + return; + } + var options = client.getOptions(); + var timeout = (options && options.shutdownTimeout && options.shutdownTimeout > 0 && options.shutdownTimeout) || + DEFAULT_SHUTDOWN_TIMEOUT; + utils_1.forget(client.close(timeout).then(function (result) { + if (!result) { + utils_1.logger.warn('We reached the timeout for emptying the request buffer, still exiting now!'); + } + global.process.exit(1); + })); +} +exports.logAndExitProcess = logAndExitProcess; +//# sourceMappingURL=handlers.js.map - if (this[INTERNALS].disturbed) { - return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`)); - } +/***/ }), - this[INTERNALS].disturbed = true; +/***/ 22783: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (this[INTERNALS].error) { - return Body.Promise.reject(this[INTERNALS].error); - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __nccwpck_require__(4351); +var types_1 = __nccwpck_require__(83789); +exports.Severity = types_1.Severity; +exports.Status = types_1.Status; +var core_1 = __nccwpck_require__(79212); +exports.addGlobalEventProcessor = core_1.addGlobalEventProcessor; +exports.addBreadcrumb = core_1.addBreadcrumb; +exports.captureException = core_1.captureException; +exports.captureEvent = core_1.captureEvent; +exports.captureMessage = core_1.captureMessage; +exports.configureScope = core_1.configureScope; +exports.getHubFromCarrier = core_1.getHubFromCarrier; +exports.getCurrentHub = core_1.getCurrentHub; +exports.Hub = core_1.Hub; +exports.makeMain = core_1.makeMain; +exports.Scope = core_1.Scope; +exports.startTransaction = core_1.startTransaction; +exports.setContext = core_1.setContext; +exports.setExtra = core_1.setExtra; +exports.setExtras = core_1.setExtras; +exports.setTag = core_1.setTag; +exports.setTags = core_1.setTags; +exports.setUser = core_1.setUser; +exports.withScope = core_1.withScope; +var backend_1 = __nccwpck_require__(40508); +exports.NodeBackend = backend_1.NodeBackend; +var client_1 = __nccwpck_require__(86147); +exports.NodeClient = client_1.NodeClient; +var sdk_1 = __nccwpck_require__(38836); +exports.defaultIntegrations = sdk_1.defaultIntegrations; +exports.init = sdk_1.init; +exports.lastEventId = sdk_1.lastEventId; +exports.flush = sdk_1.flush; +exports.close = sdk_1.close; +var version_1 = __nccwpck_require__(31271); +exports.SDK_NAME = version_1.SDK_NAME; +exports.SDK_VERSION = version_1.SDK_VERSION; +var core_2 = __nccwpck_require__(79212); +var hub_1 = __nccwpck_require__(6393); +var domain = __nccwpck_require__(13639); +var Handlers = __nccwpck_require__(45400); +exports.Handlers = Handlers; +var NodeIntegrations = __nccwpck_require__(72310); +var Transports = __nccwpck_require__(21437); +exports.Transports = Transports; +var INTEGRATIONS = tslib_1.__assign(tslib_1.__assign({}, core_2.Integrations), NodeIntegrations); +exports.Integrations = INTEGRATIONS; +// We need to patch domain on the global __SENTRY__ object to make it work for node in cross-platform packages like +// @sentry/hub. If we don't do this, browser bundlers will have troubles resolving `require('domain')`. +var carrier = hub_1.getMainCarrier(); +if (carrier.__SENTRY__) { + carrier.__SENTRY__.extensions = carrier.__SENTRY__.extensions || {}; + carrier.__SENTRY__.extensions.domain = carrier.__SENTRY__.extensions.domain || domain; +} +//# sourceMappingURL=index.js.map - let body = this.body; +/***/ }), - // body is null - if (body === null) { - return Body.Promise.resolve(Buffer.alloc(0)); - } +/***/ 29552: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // body is blob - if (isBlob(body)) { - body = body.stream(); - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __nccwpck_require__(4351); +var core_1 = __nccwpck_require__(79212); +var types_1 = __nccwpck_require__(83789); +var utils_1 = __nccwpck_require__(1620); +var util = __nccwpck_require__(73837); +/** Console module integration */ +var Console = /** @class */ (function () { + function Console() { + /** + * @inheritDoc + */ + this.name = Console.id; + } + /** + * @inheritDoc + */ + Console.prototype.setupOnce = function () { + var e_1, _a; + var consoleModule = __nccwpck_require__(96206); + try { + for (var _b = tslib_1.__values(['debug', 'info', 'warn', 'error', 'log']), _c = _b.next(); !_c.done; _c = _b.next()) { + var level = _c.value; + utils_1.fill(consoleModule, level, createConsoleWrapper(level)); + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (_c && !_c.done && (_a = _b.return)) _a.call(_b); + } + finally { if (e_1) throw e_1.error; } + } + }; + /** + * @inheritDoc + */ + Console.id = 'Console'; + return Console; +}()); +exports.Console = Console; +/** + * Wrapper function that'll be used for every console level + */ +function createConsoleWrapper(level) { + return function consoleWrapper(originalConsoleMethod) { + var sentryLevel; + switch (level) { + case 'debug': + sentryLevel = types_1.Severity.Debug; + break; + case 'error': + sentryLevel = types_1.Severity.Error; + break; + case 'info': + sentryLevel = types_1.Severity.Info; + break; + case 'warn': + sentryLevel = types_1.Severity.Warning; + break; + default: + sentryLevel = types_1.Severity.Log; + } + return function () { + if (core_1.getCurrentHub().getIntegration(Console)) { + core_1.getCurrentHub().addBreadcrumb({ + category: 'console', + level: sentryLevel, + message: util.format.apply(undefined, arguments), + }, { + input: tslib_1.__spread(arguments), + level: level, + }); + } + originalConsoleMethod.apply(this, arguments); + }; + }; +} +//# sourceMappingURL=console.js.map - // body is buffer - if (Buffer.isBuffer(body)) { - return Body.Promise.resolve(body); - } +/***/ }), - // istanbul ignore if: should never happen - if (!(body instanceof Stream)) { - return Body.Promise.resolve(Buffer.alloc(0)); - } +/***/ 76280: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // body is stream - // get ready to actually consume the body - let accum = []; - let accumBytes = 0; - let abort = false; +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __nccwpck_require__(4351); +var core_1 = __nccwpck_require__(79212); +var utils_1 = __nccwpck_require__(1620); +var http_1 = __nccwpck_require__(84103); +var NODE_VERSION = utils_1.parseSemver(process.versions.node); +/** http module integration */ +var Http = /** @class */ (function () { + /** + * @inheritDoc + */ + function Http(options) { + if (options === void 0) { options = {}; } + /** + * @inheritDoc + */ + this.name = Http.id; + this._breadcrumbs = typeof options.breadcrumbs === 'undefined' ? true : options.breadcrumbs; + this._tracing = typeof options.tracing === 'undefined' ? false : options.tracing; + } + /** + * @inheritDoc + */ + Http.prototype.setupOnce = function () { + // No need to instrument if we don't want to track anything + if (!this._breadcrumbs && !this._tracing) { + return; + } + var wrappedHandlerMaker = _createWrappedRequestMethodFactory(this._breadcrumbs, this._tracing); + var httpModule = __nccwpck_require__(13685); + utils_1.fill(httpModule, 'get', wrappedHandlerMaker); + utils_1.fill(httpModule, 'request', wrappedHandlerMaker); + // NOTE: Prior to Node 9, `https` used internals of `http` module, thus we don't patch it. + // If we do, we'd get double breadcrumbs and double spans for `https` calls. + // It has been changed in Node 9, so for all versions equal and above, we patch `https` separately. + if (NODE_VERSION.major && NODE_VERSION.major > 8) { + var httpsModule = __nccwpck_require__(95687); + utils_1.fill(httpsModule, 'get', wrappedHandlerMaker); + utils_1.fill(httpsModule, 'request', wrappedHandlerMaker); + } + }; + /** + * @inheritDoc + */ + Http.id = 'Http'; + return Http; +}()); +exports.Http = Http; +/** + * Function which creates a function which creates wrapped versions of internal `request` and `get` calls within `http` + * and `https` modules. (NB: Not a typo - this is a creator^2!) + * + * @param breadcrumbsEnabled Whether or not to record outgoing requests as breadcrumbs + * @param tracingEnabled Whether or not to record outgoing requests as tracing spans + * + * @returns A function which accepts the exiting handler and returns a wrapped handler + */ +function _createWrappedRequestMethodFactory(breadcrumbsEnabled, tracingEnabled) { + return function wrappedRequestMethodFactory(originalRequestMethod) { + return function wrappedMethod() { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + // eslint-disable-next-line @typescript-eslint/no-this-alias + var httpModule = this; + var requestArgs = http_1.normalizeRequestArgs(args); + var requestOptions = requestArgs[0]; + var requestUrl = http_1.extractUrl(requestOptions); + // we don't want to record requests to Sentry as either breadcrumbs or spans, so just use the original method + if (http_1.isSentryRequest(requestUrl)) { + return originalRequestMethod.apply(httpModule, requestArgs); + } + var span; + var parentSpan; + var scope = core_1.getCurrentHub().getScope(); + if (scope && tracingEnabled) { + parentSpan = scope.getSpan(); + if (parentSpan) { + span = parentSpan.startChild({ + description: (requestOptions.method || 'GET') + " " + requestUrl, + op: 'request', + }); + var sentryTraceHeader = span.toTraceparent(); + utils_1.logger.log("[Tracing] Adding sentry-trace header to outgoing request: " + sentryTraceHeader); + requestOptions.headers = tslib_1.__assign(tslib_1.__assign({}, requestOptions.headers), { 'sentry-trace': sentryTraceHeader }); + } + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + return originalRequestMethod + .apply(httpModule, requestArgs) + .once('response', function (res) { + // eslint-disable-next-line @typescript-eslint/no-this-alias + var req = this; + if (breadcrumbsEnabled) { + addRequestBreadcrumb('response', requestUrl, req, res); + } + if (tracingEnabled && span) { + if (res.statusCode) { + span.setHttpStatus(res.statusCode); + } + span.description = http_1.cleanSpanDescription(span.description, requestOptions, req); + span.finish(); + } + }) + .once('error', function () { + // eslint-disable-next-line @typescript-eslint/no-this-alias + var req = this; + if (breadcrumbsEnabled) { + addRequestBreadcrumb('error', requestUrl, req); + } + if (tracingEnabled && span) { + span.setHttpStatus(500); + span.description = http_1.cleanSpanDescription(span.description, requestOptions, req); + span.finish(); + } + }); + }; + }; +} +/** + * Captures Breadcrumb based on provided request/response pair + */ +function addRequestBreadcrumb(event, url, req, res) { + if (!core_1.getCurrentHub().getIntegration(Http)) { + return; + } + core_1.getCurrentHub().addBreadcrumb({ + category: 'http', + data: { + method: req.method, + status_code: res && res.statusCode, + url: url, + }, + type: 'http', + }, { + event: event, + request: req, + response: res, + }); +} +//# sourceMappingURL=http.js.map - return new Body.Promise(function (resolve, reject) { - let resTimeout; +/***/ }), - // allow timeout on slow response body - if (_this4.timeout) { - resTimeout = setTimeout(function () { - abort = true; - reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout')); - }, _this4.timeout); - } +/***/ 72310: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // handle stream errors - body.on('error', function (err) { - if (err.name === 'AbortError') { - // if the request was aborted, reject with this Error - abort = true; - reject(err); - } else { - // other errors, such as incorrect content-encoding - reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err)); - } - }); +Object.defineProperty(exports, "__esModule", ({ value: true })); +var console_1 = __nccwpck_require__(29552); +exports.Console = console_1.Console; +var http_1 = __nccwpck_require__(76280); +exports.Http = http_1.Http; +var onuncaughtexception_1 = __nccwpck_require__(50443); +exports.OnUncaughtException = onuncaughtexception_1.OnUncaughtException; +var onunhandledrejection_1 = __nccwpck_require__(87344); +exports.OnUnhandledRejection = onunhandledrejection_1.OnUnhandledRejection; +var linkederrors_1 = __nccwpck_require__(70208); +exports.LinkedErrors = linkederrors_1.LinkedErrors; +var modules_1 = __nccwpck_require__(90046); +exports.Modules = modules_1.Modules; +//# sourceMappingURL=index.js.map - body.on('data', function (chunk) { - if (abort || chunk === null) { - return; - } +/***/ }), - if (_this4.size && accumBytes + chunk.length > _this4.size) { - abort = true; - reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size')); - return; - } +/***/ 70208: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - accumBytes += chunk.length; - accum.push(chunk); - }); +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __nccwpck_require__(4351); +var core_1 = __nccwpck_require__(79212); +var utils_1 = __nccwpck_require__(1620); +var parsers_1 = __nccwpck_require__(19090); +var DEFAULT_KEY = 'cause'; +var DEFAULT_LIMIT = 5; +/** Adds SDK info to an event. */ +var LinkedErrors = /** @class */ (function () { + /** + * @inheritDoc + */ + function LinkedErrors(options) { + if (options === void 0) { options = {}; } + /** + * @inheritDoc + */ + this.name = LinkedErrors.id; + this._key = options.key || DEFAULT_KEY; + this._limit = options.limit || DEFAULT_LIMIT; + } + /** + * @inheritDoc + */ + LinkedErrors.prototype.setupOnce = function () { + core_1.addGlobalEventProcessor(function (event, hint) { + var self = core_1.getCurrentHub().getIntegration(LinkedErrors); + if (self) { + var handler = self._handler && self._handler.bind(self); + return typeof handler === 'function' ? handler(event, hint) : event; + } + return event; + }); + }; + /** + * @inheritDoc + */ + LinkedErrors.prototype._handler = function (event, hint) { + var _this = this; + if (!event.exception || !event.exception.values || !hint || !utils_1.isInstanceOf(hint.originalException, Error)) { + return utils_1.SyncPromise.resolve(event); + } + return new utils_1.SyncPromise(function (resolve) { + _this._walkErrorTree(hint.originalException, _this._key) + .then(function (linkedErrors) { + if (event && event.exception && event.exception.values) { + event.exception.values = tslib_1.__spread(linkedErrors, event.exception.values); + } + resolve(event); + }) + .then(null, function () { + resolve(event); + }); + }); + }; + /** + * @inheritDoc + */ + LinkedErrors.prototype._walkErrorTree = function (error, key, stack) { + var _this = this; + if (stack === void 0) { stack = []; } + if (!utils_1.isInstanceOf(error[key], Error) || stack.length + 1 >= this._limit) { + return utils_1.SyncPromise.resolve(stack); + } + return new utils_1.SyncPromise(function (resolve, reject) { + parsers_1.getExceptionFromError(error[key]) + .then(function (exception) { + _this._walkErrorTree(error[key], key, tslib_1.__spread([exception], stack)) + .then(resolve) + .then(null, function () { + reject(); + }); + }) + .then(null, function () { + reject(); + }); + }); + }; + /** + * @inheritDoc + */ + LinkedErrors.id = 'LinkedErrors'; + return LinkedErrors; +}()); +exports.LinkedErrors = LinkedErrors; +//# sourceMappingURL=linkederrors.js.map - body.on('end', function () { - if (abort) { - return; - } +/***/ }), - clearTimeout(resTimeout); +/***/ 90046: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - try { - resolve(Buffer.concat(accum, accumBytes)); - } catch (err) { - // handle streams that have accumulated too much data (issue #414) - reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err)); - } - }); - }); +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __nccwpck_require__(4351); +var fs_1 = __nccwpck_require__(57147); +var path_1 = __nccwpck_require__(71017); +var moduleCache; +/** Extract information about package.json modules */ +function collectModules() { + var mainPaths = (require.main && require.main.paths) || []; + var paths = require.cache ? Object.keys(require.cache) : []; + var infos = {}; + var seen = {}; + paths.forEach(function (path) { + var dir = path; + /** Traverse directories upward in the search of package.json file */ + var updir = function () { + var orig = dir; + dir = path_1.dirname(orig); + if (!dir || orig === dir || seen[orig]) { + return undefined; + } + if (mainPaths.indexOf(dir) < 0) { + return updir(); + } + var pkgfile = path_1.join(orig, 'package.json'); + seen[orig] = true; + if (!fs_1.existsSync(pkgfile)) { + return updir(); + } + try { + var info = JSON.parse(fs_1.readFileSync(pkgfile, 'utf8')); + infos[info.name] = info.version; + } + catch (_oO) { + // no-empty + } + }; + updir(); + }); + return infos; } +/** Add node modules / packages to the event */ +var Modules = /** @class */ (function () { + function Modules() { + /** + * @inheritDoc + */ + this.name = Modules.id; + } + /** + * @inheritDoc + */ + Modules.prototype.setupOnce = function (addGlobalEventProcessor, getCurrentHub) { + var _this = this; + addGlobalEventProcessor(function (event) { + if (!getCurrentHub().getIntegration(Modules)) { + return event; + } + return tslib_1.__assign(tslib_1.__assign({}, event), { modules: _this._getModules() }); + }); + }; + /** Fetches the list of modules and the versions loaded by the entry file for your node.js app. */ + Modules.prototype._getModules = function () { + if (!moduleCache) { + moduleCache = collectModules(); + } + return moduleCache; + }; + /** + * @inheritDoc + */ + Modules.id = 'Modules'; + return Modules; +}()); +exports.Modules = Modules; +//# sourceMappingURL=modules.js.map -/** - * Detect buffer encoding and convert to target encoding - * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding - * - * @param Buffer buffer Incoming buffer - * @param String encoding Target encoding - * @return String - */ -function convertBody(buffer, headers) { - if (typeof convert !== 'function') { - throw new Error('The package `encoding` must be installed to use the textConverted() function'); - } - - const ct = headers.get('content-type'); - let charset = 'utf-8'; - let res, str; - - // header - if (ct) { - res = /charset=([^;]*)/i.exec(ct); - } - - // no charset in content type, peek at response body for at most 1024 bytes - str = buffer.slice(0, 1024).toString(); - - // html5 - if (!res && str) { - res = / { - // Brand-checking and more duck-typing as optional condition. - return obj.constructor.name === 'URLSearchParams' || Object.prototype.toString.call(obj) === '[object URLSearchParams]' || typeof obj.sort === 'function'; -} +Object.defineProperty(exports, "__esModule", ({ value: true })); +var core_1 = __nccwpck_require__(79212); +var types_1 = __nccwpck_require__(83789); +var utils_1 = __nccwpck_require__(1620); +var handlers_1 = __nccwpck_require__(45400); +/** Global Promise Rejection handler */ +var OnUncaughtException = /** @class */ (function () { + /** + * @inheritDoc + */ + function OnUncaughtException(_options) { + if (_options === void 0) { _options = {}; } + this._options = _options; + /** + * @inheritDoc + */ + this.name = OnUncaughtException.id; + /** + * @inheritDoc + */ + this.handler = this._makeErrorHandler(); + } + /** + * @inheritDoc + */ + OnUncaughtException.prototype.setupOnce = function () { + global.process.on('uncaughtException', this.handler.bind(this)); + }; + /** + * @hidden + */ + OnUncaughtException.prototype._makeErrorHandler = function () { + var _this = this; + var timeout = 2000; + var caughtFirstError = false; + var caughtSecondError = false; + var calledFatalError = false; + var firstError; + return function (error) { + var onFatalError = handlers_1.logAndExitProcess; + var client = core_1.getCurrentHub().getClient(); + if (_this._options.onFatalError) { + // eslint-disable-next-line @typescript-eslint/unbound-method + onFatalError = _this._options.onFatalError; + } + else if (client && client.getOptions().onFatalError) { + // eslint-disable-next-line @typescript-eslint/unbound-method + onFatalError = client.getOptions().onFatalError; + } + if (!caughtFirstError) { + var hub_1 = core_1.getCurrentHub(); + // this is the first uncaught error and the ultimate reason for shutting down + // we want to do absolutely everything possible to ensure it gets captured + // also we want to make sure we don't go recursion crazy if more errors happen after this one + firstError = error; + caughtFirstError = true; + if (hub_1.getIntegration(OnUncaughtException)) { + hub_1.withScope(function (scope) { + scope.setLevel(types_1.Severity.Fatal); + hub_1.captureException(error, { originalException: error }); + if (!calledFatalError) { + calledFatalError = true; + onFatalError(error); + } + }); + } + else { + if (!calledFatalError) { + calledFatalError = true; + onFatalError(error); + } + } + } + else if (calledFatalError) { + // we hit an error *after* calling onFatalError - pretty boned at this point, just shut it down + utils_1.logger.warn('uncaught exception after calling fatal error shutdown callback - this is bad! forcing shutdown'); + handlers_1.logAndExitProcess(error); + } + else if (!caughtSecondError) { + // two cases for how we can hit this branch: + // - capturing of first error blew up and we just caught the exception from that + // - quit trying to capture, proceed with shutdown + // - a second independent error happened while waiting for first error to capture + // - want to avoid causing premature shutdown before first error capture finishes + // it's hard to immediately tell case 1 from case 2 without doing some fancy/questionable domain stuff + // so let's instead just delay a bit before we proceed with our action here + // in case 1, we just wait a bit unnecessarily but ultimately do the same thing + // in case 2, the delay hopefully made us wait long enough for the capture to finish + // two potential nonideal outcomes: + // nonideal case 1: capturing fails fast, we sit around for a few seconds unnecessarily before proceeding correctly by calling onFatalError + // nonideal case 2: case 2 happens, 1st error is captured but slowly, timeout completes before capture and we treat second error as the sendErr of (nonexistent) failure from trying to capture first error + // note that after hitting this branch, we might catch more errors where (caughtSecondError && !calledFatalError) + // we ignore them - they don't matter to us, we're just waiting for the second error timeout to finish + caughtSecondError = true; + setTimeout(function () { + if (!calledFatalError) { + // it was probably case 1, let's treat err as the sendErr and call onFatalError + calledFatalError = true; + onFatalError(firstError, error); + } + else { + // it was probably case 2, our first error finished capturing while we waited, cool, do nothing + } + }, timeout); // capturing could take at least sendTimeout to fail, plus an arbitrary second for how long it takes to collect surrounding source etc + } + }; + }; + /** + * @inheritDoc + */ + OnUncaughtException.id = 'OnUncaughtException'; + return OnUncaughtException; +}()); +exports.OnUncaughtException = OnUncaughtException; +//# sourceMappingURL=onuncaughtexception.js.map -/** - * Check if `obj` is a W3C `Blob` object (which `File` inherits from) - * @param {*} obj - * @return {boolean} - */ -function isBlob(obj) { - return typeof obj === 'object' && typeof obj.arrayBuffer === 'function' && typeof obj.type === 'string' && typeof obj.stream === 'function' && typeof obj.constructor === 'function' && typeof obj.constructor.name === 'string' && /^(Blob|File)$/.test(obj.constructor.name) && /^(Blob|File)$/.test(obj[Symbol.toStringTag]); -} +/***/ }), -/** - * Clone body given Res/Req instance - * - * @param Mixed instance Response or Request instance - * @return Mixed - */ -function clone(instance) { - let p1, p2; - let body = instance.body; +/***/ 87344: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // don't allow cloning a used body - if (instance.bodyUsed) { - throw new Error('cannot clone body after it is used'); - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +var core_1 = __nccwpck_require__(79212); +var utils_1 = __nccwpck_require__(1620); +var handlers_1 = __nccwpck_require__(45400); +/** Global Promise Rejection handler */ +var OnUnhandledRejection = /** @class */ (function () { + /** + * @inheritDoc + */ + function OnUnhandledRejection(_options) { + if (_options === void 0) { _options = { mode: 'warn' }; } + this._options = _options; + /** + * @inheritDoc + */ + this.name = OnUnhandledRejection.id; + } + /** + * @inheritDoc + */ + OnUnhandledRejection.prototype.setupOnce = function () { + global.process.on('unhandledRejection', this.sendUnhandledPromise.bind(this)); + }; + /** + * Send an exception with reason + * @param reason string + * @param promise promise + */ + // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any + OnUnhandledRejection.prototype.sendUnhandledPromise = function (reason, promise) { + var hub = core_1.getCurrentHub(); + if (!hub.getIntegration(OnUnhandledRejection)) { + this._handleRejection(reason); + return; + } + /* eslint-disable @typescript-eslint/no-unsafe-member-access */ + var context = (promise.domain && promise.domain.sentryContext) || {}; + hub.withScope(function (scope) { + scope.setExtra('unhandledPromiseRejection', true); + // Preserve backwards compatibility with raven-node for now + if (context.user) { + scope.setUser(context.user); + } + if (context.tags) { + scope.setTags(context.tags); + } + if (context.extra) { + scope.setExtras(context.extra); + } + hub.captureException(reason, { originalException: promise }); + }); + /* eslint-disable @typescript-eslint/no-unsafe-member-access */ + this._handleRejection(reason); + }; + /** + * Handler for `mode` option + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + OnUnhandledRejection.prototype._handleRejection = function (reason) { + // https://github.com/nodejs/node/blob/7cf6f9e964aa00772965391c23acda6d71972a9a/lib/internal/process/promises.js#L234-L240 + var rejectionWarning = 'This error originated either by ' + + 'throwing inside of an async function without a catch block, ' + + 'or by rejecting a promise which was not handled with .catch().' + + ' The promise rejected with the reason:'; + /* eslint-disable no-console */ + if (this._options.mode === 'warn') { + utils_1.consoleSandbox(function () { + console.warn(rejectionWarning); + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + console.error(reason && reason.stack ? reason.stack : reason); + }); + } + else if (this._options.mode === 'strict') { + utils_1.consoleSandbox(function () { + console.warn(rejectionWarning); + }); + handlers_1.logAndExitProcess(reason); + } + /* eslint-enable no-console */ + }; + /** + * @inheritDoc + */ + OnUnhandledRejection.id = 'OnUnhandledRejection'; + return OnUnhandledRejection; +}()); +exports.OnUnhandledRejection = OnUnhandledRejection; +//# sourceMappingURL=onunhandledrejection.js.map - // check that body is a stream and not form-data object - // note: we can't clone the form-data object without having it as a dependency - if (body instanceof Stream && typeof body.getBoundary !== 'function') { - // tee instance body - p1 = new PassThrough(); - p2 = new PassThrough(); - body.pipe(p1); - body.pipe(p2); - // set instance body to teed body and return the other teed body - instance[INTERNALS].body = p1; - body = p2; - } +/***/ }), - return body; -} +/***/ 84103: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __nccwpck_require__(4351); +var core_1 = __nccwpck_require__(79212); +var url_1 = __nccwpck_require__(57310); /** - * Performs the operation "extract a `Content-Type` value from |object|" as - * specified in the specification: - * https://fetch.spec.whatwg.org/#concept-bodyinit-extract - * - * This function assumes that instance.body is present. - * - * @param Mixed instance Any options.body input + * Checks whether given url points to Sentry server + * @param url url to verify */ -function extractContentType(body) { - if (body === null) { - // body is null - return null; - } else if (typeof body === 'string') { - // body is string - return 'text/plain;charset=UTF-8'; - } else if (isURLSearchParams(body)) { - // body is a URLSearchParams - return 'application/x-www-form-urlencoded;charset=UTF-8'; - } else if (isBlob(body)) { - // body is blob - return body.type || null; - } else if (Buffer.isBuffer(body)) { - // body is buffer - return null; - } else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') { - // body is ArrayBuffer - return null; - } else if (ArrayBuffer.isView(body)) { - // body is ArrayBufferView - return null; - } else if (typeof body.getBoundary === 'function') { - // detect form data input from form-data module - return `multipart/form-data;boundary=${body.getBoundary()}`; - } else if (body instanceof Stream) { - // body is stream - // can't really do much about this - return null; - } else { - // Body constructor defaults other things to string - return 'text/plain;charset=UTF-8'; - } +function isSentryRequest(url) { + var _a; + var dsn = (_a = core_1.getCurrentHub() + .getClient()) === null || _a === void 0 ? void 0 : _a.getDsn(); + return dsn ? url.includes(dsn.host) : false; } - +exports.isSentryRequest = isSentryRequest; /** - * The Fetch Standard treats this as if "total bytes" is a property on the body. - * For us, we have to explicitly get it with a function. - * - * ref: https://fetch.spec.whatwg.org/#concept-body-total-bytes + * Assemble a URL to be used for breadcrumbs and spans. * - * @param Body instance Instance of Body - * @return Number? Number of bytes, or null if not possible + * @param requestOptions RequestOptions object containing the component parts for a URL + * @returns Fully-formed URL */ -function getTotalBytes(instance) { - const body = instance.body; - - - if (body === null) { - // body is null - return 0; - } else if (isBlob(body)) { - return body.size; - } else if (Buffer.isBuffer(body)) { - // body is buffer - return body.length; - } else if (body && typeof body.getLengthSync === 'function') { - // detect form data input from form-data module - if (body._lengthRetrievers && body._lengthRetrievers.length == 0 || // 1.x - body.hasKnownLength && body.hasKnownLength()) { - // 2.x - return body.getLengthSync(); - } - return null; - } else { - // body is stream - return null; - } +function extractUrl(requestOptions) { + var protocol = requestOptions.protocol || ''; + var hostname = requestOptions.hostname || requestOptions.host || ''; + // Don't log standard :80 (http) and :443 (https) ports to reduce the noise + var port = !requestOptions.port || requestOptions.port === 80 || requestOptions.port === 443 ? '' : ":" + requestOptions.port; + var path = requestOptions.path ? requestOptions.path : '/'; + return protocol + "//" + hostname + port + path; } - +exports.extractUrl = extractUrl; /** - * Write a Body to a Node.js WritableStream (e.g. http.Request) object. + * Handle various edge cases in the span description (for spans representing http(s) requests). * - * @param Body instance Instance of Body - * @return Void + * @param description current `description` property of the span representing the request + * @param requestOptions Configuration data for the request + * @param Request Request object + * + * @returns The cleaned description */ -function writeToStream(dest, instance) { - const body = instance.body; - - - if (body === null) { - // body is null - dest.end(); - } else if (isBlob(body)) { - body.stream().pipe(dest); - } else if (Buffer.isBuffer(body)) { - // body is buffer - dest.write(body); - dest.end(); - } else { - // body is stream - body.pipe(dest); - } +function cleanSpanDescription(description, requestOptions, request) { + var _a, _b, _c; + // nothing to clean + if (!description) { + return description; + } + // eslint-disable-next-line prefer-const + var _d = tslib_1.__read(description.split(' '), 2), method = _d[0], requestUrl = _d[1]; + // superagent sticks the protocol in a weird place (we check for host because if both host *and* protocol are missing, + // we're likely dealing with an internal route and this doesn't apply) + if (requestOptions.host && !requestOptions.protocol) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any + requestOptions.protocol = (_b = (_a = request) === null || _a === void 0 ? void 0 : _a.agent) === null || _b === void 0 ? void 0 : _b.protocol; // worst comes to worst, this is undefined and nothing changes + requestUrl = extractUrl(requestOptions); + } + // internal routes can end up starting with a triple slash rather than a single one + if ((_c = requestUrl) === null || _c === void 0 ? void 0 : _c.startsWith('///')) { + requestUrl = requestUrl.slice(2); + } + return method + " " + requestUrl; } - -// expose Promise -Body.Promise = global.Promise; - +exports.cleanSpanDescription = cleanSpanDescription; /** - * headers.js + * Convert a URL object into a RequestOptions object. * - * Headers class offers convenient helpers + * Copied from Node's internals (where it's used in http(s).request() and http(s).get()), modified only to use the + * RequestOptions type above. + * + * See https://github.com/nodejs/node/blob/master/lib/internal/url.js. */ - -const invalidTokenRegex = /[^\^_`a-zA-Z\-0-9!#$%&'*+.|~]/; -const invalidHeaderCharRegex = /[^\t\x20-\x7e\x80-\xff]/; - -function validateName(name) { - name = `${name}`; - if (invalidTokenRegex.test(name) || name === '') { - throw new TypeError(`${name} is not a legal HTTP header name`); - } -} - -function validateValue(value) { - value = `${value}`; - if (invalidHeaderCharRegex.test(value)) { - throw new TypeError(`${value} is not a legal HTTP header value`); - } +function urlToOptions(url) { + var options = { + protocol: url.protocol, + hostname: typeof url.hostname === 'string' && url.hostname.startsWith('[') ? url.hostname.slice(1, -1) : url.hostname, + hash: url.hash, + search: url.search, + pathname: url.pathname, + path: "" + (url.pathname || '') + (url.search || ''), + href: url.href, + }; + if (url.port !== '') { + options.port = Number(url.port); + } + if (url.username || url.password) { + options.auth = url.username + ":" + url.password; + } + return options; } - +exports.urlToOptions = urlToOptions; /** - * Find the key in the map object given a header name. + * Normalize inputs to `http(s).request()` and `http(s).get()`. * - * Returns undefined if not found. + * Legal inputs to `http(s).request()` and `http(s).get()` can take one of ten forms: + * [ RequestOptions | string | URL ], + * [ RequestOptions | string | URL, RequestCallback ], + * [ string | URL, RequestOptions ], and + * [ string | URL, RequestOptions, RequestCallback ]. * - * @param String name Header name - * @return String|Undefined + * This standardizes to one of two forms: [ RequestOptions ] and [ RequestOptions, RequestCallback ]. A similar thing is + * done as the first step of `http(s).request()` and `http(s).get()`; this just does it early so that we can interact + * with the args in a standard way. + * + * @param requestArgs The inputs to `http(s).request()` or `http(s).get()`, as an array. + * + * @returns Equivalent args of the form [ RequestOptions ] or [ RequestOptions, RequestCallback ]. */ -function find(map, name) { - name = name.toLowerCase(); - for (const key in map) { - if (key.toLowerCase() === name) { - return key; - } - } - return undefined; +function normalizeRequestArgs(requestArgs) { + var callback, requestOptions; + // pop off the callback, if there is one + if (typeof requestArgs[requestArgs.length - 1] === 'function') { + callback = requestArgs.pop(); + } + // create a RequestOptions object of whatever's at index 0 + if (typeof requestArgs[0] === 'string') { + requestOptions = urlToOptions(new url_1.URL(requestArgs[0])); + } + else if (requestArgs[0] instanceof url_1.URL) { + requestOptions = urlToOptions(requestArgs[0]); + } + else { + requestOptions = requestArgs[0]; + } + // if the options were given separately from the URL, fold them in + if (requestArgs.length === 2) { + requestOptions = tslib_1.__assign(tslib_1.__assign({}, requestOptions), requestArgs[1]); + } + // return args in standardized form + if (callback) { + return [requestOptions, callback]; + } + else { + return [requestOptions]; + } } +exports.normalizeRequestArgs = normalizeRequestArgs; +//# sourceMappingURL=http.js.map -const MAP = Symbol('map'); -class Headers { - /** - * Headers class - * - * @param Object headers Response headers - * @return Void - */ - constructor() { - let init = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : undefined; - - this[MAP] = Object.create(null); - - if (init instanceof Headers) { - const rawHeaders = init.raw(); - const headerNames = Object.keys(rawHeaders); - - for (const headerName of headerNames) { - for (const value of rawHeaders[headerName]) { - this.append(headerName, value); - } - } - - return; - } - - // We don't worry about converting prop to ByteString here as append() - // will handle it. - if (init == null) ; else if (typeof init === 'object') { - const method = init[Symbol.iterator]; - if (method != null) { - if (typeof method !== 'function') { - throw new TypeError('Header pairs must be iterable'); - } - - // sequence> - // Note: per spec we have to first exhaust the lists then process them - const pairs = []; - for (const pair of init) { - if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') { - throw new TypeError('Each header pair must be iterable'); - } - pairs.push(Array.from(pair)); - } - - for (const pair of pairs) { - if (pair.length !== 2) { - throw new TypeError('Each header pair must be a name/value tuple'); - } - this.append(pair[0], pair[1]); - } - } else { - // record - for (const key of Object.keys(init)) { - const value = init[key]; - this.append(key, value); - } - } - } else { - throw new TypeError('Provided initializer must be an object'); - } - } - - /** - * Return combined header value given name - * - * @param String name Header name - * @return Mixed - */ - get(name) { - name = `${name}`; - validateName(name); - const key = find(this[MAP], name); - if (key === undefined) { - return null; - } - - return this[MAP][key].join(', '); - } - - /** - * Iterate over all headers - * - * @param Function callback Executed for each item with parameters (value, name, thisArg) - * @param Boolean thisArg `this` context for callback function - * @return Void - */ - forEach(callback) { - let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; - - let pairs = getHeaders(this); - let i = 0; - while (i < pairs.length) { - var _pairs$i = pairs[i]; - const name = _pairs$i[0], - value = _pairs$i[1]; - - callback.call(thisArg, value, name, this); - pairs = getHeaders(this); - i++; - } - } - - /** - * Overwrite header values given name - * - * @param String name Header name - * @param String value Header value - * @return Void - */ - set(name, value) { - name = `${name}`; - value = `${value}`; - validateName(name); - validateValue(value); - const key = find(this[MAP], name); - this[MAP][key !== undefined ? key : name] = [value]; - } - - /** - * Append a value onto existing header - * - * @param String name Header name - * @param String value Header value - * @return Void - */ - append(name, value) { - name = `${name}`; - value = `${value}`; - validateName(name); - validateValue(value); - const key = find(this[MAP], name); - if (key !== undefined) { - this[MAP][key].push(value); - } else { - this[MAP][name] = [value]; - } - } - - /** - * Check for header name existence - * - * @param String name Header name - * @return Boolean - */ - has(name) { - name = `${name}`; - validateName(name); - return find(this[MAP], name) !== undefined; - } - - /** - * Delete all header values given name - * - * @param String name Header name - * @return Void - */ - delete(name) { - name = `${name}`; - validateName(name); - const key = find(this[MAP], name); - if (key !== undefined) { - delete this[MAP][key]; - } - } - - /** - * Return raw headers (non-spec api) - * - * @return Object - */ - raw() { - return this[MAP]; - } - - /** - * Get an iterator on keys. - * - * @return Iterator - */ - keys() { - return createHeadersIterator(this, 'key'); - } +/***/ }), - /** - * Get an iterator on values. - * - * @return Iterator - */ - values() { - return createHeadersIterator(this, 'value'); - } +/***/ 19090: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - /** - * Get an iterator on entries. - * - * This is the default iterator of the Headers object. - * - * @return Iterator - */ - [Symbol.iterator]() { - return createHeadersIterator(this, 'key+value'); - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +var utils_1 = __nccwpck_require__(1620); +var fs_1 = __nccwpck_require__(57147); +var lru_map_1 = __nccwpck_require__(18424); +var stacktrace = __nccwpck_require__(46276); +var DEFAULT_LINES_OF_CONTEXT = 7; +var FILE_CONTENT_CACHE = new lru_map_1.LRUMap(100); +/** + * Resets the file cache. Exists for testing purposes. + * @hidden + */ +function resetFileContentCache() { + FILE_CONTENT_CACHE.clear(); } -Headers.prototype.entries = Headers.prototype[Symbol.iterator]; - -Object.defineProperty(Headers.prototype, Symbol.toStringTag, { - value: 'Headers', - writable: false, - enumerable: false, - configurable: true -}); - -Object.defineProperties(Headers.prototype, { - get: { enumerable: true }, - forEach: { enumerable: true }, - set: { enumerable: true }, - append: { enumerable: true }, - has: { enumerable: true }, - delete: { enumerable: true }, - keys: { enumerable: true }, - values: { enumerable: true }, - entries: { enumerable: true } -}); - -function getHeaders(headers) { - let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value'; - - const keys = Object.keys(headers[MAP]).sort(); - return keys.map(kind === 'key' ? function (k) { - return k.toLowerCase(); - } : kind === 'value' ? function (k) { - return headers[MAP][k].join(', '); - } : function (k) { - return [k.toLowerCase(), headers[MAP][k].join(', ')]; - }); +exports.resetFileContentCache = resetFileContentCache; +/** JSDoc */ +function getFunction(frame) { + try { + return frame.functionName || frame.typeName + "." + (frame.methodName || ''); + } + catch (e) { + // This seems to happen sometimes when using 'use strict', + // stemming from `getTypeName`. + // [TypeError: Cannot read property 'constructor' of undefined] + return ''; + } } - -const INTERNAL = Symbol('internal'); - -function createHeadersIterator(target, kind) { - const iterator = Object.create(HeadersIteratorPrototype); - iterator[INTERNAL] = { - target, - kind, - index: 0 - }; - return iterator; +var mainModule = ((require.main && require.main.filename && utils_1.dirname(require.main.filename)) || + global.process.cwd()) + "/"; +/** JSDoc */ +function getModule(filename, base) { + if (!base) { + // eslint-disable-next-line no-param-reassign + base = mainModule; + } + // It's specifically a module + var file = utils_1.basename(filename, '.js'); + // eslint-disable-next-line no-param-reassign + filename = utils_1.dirname(filename); + var n = filename.lastIndexOf('/node_modules/'); + if (n > -1) { + // /node_modules/ is 14 chars + return filename.substr(n + 14).replace(/\//g, '.') + ":" + file; + } + // Let's see if it's a part of the main module + // To be a part of main module, it has to share the same base + n = (filename + "/").lastIndexOf(base, 0); + if (n === 0) { + var moduleName = filename.substr(base.length).replace(/\//g, '.'); + if (moduleName) { + moduleName += ':'; + } + moduleName += file; + return moduleName; + } + return file; +} +/** + * This function reads file contents and caches them in a global LRU cache. + * Returns a Promise filepath => content array for all files that we were able to read. + * + * @param filenames Array of filepaths to read content from. + */ +function readSourceFiles(filenames) { + // we're relying on filenames being de-duped already + if (filenames.length === 0) { + return utils_1.SyncPromise.resolve({}); + } + return new utils_1.SyncPromise(function (resolve) { + var sourceFiles = {}; + var count = 0; + var _loop_1 = function (i) { + var filename = filenames[i]; + var cache = FILE_CONTENT_CACHE.get(filename); + // We have a cache hit + if (cache !== undefined) { + // If it's not null (which means we found a file and have a content) + // we set the content and return it later. + if (cache !== null) { + sourceFiles[filename] = cache; + } + // eslint-disable-next-line no-plusplus + count++; + // In any case we want to skip here then since we have a content already or we couldn't + // read the file and don't want to try again. + if (count === filenames.length) { + resolve(sourceFiles); + } + return "continue"; + } + fs_1.readFile(filename, function (err, data) { + var content = err ? null : data.toString(); + sourceFiles[filename] = content; + // We always want to set the cache, even to null which means there was an error reading the file. + // We do not want to try to read the file again. + FILE_CONTENT_CACHE.set(filename, content); + // eslint-disable-next-line no-plusplus + count++; + if (count === filenames.length) { + resolve(sourceFiles); + } + }); + }; + // eslint-disable-next-line @typescript-eslint/prefer-for-of + for (var i = 0; i < filenames.length; i++) { + _loop_1(i); + } + }); } - -const HeadersIteratorPrototype = Object.setPrototypeOf({ - next() { - // istanbul ignore if - if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) { - throw new TypeError('Value of `this` is not a HeadersIterator'); - } - - var _INTERNAL = this[INTERNAL]; - const target = _INTERNAL.target, - kind = _INTERNAL.kind, - index = _INTERNAL.index; - - const values = getHeaders(target, kind); - const len = values.length; - if (index >= len) { - return { - value: undefined, - done: true - }; - } - - this[INTERNAL].index = index + 1; - - return { - value: values[index], - done: false - }; - } -}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))); - -Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, { - value: 'HeadersIterator', - writable: false, - enumerable: false, - configurable: true -}); - /** - * Export the Headers object in a form that Node.js can consume. - * - * @param Headers headers - * @return Object + * @hidden */ -function exportNodeCompatibleHeaders(headers) { - const obj = Object.assign({ __proto__: null }, headers[MAP]); - - // http.request() only supports string as Host header. This hack makes - // specifying custom Host header possible. - const hostHeaderKey = find(headers[MAP], 'Host'); - if (hostHeaderKey !== undefined) { - obj[hostHeaderKey] = obj[hostHeaderKey][0]; - } - - return obj; +function extractStackFromError(error) { + var stack = stacktrace.parse(error); + if (!stack) { + return []; + } + return stack; } - +exports.extractStackFromError = extractStackFromError; /** - * Create a Headers object from an object of headers, ignoring those that do - * not conform to HTTP grammar productions. - * - * @param Object obj Object of headers - * @return Headers + * @hidden */ -function createHeadersLenient(obj) { - const headers = new Headers(); - for (const name of Object.keys(obj)) { - if (invalidTokenRegex.test(name)) { - continue; - } - if (Array.isArray(obj[name])) { - for (const val of obj[name]) { - if (invalidHeaderCharRegex.test(val)) { - continue; - } - if (headers[MAP][name] === undefined) { - headers[MAP][name] = [val]; - } else { - headers[MAP][name].push(val); - } - } - } else if (!invalidHeaderCharRegex.test(obj[name])) { - headers[MAP][name] = [obj[name]]; - } - } - return headers; +function parseStack(stack, options) { + var filesToRead = []; + var linesOfContext = options && options.frameContextLines !== undefined ? options.frameContextLines : DEFAULT_LINES_OF_CONTEXT; + var frames = stack.map(function (frame) { + var parsedFrame = { + colno: frame.columnNumber, + filename: frame.fileName || '', + function: getFunction(frame), + lineno: frame.lineNumber, + }; + var isInternal = frame.native || + (parsedFrame.filename && + !parsedFrame.filename.startsWith('/') && + !parsedFrame.filename.startsWith('.') && + parsedFrame.filename.indexOf(':\\') !== 1); + // in_app is all that's not an internal Node function or a module within node_modules + // note that isNative appears to return true even for node core libraries + // see https://github.com/getsentry/raven-node/issues/176 + parsedFrame.in_app = + !isInternal && parsedFrame.filename !== undefined && parsedFrame.filename.indexOf('node_modules/') === -1; + // Extract a module name based on the filename + if (parsedFrame.filename) { + parsedFrame.module = getModule(parsedFrame.filename); + if (!isInternal && linesOfContext > 0 && filesToRead.indexOf(parsedFrame.filename) === -1) { + filesToRead.push(parsedFrame.filename); + } + } + return parsedFrame; + }); + // We do an early return if we do not want to fetch context liens + if (linesOfContext <= 0) { + return utils_1.SyncPromise.resolve(frames); + } + try { + return addPrePostContext(filesToRead, frames, linesOfContext); + } + catch (_) { + // This happens in electron for example where we are not able to read files from asar. + // So it's fine, we recover be just returning all frames without pre/post context. + return utils_1.SyncPromise.resolve(frames); + } } - -const INTERNALS$1 = Symbol('Response internals'); - -// fix an issue where "STATUS_CODES" aren't a named export for node <10 -const STATUS_CODES = http.STATUS_CODES; - +exports.parseStack = parseStack; /** - * Response class - * - * @param Stream body Readable stream - * @param Object opts Response options - * @return Void + * This function tries to read the source files + adding pre and post context (source code) + * to a frame. + * @param filesToRead string[] of filepaths + * @param frames StackFrame[] containg all frames */ -class Response { - constructor() { - let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; - let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - - Body.call(this, body, opts); - - const status = opts.status || 200; - const headers = new Headers(opts.headers); - - if (body != null && !headers.has('Content-Type')) { - const contentType = extractContentType(body); - if (contentType) { - headers.append('Content-Type', contentType); - } - } - - this[INTERNALS$1] = { - url: opts.url, - status, - statusText: opts.statusText || STATUS_CODES[status], - headers, - counter: opts.counter - }; - } - - get url() { - return this[INTERNALS$1].url || ''; - } - - get status() { - return this[INTERNALS$1].status; - } - - /** - * Convenience property representing if the request ended normally - */ - get ok() { - return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300; - } - - get redirected() { - return this[INTERNALS$1].counter > 0; - } - - get statusText() { - return this[INTERNALS$1].statusText; - } - - get headers() { - return this[INTERNALS$1].headers; - } - - /** - * Clone this response - * - * @return Response - */ - clone() { - return new Response(clone(this), { - url: this.url, - status: this.status, - statusText: this.statusText, - headers: this.headers, - ok: this.ok, - redirected: this.redirected - }); - } +function addPrePostContext(filesToRead, frames, linesOfContext) { + return new utils_1.SyncPromise(function (resolve) { + return readSourceFiles(filesToRead).then(function (sourceFiles) { + var result = frames.map(function (frame) { + if (frame.filename && sourceFiles[frame.filename]) { + try { + var lines = sourceFiles[frame.filename].split('\n'); + utils_1.addContextToFrame(lines, frame, linesOfContext); + } + catch (e) { + // anomaly, being defensive in case + // unlikely to ever happen in practice but can definitely happen in theory + } + } + return frame; + }); + resolve(result); + }); + }); } - -Body.mixIn(Response.prototype); - -Object.defineProperties(Response.prototype, { - url: { enumerable: true }, - status: { enumerable: true }, - ok: { enumerable: true }, - redirected: { enumerable: true }, - statusText: { enumerable: true }, - headers: { enumerable: true }, - clone: { enumerable: true } -}); - -Object.defineProperty(Response.prototype, Symbol.toStringTag, { - value: 'Response', - writable: false, - enumerable: false, - configurable: true -}); - -const INTERNALS$2 = Symbol('Request internals'); - -// fix an issue where "format", "parse" aren't a named export for node <10 -const parse_url = Url.parse; -const format_url = Url.format; - -const streamDestructionSupported = 'destroy' in Stream.Readable.prototype; - /** - * Check if a value is an instance of Request. - * - * @param Mixed input - * @return Boolean + * @hidden */ -function isRequest(input) { - return typeof input === 'object' && typeof input[INTERNALS$2] === 'object'; +function getExceptionFromError(error, options) { + var name = error.name || error.constructor.name; + var stack = extractStackFromError(error); + return new utils_1.SyncPromise(function (resolve) { + return parseStack(stack, options).then(function (frames) { + var result = { + stacktrace: { + frames: prepareFramesForEvent(frames), + }, + type: name, + value: error.message, + }; + resolve(result); + }); + }); } - -function isAbortSignal(signal) { - const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal); - return !!(proto && proto.constructor.name === 'AbortSignal'); +exports.getExceptionFromError = getExceptionFromError; +/** + * @hidden + */ +function parseError(error, options) { + return new utils_1.SyncPromise(function (resolve) { + return getExceptionFromError(error, options).then(function (exception) { + resolve({ + exception: { + values: [exception], + }, + }); + }); + }); } - +exports.parseError = parseError; /** - * Request class - * - * @param Mixed input Url or Request instance - * @param Object init Custom options - * @return Void + * @hidden */ -class Request { - constructor(input) { - let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - - let parsedURL; - - // normalize input - if (!isRequest(input)) { - if (input && input.href) { - // in order to support Node.js' Url objects; though WHATWG's URL objects - // will fall into this branch also (since their `toString()` will return - // `href` property anyway) - parsedURL = parse_url(input.href); - } else { - // coerce input to a string before attempting to parse - parsedURL = parse_url(`${input}`); - } - input = {}; - } else { - parsedURL = parse_url(input.url); - } - - let method = init.method || input.method || 'GET'; - method = method.toUpperCase(); - - if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) { - throw new TypeError('Request with GET/HEAD method cannot have body'); - } - - let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null; - - Body.call(this, inputBody, { - timeout: init.timeout || input.timeout || 0, - size: init.size || input.size || 0 - }); - - const headers = new Headers(init.headers || input.headers || {}); - - if (inputBody != null && !headers.has('Content-Type')) { - const contentType = extractContentType(inputBody); - if (contentType) { - headers.append('Content-Type', contentType); - } - } - - let signal = isRequest(input) ? input.signal : null; - if ('signal' in init) signal = init.signal; - - if (signal != null && !isAbortSignal(signal)) { - throw new TypeError('Expected signal to be an instanceof AbortSignal'); - } - - this[INTERNALS$2] = { - method, - redirect: init.redirect || input.redirect || 'follow', - headers, - parsedURL, - signal - }; - - // node-fetch-only options - this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20; - this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true; - this.counter = init.counter || input.counter || 0; - this.agent = init.agent || input.agent; - } - - get method() { - return this[INTERNALS$2].method; - } - - get url() { - return format_url(this[INTERNALS$2].parsedURL); - } - - get headers() { - return this[INTERNALS$2].headers; - } +function prepareFramesForEvent(stack) { + if (!stack || !stack.length) { + return []; + } + var localStack = stack; + var firstFrameFunction = localStack[0].function || ''; + if (firstFrameFunction.indexOf('captureMessage') !== -1 || firstFrameFunction.indexOf('captureException') !== -1) { + localStack = localStack.slice(1); + } + // The frame where the crash happened, should be the last entry in the array + return localStack.reverse(); +} +exports.prepareFramesForEvent = prepareFramesForEvent; +//# sourceMappingURL=parsers.js.map - get redirect() { - return this[INTERNALS$2].redirect; - } +/***/ }), - get signal() { - return this[INTERNALS$2].signal; - } +/***/ 38836: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - /** - * Clone this request - * - * @return Request - */ - clone() { - return new Request(this); - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __nccwpck_require__(4351); +var core_1 = __nccwpck_require__(79212); +var hub_1 = __nccwpck_require__(6393); +var utils_1 = __nccwpck_require__(1620); +var domain = __nccwpck_require__(13639); +var client_1 = __nccwpck_require__(86147); +var integrations_1 = __nccwpck_require__(72310); +exports.defaultIntegrations = [ + // Common + new core_1.Integrations.InboundFilters(), + new core_1.Integrations.FunctionToString(), + // Native Wrappers + new integrations_1.Console(), + new integrations_1.Http(), + // Global Handlers + new integrations_1.OnUncaughtException(), + new integrations_1.OnUnhandledRejection(), + // Misc + new integrations_1.LinkedErrors(), +]; +/** + * The Sentry Node SDK Client. + * + * To use this SDK, call the {@link init} function as early as possible in the + * main entry module. To set context information or send manual events, use the + * provided methods. + * + * @example + * ``` + * + * const { init } = require('@sentry/node'); + * + * init({ + * dsn: '__DSN__', + * // ... + * }); + * ``` + * + * @example + * ``` + * + * const { configureScope } = require('@sentry/node'); + * configureScope((scope: Scope) => { + * scope.setExtra({ battery: 0.7 }); + * scope.setTag({ user_mode: 'admin' }); + * scope.setUser({ id: '4711' }); + * }); + * ``` + * + * @example + * ``` + * + * const { addBreadcrumb } = require('@sentry/node'); + * addBreadcrumb({ + * message: 'My Breadcrumb', + * // ... + * }); + * ``` + * + * @example + * ``` + * + * const Sentry = require('@sentry/node'); + * Sentry.captureMessage('Hello, world!'); + * Sentry.captureException(new Error('Good bye')); + * Sentry.captureEvent({ + * message: 'Manual', + * stacktrace: [ + * // ... + * ], + * }); + * ``` + * + * @see {@link NodeOptions} for documentation on configuration options. + */ +function init(options) { + if (options === void 0) { options = {}; } + if (options.defaultIntegrations === undefined) { + options.defaultIntegrations = exports.defaultIntegrations; + } + if (options.dsn === undefined && process.env.SENTRY_DSN) { + options.dsn = process.env.SENTRY_DSN; + } + if (options.release === undefined) { + var global_1 = utils_1.getGlobalObject(); + // Prefer env var over global + if (process.env.SENTRY_RELEASE) { + options.release = process.env.SENTRY_RELEASE; + } + // This supports the variable that sentry-webpack-plugin injects + else if (global_1.SENTRY_RELEASE && global_1.SENTRY_RELEASE.id) { + options.release = global_1.SENTRY_RELEASE.id; + } + } + if (options.environment === undefined && process.env.SENTRY_ENVIRONMENT) { + options.environment = process.env.SENTRY_ENVIRONMENT; + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any + if (domain.active) { + hub_1.setHubOnCarrier(hub_1.getMainCarrier(), core_1.getCurrentHub()); + } + core_1.initAndBind(client_1.NodeClient, options); } - -Body.mixIn(Request.prototype); - -Object.defineProperty(Request.prototype, Symbol.toStringTag, { - value: 'Request', - writable: false, - enumerable: false, - configurable: true -}); - -Object.defineProperties(Request.prototype, { - method: { enumerable: true }, - url: { enumerable: true }, - headers: { enumerable: true }, - redirect: { enumerable: true }, - clone: { enumerable: true }, - signal: { enumerable: true } -}); - +exports.init = init; /** - * Convert a Request to Node.js http request options. + * This is the getter for lastEventId. * - * @param Request A Request instance - * @return Object The options object to be passed to http.request + * @returns The last event id of a captured event. */ -function getNodeRequestOptions(request) { - const parsedURL = request[INTERNALS$2].parsedURL; - const headers = new Headers(request[INTERNALS$2].headers); - - // fetch step 1.3 - if (!headers.has('Accept')) { - headers.set('Accept', '*/*'); - } - - // Basic fetch - if (!parsedURL.protocol || !parsedURL.hostname) { - throw new TypeError('Only absolute URLs are supported'); - } - - if (!/^https?:$/.test(parsedURL.protocol)) { - throw new TypeError('Only HTTP(S) protocols are supported'); - } - - if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) { - throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8'); - } - - // HTTP-network-or-cache fetch steps 2.4-2.7 - let contentLengthValue = null; - if (request.body == null && /^(POST|PUT)$/i.test(request.method)) { - contentLengthValue = '0'; - } - if (request.body != null) { - const totalBytes = getTotalBytes(request); - if (typeof totalBytes === 'number') { - contentLengthValue = String(totalBytes); - } - } - if (contentLengthValue) { - headers.set('Content-Length', contentLengthValue); - } - - // HTTP-network-or-cache fetch step 2.11 - if (!headers.has('User-Agent')) { - headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)'); - } - - // HTTP-network-or-cache fetch step 2.15 - if (request.compress && !headers.has('Accept-Encoding')) { - headers.set('Accept-Encoding', 'gzip,deflate'); - } - - let agent = request.agent; - if (typeof agent === 'function') { - agent = agent(parsedURL); - } - - if (!headers.has('Connection') && !agent) { - headers.set('Connection', 'close'); - } - - // HTTP-network fetch step 4.2 - // chunked encoding is handled by Node.js - - return Object.assign({}, parsedURL, { - method: request.method, - headers: exportNodeCompatibleHeaders(headers), - agent - }); +function lastEventId() { + return core_1.getCurrentHub().lastEventId(); } - +exports.lastEventId = lastEventId; /** - * abort-error.js + * A promise that resolves when all current events have been sent. + * If you provide a timeout and the queue takes longer to drain the promise returns false. * - * AbortError interface for cancelled requests + * @param timeout Maximum time in ms the client should wait. */ - +function flush(timeout) { + return tslib_1.__awaiter(this, void 0, void 0, function () { + var client; + return tslib_1.__generator(this, function (_a) { + client = core_1.getCurrentHub().getClient(); + if (client) { + return [2 /*return*/, client.flush(timeout)]; + } + return [2 /*return*/, Promise.reject(false)]; + }); + }); +} +exports.flush = flush; /** - * Create AbortError instance + * A promise that resolves when all current events have been sent. + * If you provide a timeout and the queue takes longer to drain the promise returns false. * - * @param String message Error message for human - * @return AbortError + * @param timeout Maximum time in ms the client should wait. */ -function AbortError(message) { - Error.call(this, message); - - this.type = 'aborted'; - this.message = message; - - // hide custom error implementation details from end-users - Error.captureStackTrace(this, this.constructor); +function close(timeout) { + return tslib_1.__awaiter(this, void 0, void 0, function () { + var client; + return tslib_1.__generator(this, function (_a) { + client = core_1.getCurrentHub().getClient(); + if (client) { + return [2 /*return*/, client.close(timeout)]; + } + return [2 /*return*/, Promise.reject(false)]; + }); + }); } +exports.close = close; +//# sourceMappingURL=sdk.js.map -AbortError.prototype = Object.create(Error.prototype); -AbortError.prototype.constructor = AbortError; -AbortError.prototype.name = 'AbortError'; +/***/ }), -// fix an issue where "PassThrough", "resolve" aren't a named export for node <10 -const PassThrough$1 = Stream.PassThrough; -const resolve_url = Url.resolve; +/***/ 46276: +/***/ ((__unused_webpack_module, exports) => { /** - * Fetch function + * stack-trace - Parses node.js stack traces * - * @param Mixed url Absolute url or Request instance - * @param Object opts Fetch options - * @return Promise + * This was originally forked to fix this issue: + * https://github.com/felixge/node-stack-trace/issues/31 + * + * Mar 19,2019 - #4fd379e + * + * https://github.com/felixge/node-stack-trace/ + * @license MIT */ -function fetch(url, opts) { - - // allow custom promise - if (!fetch.Promise) { - throw new Error('native promise missing, set fetch.Promise to your favorite alternative'); - } - - Body.Promise = fetch.Promise; - - // wrap http.request into fetch - return new fetch.Promise(function (resolve, reject) { - // build request object - const request = new Request(url, opts); - const options = getNodeRequestOptions(request); - - const send = (options.protocol === 'https:' ? https : http).request; - const signal = request.signal; - - let response = null; - - const abort = function abort() { - let error = new AbortError('The user aborted a request.'); - reject(error); - if (request.body && request.body instanceof Stream.Readable) { - request.body.destroy(error); - } - if (!response || !response.body) return; - response.body.emit('error', error); - }; - - if (signal && signal.aborted) { - abort(); - return; - } - - const abortAndFinalize = function abortAndFinalize() { - abort(); - finalize(); - }; - - // send request - const req = send(options); - let reqTimeout; - - if (signal) { - signal.addEventListener('abort', abortAndFinalize); - } - - function finalize() { - req.abort(); - if (signal) signal.removeEventListener('abort', abortAndFinalize); - clearTimeout(reqTimeout); - } - - if (request.timeout) { - req.once('socket', function (socket) { - reqTimeout = setTimeout(function () { - reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout')); - finalize(); - }, request.timeout); - }); - } - - req.on('error', function (err) { - reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err)); - finalize(); - }); - - req.on('response', function (res) { - clearTimeout(reqTimeout); - - const headers = createHeadersLenient(res.headers); - - // HTTP fetch step 5 - if (fetch.isRedirect(res.statusCode)) { - // HTTP fetch step 5.2 - const location = headers.get('Location'); - - // HTTP fetch step 5.3 - const locationURL = location === null ? null : resolve_url(request.url, location); - - // HTTP fetch step 5.5 - switch (request.redirect) { - case 'error': - reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect')); - finalize(); - return; - case 'manual': - // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL. - if (locationURL !== null) { - // handle corrupted header - try { - headers.set('Location', locationURL); - } catch (err) { - // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request - reject(err); - } - } - break; - case 'follow': - // HTTP-redirect fetch step 2 - if (locationURL === null) { - break; - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +/** Extracts StackFrames from the Error */ +function parse(err) { + if (!err.stack) { + return []; + } + var lines = err.stack.split('\n').slice(1); + return lines + .map(function (line) { + if (line.match(/^\s*[-]{4,}$/)) { + return { + columnNumber: null, + fileName: line, + functionName: null, + lineNumber: null, + methodName: null, + native: null, + typeName: null, + }; + } + var lineMatch = line.match(/at (?:(.+?)\s+\()?(?:(.+?):(\d+)(?::(\d+))?|([^)]+))\)?/); + if (!lineMatch) { + return undefined; + } + var object = null; + var method = null; + var functionName = null; + var typeName = null; + var methodName = null; + var isNative = lineMatch[5] === 'native'; + if (lineMatch[1]) { + functionName = lineMatch[1]; + var methodStart = functionName.lastIndexOf('.'); + if (functionName[methodStart - 1] === '.') { + // eslint-disable-next-line no-plusplus + methodStart--; + } + if (methodStart > 0) { + object = functionName.substr(0, methodStart); + method = functionName.substr(methodStart + 1); + var objectEnd = object.indexOf('.Module'); + if (objectEnd > 0) { + functionName = functionName.substr(objectEnd + 1); + object = object.substr(0, objectEnd); + } + } + typeName = null; + } + if (method) { + typeName = object; + methodName = method; + } + if (method === '') { + methodName = null; + functionName = null; + } + var properties = { + columnNumber: parseInt(lineMatch[4], 10) || null, + fileName: lineMatch[2] || null, + functionName: functionName, + lineNumber: parseInt(lineMatch[3], 10) || null, + methodName: methodName, + native: isNative, + typeName: typeName, + }; + return properties; + }) + .filter(function (callSite) { return !!callSite; }); +} +exports.parse = parse; +//# sourceMappingURL=stacktrace.js.map - // HTTP-redirect fetch step 5 - if (request.counter >= request.follow) { - reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect')); - finalize(); - return; - } +/***/ }), - // HTTP-redirect fetch step 6 (counter increment) - // Create a new Request object. - const requestOpts = { - headers: new Headers(request.headers), - follow: request.follow, - counter: request.counter + 1, - agent: request.agent, - compress: request.compress, - method: request.method, - body: request.body, - signal: request.signal, - timeout: request.timeout, - size: request.size - }; +/***/ 43240: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // HTTP-redirect fetch step 9 - if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) { - reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect')); - finalize(); - return; - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __nccwpck_require__(4351); +var core_1 = __nccwpck_require__(79212); +var types_1 = __nccwpck_require__(83789); +var utils_1 = __nccwpck_require__(1620); +var fs = __nccwpck_require__(57147); +var url = __nccwpck_require__(57310); +var version_1 = __nccwpck_require__(31271); +/** Base Transport class implementation */ +var BaseTransport = /** @class */ (function () { + /** Create instance and set this.dsn */ + function BaseTransport(options) { + this.options = options; + /** A simple buffer holding all requests. */ + this._buffer = new utils_1.PromiseBuffer(30); + /** Locks transport after receiving 429 response */ + this._disabledUntil = new Date(Date.now()); + this._api = new core_1.API(options.dsn); + } + /** + * @inheritDoc + */ + BaseTransport.prototype.sendEvent = function (_) { + throw new utils_1.SentryError('Transport Class has to implement `sendEvent` method.'); + }; + /** + * @inheritDoc + */ + BaseTransport.prototype.close = function (timeout) { + return this._buffer.drain(timeout); + }; + /** Returns a build request option object used by request */ + BaseTransport.prototype._getRequestOptions = function (uri) { + var headers = tslib_1.__assign(tslib_1.__assign({}, this._api.getRequestHeaders(version_1.SDK_NAME, version_1.SDK_VERSION)), this.options.headers); + var hostname = uri.hostname, pathname = uri.pathname, port = uri.port, protocol = uri.protocol; + // See https://github.com/nodejs/node/blob/38146e717fed2fabe3aacb6540d839475e0ce1c6/lib/internal/url.js#L1268-L1290 + // We ignore the query string on purpose + var path = "" + pathname; + return tslib_1.__assign({ agent: this.client, headers: headers, + hostname: hostname, method: 'POST', path: path, + port: port, + protocol: protocol }, (this.options.caCerts && { + ca: fs.readFileSync(this.options.caCerts), + })); + }; + /** JSDoc */ + BaseTransport.prototype._sendWithModule = function (httpModule, event) { + return tslib_1.__awaiter(this, void 0, void 0, function () { + var _this = this; + return tslib_1.__generator(this, function (_a) { + if (new Date(Date.now()) < this._disabledUntil) { + return [2 /*return*/, Promise.reject(new utils_1.SentryError("Transport locked till " + this._disabledUntil + " due to too many requests."))]; + } + if (!this._buffer.isReady()) { + return [2 /*return*/, Promise.reject(new utils_1.SentryError('Not adding Promise due to buffer limit reached.'))]; + } + return [2 /*return*/, this._buffer.add(new Promise(function (resolve, reject) { + var sentryReq = core_1.eventToSentryRequest(event, _this._api); + var options = _this._getRequestOptions(new url.URL(sentryReq.url)); + var req = httpModule.request(options, function (res) { + var statusCode = res.statusCode || 500; + var status = types_1.Status.fromHttpCode(statusCode); + res.setEncoding('utf8'); + if (status === types_1.Status.Success) { + resolve({ status: status }); + } + else { + if (status === types_1.Status.RateLimit) { + var now = Date.now(); + /** + * "Key-value pairs of header names and values. Header names are lower-cased." + * https://nodejs.org/api/http.html#http_message_headers + */ + var retryAfterHeader = res.headers ? res.headers['retry-after'] : ''; + retryAfterHeader = (Array.isArray(retryAfterHeader) ? retryAfterHeader[0] : retryAfterHeader); + _this._disabledUntil = new Date(now + utils_1.parseRetryAfterHeader(now, retryAfterHeader)); + utils_1.logger.warn("Too many requests, backing off till: " + _this._disabledUntil); + } + var rejectionMessage = "HTTP Error (" + statusCode + ")"; + if (res.headers && res.headers['x-sentry-error']) { + rejectionMessage += ": " + res.headers['x-sentry-error']; + } + reject(new utils_1.SentryError(rejectionMessage)); + } + // Force the socket to drain + res.on('data', function () { + // Drain + }); + res.on('end', function () { + // Drain + }); + }); + req.on('error', reject); + req.end(sentryReq.body); + }))]; + }); + }); + }; + return BaseTransport; +}()); +exports.BaseTransport = BaseTransport; +//# sourceMappingURL=base.js.map - // HTTP-redirect fetch step 11 - if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') { - requestOpts.method = 'GET'; - requestOpts.body = undefined; - requestOpts.headers.delete('content-length'); - } +/***/ }), - // HTTP-redirect fetch step 15 - resolve(fetch(new Request(locationURL, requestOpts))); - finalize(); - return; - } - } +/***/ 84490: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // prepare response - res.once('end', function () { - if (signal) signal.removeEventListener('abort', abortAndFinalize); - }); - let body = res.pipe(new PassThrough$1()); +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __nccwpck_require__(4351); +var utils_1 = __nccwpck_require__(1620); +var http = __nccwpck_require__(13685); +var base_1 = __nccwpck_require__(43240); +/** Node http module transport */ +var HTTPTransport = /** @class */ (function (_super) { + tslib_1.__extends(HTTPTransport, _super); + /** Create a new instance and set this.agent */ + function HTTPTransport(options) { + var _this = _super.call(this, options) || this; + _this.options = options; + var proxy = options.httpProxy || process.env.http_proxy; + _this.module = http; + _this.client = proxy + ? new (__nccwpck_require__(77219))(proxy) + : new http.Agent({ keepAlive: false, maxSockets: 30, timeout: 2000 }); + return _this; + } + /** + * @inheritDoc + */ + HTTPTransport.prototype.sendEvent = function (event) { + if (!this.module) { + throw new utils_1.SentryError('No module available in HTTPTransport'); + } + return this._sendWithModule(this.module, event); + }; + return HTTPTransport; +}(base_1.BaseTransport)); +exports.HTTPTransport = HTTPTransport; +//# sourceMappingURL=http.js.map - const response_options = { - url: request.url, - status: res.statusCode, - statusText: res.statusMessage, - headers: headers, - size: request.size, - timeout: request.timeout, - counter: request.counter - }; +/***/ }), - // HTTP-network fetch step 12.1.1.3 - const codings = headers.get('Content-Encoding'); +/***/ 68621: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // HTTP-network fetch step 12.1.1.4: handle content codings +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __nccwpck_require__(4351); +var utils_1 = __nccwpck_require__(1620); +var https = __nccwpck_require__(95687); +var base_1 = __nccwpck_require__(43240); +/** Node https module transport */ +var HTTPSTransport = /** @class */ (function (_super) { + tslib_1.__extends(HTTPSTransport, _super); + /** Create a new instance and set this.agent */ + function HTTPSTransport(options) { + var _this = _super.call(this, options) || this; + _this.options = options; + var proxy = options.httpsProxy || options.httpProxy || process.env.https_proxy || process.env.http_proxy; + _this.module = https; + _this.client = proxy + ? new (__nccwpck_require__(77219))(proxy) + : new https.Agent({ keepAlive: false, maxSockets: 30, timeout: 2000 }); + return _this; + } + /** + * @inheritDoc + */ + HTTPSTransport.prototype.sendEvent = function (event) { + if (!this.module) { + throw new utils_1.SentryError('No module available in HTTPSTransport'); + } + return this._sendWithModule(this.module, event); + }; + return HTTPSTransport; +}(base_1.BaseTransport)); +exports.HTTPSTransport = HTTPSTransport; +//# sourceMappingURL=https.js.map - // in following scenarios we ignore compression support - // 1. compression support is disabled - // 2. HEAD request - // 3. no Content-Encoding header - // 4. no content response (204) - // 5. content not modified response (304) - if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) { - response = new Response(body, response_options); - resolve(response); - return; - } +/***/ }), - // For Node v6+ - // Be less strict when decoding compressed responses, since sometimes - // servers send slightly invalid responses that are still accepted - // by common browsers. - // Always using Z_SYNC_FLUSH is what cURL does. - const zlibOptions = { - flush: zlib.Z_SYNC_FLUSH, - finishFlush: zlib.Z_SYNC_FLUSH - }; +/***/ 21437: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // for gzip - if (codings == 'gzip' || codings == 'x-gzip') { - body = body.pipe(zlib.createGunzip(zlibOptions)); - response = new Response(body, response_options); - resolve(response); - return; - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +var base_1 = __nccwpck_require__(43240); +exports.BaseTransport = base_1.BaseTransport; +var http_1 = __nccwpck_require__(84490); +exports.HTTPTransport = http_1.HTTPTransport; +var https_1 = __nccwpck_require__(68621); +exports.HTTPSTransport = https_1.HTTPSTransport; +//# sourceMappingURL=index.js.map - // for deflate - if (codings == 'deflate' || codings == 'x-deflate') { - // handle the infamous raw deflate response from old servers - // a hack for old IIS and Apache servers - const raw = res.pipe(new PassThrough$1()); - raw.once('data', function (chunk) { - // see http://stackoverflow.com/questions/37519828 - if ((chunk[0] & 0x0F) === 0x08) { - body = body.pipe(zlib.createInflate()); - } else { - body = body.pipe(zlib.createInflateRaw()); - } - response = new Response(body, response_options); - resolve(response); - }); - return; - } +/***/ }), - // for br - if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') { - body = body.pipe(zlib.createBrotliDecompress()); - response = new Response(body, response_options); - resolve(response); - return; - } +/***/ 31271: +/***/ ((__unused_webpack_module, exports) => { - // otherwise, use response as-is - response = new Response(body, response_options); - resolve(response); - }); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SDK_NAME = 'sentry.javascript.node'; +exports.SDK_VERSION = '5.29.2'; +//# sourceMappingURL=version.js.map - writeToStream(req, request); - }); -} -/** - * Redirect code matching - * - * @param Number code Status code - * @return Boolean - */ -fetch.isRedirect = function (code) { - return code === 301 || code === 302 || code === 303 || code === 307 || code === 308; -}; +/***/ }), -// expose Promise -fetch.Promise = global.Promise; +/***/ 81867: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -module.exports = exports = fetch; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = exports; -exports.Headers = Headers; -exports.Request = Request; -exports.Response = Response; -exports.FetchError = FetchError; - +var utils_1 = __nccwpck_require__(1620); +var spanstatus_1 = __nccwpck_require__(58522); +var utils_2 = __nccwpck_require__(31386); +var global = utils_1.getGlobalObject(); +/** + * Add a listener that cancels and finishes a transaction when the global + * document is hidden. + */ +function registerBackgroundTabDetection() { + if (global && global.document) { + global.document.addEventListener('visibilitychange', function () { + var activeTransaction = utils_2.getActiveTransaction(); + if (global.document.hidden && activeTransaction) { + utils_1.logger.log("[Tracing] Transaction: " + spanstatus_1.SpanStatus.Cancelled + " -> since tab moved to the background, op: " + activeTransaction.op); + // We should not set status if it is already set, this prevent important statuses like + // error or data loss from being overwritten on transaction. + if (!activeTransaction.status) { + activeTransaction.setStatus(spanstatus_1.SpanStatus.Cancelled); + } + activeTransaction.setTag('visibilitychange', 'document.hidden'); + activeTransaction.finish(); + } + }); + } + else { + utils_1.logger.warn('[Tracing] Could not set up background tab detection due to lack of global document'); + } +} +exports.registerBackgroundTabDetection = registerBackgroundTabDetection; +//# sourceMappingURL=backgroundtab.js.map /***/ }), -/***/ 49768: +/***/ 33577: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; - - Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __nccwpck_require__(4351); +var utils_1 = __nccwpck_require__(1620); +var hubextensions_1 = __nccwpck_require__(31409); +var idletransaction_1 = __nccwpck_require__(2171); +var spanstatus_1 = __nccwpck_require__(58522); +var utils_2 = __nccwpck_require__(31386); +var backgroundtab_1 = __nccwpck_require__(81867); +var metrics_1 = __nccwpck_require__(68451); +var request_1 = __nccwpck_require__(27854); +var router_1 = __nccwpck_require__(40348); +exports.DEFAULT_MAX_TRANSACTION_DURATION_SECONDS = 600; +var DEFAULT_BROWSER_TRACING_OPTIONS = tslib_1.__assign({ idleTimeout: idletransaction_1.DEFAULT_IDLE_TIMEOUT, markBackgroundTransactions: true, maxTransactionDuration: exports.DEFAULT_MAX_TRANSACTION_DURATION_SECONDS, routingInstrumentation: router_1.defaultRoutingInstrumentation, startTransactionOnLocationChange: true, startTransactionOnPageLoad: true }, request_1.defaultRequestInstrumentationOptions); +/** + * The Browser Tracing integration automatically instruments browser pageload/navigation + * actions as transactions, and captures requests, metrics and errors as spans. + * + * The integration can be configured with a variety of options, and can be extended to use + * any routing library. This integration uses {@see IdleTransaction} to create transactions. + */ +var BrowserTracing = /** @class */ (function () { + function BrowserTracing(_options) { + /** + * @inheritDoc + */ + this.name = BrowserTracing.id; + this._metrics = new metrics_1.MetricsInstrumentation(); + this._emitOptionsWarning = false; + var tracingOrigins = request_1.defaultRequestInstrumentationOptions.tracingOrigins; + // NOTE: Logger doesn't work in constructors, as it's initialized after integrations instances + if (_options && + _options.tracingOrigins && + Array.isArray(_options.tracingOrigins) && + _options.tracingOrigins.length !== 0) { + tracingOrigins = _options.tracingOrigins; + } + else { + this._emitOptionsWarning = true; + } + this.options = tslib_1.__assign(tslib_1.__assign(tslib_1.__assign({}, DEFAULT_BROWSER_TRACING_OPTIONS), _options), { tracingOrigins: tracingOrigins }); + } + /** + * @inheritDoc + */ + BrowserTracing.prototype.setupOnce = function (_, getCurrentHub) { + var _this = this; + this._getCurrentHub = getCurrentHub; + if (this._emitOptionsWarning) { + utils_1.logger.warn('[Tracing] You need to define `tracingOrigins` in the options. Set an array of urls or patterns to trace.'); + utils_1.logger.warn("[Tracing] We added a reasonable default for you: " + request_1.defaultRequestInstrumentationOptions.tracingOrigins); + } + // eslint-disable-next-line @typescript-eslint/unbound-method + var _a = this.options, routingInstrumentation = _a.routingInstrumentation, startTransactionOnLocationChange = _a.startTransactionOnLocationChange, startTransactionOnPageLoad = _a.startTransactionOnPageLoad, markBackgroundTransactions = _a.markBackgroundTransactions, traceFetch = _a.traceFetch, traceXHR = _a.traceXHR, tracingOrigins = _a.tracingOrigins, shouldCreateSpanForRequest = _a.shouldCreateSpanForRequest; + routingInstrumentation(function (context) { return _this._createRouteTransaction(context); }, startTransactionOnPageLoad, startTransactionOnLocationChange); + if (markBackgroundTransactions) { + backgroundtab_1.registerBackgroundTabDetection(); + } + request_1.registerRequestInstrumentation({ traceFetch: traceFetch, traceXHR: traceXHR, tracingOrigins: tracingOrigins, shouldCreateSpanForRequest: shouldCreateSpanForRequest }); + }; + /** Create routing idle transaction. */ + BrowserTracing.prototype._createRouteTransaction = function (context) { + var _this = this; + if (!this._getCurrentHub) { + utils_1.logger.warn("[Tracing] Did not create " + context.op + " transaction because _getCurrentHub is invalid."); + return undefined; + } + // eslint-disable-next-line @typescript-eslint/unbound-method + var _a = this.options, beforeNavigate = _a.beforeNavigate, idleTimeout = _a.idleTimeout, maxTransactionDuration = _a.maxTransactionDuration; + var parentContextFromHeader = context.op === 'pageload' ? getHeaderContext() : undefined; + var expandedContext = tslib_1.__assign(tslib_1.__assign(tslib_1.__assign({}, context), parentContextFromHeader), { trimEnd: true }); + var modifiedContext = typeof beforeNavigate === 'function' ? beforeNavigate(expandedContext) : expandedContext; + // For backwards compatibility reasons, beforeNavigate can return undefined to "drop" the transaction (prevent it + // from being sent to Sentry). + var finalContext = modifiedContext === undefined ? tslib_1.__assign(tslib_1.__assign({}, expandedContext), { sampled: false }) : modifiedContext; + if (finalContext.sampled === false) { + utils_1.logger.log("[Tracing] Will not send " + finalContext.op + " transaction because of beforeNavigate."); + } + var hub = this._getCurrentHub(); + var idleTransaction = hubextensions_1.startIdleTransaction(hub, finalContext, idleTimeout, true); + utils_1.logger.log("[Tracing] Starting " + finalContext.op + " transaction on scope"); + idleTransaction.registerBeforeFinishCallback(function (transaction, endTimestamp) { + _this._metrics.addPerformanceEntries(transaction); + adjustTransactionDuration(utils_2.secToMs(maxTransactionDuration), transaction, endTimestamp); + }); + return idleTransaction; + }; + /** + * @inheritDoc + */ + BrowserTracing.id = 'BrowserTracing'; + return BrowserTracing; +}()); +exports.BrowserTracing = BrowserTracing; +/** + * Gets transaction context from a sentry-trace meta. + * + * @returns Transaction context data from the header or undefined if there's no header or the header is malformed + */ +function getHeaderContext() { + var header = getMetaContent('sentry-trace'); + if (header) { + return utils_2.extractTraceparentData(header); + } + return undefined; +} +exports.getHeaderContext = getHeaderContext; +/** Returns the value of a meta tag */ +function getMetaContent(metaName) { + var el = document.querySelector("meta[name=" + metaName + "]"); + return el ? el.getAttribute('content') : null; +} +exports.getMetaContent = getMetaContent; +/** Adjusts transaction value based on max transaction duration */ +function adjustTransactionDuration(maxDuration, transaction, endTimestamp) { + var diff = endTimestamp - transaction.startTimestamp; + var isOutdatedTransaction = endTimestamp && (diff > maxDuration || diff < 0); + if (isOutdatedTransaction) { + transaction.setStatus(spanstatus_1.SpanStatus.DeadlineExceeded); + transaction.setTag('maxTransactionDurationExceeded', 'true'); + } +} +//# sourceMappingURL=browsertracing.js.map -var crypto = __nccwpck_require__(6113); -var buffer = __nccwpck_require__(14300); - -const VERSION = "2.0.0"; - -var Algorithm; +/***/ }), -(function (Algorithm) { - Algorithm["SHA1"] = "sha1"; - Algorithm["SHA256"] = "sha256"; -})(Algorithm || (Algorithm = {})); +/***/ 71425: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -async function sign(options, payload) { - const { - secret, - algorithm - } = typeof options === "object" ? { - secret: options.secret, - algorithm: options.algorithm || Algorithm.SHA256 - } : { - secret: options, - algorithm: Algorithm.SHA256 - }; +Object.defineProperty(exports, "__esModule", ({ value: true })); +var browsertracing_1 = __nccwpck_require__(33577); +exports.BrowserTracing = browsertracing_1.BrowserTracing; +//# sourceMappingURL=index.js.map - if (!secret || !payload) { - throw new TypeError("[@octokit/webhooks-methods] secret & payload required for sign()"); - } +/***/ }), - if (!Object.values(Algorithm).includes(algorithm)) { - throw new TypeError(`[@octokit/webhooks] Algorithm ${algorithm} is not supported. Must be 'sha1' or 'sha256'`); - } +/***/ 68451: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - return `${algorithm}=${crypto.createHmac(algorithm, secret).update(payload).digest("hex")}`; +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __nccwpck_require__(4351); +var utils_1 = __nccwpck_require__(1620); +var utils_2 = __nccwpck_require__(31386); +var getCLS_1 = __nccwpck_require__(56982); +var getFID_1 = __nccwpck_require__(82496); +var getLCP_1 = __nccwpck_require__(99382); +var getTTFB_1 = __nccwpck_require__(55909); +var getFirstHidden_1 = __nccwpck_require__(88493); +var global = utils_1.getGlobalObject(); +/** Class tracking metrics */ +var MetricsInstrumentation = /** @class */ (function () { + function MetricsInstrumentation() { + this._measurements = {}; + this._performanceCursor = 0; + if (global && global.performance) { + if (global.performance.mark) { + global.performance.mark('sentry-tracing-init'); + } + this._trackCLS(); + this._trackLCP(); + this._trackFID(); + this._trackTTFB(); + } + } + /** Add performance related spans to a transaction */ + MetricsInstrumentation.prototype.addPerformanceEntries = function (transaction) { + var _this = this; + if (!global || !global.performance || !global.performance.getEntries || !utils_1.browserPerformanceTimeOrigin) { + // Gatekeeper if performance API not available + return; + } + utils_1.logger.log('[Tracing] Adding & adjusting spans using Performance API'); + var timeOrigin = utils_2.msToSec(utils_1.browserPerformanceTimeOrigin); + var entryScriptSrc; + if (global.document) { + // eslint-disable-next-line @typescript-eslint/prefer-for-of + for (var i = 0; i < document.scripts.length; i++) { + // We go through all scripts on the page and look for 'data-entry' + // We remember the name and measure the time between this script finished loading and + // our mark 'sentry-tracing-init' + if (document.scripts[i].dataset.entry === 'true') { + entryScriptSrc = document.scripts[i].src; + break; + } + } + } + var entryScriptStartTimestamp; + var tracingInitMarkStartTime; + global.performance + .getEntries() + .slice(this._performanceCursor) + .forEach(function (entry) { + var startTime = utils_2.msToSec(entry.startTime); + var duration = utils_2.msToSec(entry.duration); + if (transaction.op === 'navigation' && timeOrigin + startTime < transaction.startTimestamp) { + return; + } + switch (entry.entryType) { + case 'navigation': + addNavigationSpans(transaction, entry, timeOrigin); + break; + case 'mark': + case 'paint': + case 'measure': { + var startTimestamp = addMeasureSpans(transaction, entry, startTime, duration, timeOrigin); + if (tracingInitMarkStartTime === undefined && entry.name === 'sentry-tracing-init') { + tracingInitMarkStartTime = startTimestamp; + } + // capture web vitals + var firstHidden = getFirstHidden_1.getFirstHidden(); + // Only report if the page wasn't hidden prior to the web vital. + var shouldRecord = entry.startTime < firstHidden.timeStamp; + if (entry.name === 'first-paint' && shouldRecord) { + utils_1.logger.log('[Measurements] Adding FP'); + _this._measurements['fp'] = { value: entry.startTime }; + _this._measurements['mark.fp'] = { value: startTimestamp }; + } + if (entry.name === 'first-contentful-paint' && shouldRecord) { + utils_1.logger.log('[Measurements] Adding FCP'); + _this._measurements['fcp'] = { value: entry.startTime }; + _this._measurements['mark.fcp'] = { value: startTimestamp }; + } + break; + } + case 'resource': { + var resourceName = entry.name.replace(window.location.origin, ''); + var endTimestamp = addResourceSpans(transaction, entry, resourceName, startTime, duration, timeOrigin); + // We remember the entry script end time to calculate the difference to the first init mark + if (entryScriptStartTimestamp === undefined && (entryScriptSrc || '').indexOf(resourceName) > -1) { + entryScriptStartTimestamp = endTimestamp; + } + break; + } + default: + // Ignore other entry types. + } + }); + if (entryScriptStartTimestamp !== undefined && tracingInitMarkStartTime !== undefined) { + _startChild(transaction, { + description: 'evaluation', + endTimestamp: tracingInitMarkStartTime, + op: 'script', + startTimestamp: entryScriptStartTimestamp, + }); + } + this._performanceCursor = Math.max(performance.getEntries().length - 1, 0); + this._trackNavigator(transaction); + // Measurements are only available for pageload transactions + if (transaction.op === 'pageload') { + // normalize applicable web vital values to be relative to transaction.startTimestamp + var timeOrigin_1 = utils_2.msToSec(utils_1.browserPerformanceTimeOrigin); + ['fcp', 'fp', 'lcp', 'ttfb'].forEach(function (name) { + if (!_this._measurements[name] || timeOrigin_1 >= transaction.startTimestamp) { + return; + } + // The web vitals, fcp, fp, lcp, and ttfb, all measure relative to timeOrigin. + // Unfortunately, timeOrigin is not captured within the transaction span data, so these web vitals will need + // to be adjusted to be relative to transaction.startTimestamp. + var oldValue = _this._measurements[name].value; + var measurementTimestamp = timeOrigin_1 + utils_2.msToSec(oldValue); + // normalizedValue should be in milliseconds + var normalizedValue = Math.abs((measurementTimestamp - transaction.startTimestamp) * 1000); + var delta = normalizedValue - oldValue; + utils_1.logger.log("[Measurements] Normalized " + name + " from " + oldValue + " to " + normalizedValue + " (" + delta + ")"); + _this._measurements[name].value = normalizedValue; + }); + if (this._measurements['mark.fid'] && this._measurements['fid']) { + // create span for FID + _startChild(transaction, { + description: 'first input delay', + endTimestamp: this._measurements['mark.fid'].value + utils_2.msToSec(this._measurements['fid'].value), + op: 'web.vitals', + startTimestamp: this._measurements['mark.fid'].value, + }); + } + transaction.setMeasurements(this._measurements); + } + }; + /** Starts tracking the Cumulative Layout Shift on the current page. */ + MetricsInstrumentation.prototype._trackCLS = function () { + var _this = this; + getCLS_1.getCLS(function (metric) { + var entry = metric.entries.pop(); + if (!entry) { + return; + } + utils_1.logger.log('[Measurements] Adding CLS'); + _this._measurements['cls'] = { value: metric.value }; + }); + }; + /** + * Capture the information of the user agent. + */ + MetricsInstrumentation.prototype._trackNavigator = function (transaction) { + var navigator = global.navigator; + if (!navigator) { + return; + } + // track network connectivity + var connection = navigator.connection; + if (connection) { + if (connection.effectiveType) { + transaction.setTag('effectiveConnectionType', connection.effectiveType); + } + if (connection.type) { + transaction.setTag('connectionType', connection.type); + } + if (isMeasurementValue(connection.rtt)) { + this._measurements['connection.rtt'] = { value: connection.rtt }; + } + if (isMeasurementValue(connection.downlink)) { + this._measurements['connection.downlink'] = { value: connection.downlink }; + } + } + if (isMeasurementValue(navigator.deviceMemory)) { + transaction.setTag('deviceMemory', String(navigator.deviceMemory)); + } + if (isMeasurementValue(navigator.hardwareConcurrency)) { + transaction.setTag('hardwareConcurrency', String(navigator.hardwareConcurrency)); + } + }; + /** Starts tracking the Largest Contentful Paint on the current page. */ + MetricsInstrumentation.prototype._trackLCP = function () { + var _this = this; + getLCP_1.getLCP(function (metric) { + var entry = metric.entries.pop(); + if (!entry) { + return; + } + var timeOrigin = utils_2.msToSec(performance.timeOrigin); + var startTime = utils_2.msToSec(entry.startTime); + utils_1.logger.log('[Measurements] Adding LCP'); + _this._measurements['lcp'] = { value: metric.value }; + _this._measurements['mark.lcp'] = { value: timeOrigin + startTime }; + }); + }; + /** Starts tracking the First Input Delay on the current page. */ + MetricsInstrumentation.prototype._trackFID = function () { + var _this = this; + getFID_1.getFID(function (metric) { + var entry = metric.entries.pop(); + if (!entry) { + return; + } + var timeOrigin = utils_2.msToSec(performance.timeOrigin); + var startTime = utils_2.msToSec(entry.startTime); + utils_1.logger.log('[Measurements] Adding FID'); + _this._measurements['fid'] = { value: metric.value }; + _this._measurements['mark.fid'] = { value: timeOrigin + startTime }; + }); + }; + /** Starts tracking the Time to First Byte on the current page. */ + MetricsInstrumentation.prototype._trackTTFB = function () { + var _this = this; + getTTFB_1.getTTFB(function (metric) { + var _a; + var entry = metric.entries.pop(); + if (!entry) { + return; + } + utils_1.logger.log('[Measurements] Adding TTFB'); + _this._measurements['ttfb'] = { value: metric.value }; + // Capture the time spent making the request and receiving the first byte of the response + var requestTime = metric.value - (_a = metric.entries[0], (_a !== null && _a !== void 0 ? _a : entry)).requestStart; + _this._measurements['ttfb.requestTime'] = { value: requestTime }; + }); + }; + return MetricsInstrumentation; +}()); +exports.MetricsInstrumentation = MetricsInstrumentation; +/** Instrument navigation entries */ +function addNavigationSpans(transaction, entry, timeOrigin) { + addPerformanceNavigationTiming(transaction, entry, 'unloadEvent', timeOrigin); + addPerformanceNavigationTiming(transaction, entry, 'redirect', timeOrigin); + addPerformanceNavigationTiming(transaction, entry, 'domContentLoadedEvent', timeOrigin); + addPerformanceNavigationTiming(transaction, entry, 'loadEvent', timeOrigin); + addPerformanceNavigationTiming(transaction, entry, 'connect', timeOrigin); + addPerformanceNavigationTiming(transaction, entry, 'secureConnection', timeOrigin, 'connectEnd'); + addPerformanceNavigationTiming(transaction, entry, 'fetch', timeOrigin, 'domainLookupStart'); + addPerformanceNavigationTiming(transaction, entry, 'domainLookup', timeOrigin); + addRequest(transaction, entry, timeOrigin); } -sign.VERSION = VERSION; - -const getAlgorithm = signature => { - return signature.startsWith("sha256=") ? "sha256" : "sha1"; -}; - -async function verify(secret, eventPayload, signature) { - if (!secret || !eventPayload || !signature) { - throw new TypeError("[@octokit/webhooks-methods] secret, eventPayload & signature required"); - } - - const signatureBuffer = buffer.Buffer.from(signature); - const algorithm = getAlgorithm(signature); - const verificationBuffer = buffer.Buffer.from(await sign({ - secret, - algorithm - }, eventPayload)); - - if (signatureBuffer.length !== verificationBuffer.length) { - return false; - } // constant time comparison to prevent timing attachs - // https://stackoverflow.com/a/31096242/206879 - // https://en.wikipedia.org/wiki/Timing_attack - - - return crypto.timingSafeEqual(signatureBuffer, verificationBuffer); +/** Create measure related spans */ +function addMeasureSpans(transaction, entry, startTime, duration, timeOrigin) { + var measureStartTimestamp = timeOrigin + startTime; + var measureEndTimestamp = measureStartTimestamp + duration; + _startChild(transaction, { + description: entry.name, + endTimestamp: measureEndTimestamp, + op: entry.entryType, + startTimestamp: measureStartTimestamp, + }); + return measureStartTimestamp; } -verify.VERSION = VERSION; - -exports.sign = sign; -exports.verify = verify; -//# sourceMappingURL=index.js.map - - -/***/ }), - -/***/ 18513: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ value: true })); - -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - -var AggregateError = _interopDefault(__nccwpck_require__(61231)); -var webhooksMethods = __nccwpck_require__(49768); - -function ownKeys(object, enumerableOnly) { - var keys = Object.keys(object); - - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(object); - - if (enumerableOnly) { - symbols = symbols.filter(function (sym) { - return Object.getOwnPropertyDescriptor(object, sym).enumerable; - }); +/** Create resource related spans */ +function addResourceSpans(transaction, entry, resourceName, startTime, duration, timeOrigin) { + // we already instrument based on fetch and xhr, so we don't need to + // duplicate spans here. + if (entry.initiatorType === 'xmlhttprequest' || entry.initiatorType === 'fetch') { + return undefined; } - - keys.push.apply(keys, symbols); - } - - return keys; -} - -function _objectSpread2(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? arguments[i] : {}; - - if (i % 2) { - ownKeys(Object(source), true).forEach(function (key) { - _defineProperty(target, key, source[key]); - }); - } else if (Object.getOwnPropertyDescriptors) { - Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); - } else { - ownKeys(Object(source)).forEach(function (key) { - Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); - }); + var data = {}; + if ('transferSize' in entry) { + data['Transfer Size'] = entry.transferSize; } - } - - return target; -} - -function _defineProperty(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true + if ('encodedBodySize' in entry) { + data['Encoded Body Size'] = entry.encodedBodySize; + } + if ('decodedBodySize' in entry) { + data['Decoded Body Size'] = entry.decodedBodySize; + } + var startTimestamp = timeOrigin + startTime; + var endTimestamp = startTimestamp + duration; + _startChild(transaction, { + description: resourceName, + endTimestamp: endTimestamp, + op: entry.initiatorType ? "resource." + entry.initiatorType : 'resource', + startTimestamp: startTimestamp, + data: data, }); - } else { - obj[key] = value; - } - - return obj; + return endTimestamp; } - -const createLogger = logger => _objectSpread2({ - debug: () => {}, - info: () => {}, - warn: console.warn.bind(console), - error: console.error.bind(console) -}, logger); - -// THIS FILE IS GENERATED - DO NOT EDIT DIRECTLY -// make edits in scripts/generate-types.ts -const emitterEventNames = ["branch_protection_rule", "branch_protection_rule.created", "branch_protection_rule.deleted", "branch_protection_rule.edited", "check_run", "check_run.completed", "check_run.created", "check_run.requested_action", "check_run.rerequested", "check_suite", "check_suite.completed", "check_suite.requested", "check_suite.rerequested", "code_scanning_alert", "code_scanning_alert.appeared_in_branch", "code_scanning_alert.closed_by_user", "code_scanning_alert.created", "code_scanning_alert.fixed", "code_scanning_alert.reopened", "code_scanning_alert.reopened_by_user", "commit_comment", "commit_comment.created", "create", "delete", "deploy_key", "deploy_key.created", "deploy_key.deleted", "deployment", "deployment.created", "deployment_status", "deployment_status.created", "discussion", "discussion.answered", "discussion.category_changed", "discussion.created", "discussion.deleted", "discussion.edited", "discussion.labeled", "discussion.locked", "discussion.pinned", "discussion.transferred", "discussion.unanswered", "discussion.unlabeled", "discussion.unlocked", "discussion.unpinned", "discussion_comment", "discussion_comment.created", "discussion_comment.deleted", "discussion_comment.edited", "fork", "github_app_authorization", "github_app_authorization.revoked", "gollum", "installation", "installation.created", "installation.deleted", "installation.new_permissions_accepted", "installation.suspend", "installation.unsuspend", "installation_repositories", "installation_repositories.added", "installation_repositories.removed", "issue_comment", "issue_comment.created", "issue_comment.deleted", "issue_comment.edited", "issues", "issues.assigned", "issues.closed", "issues.deleted", "issues.demilestoned", "issues.edited", "issues.labeled", "issues.locked", "issues.milestoned", "issues.opened", "issues.pinned", "issues.reopened", "issues.transferred", "issues.unassigned", "issues.unlabeled", "issues.unlocked", "issues.unpinned", "label", "label.created", "label.deleted", "label.edited", "marketplace_purchase", "marketplace_purchase.cancelled", "marketplace_purchase.changed", "marketplace_purchase.pending_change", "marketplace_purchase.pending_change_cancelled", "marketplace_purchase.purchased", "member", "member.added", "member.edited", "member.removed", "membership", "membership.added", "membership.removed", "meta", "meta.deleted", "milestone", "milestone.closed", "milestone.created", "milestone.deleted", "milestone.edited", "milestone.opened", "org_block", "org_block.blocked", "org_block.unblocked", "organization", "organization.deleted", "organization.member_added", "organization.member_invited", "organization.member_removed", "organization.renamed", "package", "package.published", "package.updated", "page_build", "ping", "project", "project.closed", "project.created", "project.deleted", "project.edited", "project.reopened", "project_card", "project_card.converted", "project_card.created", "project_card.deleted", "project_card.edited", "project_card.moved", "project_column", "project_column.created", "project_column.deleted", "project_column.edited", "project_column.moved", "public", "pull_request", "pull_request.assigned", "pull_request.auto_merge_disabled", "pull_request.auto_merge_enabled", "pull_request.closed", "pull_request.converted_to_draft", "pull_request.edited", "pull_request.labeled", "pull_request.locked", "pull_request.opened", "pull_request.ready_for_review", "pull_request.reopened", "pull_request.review_request_removed", "pull_request.review_requested", "pull_request.synchronize", "pull_request.unassigned", "pull_request.unlabeled", "pull_request.unlocked", "pull_request_review", "pull_request_review.dismissed", "pull_request_review.edited", "pull_request_review.submitted", "pull_request_review_comment", "pull_request_review_comment.created", "pull_request_review_comment.deleted", "pull_request_review_comment.edited", "pull_request_review_thread", "pull_request_review_thread.resolved", "pull_request_review_thread.unresolved", "push", "release", "release.created", "release.deleted", "release.edited", "release.prereleased", "release.published", "release.released", "release.unpublished", "repository", "repository.archived", "repository.created", "repository.deleted", "repository.edited", "repository.privatized", "repository.publicized", "repository.renamed", "repository.transferred", "repository.unarchived", "repository_dispatch", "repository_import", "repository_vulnerability_alert", "repository_vulnerability_alert.create", "repository_vulnerability_alert.dismiss", "repository_vulnerability_alert.resolve", "secret_scanning_alert", "secret_scanning_alert.created", "secret_scanning_alert.reopened", "secret_scanning_alert.resolved", "security_advisory", "security_advisory.performed", "security_advisory.published", "security_advisory.updated", "security_advisory.withdrawn", "sponsorship", "sponsorship.cancelled", "sponsorship.created", "sponsorship.edited", "sponsorship.pending_cancellation", "sponsorship.pending_tier_change", "sponsorship.tier_changed", "star", "star.created", "star.deleted", "status", "team", "team.added_to_repository", "team.created", "team.deleted", "team.edited", "team.removed_from_repository", "team_add", "watch", "watch.started", "workflow_dispatch", "workflow_job", "workflow_job.completed", "workflow_job.in_progress", "workflow_job.queued", "workflow_job.started", "workflow_run", "workflow_run.completed", "workflow_run.requested"]; - -function handleEventHandlers(state, webhookName, handler) { - if (!state.hooks[webhookName]) { - state.hooks[webhookName] = []; - } - - state.hooks[webhookName].push(handler); +exports.addResourceSpans = addResourceSpans; +/** Create performance navigation related spans */ +function addPerformanceNavigationTiming(transaction, entry, event, timeOrigin, eventEnd) { + var end = eventEnd ? entry[eventEnd] : entry[event + "End"]; + var start = entry[event + "Start"]; + if (!start || !end) { + return; + } + _startChild(transaction, { + description: event, + endTimestamp: timeOrigin + utils_2.msToSec(end), + op: 'browser', + startTimestamp: timeOrigin + utils_2.msToSec(start), + }); } - -function receiverOn(state, webhookNameOrNames, handler) { - if (Array.isArray(webhookNameOrNames)) { - webhookNameOrNames.forEach(webhookName => receiverOn(state, webhookName, handler)); - return; - } - - if (["*", "error"].includes(webhookNameOrNames)) { - const webhookName = webhookNameOrNames === "*" ? "any" : webhookNameOrNames; - const message = `Using the "${webhookNameOrNames}" event with the regular Webhooks.on() function is not supported. Please use the Webhooks.on${webhookName.charAt(0).toUpperCase() + webhookName.slice(1)}() method instead`; - throw new Error(message); - } - - if (!emitterEventNames.includes(webhookNameOrNames)) { - state.log.warn(`"${webhookNameOrNames}" is not a known webhook name (https://developer.github.com/v3/activity/events/types/)`); - } - - handleEventHandlers(state, webhookNameOrNames, handler); +/** Create request and response related spans */ +function addRequest(transaction, entry, timeOrigin) { + _startChild(transaction, { + description: 'request', + endTimestamp: timeOrigin + utils_2.msToSec(entry.responseEnd), + op: 'browser', + startTimestamp: timeOrigin + utils_2.msToSec(entry.requestStart), + }); + _startChild(transaction, { + description: 'response', + endTimestamp: timeOrigin + utils_2.msToSec(entry.responseEnd), + op: 'browser', + startTimestamp: timeOrigin + utils_2.msToSec(entry.responseStart), + }); } -function receiverOnAny(state, handler) { - handleEventHandlers(state, "*", handler); +/** + * Helper function to start child on transactions. This function will make sure that the transaction will + * use the start timestamp of the created child span if it is earlier than the transactions actual + * start timestamp. + */ +function _startChild(transaction, _a) { + var startTimestamp = _a.startTimestamp, ctx = tslib_1.__rest(_a, ["startTimestamp"]); + if (startTimestamp && transaction.startTimestamp > startTimestamp) { + transaction.startTimestamp = startTimestamp; + } + return transaction.startChild(tslib_1.__assign({ startTimestamp: startTimestamp }, ctx)); } -function receiverOnError(state, handler) { - handleEventHandlers(state, "error", handler); +exports._startChild = _startChild; +/** + * Checks if a given value is a valid measurement value. + */ +function isMeasurementValue(value) { + return typeof value === 'number' && isFinite(value); } +//# sourceMappingURL=metrics.js.map -// Errors thrown or rejected Promises in "error" event handlers are not handled -// as they are in the webhook event handlers. If errors occur, we log a -// "Fatal: Error occurred" message to stdout -function wrapErrorHandler(handler, error) { - let returnValue; +/***/ }), - try { - returnValue = handler(error); - } catch (error) { - console.log('FATAL: Error occurred in "error" event handler'); - console.log(error); - } +/***/ 27854: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (returnValue && returnValue.catch) { - returnValue.catch(error => { - console.log('FATAL: Error occurred in "error" event handler'); - console.log(error); - }); - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __nccwpck_require__(4351); +var hub_1 = __nccwpck_require__(6393); +var utils_1 = __nccwpck_require__(1620); +var utils_2 = __nccwpck_require__(31386); +exports.DEFAULT_TRACING_ORIGINS = ['localhost', /^\//]; +exports.defaultRequestInstrumentationOptions = { + traceFetch: true, + traceXHR: true, + tracingOrigins: exports.DEFAULT_TRACING_ORIGINS, +}; +/** Registers span creators for xhr and fetch requests */ +function registerRequestInstrumentation(_options) { + // eslint-disable-next-line @typescript-eslint/unbound-method + var _a = tslib_1.__assign(tslib_1.__assign({}, exports.defaultRequestInstrumentationOptions), _options), traceFetch = _a.traceFetch, traceXHR = _a.traceXHR, tracingOrigins = _a.tracingOrigins, shouldCreateSpanForRequest = _a.shouldCreateSpanForRequest; + // We should cache url -> decision so that we don't have to compute + // regexp everytime we create a request. + var urlMap = {}; + var defaultShouldCreateSpan = function (url) { + if (urlMap[url]) { + return urlMap[url]; + } + var origins = tracingOrigins; + urlMap[url] = + origins.some(function (origin) { return utils_1.isMatchingPattern(url, origin); }) && + !utils_1.isMatchingPattern(url, 'sentry_key'); + return urlMap[url]; + }; + // We want that our users don't have to re-implement shouldCreateSpanForRequest themselves + // That's why we filter out already unwanted Spans from tracingOrigins + var shouldCreateSpan = defaultShouldCreateSpan; + if (typeof shouldCreateSpanForRequest === 'function') { + shouldCreateSpan = function (url) { + return defaultShouldCreateSpan(url) && shouldCreateSpanForRequest(url); + }; + } + var spans = {}; + if (traceFetch) { + utils_1.addInstrumentationHandler({ + callback: function (handlerData) { + fetchCallback(handlerData, shouldCreateSpan, spans); + }, + type: 'fetch', + }); + } + if (traceXHR) { + utils_1.addInstrumentationHandler({ + callback: function (handlerData) { + xhrCallback(handlerData, shouldCreateSpan, spans); + }, + type: 'xhr', + }); + } } - -// @ts-ignore to address #245 - -function getHooks(state, eventPayloadAction, eventName) { - const hooks = [state.hooks[eventName], state.hooks["*"]]; - - if (eventPayloadAction) { - hooks.unshift(state.hooks[`${eventName}.${eventPayloadAction}`]); - } - - return [].concat(...hooks.filter(Boolean)); -} // main handler function - - -function receiverHandle(state, event) { - const errorHandlers = state.hooks.error || []; - - if (event instanceof Error) { - const error = Object.assign(new AggregateError([event]), { - event, - errors: [event] - }); - errorHandlers.forEach(handler => wrapErrorHandler(handler, error)); - return Promise.reject(error); - } - - if (!event || !event.name) { - throw new AggregateError(["Event name not passed"]); - } - - if (!event.payload) { - throw new AggregateError(["Event payload not passed"]); - } // flatten arrays of event listeners and remove undefined values - - - const hooks = getHooks(state, "action" in event.payload ? event.payload.action : null, event.name); - - if (hooks.length === 0) { - return Promise.resolve(); - } - - const errors = []; - const promises = hooks.map(handler => { - let promise = Promise.resolve(event); - - if (state.transform) { - promise = promise.then(state.transform); +exports.registerRequestInstrumentation = registerRequestInstrumentation; +/** + * Create and track fetch request spans + */ +function fetchCallback(handlerData, shouldCreateSpan, spans) { + var _a; + var currentClientOptions = (_a = hub_1.getCurrentHub() + .getClient()) === null || _a === void 0 ? void 0 : _a.getOptions(); + if (!(currentClientOptions && utils_2.hasTracingEnabled(currentClientOptions)) || + !(handlerData.fetchData && shouldCreateSpan(handlerData.fetchData.url))) { + return; } - - return promise.then(event => { - return handler(event); - }).catch(error => errors.push(Object.assign(error, { - event - }))); - }); - return Promise.all(promises).then(() => { - if (errors.length === 0) { - return; + if (handlerData.endTimestamp && handlerData.fetchData.__span) { + var span = spans[handlerData.fetchData.__span]; + if (span) { + var response = handlerData.response; + if (response) { + // TODO (kmclb) remove this once types PR goes through + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + span.setHttpStatus(response.status); + } + span.finish(); + // eslint-disable-next-line @typescript-eslint/no-dynamic-delete + delete spans[handlerData.fetchData.__span]; + } + return; + } + var activeTransaction = utils_2.getActiveTransaction(); + if (activeTransaction) { + var span = activeTransaction.startChild({ + data: tslib_1.__assign(tslib_1.__assign({}, handlerData.fetchData), { type: 'fetch' }), + description: handlerData.fetchData.method + " " + handlerData.fetchData.url, + op: 'http', + }); + handlerData.fetchData.__span = span.spanId; + spans[span.spanId] = span; + var request = (handlerData.args[0] = handlerData.args[0]); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + var options = (handlerData.args[1] = handlerData.args[1] || {}); + var headers = options.headers; + if (utils_1.isInstanceOf(request, Request)) { + headers = request.headers; + } + if (headers) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + if (typeof headers.append === 'function') { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + headers.append('sentry-trace', span.toTraceparent()); + } + else if (Array.isArray(headers)) { + headers = tslib_1.__spread(headers, [['sentry-trace', span.toTraceparent()]]); + } + else { + headers = tslib_1.__assign(tslib_1.__assign({}, headers), { 'sentry-trace': span.toTraceparent() }); + } + } + else { + headers = { 'sentry-trace': span.toTraceparent() }; + } + options.headers = headers; } - - const error = new AggregateError(errors); - Object.assign(error, { - event, - errors - }); - errorHandlers.forEach(handler => wrapErrorHandler(handler, error)); - throw error; - }); } - -function removeListener(state, webhookNameOrNames, handler) { - if (Array.isArray(webhookNameOrNames)) { - webhookNameOrNames.forEach(webhookName => removeListener(state, webhookName, handler)); - return; - } - - if (!state.hooks[webhookNameOrNames]) { - return; - } // remove last hook that has been added, that way - // it behaves the same as removeListener - - - for (let i = state.hooks[webhookNameOrNames].length - 1; i >= 0; i--) { - if (state.hooks[webhookNameOrNames][i] === handler) { - state.hooks[webhookNameOrNames].splice(i, 1); - return; +exports.fetchCallback = fetchCallback; +/** + * Create and track xhr request spans + */ +function xhrCallback(handlerData, shouldCreateSpan, spans) { + var _a; + var currentClientOptions = (_a = hub_1.getCurrentHub() + .getClient()) === null || _a === void 0 ? void 0 : _a.getOptions(); + if (!(currentClientOptions && utils_2.hasTracingEnabled(currentClientOptions)) || + !(handlerData.xhr && handlerData.xhr.__sentry_xhr__ && shouldCreateSpan(handlerData.xhr.__sentry_xhr__.url)) || + handlerData.xhr.__sentry_own_request__) { + return; + } + var xhr = handlerData.xhr.__sentry_xhr__; + // check first if the request has finished and is tracked by an existing span which should now end + if (handlerData.endTimestamp && handlerData.xhr.__sentry_xhr_span_id__) { + var span = spans[handlerData.xhr.__sentry_xhr_span_id__]; + if (span) { + span.setHttpStatus(xhr.status_code); + span.finish(); + // eslint-disable-next-line @typescript-eslint/no-dynamic-delete + delete spans[handlerData.xhr.__sentry_xhr_span_id__]; + } + return; + } + // if not, create a new span to track it + var activeTransaction = utils_2.getActiveTransaction(); + if (activeTransaction) { + var span = activeTransaction.startChild({ + data: tslib_1.__assign(tslib_1.__assign({}, xhr.data), { type: 'xhr', method: xhr.method, url: xhr.url }), + description: xhr.method + " " + xhr.url, + op: 'http', + }); + handlerData.xhr.__sentry_xhr_span_id__ = span.spanId; + spans[handlerData.xhr.__sentry_xhr_span_id__] = span; + if (handlerData.xhr.setRequestHeader) { + try { + handlerData.xhr.setRequestHeader('sentry-trace', span.toTraceparent()); + } + catch (_) { + // Error: InvalidStateError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': The object's state must be OPENED. + } + } } - } } +exports.xhrCallback = xhrCallback; +//# sourceMappingURL=request.js.map -function createEventHandler(options) { - const state = { - hooks: {}, - log: createLogger(options && options.log) - }; - - if (options && options.transform) { - state.transform = options.transform; - } +/***/ }), - return { - on: receiverOn.bind(null, state), - onAny: receiverOnAny.bind(null, state), - onError: receiverOnError.bind(null, state), - removeListener: removeListener.bind(null, state), - receive: receiverHandle.bind(null, state) - }; -} +/***/ 40348: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +Object.defineProperty(exports, "__esModule", ({ value: true })); +var utils_1 = __nccwpck_require__(1620); +var global = utils_1.getGlobalObject(); /** - * GitHub sends its JSON with an indentation of 2 spaces and a line break at the end + * Default function implementing pageload and navigation transactions */ -function toNormalizedJsonString(payload) { - const payloadString = JSON.stringify(payload); - return payloadString.replace(/[^\\]\\u[\da-f]{4}/g, s => { - return s.substr(0, 3) + s.substr(3).toUpperCase(); - }); -} - -async function sign(secret, payload) { - return webhooksMethods.sign(secret, typeof payload === "string" ? payload : toNormalizedJsonString(payload)); -} - -async function verify(secret, payload, signature) { - return webhooksMethods.verify(secret, typeof payload === "string" ? payload : toNormalizedJsonString(payload), signature); +function defaultRoutingInstrumentation(startTransaction, startTransactionOnPageLoad, startTransactionOnLocationChange) { + if (startTransactionOnPageLoad === void 0) { startTransactionOnPageLoad = true; } + if (startTransactionOnLocationChange === void 0) { startTransactionOnLocationChange = true; } + if (!global || !global.location) { + utils_1.logger.warn('Could not initialize routing instrumentation due to invalid location'); + return; + } + var startingUrl = global.location.href; + var activeTransaction; + if (startTransactionOnPageLoad) { + activeTransaction = startTransaction({ name: global.location.pathname, op: 'pageload' }); + } + if (startTransactionOnLocationChange) { + utils_1.addInstrumentationHandler({ + callback: function (_a) { + var to = _a.to, from = _a.from; + /** + * This early return is there to account for some cases where a navigation transaction starts right after + * long-running pageload. We make sure that if `from` is undefined and a valid `startingURL` exists, we don't + * create an uneccessary navigation transaction. + * + * This was hard to duplicate, but this behavior stopped as soon as this fix was applied. This issue might also + * only be caused in certain development environments where the usage of a hot module reloader is causing + * errors. + */ + if (from === undefined && startingUrl && startingUrl.indexOf(to) !== -1) { + startingUrl = undefined; + return; + } + if (from !== to) { + startingUrl = undefined; + if (activeTransaction) { + utils_1.logger.log("[Tracing] Finishing current transaction with op: " + activeTransaction.op); + // If there's an open transaction on the scope, we need to finish it before creating an new one. + activeTransaction.finish(); + } + activeTransaction = startTransaction({ name: global.location.pathname, op: 'navigation' }); + } + }, + type: 'history', + }); + } } +exports.defaultRoutingInstrumentation = defaultRoutingInstrumentation; +//# sourceMappingURL=router.js.map -async function verifyAndReceive(state, event) { - // verify will validate that the secret is not undefined - const matchesSignature = await webhooksMethods.verify(state.secret, typeof event.payload === "object" ? toNormalizedJsonString(event.payload) : event.payload, event.signature); - - if (!matchesSignature) { - const error = new Error("[@octokit/webhooks] signature does not match event payload and secret"); - return state.eventHandler.receive(Object.assign(error, { - event, - status: 400 - })); - } - - return state.eventHandler.receive({ - id: event.id, - name: event.name, - payload: typeof event.payload === "string" ? JSON.parse(event.payload) : event.payload - }); -} +/***/ }), -const WEBHOOK_HEADERS = ["x-github-event", "x-hub-signature-256", "x-github-delivery"]; // https://docs.github.com/en/developers/webhooks-and-events/webhook-events-and-payloads#delivery-headers +/***/ 56982: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -function getMissingHeaders(request) { - return WEBHOOK_HEADERS.filter(header => !(header in request.headers)); -} +/* + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +var bindReporter_1 = __nccwpck_require__(54592); +var initMetric_1 = __nccwpck_require__(45300); +var observe_1 = __nccwpck_require__(17984); +var onHidden_1 = __nccwpck_require__(9658); +exports.getCLS = function (onReport, reportAllChanges) { + if (reportAllChanges === void 0) { reportAllChanges = false; } + var metric = initMetric_1.initMetric('CLS', 0); + var report; + var entryHandler = function (entry) { + // Only count layout shifts without recent user input. + if (!entry.hadRecentInput) { + metric.value += entry.value; + metric.entries.push(entry); + report(); + } + }; + var po = observe_1.observe('layout-shift', entryHandler); + if (po) { + report = bindReporter_1.bindReporter(onReport, metric, po, reportAllChanges); + onHidden_1.onHidden(function (_a) { + var isUnloading = _a.isUnloading; + po.takeRecords().map(entryHandler); + if (isUnloading) { + metric.isFinal = true; + } + report(); + }); + } +}; +//# sourceMappingURL=getCLS.js.map -// @ts-ignore to address #245 -function getPayload(request) { - // If request.body already exists we can stop here - // See https://github.com/octokit/webhooks.js/pull/23 - if (request.body) return Promise.resolve(request.body); - return new Promise((resolve, reject) => { - let data = ""; - request.setEncoding("utf8"); // istanbul ignore next +/***/ }), - request.on("error", error => reject(new AggregateError([error]))); - request.on("data", chunk => data += chunk); - request.on("end", () => { - try { - resolve(JSON.parse(data)); - } catch (error) { - error.message = "Invalid JSON"; - error.status = 400; - reject(new AggregateError([error])); - } - }); - }); -} +/***/ 82496: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -async function middleware(webhooks, options, request, response, next) { - let pathname; +/* + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +var bindReporter_1 = __nccwpck_require__(54592); +var getFirstHidden_1 = __nccwpck_require__(88493); +var initMetric_1 = __nccwpck_require__(45300); +var observe_1 = __nccwpck_require__(17984); +var onHidden_1 = __nccwpck_require__(9658); +exports.getFID = function (onReport) { + var metric = initMetric_1.initMetric('FID'); + var firstHidden = getFirstHidden_1.getFirstHidden(); + var entryHandler = function (entry) { + // Only report if the page wasn't hidden prior to the first input. + if (entry.startTime < firstHidden.timeStamp) { + metric.value = entry.processingStart - entry.startTime; + metric.entries.push(entry); + metric.isFinal = true; + report(); + } + }; + var po = observe_1.observe('first-input', entryHandler); + var report = bindReporter_1.bindReporter(onReport, metric, po); + if (po) { + onHidden_1.onHidden(function () { + po.takeRecords().map(entryHandler); + po.disconnect(); + }, true); + } + else { + if (window.perfMetrics && window.perfMetrics.onFirstInputDelay) { + window.perfMetrics.onFirstInputDelay(function (value, event) { + // Only report if the page wasn't hidden prior to the first input. + if (event.timeStamp < firstHidden.timeStamp) { + metric.value = value; + metric.isFinal = true; + metric.entries = [ + { + entryType: 'first-input', + name: event.type, + target: event.target, + cancelable: event.cancelable, + startTime: event.timeStamp, + processingStart: event.timeStamp + value, + }, + ]; + report(); + } + }); + } + } +}; +//# sourceMappingURL=getFID.js.map - try { - pathname = new URL(request.url, "http://localhost").pathname; - } catch (error) { - response.writeHead(422, { - "content-type": "application/json" - }); - response.end(JSON.stringify({ - error: `Request URL could not be parsed: ${request.url}` - })); - return; - } +/***/ }), - const isUnknownRoute = request.method !== "POST" || pathname !== options.path; - const isExpressMiddleware = typeof next === "function"; +/***/ 99382: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (isUnknownRoute) { - if (isExpressMiddleware) { - return next(); - } else { - return options.onUnhandledRequest(request, response); +/* + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +var bindReporter_1 = __nccwpck_require__(54592); +var getFirstHidden_1 = __nccwpck_require__(88493); +var initMetric_1 = __nccwpck_require__(45300); +var observe_1 = __nccwpck_require__(17984); +var onHidden_1 = __nccwpck_require__(9658); +var whenInput_1 = __nccwpck_require__(45181); +exports.getLCP = function (onReport, reportAllChanges) { + if (reportAllChanges === void 0) { reportAllChanges = false; } + var metric = initMetric_1.initMetric('LCP'); + var firstHidden = getFirstHidden_1.getFirstHidden(); + var report; + var entryHandler = function (entry) { + // The startTime attribute returns the value of the renderTime if it is not 0, + // and the value of the loadTime otherwise. + var value = entry.startTime; + // If the page was hidden prior to paint time of the entry, + // ignore it and mark the metric as final, otherwise add the entry. + if (value < firstHidden.timeStamp) { + metric.value = value; + metric.entries.push(entry); + } + else { + metric.isFinal = true; + } + report(); + }; + var po = observe_1.observe('largest-contentful-paint', entryHandler); + if (po) { + report = bindReporter_1.bindReporter(onReport, metric, po, reportAllChanges); + var onFinal = function () { + if (!metric.isFinal) { + po.takeRecords().map(entryHandler); + metric.isFinal = true; + report(); + } + }; + void whenInput_1.whenInput().then(onFinal); + onHidden_1.onHidden(onFinal, true); } - } - - const missingHeaders = getMissingHeaders(request).join(", "); - - if (missingHeaders) { - response.writeHead(400, { - "content-type": "application/json" - }); - response.end(JSON.stringify({ - error: `Required headers missing: ${missingHeaders}` - })); - return; - } +}; +//# sourceMappingURL=getLCP.js.map - const eventName = request.headers["x-github-event"]; - const signatureSHA256 = request.headers["x-hub-signature-256"]; - const id = request.headers["x-github-delivery"]; - options.log.debug(`${eventName} event received (id: ${id})`); // GitHub will abort the request if it does not receive a response within 10s - // See https://github.com/octokit/webhooks.js/issues/185 +/***/ }), - let didTimeout = false; - const timeout = setTimeout(() => { - didTimeout = true; - response.statusCode = 202; - response.end("still processing\n"); - }, 9000).unref(); +/***/ 55909: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - try { - const payload = await getPayload(request); - await webhooks.verifyAndReceive({ - id: id, - name: eventName, - payload: payload, - signature: signatureSHA256 +/* + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +var utils_1 = __nccwpck_require__(1620); +var initMetric_1 = __nccwpck_require__(45300); +var global = utils_1.getGlobalObject(); +var afterLoad = function (callback) { + if (document.readyState === 'complete') { + // Queue a task so the callback runs after `loadEventEnd`. + setTimeout(callback, 0); + } + else { + // Use `pageshow` so the callback runs after `loadEventEnd`. + addEventListener('pageshow', callback); + } +}; +var getNavigationEntryFromPerformanceTiming = function () { + // Really annoying that TypeScript errors when using `PerformanceTiming`. + // eslint-disable-next-line deprecation/deprecation + var timing = global.performance.timing; + var navigationEntry = { + entryType: 'navigation', + startTime: 0, + }; + for (var key in timing) { + if (key !== 'navigationStart' && key !== 'toJSON') { + navigationEntry[key] = Math.max(timing[key] - timing.navigationStart, 0); + } + } + return navigationEntry; +}; +exports.getTTFB = function (onReport) { + var metric = initMetric_1.initMetric('TTFB'); + afterLoad(function () { + try { + // Use the NavigationTiming L2 entry if available. + var navigationEntry = global.performance.getEntriesByType('navigation')[0] || getNavigationEntryFromPerformanceTiming(); + metric.value = metric.delta = navigationEntry.responseStart; + metric.entries = [navigationEntry]; + onReport(metric); + } + catch (error) { + // Do nothing. + } }); - clearTimeout(timeout); - if (didTimeout) return; - response.end("ok\n"); - } catch (error) { - clearTimeout(timeout); - if (didTimeout) return; - const statusCode = Array.from(error)[0].status; - response.statusCode = typeof statusCode !== "undefined" ? statusCode : 500; - response.end(String(error)); - } -} - -function onUnhandledRequestDefault(request, response) { - response.writeHead(404, { - "content-type": "application/json" - }); - response.end(JSON.stringify({ - error: `Unknown route: ${request.method} ${request.url}` - })); -} +}; +//# sourceMappingURL=getTTFB.js.map -function createNodeMiddleware(webhooks, { - path = "/api/github/webhooks", - onUnhandledRequest = onUnhandledRequestDefault, - log = createLogger() -} = {}) { - return middleware.bind(null, webhooks, { - path, - onUnhandledRequest, - log - }); -} +/***/ }), -class Webhooks { - constructor(options) { - if (!options || !options.secret) { - throw new Error("[@octokit/webhooks] options.secret required"); - } +/***/ 54592: +/***/ ((__unused_webpack_module, exports) => { - const state = { - eventHandler: createEventHandler(options), - secret: options.secret, - hooks: {}, - log: createLogger(options.log) +/* + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.bindReporter = function (callback, metric, po, observeAllUpdates) { + var prevValue; + return function () { + if (po && metric.isFinal) { + po.disconnect(); + } + if (metric.value >= 0) { + if (observeAllUpdates || metric.isFinal || document.visibilityState === 'hidden') { + metric.delta = metric.value - (prevValue || 0); + // Report the metric if there's a non-zero delta, if the metric is + // final, or if no previous value exists (which can happen in the case + // of the document becoming hidden when the metric value is 0). + // See: https://github.com/GoogleChrome/web-vitals/issues/14 + if (metric.delta || metric.isFinal || prevValue === undefined) { + callback(metric); + prevValue = metric.value; + } + } + } }; - this.sign = sign.bind(null, options.secret); - this.verify = verify.bind(null, options.secret); - this.on = state.eventHandler.on; - this.onAny = state.eventHandler.onAny; - this.onError = state.eventHandler.onError; - this.removeListener = state.eventHandler.removeListener; - this.receive = state.eventHandler.receive; - this.verifyAndReceive = verifyAndReceive.bind(null, state); - } +}; +//# sourceMappingURL=bindReporter.js.map -} +/***/ }), -exports.Webhooks = Webhooks; -exports.createEventHandler = createEventHandler; -exports.createNodeMiddleware = createNodeMiddleware; -exports.emitterEventNames = emitterEventNames; -//# sourceMappingURL=index.js.map +/***/ 70093: +/***/ ((__unused_webpack_module, exports) => { +/* + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +/** + * Performantly generate a unique, 27-char string by combining the current + * timestamp with a 13-digit random number. + * @return {string} + */ +exports.generateUniqueID = function () { + return Date.now() + "-" + (Math.floor(Math.random() * (9e12 - 1)) + 1e12); +}; +//# sourceMappingURL=generateUniqueID.js.map /***/ }), -/***/ 93159: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 88493: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -const ProbotExports = __nccwpck_require__(93181); -const pino = __nccwpck_require__(79608); +/* + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +var onHidden_1 = __nccwpck_require__(9658); +var firstHiddenTime; +exports.getFirstHidden = function () { + if (firstHiddenTime === undefined) { + // If the document is hidden when this code runs, assume it was hidden + // since navigation start. This isn't a perfect heuristic, but it's the + // best we can do until an API is available to support querying past + // visibilityState. + firstHiddenTime = document.visibilityState === 'hidden' ? 0 : Infinity; + // Update the time if/when the document becomes hidden. + onHidden_1.onHidden(function (_a) { + var timeStamp = _a.timeStamp; + return (firstHiddenTime = timeStamp); + }, true); + } + return { + get timeStamp() { + return firstHiddenTime; + }, + }; +}; +//# sourceMappingURL=getFirstHidden.js.map -const { transport } = __nccwpck_require__(96645); +/***/ }), -module.exports = { ...ProbotExports, run }; +/***/ 45300: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -async function run(app) { - const log = pino({}, transport); +/* + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +var generateUniqueID_1 = __nccwpck_require__(70093); +exports.initMetric = function (name, value) { + if (value === void 0) { value = -1; } + return { + name: name, + value: value, + delta: 0, + entries: [], + id: generateUniqueID_1.generateUniqueID(), + isFinal: false, + }; +}; +//# sourceMappingURL=initMetric.js.map - const githubToken = - process.env.GITHUB_TOKEN || - process.env.INPUT_GITHUB_TOKEN || - process.env.INPUT_TOKEN; +/***/ }), - if (!githubToken) { - log.error( - "[probot/adapter-github-actions] a token must be passed as `env.GITHUB_TOKEN` or `with.GITHUB_TOKEN` or `with.token`, see https://github.com/probot/adapter-github-actions#usage" - ); +/***/ 17984: +/***/ ((__unused_webpack_module, exports) => { + +/* + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +/** + * Takes a performance entry type and a callback function, and creates a + * `PerformanceObserver` instance that will observe the specified entry type + * with buffering enabled and call the callback _for each entry_. + * + * This function also feature-detects entry support and wraps the logic in a + * try/catch to avoid errors in unsupporting browsers. + */ +exports.observe = function (type, callback) { + try { + if (PerformanceObserver.supportedEntryTypes.includes(type)) { + var po = new PerformanceObserver(function (l) { return l.getEntries().map(callback); }); + po.observe({ type: type, buffered: true }); + return po; + } + } + catch (e) { + // Do nothing. + } return; - } +}; +//# sourceMappingURL=observe.js.map - const envVariablesMissing = [ - "GITHUB_RUN_ID", - "GITHUB_EVENT_NAME", - "GITHUB_EVENT_PATH", - ].filter((name) => !process.env[name]); +/***/ }), - if (envVariablesMissing.length) { - log.error( - `[probot/adapter-github-actions] GitHub Action default environment variables missing: ${envVariablesMissing.join( - ", " - )}. See https://docs.github.com/en/free-pro-team@latest/actions/reference/environment-variables#default-environment-variables` - ); - return; - } +/***/ 9658: +/***/ ((__unused_webpack_module, exports) => { - const probot = ProbotExports.createProbot({ - overrides: { - githubToken, - log, - }, - }); +/* + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +var isUnloading = false; +var listenersAdded = false; +var onPageHide = function (event) { + isUnloading = !event.persisted; +}; +var addListeners = function () { + addEventListener('pagehide', onPageHide); + // `beforeunload` is needed to fix this bug: + // https://bugs.chromium.org/p/chromium/issues/detail?id=987409 + // eslint-disable-next-line @typescript-eslint/no-empty-function + addEventListener('beforeunload', function () { }); +}; +exports.onHidden = function (cb, once) { + if (once === void 0) { once = false; } + if (!listenersAdded) { + addListeners(); + listenersAdded = true; + } + addEventListener('visibilitychange', function (_a) { + var timeStamp = _a.timeStamp; + if (document.visibilityState === 'hidden') { + cb({ timeStamp: timeStamp, isUnloading: isUnloading }); + } + }, { capture: true, once: once }); +}; +//# sourceMappingURL=onHidden.js.map - await probot.load(app); +/***/ }), - return probot - .receive({ - id: process.env.GITHUB_RUN_ID, - name: process.env.GITHUB_EVENT_NAME, - payload: require(process.env.GITHUB_EVENT_PATH), - }) - .catch((error) => { - probot.log.error(error); - }); -} +/***/ 45181: +/***/ ((__unused_webpack_module, exports) => { +/* + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +var inputPromise; +exports.whenInput = function () { + if (!inputPromise) { + inputPromise = new Promise(function (r) { + return ['scroll', 'keydown', 'pointerdown'].map(function (type) { + addEventListener(type, r, { + once: true, + passive: true, + capture: true, + }); + }); + }); + } + return inputPromise; +}; +//# sourceMappingURL=whenInput.js.map /***/ }), -/***/ 18915: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; +/***/ 47906: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; -}; Object.defineProperty(exports, "__esModule", ({ value: true })); -const os = __importStar(__nccwpck_require__(22037)); -const utils_1 = __nccwpck_require__(53322); +var utils_1 = __nccwpck_require__(1620); +var spanstatus_1 = __nccwpck_require__(58522); +var utils_2 = __nccwpck_require__(31386); /** - * Commands - * - * Command Format: - * ::name key=value,key=value::message - * - * Examples: - * ::warning::This is the message - * ::set-env name=MY_VAR::some value + * Configures global error listeners */ -function issueCommand(command, properties, message) { - const cmd = new Command(command, properties, message); - process.stdout.write(cmd.toString() + os.EOL); -} -exports.issueCommand = issueCommand; -function issue(name, message = '') { - issueCommand(name, {}, message); +function registerErrorInstrumentation() { + utils_1.addInstrumentationHandler({ + callback: errorCallback, + type: 'error', + }); + utils_1.addInstrumentationHandler({ + callback: errorCallback, + type: 'unhandledrejection', + }); } -exports.issue = issue; -const CMD_STRING = '::'; -class Command { - constructor(command, properties, message) { - if (!command) { - command = 'missing.command'; - } - this.command = command; - this.properties = properties; - this.message = message; - } - toString() { - let cmdStr = CMD_STRING + this.command; - if (this.properties && Object.keys(this.properties).length > 0) { - cmdStr += ' '; - let first = true; - for (const key in this.properties) { - if (this.properties.hasOwnProperty(key)) { - const val = this.properties[key]; - if (val) { - if (first) { - first = false; - } - else { - cmdStr += ','; - } - cmdStr += `${key}=${escapeProperty(val)}`; - } - } - } - } - cmdStr += `${CMD_STRING}${escapeData(this.message)}`; - return cmdStr; +exports.registerErrorInstrumentation = registerErrorInstrumentation; +/** + * If an error or unhandled promise occurs, we mark the active transaction as failed + */ +function errorCallback() { + var activeTransaction = utils_2.getActiveTransaction(); + if (activeTransaction) { + utils_1.logger.log("[Tracing] Transaction: " + spanstatus_1.SpanStatus.InternalError + " -> Global error occured"); + activeTransaction.setStatus(spanstatus_1.SpanStatus.InternalError); } } -function escapeData(s) { - return utils_1.toCommandValue(s) - .replace(/%/g, '%25') - .replace(/\r/g, '%0D') - .replace(/\n/g, '%0A'); -} -function escapeProperty(s) { - return utils_1.toCommandValue(s) - .replace(/%/g, '%25') - .replace(/\r/g, '%0D') - .replace(/\n/g, '%0A') - .replace(/:/g, '%3A') - .replace(/,/g, '%2C'); -} -//# sourceMappingURL=command.js.map +//# sourceMappingURL=errors.js.map /***/ }), -/***/ 68648: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; +/***/ 31409: +/***/ ((module, exports, __nccwpck_require__) => { -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 __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; -}; +/* module decorator */ module = __nccwpck_require__.nmd(module); Object.defineProperty(exports, "__esModule", ({ value: true })); -const command_1 = __nccwpck_require__(18915); -const file_command_1 = __nccwpck_require__(20); -const utils_1 = __nccwpck_require__(53322); -const os = __importStar(__nccwpck_require__(22037)); -const path = __importStar(__nccwpck_require__(71017)); -/** - * The code to exit an action - */ -var ExitCode; -(function (ExitCode) { - /** - * A code indicating that the action was successful - */ - ExitCode[ExitCode["Success"] = 0] = "Success"; - /** - * A code indicating that the action was a failure - */ - ExitCode[ExitCode["Failure"] = 1] = "Failure"; -})(ExitCode = exports.ExitCode || (exports.ExitCode = {})); -//----------------------------------------------------------------------- -// Variables -//----------------------------------------------------------------------- +var tslib_1 = __nccwpck_require__(4351); +var hub_1 = __nccwpck_require__(6393); +var types_1 = __nccwpck_require__(83789); +var utils_1 = __nccwpck_require__(1620); +var errors_1 = __nccwpck_require__(47906); +var idletransaction_1 = __nccwpck_require__(2171); +var transaction_1 = __nccwpck_require__(8186); +var utils_2 = __nccwpck_require__(31386); +/** Returns all trace headers that are currently on the top scope. */ +function traceHeaders() { + var scope = this.getScope(); + if (scope) { + var span = scope.getSpan(); + if (span) { + return { + 'sentry-trace': span.toTraceparent(), + }; + } + } + return {}; +} /** - * Sets env variable for this action and future actions in the job - * @param name the name of the variable to set - * @param val the value of the variable. Non-string values will be converted to a string via JSON.stringify + * Makes a sampling decision for the given transaction and stores it on the transaction. + * + * Called every time a transaction is created. Only transactions which emerge with a `sampled` value of `true` will be + * sent to Sentry. + * + * @param hub: The hub off of which to read config options + * @param transaction: The transaction needing a sampling decision + * @param samplingContext: Default and user-provided data which may be used to help make the decision + * + * @returns The given transaction with its `sampled` value set */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function exportVariable(name, val) { - const convertedVal = utils_1.toCommandValue(val); - process.env[name] = convertedVal; - const filePath = process.env['GITHUB_ENV'] || ''; - if (filePath) { - const delimiter = '_GitHubActionsFileCommandDelimeter_'; - const commandValue = `${name}<<${delimiter}${os.EOL}${convertedVal}${os.EOL}${delimiter}`; - file_command_1.issueCommand('ENV', commandValue); +function sample(hub, transaction, samplingContext) { + var _a; + var client = hub.getClient(); + var options = (client && client.getOptions()) || {}; + // nothing to do if there's no client or if tracing is disabled + if (!client || !utils_2.hasTracingEnabled(options)) { + transaction.sampled = false; + return transaction; + } + // if the user has forced a sampling decision by passing a `sampled` value in their transaction context, go with that + if (transaction.sampled !== undefined) { + transaction.tags = tslib_1.__assign(tslib_1.__assign({}, transaction.tags), { __sentry_samplingMethod: types_1.TransactionSamplingMethod.Explicit }); + return transaction; + } + // we would have bailed already if neither `tracesSampler` nor `tracesSampleRate` were defined, so one of these should + // work; prefer the hook if so + var sampleRate; + if (typeof options.tracesSampler === 'function') { + sampleRate = options.tracesSampler(samplingContext); + // cast the rate to a number first in case it's a boolean + transaction.tags = tslib_1.__assign(tslib_1.__assign({}, transaction.tags), { __sentry_samplingMethod: types_1.TransactionSamplingMethod.Sampler, + // TODO kmclb - once tag types are loosened, don't need to cast to string here + __sentry_sampleRate: String(Number(sampleRate)) }); + } + else if (samplingContext.parentSampled !== undefined) { + sampleRate = samplingContext.parentSampled; + transaction.tags = tslib_1.__assign(tslib_1.__assign({}, transaction.tags), { __sentry_samplingMethod: types_1.TransactionSamplingMethod.Inheritance }); } else { - command_1.issueCommand('set-env', { name }, convertedVal); + sampleRate = options.tracesSampleRate; + // cast the rate to a number first in case it's a boolean + transaction.tags = tslib_1.__assign(tslib_1.__assign({}, transaction.tags), { __sentry_samplingMethod: types_1.TransactionSamplingMethod.Rate, + // TODO kmclb - once tag types are loosened, don't need to cast to string here + __sentry_sampleRate: String(Number(sampleRate)) }); } + // Since this is coming from the user (or from a function provided by the user), who knows what we might get. (The + // only valid values are booleans or numbers between 0 and 1.) + if (!isValidSampleRate(sampleRate)) { + utils_1.logger.warn("[Tracing] Discarding transaction because of invalid sample rate."); + transaction.sampled = false; + return transaction; + } + // if the function returned 0 (or false), or if `tracesSampleRate` is 0, it's a sign the transaction should be dropped + if (!sampleRate) { + utils_1.logger.log("[Tracing] Discarding transaction because " + (typeof options.tracesSampler === 'function' + ? 'tracesSampler returned 0 or false' + : 'a negative sampling decision was inherited or tracesSampleRate is set to 0')); + transaction.sampled = false; + return transaction; + } + // Now we roll the dice. Math.random is inclusive of 0, but not of 1, so strict < is safe here. In case sampleRate is + // a boolean, the < comparison will cause it to be automatically cast to 1 if it's true and 0 if it's false. + transaction.sampled = Math.random() < sampleRate; + // if we're not going to keep it, we're done + if (!transaction.sampled) { + utils_1.logger.log("[Tracing] Discarding transaction because it's not included in the random sample (sampling rate = " + Number(sampleRate) + ")"); + return transaction; + } + // at this point we know we're keeping the transaction, whether because of an inherited decision or because it got + // lucky with the dice roll + transaction.initSpanRecorder((_a = options._experiments) === null || _a === void 0 ? void 0 : _a.maxSpans); + utils_1.logger.log("[Tracing] starting " + transaction.op + " transaction - " + transaction.name); + return transaction; } -exports.exportVariable = exportVariable; -/** - * Registers a secret which will get masked from logs - * @param secret value of the secret - */ -function setSecret(secret) { - command_1.issueCommand('add-mask', {}, secret); -} -exports.setSecret = setSecret; /** - * Prepends inputPath to the PATH (for this action and future actions) - * @param inputPath + * Gets the correct context to pass to the tracesSampler, based on the environment (i.e., which SDK is being used) + * + * @returns The default sample context */ -function addPath(inputPath) { - const filePath = process.env['GITHUB_PATH'] || ''; - if (filePath) { - file_command_1.issueCommand('PATH', inputPath); +function getDefaultSamplingContext(transactionContext) { + // promote parent sampling decision (if any) for easy access + var parentSampled = transactionContext.parentSampled; + var defaultSamplingContext = { transactionContext: transactionContext, parentSampled: parentSampled }; + if (utils_1.isNodeEnv()) { + var domain = hub_1.getActiveDomain(); + if (domain) { + // for all node servers that we currently support, we store the incoming request object (which is an instance of + // http.IncomingMessage) on the domain + // the domain members are stored as an array, so our only way to find the request is to iterate through the array + // and compare types + var nodeHttpModule = utils_1.dynamicRequire(module, 'http'); + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + var requestType_1 = nodeHttpModule.IncomingMessage; + var request = domain.members.find(function (member) { return utils_1.isInstanceOf(member, requestType_1); }); + if (request) { + defaultSamplingContext.request = utils_1.extractNodeRequestData(request); + } + } } + // we must be in browser-js (or some derivative thereof) else { - command_1.issueCommand('add-path', {}, inputPath); + // we use `getGlobalObject()` rather than `window` since service workers also have a `location` property on `self` + var globalObject = utils_1.getGlobalObject(); + if ('location' in globalObject) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any + defaultSamplingContext.location = tslib_1.__assign({}, globalObject.location); + } } - process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`; + return defaultSamplingContext; } -exports.addPath = addPath; /** - * Gets the value of an input. The value is also trimmed. - * - * @param name name of the input to get - * @param options optional. See InputOptions. - * @returns string + * Checks the given sample rate to make sure it is valid type and value (a boolean, or a number between 0 and 1). */ -function getInput(name, options) { - const val = process.env[`INPUT_${name.replace(/ /g, '_').toUpperCase()}`] || ''; - if (options && options.required && !val) { - throw new Error(`Input required and not supplied: ${name}`); +function isValidSampleRate(rate) { + // we need to check NaN explicitly because it's of type 'number' and therefore wouldn't get caught by this typecheck + // eslint-disable-next-line @typescript-eslint/no-explicit-any + if (isNaN(rate) || !(typeof rate === 'number' || typeof rate === 'boolean')) { + utils_1.logger.warn("[Tracing] Given sample rate is invalid. Sample rate must be a boolean or a number between 0 and 1. Got " + JSON.stringify(rate) + " of type " + JSON.stringify(typeof rate) + "."); + return false; } - return val.trim(); + // in case sampleRate is a boolean, it will get automatically cast to 1 if it's true and 0 if it's false + if (rate < 0 || rate > 1) { + utils_1.logger.warn("[Tracing] Given sample rate is invalid. Sample rate must be between 0 and 1. Got " + rate + "."); + return false; + } + return true; } -exports.getInput = getInput; /** - * Sets the value of an output. + * Creates a new transaction and adds a sampling decision if it doesn't yet have one. * - * @param name name of the output to set - * @param value value to store. Non-string values will be converted to a string via JSON.stringify - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function setOutput(name, value) { - command_1.issueCommand('set-output', { name }, value); -} -exports.setOutput = setOutput; -/** - * Enables or disables the echoing of commands into stdout for the rest of the step. - * Echoing is disabled by default if ACTIONS_STEP_DEBUG is not set. + * The Hub.startTransaction method delegates to this method to do its work, passing the Hub instance in as `this`, as if + * it had been called on the hub directly. Exists as a separate function so that it can be injected into the class as an + * "extension method." * + * @param this: The Hub starting the transaction + * @param transactionContext: Data used to configure the transaction + * @param CustomSamplingContext: Optional data to be provided to the `tracesSampler` function (if any) + * + * @returns The new transaction + * + * @see {@link Hub.startTransaction} */ -function setCommandEcho(enabled) { - command_1.issue('echo', enabled ? 'on' : 'off'); -} -exports.setCommandEcho = setCommandEcho; -//----------------------------------------------------------------------- -// Results -//----------------------------------------------------------------------- -/** - * Sets the action status to failed. - * When the action exits it will be with an exit code of 1 - * @param message add error issue message - */ -function setFailed(message) { - process.exitCode = ExitCode.Failure; - error(message); -} -exports.setFailed = setFailed; -//----------------------------------------------------------------------- -// Logging Commands -//----------------------------------------------------------------------- -/** - * Gets whether Actions Step Debug is on or not - */ -function isDebug() { - return process.env['RUNNER_DEBUG'] === '1'; -} -exports.isDebug = isDebug; -/** - * Writes debug message to user log - * @param message debug message - */ -function debug(message) { - command_1.issueCommand('debug', {}, message); -} -exports.debug = debug; -/** - * Adds an error issue - * @param message error issue message. Errors will be converted to string via toString() - */ -function error(message) { - command_1.issue('error', message instanceof Error ? message.toString() : message); +function _startTransaction(transactionContext, customSamplingContext) { + var transaction = new transaction_1.Transaction(transactionContext, this); + return sample(this, transaction, tslib_1.__assign(tslib_1.__assign({}, getDefaultSamplingContext(transactionContext)), customSamplingContext)); } -exports.error = error; /** - * Adds an warning issue - * @param message warning issue message. Errors will be converted to string via toString() + * Create new idle transaction. */ -function warning(message) { - command_1.issue('warning', message instanceof Error ? message.toString() : message); +function startIdleTransaction(hub, transactionContext, idleTimeout, onScope) { + var transaction = new idletransaction_1.IdleTransaction(transactionContext, hub, idleTimeout, onScope); + return sample(hub, transaction, getDefaultSamplingContext(transactionContext)); } -exports.warning = warning; +exports.startIdleTransaction = startIdleTransaction; /** - * Writes info to log with console.log. - * @param message info message + * @private */ -function info(message) { - process.stdout.write(message + os.EOL); +function _addTracingExtensions() { + var carrier = hub_1.getMainCarrier(); + if (carrier.__SENTRY__) { + carrier.__SENTRY__.extensions = carrier.__SENTRY__.extensions || {}; + if (!carrier.__SENTRY__.extensions.startTransaction) { + carrier.__SENTRY__.extensions.startTransaction = _startTransaction; + } + if (!carrier.__SENTRY__.extensions.traceHeaders) { + carrier.__SENTRY__.extensions.traceHeaders = traceHeaders; + } + } } -exports.info = info; +exports._addTracingExtensions = _addTracingExtensions; /** - * Begin an output group. - * - * Output until the next `groupEnd` will be foldable in this group - * - * @param name The name of the output group + * This patches the global object and injects the Tracing extensions methods */ -function startGroup(name) { - command_1.issue('group', name); +function addExtensionMethods() { + _addTracingExtensions(); + // If an error happens globally, we should make sure transaction status is set to error. + errors_1.registerErrorInstrumentation(); } -exports.startGroup = startGroup; +exports.addExtensionMethods = addExtensionMethods; +//# sourceMappingURL=hubextensions.js.map + +/***/ }), + +/***/ 2171: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __nccwpck_require__(4351); +var utils_1 = __nccwpck_require__(1620); +var span_1 = __nccwpck_require__(64655); +var spanstatus_1 = __nccwpck_require__(58522); +var transaction_1 = __nccwpck_require__(8186); +exports.DEFAULT_IDLE_TIMEOUT = 1000; /** - * End an output group. + * @inheritDoc */ -function endGroup() { - command_1.issue('endgroup'); -} -exports.endGroup = endGroup; +var IdleTransactionSpanRecorder = /** @class */ (function (_super) { + tslib_1.__extends(IdleTransactionSpanRecorder, _super); + function IdleTransactionSpanRecorder(_pushActivity, _popActivity, transactionSpanId, maxlen) { + if (transactionSpanId === void 0) { transactionSpanId = ''; } + var _this = _super.call(this, maxlen) || this; + _this._pushActivity = _pushActivity; + _this._popActivity = _popActivity; + _this.transactionSpanId = transactionSpanId; + return _this; + } + /** + * @inheritDoc + */ + IdleTransactionSpanRecorder.prototype.add = function (span) { + var _this = this; + // We should make sure we do not push and pop activities for + // the transaction that this span recorder belongs to. + if (span.spanId !== this.transactionSpanId) { + // We patch span.finish() to pop an activity after setting an endTimestamp. + span.finish = function (endTimestamp) { + span.endTimestamp = typeof endTimestamp === 'number' ? endTimestamp : utils_1.timestampWithMs(); + _this._popActivity(span.spanId); + }; + // We should only push new activities if the span does not have an end timestamp. + if (span.endTimestamp === undefined) { + this._pushActivity(span.spanId); + } + } + _super.prototype.add.call(this, span); + }; + return IdleTransactionSpanRecorder; +}(span_1.SpanRecorder)); +exports.IdleTransactionSpanRecorder = IdleTransactionSpanRecorder; /** - * Wrap an asynchronous function call in a group. - * - * Returns the same type as the function itself. - * - * @param name The name of the group - * @param fn The function to wrap in the group + * An IdleTransaction is a transaction that automatically finishes. It does this by tracking child spans as activities. + * You can have multiple IdleTransactions active, but if the `onScope` option is specified, the idle transaction will + * put itself on the scope on creation. */ -function group(name, fn) { - return __awaiter(this, void 0, void 0, function* () { - startGroup(name); - let result; - try { - result = yield fn(); +var IdleTransaction = /** @class */ (function (_super) { + tslib_1.__extends(IdleTransaction, _super); + function IdleTransaction(transactionContext, _idleHub, + // The time to wait in ms until the idle transaction will be finished. Default: 1000 + _idleTimeout, + // If an idle transaction should be put itself on and off the scope automatically. + _onScope) { + if (_idleTimeout === void 0) { _idleTimeout = exports.DEFAULT_IDLE_TIMEOUT; } + if (_onScope === void 0) { _onScope = false; } + var _this = _super.call(this, transactionContext, _idleHub) || this; + _this._idleHub = _idleHub; + _this._idleTimeout = _idleTimeout; + _this._onScope = _onScope; + // Activities store a list of active spans + _this.activities = {}; + // Stores reference to the timeout that calls _beat(). + _this._heartbeatTimer = 0; + // Amount of times heartbeat has counted. Will cause transaction to finish after 3 beats. + _this._heartbeatCounter = 0; + // We should not use heartbeat if we finished a transaction + _this._finished = false; + _this._beforeFinishCallbacks = []; + if (_idleHub && _onScope) { + // There should only be one active transaction on the scope + clearActiveTransaction(_idleHub); + // We set the transaction here on the scope so error events pick up the trace + // context and attach it to the error. + utils_1.logger.log("Setting idle transaction on scope. Span ID: " + _this.spanId); + _idleHub.configureScope(function (scope) { return scope.setSpan(_this); }); } - finally { - endGroup(); + return _this; + } + /** {@inheritDoc} */ + IdleTransaction.prototype.finish = function (endTimestamp) { + var e_1, _a; + var _this = this; + if (endTimestamp === void 0) { endTimestamp = utils_1.timestampWithMs(); } + this._finished = true; + this.activities = {}; + if (this.spanRecorder) { + utils_1.logger.log('[Tracing] finishing IdleTransaction', new Date(endTimestamp * 1000).toISOString(), this.op); + try { + for (var _b = tslib_1.__values(this._beforeFinishCallbacks), _c = _b.next(); !_c.done; _c = _b.next()) { + var callback = _c.value; + callback(this, endTimestamp); + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (_c && !_c.done && (_a = _b.return)) _a.call(_b); + } + finally { if (e_1) throw e_1.error; } + } + this.spanRecorder.spans = this.spanRecorder.spans.filter(function (span) { + // If we are dealing with the transaction itself, we just return it + if (span.spanId === _this.spanId) { + return true; + } + // We cancel all pending spans with status "cancelled" to indicate the idle transaction was finished early + if (!span.endTimestamp) { + span.endTimestamp = endTimestamp; + span.setStatus(spanstatus_1.SpanStatus.Cancelled); + utils_1.logger.log('[Tracing] cancelling span since transaction ended early', JSON.stringify(span, undefined, 2)); + } + var keepSpan = span.startTimestamp < endTimestamp; + if (!keepSpan) { + utils_1.logger.log('[Tracing] discarding Span since it happened after Transaction was finished', JSON.stringify(span, undefined, 2)); + } + return keepSpan; + }); + // this._onScope is true if the transaction was previously on the scope. + if (this._onScope) { + clearActiveTransaction(this._idleHub); + } + utils_1.logger.log('[Tracing] flushing IdleTransaction'); } - return result; - }); -} -exports.group = group; -//----------------------------------------------------------------------- -// Wrapper action state -//----------------------------------------------------------------------- -/** - * Saves state for current action, the state can only be retrieved by this action's post job execution. - * - * @param name name of the state to store - * @param value value to store. Non-string values will be converted to a string via JSON.stringify - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function saveState(name, value) { - command_1.issueCommand('save-state', { name }, value); -} -exports.saveState = saveState; + else { + utils_1.logger.log('[Tracing] No active IdleTransaction'); + } + return _super.prototype.finish.call(this, endTimestamp); + }; + /** + * Register a callback function that gets excecuted before the transaction finishes. + * Useful for cleanup or if you want to add any additional spans based on current context. + * + * This is exposed because users have no other way of running something before an idle transaction + * finishes. + */ + IdleTransaction.prototype.registerBeforeFinishCallback = function (callback) { + this._beforeFinishCallbacks.push(callback); + }; + /** + * @inheritDoc + */ + IdleTransaction.prototype.initSpanRecorder = function (maxlen) { + var _this = this; + if (!this.spanRecorder) { + this._initTimeout = setTimeout(function () { + if (!_this._finished) { + _this.finish(); + } + }, this._idleTimeout); + var pushActivity = function (id) { + if (_this._finished) { + return; + } + _this._pushActivity(id); + }; + var popActivity = function (id) { + if (_this._finished) { + return; + } + _this._popActivity(id); + }; + this.spanRecorder = new IdleTransactionSpanRecorder(pushActivity, popActivity, this.spanId, maxlen); + // Start heartbeat so that transactions do not run forever. + utils_1.logger.log('Starting heartbeat'); + this._pingHeartbeat(); + } + this.spanRecorder.add(this); + }; + /** + * Start tracking a specific activity. + * @param spanId The span id that represents the activity + */ + IdleTransaction.prototype._pushActivity = function (spanId) { + if (this._initTimeout) { + clearTimeout(this._initTimeout); + this._initTimeout = undefined; + } + utils_1.logger.log("[Tracing] pushActivity: " + spanId); + this.activities[spanId] = true; + utils_1.logger.log('[Tracing] new activities count', Object.keys(this.activities).length); + }; + /** + * Remove an activity from usage + * @param spanId The span id that represents the activity + */ + IdleTransaction.prototype._popActivity = function (spanId) { + var _this = this; + if (this.activities[spanId]) { + utils_1.logger.log("[Tracing] popActivity " + spanId); + // eslint-disable-next-line @typescript-eslint/no-dynamic-delete + delete this.activities[spanId]; + utils_1.logger.log('[Tracing] new activities count', Object.keys(this.activities).length); + } + if (Object.keys(this.activities).length === 0) { + var timeout = this._idleTimeout; + // We need to add the timeout here to have the real endtimestamp of the transaction + // Remember timestampWithMs is in seconds, timeout is in ms + var end_1 = utils_1.timestampWithMs() + timeout / 1000; + setTimeout(function () { + if (!_this._finished) { + _this.finish(end_1); + } + }, timeout); + } + }; + /** + * Checks when entries of this.activities are not changing for 3 beats. + * If this occurs we finish the transaction. + */ + IdleTransaction.prototype._beat = function () { + clearTimeout(this._heartbeatTimer); + // We should not be running heartbeat if the idle transaction is finished. + if (this._finished) { + return; + } + var keys = Object.keys(this.activities); + var heartbeatString = keys.length ? keys.reduce(function (prev, current) { return prev + current; }) : ''; + if (heartbeatString === this._prevHeartbeatString) { + this._heartbeatCounter += 1; + } + else { + this._heartbeatCounter = 1; + } + this._prevHeartbeatString = heartbeatString; + if (this._heartbeatCounter >= 3) { + utils_1.logger.log("[Tracing] Transaction finished because of no change for 3 heart beats"); + this.setStatus(spanstatus_1.SpanStatus.DeadlineExceeded); + this.setTag('heartbeat', 'failed'); + this.finish(); + } + else { + this._pingHeartbeat(); + } + }; + /** + * Pings the heartbeat + */ + IdleTransaction.prototype._pingHeartbeat = function () { + var _this = this; + utils_1.logger.log("pinging Heartbeat -> current counter: " + this._heartbeatCounter); + this._heartbeatTimer = setTimeout(function () { + _this._beat(); + }, 5000); + }; + return IdleTransaction; +}(transaction_1.Transaction)); +exports.IdleTransaction = IdleTransaction; /** - * Gets the value of an state set by this action's main execution. - * - * @param name name of the state to get - * @returns string + * Reset active transaction on scope */ -function getState(name) { - return process.env[`STATE_${name}`] || ''; +function clearActiveTransaction(hub) { + if (hub) { + var scope = hub.getScope(); + if (scope) { + var transaction = scope.getTransaction(); + if (transaction) { + scope.setSpan(undefined); + } + } + } } -exports.getState = getState; -//# sourceMappingURL=core.js.map +//# sourceMappingURL=idletransaction.js.map /***/ }), -/***/ 20: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; +/***/ 64358: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -// For internal use, subject to change. -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; -}; Object.defineProperty(exports, "__esModule", ({ value: true })); -// We use any as a valid input type -/* eslint-disable @typescript-eslint/no-explicit-any */ -const fs = __importStar(__nccwpck_require__(57147)); -const os = __importStar(__nccwpck_require__(22037)); -const utils_1 = __nccwpck_require__(53322); -function issueCommand(command, message) { - const filePath = process.env[`GITHUB_${command}`]; - if (!filePath) { - throw new Error(`Unable to find environment variable for file command ${command}`); - } - if (!fs.existsSync(filePath)) { - throw new Error(`Missing file at path: ${filePath}`); - } - fs.appendFileSync(filePath, `${utils_1.toCommandValue(message)}${os.EOL}`, { - encoding: 'utf8' - }); -} -exports.issueCommand = issueCommand; -//# sourceMappingURL=file-command.js.map +var tslib_1 = __nccwpck_require__(4351); +var browser_1 = __nccwpck_require__(71425); +var hubextensions_1 = __nccwpck_require__(31409); +exports.addExtensionMethods = hubextensions_1.addExtensionMethods; +var TracingIntegrations = __nccwpck_require__(28502); +var Integrations = tslib_1.__assign(tslib_1.__assign({}, TracingIntegrations), { BrowserTracing: browser_1.BrowserTracing }); +exports.Integrations = Integrations; +var span_1 = __nccwpck_require__(64655); +exports.Span = span_1.Span; +var transaction_1 = __nccwpck_require__(8186); +exports.Transaction = transaction_1.Transaction; +var spanstatus_1 = __nccwpck_require__(58522); +exports.SpanStatus = spanstatus_1.SpanStatus; +// We are patching the global object with our hub extension methods +hubextensions_1.addExtensionMethods(); +var utils_1 = __nccwpck_require__(31386); +exports.extractTraceparentData = utils_1.extractTraceparentData; +exports.getActiveTransaction = utils_1.getActiveTransaction; +exports.hasTracingEnabled = utils_1.hasTracingEnabled; +exports.stripUrlQueryAndFragment = utils_1.stripUrlQueryAndFragment; +exports.TRACEPARENT_REGEXP = utils_1.TRACEPARENT_REGEXP; +//# sourceMappingURL=index.js.map /***/ }), -/***/ 53322: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; +/***/ 96221: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -// We use any as a valid input type -/* eslint-disable @typescript-eslint/no-explicit-any */ Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __nccwpck_require__(4351); +var utils_1 = __nccwpck_require__(1620); /** - * Sanitizes an input into a string so it can be passed into issueCommand safely - * @param input input to sanitize into a string + * Express integration + * + * Provides an request and error handler for Express framework as well as tracing capabilities */ -function toCommandValue(input) { - if (input === null || input === undefined) { - return ''; - } - else if (typeof input === 'string' || input instanceof String) { - return input; - } - return JSON.stringify(input); -} -exports.toCommandValue = toCommandValue; -//# sourceMappingURL=utils.js.map - -/***/ }), - -/***/ 3598: -/***/ (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.defaultApp = void 0; -const path_1 = __importDefault(__nccwpck_require__(71017)); -function defaultApp(app, { getRouter }) { - if (!getRouter) { - throw new Error("getRouter() is required for defaultApp"); +var Express = /** @class */ (function () { + /** + * @inheritDoc + */ + function Express(options) { + if (options === void 0) { options = {}; } + /** + * @inheritDoc + */ + this.name = Express.id; + this._router = options.router || options.app; + this._methods = (Array.isArray(options.methods) ? options.methods : []).concat('use'); } - const router = getRouter(); - router.get("/probot", (req, res) => { - let pkg; - try { - pkg = require(path_1.default.join(process.cwd(), "package.json")); - } - catch (e) { - pkg = {}; + /** + * @inheritDoc + */ + Express.prototype.setupOnce = function () { + if (!this._router) { + utils_1.logger.error('ExpressIntegration is missing an Express instance'); + return; } - res.render("probot.hbs", pkg); - }); - router.get("/", (req, res, next) => res.redirect("/probot")); -} -exports.defaultApp = defaultApp; -//# sourceMappingURL=default.js.map - -/***/ }), - -/***/ 36769: -/***/ (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.setupAppFactory = void 0; -const body_parser_1 = __importDefault(__nccwpck_require__(97076)); -const child_process_1 = __nccwpck_require__(32081); -const update_dotenv_1 = __importDefault(__nccwpck_require__(51023)); -const manifest_creation_1 = __nccwpck_require__(18785); -const logging_middleware_1 = __nccwpck_require__(24631); -const is_production_1 = __nccwpck_require__(75381); -const setupAppFactory = (host, port) => async function setupApp(app, { getRouter }) { - const setup = new manifest_creation_1.ManifestCreation(); - // If not on Glitch or Production, create a smee URL - if (!is_production_1.isProduction() && - !(process.env.PROJECT_DOMAIN || - process.env.WEBHOOK_PROXY_URL || - process.env.NO_SMEE_SETUP === "true")) { - await setup.createWebhookChannel(); - } - if (!getRouter) { - throw new Error("getRouter is required to use the setup app"); - } - const route = getRouter(); - route.use(logging_middleware_1.getLoggingMiddleware(app.log)); - printWelcomeMessage(app, host, port); - route.get("/probot", async (req, res) => { - const baseUrl = getBaseUrl(req); - const pkg = setup.pkg; - const manifest = setup.getManifest(pkg, baseUrl); - const createAppUrl = setup.createAppUrl; - // Pass the manifest to be POST'd - res.render("setup.hbs", { pkg, createAppUrl, manifest }); - }); - route.get("/probot/setup", async (req, res) => { - const { code } = req.query; - const response = await setup.createAppFromCode(code); - // If using glitch, restart the app - if (process.env.PROJECT_DOMAIN) { - child_process_1.exec("refresh", (error) => { - if (error) { - app.log.error(error); + instrumentMiddlewares(this._router, this._methods); + }; + /** + * @inheritDoc + */ + Express.id = 'Express'; + return Express; +}()); +exports.Express = Express; +/** + * Wraps original middleware function in a tracing call, which stores the info about the call as a span, + * and finishes it once the middleware is done invoking. + * + * Express middlewares have 3 various forms, thus we have to take care of all of them: + * // sync + * app.use(function (req, res) { ... }) + * // async + * app.use(function (req, res, next) { ... }) + * // error handler + * app.use(function (err, req, res, next) { ... }) + * + * They all internally delegate to the `router[method]` of the given application instance. + */ +// eslint-disable-next-line @typescript-eslint/ban-types, @typescript-eslint/no-explicit-any +function wrap(fn, method) { + var arity = fn.length; + switch (arity) { + case 2: { + return function (req, res) { + var transaction = res.__sentry_transaction; + if (transaction) { + var span_1 = transaction.startChild({ + description: fn.name, + op: "middleware." + method, + }); + res.once('finish', function () { + span_1.finish(); + }); } - }); + return fn.call(this, req, res); + }; } - else { - printRestartMessage(app); + case 3: { + return function (req, res, next) { + var _a; + var transaction = res.__sentry_transaction; + var span = (_a = transaction) === null || _a === void 0 ? void 0 : _a.startChild({ + description: fn.name, + op: "middleware." + method, + }); + fn.call(this, req, res, function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + var _a; + (_a = span) === null || _a === void 0 ? void 0 : _a.finish(); + next.call.apply(next, tslib_1.__spread([this], args)); + }); + }; } - res.redirect(`${response}/installations/new`); - }); - route.get("/probot/import", async (_req, res) => { - const { WEBHOOK_PROXY_URL, GHE_HOST } = process.env; - const GH_HOST = `https://${GHE_HOST !== null && GHE_HOST !== void 0 ? GHE_HOST : "github.com"}`; - res.render("import.hbs", { WEBHOOK_PROXY_URL, GH_HOST }); - }); - route.post("/probot/import", body_parser_1.default.json(), async (req, res) => { - const { appId, pem, webhook_secret } = req.body; - if (!appId || !pem || !webhook_secret) { - res.status(400).send("appId and/or pem and/or webhook_secret missing"); - return; + case 4: { + return function (err, req, res, next) { + var _a; + var transaction = res.__sentry_transaction; + var span = (_a = transaction) === null || _a === void 0 ? void 0 : _a.startChild({ + description: fn.name, + op: "middleware." + method, + }); + fn.call(this, err, req, res, function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + var _a; + (_a = span) === null || _a === void 0 ? void 0 : _a.finish(); + next.call.apply(next, tslib_1.__spread([this], args)); + }); + }; } - update_dotenv_1.default({ - APP_ID: appId, - PRIVATE_KEY: `"${pem}"`, - WEBHOOK_SECRET: webhook_secret, - }); - res.end(); - printRestartMessage(app); - }); - route.get("/probot/success", async (req, res) => { - res.render("success.hbs"); - }); - route.get("/", (req, res, next) => res.redirect("/probot")); -}; -exports.setupAppFactory = setupAppFactory; -function printWelcomeMessage(app, host, port) { - // use glitch env to get correct domain welcome message - // https://glitch.com/help/project/ - const domain = process.env.PROJECT_DOMAIN || - `http://${host !== null && host !== void 0 ? host : "localhost"}:${port || 3000}`; - [ - ``, - `Welcome to Probot!`, - `Probot is in setup mode, webhooks cannot be received and`, - `custom routes will not work until APP_ID and PRIVATE_KEY`, - `are configured in .env.`, - `Please follow the instructions at ${domain} to configure .env.`, - `Once you are done, restart the server.`, - ``, - ].forEach((line) => { - app.log.info(line); - }); -} -function printRestartMessage(app) { - app.log.info(""); - app.log.info("Probot has been set up, please restart the server!"); - app.log.info(""); -} -function getBaseUrl(req) { - const protocols = req.headers["x-forwarded-proto"] || req.protocol; - const protocol = typeof protocols === "string" ? protocols.split(",")[0] : protocols[0]; - const host = req.headers["x-forwarded-host"] || req.get("host"); - const baseUrl = `${protocol}://${host}`; - return baseUrl; + default: { + throw new Error("Express middleware takes 2-4 arguments. Got: " + arity); + } + } } -//# sourceMappingURL=setup.js.map - -/***/ }), - -/***/ 81084: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.auth = void 0; -const get_authenticated_octokit_1 = __nccwpck_require__(53535); /** - * Authenticate and get a GitHub client that can be used to make API calls. - * - * You'll probably want to use `context.octokit` instead. - * - * **Note**: `app.auth` is asynchronous, so it needs to be prefixed with a - * [`await`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await) - * to wait for the magic to happen. - * - * ```js - * module.exports = (app) => { - * app.on('issues.opened', async context => { - * const octokit = await app.auth(); - * }); - * }; - * ``` - * - * @param id - ID of the installation, which can be extracted from - * `context.payload.installation.id`. If called without this parameter, the - * client wil authenticate [as the app](https://docs.github.com/en/developers/apps/authenticating-with-github-apps#authenticating-as-a-github-app) - * instead of as a specific installation, which means it can only be used for - * [app APIs](https://docs.github.com/apps/). + * Takes all the function arguments passed to the original `app` or `router` method, eg. `app.use` or `router.use` + * and wraps every function, as well as array of functions with a call to our `wrap` method. + * We have to take care of the arrays as well as iterate over all of the arguments, + * as `app.use` can accept middlewares in few various forms. * - * @returns An authenticated GitHub API client + * app.use([], ) + * app.use([], , ...) + * app.use([], ...[]) */ -async function auth(state, installationId, log) { - return get_authenticated_octokit_1.getAuthenticatedOctokit(Object.assign({}, state, log ? { log } : null), installationId); +function wrapMiddlewareArgs(args, method) { + return args.map(function (arg) { + if (typeof arg === 'function') { + return wrap(arg, method); + } + if (Array.isArray(arg)) { + return arg.map(function (a) { + if (typeof a === 'function') { + return wrap(a, method); + } + return a; + }); + } + return arg; + }); } -exports.auth = auth; -//# sourceMappingURL=auth.js.map - -/***/ }), - -/***/ 57767: -/***/ (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.readCliOptions = void 0; -const commander_1 = __importDefault(__nccwpck_require__(61904)); -const get_private_key_1 = __nccwpck_require__(97743); -function readCliOptions(argv) { - commander_1.default - .usage("[options] ") - .option("-p, --port ", "Port to start the server on", String(process.env.PORT || 3000)) - .option("-H --host ", "Host to start the server on", process.env.HOST) - .option("-W, --webhook-proxy ", "URL of the webhook proxy service.`", process.env.WEBHOOK_PROXY_URL) - .option("-w, --webhook-path ", "URL path which receives webhooks. Ex: `/webhook`", process.env.WEBHOOK_PATH) - .option("-a, --app ", "ID of the GitHub App", process.env.APP_ID) - .option("-s, --secret ", "Webhook secret of the GitHub App", process.env.WEBHOOK_SECRET) - .option("-P, --private-key ", "Path to private key file (.pem) for the GitHub App", process.env.PRIVATE_KEY_PATH) - .option("-L, --log-level ", 'One of: "trace" | "debug" | "info" | "warn" | "error" | "fatal"', process.env.LOG_LEVEL || "info") - .option("--log-format ", 'One of: "pretty", "json"', process.env.LOG_FORMAT) - .option("--log-level-in-string", "Set to log levels (trace, debug, info, ...) as words instead of numbers (10, 20, 30, ...)", process.env.LOG_LEVEL_IN_STRING === "true") - .option("--sentry-dsn ", 'Set to your Sentry DSN, e.g. "https://1234abcd@sentry.io/12345"', process.env.SENTRY_DSN) - .option("--redis-url ", 'Set to a "redis://" url in order to enable cluster support for request throttling. Example: "redis://:secret@redis-123.redislabs.com:12345/0"', process.env.REDIS_URL) - .option("--base-url ", 'GitHub API base URL. If you use GitHub Enterprise Server, and your hostname is "https://github.acme-inc.com", then the root URL is "https://github.acme-inc.com/api/v3"', process.env.GHE_HOST - ? `${process.env.GHE_PROTOCOL || "https"}://${process.env.GHE_HOST}/api/v3` - : "https://api.github.com") - .parse(argv); - const { app: appId, privateKey: privateKeyPath, redisUrl, ...options } = commander_1.default; - return { - privateKey: get_private_key_1.getPrivateKey({ filepath: privateKeyPath }) || undefined, - appId, - redisConfig: redisUrl, - ...options, +/** + * Patches original router to utilize our tracing functionality + */ +function patchMiddleware(router, method) { + var originalCallback = router[method]; + router[method] = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return originalCallback.call.apply(originalCallback, tslib_1.__spread([this], wrapMiddlewareArgs(args, method))); }; + return router; } -exports.readCliOptions = readCliOptions; -//# sourceMappingURL=read-cli-options.js.map +/** + * Patches original router methods + */ +function instrumentMiddlewares(router, methods) { + if (methods === void 0) { methods = []; } + methods.forEach(function (method) { return patchMiddleware(router, method); }); +} +//# sourceMappingURL=express.js.map /***/ }), -/***/ 74420: +/***/ 28502: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; - Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.readEnvOptions = void 0; -const get_private_key_1 = __nccwpck_require__(97743); -function readEnvOptions(env = process.env) { - const privateKey = get_private_key_1.getPrivateKey({ env }); - const logFormat = env.LOG_FORMAT || (env.NODE_ENV === "production" ? "json" : "pretty"); - return { - args: [], - privateKey: (privateKey && privateKey.toString()) || undefined, - appId: Number(env.APP_ID), - port: Number(env.PORT) || 3000, - host: env.HOST, - secret: env.WEBHOOK_SECRET, - webhookPath: env.WEBHOOK_PATH, - webhookProxy: env.WEBHOOK_PROXY_URL, - logLevel: env.LOG_LEVEL, - logFormat: logFormat, - logLevelInString: env.LOG_LEVEL_IN_STRING === "true", - logMessageKey: env.LOG_MESSAGE_KEY, - sentryDsn: env.SENTRY_DSN, - redisConfig: env.REDIS_URL, - baseUrl: env.GHE_HOST - ? `${env.GHE_PROTOCOL || "https"}://${env.GHE_HOST}/api/v3` - : "https://api.github.com", - }; -} -exports.readEnvOptions = readEnvOptions; -//# sourceMappingURL=read-env-options.js.map +var express_1 = __nccwpck_require__(96221); +exports.Express = express_1.Express; +var postgres_1 = __nccwpck_require__(31931); +exports.Postgres = postgres_1.Postgres; +var mysql_1 = __nccwpck_require__(67082); +exports.Mysql = mysql_1.Mysql; +var mongo_1 = __nccwpck_require__(22606); +exports.Mongo = mongo_1.Mongo; +//# sourceMappingURL=index.js.map /***/ }), -/***/ 45006: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +/***/ 22606: +/***/ ((module, exports, __nccwpck_require__) => { + +/* module decorator */ module = __nccwpck_require__.nmd(module); Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Context = void 0; -const path_1 = __importDefault(__nccwpck_require__(71017)); -const deepmerge_1 = __importDefault(__nccwpck_require__(56323)); -const alias_log_1 = __nccwpck_require__(19752); -/** - * The context of the event that was triggered, including the payload and - * helpers for extracting information can be passed to GitHub API calls. - * - * ```js - * module.exports = app => { - * app.on('push', context => { - * context.log.info('Code was pushed to the repo, what should we do with it?'); - * }); - * }; - * ``` - * - * @property {octokit} octokit - An Octokit instance - * @property {payload} payload - The webhook event payload - * @property {log} log - A pino instance - */ -class Context { - constructor(event, octokit, log) { - this.name = event.name; - this.id = event.id; - this.payload = event.payload; - this.octokit = octokit; - this.log = alias_log_1.aliasLog(log); - } +var tslib_1 = __nccwpck_require__(4351); +var utils_1 = __nccwpck_require__(1620); +var OPERATIONS = [ + 'aggregate', + 'bulkWrite', + 'countDocuments', + 'createIndex', + 'createIndexes', + 'deleteMany', + 'deleteOne', + 'distinct', + 'drop', + 'dropIndex', + 'dropIndexes', + 'estimatedDocumentCount', + 'findOne', + 'findOneAndDelete', + 'findOneAndReplace', + 'findOneAndUpdate', + 'indexes', + 'indexExists', + 'indexInformation', + 'initializeOrderedBulkOp', + 'insertMany', + 'insertOne', + 'isCapped', + 'mapReduce', + 'options', + 'parallelCollectionScan', + 'rename', + 'replaceOne', + 'stats', + 'updateMany', + 'updateOne', +]; +// All of the operations above take `options` and `callback` as their final parameters, but some of them +// take additional parameters as well. For those operations, this is a map of +// { : [] }, as a way to know what to call the operation's +// positional arguments when we add them to the span's `data` object later +var OPERATION_SIGNATURES = { + // aggregate intentionally not included because `pipeline` arguments are too complex to serialize well + // see https://github.com/getsentry/sentry-javascript/pull/3102 + bulkWrite: ['operations'], + countDocuments: ['query'], + createIndex: ['fieldOrSpec'], + createIndexes: ['indexSpecs'], + deleteMany: ['filter'], + deleteOne: ['filter'], + distinct: ['key', 'query'], + dropIndex: ['indexName'], + findOne: ['query'], + findOneAndDelete: ['filter'], + findOneAndReplace: ['filter', 'replacement'], + findOneAndUpdate: ['filter', 'update'], + indexExists: ['indexes'], + insertMany: ['docs'], + insertOne: ['doc'], + mapReduce: ['map', 'reduce'], + rename: ['newName'], + replaceOne: ['filter', 'doc'], + updateMany: ['filter', 'update'], + updateOne: ['filter', 'update'], +}; +/** Tracing integration for mongo package */ +var Mongo = /** @class */ (function () { /** - * Return the `owner` and `repo` params for making API requests against a - * repository. - * - * ```js - * const params = context.repo({path: '.github/config.yml'}) - * // Returns: {owner: 'username', repo: 'reponame', path: '.github/config.yml'} - * ``` - * - * @param object - Params to be merged with the repo params. - * + * @inheritDoc */ - repo(object) { - // @ts-ignore `repository` is not always present in this.payload - const repo = this.payload.repository; - if (!repo) { - throw new Error("context.repo() is not supported for this webhook event."); - } - return Object.assign({ - owner: repo.owner.login, - repo: repo.name, - }, object); + function Mongo(options) { + if (options === void 0) { options = {}; } + /** + * @inheritDoc + */ + this.name = Mongo.id; + this._operations = Array.isArray(options.operations) + ? options.operations + : OPERATIONS; + this._describeOperations = 'describeOperations' in options ? options.describeOperations : true; } /** - * Return the `owner`, `repo`, and `issue_number` params for making API requests - * against an issue. The object passed in will be merged with the repo params. - * - * - * ```js - * const params = context.issue({body: 'Hello World!'}) - * // Returns: {owner: 'username', repo: 'reponame', issue_number: 123, body: 'Hello World!'} - * ``` - * - * @param object - Params to be merged with the issue params. + * @inheritDoc */ - issue(object) { - return Object.assign({ - issue_number: - // @ts-ignore - this.payload may not have `issue` or `pull_request` keys - (this.payload.issue || this.payload.pull_request || this.payload) - .number, - }, this.repo(object)); - } + Mongo.prototype.setupOnce = function (_, getCurrentHub) { + var collection; + try { + var mongodbModule = utils_1.dynamicRequire(module, 'mongodb'); + collection = mongodbModule.Collection; + } + catch (e) { + utils_1.logger.error('Mongo Integration was unable to require `mongodb` package.'); + return; + } + this._instrumentOperations(collection, this._operations, getCurrentHub); + }; /** - * Return the `owner`, `repo`, and `pull_number` params for making API requests - * against a pull request. The object passed in will be merged with the repo params. - * - * - * ```js - * const params = context.pullRequest({body: 'Hello World!'}) - * // Returns: {owner: 'username', repo: 'reponame', pull_number: 123, body: 'Hello World!'} - * ``` - * - * @param object - Params to be merged with the pull request params. + * Patches original collection methods */ - pullRequest(object) { - const payload = this.payload; - return Object.assign({ - // @ts-ignore - this.payload may not have `issue` or `pull_request` keys - pull_number: (payload.issue || payload.pull_request || payload).number, - }, this.repo(object)); - } + Mongo.prototype._instrumentOperations = function (collection, operations, getCurrentHub) { + var _this = this; + operations.forEach(function (operation) { return _this._patchOperation(collection, operation, getCurrentHub); }); + }; /** - * Returns a boolean if the actor on the event was a bot. - * @type {boolean} + * Patches original collection to utilize our tracing functionality */ - get isBot() { - // @ts-expect-error - `sender` key is currently not present in all events - // see https://github.com/octokit/webhooks/issues/510 - return this.payload.sender.type === "Bot"; - } + Mongo.prototype._patchOperation = function (collection, operation, getCurrentHub) { + if (!(operation in collection.prototype)) + return; + var getSpanContext = this._getSpanContextFromOperationArguments.bind(this); + utils_1.fill(collection.prototype, operation, function (orig) { + return function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + var _a, _b, _c; + var lastArg = args[args.length - 1]; + var scope = getCurrentHub().getScope(); + var parentSpan = (_a = scope) === null || _a === void 0 ? void 0 : _a.getSpan(); + // Check if the operation was passed a callback. (mapReduce requires a different check, as + // its (non-callback) arguments can also be functions.) + if (typeof lastArg !== 'function' || (operation === 'mapReduce' && args.length === 2)) { + var span_1 = (_b = parentSpan) === null || _b === void 0 ? void 0 : _b.startChild(getSpanContext(this, operation, args)); + return orig.call.apply(orig, tslib_1.__spread([this], args)).then(function (res) { + var _a; + (_a = span_1) === null || _a === void 0 ? void 0 : _a.finish(); + return res; + }); + } + var span = (_c = parentSpan) === null || _c === void 0 ? void 0 : _c.startChild(getSpanContext(this, operation, args.slice(0, -1))); + return orig.call.apply(orig, tslib_1.__spread([this], args.slice(0, -1), [function (err, result) { + var _a; + (_a = span) === null || _a === void 0 ? void 0 : _a.finish(); + lastArg(err, result); + }])); + }; + }); + }; /** - * Reads the app configuration from the given YAML file in the `.github` - * directory of the repository. - * - * For example, given a file named `.github/config.yml`: - * - * ```yml - * close: true - * comment: Check the specs on the rotary girder. - * ``` - * - * Your app can read that file from the target repository: - * - * ```js - * // Load config from .github/config.yml in the repository - * const config = await context.config('config.yml') - * - * if (config.close) { - * context.octokit.issues.comment(context.issue({body: config.comment})) - * context.octokit.issues.edit(context.issue({state: 'closed'})) - * } - * ``` - * - * You can also use a `defaultConfig` object: - * - * ```js - * // Load config from .github/config.yml in the repository and combine with default config - * const config = await context.config('config.yml', {comment: 'Make sure to check all the specs.'}) - * - * if (config.close) { - * context.octokit.issues.comment(context.issue({body: config.comment})); - * context.octokit.issues.edit(context.issue({state: 'closed'})) - * } - * ``` - * - * Config files can also specify a base that they extend. `deepMergeOptions` can be used - * to configure how the target config, extended base, and default configs are merged. - * - * For security reasons, configuration is only loaded from the repository's default branch, - * changes made in pull requests from different branches or forks are ignored. - * - * If you need more lower-level control over reading and merging configuration files, - * you can `context.octokit.config.get(options)`, see https://github.com/probot/octokit-plugin-config. - * - * @param fileName - Name of the YAML file in the `.github` directory - * @param defaultConfig - An object of default config options - * @param deepMergeOptions - Controls merging configs (from the [deepmerge](https://github.com/TehShrike/deepmerge) module) - * @return Configuration object read from the file + * Form a SpanContext based on the user input to a given operation. */ - async config(fileName, defaultConfig, deepMergeOptions) { - const params = this.repo({ - path: path_1.default.posix.join(".github", fileName), - defaults(configs) { - const result = deepmerge_1.default.all([defaultConfig || {}, ...configs], deepMergeOptions); - return result; - }, - }); - // @ts-ignore - const { config, files } = await this.octokit.config.get(params); - // if no default config is set, and no config files are found, return null - if (!defaultConfig && !files.find((file) => file.config !== null)) { - return null; + Mongo.prototype._getSpanContextFromOperationArguments = function (collection, operation, args) { + var data = { + collectionName: collection.collectionName, + dbName: collection.dbName, + namespace: collection.namespace, + }; + var spanContext = { + op: "db", + description: operation, + data: data, + }; + // If the operation takes no arguments besides `options` and `callback`, or if argument + // collection is disabled for this operation, just return early. + var signature = OPERATION_SIGNATURES[operation]; + var shouldDescribe = Array.isArray(this._describeOperations) + ? this._describeOperations.includes(operation) + : this._describeOperations; + if (!signature || !shouldDescribe) { + return spanContext; } - return config; - } -} -exports.Context = Context; -//# sourceMappingURL=context.js.map + try { + // Special case for `mapReduce`, as the only one accepting functions as arguments. + if (operation === 'mapReduce') { + var _a = tslib_1.__read(args, 2), map = _a[0], reduce = _a[1]; + data[signature[0]] = typeof map === 'string' ? map : map.name || ''; + data[signature[1]] = typeof reduce === 'string' ? reduce : reduce.name || ''; + } + else { + for (var i = 0; i < signature.length; i++) { + data[signature[i]] = JSON.stringify(args[i]); + } + } + } + catch (_oO) { + // no-empty + } + return spanContext; + }; + /** + * @inheritDoc + */ + Mongo.id = 'Mongo'; + return Mongo; +}()); +exports.Mongo = Mongo; +//# sourceMappingURL=mongo.js.map /***/ }), -/***/ 44488: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; +/***/ 67082: +/***/ ((module, exports, __nccwpck_require__) => { +/* module decorator */ module = __nccwpck_require__.nmd(module); Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.createNodeMiddleware = void 0; -const webhooks_1 = __nccwpck_require__(18513); -function createNodeMiddleware(appFn, { probot, webhooksPath }) { - probot.load(appFn); - return webhooks_1.createNodeMiddleware(probot.webhooks, { - path: webhooksPath || "/", - }); -} -exports.createNodeMiddleware = createNodeMiddleware; -//# sourceMappingURL=create-node-middleware.js.map +var utils_1 = __nccwpck_require__(1620); +/** Tracing integration for node-mysql package */ +var Mysql = /** @class */ (function () { + function Mysql() { + /** + * @inheritDoc + */ + this.name = Mysql.id; + } + /** + * @inheritDoc + */ + Mysql.prototype.setupOnce = function (_, getCurrentHub) { + var connection; + try { + // Unfortunatelly mysql is using some custom loading system and `Connection` is not exported directly. + connection = utils_1.dynamicRequire(module, 'mysql/lib/Connection.js'); + } + catch (e) { + utils_1.logger.error('Mysql Integration was unable to require `mysql` package.'); + return; + } + // The original function will have one of these signatures: + // function (callback) => void + // function (options, callback) => void + // function (options, values, callback) => void + utils_1.fill(connection.prototype, 'query', function (orig) { + return function (options, values, callback) { + var _a, _b; + var scope = getCurrentHub().getScope(); + var parentSpan = (_a = scope) === null || _a === void 0 ? void 0 : _a.getSpan(); + var span = (_b = parentSpan) === null || _b === void 0 ? void 0 : _b.startChild({ + description: typeof options === 'string' ? options : options.sql, + op: "db", + }); + if (typeof callback === 'function') { + return orig.call(this, options, values, function (err, result, fields) { + var _a; + (_a = span) === null || _a === void 0 ? void 0 : _a.finish(); + callback(err, result, fields); + }); + } + if (typeof values === 'function') { + return orig.call(this, options, function (err, result, fields) { + var _a; + (_a = span) === null || _a === void 0 ? void 0 : _a.finish(); + values(err, result, fields); + }); + } + return orig.call(this, options, values, callback); + }; + }); + }; + /** + * @inheritDoc + */ + Mysql.id = 'Mysql'; + return Mysql; +}()); +exports.Mysql = Mysql; +//# sourceMappingURL=mysql.js.map /***/ }), -/***/ 52728: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; +/***/ 31931: +/***/ ((module, exports, __nccwpck_require__) => { +/* module decorator */ module = __nccwpck_require__.nmd(module); Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.createProbot = void 0; -const get_private_key_1 = __nccwpck_require__(97743); -const get_log_1 = __nccwpck_require__(90751); -const probot_1 = __nccwpck_require__(22357); -const DEFAULTS = { - APP_ID: "", - WEBHOOK_SECRET: "", - GHE_HOST: "", - GHE_PROTOCOL: "", - LOG_FORMAT: "", - LOG_LEVEL: "warn", - LOG_LEVEL_IN_STRING: "", - LOG_MESSAGE_KEY: "msg", - REDIS_URL: "", - SENTRY_DSN: "", -}; -/** - * Merges configuration from defaults/environment variables/overrides and returns - * a Probot instance. Finds private key using [`@probot/get-private-key`](https://github.com/probot/get-private-key). - * - * @see https://probot.github.io/docs/configuration/ - * @param defaults default Options, will be overwritten if according environment variable is set - * @param overrides overwrites defaults and according environment variables - * @param env defaults to process.env - */ -function createProbot({ overrides = {}, defaults = {}, env = process.env, } = {}) { - const privateKey = get_private_key_1.getPrivateKey({ env }); - const envWithDefaults = { ...DEFAULTS, ...env }; - const envOptions = { - logLevel: envWithDefaults.LOG_LEVEL, - appId: Number(envWithDefaults.APP_ID), - privateKey: (privateKey && privateKey.toString()) || undefined, - secret: envWithDefaults.WEBHOOK_SECRET, - redisConfig: envWithDefaults.REDIS_URL, - baseUrl: envWithDefaults.GHE_HOST - ? `${envWithDefaults.GHE_PROTOCOL || "https"}://${envWithDefaults.GHE_HOST}/api/v3` - : "https://api.github.com", - }; - const probotOptions = { - ...defaults, - ...envOptions, - ...overrides, - }; - const logOptions = { - level: probotOptions.logLevel, - logFormat: envWithDefaults.LOG_FORMAT, - logLevelInString: envWithDefaults.LOG_LEVEL_IN_STRING === "true", - logMessageKey: envWithDefaults.LOG_MESSAGE_KEY, - sentryDsn: envWithDefaults.SENTRY_DSN, +var utils_1 = __nccwpck_require__(1620); +/** Tracing integration for node-postgres package */ +var Postgres = /** @class */ (function () { + function Postgres() { + /** + * @inheritDoc + */ + this.name = Postgres.id; + } + /** + * @inheritDoc + */ + Postgres.prototype.setupOnce = function (_, getCurrentHub) { + var client; + try { + var pgModule = utils_1.dynamicRequire(module, 'pg'); + client = pgModule.Client; + } + catch (e) { + utils_1.logger.error('Postgres Integration was unable to require `pg` package.'); + return; + } + /** + * function (query, callback) => void + * function (query, params, callback) => void + * function (query) => Promise + * function (query, params) => Promise + */ + utils_1.fill(client.prototype, 'query', function (orig) { + return function (config, values, callback) { + var _a, _b; + var scope = getCurrentHub().getScope(); + var parentSpan = (_a = scope) === null || _a === void 0 ? void 0 : _a.getSpan(); + var span = (_b = parentSpan) === null || _b === void 0 ? void 0 : _b.startChild({ + description: typeof config === 'string' ? config : config.text, + op: "db", + }); + if (typeof callback === 'function') { + return orig.call(this, config, values, function (err, result) { + var _a; + (_a = span) === null || _a === void 0 ? void 0 : _a.finish(); + callback(err, result); + }); + } + if (typeof values === 'function') { + return orig.call(this, config, function (err, result) { + var _a; + (_a = span) === null || _a === void 0 ? void 0 : _a.finish(); + values(err, result); + }); + } + return orig.call(this, config, values).then(function (res) { + var _a; + (_a = span) === null || _a === void 0 ? void 0 : _a.finish(); + return res; + }); + }; + }); }; - const log = get_log_1.getLog(logOptions).child({ name: "server" }); - return new probot_1.Probot({ - log: log.child({ name: "probot" }), - ...probotOptions, - }); -} -exports.createProbot = createProbot; -//# sourceMappingURL=create-probot.js.map + /** + * @inheritDoc + */ + Postgres.id = 'Postgres'; + return Postgres; +}()); +exports.Postgres = Postgres; +//# sourceMappingURL=postgres.js.map /***/ }), -/***/ 19752: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; +/***/ 64655: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.aliasLog = void 0; +var tslib_1 = __nccwpck_require__(4351); +var utils_1 = __nccwpck_require__(1620); +var spanstatus_1 = __nccwpck_require__(58522); /** - * `probot.log()`, `app.log()` and `context.log()` are aliasing `.log.info()`. - * We will probably remove the aliasing in future. + * Keeps track of finished spans for a given transaction + * @internal + * @hideconstructor + * @hidden */ -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]; +var SpanRecorder = /** @class */ (function () { + function SpanRecorder(maxlen) { + if (maxlen === void 0) { maxlen = 1000; } + this.spans = []; + this._maxlen = maxlen; } - // @ts-ignore - return logInfo; -} -exports.aliasLog = aliasLog; -//# sourceMappingURL=alias-log.js.map - -/***/ }), - -/***/ 5789: -/***/ ((__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); + /** + * This is just so that we don't run out of memory while recording a lot + * of spans. At some point we just stop and flush out the start of the + * trace tree (i.e.the first n spans with the smallest + * start_timestamp). + */ + SpanRecorder.prototype.add = function (span) { + if (this.spans.length > this._maxlen) { + span.spanRecorder = undefined; + } + else { + this.spans.push(span); } }; -} -exports.getErrorHandler = getErrorHandler; -//# sourceMappingURL=get-error-handler.js.map - -/***/ }), - -/***/ 90751: -/***/ (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; + return SpanRecorder; +}()); +exports.SpanRecorder = SpanRecorder; /** - * 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!"); - * ``` + * Span contains all data about a span */ -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", +var Span = /** @class */ (function () { + /** + * You should never call the constructor manually, always use `Sentry.startTransaction()` + * or call `startChild()` on an existing span. + * @internal + * @hideconstructor + * @hidden + */ + function Span(spanContext) { + /** + * @inheritDoc + */ + this.traceId = utils_1.uuid4(); + /** + * @inheritDoc + */ + this.spanId = utils_1.uuid4().substring(16); + /** + * Timestamp in seconds when the span was created. + */ + this.startTimestamp = utils_1.timestampWithMs(); + /** + * @inheritDoc + */ + this.tags = {}; + /** + * @inheritDoc + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + this.data = {}; + if (!spanContext) { + return this; + } + if (spanContext.traceId) { + this.traceId = spanContext.traceId; + } + if (spanContext.spanId) { + this.spanId = spanContext.spanId; + } + if (spanContext.parentSpanId) { + this.parentSpanId = spanContext.parentSpanId; + } + // We want to include booleans as well here + if ('sampled' in spanContext) { + this.sampled = spanContext.sampled; + } + if (spanContext.op) { + this.op = spanContext.op; + } + if (spanContext.description) { + this.description = spanContext.description; + } + if (spanContext.data) { + this.data = spanContext.data; + } + if (spanContext.tags) { + this.tags = spanContext.tags; + } + if (spanContext.status) { + this.status = spanContext.status; + } + if (spanContext.startTimestamp) { + this.startTimestamp = spanContext.startTimestamp; + } + if (spanContext.endTimestamp) { + this.endTimestamp = spanContext.endTimestamp; + } + } + /** + * @inheritDoc + * @deprecated + */ + Span.prototype.child = function (spanContext) { + return this.startChild(spanContext); }; - 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 + /** + * @inheritDoc + */ + Span.prototype.startChild = function (spanContext) { + var childSpan = new Span(tslib_1.__assign(tslib_1.__assign({}, spanContext), { parentSpanId: this.spanId, sampled: this.sampled, traceId: this.traceId })); + childSpan.spanRecorder = this.spanRecorder; + if (childSpan.spanRecorder) { + childSpan.spanRecorder.add(childSpan); + } + childSpan.transaction = this.transaction; + return childSpan; + }; + /** + * @inheritDoc + */ + Span.prototype.setTag = function (key, value) { + var _a; + this.tags = tslib_1.__assign(tslib_1.__assign({}, this.tags), (_a = {}, _a[key] = value, _a)); + return this; + }; + /** + * @inheritDoc + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types + Span.prototype.setData = function (key, value) { + var _a; + this.data = tslib_1.__assign(tslib_1.__assign({}, this.data), (_a = {}, _a[key] = value, _a)); + return this; + }; + /** + * @inheritDoc + */ + Span.prototype.setStatus = function (value) { + this.status = value; + return this; + }; + /** + * @inheritDoc + */ + Span.prototype.setHttpStatus = function (httpStatus) { + this.setTag('http.status_code', String(httpStatus)); + var spanStatus = spanstatus_1.SpanStatus.fromHttpCode(httpStatus); + if (spanStatus !== spanstatus_1.SpanStatus.UnknownError) { + this.setStatus(spanStatus); + } + return this; + }; + /** + * @inheritDoc + */ + Span.prototype.isSuccess = function () { + return this.status === spanstatus_1.SpanStatus.Ok; + }; + /** + * @inheritDoc + */ + Span.prototype.finish = function (endTimestamp) { + this.endTimestamp = typeof endTimestamp === 'number' ? endTimestamp : utils_1.timestampWithMs(); + }; + /** + * @inheritDoc + */ + Span.prototype.toTraceparent = function () { + var sampledString = ''; + if (this.sampled !== undefined) { + sampledString = this.sampled ? '-1' : '-0'; + } + return this.traceId + "-" + this.spanId + sampledString; + }; + /** + * @inheritDoc + */ + Span.prototype.getTraceContext = function () { + return utils_1.dropUndefinedKeys({ + data: Object.keys(this.data).length > 0 ? this.data : undefined, + description: this.description, + op: this.op, + parent_span_id: this.parentSpanId, + span_id: this.spanId, + status: this.status, + tags: Object.keys(this.tags).length > 0 ? this.tags : undefined, + trace_id: this.traceId, + }); + }; + /** + * @inheritDoc + */ + Span.prototype.toJSON = function () { + return utils_1.dropUndefinedKeys({ + data: Object.keys(this.data).length > 0 ? this.data : undefined, + description: this.description, + op: this.op, + parent_span_id: this.parentSpanId, + span_id: this.spanId, + start_timestamp: this.startTimestamp, + status: this.status, + tags: Object.keys(this.tags).length > 0 ? this.tags : undefined, + timestamp: this.endTimestamp, + trace_id: this.traceId, + }); + }; + return Span; +}()); +exports.Span = Span; +//# sourceMappingURL=span.js.map /***/ }), -/***/ 75381: +/***/ 58522: /***/ ((__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 +/** The status of an Span. */ +// eslint-disable-next-line import/export +var SpanStatus; +(function (SpanStatus) { + /** The operation completed successfully. */ + SpanStatus["Ok"] = "ok"; + /** Deadline expired before operation could complete. */ + SpanStatus["DeadlineExceeded"] = "deadline_exceeded"; + /** 401 Unauthorized (actually does mean unauthenticated according to RFC 7235) */ + SpanStatus["Unauthenticated"] = "unauthenticated"; + /** 403 Forbidden */ + SpanStatus["PermissionDenied"] = "permission_denied"; + /** 404 Not Found. Some requested entity (file or directory) was not found. */ + SpanStatus["NotFound"] = "not_found"; + /** 429 Too Many Requests */ + SpanStatus["ResourceExhausted"] = "resource_exhausted"; + /** Client specified an invalid argument. 4xx. */ + SpanStatus["InvalidArgument"] = "invalid_argument"; + /** 501 Not Implemented */ + SpanStatus["Unimplemented"] = "unimplemented"; + /** 503 Service Unavailable */ + SpanStatus["Unavailable"] = "unavailable"; + /** Other/generic 5xx. */ + SpanStatus["InternalError"] = "internal_error"; + /** Unknown. Any non-standard HTTP status code. */ + SpanStatus["UnknownError"] = "unknown_error"; + /** The operation was cancelled (typically by the user). */ + SpanStatus["Cancelled"] = "cancelled"; + /** Already exists (409) */ + SpanStatus["AlreadyExists"] = "already_exists"; + /** Operation was rejected because the system is not in a state required for the operation's */ + SpanStatus["FailedPrecondition"] = "failed_precondition"; + /** The operation was aborted, typically due to a concurrency issue. */ + SpanStatus["Aborted"] = "aborted"; + /** Operation was attempted past the valid range. */ + SpanStatus["OutOfRange"] = "out_of_range"; + /** Unrecoverable data loss or corruption */ + SpanStatus["DataLoss"] = "data_loss"; +})(SpanStatus = exports.SpanStatus || (exports.SpanStatus = {})); +// eslint-disable-next-line @typescript-eslint/no-namespace, import/export +(function (SpanStatus) { + /** + * Converts a HTTP status code into a {@link SpanStatus}. + * + * @param httpStatus The HTTP response status code. + * @returns The span status or {@link SpanStatus.UnknownError}. + */ + function fromHttpCode(httpStatus) { + if (httpStatus < 400) { + return SpanStatus.Ok; + } + if (httpStatus >= 400 && httpStatus < 500) { + switch (httpStatus) { + case 401: + return SpanStatus.Unauthenticated; + case 403: + return SpanStatus.PermissionDenied; + case 404: + return SpanStatus.NotFound; + case 409: + return SpanStatus.AlreadyExists; + case 413: + return SpanStatus.FailedPrecondition; + case 429: + return SpanStatus.ResourceExhausted; + default: + return SpanStatus.InvalidArgument; + } + } + if (httpStatus >= 500 && httpStatus < 600) { + switch (httpStatus) { + case 501: + return SpanStatus.Unimplemented; + case 503: + return SpanStatus.Unavailable; + case 504: + return SpanStatus.DeadlineExceeded; + default: + return SpanStatus.InternalError; + } + } + return SpanStatus.UnknownError; + } + SpanStatus.fromHttpCode = fromHttpCode; +})(SpanStatus = exports.SpanStatus || (exports.SpanStatus = {})); +//# sourceMappingURL=spanstatus.js.map /***/ }), -/***/ 33208: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; +/***/ 8186: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -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 +var tslib_1 = __nccwpck_require__(4351); +var hub_1 = __nccwpck_require__(6393); +var utils_1 = __nccwpck_require__(1620); +var span_1 = __nccwpck_require__(64655); +/** JSDoc */ +var Transaction = /** @class */ (function (_super) { + tslib_1.__extends(Transaction, _super); + /** + * This constructor should never be called manually. Those instrumenting tracing should use + * `Sentry.startTransaction()`, and internal methods should use `hub.startTransaction()`. + * @internal + * @hideconstructor + * @hidden + */ + function Transaction(transactionContext, hub) { + var _this = _super.call(this, transactionContext) || this; + _this._measurements = {}; + /** + * The reference to the current hub. + */ + _this._hub = hub_1.getCurrentHub(); + if (utils_1.isInstanceOf(hub, hub_1.Hub)) { + _this._hub = hub; + } + _this.name = transactionContext.name ? transactionContext.name : ''; + _this._trimEnd = transactionContext.trimEnd; + // this is because transactions are also spans, and spans have a transaction pointer + _this.transaction = _this; + return _this; + } + /** + * JSDoc + */ + Transaction.prototype.setName = function (name) { + this.name = name; + }; + /** + * Attaches SpanRecorder to the span itself + * @param maxlen maximum number of spans that can be recorded + */ + Transaction.prototype.initSpanRecorder = function (maxlen) { + if (maxlen === void 0) { maxlen = 1000; } + if (!this.spanRecorder) { + this.spanRecorder = new span_1.SpanRecorder(maxlen); + } + this.spanRecorder.add(this); + }; + /** + * Set observed measurements for this transaction. + * @hidden + */ + Transaction.prototype.setMeasurements = function (measurements) { + this._measurements = tslib_1.__assign({}, measurements); + }; + /** + * @inheritDoc + */ + Transaction.prototype.finish = function (endTimestamp) { + var _this = this; + // This transaction is already finished, so we should not flush it again. + if (this.endTimestamp !== undefined) { + return undefined; + } + if (!this.name) { + utils_1.logger.warn('Transaction has no name, falling back to ``.'); + this.name = ''; + } + // just sets the end timestamp + _super.prototype.finish.call(this, endTimestamp); + if (this.sampled !== true) { + // At this point if `sampled !== true` we want to discard the transaction. + utils_1.logger.log('[Tracing] Discarding transaction because its trace was not chosen to be sampled.'); + return undefined; + } + var finishedSpans = this.spanRecorder ? this.spanRecorder.spans.filter(function (s) { return s !== _this && s.endTimestamp; }) : []; + if (this._trimEnd && finishedSpans.length > 0) { + this.endTimestamp = finishedSpans.reduce(function (prev, current) { + if (prev.endTimestamp && current.endTimestamp) { + return prev.endTimestamp > current.endTimestamp ? prev : current; + } + return prev; + }).endTimestamp; + } + var transaction = { + contexts: { + trace: this.getTraceContext(), + }, + spans: finishedSpans, + start_timestamp: this.startTimestamp, + tags: this.tags, + timestamp: this.endTimestamp, + transaction: this.name, + type: 'transaction', + }; + var hasMeasurements = Object.keys(this._measurements).length > 0; + if (hasMeasurements) { + utils_1.logger.log('[Measurements] Adding measurements to transaction', JSON.stringify(this._measurements, undefined, 2)); + transaction.measurements = this._measurements; + } + return this._hub.captureEvent(transaction); + }; + return Transaction; +}(span_1.Span)); +exports.Transaction = Transaction; +//# sourceMappingURL=transaction.js.map /***/ }), -/***/ 66217: +/***/ 31386: /***/ ((__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; +var hub_1 = __nccwpck_require__(6393); +exports.TRACEPARENT_REGEXP = new RegExp('^[ \\t]*' + // whitespace + '([0-9a-f]{32})?' + // trace_id + '-?([0-9a-f]{16})?' + // span_id + '-?([01])?' + // sampled + '[ \\t]*$'); +/** + * Determines if tracing is currently enabled. + * + * Tracing is enabled when at least one of `tracesSampleRate` and `tracesSampler` is defined in the SDK config. + */ +function hasTracingEnabled(options) { + return 'tracesSampleRate' in options || 'tracesSampler' in options; +} +exports.hasTracingEnabled = hasTracingEnabled; +/** + * Extract transaction context data from a `sentry-trace` header. + * + * @param traceparent Traceparent string + * + * @returns Object containing data from the header, or undefined if traceparent string is malformed + */ +function extractTraceparentData(traceparent) { + var matches = traceparent.match(exports.TRACEPARENT_REGEXP); + if (matches) { + var parentSampled = void 0; + if (matches[3] === '1') { + parentSampled = true; + } + else if (matches[3] === '0') { + parentSampled = false; + } + return { + traceId: matches[1], + parentSampled: parentSampled, + parentSpanId: matches[2], + }; } -}; -exports.createWebhookProxy = createWebhookProxy; -//# sourceMappingURL=webhook-proxy.js.map + return undefined; +} +exports.extractTraceparentData = extractTraceparentData; +/** Grabs active transaction off scope, if any */ +function getActiveTransaction(hub) { + if (hub === void 0) { hub = hub_1.getCurrentHub(); } + var _a, _b; + return (_b = (_a = hub) === null || _a === void 0 ? void 0 : _a.getScope()) === null || _b === void 0 ? void 0 : _b.getTransaction(); +} +exports.getActiveTransaction = getActiveTransaction; +/** + * Converts from milliseconds to seconds + * @param time time in ms + */ +function msToSec(time) { + return time / 1000; +} +exports.msToSec = msToSec; +/** + * Converts from seconds to milliseconds + * @param time time in seconds + */ +function secToMs(time) { + return time * 1000; +} +exports.secToMs = secToMs; +// so it can be used in manual instrumentation without necessitating a hard dependency on @sentry/utils +var utils_1 = __nccwpck_require__(1620); +exports.stripUrlQueryAndFragment = utils_1.stripUrlQueryAndFragment; +//# sourceMappingURL=utils.js.map /***/ }), -/***/ 93181: +/***/ 83789: /***/ ((__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__(45006); -Object.defineProperty(exports, "Context", ({ enumerable: true, get: function () { return context_1.Context; } })); -const probot_1 = __nccwpck_require__(22357); -Object.defineProperty(exports, "Probot", ({ enumerable: true, get: function () { return probot_1.Probot; } })); -const server_1 = __nccwpck_require__(83148); -Object.defineProperty(exports, "Server", ({ enumerable: true, get: function () { return server_1.Server; } })); -const probot_octokit_1 = __nccwpck_require__(97268); -Object.defineProperty(exports, "ProbotOctokit", ({ enumerable: true, get: function () { return probot_octokit_1.ProbotOctokit; } })); -const run_1 = __nccwpck_require__(57124); -Object.defineProperty(exports, "run", ({ enumerable: true, get: function () { return run_1.run; } })); -const create_node_middleware_1 = __nccwpck_require__(44488); -Object.defineProperty(exports, "createNodeMiddleware", ({ enumerable: true, get: function () { return create_node_middleware_1.createNodeMiddleware; } })); -const create_probot_1 = __nccwpck_require__(52728); -Object.defineProperty(exports, "createProbot", ({ enumerable: true, get: function () { return create_probot_1.createProbot; } })); +var loglevel_1 = __nccwpck_require__(6853); +exports.LogLevel = loglevel_1.LogLevel; +var session_1 = __nccwpck_require__(84954); +exports.SessionStatus = session_1.SessionStatus; +var severity_1 = __nccwpck_require__(94124); +exports.Severity = severity_1.Severity; +var status_1 = __nccwpck_require__(61277); +exports.Status = status_1.Status; +var transaction_1 = __nccwpck_require__(47540); +exports.TransactionSamplingMethod = transaction_1.TransactionSamplingMethod; //# sourceMappingURL=index.js.map /***/ }), -/***/ 18785: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; +/***/ 6853: +/***/ ((__unused_webpack_module, exports) => { -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__(21917)); -const path_1 = __importDefault(__nccwpck_require__(71017)); -const update_dotenv_1 = __importDefault(__nccwpck_require__(51023)); -const probot_octokit_1 = __nccwpck_require__(97268); -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}/settings/apps/new`; - } -} -exports.ManifestCreation = ManifestCreation; -//# sourceMappingURL=manifest-creation.js.map +/** Console logging verbosity for the SDK. */ +var LogLevel; +(function (LogLevel) { + /** No logs will be generated. */ + LogLevel[LogLevel["None"] = 0] = "None"; + /** Only SDK internal errors will be logged. */ + LogLevel[LogLevel["Error"] = 1] = "Error"; + /** Information useful for debugging the SDK will be logged. */ + LogLevel[LogLevel["Debug"] = 2] = "Debug"; + /** All SDK actions will be logged. */ + LogLevel[LogLevel["Verbose"] = 3] = "Verbose"; +})(LogLevel = exports.LogLevel || (exports.LogLevel = {})); +//# sourceMappingURL=loglevel.js.map /***/ }), -/***/ 53535: +/***/ 84954: /***/ ((__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 +/** + * Session Status + */ +var SessionStatus; +(function (SessionStatus) { + /** JSDoc */ + SessionStatus["Ok"] = "ok"; + /** JSDoc */ + SessionStatus["Exited"] = "exited"; + /** JSDoc */ + SessionStatus["Crashed"] = "crashed"; + /** JSDoc */ + SessionStatus["Abnormal"] = "abnormal"; +})(SessionStatus = exports.SessionStatus || (exports.SessionStatus = {})); +//# sourceMappingURL=session.js.map /***/ }), -/***/ 51729: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; +/***/ 94124: +/***/ ((__unused_webpack_module, exports) => { -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 +/** JSDoc */ +// eslint-disable-next-line import/export +var Severity; +(function (Severity) { + /** JSDoc */ + Severity["Fatal"] = "fatal"; + /** JSDoc */ + Severity["Error"] = "error"; + /** JSDoc */ + Severity["Warning"] = "warning"; + /** JSDoc */ + Severity["Log"] = "log"; + /** JSDoc */ + Severity["Info"] = "info"; + /** JSDoc */ + Severity["Debug"] = "debug"; + /** JSDoc */ + Severity["Critical"] = "critical"; +})(Severity = exports.Severity || (exports.Severity = {})); +// eslint-disable-next-line @typescript-eslint/no-namespace, import/export +(function (Severity) { + /** + * Converts a string-based level into a {@link Severity}. + * + * @param level string representation of Severity + * @returns Severity + */ + function fromString(level) { + switch (level) { + case 'debug': + return Severity.Debug; + case 'info': + return Severity.Info; + case 'warn': + case 'warning': + return Severity.Warning; + case 'error': + return Severity.Error; + case 'fatal': + return Severity.Fatal; + case 'critical': + return Severity.Critical; + case 'log': + default: + return Severity.Log; + } + } + Severity.fromString = fromString; +})(Severity = exports.Severity || (exports.Severity = {})); +//# sourceMappingURL=severity.js.map /***/ }), -/***/ 1330: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; +/***/ 61277: +/***/ ((__unused_webpack_module, exports) => { Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getProbotOctokitWithDefaults = void 0; -const get_octokit_throttle_options_1 = __nccwpck_require__(51729); -/** - * 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, +/** The status of an event. */ +// eslint-disable-next-line import/export +var Status; +(function (Status) { + /** The status could not be determined. */ + Status["Unknown"] = "unknown"; + /** The event was skipped due to configuration or callbacks. */ + Status["Skipped"] = "skipped"; + /** The event was sent to Sentry successfully. */ + Status["Success"] = "success"; + /** The client is currently rate limited and will try again later. */ + Status["RateLimit"] = "rate_limit"; + /** The event could not be processed. */ + Status["Invalid"] = "invalid"; + /** A server-side error ocurred during submission. */ + Status["Failed"] = "failed"; +})(Status = exports.Status || (exports.Status = {})); +// eslint-disable-next-line @typescript-eslint/no-namespace, import/export +(function (Status) { + /** + * Converts a HTTP status code into a {@link Status}. + * + * @param code The HTTP response status code. + * @returns The send status or {@link Status.Unknown}. + */ + function fromHttpCode(code) { + if (code >= 200 && code < 300) { + return Status.Success; } - : { - 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); + if (code === 429) { + return Status.RateLimit; + } + if (code >= 400 && code < 500) { + return Status.Invalid; } - return options; - }); -} -exports.getProbotOctokitWithDefaults = getProbotOctokitWithDefaults; -//# sourceMappingURL=get-probot-octokit-with-defaults.js.map + if (code >= 500) { + return Status.Failed; + } + return Status.Unknown; + } + Status.fromHttpCode = fromHttpCode; +})(Status = exports.Status || (exports.Status = {})); +//# sourceMappingURL=status.js.map /***/ }), -/***/ 879: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; +/***/ 47540: +/***/ ((__unused_webpack_module, exports) => { Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getWebhooks = void 0; -const webhooks_1 = __nccwpck_require__(18513); -const get_error_handler_1 = __nccwpck_require__(5789); -const octokit_webhooks_transform_1 = __nccwpck_require__(16973); -// 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 +var TransactionSamplingMethod; +(function (TransactionSamplingMethod) { + TransactionSamplingMethod["Explicit"] = "explicitly_set"; + TransactionSamplingMethod["Sampler"] = "client_sampler"; + TransactionSamplingMethod["Rate"] = "client_rate"; + TransactionSamplingMethod["Inheritance"] = "inheritance"; +})(TransactionSamplingMethod = exports.TransactionSamplingMethod || (exports.TransactionSamplingMethod = {})); +//# sourceMappingURL=transaction.js.map /***/ }), -/***/ 7828: +/***/ 58343: /***/ ((__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); +/** + * Consumes the promise and logs the error when it rejects. + * @param promise A promise to forget. + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function forget(promise) { + promise.then(null, function (e) { + // TODO: Use a better logging mechanism + // eslint-disable-next-line no-console + console.error(e); }); } -exports.probotRequestLogging = probotRequestLogging; -//# sourceMappingURL=octokit-plugin-probot-request-logging.js.map +exports.forget = forget; +//# sourceMappingURL=async.js.map /***/ }), -/***/ 16973: +/***/ 30597: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; - Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.webhookTransform = void 0; -const context_1 = __nccwpck_require__(45006); +var is_1 = __nccwpck_require__(92757); /** - * 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 + * Given a child DOM element, returns a query-selector statement describing that + * and its ancestors + * e.g. [HTMLElement] => body > div > input#foo.btn[name=baz] + * @returns generated DOM path */ -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); +function htmlTreeAsString(elem) { + // try/catch both: + // - accessing event.target (see getsentry/raven-js#838, #768) + // - `htmlTreeAsString` because it's complex, and just accessing the DOM incorrectly + // - can throw an exception in some circumstances. + try { + var currentElem = elem; + var MAX_TRAVERSE_HEIGHT = 5; + var MAX_OUTPUT_LEN = 80; + var out = []; + var height = 0; + var len = 0; + var separator = ' > '; + var sepLength = separator.length; + var nextStr = void 0; + // eslint-disable-next-line no-plusplus + while (currentElem && height++ < MAX_TRAVERSE_HEIGHT) { + nextStr = _htmlElementAsString(currentElem); + // bail out if + // - nextStr is the 'html' element + // - the length of the string that would be created exceeds MAX_OUTPUT_LEN + // (ignore this limit if we are on the first iteration) + if (nextStr === 'html' || (height > 1 && len + out.length * sepLength + nextStr.length >= MAX_OUTPUT_LEN)) { + break; + } + out.push(nextStr); + len += nextStr.length; + currentElem = currentElem.parentNode; + } + return out.reverse().join(separator); + } + catch (_oO) { + return ''; + } } -exports.webhookTransform = webhookTransform; -//# sourceMappingURL=octokit-webhooks-transform.js.map +exports.htmlTreeAsString = htmlTreeAsString; +/** + * Returns a simple, query-selector representation of a DOM element + * e.g. [HTMLElement] => input#foo.btn[name=baz] + * @returns generated DOM path + */ +function _htmlElementAsString(el) { + var elem = el; + var out = []; + var className; + var classes; + var key; + var attr; + var i; + if (!elem || !elem.tagName) { + return ''; + } + out.push(elem.tagName.toLowerCase()); + if (elem.id) { + out.push("#" + elem.id); + } + // eslint-disable-next-line prefer-const + className = elem.className; + if (className && is_1.isString(className)) { + classes = className.split(/\s+/); + for (i = 0; i < classes.length; i++) { + out.push("." + classes[i]); + } + } + var allowedAttrs = ['type', 'name', 'title', 'alt']; + for (i = 0; i < allowedAttrs.length; i++) { + key = allowedAttrs[i]; + attr = elem.getAttribute(key); + if (attr) { + out.push("[" + key + "=\"" + attr + "\"]"); + } + } + return out.join(''); +} +//# sourceMappingURL=browser.js.map /***/ }), -/***/ 97268: +/***/ 3275: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __nccwpck_require__(4351); +var error_1 = __nccwpck_require__(66238); +/** Regular expression used to parse a Dsn. */ +var DSN_REGEX = /^(?:(\w+):)\/\/(?:(\w+)(?::(\w+))?@)([\w.-]+)(?::(\d+))?\/(.+)/; +/** Error message */ +var ERROR_MESSAGE = 'Invalid Dsn'; +/** The Sentry Dsn, identifying a Sentry instance and project. */ +var Dsn = /** @class */ (function () { + /** Creates a new Dsn component */ + function Dsn(from) { + if (typeof from === 'string') { + this._fromString(from); + } + else { + this._fromComponents(from); + } + this._validate(); + } + /** + * Renders the string representation of this Dsn. + * + * By default, this will render the public representation without the password + * component. To get the deprecated private representation, set `withPassword` + * to true. + * + * @param withPassword When set to true, the password will be included. + */ + Dsn.prototype.toString = function (withPassword) { + if (withPassword === void 0) { withPassword = false; } + var _a = this, host = _a.host, path = _a.path, pass = _a.pass, port = _a.port, projectId = _a.projectId, protocol = _a.protocol, user = _a.user; + return (protocol + "://" + user + (withPassword && pass ? ":" + pass : '') + + ("@" + host + (port ? ":" + port : '') + "/" + (path ? path + "/" : path) + projectId)); + }; + /** Parses a string into this Dsn. */ + Dsn.prototype._fromString = function (str) { + var match = DSN_REGEX.exec(str); + if (!match) { + throw new error_1.SentryError(ERROR_MESSAGE); + } + var _a = tslib_1.__read(match.slice(1), 6), protocol = _a[0], user = _a[1], _b = _a[2], pass = _b === void 0 ? '' : _b, host = _a[3], _c = _a[4], port = _c === void 0 ? '' : _c, lastPath = _a[5]; + var path = ''; + var projectId = lastPath; + var split = projectId.split('/'); + if (split.length > 1) { + path = split.slice(0, -1).join('/'); + projectId = split.pop(); + } + if (projectId) { + var projectMatch = projectId.match(/^\d+/); + if (projectMatch) { + projectId = projectMatch[0]; + } + } + this._fromComponents({ host: host, pass: pass, path: path, projectId: projectId, port: port, protocol: protocol, user: user }); + }; + /** Maps Dsn components into this instance. */ + Dsn.prototype._fromComponents = function (components) { + this.protocol = components.protocol; + this.user = components.user; + this.pass = components.pass || ''; + this.host = components.host; + this.port = components.port || ''; + this.path = components.path || ''; + this.projectId = components.projectId; + }; + /** Validates this Dsn and throws on error. */ + Dsn.prototype._validate = function () { + var _this = this; + ['protocol', 'user', 'host', 'projectId'].forEach(function (component) { + if (!_this[component]) { + throw new error_1.SentryError(ERROR_MESSAGE + ": " + component + " missing"); + } + }); + if (!this.projectId.match(/^\d+$/)) { + throw new error_1.SentryError(ERROR_MESSAGE + ": Invalid projectId " + this.projectId); + } + if (this.protocol !== 'http' && this.protocol !== 'https') { + throw new error_1.SentryError(ERROR_MESSAGE + ": Invalid protocol " + this.protocol); + } + if (this.port && isNaN(parseInt(this.port, 10))) { + throw new error_1.SentryError(ERROR_MESSAGE + ": Invalid port " + this.port); + } + }; + return Dsn; +}()); +exports.Dsn = Dsn; +//# sourceMappingURL=dsn.js.map + +/***/ }), + +/***/ 66238: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 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__(7828); -const version_1 = __nccwpck_require__(1403); -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 +var tslib_1 = __nccwpck_require__(4351); +var polyfill_1 = __nccwpck_require__(1243); +/** An error emitted by Sentry SDKs and related utilities. */ +var SentryError = /** @class */ (function (_super) { + tslib_1.__extends(SentryError, _super); + function SentryError(message) { + var _newTarget = this.constructor; + var _this = _super.call(this, message) || this; + _this.message = message; + _this.name = _newTarget.prototype.constructor.name; + polyfill_1.setPrototypeOf(_this, _newTarget.prototype); + return _this; + } + return SentryError; +}(Error)); +exports.SentryError = SentryError; +//# sourceMappingURL=error.js.map /***/ }), -/***/ 22357: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ 1620: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __nccwpck_require__(4351); +tslib_1.__exportStar(__nccwpck_require__(58343), exports); +tslib_1.__exportStar(__nccwpck_require__(30597), exports); +tslib_1.__exportStar(__nccwpck_require__(3275), exports); +tslib_1.__exportStar(__nccwpck_require__(66238), exports); +tslib_1.__exportStar(__nccwpck_require__(65474), exports); +tslib_1.__exportStar(__nccwpck_require__(92757), exports); +tslib_1.__exportStar(__nccwpck_require__(15577), exports); +tslib_1.__exportStar(__nccwpck_require__(49515), exports); +tslib_1.__exportStar(__nccwpck_require__(32154), exports); +tslib_1.__exportStar(__nccwpck_require__(16411), exports); +tslib_1.__exportStar(__nccwpck_require__(69249), exports); +tslib_1.__exportStar(__nccwpck_require__(39188), exports); +tslib_1.__exportStar(__nccwpck_require__(31811), exports); +tslib_1.__exportStar(__nccwpck_require__(5986), exports); +tslib_1.__exportStar(__nccwpck_require__(66538), exports); +tslib_1.__exportStar(__nccwpck_require__(88714), exports); +tslib_1.__exportStar(__nccwpck_require__(87833), exports); +tslib_1.__exportStar(__nccwpck_require__(1735), exports); +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 65474: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -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__(19752); -const auth_1 = __nccwpck_require__(81084); -const get_log_1 = __nccwpck_require__(90751); -const get_probot_octokit_with_defaults_1 = __nccwpck_require__(1330); -const get_webhooks_1 = __nccwpck_require__(879); -const probot_octokit_1 = __nccwpck_require__(97268); -const version_1 = __nccwpck_require__(1403); -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; +var tslib_1 = __nccwpck_require__(4351); +var is_1 = __nccwpck_require__(92757); +var logger_1 = __nccwpck_require__(15577); +var misc_1 = __nccwpck_require__(32154); +var object_1 = __nccwpck_require__(69249); +var stacktrace_1 = __nccwpck_require__(5986); +var supports_1 = __nccwpck_require__(88714); +var global = misc_1.getGlobalObject(); +/** + * Instrument native APIs to call handlers that can be used to create breadcrumbs, APM spans etc. + * - Console API + * - Fetch API + * - XHR API + * - History API + * - DOM API (click/typing) + * - Error API + * - UnhandledRejection API + */ +var handlers = {}; +var instrumented = {}; +/** Instruments given API */ +function instrument(type) { + if (instrumented[type]) { + return; + } + instrumented[type] = true; + switch (type) { + case 'console': + instrumentConsole(); + break; + case 'dom': + instrumentDOM(); + break; + case 'xhr': + instrumentXHR(); + break; + case 'fetch': + instrumentFetch(); + break; + case 'history': + instrumentHistory(); + break; + case 'error': + instrumentError(); + break; + case 'unhandledrejection': + instrumentUnhandledRejection(); + break; + default: + logger_1.logger.warn('unknown instrumentation type:', type); + } +} +/** + * Add handler that will be called when given type of instrumentation triggers. + * Use at your own risk, this might break without changelog notice, only used internally. + * @hidden + */ +function addInstrumentationHandler(handler) { + if (!handler || typeof handler.type !== 'string' || typeof handler.callback !== 'function') { + return; + } + handlers[handler.type] = handlers[handler.type] || []; + handlers[handler.type].push(handler.callback); + instrument(handler.type); +} +exports.addInstrumentationHandler = addInstrumentationHandler; +/** JSDoc */ +function triggerHandlers(type, data) { + var e_1, _a; + if (!type || !handlers[type]) { + return; + } + try { + for (var _b = tslib_1.__values(handlers[type] || []), _c = _b.next(); !_c.done; _c = _b.next()) { + var handler = _c.value; + try { + handler(data); + } + catch (e) { + logger_1.logger.error("Error while triggering instrumentation handler.\nType: " + type + "\nName: " + stacktrace_1.getFunctionName(handler) + "\nError: " + e); + } + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (_c && !_c.done && (_a = _b.return)) _a.call(_b); + } + finally { if (e_1) throw e_1.error; } + } +} +/** JSDoc */ +function instrumentConsole() { + if (!('console' in global)) { + return; + } + ['debug', 'info', 'warn', 'error', 'log', 'assert'].forEach(function (level) { + if (!(level in global.console)) { + return; + } + object_1.fill(global.console, level, function (originalConsoleLevel) { + return function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + triggerHandlers('console', { args: args, level: level }); + // this fails for some browsers. :( + if (originalConsoleLevel) { + Function.prototype.apply.call(originalConsoleLevel, global.console, args); + } + }; + }); + }); +} +/** JSDoc */ +function instrumentFetch() { + if (!supports_1.supportsNativeFetch()) { + return; } - static defaults(defaults) { - const ProbotWithDefaults = class extends this { - constructor(...args) { - const options = args[0] || {}; - super(Object.assign({}, defaults, options)); + object_1.fill(global, 'fetch', function (originalFetch) { + return function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; } + var handlerData = { + args: args, + fetchData: { + method: getFetchMethod(args), + url: getFetchUrl(args), + }, + startTimestamp: Date.now(), + }; + triggerHandlers('fetch', tslib_1.__assign({}, handlerData)); + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + return originalFetch.apply(global, args).then(function (response) { + triggerHandlers('fetch', tslib_1.__assign(tslib_1.__assign({}, handlerData), { endTimestamp: Date.now(), response: response })); + return response; + }, function (error) { + triggerHandlers('fetch', tslib_1.__assign(tslib_1.__assign({}, handlerData), { endTimestamp: Date.now(), error: error })); + // NOTE: If you are a Sentry user, and you are seeing this stack frame, + // it means the sentry.javascript SDK caught an error invoking your application code. + // This is expected behavior and NOT indicative of a bug with sentry.javascript. + throw error; + }); }; - return ProbotWithDefaults; + }); +} +/* eslint-disable @typescript-eslint/no-unsafe-member-access */ +/** Extract `method` from fetch call arguments */ +function getFetchMethod(fetchArgs) { + if (fetchArgs === void 0) { fetchArgs = []; } + if ('Request' in global && is_1.isInstanceOf(fetchArgs[0], Request) && fetchArgs[0].method) { + return String(fetchArgs[0].method).toUpperCase(); } - receive(event) { - this.log.debug({ event }, "Webhook received"); - return this.webhooks.receive(event); + if (fetchArgs[1] && fetchArgs[1].method) { + return String(fetchArgs[1].method).toUpperCase(); } - async load(appFn) { - if (Array.isArray(appFn)) { - for (const fn of appFn) { - await this.load(fn); - } - return; - } - return appFn(this, {}); + return 'GET'; +} +/** Extract `url` from fetch call arguments */ +function getFetchUrl(fetchArgs) { + if (fetchArgs === void 0) { fetchArgs = []; } + if (typeof fetchArgs[0] === 'string') { + return fetchArgs[0]; + } + if ('Request' in global && is_1.isInstanceOf(fetchArgs[0], Request)) { + return fetchArgs[0].url; } + return String(fetchArgs[0]); } -exports.Probot = Probot; -Probot.version = version_1.VERSION; -//# sourceMappingURL=probot.js.map - -/***/ }), - -/***/ 57124: -/***/ (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__(93181); -const setup_1 = __nccwpck_require__(36769); -const get_log_1 = __nccwpck_require__(90751); -const read_cli_options_1 = __nccwpck_require__(57767); -const read_env_options_1 = __nccwpck_require__(74420); -const server_1 = __nccwpck_require__(83148); -const default_1 = __nccwpck_require__(3598); -const resolve_app_function_1 = __nccwpck_require__(33208); -const is_production_1 = __nccwpck_require__(75381); -/** - * - * @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."); +/* eslint-enable @typescript-eslint/no-unsafe-member-access */ +/** JSDoc */ +function instrumentXHR() { + if (!('XMLHttpRequest' in global)) { + return; + } + // Poor man's implementation of ES6 `Map`, tracking and keeping in sync key and value separately. + var requestKeys = []; + var requestValues = []; + var xhrproto = XMLHttpRequest.prototype; + object_1.fill(xhrproto, 'open', function (originalOpen) { + return function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; } - 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"); + // eslint-disable-next-line @typescript-eslint/no-this-alias + var xhr = this; + var url = args[1]; + xhr.__sentry_xhr__ = { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + method: is_1.isString(args[0]) ? args[0].toUpperCase() : args[0], + url: args[1], + }; + // if Sentry key appears in URL, don't capture it as a request + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + if (is_1.isString(url) && xhr.__sentry_xhr__.method === 'POST' && url.match(/sentry_key/)) { + xhr.__sentry_own_request__ = true; } - } - // 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); + var onreadystatechangeHandler = function () { + if (xhr.readyState === 4) { + try { + // touching statusCode in some platforms throws + // an exception + if (xhr.__sentry_xhr__) { + xhr.__sentry_xhr__.status_code = xhr.status; + } + } + catch (e) { + /* do nothing */ + } + try { + var requestPos = requestKeys.indexOf(xhr); + if (requestPos !== -1) { + // Make sure to pop both key and value to keep it in sync. + requestKeys.splice(requestPos); + var args_1 = requestValues.splice(requestPos)[0]; + if (xhr.__sentry_xhr__ && args_1[0] !== undefined) { + xhr.__sentry_xhr__.body = args_1[0]; + } + } + } + catch (e) { + /* do nothing */ + } + triggerHandlers('xhr', { + args: args, + endTimestamp: Date.now(), + startTimestamp: Date.now(), + xhr: xhr, + }); } + }; + if ('onreadystatechange' in xhr && typeof xhr.onreadystatechange === 'function') { + object_1.fill(xhr, 'onreadystatechange', function (original) { + return function () { + var readyStateArgs = []; + for (var _i = 0; _i < arguments.length; _i++) { + readyStateArgs[_i] = arguments[_i]; + } + onreadystatechangeHandler(); + return original.apply(xhr, readyStateArgs); + }; + }); } - const [appPath] = args; - const appFn = await resolve_app_function_1.resolveAppFunction(appPath); - await server.load(appFn); + else { + xhr.addEventListener('readystatechange', onreadystatechangeHandler); + } + return originalOpen.apply(xhr, args); }; - 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 - -/***/ }), - -/***/ 24631: -/***/ (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 - -/***/ }), - -/***/ 83148: -/***/ (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__(90751); -const logging_middleware_1 = __nccwpck_require__(24631); -const webhook_proxy_1 = __nccwpck_require__(66217); -const version_1 = __nccwpck_require__(1403); -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, + object_1.fill(xhrproto, 'send', function (originalSend) { + return function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + requestKeys.push(this); + requestValues.push(args); + triggerHandlers('xhr', { + args: args, + startTimestamp: Date.now(), + xhr: this, + }); + return originalSend.apply(this, args); }; - 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")); + }); +} +var lastHref; +/** JSDoc */ +function instrumentHistory() { + if (!supports_1.supportsHistory()) { + return; } - async load(appFn) { - await appFn(this.probotApp, { - getRouter: (path) => this.router(path), + var oldOnPopState = global.onpopstate; + global.onpopstate = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + var to = global.location.href; + // keep track of the current URL state, as we always receive only the updated state + var from = lastHref; + lastHref = to; + triggerHandlers('history', { + from: from, + to: to, }); + if (oldOnPopState) { + return oldOnPopState.apply(this, args); + } + }; + /** @hidden */ + function historyReplacementFunction(originalHistoryFunction) { + return function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + var url = args.length > 2 ? args[2] : undefined; + if (url) { + // coerce to string (this is what pushState does) + var from = lastHref; + var to = String(url); + // keep track of the current URL state, as we always receive only the updated state + lastHref = to; + triggerHandlers('history', { + from: from, + to: to, + }); + } + return originalHistoryFunction.apply(this, args); + }; } - 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, - }); + object_1.fill(global.history, 'pushState', historyReplacementFunction); + object_1.fill(global.history, 'replaceState', historyReplacementFunction); +} +/** JSDoc */ +function instrumentDOM() { + if (!('document' in global)) { + return; + } + // Capture breadcrumbs from any click that is unhandled / bubbled up all the way + // to the document. Do this before we instrument addEventListener. + global.document.addEventListener('click', domEventHandler('click', triggerHandlers.bind(null, 'dom')), false); + global.document.addEventListener('keypress', keypressEventHandler(triggerHandlers.bind(null, 'dom')), false); + // After hooking into document bubbled up click and keypresses events, we also hook into user handled click & keypresses. + ['EventTarget', 'Node'].forEach(function (target) { + /* eslint-disable @typescript-eslint/no-unsafe-member-access */ + var proto = global[target] && global[target].prototype; + // eslint-disable-next-line no-prototype-builtins + if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty('addEventListener')) { + return; + } + /* eslint-enable @typescript-eslint/no-unsafe-member-access */ + object_1.fill(proto, 'addEventListener', function (original) { + return function (eventName, fn, options) { + if (fn && fn.handleEvent) { + if (eventName === 'click') { + object_1.fill(fn, 'handleEvent', function (innerOriginal) { + return function (event) { + domEventHandler('click', triggerHandlers.bind(null, 'dom'))(event); + return innerOriginal.call(this, event); + }; + }); + } + if (eventName === 'keypress') { + object_1.fill(fn, 'handleEvent', function (innerOriginal) { + return function (event) { + keypressEventHandler(triggerHandlers.bind(null, 'dom'))(event); + return innerOriginal.call(this, event); + }; + }); + } } - 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.`, - }); + else { + if (eventName === 'click') { + domEventHandler('click', triggerHandlers.bind(null, 'dom'), true)(this); + } + if (eventName === 'keypress') { + keypressEventHandler(triggerHandlers.bind(null, 'dom'))(this); + } } - this.log.error(error); - reject(error); + return original.call(this, eventName, fn, options); + }; + }); + object_1.fill(proto, 'removeEventListener', function (original) { + return function (eventName, fn, options) { + try { + original.call(this, eventName, fn.__sentry_wrapped__, options); + } + catch (e) { + // ignore, accessing __sentry_wrapped__ will throw in some Selenium environments + } + return original.call(this, eventName, fn, options); + }; + }); + }); +} +var debounceDuration = 1000; +var debounceTimer = 0; +var keypressTimeout; +var lastCapturedEvent; +/** + * Wraps addEventListener to capture UI breadcrumbs + * @param name the event name (e.g. "click") + * @param handler function that will be triggered + * @param debounce decides whether it should wait till another event loop + * @returns wrapped breadcrumb events handler + * @hidden + */ +function domEventHandler(name, handler, debounce) { + if (debounce === void 0) { debounce = false; } + return function (event) { + // reset keypress timeout; e.g. triggering a 'click' after + // a 'keypress' will reset the keypress debounce so that a new + // set of keypresses can be recorded + keypressTimeout = undefined; + // It's possible this handler might trigger multiple times for the same + // event (e.g. event propagation through node ancestors). Ignore if we've + // already captured the event. + if (!event || lastCapturedEvent === event) { + return; + } + lastCapturedEvent = event; + if (debounceTimer) { + clearTimeout(debounceTimer); + } + if (debounce) { + debounceTimer = setTimeout(function () { + handler({ event: event, name: name }); }); - })); - return this.state.httpServer; - } - async stop() { - if (this.state.eventSource) - this.state.eventSource.close(); - if (!this.state.httpServer) + } + else { + handler({ event: event, name: name }); + } + }; +} +/** + * Wraps addEventListener to capture keypress UI events + * @param handler function that will be triggered + * @returns wrapped keypress events handler + * @hidden + */ +function keypressEventHandler(handler) { + // TODO: if somehow user switches keypress target before + // debounce timeout is triggered, we will only capture + // a single breadcrumb from the FIRST target (acceptable?) + return function (event) { + var target; + try { + target = event.target; + } + catch (e) { + // just accessing event properties can throw an exception in some rare circumstances + // see: https://github.com/getsentry/raven-js/issues/838 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; - } + } + var tagName = target && target.tagName; + // only consider keypress events on actual input elements + // this will disregard keypresses targeting body (e.g. tabbing + // through elements, hotkeys, etc) + if (!tagName || (tagName !== 'INPUT' && tagName !== 'TEXTAREA' && !target.isContentEditable)) { + return; + } + // record first keypress in a series, but ignore subsequent + // keypresses until debounce clears + if (!keypressTimeout) { + domEventHandler('input', handler)(event); + } + clearTimeout(keypressTimeout); + keypressTimeout = setTimeout(function () { + keypressTimeout = undefined; + }, debounceDuration); + }; } -exports.Server = Server; -Server.version = version_1.VERSION; -//# sourceMappingURL=server.js.map +var _oldOnErrorHandler = null; +/** JSDoc */ +function instrumentError() { + _oldOnErrorHandler = global.onerror; + global.onerror = function (msg, url, line, column, error) { + triggerHandlers('error', { + column: column, + error: error, + line: line, + msg: msg, + url: url, + }); + if (_oldOnErrorHandler) { + // eslint-disable-next-line prefer-rest-params + return _oldOnErrorHandler.apply(this, arguments); + } + return false; + }; +} +var _oldOnUnhandledRejectionHandler = null; +/** JSDoc */ +function instrumentUnhandledRejection() { + _oldOnUnhandledRejectionHandler = global.onunhandledrejection; + global.onunhandledrejection = function (e) { + triggerHandlers('unhandledrejection', e); + if (_oldOnUnhandledRejectionHandler) { + // eslint-disable-next-line prefer-rest-params + return _oldOnUnhandledRejectionHandler.apply(this, arguments); + } + return true; + }; +} +//# sourceMappingURL=instrument.js.map /***/ }), -/***/ 1403: +/***/ 92757: /***/ ((__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.1.4"; -//# sourceMappingURL=version.js.map - -/***/ }), - -/***/ 96645: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const { inspect } = __nccwpck_require__(73837); - -const through = __nccwpck_require__(18180); -const core = __nccwpck_require__(68648); -const pino = __nccwpck_require__(79608); - -const LEVEL_TO_ACTIONS_CORE_LOG_METHOD = { - trace: "debug", - debug: "debug", - info: "info", - warn: "warning", - error: "error", - fatal: "error", -}; - -const transport = through.obj(function (chunk, enc, cb) { - const { level, hostname, pid, msg, time, ...meta } = JSON.parse(chunk); - const levelLabel = pino.levels.labels[level] || level; - const logMethodName = LEVEL_TO_ACTIONS_CORE_LOG_METHOD[levelLabel]; - - const output = [ - msg, - Object.keys(meta).length ? inspect(meta, { depth: Infinity }) : "", - ] - .join("\n") - .trim(); - - if (logMethodName in core) { - core[logMethodName](output); - } else { - core.error(`"${level}" is not a known log level - ${output}`); - } - - cb(); -}); - -module.exports = { transport }; - - -/***/ }), - -/***/ 97743: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - +/* eslint-disable @typescript-eslint/no-explicit-any */ +/* eslint-disable @typescript-eslint/explicit-module-boundary-types */ Object.defineProperty(exports, "__esModule", ({ value: true })); - -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - -var path = __nccwpck_require__(71017); -var fs = __nccwpck_require__(57147); -var isBase64 = _interopDefault(__nccwpck_require__(31310)); - -const VERSION = "0.0.0-development"; - -function getPrivateKey(options = {}) { - const env = options.env || process.env; - const cwd = options.cwd || process.cwd(); - - if (options.filepath) { - return fs.readFileSync(path.resolve(cwd, options.filepath), "utf-8"); - } - - if (env.PRIVATE_KEY) { - let privateKey = env.PRIVATE_KEY; - - if (isBase64(privateKey)) { - // Decode base64-encoded certificate - privateKey = Buffer.from(privateKey, "base64").toString(); - } - - const begin = "-----BEGIN RSA PRIVATE KEY-----"; - const end = "-----END RSA PRIVATE KEY-----"; - - if (privateKey.includes(begin) && privateKey.includes(end)) { - // Full key with new lines - return privateKey.replace(/\\n/g, "\n"); - } - - throw new Error(`[@probot/get-private-key] The contents of "env.PRIVATE_KEY" could not be validated. Please check to ensure you have copied the contents of the .pem file correctly.`); - } - - if (env.PRIVATE_KEY_PATH) { - const filepath = path.resolve(cwd, env.PRIVATE_KEY_PATH); - - if (fs.existsSync(filepath)) { - return fs.readFileSync(filepath, "utf-8"); - } else { - throw new Error(`[@probot/get-private-key] Private key does not exists at path: "${env.PRIVATE_KEY_PATH}". Please check to ensure that "env.PRIVATE_KEY_PATH" is correct.`); +/** + * Checks whether given value's type is one of a few Error or Error-like + * {@link isError}. + * + * @param wat A value to be checked. + * @returns A boolean representing the result. + */ +function isError(wat) { + switch (Object.prototype.toString.call(wat)) { + case '[object Error]': + return true; + case '[object Exception]': + return true; + case '[object DOMException]': + return true; + default: + return isInstanceOf(wat, Error); } - } - - const pemFiles = fs.readdirSync(cwd).filter(path => path.endsWith(".pem")); - - if (pemFiles.length > 1) { - const paths = pemFiles.join(", "); - throw new Error(`[@probot/get-private-key] More than one file found: "${paths}". Set { filepath } option or set one of the environment variables: PRIVATE_KEY, PRIVATE_KEY_PATH`); - } else if (pemFiles[0]) { - return getPrivateKey({ - filepath: pemFiles[0], - cwd - }); - } - - return null; } -getPrivateKey.VERSION = VERSION; - -exports.getPrivateKey = getPrivateKey; -//# sourceMappingURL=index.js.map - - -/***/ }), - -/***/ 59326: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ value: true })); - -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - -var yaml = _interopDefault(__nccwpck_require__(21917)); - -const VERSION = "1.0.1"; - -function _defineProperty(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; - } - - return obj; +exports.isError = isError; +/** + * Checks whether given value's type is ErrorEvent + * {@link isErrorEvent}. + * + * @param wat A value to be checked. + * @returns A boolean representing the result. + */ +function isErrorEvent(wat) { + return Object.prototype.toString.call(wat) === '[object ErrorEvent]'; } - -function ownKeys(object, enumerableOnly) { - var keys = Object.keys(object); - - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(object); - if (enumerableOnly) symbols = symbols.filter(function (sym) { - return Object.getOwnPropertyDescriptor(object, sym).enumerable; - }); - keys.push.apply(keys, symbols); - } - - return keys; +exports.isErrorEvent = isErrorEvent; +/** + * Checks whether given value's type is DOMError + * {@link isDOMError}. + * + * @param wat A value to be checked. + * @returns A boolean representing the result. + */ +function isDOMError(wat) { + return Object.prototype.toString.call(wat) === '[object DOMError]'; } - -function _objectSpread2(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? arguments[i] : {}; - - if (i % 2) { - ownKeys(Object(source), true).forEach(function (key) { - _defineProperty(target, key, source[key]); - }); - } else if (Object.getOwnPropertyDescriptors) { - Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); - } else { - ownKeys(Object(source)).forEach(function (key) { - Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); - }); - } - } - - return target; +exports.isDOMError = isDOMError; +/** + * Checks whether given value's type is DOMException + * {@link isDOMException}. + * + * @param wat A value to be checked. + * @returns A boolean representing the result. + */ +function isDOMException(wat) { + return Object.prototype.toString.call(wat) === '[object DOMException]'; } - -const SUPPORTED_FILE_EXTENSIONS = ["json", "yml", "yaml"]; +exports.isDOMException = isDOMException; /** - * Load configuration from a given repository and path. + * Checks whether given value's type is a string + * {@link isString}. * - * @param octokit Octokit instance - * @param options + * @param wat A value to be checked. + * @returns A boolean representing the result. */ - -async function getConfigFile(octokit, { - owner, - repo, - path, - ref -}) { - const fileExtension = path.split(".").pop().toLowerCase(); - - if (!SUPPORTED_FILE_EXTENSIONS.includes(fileExtension)) { - throw new Error(`[@probot/octokit-plugin-config] .${fileExtension} extension is not support for configuration (path: "${path}")`); - } // https://docs.github.com/en/rest/reference/repos#get-repository-content - - - const requestOptions = await octokit.request.endpoint("GET /repos/{owner}/{repo}/contents/{path}", _objectSpread2({ - owner, - repo, - path, - mediaType: { - format: "raw" - } - }, ref ? { - ref - } : {})); - const emptyConfigResult = { - owner, - repo, - path, - url: requestOptions.url, - config: null - }; - - try { - const { - data, - headers - } = await octokit.request(requestOptions); // If path is a submodule, or a folder, then a JSON string is returned with - // the "Content-Type" header set to "application/json; charset=utf-8". - // - // - https://docs.github.com/en/rest/reference/repos#if-the-content-is-a-submodule - // - https://docs.github.com/en/rest/reference/repos#if-the-content-is-a-directory - // - // symlinks just return the content of the linked file when requesting the raw formt, - // so we are fine - - if (headers["content-type"] === "application/json; charset=utf-8") { - throw new Error(`[@probot/octokit-plugin-config] ${requestOptions.url} exists, but is either a directory or a submodule. Ignoring.`); - } - - if (fileExtension === "json") { - if (typeof data === "string") { - throw new Error(`[@probot/octokit-plugin-config] Configuration could not be parsed from ${requestOptions.url} (invalid JSON)`); - } - - return _objectSpread2(_objectSpread2({}, emptyConfigResult), {}, { - config: data - }); - } - - const config = yaml.safeLoad(data) || {}; - - if (typeof config === "string") { - throw new Error(`[@probot/octokit-plugin-config] Configuration could not be parsed from ${requestOptions.url} (YAML is not an object)`); - } - - return _objectSpread2(_objectSpread2({}, emptyConfigResult), {}, { - config - }); - } catch (error) { - if (error.status === 404) { - return emptyConfigResult; - } - - if (error.name === "YAMLException") { - const reason = /unknown tag/.test(error.message) ? "unsafe YAML" : "invalid YAML"; - throw new Error(`[@probot/octokit-plugin-config] Configuration could not be parsed from ${requestOptions.url} (${reason})`); - } - - throw error; - } +function isString(wat) { + return Object.prototype.toString.call(wat) === '[object String]'; } - -const EXTENDS_REGEX = new RegExp("^" + "(?:([a-z\\d](?:[a-z\\d]|-(?=[a-z\\d])){0,38})/)?" + // org -"([-_.\\w\\d]+)" + // project -"(?::([-_./\\w\\d]+\\.ya?ml))?" + // filename -"$", "i"); +exports.isString = isString; /** - * Computes parameters to retrieve the configuration file specified in _extends + * Checks whether given value's is a primitive (undefined, null, number, boolean, string, bigint, symbol) + * {@link isPrimitive}. * - * Base can either be the name of a repository in the same organization or - * a full slug "organization/repo". + * @param wat A value to be checked. + * @returns A boolean representing the result. + */ +function isPrimitive(wat) { + return wat === null || (typeof wat !== 'object' && typeof wat !== 'function'); +} +exports.isPrimitive = isPrimitive; +/** + * Checks whether given value's type is an object literal + * {@link isPlainObject}. * - * @param options - * @return The params needed to retrieve a configuration file + * @param wat A value to be checked. + * @returns A boolean representing the result. */ - -function extendsToGetContentParams({ - owner, - path, - url, - extendsValue -}) { - if (typeof extendsValue !== "string") { - throw new Error(`[@probot/octokit-plugin-config] Invalid value ${JSON.stringify(extendsValue)} for _extends in ${url}`); - } - - const match = extendsValue.match(EXTENDS_REGEX); - - if (match === null) { - throw new Error(`[@probot/octokit-plugin-config] Invalid value "${extendsValue}" for _extends in ${url}`); - } - - return { - owner: match[1] || owner, - repo: match[2], - path: match[3] || path - }; +function isPlainObject(wat) { + return Object.prototype.toString.call(wat) === '[object Object]'; +} +exports.isPlainObject = isPlainObject; +/** + * Checks whether given value's type is an Event instance + * {@link isEvent}. + * + * @param wat A value to be checked. + * @returns A boolean representing the result. + */ +function isEvent(wat) { + return typeof Event !== 'undefined' && isInstanceOf(wat, Event); } - +exports.isEvent = isEvent; /** - * Load configuration from selected repository file. If the file does not exist - * it loads configuration from the owners `.github` repository. - * - * If the repository file configuration includes an `_extends` key, that file - * is loaded. Same with the target file until no `_extends` key is present. + * Checks whether given value's type is an Element instance + * {@link isElement}. * - * @param octokit Octokit instance - * @param options + * @param wat A value to be checked. + * @returns A boolean representing the result. */ - -async function getConfigFiles(octokit, { - owner, - repo, - path, - branch -}) { - const requestedRepoFile = await getConfigFile(octokit, { - owner, - repo, - path, - ref: branch - }); // if no configuration file present in selected repository, - // try to load it from the `.github` repository - - if (!requestedRepoFile.config) { - if (repo === ".github") { - return [requestedRepoFile]; - } - - const defaultRepoConfig = await getConfigFile(octokit, { - owner, - repo: ".github", - path - }); - return [requestedRepoFile, defaultRepoConfig]; - } // if the configuration has no `_extends` key, we are done here. - - - if (!requestedRepoFile.config._extends) { - return [requestedRepoFile]; - } // parse the value of `_extends` into request parameters to - // retrieve the new configuration file - - - let extendConfigOptions = extendsToGetContentParams({ - owner, - path, - url: requestedRepoFile.url, - extendsValue: requestedRepoFile.config._extends - }); // remove the `_extends` key from the configuration that is returned - - delete requestedRepoFile.config._extends; - const files = [requestedRepoFile]; // now load the configuration linked from the `_extends` key. If that - // configuration also includes an `_extends` key, then load that configuration - // as well, until the target configuration has no `_extends` key - - do { - const extendRepoConfig = await getConfigFile(octokit, extendConfigOptions); - files.push(extendRepoConfig); - - if (!extendRepoConfig.config || !extendRepoConfig.config._extends) { - return files; - } - - extendConfigOptions = extendsToGetContentParams({ - owner, - path, - url: extendRepoConfig.url, - extendsValue: extendRepoConfig.config._extends - }); - delete extendRepoConfig.config._extends; // Avoid loops - - const alreadyLoaded = files.find(file => file.owner === extendConfigOptions.owner && file.repo === extendConfigOptions.repo && file.path === extendConfigOptions.path); - - if (alreadyLoaded) { - throw new Error(`[@probot/octokit-plugin-config] Recursion detected. Ignoring "_extends: ${extendRepoConfig.config._extends}" from ${extendRepoConfig.url} because ${alreadyLoaded.url} was already loaded.`); - } - } while (true); +function isElement(wat) { + return typeof Element !== 'undefined' && isInstanceOf(wat, Element); } - +exports.isElement = isElement; /** - * Loads configuration from one or multiple files and resolves with - * the combined configuration as well as the list of files the configuration - * was loaded from + * Checks whether given value's type is an regexp + * {@link isRegExp}. * - * @param octokit Octokit instance - * @param options + * @param wat A value to be checked. + * @returns A boolean representing the result. */ - -async function composeConfigGet(octokit, { - owner, - repo, - defaults, - path, - branch -}) { - const files = await getConfigFiles(octokit, { - owner, - repo, - path, - branch - }); - const configs = files.map(file => file.config).reverse().filter(Boolean); - return { - files, - config: typeof defaults === "function" ? defaults(configs) : Object.assign({}, defaults, ...configs) - }; +function isRegExp(wat) { + return Object.prototype.toString.call(wat) === '[object RegExp]'; } - +exports.isRegExp = isRegExp; /** - * @param octokit Octokit instance + * Checks whether given value has a then function. + * @param wat A value to be checked. */ - -function config(octokit) { - return { - config: { - async get(options) { - return composeConfigGet(octokit, options); - } - - } - }; +function isThenable(wat) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + return Boolean(wat && wat.then && typeof wat.then === 'function'); } -config.VERSION = VERSION; - -exports.composeConfigGet = composeConfigGet; -exports.config = config; -//# sourceMappingURL=index.js.map - - -/***/ }), - -/***/ 39662: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -module.exports = { getTransformStream }; - -const { Transform } = __nccwpck_require__(51642); - -const prettyFactory = __nccwpck_require__(31691); -const Sentry = __nccwpck_require__(22783); - -const LEVEL_MAP = { - 10: "trace", - 20: "debug", - 30: "info", - 40: "warn", - 50: "error", - 60: "fatal", -}; - +exports.isThenable = isThenable; /** - * Implements Probot's default logging formatting and error captionaing using Sentry. + * Checks whether given value's type is a SyntheticEvent + * {@link isSyntheticEvent}. * - * @param {import("./").Options} options - * @returns Transform - * @see https://getpino.io/#/docs/transports + * @param wat A value to be checked. + * @returns A boolean representing the result. */ -function getTransformStream(options = {}) { - const formattingEnabled = options.logFormat !== "json"; - const levelAsString = options.logLevelInString === "true"; - const sentryEnabled = !!options.sentryDsn; - - if (sentryEnabled) { - Sentry.init({ - dsn: options.sentryDsn, - // See https://github.com/getsentry/sentry-javascript/issues/1964#issuecomment-688482615 - // 6 is enough to serialize the deepest property across all GitHub Event payloads - normalizeDepth: 6, - }); - } - - const pretty = prettyFactory({ - ignore: [ - // default pino keys - "time", - "pid", - "hostname", - // remove keys from pino-http - "req", - "res", - "responseTime", - ].join(","), - errorProps: ["event", "status", "headers", "request"].join(","), - }); - - return new Transform({ - objectMode: true, - transform(chunk, enc, cb) { - const line = chunk.toString().trim(); - - /* istanbul ignore if */ - if (line === undefined) return cb(); - - const data = sentryEnabled ? JSON.parse(line) : null; - - if (sentryEnabled && data.level >= 50) { - Sentry.withScope(function (scope) { - const sentryLevelName = - data.level === 50 ? Sentry.Severity.Error : Sentry.Severity.Fatal; - scope.setLevel(sentryLevelName); - - for (const extra of ["event", "headers", "request", "status"]) { - if (!data[extra]) continue; - - scope.setExtra(extra, data[extra]); - } - - // set user id and username to installation ID and account login - if (data.event && data.event.payload) { - const { - // When GitHub App is installed organization wide - installation: { id, account: { login: account } = {} } = {}, - - // When the repository belongs to an organization - organization: { login: organization } = {}, - // When the repository belongs to a user - repository: { owner: { login: owner } = {} } = {}, - } = data.event.payload; - - scope.setUser({ - id: id, - username: account || organization || owner, - }); - } - - Sentry.captureException(toSentryError(data)); - }); - } - - if (formattingEnabled) { - return cb(null, pretty(data || line)); - } - - if (levelAsString) { - return cb(null, stringifyLogLevel(data || JSON.parse(line))); - } - - cb(null, line + "\n"); - }, - }); -} - -function stringifyLogLevel(data) { - data.level = LEVEL_MAP[data.level]; - return JSON.stringify(data) + "\n"; +function isSyntheticEvent(wat) { + return isPlainObject(wat) && 'nativeEvent' in wat && 'preventDefault' in wat && 'stopPropagation' in wat; } - -function toSentryError(data) { - const error = new Error(data.msg); - error.name = data.type; - error.stack = data.stack; - return error; +exports.isSyntheticEvent = isSyntheticEvent; +/** + * Checks whether given value's type is an instance of provided constructor. + * {@link isInstanceOf}. + * + * @param wat A value to be checked. + * @param base A constructor to be used in a check. + * @returns A boolean representing the result. + */ +function isInstanceOf(wat, base) { + try { + return wat instanceof base; + } + catch (_e) { + return false; + } } - +exports.isInstanceOf = isInstanceOf; +//# sourceMappingURL=is.js.map /***/ }), -/***/ 90785: +/***/ 15577: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); -var utils_1 = __nccwpck_require__(1620); -var SENTRY_API_VERSION = '7'; -/** Helper class to provide urls to different Sentry endpoints. */ -var API = /** @class */ (function () { - /** Create a new instance of API */ - function API(dsn) { - this.dsn = dsn; - this._dsnObject = new utils_1.Dsn(dsn); +/* eslint-disable @typescript-eslint/no-explicit-any */ +var misc_1 = __nccwpck_require__(32154); +// TODO: Implement different loggers for different environments +var global = misc_1.getGlobalObject(); +/** Prefix for logging strings */ +var PREFIX = 'Sentry Logger '; +/** JSDoc */ +var Logger = /** @class */ (function () { + /** JSDoc */ + function Logger() { + this._enabled = false; } - /** Returns the Dsn object. */ - API.prototype.getDsn = function () { - return this._dsnObject; - }; - /** Returns the prefix to construct Sentry ingestion API endpoints. */ - API.prototype.getBaseApiEndpoint = function () { - var dsn = this._dsnObject; - var protocol = dsn.protocol ? dsn.protocol + ":" : ''; - var port = dsn.port ? ":" + dsn.port : ''; - return protocol + "//" + dsn.host + port + (dsn.path ? "/" + dsn.path : '') + "/api/"; - }; - /** Returns the store endpoint URL. */ - API.prototype.getStoreEndpoint = function () { - return this._getIngestEndpoint('store'); - }; - /** - * Returns the store endpoint URL with auth in the query string. - * - * Sending auth as part of the query string and not as custom HTTP headers avoids CORS preflight requests. - */ - API.prototype.getStoreEndpointWithUrlEncodedAuth = function () { - return this.getStoreEndpoint() + "?" + this._encodedAuth(); - }; - /** - * Returns the envelope endpoint URL with auth in the query string. - * - * Sending auth as part of the query string and not as custom HTTP headers avoids CORS preflight requests. - */ - API.prototype.getEnvelopeEndpointWithUrlEncodedAuth = function () { - return this._getEnvelopeEndpoint() + "?" + this._encodedAuth(); + /** JSDoc */ + Logger.prototype.disable = function () { + this._enabled = false; }; - /** Returns only the path component for the store endpoint. */ - API.prototype.getStoreEndpointPath = function () { - var dsn = this._dsnObject; - return (dsn.path ? "/" + dsn.path : '') + "/api/" + dsn.projectId + "/store/"; + /** JSDoc */ + Logger.prototype.enable = function () { + this._enabled = true; }; - /** - * Returns an object that can be used in request headers. - * This is needed for node and the old /store endpoint in sentry - */ - API.prototype.getRequestHeaders = function (clientName, clientVersion) { - var dsn = this._dsnObject; - var header = ["Sentry sentry_version=" + SENTRY_API_VERSION]; - header.push("sentry_client=" + clientName + "/" + clientVersion); - header.push("sentry_key=" + dsn.user); - if (dsn.pass) { - header.push("sentry_secret=" + dsn.pass); + /** JSDoc */ + Logger.prototype.log = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; } - return { - 'Content-Type': 'application/json', - 'X-Sentry-Auth': header.join(', '), - }; + if (!this._enabled) { + return; + } + misc_1.consoleSandbox(function () { + global.console.log(PREFIX + "[Log]: " + args.join(' ')); + }); }; - /** Returns the url to the report dialog endpoint. */ - API.prototype.getReportDialogEndpoint = function (dialogOptions) { - if (dialogOptions === void 0) { dialogOptions = {}; } - var dsn = this._dsnObject; - var endpoint = this.getBaseApiEndpoint() + "embed/error-page/"; - var encodedOptions = []; - encodedOptions.push("dsn=" + dsn.toString()); - for (var key in dialogOptions) { - if (key === 'dsn') { - continue; - } - if (key === 'user') { - if (!dialogOptions.user) { - continue; - } - if (dialogOptions.user.name) { - encodedOptions.push("name=" + encodeURIComponent(dialogOptions.user.name)); - } - if (dialogOptions.user.email) { - encodedOptions.push("email=" + encodeURIComponent(dialogOptions.user.email)); - } - } - else { - encodedOptions.push(encodeURIComponent(key) + "=" + encodeURIComponent(dialogOptions[key])); - } + /** JSDoc */ + Logger.prototype.warn = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; } - if (encodedOptions.length) { - return endpoint + "?" + encodedOptions.join('&'); + if (!this._enabled) { + return; } - return endpoint; - }; - /** Returns the envelope endpoint URL. */ - API.prototype._getEnvelopeEndpoint = function () { - return this._getIngestEndpoint('envelope'); - }; - /** Returns the ingest API endpoint for target. */ - API.prototype._getIngestEndpoint = function (target) { - var base = this.getBaseApiEndpoint(); - var dsn = this._dsnObject; - return "" + base + dsn.projectId + "/" + target + "/"; + misc_1.consoleSandbox(function () { + global.console.warn(PREFIX + "[Warn]: " + args.join(' ')); + }); }; - /** Returns a URL-encoded string with auth config suitable for a query string. */ - API.prototype._encodedAuth = function () { - var dsn = this._dsnObject; - var auth = { - // We send only the minimum set of required information. See - // https://github.com/getsentry/sentry-javascript/issues/2572. - sentry_key: dsn.user, - sentry_version: SENTRY_API_VERSION, - }; - return utils_1.urlEncode(auth); + /** JSDoc */ + Logger.prototype.error = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + if (!this._enabled) { + return; + } + misc_1.consoleSandbox(function () { + global.console.error(PREFIX + "[Error]: " + args.join(' ')); + }); }; - return API; + return Logger; }()); -exports.API = API; -//# sourceMappingURL=api.js.map +// Ensure we only have a single logger instance, even if multiple versions of @sentry/utils are being used +global.__SENTRY__ = global.__SENTRY__ || {}; +var logger = global.__SENTRY__.logger || (global.__SENTRY__.logger = new Logger()); +exports.logger = logger; +//# sourceMappingURL=logger.js.map /***/ }), -/***/ 25886: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 49515: +/***/ ((__unused_webpack_module, exports) => { Object.defineProperty(exports, "__esModule", ({ value: true })); -var utils_1 = __nccwpck_require__(1620); -var noop_1 = __nccwpck_require__(68641); +/* eslint-disable @typescript-eslint/no-unsafe-member-access */ +/* eslint-disable @typescript-eslint/no-explicit-any */ +/* eslint-disable @typescript-eslint/explicit-module-boundary-types */ /** - * This is the base implemention of a Backend. - * @hidden + * Memo class used for decycle json objects. Uses WeakSet if available otherwise array. */ -var BaseBackend = /** @class */ (function () { - /** Creates a new backend instance. */ - function BaseBackend(options) { - this._options = options; - if (!this._options.dsn) { - utils_1.logger.warn('No DSN provided, backend will not do anything.'); - } - this._transport = this._setupTransport(); +var Memo = /** @class */ (function () { + function Memo() { + this._hasWeakSet = typeof WeakSet === 'function'; + this._inner = this._hasWeakSet ? new WeakSet() : []; } /** - * @inheritDoc - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types - BaseBackend.prototype.eventFromException = function (_exception, _hint) { - throw new utils_1.SentryError('Backend has to implement `eventFromException` method'); - }; - /** - * @inheritDoc - */ - BaseBackend.prototype.eventFromMessage = function (_message, _level, _hint) { - throw new utils_1.SentryError('Backend has to implement `eventFromMessage` method'); - }; - /** - * @inheritDoc - */ - BaseBackend.prototype.sendEvent = function (event) { - this._transport.sendEvent(event).then(null, function (reason) { - utils_1.logger.error("Error while sending event: " + reason); - }); - }; - /** - * @inheritDoc - */ - BaseBackend.prototype.sendSession = function (session) { - if (!this._transport.sendSession) { - utils_1.logger.warn("Dropping session because custom transport doesn't implement sendSession"); - return; - } - this._transport.sendSession(session).then(null, function (reason) { - utils_1.logger.error("Error while sending session: " + reason); - }); - }; - /** - * @inheritDoc + * Sets obj to remember. + * @param obj Object to remember */ - BaseBackend.prototype.getTransport = function () { - return this._transport; + Memo.prototype.memoize = function (obj) { + if (this._hasWeakSet) { + if (this._inner.has(obj)) { + return true; + } + this._inner.add(obj); + return false; + } + // eslint-disable-next-line @typescript-eslint/prefer-for-of + for (var i = 0; i < this._inner.length; i++) { + var value = this._inner[i]; + if (value === obj) { + return true; + } + } + this._inner.push(obj); + return false; }; /** - * Sets up the transport so it can be used later to send requests. + * Removes object from internal storage. + * @param obj Object to forget */ - BaseBackend.prototype._setupTransport = function () { - return new noop_1.NoopTransport(); + Memo.prototype.unmemoize = function (obj) { + if (this._hasWeakSet) { + this._inner.delete(obj); + } + else { + for (var i = 0; i < this._inner.length; i++) { + if (this._inner[i] === obj) { + this._inner.splice(i, 1); + break; + } + } + } }; - return BaseBackend; + return Memo; }()); -exports.BaseBackend = BaseBackend; -//# sourceMappingURL=basebackend.js.map +exports.Memo = Memo; +//# sourceMappingURL=memo.js.map /***/ }), -/***/ 25684: +/***/ 32154: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -/* eslint-disable max-lines */ -var hub_1 = __nccwpck_require__(6393); -var types_1 = __nccwpck_require__(83789); -var utils_1 = __nccwpck_require__(1620); -var integration_1 = __nccwpck_require__(58500); +var node_1 = __nccwpck_require__(16411); +var string_1 = __nccwpck_require__(66538); +var fallbackGlobalObject = {}; /** - * Base implementation for all JavaScript SDK clients. - * - * Call the constructor with the corresponding backend constructor and options - * specific to the client subclass. To access these options later, use - * {@link Client.getOptions}. Also, the Backend instance is available via - * {@link Client.getBackend}. - * - * If a Dsn is specified in the options, it will be parsed and stored. Use - * {@link Client.getDsn} to retrieve the Dsn at any moment. In case the Dsn is - * invalid, the constructor will throw a {@link SentryException}. Note that - * without a valid Dsn, the SDK will not send any events to Sentry. - * - * Before sending an event via the backend, it is passed through - * {@link BaseClient.prepareEvent} to add SDK information and scope data - * (breadcrumbs and context). To add more custom information, override this - * method and extend the resulting prepared event. - * - * To issue automatically created events (e.g. via instrumentation), use - * {@link Client.captureEvent}. It will prepare the event and pass it through - * the callback lifecycle. To issue auto-breadcrumbs, use - * {@link Client.addBreadcrumb}. + * Safely get global scope object * - * @example - * class NodeClient extends BaseClient { - * public constructor(options: NodeOptions) { - * super(NodeBackend, options); - * } + * @returns Global scope object + */ +function getGlobalObject() { + return (node_1.isNodeEnv() + ? global + : typeof window !== 'undefined' + ? window + : typeof self !== 'undefined' + ? self + : fallbackGlobalObject); +} +exports.getGlobalObject = getGlobalObject; +/** + * UUID4 generator * - * // ... - * } + * @returns string Generated UUID4. */ -var BaseClient = /** @class */ (function () { - /** - * Initializes this client instance. - * - * @param backendClass A constructor function to create the backend. - * @param options Options for the client. - */ - function BaseClient(backendClass, options) { - /** Array of used integrations. */ - this._integrations = {}; - /** Number of call being processed */ - this._processing = 0; - this._backend = new backendClass(options); - this._options = options; - if (options.dsn) { - this._dsn = new utils_1.Dsn(options.dsn); - } +function uuid4() { + var global = getGlobalObject(); + var crypto = global.crypto || global.msCrypto; + if (!(crypto === void 0) && crypto.getRandomValues) { + // Use window.crypto API if available + var arr = new Uint16Array(8); + crypto.getRandomValues(arr); + // set 4 in byte 7 + // eslint-disable-next-line no-bitwise + arr[3] = (arr[3] & 0xfff) | 0x4000; + // set 2 most significant bits of byte 9 to '10' + // eslint-disable-next-line no-bitwise + arr[4] = (arr[4] & 0x3fff) | 0x8000; + var pad = function (num) { + var v = num.toString(16); + while (v.length < 4) { + v = "0" + v; + } + return v; + }; + return (pad(arr[0]) + pad(arr[1]) + pad(arr[2]) + pad(arr[3]) + pad(arr[4]) + pad(arr[5]) + pad(arr[6]) + pad(arr[7])); } - /** - * @inheritDoc - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types - BaseClient.prototype.captureException = function (exception, hint, scope) { - var _this = this; - var eventId = hint && hint.event_id; - this._process(this._getBackend() - .eventFromException(exception, hint) - .then(function (event) { return _this._captureEvent(event, hint, scope); }) - .then(function (result) { - eventId = result; - })); - return eventId; - }; - /** - * @inheritDoc - */ - BaseClient.prototype.captureMessage = function (message, level, hint, scope) { - var _this = this; - var eventId = hint && hint.event_id; - var promisedEvent = utils_1.isPrimitive(message) - ? this._getBackend().eventFromMessage(String(message), level, hint) - : this._getBackend().eventFromException(message, hint); - this._process(promisedEvent - .then(function (event) { return _this._captureEvent(event, hint, scope); }) - .then(function (result) { - eventId = result; - })); - return eventId; - }; - /** - * @inheritDoc - */ - BaseClient.prototype.captureEvent = function (event, hint, scope) { - var eventId = hint && hint.event_id; - this._process(this._captureEvent(event, hint, scope).then(function (result) { - eventId = result; - })); - return eventId; + // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523 + return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function (c) { + // eslint-disable-next-line no-bitwise + var r = (Math.random() * 16) | 0; + // eslint-disable-next-line no-bitwise + var v = c === 'x' ? r : (r & 0x3) | 0x8; + return v.toString(16); + }); +} +exports.uuid4 = uuid4; +/** + * Parses string form of URL into an object + * // borrowed from https://tools.ietf.org/html/rfc3986#appendix-B + * // intentionally using regex and not href parsing trick because React Native and other + * // environments where DOM might not be available + * @returns parsed URL object + */ +function parseUrl(url) { + if (!url) { + return {}; + } + var match = url.match(/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/); + if (!match) { + return {}; + } + // coerce to undefined values to empty string so we don't get 'undefined' + var query = match[6] || ''; + var fragment = match[8] || ''; + return { + host: match[4], + path: match[5], + protocol: match[2], + relative: match[5] + query + fragment, }; - /** - * @inheritDoc - */ - BaseClient.prototype.captureSession = function (session) { - if (!session.release) { - utils_1.logger.warn('Discarded session because of missing release'); +} +exports.parseUrl = parseUrl; +/** + * Extracts either message or type+value from an event that can be used for user-facing logs + * @returns event's description + */ +function getEventDescription(event) { + if (event.message) { + return event.message; + } + if (event.exception && event.exception.values && event.exception.values[0]) { + var exception = event.exception.values[0]; + if (exception.type && exception.value) { + return exception.type + ": " + exception.value; } - else { - this._sendSession(session); + return exception.type || exception.value || event.event_id || ''; + } + return event.event_id || ''; +} +exports.getEventDescription = getEventDescription; +/** JSDoc */ +function consoleSandbox(callback) { + var global = getGlobalObject(); + var levels = ['debug', 'info', 'warn', 'error', 'log', 'assert']; + if (!('console' in global)) { + return callback(); + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + var originalConsole = global.console; + var wrappedLevels = {}; + // Restore all wrapped console methods + levels.forEach(function (level) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + if (level in global.console && originalConsole[level].__sentry_original__) { + wrappedLevels[level] = originalConsole[level]; + originalConsole[level] = originalConsole[level].__sentry_original__; } - }; - /** - * @inheritDoc - */ - BaseClient.prototype.getDsn = function () { - return this._dsn; - }; - /** - * @inheritDoc - */ - BaseClient.prototype.getOptions = function () { - return this._options; - }; - /** - * @inheritDoc - */ - BaseClient.prototype.flush = function (timeout) { - var _this = this; - return this._isClientProcessing(timeout).then(function (ready) { - return _this._getBackend() - .getTransport() - .close(timeout) - .then(function (transportFlushed) { return ready && transportFlushed; }); - }); - }; - /** - * @inheritDoc - */ - BaseClient.prototype.close = function (timeout) { - var _this = this; - return this.flush(timeout).then(function (result) { - _this.getOptions().enabled = false; - return result; + }); + // Perform callback manipulations + var result = callback(); + // Revert restoration to wrapped state + Object.keys(wrappedLevels).forEach(function (level) { + originalConsole[level] = wrappedLevels[level]; + }); + return result; +} +exports.consoleSandbox = consoleSandbox; +/** + * Adds exception values, type and value to an synthetic Exception. + * @param event The event to modify. + * @param value Value of the exception. + * @param type Type of the exception. + * @hidden + */ +function addExceptionTypeValue(event, value, type) { + event.exception = event.exception || {}; + event.exception.values = event.exception.values || []; + event.exception.values[0] = event.exception.values[0] || {}; + event.exception.values[0].value = event.exception.values[0].value || value || ''; + event.exception.values[0].type = event.exception.values[0].type || type || 'Error'; +} +exports.addExceptionTypeValue = addExceptionTypeValue; +/** + * Adds exception mechanism to a given event. + * @param event The event to modify. + * @param mechanism Mechanism of the mechanism. + * @hidden + */ +function addExceptionMechanism(event, mechanism) { + if (mechanism === void 0) { mechanism = {}; } + // TODO: Use real type with `keyof Mechanism` thingy and maybe make it better? + try { + // @ts-ignore Type 'Mechanism | {}' is not assignable to type 'Mechanism | undefined' + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + event.exception.values[0].mechanism = event.exception.values[0].mechanism || {}; + Object.keys(mechanism).forEach(function (key) { + // @ts-ignore Mechanism has no index signature + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + event.exception.values[0].mechanism[key] = mechanism[key]; }); + } + catch (_oO) { + // no-empty + } +} +exports.addExceptionMechanism = addExceptionMechanism; +/** + * A safe form of location.href + */ +function getLocationHref() { + try { + return document.location.href; + } + catch (oO) { + return ''; + } +} +exports.getLocationHref = getLocationHref; +// https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string +var SEMVER_REGEXP = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/; +/** + * Parses input into a SemVer interface + * @param input string representation of a semver version + */ +function parseSemver(input) { + var match = input.match(SEMVER_REGEXP) || []; + var major = parseInt(match[1], 10); + var minor = parseInt(match[2], 10); + var patch = parseInt(match[3], 10); + return { + buildmetadata: match[5], + major: isNaN(major) ? undefined : major, + minor: isNaN(minor) ? undefined : minor, + patch: isNaN(patch) ? undefined : patch, + prerelease: match[4], }; - /** - * Sets up the integrations - */ - BaseClient.prototype.setupIntegrations = function () { - if (this._isEnabled()) { - this._integrations = integration_1.setupIntegrations(this._options); - } - }; - /** - * @inheritDoc - */ - BaseClient.prototype.getIntegration = function (integration) { - try { - return this._integrations[integration.id] || null; - } - catch (_oO) { - utils_1.logger.warn("Cannot retrieve integration " + integration.id + " from the current Client"); - return null; - } - }; - /** Updates existing session based on the provided event */ - BaseClient.prototype._updateSessionFromEvent = function (session, event) { - var e_1, _a; - var crashed = false; - var errored = false; - var userAgent; - var exceptions = event.exception && event.exception.values; - if (exceptions) { - errored = true; - try { - for (var exceptions_1 = tslib_1.__values(exceptions), exceptions_1_1 = exceptions_1.next(); !exceptions_1_1.done; exceptions_1_1 = exceptions_1.next()) { - var ex = exceptions_1_1.value; - var mechanism = ex.mechanism; - if (mechanism && mechanism.handled === false) { - crashed = true; - break; - } - } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (exceptions_1_1 && !exceptions_1_1.done && (_a = exceptions_1.return)) _a.call(exceptions_1); - } - finally { if (e_1) throw e_1.error; } - } - } - var user = event.user; - if (!session.userAgent) { - var headers = event.request ? event.request.headers : {}; - for (var key in headers) { - if (key.toLowerCase() === 'user-agent') { - userAgent = headers[key]; +} +exports.parseSemver = parseSemver; +var defaultRetryAfter = 60 * 1000; // 60 seconds +/** + * Extracts Retry-After value from the request header or returns default value + * @param now current unix timestamp + * @param header string representation of 'Retry-After' header + */ +function parseRetryAfterHeader(now, header) { + if (!header) { + return defaultRetryAfter; + } + var headerDelay = parseInt("" + header, 10); + if (!isNaN(headerDelay)) { + return headerDelay * 1000; + } + var headerDate = Date.parse("" + header); + if (!isNaN(headerDate)) { + return headerDate - now; + } + return defaultRetryAfter; +} +exports.parseRetryAfterHeader = parseRetryAfterHeader; +/** + * This function adds context (pre/post/line) lines to the provided frame + * + * @param lines string[] containing all lines + * @param frame StackFrame that will be mutated + * @param linesOfContext number of context lines we want to add pre/post + */ +function addContextToFrame(lines, frame, linesOfContext) { + if (linesOfContext === void 0) { linesOfContext = 5; } + var lineno = frame.lineno || 0; + var maxLines = lines.length; + var sourceLine = Math.max(Math.min(maxLines, lineno - 1), 0); + frame.pre_context = lines + .slice(Math.max(0, sourceLine - linesOfContext), sourceLine) + .map(function (line) { return string_1.snipLine(line, 0); }); + frame.context_line = string_1.snipLine(lines[Math.min(maxLines - 1, sourceLine)], frame.colno || 0); + frame.post_context = lines + .slice(Math.min(sourceLine + 1, maxLines), sourceLine + 1 + linesOfContext) + .map(function (line) { return string_1.snipLine(line, 0); }); +} +exports.addContextToFrame = addContextToFrame; +/** + * Strip the query string and fragment off of a given URL or path (if present) + * + * @param urlPath Full URL or path, including possible query string and/or fragment + * @returns URL or path without query string or fragment + */ +function stripUrlQueryAndFragment(urlPath) { + // eslint-disable-next-line no-useless-escape + return urlPath.split(/[\?#]/, 1)[0]; +} +exports.stripUrlQueryAndFragment = stripUrlQueryAndFragment; +//# sourceMappingURL=misc.js.map + +/***/ }), + +/***/ 16411: +/***/ ((module, exports, __nccwpck_require__) => { + +/* module decorator */ module = __nccwpck_require__.nmd(module); +Object.defineProperty(exports, "__esModule", ({ value: true })); +var is_1 = __nccwpck_require__(92757); +var object_1 = __nccwpck_require__(69249); +/** + * Checks whether we're in the Node.js or Browser environment + * + * @returns Answer to given question + */ +function isNodeEnv() { + return Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]'; +} +exports.isNodeEnv = isNodeEnv; +/** + * Requires a module which is protected against bundler minification. + * + * @param request The module path to resolve + */ +// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types +function dynamicRequire(mod, request) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + return mod.require(request); +} +exports.dynamicRequire = dynamicRequire; +/** Default request keys that'll be used to extract data from the request */ +var DEFAULT_REQUEST_KEYS = ['cookies', 'data', 'headers', 'method', 'query_string', 'url']; +/** + * Normalizes data from the request object, accounting for framework differences. + * + * @param req The request object from which to extract data + * @param keys An optional array of keys to include in the normalized data. Defaults to DEFAULT_REQUEST_KEYS if not + * provided. + * @returns An object containing normalized request data + */ +function extractNodeRequestData(req, keys) { + if (keys === void 0) { keys = DEFAULT_REQUEST_KEYS; } + // make sure we can safely use dynamicRequire below + if (!isNodeEnv()) { + throw new Error("Can't get node request data outside of a node environment"); + } + var requestData = {}; + // headers: + // node, express: req.headers + // koa: req.header + var headers = (req.headers || req.header || {}); + // method: + // node, express, koa: req.method + var method = req.method; + // host: + // express: req.hostname in > 4 and req.host in < 4 + // koa: req.host + // node: req.headers.host + var host = req.hostname || req.host || headers.host || ''; + // protocol: + // node: + // express, koa: req.protocol + var protocol = req.protocol === 'https' || req.secure || (req.socket || {}).encrypted + ? 'https' + : 'http'; + // url (including path and query string): + // node, express: req.originalUrl + // koa: req.url + var originalUrl = (req.originalUrl || req.url || ''); + // absolute url + var absoluteUrl = protocol + "://" + host + originalUrl; + keys.forEach(function (key) { + switch (key) { + case 'headers': + requestData.headers = headers; + break; + case 'method': + requestData.method = method; + break; + case 'url': + requestData.url = absoluteUrl; + break; + case 'cookies': + // cookies: + // node, express, koa: req.headers.cookie + // vercel, sails.js, express (w/ cookie middleware): req.cookies + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + requestData.cookies = req.cookies || dynamicRequire(module, 'cookie').parse(headers.cookie || ''); + break; + case 'query_string': + // query string: + // node: req.url (raw) + // express, koa: req.query + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + requestData.query_string = dynamicRequire(module, 'url').parse(originalUrl || '', false).query; + break; + case 'data': + if (method === 'GET' || method === 'HEAD') { break; } - } - } - session.update(tslib_1.__assign(tslib_1.__assign({}, (crashed && { status: types_1.SessionStatus.Crashed })), { user: user, - userAgent: userAgent, errors: session.errors + Number(errored || crashed) })); - }; - /** Deliver captured session to Sentry */ - BaseClient.prototype._sendSession = function (session) { - this._getBackend().sendSession(session); - }; - /** Waits for the client to be done with processing. */ - BaseClient.prototype._isClientProcessing = function (timeout) { - var _this = this; - return new utils_1.SyncPromise(function (resolve) { - var ticked = 0; - var tick = 1; - var interval = setInterval(function () { - if (_this._processing == 0) { - clearInterval(interval); - resolve(true); + // body data: + // node, express, koa: req.body + if (req.body !== undefined) { + requestData.data = is_1.isString(req.body) ? req.body : JSON.stringify(object_1.normalize(req.body)); } - else { - ticked += tick; - if (timeout && ticked >= timeout) { - clearInterval(interval); - resolve(false); - } + break; + default: + if ({}.hasOwnProperty.call(req, key)) { + requestData[key] = req[key]; } - }, tick); - }); - }; - /** Returns the current backend. */ - BaseClient.prototype._getBackend = function () { - return this._backend; - }; - /** Determines whether this SDK is enabled and a valid Dsn is present. */ - BaseClient.prototype._isEnabled = function () { - return this.getOptions().enabled !== false && this._dsn !== undefined; - }; - /** - * Adds common information to events. - * - * The information includes release and environment from `options`, - * breadcrumbs and context (extra, tags and user) from the scope. - * - * Information that is already present in the event is never overwritten. For - * nested objects, such as the context, keys are merged. - * - * @param event The original event. - * @param hint May contain additional information about the original exception. - * @param scope A scope containing event metadata. - * @returns A new event with more information. - */ - BaseClient.prototype._prepareEvent = function (event, scope, hint) { - var _this = this; - var _a = this.getOptions().normalizeDepth, normalizeDepth = _a === void 0 ? 3 : _a; - var prepared = tslib_1.__assign(tslib_1.__assign({}, event), { event_id: event.event_id || (hint && hint.event_id ? hint.event_id : utils_1.uuid4()), timestamp: event.timestamp || utils_1.dateTimestampInSeconds() }); - this._applyClientOptions(prepared); - this._applyIntegrationsMetadata(prepared); - // If we have scope given to us, use it as the base for further modifications. - // This allows us to prevent unnecessary copying of data if `captureContext` is not provided. - var finalScope = scope; - if (hint && hint.captureContext) { - finalScope = hub_1.Scope.clone(finalScope).update(hint.captureContext); } - // We prepare the result here with a resolved Event. - var result = utils_1.SyncPromise.resolve(prepared); - // This should be the last thing called, since we want that - // {@link Hub.addEventProcessor} gets the finished prepared event. - if (finalScope) { - // In case we have a hub we reassign it. - result = finalScope.applyToEvent(prepared, hint); + }); + return requestData; +} +exports.extractNodeRequestData = extractNodeRequestData; +//# sourceMappingURL=node.js.map + +/***/ }), + +/***/ 69249: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __nccwpck_require__(4351); +var browser_1 = __nccwpck_require__(30597); +var is_1 = __nccwpck_require__(92757); +var memo_1 = __nccwpck_require__(49515); +var stacktrace_1 = __nccwpck_require__(5986); +var string_1 = __nccwpck_require__(66538); +/** + * Wrap a given object method with a higher-order function + * + * @param source An object that contains a method to be wrapped. + * @param name A name of method to be wrapped. + * @param replacement A function that should be used to wrap a given method. + * @returns void + */ +function fill(source, name, replacement) { + if (!(name in source)) { + return; + } + var original = source[name]; + var wrapped = replacement(original); + // Make sure it's a function first, as we need to attach an empty prototype for `defineProperties` to work + // otherwise it'll throw "TypeError: Object.defineProperties called on non-object" + if (typeof wrapped === 'function') { + try { + wrapped.prototype = wrapped.prototype || {}; + Object.defineProperties(wrapped, { + __sentry_original__: { + enumerable: false, + value: original, + }, + }); } - return result.then(function (evt) { - if (typeof normalizeDepth === 'number' && normalizeDepth > 0) { - return _this._normalizeEvent(evt, normalizeDepth); - } - return evt; - }); - }; - /** - * Applies `normalize` function on necessary `Event` attributes to make them safe for serialization. - * Normalized keys: - * - `breadcrumbs.data` - * - `user` - * - `contexts` - * - `extra` - * @param event Event - * @returns Normalized event - */ - BaseClient.prototype._normalizeEvent = function (event, depth) { - if (!event) { - return null; + catch (_Oo) { + // This can throw if multiple fill happens on a global object like XMLHttpRequest + // Fixes https://github.com/getsentry/sentry-javascript/issues/2043 } - var normalized = tslib_1.__assign(tslib_1.__assign(tslib_1.__assign(tslib_1.__assign(tslib_1.__assign({}, event), (event.breadcrumbs && { - breadcrumbs: event.breadcrumbs.map(function (b) { return (tslib_1.__assign(tslib_1.__assign({}, b), (b.data && { - data: utils_1.normalize(b.data, depth), - }))); }), - })), (event.user && { - user: utils_1.normalize(event.user, depth), - })), (event.contexts && { - contexts: utils_1.normalize(event.contexts, depth), - })), (event.extra && { - extra: utils_1.normalize(event.extra, depth), - })); - // event.contexts.trace stores information about a Transaction. Similarly, - // event.spans[] stores information about child Spans. Given that a - // Transaction is conceptually a Span, normalization should apply to both - // Transactions and Spans consistently. - // For now the decision is to skip normalization of Transactions and Spans, - // so this block overwrites the normalized event to add back the original - // Transaction information prior to normalization. - if (event.contexts && event.contexts.trace) { - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - normalized.contexts.trace = event.contexts.trace; + } + source[name] = wrapped; +} +exports.fill = fill; +/** + * Encodes given object into url-friendly format + * + * @param object An object that contains serializable values + * @returns string Encoded + */ +function urlEncode(object) { + return Object.keys(object) + .map(function (key) { return encodeURIComponent(key) + "=" + encodeURIComponent(object[key]); }) + .join('&'); +} +exports.urlEncode = urlEncode; +/** + * Transforms any object into an object literal with all it's attributes + * attached to it. + * + * @param value Initial source that we have to transform in order to be usable by the serializer + */ +function getWalkSource(value) { + if (is_1.isError(value)) { + var error = value; + var err = { + message: error.message, + name: error.name, + stack: error.stack, + }; + for (var i in error) { + if (Object.prototype.hasOwnProperty.call(error, i)) { + err[i] = error[i]; + } } - return normalized; - }; - /** - * Enhances event using the client configuration. - * It takes care of all "static" values like environment, release and `dist`, - * as well as truncating overly long values. - * @param event event instance to be enhanced - */ - BaseClient.prototype._applyClientOptions = function (event) { - var options = this.getOptions(); - var environment = options.environment, release = options.release, dist = options.dist, _a = options.maxValueLength, maxValueLength = _a === void 0 ? 250 : _a; - if (!('environment' in event)) { - event.environment = 'environment' in options ? environment : 'production'; + return err; + } + if (is_1.isEvent(value)) { + var event_1 = value; + var source = {}; + source.type = event_1.type; + // Accessing event.target can throw (see getsentry/raven-js#838, #768) + try { + source.target = is_1.isElement(event_1.target) + ? browser_1.htmlTreeAsString(event_1.target) + : Object.prototype.toString.call(event_1.target); } - if (event.release === undefined && release !== undefined) { - event.release = release; + catch (_oO) { + source.target = ''; } - if (event.dist === undefined && dist !== undefined) { - event.dist = dist; + try { + source.currentTarget = is_1.isElement(event_1.currentTarget) + ? browser_1.htmlTreeAsString(event_1.currentTarget) + : Object.prototype.toString.call(event_1.currentTarget); } - if (event.message) { - event.message = utils_1.truncate(event.message, maxValueLength); + catch (_oO) { + source.currentTarget = ''; } - var exception = event.exception && event.exception.values && event.exception.values[0]; - if (exception && exception.value) { - exception.value = utils_1.truncate(exception.value, maxValueLength); + if (typeof CustomEvent !== 'undefined' && is_1.isInstanceOf(value, CustomEvent)) { + source.detail = event_1.detail; } - var request = event.request; - if (request && request.url) { - request.url = utils_1.truncate(request.url, maxValueLength); + for (var i in event_1) { + if (Object.prototype.hasOwnProperty.call(event_1, i)) { + source[i] = event_1; + } } - }; - /** - * This function adds all used integrations to the SDK info in the event. - * @param sdkInfo The sdkInfo of the event that will be filled with all integrations. - */ - BaseClient.prototype._applyIntegrationsMetadata = function (event) { - var sdkInfo = event.sdk; - var integrationsArray = Object.keys(this._integrations); - if (sdkInfo && integrationsArray.length > 0) { - sdkInfo.integrations = integrationsArray; + return source; + } + return value; +} +/** Calculates bytes size of input string */ +function utf8Length(value) { + // eslint-disable-next-line no-bitwise + return ~-encodeURI(value).split(/%..|./).length; +} +/** Calculates bytes size of input object */ +function jsonSize(value) { + return utf8Length(JSON.stringify(value)); +} +/** JSDoc */ +function normalizeToSize(object, +// Default Node.js REPL depth +depth, +// 100kB, as 200kB is max payload size, so half sounds reasonable +maxSize) { + if (depth === void 0) { depth = 3; } + if (maxSize === void 0) { maxSize = 100 * 1024; } + var serialized = normalize(object, depth); + if (jsonSize(serialized) > maxSize) { + return normalizeToSize(object, depth - 1, maxSize); + } + return serialized; +} +exports.normalizeToSize = normalizeToSize; +/** + * Transform any non-primitive, BigInt, or Symbol-type value into a string. Acts as a no-op on strings, numbers, + * booleans, null, and undefined. + * + * @param value The value to stringify + * @returns For non-primitive, BigInt, and Symbol-type values, a string denoting the value's type, type and value, or + * type and `description` property, respectively. For non-BigInt, non-Symbol primitives, returns the original value, + * unchanged. + */ +function serializeValue(value) { + var type = Object.prototype.toString.call(value); + // Node.js REPL notation + if (typeof value === 'string') { + return value; + } + if (type === '[object Object]') { + return '[Object]'; + } + if (type === '[object Array]') { + return '[Array]'; + } + var normalized = normalizeValue(value); + return is_1.isPrimitive(normalized) ? normalized : type; +} +/** + * normalizeValue() + * + * Takes unserializable input and make it serializable friendly + * + * - translates undefined/NaN values to "[undefined]"/"[NaN]" respectively, + * - serializes Error objects + * - filter global objects + */ +function normalizeValue(value, key) { + if (key === 'domain' && value && typeof value === 'object' && value._events) { + return '[Domain]'; + } + if (key === 'domainEmitter') { + return '[DomainEmitter]'; + } + if (typeof global !== 'undefined' && value === global) { + return '[Global]'; + } + if (typeof window !== 'undefined' && value === window) { + return '[Window]'; + } + if (typeof document !== 'undefined' && value === document) { + return '[Document]'; + } + // React's SyntheticEvent thingy + if (is_1.isSyntheticEvent(value)) { + return '[SyntheticEvent]'; + } + if (typeof value === 'number' && value !== value) { + return '[NaN]'; + } + if (value === void 0) { + return '[undefined]'; + } + if (typeof value === 'function') { + return "[Function: " + stacktrace_1.getFunctionName(value) + "]"; + } + // symbols and bigints are considered primitives by TS, but aren't natively JSON-serilaizable + if (typeof value === 'symbol') { + return "[" + String(value) + "]"; + } + if (typeof value === 'bigint') { + return "[BigInt: " + String(value) + "]"; + } + return value; +} +/** + * Walks an object to perform a normalization on it + * + * @param key of object that's walked in current iteration + * @param value object to be walked + * @param depth Optional number indicating how deep should walking be performed + * @param memo Optional Memo class handling decycling + */ +// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types +function walk(key, value, depth, memo) { + if (depth === void 0) { depth = +Infinity; } + if (memo === void 0) { memo = new memo_1.Memo(); } + // If we reach the maximum depth, serialize whatever has left + if (depth === 0) { + return serializeValue(value); + } + /* eslint-disable @typescript-eslint/no-unsafe-member-access */ + // If value implements `toJSON` method, call it and return early + if (value !== null && value !== undefined && typeof value.toJSON === 'function') { + return value.toJSON(); + } + /* eslint-enable @typescript-eslint/no-unsafe-member-access */ + // If normalized value is a primitive, there are no branches left to walk, so we can just bail out, as theres no point in going down that branch any further + var normalized = normalizeValue(value, key); + if (is_1.isPrimitive(normalized)) { + return normalized; + } + // Create source that we will use for next itterations, either objectified error object (Error type with extracted keys:value pairs) or the input itself + var source = getWalkSource(value); + // Create an accumulator that will act as a parent for all future itterations of that branch + var acc = Array.isArray(value) ? [] : {}; + // If we already walked that branch, bail out, as it's circular reference + if (memo.memoize(value)) { + return '[Circular ~]'; + } + // Walk all keys of the source + for (var innerKey in source) { + // Avoid iterating over fields in the prototype if they've somehow been exposed to enumeration. + if (!Object.prototype.hasOwnProperty.call(source, innerKey)) { + continue; } - }; - /** - * Tells the backend to send this event - * @param event The Sentry event to send - */ - BaseClient.prototype._sendEvent = function (event) { - this._getBackend().sendEvent(event); - }; - /** - * Processes the event and logs an error in case of rejection - * @param event - * @param hint - * @param scope - */ - BaseClient.prototype._captureEvent = function (event, hint, scope) { - return this._processEvent(event, hint, scope).then(function (finalEvent) { - return finalEvent.event_id; - }, function (reason) { - utils_1.logger.error(reason); - return undefined; - }); - }; - /** - * Processes an event (either error or message) and sends it to Sentry. - * - * This also adds breadcrumbs and context information to the event. However, - * platform specific meta data (such as the User's IP address) must be added - * by the SDK implementor. - * - * - * @param event The event to send to Sentry. - * @param hint May contain additional information about the original exception. - * @param scope A scope containing event metadata. - * @returns A SyncPromise that resolves with the event or rejects in case event was/will not be send. - */ - BaseClient.prototype._processEvent = function (event, hint, scope) { - var _this = this; - // eslint-disable-next-line @typescript-eslint/unbound-method - var _a = this.getOptions(), beforeSend = _a.beforeSend, sampleRate = _a.sampleRate; - if (!this._isEnabled()) { - return utils_1.SyncPromise.reject(new utils_1.SentryError('SDK not enabled, will not send event.')); + // Recursively walk through all the child nodes + acc[innerKey] = walk(innerKey, source[innerKey], depth - 1, memo); + } + // Once walked through all the branches, remove the parent from memo storage + memo.unmemoize(value); + // Return accumulated values + return acc; +} +exports.walk = walk; +/** + * normalize() + * + * - Creates a copy to prevent original input mutation + * - Skip non-enumerablers + * - Calls `toJSON` if implemented + * - Removes circular references + * - Translates non-serializeable values (undefined/NaN/Functions) to serializable format + * - Translates known global objects/Classes to a string representations + * - Takes care of Error objects serialization + * - Optionally limit depth of final output + */ +// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types +function normalize(input, depth) { + try { + return JSON.parse(JSON.stringify(input, function (key, value) { return walk(key, value, depth); })); + } + catch (_oO) { + return '**non-serializable**'; + } +} +exports.normalize = normalize; +/** + * Given any captured exception, extract its keys and create a sorted + * and truncated list that will be used inside the event message. + * eg. `Non-error exception captured with keys: foo, bar, baz` + */ +// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types +function extractExceptionKeysForMessage(exception, maxLength) { + if (maxLength === void 0) { maxLength = 40; } + var keys = Object.keys(getWalkSource(exception)); + keys.sort(); + if (!keys.length) { + return '[object has no keys]'; + } + if (keys[0].length >= maxLength) { + return string_1.truncate(keys[0], maxLength); + } + for (var includedKeys = keys.length; includedKeys > 0; includedKeys--) { + var serialized = keys.slice(0, includedKeys).join(', '); + if (serialized.length > maxLength) { + continue; } - var isTransaction = event.type === 'transaction'; - // 1.0 === 100% events are sent - // 0.0 === 0% events are sent - // Sampling for transaction happens somewhere else - if (!isTransaction && typeof sampleRate === 'number' && Math.random() > sampleRate) { - return utils_1.SyncPromise.reject(new utils_1.SentryError('This event has been sampled, will not send event.')); + if (includedKeys === keys.length) { + return serialized; } - return this._prepareEvent(event, scope, hint) - .then(function (prepared) { - if (prepared === null) { - throw new utils_1.SentryError('An event processor returned null, will not send event.'); - } - var isInternalException = hint && hint.data && hint.data.__sentry__ === true; - if (isInternalException || isTransaction || !beforeSend) { - return prepared; - } - var beforeSendResult = beforeSend(prepared, hint); - if (typeof beforeSendResult === 'undefined') { - throw new utils_1.SentryError('`beforeSend` method has to return `null` or a valid event.'); - } - else if (utils_1.isThenable(beforeSendResult)) { - return beforeSendResult.then(function (event) { return event; }, function (e) { - throw new utils_1.SentryError("beforeSend rejected with " + e); - }); - } - return beforeSendResult; - }) - .then(function (processedEvent) { - if (processedEvent === null) { - throw new utils_1.SentryError('`beforeSend` returned `null`, will not send event.'); - } - var session = scope && scope.getSession && scope.getSession(); - if (!isTransaction && session) { - _this._updateSessionFromEvent(session, processedEvent); + return string_1.truncate(serialized, maxLength); + } + return ''; +} +exports.extractExceptionKeysForMessage = extractExceptionKeysForMessage; +/** + * Given any object, return the new object with removed keys that value was `undefined`. + * Works recursively on objects and arrays. + */ +function dropUndefinedKeys(val) { + var e_1, _a; + if (is_1.isPlainObject(val)) { + var obj = val; + var rv = {}; + try { + for (var _b = tslib_1.__values(Object.keys(obj)), _c = _b.next(); !_c.done; _c = _b.next()) { + var key = _c.value; + if (typeof obj[key] !== 'undefined') { + rv[key] = dropUndefinedKeys(obj[key]); + } } - _this._sendEvent(processedEvent); - return processedEvent; - }) - .then(null, function (reason) { - if (reason instanceof utils_1.SentryError) { - throw reason; + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (_c && !_c.done && (_a = _b.return)) _a.call(_b); } - _this.captureException(reason, { - data: { - __sentry__: true, - }, - originalException: reason, - }); - throw new utils_1.SentryError("Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.\nReason: " + reason); - }); - }; - /** - * Occupies the client with processing and event - */ - BaseClient.prototype._process = function (promise) { - var _this = this; - this._processing += 1; - promise.then(function (value) { - _this._processing -= 1; - return value; - }, function (reason) { - _this._processing -= 1; - return reason; - }); - }; - return BaseClient; -}()); -exports.BaseClient = BaseClient; -//# sourceMappingURL=baseclient.js.map - -/***/ }), - -/***/ 79212: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -Object.defineProperty(exports, "__esModule", ({ value: true })); -var minimal_1 = __nccwpck_require__(88455); -exports.addBreadcrumb = minimal_1.addBreadcrumb; -exports.captureException = minimal_1.captureException; -exports.captureEvent = minimal_1.captureEvent; -exports.captureMessage = minimal_1.captureMessage; -exports.configureScope = minimal_1.configureScope; -exports.startTransaction = minimal_1.startTransaction; -exports.setContext = minimal_1.setContext; -exports.setExtra = minimal_1.setExtra; -exports.setExtras = minimal_1.setExtras; -exports.setTag = minimal_1.setTag; -exports.setTags = minimal_1.setTags; -exports.setUser = minimal_1.setUser; -exports.withScope = minimal_1.withScope; -var hub_1 = __nccwpck_require__(6393); -exports.addGlobalEventProcessor = hub_1.addGlobalEventProcessor; -exports.getCurrentHub = hub_1.getCurrentHub; -exports.getHubFromCarrier = hub_1.getHubFromCarrier; -exports.Hub = hub_1.Hub; -exports.makeMain = hub_1.makeMain; -exports.Scope = hub_1.Scope; -var api_1 = __nccwpck_require__(90785); -exports.API = api_1.API; -var baseclient_1 = __nccwpck_require__(25684); -exports.BaseClient = baseclient_1.BaseClient; -var basebackend_1 = __nccwpck_require__(25886); -exports.BaseBackend = basebackend_1.BaseBackend; -var request_1 = __nccwpck_require__(1553); -exports.eventToSentryRequest = request_1.eventToSentryRequest; -exports.sessionToSentryRequest = request_1.sessionToSentryRequest; -var sdk_1 = __nccwpck_require__(46406); -exports.initAndBind = sdk_1.initAndBind; -var noop_1 = __nccwpck_require__(68641); -exports.NoopTransport = noop_1.NoopTransport; -var Integrations = __nccwpck_require__(96727); -exports.Integrations = Integrations; -//# sourceMappingURL=index.js.map + finally { if (e_1) throw e_1.error; } + } + return rv; + } + if (Array.isArray(val)) { + return val.map(dropUndefinedKeys); + } + return val; +} +exports.dropUndefinedKeys = dropUndefinedKeys; +//# sourceMappingURL=object.js.map /***/ }), -/***/ 58500: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 39188: +/***/ ((__unused_webpack_module, exports) => { +// Slightly modified (no IE8 support, ES6) and transcribed to TypeScript +// https://raw.githubusercontent.com/calvinmetcalf/rollup-plugin-node-builtins/master/src/es6/path.js Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var hub_1 = __nccwpck_require__(6393); -var utils_1 = __nccwpck_require__(1620); -exports.installedIntegrations = []; -/** Gets integration to install */ -function getIntegrationsToSetup(options) { - var defaultIntegrations = (options.defaultIntegrations && tslib_1.__spread(options.defaultIntegrations)) || []; - var userIntegrations = options.integrations; - var integrations = []; - if (Array.isArray(userIntegrations)) { - var userIntegrationsNames_1 = userIntegrations.map(function (i) { return i.name; }); - var pickedIntegrationsNames_1 = []; - // Leave only unique default integrations, that were not overridden with provided user integrations - defaultIntegrations.forEach(function (defaultIntegration) { - if (userIntegrationsNames_1.indexOf(defaultIntegration.name) === -1 && - pickedIntegrationsNames_1.indexOf(defaultIntegration.name) === -1) { - integrations.push(defaultIntegration); - pickedIntegrationsNames_1.push(defaultIntegration.name); - } - }); - // Don't add same user integration twice - userIntegrations.forEach(function (userIntegration) { - if (pickedIntegrationsNames_1.indexOf(userIntegration.name) === -1) { - integrations.push(userIntegration); - pickedIntegrationsNames_1.push(userIntegration.name); - } - }); +/** JSDoc */ +function normalizeArray(parts, allowAboveRoot) { + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = parts.length - 1; i >= 0; i--) { + var last = parts[i]; + if (last === '.') { + parts.splice(i, 1); + } + else if (last === '..') { + parts.splice(i, 1); + // eslint-disable-next-line no-plusplus + up++; + } + else if (up) { + parts.splice(i, 1); + // eslint-disable-next-line no-plusplus + up--; + } } - else if (typeof userIntegrations === 'function') { - integrations = userIntegrations(defaultIntegrations); - integrations = Array.isArray(integrations) ? integrations : [integrations]; + // if the path is allowed to go above the root, restore leading ..s + if (allowAboveRoot) { + // eslint-disable-next-line no-plusplus + for (; up--; up) { + parts.unshift('..'); + } } - else { - integrations = tslib_1.__spread(defaultIntegrations); + return parts; +} +// Split a filename into [root, dir, basename, ext], unix version +// 'root' is just a slash, or nothing. +var splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^/]+?|)(\.[^./]*|))(?:[/]*)$/; +/** JSDoc */ +function splitPath(filename) { + var parts = splitPathRe.exec(filename); + return parts ? parts.slice(1) : []; +} +// path.resolve([from ...], to) +// posix version +/** JSDoc */ +function resolve() { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; } - // Make sure that if present, `Debug` integration will always run last - var integrationsNames = integrations.map(function (i) { return i.name; }); - var alwaysLastToRun = 'Debug'; - if (integrationsNames.indexOf(alwaysLastToRun) !== -1) { - integrations.push.apply(integrations, tslib_1.__spread(integrations.splice(integrationsNames.indexOf(alwaysLastToRun), 1))); + var resolvedPath = ''; + var resolvedAbsolute = false; + for (var i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) { + var path = i >= 0 ? args[i] : '/'; + // Skip empty entries + if (!path) { + continue; + } + resolvedPath = path + "/" + resolvedPath; + resolvedAbsolute = path.charAt(0) === '/'; } - return integrations; + // At this point the path should be resolved to a full absolute path, but + // handle relative paths to be safe (might happen when process.cwd() fails) + // Normalize the path + resolvedPath = normalizeArray(resolvedPath.split('/').filter(function (p) { return !!p; }), !resolvedAbsolute).join('/'); + return (resolvedAbsolute ? '/' : '') + resolvedPath || '.'; } -exports.getIntegrationsToSetup = getIntegrationsToSetup; -/** Setup given integration */ -function setupIntegration(integration) { - if (exports.installedIntegrations.indexOf(integration.name) !== -1) { - return; +exports.resolve = resolve; +/** JSDoc */ +function trim(arr) { + var start = 0; + for (; start < arr.length; start++) { + if (arr[start] !== '') { + break; + } } - integration.setupOnce(hub_1.addGlobalEventProcessor, hub_1.getCurrentHub); - exports.installedIntegrations.push(integration.name); - utils_1.logger.log("Integration installed: " + integration.name); + var end = arr.length - 1; + for (; end >= 0; end--) { + if (arr[end] !== '') { + break; + } + } + if (start > end) { + return []; + } + return arr.slice(start, end - start + 1); } -exports.setupIntegration = setupIntegration; -/** - * Given a list of integration instances this installs them all. When `withDefaults` is set to `true` then all default - * integrations are added unless they were already provided before. - * @param integrations array of integration instances - * @param withDefault should enable default integrations - */ -function setupIntegrations(options) { - var integrations = {}; - getIntegrationsToSetup(options).forEach(function (integration) { - integrations[integration.name] = integration; - setupIntegration(integration); - }); - return integrations; +// path.relative(from, to) +// posix version +/** JSDoc */ +function relative(from, to) { + /* eslint-disable no-param-reassign */ + from = resolve(from).substr(1); + to = resolve(to).substr(1); + /* eslint-enable no-param-reassign */ + var fromParts = trim(from.split('/')); + var toParts = trim(to.split('/')); + var length = Math.min(fromParts.length, toParts.length); + var samePartsLength = length; + for (var i = 0; i < length; i++) { + if (fromParts[i] !== toParts[i]) { + samePartsLength = i; + break; + } + } + var outputParts = []; + for (var i = samePartsLength; i < fromParts.length; i++) { + outputParts.push('..'); + } + outputParts = outputParts.concat(toParts.slice(samePartsLength)); + return outputParts.join('/'); } -exports.setupIntegrations = setupIntegrations; -//# sourceMappingURL=integration.js.map - -/***/ }), - -/***/ 87349: -/***/ ((__unused_webpack_module, exports) => { - -Object.defineProperty(exports, "__esModule", ({ value: true })); -var originalFunctionToString; -/** Patch toString calls to return proper name for wrapped functions */ -var FunctionToString = /** @class */ (function () { - function FunctionToString() { - /** - * @inheritDoc - */ - this.name = FunctionToString.id; +exports.relative = relative; +// path.normalize(path) +// posix version +/** JSDoc */ +function normalizePath(path) { + var isPathAbsolute = isAbsolute(path); + var trailingSlash = path.substr(-1) === '/'; + // Normalize the path + var normalizedPath = normalizeArray(path.split('/').filter(function (p) { return !!p; }), !isPathAbsolute).join('/'); + if (!normalizedPath && !isPathAbsolute) { + normalizedPath = '.'; } - /** - * @inheritDoc - */ - FunctionToString.prototype.setupOnce = function () { - // eslint-disable-next-line @typescript-eslint/unbound-method - originalFunctionToString = Function.prototype.toString; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - Function.prototype.toString = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - var context = this.__sentry_original__ || this; - return originalFunctionToString.apply(context, args); - }; - }; - /** - * @inheritDoc - */ - FunctionToString.id = 'FunctionToString'; - return FunctionToString; -}()); -exports.FunctionToString = FunctionToString; -//# sourceMappingURL=functiontostring.js.map + if (normalizedPath && trailingSlash) { + normalizedPath += '/'; + } + return (isPathAbsolute ? '/' : '') + normalizedPath; +} +exports.normalizePath = normalizePath; +// posix version +/** JSDoc */ +function isAbsolute(path) { + return path.charAt(0) === '/'; +} +exports.isAbsolute = isAbsolute; +// posix version +/** JSDoc */ +function join() { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return normalizePath(args.join('/')); +} +exports.join = join; +/** JSDoc */ +function dirname(path) { + var result = splitPath(path); + var root = result[0]; + var dir = result[1]; + if (!root && !dir) { + // No dirname whatsoever + return '.'; + } + if (dir) { + // It has a dirname, strip trailing slash + dir = dir.substr(0, dir.length - 1); + } + return root + dir; +} +exports.dirname = dirname; +/** JSDoc */ +function basename(path, ext) { + var f = splitPath(path)[2]; + if (ext && f.substr(ext.length * -1) === ext) { + f = f.substr(0, f.length - ext.length); + } + return f; +} +exports.basename = basename; +//# sourceMappingURL=path.js.map /***/ }), -/***/ 54838: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 1243: +/***/ ((__unused_webpack_module, exports) => { Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var hub_1 = __nccwpck_require__(6393); -var utils_1 = __nccwpck_require__(1620); -// "Script error." is hard coded into browsers for errors that it can't read. -// this is the result of a script being pulled in from an external domain and CORS. -var DEFAULT_IGNORE_ERRORS = [/^Script error\.?$/, /^Javascript error: Script error\.? on line 0$/]; -/** Inbound filters configurable by the user */ -var InboundFilters = /** @class */ (function () { - function InboundFilters(_options) { - if (_options === void 0) { _options = {}; } - this._options = _options; - /** - * @inheritDoc - */ - this.name = InboundFilters.id; - } - /** - * @inheritDoc - */ - InboundFilters.prototype.setupOnce = function () { - hub_1.addGlobalEventProcessor(function (event) { - var hub = hub_1.getCurrentHub(); - if (!hub) { - return event; - } - var self = hub.getIntegration(InboundFilters); - if (self) { - var client = hub.getClient(); - var clientOptions = client ? client.getOptions() : {}; - var options = self._mergeOptions(clientOptions); - if (self._shouldDropEvent(event, options)) { - return null; - } - } - return event; - }); - }; - /** JSDoc */ - InboundFilters.prototype._shouldDropEvent = function (event, options) { - if (this._isSentryError(event, options)) { - utils_1.logger.warn("Event dropped due to being internal Sentry Error.\nEvent: " + utils_1.getEventDescription(event)); - return true; - } - if (this._isIgnoredError(event, options)) { - utils_1.logger.warn("Event dropped due to being matched by `ignoreErrors` option.\nEvent: " + utils_1.getEventDescription(event)); - return true; - } - if (this._isDeniedUrl(event, options)) { - utils_1.logger.warn("Event dropped due to being matched by `denyUrls` option.\nEvent: " + utils_1.getEventDescription(event) + ".\nUrl: " + this._getEventFilterUrl(event)); - return true; - } - if (!this._isAllowedUrl(event, options)) { - utils_1.logger.warn("Event dropped due to not being matched by `allowUrls` option.\nEvent: " + utils_1.getEventDescription(event) + ".\nUrl: " + this._getEventFilterUrl(event)); - return true; +exports.setPrototypeOf = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array ? setProtoOf : mixinProperties); +/** + * setPrototypeOf polyfill using __proto__ + */ +// eslint-disable-next-line @typescript-eslint/ban-types +function setProtoOf(obj, proto) { + // @ts-ignore __proto__ does not exist on obj + obj.__proto__ = proto; + return obj; +} +/** + * setPrototypeOf polyfill using mixin + */ +// eslint-disable-next-line @typescript-eslint/ban-types +function mixinProperties(obj, proto) { + for (var prop in proto) { + // eslint-disable-next-line no-prototype-builtins + if (!obj.hasOwnProperty(prop)) { + // @ts-ignore typescript complains about indexing so we remove + obj[prop] = proto[prop]; } - return false; + } + return obj; +} +//# sourceMappingURL=polyfill.js.map + +/***/ }), + +/***/ 31811: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); +var error_1 = __nccwpck_require__(66238); +var syncpromise_1 = __nccwpck_require__(87833); +/** A simple queue that holds promises. */ +var PromiseBuffer = /** @class */ (function () { + function PromiseBuffer(_limit) { + this._limit = _limit; + /** Internal set of queued Promises */ + this._buffer = []; + } + /** + * Says if the buffer is ready to take more requests + */ + PromiseBuffer.prototype.isReady = function () { + return this._limit === undefined || this.length() < this._limit; }; - /** JSDoc */ - InboundFilters.prototype._isSentryError = function (event, options) { - if (!options.ignoreInternal) { - return false; - } - try { - return ((event && - event.exception && - event.exception.values && - event.exception.values[0] && - event.exception.values[0].type === 'SentryError') || - false); - } - catch (_oO) { - return false; + /** + * Add a promise to the queue. + * + * @param task Can be any PromiseLike + * @returns The original promise. + */ + PromiseBuffer.prototype.add = function (task) { + var _this = this; + if (!this.isReady()) { + return syncpromise_1.SyncPromise.reject(new error_1.SentryError('Not adding Promise due to buffer limit reached.')); } - }; - /** JSDoc */ - InboundFilters.prototype._isIgnoredError = function (event, options) { - if (!options.ignoreErrors || !options.ignoreErrors.length) { - return false; + if (this._buffer.indexOf(task) === -1) { + this._buffer.push(task); } - return this._getPossibleEventMessages(event).some(function (message) { - // Not sure why TypeScript complains here... - return options.ignoreErrors.some(function (pattern) { return utils_1.isMatchingPattern(message, pattern); }); + task + .then(function () { return _this.remove(task); }) + .then(null, function () { + return _this.remove(task).then(null, function () { + // We have to add this catch here otherwise we have an unhandledPromiseRejection + // because it's a new Promise chain. + }); }); + return task; }; - /** JSDoc */ - InboundFilters.prototype._isDeniedUrl = function (event, options) { - // TODO: Use Glob instead? - if (!options.denyUrls || !options.denyUrls.length) { - return false; - } - var url = this._getEventFilterUrl(event); - return !url ? false : options.denyUrls.some(function (pattern) { return utils_1.isMatchingPattern(url, pattern); }); - }; - /** JSDoc */ - InboundFilters.prototype._isAllowedUrl = function (event, options) { - // TODO: Use Glob instead? - if (!options.allowUrls || !options.allowUrls.length) { - return true; - } - var url = this._getEventFilterUrl(event); - return !url ? true : options.allowUrls.some(function (pattern) { return utils_1.isMatchingPattern(url, pattern); }); - }; - /** JSDoc */ - InboundFilters.prototype._mergeOptions = function (clientOptions) { - if (clientOptions === void 0) { clientOptions = {}; } - return { - allowUrls: tslib_1.__spread((this._options.whitelistUrls || []), (this._options.allowUrls || []), (clientOptions.whitelistUrls || []), (clientOptions.allowUrls || [])), - denyUrls: tslib_1.__spread((this._options.blacklistUrls || []), (this._options.denyUrls || []), (clientOptions.blacklistUrls || []), (clientOptions.denyUrls || [])), - ignoreErrors: tslib_1.__spread((this._options.ignoreErrors || []), (clientOptions.ignoreErrors || []), DEFAULT_IGNORE_ERRORS), - ignoreInternal: typeof this._options.ignoreInternal !== 'undefined' ? this._options.ignoreInternal : true, - }; - }; - /** JSDoc */ - InboundFilters.prototype._getPossibleEventMessages = function (event) { - if (event.message) { - return [event.message]; - } - if (event.exception) { - try { - var _a = (event.exception.values && event.exception.values[0]) || {}, _b = _a.type, type = _b === void 0 ? '' : _b, _c = _a.value, value = _c === void 0 ? '' : _c; - return ["" + value, type + ": " + value]; - } - catch (oO) { - utils_1.logger.error("Cannot extract message for event " + utils_1.getEventDescription(event)); - return []; - } - } - return []; + /** + * Remove a promise to the queue. + * + * @param task Can be any PromiseLike + * @returns Removed promise. + */ + PromiseBuffer.prototype.remove = function (task) { + var removedTask = this._buffer.splice(this._buffer.indexOf(task), 1)[0]; + return removedTask; }; - /** JSDoc */ - InboundFilters.prototype._getEventFilterUrl = function (event) { - try { - if (event.stacktrace) { - var frames_1 = event.stacktrace.frames; - return (frames_1 && frames_1[frames_1.length - 1].filename) || null; - } - if (event.exception) { - var frames_2 = event.exception.values && event.exception.values[0].stacktrace && event.exception.values[0].stacktrace.frames; - return (frames_2 && frames_2[frames_2.length - 1].filename) || null; - } - return null; - } - catch (oO) { - utils_1.logger.error("Cannot extract url for event " + utils_1.getEventDescription(event)); - return null; - } + /** + * This function returns the number of unresolved promises in the queue. + */ + PromiseBuffer.prototype.length = function () { + return this._buffer.length; }; /** - * @inheritDoc + * This will drain the whole queue, returns true if queue is empty or drained. + * If timeout is provided and the queue takes longer to drain, the promise still resolves but with false. + * + * @param timeout Number in ms to wait until it resolves with false. */ - InboundFilters.id = 'InboundFilters'; - return InboundFilters; + PromiseBuffer.prototype.drain = function (timeout) { + var _this = this; + return new syncpromise_1.SyncPromise(function (resolve) { + var capturedSetTimeout = setTimeout(function () { + if (timeout && timeout > 0) { + resolve(false); + } + }, timeout); + syncpromise_1.SyncPromise.all(_this._buffer) + .then(function () { + clearTimeout(capturedSetTimeout); + resolve(true); + }) + .then(null, function () { + resolve(true); + }); + }); + }; + return PromiseBuffer; }()); -exports.InboundFilters = InboundFilters; -//# sourceMappingURL=inboundfilters.js.map +exports.PromiseBuffer = PromiseBuffer; +//# sourceMappingURL=promisebuffer.js.map /***/ }), -/***/ 96727: +/***/ 5986: +/***/ ((__unused_webpack_module, exports) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); +var defaultFunctionName = ''; +/** + * Safely extract function name from itself + */ +function getFunctionName(fn) { + try { + if (!fn || typeof fn !== 'function') { + return defaultFunctionName; + } + return fn.name || defaultFunctionName; + } + catch (e) { + // Just accessing custom props in some Selenium environments + // can cause a "Permission denied" exception (see raven-js#495). + return defaultFunctionName; + } +} +exports.getFunctionName = getFunctionName; +//# sourceMappingURL=stacktrace.js.map + +/***/ }), + +/***/ 66538: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); -var functiontostring_1 = __nccwpck_require__(87349); -exports.FunctionToString = functiontostring_1.FunctionToString; -var inboundfilters_1 = __nccwpck_require__(54838); -exports.InboundFilters = inboundfilters_1.InboundFilters; -//# sourceMappingURL=index.js.map +var is_1 = __nccwpck_require__(92757); +/** + * Truncates given string to the maximum characters count + * + * @param str An object that contains serializable values + * @param max Maximum number of characters in truncated string + * @returns string Encoded + */ +function truncate(str, max) { + if (max === void 0) { max = 0; } + if (typeof str !== 'string' || max === 0) { + return str; + } + return str.length <= max ? str : str.substr(0, max) + "..."; +} +exports.truncate = truncate; +/** + * This is basically just `trim_line` from + * https://github.com/getsentry/sentry/blob/master/src/sentry/lang/javascript/processor.py#L67 + * + * @param str An object that contains serializable values + * @param max Maximum number of characters in truncated string + * @returns string Encoded + */ +function snipLine(line, colno) { + var newLine = line; + var ll = newLine.length; + if (ll <= 150) { + return newLine; + } + if (colno > ll) { + // eslint-disable-next-line no-param-reassign + colno = ll; + } + var start = Math.max(colno - 60, 0); + if (start < 5) { + start = 0; + } + var end = Math.min(start + 140, ll); + if (end > ll - 5) { + end = ll; + } + if (end === ll) { + start = Math.max(end - 140, 0); + } + newLine = newLine.slice(start, end); + if (start > 0) { + newLine = "'{snip} " + newLine; + } + if (end < ll) { + newLine += ' {snip}'; + } + return newLine; +} +exports.snipLine = snipLine; +/** + * Join values in array + * @param input array of values to be joined together + * @param delimiter string to be placed in-between values + * @returns Joined values + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function safeJoin(input, delimiter) { + if (!Array.isArray(input)) { + return ''; + } + var output = []; + // eslint-disable-next-line @typescript-eslint/prefer-for-of + for (var i = 0; i < input.length; i++) { + var value = input[i]; + try { + output.push(String(value)); + } + catch (e) { + output.push('[value cannot be serialized]'); + } + } + return output.join(delimiter); +} +exports.safeJoin = safeJoin; +/** + * Checks if the value matches a regex or includes the string + * @param value The string value to be checked against + * @param pattern Either a regex or a string that must be contained in value + */ +function isMatchingPattern(value, pattern) { + if (!is_1.isString(value)) { + return false; + } + if (is_1.isRegExp(pattern)) { + return pattern.test(value); + } + if (typeof pattern === 'string') { + return value.indexOf(pattern) !== -1; + } + return false; +} +exports.isMatchingPattern = isMatchingPattern; +//# sourceMappingURL=string.js.map /***/ }), -/***/ 1553: +/***/ 88714: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -/** Creates a SentryRequest from an event. */ -function sessionToSentryRequest(session, api) { - var envelopeHeaders = JSON.stringify({ - sent_at: new Date().toISOString(), - }); - var itemHeaders = JSON.stringify({ - type: 'session', - }); - return { - body: envelopeHeaders + "\n" + itemHeaders + "\n" + JSON.stringify(session), - type: 'session', - url: api.getEnvelopeEndpointWithUrlEncodedAuth(), - }; +var logger_1 = __nccwpck_require__(15577); +var misc_1 = __nccwpck_require__(32154); +/** + * Tells whether current environment supports ErrorEvent objects + * {@link supportsErrorEvent}. + * + * @returns Answer to the given question. + */ +function supportsErrorEvent() { + try { + new ErrorEvent(''); + return true; + } + catch (e) { + return false; + } } -exports.sessionToSentryRequest = sessionToSentryRequest; -/** Creates a SentryRequest from an event. */ -function eventToSentryRequest(event, api) { - // since JS has no Object.prototype.pop() - var _a = event.tags || {}, samplingMethod = _a.__sentry_samplingMethod, sampleRate = _a.__sentry_sampleRate, otherTags = tslib_1.__rest(_a, ["__sentry_samplingMethod", "__sentry_sampleRate"]); - event.tags = otherTags; - var useEnvelope = event.type === 'transaction'; - var req = { - body: JSON.stringify(event), - type: event.type || 'event', - url: useEnvelope ? api.getEnvelopeEndpointWithUrlEncodedAuth() : api.getStoreEndpointWithUrlEncodedAuth(), - }; - // https://develop.sentry.dev/sdk/envelopes/ - // Since we don't need to manipulate envelopes nor store them, there is no - // exported concept of an Envelope with operations including serialization and - // deserialization. Instead, we only implement a minimal subset of the spec to - // serialize events inline here. - if (useEnvelope) { - var envelopeHeaders = JSON.stringify({ - event_id: event.event_id, - sent_at: new Date().toISOString(), - }); - var itemHeaders = JSON.stringify({ - type: event.type, - // TODO: Right now, sampleRate may or may not be defined (it won't be in the cases of inheritance and - // explicitly-set sampling decisions). Are we good with that? - sample_rates: [{ id: samplingMethod, rate: sampleRate }], - }); - // The trailing newline is optional. We intentionally don't send it to avoid - // sending unnecessary bytes. - // - // const envelope = `${envelopeHeaders}\n${itemHeaders}\n${req.body}\n`; - var envelope = envelopeHeaders + "\n" + itemHeaders + "\n" + req.body; - req.body = envelope; +exports.supportsErrorEvent = supportsErrorEvent; +/** + * Tells whether current environment supports DOMError objects + * {@link supportsDOMError}. + * + * @returns Answer to the given question. + */ +function supportsDOMError() { + try { + // Chrome: VM89:1 Uncaught TypeError: Failed to construct 'DOMError': + // 1 argument required, but only 0 present. + // @ts-ignore It really needs 1 argument, not 0. + new DOMError(''); + return true; + } + catch (e) { + return false; + } +} +exports.supportsDOMError = supportsDOMError; +/** + * Tells whether current environment supports DOMException objects + * {@link supportsDOMException}. + * + * @returns Answer to the given question. + */ +function supportsDOMException() { + try { + new DOMException(''); + return true; + } + catch (e) { + return false; + } +} +exports.supportsDOMException = supportsDOMException; +/** + * Tells whether current environment supports Fetch API + * {@link supportsFetch}. + * + * @returns Answer to the given question. + */ +function supportsFetch() { + if (!('fetch' in misc_1.getGlobalObject())) { + return false; + } + try { + new Headers(); + new Request(''); + new Response(); + return true; + } + catch (e) { + return false; + } +} +exports.supportsFetch = supportsFetch; +/** + * isNativeFetch checks if the given function is a native implementation of fetch() + */ +// eslint-disable-next-line @typescript-eslint/ban-types +function isNativeFetch(func) { + return func && /^function fetch\(\)\s+\{\s+\[native code\]\s+\}$/.test(func.toString()); +} +/** + * Tells whether current environment supports Fetch API natively + * {@link supportsNativeFetch}. + * + * @returns true if `window.fetch` is natively implemented, false otherwise + */ +function supportsNativeFetch() { + if (!supportsFetch()) { + return false; + } + var global = misc_1.getGlobalObject(); + // Fast path to avoid DOM I/O + // eslint-disable-next-line @typescript-eslint/unbound-method + if (isNativeFetch(global.fetch)) { + return true; + } + // window.fetch is implemented, but is polyfilled or already wrapped (e.g: by a chrome extension) + // so create a "pure" iframe to see if that has native fetch + var result = false; + var doc = global.document; + // eslint-disable-next-line deprecation/deprecation + if (doc && typeof doc.createElement === "function") { + try { + var sandbox = doc.createElement('iframe'); + sandbox.hidden = true; + doc.head.appendChild(sandbox); + if (sandbox.contentWindow && sandbox.contentWindow.fetch) { + // eslint-disable-next-line @typescript-eslint/unbound-method + result = isNativeFetch(sandbox.contentWindow.fetch); + } + doc.head.removeChild(sandbox); + } + catch (err) { + logger_1.logger.warn('Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ', err); + } + } + return result; +} +exports.supportsNativeFetch = supportsNativeFetch; +/** + * Tells whether current environment supports ReportingObserver API + * {@link supportsReportingObserver}. + * + * @returns Answer to the given question. + */ +function supportsReportingObserver() { + return 'ReportingObserver' in misc_1.getGlobalObject(); +} +exports.supportsReportingObserver = supportsReportingObserver; +/** + * Tells whether current environment supports Referrer Policy API + * {@link supportsReferrerPolicy}. + * + * @returns Answer to the given question. + */ +function supportsReferrerPolicy() { + // Despite all stars in the sky saying that Edge supports old draft syntax, aka 'never', 'always', 'origin' and 'default + // https://caniuse.com/#feat=referrer-policy + // It doesn't. And it throw exception instead of ignoring this parameter... + // REF: https://github.com/getsentry/raven-js/issues/1233 + if (!supportsFetch()) { + return false; + } + try { + new Request('_', { + referrerPolicy: 'origin', + }); + return true; + } + catch (e) { + return false; } - return req; } -exports.eventToSentryRequest = eventToSentryRequest; -//# sourceMappingURL=request.js.map - -/***/ }), - -/***/ 46406: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -Object.defineProperty(exports, "__esModule", ({ value: true })); -var hub_1 = __nccwpck_require__(6393); -var utils_1 = __nccwpck_require__(1620); +exports.supportsReferrerPolicy = supportsReferrerPolicy; /** - * Internal function to create a new SDK client instance. The client is - * installed and then bound to the current scope. + * Tells whether current environment supports History API + * {@link supportsHistory}. * - * @param clientClass The client class to instantiate. - * @param options Options to pass to the client. + * @returns Answer to the given question. */ -function initAndBind(clientClass, options) { - if (options.debug === true) { - utils_1.logger.enable(); - } - var hub = hub_1.getCurrentHub(); - var client = new clientClass(options); - hub.bindClient(client); +function supportsHistory() { + // NOTE: in Chrome App environment, touching history.pushState, *even inside + // a try/catch block*, will cause Chrome to output an error to console.error + // borrowed from: https://github.com/angular/angular.js/pull/13945/files + var global = misc_1.getGlobalObject(); + /* eslint-disable @typescript-eslint/no-unsafe-member-access */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + var chrome = global.chrome; + var isChromePackagedApp = chrome && chrome.app && chrome.app.runtime; + /* eslint-enable @typescript-eslint/no-unsafe-member-access */ + var hasHistoryApi = 'history' in global && !!global.history.pushState && !!global.history.replaceState; + return !isChromePackagedApp && hasHistoryApi; } -exports.initAndBind = initAndBind; -//# sourceMappingURL=sdk.js.map - -/***/ }), - -/***/ 68641: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -Object.defineProperty(exports, "__esModule", ({ value: true })); -var types_1 = __nccwpck_require__(83789); -var utils_1 = __nccwpck_require__(1620); -/** Noop transport */ -var NoopTransport = /** @class */ (function () { - function NoopTransport() { - } - /** - * @inheritDoc - */ - NoopTransport.prototype.sendEvent = function (_) { - return utils_1.SyncPromise.resolve({ - reason: "NoopTransport: Event has been skipped because no Dsn is configured.", - status: types_1.Status.Skipped, - }); - }; - /** - * @inheritDoc - */ - NoopTransport.prototype.close = function (_) { - return utils_1.SyncPromise.resolve(true); - }; - return NoopTransport; -}()); -exports.NoopTransport = NoopTransport; -//# sourceMappingURL=noop.js.map +exports.supportsHistory = supportsHistory; +//# sourceMappingURL=supports.js.map /***/ }), -/***/ 53536: +/***/ 87833: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var utils_1 = __nccwpck_require__(1620); -var scope_1 = __nccwpck_require__(4213); -var session_1 = __nccwpck_require__(12474); -/** - * API compatibility version of this hub. - * - * WARNING: This number should only be increased when the global interface - * changes and new methods are introduced. - * - * @hidden - */ -exports.API_VERSION = 3; -/** - * Default maximum number of breadcrumbs added to an event. Can be overwritten - * with {@link Options.maxBreadcrumbs}. - */ -var DEFAULT_BREADCRUMBS = 100; -/** - * Absolute maximum number of breadcrumbs added to an event. The - * `maxBreadcrumbs` option cannot be higher than this value. - */ -var MAX_BREADCRUMBS = 100; +/* eslint-disable @typescript-eslint/explicit-function-return-type */ +/* eslint-disable @typescript-eslint/typedef */ +/* eslint-disable @typescript-eslint/explicit-module-boundary-types */ +/* eslint-disable @typescript-eslint/no-explicit-any */ +var is_1 = __nccwpck_require__(92757); +/** SyncPromise internal states */ +var States; +(function (States) { + /** Pending */ + States["PENDING"] = "PENDING"; + /** Resolved / OK */ + States["RESOLVED"] = "RESOLVED"; + /** Rejected / Error */ + States["REJECTED"] = "REJECTED"; +})(States || (States = {})); /** - * @inheritDoc + * Thenable class that behaves like a Promise and follows it's interface + * but is not async internally */ -var Hub = /** @class */ (function () { - /** - * Creates a new instance of the hub, will push one {@link Layer} into the - * internal stack on creation. - * - * @param client bound to the hub. - * @param scope bound to the hub. - * @param version number, higher number means higher priority. - */ - function Hub(client, scope, _version) { - if (scope === void 0) { scope = new scope_1.Scope(); } - if (_version === void 0) { _version = exports.API_VERSION; } - this._version = _version; - /** Is a {@link Layer}[] containing the client and scope */ - this._stack = [{}]; - this.getStackTop().scope = scope; - this.bindClient(client); - } - /** - * @inheritDoc - */ - Hub.prototype.isOlderThan = function (version) { - return this._version < version; - }; - /** - * @inheritDoc - */ - Hub.prototype.bindClient = function (client) { - var top = this.getStackTop(); - top.client = client; - if (client && client.setupIntegrations) { - client.setupIntegrations(); - } - }; - /** - * @inheritDoc - */ - Hub.prototype.pushScope = function () { - // We want to clone the content of prev scope - var scope = scope_1.Scope.clone(this.getScope()); - this.getStack().push({ - client: this.getClient(), - scope: scope, - }); - return scope; - }; - /** - * @inheritDoc - */ - Hub.prototype.popScope = function () { - if (this.getStack().length <= 1) - return false; - return !!this.getStack().pop(); - }; - /** - * @inheritDoc - */ - Hub.prototype.withScope = function (callback) { - var scope = this.pushScope(); +var SyncPromise = /** @class */ (function () { + function SyncPromise(executor) { + var _this = this; + this._state = States.PENDING; + this._handlers = []; + /** JSDoc */ + this._resolve = function (value) { + _this._setResult(States.RESOLVED, value); + }; + /** JSDoc */ + this._reject = function (reason) { + _this._setResult(States.REJECTED, reason); + }; + /** JSDoc */ + this._setResult = function (state, value) { + if (_this._state !== States.PENDING) { + return; + } + if (is_1.isThenable(value)) { + value.then(_this._resolve, _this._reject); + return; + } + _this._state = state; + _this._value = value; + _this._executeHandlers(); + }; + // TODO: FIXME + /** JSDoc */ + this._attachHandler = function (handler) { + _this._handlers = _this._handlers.concat(handler); + _this._executeHandlers(); + }; + /** JSDoc */ + this._executeHandlers = function () { + if (_this._state === States.PENDING) { + return; + } + var cachedHandlers = _this._handlers.slice(); + _this._handlers = []; + cachedHandlers.forEach(function (handler) { + if (handler.done) { + return; + } + if (_this._state === States.RESOLVED) { + if (handler.onfulfilled) { + // eslint-disable-next-line @typescript-eslint/no-floating-promises + handler.onfulfilled(_this._value); + } + } + if (_this._state === States.REJECTED) { + if (handler.onrejected) { + handler.onrejected(_this._value); + } + } + handler.done = true; + }); + }; try { - callback(scope); + executor(this._resolve, this._reject); } - finally { - this.popScope(); + catch (e) { + this._reject(e); } + } + /** JSDoc */ + SyncPromise.resolve = function (value) { + return new SyncPromise(function (resolve) { + resolve(value); + }); }; - /** - * @inheritDoc - */ - Hub.prototype.getClient = function () { - return this.getStackTop().client; - }; - /** Returns the scope of the top stack. */ - Hub.prototype.getScope = function () { - return this.getStackTop().scope; - }; - /** Returns the scope stack for domains or the process. */ - Hub.prototype.getStack = function () { - return this._stack; - }; - /** Returns the topmost scope layer in the order domain > local > process. */ - Hub.prototype.getStackTop = function () { - return this._stack[this._stack.length - 1]; - }; - /** - * @inheritDoc - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types - Hub.prototype.captureException = function (exception, hint) { - var eventId = (this._lastEventId = utils_1.uuid4()); - var finalHint = hint; - // If there's no explicit hint provided, mimick the same thing that would happen - // in the minimal itself to create a consistent behavior. - // We don't do this in the client, as it's the lowest level API, and doing this, - // would prevent user from having full control over direct calls. - if (!hint) { - var syntheticException = void 0; - try { - throw new Error('Sentry syntheticException'); - } - catch (exception) { - syntheticException = exception; - } - finalHint = { - originalException: exception, - syntheticException: syntheticException, - }; - } - this._invokeClient('captureException', exception, tslib_1.__assign(tslib_1.__assign({}, finalHint), { event_id: eventId })); - return eventId; + /** JSDoc */ + SyncPromise.reject = function (reason) { + return new SyncPromise(function (_, reject) { + reject(reason); + }); }; - /** - * @inheritDoc - */ - Hub.prototype.captureMessage = function (message, level, hint) { - var eventId = (this._lastEventId = utils_1.uuid4()); - var finalHint = hint; - // If there's no explicit hint provided, mimick the same thing that would happen - // in the minimal itself to create a consistent behavior. - // We don't do this in the client, as it's the lowest level API, and doing this, - // would prevent user from having full control over direct calls. - if (!hint) { - var syntheticException = void 0; - try { - throw new Error(message); + /** JSDoc */ + SyncPromise.all = function (collection) { + return new SyncPromise(function (resolve, reject) { + if (!Array.isArray(collection)) { + reject(new TypeError("Promise.all requires an array as input.")); + return; } - catch (exception) { - syntheticException = exception; + if (collection.length === 0) { + resolve([]); + return; } - finalHint = { - originalException: message, - syntheticException: syntheticException, - }; - } - this._invokeClient('captureMessage', message, level, tslib_1.__assign(tslib_1.__assign({}, finalHint), { event_id: eventId })); - return eventId; - }; - /** - * @inheritDoc - */ - Hub.prototype.captureEvent = function (event, hint) { - var eventId = (this._lastEventId = utils_1.uuid4()); - this._invokeClient('captureEvent', event, tslib_1.__assign(tslib_1.__assign({}, hint), { event_id: eventId })); - return eventId; - }; - /** - * @inheritDoc - */ - Hub.prototype.lastEventId = function () { - return this._lastEventId; - }; - /** - * @inheritDoc - */ - Hub.prototype.addBreadcrumb = function (breadcrumb, hint) { - var _a = this.getStackTop(), scope = _a.scope, client = _a.client; - if (!scope || !client) - return; - // eslint-disable-next-line @typescript-eslint/unbound-method - var _b = (client.getOptions && client.getOptions()) || {}, _c = _b.beforeBreadcrumb, beforeBreadcrumb = _c === void 0 ? null : _c, _d = _b.maxBreadcrumbs, maxBreadcrumbs = _d === void 0 ? DEFAULT_BREADCRUMBS : _d; - if (maxBreadcrumbs <= 0) - return; - var timestamp = utils_1.dateTimestampInSeconds(); - var mergedBreadcrumb = tslib_1.__assign({ timestamp: timestamp }, breadcrumb); - var finalBreadcrumb = beforeBreadcrumb - ? utils_1.consoleSandbox(function () { return beforeBreadcrumb(mergedBreadcrumb, hint); }) - : mergedBreadcrumb; - if (finalBreadcrumb === null) - return; - scope.addBreadcrumb(finalBreadcrumb, Math.min(maxBreadcrumbs, MAX_BREADCRUMBS)); + var counter = collection.length; + var resolvedCollection = []; + collection.forEach(function (item, index) { + SyncPromise.resolve(item) + .then(function (value) { + resolvedCollection[index] = value; + counter -= 1; + if (counter !== 0) { + return; + } + resolve(resolvedCollection); + }) + .then(null, reject); + }); + }); }; - /** - * @inheritDoc - */ - Hub.prototype.setUser = function (user) { - var scope = this.getScope(); - if (scope) - scope.setUser(user); + /** JSDoc */ + SyncPromise.prototype.then = function (onfulfilled, onrejected) { + var _this = this; + return new SyncPromise(function (resolve, reject) { + _this._attachHandler({ + done: false, + onfulfilled: function (result) { + if (!onfulfilled) { + // TODO: ¯\_(ツ)_/¯ + // TODO: FIXME + resolve(result); + return; + } + try { + resolve(onfulfilled(result)); + return; + } + catch (e) { + reject(e); + return; + } + }, + onrejected: function (reason) { + if (!onrejected) { + reject(reason); + return; + } + try { + resolve(onrejected(reason)); + return; + } + catch (e) { + reject(e); + return; + } + }, + }); + }); }; - /** - * @inheritDoc - */ - Hub.prototype.setTags = function (tags) { - var scope = this.getScope(); - if (scope) - scope.setTags(tags); + /** JSDoc */ + SyncPromise.prototype.catch = function (onrejected) { + return this.then(function (val) { return val; }, onrejected); }; - /** - * @inheritDoc - */ - Hub.prototype.setExtras = function (extras) { - var scope = this.getScope(); - if (scope) - scope.setExtras(extras); + /** JSDoc */ + SyncPromise.prototype.finally = function (onfinally) { + var _this = this; + return new SyncPromise(function (resolve, reject) { + var val; + var isRejected; + return _this.then(function (value) { + isRejected = false; + val = value; + if (onfinally) { + onfinally(); + } + }, function (reason) { + isRejected = true; + val = reason; + if (onfinally) { + onfinally(); + } + }).then(function () { + if (isRejected) { + reject(val); + return; + } + resolve(val); + }); + }); }; - /** - * @inheritDoc - */ - Hub.prototype.setTag = function (key, value) { - var scope = this.getScope(); - if (scope) - scope.setTag(key, value); + /** JSDoc */ + SyncPromise.prototype.toString = function () { + return '[object SyncPromise]'; }; - /** - * @inheritDoc - */ - Hub.prototype.setExtra = function (key, extra) { - var scope = this.getScope(); - if (scope) - scope.setExtra(key, extra); + return SyncPromise; +}()); +exports.SyncPromise = SyncPromise; +//# sourceMappingURL=syncpromise.js.map + +/***/ }), + +/***/ 1735: +/***/ ((module, exports, __nccwpck_require__) => { + +/* module decorator */ module = __nccwpck_require__.nmd(module); +Object.defineProperty(exports, "__esModule", ({ value: true })); +var misc_1 = __nccwpck_require__(32154); +var node_1 = __nccwpck_require__(16411); +/** + * A TimestampSource implementation for environments that do not support the Performance Web API natively. + * + * Note that this TimestampSource does not use a monotonic clock. A call to `nowSeconds` may return a timestamp earlier + * than a previously returned value. We do not try to emulate a monotonic behavior in order to facilitate debugging. It + * is more obvious to explain "why does my span have negative duration" than "why my spans have zero duration". + */ +var dateTimestampSource = { + nowSeconds: function () { return Date.now() / 1000; }, +}; +/** + * Returns a wrapper around the native Performance API browser implementation, or undefined for browsers that do not + * support the API. + * + * Wrapping the native API works around differences in behavior from different browsers. + */ +function getBrowserPerformance() { + var performance = misc_1.getGlobalObject().performance; + if (!performance || !performance.now) { + return undefined; + } + // Replace performance.timeOrigin with our own timeOrigin based on Date.now(). + // + // This is a partial workaround for browsers reporting performance.timeOrigin such that performance.timeOrigin + + // performance.now() gives a date arbitrarily in the past. + // + // Additionally, computing timeOrigin in this way fills the gap for browsers where performance.timeOrigin is + // undefined. + // + // The assumption that performance.timeOrigin + performance.now() ~= Date.now() is flawed, but we depend on it to + // interact with data coming out of performance entries. + // + // Note that despite recommendations against it in the spec, browsers implement the Performance API with a clock that + // might stop when the computer is asleep (and perhaps under other circumstances). Such behavior causes + // performance.timeOrigin + performance.now() to have an arbitrary skew over Date.now(). In laptop computers, we have + // observed skews that can be as long as days, weeks or months. + // + // See https://github.com/getsentry/sentry-javascript/issues/2590. + // + // BUG: despite our best intentions, this workaround has its limitations. It mostly addresses timings of pageload + // transactions, but ignores the skew built up over time that can aversely affect timestamps of navigation + // transactions of long-lived web pages. + var timeOrigin = Date.now() - performance.now(); + return { + now: function () { return performance.now(); }, + timeOrigin: timeOrigin, }; - /** - * @inheritDoc - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - Hub.prototype.setContext = function (name, context) { - var scope = this.getScope(); - if (scope) - scope.setContext(name, context); +} +/** + * Returns the native Performance API implementation from Node.js. Returns undefined in old Node.js versions that don't + * implement the API. + */ +function getNodePerformance() { + try { + var perfHooks = node_1.dynamicRequire(module, 'perf_hooks'); + return perfHooks.performance; + } + catch (_) { + return undefined; + } +} +/** + * The Performance API implementation for the current platform, if available. + */ +var platformPerformance = node_1.isNodeEnv() ? getNodePerformance() : getBrowserPerformance(); +var timestampSource = platformPerformance === undefined + ? dateTimestampSource + : { + nowSeconds: function () { return (platformPerformance.timeOrigin + platformPerformance.now()) / 1000; }, }; - /** - * @inheritDoc - */ - Hub.prototype.configureScope = function (callback) { - var _a = this.getStackTop(), scope = _a.scope, client = _a.client; - if (scope && client) { - callback(scope); +/** + * Returns a timestamp in seconds since the UNIX epoch using the Date API. + */ +exports.dateTimestampInSeconds = dateTimestampSource.nowSeconds.bind(dateTimestampSource); +/** + * Returns a timestamp in seconds since the UNIX epoch using either the Performance or Date APIs, depending on the + * availability of the Performance API. + * + * See `usingPerformanceAPI` to test whether the Performance API is used. + * + * BUG: Note that because of how browsers implement the Performance API, the clock might stop when the computer is + * asleep. This creates a skew between `dateTimestampInSeconds` and `timestampInSeconds`. The + * skew can grow to arbitrary amounts like days, weeks or months. + * See https://github.com/getsentry/sentry-javascript/issues/2590. + */ +exports.timestampInSeconds = timestampSource.nowSeconds.bind(timestampSource); +// Re-exported with an old name for backwards-compatibility. +exports.timestampWithMs = exports.timestampInSeconds; +/** + * A boolean that is true when timestampInSeconds uses the Performance API to produce monotonic timestamps. + */ +exports.usingPerformanceAPI = platformPerformance !== undefined; +/** + * The number of milliseconds since the UNIX epoch. This value is only usable in a browser, and only when the + * performance API is available. + */ +exports.browserPerformanceTimeOrigin = (function () { + var performance = misc_1.getGlobalObject().performance; + if (!performance) { + return undefined; + } + if (performance.timeOrigin) { + return performance.timeOrigin; + } + // While performance.timing.navigationStart is deprecated in favor of performance.timeOrigin, performance.timeOrigin + // is not as widely supported. Namely, performance.timeOrigin is undefined in Safari as of writing. + // Also as of writing, performance.timing is not available in Web Workers in mainstream browsers, so it is not always + // a valid fallback. In the absence of an initial time provided by the browser, fallback to the current time from the + // Date API. + // eslint-disable-next-line deprecation/deprecation + return (performance.timing && performance.timing.navigationStart) || Date.now(); +})(); +//# sourceMappingURL=time.js.map + +/***/ }), + +/***/ 97425: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +const Url = __nccwpck_require__(57310); + +const Errors = __nccwpck_require__(91594); + + +const internals = { + minDomainSegments: 2, + nonAsciiRx: /[^\x00-\x7f]/, + domainControlRx: /[\x00-\x20@\:\/\\#!\$&\'\(\)\*\+,;=\?]/, // Control + space + separators + tldSegmentRx: /^[a-zA-Z](?:[a-zA-Z0-9\-]*[a-zA-Z0-9])?$/, + domainSegmentRx: /^[a-zA-Z0-9](?:[a-zA-Z0-9\-]*[a-zA-Z0-9])?$/, + URL: Url.URL || URL // $lab:coverage:ignore$ +}; + + +exports.analyze = function (domain, options = {}) { + + if (!domain) { // Catch null / undefined + return Errors.code('DOMAIN_NON_EMPTY_STRING'); + } + + if (typeof domain !== 'string') { + throw new Error('Invalid input: domain must be a string'); + } + + if (domain.length > 256) { + return Errors.code('DOMAIN_TOO_LONG'); + } + + const ascii = !internals.nonAsciiRx.test(domain); + if (!ascii) { + if (options.allowUnicode === false) { // Defaults to true + return Errors.code('DOMAIN_INVALID_UNICODE_CHARS'); } - }; - /** - * @inheritDoc - */ - Hub.prototype.run = function (callback) { - var oldHub = makeMain(this); - try { - callback(this); + + domain = domain.normalize('NFC'); + } + + if (internals.domainControlRx.test(domain)) { + return Errors.code('DOMAIN_INVALID_CHARS'); + } + + domain = internals.punycode(domain); + + // https://tools.ietf.org/html/rfc1035 section 2.3.1 + + if (options.allowFullyQualified && + domain[domain.length - 1] === '.') { + + domain = domain.slice(0, -1); + } + + const minDomainSegments = options.minDomainSegments || internals.minDomainSegments; + + const segments = domain.split('.'); + if (segments.length < minDomainSegments) { + return Errors.code('DOMAIN_SEGMENTS_COUNT'); + } + + if (options.maxDomainSegments) { + if (segments.length > options.maxDomainSegments) { + return Errors.code('DOMAIN_SEGMENTS_COUNT_MAX'); } - finally { - makeMain(oldHub); + } + + const tlds = options.tlds; + if (tlds) { + const tld = segments[segments.length - 1].toLowerCase(); + if (tlds.deny && tlds.deny.has(tld) || + tlds.allow && !tlds.allow.has(tld)) { + + return Errors.code('DOMAIN_FORBIDDEN_TLDS'); } - }; - /** - * @inheritDoc - */ - Hub.prototype.getIntegration = function (integration) { - var client = this.getClient(); - if (!client) - return null; - try { - return client.getIntegration(integration); + } + + for (let i = 0; i < segments.length; ++i) { + const segment = segments[i]; + + if (!segment.length) { + return Errors.code('DOMAIN_EMPTY_SEGMENT'); } - catch (_oO) { - utils_1.logger.warn("Cannot retrieve integration " + integration.id + " from the current Hub"); - return null; + + if (segment.length > 63) { + return Errors.code('DOMAIN_LONG_SEGMENT'); } - }; - /** - * @inheritDoc - */ - Hub.prototype.startSpan = function (context) { - return this._callExtensionMethod('startSpan', context); - }; - /** - * @inheritDoc - */ - Hub.prototype.startTransaction = function (context, customSamplingContext) { - return this._callExtensionMethod('startTransaction', context, customSamplingContext); - }; - /** - * @inheritDoc - */ - Hub.prototype.traceHeaders = function () { - return this._callExtensionMethod('traceHeaders'); - }; - /** - * @inheritDoc - */ - Hub.prototype.startSession = function (context) { - // End existing session if there's one - this.endSession(); - var _a = this.getStackTop(), scope = _a.scope, client = _a.client; - var _b = (client && client.getOptions()) || {}, release = _b.release, environment = _b.environment; - var session = new session_1.Session(tslib_1.__assign(tslib_1.__assign({ release: release, - environment: environment }, (scope && { user: scope.getUser() })), context)); - if (scope) { - scope.setSession(session); + + if (i < segments.length - 1) { + if (!internals.domainSegmentRx.test(segment)) { + return Errors.code('DOMAIN_INVALID_CHARS'); + } } - return session; - }; - /** - * @inheritDoc - */ - Hub.prototype.endSession = function () { - var _a = this.getStackTop(), scope = _a.scope, client = _a.client; - if (!scope) - return; - var session = scope.getSession && scope.getSession(); - if (session) { - session.close(); - if (client && client.captureSession) { - client.captureSession(session); + else { + if (!internals.tldSegmentRx.test(segment)) { + return Errors.code('DOMAIN_INVALID_TLDS_CHARS'); } - scope.setSession(); } - }; - /** - * Internal helper function to call a method on the top client if it exists. - * - * @param method The method to call on the client. - * @param args Arguments to pass to the client function. - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - Hub.prototype._invokeClient = function (method) { - var _a; - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; + } + + return null; +}; + + +exports.isValid = function (domain, options) { + + return !exports.analyze(domain, options); +}; + + +internals.punycode = function (domain) { + + if (domain.includes('%')) { + domain = domain.replace(/%/g, '%25'); + } + + try { + return new internals.URL(`http://${domain}`).host; + } + catch (err) { + return domain; + } +}; + + +/***/ }), + +/***/ 3283: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +const Util = __nccwpck_require__(73837); + +const Domain = __nccwpck_require__(97425); +const Errors = __nccwpck_require__(91594); + + +const internals = { + nonAsciiRx: /[^\x00-\x7f]/, + encoder: new (Util.TextEncoder || TextEncoder)() // $lab:coverage:ignore$ +}; + + +exports.analyze = function (email, options) { + + return internals.email(email, options); +}; + + +exports.isValid = function (email, options) { + + return !internals.email(email, options); +}; + + +internals.email = function (email, options = {}) { + + if (typeof email !== 'string') { + throw new Error('Invalid input: email must be a string'); + } + + if (!email) { + return Errors.code('EMPTY_STRING'); + } + + // Unicode + + const ascii = !internals.nonAsciiRx.test(email); + if (!ascii) { + if (options.allowUnicode === false) { // Defaults to true + return Errors.code('FORBIDDEN_UNICODE'); } - var _b = this.getStackTop(), scope = _b.scope, client = _b.client; - if (client && client[method]) { - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any - (_a = client)[method].apply(_a, tslib_1.__spread(args, [scope])); + + email = email.normalize('NFC'); + } + + // Basic structure + + const parts = email.split('@'); + if (parts.length !== 2) { + return parts.length > 2 ? Errors.code('MULTIPLE_AT_CHAR') : Errors.code('MISSING_AT_CHAR'); + } + + const [local, domain] = parts; + + if (!local) { + return Errors.code('EMPTY_LOCAL'); + } + + if (!options.ignoreLength) { + if (email.length > 254) { // http://tools.ietf.org/html/rfc5321#section-4.5.3.1.3 + return Errors.code('ADDRESS_TOO_LONG'); } - }; - /** - * Calls global extension method and binding current instance to the function call - */ - // @ts-ignore Function lacks ending return statement and return type does not include 'undefined'. ts(2366) - // eslint-disable-next-line @typescript-eslint/no-explicit-any - Hub.prototype._callExtensionMethod = function (method) { - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; + + if (internals.encoder.encode(local).length > 64) { // http://tools.ietf.org/html/rfc5321#section-4.5.3.1.1 + return Errors.code('LOCAL_TOO_LONG'); } - var carrier = getMainCarrier(); - var sentry = carrier.__SENTRY__; - if (sentry && sentry.extensions && typeof sentry.extensions[method] === 'function') { - return sentry.extensions[method].apply(this, args); + } + + // Validate parts + + return internals.local(local, ascii) || Domain.analyze(domain, options); +}; + + +internals.local = function (local, ascii) { + + const segments = local.split('.'); + for (const segment of segments) { + if (!segment.length) { + return Errors.code('EMPTY_LOCAL_SEGMENT'); } - utils_1.logger.warn("Extension method " + method + " couldn't be found, doing nothing."); - }; - return Hub; -}()); -exports.Hub = Hub; -/** Returns the global shim registry. */ -function getMainCarrier() { - var carrier = utils_1.getGlobalObject(); - carrier.__SENTRY__ = carrier.__SENTRY__ || { - extensions: {}, - hub: undefined, - }; - return carrier; -} -exports.getMainCarrier = getMainCarrier; -/** - * Replaces the current main hub with the passed one on the global object - * - * @returns The old replaced hub - */ -function makeMain(hub) { - var registry = getMainCarrier(); - var oldHub = getHubFromCarrier(registry); - setHubOnCarrier(registry, hub); - return oldHub; -} -exports.makeMain = makeMain; -/** - * Returns the default hub instance. - * - * If a hub is already registered in the global carrier but this module - * contains a more recent version, it replaces the registered version. - * Otherwise, the currently registered hub will be returned. - */ -function getCurrentHub() { - // Get main carrier (global for every environment) - var registry = getMainCarrier(); - // If there's no hub, or its an old API, assign a new one - if (!hasHubOnCarrier(registry) || getHubFromCarrier(registry).isOlderThan(exports.API_VERSION)) { - setHubOnCarrier(registry, new Hub()); + + if (ascii) { + if (!internals.atextRx.test(segment)) { + return Errors.code('INVALID_LOCAL_CHARS'); + } + + continue; + } + + for (const char of segment) { + if (internals.atextRx.test(char)) { + continue; + } + + const binary = internals.binary(char); + if (!internals.atomRx.test(binary)) { + return Errors.code('INVALID_LOCAL_CHARS'); + } + } + } +}; + + +internals.binary = function (char) { + + return Array.from(internals.encoder.encode(char)).map((v) => String.fromCharCode(v)).join(''); +}; + + +/* + From RFC 5321: + + Mailbox = Local-part "@" ( Domain / address-literal ) + + Local-part = Dot-string / Quoted-string + Dot-string = Atom *("." Atom) + Atom = 1*atext + atext = ALPHA / DIGIT / "!" / "#" / "$" / "%" / "&" / "'" / "*" / "+" / "-" / "/" / "=" / "?" / "^" / "_" / "`" / "{" / "|" / "}" / "~" + + Domain = sub-domain *("." sub-domain) + sub-domain = Let-dig [Ldh-str] + Let-dig = ALPHA / DIGIT + Ldh-str = *( ALPHA / DIGIT / "-" ) Let-dig + + ALPHA = %x41-5A / %x61-7A ; a-z, A-Z + DIGIT = %x30-39 ; 0-9 + + From RFC 6531: + + sub-domain =/ U-label + atext =/ UTF8-non-ascii + + UTF8-non-ascii = UTF8-2 / UTF8-3 / UTF8-4 + + UTF8-2 = %xC2-DF UTF8-tail + UTF8-3 = %xE0 %xA0-BF UTF8-tail / + %xE1-EC 2( UTF8-tail ) / + %xED %x80-9F UTF8-tail / + %xEE-EF 2( UTF8-tail ) + UTF8-4 = %xF0 %x90-BF 2( UTF8-tail ) / + %xF1-F3 3( UTF8-tail ) / + %xF4 %x80-8F 2( UTF8-tail ) + + UTF8-tail = %x80-BF + + Note: The following are not supported: + + RFC 5321: address-literal, Quoted-string + RFC 5322: obs-*, CFWS +*/ + + +internals.atextRx = /^[\w!#\$%&'\*\+\-/=\?\^`\{\|\}~]+$/; // _ included in \w + + +internals.atomRx = new RegExp([ + + // %xC2-DF UTF8-tail + '(?:[\\xc2-\\xdf][\\x80-\\xbf])', + + // %xE0 %xA0-BF UTF8-tail %xE1-EC 2( UTF8-tail ) %xED %x80-9F UTF8-tail %xEE-EF 2( UTF8-tail ) + '(?:\\xe0[\\xa0-\\xbf][\\x80-\\xbf])|(?:[\\xe1-\\xec][\\x80-\\xbf]{2})|(?:\\xed[\\x80-\\x9f][\\x80-\\xbf])|(?:[\\xee-\\xef][\\x80-\\xbf]{2})', + + // %xF0 %x90-BF 2( UTF8-tail ) %xF1-F3 3( UTF8-tail ) %xF4 %x80-8F 2( UTF8-tail ) + '(?:\\xf0[\\x90-\\xbf][\\x80-\\xbf]{2})|(?:[\\xf1-\\xf3][\\x80-\\xbf]{3})|(?:\\xf4[\\x80-\\x8f][\\x80-\\xbf]{2})' + +].join('|')); + + +/***/ }), + +/***/ 91594: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +exports.codes = { + EMPTY_STRING: 'Address must be a non-empty string', + FORBIDDEN_UNICODE: 'Address contains forbidden Unicode characters', + MULTIPLE_AT_CHAR: 'Address cannot contain more than one @ character', + MISSING_AT_CHAR: 'Address must contain one @ character', + EMPTY_LOCAL: 'Address local part cannot be empty', + ADDRESS_TOO_LONG: 'Address too long', + LOCAL_TOO_LONG: 'Address local part too long', + EMPTY_LOCAL_SEGMENT: 'Address local part contains empty dot-separated segment', + INVALID_LOCAL_CHARS: 'Address local part contains invalid character', + DOMAIN_NON_EMPTY_STRING: 'Domain must be a non-empty string', + DOMAIN_TOO_LONG: 'Domain too long', + DOMAIN_INVALID_UNICODE_CHARS: 'Domain contains forbidden Unicode characters', + DOMAIN_INVALID_CHARS: 'Domain contains invalid character', + DOMAIN_INVALID_TLDS_CHARS: 'Domain contains invalid tld character', + DOMAIN_SEGMENTS_COUNT: 'Domain lacks the minimum required number of segments', + DOMAIN_SEGMENTS_COUNT_MAX: 'Domain contains too many segments', + DOMAIN_FORBIDDEN_TLDS: 'Domain uses forbidden TLD', + DOMAIN_EMPTY_SEGMENT: 'Domain contains empty dot-separated segment', + DOMAIN_LONG_SEGMENT: 'Domain contains dot-separated segment that is too long' +}; + + +exports.code = function (code) { + + return { code, error: exports.codes[code] }; +}; + + +/***/ }), + +/***/ 82337: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +const Assert = __nccwpck_require__(32718); + +const Uri = __nccwpck_require__(74983); + + +const internals = {}; + + +exports.regex = function (options = {}) { + + // CIDR + + Assert(options.cidr === undefined || typeof options.cidr === 'string', 'options.cidr must be a string'); + const cidr = options.cidr ? options.cidr.toLowerCase() : 'optional'; + Assert(['required', 'optional', 'forbidden'].includes(cidr), 'options.cidr must be one of required, optional, forbidden'); + + // Versions + + Assert(options.version === undefined || typeof options.version === 'string' || Array.isArray(options.version), 'options.version must be a string or an array of string'); + let versions = options.version || ['ipv4', 'ipv6', 'ipvfuture']; + if (!Array.isArray(versions)) { + versions = [versions]; } - // Prefer domains over global if they are there (applicable only to Node environment) - if (utils_1.isNodeEnv()) { - return getHubFromActiveDomain(registry); + + Assert(versions.length >= 1, 'options.version must have at least 1 version specified'); + + for (let i = 0; i < versions.length; ++i) { + Assert(typeof versions[i] === 'string', 'options.version must only contain strings'); + versions[i] = versions[i].toLowerCase(); + Assert(['ipv4', 'ipv6', 'ipvfuture'].includes(versions[i]), 'options.version contains unknown version ' + versions[i] + ' - must be one of ipv4, ipv6, ipvfuture'); } - // Return hub that lives on a global object - return getHubFromCarrier(registry); -} -exports.getCurrentHub = getCurrentHub; -/** - * Returns the active domain, if one exists - * - * @returns The domain, or undefined if there is no active domain - */ -function getActiveDomain() { - var sentry = getMainCarrier().__SENTRY__; - return sentry && sentry.extensions && sentry.extensions.domain && sentry.extensions.domain.active; -} -exports.getActiveDomain = getActiveDomain; -/** - * Try to read the hub from an active domain, and fallback to the registry if one doesn't exist - * @returns discovered hub - */ -function getHubFromActiveDomain(registry) { - try { - var activeDomain = getActiveDomain(); - // If there's no active domain, just return global hub - if (!activeDomain) { - return getHubFromCarrier(registry); + + versions = Array.from(new Set(versions)); + + // Regex + + const parts = versions.map((version) => { + + // Forbidden + + if (cidr === 'forbidden') { + return Uri.ip[version]; } - // If there's no hub on current domain, or it's an old API, assign a new one - if (!hasHubOnCarrier(activeDomain) || getHubFromCarrier(activeDomain).isOlderThan(exports.API_VERSION)) { - var registryHubTopStack = getHubFromCarrier(registry).getStackTop(); - setHubOnCarrier(activeDomain, new Hub(registryHubTopStack.client, scope_1.Scope.clone(registryHubTopStack.scope))); + + // Required + + const cidrpart = `\\/${version === 'ipv4' ? Uri.ip.v4Cidr : Uri.ip.v6Cidr}`; + + if (cidr === 'required') { + return `${Uri.ip[version]}${cidrpart}`; } - // Return hub that lives on a domain - return getHubFromCarrier(activeDomain); - } - catch (_Oo) { - // Return hub that lives on a global object - return getHubFromCarrier(registry); - } -} -/** - * This will tell whether a carrier has a hub on it or not - * @param carrier object - */ -function hasHubOnCarrier(carrier) { - return !!(carrier && carrier.__SENTRY__ && carrier.__SENTRY__.hub); -} -/** - * This will create a new {@link Hub} and add to the passed object on - * __SENTRY__.hub. - * @param carrier object - * @hidden - */ -function getHubFromCarrier(carrier) { - if (carrier && carrier.__SENTRY__ && carrier.__SENTRY__.hub) - return carrier.__SENTRY__.hub; - carrier.__SENTRY__ = carrier.__SENTRY__ || {}; - carrier.__SENTRY__.hub = new Hub(); - return carrier.__SENTRY__.hub; -} -exports.getHubFromCarrier = getHubFromCarrier; -/** - * This will set passed {@link Hub} on the passed object's __SENTRY__.hub attribute - * @param carrier object - * @param hub Hub - */ -function setHubOnCarrier(carrier, hub) { - if (!carrier) - return false; - carrier.__SENTRY__ = carrier.__SENTRY__ || {}; - carrier.__SENTRY__.hub = hub; - return true; -} -exports.setHubOnCarrier = setHubOnCarrier; -//# sourceMappingURL=hub.js.map -/***/ }), + // Optional + + return `${Uri.ip[version]}(?:${cidrpart})?`; + }); + + const raw = `(?:${parts.join('|')})`; + const regex = new RegExp(`^${raw}$`); + return { cidr, versions, regex, raw }; +}; + + +/***/ }), + +/***/ 53092: +/***/ ((module) => { + +"use strict"; + + +const internals = {}; + + +// http://data.iana.org/TLD/tlds-alpha-by-domain.txt +// # Version 2021020700, Last Updated Sun Feb 7 07: 07: 01 2021 UTC + + +internals.tlds = [ + 'AAA', + 'AARP', + 'ABARTH', + 'ABB', + 'ABBOTT', + 'ABBVIE', + 'ABC', + 'ABLE', + 'ABOGADO', + 'ABUDHABI', + 'AC', + 'ACADEMY', + 'ACCENTURE', + 'ACCOUNTANT', + 'ACCOUNTANTS', + 'ACO', + 'ACTOR', + 'AD', + 'ADAC', + 'ADS', + 'ADULT', + 'AE', + 'AEG', + 'AERO', + 'AETNA', + 'AF', + 'AFAMILYCOMPANY', + 'AFL', + 'AFRICA', + 'AG', + 'AGAKHAN', + 'AGENCY', + 'AI', + 'AIG', + 'AIRBUS', + 'AIRFORCE', + 'AIRTEL', + 'AKDN', + 'AL', + 'ALFAROMEO', + 'ALIBABA', + 'ALIPAY', + 'ALLFINANZ', + 'ALLSTATE', + 'ALLY', + 'ALSACE', + 'ALSTOM', + 'AM', + 'AMAZON', + 'AMERICANEXPRESS', + 'AMERICANFAMILY', + 'AMEX', + 'AMFAM', + 'AMICA', + 'AMSTERDAM', + 'ANALYTICS', + 'ANDROID', + 'ANQUAN', + 'ANZ', + 'AO', + 'AOL', + 'APARTMENTS', + 'APP', + 'APPLE', + 'AQ', + 'AQUARELLE', + 'AR', + 'ARAB', + 'ARAMCO', + 'ARCHI', + 'ARMY', + 'ARPA', + 'ART', + 'ARTE', + 'AS', + 'ASDA', + 'ASIA', + 'ASSOCIATES', + 'AT', + 'ATHLETA', + 'ATTORNEY', + 'AU', + 'AUCTION', + 'AUDI', + 'AUDIBLE', + 'AUDIO', + 'AUSPOST', + 'AUTHOR', + 'AUTO', + 'AUTOS', + 'AVIANCA', + 'AW', + 'AWS', + 'AX', + 'AXA', + 'AZ', + 'AZURE', + 'BA', + 'BABY', + 'BAIDU', + 'BANAMEX', + 'BANANAREPUBLIC', + 'BAND', + 'BANK', + 'BAR', + 'BARCELONA', + 'BARCLAYCARD', + 'BARCLAYS', + 'BAREFOOT', + 'BARGAINS', + 'BASEBALL', + 'BASKETBALL', + 'BAUHAUS', + 'BAYERN', + 'BB', + 'BBC', + 'BBT', + 'BBVA', + 'BCG', + 'BCN', + 'BD', + 'BE', + 'BEATS', + 'BEAUTY', + 'BEER', + 'BENTLEY', + 'BERLIN', + 'BEST', + 'BESTBUY', + 'BET', + 'BF', + 'BG', + 'BH', + 'BHARTI', + 'BI', + 'BIBLE', + 'BID', + 'BIKE', + 'BING', + 'BINGO', + 'BIO', + 'BIZ', + 'BJ', + 'BLACK', + 'BLACKFRIDAY', + 'BLOCKBUSTER', + 'BLOG', + 'BLOOMBERG', + 'BLUE', + 'BM', + 'BMS', + 'BMW', + 'BN', + 'BNPPARIBAS', + 'BO', + 'BOATS', + 'BOEHRINGER', + 'BOFA', + 'BOM', + 'BOND', + 'BOO', + 'BOOK', + 'BOOKING', + 'BOSCH', + 'BOSTIK', + 'BOSTON', + 'BOT', + 'BOUTIQUE', + 'BOX', + 'BR', + 'BRADESCO', + 'BRIDGESTONE', + 'BROADWAY', + 'BROKER', + 'BROTHER', + 'BRUSSELS', + 'BS', + 'BT', + 'BUDAPEST', + 'BUGATTI', + 'BUILD', + 'BUILDERS', + 'BUSINESS', + 'BUY', + 'BUZZ', + 'BV', + 'BW', + 'BY', + 'BZ', + 'BZH', + 'CA', + 'CAB', + 'CAFE', + 'CAL', + 'CALL', + 'CALVINKLEIN', + 'CAM', + 'CAMERA', + 'CAMP', + 'CANCERRESEARCH', + 'CANON', + 'CAPETOWN', + 'CAPITAL', + 'CAPITALONE', + 'CAR', + 'CARAVAN', + 'CARDS', + 'CARE', + 'CAREER', + 'CAREERS', + 'CARS', + 'CASA', + 'CASE', + 'CASEIH', + 'CASH', + 'CASINO', + 'CAT', + 'CATERING', + 'CATHOLIC', + 'CBA', + 'CBN', + 'CBRE', + 'CBS', + 'CC', + 'CD', + 'CENTER', + 'CEO', + 'CERN', + 'CF', + 'CFA', + 'CFD', + 'CG', + 'CH', + 'CHANEL', + 'CHANNEL', + 'CHARITY', + 'CHASE', + 'CHAT', + 'CHEAP', + 'CHINTAI', + 'CHRISTMAS', + 'CHROME', + 'CHURCH', + 'CI', + 'CIPRIANI', + 'CIRCLE', + 'CISCO', + 'CITADEL', + 'CITI', + 'CITIC', + 'CITY', + 'CITYEATS', + 'CK', + 'CL', + 'CLAIMS', + 'CLEANING', + 'CLICK', + 'CLINIC', + 'CLINIQUE', + 'CLOTHING', + 'CLOUD', + 'CLUB', + 'CLUBMED', + 'CM', + 'CN', + 'CO', + 'COACH', + 'CODES', + 'COFFEE', + 'COLLEGE', + 'COLOGNE', + 'COM', + 'COMCAST', + 'COMMBANK', + 'COMMUNITY', + 'COMPANY', + 'COMPARE', + 'COMPUTER', + 'COMSEC', + 'CONDOS', + 'CONSTRUCTION', + 'CONSULTING', + 'CONTACT', + 'CONTRACTORS', + 'COOKING', + 'COOKINGCHANNEL', + 'COOL', + 'COOP', + 'CORSICA', + 'COUNTRY', + 'COUPON', + 'COUPONS', + 'COURSES', + 'CPA', + 'CR', + 'CREDIT', + 'CREDITCARD', + 'CREDITUNION', + 'CRICKET', + 'CROWN', + 'CRS', + 'CRUISE', + 'CRUISES', + 'CSC', + 'CU', + 'CUISINELLA', + 'CV', + 'CW', + 'CX', + 'CY', + 'CYMRU', + 'CYOU', + 'CZ', + 'DABUR', + 'DAD', + 'DANCE', + 'DATA', + 'DATE', + 'DATING', + 'DATSUN', + 'DAY', + 'DCLK', + 'DDS', + 'DE', + 'DEAL', + 'DEALER', + 'DEALS', + 'DEGREE', + 'DELIVERY', + 'DELL', + 'DELOITTE', + 'DELTA', + 'DEMOCRAT', + 'DENTAL', + 'DENTIST', + 'DESI', + 'DESIGN', + 'DEV', + 'DHL', + 'DIAMONDS', + 'DIET', + 'DIGITAL', + 'DIRECT', + 'DIRECTORY', + 'DISCOUNT', + 'DISCOVER', + 'DISH', + 'DIY', + 'DJ', + 'DK', + 'DM', + 'DNP', + 'DO', + 'DOCS', + 'DOCTOR', + 'DOG', + 'DOMAINS', + 'DOT', + 'DOWNLOAD', + 'DRIVE', + 'DTV', + 'DUBAI', + 'DUCK', + 'DUNLOP', + 'DUPONT', + 'DURBAN', + 'DVAG', + 'DVR', + 'DZ', + 'EARTH', + 'EAT', + 'EC', + 'ECO', + 'EDEKA', + 'EDU', + 'EDUCATION', + 'EE', + 'EG', + 'EMAIL', + 'EMERCK', + 'ENERGY', + 'ENGINEER', + 'ENGINEERING', + 'ENTERPRISES', + 'EPSON', + 'EQUIPMENT', + 'ER', + 'ERICSSON', + 'ERNI', + 'ES', + 'ESQ', + 'ESTATE', + 'ET', + 'ETISALAT', + 'EU', + 'EUROVISION', + 'EUS', + 'EVENTS', + 'EXCHANGE', + 'EXPERT', + 'EXPOSED', + 'EXPRESS', + 'EXTRASPACE', + 'FAGE', + 'FAIL', + 'FAIRWINDS', + 'FAITH', + 'FAMILY', + 'FAN', + 'FANS', + 'FARM', + 'FARMERS', + 'FASHION', + 'FAST', + 'FEDEX', + 'FEEDBACK', + 'FERRARI', + 'FERRERO', + 'FI', + 'FIAT', + 'FIDELITY', + 'FIDO', + 'FILM', + 'FINAL', + 'FINANCE', + 'FINANCIAL', + 'FIRE', + 'FIRESTONE', + 'FIRMDALE', + 'FISH', + 'FISHING', + 'FIT', + 'FITNESS', + 'FJ', + 'FK', + 'FLICKR', + 'FLIGHTS', + 'FLIR', + 'FLORIST', + 'FLOWERS', + 'FLY', + 'FM', + 'FO', + 'FOO', + 'FOOD', + 'FOODNETWORK', + 'FOOTBALL', + 'FORD', + 'FOREX', + 'FORSALE', + 'FORUM', + 'FOUNDATION', + 'FOX', + 'FR', + 'FREE', + 'FRESENIUS', + 'FRL', + 'FROGANS', + 'FRONTDOOR', + 'FRONTIER', + 'FTR', + 'FUJITSU', + 'FUJIXEROX', + 'FUN', + 'FUND', + 'FURNITURE', + 'FUTBOL', + 'FYI', + 'GA', + 'GAL', + 'GALLERY', + 'GALLO', + 'GALLUP', + 'GAME', + 'GAMES', + 'GAP', + 'GARDEN', + 'GAY', + 'GB', + 'GBIZ', + 'GD', + 'GDN', + 'GE', + 'GEA', + 'GENT', + 'GENTING', + 'GEORGE', + 'GF', + 'GG', + 'GGEE', + 'GH', + 'GI', + 'GIFT', + 'GIFTS', + 'GIVES', + 'GIVING', + 'GL', + 'GLADE', + 'GLASS', + 'GLE', + 'GLOBAL', + 'GLOBO', + 'GM', + 'GMAIL', + 'GMBH', + 'GMO', + 'GMX', + 'GN', + 'GODADDY', + 'GOLD', + 'GOLDPOINT', + 'GOLF', + 'GOO', + 'GOODYEAR', + 'GOOG', + 'GOOGLE', + 'GOP', + 'GOT', + 'GOV', + 'GP', + 'GQ', + 'GR', + 'GRAINGER', + 'GRAPHICS', + 'GRATIS', + 'GREEN', + 'GRIPE', + 'GROCERY', + 'GROUP', + 'GS', + 'GT', + 'GU', + 'GUARDIAN', + 'GUCCI', + 'GUGE', + 'GUIDE', + 'GUITARS', + 'GURU', + 'GW', + 'GY', + 'HAIR', + 'HAMBURG', + 'HANGOUT', + 'HAUS', + 'HBO', + 'HDFC', + 'HDFCBANK', + 'HEALTH', + 'HEALTHCARE', + 'HELP', + 'HELSINKI', + 'HERE', + 'HERMES', + 'HGTV', + 'HIPHOP', + 'HISAMITSU', + 'HITACHI', + 'HIV', + 'HK', + 'HKT', + 'HM', + 'HN', + 'HOCKEY', + 'HOLDINGS', + 'HOLIDAY', + 'HOMEDEPOT', + 'HOMEGOODS', + 'HOMES', + 'HOMESENSE', + 'HONDA', + 'HORSE', + 'HOSPITAL', + 'HOST', + 'HOSTING', + 'HOT', + 'HOTELES', + 'HOTELS', + 'HOTMAIL', + 'HOUSE', + 'HOW', + 'HR', + 'HSBC', + 'HT', + 'HU', + 'HUGHES', + 'HYATT', + 'HYUNDAI', + 'IBM', + 'ICBC', + 'ICE', + 'ICU', + 'ID', + 'IE', + 'IEEE', + 'IFM', + 'IKANO', + 'IL', + 'IM', + 'IMAMAT', + 'IMDB', + 'IMMO', + 'IMMOBILIEN', + 'IN', + 'INC', + 'INDUSTRIES', + 'INFINITI', + 'INFO', + 'ING', + 'INK', + 'INSTITUTE', + 'INSURANCE', + 'INSURE', + 'INT', + 'INTERNATIONAL', + 'INTUIT', + 'INVESTMENTS', + 'IO', + 'IPIRANGA', + 'IQ', + 'IR', + 'IRISH', + 'IS', + 'ISMAILI', + 'IST', + 'ISTANBUL', + 'IT', + 'ITAU', + 'ITV', + 'IVECO', + 'JAGUAR', + 'JAVA', + 'JCB', + 'JE', + 'JEEP', + 'JETZT', + 'JEWELRY', + 'JIO', + 'JLL', + 'JM', + 'JMP', + 'JNJ', + 'JO', + 'JOBS', + 'JOBURG', + 'JOT', + 'JOY', + 'JP', + 'JPMORGAN', + 'JPRS', + 'JUEGOS', + 'JUNIPER', + 'KAUFEN', + 'KDDI', + 'KE', + 'KERRYHOTELS', + 'KERRYLOGISTICS', + 'KERRYPROPERTIES', + 'KFH', + 'KG', + 'KH', + 'KI', + 'KIA', + 'KIM', + 'KINDER', + 'KINDLE', + 'KITCHEN', + 'KIWI', + 'KM', + 'KN', + 'KOELN', + 'KOMATSU', + 'KOSHER', + 'KP', + 'KPMG', + 'KPN', + 'KR', + 'KRD', + 'KRED', + 'KUOKGROUP', + 'KW', + 'KY', + 'KYOTO', + 'KZ', + 'LA', + 'LACAIXA', + 'LAMBORGHINI', + 'LAMER', + 'LANCASTER', + 'LANCIA', + 'LAND', + 'LANDROVER', + 'LANXESS', + 'LASALLE', + 'LAT', + 'LATINO', + 'LATROBE', + 'LAW', + 'LAWYER', + 'LB', + 'LC', + 'LDS', + 'LEASE', + 'LECLERC', + 'LEFRAK', + 'LEGAL', + 'LEGO', + 'LEXUS', + 'LGBT', + 'LI', + 'LIDL', + 'LIFE', + 'LIFEINSURANCE', + 'LIFESTYLE', + 'LIGHTING', + 'LIKE', + 'LILLY', + 'LIMITED', + 'LIMO', + 'LINCOLN', + 'LINDE', + 'LINK', + 'LIPSY', + 'LIVE', + 'LIVING', + 'LIXIL', + 'LK', + 'LLC', + 'LLP', + 'LOAN', + 'LOANS', + 'LOCKER', + 'LOCUS', + 'LOFT', + 'LOL', + 'LONDON', + 'LOTTE', + 'LOTTO', + 'LOVE', + 'LPL', + 'LPLFINANCIAL', + 'LR', + 'LS', + 'LT', + 'LTD', + 'LTDA', + 'LU', + 'LUNDBECK', + 'LUXE', + 'LUXURY', + 'LV', + 'LY', + 'MA', + 'MACYS', + 'MADRID', + 'MAIF', + 'MAISON', + 'MAKEUP', + 'MAN', + 'MANAGEMENT', + 'MANGO', + 'MAP', + 'MARKET', + 'MARKETING', + 'MARKETS', + 'MARRIOTT', + 'MARSHALLS', + 'MASERATI', + 'MATTEL', + 'MBA', + 'MC', + 'MCKINSEY', + 'MD', + 'ME', + 'MED', + 'MEDIA', + 'MEET', + 'MELBOURNE', + 'MEME', + 'MEMORIAL', + 'MEN', + 'MENU', + 'MERCKMSD', + 'MG', + 'MH', + 'MIAMI', + 'MICROSOFT', + 'MIL', + 'MINI', + 'MINT', + 'MIT', + 'MITSUBISHI', + 'MK', + 'ML', + 'MLB', + 'MLS', + 'MM', + 'MMA', + 'MN', + 'MO', + 'MOBI', + 'MOBILE', + 'MODA', + 'MOE', + 'MOI', + 'MOM', + 'MONASH', + 'MONEY', + 'MONSTER', + 'MORMON', + 'MORTGAGE', + 'MOSCOW', + 'MOTO', + 'MOTORCYCLES', + 'MOV', + 'MOVIE', + 'MP', + 'MQ', + 'MR', + 'MS', + 'MSD', + 'MT', + 'MTN', + 'MTR', + 'MU', + 'MUSEUM', + 'MUTUAL', + 'MV', + 'MW', + 'MX', + 'MY', + 'MZ', + 'NA', + 'NAB', + 'NAGOYA', + 'NAME', + 'NATIONWIDE', + 'NATURA', + 'NAVY', + 'NBA', + 'NC', + 'NE', + 'NEC', + 'NET', + 'NETBANK', + 'NETFLIX', + 'NETWORK', + 'NEUSTAR', + 'NEW', + 'NEWHOLLAND', + 'NEWS', + 'NEXT', + 'NEXTDIRECT', + 'NEXUS', + 'NF', + 'NFL', + 'NG', + 'NGO', + 'NHK', + 'NI', + 'NICO', + 'NIKE', + 'NIKON', + 'NINJA', + 'NISSAN', + 'NISSAY', + 'NL', + 'NO', + 'NOKIA', + 'NORTHWESTERNMUTUAL', + 'NORTON', + 'NOW', + 'NOWRUZ', + 'NOWTV', + 'NP', + 'NR', + 'NRA', + 'NRW', + 'NTT', + 'NU', + 'NYC', + 'NZ', + 'OBI', + 'OBSERVER', + 'OFF', + 'OFFICE', + 'OKINAWA', + 'OLAYAN', + 'OLAYANGROUP', + 'OLDNAVY', + 'OLLO', + 'OM', + 'OMEGA', + 'ONE', + 'ONG', + 'ONL', + 'ONLINE', + 'ONYOURSIDE', + 'OOO', + 'OPEN', + 'ORACLE', + 'ORANGE', + 'ORG', + 'ORGANIC', + 'ORIGINS', + 'OSAKA', + 'OTSUKA', + 'OTT', + 'OVH', + 'PA', + 'PAGE', + 'PANASONIC', + 'PARIS', + 'PARS', + 'PARTNERS', + 'PARTS', + 'PARTY', + 'PASSAGENS', + 'PAY', + 'PCCW', + 'PE', + 'PET', + 'PF', + 'PFIZER', + 'PG', + 'PH', + 'PHARMACY', + 'PHD', + 'PHILIPS', + 'PHONE', + 'PHOTO', + 'PHOTOGRAPHY', + 'PHOTOS', + 'PHYSIO', + 'PICS', + 'PICTET', + 'PICTURES', + 'PID', + 'PIN', + 'PING', + 'PINK', + 'PIONEER', + 'PIZZA', + 'PK', + 'PL', + 'PLACE', + 'PLAY', + 'PLAYSTATION', + 'PLUMBING', + 'PLUS', + 'PM', + 'PN', + 'PNC', + 'POHL', + 'POKER', + 'POLITIE', + 'PORN', + 'POST', + 'PR', + 'PRAMERICA', + 'PRAXI', + 'PRESS', + 'PRIME', + 'PRO', + 'PROD', + 'PRODUCTIONS', + 'PROF', + 'PROGRESSIVE', + 'PROMO', + 'PROPERTIES', + 'PROPERTY', + 'PROTECTION', + 'PRU', + 'PRUDENTIAL', + 'PS', + 'PT', + 'PUB', + 'PW', + 'PWC', + 'PY', + 'QA', + 'QPON', + 'QUEBEC', + 'QUEST', + 'QVC', + 'RACING', + 'RADIO', + 'RAID', + 'RE', + 'READ', + 'REALESTATE', + 'REALTOR', + 'REALTY', + 'RECIPES', + 'RED', + 'REDSTONE', + 'REDUMBRELLA', + 'REHAB', + 'REISE', + 'REISEN', + 'REIT', + 'RELIANCE', + 'REN', + 'RENT', + 'RENTALS', + 'REPAIR', + 'REPORT', + 'REPUBLICAN', + 'REST', + 'RESTAURANT', + 'REVIEW', + 'REVIEWS', + 'REXROTH', + 'RICH', + 'RICHARDLI', + 'RICOH', + 'RIL', + 'RIO', + 'RIP', + 'RMIT', + 'RO', + 'ROCHER', + 'ROCKS', + 'RODEO', + 'ROGERS', + 'ROOM', + 'RS', + 'RSVP', + 'RU', + 'RUGBY', + 'RUHR', + 'RUN', + 'RW', + 'RWE', + 'RYUKYU', + 'SA', + 'SAARLAND', + 'SAFE', + 'SAFETY', + 'SAKURA', + 'SALE', + 'SALON', + 'SAMSCLUB', + 'SAMSUNG', + 'SANDVIK', + 'SANDVIKCOROMANT', + 'SANOFI', + 'SAP', + 'SARL', + 'SAS', + 'SAVE', + 'SAXO', + 'SB', + 'SBI', + 'SBS', + 'SC', + 'SCA', + 'SCB', + 'SCHAEFFLER', + 'SCHMIDT', + 'SCHOLARSHIPS', + 'SCHOOL', + 'SCHULE', + 'SCHWARZ', + 'SCIENCE', + 'SCJOHNSON', + 'SCOT', + 'SD', + 'SE', + 'SEARCH', + 'SEAT', + 'SECURE', + 'SECURITY', + 'SEEK', + 'SELECT', + 'SENER', + 'SERVICES', + 'SES', + 'SEVEN', + 'SEW', + 'SEX', + 'SEXY', + 'SFR', + 'SG', + 'SH', + 'SHANGRILA', + 'SHARP', + 'SHAW', + 'SHELL', + 'SHIA', + 'SHIKSHA', + 'SHOES', + 'SHOP', + 'SHOPPING', + 'SHOUJI', + 'SHOW', + 'SHOWTIME', + 'SI', + 'SILK', + 'SINA', + 'SINGLES', + 'SITE', + 'SJ', + 'SK', + 'SKI', + 'SKIN', + 'SKY', + 'SKYPE', + 'SL', + 'SLING', + 'SM', + 'SMART', + 'SMILE', + 'SN', + 'SNCF', + 'SO', + 'SOCCER', + 'SOCIAL', + 'SOFTBANK', + 'SOFTWARE', + 'SOHU', + 'SOLAR', + 'SOLUTIONS', + 'SONG', + 'SONY', + 'SOY', + 'SPA', + 'SPACE', + 'SPORT', + 'SPOT', + 'SPREADBETTING', + 'SR', + 'SRL', + 'SS', + 'ST', + 'STADA', + 'STAPLES', + 'STAR', + 'STATEBANK', + 'STATEFARM', + 'STC', + 'STCGROUP', + 'STOCKHOLM', + 'STORAGE', + 'STORE', + 'STREAM', + 'STUDIO', + 'STUDY', + 'STYLE', + 'SU', + 'SUCKS', + 'SUPPLIES', + 'SUPPLY', + 'SUPPORT', + 'SURF', + 'SURGERY', + 'SUZUKI', + 'SV', + 'SWATCH', + 'SWIFTCOVER', + 'SWISS', + 'SX', + 'SY', + 'SYDNEY', + 'SYSTEMS', + 'SZ', + 'TAB', + 'TAIPEI', + 'TALK', + 'TAOBAO', + 'TARGET', + 'TATAMOTORS', + 'TATAR', + 'TATTOO', + 'TAX', + 'TAXI', + 'TC', + 'TCI', + 'TD', + 'TDK', + 'TEAM', + 'TECH', + 'TECHNOLOGY', + 'TEL', + 'TEMASEK', + 'TENNIS', + 'TEVA', + 'TF', + 'TG', + 'TH', + 'THD', + 'THEATER', + 'THEATRE', + 'TIAA', + 'TICKETS', + 'TIENDA', + 'TIFFANY', + 'TIPS', + 'TIRES', + 'TIROL', + 'TJ', + 'TJMAXX', + 'TJX', + 'TK', + 'TKMAXX', + 'TL', + 'TM', + 'TMALL', + 'TN', + 'TO', + 'TODAY', + 'TOKYO', + 'TOOLS', + 'TOP', + 'TORAY', + 'TOSHIBA', + 'TOTAL', + 'TOURS', + 'TOWN', + 'TOYOTA', + 'TOYS', + 'TR', + 'TRADE', + 'TRADING', + 'TRAINING', + 'TRAVEL', + 'TRAVELCHANNEL', + 'TRAVELERS', + 'TRAVELERSINSURANCE', + 'TRUST', + 'TRV', + 'TT', + 'TUBE', + 'TUI', + 'TUNES', + 'TUSHU', + 'TV', + 'TVS', + 'TW', + 'TZ', + 'UA', + 'UBANK', + 'UBS', + 'UG', + 'UK', + 'UNICOM', + 'UNIVERSITY', + 'UNO', + 'UOL', + 'UPS', + 'US', + 'UY', + 'UZ', + 'VA', + 'VACATIONS', + 'VANA', + 'VANGUARD', + 'VC', + 'VE', + 'VEGAS', + 'VENTURES', + 'VERISIGN', + 'VERSICHERUNG', + 'VET', + 'VG', + 'VI', + 'VIAJES', + 'VIDEO', + 'VIG', + 'VIKING', + 'VILLAS', + 'VIN', + 'VIP', + 'VIRGIN', + 'VISA', + 'VISION', + 'VIVA', + 'VIVO', + 'VLAANDEREN', + 'VN', + 'VODKA', + 'VOLKSWAGEN', + 'VOLVO', + 'VOTE', + 'VOTING', + 'VOTO', + 'VOYAGE', + 'VU', + 'VUELOS', + 'WALES', + 'WALMART', + 'WALTER', + 'WANG', + 'WANGGOU', + 'WATCH', + 'WATCHES', + 'WEATHER', + 'WEATHERCHANNEL', + 'WEBCAM', + 'WEBER', + 'WEBSITE', + 'WED', + 'WEDDING', + 'WEIBO', + 'WEIR', + 'WF', + 'WHOSWHO', + 'WIEN', + 'WIKI', + 'WILLIAMHILL', + 'WIN', + 'WINDOWS', + 'WINE', + 'WINNERS', + 'WME', + 'WOLTERSKLUWER', + 'WOODSIDE', + 'WORK', + 'WORKS', + 'WORLD', + 'WOW', + 'WS', + 'WTC', + 'WTF', + 'XBOX', + 'XEROX', + 'XFINITY', + 'XIHUAN', + 'XIN', + 'XN--11B4C3D', + 'XN--1CK2E1B', + 'XN--1QQW23A', + 'XN--2SCRJ9C', + 'XN--30RR7Y', + 'XN--3BST00M', + 'XN--3DS443G', + 'XN--3E0B707E', + 'XN--3HCRJ9C', + 'XN--3OQ18VL8PN36A', + 'XN--3PXU8K', + 'XN--42C2D9A', + 'XN--45BR5CYL', + 'XN--45BRJ9C', + 'XN--45Q11C', + 'XN--4GBRIM', + 'XN--54B7FTA0CC', + 'XN--55QW42G', + 'XN--55QX5D', + 'XN--5SU34J936BGSG', + 'XN--5TZM5G', + 'XN--6FRZ82G', + 'XN--6QQ986B3XL', + 'XN--80ADXHKS', + 'XN--80AO21A', + 'XN--80AQECDR1A', + 'XN--80ASEHDB', + 'XN--80ASWG', + 'XN--8Y0A063A', + 'XN--90A3AC', + 'XN--90AE', + 'XN--90AIS', + 'XN--9DBQ2A', + 'XN--9ET52U', + 'XN--9KRT00A', + 'XN--B4W605FERD', + 'XN--BCK1B9A5DRE4C', + 'XN--C1AVG', + 'XN--C2BR7G', + 'XN--CCK2B3B', + 'XN--CCKWCXETD', + 'XN--CG4BKI', + 'XN--CLCHC0EA0B2G2A9GCD', + 'XN--CZR694B', + 'XN--CZRS0T', + 'XN--CZRU2D', + 'XN--D1ACJ3B', + 'XN--D1ALF', + 'XN--E1A4C', + 'XN--ECKVDTC9D', + 'XN--EFVY88H', + 'XN--FCT429K', + 'XN--FHBEI', + 'XN--FIQ228C5HS', + 'XN--FIQ64B', + 'XN--FIQS8S', + 'XN--FIQZ9S', + 'XN--FJQ720A', + 'XN--FLW351E', + 'XN--FPCRJ9C3D', + 'XN--FZC2C9E2C', + 'XN--FZYS8D69UVGM', + 'XN--G2XX48C', + 'XN--GCKR3F0F', + 'XN--GECRJ9C', + 'XN--GK3AT1E', + 'XN--H2BREG3EVE', + 'XN--H2BRJ9C', + 'XN--H2BRJ9C8C', + 'XN--HXT814E', + 'XN--I1B6B1A6A2E', + 'XN--IMR513N', + 'XN--IO0A7I', + 'XN--J1AEF', + 'XN--J1AMH', + 'XN--J6W193G', + 'XN--JLQ480N2RG', + 'XN--JLQ61U9W7B', + 'XN--JVR189M', + 'XN--KCRX77D1X4A', + 'XN--KPRW13D', + 'XN--KPRY57D', + 'XN--KPUT3I', + 'XN--L1ACC', + 'XN--LGBBAT1AD8J', + 'XN--MGB9AWBF', + 'XN--MGBA3A3EJT', + 'XN--MGBA3A4F16A', + 'XN--MGBA7C0BBN0A', + 'XN--MGBAAKC7DVF', + 'XN--MGBAAM7A8H', + 'XN--MGBAB2BD', + 'XN--MGBAH1A3HJKRD', + 'XN--MGBAI9AZGQP6J', + 'XN--MGBAYH7GPA', + 'XN--MGBBH1A', + 'XN--MGBBH1A71E', + 'XN--MGBC0A9AZCG', + 'XN--MGBCA7DZDO', + 'XN--MGBCPQ6GPA1A', + 'XN--MGBERP4A5D4AR', + 'XN--MGBGU82A', + 'XN--MGBI4ECEXP', + 'XN--MGBPL2FH', + 'XN--MGBT3DHD', + 'XN--MGBTX2B', + 'XN--MGBX4CD0AB', + 'XN--MIX891F', + 'XN--MK1BU44C', + 'XN--MXTQ1M', + 'XN--NGBC5AZD', + 'XN--NGBE9E0A', + 'XN--NGBRX', + 'XN--NODE', + 'XN--NQV7F', + 'XN--NQV7FS00EMA', + 'XN--NYQY26A', + 'XN--O3CW4H', + 'XN--OGBPF8FL', + 'XN--OTU796D', + 'XN--P1ACF', + 'XN--P1AI', + 'XN--PGBS0DH', + 'XN--PSSY2U', + 'XN--Q7CE6A', + 'XN--Q9JYB4C', + 'XN--QCKA1PMC', + 'XN--QXA6A', + 'XN--QXAM', + 'XN--RHQV96G', + 'XN--ROVU88B', + 'XN--RVC1E0AM3E', + 'XN--S9BRJ9C', + 'XN--SES554G', + 'XN--T60B56A', + 'XN--TCKWE', + 'XN--TIQ49XQYJ', + 'XN--UNUP4Y', + 'XN--VERMGENSBERATER-CTB', + 'XN--VERMGENSBERATUNG-PWB', + 'XN--VHQUV', + 'XN--VUQ861B', + 'XN--W4R85EL8FHU5DNRA', + 'XN--W4RS40L', + 'XN--WGBH1C', + 'XN--WGBL6A', + 'XN--XHQ521B', + 'XN--XKC2AL3HYE2A', + 'XN--XKC2DL3A5EE0H', + 'XN--Y9A3AQ', + 'XN--YFRO4I67O', + 'XN--YGBI2AMMX', + 'XN--ZFR164B', + 'XXX', + 'XYZ', + 'YACHTS', + 'YAHOO', + 'YAMAXUN', + 'YANDEX', + 'YE', + 'YODOBASHI', + 'YOGA', + 'YOKOHAMA', + 'YOU', + 'YOUTUBE', + 'YT', + 'YUN', + 'ZA', + 'ZAPPOS', + 'ZARA', + 'ZERO', + 'ZIP', + 'ZM', + 'ZONE', + 'ZUERICH', + 'ZW' +]; + -/***/ 6393: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +// Keep as upper-case to make updating from source easier + +module.exports = new Set(internals.tlds.map((tld) => tld.toLowerCase())); -Object.defineProperty(exports, "__esModule", ({ value: true })); -var scope_1 = __nccwpck_require__(4213); -exports.addGlobalEventProcessor = scope_1.addGlobalEventProcessor; -exports.Scope = scope_1.Scope; -var session_1 = __nccwpck_require__(12474); -exports.Session = session_1.Session; -var hub_1 = __nccwpck_require__(53536); -exports.getActiveDomain = hub_1.getActiveDomain; -exports.getCurrentHub = hub_1.getCurrentHub; -exports.getHubFromCarrier = hub_1.getHubFromCarrier; -exports.getMainCarrier = hub_1.getMainCarrier; -exports.Hub = hub_1.Hub; -exports.makeMain = hub_1.makeMain; -exports.setHubOnCarrier = hub_1.setHubOnCarrier; -//# sourceMappingURL=index.js.map /***/ }), -/***/ 4213: +/***/ 74983: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var utils_1 = __nccwpck_require__(1620); -/** - * Holds additional event information. {@link Scope.applyToEvent} will be - * called by the client before an event will be sent. - */ -var Scope = /** @class */ (function () { - function Scope() { - /** Flag if notifiying is happening. */ - this._notifyingListeners = false; - /** Callback for client to receive scope changes. */ - this._scopeListeners = []; - /** Callback list that will be called after {@link applyToEvent}. */ - this._eventProcessors = []; - /** Array of breadcrumbs. */ - this._breadcrumbs = []; - /** User */ - this._user = {}; - /** Tags */ - this._tags = {}; - /** Extra */ - this._extra = {}; - /** Contexts */ - this._contexts = {}; +"use strict"; + + +const Assert = __nccwpck_require__(32718); +const EscapeRegex = __nccwpck_require__(91965); + + +const internals = {}; + + +internals.generate = function () { + + const rfc3986 = {}; + + const hexDigit = '\\dA-Fa-f'; // HEXDIG = DIGIT / "A" / "B" / "C" / "D" / "E" / "F" + const hexDigitOnly = '[' + hexDigit + ']'; + + const unreserved = '\\w-\\.~'; // unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" + const subDelims = '!\\$&\'\\(\\)\\*\\+,;='; // sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "=" + const pctEncoded = '%' + hexDigit; // pct-encoded = "%" HEXDIG HEXDIG + const pchar = unreserved + pctEncoded + subDelims + ':@'; // pchar = unreserved / pct-encoded / sub-delims / ":" / "@" + const pcharOnly = '[' + pchar + ']'; + const decOctect = '(?:0{0,2}\\d|0?[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])'; // dec-octet = DIGIT / %x31-39 DIGIT / "1" 2DIGIT / "2" %x30-34 DIGIT / "25" %x30-35 ; 0-9 / 10-99 / 100-199 / 200-249 / 250-255 + + rfc3986.ipv4address = '(?:' + decOctect + '\\.){3}' + decOctect; // IPv4address = dec-octet "." dec-octet "." dec-octet "." dec-octet + + /* + h16 = 1*4HEXDIG ; 16 bits of address represented in hexadecimal + ls32 = ( h16 ":" h16 ) / IPv4address ; least-significant 32 bits of address + IPv6address = 6( h16 ":" ) ls32 + / "::" 5( h16 ":" ) ls32 + / [ h16 ] "::" 4( h16 ":" ) ls32 + / [ *1( h16 ":" ) h16 ] "::" 3( h16 ":" ) ls32 + / [ *2( h16 ":" ) h16 ] "::" 2( h16 ":" ) ls32 + / [ *3( h16 ":" ) h16 ] "::" h16 ":" ls32 + / [ *4( h16 ":" ) h16 ] "::" ls32 + / [ *5( h16 ":" ) h16 ] "::" h16 + / [ *6( h16 ":" ) h16 ] "::" + */ + + const h16 = hexDigitOnly + '{1,4}'; + const ls32 = '(?:' + h16 + ':' + h16 + '|' + rfc3986.ipv4address + ')'; + const IPv6SixHex = '(?:' + h16 + ':){6}' + ls32; + const IPv6FiveHex = '::(?:' + h16 + ':){5}' + ls32; + const IPv6FourHex = '(?:' + h16 + ')?::(?:' + h16 + ':){4}' + ls32; + const IPv6ThreeHex = '(?:(?:' + h16 + ':){0,1}' + h16 + ')?::(?:' + h16 + ':){3}' + ls32; + const IPv6TwoHex = '(?:(?:' + h16 + ':){0,2}' + h16 + ')?::(?:' + h16 + ':){2}' + ls32; + const IPv6OneHex = '(?:(?:' + h16 + ':){0,3}' + h16 + ')?::' + h16 + ':' + ls32; + const IPv6NoneHex = '(?:(?:' + h16 + ':){0,4}' + h16 + ')?::' + ls32; + const IPv6NoneHex2 = '(?:(?:' + h16 + ':){0,5}' + h16 + ')?::' + h16; + const IPv6NoneHex3 = '(?:(?:' + h16 + ':){0,6}' + h16 + ')?::'; + + rfc3986.ipv4Cidr = '(?:\\d|[1-2]\\d|3[0-2])'; // IPv4 cidr = DIGIT / %x31-32 DIGIT / "3" %x30-32 ; 0-9 / 10-29 / 30-32 + rfc3986.ipv6Cidr = '(?:0{0,2}\\d|0?[1-9]\\d|1[01]\\d|12[0-8])'; // IPv6 cidr = DIGIT / %x31-39 DIGIT / "1" %x0-1 DIGIT / "12" %x0-8; 0-9 / 10-99 / 100-119 / 120-128 + rfc3986.ipv6address = '(?:' + IPv6SixHex + '|' + IPv6FiveHex + '|' + IPv6FourHex + '|' + IPv6ThreeHex + '|' + IPv6TwoHex + '|' + IPv6OneHex + '|' + IPv6NoneHex + '|' + IPv6NoneHex2 + '|' + IPv6NoneHex3 + ')'; + rfc3986.ipvFuture = 'v' + hexDigitOnly + '+\\.[' + unreserved + subDelims + ':]+'; // IPvFuture = "v" 1*HEXDIG "." 1*( unreserved / sub-delims / ":" ) + + rfc3986.scheme = '[a-zA-Z][a-zA-Z\\d+-\\.]*'; // scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) + rfc3986.schemeRegex = new RegExp(rfc3986.scheme); + + const userinfo = '[' + unreserved + pctEncoded + subDelims + ':]*'; // userinfo = *( unreserved / pct-encoded / sub-delims / ":" ) + const IPLiteral = '\\[(?:' + rfc3986.ipv6address + '|' + rfc3986.ipvFuture + ')\\]'; // IP-literal = "[" ( IPv6address / IPvFuture ) "]" + const regName = '[' + unreserved + pctEncoded + subDelims + ']{1,255}'; // reg-name = *( unreserved / pct-encoded / sub-delims ) + const host = '(?:' + IPLiteral + '|' + rfc3986.ipv4address + '|' + regName + ')'; // host = IP-literal / IPv4address / reg-name + const port = '\\d*'; // port = *DIGIT + const authority = '(?:' + userinfo + '@)?' + host + '(?::' + port + ')?'; // authority = [ userinfo "@" ] host [ ":" port ] + const authorityCapture = '(?:' + userinfo + '@)?(' + host + ')(?::' + port + ')?'; + + /* + segment = *pchar + segment-nz = 1*pchar + path = path-abempty ; begins with "/" '|' is empty + / path-absolute ; begins with "/" but not "//" + / path-noscheme ; begins with a non-colon segment + / path-rootless ; begins with a segment + / path-empty ; zero characters + path-abempty = *( "/" segment ) + path-absolute = "/" [ segment-nz *( "/" segment ) ] + path-rootless = segment-nz *( "/" segment ) + */ + + const segment = pcharOnly + '*'; + const segmentNz = pcharOnly + '+'; + const segmentNzNc = '[' + unreserved + pctEncoded + subDelims + '@' + ']+'; + const pathEmpty = ''; + const pathAbEmpty = '(?:\\/' + segment + ')*'; + const pathAbsolute = '\\/(?:' + segmentNz + pathAbEmpty + ')?'; + const pathRootless = segmentNz + pathAbEmpty; + const pathNoScheme = segmentNzNc + pathAbEmpty; + const pathAbNoAuthority = '(?:\\/\\/\\/' + segment + pathAbEmpty + ')'; // Used by file:/// + + // hier-part = "//" authority path + + rfc3986.hierPart = '(?:' + '(?:\\/\\/' + authority + pathAbEmpty + ')' + '|' + pathAbsolute + '|' + pathRootless + '|' + pathAbNoAuthority + ')'; + rfc3986.hierPartCapture = '(?:' + '(?:\\/\\/' + authorityCapture + pathAbEmpty + ')' + '|' + pathAbsolute + '|' + pathRootless + ')'; + + // relative-part = "//" authority path-abempty / path-absolute / path-noscheme / path-empty + + rfc3986.relativeRef = '(?:' + '(?:\\/\\/' + authority + pathAbEmpty + ')' + '|' + pathAbsolute + '|' + pathNoScheme + '|' + pathEmpty + ')'; + rfc3986.relativeRefCapture = '(?:' + '(?:\\/\\/' + authorityCapture + pathAbEmpty + ')' + '|' + pathAbsolute + '|' + pathNoScheme + '|' + pathEmpty + ')'; + + // query = *( pchar / "/" / "?" ) + // query = *( pchar / "[" / "]" / "/" / "?" ) + + rfc3986.query = '[' + pchar + '\\/\\?]*(?=#|$)'; //Finish matching either at the fragment part '|' end of the line. + rfc3986.queryWithSquareBrackets = '[' + pchar + '\\[\\]\\/\\?]*(?=#|$)'; + + // fragment = *( pchar / "/" / "?" ) + + rfc3986.fragment = '[' + pchar + '\\/\\?]*'; + + return rfc3986; +}; + +internals.rfc3986 = internals.generate(); + + +exports.ip = { + v4Cidr: internals.rfc3986.ipv4Cidr, + v6Cidr: internals.rfc3986.ipv6Cidr, + ipv4: internals.rfc3986.ipv4address, + ipv6: internals.rfc3986.ipv6address, + ipvfuture: internals.rfc3986.ipvFuture +}; + + +internals.createRegex = function (options) { + + const rfc = internals.rfc3986; + + // Construct expression + + const query = options.allowQuerySquareBrackets ? rfc.queryWithSquareBrackets : rfc.query; + const suffix = '(?:\\?' + query + ')?' + '(?:#' + rfc.fragment + ')?'; + + // relative-ref = relative-part [ "?" query ] [ "#" fragment ] + + const relative = options.domain ? rfc.relativeRefCapture : rfc.relativeRef; + + if (options.relativeOnly) { + return internals.wrap(relative + suffix); } - /** - * Inherit values from the parent scope. - * @param scope to clone. - */ - Scope.clone = function (scope) { - var newScope = new Scope(); - if (scope) { - newScope._breadcrumbs = tslib_1.__spread(scope._breadcrumbs); - newScope._tags = tslib_1.__assign({}, scope._tags); - newScope._extra = tslib_1.__assign({}, scope._extra); - newScope._contexts = tslib_1.__assign({}, scope._contexts); - newScope._user = scope._user; - newScope._level = scope._level; - newScope._span = scope._span; - newScope._session = scope._session; - newScope._transactionName = scope._transactionName; - newScope._fingerprint = scope._fingerprint; - newScope._eventProcessors = tslib_1.__spread(scope._eventProcessors); - } - return newScope; - }; - /** - * Add internal on change listener. Used for sub SDKs that need to store the scope. - * @hidden - */ - Scope.prototype.addScopeListener = function (callback) { - this._scopeListeners.push(callback); - }; - /** - * @inheritDoc - */ - Scope.prototype.addEventProcessor = function (callback) { - this._eventProcessors.push(callback); - return this; - }; - /** - * @inheritDoc - */ - Scope.prototype.setUser = function (user) { - this._user = user || {}; - if (this._session) { - this._session.update({ user: user }); - } - this._notifyScopeListeners(); - return this; - }; - /** - * @inheritDoc - */ - Scope.prototype.getUser = function () { - return this._user; - }; - /** - * @inheritDoc - */ - Scope.prototype.setTags = function (tags) { - this._tags = tslib_1.__assign(tslib_1.__assign({}, this._tags), tags); - this._notifyScopeListeners(); - return this; - }; - /** - * @inheritDoc - */ - Scope.prototype.setTag = function (key, value) { - var _a; - this._tags = tslib_1.__assign(tslib_1.__assign({}, this._tags), (_a = {}, _a[key] = value, _a)); - this._notifyScopeListeners(); - return this; - }; - /** - * @inheritDoc - */ - Scope.prototype.setExtras = function (extras) { - this._extra = tslib_1.__assign(tslib_1.__assign({}, this._extra), extras); - this._notifyScopeListeners(); - return this; - }; - /** - * @inheritDoc - */ - Scope.prototype.setExtra = function (key, extra) { - var _a; - this._extra = tslib_1.__assign(tslib_1.__assign({}, this._extra), (_a = {}, _a[key] = extra, _a)); - this._notifyScopeListeners(); - return this; - }; - /** - * @inheritDoc - */ - Scope.prototype.setFingerprint = function (fingerprint) { - this._fingerprint = fingerprint; - this._notifyScopeListeners(); - return this; - }; - /** - * @inheritDoc - */ - Scope.prototype.setLevel = function (level) { - this._level = level; - this._notifyScopeListeners(); - return this; - }; - /** - * @inheritDoc - */ - Scope.prototype.setTransactionName = function (name) { - this._transactionName = name; - this._notifyScopeListeners(); - return this; - }; - /** - * Can be removed in major version. - * @deprecated in favor of {@link this.setTransactionName} - */ - Scope.prototype.setTransaction = function (name) { - return this.setTransactionName(name); - }; - /** - * @inheritDoc - */ - Scope.prototype.setContext = function (key, context) { - var _a; - if (context === null) { - // eslint-disable-next-line @typescript-eslint/no-dynamic-delete - delete this._contexts[key]; - } - else { - this._contexts = tslib_1.__assign(tslib_1.__assign({}, this._contexts), (_a = {}, _a[key] = context, _a)); - } - this._notifyScopeListeners(); - return this; - }; - /** - * @inheritDoc - */ - Scope.prototype.setSpan = function (span) { - this._span = span; - this._notifyScopeListeners(); - return this; - }; - /** - * @inheritDoc - */ - Scope.prototype.getSpan = function () { - return this._span; - }; - /** - * @inheritDoc - */ - Scope.prototype.getTransaction = function () { - var _a, _b, _c, _d; - // often, this span will be a transaction, but it's not guaranteed to be - var span = this.getSpan(); - // try it the new way first - if ((_a = span) === null || _a === void 0 ? void 0 : _a.transaction) { - return (_b = span) === null || _b === void 0 ? void 0 : _b.transaction; - } - // fallback to the old way (known bug: this only finds transactions with sampled = true) - if ((_d = (_c = span) === null || _c === void 0 ? void 0 : _c.spanRecorder) === null || _d === void 0 ? void 0 : _d.spans[0]) { - return span.spanRecorder.spans[0]; - } - // neither way found a transaction - return undefined; - }; - /** - * @inheritDoc - */ - Scope.prototype.setSession = function (session) { - if (!session) { - delete this._session; - } - else { - this._session = session; + + // Custom schemes + + let customScheme = ''; + if (options.scheme) { + Assert(options.scheme instanceof RegExp || typeof options.scheme === 'string' || Array.isArray(options.scheme), 'scheme must be a RegExp, String, or Array'); + + const schemes = [].concat(options.scheme); + Assert(schemes.length >= 1, 'scheme must have at least 1 scheme specified'); + + // Flatten the array into a string to be used to match the schemes + + const selections = []; + for (let i = 0; i < schemes.length; ++i) { + const scheme = schemes[i]; + Assert(scheme instanceof RegExp || typeof scheme === 'string', 'scheme at position ' + i + ' must be a RegExp or String'); + + if (scheme instanceof RegExp) { + selections.push(scheme.source.toString()); + } + else { + Assert(rfc.schemeRegex.test(scheme), 'scheme at position ' + i + ' must be a valid scheme'); + selections.push(EscapeRegex(scheme)); + } } - this._notifyScopeListeners(); - return this; - }; - /** - * @inheritDoc - */ - Scope.prototype.getSession = function () { - return this._session; + + customScheme = selections.join('|'); + } + + // URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ] + + const scheme = customScheme ? '(?:' + customScheme + ')' : rfc.scheme; + const absolute = '(?:' + scheme + ':' + (options.domain ? rfc.hierPartCapture : rfc.hierPart) + ')'; + const prefix = options.allowRelative ? '(?:' + absolute + '|' + relative + ')' : absolute; + return internals.wrap(prefix + suffix, customScheme); +}; + + +internals.wrap = function (raw, scheme) { + + raw = `(?=.)(?!https?\:/(?:$|[^/]))(?!https?\:///)(?!https?\:[^/])${raw}`; // Require at least one character and explicitly forbid 'http:/' or HTTP with empty domain + + return { + raw, + regex: new RegExp(`^${raw}$`), + scheme }; - /** - * @inheritDoc - */ - Scope.prototype.update = function (captureContext) { - if (!captureContext) { - return this; - } - if (typeof captureContext === 'function') { - var updatedScope = captureContext(this); - return updatedScope instanceof Scope ? updatedScope : this; +}; + + +internals.uriRegex = internals.createRegex({}); + + +exports.regex = function (options = {}) { + + if (options.scheme || + options.allowRelative || + options.relativeOnly || + options.allowQuerySquareBrackets || + options.domain) { + + return internals.createRegex(options); + } + + return internals.uriRegex; +}; + + +/***/ }), + +/***/ 34379: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +const internals = { + operators: ['!', '^', '*', '/', '%', '+', '-', '<', '<=', '>', '>=', '==', '!=', '&&', '||', '??'], + operatorCharacters: ['!', '^', '*', '/', '%', '+', '-', '<', '=', '>', '&', '|', '?'], + operatorsOrder: [['^'], ['*', '/', '%'], ['+', '-'], ['<', '<=', '>', '>='], ['==', '!='], ['&&'], ['||', '??']], + operatorsPrefix: ['!', 'n'], + + literals: { + '"': '"', + '`': '`', + '\'': '\'', + '[': ']' + }, + + numberRx: /^(?:[0-9]*\.?[0-9]*){1}$/, + tokenRx: /^[\w\$\#\.\@\:\{\}]+$/, + + symbol: Symbol('formula'), + settings: Symbol('settings') +}; + + +exports.Parser = class { + + constructor(string, options = {}) { + + if (!options[internals.settings] && + options.constants) { + + for (const constant in options.constants) { + const value = options.constants[constant]; + if (value !== null && + !['boolean', 'number', 'string'].includes(typeof value)) { + + throw new Error(`Formula constant ${constant} contains invalid ${typeof value} value type`); + } + } } - if (captureContext instanceof Scope) { - this._tags = tslib_1.__assign(tslib_1.__assign({}, this._tags), captureContext._tags); - this._extra = tslib_1.__assign(tslib_1.__assign({}, this._extra), captureContext._extra); - this._contexts = tslib_1.__assign(tslib_1.__assign({}, this._contexts), captureContext._contexts); - if (captureContext._user && Object.keys(captureContext._user).length) { - this._user = captureContext._user; + + this.settings = options[internals.settings] ? options : Object.assign({ [internals.settings]: true, constants: {}, functions: {} }, options); + this.single = null; + + this._parts = null; + this._parse(string); + } + + _parse(string) { + + let parts = []; + let current = ''; + let parenthesis = 0; + let literal = false; + + const flush = (inner) => { + + if (parenthesis) { + throw new Error('Formula missing closing parenthesis'); + } + + const last = parts.length ? parts[parts.length - 1] : null; + + if (!literal && + !current && + !inner) { + + return; + } + + if (last && + last.type === 'reference' && + inner === ')') { // Function + + last.type = 'function'; + last.value = this._subFormula(current, last.value); + current = ''; + return; + } + + if (inner === ')') { // Segment + const sub = new exports.Parser(current, this.settings); + parts.push({ type: 'segment', value: sub }); + } + else if (literal) { + if (literal === ']') { // Reference + parts.push({ type: 'reference', value: current }); + current = ''; + return; + } + + parts.push({ type: 'literal', value: current }); // Literal + } + else if (internals.operatorCharacters.includes(current)) { // Operator + if (last && + last.type === 'operator' && + internals.operators.includes(last.value + current)) { // 2 characters operator + + last.value += current; + } + else { + parts.push({ type: 'operator', value: current }); + } + } + else if (current.match(internals.numberRx)) { // Number + parts.push({ type: 'constant', value: parseFloat(current) }); + } + else if (this.settings.constants[current] !== undefined) { // Constant + parts.push({ type: 'constant', value: this.settings.constants[current] }); + } + else { // Reference + if (!current.match(internals.tokenRx)) { + throw new Error(`Formula contains invalid token: ${current}`); + } + + parts.push({ type: 'reference', value: current }); + } + + current = ''; + }; + + for (const c of string) { + if (literal) { + if (c === literal) { + flush(); + literal = false; + } + else { + current += c; + } + } + else if (parenthesis) { + if (c === '(') { + current += c; + ++parenthesis; + } + else if (c === ')') { + --parenthesis; + if (!parenthesis) { + flush(c); + } + else { + current += c; + } + } + else { + current += c; + } } - if (captureContext._level) { - this._level = captureContext._level; + else if (c in internals.literals) { + literal = internals.literals[c]; } - if (captureContext._fingerprint) { - this._fingerprint = captureContext._fingerprint; + else if (c === '(') { + flush(); + ++parenthesis; } - } - else if (utils_1.isPlainObject(captureContext)) { - // eslint-disable-next-line no-param-reassign - captureContext = captureContext; - this._tags = tslib_1.__assign(tslib_1.__assign({}, this._tags), captureContext.tags); - this._extra = tslib_1.__assign(tslib_1.__assign({}, this._extra), captureContext.extra); - this._contexts = tslib_1.__assign(tslib_1.__assign({}, this._contexts), captureContext.contexts); - if (captureContext.user) { - this._user = captureContext.user; + else if (internals.operatorCharacters.includes(c)) { + flush(); + current = c; + flush(); } - if (captureContext.level) { - this._level = captureContext.level; + else if (c !== ' ') { + current += c; } - if (captureContext.fingerprint) { - this._fingerprint = captureContext.fingerprint; + else { + flush(); } } - return this; - }; - /** - * @inheritDoc - */ - Scope.prototype.clear = function () { - this._breadcrumbs = []; - this._tags = {}; - this._extra = {}; - this._user = {}; - this._contexts = {}; - this._level = undefined; - this._transactionName = undefined; - this._fingerprint = undefined; - this._span = undefined; - this._session = undefined; - this._notifyScopeListeners(); - return this; - }; - /** - * @inheritDoc - */ - Scope.prototype.addBreadcrumb = function (breadcrumb, maxBreadcrumbs) { - var mergedBreadcrumb = tslib_1.__assign({ timestamp: utils_1.dateTimestampInSeconds() }, breadcrumb); - this._breadcrumbs = - maxBreadcrumbs !== undefined && maxBreadcrumbs >= 0 - ? tslib_1.__spread(this._breadcrumbs, [mergedBreadcrumb]).slice(-maxBreadcrumbs) - : tslib_1.__spread(this._breadcrumbs, [mergedBreadcrumb]); - this._notifyScopeListeners(); - return this; - }; - /** - * @inheritDoc - */ - Scope.prototype.clearBreadcrumbs = function () { - this._breadcrumbs = []; - this._notifyScopeListeners(); - return this; - }; - /** - * Applies the current context and fingerprint to the event. - * Note that breadcrumbs will be added by the client. - * Also if the event has already breadcrumbs on it, we do not merge them. - * @param event Event - * @param hint May contain additional informartion about the original exception. - * @hidden - */ - Scope.prototype.applyToEvent = function (event, hint) { - var _a; - if (this._extra && Object.keys(this._extra).length) { - event.extra = tslib_1.__assign(tslib_1.__assign({}, this._extra), event.extra); - } - if (this._tags && Object.keys(this._tags).length) { - event.tags = tslib_1.__assign(tslib_1.__assign({}, this._tags), event.tags); - } - if (this._user && Object.keys(this._user).length) { - event.user = tslib_1.__assign(tslib_1.__assign({}, this._user), event.user); + + flush(); + + // Replace prefix - to internal negative operator + + parts = parts.map((part, i) => { + + if (part.type !== 'operator' || + part.value !== '-' || + i && parts[i - 1].type !== 'operator') { + + return part; + } + + return { type: 'operator', value: 'n' }; + }); + + // Validate tokens order + + let operator = false; + for (const part of parts) { + if (part.type === 'operator') { + if (internals.operatorsPrefix.includes(part.value)) { + continue; + } + + if (!operator) { + throw new Error('Formula contains an operator in invalid position'); + } + + if (!internals.operators.includes(part.value)) { + throw new Error(`Formula contains an unknown operator ${part.value}`); + } + } + else if (operator) { + throw new Error('Formula missing expected operator'); + } + + operator = !operator; } - if (this._contexts && Object.keys(this._contexts).length) { - event.contexts = tslib_1.__assign(tslib_1.__assign({}, this._contexts), event.contexts); + + if (!operator) { + throw new Error('Formula contains invalid trailing operator'); } - if (this._level) { - event.level = this._level; + + // Identify single part + + if (parts.length === 1 && + ['reference', 'literal', 'constant'].includes(parts[0].type)) { + + this.single = { type: parts[0].type === 'reference' ? 'reference' : 'value', value: parts[0].value }; } - if (this._transactionName) { - event.transaction = this._transactionName; + + // Process parts + + this._parts = parts.map((part) => { + + // Operators + + if (part.type === 'operator') { + return internals.operatorsPrefix.includes(part.value) ? part : part.value; + } + + // Literals, constants, segments + + if (part.type !== 'reference') { + return part.value; + } + + // References + + if (this.settings.tokenRx && + !this.settings.tokenRx.test(part.value)) { + + throw new Error(`Formula contains invalid reference ${part.value}`); + } + + if (this.settings.reference) { + return this.settings.reference(part.value); + } + + return internals.reference(part.value); + }); + } + + _subFormula(string, name) { + + const method = this.settings.functions[name]; + if (typeof method !== 'function') { + throw new Error(`Formula contains unknown function ${name}`); } - // We want to set the trace context for normal events only if there isn't already - // a trace context on the event. There is a product feature in place where we link - // errors with transaction and it relys on that. - if (this._span) { - event.contexts = tslib_1.__assign({ trace: this._span.getTraceContext() }, event.contexts); - var transactionName = (_a = this._span.transaction) === null || _a === void 0 ? void 0 : _a.name; - if (transactionName) { - event.tags = tslib_1.__assign({ transaction: transactionName }, event.tags); + + let args = []; + if (string) { + let current = ''; + let parenthesis = 0; + let literal = false; + + const flush = () => { + + if (!current) { + throw new Error(`Formula contains function ${name} with invalid arguments ${string}`); + } + + args.push(current); + current = ''; + }; + + for (let i = 0; i < string.length; ++i) { + const c = string[i]; + if (literal) { + current += c; + if (c === literal) { + literal = false; + } + } + else if (c in internals.literals && + !parenthesis) { + + current += c; + literal = internals.literals[c]; + } + else if (c === ',' && + !parenthesis) { + + flush(); + } + else { + current += c; + if (c === '(') { + ++parenthesis; + } + else if (c === ')') { + --parenthesis; + } + } } + + flush(); } - this._applyFingerprint(event); - event.breadcrumbs = tslib_1.__spread((event.breadcrumbs || []), this._breadcrumbs); - event.breadcrumbs = event.breadcrumbs.length > 0 ? event.breadcrumbs : undefined; - return this._notifyEventProcessors(tslib_1.__spread(getGlobalEventProcessors(), this._eventProcessors), event, hint); - }; - /** - * This will be called after {@link applyToEvent} is finished. - */ - Scope.prototype._notifyEventProcessors = function (processors, event, hint, index) { - var _this = this; - if (index === void 0) { index = 0; } - return new utils_1.SyncPromise(function (resolve, reject) { - var processor = processors[index]; - if (event === null || typeof processor !== 'function') { - resolve(event); + + args = args.map((arg) => new exports.Parser(arg, this.settings)); + + return function (context) { + + const innerValues = []; + for (const arg of args) { + innerValues.push(arg.evaluate(context)); } - else { - var result = processor(tslib_1.__assign({}, event), hint); - if (utils_1.isThenable(result)) { - result - .then(function (final) { return _this._notifyEventProcessors(processors, final, hint, index + 1).then(resolve); }) - .then(null, reject); + + return method.call(context, ...innerValues); + }; + } + + evaluate(context) { + + const parts = this._parts.slice(); + + // Prefix operators + + for (let i = parts.length - 2; i >= 0; --i) { + const part = parts[i]; + if (part && + part.type === 'operator') { + + const current = parts[i + 1]; + parts.splice(i + 1, 1); + const value = internals.evaluate(current, context); + parts[i] = internals.single(part.value, value); + } + } + + // Left-right operators + + internals.operatorsOrder.forEach((set) => { + + for (let i = 1; i < parts.length - 1;) { + if (set.includes(parts[i])) { + const operator = parts[i]; + const left = internals.evaluate(parts[i - 1], context); + const right = internals.evaluate(parts[i + 1], context); + + parts.splice(i, 2); + const result = internals.calculate(operator, left, right); + parts[i - 1] = result === 0 ? 0 : result; // Convert -0 } else { - _this._notifyEventProcessors(processors, result, hint, index + 1) - .then(resolve) - .then(null, reject); + i += 2; } } }); + + return internals.evaluate(parts[0], context); + } +}; + + +exports.Parser.prototype[internals.symbol] = true; + + +internals.reference = function (name) { + + return function (context) { + + return context && context[name] !== undefined ? context[name] : null; }; - /** - * This will be called on every set call. - */ - Scope.prototype._notifyScopeListeners = function () { - var _this = this; - // We need this check for this._notifyingListeners to be able to work on scope during updates - // If this check is not here we'll produce endless recursion when something is done with the scope - // during the callback. - if (!this._notifyingListeners) { - this._notifyingListeners = true; - this._scopeListeners.forEach(function (callback) { - callback(_this); - }); - this._notifyingListeners = false; - } - }; - /** - * Applies fingerprint from the scope to the event if there's one, - * uses message if there's one instead or get rid of empty fingerprint - */ - Scope.prototype._applyFingerprint = function (event) { - // Make sure it's an array first and we actually have something in place - event.fingerprint = event.fingerprint - ? Array.isArray(event.fingerprint) - ? event.fingerprint - : [event.fingerprint] - : []; - // If we have something on the scope, then merge it with event - if (this._fingerprint) { - event.fingerprint = event.fingerprint.concat(this._fingerprint); +}; + + +internals.evaluate = function (part, context) { + + if (part === null) { + return null; + } + + if (typeof part === 'function') { + return part(context); + } + + if (part[internals.symbol]) { + return part.evaluate(context); + } + + return part; +}; + + +internals.single = function (operator, value) { + + if (operator === '!') { + return value ? false : true; + } + + // operator === 'n' + + const negative = -value; + if (negative === 0) { // Override -0 + return 0; + } + + return negative; +}; + + +internals.calculate = function (operator, left, right) { + + if (operator === '??') { + return internals.exists(left) ? left : right; + } + + if (typeof left === 'string' || + typeof right === 'string') { + + if (operator === '+') { + left = internals.exists(left) ? left : ''; + right = internals.exists(right) ? right : ''; + return left + right; } - // If we have no data at all, remove empty array default - if (event.fingerprint && !event.fingerprint.length) { - delete event.fingerprint; + } + else { + switch (operator) { + case '^': return Math.pow(left, right); + case '*': return left * right; + case '/': return left / right; + case '%': return left % right; + case '+': return left + right; + case '-': return left - right; } + } + + switch (operator) { + case '<': return left < right; + case '<=': return left <= right; + case '>': return left > right; + case '>=': return left >= right; + case '==': return left === right; + case '!=': return left !== right; + case '&&': return left && right; + case '||': return left || right; + } + + return null; +}; + + +internals.exists = function (value) { + + return value !== null && value !== undefined; +}; + + +/***/ }), + +/***/ 75604: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +const internals = {}; + + +exports.location = function (depth = 0) { + + const orig = Error.prepareStackTrace; + Error.prepareStackTrace = (ignore, stack) => stack; + + const capture = {}; + Error.captureStackTrace(capture, this); + const line = capture.stack[depth + 1]; + + Error.prepareStackTrace = orig; + + return { + filename: line.getFileName(), + line: line.getLineNumber() }; - return Scope; -}()); -exports.Scope = Scope; +}; + + +/***/ }), + +/***/ 83633: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; +/*! + * accepts + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + + + +/** + * Module dependencies. + * @private + */ + +var Negotiator = __nccwpck_require__(95385) +var mime = __nccwpck_require__(43583) + +/** + * Module exports. + * @public + */ + +module.exports = Accepts + +/** + * Create a new Accepts object for the given req. + * + * @param {object} req + * @public + */ + +function Accepts (req) { + if (!(this instanceof Accepts)) { + return new Accepts(req) + } + + this.headers = req.headers + this.negotiator = new Negotiator(req) +} + +/** + * 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", the extension name + * such as "json" 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 + * this.types('html'); + * // => "html" + * + * // Accept: text/*, application/json + * this.types('html'); + * // => "html" + * this.types('text/html'); + * // => "text/html" + * this.types('json', 'text'); + * // => "json" + * this.types('application/json'); + * // => "application/json" + * + * // Accept: text/*, application/json + * this.types('image/png'); + * this.types('png'); + * // => undefined + * + * // Accept: text/*;q=.5, application/json + * this.types(['html', 'json']); + * this.types('html', 'json'); + * // => "json" + * + * @param {String|Array} types... + * @return {String|Array|Boolean} + * @public + */ + +Accepts.prototype.type = +Accepts.prototype.types = function (types_) { + var types = types_ + + // support flattened arguments + if (types && !Array.isArray(types)) { + types = new Array(arguments.length) + for (var i = 0; i < types.length; i++) { + types[i] = arguments[i] + } + } + + // no types, return all requested types + if (!types || types.length === 0) { + return this.negotiator.mediaTypes() + } + + // no accept header, return first given type + if (!this.headers.accept) { + return types[0] + } + + var mimes = types.map(extToMime) + var accepts = this.negotiator.mediaTypes(mimes.filter(validMime)) + var first = accepts[0] + + return first + ? types[mimes.indexOf(first)] + : false +} + +/** + * Return accepted encodings or best fit based on `encodings`. + * + * Given `Accept-Encoding: gzip, deflate` + * an array sorted by quality is returned: + * + * ['gzip', 'deflate'] + * + * @param {String|Array} encodings... + * @return {String|Array} + * @public + */ + +Accepts.prototype.encoding = +Accepts.prototype.encodings = function (encodings_) { + var encodings = encodings_ + + // support flattened arguments + if (encodings && !Array.isArray(encodings)) { + encodings = new Array(arguments.length) + for (var i = 0; i < encodings.length; i++) { + encodings[i] = arguments[i] + } + } + + // no encodings, return all requested encodings + if (!encodings || encodings.length === 0) { + return this.negotiator.encodings() + } + + return this.negotiator.encodings(encodings)[0] || false +} + +/** + * Return accepted charsets or best fit based on `charsets`. + * + * Given `Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5` + * an array sorted by quality is returned: + * + * ['utf-8', 'utf-7', 'iso-8859-1'] + * + * @param {String|Array} charsets... + * @return {String|Array} + * @public + */ + +Accepts.prototype.charset = +Accepts.prototype.charsets = function (charsets_) { + var charsets = charsets_ + + // support flattened arguments + if (charsets && !Array.isArray(charsets)) { + charsets = new Array(arguments.length) + for (var i = 0; i < charsets.length; i++) { + charsets[i] = arguments[i] + } + } + + // no charsets, return all requested charsets + if (!charsets || charsets.length === 0) { + return this.negotiator.charsets() + } + + return this.negotiator.charsets(charsets)[0] || false +} + +/** + * Return accepted languages or best fit based on `langs`. + * + * Given `Accept-Language: en;q=0.8, es, pt` + * an array sorted by quality is returned: + * + * ['es', 'pt', 'en'] + * + * @param {String|Array} langs... + * @return {Array|String} + * @public + */ + +Accepts.prototype.lang = +Accepts.prototype.langs = +Accepts.prototype.language = +Accepts.prototype.languages = function (languages_) { + var languages = languages_ + + // support flattened arguments + if (languages && !Array.isArray(languages)) { + languages = new Array(arguments.length) + for (var i = 0; i < languages.length; i++) { + languages[i] = arguments[i] + } + } + + // no languages, return all requested languages + if (!languages || languages.length === 0) { + return this.negotiator.languages() + } + + return this.negotiator.languages(languages)[0] || false +} + /** - * Retruns the global event processors. + * Convert extnames to mime. + * + * @param {String} type + * @return {String} + * @private */ -function getGlobalEventProcessors() { - /* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access */ - var global = utils_1.getGlobalObject(); - global.__SENTRY__ = global.__SENTRY__ || {}; - global.__SENTRY__.globalEventProcessors = global.__SENTRY__.globalEventProcessors || []; - return global.__SENTRY__.globalEventProcessors; - /* eslint-enable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access */ + +function extToMime (type) { + return type.indexOf('/') === -1 + ? mime.lookup(type) + : type } + /** - * Add a EventProcessor to be kept globally. - * @param callback EventProcessor to add + * Check if mime is valid. + * + * @param {String} type + * @return {String} + * @private */ -function addGlobalEventProcessor(callback) { - getGlobalEventProcessors().push(callback); + +function validMime (type) { + return typeof type === 'string' } -exports.addGlobalEventProcessor = addGlobalEventProcessor; -//# sourceMappingURL=scope.js.map + /***/ }), -/***/ 12474: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 49690: +/***/ (function(module, __unused_webpack_exports, __nccwpck_require__) { -Object.defineProperty(exports, "__esModule", ({ value: true })); -var types_1 = __nccwpck_require__(83789); -var utils_1 = __nccwpck_require__(1620); -/** - * @inheritdoc - */ -var Session = /** @class */ (function () { - function Session(context) { - this.errors = 0; - this.sid = utils_1.uuid4(); - this.timestamp = Date.now(); - this.started = Date.now(); - this.duration = 0; - this.status = types_1.SessionStatus.Ok; - if (context) { - this.update(context); - } - } - /** JSDoc */ - // eslint-disable-next-line complexity - Session.prototype.update = function (context) { - if (context === void 0) { context = {}; } - if (context.user) { - if (context.user.ip_address) { - this.ipAddress = context.user.ip_address; +"use strict"; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +const events_1 = __nccwpck_require__(82361); +const debug_1 = __importDefault(__nccwpck_require__(38237)); +const promisify_1 = __importDefault(__nccwpck_require__(66570)); +const debug = debug_1.default('agent-base'); +function isAgent(v) { + return Boolean(v) && typeof v.addRequest === 'function'; +} +function isSecureEndpoint() { + const { stack } = new Error(); + if (typeof stack !== 'string') + return false; + return stack.split('\n').some(l => l.indexOf('(https.js:') !== -1 || l.indexOf('node:https:') !== -1); +} +function createAgent(callback, opts) { + return new createAgent.Agent(callback, opts); +} +(function (createAgent) { + /** + * Base `http.Agent` implementation. + * No pooling/keep-alive is implemented by default. + * + * @param {Function} callback + * @api public + */ + class Agent extends events_1.EventEmitter { + constructor(callback, _opts) { + super(); + let opts = _opts; + if (typeof callback === 'function') { + this.callback = callback; } - if (!context.did) { - this.did = context.user.id || context.user.email || context.user.username; + else if (callback) { + opts = callback; } + // Timeout for the socket to be returned from the callback + this.timeout = null; + if (opts && typeof opts.timeout === 'number') { + this.timeout = opts.timeout; + } + // These aren't actually used by `agent-base`, but are required + // for the TypeScript definition files in `@types/node` :/ + this.maxFreeSockets = 1; + this.maxSockets = 1; + this.maxTotalSockets = Infinity; + this.sockets = {}; + this.freeSockets = {}; + this.requests = {}; + this.options = {}; } - this.timestamp = context.timestamp || Date.now(); - if (context.sid) { - // Good enough uuid validation. — Kamil - this.sid = context.sid.length === 32 ? context.sid : utils_1.uuid4(); - } - if (context.did) { - this.did = "" + context.did; - } - if (typeof context.started === 'number') { - this.started = context.started; - } - if (typeof context.duration === 'number') { - this.duration = context.duration; - } - else { - this.duration = this.timestamp - this.started; - } - if (context.release) { - this.release = context.release; - } - if (context.environment) { - this.environment = context.environment; + get defaultPort() { + if (typeof this.explicitDefaultPort === 'number') { + return this.explicitDefaultPort; + } + return isSecureEndpoint() ? 443 : 80; } - if (context.ipAddress) { - this.ipAddress = context.ipAddress; + set defaultPort(v) { + this.explicitDefaultPort = v; } - if (context.userAgent) { - this.userAgent = context.userAgent; + get protocol() { + if (typeof this.explicitProtocol === 'string') { + return this.explicitProtocol; + } + return isSecureEndpoint() ? 'https:' : 'http:'; } - if (typeof context.errors === 'number') { - this.errors = context.errors; + set protocol(v) { + this.explicitProtocol = v; } - if (context.status) { - this.status = context.status; + callback(req, opts, fn) { + throw new Error('"agent-base" has no default implementation, you must subclass and override `callback()`'); } - }; - /** JSDoc */ - Session.prototype.close = function (status) { - if (status) { - this.update({ status: status }); + /** + * Called by node-core's "_http_client.js" module when creating + * a new HTTP request with this Agent instance. + * + * @api public + */ + addRequest(req, _opts) { + const opts = Object.assign({}, _opts); + if (typeof opts.secureEndpoint !== 'boolean') { + opts.secureEndpoint = isSecureEndpoint(); + } + if (opts.host == null) { + opts.host = 'localhost'; + } + if (opts.port == null) { + opts.port = opts.secureEndpoint ? 443 : 80; + } + if (opts.protocol == null) { + opts.protocol = opts.secureEndpoint ? 'https:' : 'http:'; + } + if (opts.host && opts.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 opts.path; + } + delete opts.agent; + delete opts.hostname; + delete opts._defaultAgent; + delete opts.defaultPort; + delete opts.createConnection; + // Hint to use "Connection: close" + // XXX: non-documented `http` module API :( + req._last = true; + req.shouldKeepAlive = false; + let timedOut = false; + let timeoutId = null; + const timeoutMs = opts.timeout || this.timeout; + const onerror = (err) => { + if (req._hadError) + return; + req.emit('error', err); + // For Safety. Some additional errors might fire later on + // and we need to make sure we don't double-fire the error event. + req._hadError = true; + }; + const ontimeout = () => { + timeoutId = null; + timedOut = true; + const err = new Error(`A "socket" was not created for HTTP request before ${timeoutMs}ms`); + err.code = 'ETIMEOUT'; + onerror(err); + }; + const callbackError = (err) => { + if (timedOut) + return; + if (timeoutId !== null) { + clearTimeout(timeoutId); + timeoutId = null; + } + onerror(err); + }; + const onsocket = (socket) => { + if (timedOut) + return; + if (timeoutId != null) { + clearTimeout(timeoutId); + timeoutId = null; + } + if (isAgent(socket)) { + // `socket` is actually an `http.Agent` instance, so + // relinquish responsibility for this `req` to the Agent + // from here on + debug('Callback returned another Agent instance %o', socket.constructor.name); + socket.addRequest(req, opts); + return; + } + if (socket) { + socket.once('free', () => { + this.freeSocket(socket, opts); + }); + req.onSocket(socket); + return; + } + const err = new Error(`no Duplex stream was returned to agent-base for \`${req.method} ${req.path}\``); + onerror(err); + }; + if (typeof this.callback !== 'function') { + onerror(new Error('`callback` is not defined')); + return; + } + if (!this.promisifiedCallback) { + if (this.callback.length >= 3) { + debug('Converting legacy callback function to promise'); + this.promisifiedCallback = promisify_1.default(this.callback); + } + else { + this.promisifiedCallback = this.callback; + } + } + if (typeof timeoutMs === 'number' && timeoutMs > 0) { + timeoutId = setTimeout(ontimeout, timeoutMs); + } + if ('port' in opts && typeof opts.port !== 'number') { + opts.port = Number(opts.port); + } + try { + debug('Resolving socket for %o request: %o', opts.protocol, `${req.method} ${req.path}`); + Promise.resolve(this.promisifiedCallback(req, opts)).then(onsocket, callbackError); + } + catch (err) { + Promise.reject(err).catch(callbackError); + } } - else if (this.status === types_1.SessionStatus.Ok) { - this.update({ status: types_1.SessionStatus.Exited }); + freeSocket(socket, opts) { + debug('Freeing socket %o %o', socket.constructor.name, opts); + socket.destroy(); } - else { - this.update(); + destroy() { + debug('Destroying agent %o', this.constructor.name); } - }; - /** JSDoc */ - Session.prototype.toJSON = function () { - return utils_1.dropUndefinedKeys({ - sid: "" + this.sid, - init: true, - started: new Date(this.started).toISOString(), - timestamp: new Date(this.timestamp).toISOString(), - status: this.status, - errors: this.errors, - did: typeof this.did === 'number' || typeof this.did === 'string' ? "" + this.did : undefined, - duration: this.duration, - attrs: utils_1.dropUndefinedKeys({ - release: this.release, - environment: this.environment, - ip_address: this.ipAddress, - user_agent: this.userAgent, - }), + } + createAgent.Agent = Agent; + // So that `instanceof` works correctly + createAgent.prototype = createAgent.Agent.prototype; +})(createAgent || (createAgent = {})); +module.exports = createAgent; +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 66570: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +function promisify(fn) { + return function (req, opts) { + return new Promise((resolve, reject) => { + fn.call(this, req, opts, (err, rtn) => { + if (err) { + reject(err); + } + else { + resolve(rtn); + } + }); }); }; - return Session; -}()); -exports.Session = Session; -//# sourceMappingURL=session.js.map +} +exports["default"] = promisify; +//# sourceMappingURL=promisify.js.map + +/***/ }), + +/***/ 61231: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + +const indentString = __nccwpck_require__(98043); +const cleanStack = __nccwpck_require__(27972); + +const cleanInternalStack = stack => stack.replace(/\s+at .*aggregate-error\/index.js:\d+:\d+\)?/g, ''); + +class AggregateError extends Error { + constructor(errors) { + if (!Array.isArray(errors)) { + throw new TypeError(`Expected input to be an Array, got ${typeof errors}`); + } + + errors = [...errors].map(error => { + if (error instanceof Error) { + return error; + } + + if (error !== null && typeof error === 'object') { + // Handle plain error objects with message property and/or possibly other metadata + return Object.assign(new Error(error.message), error); + } + + return new Error(error); + }); + + let message = errors + .map(error => { + // The `stack` property is not standardized, so we can't assume it exists + return typeof error.stack === 'string' ? cleanInternalStack(cleanStack(error.stack)) : String(error); + }) + .join('\n'); + message = '\n' + indentString(message, 4); + super(message); + + this.name = 'AggregateError'; + + Object.defineProperty(this, '_errors', {value: errors}); + } + + * [Symbol.iterator]() { + for (const error of this._errors) { + yield error; + } + } +} + +module.exports = AggregateError; + + +/***/ }), + +/***/ 65063: +/***/ ((module) => { + +"use strict"; + + +module.exports = ({onlyFirst = false} = {}) => { + const pattern = [ + '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)', + '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))' + ].join('|'); + + return new RegExp(pattern, onlyFirst ? undefined : 'g'); +}; + + +/***/ }), + +/***/ 52068: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; +/* module decorator */ module = __nccwpck_require__.nmd(module); + + +const wrapAnsi16 = (fn, offset) => (...args) => { + const code = fn(...args); + return `\u001B[${code + offset}m`; +}; + +const wrapAnsi256 = (fn, offset) => (...args) => { + const code = fn(...args); + return `\u001B[${38 + offset};5;${code}m`; +}; + +const wrapAnsi16m = (fn, offset) => (...args) => { + const rgb = fn(...args); + return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; +}; + +const ansi2ansi = n => n; +const rgb2rgb = (r, g, b) => [r, g, b]; + +const setLazyProperty = (object, property, get) => { + Object.defineProperty(object, property, { + get: () => { + const value = get(); + + Object.defineProperty(object, property, { + value, + enumerable: true, + configurable: true + }); + + return value; + }, + enumerable: true, + configurable: true + }); +}; + +/** @type {typeof import('color-convert')} */ +let colorConvert; +const makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => { + if (colorConvert === undefined) { + colorConvert = __nccwpck_require__(86931); + } + + const offset = isBackground ? 10 : 0; + const styles = {}; + + for (const [sourceSpace, suite] of Object.entries(colorConvert)) { + const name = sourceSpace === 'ansi16' ? 'ansi' : sourceSpace; + if (sourceSpace === targetSpace) { + styles[name] = wrap(identity, offset); + } else if (typeof suite === 'object') { + styles[name] = wrap(suite[targetSpace], offset); + } + } + + return styles; +}; + +function assembleStyles() { + const codes = new Map(); + const styles = { + modifier: { + reset: [0, 0], + // 21 isn't widely supported and 22 does the same thing + bold: [1, 22], + dim: [2, 22], + italic: [3, 23], + underline: [4, 24], + inverse: [7, 27], + hidden: [8, 28], + strikethrough: [9, 29] + }, + color: { + black: [30, 39], + red: [31, 39], + green: [32, 39], + yellow: [33, 39], + blue: [34, 39], + magenta: [35, 39], + cyan: [36, 39], + white: [37, 39], + + // Bright color + blackBright: [90, 39], + redBright: [91, 39], + greenBright: [92, 39], + yellowBright: [93, 39], + blueBright: [94, 39], + magentaBright: [95, 39], + cyanBright: [96, 39], + whiteBright: [97, 39] + }, + bgColor: { + bgBlack: [40, 49], + bgRed: [41, 49], + bgGreen: [42, 49], + bgYellow: [43, 49], + bgBlue: [44, 49], + bgMagenta: [45, 49], + bgCyan: [46, 49], + bgWhite: [47, 49], + + // Bright color + bgBlackBright: [100, 49], + bgRedBright: [101, 49], + bgGreenBright: [102, 49], + bgYellowBright: [103, 49], + bgBlueBright: [104, 49], + bgMagentaBright: [105, 49], + bgCyanBright: [106, 49], + bgWhiteBright: [107, 49] + } + }; + + // Alias bright black as gray (and grey) + styles.color.gray = styles.color.blackBright; + styles.bgColor.bgGray = styles.bgColor.bgBlackBright; + styles.color.grey = styles.color.blackBright; + styles.bgColor.bgGrey = styles.bgColor.bgBlackBright; + + for (const [groupName, group] of Object.entries(styles)) { + for (const [styleName, style] of Object.entries(group)) { + styles[styleName] = { + open: `\u001B[${style[0]}m`, + close: `\u001B[${style[1]}m` + }; + + group[styleName] = styles[styleName]; + + codes.set(style[0], style[1]); + } + + Object.defineProperty(styles, groupName, { + value: group, + enumerable: false + }); + } + + Object.defineProperty(styles, 'codes', { + value: codes, + enumerable: false + }); + + styles.color.close = '\u001B[39m'; + styles.bgColor.close = '\u001B[49m'; + + setLazyProperty(styles.color, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, false)); + setLazyProperty(styles.color, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, false)); + setLazyProperty(styles.color, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, false)); + setLazyProperty(styles.bgColor, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, true)); + setLazyProperty(styles.bgColor, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, true)); + setLazyProperty(styles.bgColor, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, true)); + + return styles; +} + +// Make the export immutable +Object.defineProperty(module, 'exports', { + enumerable: true, + get: assembleStyles +}); + /***/ }), -/***/ 88455: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 62003: +/***/ ((module) => { + +"use strict"; + -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var hub_1 = __nccwpck_require__(6393); /** - * This calls a function on the current hub. - * @param method function to call on hub. - * @param args to pass to function. + * Expose `arrayFlatten`. */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function callOnHub(method) { - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - var hub = hub_1.getCurrentHub(); - if (hub && hub[method]) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - return hub[method].apply(hub, tslib_1.__spread(args)); - } - throw new Error("No hub defined or " + method + " was not found on the hub, please open a bug report."); -} +module.exports = arrayFlatten + /** - * Captures an exception event and sends it to Sentry. + * Recursive flatten function with depth. * - * @param exception An exception-like object. - * @returns The generated eventId. + * @param {Array} array + * @param {Array} result + * @param {Number} depth + * @return {Array} */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types -function captureException(exception, captureContext) { - var syntheticException; - try { - throw new Error('Sentry syntheticException'); - } - catch (exception) { - syntheticException = exception; +function flattenWithDepth (array, result, depth) { + for (var i = 0; i < array.length; i++) { + var value = array[i] + + if (depth > 0 && Array.isArray(value)) { + flattenWithDepth(value, result, depth - 1) + } else { + result.push(value) } - return callOnHub('captureException', exception, { - captureContext: captureContext, - originalException: exception, - syntheticException: syntheticException, - }); + } + + return result } -exports.captureException = captureException; + /** - * Captures a message event and sends it to Sentry. + * Recursive flatten function. Omitting depth is slightly faster. * - * @param message The message to send to Sentry. - * @param level Define the level of the message. - * @returns The generated eventId. + * @param {Array} array + * @param {Array} result + * @return {Array} */ -function captureMessage(message, captureContext) { - var syntheticException; - try { - throw new Error(message); - } - catch (exception) { - syntheticException = exception; +function flattenForever (array, result) { + for (var i = 0; i < array.length; i++) { + var value = array[i] + + if (Array.isArray(value)) { + flattenForever(value, result) + } else { + result.push(value) } - // This is necessary to provide explicit scopes upgrade, without changing the original - // arity of the `captureMessage(message, level)` method. - var level = typeof captureContext === 'string' ? captureContext : undefined; - var context = typeof captureContext !== 'string' ? { captureContext: captureContext } : undefined; - return callOnHub('captureMessage', message, level, tslib_1.__assign({ originalException: message, syntheticException: syntheticException }, context)); -} -exports.captureMessage = captureMessage; -/** - * Captures a manually created event and sends it to Sentry. - * - * @param event The event to send to Sentry. - * @returns The generated eventId. - */ -function captureEvent(event) { - return callOnHub('captureEvent', event); -} -exports.captureEvent = captureEvent; -/** - * Callback to set context information onto the scope. - * @param callback Callback function that receives Scope. - */ -function configureScope(callback) { - callOnHub('configureScope', callback); + } + + return result } -exports.configureScope = configureScope; + /** - * Records a new breadcrumb which will be attached to future events. - * - * Breadcrumbs will be added to subsequent events to provide more context on - * user's actions prior to an error or crash. + * Flatten an array, with the ability to define a depth. * - * @param breadcrumb The breadcrumb to record. + * @param {Array} array + * @param {Number} depth + * @return {Array} */ -function addBreadcrumb(breadcrumb) { - callOnHub('addBreadcrumb', breadcrumb); +function arrayFlatten (array, depth) { + if (depth == null) { + return flattenForever(array, []) + } + + return flattenWithDepth(array, [], depth) } -exports.addBreadcrumb = addBreadcrumb; -/** - * Sets context data with the given name. - * @param name of the context - * @param context Any kind of data. This data will be normalized. - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function setContext(name, context) { - callOnHub('setContext', name, context); + + +/***/ }), + +/***/ 86950: +/***/ ((module) => { + +"use strict"; + + +/* global SharedArrayBuffer, Atomics */ + +if (typeof SharedArrayBuffer !== 'undefined' && typeof Atomics !== 'undefined') { + const nil = new Int32Array(new SharedArrayBuffer(4)) + + function sleep (ms) { + // also filters out NaN, non-number types, including empty strings, but allows bigints + const valid = ms > 0 && ms < Infinity + if (valid === false) { + if (typeof ms !== 'number' && typeof ms !== 'bigint') { + throw TypeError('sleep: ms must be a number') + } + throw RangeError('sleep: ms must be a number that is greater than 0 but less than Infinity') + } + + Atomics.wait(nil, 0, 0, Number(ms)) + } + module.exports = sleep +} else { + + function sleep (ms) { + // also filters out NaN, non-number types, including empty strings, but allows bigints + const valid = ms > 0 && ms < Infinity + if (valid === false) { + if (typeof ms !== 'number' && typeof ms !== 'bigint') { + throw TypeError('sleep: ms must be a number') + } + throw RangeError('sleep: ms must be a number that is greater than 0 but less than Infinity') + } + const target = Date.now() + Number(ms) + while (target > Date.now()){} + } + + module.exports = sleep + } -exports.setContext = setContext; -/** - * Set an object that will be merged sent as extra data with the event. - * @param extras Extras object to merge into current context. - */ -function setExtras(extras) { - callOnHub('setExtras', extras); + + +/***/ }), + +/***/ 83682: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var register = __nccwpck_require__(44670) +var addHook = __nccwpck_require__(5549) +var removeHook = __nccwpck_require__(6819) + +// bind with array of arguments: https://stackoverflow.com/a/21792913 +var bind = Function.bind +var bindable = bind.bind(bind) + +function bindApi (hook, state, name) { + var removeHookRef = bindable(removeHook, null).apply(null, name ? [state, name] : [state]) + hook.api = { remove: removeHookRef } + hook.remove = removeHookRef + + ;['before', 'error', 'after', 'wrap'].forEach(function (kind) { + var args = name ? [state, kind, name] : [state, kind] + hook[kind] = hook.api[kind] = bindable(addHook, null).apply(null, args) + }) } -exports.setExtras = setExtras; -/** - * Set an object that will be merged sent as tags data with the event. - * @param tags Tags context object to merge into current context. - */ -function setTags(tags) { - callOnHub('setTags', tags); + +function HookSingular () { + var singularHookName = 'h' + var singularHookState = { + registry: {} + } + var singularHook = register.bind(null, singularHookState, singularHookName) + bindApi(singularHook, singularHookState, singularHookName) + return singularHook } -exports.setTags = setTags; -/** - * Set key:value that will be sent as extra data with the event. - * @param key String of extra - * @param extra Any kind of data. This data will be normalized. - */ -function setExtra(key, extra) { - callOnHub('setExtra', key, extra); + +function HookCollection () { + var state = { + registry: {} + } + + var hook = register.bind(null, state) + bindApi(hook, state) + + return hook } -exports.setExtra = setExtra; -/** - * Set key:value that will be sent as tags data with the event. - * - * Can also be used to unset a tag, by passing `undefined`. - * - * @param key String key of tag - * @param value Value of tag - */ -function setTag(key, value) { - callOnHub('setTag', key, value); + +var collectionHookDeprecationMessageDisplayed = false +function Hook () { + if (!collectionHookDeprecationMessageDisplayed) { + console.warn('[before-after-hook]: "Hook()" repurposing warning, use "Hook.Collection()". Read more: https://git.io/upgrade-before-after-hook-to-1.4') + collectionHookDeprecationMessageDisplayed = true + } + return HookCollection() } -exports.setTag = setTag; -/** - * Updates user context information for future events. - * - * @param user User context object to be set in the current context. Pass `null` to unset the user. - */ -function setUser(user) { - callOnHub('setUser', user); + +Hook.Singular = HookSingular.bind() +Hook.Collection = HookCollection.bind() + +module.exports = Hook +// expose constructors as a named property for TypeScript +module.exports.Hook = Hook +module.exports.Singular = Hook.Singular +module.exports.Collection = Hook.Collection + + +/***/ }), + +/***/ 5549: +/***/ ((module) => { + +module.exports = addHook + +function addHook (state, kind, name, hook) { + var orig = hook + if (!state.registry[name]) { + state.registry[name] = [] + } + + if (kind === 'before') { + hook = function (method, options) { + return Promise.resolve() + .then(orig.bind(null, options)) + .then(method.bind(null, options)) + } + } + + if (kind === 'after') { + hook = function (method, options) { + var result + return Promise.resolve() + .then(method.bind(null, options)) + .then(function (result_) { + result = result_ + return orig(result, options) + }) + .then(function () { + return result + }) + } + } + + if (kind === 'error') { + hook = function (method, options) { + return Promise.resolve() + .then(method.bind(null, options)) + .catch(function (error) { + return orig(error, options) + }) + } + } + + state.registry[name].push({ + hook: hook, + orig: orig + }) } -exports.setUser = setUser; -/** - * Creates a new scope with and executes the given operation within. - * The scope is automatically removed once the operation - * finishes or throws. - * - * This is essentially a convenience function for: - * - * pushScope(); - * callback(); - * popScope(); - * - * @param callback that will be enclosed into push/popScope. - */ -function withScope(callback) { - callOnHub('withScope', callback); + + +/***/ }), + +/***/ 44670: +/***/ ((module) => { + +module.exports = register + +function register (state, name, method, options) { + if (typeof method !== 'function') { + throw new Error('method for before hook must be a function') + } + + if (!options) { + options = {} + } + + if (Array.isArray(name)) { + return name.reverse().reduce(function (callback, name) { + return register.bind(null, state, name, callback, options) + }, method)() + } + + return Promise.resolve() + .then(function () { + if (!state.registry[name]) { + return method(options) + } + + return (state.registry[name]).reduce(function (method, registered) { + return registered.hook.bind(null, method, options) + }, method)() + }) } -exports.withScope = withScope; -/** - * Calls a function on the latest client. Use this with caution, it's meant as - * in "internal" helper so we don't need to expose every possible function in - * the shim. It is not guaranteed that the client actually implements the - * function. - * - * @param method The method to call on the client/client. - * @param args Arguments to pass to the client/fontend. - * @hidden - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function _callOnClient(method) { - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - callOnHub.apply(void 0, tslib_1.__spread(['_invokeClient', method], args)); + + +/***/ }), + +/***/ 6819: +/***/ ((module) => { + +module.exports = removeHook + +function removeHook (state, name, method) { + if (!state.registry[name]) { + return + } + + var index = state.registry[name] + .map(function (registered) { return registered.orig }) + .indexOf(method) + + if (index === -1) { + return + } + + state.registry[name].splice(index, 1) } -exports._callOnClient = _callOnClient; + + +/***/ }), + +/***/ 97076: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; +/*! + * body-parser + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + + + /** - * Starts a new `Transaction` and returns it. This is the entry point to manual tracing instrumentation. - * - * A tree structure can be built by adding child spans to the transaction, and child spans to other spans. To start a - * new child span within the transaction or any span, call the respective `.startChild()` method. - * - * Every child span must be finished before the transaction is finished, otherwise the unfinished spans are discarded. - * - * The transaction must be finished with a call to its `.finish()` method, at which point the transaction with all its - * finished child spans will be sent to Sentry. - * - * @param context Properties of the new `Transaction`. - * @param customSamplingContext Information given to the transaction sampling function (along with context-dependent - * default values). See {@link Options.tracesSampler}. - * - * @returns The transaction which was just started + * Module dependencies. + * @private */ -function startTransaction(context, customSamplingContext) { - return callOnHub('startTransaction', tslib_1.__assign({}, context), customSamplingContext); -} -exports.startTransaction = startTransaction; -//# sourceMappingURL=index.js.map -/***/ }), +var deprecate = __nccwpck_require__(18883)('body-parser') -/***/ 40508: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/** + * Cache of loaded parsers. + * @private + */ + +var parsers = Object.create(null) -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var core_1 = __nccwpck_require__(79212); -var types_1 = __nccwpck_require__(83789); -var utils_1 = __nccwpck_require__(1620); -var parsers_1 = __nccwpck_require__(19090); -var transports_1 = __nccwpck_require__(21437); /** - * The Sentry Node SDK Backend. - * @hidden + * @typedef Parsers + * @type {function} + * @property {function} json + * @property {function} raw + * @property {function} text + * @property {function} urlencoded */ -var NodeBackend = /** @class */ (function (_super) { - tslib_1.__extends(NodeBackend, _super); - function NodeBackend() { - return _super !== null && _super.apply(this, arguments) || this; - } - /** - * @inheritDoc - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types - NodeBackend.prototype.eventFromException = function (exception, hint) { - var _this = this; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - var ex = exception; - var mechanism = { - handled: true, - type: 'generic', - }; - if (!utils_1.isError(exception)) { - if (utils_1.isPlainObject(exception)) { - // This will allow us to group events based on top-level keys - // which is much better than creating new group when any key/value change - var message = "Non-Error exception captured with keys: " + utils_1.extractExceptionKeysForMessage(exception); - core_1.getCurrentHub().configureScope(function (scope) { - scope.setExtra('__serialized__', utils_1.normalizeToSize(exception)); - }); - ex = (hint && hint.syntheticException) || new Error(message); - ex.message = message; - } - else { - // This handles when someone does: `throw "something awesome";` - // We use synthesized Error here so we can extract a (rough) stack trace. - ex = (hint && hint.syntheticException) || new Error(exception); - ex.message = exception; - } - mechanism.synthetic = true; - } - return new utils_1.SyncPromise(function (resolve, reject) { - return parsers_1.parseError(ex, _this._options) - .then(function (event) { - utils_1.addExceptionTypeValue(event, undefined, undefined); - utils_1.addExceptionMechanism(event, mechanism); - resolve(tslib_1.__assign(tslib_1.__assign({}, event), { event_id: hint && hint.event_id })); - }) - .then(null, reject); - }); - }; - /** - * @inheritDoc - */ - NodeBackend.prototype.eventFromMessage = function (message, level, hint) { - var _this = this; - if (level === void 0) { level = types_1.Severity.Info; } - var event = { - event_id: hint && hint.event_id, - level: level, - message: message, - }; - return new utils_1.SyncPromise(function (resolve) { - if (_this._options.attachStacktrace && hint && hint.syntheticException) { - var stack = hint.syntheticException ? parsers_1.extractStackFromError(hint.syntheticException) : []; - parsers_1.parseStack(stack, _this._options) - .then(function (frames) { - event.stacktrace = { - frames: parsers_1.prepareFramesForEvent(frames), - }; - resolve(event); - }) - .then(null, function () { - resolve(event); - }); - } - else { - resolve(event); - } - }); - }; - /** - * @inheritDoc - */ - NodeBackend.prototype._setupTransport = function () { - if (!this._options.dsn) { - // We return the noop transport here in case there is no Dsn. - return _super.prototype._setupTransport.call(this); - } - var dsn = new utils_1.Dsn(this._options.dsn); - var transportOptions = tslib_1.__assign(tslib_1.__assign(tslib_1.__assign(tslib_1.__assign(tslib_1.__assign({}, this._options.transportOptions), (this._options.httpProxy && { httpProxy: this._options.httpProxy })), (this._options.httpsProxy && { httpsProxy: this._options.httpsProxy })), (this._options.caCerts && { caCerts: this._options.caCerts })), { dsn: this._options.dsn }); - if (this._options.transport) { - return new this._options.transport(transportOptions); - } - if (dsn.protocol === 'http') { - return new transports_1.HTTPTransport(transportOptions); - } - return new transports_1.HTTPSTransport(transportOptions); - }; - return NodeBackend; -}(core_1.BaseBackend)); -exports.NodeBackend = NodeBackend; -//# sourceMappingURL=backend.js.map -/***/ }), +/** + * Module exports. + * @type {Parsers} + */ -/***/ 86147: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +exports = module.exports = deprecate.function(bodyParser, + 'bodyParser: use individual json/urlencoded middlewares') -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var core_1 = __nccwpck_require__(79212); -var backend_1 = __nccwpck_require__(40508); -var version_1 = __nccwpck_require__(31271); /** - * The Sentry Node SDK Client. - * - * @see NodeOptions for documentation on configuration options. - * @see SentryClient for usage documentation. + * JSON parser. + * @public */ -var NodeClient = /** @class */ (function (_super) { - tslib_1.__extends(NodeClient, _super); - /** - * Creates a new Node SDK instance. - * @param options Configuration options for this SDK. - */ - function NodeClient(options) { - return _super.call(this, backend_1.NodeBackend, options) || this; - } - /** - * @inheritDoc - */ - NodeClient.prototype._prepareEvent = function (event, scope, hint) { - event.platform = event.platform || 'node'; - event.sdk = tslib_1.__assign(tslib_1.__assign({}, event.sdk), { name: version_1.SDK_NAME, packages: tslib_1.__spread(((event.sdk && event.sdk.packages) || []), [ - { - name: 'npm:@sentry/node', - version: version_1.SDK_VERSION, - }, - ]), version: version_1.SDK_VERSION }); - if (this.getOptions().serverName) { - event.server_name = this.getOptions().serverName; - } - return _super.prototype._prepareEvent.call(this, event, scope, hint); - }; - return NodeClient; -}(core_1.BaseClient)); -exports.NodeClient = NodeClient; -//# sourceMappingURL=client.js.map -/***/ }), +Object.defineProperty(exports, "json", ({ + configurable: true, + enumerable: true, + get: createParserGetter('json') +})) -/***/ 45400: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/** + * Raw parser. + * @public + */ + +Object.defineProperty(exports, "raw", ({ + configurable: true, + enumerable: true, + get: createParserGetter('raw') +})) -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -/* eslint-disable max-lines */ -/* eslint-disable @typescript-eslint/no-explicit-any */ -var core_1 = __nccwpck_require__(79212); -var tracing_1 = __nccwpck_require__(64358); -var utils_1 = __nccwpck_require__(1620); -var domain = __nccwpck_require__(13639); -var os = __nccwpck_require__(22037); -var sdk_1 = __nccwpck_require__(38836); -var DEFAULT_SHUTDOWN_TIMEOUT = 2000; /** - * Express-compatible tracing handler. - * @see Exposed as `Handlers.tracingHandler` + * Text parser. + * @public */ -function tracingHandler() { - return function sentryTracingMiddleware(req, res, next) { - // If there is a trace header set, we extract the data from it (parentSpanId, traceId, and sampling decision) - var traceparentData; - if (req.headers && utils_1.isString(req.headers['sentry-trace'])) { - traceparentData = tracing_1.extractTraceparentData(req.headers['sentry-trace']); - } - var transaction = core_1.startTransaction(tslib_1.__assign({ name: extractExpressTransactionName(req, { path: true, method: true }), op: 'http.server' }, traceparentData)); - // We put the transaction on the scope so users can attach children to it - core_1.getCurrentHub().configureScope(function (scope) { - scope.setSpan(transaction); - }); - // We also set __sentry_transaction on the response so people can grab the transaction there to add - // spans to it later. - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - res.__sentry_transaction = transaction; - res.once('finish', function () { - // Push `transaction.finish` to the next event loop so open spans have a chance to finish before the transaction - // closes - setImmediate(function () { - addExpressReqToTransaction(transaction, req); - transaction.setHttpStatus(res.statusCode); - transaction.finish(); - }); - }); - next(); - }; -} -exports.tracingHandler = tracingHandler; + +Object.defineProperty(exports, "text", ({ + configurable: true, + enumerable: true, + get: createParserGetter('text') +})) + /** - * Set parameterized as transaction name e.g.: `GET /users/:id` - * Also adds more context data on the transaction from the request + * URL-encoded parser. + * @public */ -function addExpressReqToTransaction(transaction, req) { - if (!transaction) - return; - transaction.name = extractExpressTransactionName(req, { path: true, method: true }); - transaction.setData('url', req.originalUrl); - transaction.setData('baseUrl', req.baseUrl); - transaction.setData('query', req.query); -} + +Object.defineProperty(exports, "urlencoded", ({ + configurable: true, + enumerable: true, + get: createParserGetter('urlencoded') +})) + /** - * Extracts complete generalized path from the request object and uses it to construct transaction name. - * - * eg. GET /mountpoint/user/:id - * - * @param req The ExpressRequest object - * @param options What to include in the transaction name (method, path, or both) + * Create a middleware to parse json and urlencoded bodies. * - * @returns The fully constructed transaction name + * @param {object} [options] + * @return {function} + * @deprecated + * @public */ -function extractExpressTransactionName(req, options) { - if (options === void 0) { options = {}; } - var _a; - var method = (_a = req.method) === null || _a === void 0 ? void 0 : _a.toUpperCase(); - var path = ''; - if (req.route) { - // if the mountpoint is `/`, req.baseUrl is '' (not undefined), so it's safe to include it here - // see https://github.com/expressjs/express/blob/508936853a6e311099c9985d4c11a4b1b8f6af07/test/req.baseUrl.js#L7 - path = "" + req.baseUrl + req.route.path; - } - else if (req.originalUrl || req.url) { - path = utils_1.stripUrlQueryAndFragment(req.originalUrl || req.url || ''); - } - var info = ''; - if (options.method && method) { - info += method; - } - if (options.method && options.path) { - info += " "; - } - if (options.path && path) { - info += path; - } - return info; -} -/** JSDoc */ -function extractTransaction(req, type) { - var _a; - switch (type) { - case 'path': { - return extractExpressTransactionName(req, { path: true }); - } - case 'handler': { - return ((_a = req.route) === null || _a === void 0 ? void 0 : _a.stack[0].name) || ''; - } - case 'methodPath': - default: { - return extractExpressTransactionName(req, { path: true, method: true }); - } + +function bodyParser (options) { + var opts = {} + + // exclude type option + if (options) { + for (var prop in options) { + if (prop !== 'type') { + opts[prop] = options[prop] + } } + } + + var _urlencoded = exports.urlencoded(opts) + var _json = exports.json(opts) + + return function bodyParser (req, res, next) { + _json(req, res, function (err) { + if (err) return next(err) + _urlencoded(req, res, next) + }) + } } -/** Default user keys that'll be used to extract data from the request */ -var DEFAULT_USER_KEYS = ['id', 'username', 'email']; -/** JSDoc */ -function extractUserData(user, keys) { - var extractedUser = {}; - var attributes = Array.isArray(keys) ? keys : DEFAULT_USER_KEYS; - attributes.forEach(function (key) { - if (user && key in user) { - extractedUser[key] = user[key]; - } - }); - return extractedUser; -} + /** - * Enriches passed event with request data. - * - * @param event Will be mutated and enriched with req data - * @param req Request object - * @param options object containing flags to enable functionality - * @hidden + * Create a getter for loading a parser. + * @private */ -function parseRequest(event, req, options) { - // eslint-disable-next-line no-param-reassign - options = tslib_1.__assign({ ip: false, request: true, serverName: true, transaction: true, user: true, version: true }, options); - if (options.version) { - event.contexts = tslib_1.__assign(tslib_1.__assign({}, event.contexts), { runtime: { - name: 'node', - version: global.process.version, - } }); - } - if (options.request) { - // if the option value is `true`, use the default set of keys by not passing anything to `extractNodeRequestData()` - var extractedRequestData = Array.isArray(options.request) - ? utils_1.extractNodeRequestData(req, options.request) - : utils_1.extractNodeRequestData(req); - event.request = tslib_1.__assign(tslib_1.__assign({}, event.request), extractedRequestData); - } - if (options.serverName && !event.server_name) { - event.server_name = global.process.env.SENTRY_NAME || os.hostname(); - } - if (options.user) { - var extractedUser = req.user && utils_1.isPlainObject(req.user) ? extractUserData(req.user, options.user) : {}; - if (Object.keys(extractedUser)) { - event.user = tslib_1.__assign(tslib_1.__assign({}, event.user), extractedUser); - } - } - // client ip: - // node: req.connection.remoteAddress - // express, koa: req.ip - if (options.ip) { - var ip = req.ip || (req.connection && req.connection.remoteAddress); - if (ip) { - event.user = tslib_1.__assign(tslib_1.__assign({}, event.user), { ip_address: ip }); - } - } - if (options.transaction && !event.transaction) { - event.transaction = extractTransaction(req, options.transaction); - } - return event; + +function createParserGetter (name) { + return function get () { + return loadParser(name) + } } -exports.parseRequest = parseRequest; + /** - * Express compatible request handler. - * @see Exposed as `Handlers.requestHandler` + * Load a parser module. + * @private */ -function requestHandler(options) { - return function sentryRequestMiddleware(req, res, next) { - if (options && options.flushTimeout && options.flushTimeout > 0) { - // eslint-disable-next-line @typescript-eslint/unbound-method - var _end_1 = res.end; - res.end = function (chunk, encoding, cb) { - var _this = this; - sdk_1.flush(options.flushTimeout) - .then(function () { - _end_1.call(_this, chunk, encoding, cb); - }) - .then(null, function (e) { - utils_1.logger.error(e); - }); - }; - } - var local = domain.create(); - local.add(req); - local.add(res); - local.on('error', next); - local.run(function () { - core_1.getCurrentHub().configureScope(function (scope) { - return scope.addEventProcessor(function (event) { return parseRequest(event, req, options); }); - }); - next(); - }); - }; -} -exports.requestHandler = requestHandler; -/** JSDoc */ -function getStatusCodeFromResponse(error) { - var statusCode = error.status || error.statusCode || error.status_code || (error.output && error.output.statusCode); - return statusCode ? parseInt(statusCode, 10) : 500; -} -/** Returns true if response code is internal server error */ -function defaultShouldHandleError(error) { - var status = getStatusCodeFromResponse(error); - return status >= 500; + +function loadParser (parserName) { + var parser = parsers[parserName] + + if (parser !== undefined) { + return parser + } + + // this uses a switch for static require analysis + switch (parserName) { + case 'json': + parser = __nccwpck_require__(20859) + break + case 'raw': + parser = __nccwpck_require__(49609) + break + case 'text': + parser = __nccwpck_require__(26382) + break + case 'urlencoded': + parser = __nccwpck_require__(76100) + break + } + + // store to prevent invoking require() + return (parsers[parserName] = parser) } + + +/***/ }), + +/***/ 88862: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; +/*! + * body-parser + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + + + /** - * Express compatible error handler. - * @see Exposed as `Handlers.errorHandler` + * Module dependencies. + * @private */ -function errorHandler(options) { - return function sentryErrorMiddleware(error, _req, res, next) { - // eslint-disable-next-line @typescript-eslint/unbound-method - var shouldHandleError = (options && options.shouldHandleError) || defaultShouldHandleError; - if (shouldHandleError(error)) { - core_1.withScope(function (_scope) { - // For some reason we need to set the transaction on the scope again - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - var transaction = res.__sentry_transaction; - if (transaction && _scope.getSpan() === undefined) { - _scope.setSpan(transaction); - } - var eventId = core_1.captureException(error); - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - res.sentry = eventId; - next(error); - }); - return; - } - next(error); - }; -} -exports.errorHandler = errorHandler; + +var createError = __nccwpck_require__(95193) +var getBody = __nccwpck_require__(47742) +var iconv = __nccwpck_require__(19032) +var onFinished = __nccwpck_require__(92098) +var zlib = __nccwpck_require__(59796) + /** - * @hidden + * Module exports. */ -function logAndExitProcess(error) { - // eslint-disable-next-line no-console - console.error(error && error.stack ? error.stack : error); - var client = core_1.getCurrentHub().getClient(); - if (client === undefined) { - utils_1.logger.warn('No NodeClient was defined, we are exiting the process now.'); - global.process.exit(1); - return; + +module.exports = read + +/** + * Read a request into a buffer and parse. + * + * @param {object} req + * @param {object} res + * @param {function} next + * @param {function} parse + * @param {function} debug + * @param {object} options + * @private + */ + +function read (req, res, next, parse, debug, options) { + var length + var opts = options + var stream + + // flag as parsed + req._body = true + + // read options + var encoding = opts.encoding !== null + ? opts.encoding + : null + var verify = opts.verify + + try { + // get the content stream + stream = contentstream(req, debug, opts.inflate) + length = stream.length + stream.length = undefined + } catch (err) { + return next(err) + } + + // set raw-body options + opts.length = length + opts.encoding = verify + ? null + : encoding + + // assert charset is supported + if (opts.encoding === null && encoding !== null && !iconv.encodingExists(encoding)) { + return next(createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', { + charset: encoding.toLowerCase(), + type: 'charset.unsupported' + })) + } + + // read body + debug('read body') + getBody(stream, opts, function (error, body) { + if (error) { + var _error + + if (error.type === 'encoding.unsupported') { + // echo back charset + _error = createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', { + charset: encoding.toLowerCase(), + type: 'charset.unsupported' + }) + } else { + // set status code on error + _error = createError(400, error) + } + + // read off entire request + stream.resume() + onFinished(req, function onfinished () { + next(createError(400, _error)) + }) + return } - var options = client.getOptions(); - var timeout = (options && options.shutdownTimeout && options.shutdownTimeout > 0 && options.shutdownTimeout) || - DEFAULT_SHUTDOWN_TIMEOUT; - utils_1.forget(client.close(timeout).then(function (result) { - if (!result) { - utils_1.logger.warn('We reached the timeout for emptying the request buffer, still exiting now!'); - } - global.process.exit(1); - })); + + // verify + if (verify) { + try { + debug('verify body') + verify(req, res, body, encoding) + } catch (err) { + next(createError(403, err, { + body: body, + type: err.type || 'entity.verify.failed' + })) + return + } + } + + // parse + var str = body + try { + debug('parse body') + str = typeof body !== 'string' && encoding !== null + ? iconv.decode(body, encoding) + : body + req.body = parse(str) + } catch (err) { + next(createError(400, err, { + body: str, + type: err.type || 'entity.parse.failed' + })) + return + } + + next() + }) } -exports.logAndExitProcess = logAndExitProcess; -//# sourceMappingURL=handlers.js.map -/***/ }), +/** + * Get the content stream of the request. + * + * @param {object} req + * @param {function} debug + * @param {boolean} [inflate=true] + * @return {object} + * @api private + */ -/***/ 22783: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +function contentstream (req, debug, inflate) { + var encoding = (req.headers['content-encoding'] || 'identity').toLowerCase() + var length = req.headers['content-length'] + var stream -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var types_1 = __nccwpck_require__(83789); -exports.Severity = types_1.Severity; -exports.Status = types_1.Status; -var core_1 = __nccwpck_require__(79212); -exports.addGlobalEventProcessor = core_1.addGlobalEventProcessor; -exports.addBreadcrumb = core_1.addBreadcrumb; -exports.captureException = core_1.captureException; -exports.captureEvent = core_1.captureEvent; -exports.captureMessage = core_1.captureMessage; -exports.configureScope = core_1.configureScope; -exports.getHubFromCarrier = core_1.getHubFromCarrier; -exports.getCurrentHub = core_1.getCurrentHub; -exports.Hub = core_1.Hub; -exports.makeMain = core_1.makeMain; -exports.Scope = core_1.Scope; -exports.startTransaction = core_1.startTransaction; -exports.setContext = core_1.setContext; -exports.setExtra = core_1.setExtra; -exports.setExtras = core_1.setExtras; -exports.setTag = core_1.setTag; -exports.setTags = core_1.setTags; -exports.setUser = core_1.setUser; -exports.withScope = core_1.withScope; -var backend_1 = __nccwpck_require__(40508); -exports.NodeBackend = backend_1.NodeBackend; -var client_1 = __nccwpck_require__(86147); -exports.NodeClient = client_1.NodeClient; -var sdk_1 = __nccwpck_require__(38836); -exports.defaultIntegrations = sdk_1.defaultIntegrations; -exports.init = sdk_1.init; -exports.lastEventId = sdk_1.lastEventId; -exports.flush = sdk_1.flush; -exports.close = sdk_1.close; -var version_1 = __nccwpck_require__(31271); -exports.SDK_NAME = version_1.SDK_NAME; -exports.SDK_VERSION = version_1.SDK_VERSION; -var core_2 = __nccwpck_require__(79212); -var hub_1 = __nccwpck_require__(6393); -var domain = __nccwpck_require__(13639); -var Handlers = __nccwpck_require__(45400); -exports.Handlers = Handlers; -var NodeIntegrations = __nccwpck_require__(72310); -var Transports = __nccwpck_require__(21437); -exports.Transports = Transports; -var INTEGRATIONS = tslib_1.__assign(tslib_1.__assign({}, core_2.Integrations), NodeIntegrations); -exports.Integrations = INTEGRATIONS; -// We need to patch domain on the global __SENTRY__ object to make it work for node in cross-platform packages like -// @sentry/hub. If we don't do this, browser bundlers will have troubles resolving `require('domain')`. -var carrier = hub_1.getMainCarrier(); -if (carrier.__SENTRY__) { - carrier.__SENTRY__.extensions = carrier.__SENTRY__.extensions || {}; - carrier.__SENTRY__.extensions.domain = carrier.__SENTRY__.extensions.domain || domain; + debug('content-encoding "%s"', encoding) + + if (inflate === false && encoding !== 'identity') { + throw createError(415, 'content encoding unsupported', { + encoding: encoding, + type: 'encoding.unsupported' + }) + } + + switch (encoding) { + case 'deflate': + stream = zlib.createInflate() + debug('inflate body') + req.pipe(stream) + break + case 'gzip': + stream = zlib.createGunzip() + debug('gunzip body') + req.pipe(stream) + break + case 'identity': + stream = req + stream.length = length + break + default: + throw createError(415, 'unsupported content encoding "' + encoding + '"', { + encoding: encoding, + type: 'encoding.unsupported' + }) + } + + return stream } -//# sourceMappingURL=index.js.map + /***/ }), -/***/ 29552: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 20859: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; +/*! + * body-parser + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + + -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var core_1 = __nccwpck_require__(79212); -var types_1 = __nccwpck_require__(83789); -var utils_1 = __nccwpck_require__(1620); -var util = __nccwpck_require__(73837); -/** Console module integration */ -var Console = /** @class */ (function () { - function Console() { - /** - * @inheritDoc - */ - this.name = Console.id; - } - /** - * @inheritDoc - */ - Console.prototype.setupOnce = function () { - var e_1, _a; - var consoleModule = __nccwpck_require__(96206); - try { - for (var _b = tslib_1.__values(['debug', 'info', 'warn', 'error', 'log']), _c = _b.next(); !_c.done; _c = _b.next()) { - var level = _c.value; - utils_1.fill(consoleModule, level, createConsoleWrapper(level)); - } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (_c && !_c.done && (_a = _b.return)) _a.call(_b); - } - finally { if (e_1) throw e_1.error; } - } - }; - /** - * @inheritDoc - */ - Console.id = 'Console'; - return Console; -}()); -exports.Console = Console; /** - * Wrapper function that'll be used for every console level + * Module dependencies. + * @private */ -function createConsoleWrapper(level) { - return function consoleWrapper(originalConsoleMethod) { - var sentryLevel; - switch (level) { - case 'debug': - sentryLevel = types_1.Severity.Debug; - break; - case 'error': - sentryLevel = types_1.Severity.Error; - break; - case 'info': - sentryLevel = types_1.Severity.Info; - break; - case 'warn': - sentryLevel = types_1.Severity.Warning; - break; - default: - sentryLevel = types_1.Severity.Log; - } - return function () { - if (core_1.getCurrentHub().getIntegration(Console)) { - core_1.getCurrentHub().addBreadcrumb({ - category: 'console', - level: sentryLevel, - message: util.format.apply(undefined, arguments), - }, { - input: tslib_1.__spread(arguments), - level: level, - }); - } - originalConsoleMethod.apply(this, arguments); - }; - }; -} -//# sourceMappingURL=console.js.map -/***/ }), +var bytes = __nccwpck_require__(86966) +var contentType = __nccwpck_require__(99915) +var createError = __nccwpck_require__(95193) +var debug = __nccwpck_require__(7471)('body-parser:json') +var read = __nccwpck_require__(88862) +var typeis = __nccwpck_require__(71159) -/***/ 76280: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/** + * Module exports. + */ + +module.exports = json -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var core_1 = __nccwpck_require__(79212); -var utils_1 = __nccwpck_require__(1620); -var http_1 = __nccwpck_require__(84103); -var NODE_VERSION = utils_1.parseSemver(process.versions.node); -/** http module integration */ -var Http = /** @class */ (function () { - /** - * @inheritDoc - */ - function Http(options) { - if (options === void 0) { options = {}; } - /** - * @inheritDoc - */ - this.name = Http.id; - this._breadcrumbs = typeof options.breadcrumbs === 'undefined' ? true : options.breadcrumbs; - this._tracing = typeof options.tracing === 'undefined' ? false : options.tracing; - } - /** - * @inheritDoc - */ - Http.prototype.setupOnce = function () { - // No need to instrument if we don't want to track anything - if (!this._breadcrumbs && !this._tracing) { - return; - } - var wrappedHandlerMaker = _createWrappedRequestMethodFactory(this._breadcrumbs, this._tracing); - var httpModule = __nccwpck_require__(13685); - utils_1.fill(httpModule, 'get', wrappedHandlerMaker); - utils_1.fill(httpModule, 'request', wrappedHandlerMaker); - // NOTE: Prior to Node 9, `https` used internals of `http` module, thus we don't patch it. - // If we do, we'd get double breadcrumbs and double spans for `https` calls. - // It has been changed in Node 9, so for all versions equal and above, we patch `https` separately. - if (NODE_VERSION.major && NODE_VERSION.major > 8) { - var httpsModule = __nccwpck_require__(95687); - utils_1.fill(httpsModule, 'get', wrappedHandlerMaker); - utils_1.fill(httpsModule, 'request', wrappedHandlerMaker); - } - }; - /** - * @inheritDoc - */ - Http.id = 'Http'; - return Http; -}()); -exports.Http = Http; /** - * Function which creates a function which creates wrapped versions of internal `request` and `get` calls within `http` - * and `https` modules. (NB: Not a typo - this is a creator^2!) + * RegExp to match the first non-space in a string. * - * @param breadcrumbsEnabled Whether or not to record outgoing requests as breadcrumbs - * @param tracingEnabled Whether or not to record outgoing requests as tracing spans + * Allowed whitespace is defined in RFC 7159: * - * @returns A function which accepts the exiting handler and returns a wrapped handler + * ws = *( + * %x20 / ; Space + * %x09 / ; Horizontal tab + * %x0A / ; Line feed or New line + * %x0D ) ; Carriage return */ -function _createWrappedRequestMethodFactory(breadcrumbsEnabled, tracingEnabled) { - return function wrappedRequestMethodFactory(originalRequestMethod) { - return function wrappedMethod() { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - // eslint-disable-next-line @typescript-eslint/no-this-alias - var httpModule = this; - var requestArgs = http_1.normalizeRequestArgs(args); - var requestOptions = requestArgs[0]; - var requestUrl = http_1.extractUrl(requestOptions); - // we don't want to record requests to Sentry as either breadcrumbs or spans, so just use the original method - if (http_1.isSentryRequest(requestUrl)) { - return originalRequestMethod.apply(httpModule, requestArgs); - } - var span; - var parentSpan; - var scope = core_1.getCurrentHub().getScope(); - if (scope && tracingEnabled) { - parentSpan = scope.getSpan(); - if (parentSpan) { - span = parentSpan.startChild({ - description: (requestOptions.method || 'GET') + " " + requestUrl, - op: 'request', - }); - var sentryTraceHeader = span.toTraceparent(); - utils_1.logger.log("[Tracing] Adding sentry-trace header to outgoing request: " + sentryTraceHeader); - requestOptions.headers = tslib_1.__assign(tslib_1.__assign({}, requestOptions.headers), { 'sentry-trace': sentryTraceHeader }); - } - } - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - return originalRequestMethod - .apply(httpModule, requestArgs) - .once('response', function (res) { - // eslint-disable-next-line @typescript-eslint/no-this-alias - var req = this; - if (breadcrumbsEnabled) { - addRequestBreadcrumb('response', requestUrl, req, res); - } - if (tracingEnabled && span) { - if (res.statusCode) { - span.setHttpStatus(res.statusCode); - } - span.description = http_1.cleanSpanDescription(span.description, requestOptions, req); - span.finish(); - } - }) - .once('error', function () { - // eslint-disable-next-line @typescript-eslint/no-this-alias - var req = this; - if (breadcrumbsEnabled) { - addRequestBreadcrumb('error', requestUrl, req); - } - if (tracingEnabled && span) { - span.setHttpStatus(500); - span.description = http_1.cleanSpanDescription(span.description, requestOptions, req); - span.finish(); - } - }); - }; - }; -} + +var FIRST_CHAR_REGEXP = /^[\x20\x09\x0a\x0d]*(.)/ // eslint-disable-line no-control-regex + /** - * Captures Breadcrumb based on provided request/response pair + * Create a middleware to parse JSON bodies. + * + * @param {object} [options] + * @return {function} + * @public */ -function addRequestBreadcrumb(event, url, req, res) { - if (!core_1.getCurrentHub().getIntegration(Http)) { - return; - } - core_1.getCurrentHub().addBreadcrumb({ - category: 'http', - data: { - method: req.method, - status_code: res && res.statusCode, - url: url, - }, - type: 'http', - }, { - event: event, - request: req, - response: res, - }); -} -//# sourceMappingURL=http.js.map - -/***/ }), -/***/ 72310: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +function json (options) { + var opts = options || {} -Object.defineProperty(exports, "__esModule", ({ value: true })); -var console_1 = __nccwpck_require__(29552); -exports.Console = console_1.Console; -var http_1 = __nccwpck_require__(76280); -exports.Http = http_1.Http; -var onuncaughtexception_1 = __nccwpck_require__(50443); -exports.OnUncaughtException = onuncaughtexception_1.OnUncaughtException; -var onunhandledrejection_1 = __nccwpck_require__(87344); -exports.OnUnhandledRejection = onunhandledrejection_1.OnUnhandledRejection; -var linkederrors_1 = __nccwpck_require__(70208); -exports.LinkedErrors = linkederrors_1.LinkedErrors; -var modules_1 = __nccwpck_require__(90046); -exports.Modules = modules_1.Modules; -//# sourceMappingURL=index.js.map + var limit = typeof opts.limit !== 'number' + ? bytes.parse(opts.limit || '100kb') + : opts.limit + var inflate = opts.inflate !== false + var reviver = opts.reviver + var strict = opts.strict !== false + var type = opts.type || 'application/json' + var verify = opts.verify || false -/***/ }), + if (verify !== false && typeof verify !== 'function') { + throw new TypeError('option verify must be function') + } -/***/ 70208: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + // create the appropriate type checking function + var shouldParse = typeof type !== 'function' + ? typeChecker(type) + : type -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var core_1 = __nccwpck_require__(79212); -var utils_1 = __nccwpck_require__(1620); -var parsers_1 = __nccwpck_require__(19090); -var DEFAULT_KEY = 'cause'; -var DEFAULT_LIMIT = 5; -/** Adds SDK info to an event. */ -var LinkedErrors = /** @class */ (function () { - /** - * @inheritDoc - */ - function LinkedErrors(options) { - if (options === void 0) { options = {}; } - /** - * @inheritDoc - */ - this.name = LinkedErrors.id; - this._key = options.key || DEFAULT_KEY; - this._limit = options.limit || DEFAULT_LIMIT; + function parse (body) { + if (body.length === 0) { + // special-case empty json body, as it's a common client-side mistake + // TODO: maybe make this configurable or part of "strict" option + return {} } - /** - * @inheritDoc - */ - LinkedErrors.prototype.setupOnce = function () { - core_1.addGlobalEventProcessor(function (event, hint) { - var self = core_1.getCurrentHub().getIntegration(LinkedErrors); - if (self) { - var handler = self._handler && self._handler.bind(self); - return typeof handler === 'function' ? handler(event, hint) : event; - } - return event; - }); - }; - /** - * @inheritDoc - */ - LinkedErrors.prototype._handler = function (event, hint) { - var _this = this; - if (!event.exception || !event.exception.values || !hint || !utils_1.isInstanceOf(hint.originalException, Error)) { - return utils_1.SyncPromise.resolve(event); - } - return new utils_1.SyncPromise(function (resolve) { - _this._walkErrorTree(hint.originalException, _this._key) - .then(function (linkedErrors) { - if (event && event.exception && event.exception.values) { - event.exception.values = tslib_1.__spread(linkedErrors, event.exception.values); - } - resolve(event); - }) - .then(null, function () { - resolve(event); - }); - }); - }; - /** - * @inheritDoc - */ - LinkedErrors.prototype._walkErrorTree = function (error, key, stack) { - var _this = this; - if (stack === void 0) { stack = []; } - if (!utils_1.isInstanceOf(error[key], Error) || stack.length + 1 >= this._limit) { - return utils_1.SyncPromise.resolve(stack); - } - return new utils_1.SyncPromise(function (resolve, reject) { - parsers_1.getExceptionFromError(error[key]) - .then(function (exception) { - _this._walkErrorTree(error[key], key, tslib_1.__spread([exception], stack)) - .then(resolve) - .then(null, function () { - reject(); - }); - }) - .then(null, function () { - reject(); - }); - }); - }; - /** - * @inheritDoc - */ - LinkedErrors.id = 'LinkedErrors'; - return LinkedErrors; -}()); -exports.LinkedErrors = LinkedErrors; -//# sourceMappingURL=linkederrors.js.map -/***/ }), + if (strict) { + var first = firstchar(body) -/***/ 90046: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + if (first !== '{' && first !== '[') { + debug('strict violation') + throw createStrictSyntaxError(body, first) + } + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var fs_1 = __nccwpck_require__(57147); -var path_1 = __nccwpck_require__(71017); -var moduleCache; -/** Extract information about package.json modules */ -function collectModules() { - var mainPaths = (require.main && require.main.paths) || []; - var paths = require.cache ? Object.keys(require.cache) : []; - var infos = {}; - var seen = {}; - paths.forEach(function (path) { - var dir = path; - /** Traverse directories upward in the search of package.json file */ - var updir = function () { - var orig = dir; - dir = path_1.dirname(orig); - if (!dir || orig === dir || seen[orig]) { - return undefined; - } - if (mainPaths.indexOf(dir) < 0) { - return updir(); - } - var pkgfile = path_1.join(orig, 'package.json'); - seen[orig] = true; - if (!fs_1.existsSync(pkgfile)) { - return updir(); - } - try { - var info = JSON.parse(fs_1.readFileSync(pkgfile, 'utf8')); - infos[info.name] = info.version; - } - catch (_oO) { - // no-empty - } - }; - updir(); - }); - return infos; -} -/** Add node modules / packages to the event */ -var Modules = /** @class */ (function () { - function Modules() { - /** - * @inheritDoc - */ - this.name = Modules.id; + try { + debug('parse json') + return JSON.parse(body, reviver) + } catch (e) { + throw normalizeJsonSyntaxError(e, { + message: e.message, + stack: e.stack + }) } - /** - * @inheritDoc - */ - Modules.prototype.setupOnce = function (addGlobalEventProcessor, getCurrentHub) { - var _this = this; - addGlobalEventProcessor(function (event) { - if (!getCurrentHub().getIntegration(Modules)) { - return event; - } - return tslib_1.__assign(tslib_1.__assign({}, event), { modules: _this._getModules() }); - }); - }; - /** Fetches the list of modules and the versions loaded by the entry file for your node.js app. */ - Modules.prototype._getModules = function () { - if (!moduleCache) { - moduleCache = collectModules(); - } - return moduleCache; - }; - /** - * @inheritDoc - */ - Modules.id = 'Modules'; - return Modules; -}()); -exports.Modules = Modules; -//# sourceMappingURL=modules.js.map + } -/***/ }), + return function jsonParser (req, res, next) { + if (req._body) { + debug('body already parsed') + next() + return + } -/***/ 50443: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + req.body = req.body || {} -Object.defineProperty(exports, "__esModule", ({ value: true })); -var core_1 = __nccwpck_require__(79212); -var types_1 = __nccwpck_require__(83789); -var utils_1 = __nccwpck_require__(1620); -var handlers_1 = __nccwpck_require__(45400); -/** Global Promise Rejection handler */ -var OnUncaughtException = /** @class */ (function () { - /** - * @inheritDoc - */ - function OnUncaughtException(_options) { - if (_options === void 0) { _options = {}; } - this._options = _options; - /** - * @inheritDoc - */ - this.name = OnUncaughtException.id; - /** - * @inheritDoc - */ - this.handler = this._makeErrorHandler(); + // skip requests without bodies + if (!typeis.hasBody(req)) { + debug('skip empty body') + next() + return } - /** - * @inheritDoc - */ - OnUncaughtException.prototype.setupOnce = function () { - global.process.on('uncaughtException', this.handler.bind(this)); - }; - /** - * @hidden - */ - OnUncaughtException.prototype._makeErrorHandler = function () { - var _this = this; - var timeout = 2000; - var caughtFirstError = false; - var caughtSecondError = false; - var calledFatalError = false; - var firstError; - return function (error) { - var onFatalError = handlers_1.logAndExitProcess; - var client = core_1.getCurrentHub().getClient(); - if (_this._options.onFatalError) { - // eslint-disable-next-line @typescript-eslint/unbound-method - onFatalError = _this._options.onFatalError; - } - else if (client && client.getOptions().onFatalError) { - // eslint-disable-next-line @typescript-eslint/unbound-method - onFatalError = client.getOptions().onFatalError; - } - if (!caughtFirstError) { - var hub_1 = core_1.getCurrentHub(); - // this is the first uncaught error and the ultimate reason for shutting down - // we want to do absolutely everything possible to ensure it gets captured - // also we want to make sure we don't go recursion crazy if more errors happen after this one - firstError = error; - caughtFirstError = true; - if (hub_1.getIntegration(OnUncaughtException)) { - hub_1.withScope(function (scope) { - scope.setLevel(types_1.Severity.Fatal); - hub_1.captureException(error, { originalException: error }); - if (!calledFatalError) { - calledFatalError = true; - onFatalError(error); - } - }); - } - else { - if (!calledFatalError) { - calledFatalError = true; - onFatalError(error); - } - } - } - else if (calledFatalError) { - // we hit an error *after* calling onFatalError - pretty boned at this point, just shut it down - utils_1.logger.warn('uncaught exception after calling fatal error shutdown callback - this is bad! forcing shutdown'); - handlers_1.logAndExitProcess(error); - } - else if (!caughtSecondError) { - // two cases for how we can hit this branch: - // - capturing of first error blew up and we just caught the exception from that - // - quit trying to capture, proceed with shutdown - // - a second independent error happened while waiting for first error to capture - // - want to avoid causing premature shutdown before first error capture finishes - // it's hard to immediately tell case 1 from case 2 without doing some fancy/questionable domain stuff - // so let's instead just delay a bit before we proceed with our action here - // in case 1, we just wait a bit unnecessarily but ultimately do the same thing - // in case 2, the delay hopefully made us wait long enough for the capture to finish - // two potential nonideal outcomes: - // nonideal case 1: capturing fails fast, we sit around for a few seconds unnecessarily before proceeding correctly by calling onFatalError - // nonideal case 2: case 2 happens, 1st error is captured but slowly, timeout completes before capture and we treat second error as the sendErr of (nonexistent) failure from trying to capture first error - // note that after hitting this branch, we might catch more errors where (caughtSecondError && !calledFatalError) - // we ignore them - they don't matter to us, we're just waiting for the second error timeout to finish - caughtSecondError = true; - setTimeout(function () { - if (!calledFatalError) { - // it was probably case 1, let's treat err as the sendErr and call onFatalError - calledFatalError = true; - onFatalError(firstError, error); - } - else { - // it was probably case 2, our first error finished capturing while we waited, cool, do nothing - } - }, timeout); // capturing could take at least sendTimeout to fail, plus an arbitrary second for how long it takes to collect surrounding source etc - } - }; - }; - /** - * @inheritDoc - */ - OnUncaughtException.id = 'OnUncaughtException'; - return OnUncaughtException; -}()); -exports.OnUncaughtException = OnUncaughtException; -//# sourceMappingURL=onuncaughtexception.js.map - -/***/ }), -/***/ 87344: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + debug('content-type %j', req.headers['content-type']) -Object.defineProperty(exports, "__esModule", ({ value: true })); -var core_1 = __nccwpck_require__(79212); -var utils_1 = __nccwpck_require__(1620); -var handlers_1 = __nccwpck_require__(45400); -/** Global Promise Rejection handler */ -var OnUnhandledRejection = /** @class */ (function () { - /** - * @inheritDoc - */ - function OnUnhandledRejection(_options) { - if (_options === void 0) { _options = { mode: 'warn' }; } - this._options = _options; - /** - * @inheritDoc - */ - this.name = OnUnhandledRejection.id; + // determine if request should be parsed + if (!shouldParse(req)) { + debug('skip parsing') + next() + return } - /** - * @inheritDoc - */ - OnUnhandledRejection.prototype.setupOnce = function () { - global.process.on('unhandledRejection', this.sendUnhandledPromise.bind(this)); - }; - /** - * Send an exception with reason - * @param reason string - * @param promise promise - */ - // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any - OnUnhandledRejection.prototype.sendUnhandledPromise = function (reason, promise) { - var hub = core_1.getCurrentHub(); - if (!hub.getIntegration(OnUnhandledRejection)) { - this._handleRejection(reason); - return; - } - /* eslint-disable @typescript-eslint/no-unsafe-member-access */ - var context = (promise.domain && promise.domain.sentryContext) || {}; - hub.withScope(function (scope) { - scope.setExtra('unhandledPromiseRejection', true); - // Preserve backwards compatibility with raven-node for now - if (context.user) { - scope.setUser(context.user); - } - if (context.tags) { - scope.setTags(context.tags); - } - if (context.extra) { - scope.setExtras(context.extra); - } - hub.captureException(reason, { originalException: promise }); - }); - /* eslint-disable @typescript-eslint/no-unsafe-member-access */ - this._handleRejection(reason); - }; - /** - * Handler for `mode` option - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - OnUnhandledRejection.prototype._handleRejection = function (reason) { - // https://github.com/nodejs/node/blob/7cf6f9e964aa00772965391c23acda6d71972a9a/lib/internal/process/promises.js#L234-L240 - var rejectionWarning = 'This error originated either by ' + - 'throwing inside of an async function without a catch block, ' + - 'or by rejecting a promise which was not handled with .catch().' + - ' The promise rejected with the reason:'; - /* eslint-disable no-console */ - if (this._options.mode === 'warn') { - utils_1.consoleSandbox(function () { - console.warn(rejectionWarning); - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - console.error(reason && reason.stack ? reason.stack : reason); - }); - } - else if (this._options.mode === 'strict') { - utils_1.consoleSandbox(function () { - console.warn(rejectionWarning); - }); - handlers_1.logAndExitProcess(reason); - } - /* eslint-enable no-console */ - }; - /** - * @inheritDoc - */ - OnUnhandledRejection.id = 'OnUnhandledRejection'; - return OnUnhandledRejection; -}()); -exports.OnUnhandledRejection = OnUnhandledRejection; -//# sourceMappingURL=onunhandledrejection.js.map -/***/ }), + // assert charset per RFC 7159 sec 8.1 + var charset = getCharset(req) || 'utf-8' + if (charset.substr(0, 4) !== 'utf-') { + debug('invalid charset') + next(createError(415, 'unsupported charset "' + charset.toUpperCase() + '"', { + charset: charset, + type: 'charset.unsupported' + })) + return + } -/***/ 84103: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + // read + read(req, res, next, parse, debug, { + encoding: charset, + inflate: inflate, + limit: limit, + verify: verify + }) + } +} -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var core_1 = __nccwpck_require__(79212); -var url_1 = __nccwpck_require__(57310); /** - * Checks whether given url points to Sentry server - * @param url url to verify - */ -function isSentryRequest(url) { - var _a; - var dsn = (_a = core_1.getCurrentHub() - .getClient()) === null || _a === void 0 ? void 0 : _a.getDsn(); - return dsn ? url.includes(dsn.host) : false; + * Create strict violation syntax error matching native error. + * + * @param {string} str + * @param {string} char + * @return {Error} + * @private + */ + +function createStrictSyntaxError (str, char) { + var index = str.indexOf(char) + var partial = str.substring(0, index) + '#' + + try { + JSON.parse(partial); /* istanbul ignore next */ throw new SyntaxError('strict violation') + } catch (e) { + return normalizeJsonSyntaxError(e, { + message: e.message.replace('#', char), + stack: e.stack + }) + } } -exports.isSentryRequest = isSentryRequest; + /** - * Assemble a URL to be used for breadcrumbs and spans. + * Get the first non-whitespace character in a string. * - * @param requestOptions RequestOptions object containing the component parts for a URL - * @returns Fully-formed URL + * @param {string} str + * @return {function} + * @private */ -function extractUrl(requestOptions) { - var protocol = requestOptions.protocol || ''; - var hostname = requestOptions.hostname || requestOptions.host || ''; - // Don't log standard :80 (http) and :443 (https) ports to reduce the noise - var port = !requestOptions.port || requestOptions.port === 80 || requestOptions.port === 443 ? '' : ":" + requestOptions.port; - var path = requestOptions.path ? requestOptions.path : '/'; - return protocol + "//" + hostname + port + path; + +function firstchar (str) { + return FIRST_CHAR_REGEXP.exec(str)[1] } -exports.extractUrl = extractUrl; + /** - * Handle various edge cases in the span description (for spans representing http(s) requests). - * - * @param description current `description` property of the span representing the request - * @param requestOptions Configuration data for the request - * @param Request Request object + * Get the charset of a request. * - * @returns The cleaned description + * @param {object} req + * @api private */ -function cleanSpanDescription(description, requestOptions, request) { - var _a, _b, _c; - // nothing to clean - if (!description) { - return description; - } - // eslint-disable-next-line prefer-const - var _d = tslib_1.__read(description.split(' '), 2), method = _d[0], requestUrl = _d[1]; - // superagent sticks the protocol in a weird place (we check for host because if both host *and* protocol are missing, - // we're likely dealing with an internal route and this doesn't apply) - if (requestOptions.host && !requestOptions.protocol) { - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any - requestOptions.protocol = (_b = (_a = request) === null || _a === void 0 ? void 0 : _a.agent) === null || _b === void 0 ? void 0 : _b.protocol; // worst comes to worst, this is undefined and nothing changes - requestUrl = extractUrl(requestOptions); - } - // internal routes can end up starting with a triple slash rather than a single one - if ((_c = requestUrl) === null || _c === void 0 ? void 0 : _c.startsWith('///')) { - requestUrl = requestUrl.slice(2); - } - return method + " " + requestUrl; + +function getCharset (req) { + try { + return (contentType.parse(req).parameters.charset || '').toLowerCase() + } catch (e) { + return undefined + } } -exports.cleanSpanDescription = cleanSpanDescription; + /** - * Convert a URL object into a RequestOptions object. - * - * Copied from Node's internals (where it's used in http(s).request() and http(s).get()), modified only to use the - * RequestOptions type above. + * Normalize a SyntaxError for JSON.parse. * - * See https://github.com/nodejs/node/blob/master/lib/internal/url.js. + * @param {SyntaxError} error + * @param {object} obj + * @return {SyntaxError} */ -function urlToOptions(url) { - var options = { - protocol: url.protocol, - hostname: typeof url.hostname === 'string' && url.hostname.startsWith('[') ? url.hostname.slice(1, -1) : url.hostname, - hash: url.hash, - search: url.search, - pathname: url.pathname, - path: "" + (url.pathname || '') + (url.search || ''), - href: url.href, - }; - if (url.port !== '') { - options.port = Number(url.port); - } - if (url.username || url.password) { - options.auth = url.username + ":" + url.password; + +function normalizeJsonSyntaxError (error, obj) { + var keys = Object.getOwnPropertyNames(error) + + for (var i = 0; i < keys.length; i++) { + var key = keys[i] + if (key !== 'stack' && key !== 'message') { + delete error[key] } - return options; + } + + // replace stack before message for Node.js 0.10 and below + error.stack = obj.stack.replace(error.message, obj.message) + error.message = obj.message + + return error } -exports.urlToOptions = urlToOptions; + /** - * Normalize inputs to `http(s).request()` and `http(s).get()`. - * - * Legal inputs to `http(s).request()` and `http(s).get()` can take one of ten forms: - * [ RequestOptions | string | URL ], - * [ RequestOptions | string | URL, RequestCallback ], - * [ string | URL, RequestOptions ], and - * [ string | URL, RequestOptions, RequestCallback ]. - * - * This standardizes to one of two forms: [ RequestOptions ] and [ RequestOptions, RequestCallback ]. A similar thing is - * done as the first step of `http(s).request()` and `http(s).get()`; this just does it early so that we can interact - * with the args in a standard way. - * - * @param requestArgs The inputs to `http(s).request()` or `http(s).get()`, as an array. + * Get the simple type checker. * - * @returns Equivalent args of the form [ RequestOptions ] or [ RequestOptions, RequestCallback ]. + * @param {string} type + * @return {function} */ -function normalizeRequestArgs(requestArgs) { - var callback, requestOptions; - // pop off the callback, if there is one - if (typeof requestArgs[requestArgs.length - 1] === 'function') { - callback = requestArgs.pop(); - } - // create a RequestOptions object of whatever's at index 0 - if (typeof requestArgs[0] === 'string') { - requestOptions = urlToOptions(new url_1.URL(requestArgs[0])); - } - else if (requestArgs[0] instanceof url_1.URL) { - requestOptions = urlToOptions(requestArgs[0]); - } - else { - requestOptions = requestArgs[0]; - } - // if the options were given separately from the URL, fold them in - if (requestArgs.length === 2) { - requestOptions = tslib_1.__assign(tslib_1.__assign({}, requestOptions), requestArgs[1]); - } - // return args in standardized form - if (callback) { - return [requestOptions, callback]; - } - else { - return [requestOptions]; - } + +function typeChecker (type) { + return function checkType (req) { + return Boolean(typeis(req, type)) + } } -exports.normalizeRequestArgs = normalizeRequestArgs; -//# sourceMappingURL=http.js.map + /***/ }), -/***/ 19090: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 49609: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; +/*! + * body-parser + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + + -Object.defineProperty(exports, "__esModule", ({ value: true })); -var utils_1 = __nccwpck_require__(1620); -var fs_1 = __nccwpck_require__(57147); -var lru_map_1 = __nccwpck_require__(18424); -var stacktrace = __nccwpck_require__(46276); -var DEFAULT_LINES_OF_CONTEXT = 7; -var FILE_CONTENT_CACHE = new lru_map_1.LRUMap(100); /** - * Resets the file cache. Exists for testing purposes. - * @hidden + * Module dependencies. */ -function resetFileContentCache() { - FILE_CONTENT_CACHE.clear(); -} -exports.resetFileContentCache = resetFileContentCache; -/** JSDoc */ -function getFunction(frame) { - try { - return frame.functionName || frame.typeName + "." + (frame.methodName || ''); - } - catch (e) { - // This seems to happen sometimes when using 'use strict', - // stemming from `getTypeName`. - // [TypeError: Cannot read property 'constructor' of undefined] - return ''; - } -} -var mainModule = ((require.main && require.main.filename && utils_1.dirname(require.main.filename)) || - global.process.cwd()) + "/"; -/** JSDoc */ -function getModule(filename, base) { - if (!base) { - // eslint-disable-next-line no-param-reassign - base = mainModule; + +var bytes = __nccwpck_require__(86966) +var debug = __nccwpck_require__(7471)('body-parser:raw') +var read = __nccwpck_require__(88862) +var typeis = __nccwpck_require__(71159) + +/** + * Module exports. + */ + +module.exports = raw + +/** + * Create a middleware to parse raw bodies. + * + * @param {object} [options] + * @return {function} + * @api public + */ + +function raw (options) { + var opts = options || {} + + var inflate = opts.inflate !== false + var limit = typeof opts.limit !== 'number' + ? bytes.parse(opts.limit || '100kb') + : opts.limit + var type = opts.type || 'application/octet-stream' + var verify = opts.verify || false + + if (verify !== false && typeof verify !== 'function') { + throw new TypeError('option verify must be function') + } + + // create the appropriate type checking function + var shouldParse = typeof type !== 'function' + ? typeChecker(type) + : type + + function parse (buf) { + return buf + } + + return function rawParser (req, res, next) { + if (req._body) { + debug('body already parsed') + next() + return } - // It's specifically a module - var file = utils_1.basename(filename, '.js'); - // eslint-disable-next-line no-param-reassign - filename = utils_1.dirname(filename); - var n = filename.lastIndexOf('/node_modules/'); - if (n > -1) { - // /node_modules/ is 14 chars - return filename.substr(n + 14).replace(/\//g, '.') + ":" + file; + + req.body = req.body || {} + + // skip requests without bodies + if (!typeis.hasBody(req)) { + debug('skip empty body') + next() + return } - // Let's see if it's a part of the main module - // To be a part of main module, it has to share the same base - n = (filename + "/").lastIndexOf(base, 0); - if (n === 0) { - var moduleName = filename.substr(base.length).replace(/\//g, '.'); - if (moduleName) { - moduleName += ':'; - } - moduleName += file; - return moduleName; + + debug('content-type %j', req.headers['content-type']) + + // determine if request should be parsed + if (!shouldParse(req)) { + debug('skip parsing') + next() + return } - return file; + + // read + read(req, res, next, parse, debug, { + encoding: null, + inflate: inflate, + limit: limit, + verify: verify + }) + } } + /** - * This function reads file contents and caches them in a global LRU cache. - * Returns a Promise filepath => content array for all files that we were able to read. + * Get the simple type checker. * - * @param filenames Array of filepaths to read content from. + * @param {string} type + * @return {function} */ -function readSourceFiles(filenames) { - // we're relying on filenames being de-duped already - if (filenames.length === 0) { - return utils_1.SyncPromise.resolve({}); - } - return new utils_1.SyncPromise(function (resolve) { - var sourceFiles = {}; - var count = 0; - var _loop_1 = function (i) { - var filename = filenames[i]; - var cache = FILE_CONTENT_CACHE.get(filename); - // We have a cache hit - if (cache !== undefined) { - // If it's not null (which means we found a file and have a content) - // we set the content and return it later. - if (cache !== null) { - sourceFiles[filename] = cache; - } - // eslint-disable-next-line no-plusplus - count++; - // In any case we want to skip here then since we have a content already or we couldn't - // read the file and don't want to try again. - if (count === filenames.length) { - resolve(sourceFiles); - } - return "continue"; - } - fs_1.readFile(filename, function (err, data) { - var content = err ? null : data.toString(); - sourceFiles[filename] = content; - // We always want to set the cache, even to null which means there was an error reading the file. - // We do not want to try to read the file again. - FILE_CONTENT_CACHE.set(filename, content); - // eslint-disable-next-line no-plusplus - count++; - if (count === filenames.length) { - resolve(sourceFiles); - } - }); - }; - // eslint-disable-next-line @typescript-eslint/prefer-for-of - for (var i = 0; i < filenames.length; i++) { - _loop_1(i); - } - }); + +function typeChecker (type) { + return function checkType (req) { + return Boolean(typeis(req, type)) + } } + + +/***/ }), + +/***/ 26382: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; +/*! + * body-parser + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + + + /** - * @hidden + * Module dependencies. */ -function extractStackFromError(error) { - var stack = stacktrace.parse(error); - if (!stack) { - return []; - } - return stack; -} -exports.extractStackFromError = extractStackFromError; + +var bytes = __nccwpck_require__(86966) +var contentType = __nccwpck_require__(99915) +var debug = __nccwpck_require__(7471)('body-parser:text') +var read = __nccwpck_require__(88862) +var typeis = __nccwpck_require__(71159) + /** - * @hidden + * Module exports. */ -function parseStack(stack, options) { - var filesToRead = []; - var linesOfContext = options && options.frameContextLines !== undefined ? options.frameContextLines : DEFAULT_LINES_OF_CONTEXT; - var frames = stack.map(function (frame) { - var parsedFrame = { - colno: frame.columnNumber, - filename: frame.fileName || '', - function: getFunction(frame), - lineno: frame.lineNumber, - }; - var isInternal = frame.native || - (parsedFrame.filename && - !parsedFrame.filename.startsWith('/') && - !parsedFrame.filename.startsWith('.') && - parsedFrame.filename.indexOf(':\\') !== 1); - // in_app is all that's not an internal Node function or a module within node_modules - // note that isNative appears to return true even for node core libraries - // see https://github.com/getsentry/raven-node/issues/176 - parsedFrame.in_app = - !isInternal && parsedFrame.filename !== undefined && parsedFrame.filename.indexOf('node_modules/') === -1; - // Extract a module name based on the filename - if (parsedFrame.filename) { - parsedFrame.module = getModule(parsedFrame.filename); - if (!isInternal && linesOfContext > 0 && filesToRead.indexOf(parsedFrame.filename) === -1) { - filesToRead.push(parsedFrame.filename); - } - } - return parsedFrame; - }); - // We do an early return if we do not want to fetch context liens - if (linesOfContext <= 0) { - return utils_1.SyncPromise.resolve(frames); - } - try { - return addPrePostContext(filesToRead, frames, linesOfContext); - } - catch (_) { - // This happens in electron for example where we are not able to read files from asar. - // So it's fine, we recover be just returning all frames without pre/post context. - return utils_1.SyncPromise.resolve(frames); - } -} -exports.parseStack = parseStack; + +module.exports = text + /** - * This function tries to read the source files + adding pre and post context (source code) - * to a frame. - * @param filesToRead string[] of filepaths - * @param frames StackFrame[] containg all frames + * Create a middleware to parse text bodies. + * + * @param {object} [options] + * @return {function} + * @api public */ -function addPrePostContext(filesToRead, frames, linesOfContext) { - return new utils_1.SyncPromise(function (resolve) { - return readSourceFiles(filesToRead).then(function (sourceFiles) { - var result = frames.map(function (frame) { - if (frame.filename && sourceFiles[frame.filename]) { - try { - var lines = sourceFiles[frame.filename].split('\n'); - utils_1.addContextToFrame(lines, frame, linesOfContext); - } - catch (e) { - // anomaly, being defensive in case - // unlikely to ever happen in practice but can definitely happen in theory - } - } - return frame; - }); - resolve(result); - }); - }); + +function text (options) { + var opts = options || {} + + var defaultCharset = opts.defaultCharset || 'utf-8' + var inflate = opts.inflate !== false + var limit = typeof opts.limit !== 'number' + ? bytes.parse(opts.limit || '100kb') + : opts.limit + var type = opts.type || 'text/plain' + var verify = opts.verify || false + + if (verify !== false && typeof verify !== 'function') { + throw new TypeError('option verify must be function') + } + + // create the appropriate type checking function + var shouldParse = typeof type !== 'function' + ? typeChecker(type) + : type + + function parse (buf) { + return buf + } + + return function textParser (req, res, next) { + if (req._body) { + debug('body already parsed') + next() + return + } + + req.body = req.body || {} + + // skip requests without bodies + if (!typeis.hasBody(req)) { + debug('skip empty body') + next() + return + } + + debug('content-type %j', req.headers['content-type']) + + // determine if request should be parsed + if (!shouldParse(req)) { + debug('skip parsing') + next() + return + } + + // get charset + var charset = getCharset(req) || defaultCharset + + // read + read(req, res, next, parse, debug, { + encoding: charset, + inflate: inflate, + limit: limit, + verify: verify + }) + } } + /** - * @hidden + * Get the charset of a request. + * + * @param {object} req + * @api private */ -function getExceptionFromError(error, options) { - var name = error.name || error.constructor.name; - var stack = extractStackFromError(error); - return new utils_1.SyncPromise(function (resolve) { - return parseStack(stack, options).then(function (frames) { - var result = { - stacktrace: { - frames: prepareFramesForEvent(frames), - }, - type: name, - value: error.message, - }; - resolve(result); - }); - }); + +function getCharset (req) { + try { + return (contentType.parse(req).parameters.charset || '').toLowerCase() + } catch (e) { + return undefined + } } -exports.getExceptionFromError = getExceptionFromError; + /** - * @hidden + * Get the simple type checker. + * + * @param {string} type + * @return {function} */ -function parseError(error, options) { - return new utils_1.SyncPromise(function (resolve) { - return getExceptionFromError(error, options).then(function (exception) { - resolve({ - exception: { - values: [exception], - }, - }); - }); - }); + +function typeChecker (type) { + return function checkType (req) { + return Boolean(typeis(req, type)) + } } -exports.parseError = parseError; + + +/***/ }), + +/***/ 76100: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; +/*! + * body-parser + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + + + /** - * @hidden + * Module dependencies. + * @private */ -function prepareFramesForEvent(stack) { - if (!stack || !stack.length) { - return []; - } - var localStack = stack; - var firstFrameFunction = localStack[0].function || ''; - if (firstFrameFunction.indexOf('captureMessage') !== -1 || firstFrameFunction.indexOf('captureException') !== -1) { - localStack = localStack.slice(1); - } - // The frame where the crash happened, should be the last entry in the array - return localStack.reverse(); -} -exports.prepareFramesForEvent = prepareFramesForEvent; -//# sourceMappingURL=parsers.js.map -/***/ }), +var bytes = __nccwpck_require__(86966) +var contentType = __nccwpck_require__(99915) +var createError = __nccwpck_require__(95193) +var debug = __nccwpck_require__(7471)('body-parser:urlencoded') +var deprecate = __nccwpck_require__(18883)('body-parser') +var read = __nccwpck_require__(88862) +var typeis = __nccwpck_require__(71159) -/***/ 38836: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/** + * Module exports. + */ + +module.exports = urlencoded -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var core_1 = __nccwpck_require__(79212); -var hub_1 = __nccwpck_require__(6393); -var utils_1 = __nccwpck_require__(1620); -var domain = __nccwpck_require__(13639); -var client_1 = __nccwpck_require__(86147); -var integrations_1 = __nccwpck_require__(72310); -exports.defaultIntegrations = [ - // Common - new core_1.Integrations.InboundFilters(), - new core_1.Integrations.FunctionToString(), - // Native Wrappers - new integrations_1.Console(), - new integrations_1.Http(), - // Global Handlers - new integrations_1.OnUncaughtException(), - new integrations_1.OnUnhandledRejection(), - // Misc - new integrations_1.LinkedErrors(), -]; /** - * The Sentry Node SDK Client. - * - * To use this SDK, call the {@link init} function as early as possible in the - * main entry module. To set context information or send manual events, use the - * provided methods. - * - * @example - * ``` - * - * const { init } = require('@sentry/node'); - * - * init({ - * dsn: '__DSN__', - * // ... - * }); - * ``` - * - * @example - * ``` - * - * const { configureScope } = require('@sentry/node'); - * configureScope((scope: Scope) => { - * scope.setExtra({ battery: 0.7 }); - * scope.setTag({ user_mode: 'admin' }); - * scope.setUser({ id: '4711' }); - * }); - * ``` - * - * @example - * ``` - * - * const { addBreadcrumb } = require('@sentry/node'); - * addBreadcrumb({ - * message: 'My Breadcrumb', - * // ... - * }); - * ``` - * - * @example - * ``` - * - * const Sentry = require('@sentry/node'); - * Sentry.captureMessage('Hello, world!'); - * Sentry.captureException(new Error('Good bye')); - * Sentry.captureEvent({ - * message: 'Manual', - * stacktrace: [ - * // ... - * ], - * }); - * ``` + * Cache of parser modules. + */ + +var parsers = Object.create(null) + +/** + * Create a middleware to parse urlencoded bodies. * - * @see {@link NodeOptions} for documentation on configuration options. + * @param {object} [options] + * @return {function} + * @public */ -function init(options) { - if (options === void 0) { options = {}; } - if (options.defaultIntegrations === undefined) { - options.defaultIntegrations = exports.defaultIntegrations; - } - if (options.dsn === undefined && process.env.SENTRY_DSN) { - options.dsn = process.env.SENTRY_DSN; + +function urlencoded (options) { + var opts = options || {} + + // notice because option default will flip in next major + if (opts.extended === undefined) { + deprecate('undefined extended: provide extended option') + } + + var extended = opts.extended !== false + var inflate = opts.inflate !== false + var limit = typeof opts.limit !== 'number' + ? bytes.parse(opts.limit || '100kb') + : opts.limit + var type = opts.type || 'application/x-www-form-urlencoded' + var verify = opts.verify || false + + if (verify !== false && typeof verify !== 'function') { + throw new TypeError('option verify must be function') + } + + // create the appropriate query parser + var queryparse = extended + ? extendedparser(opts) + : simpleparser(opts) + + // create the appropriate type checking function + var shouldParse = typeof type !== 'function' + ? typeChecker(type) + : type + + function parse (body) { + return body.length + ? queryparse(body) + : {} + } + + return function urlencodedParser (req, res, next) { + if (req._body) { + debug('body already parsed') + next() + return } - if (options.release === undefined) { - var global_1 = utils_1.getGlobalObject(); - // Prefer env var over global - if (process.env.SENTRY_RELEASE) { - options.release = process.env.SENTRY_RELEASE; - } - // This supports the variable that sentry-webpack-plugin injects - else if (global_1.SENTRY_RELEASE && global_1.SENTRY_RELEASE.id) { - options.release = global_1.SENTRY_RELEASE.id; - } + + req.body = req.body || {} + + // skip requests without bodies + if (!typeis.hasBody(req)) { + debug('skip empty body') + next() + return } - if (options.environment === undefined && process.env.SENTRY_ENVIRONMENT) { - options.environment = process.env.SENTRY_ENVIRONMENT; + + debug('content-type %j', req.headers['content-type']) + + // determine if request should be parsed + if (!shouldParse(req)) { + debug('skip parsing') + next() + return } - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any - if (domain.active) { - hub_1.setHubOnCarrier(hub_1.getMainCarrier(), core_1.getCurrentHub()); + + // assert charset + var charset = getCharset(req) || 'utf-8' + if (charset !== 'utf-8') { + debug('invalid charset') + next(createError(415, 'unsupported charset "' + charset.toUpperCase() + '"', { + charset: charset, + type: 'charset.unsupported' + })) + return } - core_1.initAndBind(client_1.NodeClient, options); + + // read + read(req, res, next, parse, debug, { + debug: debug, + encoding: charset, + inflate: inflate, + limit: limit, + verify: verify + }) + } } -exports.init = init; + /** - * This is the getter for lastEventId. + * Get the extended query parser. * - * @returns The last event id of a captured event. + * @param {object} options */ -function lastEventId() { - return core_1.getCurrentHub().lastEventId(); + +function extendedparser (options) { + var parameterLimit = options.parameterLimit !== undefined + ? options.parameterLimit + : 1000 + var parse = parser('qs') + + if (isNaN(parameterLimit) || parameterLimit < 1) { + throw new TypeError('option parameterLimit must be a positive number') + } + + if (isFinite(parameterLimit)) { + parameterLimit = parameterLimit | 0 + } + + return function queryparse (body) { + var paramCount = parameterCount(body, parameterLimit) + + if (paramCount === undefined) { + debug('too many parameters') + throw createError(413, 'too many parameters', { + type: 'parameters.too.many' + }) + } + + var arrayLimit = Math.max(100, paramCount) + + debug('parse extended urlencoding') + return parse(body, { + allowPrototypes: true, + arrayLimit: arrayLimit, + depth: Infinity, + parameterLimit: parameterLimit + }) + } } -exports.lastEventId = lastEventId; + /** - * A promise that resolves when all current events have been sent. - * If you provide a timeout and the queue takes longer to drain the promise returns false. + * Get the charset of a request. * - * @param timeout Maximum time in ms the client should wait. + * @param {object} req + * @api private */ -function flush(timeout) { - return tslib_1.__awaiter(this, void 0, void 0, function () { - var client; - return tslib_1.__generator(this, function (_a) { - client = core_1.getCurrentHub().getClient(); - if (client) { - return [2 /*return*/, client.flush(timeout)]; - } - return [2 /*return*/, Promise.reject(false)]; - }); - }); + +function getCharset (req) { + try { + return (contentType.parse(req).parameters.charset || '').toLowerCase() + } catch (e) { + return undefined + } } -exports.flush = flush; + /** - * A promise that resolves when all current events have been sent. - * If you provide a timeout and the queue takes longer to drain the promise returns false. + * Count the number of parameters, stopping once limit reached * - * @param timeout Maximum time in ms the client should wait. + * @param {string} body + * @param {number} limit + * @api private */ -function close(timeout) { - return tslib_1.__awaiter(this, void 0, void 0, function () { - var client; - return tslib_1.__generator(this, function (_a) { - client = core_1.getCurrentHub().getClient(); - if (client) { - return [2 /*return*/, client.close(timeout)]; - } - return [2 /*return*/, Promise.reject(false)]; - }); - }); -} -exports.close = close; -//# sourceMappingURL=sdk.js.map -/***/ }), +function parameterCount (body, limit) { + var count = 0 + var index = 0 -/***/ 46276: -/***/ ((__unused_webpack_module, exports) => { + while ((index = body.indexOf('&', index)) !== -1) { + count++ + index++ + + if (count === limit) { + return undefined + } + } + + return count +} /** - * stack-trace - Parses node.js stack traces - * - * This was originally forked to fix this issue: - * https://github.com/felixge/node-stack-trace/issues/31 - * - * Mar 19,2019 - #4fd379e + * Get parser for module name dynamically. * - * https://github.com/felixge/node-stack-trace/ - * @license MIT + * @param {string} name + * @return {function} + * @api private */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -/** Extracts StackFrames from the Error */ -function parse(err) { - if (!err.stack) { - return []; - } - var lines = err.stack.split('\n').slice(1); - return lines - .map(function (line) { - if (line.match(/^\s*[-]{4,}$/)) { - return { - columnNumber: null, - fileName: line, - functionName: null, - lineNumber: null, - methodName: null, - native: null, - typeName: null, - }; - } - var lineMatch = line.match(/at (?:(.+?)\s+\()?(?:(.+?):(\d+)(?::(\d+))?|([^)]+))\)?/); - if (!lineMatch) { - return undefined; - } - var object = null; - var method = null; - var functionName = null; - var typeName = null; - var methodName = null; - var isNative = lineMatch[5] === 'native'; - if (lineMatch[1]) { - functionName = lineMatch[1]; - var methodStart = functionName.lastIndexOf('.'); - if (functionName[methodStart - 1] === '.') { - // eslint-disable-next-line no-plusplus - methodStart--; - } - if (methodStart > 0) { - object = functionName.substr(0, methodStart); - method = functionName.substr(methodStart + 1); - var objectEnd = object.indexOf('.Module'); - if (objectEnd > 0) { - functionName = functionName.substr(objectEnd + 1); - object = object.substr(0, objectEnd); - } - } - typeName = null; - } - if (method) { - typeName = object; - methodName = method; - } - if (method === '') { - methodName = null; - functionName = null; - } - var properties = { - columnNumber: parseInt(lineMatch[4], 10) || null, - fileName: lineMatch[2] || null, - functionName: functionName, - lineNumber: parseInt(lineMatch[3], 10) || null, - methodName: methodName, - native: isNative, - typeName: typeName, - }; - return properties; - }) - .filter(function (callSite) { return !!callSite; }); + +function parser (name) { + var mod = parsers[name] + + if (mod !== undefined) { + return mod.parse + } + + // this uses a switch for static require analysis + switch (name) { + case 'qs': + mod = __nccwpck_require__(22760) + break + case 'querystring': + mod = __nccwpck_require__(63477) + break + } + + // store to prevent invoking require() + parsers[name] = mod + + return mod.parse } -exports.parse = parse; -//# sourceMappingURL=stacktrace.js.map -/***/ }), +/** + * Get the simple query parser. + * + * @param {object} options + */ -/***/ 43240: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +function simpleparser (options) { + var parameterLimit = options.parameterLimit !== undefined + ? options.parameterLimit + : 1000 + var parse = parser('querystring') -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var core_1 = __nccwpck_require__(79212); -var types_1 = __nccwpck_require__(83789); -var utils_1 = __nccwpck_require__(1620); -var fs = __nccwpck_require__(57147); -var url = __nccwpck_require__(57310); -var version_1 = __nccwpck_require__(31271); -/** Base Transport class implementation */ -var BaseTransport = /** @class */ (function () { - /** Create instance and set this.dsn */ - function BaseTransport(options) { - this.options = options; - /** A simple buffer holding all requests. */ - this._buffer = new utils_1.PromiseBuffer(30); - /** Locks transport after receiving 429 response */ - this._disabledUntil = new Date(Date.now()); - this._api = new core_1.API(options.dsn); - } - /** - * @inheritDoc - */ - BaseTransport.prototype.sendEvent = function (_) { - throw new utils_1.SentryError('Transport Class has to implement `sendEvent` method.'); - }; - /** - * @inheritDoc - */ - BaseTransport.prototype.close = function (timeout) { - return this._buffer.drain(timeout); - }; - /** Returns a build request option object used by request */ - BaseTransport.prototype._getRequestOptions = function (uri) { - var headers = tslib_1.__assign(tslib_1.__assign({}, this._api.getRequestHeaders(version_1.SDK_NAME, version_1.SDK_VERSION)), this.options.headers); - var hostname = uri.hostname, pathname = uri.pathname, port = uri.port, protocol = uri.protocol; - // See https://github.com/nodejs/node/blob/38146e717fed2fabe3aacb6540d839475e0ce1c6/lib/internal/url.js#L1268-L1290 - // We ignore the query string on purpose - var path = "" + pathname; - return tslib_1.__assign({ agent: this.client, headers: headers, - hostname: hostname, method: 'POST', path: path, - port: port, - protocol: protocol }, (this.options.caCerts && { - ca: fs.readFileSync(this.options.caCerts), - })); - }; - /** JSDoc */ - BaseTransport.prototype._sendWithModule = function (httpModule, event) { - return tslib_1.__awaiter(this, void 0, void 0, function () { - var _this = this; - return tslib_1.__generator(this, function (_a) { - if (new Date(Date.now()) < this._disabledUntil) { - return [2 /*return*/, Promise.reject(new utils_1.SentryError("Transport locked till " + this._disabledUntil + " due to too many requests."))]; - } - if (!this._buffer.isReady()) { - return [2 /*return*/, Promise.reject(new utils_1.SentryError('Not adding Promise due to buffer limit reached.'))]; - } - return [2 /*return*/, this._buffer.add(new Promise(function (resolve, reject) { - var sentryReq = core_1.eventToSentryRequest(event, _this._api); - var options = _this._getRequestOptions(new url.URL(sentryReq.url)); - var req = httpModule.request(options, function (res) { - var statusCode = res.statusCode || 500; - var status = types_1.Status.fromHttpCode(statusCode); - res.setEncoding('utf8'); - if (status === types_1.Status.Success) { - resolve({ status: status }); - } - else { - if (status === types_1.Status.RateLimit) { - var now = Date.now(); - /** - * "Key-value pairs of header names and values. Header names are lower-cased." - * https://nodejs.org/api/http.html#http_message_headers - */ - var retryAfterHeader = res.headers ? res.headers['retry-after'] : ''; - retryAfterHeader = (Array.isArray(retryAfterHeader) ? retryAfterHeader[0] : retryAfterHeader); - _this._disabledUntil = new Date(now + utils_1.parseRetryAfterHeader(now, retryAfterHeader)); - utils_1.logger.warn("Too many requests, backing off till: " + _this._disabledUntil); - } - var rejectionMessage = "HTTP Error (" + statusCode + ")"; - if (res.headers && res.headers['x-sentry-error']) { - rejectionMessage += ": " + res.headers['x-sentry-error']; - } - reject(new utils_1.SentryError(rejectionMessage)); - } - // Force the socket to drain - res.on('data', function () { - // Drain - }); - res.on('end', function () { - // Drain - }); - }); - req.on('error', reject); - req.end(sentryReq.body); - }))]; - }); - }); - }; - return BaseTransport; -}()); -exports.BaseTransport = BaseTransport; -//# sourceMappingURL=base.js.map + if (isNaN(parameterLimit) || parameterLimit < 1) { + throw new TypeError('option parameterLimit must be a positive number') + } -/***/ }), + if (isFinite(parameterLimit)) { + parameterLimit = parameterLimit | 0 + } -/***/ 84490: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + return function queryparse (body) { + var paramCount = parameterCount(body, parameterLimit) -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var utils_1 = __nccwpck_require__(1620); -var http = __nccwpck_require__(13685); -var base_1 = __nccwpck_require__(43240); -/** Node http module transport */ -var HTTPTransport = /** @class */ (function (_super) { - tslib_1.__extends(HTTPTransport, _super); - /** Create a new instance and set this.agent */ - function HTTPTransport(options) { - var _this = _super.call(this, options) || this; - _this.options = options; - var proxy = options.httpProxy || process.env.http_proxy; - _this.module = http; - _this.client = proxy - ? new (__nccwpck_require__(77219))(proxy) - : new http.Agent({ keepAlive: false, maxSockets: 30, timeout: 2000 }); - return _this; + if (paramCount === undefined) { + debug('too many parameters') + throw createError(413, 'too many parameters', { + type: 'parameters.too.many' + }) } - /** - * @inheritDoc - */ - HTTPTransport.prototype.sendEvent = function (event) { - if (!this.module) { - throw new utils_1.SentryError('No module available in HTTPTransport'); - } - return this._sendWithModule(this.module, event); - }; - return HTTPTransport; -}(base_1.BaseTransport)); -exports.HTTPTransport = HTTPTransport; -//# sourceMappingURL=http.js.map -/***/ }), + debug('parse urlencoding') + return parse(body, undefined, undefined, { maxKeys: parameterLimit }) + } +} -/***/ 68621: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/** + * Get the simple type checker. + * + * @param {string} type + * @return {function} + */ + +function typeChecker (type) { + return function checkType (req) { + return Boolean(typeis(req, type)) + } +} -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var utils_1 = __nccwpck_require__(1620); -var https = __nccwpck_require__(95687); -var base_1 = __nccwpck_require__(43240); -/** Node https module transport */ -var HTTPSTransport = /** @class */ (function (_super) { - tslib_1.__extends(HTTPSTransport, _super); - /** Create a new instance and set this.agent */ - function HTTPSTransport(options) { - var _this = _super.call(this, options) || this; - _this.options = options; - var proxy = options.httpsProxy || options.httpProxy || process.env.https_proxy || process.env.http_proxy; - _this.module = https; - _this.client = proxy - ? new (__nccwpck_require__(77219))(proxy) - : new https.Agent({ keepAlive: false, maxSockets: 30, timeout: 2000 }); - return _this; - } - /** - * @inheritDoc - */ - HTTPSTransport.prototype.sendEvent = function (event) { - if (!this.module) { - throw new utils_1.SentryError('No module available in HTTPSTransport'); - } - return this._sendWithModule(this.module, event); - }; - return HTTPSTransport; -}(base_1.BaseTransport)); -exports.HTTPSTransport = HTTPSTransport; -//# sourceMappingURL=https.js.map /***/ }), -/***/ 21437: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 15377: +/***/ ((module, exports, __nccwpck_require__) => { -Object.defineProperty(exports, "__esModule", ({ value: true })); -var base_1 = __nccwpck_require__(43240); -exports.BaseTransport = base_1.BaseTransport; -var http_1 = __nccwpck_require__(84490); -exports.HTTPTransport = http_1.HTTPTransport; -var https_1 = __nccwpck_require__(68621); -exports.HTTPSTransport = https_1.HTTPSTransport; -//# sourceMappingURL=index.js.map +/** + * This is the web browser implementation of `debug()`. + * + * Expose `debug()` as the module. + */ -/***/ }), +exports = module.exports = __nccwpck_require__(22552); +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(); -/***/ 31271: -/***/ ((__unused_webpack_module, exports) => { +/** + * Colors. + */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.SDK_NAME = 'sentry.javascript.node'; -exports.SDK_VERSION = '5.29.2'; -//# sourceMappingURL=version.js.map +exports.colors = [ + 'lightseagreen', + 'forestgreen', + 'goldenrod', + 'dodgerblue', + 'darkorchid', + 'crimson' +]; -/***/ }), +/** + * 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 + */ -/***/ 81867: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +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+)/)); +} -Object.defineProperty(exports, "__esModule", ({ value: true })); -var utils_1 = __nccwpck_require__(1620); -var spanstatus_1 = __nccwpck_require__(58522); -var utils_2 = __nccwpck_require__(31386); -var global = utils_1.getGlobalObject(); /** - * Add a listener that cancels and finishes a transaction when the global - * document is hidden. + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. */ -function registerBackgroundTabDetection() { - if (global && global.document) { - global.document.addEventListener('visibilitychange', function () { - var activeTransaction = utils_2.getActiveTransaction(); - if (global.document.hidden && activeTransaction) { - utils_1.logger.log("[Tracing] Transaction: " + spanstatus_1.SpanStatus.Cancelled + " -> since tab moved to the background, op: " + activeTransaction.op); - // We should not set status if it is already set, this prevent important statuses like - // error or data loss from being overwritten on transaction. - if (!activeTransaction.status) { - activeTransaction.setStatus(spanstatus_1.SpanStatus.Cancelled); - } - activeTransaction.setTag('visibilitychange', 'document.hidden'); - activeTransaction.finish(); - } - }); - } - else { - utils_1.logger.warn('[Tracing] Could not set up background tab detection due to lack of global document'); + +exports.formatters.j = function(v) { + try { + return JSON.stringify(v); + } catch (err) { + return '[UnexpectedJSONParseError]: ' + err.message; + } +}; + + +/** + * Colorize log arguments if enabled. + * + * @api public + */ + +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; + + 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); } -exports.registerBackgroundTabDetection = registerBackgroundTabDetection; -//# sourceMappingURL=backgroundtab.js.map -/***/ }), +/** + * Invokes `console.log()` when available. + * No-op when `console.log` is not a "function". + * + * @api public + */ -/***/ 33577: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +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); +} -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var utils_1 = __nccwpck_require__(1620); -var hubextensions_1 = __nccwpck_require__(31409); -var idletransaction_1 = __nccwpck_require__(2171); -var spanstatus_1 = __nccwpck_require__(58522); -var utils_2 = __nccwpck_require__(31386); -var backgroundtab_1 = __nccwpck_require__(81867); -var metrics_1 = __nccwpck_require__(68451); -var request_1 = __nccwpck_require__(27854); -var router_1 = __nccwpck_require__(40348); -exports.DEFAULT_MAX_TRANSACTION_DURATION_SECONDS = 600; -var DEFAULT_BROWSER_TRACING_OPTIONS = tslib_1.__assign({ idleTimeout: idletransaction_1.DEFAULT_IDLE_TIMEOUT, markBackgroundTransactions: true, maxTransactionDuration: exports.DEFAULT_MAX_TRANSACTION_DURATION_SECONDS, routingInstrumentation: router_1.defaultRoutingInstrumentation, startTransactionOnLocationChange: true, startTransactionOnPageLoad: true }, request_1.defaultRequestInstrumentationOptions); /** - * The Browser Tracing integration automatically instruments browser pageload/navigation - * actions as transactions, and captures requests, metrics and errors as spans. + * Save `namespaces`. * - * The integration can be configured with a variety of options, and can be extended to use - * any routing library. This integration uses {@see IdleTransaction} to create transactions. + * @param {String} namespaces + * @api private */ -var BrowserTracing = /** @class */ (function () { - function BrowserTracing(_options) { - /** - * @inheritDoc - */ - this.name = BrowserTracing.id; - this._metrics = new metrics_1.MetricsInstrumentation(); - this._emitOptionsWarning = false; - var tracingOrigins = request_1.defaultRequestInstrumentationOptions.tracingOrigins; - // NOTE: Logger doesn't work in constructors, as it's initialized after integrations instances - if (_options && - _options.tracingOrigins && - Array.isArray(_options.tracingOrigins) && - _options.tracingOrigins.length !== 0) { - tracingOrigins = _options.tracingOrigins; - } - else { - this._emitOptionsWarning = true; - } - this.options = tslib_1.__assign(tslib_1.__assign(tslib_1.__assign({}, DEFAULT_BROWSER_TRACING_OPTIONS), _options), { tracingOrigins: tracingOrigins }); + +function save(namespaces) { + try { + if (null == namespaces) { + exports.storage.removeItem('debug'); + } else { + exports.storage.debug = namespaces; } - /** - * @inheritDoc - */ - BrowserTracing.prototype.setupOnce = function (_, getCurrentHub) { - var _this = this; - this._getCurrentHub = getCurrentHub; - if (this._emitOptionsWarning) { - utils_1.logger.warn('[Tracing] You need to define `tracingOrigins` in the options. Set an array of urls or patterns to trace.'); - utils_1.logger.warn("[Tracing] We added a reasonable default for you: " + request_1.defaultRequestInstrumentationOptions.tracingOrigins); - } - // eslint-disable-next-line @typescript-eslint/unbound-method - var _a = this.options, routingInstrumentation = _a.routingInstrumentation, startTransactionOnLocationChange = _a.startTransactionOnLocationChange, startTransactionOnPageLoad = _a.startTransactionOnPageLoad, markBackgroundTransactions = _a.markBackgroundTransactions, traceFetch = _a.traceFetch, traceXHR = _a.traceXHR, tracingOrigins = _a.tracingOrigins, shouldCreateSpanForRequest = _a.shouldCreateSpanForRequest; - routingInstrumentation(function (context) { return _this._createRouteTransaction(context); }, startTransactionOnPageLoad, startTransactionOnLocationChange); - if (markBackgroundTransactions) { - backgroundtab_1.registerBackgroundTabDetection(); - } - request_1.registerRequestInstrumentation({ traceFetch: traceFetch, traceXHR: traceXHR, tracingOrigins: tracingOrigins, shouldCreateSpanForRequest: shouldCreateSpanForRequest }); - }; - /** Create routing idle transaction. */ - BrowserTracing.prototype._createRouteTransaction = function (context) { - var _this = this; - if (!this._getCurrentHub) { - utils_1.logger.warn("[Tracing] Did not create " + context.op + " transaction because _getCurrentHub is invalid."); - return undefined; - } - // eslint-disable-next-line @typescript-eslint/unbound-method - var _a = this.options, beforeNavigate = _a.beforeNavigate, idleTimeout = _a.idleTimeout, maxTransactionDuration = _a.maxTransactionDuration; - var parentContextFromHeader = context.op === 'pageload' ? getHeaderContext() : undefined; - var expandedContext = tslib_1.__assign(tslib_1.__assign(tslib_1.__assign({}, context), parentContextFromHeader), { trimEnd: true }); - var modifiedContext = typeof beforeNavigate === 'function' ? beforeNavigate(expandedContext) : expandedContext; - // For backwards compatibility reasons, beforeNavigate can return undefined to "drop" the transaction (prevent it - // from being sent to Sentry). - var finalContext = modifiedContext === undefined ? tslib_1.__assign(tslib_1.__assign({}, expandedContext), { sampled: false }) : modifiedContext; - if (finalContext.sampled === false) { - utils_1.logger.log("[Tracing] Will not send " + finalContext.op + " transaction because of beforeNavigate."); - } - var hub = this._getCurrentHub(); - var idleTransaction = hubextensions_1.startIdleTransaction(hub, finalContext, idleTimeout, true); - utils_1.logger.log("[Tracing] Starting " + finalContext.op + " transaction on scope"); - idleTransaction.registerBeforeFinishCallback(function (transaction, endTimestamp) { - _this._metrics.addPerformanceEntries(transaction); - adjustTransactionDuration(utils_2.secToMs(maxTransactionDuration), transaction, endTimestamp); - }); - return idleTransaction; - }; - /** - * @inheritDoc - */ - BrowserTracing.id = 'BrowserTracing'; - return BrowserTracing; -}()); -exports.BrowserTracing = BrowserTracing; + } catch(e) {} +} + /** - * Gets transaction context from a sentry-trace meta. + * 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; + } + + return r; +} + +/** + * Enable namespaces listed in `localStorage.debug` initially. + */ + +exports.enable(load()); + +/** + * Localstorage attempts to return the localstorage. * - * @returns Transaction context data from the header or undefined if there's no header or the header is malformed + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. + * + * @return {LocalStorage} + * @api private */ -function getHeaderContext() { - var header = getMetaContent('sentry-trace'); - if (header) { - return utils_2.extractTraceparentData(header); - } - return undefined; -} -exports.getHeaderContext = getHeaderContext; -/** Returns the value of a meta tag */ -function getMetaContent(metaName) { - var el = document.querySelector("meta[name=" + metaName + "]"); - return el ? el.getAttribute('content') : null; -} -exports.getMetaContent = getMetaContent; -/** Adjusts transaction value based on max transaction duration */ -function adjustTransactionDuration(maxDuration, transaction, endTimestamp) { - var diff = endTimestamp - transaction.startTimestamp; - var isOutdatedTransaction = endTimestamp && (diff > maxDuration || diff < 0); - if (isOutdatedTransaction) { - transaction.setStatus(spanstatus_1.SpanStatus.DeadlineExceeded); - transaction.setTag('maxTransactionDurationExceeded', 'true'); - } + +function localstorage() { + try { + return window.localStorage; + } catch (e) {} } -//# sourceMappingURL=browsertracing.js.map + /***/ }), -/***/ 71425: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 22552: +/***/ ((module, exports, __nccwpck_require__) => { -Object.defineProperty(exports, "__esModule", ({ value: true })); -var browsertracing_1 = __nccwpck_require__(33577); -exports.BrowserTracing = browsertracing_1.BrowserTracing; -//# sourceMappingURL=index.js.map -/***/ }), +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + * + * Expose `debug()` as the module. + */ -/***/ 68451: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; +exports.coerce = coerce; +exports.disable = disable; +exports.enable = enable; +exports.enabled = enabled; +exports.humanize = __nccwpck_require__(73233); -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var utils_1 = __nccwpck_require__(1620); -var utils_2 = __nccwpck_require__(31386); -var getCLS_1 = __nccwpck_require__(56982); -var getFID_1 = __nccwpck_require__(82496); -var getLCP_1 = __nccwpck_require__(99382); -var getTTFB_1 = __nccwpck_require__(55909); -var getFirstHidden_1 = __nccwpck_require__(88493); -var global = utils_1.getGlobalObject(); -/** Class tracking metrics */ -var MetricsInstrumentation = /** @class */ (function () { - function MetricsInstrumentation() { - this._measurements = {}; - this._performanceCursor = 0; - if (global && global.performance) { - if (global.performance.mark) { - global.performance.mark('sentry-tracing-init'); - } - this._trackCLS(); - this._trackLCP(); - this._trackFID(); - this._trackTTFB(); - } - } - /** Add performance related spans to a transaction */ - MetricsInstrumentation.prototype.addPerformanceEntries = function (transaction) { - var _this = this; - if (!global || !global.performance || !global.performance.getEntries || !utils_1.browserPerformanceTimeOrigin) { - // Gatekeeper if performance API not available - return; - } - utils_1.logger.log('[Tracing] Adding & adjusting spans using Performance API'); - var timeOrigin = utils_2.msToSec(utils_1.browserPerformanceTimeOrigin); - var entryScriptSrc; - if (global.document) { - // eslint-disable-next-line @typescript-eslint/prefer-for-of - for (var i = 0; i < document.scripts.length; i++) { - // We go through all scripts on the page and look for 'data-entry' - // We remember the name and measure the time between this script finished loading and - // our mark 'sentry-tracing-init' - if (document.scripts[i].dataset.entry === 'true') { - entryScriptSrc = document.scripts[i].src; - break; - } - } - } - var entryScriptStartTimestamp; - var tracingInitMarkStartTime; - global.performance - .getEntries() - .slice(this._performanceCursor) - .forEach(function (entry) { - var startTime = utils_2.msToSec(entry.startTime); - var duration = utils_2.msToSec(entry.duration); - if (transaction.op === 'navigation' && timeOrigin + startTime < transaction.startTimestamp) { - return; - } - switch (entry.entryType) { - case 'navigation': - addNavigationSpans(transaction, entry, timeOrigin); - break; - case 'mark': - case 'paint': - case 'measure': { - var startTimestamp = addMeasureSpans(transaction, entry, startTime, duration, timeOrigin); - if (tracingInitMarkStartTime === undefined && entry.name === 'sentry-tracing-init') { - tracingInitMarkStartTime = startTimestamp; - } - // capture web vitals - var firstHidden = getFirstHidden_1.getFirstHidden(); - // Only report if the page wasn't hidden prior to the web vital. - var shouldRecord = entry.startTime < firstHidden.timeStamp; - if (entry.name === 'first-paint' && shouldRecord) { - utils_1.logger.log('[Measurements] Adding FP'); - _this._measurements['fp'] = { value: entry.startTime }; - _this._measurements['mark.fp'] = { value: startTimestamp }; - } - if (entry.name === 'first-contentful-paint' && shouldRecord) { - utils_1.logger.log('[Measurements] Adding FCP'); - _this._measurements['fcp'] = { value: entry.startTime }; - _this._measurements['mark.fcp'] = { value: startTimestamp }; - } - break; - } - case 'resource': { - var resourceName = entry.name.replace(window.location.origin, ''); - var endTimestamp = addResourceSpans(transaction, entry, resourceName, startTime, duration, timeOrigin); - // We remember the entry script end time to calculate the difference to the first init mark - if (entryScriptStartTimestamp === undefined && (entryScriptSrc || '').indexOf(resourceName) > -1) { - entryScriptStartTimestamp = endTimestamp; - } - break; - } - default: - // Ignore other entry types. - } - }); - if (entryScriptStartTimestamp !== undefined && tracingInitMarkStartTime !== undefined) { - _startChild(transaction, { - description: 'evaluation', - endTimestamp: tracingInitMarkStartTime, - op: 'script', - startTimestamp: entryScriptStartTimestamp, - }); - } - this._performanceCursor = Math.max(performance.getEntries().length - 1, 0); - this._trackNavigator(transaction); - // Measurements are only available for pageload transactions - if (transaction.op === 'pageload') { - // normalize applicable web vital values to be relative to transaction.startTimestamp - var timeOrigin_1 = utils_2.msToSec(utils_1.browserPerformanceTimeOrigin); - ['fcp', 'fp', 'lcp', 'ttfb'].forEach(function (name) { - if (!_this._measurements[name] || timeOrigin_1 >= transaction.startTimestamp) { - return; - } - // The web vitals, fcp, fp, lcp, and ttfb, all measure relative to timeOrigin. - // Unfortunately, timeOrigin is not captured within the transaction span data, so these web vitals will need - // to be adjusted to be relative to transaction.startTimestamp. - var oldValue = _this._measurements[name].value; - var measurementTimestamp = timeOrigin_1 + utils_2.msToSec(oldValue); - // normalizedValue should be in milliseconds - var normalizedValue = Math.abs((measurementTimestamp - transaction.startTimestamp) * 1000); - var delta = normalizedValue - oldValue; - utils_1.logger.log("[Measurements] Normalized " + name + " from " + oldValue + " to " + normalizedValue + " (" + delta + ")"); - _this._measurements[name].value = normalizedValue; - }); - if (this._measurements['mark.fid'] && this._measurements['fid']) { - // create span for FID - _startChild(transaction, { - description: 'first input delay', - endTimestamp: this._measurements['mark.fid'].value + utils_2.msToSec(this._measurements['fid'].value), - op: 'web.vitals', - startTimestamp: this._measurements['mark.fid'].value, - }); - } - transaction.setMeasurements(this._measurements); - } - }; - /** Starts tracking the Cumulative Layout Shift on the current page. */ - MetricsInstrumentation.prototype._trackCLS = function () { - var _this = this; - getCLS_1.getCLS(function (metric) { - var entry = metric.entries.pop(); - if (!entry) { - return; - } - utils_1.logger.log('[Measurements] Adding CLS'); - _this._measurements['cls'] = { value: metric.value }; - }); - }; - /** - * Capture the information of the user agent. - */ - MetricsInstrumentation.prototype._trackNavigator = function (transaction) { - var navigator = global.navigator; - if (!navigator) { - return; - } - // track network connectivity - var connection = navigator.connection; - if (connection) { - if (connection.effectiveType) { - transaction.setTag('effectiveConnectionType', connection.effectiveType); - } - if (connection.type) { - transaction.setTag('connectionType', connection.type); - } - if (isMeasurementValue(connection.rtt)) { - this._measurements['connection.rtt'] = { value: connection.rtt }; - } - if (isMeasurementValue(connection.downlink)) { - this._measurements['connection.downlink'] = { value: connection.downlink }; - } - } - if (isMeasurementValue(navigator.deviceMemory)) { - transaction.setTag('deviceMemory', String(navigator.deviceMemory)); - } - if (isMeasurementValue(navigator.hardwareConcurrency)) { - transaction.setTag('hardwareConcurrency', String(navigator.hardwareConcurrency)); - } - }; - /** Starts tracking the Largest Contentful Paint on the current page. */ - MetricsInstrumentation.prototype._trackLCP = function () { - var _this = this; - getLCP_1.getLCP(function (metric) { - var entry = metric.entries.pop(); - if (!entry) { - return; - } - var timeOrigin = utils_2.msToSec(performance.timeOrigin); - var startTime = utils_2.msToSec(entry.startTime); - utils_1.logger.log('[Measurements] Adding LCP'); - _this._measurements['lcp'] = { value: metric.value }; - _this._measurements['mark.lcp'] = { value: timeOrigin + startTime }; - }); - }; - /** Starts tracking the First Input Delay on the current page. */ - MetricsInstrumentation.prototype._trackFID = function () { - var _this = this; - getFID_1.getFID(function (metric) { - var entry = metric.entries.pop(); - if (!entry) { - return; - } - var timeOrigin = utils_2.msToSec(performance.timeOrigin); - var startTime = utils_2.msToSec(entry.startTime); - utils_1.logger.log('[Measurements] Adding FID'); - _this._measurements['fid'] = { value: metric.value }; - _this._measurements['mark.fid'] = { value: timeOrigin + startTime }; - }); - }; - /** Starts tracking the Time to First Byte on the current page. */ - MetricsInstrumentation.prototype._trackTTFB = function () { - var _this = this; - getTTFB_1.getTTFB(function (metric) { - var _a; - var entry = metric.entries.pop(); - if (!entry) { - return; - } - utils_1.logger.log('[Measurements] Adding TTFB'); - _this._measurements['ttfb'] = { value: metric.value }; - // Capture the time spent making the request and receiving the first byte of the response - var requestTime = metric.value - (_a = metric.entries[0], (_a !== null && _a !== void 0 ? _a : entry)).requestStart; - _this._measurements['ttfb.requestTime'] = { value: requestTime }; - }); - }; - return MetricsInstrumentation; -}()); -exports.MetricsInstrumentation = MetricsInstrumentation; -/** Instrument navigation entries */ -function addNavigationSpans(transaction, entry, timeOrigin) { - addPerformanceNavigationTiming(transaction, entry, 'unloadEvent', timeOrigin); - addPerformanceNavigationTiming(transaction, entry, 'redirect', timeOrigin); - addPerformanceNavigationTiming(transaction, entry, 'domContentLoadedEvent', timeOrigin); - addPerformanceNavigationTiming(transaction, entry, 'loadEvent', timeOrigin); - addPerformanceNavigationTiming(transaction, entry, 'connect', timeOrigin); - addPerformanceNavigationTiming(transaction, entry, 'secureConnection', timeOrigin, 'connectEnd'); - addPerformanceNavigationTiming(transaction, entry, 'fetch', timeOrigin, 'domainLookupStart'); - addPerformanceNavigationTiming(transaction, entry, 'domainLookup', timeOrigin); - addRequest(transaction, entry, timeOrigin); -} -/** Create measure related spans */ -function addMeasureSpans(transaction, entry, startTime, duration, timeOrigin) { - var measureStartTimestamp = timeOrigin + startTime; - var measureEndTimestamp = measureStartTimestamp + duration; - _startChild(transaction, { - description: entry.name, - endTimestamp: measureEndTimestamp, - op: entry.entryType, - startTimestamp: measureStartTimestamp, - }); - return measureStartTimestamp; +/** + * 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 + } + + return exports.colors[Math.abs(hash) % exports.colors.length]; } -/** Create resource related spans */ -function addResourceSpans(transaction, entry, resourceName, startTime, duration, timeOrigin) { - // we already instrument based on fetch and xhr, so we don't need to - // duplicate spans here. - if (entry.initiatorType === 'xmlhttprequest' || entry.initiatorType === 'fetch') { - return undefined; - } - var data = {}; - if ('transferSize' in entry) { - data['Transfer Size'] = entry.transferSize; - } - if ('encodedBodySize' in entry) { - data['Encoded Body Size'] = entry.encodedBodySize; + +/** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + +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]; } - if ('decodedBodySize' in entry) { - data['Decoded Body Size'] = entry.decodedBodySize; + + args[0] = exports.coerce(args[0]); + + if ('string' !== typeof args[0]) { + // anything else let's inspect with %O + args.unshift('%O'); } - var startTimestamp = timeOrigin + startTime; - var endTimestamp = startTimestamp + duration; - _startChild(transaction, { - description: resourceName, - endTimestamp: endTimestamp, - op: entry.initiatorType ? "resource." + entry.initiatorType : 'resource', - startTimestamp: startTimestamp, - data: data, + + // 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; }); - return endTimestamp; + + // 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); + + // env-specific initialization logic for debug instances + if ('function' === typeof exports.init) { + exports.init(debug); + } + + return debug; } -exports.addResourceSpans = addResourceSpans; -/** Create performance navigation related spans */ -function addPerformanceNavigationTiming(transaction, entry, event, timeOrigin, eventEnd) { - var end = eventEnd ? entry[eventEnd] : entry[event + "End"]; - var start = entry[event + "Start"]; - if (!start || !end) { - return; + +/** + * 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 = []; + + 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 + '$')); } - _startChild(transaction, { - description: event, - endTimestamp: timeOrigin + utils_2.msToSec(end), - op: 'browser', - startTimestamp: timeOrigin + utils_2.msToSec(start), - }); -} -/** Create request and response related spans */ -function addRequest(transaction, entry, timeOrigin) { - _startChild(transaction, { - description: 'request', - endTimestamp: timeOrigin + utils_2.msToSec(entry.responseEnd), - op: 'browser', - startTimestamp: timeOrigin + utils_2.msToSec(entry.requestStart), - }); - _startChild(transaction, { - description: 'response', - endTimestamp: timeOrigin + utils_2.msToSec(entry.responseEnd), - op: 'browser', - startTimestamp: timeOrigin + utils_2.msToSec(entry.responseStart), - }); + } } + /** - * Helper function to start child on transactions. This function will make sure that the transaction will - * use the start timestamp of the created child span if it is earlier than the transactions actual - * start timestamp. + * Disable debug output. + * + * @api public + */ + +function disable() { + exports.enable(''); +} + +/** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public */ -function _startChild(transaction, _a) { - var startTimestamp = _a.startTimestamp, ctx = tslib_1.__rest(_a, ["startTimestamp"]); - if (startTimestamp && transaction.startTimestamp > startTimestamp) { - transaction.startTimestamp = startTimestamp; + +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 transaction.startChild(tslib_1.__assign({ startTimestamp: startTimestamp }, ctx)); + } + for (i = 0, len = exports.names.length; i < len; i++) { + if (exports.names[i].test(name)) { + return true; + } + } + return false; } -exports._startChild = _startChild; + /** - * Checks if a given value is a valid measurement value. + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private */ -function isMeasurementValue(value) { - return typeof value === 'number' && isFinite(value); + +function coerce(val) { + if (val instanceof Error) return val.stack || val.message; + return val; } -//# sourceMappingURL=metrics.js.map + /***/ }), -/***/ 27854: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 7471: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var hub_1 = __nccwpck_require__(6393); -var utils_1 = __nccwpck_require__(1620); -var utils_2 = __nccwpck_require__(31386); -exports.DEFAULT_TRACING_ORIGINS = ['localhost', /^\//]; -exports.defaultRequestInstrumentationOptions = { - traceFetch: true, - traceXHR: true, - tracingOrigins: exports.DEFAULT_TRACING_ORIGINS, -}; -/** Registers span creators for xhr and fetch requests */ -function registerRequestInstrumentation(_options) { - // eslint-disable-next-line @typescript-eslint/unbound-method - var _a = tslib_1.__assign(tslib_1.__assign({}, exports.defaultRequestInstrumentationOptions), _options), traceFetch = _a.traceFetch, traceXHR = _a.traceXHR, tracingOrigins = _a.tracingOrigins, shouldCreateSpanForRequest = _a.shouldCreateSpanForRequest; - // We should cache url -> decision so that we don't have to compute - // regexp everytime we create a request. - var urlMap = {}; - var defaultShouldCreateSpan = function (url) { - if (urlMap[url]) { - return urlMap[url]; - } - var origins = tracingOrigins; - urlMap[url] = - origins.some(function (origin) { return utils_1.isMatchingPattern(url, origin); }) && - !utils_1.isMatchingPattern(url, 'sentry_key'); - return urlMap[url]; - }; - // We want that our users don't have to re-implement shouldCreateSpanForRequest themselves - // That's why we filter out already unwanted Spans from tracingOrigins - var shouldCreateSpan = defaultShouldCreateSpan; - if (typeof shouldCreateSpanForRequest === 'function') { - shouldCreateSpan = function (url) { - return defaultShouldCreateSpan(url) && shouldCreateSpanForRequest(url); - }; - } - var spans = {}; - if (traceFetch) { - utils_1.addInstrumentationHandler({ - callback: function (handlerData) { - fetchCallback(handlerData, shouldCreateSpan, spans); - }, - type: 'fetch', - }); - } - if (traceXHR) { - utils_1.addInstrumentationHandler({ - callback: function (handlerData) { - xhrCallback(handlerData, shouldCreateSpan, spans); - }, - type: 'xhr', - }); - } +/** + * Detect Electron renderer process, which is node, but we should + * treat as a browser. + */ + +if (typeof process !== 'undefined' && process.type === 'renderer') { + module.exports = __nccwpck_require__(15377); +} else { + module.exports = __nccwpck_require__(74117); } -exports.registerRequestInstrumentation = registerRequestInstrumentation; + + +/***/ }), + +/***/ 74117: +/***/ ((module, exports, __nccwpck_require__) => { + /** - * Create and track fetch request spans + * Module dependencies. */ -function fetchCallback(handlerData, shouldCreateSpan, spans) { - var _a; - var currentClientOptions = (_a = hub_1.getCurrentHub() - .getClient()) === null || _a === void 0 ? void 0 : _a.getOptions(); - if (!(currentClientOptions && utils_2.hasTracingEnabled(currentClientOptions)) || - !(handlerData.fetchData && shouldCreateSpan(handlerData.fetchData.url))) { - return; - } - if (handlerData.endTimestamp && handlerData.fetchData.__span) { - var span = spans[handlerData.fetchData.__span]; - if (span) { - var response = handlerData.response; - if (response) { - // TODO (kmclb) remove this once types PR goes through - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - span.setHttpStatus(response.status); - } - span.finish(); - // eslint-disable-next-line @typescript-eslint/no-dynamic-delete - delete spans[handlerData.fetchData.__span]; - } - return; - } - var activeTransaction = utils_2.getActiveTransaction(); - if (activeTransaction) { - var span = activeTransaction.startChild({ - data: tslib_1.__assign(tslib_1.__assign({}, handlerData.fetchData), { type: 'fetch' }), - description: handlerData.fetchData.method + " " + handlerData.fetchData.url, - op: 'http', - }); - handlerData.fetchData.__span = span.spanId; - spans[span.spanId] = span; - var request = (handlerData.args[0] = handlerData.args[0]); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - var options = (handlerData.args[1] = handlerData.args[1] || {}); - var headers = options.headers; - if (utils_1.isInstanceOf(request, Request)) { - headers = request.headers; - } - if (headers) { - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - if (typeof headers.append === 'function') { - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - headers.append('sentry-trace', span.toTraceparent()); - } - else if (Array.isArray(headers)) { - headers = tslib_1.__spread(headers, [['sentry-trace', span.toTraceparent()]]); - } - else { - headers = tslib_1.__assign(tslib_1.__assign({}, headers), { 'sentry-trace': span.toTraceparent() }); - } - } - else { - headers = { 'sentry-trace': span.toTraceparent() }; - } - options.headers = headers; - } + +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__(22552); +exports.init = init; +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; + +/** + * Colors. + */ + +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 + */ + +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; +}, {}); + +/** + * 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 + */ + +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)')() } -exports.fetchCallback = fetchCallback; + +var stream = 1 === fd ? process.stdout : + 2 === fd ? process.stderr : + createWritableStdioStream(fd); + /** - * Create and track xhr request spans + * Is stdout a TTY? Colored output is enabled when `true`. */ -function xhrCallback(handlerData, shouldCreateSpan, spans) { - var _a; - var currentClientOptions = (_a = hub_1.getCurrentHub() - .getClient()) === null || _a === void 0 ? void 0 : _a.getOptions(); - if (!(currentClientOptions && utils_2.hasTracingEnabled(currentClientOptions)) || - !(handlerData.xhr && handlerData.xhr.__sentry_xhr__ && shouldCreateSpan(handlerData.xhr.__sentry_xhr__.url)) || - handlerData.xhr.__sentry_own_request__) { - return; - } - var xhr = handlerData.xhr.__sentry_xhr__; - // check first if the request has finished and is tracked by an existing span which should now end - if (handlerData.endTimestamp && handlerData.xhr.__sentry_xhr_span_id__) { - var span = spans[handlerData.xhr.__sentry_xhr_span_id__]; - if (span) { - span.setHttpStatus(xhr.status_code); - span.finish(); - // eslint-disable-next-line @typescript-eslint/no-dynamic-delete - delete spans[handlerData.xhr.__sentry_xhr_span_id__]; - } - return; - } - // if not, create a new span to track it - var activeTransaction = utils_2.getActiveTransaction(); - if (activeTransaction) { - var span = activeTransaction.startChild({ - data: tslib_1.__assign(tslib_1.__assign({}, xhr.data), { type: 'xhr', method: xhr.method, url: xhr.url }), - description: xhr.method + " " + xhr.url, - op: 'http', - }); - handlerData.xhr.__sentry_xhr_span_id__ = span.spanId; - spans[handlerData.xhr.__sentry_xhr_span_id__] = span; - if (handlerData.xhr.setRequestHeader) { - try { - handlerData.xhr.setRequestHeader('sentry-trace', span.toTraceparent()); - } - catch (_) { - // Error: InvalidStateError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': The object's state must be OPENED. - } - } - } + +function useColors() { + return 'colors' in exports.inspectOpts + ? Boolean(exports.inspectOpts.colors) + : tty.isatty(fd); } -exports.xhrCallback = xhrCallback; -//# sourceMappingURL=request.js.map -/***/ }), +/** + * Map %o to `util.inspect()`, all on a single line. + */ -/***/ 40348: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +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(' '); +}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -var utils_1 = __nccwpck_require__(1620); -var global = utils_1.getGlobalObject(); /** - * Default function implementing pageload and navigation transactions + * Map %o to `util.inspect()`, allowing multiple lines if needed. */ -function defaultRoutingInstrumentation(startTransaction, startTransactionOnPageLoad, startTransactionOnLocationChange) { - if (startTransactionOnPageLoad === void 0) { startTransactionOnPageLoad = true; } - if (startTransactionOnLocationChange === void 0) { startTransactionOnLocationChange = true; } - if (!global || !global.location) { - utils_1.logger.warn('Could not initialize routing instrumentation due to invalid location'); - return; - } - var startingUrl = global.location.href; - var activeTransaction; - if (startTransactionOnPageLoad) { - activeTransaction = startTransaction({ name: global.location.pathname, op: 'pageload' }); - } - if (startTransactionOnLocationChange) { - utils_1.addInstrumentationHandler({ - callback: function (_a) { - var to = _a.to, from = _a.from; - /** - * This early return is there to account for some cases where a navigation transaction starts right after - * long-running pageload. We make sure that if `from` is undefined and a valid `startingURL` exists, we don't - * create an uneccessary navigation transaction. - * - * This was hard to duplicate, but this behavior stopped as soon as this fix was applied. This issue might also - * only be caused in certain development environments where the usage of a hot module reloader is causing - * errors. - */ - if (from === undefined && startingUrl && startingUrl.indexOf(to) !== -1) { - startingUrl = undefined; - return; - } - if (from !== to) { - startingUrl = undefined; - if (activeTransaction) { - utils_1.logger.log("[Tracing] Finishing current transaction with op: " + activeTransaction.op); - // If there's an open transaction on the scope, we need to finish it before creating an new one. - activeTransaction.finish(); - } - activeTransaction = startTransaction({ name: global.location.pathname, op: 'navigation' }); - } - }, - type: 'history', - }); - } + +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]; + } } -exports.defaultRoutingInstrumentation = defaultRoutingInstrumentation; -//# sourceMappingURL=router.js.map -/***/ }), +/** + * Invokes `util.format()` with the specified arguments and writes to `stream`. + */ -/***/ 56982: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +function log() { + return stream.write(util.format.apply(util, arguments) + '\n'); +} -/* - * Copyright 2020 Google LLC +/** + * Save `namespaces`. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * @param {String} namespaces + * @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; + } +} + +/** + * Load `namespaces`. * - * https://www.apache.org/licenses/LICENSE-2.0 + * @return {String} returns the previously persisted debug modes + * @api private + */ + +function load() { + return process.env.DEBUG; +} + +/** + * Copied from `node/src/node.js`. * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * 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. */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -var bindReporter_1 = __nccwpck_require__(54592); -var initMetric_1 = __nccwpck_require__(45300); -var observe_1 = __nccwpck_require__(17984); -var onHidden_1 = __nccwpck_require__(9658); -exports.getCLS = function (onReport, reportAllChanges) { - if (reportAllChanges === void 0) { reportAllChanges = false; } - var metric = initMetric_1.initMetric('CLS', 0); - var report; - var entryHandler = function (entry) { - // Only count layout shifts without recent user input. - if (!entry.hadRecentInput) { - metric.value += entry.value; - metric.entries.push(entry); - report(); - } - }; - var po = observe_1.observe('layout-shift', entryHandler); - if (po) { - report = bindReporter_1.bindReporter(onReport, metric, po, reportAllChanges); - onHidden_1.onHidden(function (_a) { - var isUnloading = _a.isUnloading; - po.takeRecords().map(entryHandler); - if (isUnloading) { - metric.isFinal = true; - } - report(); - }); - } -}; -//# sourceMappingURL=getCLS.js.map -/***/ }), +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(); + } + 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; -/***/ 82496: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + stream._isStdio = true; -/* - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 + return stream; +} + +/** + * Init logic for `debug` instances. * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -var bindReporter_1 = __nccwpck_require__(54592); -var getFirstHidden_1 = __nccwpck_require__(88493); -var initMetric_1 = __nccwpck_require__(45300); -var observe_1 = __nccwpck_require__(17984); -var onHidden_1 = __nccwpck_require__(9658); -exports.getFID = function (onReport) { - var metric = initMetric_1.initMetric('FID'); - var firstHidden = getFirstHidden_1.getFirstHidden(); - var entryHandler = function (entry) { - // Only report if the page wasn't hidden prior to the first input. - if (entry.startTime < firstHidden.timeStamp) { - metric.value = entry.processingStart - entry.startTime; - metric.entries.push(entry); - metric.isFinal = true; - report(); - } - }; - var po = observe_1.observe('first-input', entryHandler); - var report = bindReporter_1.bindReporter(onReport, metric, po); - if (po) { - onHidden_1.onHidden(function () { - po.takeRecords().map(entryHandler); - po.disconnect(); - }, true); - } - else { - if (window.perfMetrics && window.perfMetrics.onFirstInputDelay) { - window.perfMetrics.onFirstInputDelay(function (value, event) { - // Only report if the page wasn't hidden prior to the first input. - if (event.timeStamp < firstHidden.timeStamp) { - metric.value = value; - metric.isFinal = true; - metric.entries = [ - { - entryType: 'first-input', - name: event.type, - target: event.target, - cancelable: event.cancelable, - startTime: event.timeStamp, - processingStart: event.timeStamp + value, - }, - ]; - report(); - } - }); - } - } -}; -//# sourceMappingURL=getFID.js.map -/***/ }), +function init (debug) { + debug.inspectOpts = {}; -/***/ 99382: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + var keys = Object.keys(exports.inspectOpts); + for (var i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } +} -/* - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. +/** + * Enable namespaces listed in `process.env.DEBUG` initially. */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -var bindReporter_1 = __nccwpck_require__(54592); -var getFirstHidden_1 = __nccwpck_require__(88493); -var initMetric_1 = __nccwpck_require__(45300); -var observe_1 = __nccwpck_require__(17984); -var onHidden_1 = __nccwpck_require__(9658); -var whenInput_1 = __nccwpck_require__(45181); -exports.getLCP = function (onReport, reportAllChanges) { - if (reportAllChanges === void 0) { reportAllChanges = false; } - var metric = initMetric_1.initMetric('LCP'); - var firstHidden = getFirstHidden_1.getFirstHidden(); - var report; - var entryHandler = function (entry) { - // The startTime attribute returns the value of the renderTime if it is not 0, - // and the value of the loadTime otherwise. - var value = entry.startTime; - // If the page was hidden prior to paint time of the entry, - // ignore it and mark the metric as final, otherwise add the entry. - if (value < firstHidden.timeStamp) { - metric.value = value; - metric.entries.push(entry); - } - else { - metric.isFinal = true; - } - report(); - }; - var po = observe_1.observe('largest-contentful-paint', entryHandler); - if (po) { - report = bindReporter_1.bindReporter(onReport, metric, po, reportAllChanges); - var onFinal = function () { - if (!metric.isFinal) { - po.takeRecords().map(entryHandler); - metric.isFinal = true; - report(); - } - }; - void whenInput_1.whenInput().then(onFinal); - onHidden_1.onHidden(onFinal, true); - } -}; -//# sourceMappingURL=getLCP.js.map + +exports.enable(load()); + /***/ }), -/***/ 55909: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 73233: +/***/ ((module) => { -/* - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. +/** + * Helpers. */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -var utils_1 = __nccwpck_require__(1620); -var initMetric_1 = __nccwpck_require__(45300); -var global = utils_1.getGlobalObject(); -var afterLoad = function (callback) { - if (document.readyState === 'complete') { - // Queue a task so the callback runs after `loadEventEnd`. - setTimeout(callback, 0); - } - else { - // Use `pageshow` so the callback runs after `loadEventEnd`. - addEventListener('pageshow', callback); - } -}; -var getNavigationEntryFromPerformanceTiming = function () { - // Really annoying that TypeScript errors when using `PerformanceTiming`. - // eslint-disable-next-line deprecation/deprecation - var timing = global.performance.timing; - var navigationEntry = { - entryType: 'navigation', - startTime: 0, - }; - for (var key in timing) { - if (key !== 'navigationStart' && key !== 'toJSON') { - navigationEntry[key] = Math.max(timing[key] - timing.navigationStart, 0); - } - } - return navigationEntry; -}; -exports.getTTFB = function (onReport) { - var metric = initMetric_1.initMetric('TTFB'); - afterLoad(function () { - try { - // Use the NavigationTiming L2 entry if available. - var navigationEntry = global.performance.getEntriesByType('navigation')[0] || getNavigationEntryFromPerformanceTiming(); - metric.value = metric.delta = navigationEntry.responseStart; - metric.entries = [navigationEntry]; - onReport(metric); - } - catch (error) { - // Do nothing. - } - }); -}; -//# sourceMappingURL=getTTFB.js.map -/***/ }), - -/***/ 54592: -/***/ ((__unused_webpack_module, exports) => { +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var y = d * 365.25; -/* - * Copyright 2020 Google LLC +/** + * Parse or format the given `val`. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Options: * - * https://www.apache.org/licenses/LICENSE-2.0 + * - `long` verbose formatting [false] * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * @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 */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.bindReporter = function (callback, metric, po, observeAllUpdates) { - var prevValue; - return function () { - if (po && metric.isFinal) { - po.disconnect(); - } - if (metric.value >= 0) { - if (observeAllUpdates || metric.isFinal || document.visibilityState === 'hidden') { - metric.delta = metric.value - (prevValue || 0); - // Report the metric if there's a non-zero delta, if the metric is - // final, or if no previous value exists (which can happen in the case - // of the document becoming hidden when the metric value is 0). - // See: https://github.com/GoogleChrome/web-vitals/issues/14 - if (metric.delta || metric.isFinal || prevValue === undefined) { - callback(metric); - prevValue = metric.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' && 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) + ); }; -//# sourceMappingURL=bindReporter.js.map -/***/ }), +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ -/***/ 70093: -/***/ ((__unused_webpack_module, exports) => { +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; + } +} -/* - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at +/** + * Short format for `ms`. * - * https://www.apache.org/licenses/LICENSE-2.0 + * @param {Number} ms + * @return {String} + * @api private + */ + +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`. * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * @param {Number} ms + * @return {String} + * @api private */ -Object.defineProperty(exports, "__esModule", ({ value: true })); + +function fmtLong(ms) { + return plural(ms, d, 'day') || + plural(ms, h, 'hour') || + plural(ms, m, 'minute') || + plural(ms, s, 'second') || + ms + ' ms'; +} + /** - * Performantly generate a unique, 27-char string by combining the current - * timestamp with a 13-digit random number. - * @return {string} + * Pluralization helper. */ -exports.generateUniqueID = function () { - return Date.now() + "-" + (Math.floor(Math.random() * (9e12 - 1)) + 1e12); -}; -//# sourceMappingURL=generateUniqueID.js.map + +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'; +} + /***/ }), -/***/ 88493: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 85442: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/* - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -var onHidden_1 = __nccwpck_require__(9658); -var firstHiddenTime; -exports.getFirstHidden = function () { - if (firstHiddenTime === undefined) { - // If the document is hidden when this code runs, assume it was hidden - // since navigation start. This isn't a perfect heuristic, but it's the - // best we can do until an API is available to support querying past - // visibilityState. - firstHiddenTime = document.visibilityState === 'hidden' ? 0 : Infinity; - // Update the time if/when the document becomes hidden. - onHidden_1.onHidden(function (_a) { - var timeStamp = _a.timeStamp; - return (firstHiddenTime = timeStamp); - }, true); +"use strict"; + + +var Batcher, Events, parser; +parser = __nccwpck_require__(67823); +Events = __nccwpck_require__(107); + +Batcher = function () { + class Batcher { + constructor(options = {}) { + this.options = options; + parser.load(this.options, this.defaults, this); + this.Events = new Events(this); + this._arr = []; + + this._resetPromise(); + + this._lastFlush = Date.now(); } - return { - get timeStamp() { - return firstHiddenTime; - }, - }; -}; -//# sourceMappingURL=getFirstHidden.js.map + + _resetPromise() { + return this._promise = new this.Promise((res, rej) => { + return this._resolve = res; + }); + } + + _flush() { + clearTimeout(this._timeout); + this._lastFlush = Date.now(); + + this._resolve(); + + this.Events.trigger("batch", this._arr); + this._arr = []; + return this._resetPromise(); + } + + add(data) { + var ret; + + this._arr.push(data); + + ret = this._promise; + + if (this._arr.length === this.maxSize) { + this._flush(); + } else if (this.maxTime != null && this._arr.length === 1) { + this._timeout = setTimeout(() => { + return this._flush(); + }, this.maxTime); + } + + return ret; + } + + } + + ; + Batcher.prototype.defaults = { + maxTime: null, + maxSize: null, + Promise: Promise + }; + return Batcher; +}.call(void 0); + +module.exports = Batcher; /***/ }), -/***/ 45300: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 83911: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/* - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -var generateUniqueID_1 = __nccwpck_require__(70093); -exports.initMetric = function (name, value) { - if (value === void 0) { value = -1; } - return { - name: name, - value: value, - delta: 0, - entries: [], - id: generateUniqueID_1.generateUniqueID(), - isFinal: false, - }; -}; -//# sourceMappingURL=initMetric.js.map +"use strict"; -/***/ }), -/***/ 17984: -/***/ ((__unused_webpack_module, exports) => { +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } -/* - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -/** - * Takes a performance entry type and a callback function, and creates a - * `PerformanceObserver` instance that will observe the specified entry type - * with buffering enabled and call the callback _for each entry_. - * - * This function also feature-detects entry support and wraps the logic in a - * try/catch to avoid errors in unsupporting browsers. - */ -exports.observe = function (type, callback) { - try { - if (PerformanceObserver.supportedEntryTypes.includes(type)) { - var po = new PerformanceObserver(function (l) { return l.getEntries().map(callback); }); - po.observe({ type: type, buffered: true }); - return po; - } - } - catch (e) { - // Do nothing. - } - return; -}; -//# sourceMappingURL=observe.js.map +function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } -/***/ }), +function _toArray(arr) { return _arrayWithHoles(arr) || _iterableToArray(arr) || _nonIterableRest(); } -/***/ 9658: -/***/ ((__unused_webpack_module, exports) => { +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } -/* - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -var isUnloading = false; -var listenersAdded = false; -var onPageHide = function (event) { - isUnloading = !event.persisted; -}; -var addListeners = function () { - addEventListener('pagehide', onPageHide); - // `beforeunload` is needed to fix this bug: - // https://bugs.chromium.org/p/chromium/issues/detail?id=987409 - // eslint-disable-next-line @typescript-eslint/no-empty-function - addEventListener('beforeunload', function () { }); -}; -exports.onHidden = function (cb, once) { - if (once === void 0) { once = false; } - if (!listenersAdded) { - addListeners(); - listenersAdded = true; - } - addEventListener('visibilitychange', function (_a) { - var timeStamp = _a.timeStamp; - if (document.visibilityState === 'hidden') { - cb({ timeStamp: timeStamp, isUnloading: isUnloading }); +function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } + +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } + +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } + +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } + +var Bottleneck, + DEFAULT_PRIORITY, + Events, + LocalDatastore, + NUM_PRIORITIES, + Queues, + RedisDatastore, + States, + Sync, + parser, + splice = [].splice; +NUM_PRIORITIES = 10; +DEFAULT_PRIORITY = 5; +parser = __nccwpck_require__(67823); +Queues = __nccwpck_require__(65893); +LocalDatastore = __nccwpck_require__(38979); +RedisDatastore = __nccwpck_require__(4946); +Events = __nccwpck_require__(107); +States = __nccwpck_require__(2527); +Sync = __nccwpck_require__(56029); + +Bottleneck = function () { + class Bottleneck { + constructor(options = {}, ...invalid) { + var storeInstanceOptions, storeOptions; + this._drainOne = this._drainOne.bind(this); + this.submit = this.submit.bind(this); + this.schedule = this.schedule.bind(this); + this.updateSettings = this.updateSettings.bind(this); + this.incrementReservoir = this.incrementReservoir.bind(this); + + this._validateOptions(options, invalid); + + parser.load(options, this.instanceDefaults, this); + this._queues = new Queues(NUM_PRIORITIES); + this._scheduled = {}; + this._states = new States(["RECEIVED", "QUEUED", "RUNNING", "EXECUTING"].concat(this.trackDoneStatus ? ["DONE"] : [])); + this._limiter = null; + this.Events = new Events(this); + this._submitLock = new Sync("submit", this.Promise); + this._registerLock = new Sync("register", this.Promise); + storeOptions = parser.load(options, this.storeDefaults, {}); + + this._store = function () { + if (this.datastore === "redis" || this.datastore === "ioredis" || this.connection != null) { + storeInstanceOptions = parser.load(options, this.redisStoreDefaults, {}); + return new RedisDatastore(this, storeOptions, storeInstanceOptions); + } else if (this.datastore === "local") { + storeInstanceOptions = parser.load(options, this.localStoreDefaults, {}); + return new LocalDatastore(this, storeOptions, storeInstanceOptions); + } else { + throw new Bottleneck.prototype.BottleneckError(`Invalid datastore type: ${this.datastore}`); } - }, { capture: true, once: once }); -}; -//# sourceMappingURL=onHidden.js.map + }.call(this); -/***/ }), + this._queues.on("leftzero", () => { + var base; + return typeof (base = this._store.heartbeat).ref === "function" ? base.ref() : void 0; + }); -/***/ 45181: -/***/ ((__unused_webpack_module, exports) => { + this._queues.on("zero", () => { + var base; + return typeof (base = this._store.heartbeat).unref === "function" ? base.unref() : void 0; + }); + } -/* - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -var inputPromise; -exports.whenInput = function () { - if (!inputPromise) { - inputPromise = new Promise(function (r) { - return ['scroll', 'keydown', 'pointerdown'].map(function (type) { - addEventListener(type, r, { - once: true, - passive: true, - capture: true, - }); - }); - }); + _validateOptions(options, invalid) { + if (!(options != null && typeof options === "object" && invalid.length === 0)) { + throw new Bottleneck.prototype.BottleneckError("Bottleneck v2 takes a single object argument. Refer to https://github.com/SGrondin/bottleneck#upgrading-to-v2 if you're upgrading from Bottleneck v1."); + } } - return inputPromise; -}; -//# sourceMappingURL=whenInput.js.map -/***/ }), + ready() { + return this._store.ready; + } -/***/ 47906: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + clients() { + return this._store.clients; + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -var utils_1 = __nccwpck_require__(1620); -var spanstatus_1 = __nccwpck_require__(58522); -var utils_2 = __nccwpck_require__(31386); -/** - * Configures global error listeners - */ -function registerErrorInstrumentation() { - utils_1.addInstrumentationHandler({ - callback: errorCallback, - type: 'error', - }); - utils_1.addInstrumentationHandler({ - callback: errorCallback, - type: 'unhandledrejection', - }); -} -exports.registerErrorInstrumentation = registerErrorInstrumentation; -/** - * If an error or unhandled promise occurs, we mark the active transaction as failed - */ -function errorCallback() { - var activeTransaction = utils_2.getActiveTransaction(); - if (activeTransaction) { - utils_1.logger.log("[Tracing] Transaction: " + spanstatus_1.SpanStatus.InternalError + " -> Global error occured"); - activeTransaction.setStatus(spanstatus_1.SpanStatus.InternalError); + channel() { + return `b_${this.id}`; } -} -//# sourceMappingURL=errors.js.map -/***/ }), + channel_client() { + return `b_${this.id}_${this._store.clientId}`; + } -/***/ 31409: -/***/ ((module, exports, __nccwpck_require__) => { + publish(message) { + return this._store.__publish__(message); + } -/* module decorator */ module = __nccwpck_require__.nmd(module); -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var hub_1 = __nccwpck_require__(6393); -var types_1 = __nccwpck_require__(83789); -var utils_1 = __nccwpck_require__(1620); -var errors_1 = __nccwpck_require__(47906); -var idletransaction_1 = __nccwpck_require__(2171); -var transaction_1 = __nccwpck_require__(8186); -var utils_2 = __nccwpck_require__(31386); -/** Returns all trace headers that are currently on the top scope. */ -function traceHeaders() { - var scope = this.getScope(); - if (scope) { - var span = scope.getSpan(); - if (span) { - return { - 'sentry-trace': span.toTraceparent(), - }; - } + disconnect(flush = true) { + return this._store.__disconnect__(flush); } - return {}; -} -/** - * Makes a sampling decision for the given transaction and stores it on the transaction. - * - * Called every time a transaction is created. Only transactions which emerge with a `sampled` value of `true` will be - * sent to Sentry. - * - * @param hub: The hub off of which to read config options - * @param transaction: The transaction needing a sampling decision - * @param samplingContext: Default and user-provided data which may be used to help make the decision - * - * @returns The given transaction with its `sampled` value set - */ -function sample(hub, transaction, samplingContext) { - var _a; - var client = hub.getClient(); - var options = (client && client.getOptions()) || {}; - // nothing to do if there's no client or if tracing is disabled - if (!client || !utils_2.hasTracingEnabled(options)) { - transaction.sampled = false; - return transaction; + + chain(_limiter) { + this._limiter = _limiter; + return this; } - // if the user has forced a sampling decision by passing a `sampled` value in their transaction context, go with that - if (transaction.sampled !== undefined) { - transaction.tags = tslib_1.__assign(tslib_1.__assign({}, transaction.tags), { __sentry_samplingMethod: types_1.TransactionSamplingMethod.Explicit }); - return transaction; + + queued(priority) { + return this._queues.queued(priority); } - // we would have bailed already if neither `tracesSampler` nor `tracesSampleRate` were defined, so one of these should - // work; prefer the hook if so - var sampleRate; - if (typeof options.tracesSampler === 'function') { - sampleRate = options.tracesSampler(samplingContext); - // cast the rate to a number first in case it's a boolean - transaction.tags = tslib_1.__assign(tslib_1.__assign({}, transaction.tags), { __sentry_samplingMethod: types_1.TransactionSamplingMethod.Sampler, - // TODO kmclb - once tag types are loosened, don't need to cast to string here - __sentry_sampleRate: String(Number(sampleRate)) }); + + clusterQueued() { + return this._store.__queued__(); } - else if (samplingContext.parentSampled !== undefined) { - sampleRate = samplingContext.parentSampled; - transaction.tags = tslib_1.__assign(tslib_1.__assign({}, transaction.tags), { __sentry_samplingMethod: types_1.TransactionSamplingMethod.Inheritance }); + + empty() { + return this.queued() === 0 && this._submitLock.isEmpty(); } - else { - sampleRate = options.tracesSampleRate; - // cast the rate to a number first in case it's a boolean - transaction.tags = tslib_1.__assign(tslib_1.__assign({}, transaction.tags), { __sentry_samplingMethod: types_1.TransactionSamplingMethod.Rate, - // TODO kmclb - once tag types are loosened, don't need to cast to string here - __sentry_sampleRate: String(Number(sampleRate)) }); + + running() { + return this._store.__running__(); } - // Since this is coming from the user (or from a function provided by the user), who knows what we might get. (The - // only valid values are booleans or numbers between 0 and 1.) - if (!isValidSampleRate(sampleRate)) { - utils_1.logger.warn("[Tracing] Discarding transaction because of invalid sample rate."); - transaction.sampled = false; - return transaction; + + done() { + return this._store.__done__(); } - // if the function returned 0 (or false), or if `tracesSampleRate` is 0, it's a sign the transaction should be dropped - if (!sampleRate) { - utils_1.logger.log("[Tracing] Discarding transaction because " + (typeof options.tracesSampler === 'function' - ? 'tracesSampler returned 0 or false' - : 'a negative sampling decision was inherited or tracesSampleRate is set to 0')); - transaction.sampled = false; - return transaction; + + jobStatus(id) { + return this._states.jobStatus(id); } - // Now we roll the dice. Math.random is inclusive of 0, but not of 1, so strict < is safe here. In case sampleRate is - // a boolean, the < comparison will cause it to be automatically cast to 1 if it's true and 0 if it's false. - transaction.sampled = Math.random() < sampleRate; - // if we're not going to keep it, we're done - if (!transaction.sampled) { - utils_1.logger.log("[Tracing] Discarding transaction because it's not included in the random sample (sampling rate = " + Number(sampleRate) + ")"); - return transaction; + + jobs(status) { + return this._states.statusJobs(status); } - // at this point we know we're keeping the transaction, whether because of an inherited decision or because it got - // lucky with the dice roll - transaction.initSpanRecorder((_a = options._experiments) === null || _a === void 0 ? void 0 : _a.maxSpans); - utils_1.logger.log("[Tracing] starting " + transaction.op + " transaction - " + transaction.name); - return transaction; -} -/** - * Gets the correct context to pass to the tracesSampler, based on the environment (i.e., which SDK is being used) - * - * @returns The default sample context - */ -function getDefaultSamplingContext(transactionContext) { - // promote parent sampling decision (if any) for easy access - var parentSampled = transactionContext.parentSampled; - var defaultSamplingContext = { transactionContext: transactionContext, parentSampled: parentSampled }; - if (utils_1.isNodeEnv()) { - var domain = hub_1.getActiveDomain(); - if (domain) { - // for all node servers that we currently support, we store the incoming request object (which is an instance of - // http.IncomingMessage) on the domain - // the domain members are stored as an array, so our only way to find the request is to iterate through the array - // and compare types - var nodeHttpModule = utils_1.dynamicRequire(module, 'http'); - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - var requestType_1 = nodeHttpModule.IncomingMessage; - var request = domain.members.find(function (member) { return utils_1.isInstanceOf(member, requestType_1); }); - if (request) { - defaultSamplingContext.request = utils_1.extractNodeRequestData(request); - } - } + + counts() { + return this._states.statusCounts(); } - // we must be in browser-js (or some derivative thereof) - else { - // we use `getGlobalObject()` rather than `window` since service workers also have a `location` property on `self` - var globalObject = utils_1.getGlobalObject(); - if ('location' in globalObject) { - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any - defaultSamplingContext.location = tslib_1.__assign({}, globalObject.location); - } + + _sanitizePriority(priority) { + var sProperty; + sProperty = ~~priority !== priority ? DEFAULT_PRIORITY : priority; + + if (sProperty < 0) { + return 0; + } else if (sProperty > NUM_PRIORITIES - 1) { + return NUM_PRIORITIES - 1; + } else { + return sProperty; + } } - return defaultSamplingContext; -} -/** - * Checks the given sample rate to make sure it is valid type and value (a boolean, or a number between 0 and 1). - */ -function isValidSampleRate(rate) { - // we need to check NaN explicitly because it's of type 'number' and therefore wouldn't get caught by this typecheck - // eslint-disable-next-line @typescript-eslint/no-explicit-any - if (isNaN(rate) || !(typeof rate === 'number' || typeof rate === 'boolean')) { - utils_1.logger.warn("[Tracing] Given sample rate is invalid. Sample rate must be a boolean or a number between 0 and 1. Got " + JSON.stringify(rate) + " of type " + JSON.stringify(typeof rate) + "."); - return false; + + _randomIndex() { + return Math.random().toString(36).slice(2); } - // in case sampleRate is a boolean, it will get automatically cast to 1 if it's true and 0 if it's false - if (rate < 0 || rate > 1) { - utils_1.logger.warn("[Tracing] Given sample rate is invalid. Sample rate must be between 0 and 1. Got " + rate + "."); - return false; + + check(weight = 1) { + return this._store.__check__(weight); + } + + _run(next, wait, index, retryCount) { + var _this = this; + + var completed, done; + this.Events.trigger("debug", `Scheduling ${next.options.id}`, { + args: next.args, + options: next.options + }); + done = false; + + completed = + /*#__PURE__*/ + function () { + var _ref = _asyncToGenerator(function* (...args) { + var e, error, eventInfo, retry, retryAfter, running; + + if (!done) { + try { + done = true; + clearTimeout(_this._scheduled[index].expiration); + delete _this._scheduled[index]; + eventInfo = { + args: next.args, + options: next.options, + retryCount + }; + + if ((error = args[0]) != null) { + retry = yield _this.Events.trigger("failed", error, eventInfo); + + if (retry != null) { + retryAfter = ~~retry; + + _this.Events.trigger("retry", `Retrying ${next.options.id} after ${retryAfter} ms`, eventInfo); + + return _this._run(next, retryAfter, index, retryCount + 1); + } + } + + _this._states.next(next.options.id); // DONE + + + _this.Events.trigger("debug", `Completed ${next.options.id}`, eventInfo); + + _this.Events.trigger("done", `Completed ${next.options.id}`, eventInfo); + + var _ref2 = yield _this._store.__free__(index, next.options.weight); + + running = _ref2.running; + + _this.Events.trigger("debug", `Freed ${next.options.id}`, eventInfo); + + if (running === 0 && _this.empty()) { + _this.Events.trigger("idle"); + } + + return typeof next.cb === "function" ? next.cb(...args) : void 0; + } catch (error1) { + e = error1; + return _this.Events.trigger("error", e); + } + } + }); + + return function completed() { + return _ref.apply(this, arguments); + }; + }(); + + if (retryCount === 0) { + // RUNNING + this._states.next(next.options.id); + } + + return this._scheduled[index] = { + timeout: setTimeout(() => { + this.Events.trigger("debug", `Executing ${next.options.id}`, { + args: next.args, + options: next.options + }); + + if (retryCount === 0) { + // EXECUTING + this._states.next(next.options.id); + } + + if (this._limiter != null) { + return this._limiter.submit(next.options, next.task, ...next.args, completed); + } else { + return next.task(...next.args, completed); + } + }, wait), + expiration: next.options.expiration != null ? setTimeout(() => { + return completed(new Bottleneck.prototype.BottleneckError(`This job timed out after ${next.options.expiration} ms.`)); + }, wait + next.options.expiration) : void 0, + job: next + }; } - return true; -} -/** - * Creates a new transaction and adds a sampling decision if it doesn't yet have one. - * - * The Hub.startTransaction method delegates to this method to do its work, passing the Hub instance in as `this`, as if - * it had been called on the hub directly. Exists as a separate function so that it can be injected into the class as an - * "extension method." - * - * @param this: The Hub starting the transaction - * @param transactionContext: Data used to configure the transaction - * @param CustomSamplingContext: Optional data to be provided to the `tracesSampler` function (if any) - * - * @returns The new transaction - * - * @see {@link Hub.startTransaction} - */ -function _startTransaction(transactionContext, customSamplingContext) { - var transaction = new transaction_1.Transaction(transactionContext, this); - return sample(this, transaction, tslib_1.__assign(tslib_1.__assign({}, getDefaultSamplingContext(transactionContext)), customSamplingContext)); -} -/** - * Create new idle transaction. - */ -function startIdleTransaction(hub, transactionContext, idleTimeout, onScope) { - var transaction = new idletransaction_1.IdleTransaction(transactionContext, hub, idleTimeout, onScope); - return sample(hub, transaction, getDefaultSamplingContext(transactionContext)); -} -exports.startIdleTransaction = startIdleTransaction; -/** - * @private - */ -function _addTracingExtensions() { - var carrier = hub_1.getMainCarrier(); - if (carrier.__SENTRY__) { - carrier.__SENTRY__.extensions = carrier.__SENTRY__.extensions || {}; - if (!carrier.__SENTRY__.extensions.startTransaction) { - carrier.__SENTRY__.extensions.startTransaction = _startTransaction; + + _drainOne(capacity) { + return this._registerLock.schedule(() => { + var args, index, next, options, queue; + + if (this.queued() === 0) { + return this.Promise.resolve(null); } - if (!carrier.__SENTRY__.extensions.traceHeaders) { - carrier.__SENTRY__.extensions.traceHeaders = traceHeaders; + + queue = this._queues.getFirst(); + + var _next2 = next = queue.first(); + + options = _next2.options; + args = _next2.args; + + if (capacity != null && options.weight > capacity) { + return this.Promise.resolve(null); } - } -} -exports._addTracingExtensions = _addTracingExtensions; -/** - * This patches the global object and injects the Tracing extensions methods - */ -function addExtensionMethods() { - _addTracingExtensions(); - // If an error happens globally, we should make sure transaction status is set to error. - errors_1.registerErrorInstrumentation(); -} -exports.addExtensionMethods = addExtensionMethods; -//# sourceMappingURL=hubextensions.js.map -/***/ }), + this.Events.trigger("debug", `Draining ${options.id}`, { + args, + options + }); + index = this._randomIndex(); + return this._store.__register__(index, options.weight, options.expiration).then(({ + success, + wait, + reservoir + }) => { + var empty; + this.Events.trigger("debug", `Drained ${options.id}`, { + success, + args, + options + }); -/***/ 2171: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + if (success) { + queue.shift(); + empty = this.empty(); -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var utils_1 = __nccwpck_require__(1620); -var span_1 = __nccwpck_require__(64655); -var spanstatus_1 = __nccwpck_require__(58522); -var transaction_1 = __nccwpck_require__(8186); -exports.DEFAULT_IDLE_TIMEOUT = 1000; -/** - * @inheritDoc - */ -var IdleTransactionSpanRecorder = /** @class */ (function (_super) { - tslib_1.__extends(IdleTransactionSpanRecorder, _super); - function IdleTransactionSpanRecorder(_pushActivity, _popActivity, transactionSpanId, maxlen) { - if (transactionSpanId === void 0) { transactionSpanId = ''; } - var _this = _super.call(this, maxlen) || this; - _this._pushActivity = _pushActivity; - _this._popActivity = _popActivity; - _this.transactionSpanId = transactionSpanId; - return _this; - } - /** - * @inheritDoc - */ - IdleTransactionSpanRecorder.prototype.add = function (span) { - var _this = this; - // We should make sure we do not push and pop activities for - // the transaction that this span recorder belongs to. - if (span.spanId !== this.transactionSpanId) { - // We patch span.finish() to pop an activity after setting an endTimestamp. - span.finish = function (endTimestamp) { - span.endTimestamp = typeof endTimestamp === 'number' ? endTimestamp : utils_1.timestampWithMs(); - _this._popActivity(span.spanId); - }; - // We should only push new activities if the span does not have an end timestamp. - if (span.endTimestamp === undefined) { - this._pushActivity(span.spanId); + if (empty) { + this.Events.trigger("empty"); + } + + if (reservoir === 0) { + this.Events.trigger("depleted", empty); } + + this._run(next, wait, index, 0); + + return this.Promise.resolve(options.weight); + } else { + return this.Promise.resolve(null); + } + }); + }); + } + + _drainAll(capacity, total = 0) { + return this._drainOne(capacity).then(drained => { + var newCapacity; + + if (drained != null) { + newCapacity = capacity != null ? capacity - drained : capacity; + return this._drainAll(newCapacity, total + drained); + } else { + return this.Promise.resolve(total); } - _super.prototype.add.call(this, span); - }; - return IdleTransactionSpanRecorder; -}(span_1.SpanRecorder)); -exports.IdleTransactionSpanRecorder = IdleTransactionSpanRecorder; -/** - * An IdleTransaction is a transaction that automatically finishes. It does this by tracking child spans as activities. - * You can have multiple IdleTransactions active, but if the `onScope` option is specified, the idle transaction will - * put itself on the scope on creation. - */ -var IdleTransaction = /** @class */ (function (_super) { - tslib_1.__extends(IdleTransaction, _super); - function IdleTransaction(transactionContext, _idleHub, - // The time to wait in ms until the idle transaction will be finished. Default: 1000 - _idleTimeout, - // If an idle transaction should be put itself on and off the scope automatically. - _onScope) { - if (_idleTimeout === void 0) { _idleTimeout = exports.DEFAULT_IDLE_TIMEOUT; } - if (_onScope === void 0) { _onScope = false; } - var _this = _super.call(this, transactionContext, _idleHub) || this; - _this._idleHub = _idleHub; - _this._idleTimeout = _idleTimeout; - _this._onScope = _onScope; - // Activities store a list of active spans - _this.activities = {}; - // Stores reference to the timeout that calls _beat(). - _this._heartbeatTimer = 0; - // Amount of times heartbeat has counted. Will cause transaction to finish after 3 beats. - _this._heartbeatCounter = 0; - // We should not use heartbeat if we finished a transaction - _this._finished = false; - _this._beforeFinishCallbacks = []; - if (_idleHub && _onScope) { - // There should only be one active transaction on the scope - clearActiveTransaction(_idleHub); - // We set the transaction here on the scope so error events pick up the trace - // context and attach it to the error. - utils_1.logger.log("Setting idle transaction on scope. Span ID: " + _this.spanId); - _idleHub.configureScope(function (scope) { return scope.setSpan(_this); }); + }).catch(e => { + return this.Events.trigger("error", e); + }); + } + + _drop(job, message = "This job has been dropped by Bottleneck") { + if (this._states.remove(job.options.id)) { + if (this.rejectOnDrop) { + if (typeof job.cb === "function") { + job.cb(new Bottleneck.prototype.BottleneckError(message)); + } } - return _this; + + return this.Events.trigger("dropped", job); + } } - /** {@inheritDoc} */ - IdleTransaction.prototype.finish = function (endTimestamp) { - var e_1, _a; - var _this = this; - if (endTimestamp === void 0) { endTimestamp = utils_1.timestampWithMs(); } - this._finished = true; - this.activities = {}; - if (this.spanRecorder) { - utils_1.logger.log('[Tracing] finishing IdleTransaction', new Date(endTimestamp * 1000).toISOString(), this.op); - try { - for (var _b = tslib_1.__values(this._beforeFinishCallbacks), _c = _b.next(); !_c.done; _c = _b.next()) { - var callback = _c.value; - callback(this, endTimestamp); - } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (_c && !_c.done && (_a = _b.return)) _a.call(_b); - } - finally { if (e_1) throw e_1.error; } - } - this.spanRecorder.spans = this.spanRecorder.spans.filter(function (span) { - // If we are dealing with the transaction itself, we just return it - if (span.spanId === _this.spanId) { - return true; - } - // We cancel all pending spans with status "cancelled" to indicate the idle transaction was finished early - if (!span.endTimestamp) { - span.endTimestamp = endTimestamp; - span.setStatus(spanstatus_1.SpanStatus.Cancelled); - utils_1.logger.log('[Tracing] cancelling span since transaction ended early', JSON.stringify(span, undefined, 2)); - } - var keepSpan = span.startTimestamp < endTimestamp; - if (!keepSpan) { - utils_1.logger.log('[Tracing] discarding Span since it happened after Transaction was finished', JSON.stringify(span, undefined, 2)); - } - return keepSpan; + + _dropAllQueued(message) { + return this._queues.shiftAll(job => { + return this._drop(job, message); + }); + } + + stop(options = {}) { + var done, waitForExecuting; + options = parser.load(options, this.stopDefaults); + + waitForExecuting = at => { + var finished; + + finished = () => { + var counts; + counts = this._states.counts; + return counts[0] + counts[1] + counts[2] + counts[3] === at; + }; + + return new this.Promise((resolve, reject) => { + if (finished()) { + return resolve(); + } else { + return this.on("done", () => { + if (finished()) { + this.removeAllListeners("done"); + return resolve(); + } }); - // this._onScope is true if the transaction was previously on the scope. - if (this._onScope) { - clearActiveTransaction(this._idleHub); + } + }); + }; + + done = options.dropWaitingJobs ? (this._run = next => { + return this._drop(next, options.dropErrorMessage); + }, this._drainOne = () => { + return this.Promise.resolve(null); + }, this._registerLock.schedule(() => { + return this._submitLock.schedule(() => { + var k, ref, v; + ref = this._scheduled; + + for (k in ref) { + v = ref[k]; + + if (this.jobStatus(v.job.options.id) === "RUNNING") { + clearTimeout(v.timeout); + clearTimeout(v.expiration); + + this._drop(v.job, options.dropErrorMessage); } - utils_1.logger.log('[Tracing] flushing IdleTransaction'); - } - else { - utils_1.logger.log('[Tracing] No active IdleTransaction'); - } - return _super.prototype.finish.call(this, endTimestamp); - }; - /** - * Register a callback function that gets excecuted before the transaction finishes. - * Useful for cleanup or if you want to add any additional spans based on current context. - * - * This is exposed because users have no other way of running something before an idle transaction - * finishes. - */ - IdleTransaction.prototype.registerBeforeFinishCallback = function (callback) { - this._beforeFinishCallbacks.push(callback); - }; - /** - * @inheritDoc - */ - IdleTransaction.prototype.initSpanRecorder = function (maxlen) { - var _this = this; - if (!this.spanRecorder) { - this._initTimeout = setTimeout(function () { - if (!_this._finished) { - _this.finish(); - } - }, this._idleTimeout); - var pushActivity = function (id) { - if (_this._finished) { - return; - } - _this._pushActivity(id); - }; - var popActivity = function (id) { - if (_this._finished) { - return; - } - _this._popActivity(id); - }; - this.spanRecorder = new IdleTransactionSpanRecorder(pushActivity, popActivity, this.spanId, maxlen); - // Start heartbeat so that transactions do not run forever. - utils_1.logger.log('Starting heartbeat'); - this._pingHeartbeat(); - } - this.spanRecorder.add(this); - }; - /** - * Start tracking a specific activity. - * @param spanId The span id that represents the activity - */ - IdleTransaction.prototype._pushActivity = function (spanId) { - if (this._initTimeout) { - clearTimeout(this._initTimeout); - this._initTimeout = undefined; - } - utils_1.logger.log("[Tracing] pushActivity: " + spanId); - this.activities[spanId] = true; - utils_1.logger.log('[Tracing] new activities count', Object.keys(this.activities).length); - }; - /** - * Remove an activity from usage - * @param spanId The span id that represents the activity - */ - IdleTransaction.prototype._popActivity = function (spanId) { - var _this = this; - if (this.activities[spanId]) { - utils_1.logger.log("[Tracing] popActivity " + spanId); - // eslint-disable-next-line @typescript-eslint/no-dynamic-delete - delete this.activities[spanId]; - utils_1.logger.log('[Tracing] new activities count', Object.keys(this.activities).length); - } - if (Object.keys(this.activities).length === 0) { - var timeout = this._idleTimeout; - // We need to add the timeout here to have the real endtimestamp of the transaction - // Remember timestampWithMs is in seconds, timeout is in ms - var end_1 = utils_1.timestampWithMs() + timeout / 1000; - setTimeout(function () { - if (!_this._finished) { - _this.finish(end_1); - } - }, timeout); - } - }; - /** - * Checks when entries of this.activities are not changing for 3 beats. - * If this occurs we finish the transaction. - */ - IdleTransaction.prototype._beat = function () { - clearTimeout(this._heartbeatTimer); - // We should not be running heartbeat if the idle transaction is finished. - if (this._finished) { - return; - } - var keys = Object.keys(this.activities); - var heartbeatString = keys.length ? keys.reduce(function (prev, current) { return prev + current; }) : ''; - if (heartbeatString === this._prevHeartbeatString) { - this._heartbeatCounter += 1; - } - else { - this._heartbeatCounter = 1; - } - this._prevHeartbeatString = heartbeatString; - if (this._heartbeatCounter >= 3) { - utils_1.logger.log("[Tracing] Transaction finished because of no change for 3 heart beats"); - this.setStatus(spanstatus_1.SpanStatus.DeadlineExceeded); - this.setTag('heartbeat', 'failed'); - this.finish(); + } + + this._dropAllQueued(options.dropErrorMessage); + + return waitForExecuting(0); + }); + })) : this.schedule({ + priority: NUM_PRIORITIES - 1, + weight: 0 + }, () => { + return waitForExecuting(1); + }); + + this.submit = (...args) => { + var _ref3, _ref4, _splice$call, _splice$call2; + + var cb, ref; + ref = args, (_ref3 = ref, _ref4 = _toArray(_ref3), args = _ref4.slice(0), _ref3), (_splice$call = splice.call(args, -1), _splice$call2 = _slicedToArray(_splice$call, 1), cb = _splice$call2[0], _splice$call); + return typeof cb === "function" ? cb(new Bottleneck.prototype.BottleneckError(options.enqueueErrorMessage)) : void 0; + }; + + this.stop = () => { + return this.Promise.reject(new Bottleneck.prototype.BottleneckError("stop() has already been called")); + }; + + return done; + } + + submit(...args) { + var _this2 = this; + + var cb, job, options, ref, ref1, task; + + if (typeof args[0] === "function") { + var _ref5, _ref6, _splice$call3, _splice$call4; + + ref = args, (_ref5 = ref, _ref6 = _toArray(_ref5), task = _ref6[0], args = _ref6.slice(1), _ref5), (_splice$call3 = splice.call(args, -1), _splice$call4 = _slicedToArray(_splice$call3, 1), cb = _splice$call4[0], _splice$call3); + options = parser.load({}, this.jobDefaults, {}); + } else { + var _ref7, _ref8, _splice$call5, _splice$call6; + + ref1 = args, (_ref7 = ref1, _ref8 = _toArray(_ref7), options = _ref8[0], task = _ref8[1], args = _ref8.slice(2), _ref7), (_splice$call5 = splice.call(args, -1), _splice$call6 = _slicedToArray(_splice$call5, 1), cb = _splice$call6[0], _splice$call5); + options = parser.load(options, this.jobDefaults); + } + + job = { + options, + task, + args, + cb + }; + options.priority = this._sanitizePriority(options.priority); + + if (options.id === this.jobDefaults.id) { + options.id = `${options.id}-${this._randomIndex()}`; + } + + if (this.jobStatus(options.id) != null) { + if (typeof job.cb === "function") { + job.cb(new Bottleneck.prototype.BottleneckError(`A job with the same id already exists (id=${options.id})`)); } - else { - this._pingHeartbeat(); + + return false; + } + + this._states.start(options.id); // RECEIVED + + + this.Events.trigger("debug", `Queueing ${options.id}`, { + args, + options + }); + return this._submitLock.schedule( + /*#__PURE__*/ + _asyncToGenerator(function* () { + var blocked, e, reachedHWM, shifted, strategy; + + try { + var _ref10 = yield _this2._store.__submit__(_this2.queued(), options.weight); + + reachedHWM = _ref10.reachedHWM; + blocked = _ref10.blocked; + strategy = _ref10.strategy; + + _this2.Events.trigger("debug", `Queued ${options.id}`, { + args, + options, + reachedHWM, + blocked + }); + } catch (error1) { + e = error1; + + _this2._states.remove(options.id); + + _this2.Events.trigger("debug", `Could not queue ${options.id}`, { + args, + options, + error: e + }); + + if (typeof job.cb === "function") { + job.cb(e); + } + + return false; } - }; - /** - * Pings the heartbeat - */ - IdleTransaction.prototype._pingHeartbeat = function () { - var _this = this; - utils_1.logger.log("pinging Heartbeat -> current counter: " + this._heartbeatCounter); - this._heartbeatTimer = setTimeout(function () { - _this._beat(); - }, 5000); - }; - return IdleTransaction; -}(transaction_1.Transaction)); -exports.IdleTransaction = IdleTransaction; -/** - * Reset active transaction on scope - */ -function clearActiveTransaction(hub) { - if (hub) { - var scope = hub.getScope(); - if (scope) { - var transaction = scope.getTransaction(); - if (transaction) { - scope.setSpan(undefined); + + if (blocked) { + _this2._drop(job); + + return true; + } else if (reachedHWM) { + shifted = strategy === Bottleneck.prototype.strategy.LEAK ? _this2._queues.shiftLastFrom(options.priority) : strategy === Bottleneck.prototype.strategy.OVERFLOW_PRIORITY ? _this2._queues.shiftLastFrom(options.priority + 1) : strategy === Bottleneck.prototype.strategy.OVERFLOW ? job : void 0; + + if (shifted != null) { + _this2._drop(shifted); + } + + if (shifted == null || strategy === Bottleneck.prototype.strategy.OVERFLOW) { + if (shifted == null) { + _this2._drop(job); } + + return reachedHWM; + } } + + _this2._states.next(job.options.id); // QUEUED + + + _this2._queues.push(options.priority, job); + + yield _this2._drainAll(); + return reachedHWM; + })); } -} -//# sourceMappingURL=idletransaction.js.map + + schedule(...args) { + var options, task, wrapped; + + if (typeof args[0] === "function") { + var _args = args; + + var _args2 = _toArray(_args); + + task = _args2[0]; + args = _args2.slice(1); + options = parser.load({}, this.jobDefaults, {}); + } else { + var _args3 = args; + + var _args4 = _toArray(_args3); + + options = _args4[0]; + task = _args4[1]; + args = _args4.slice(2); + options = parser.load(options, this.jobDefaults); + } + + wrapped = (...args) => { + var _ref11, _ref12, _splice$call7, _splice$call8; + + var cb, e, ref, returned; + ref = args, (_ref11 = ref, _ref12 = _toArray(_ref11), args = _ref12.slice(0), _ref11), (_splice$call7 = splice.call(args, -1), _splice$call8 = _slicedToArray(_splice$call7, 1), cb = _splice$call8[0], _splice$call7); + + returned = function () { + try { + return task(...args); + } catch (error1) { + e = error1; + return this.Promise.reject(e); + } + }.call(this); + + return (!((returned != null ? returned.then : void 0) != null && typeof returned.then === "function") ? this.Promise.resolve(returned) : returned).then(function (...args) { + return cb(null, ...args); + }).catch(function (...args) { + return cb(...args); + }); + }; + + return new this.Promise((resolve, reject) => { + return this.submit(options, wrapped, ...args, function (...args) { + return (args[0] != null ? reject : (args.shift(), resolve))(...args); + }).catch(e => { + return this.Events.trigger("error", e); + }); + }); + } + + wrap(fn) { + var schedule, wrapped; + schedule = this.schedule; + + wrapped = function wrapped(...args) { + return schedule(fn.bind(this), ...args); + }; + + wrapped.withOptions = (options, ...args) => { + return schedule(options, fn, ...args); + }; + + return wrapped; + } + + updateSettings(options = {}) { + var _this3 = this; + + return _asyncToGenerator(function* () { + yield _this3._store.__updateSettings__(parser.overwrite(options, _this3.storeDefaults)); + parser.overwrite(options, _this3.instanceDefaults, _this3); + return _this3; + })(); + } + + currentReservoir() { + return this._store.__currentReservoir__(); + } + + incrementReservoir(incr = 0) { + return this._store.__incrementReservoir__(incr); + } + + } + + ; + Bottleneck.default = Bottleneck; + Bottleneck.Events = Events; + Bottleneck.version = Bottleneck.prototype.version = (__nccwpck_require__(82636)/* .version */ .i); + Bottleneck.strategy = Bottleneck.prototype.strategy = { + LEAK: 1, + OVERFLOW: 2, + OVERFLOW_PRIORITY: 4, + BLOCK: 3 + }; + Bottleneck.BottleneckError = Bottleneck.prototype.BottleneckError = __nccwpck_require__(93529); + Bottleneck.Group = Bottleneck.prototype.Group = __nccwpck_require__(53068); + Bottleneck.RedisConnection = Bottleneck.prototype.RedisConnection = __nccwpck_require__(29992); + Bottleneck.IORedisConnection = Bottleneck.prototype.IORedisConnection = __nccwpck_require__(47710); + Bottleneck.Batcher = Bottleneck.prototype.Batcher = __nccwpck_require__(85442); + Bottleneck.prototype.jobDefaults = { + priority: DEFAULT_PRIORITY, + weight: 1, + expiration: null, + id: "" + }; + Bottleneck.prototype.storeDefaults = { + maxConcurrent: null, + minTime: 0, + highWater: null, + strategy: Bottleneck.prototype.strategy.LEAK, + penalty: null, + reservoir: null, + reservoirRefreshInterval: null, + reservoirRefreshAmount: null + }; + Bottleneck.prototype.localStoreDefaults = { + Promise: Promise, + timeout: null, + heartbeatInterval: 250 + }; + Bottleneck.prototype.redisStoreDefaults = { + Promise: Promise, + timeout: null, + heartbeatInterval: 5000, + clientTimeout: 10000, + clientOptions: {}, + clusterNodes: null, + clearDatastore: false, + connection: null + }; + Bottleneck.prototype.instanceDefaults = { + datastore: "local", + connection: null, + id: "", + rejectOnDrop: true, + trackDoneStatus: false, + Promise: Promise + }; + Bottleneck.prototype.stopDefaults = { + enqueueErrorMessage: "This limiter has been stopped and cannot accept new jobs.", + dropWaitingJobs: true, + dropErrorMessage: "This limiter has been stopped." + }; + return Bottleneck; +}.call(void 0); + +module.exports = Bottleneck; /***/ }), -/***/ 64358: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 93529: +/***/ ((module) => { -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var browser_1 = __nccwpck_require__(71425); -var hubextensions_1 = __nccwpck_require__(31409); -exports.addExtensionMethods = hubextensions_1.addExtensionMethods; -var TracingIntegrations = __nccwpck_require__(28502); -var Integrations = tslib_1.__assign(tslib_1.__assign({}, TracingIntegrations), { BrowserTracing: browser_1.BrowserTracing }); -exports.Integrations = Integrations; -var span_1 = __nccwpck_require__(64655); -exports.Span = span_1.Span; -var transaction_1 = __nccwpck_require__(8186); -exports.Transaction = transaction_1.Transaction; -var spanstatus_1 = __nccwpck_require__(58522); -exports.SpanStatus = spanstatus_1.SpanStatus; -// We are patching the global object with our hub extension methods -hubextensions_1.addExtensionMethods(); -var utils_1 = __nccwpck_require__(31386); -exports.extractTraceparentData = utils_1.extractTraceparentData; -exports.getActiveTransaction = utils_1.getActiveTransaction; -exports.hasTracingEnabled = utils_1.hasTracingEnabled; -exports.stripUrlQueryAndFragment = utils_1.stripUrlQueryAndFragment; -exports.TRACEPARENT_REGEXP = utils_1.TRACEPARENT_REGEXP; -//# sourceMappingURL=index.js.map +"use strict"; + + +var BottleneckError; +BottleneckError = class BottleneckError extends Error {}; +module.exports = BottleneckError; /***/ }), -/***/ 96221: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 38579: +/***/ ((module) => { -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var utils_1 = __nccwpck_require__(1620); -/** - * Express integration - * - * Provides an request and error handler for Express framework as well as tracing capabilities - */ -var Express = /** @class */ (function () { - /** - * @inheritDoc - */ - function Express(options) { - if (options === void 0) { options = {}; } - /** - * @inheritDoc - */ - this.name = Express.id; - this._router = options.router || options.app; - this._methods = (Array.isArray(options.methods) ? options.methods : []).concat('use'); +"use strict"; + + +var DLList; +DLList = class DLList { + constructor(_queues) { + this._queues = _queues; + this._first = null; + this._last = null; + this.length = 0; + } + + push(value) { + var node, ref1; + this.length++; + + if ((ref1 = this._queues) != null) { + ref1.incr(); } - /** - * @inheritDoc - */ - Express.prototype.setupOnce = function () { - if (!this._router) { - utils_1.logger.error('ExpressIntegration is missing an Express instance'); - return; - } - instrumentMiddlewares(this._router, this._methods); + + node = { + value, + next: null }; - /** - * @inheritDoc - */ - Express.id = 'Express'; - return Express; -}()); -exports.Express = Express; -/** - * Wraps original middleware function in a tracing call, which stores the info about the call as a span, - * and finishes it once the middleware is done invoking. - * - * Express middlewares have 3 various forms, thus we have to take care of all of them: - * // sync - * app.use(function (req, res) { ... }) - * // async - * app.use(function (req, res, next) { ... }) - * // error handler - * app.use(function (err, req, res, next) { ... }) - * - * They all internally delegate to the `router[method]` of the given application instance. - */ -// eslint-disable-next-line @typescript-eslint/ban-types, @typescript-eslint/no-explicit-any -function wrap(fn, method) { - var arity = fn.length; - switch (arity) { - case 2: { - return function (req, res) { - var transaction = res.__sentry_transaction; - if (transaction) { - var span_1 = transaction.startChild({ - description: fn.name, - op: "middleware." + method, - }); - res.once('finish', function () { - span_1.finish(); - }); - } - return fn.call(this, req, res); - }; - } - case 3: { - return function (req, res, next) { - var _a; - var transaction = res.__sentry_transaction; - var span = (_a = transaction) === null || _a === void 0 ? void 0 : _a.startChild({ - description: fn.name, - op: "middleware." + method, - }); - fn.call(this, req, res, function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - var _a; - (_a = span) === null || _a === void 0 ? void 0 : _a.finish(); - next.call.apply(next, tslib_1.__spread([this], args)); - }); - }; - } - case 4: { - return function (err, req, res, next) { - var _a; - var transaction = res.__sentry_transaction; - var span = (_a = transaction) === null || _a === void 0 ? void 0 : _a.startChild({ - description: fn.name, - op: "middleware." + method, - }); - fn.call(this, err, req, res, function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - var _a; - (_a = span) === null || _a === void 0 ? void 0 : _a.finish(); - next.call.apply(next, tslib_1.__spread([this], args)); - }); - }; - } - default: { - throw new Error("Express middleware takes 2-4 arguments. Got: " + arity); - } + + if (this._last != null) { + this._last.next = node; + this._last = node; + } else { + this._first = this._last = node; } -} -/** - * Takes all the function arguments passed to the original `app` or `router` method, eg. `app.use` or `router.use` - * and wraps every function, as well as array of functions with a call to our `wrap` method. - * We have to take care of the arrays as well as iterate over all of the arguments, - * as `app.use` can accept middlewares in few various forms. - * - * app.use([], ) - * app.use([], , ...) - * app.use([], ...[]) - */ -function wrapMiddlewareArgs(args, method) { - return args.map(function (arg) { - if (typeof arg === 'function') { - return wrap(arg, method); - } - if (Array.isArray(arg)) { - return arg.map(function (a) { - if (typeof a === 'function') { - return wrap(a, method); - } - return a; - }); - } - return arg; - }); -} -/** - * Patches original router to utilize our tracing functionality - */ -function patchMiddleware(router, method) { - var originalCallback = router[method]; - router[method] = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - return originalCallback.call.apply(originalCallback, tslib_1.__spread([this], wrapMiddlewareArgs(args, method))); - }; - return router; -} -/** - * Patches original router methods - */ -function instrumentMiddlewares(router, methods) { - if (methods === void 0) { methods = []; } - methods.forEach(function (method) { return patchMiddleware(router, method); }); -} -//# sourceMappingURL=express.js.map -/***/ }), + return void 0; + } + + shift() { + var ref1, ref2, value; + + if (this._first == null) { + return void 0; + } else { + this.length--; + + if ((ref1 = this._queues) != null) { + ref1.decr(); + } + } + + value = this._first.value; + this._first = (ref2 = this._first.next) != null ? ref2 : this._last = null; + return value; + } + + first() { + if (this._first != null) { + return this._first.value; + } + } + + getArray() { + var node, ref, results; + node = this._first; + results = []; + + while (node != null) { + results.push((ref = node, node = node.next, ref.value)); + } -/***/ 28502: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + return results; + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -var express_1 = __nccwpck_require__(96221); -exports.Express = express_1.Express; -var postgres_1 = __nccwpck_require__(31931); -exports.Postgres = postgres_1.Postgres; -var mysql_1 = __nccwpck_require__(67082); -exports.Mysql = mysql_1.Mysql; -var mongo_1 = __nccwpck_require__(22606); -exports.Mongo = mongo_1.Mongo; -//# sourceMappingURL=index.js.map + forEachShift(cb) { + var node; + node = this.shift(); -/***/ }), + while (node != null) { + cb(node), node = this.shift(); + } -/***/ 22606: -/***/ ((module, exports, __nccwpck_require__) => { + return void 0; + } -/* module decorator */ module = __nccwpck_require__.nmd(module); -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var utils_1 = __nccwpck_require__(1620); -var OPERATIONS = [ - 'aggregate', - 'bulkWrite', - 'countDocuments', - 'createIndex', - 'createIndexes', - 'deleteMany', - 'deleteOne', - 'distinct', - 'drop', - 'dropIndex', - 'dropIndexes', - 'estimatedDocumentCount', - 'findOne', - 'findOneAndDelete', - 'findOneAndReplace', - 'findOneAndUpdate', - 'indexes', - 'indexExists', - 'indexInformation', - 'initializeOrderedBulkOp', - 'insertMany', - 'insertOne', - 'isCapped', - 'mapReduce', - 'options', - 'parallelCollectionScan', - 'rename', - 'replaceOne', - 'stats', - 'updateMany', - 'updateOne', -]; -// All of the operations above take `options` and `callback` as their final parameters, but some of them -// take additional parameters as well. For those operations, this is a map of -// { : [] }, as a way to know what to call the operation's -// positional arguments when we add them to the span's `data` object later -var OPERATION_SIGNATURES = { - // aggregate intentionally not included because `pipeline` arguments are too complex to serialize well - // see https://github.com/getsentry/sentry-javascript/pull/3102 - bulkWrite: ['operations'], - countDocuments: ['query'], - createIndex: ['fieldOrSpec'], - createIndexes: ['indexSpecs'], - deleteMany: ['filter'], - deleteOne: ['filter'], - distinct: ['key', 'query'], - dropIndex: ['indexName'], - findOne: ['query'], - findOneAndDelete: ['filter'], - findOneAndReplace: ['filter', 'replacement'], - findOneAndUpdate: ['filter', 'update'], - indexExists: ['indexes'], - insertMany: ['docs'], - insertOne: ['doc'], - mapReduce: ['map', 'reduce'], - rename: ['newName'], - replaceOne: ['filter', 'doc'], - updateMany: ['filter', 'update'], - updateOne: ['filter', 'update'], }; -/** Tracing integration for mongo package */ -var Mongo = /** @class */ (function () { - /** - * @inheritDoc - */ - function Mongo(options) { - if (options === void 0) { options = {}; } - /** - * @inheritDoc - */ - this.name = Mongo.id; - this._operations = Array.isArray(options.operations) - ? options.operations - : OPERATIONS; - this._describeOperations = 'describeOperations' in options ? options.describeOperations : true; +module.exports = DLList; + +/***/ }), + +/***/ 107: +/***/ ((module) => { + +"use strict"; + + +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } + +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } + +var Events; +Events = class Events { + constructor(instance) { + this.instance = instance; + this._events = {}; + + if (this.instance.on != null || this.instance.once != null || this.instance.removeAllListeners != null) { + throw new Error("An Emitter already exists for this object"); } - /** - * @inheritDoc - */ - Mongo.prototype.setupOnce = function (_, getCurrentHub) { - var collection; - try { - var mongodbModule = utils_1.dynamicRequire(module, 'mongodb'); - collection = mongodbModule.Collection; - } - catch (e) { - utils_1.logger.error('Mongo Integration was unable to require `mongodb` package.'); - return; - } - this._instrumentOperations(collection, this._operations, getCurrentHub); + + this.instance.on = (name, cb) => { + return this._addListener(name, "many", cb); }; - /** - * Patches original collection methods - */ - Mongo.prototype._instrumentOperations = function (collection, operations, getCurrentHub) { - var _this = this; - operations.forEach(function (operation) { return _this._patchOperation(collection, operation, getCurrentHub); }); + + this.instance.once = (name, cb) => { + return this._addListener(name, "once", cb); }; - /** - * Patches original collection to utilize our tracing functionality - */ - Mongo.prototype._patchOperation = function (collection, operation, getCurrentHub) { - if (!(operation in collection.prototype)) - return; - var getSpanContext = this._getSpanContextFromOperationArguments.bind(this); - utils_1.fill(collection.prototype, operation, function (orig) { - return function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - var _a, _b, _c; - var lastArg = args[args.length - 1]; - var scope = getCurrentHub().getScope(); - var parentSpan = (_a = scope) === null || _a === void 0 ? void 0 : _a.getSpan(); - // Check if the operation was passed a callback. (mapReduce requires a different check, as - // its (non-callback) arguments can also be functions.) - if (typeof lastArg !== 'function' || (operation === 'mapReduce' && args.length === 2)) { - var span_1 = (_b = parentSpan) === null || _b === void 0 ? void 0 : _b.startChild(getSpanContext(this, operation, args)); - return orig.call.apply(orig, tslib_1.__spread([this], args)).then(function (res) { - var _a; - (_a = span_1) === null || _a === void 0 ? void 0 : _a.finish(); - return res; - }); - } - var span = (_c = parentSpan) === null || _c === void 0 ? void 0 : _c.startChild(getSpanContext(this, operation, args.slice(0, -1))); - return orig.call.apply(orig, tslib_1.__spread([this], args.slice(0, -1), [function (err, result) { - var _a; - (_a = span) === null || _a === void 0 ? void 0 : _a.finish(); - lastArg(err, result); - }])); - }; - }); + + this.instance.removeAllListeners = (name = null) => { + if (name != null) { + return delete this._events[name]; + } else { + return this._events = {}; + } }; - /** - * Form a SpanContext based on the user input to a given operation. - */ - Mongo.prototype._getSpanContextFromOperationArguments = function (collection, operation, args) { - var data = { - collectionName: collection.collectionName, - dbName: collection.dbName, - namespace: collection.namespace, - }; - var spanContext = { - op: "db", - description: operation, - data: data, - }; - // If the operation takes no arguments besides `options` and `callback`, or if argument - // collection is disabled for this operation, just return early. - var signature = OPERATION_SIGNATURES[operation]; - var shouldDescribe = Array.isArray(this._describeOperations) - ? this._describeOperations.includes(operation) - : this._describeOperations; - if (!signature || !shouldDescribe) { - return spanContext; + } + + _addListener(name, status, cb) { + var base; + + if ((base = this._events)[name] == null) { + base[name] = []; + } + + this._events[name].push({ + cb, + status + }); + + return this.instance; + } + + listenerCount(name) { + if (this._events[name] != null) { + return this._events[name].length; + } else { + return 0; + } + } + + trigger(name, ...args) { + var _this = this; + + return _asyncToGenerator(function* () { + var e, promises; + + try { + if (name !== "debug") { + _this.trigger("debug", `Event triggered: ${name}`, args); } - try { - // Special case for `mapReduce`, as the only one accepting functions as arguments. - if (operation === 'mapReduce') { - var _a = tslib_1.__read(args, 2), map = _a[0], reduce = _a[1]; - data[signature[0]] = typeof map === 'string' ? map : map.name || ''; - data[signature[1]] = typeof reduce === 'string' ? reduce : reduce.name || ''; + + if (_this._events[name] == null) { + return; + } + + _this._events[name] = _this._events[name].filter(function (listener) { + return listener.status !== "none"; + }); + promises = _this._events[name].map( + /*#__PURE__*/ + function () { + var _ref = _asyncToGenerator(function* (listener) { + var e, returned; + + if (listener.status === "none") { + return; } - else { - for (var i = 0; i < signature.length; i++) { - data[signature[i]] = JSON.stringify(args[i]); - } + + if (listener.status === "once") { + listener.status = "none"; } + + try { + returned = typeof listener.cb === "function" ? listener.cb(...args) : void 0; + + if (typeof (returned != null ? returned.then : void 0) === "function") { + return yield returned; + } else { + return returned; + } + } catch (error) { + e = error; + + if (true) { + _this.trigger("error", e); + } + + return null; + } + }); + + return function (_x) { + return _ref.apply(this, arguments); + }; + }()); + return (yield Promise.all(promises)).find(function (x) { + return x != null; + }); + } catch (error) { + e = error; + + if (true) { + _this.trigger("error", e); } - catch (_oO) { - // no-empty - } - return spanContext; - }; - /** - * @inheritDoc - */ - Mongo.id = 'Mongo'; - return Mongo; -}()); -exports.Mongo = Mongo; -//# sourceMappingURL=mongo.js.map + + return null; + } + })(); + } + +}; +module.exports = Events; /***/ }), -/***/ 67082: -/***/ ((module, exports, __nccwpck_require__) => { +/***/ 53068: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/* module decorator */ module = __nccwpck_require__.nmd(module); -Object.defineProperty(exports, "__esModule", ({ value: true })); -var utils_1 = __nccwpck_require__(1620); -/** Tracing integration for node-mysql package */ -var Mysql = /** @class */ (function () { - function Mysql() { - /** - * @inheritDoc - */ - this.name = Mysql.id; +"use strict"; + + +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } + +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } + +function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } + +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } + +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } + +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } + +var Events, Group, IORedisConnection, RedisConnection, Scripts, parser; +parser = __nccwpck_require__(67823); +Events = __nccwpck_require__(107); +RedisConnection = __nccwpck_require__(29992); +IORedisConnection = __nccwpck_require__(47710); +Scripts = __nccwpck_require__(4169); + +Group = function () { + class Group { + constructor(limiterOptions = {}) { + this.deleteKey = this.deleteKey.bind(this); + this.updateSettings = this.updateSettings.bind(this); + this.limiterOptions = limiterOptions; + parser.load(this.limiterOptions, this.defaults, this); + this.Events = new Events(this); + this.instances = {}; + this.Bottleneck = __nccwpck_require__(83911); + + this._startAutoCleanup(); + + this.sharedConnection = this.connection != null; + + if (this.connection == null) { + if (this.limiterOptions.datastore === "redis") { + this.connection = new RedisConnection(Object.assign({}, this.limiterOptions, { + Events: this.Events + })); + } else if (this.limiterOptions.datastore === "ioredis") { + this.connection = new IORedisConnection(Object.assign({}, this.limiterOptions, { + Events: this.Events + })); + } + } } - /** - * @inheritDoc - */ - Mysql.prototype.setupOnce = function (_, getCurrentHub) { - var connection; - try { - // Unfortunatelly mysql is using some custom loading system and `Connection` is not exported directly. - connection = utils_1.dynamicRequire(module, 'mysql/lib/Connection.js'); + + key(key = "") { + var ref; + return (ref = this.instances[key]) != null ? ref : (() => { + var limiter; + limiter = this.instances[key] = new this.Bottleneck(Object.assign(this.limiterOptions, { + id: `${this.id}-${key}`, + timeout: this.timeout, + connection: this.connection + })); + this.Events.trigger("created", limiter, key); + return limiter; + })(); + } + + deleteKey(key = "") { + var _this = this; + + return _asyncToGenerator(function* () { + var deleted, instance; + instance = _this.instances[key]; + + if (_this.connection) { + deleted = yield _this.connection.__runCommand__(['del', ...Scripts.allKeys(`${_this.id}-${key}`)]); } - catch (e) { - utils_1.logger.error('Mysql Integration was unable to require `mysql` package.'); - return; + + if (instance != null) { + delete _this.instances[key]; + yield instance.disconnect(); } - // The original function will have one of these signatures: - // function (callback) => void - // function (options, callback) => void - // function (options, values, callback) => void - utils_1.fill(connection.prototype, 'query', function (orig) { - return function (options, values, callback) { - var _a, _b; - var scope = getCurrentHub().getScope(); - var parentSpan = (_a = scope) === null || _a === void 0 ? void 0 : _a.getSpan(); - var span = (_b = parentSpan) === null || _b === void 0 ? void 0 : _b.startChild({ - description: typeof options === 'string' ? options : options.sql, - op: "db", - }); - if (typeof callback === 'function') { - return orig.call(this, options, values, function (err, result, fields) { - var _a; - (_a = span) === null || _a === void 0 ? void 0 : _a.finish(); - callback(err, result, fields); - }); - } - if (typeof values === 'function') { - return orig.call(this, options, function (err, result, fields) { - var _a; - (_a = span) === null || _a === void 0 ? void 0 : _a.finish(); - values(err, result, fields); - }); - } - return orig.call(this, options, values, callback); - }; + + return instance != null || deleted > 0; + })(); + } + + limiters() { + var k, ref, results, v; + ref = this.instances; + results = []; + + for (k in ref) { + v = ref[k]; + results.push({ + key: k, + limiter: v }); - }; - /** - * @inheritDoc - */ - Mysql.id = 'Mysql'; - return Mysql; -}()); -exports.Mysql = Mysql; -//# sourceMappingURL=mysql.js.map + } + + return results; + } + + keys() { + return Object.keys(this.instances); + } + + clusterKeys() { + var _this2 = this; + + return _asyncToGenerator(function* () { + var cursor, end, found, i, k, keys, len, next, start; + + if (_this2.connection == null) { + return _this2.Promise.resolve(_this2.keys()); + } -/***/ }), + keys = []; + cursor = null; + start = `b_${_this2.id}-`.length; + end = "_settings".length; -/***/ 31931: -/***/ ((module, exports, __nccwpck_require__) => { + while (cursor !== 0) { + var _ref = yield _this2.connection.__runCommand__(["scan", cursor != null ? cursor : 0, "match", `b_${_this2.id}-*_settings`, "count", 10000]); -/* module decorator */ module = __nccwpck_require__.nmd(module); -Object.defineProperty(exports, "__esModule", ({ value: true })); -var utils_1 = __nccwpck_require__(1620); -/** Tracing integration for node-postgres package */ -var Postgres = /** @class */ (function () { - function Postgres() { - /** - * @inheritDoc - */ - this.name = Postgres.id; - } - /** - * @inheritDoc - */ - Postgres.prototype.setupOnce = function (_, getCurrentHub) { - var client; - try { - var pgModule = utils_1.dynamicRequire(module, 'pg'); - client = pgModule.Client; + var _ref2 = _slicedToArray(_ref, 2); + + next = _ref2[0]; + found = _ref2[1]; + cursor = ~~next; + + for (i = 0, len = found.length; i < len; i++) { + k = found[i]; + keys.push(k.slice(start, -end)); + } } - catch (e) { - utils_1.logger.error('Postgres Integration was unable to require `pg` package.'); - return; + + return keys; + })(); + } + + _startAutoCleanup() { + var _this3 = this; + + var base; + clearInterval(this.interval); + return typeof (base = this.interval = setInterval( + /*#__PURE__*/ + _asyncToGenerator(function* () { + var e, k, ref, results, time, v; + time = Date.now(); + ref = _this3.instances; + results = []; + + for (k in ref) { + v = ref[k]; + + try { + if (yield v._store.__groupCheck__(time)) { + results.push(_this3.deleteKey(k)); + } else { + results.push(void 0); + } + } catch (error) { + e = error; + results.push(v.Events.trigger("error", e)); + } } - /** - * function (query, callback) => void - * function (query, params, callback) => void - * function (query) => Promise - * function (query, params) => Promise - */ - utils_1.fill(client.prototype, 'query', function (orig) { - return function (config, values, callback) { - var _a, _b; - var scope = getCurrentHub().getScope(); - var parentSpan = (_a = scope) === null || _a === void 0 ? void 0 : _a.getSpan(); - var span = (_b = parentSpan) === null || _b === void 0 ? void 0 : _b.startChild({ - description: typeof config === 'string' ? config : config.text, - op: "db", - }); - if (typeof callback === 'function') { - return orig.call(this, config, values, function (err, result) { - var _a; - (_a = span) === null || _a === void 0 ? void 0 : _a.finish(); - callback(err, result); - }); - } - if (typeof values === 'function') { - return orig.call(this, config, function (err, result) { - var _a; - (_a = span) === null || _a === void 0 ? void 0 : _a.finish(); - values(err, result); - }); - } - return orig.call(this, config, values).then(function (res) { - var _a; - (_a = span) === null || _a === void 0 ? void 0 : _a.finish(); - return res; - }); - }; - }); - }; - /** - * @inheritDoc - */ - Postgres.id = 'Postgres'; - return Postgres; -}()); -exports.Postgres = Postgres; -//# sourceMappingURL=postgres.js.map -/***/ }), + return results; + }), this.timeout / 2)).unref === "function" ? base.unref() : void 0; + } -/***/ 64655: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + updateSettings(options = {}) { + parser.overwrite(options, this.defaults, this); + parser.overwrite(options, options, this.limiterOptions); -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var utils_1 = __nccwpck_require__(1620); -var spanstatus_1 = __nccwpck_require__(58522); -/** - * Keeps track of finished spans for a given transaction - * @internal - * @hideconstructor - * @hidden - */ -var SpanRecorder = /** @class */ (function () { - function SpanRecorder(maxlen) { - if (maxlen === void 0) { maxlen = 1000; } - this.spans = []; - this._maxlen = maxlen; + if (options.timeout != null) { + return this._startAutoCleanup(); + } } - /** - * This is just so that we don't run out of memory while recording a lot - * of spans. At some point we just stop and flush out the start of the - * trace tree (i.e.the first n spans with the smallest - * start_timestamp). - */ - SpanRecorder.prototype.add = function (span) { - if (this.spans.length > this._maxlen) { - span.spanRecorder = undefined; - } - else { - this.spans.push(span); - } - }; - return SpanRecorder; -}()); -exports.SpanRecorder = SpanRecorder; -/** - * Span contains all data about a span - */ -var Span = /** @class */ (function () { - /** - * You should never call the constructor manually, always use `Sentry.startTransaction()` - * or call `startChild()` on an existing span. - * @internal - * @hideconstructor - * @hidden - */ - function Span(spanContext) { - /** - * @inheritDoc - */ - this.traceId = utils_1.uuid4(); - /** - * @inheritDoc - */ - this.spanId = utils_1.uuid4().substring(16); - /** - * Timestamp in seconds when the span was created. - */ - this.startTimestamp = utils_1.timestampWithMs(); - /** - * @inheritDoc - */ - this.tags = {}; - /** - * @inheritDoc - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - this.data = {}; - if (!spanContext) { - return this; - } - if (spanContext.traceId) { - this.traceId = spanContext.traceId; - } - if (spanContext.spanId) { - this.spanId = spanContext.spanId; - } - if (spanContext.parentSpanId) { - this.parentSpanId = spanContext.parentSpanId; - } - // We want to include booleans as well here - if ('sampled' in spanContext) { - this.sampled = spanContext.sampled; - } - if (spanContext.op) { - this.op = spanContext.op; - } - if (spanContext.description) { - this.description = spanContext.description; - } - if (spanContext.data) { - this.data = spanContext.data; - } - if (spanContext.tags) { - this.tags = spanContext.tags; - } - if (spanContext.status) { - this.status = spanContext.status; - } - if (spanContext.startTimestamp) { - this.startTimestamp = spanContext.startTimestamp; - } - if (spanContext.endTimestamp) { - this.endTimestamp = spanContext.endTimestamp; - } + + disconnect(flush = true) { + var ref; + + if (!this.sharedConnection) { + return (ref = this.connection) != null ? ref.disconnect(flush) : void 0; + } } - /** - * @inheritDoc - * @deprecated - */ - Span.prototype.child = function (spanContext) { - return this.startChild(spanContext); - }; - /** - * @inheritDoc - */ - Span.prototype.startChild = function (spanContext) { - var childSpan = new Span(tslib_1.__assign(tslib_1.__assign({}, spanContext), { parentSpanId: this.spanId, sampled: this.sampled, traceId: this.traceId })); - childSpan.spanRecorder = this.spanRecorder; - if (childSpan.spanRecorder) { - childSpan.spanRecorder.add(childSpan); - } - childSpan.transaction = this.transaction; - return childSpan; - }; - /** - * @inheritDoc - */ - Span.prototype.setTag = function (key, value) { - var _a; - this.tags = tslib_1.__assign(tslib_1.__assign({}, this.tags), (_a = {}, _a[key] = value, _a)); - return this; - }; - /** - * @inheritDoc - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types - Span.prototype.setData = function (key, value) { - var _a; - this.data = tslib_1.__assign(tslib_1.__assign({}, this.data), (_a = {}, _a[key] = value, _a)); - return this; - }; - /** - * @inheritDoc - */ - Span.prototype.setStatus = function (value) { - this.status = value; - return this; - }; - /** - * @inheritDoc - */ - Span.prototype.setHttpStatus = function (httpStatus) { - this.setTag('http.status_code', String(httpStatus)); - var spanStatus = spanstatus_1.SpanStatus.fromHttpCode(httpStatus); - if (spanStatus !== spanstatus_1.SpanStatus.UnknownError) { - this.setStatus(spanStatus); - } - return this; - }; - /** - * @inheritDoc - */ - Span.prototype.isSuccess = function () { - return this.status === spanstatus_1.SpanStatus.Ok; - }; - /** - * @inheritDoc - */ - Span.prototype.finish = function (endTimestamp) { - this.endTimestamp = typeof endTimestamp === 'number' ? endTimestamp : utils_1.timestampWithMs(); - }; - /** - * @inheritDoc - */ - Span.prototype.toTraceparent = function () { - var sampledString = ''; - if (this.sampled !== undefined) { - sampledString = this.sampled ? '-1' : '-0'; - } - return this.traceId + "-" + this.spanId + sampledString; - }; - /** - * @inheritDoc - */ - Span.prototype.getTraceContext = function () { - return utils_1.dropUndefinedKeys({ - data: Object.keys(this.data).length > 0 ? this.data : undefined, - description: this.description, - op: this.op, - parent_span_id: this.parentSpanId, - span_id: this.spanId, - status: this.status, - tags: Object.keys(this.tags).length > 0 ? this.tags : undefined, - trace_id: this.traceId, - }); - }; - /** - * @inheritDoc - */ - Span.prototype.toJSON = function () { - return utils_1.dropUndefinedKeys({ - data: Object.keys(this.data).length > 0 ? this.data : undefined, - description: this.description, - op: this.op, - parent_span_id: this.parentSpanId, - span_id: this.spanId, - start_timestamp: this.startTimestamp, - status: this.status, - tags: Object.keys(this.tags).length > 0 ? this.tags : undefined, - timestamp: this.endTimestamp, - trace_id: this.traceId, - }); - }; - return Span; -}()); -exports.Span = Span; -//# sourceMappingURL=span.js.map + + } + + ; + Group.prototype.defaults = { + timeout: 1000 * 60 * 5, + connection: null, + Promise: Promise, + id: "group-key" + }; + return Group; +}.call(void 0); + +module.exports = Group; /***/ }), -/***/ 58522: -/***/ ((__unused_webpack_module, exports) => { +/***/ 47710: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -Object.defineProperty(exports, "__esModule", ({ value: true })); -/** The status of an Span. */ -// eslint-disable-next-line import/export -var SpanStatus; -(function (SpanStatus) { - /** The operation completed successfully. */ - SpanStatus["Ok"] = "ok"; - /** Deadline expired before operation could complete. */ - SpanStatus["DeadlineExceeded"] = "deadline_exceeded"; - /** 401 Unauthorized (actually does mean unauthenticated according to RFC 7235) */ - SpanStatus["Unauthenticated"] = "unauthenticated"; - /** 403 Forbidden */ - SpanStatus["PermissionDenied"] = "permission_denied"; - /** 404 Not Found. Some requested entity (file or directory) was not found. */ - SpanStatus["NotFound"] = "not_found"; - /** 429 Too Many Requests */ - SpanStatus["ResourceExhausted"] = "resource_exhausted"; - /** Client specified an invalid argument. 4xx. */ - SpanStatus["InvalidArgument"] = "invalid_argument"; - /** 501 Not Implemented */ - SpanStatus["Unimplemented"] = "unimplemented"; - /** 503 Service Unavailable */ - SpanStatus["Unavailable"] = "unavailable"; - /** Other/generic 5xx. */ - SpanStatus["InternalError"] = "internal_error"; - /** Unknown. Any non-standard HTTP status code. */ - SpanStatus["UnknownError"] = "unknown_error"; - /** The operation was cancelled (typically by the user). */ - SpanStatus["Cancelled"] = "cancelled"; - /** Already exists (409) */ - SpanStatus["AlreadyExists"] = "already_exists"; - /** Operation was rejected because the system is not in a state required for the operation's */ - SpanStatus["FailedPrecondition"] = "failed_precondition"; - /** The operation was aborted, typically due to a concurrency issue. */ - SpanStatus["Aborted"] = "aborted"; - /** Operation was attempted past the valid range. */ - SpanStatus["OutOfRange"] = "out_of_range"; - /** Unrecoverable data loss or corruption */ - SpanStatus["DataLoss"] = "data_loss"; -})(SpanStatus = exports.SpanStatus || (exports.SpanStatus = {})); -// eslint-disable-next-line @typescript-eslint/no-namespace, import/export -(function (SpanStatus) { - /** - * Converts a HTTP status code into a {@link SpanStatus}. - * - * @param httpStatus The HTTP response status code. - * @returns The span status or {@link SpanStatus.UnknownError}. - */ - function fromHttpCode(httpStatus) { - if (httpStatus < 400) { - return SpanStatus.Ok; - } - if (httpStatus >= 400 && httpStatus < 500) { - switch (httpStatus) { - case 401: - return SpanStatus.Unauthenticated; - case 403: - return SpanStatus.PermissionDenied; - case 404: - return SpanStatus.NotFound; - case 409: - return SpanStatus.AlreadyExists; - case 413: - return SpanStatus.FailedPrecondition; - case 429: - return SpanStatus.ResourceExhausted; - default: - return SpanStatus.InvalidArgument; - } +"use strict"; + + +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } + +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } + +function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } + +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } + +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } + +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } + +var Events, IORedisConnection, Scripts, parser; +parser = __nccwpck_require__(67823); +Events = __nccwpck_require__(107); +Scripts = __nccwpck_require__(4169); + +IORedisConnection = function () { + class IORedisConnection { + constructor(options = {}) { + var Redis; + Redis = eval("require")("ioredis"); // Obfuscated or else Webpack/Angular will try to inline the optional ioredis module + + parser.load(options, this.defaults, this); + + if (this.Events == null) { + this.Events = new Events(this); + } + + this.terminated = false; + + if (this.clusterNodes != null) { + this.client = new Redis.Cluster(this.clusterNodes, this.clientOptions); + this.subscriber = new Redis.Cluster(this.clusterNodes, this.clientOptions); + } else { + if (this.client == null) { + this.client = new Redis(this.clientOptions); } - if (httpStatus >= 500 && httpStatus < 600) { - switch (httpStatus) { - case 501: - return SpanStatus.Unimplemented; - case 503: - return SpanStatus.Unavailable; - case 504: - return SpanStatus.DeadlineExceeded; - default: - return SpanStatus.InternalError; - } + + this.subscriber = this.client.duplicate(); + } + + this.limiters = {}; + this.ready = this.Promise.all([this._setup(this.client, false), this._setup(this.subscriber, true)]).then(() => { + this._loadScripts(); + + return { + client: this.client, + subscriber: this.subscriber + }; + }); + } + + _setup(client, sub) { + client.setMaxListeners(0); + return new this.Promise((resolve, reject) => { + client.on("error", e => { + return this.Events.trigger("error", e); + }); + + if (sub) { + client.on("message", (channel, message) => { + var ref; + return (ref = this.limiters[channel]) != null ? ref._store.onMessage(channel, message) : void 0; + }); } - return SpanStatus.UnknownError; + + if (client.status === "ready") { + return resolve(); + } else { + return client.once("ready", resolve); + } + }); } - SpanStatus.fromHttpCode = fromHttpCode; -})(SpanStatus = exports.SpanStatus || (exports.SpanStatus = {})); -//# sourceMappingURL=spanstatus.js.map -/***/ }), + _loadScripts() { + return Scripts.names.forEach(name => { + return this.client.defineCommand(name, { + lua: Scripts.payload(name) + }); + }); + } -/***/ 8186: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + __runCommand__(cmd) { + var _this = this; -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var hub_1 = __nccwpck_require__(6393); -var utils_1 = __nccwpck_require__(1620); -var span_1 = __nccwpck_require__(64655); -/** JSDoc */ -var Transaction = /** @class */ (function (_super) { - tslib_1.__extends(Transaction, _super); - /** - * This constructor should never be called manually. Those instrumenting tracing should use - * `Sentry.startTransaction()`, and internal methods should use `hub.startTransaction()`. - * @internal - * @hideconstructor - * @hidden - */ - function Transaction(transactionContext, hub) { - var _this = _super.call(this, transactionContext) || this; - _this._measurements = {}; - /** - * The reference to the current hub. - */ - _this._hub = hub_1.getCurrentHub(); - if (utils_1.isInstanceOf(hub, hub_1.Hub)) { - _this._hub = hub; - } - _this.name = transactionContext.name ? transactionContext.name : ''; - _this._trimEnd = transactionContext.trimEnd; - // this is because transactions are also spans, and spans have a transaction pointer - _this.transaction = _this; - return _this; + return _asyncToGenerator(function* () { + var _, deleted; + + yield _this.ready; + + var _ref = yield _this.client.pipeline([cmd]).exec(); + + var _ref2 = _slicedToArray(_ref, 1); + + var _ref2$ = _slicedToArray(_ref2[0], 2); + + _ = _ref2$[0]; + deleted = _ref2$[1]; + return deleted; + })(); } - /** - * JSDoc - */ - Transaction.prototype.setName = function (name) { - this.name = name; - }; - /** - * Attaches SpanRecorder to the span itself - * @param maxlen maximum number of spans that can be recorded - */ - Transaction.prototype.initSpanRecorder = function (maxlen) { - if (maxlen === void 0) { maxlen = 1000; } - if (!this.spanRecorder) { - this.spanRecorder = new span_1.SpanRecorder(maxlen); - } - this.spanRecorder.add(this); - }; - /** - * Set observed measurements for this transaction. - * @hidden - */ - Transaction.prototype.setMeasurements = function (measurements) { - this._measurements = tslib_1.__assign({}, measurements); - }; - /** - * @inheritDoc - */ - Transaction.prototype.finish = function (endTimestamp) { - var _this = this; - // This transaction is already finished, so we should not flush it again. - if (this.endTimestamp !== undefined) { - return undefined; - } - if (!this.name) { - utils_1.logger.warn('Transaction has no name, falling back to ``.'); - this.name = ''; - } - // just sets the end timestamp - _super.prototype.finish.call(this, endTimestamp); - if (this.sampled !== true) { - // At this point if `sampled !== true` we want to discard the transaction. - utils_1.logger.log('[Tracing] Discarding transaction because its trace was not chosen to be sampled.'); - return undefined; - } - var finishedSpans = this.spanRecorder ? this.spanRecorder.spans.filter(function (s) { return s !== _this && s.endTimestamp; }) : []; - if (this._trimEnd && finishedSpans.length > 0) { - this.endTimestamp = finishedSpans.reduce(function (prev, current) { - if (prev.endTimestamp && current.endTimestamp) { - return prev.endTimestamp > current.endTimestamp ? prev : current; - } - return prev; - }).endTimestamp; - } - var transaction = { - contexts: { - trace: this.getTraceContext(), - }, - spans: finishedSpans, - start_timestamp: this.startTimestamp, - tags: this.tags, - timestamp: this.endTimestamp, - transaction: this.name, - type: 'transaction', - }; - var hasMeasurements = Object.keys(this._measurements).length > 0; - if (hasMeasurements) { - utils_1.logger.log('[Measurements] Adding measurements to transaction', JSON.stringify(this._measurements, undefined, 2)); - transaction.measurements = this._measurements; - } - return this._hub.captureEvent(transaction); - }; - return Transaction; -}(span_1.Span)); -exports.Transaction = Transaction; -//# sourceMappingURL=transaction.js.map -/***/ }), + __addLimiter__(instance) { + return this.Promise.all([instance.channel(), instance.channel_client()].map(channel => { + return new this.Promise((resolve, reject) => { + return this.subscriber.subscribe(channel, () => { + this.limiters[channel] = instance; + return resolve(); + }); + }); + })); + } -/***/ 31386: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + __removeLimiter__(instance) { + var _this2 = this; -Object.defineProperty(exports, "__esModule", ({ value: true })); -var hub_1 = __nccwpck_require__(6393); -exports.TRACEPARENT_REGEXP = new RegExp('^[ \\t]*' + // whitespace - '([0-9a-f]{32})?' + // trace_id - '-?([0-9a-f]{16})?' + // span_id - '-?([01])?' + // sampled - '[ \\t]*$'); -/** - * Determines if tracing is currently enabled. - * - * Tracing is enabled when at least one of `tracesSampleRate` and `tracesSampler` is defined in the SDK config. - */ -function hasTracingEnabled(options) { - return 'tracesSampleRate' in options || 'tracesSampler' in options; -} -exports.hasTracingEnabled = hasTracingEnabled; -/** - * Extract transaction context data from a `sentry-trace` header. - * - * @param traceparent Traceparent string - * - * @returns Object containing data from the header, or undefined if traceparent string is malformed - */ -function extractTraceparentData(traceparent) { - var matches = traceparent.match(exports.TRACEPARENT_REGEXP); - if (matches) { - var parentSampled = void 0; - if (matches[3] === '1') { - parentSampled = true; - } - else if (matches[3] === '0') { - parentSampled = false; - } - return { - traceId: matches[1], - parentSampled: parentSampled, - parentSpanId: matches[2], + return [instance.channel(), instance.channel_client()].forEach( + /*#__PURE__*/ + function () { + var _ref3 = _asyncToGenerator(function* (channel) { + if (!_this2.terminated) { + yield _this2.subscriber.unsubscribe(channel); + } + + return delete _this2.limiters[channel]; + }); + + return function (_x) { + return _ref3.apply(this, arguments); }; + }()); } - return undefined; -} -exports.extractTraceparentData = extractTraceparentData; -/** Grabs active transaction off scope, if any */ -function getActiveTransaction(hub) { - if (hub === void 0) { hub = hub_1.getCurrentHub(); } - var _a, _b; - return (_b = (_a = hub) === null || _a === void 0 ? void 0 : _a.getScope()) === null || _b === void 0 ? void 0 : _b.getTransaction(); -} -exports.getActiveTransaction = getActiveTransaction; -/** - * Converts from milliseconds to seconds - * @param time time in ms - */ -function msToSec(time) { - return time / 1000; -} -exports.msToSec = msToSec; -/** - * Converts from seconds to milliseconds - * @param time time in seconds - */ -function secToMs(time) { - return time * 1000; -} -exports.secToMs = secToMs; -// so it can be used in manual instrumentation without necessitating a hard dependency on @sentry/utils -var utils_1 = __nccwpck_require__(1620); -exports.stripUrlQueryAndFragment = utils_1.stripUrlQueryAndFragment; -//# sourceMappingURL=utils.js.map -/***/ }), + __scriptArgs__(name, id, args, cb) { + var keys; + keys = Scripts.keys(name, id); + return [keys.length].concat(keys, args, cb); + } -/***/ 83789: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + __scriptFn__(name) { + return this.client[name].bind(this.client); + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -var loglevel_1 = __nccwpck_require__(6853); -exports.LogLevel = loglevel_1.LogLevel; -var session_1 = __nccwpck_require__(84954); -exports.SessionStatus = session_1.SessionStatus; -var severity_1 = __nccwpck_require__(94124); -exports.Severity = severity_1.Severity; -var status_1 = __nccwpck_require__(61277); -exports.Status = status_1.Status; -var transaction_1 = __nccwpck_require__(47540); -exports.TransactionSamplingMethod = transaction_1.TransactionSamplingMethod; -//# sourceMappingURL=index.js.map + disconnect(flush = true) { + var i, k, len, ref; + ref = Object.keys(this.limiters); -/***/ }), + for (i = 0, len = ref.length; i < len; i++) { + k = ref[i]; + clearInterval(this.limiters[k]._store.heartbeat); + } -/***/ 6853: -/***/ ((__unused_webpack_module, exports) => { + this.limiters = {}; + this.terminated = true; -Object.defineProperty(exports, "__esModule", ({ value: true })); -/** Console logging verbosity for the SDK. */ -var LogLevel; -(function (LogLevel) { - /** No logs will be generated. */ - LogLevel[LogLevel["None"] = 0] = "None"; - /** Only SDK internal errors will be logged. */ - LogLevel[LogLevel["Error"] = 1] = "Error"; - /** Information useful for debugging the SDK will be logged. */ - LogLevel[LogLevel["Debug"] = 2] = "Debug"; - /** All SDK actions will be logged. */ - LogLevel[LogLevel["Verbose"] = 3] = "Verbose"; -})(LogLevel = exports.LogLevel || (exports.LogLevel = {})); -//# sourceMappingURL=loglevel.js.map + if (flush) { + return this.Promise.all([this.client.quit(), this.subscriber.quit()]); + } else { + this.client.disconnect(); + this.subscriber.disconnect(); + return this.Promise.resolve(); + } + } -/***/ }), + } -/***/ 84954: -/***/ ((__unused_webpack_module, exports) => { + ; + IORedisConnection.prototype.datastore = "ioredis"; + IORedisConnection.prototype.defaults = { + clientOptions: {}, + clusterNodes: null, + client: null, + Promise: Promise, + Events: null + }; + return IORedisConnection; +}.call(void 0); -Object.defineProperty(exports, "__esModule", ({ value: true })); -/** - * Session Status - */ -var SessionStatus; -(function (SessionStatus) { - /** JSDoc */ - SessionStatus["Ok"] = "ok"; - /** JSDoc */ - SessionStatus["Exited"] = "exited"; - /** JSDoc */ - SessionStatus["Crashed"] = "crashed"; - /** JSDoc */ - SessionStatus["Abnormal"] = "abnormal"; -})(SessionStatus = exports.SessionStatus || (exports.SessionStatus = {})); -//# sourceMappingURL=session.js.map +module.exports = IORedisConnection; /***/ }), -/***/ 94124: -/***/ ((__unused_webpack_module, exports) => { +/***/ 38979: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -Object.defineProperty(exports, "__esModule", ({ value: true })); -/** JSDoc */ -// eslint-disable-next-line import/export -var Severity; -(function (Severity) { - /** JSDoc */ - Severity["Fatal"] = "fatal"; - /** JSDoc */ - Severity["Error"] = "error"; - /** JSDoc */ - Severity["Warning"] = "warning"; - /** JSDoc */ - Severity["Log"] = "log"; - /** JSDoc */ - Severity["Info"] = "info"; - /** JSDoc */ - Severity["Debug"] = "debug"; - /** JSDoc */ - Severity["Critical"] = "critical"; -})(Severity = exports.Severity || (exports.Severity = {})); -// eslint-disable-next-line @typescript-eslint/no-namespace, import/export -(function (Severity) { - /** - * Converts a string-based level into a {@link Severity}. - * - * @param level string representation of Severity - * @returns Severity - */ - function fromString(level) { - switch (level) { - case 'debug': - return Severity.Debug; - case 'info': - return Severity.Info; - case 'warn': - case 'warning': - return Severity.Warning; - case 'error': - return Severity.Error; - case 'fatal': - return Severity.Fatal; - case 'critical': - return Severity.Critical; - case 'log': - default: - return Severity.Log; - } - } - Severity.fromString = fromString; -})(Severity = exports.Severity || (exports.Severity = {})); -//# sourceMappingURL=severity.js.map +"use strict"; -/***/ }), -/***/ 61277: -/***/ ((__unused_webpack_module, exports) => { +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } -Object.defineProperty(exports, "__esModule", ({ value: true })); -/** The status of an event. */ -// eslint-disable-next-line import/export -var Status; -(function (Status) { - /** The status could not be determined. */ - Status["Unknown"] = "unknown"; - /** The event was skipped due to configuration or callbacks. */ - Status["Skipped"] = "skipped"; - /** The event was sent to Sentry successfully. */ - Status["Success"] = "success"; - /** The client is currently rate limited and will try again later. */ - Status["RateLimit"] = "rate_limit"; - /** The event could not be processed. */ - Status["Invalid"] = "invalid"; - /** A server-side error ocurred during submission. */ - Status["Failed"] = "failed"; -})(Status = exports.Status || (exports.Status = {})); -// eslint-disable-next-line @typescript-eslint/no-namespace, import/export -(function (Status) { - /** - * Converts a HTTP status code into a {@link Status}. - * - * @param code The HTTP response status code. - * @returns The send status or {@link Status.Unknown}. - */ - function fromHttpCode(code) { - if (code >= 200 && code < 300) { - return Status.Success; - } - if (code === 429) { - return Status.RateLimit; - } - if (code >= 400 && code < 500) { - return Status.Invalid; - } - if (code >= 500) { - return Status.Failed; +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } + +var BottleneckError, LocalDatastore, parser; +parser = __nccwpck_require__(67823); +BottleneckError = __nccwpck_require__(93529); +LocalDatastore = class LocalDatastore { + constructor(instance, storeOptions, storeInstanceOptions) { + this.instance = instance; + this.storeOptions = storeOptions; + this.clientId = this.instance._randomIndex(); + parser.load(storeInstanceOptions, storeInstanceOptions, this); + this._nextRequest = this._lastReservoirRefresh = Date.now(); + this._running = 0; + this._done = 0; + this._unblockTime = 0; + this.ready = this.Promise.resolve(); + this.clients = {}; + + this._startHeartbeat(); + } + + _startHeartbeat() { + var base; + + if (this.heartbeat == null && this.storeOptions.reservoirRefreshInterval != null && this.storeOptions.reservoirRefreshAmount != null) { + return typeof (base = this.heartbeat = setInterval(() => { + var now; + now = Date.now(); + + if (now >= this._lastReservoirRefresh + this.storeOptions.reservoirRefreshInterval) { + this.storeOptions.reservoir = this.storeOptions.reservoirRefreshAmount; + this._lastReservoirRefresh = now; + return this.instance._drainAll(this.computeCapacity()); } - return Status.Unknown; + }, this.heartbeatInterval)).unref === "function" ? base.unref() : void 0; + } else { + return clearInterval(this.heartbeat); } - Status.fromHttpCode = fromHttpCode; -})(Status = exports.Status || (exports.Status = {})); -//# sourceMappingURL=status.js.map + } + + __publish__(message) { + var _this = this; + + return _asyncToGenerator(function* () { + yield _this.yieldLoop(); + return _this.instance.Events.trigger("message", message.toString()); + })(); + } + + __disconnect__(flush) { + var _this2 = this; + + return _asyncToGenerator(function* () { + yield _this2.yieldLoop(); + clearInterval(_this2.heartbeat); + return _this2.Promise.resolve(); + })(); + } + + yieldLoop(t = 0) { + return new this.Promise(function (resolve, reject) { + return setTimeout(resolve, t); + }); + } + + computePenalty() { + var ref; + return (ref = this.storeOptions.penalty) != null ? ref : 15 * this.storeOptions.minTime || 5000; + } + + __updateSettings__(options) { + var _this3 = this; + + return _asyncToGenerator(function* () { + yield _this3.yieldLoop(); + parser.overwrite(options, options, _this3.storeOptions); + + _this3._startHeartbeat(); + + _this3.instance._drainAll(_this3.computeCapacity()); + + return true; + })(); + } -/***/ }), + __running__() { + var _this4 = this; -/***/ 47540: -/***/ ((__unused_webpack_module, exports) => { + return _asyncToGenerator(function* () { + yield _this4.yieldLoop(); + return _this4._running; + })(); + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -var TransactionSamplingMethod; -(function (TransactionSamplingMethod) { - TransactionSamplingMethod["Explicit"] = "explicitly_set"; - TransactionSamplingMethod["Sampler"] = "client_sampler"; - TransactionSamplingMethod["Rate"] = "client_rate"; - TransactionSamplingMethod["Inheritance"] = "inheritance"; -})(TransactionSamplingMethod = exports.TransactionSamplingMethod || (exports.TransactionSamplingMethod = {})); -//# sourceMappingURL=transaction.js.map + __queued__() { + var _this5 = this; -/***/ }), + return _asyncToGenerator(function* () { + yield _this5.yieldLoop(); + return _this5.instance.queued(); + })(); + } -/***/ 58343: -/***/ ((__unused_webpack_module, exports) => { + __done__() { + var _this6 = this; -Object.defineProperty(exports, "__esModule", ({ value: true })); -/** - * Consumes the promise and logs the error when it rejects. - * @param promise A promise to forget. - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function forget(promise) { - promise.then(null, function (e) { - // TODO: Use a better logging mechanism - // eslint-disable-next-line no-console - console.error(e); - }); -} -exports.forget = forget; -//# sourceMappingURL=async.js.map + return _asyncToGenerator(function* () { + yield _this6.yieldLoop(); + return _this6._done; + })(); + } -/***/ }), + __groupCheck__(time) { + var _this7 = this; -/***/ 30597: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + return _asyncToGenerator(function* () { + yield _this7.yieldLoop(); + return _this7._nextRequest + _this7.timeout < time; + })(); + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -var is_1 = __nccwpck_require__(92757); -/** - * Given a child DOM element, returns a query-selector statement describing that - * and its ancestors - * e.g. [HTMLElement] => body > div > input#foo.btn[name=baz] - * @returns generated DOM path - */ -function htmlTreeAsString(elem) { - // try/catch both: - // - accessing event.target (see getsentry/raven-js#838, #768) - // - `htmlTreeAsString` because it's complex, and just accessing the DOM incorrectly - // - can throw an exception in some circumstances. - try { - var currentElem = elem; - var MAX_TRAVERSE_HEIGHT = 5; - var MAX_OUTPUT_LEN = 80; - var out = []; - var height = 0; - var len = 0; - var separator = ' > '; - var sepLength = separator.length; - var nextStr = void 0; - // eslint-disable-next-line no-plusplus - while (currentElem && height++ < MAX_TRAVERSE_HEIGHT) { - nextStr = _htmlElementAsString(currentElem); - // bail out if - // - nextStr is the 'html' element - // - the length of the string that would be created exceeds MAX_OUTPUT_LEN - // (ignore this limit if we are on the first iteration) - if (nextStr === 'html' || (height > 1 && len + out.length * sepLength + nextStr.length >= MAX_OUTPUT_LEN)) { - break; - } - out.push(nextStr); - len += nextStr.length; - currentElem = currentElem.parentNode; - } - return out.reverse().join(separator); - } - catch (_oO) { - return ''; - } -} -exports.htmlTreeAsString = htmlTreeAsString; -/** - * Returns a simple, query-selector representation of a DOM element - * e.g. [HTMLElement] => input#foo.btn[name=baz] - * @returns generated DOM path - */ -function _htmlElementAsString(el) { - var elem = el; - var out = []; - var className; - var classes; - var key; - var attr; - var i; - if (!elem || !elem.tagName) { - return ''; - } - out.push(elem.tagName.toLowerCase()); - if (elem.id) { - out.push("#" + elem.id); - } - // eslint-disable-next-line prefer-const - className = elem.className; - if (className && is_1.isString(className)) { - classes = className.split(/\s+/); - for (i = 0; i < classes.length; i++) { - out.push("." + classes[i]); - } - } - var allowedAttrs = ['type', 'name', 'title', 'alt']; - for (i = 0; i < allowedAttrs.length; i++) { - key = allowedAttrs[i]; - attr = elem.getAttribute(key); - if (attr) { - out.push("[" + key + "=\"" + attr + "\"]"); - } + computeCapacity() { + var maxConcurrent, reservoir; + var _this$storeOptions = this.storeOptions; + maxConcurrent = _this$storeOptions.maxConcurrent; + reservoir = _this$storeOptions.reservoir; + + if (maxConcurrent != null && reservoir != null) { + return Math.min(maxConcurrent - this._running, reservoir); + } else if (maxConcurrent != null) { + return maxConcurrent - this._running; + } else if (reservoir != null) { + return reservoir; + } else { + return null; } - return out.join(''); -} -//# sourceMappingURL=browser.js.map + } -/***/ }), + conditionsCheck(weight) { + var capacity; + capacity = this.computeCapacity(); + return capacity == null || weight <= capacity; + } -/***/ 3275: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + __incrementReservoir__(incr) { + var _this8 = this; -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var error_1 = __nccwpck_require__(66238); -/** Regular expression used to parse a Dsn. */ -var DSN_REGEX = /^(?:(\w+):)\/\/(?:(\w+)(?::(\w+))?@)([\w.-]+)(?::(\d+))?\/(.+)/; -/** Error message */ -var ERROR_MESSAGE = 'Invalid Dsn'; -/** The Sentry Dsn, identifying a Sentry instance and project. */ -var Dsn = /** @class */ (function () { - /** Creates a new Dsn component */ - function Dsn(from) { - if (typeof from === 'string') { - this._fromString(from); - } - else { - this._fromComponents(from); - } - this._validate(); - } - /** - * Renders the string representation of this Dsn. - * - * By default, this will render the public representation without the password - * component. To get the deprecated private representation, set `withPassword` - * to true. - * - * @param withPassword When set to true, the password will be included. - */ - Dsn.prototype.toString = function (withPassword) { - if (withPassword === void 0) { withPassword = false; } - var _a = this, host = _a.host, path = _a.path, pass = _a.pass, port = _a.port, projectId = _a.projectId, protocol = _a.protocol, user = _a.user; - return (protocol + "://" + user + (withPassword && pass ? ":" + pass : '') + - ("@" + host + (port ? ":" + port : '') + "/" + (path ? path + "/" : path) + projectId)); - }; - /** Parses a string into this Dsn. */ - Dsn.prototype._fromString = function (str) { - var match = DSN_REGEX.exec(str); - if (!match) { - throw new error_1.SentryError(ERROR_MESSAGE); - } - var _a = tslib_1.__read(match.slice(1), 6), protocol = _a[0], user = _a[1], _b = _a[2], pass = _b === void 0 ? '' : _b, host = _a[3], _c = _a[4], port = _c === void 0 ? '' : _c, lastPath = _a[5]; - var path = ''; - var projectId = lastPath; - var split = projectId.split('/'); - if (split.length > 1) { - path = split.slice(0, -1).join('/'); - projectId = split.pop(); - } - if (projectId) { - var projectMatch = projectId.match(/^\d+/); - if (projectMatch) { - projectId = projectMatch[0]; - } - } - this._fromComponents({ host: host, pass: pass, path: path, projectId: projectId, port: port, protocol: protocol, user: user }); - }; - /** Maps Dsn components into this instance. */ - Dsn.prototype._fromComponents = function (components) { - this.protocol = components.protocol; - this.user = components.user; - this.pass = components.pass || ''; - this.host = components.host; - this.port = components.port || ''; - this.path = components.path || ''; - this.projectId = components.projectId; - }; - /** Validates this Dsn and throws on error. */ - Dsn.prototype._validate = function () { - var _this = this; - ['protocol', 'user', 'host', 'projectId'].forEach(function (component) { - if (!_this[component]) { - throw new error_1.SentryError(ERROR_MESSAGE + ": " + component + " missing"); - } - }); - if (!this.projectId.match(/^\d+$/)) { - throw new error_1.SentryError(ERROR_MESSAGE + ": Invalid projectId " + this.projectId); - } - if (this.protocol !== 'http' && this.protocol !== 'https') { - throw new error_1.SentryError(ERROR_MESSAGE + ": Invalid protocol " + this.protocol); - } - if (this.port && isNaN(parseInt(this.port, 10))) { - throw new error_1.SentryError(ERROR_MESSAGE + ": Invalid port " + this.port); - } - }; - return Dsn; -}()); -exports.Dsn = Dsn; -//# sourceMappingURL=dsn.js.map + return _asyncToGenerator(function* () { + var reservoir; + yield _this8.yieldLoop(); + reservoir = _this8.storeOptions.reservoir += incr; -/***/ }), + _this8.instance._drainAll(_this8.computeCapacity()); -/***/ 66238: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + return reservoir; + })(); + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var polyfill_1 = __nccwpck_require__(1243); -/** An error emitted by Sentry SDKs and related utilities. */ -var SentryError = /** @class */ (function (_super) { - tslib_1.__extends(SentryError, _super); - function SentryError(message) { - var _newTarget = this.constructor; - var _this = _super.call(this, message) || this; - _this.message = message; - _this.name = _newTarget.prototype.constructor.name; - polyfill_1.setPrototypeOf(_this, _newTarget.prototype); - return _this; - } - return SentryError; -}(Error)); -exports.SentryError = SentryError; -//# sourceMappingURL=error.js.map + __currentReservoir__() { + var _this9 = this; -/***/ }), + return _asyncToGenerator(function* () { + yield _this9.yieldLoop(); + return _this9.storeOptions.reservoir; + })(); + } -/***/ 1620: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + isBlocked(now) { + return this._unblockTime >= now; + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -tslib_1.__exportStar(__nccwpck_require__(58343), exports); -tslib_1.__exportStar(__nccwpck_require__(30597), exports); -tslib_1.__exportStar(__nccwpck_require__(3275), exports); -tslib_1.__exportStar(__nccwpck_require__(66238), exports); -tslib_1.__exportStar(__nccwpck_require__(65474), exports); -tslib_1.__exportStar(__nccwpck_require__(92757), exports); -tslib_1.__exportStar(__nccwpck_require__(15577), exports); -tslib_1.__exportStar(__nccwpck_require__(49515), exports); -tslib_1.__exportStar(__nccwpck_require__(32154), exports); -tslib_1.__exportStar(__nccwpck_require__(16411), exports); -tslib_1.__exportStar(__nccwpck_require__(69249), exports); -tslib_1.__exportStar(__nccwpck_require__(39188), exports); -tslib_1.__exportStar(__nccwpck_require__(31811), exports); -tslib_1.__exportStar(__nccwpck_require__(5986), exports); -tslib_1.__exportStar(__nccwpck_require__(66538), exports); -tslib_1.__exportStar(__nccwpck_require__(88714), exports); -tslib_1.__exportStar(__nccwpck_require__(87833), exports); -tslib_1.__exportStar(__nccwpck_require__(1735), exports); -//# sourceMappingURL=index.js.map + check(weight, now) { + return this.conditionsCheck(weight) && this._nextRequest - now <= 0; + } -/***/ }), + __check__(weight) { + var _this10 = this; -/***/ 65474: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + return _asyncToGenerator(function* () { + var now; + yield _this10.yieldLoop(); + now = Date.now(); + return _this10.check(weight, now); + })(); + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var is_1 = __nccwpck_require__(92757); -var logger_1 = __nccwpck_require__(15577); -var misc_1 = __nccwpck_require__(32154); -var object_1 = __nccwpck_require__(69249); -var stacktrace_1 = __nccwpck_require__(5986); -var supports_1 = __nccwpck_require__(88714); -var global = misc_1.getGlobalObject(); -/** - * Instrument native APIs to call handlers that can be used to create breadcrumbs, APM spans etc. - * - Console API - * - Fetch API - * - XHR API - * - History API - * - DOM API (click/typing) - * - Error API - * - UnhandledRejection API - */ -var handlers = {}; -var instrumented = {}; -/** Instruments given API */ -function instrument(type) { - if (instrumented[type]) { - return; - } - instrumented[type] = true; - switch (type) { - case 'console': - instrumentConsole(); - break; - case 'dom': - instrumentDOM(); - break; - case 'xhr': - instrumentXHR(); - break; - case 'fetch': - instrumentFetch(); - break; - case 'history': - instrumentHistory(); - break; - case 'error': - instrumentError(); - break; - case 'unhandledrejection': - instrumentUnhandledRejection(); - break; - default: - logger_1.logger.warn('unknown instrumentation type:', type); - } -} -/** - * Add handler that will be called when given type of instrumentation triggers. - * Use at your own risk, this might break without changelog notice, only used internally. - * @hidden - */ -function addInstrumentationHandler(handler) { - if (!handler || typeof handler.type !== 'string' || typeof handler.callback !== 'function') { - return; - } - handlers[handler.type] = handlers[handler.type] || []; - handlers[handler.type].push(handler.callback); - instrument(handler.type); -} -exports.addInstrumentationHandler = addInstrumentationHandler; -/** JSDoc */ -function triggerHandlers(type, data) { - var e_1, _a; - if (!type || !handlers[type]) { - return; - } - try { - for (var _b = tslib_1.__values(handlers[type] || []), _c = _b.next(); !_c.done; _c = _b.next()) { - var handler = _c.value; - try { - handler(data); - } - catch (e) { - logger_1.logger.error("Error while triggering instrumentation handler.\nType: " + type + "\nName: " + stacktrace_1.getFunctionName(handler) + "\nError: " + e); - } - } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (_c && !_c.done && (_a = _b.return)) _a.call(_b); - } - finally { if (e_1) throw e_1.error; } - } -} -/** JSDoc */ -function instrumentConsole() { - if (!('console' in global)) { - return; - } - ['debug', 'info', 'warn', 'error', 'log', 'assert'].forEach(function (level) { - if (!(level in global.console)) { - return; - } - object_1.fill(global.console, level, function (originalConsoleLevel) { - return function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - triggerHandlers('console', { args: args, level: level }); - // this fails for some browsers. :( - if (originalConsoleLevel) { - Function.prototype.apply.call(originalConsoleLevel, global.console, args); - } - }; - }); - }); -} -/** JSDoc */ -function instrumentFetch() { - if (!supports_1.supportsNativeFetch()) { - return; - } - object_1.fill(global, 'fetch', function (originalFetch) { - return function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - var handlerData = { - args: args, - fetchData: { - method: getFetchMethod(args), - url: getFetchUrl(args), - }, - startTimestamp: Date.now(), - }; - triggerHandlers('fetch', tslib_1.__assign({}, handlerData)); - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - return originalFetch.apply(global, args).then(function (response) { - triggerHandlers('fetch', tslib_1.__assign(tslib_1.__assign({}, handlerData), { endTimestamp: Date.now(), response: response })); - return response; - }, function (error) { - triggerHandlers('fetch', tslib_1.__assign(tslib_1.__assign({}, handlerData), { endTimestamp: Date.now(), error: error })); - // NOTE: If you are a Sentry user, and you are seeing this stack frame, - // it means the sentry.javascript SDK caught an error invoking your application code. - // This is expected behavior and NOT indicative of a bug with sentry.javascript. - throw error; - }); - }; - }); -} -/* eslint-disable @typescript-eslint/no-unsafe-member-access */ -/** Extract `method` from fetch call arguments */ -function getFetchMethod(fetchArgs) { - if (fetchArgs === void 0) { fetchArgs = []; } - if ('Request' in global && is_1.isInstanceOf(fetchArgs[0], Request) && fetchArgs[0].method) { - return String(fetchArgs[0].method).toUpperCase(); - } - if (fetchArgs[1] && fetchArgs[1].method) { - return String(fetchArgs[1].method).toUpperCase(); - } - return 'GET'; -} -/** Extract `url` from fetch call arguments */ -function getFetchUrl(fetchArgs) { - if (fetchArgs === void 0) { fetchArgs = []; } - if (typeof fetchArgs[0] === 'string') { - return fetchArgs[0]; + __register__(index, weight, expiration) { + var _this11 = this; + + return _asyncToGenerator(function* () { + var now, wait; + yield _this11.yieldLoop(); + now = Date.now(); + + if (_this11.conditionsCheck(weight)) { + _this11._running += weight; + + if (_this11.storeOptions.reservoir != null) { + _this11.storeOptions.reservoir -= weight; + } + + wait = Math.max(_this11._nextRequest - now, 0); + _this11._nextRequest = now + wait + _this11.storeOptions.minTime; + return { + success: true, + wait, + reservoir: _this11.storeOptions.reservoir + }; + } else { + return { + success: false + }; + } + })(); + } + + strategyIsBlock() { + return this.storeOptions.strategy === 3; + } + + __submit__(queueLength, weight) { + var _this12 = this; + + return _asyncToGenerator(function* () { + var blocked, now, reachedHWM; + yield _this12.yieldLoop(); + + if (_this12.storeOptions.maxConcurrent != null && weight > _this12.storeOptions.maxConcurrent) { + throw new BottleneckError(`Impossible to add a job having a weight of ${weight} to a limiter having a maxConcurrent setting of ${_this12.storeOptions.maxConcurrent}`); + } + + now = Date.now(); + reachedHWM = _this12.storeOptions.highWater != null && queueLength === _this12.storeOptions.highWater && !_this12.check(weight, now); + blocked = _this12.strategyIsBlock() && (reachedHWM || _this12.isBlocked(now)); + + if (blocked) { + _this12._unblockTime = now + _this12.computePenalty(); + _this12._nextRequest = _this12._unblockTime + _this12.storeOptions.minTime; + + _this12.instance._dropAllQueued(); + } + + return { + reachedHWM, + blocked, + strategy: _this12.storeOptions.strategy + }; + })(); + } + + __free__(index, weight) { + var _this13 = this; + + return _asyncToGenerator(function* () { + yield _this13.yieldLoop(); + _this13._running -= weight; + _this13._done += weight; + + _this13.instance._drainAll(_this13.computeCapacity()); + + return { + running: _this13._running + }; + })(); + } + +}; +module.exports = LocalDatastore; + +/***/ }), + +/***/ 65893: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var DLList, Events, Queues; +DLList = __nccwpck_require__(38579); +Events = __nccwpck_require__(107); +Queues = class Queues { + constructor(num_priorities) { + var i; + this.Events = new Events(this); + this._length = 0; + + this._lists = function () { + var j, ref, results; + results = []; + + for (i = j = 1, ref = num_priorities; 1 <= ref ? j <= ref : j >= ref; i = 1 <= ref ? ++j : --j) { + results.push(new DLList(this)); + } + + return results; + }.call(this); + } + + incr() { + if (this._length++ === 0) { + return this.Events.trigger("leftzero"); } - if ('Request' in global && is_1.isInstanceOf(fetchArgs[0], Request)) { - return fetchArgs[0].url; + } + + decr() { + if (--this._length === 0) { + return this.Events.trigger("zero"); } - return String(fetchArgs[0]); -} -/* eslint-enable @typescript-eslint/no-unsafe-member-access */ -/** JSDoc */ -function instrumentXHR() { - if (!('XMLHttpRequest' in global)) { - return; + } + + push(priority, job) { + return this._lists[priority].push(job); + } + + queued(priority) { + if (priority != null) { + return this._lists[priority].length; + } else { + return this._length; } - // Poor man's implementation of ES6 `Map`, tracking and keeping in sync key and value separately. - var requestKeys = []; - var requestValues = []; - var xhrproto = XMLHttpRequest.prototype; - object_1.fill(xhrproto, 'open', function (originalOpen) { - return function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - // eslint-disable-next-line @typescript-eslint/no-this-alias - var xhr = this; - var url = args[1]; - xhr.__sentry_xhr__ = { - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - method: is_1.isString(args[0]) ? args[0].toUpperCase() : args[0], - url: args[1], - }; - // if Sentry key appears in URL, don't capture it as a request - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - if (is_1.isString(url) && xhr.__sentry_xhr__.method === 'POST' && url.match(/sentry_key/)) { - xhr.__sentry_own_request__ = true; - } - var onreadystatechangeHandler = function () { - if (xhr.readyState === 4) { - try { - // touching statusCode in some platforms throws - // an exception - if (xhr.__sentry_xhr__) { - xhr.__sentry_xhr__.status_code = xhr.status; - } - } - catch (e) { - /* do nothing */ - } - try { - var requestPos = requestKeys.indexOf(xhr); - if (requestPos !== -1) { - // Make sure to pop both key and value to keep it in sync. - requestKeys.splice(requestPos); - var args_1 = requestValues.splice(requestPos)[0]; - if (xhr.__sentry_xhr__ && args_1[0] !== undefined) { - xhr.__sentry_xhr__.body = args_1[0]; - } - } - } - catch (e) { - /* do nothing */ - } - triggerHandlers('xhr', { - args: args, - endTimestamp: Date.now(), - startTimestamp: Date.now(), - xhr: xhr, - }); - } - }; - if ('onreadystatechange' in xhr && typeof xhr.onreadystatechange === 'function') { - object_1.fill(xhr, 'onreadystatechange', function (original) { - return function () { - var readyStateArgs = []; - for (var _i = 0; _i < arguments.length; _i++) { - readyStateArgs[_i] = arguments[_i]; - } - onreadystatechangeHandler(); - return original.apply(xhr, readyStateArgs); - }; - }); - } - else { - xhr.addEventListener('readystatechange', onreadystatechangeHandler); - } - return originalOpen.apply(xhr, args); - }; - }); - object_1.fill(xhrproto, 'send', function (originalSend) { - return function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - requestKeys.push(this); - requestValues.push(args); - triggerHandlers('xhr', { - args: args, - startTimestamp: Date.now(), - xhr: this, - }); - return originalSend.apply(this, args); - }; + } + + shiftAll(fn) { + return this._lists.forEach(function (list) { + return list.forEachShift(fn); }); -} -var lastHref; -/** JSDoc */ -function instrumentHistory() { - if (!supports_1.supportsHistory()) { - return; + } + + getFirst(arr = this._lists) { + var j, len, list; + + for (j = 0, len = arr.length; j < len; j++) { + list = arr[j]; + + if (list.length > 0) { + return list; + } } - var oldOnPopState = global.onpopstate; - global.onpopstate = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - var to = global.location.href; - // keep track of the current URL state, as we always receive only the updated state - var from = lastHref; - lastHref = to; - triggerHandlers('history', { - from: from, - to: to, - }); - if (oldOnPopState) { - return oldOnPopState.apply(this, args); - } - }; - /** @hidden */ - function historyReplacementFunction(originalHistoryFunction) { - return function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - var url = args.length > 2 ? args[2] : undefined; - if (url) { - // coerce to string (this is what pushState does) - var from = lastHref; - var to = String(url); - // keep track of the current URL state, as we always receive only the updated state - lastHref = to; - triggerHandlers('history', { - from: from, - to: to, - }); - } - return originalHistoryFunction.apply(this, args); + + return []; + } + + shiftLastFrom(priority) { + return this.getFirst(this._lists.slice(priority).reverse()).shift(); + } + +}; +module.exports = Queues; + +/***/ }), + +/***/ 29992: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } + +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } + +var Events, RedisConnection, Scripts, parser; +parser = __nccwpck_require__(67823); +Events = __nccwpck_require__(107); +Scripts = __nccwpck_require__(4169); + +RedisConnection = function () { + class RedisConnection { + constructor(options = {}) { + var Redis; + Redis = eval("require")("redis"); // Obfuscated or else Webpack/Angular will try to inline the optional redis module + + parser.load(options, this.defaults, this); + + if (this.Events == null) { + this.Events = new Events(this); + } + + this.terminated = false; + + if (this.client == null) { + this.client = Redis.createClient(this.clientOptions); + } + + this.subscriber = this.client.duplicate(); + this.limiters = {}; + this.shas = {}; + this.ready = this.Promise.all([this._setup(this.client, false), this._setup(this.subscriber, true)]).then(() => { + return this._loadScripts(); + }).then(() => { + return { + client: this.client, + subscriber: this.subscriber }; + }); } - object_1.fill(global.history, 'pushState', historyReplacementFunction); - object_1.fill(global.history, 'replaceState', historyReplacementFunction); -} -/** JSDoc */ -function instrumentDOM() { - if (!('document' in global)) { - return; - } - // Capture breadcrumbs from any click that is unhandled / bubbled up all the way - // to the document. Do this before we instrument addEventListener. - global.document.addEventListener('click', domEventHandler('click', triggerHandlers.bind(null, 'dom')), false); - global.document.addEventListener('keypress', keypressEventHandler(triggerHandlers.bind(null, 'dom')), false); - // After hooking into document bubbled up click and keypresses events, we also hook into user handled click & keypresses. - ['EventTarget', 'Node'].forEach(function (target) { - /* eslint-disable @typescript-eslint/no-unsafe-member-access */ - var proto = global[target] && global[target].prototype; - // eslint-disable-next-line no-prototype-builtins - if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty('addEventListener')) { - return; - } - /* eslint-enable @typescript-eslint/no-unsafe-member-access */ - object_1.fill(proto, 'addEventListener', function (original) { - return function (eventName, fn, options) { - if (fn && fn.handleEvent) { - if (eventName === 'click') { - object_1.fill(fn, 'handleEvent', function (innerOriginal) { - return function (event) { - domEventHandler('click', triggerHandlers.bind(null, 'dom'))(event); - return innerOriginal.call(this, event); - }; - }); - } - if (eventName === 'keypress') { - object_1.fill(fn, 'handleEvent', function (innerOriginal) { - return function (event) { - keypressEventHandler(triggerHandlers.bind(null, 'dom'))(event); - return innerOriginal.call(this, event); - }; - }); - } - } - else { - if (eventName === 'click') { - domEventHandler('click', triggerHandlers.bind(null, 'dom'), true)(this); - } - if (eventName === 'keypress') { - keypressEventHandler(triggerHandlers.bind(null, 'dom'))(this); - } - } - return original.call(this, eventName, fn, options); - }; - }); - object_1.fill(proto, 'removeEventListener', function (original) { - return function (eventName, fn, options) { - try { - original.call(this, eventName, fn.__sentry_wrapped__, options); - } - catch (e) { - // ignore, accessing __sentry_wrapped__ will throw in some Selenium environments - } - return original.call(this, eventName, fn, options); - }; - }); - }); -} -var debounceDuration = 1000; -var debounceTimer = 0; -var keypressTimeout; -var lastCapturedEvent; -/** - * Wraps addEventListener to capture UI breadcrumbs - * @param name the event name (e.g. "click") - * @param handler function that will be triggered - * @param debounce decides whether it should wait till another event loop - * @returns wrapped breadcrumb events handler - * @hidden - */ -function domEventHandler(name, handler, debounce) { - if (debounce === void 0) { debounce = false; } - return function (event) { - // reset keypress timeout; e.g. triggering a 'click' after - // a 'keypress' will reset the keypress debounce so that a new - // set of keypresses can be recorded - keypressTimeout = undefined; - // It's possible this handler might trigger multiple times for the same - // event (e.g. event propagation through node ancestors). Ignore if we've - // already captured the event. - if (!event || lastCapturedEvent === event) { - return; - } - lastCapturedEvent = event; - if (debounceTimer) { - clearTimeout(debounceTimer); - } - if (debounce) { - debounceTimer = setTimeout(function () { - handler({ event: event, name: name }); - }); - } - else { - handler({ event: event, name: name }); - } - }; -} -/** - * Wraps addEventListener to capture keypress UI events - * @param handler function that will be triggered - * @returns wrapped keypress events handler - * @hidden - */ -function keypressEventHandler(handler) { - // TODO: if somehow user switches keypress target before - // debounce timeout is triggered, we will only capture - // a single breadcrumb from the FIRST target (acceptable?) - return function (event) { - var target; - try { - target = event.target; - } - catch (e) { - // just accessing event properties can throw an exception in some rare circumstances - // see: https://github.com/getsentry/raven-js/issues/838 - return; - } - var tagName = target && target.tagName; - // only consider keypress events on actual input elements - // this will disregard keypresses targeting body (e.g. tabbing - // through elements, hotkeys, etc) - if (!tagName || (tagName !== 'INPUT' && tagName !== 'TEXTAREA' && !target.isContentEditable)) { - return; - } - // record first keypress in a series, but ignore subsequent - // keypresses until debounce clears - if (!keypressTimeout) { - domEventHandler('input', handler)(event); - } - clearTimeout(keypressTimeout); - keypressTimeout = setTimeout(function () { - keypressTimeout = undefined; - }, debounceDuration); - }; -} -var _oldOnErrorHandler = null; -/** JSDoc */ -function instrumentError() { - _oldOnErrorHandler = global.onerror; - global.onerror = function (msg, url, line, column, error) { - triggerHandlers('error', { - column: column, - error: error, - line: line, - msg: msg, - url: url, - }); - if (_oldOnErrorHandler) { - // eslint-disable-next-line prefer-rest-params - return _oldOnErrorHandler.apply(this, arguments); - } - return false; - }; -} -var _oldOnUnhandledRejectionHandler = null; -/** JSDoc */ -function instrumentUnhandledRejection() { - _oldOnUnhandledRejectionHandler = global.onunhandledrejection; - global.onunhandledrejection = function (e) { - triggerHandlers('unhandledrejection', e); - if (_oldOnUnhandledRejectionHandler) { - // eslint-disable-next-line prefer-rest-params - return _oldOnUnhandledRejectionHandler.apply(this, arguments); + + _setup(client, sub) { + client.setMaxListeners(0); + return new this.Promise((resolve, reject) => { + client.on("error", e => { + return this.Events.trigger("error", e); + }); + + if (sub) { + client.on("message", (channel, message) => { + var ref; + return (ref = this.limiters[channel]) != null ? ref._store.onMessage(channel, message) : void 0; + }); } - return true; - }; -} -//# sourceMappingURL=instrument.js.map -/***/ }), + if (client.ready) { + return resolve(); + } else { + return client.once("ready", resolve); + } + }); + } -/***/ 92757: -/***/ ((__unused_webpack_module, exports) => { + _loadScript(name) { + return new this.Promise((resolve, reject) => { + var payload; + payload = Scripts.payload(name); + return this.client.multi([["script", "load", payload]]).exec((err, replies) => { + if (err != null) { + return reject(err); + } -/* eslint-disable @typescript-eslint/no-explicit-any */ -/* eslint-disable @typescript-eslint/explicit-module-boundary-types */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -/** - * Checks whether given value's type is one of a few Error or Error-like - * {@link isError}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isError(wat) { - switch (Object.prototype.toString.call(wat)) { - case '[object Error]': - return true; - case '[object Exception]': - return true; - case '[object DOMException]': - return true; - default: - return isInstanceOf(wat, Error); + this.shas[name] = replies[0]; + return resolve(replies[0]); + }); + }); } -} -exports.isError = isError; -/** - * Checks whether given value's type is ErrorEvent - * {@link isErrorEvent}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isErrorEvent(wat) { - return Object.prototype.toString.call(wat) === '[object ErrorEvent]'; -} -exports.isErrorEvent = isErrorEvent; -/** - * Checks whether given value's type is DOMError - * {@link isDOMError}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isDOMError(wat) { - return Object.prototype.toString.call(wat) === '[object DOMError]'; -} -exports.isDOMError = isDOMError; -/** - * Checks whether given value's type is DOMException - * {@link isDOMException}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isDOMException(wat) { - return Object.prototype.toString.call(wat) === '[object DOMException]'; -} -exports.isDOMException = isDOMException; -/** - * Checks whether given value's type is a string - * {@link isString}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isString(wat) { - return Object.prototype.toString.call(wat) === '[object String]'; -} -exports.isString = isString; -/** - * Checks whether given value's is a primitive (undefined, null, number, boolean, string, bigint, symbol) - * {@link isPrimitive}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isPrimitive(wat) { - return wat === null || (typeof wat !== 'object' && typeof wat !== 'function'); -} -exports.isPrimitive = isPrimitive; -/** - * Checks whether given value's type is an object literal - * {@link isPlainObject}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isPlainObject(wat) { - return Object.prototype.toString.call(wat) === '[object Object]'; -} -exports.isPlainObject = isPlainObject; -/** - * Checks whether given value's type is an Event instance - * {@link isEvent}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isEvent(wat) { - return typeof Event !== 'undefined' && isInstanceOf(wat, Event); -} -exports.isEvent = isEvent; -/** - * Checks whether given value's type is an Element instance - * {@link isElement}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isElement(wat) { - return typeof Element !== 'undefined' && isInstanceOf(wat, Element); -} -exports.isElement = isElement; -/** - * Checks whether given value's type is an regexp - * {@link isRegExp}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isRegExp(wat) { - return Object.prototype.toString.call(wat) === '[object RegExp]'; -} -exports.isRegExp = isRegExp; -/** - * Checks whether given value has a then function. - * @param wat A value to be checked. - */ -function isThenable(wat) { - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - return Boolean(wat && wat.then && typeof wat.then === 'function'); -} -exports.isThenable = isThenable; -/** - * Checks whether given value's type is a SyntheticEvent - * {@link isSyntheticEvent}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isSyntheticEvent(wat) { - return isPlainObject(wat) && 'nativeEvent' in wat && 'preventDefault' in wat && 'stopPropagation' in wat; -} -exports.isSyntheticEvent = isSyntheticEvent; -/** - * Checks whether given value's type is an instance of provided constructor. - * {@link isInstanceOf}. - * - * @param wat A value to be checked. - * @param base A constructor to be used in a check. - * @returns A boolean representing the result. - */ -function isInstanceOf(wat, base) { - try { - return wat instanceof base; + + _loadScripts() { + return this.Promise.all(Scripts.names.map(k => { + return this._loadScript(k); + })); } - catch (_e) { - return false; + + __runCommand__(cmd) { + var _this = this; + + return _asyncToGenerator(function* () { + yield _this.ready; + return new _this.Promise((resolve, reject) => { + return _this.client.multi([cmd]).exec_atomic(function (err, replies) { + if (err != null) { + return reject(err); + } else { + return resolve(replies[0]); + } + }); + }); + })(); } -} -exports.isInstanceOf = isInstanceOf; -//# sourceMappingURL=is.js.map + + __addLimiter__(instance) { + return this.Promise.all([instance.channel(), instance.channel_client()].map(channel => { + return new this.Promise((resolve, reject) => { + var handler; + + handler = chan => { + if (chan === channel) { + this.subscriber.removeListener("subscribe", handler); + this.limiters[channel] = instance; + return resolve(); + } + }; + + this.subscriber.on("subscribe", handler); + return this.subscriber.subscribe(channel); + }); + })); + } + + __removeLimiter__(instance) { + var _this2 = this; + + return this.Promise.all([instance.channel(), instance.channel_client()].map( + /*#__PURE__*/ + function () { + var _ref = _asyncToGenerator(function* (channel) { + if (!_this2.terminated) { + yield new _this2.Promise((resolve, reject) => { + return _this2.subscriber.unsubscribe(channel, function (err, chan) { + if (err != null) { + return reject(err); + } + + if (chan === channel) { + return resolve(); + } + }); + }); + } + + return delete _this2.limiters[channel]; + }); + + return function (_x) { + return _ref.apply(this, arguments); + }; + }())); + } + + __scriptArgs__(name, id, args, cb) { + var keys; + keys = Scripts.keys(name, id); + return [this.shas[name], keys.length].concat(keys, args, cb); + } + + __scriptFn__(name) { + return this.client.evalsha.bind(this.client); + } + + disconnect(flush = true) { + var i, k, len, ref; + ref = Object.keys(this.limiters); + + for (i = 0, len = ref.length; i < len; i++) { + k = ref[i]; + clearInterval(this.limiters[k]._store.heartbeat); + } + + this.limiters = {}; + this.terminated = true; + this.client.end(flush); + this.subscriber.end(flush); + return this.Promise.resolve(); + } + + } + + ; + RedisConnection.prototype.datastore = "redis"; + RedisConnection.prototype.defaults = { + clientOptions: {}, + client: null, + Promise: Promise, + Events: null + }; + return RedisConnection; +}.call(void 0); + +module.exports = RedisConnection; /***/ }), -/***/ 15577: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 4946: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -Object.defineProperty(exports, "__esModule", ({ value: true })); -/* eslint-disable @typescript-eslint/no-explicit-any */ -var misc_1 = __nccwpck_require__(32154); -// TODO: Implement different loggers for different environments -var global = misc_1.getGlobalObject(); -/** Prefix for logging strings */ -var PREFIX = 'Sentry Logger '; -/** JSDoc */ -var Logger = /** @class */ (function () { - /** JSDoc */ - function Logger() { - this._enabled = false; +"use strict"; + + +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } + +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } + +function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } + +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } + +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } + +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } + +var BottleneckError, IORedisConnection, RedisConnection, RedisDatastore, parser; +parser = __nccwpck_require__(67823); +BottleneckError = __nccwpck_require__(93529); +RedisConnection = __nccwpck_require__(29992); +IORedisConnection = __nccwpck_require__(47710); +RedisDatastore = class RedisDatastore { + constructor(instance, storeOptions, storeInstanceOptions) { + this.instance = instance; + this.storeOptions = storeOptions; + this.originalId = this.instance.id; + this.clientId = this.instance._randomIndex(); + parser.load(storeInstanceOptions, storeInstanceOptions, this); + this.clients = {}; + this.capacityPriorityCounters = {}; + this.sharedConnection = this.connection != null; + + if (this.connection == null) { + this.connection = this.instance.datastore === "redis" ? new RedisConnection({ + clientOptions: this.clientOptions, + Promise: this.Promise, + Events: this.instance.Events + }) : this.instance.datastore === "ioredis" ? new IORedisConnection({ + clientOptions: this.clientOptions, + clusterNodes: this.clusterNodes, + Promise: this.Promise, + Events: this.instance.Events + }) : void 0; } - /** JSDoc */ - Logger.prototype.disable = function () { - this._enabled = false; - }; - /** JSDoc */ - Logger.prototype.enable = function () { - this._enabled = true; - }; - /** JSDoc */ - Logger.prototype.log = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - if (!this._enabled) { - return; - } - misc_1.consoleSandbox(function () { - global.console.log(PREFIX + "[Log]: " + args.join(' ')); + + this.instance.connection = this.connection; + this.instance.datastore = this.connection.datastore; + this.ready = this.connection.ready.then(clients => { + this.clients = clients; + return this.runScript("init", this.prepareInitSettings(this.clearDatastore)); + }).then(() => { + return this.connection.__addLimiter__(this.instance); + }).then(() => { + return this.runScript("register_client", [this.instance.queued()]); + }).then(() => { + var base; + + if (typeof (base = this.heartbeat = setInterval(() => { + return this.runScript("heartbeat", []).catch(e => { + return this.instance.Events.trigger("error", e); }); - }; - /** JSDoc */ - Logger.prototype.warn = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - if (!this._enabled) { - return; + }, this.heartbeatInterval)).unref === "function") { + base.unref(); + } + + return this.clients; + }); + } + + __publish__(message) { + var _this = this; + + return _asyncToGenerator(function* () { + var client; + + var _ref = yield _this.ready; + + client = _ref.client; + return client.publish(_this.instance.channel(), `message:${message.toString()}`); + })(); + } + + onMessage(channel, message) { + var _this2 = this; + + return _asyncToGenerator(function* () { + var capacity, counter, data, drained, e, newCapacity, pos, priorityClient, rawCapacity, type; + + try { + pos = message.indexOf(":"); + var _ref2 = [message.slice(0, pos), message.slice(pos + 1)]; + type = _ref2[0]; + data = _ref2[1]; + + if (type === "capacity") { + return yield _this2.instance._drainAll(data.length > 0 ? ~~data : void 0); + } else if (type === "capacity-priority") { + var _data$split = data.split(":"); + + var _data$split2 = _slicedToArray(_data$split, 3); + + rawCapacity = _data$split2[0]; + priorityClient = _data$split2[1]; + counter = _data$split2[2]; + capacity = rawCapacity.length > 0 ? ~~rawCapacity : void 0; + + if (priorityClient === _this2.clientId) { + drained = yield _this2.instance._drainAll(capacity); + newCapacity = capacity != null ? capacity - (drained || 0) : ""; + return yield _this2.clients.client.publish(_this2.instance.channel(), `capacity-priority:${newCapacity}::${counter}`); + } else if (priorityClient === "") { + clearTimeout(_this2.capacityPriorityCounters[counter]); + delete _this2.capacityPriorityCounters[counter]; + return _this2.instance._drainAll(capacity); + } else { + return _this2.capacityPriorityCounters[counter] = setTimeout( + /*#__PURE__*/ + _asyncToGenerator(function* () { + var e; + + try { + delete _this2.capacityPriorityCounters[counter]; + yield _this2.runScript("blacklist_client", [priorityClient]); + return yield _this2.instance._drainAll(capacity); + } catch (error) { + e = error; + return _this2.instance.Events.trigger("error", e); + } + }), 1000); + } + } else if (type === "message") { + return _this2.instance.Events.trigger("message", data); + } else if (type === "blocked") { + return yield _this2.instance._dropAllQueued(); } - misc_1.consoleSandbox(function () { - global.console.warn(PREFIX + "[Warn]: " + args.join(' ')); + } catch (error) { + e = error; + return _this2.instance.Events.trigger("error", e); + } + })(); + } + + __disconnect__(flush) { + clearInterval(this.heartbeat); + + if (this.sharedConnection) { + return this.connection.__removeLimiter__(this.instance); + } else { + return this.connection.disconnect(flush); + } + } + + runScript(name, args) { + var _this3 = this; + + return _asyncToGenerator(function* () { + if (!(name === "init" || name === "register_client")) { + yield _this3.ready; + } + + return new _this3.Promise((resolve, reject) => { + var all_args, arr; + all_args = [Date.now(), _this3.clientId].concat(args); + + _this3.instance.Events.trigger("debug", `Calling Redis script: ${name}.lua`, all_args); + + arr = _this3.connection.__scriptArgs__(name, _this3.originalId, all_args, function (err, replies) { + if (err != null) { + return reject(err); + } + + return resolve(replies); }); - }; - /** JSDoc */ - Logger.prototype.error = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - if (!this._enabled) { - return; + return _this3.connection.__scriptFn__(name)(...arr); + }).catch(e => { + if (e.message === "SETTINGS_KEY_NOT_FOUND") { + if (name === "heartbeat") { + return _this3.Promise.resolve(); + } else { + return _this3.runScript("init", _this3.prepareInitSettings(false)).then(() => { + return _this3.runScript(name, args); + }); + } + } else if (e.message === "UNKNOWN_CLIENT") { + return _this3.runScript("register_client", [_this3.instance.queued()]).then(() => { + return _this3.runScript(name, args); + }); + } else { + return _this3.Promise.reject(e); } - misc_1.consoleSandbox(function () { - global.console.error(PREFIX + "[Error]: " + args.join(' ')); - }); - }; - return Logger; -}()); -// Ensure we only have a single logger instance, even if multiple versions of @sentry/utils are being used -global.__SENTRY__ = global.__SENTRY__ || {}; -var logger = global.__SENTRY__.logger || (global.__SENTRY__.logger = new Logger()); -exports.logger = logger; -//# sourceMappingURL=logger.js.map + }); + })(); + } -/***/ }), + prepareArray(arr) { + var i, len, results, x; + results = []; -/***/ 49515: -/***/ ((__unused_webpack_module, exports) => { + for (i = 0, len = arr.length; i < len; i++) { + x = arr[i]; + results.push(x != null ? x.toString() : ""); + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -/* eslint-disable @typescript-eslint/no-unsafe-member-access */ -/* eslint-disable @typescript-eslint/no-explicit-any */ -/* eslint-disable @typescript-eslint/explicit-module-boundary-types */ -/** - * Memo class used for decycle json objects. Uses WeakSet if available otherwise array. - */ -var Memo = /** @class */ (function () { - function Memo() { - this._hasWeakSet = typeof WeakSet === 'function'; - this._inner = this._hasWeakSet ? new WeakSet() : []; + return results; + } + + prepareObject(obj) { + var arr, k, v; + arr = []; + + for (k in obj) { + v = obj[k]; + arr.push(k, v != null ? v.toString() : ""); } - /** - * Sets obj to remember. - * @param obj Object to remember - */ - Memo.prototype.memoize = function (obj) { - if (this._hasWeakSet) { - if (this._inner.has(obj)) { - return true; - } - this._inner.add(obj); - return false; - } - // eslint-disable-next-line @typescript-eslint/prefer-for-of - for (var i = 0; i < this._inner.length; i++) { - var value = this._inner[i]; - if (value === obj) { - return true; - } - } - this._inner.push(obj); - return false; - }; - /** - * Removes object from internal storage. - * @param obj Object to forget - */ - Memo.prototype.unmemoize = function (obj) { - if (this._hasWeakSet) { - this._inner.delete(obj); - } - else { - for (var i = 0; i < this._inner.length; i++) { - if (this._inner[i] === obj) { - this._inner.splice(i, 1); - break; - } - } + + return arr; + } + + prepareInitSettings(clear) { + var args; + args = this.prepareObject(Object.assign({}, this.storeOptions, { + id: this.originalId, + version: this.instance.version, + groupTimeout: this.timeout, + clientTimeout: this.clientTimeout + })); + args.unshift(clear ? 1 : 0, this.instance.version); + return args; + } + + convertBool(b) { + return !!b; + } + + __updateSettings__(options) { + var _this4 = this; + + return _asyncToGenerator(function* () { + yield _this4.runScript("update_settings", _this4.prepareObject(options)); + return parser.overwrite(options, options, _this4.storeOptions); + })(); + } + + __running__() { + return this.runScript("running", []); + } + + __queued__() { + return this.runScript("queued", []); + } + + __done__() { + return this.runScript("done", []); + } + + __groupCheck__() { + var _this5 = this; + + return _asyncToGenerator(function* () { + return _this5.convertBool((yield _this5.runScript("group_check", []))); + })(); + } + + __incrementReservoir__(incr) { + return this.runScript("increment_reservoir", [incr]); + } + + __currentReservoir__() { + return this.runScript("current_reservoir", []); + } + + __check__(weight) { + var _this6 = this; + + return _asyncToGenerator(function* () { + return _this6.convertBool((yield _this6.runScript("check", _this6.prepareArray([weight])))); + })(); + } + + __register__(index, weight, expiration) { + var _this7 = this; + + return _asyncToGenerator(function* () { + var reservoir, success, wait; + + var _ref4 = yield _this7.runScript("register", _this7.prepareArray([index, weight, expiration])); + + var _ref5 = _slicedToArray(_ref4, 3); + + success = _ref5[0]; + wait = _ref5[1]; + reservoir = _ref5[2]; + return { + success: _this7.convertBool(success), + wait, + reservoir + }; + })(); + } + + __submit__(queueLength, weight) { + var _this8 = this; + + return _asyncToGenerator(function* () { + var blocked, e, maxConcurrent, overweight, reachedHWM, strategy; + + try { + var _ref6 = yield _this8.runScript("submit", _this8.prepareArray([queueLength, weight])); + + var _ref7 = _slicedToArray(_ref6, 3); + + reachedHWM = _ref7[0]; + blocked = _ref7[1]; + strategy = _ref7[2]; + return { + reachedHWM: _this8.convertBool(reachedHWM), + blocked: _this8.convertBool(blocked), + strategy + }; + } catch (error) { + e = error; + + if (e.message.indexOf("OVERWEIGHT") === 0) { + var _e$message$split = e.message.split(":"); + + var _e$message$split2 = _slicedToArray(_e$message$split, 3); + + overweight = _e$message$split2[0]; + weight = _e$message$split2[1]; + maxConcurrent = _e$message$split2[2]; + throw new BottleneckError(`Impossible to add a job having a weight of ${weight} to a limiter having a maxConcurrent setting of ${maxConcurrent}`); + } else { + throw e; } - }; - return Memo; -}()); -exports.Memo = Memo; -//# sourceMappingURL=memo.js.map + } + })(); + } + + __free__(index, weight) { + var _this9 = this; + + return _asyncToGenerator(function* () { + var running; + running = yield _this9.runScript("free", _this9.prepareArray([index])); + return { + running + }; + })(); + } + +}; +module.exports = RedisDatastore; /***/ }), -/***/ 32154: +/***/ 4169: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -Object.defineProperty(exports, "__esModule", ({ value: true })); -var node_1 = __nccwpck_require__(16411); -var string_1 = __nccwpck_require__(66538); -var fallbackGlobalObject = {}; -/** - * Safely get global scope object - * - * @returns Global scope object - */ -function getGlobalObject() { - return (node_1.isNodeEnv() - ? global - : typeof window !== 'undefined' - ? window - : typeof self !== 'undefined' - ? self - : fallbackGlobalObject); -} -exports.getGlobalObject = getGlobalObject; -/** - * UUID4 generator - * - * @returns string Generated UUID4. - */ -function uuid4() { - var global = getGlobalObject(); - var crypto = global.crypto || global.msCrypto; - if (!(crypto === void 0) && crypto.getRandomValues) { - // Use window.crypto API if available - var arr = new Uint16Array(8); - crypto.getRandomValues(arr); - // set 4 in byte 7 - // eslint-disable-next-line no-bitwise - arr[3] = (arr[3] & 0xfff) | 0x4000; - // set 2 most significant bits of byte 9 to '10' - // eslint-disable-next-line no-bitwise - arr[4] = (arr[4] & 0x3fff) | 0x8000; - var pad = function (num) { - var v = num.toString(16); - while (v.length < 4) { - v = "0" + v; - } - return v; - }; - return (pad(arr[0]) + pad(arr[1]) + pad(arr[2]) + pad(arr[3]) + pad(arr[4]) + pad(arr[5]) + pad(arr[6]) + pad(arr[7])); - } - // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523 - return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function (c) { - // eslint-disable-next-line no-bitwise - var r = (Math.random() * 16) | 0; - // eslint-disable-next-line no-bitwise - var v = c === 'x' ? r : (r & 0x3) | 0x8; - return v.toString(16); - }); -} -exports.uuid4 = uuid4; -/** - * Parses string form of URL into an object - * // borrowed from https://tools.ietf.org/html/rfc3986#appendix-B - * // intentionally using regex and not href parsing trick because React Native and other - * // environments where DOM might not be available - * @returns parsed URL object - */ -function parseUrl(url) { - if (!url) { - return {}; - } - var match = url.match(/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/); - if (!match) { - return {}; - } - // coerce to undefined values to empty string so we don't get 'undefined' - var query = match[6] || ''; - var fragment = match[8] || ''; - return { - host: match[4], - path: match[5], - protocol: match[2], - relative: match[5] + query + fragment, - }; -} -exports.parseUrl = parseUrl; -/** - * Extracts either message or type+value from an event that can be used for user-facing logs - * @returns event's description - */ -function getEventDescription(event) { - if (event.message) { - return event.message; - } - if (event.exception && event.exception.values && event.exception.values[0]) { - var exception = event.exception.values[0]; - if (exception.type && exception.value) { - return exception.type + ": " + exception.value; - } - return exception.type || exception.value || event.event_id || ''; - } - return event.event_id || ''; -} -exports.getEventDescription = getEventDescription; -/** JSDoc */ -function consoleSandbox(callback) { - var global = getGlobalObject(); - var levels = ['debug', 'info', 'warn', 'error', 'log', 'assert']; - if (!('console' in global)) { - return callback(); - } - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - var originalConsole = global.console; - var wrappedLevels = {}; - // Restore all wrapped console methods - levels.forEach(function (level) { - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - if (level in global.console && originalConsole[level].__sentry_original__) { - wrappedLevels[level] = originalConsole[level]; - originalConsole[level] = originalConsole[level].__sentry_original__; - } - }); - // Perform callback manipulations - var result = callback(); - // Revert restoration to wrapped state - Object.keys(wrappedLevels).forEach(function (level) { - originalConsole[level] = wrappedLevels[level]; - }); - return result; -} -exports.consoleSandbox = consoleSandbox; -/** - * Adds exception values, type and value to an synthetic Exception. - * @param event The event to modify. - * @param value Value of the exception. - * @param type Type of the exception. - * @hidden - */ -function addExceptionTypeValue(event, value, type) { - event.exception = event.exception || {}; - event.exception.values = event.exception.values || []; - event.exception.values[0] = event.exception.values[0] || {}; - event.exception.values[0].value = event.exception.values[0].value || value || ''; - event.exception.values[0].type = event.exception.values[0].type || type || 'Error'; -} -exports.addExceptionTypeValue = addExceptionTypeValue; -/** - * Adds exception mechanism to a given event. - * @param event The event to modify. - * @param mechanism Mechanism of the mechanism. - * @hidden - */ -function addExceptionMechanism(event, mechanism) { - if (mechanism === void 0) { mechanism = {}; } - // TODO: Use real type with `keyof Mechanism` thingy and maybe make it better? - try { - // @ts-ignore Type 'Mechanism | {}' is not assignable to type 'Mechanism | undefined' - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - event.exception.values[0].mechanism = event.exception.values[0].mechanism || {}; - Object.keys(mechanism).forEach(function (key) { - // @ts-ignore Mechanism has no index signature - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - event.exception.values[0].mechanism[key] = mechanism[key]; - }); - } - catch (_oO) { - // no-empty - } -} -exports.addExceptionMechanism = addExceptionMechanism; -/** - * A safe form of location.href - */ -function getLocationHref() { - try { - return document.location.href; - } - catch (oO) { - return ''; - } -} -exports.getLocationHref = getLocationHref; -// https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string -var SEMVER_REGEXP = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/; -/** - * Parses input into a SemVer interface - * @param input string representation of a semver version - */ -function parseSemver(input) { - var match = input.match(SEMVER_REGEXP) || []; - var major = parseInt(match[1], 10); - var minor = parseInt(match[2], 10); - var patch = parseInt(match[3], 10); - return { - buildmetadata: match[5], - major: isNaN(major) ? undefined : major, - minor: isNaN(minor) ? undefined : minor, - patch: isNaN(patch) ? undefined : patch, - prerelease: match[4], - }; -} -exports.parseSemver = parseSemver; -var defaultRetryAfter = 60 * 1000; // 60 seconds -/** - * Extracts Retry-After value from the request header or returns default value - * @param now current unix timestamp - * @param header string representation of 'Retry-After' header - */ -function parseRetryAfterHeader(now, header) { - if (!header) { - return defaultRetryAfter; - } - var headerDelay = parseInt("" + header, 10); - if (!isNaN(headerDelay)) { - return headerDelay * 1000; - } - var headerDate = Date.parse("" + header); - if (!isNaN(headerDate)) { - return headerDate - now; - } - return defaultRetryAfter; -} -exports.parseRetryAfterHeader = parseRetryAfterHeader; -/** - * This function adds context (pre/post/line) lines to the provided frame - * - * @param lines string[] containing all lines - * @param frame StackFrame that will be mutated - * @param linesOfContext number of context lines we want to add pre/post - */ -function addContextToFrame(lines, frame, linesOfContext) { - if (linesOfContext === void 0) { linesOfContext = 5; } - var lineno = frame.lineno || 0; - var maxLines = lines.length; - var sourceLine = Math.max(Math.min(maxLines, lineno - 1), 0); - frame.pre_context = lines - .slice(Math.max(0, sourceLine - linesOfContext), sourceLine) - .map(function (line) { return string_1.snipLine(line, 0); }); - frame.context_line = string_1.snipLine(lines[Math.min(maxLines - 1, sourceLine)], frame.colno || 0); - frame.post_context = lines - .slice(Math.min(sourceLine + 1, maxLines), sourceLine + 1 + linesOfContext) - .map(function (line) { return string_1.snipLine(line, 0); }); -} -exports.addContextToFrame = addContextToFrame; -/** - * Strip the query string and fragment off of a given URL or path (if present) - * - * @param urlPath Full URL or path, including possible query string and/or fragment - * @returns URL or path without query string or fragment - */ -function stripUrlQueryAndFragment(urlPath) { - // eslint-disable-next-line no-useless-escape - return urlPath.split(/[\?#]/, 1)[0]; -} -exports.stripUrlQueryAndFragment = stripUrlQueryAndFragment; -//# sourceMappingURL=misc.js.map +"use strict"; + + +var headers, lua, templates; +lua = __nccwpck_require__(31936); +headers = { + refs: lua["refs.lua"], + validate_keys: lua["validate_keys.lua"], + validate_client: lua["validate_client.lua"], + refresh_expiration: lua["refresh_expiration.lua"], + process_tick: lua["process_tick.lua"], + conditions_check: lua["conditions_check.lua"], + get_time: lua["get_time.lua"] +}; -/***/ }), +exports.allKeys = function (id) { + return [ + /* + HASH + */ + `b_${id}_settings`, + /* + HASH + job index -> weight + */ + `b_${id}_job_weights`, + /* + ZSET + job index -> expiration + */ + `b_${id}_job_expirations`, + /* + HASH + job index -> client + */ + `b_${id}_job_clients`, + /* + ZSET + client -> sum running + */ + `b_${id}_client_running`, + /* + HASH + client -> num queued + */ + `b_${id}_client_num_queued`, + /* + ZSET + client -> last job registered + */ + `b_${id}_client_last_registered`, + /* + ZSET + client -> last seen + */ + `b_${id}_client_last_seen`]; +}; -/***/ 16411: -/***/ ((module, exports, __nccwpck_require__) => { +templates = { + init: { + keys: exports.allKeys, + headers: ["process_tick"], + refresh_expiration: true, + code: lua["init.lua"] + }, + group_check: { + keys: exports.allKeys, + headers: [], + refresh_expiration: false, + code: lua["group_check.lua"] + }, + register_client: { + keys: exports.allKeys, + headers: ["validate_keys"], + refresh_expiration: false, + code: lua["register_client.lua"] + }, + blacklist_client: { + keys: exports.allKeys, + headers: ["validate_keys", "validate_client"], + refresh_expiration: false, + code: lua["blacklist_client.lua"] + }, + heartbeat: { + keys: exports.allKeys, + headers: ["validate_keys", "validate_client", "process_tick"], + refresh_expiration: false, + code: lua["heartbeat.lua"] + }, + update_settings: { + keys: exports.allKeys, + headers: ["validate_keys", "validate_client", "process_tick"], + refresh_expiration: true, + code: lua["update_settings.lua"] + }, + running: { + keys: exports.allKeys, + headers: ["validate_keys", "validate_client", "process_tick"], + refresh_expiration: false, + code: lua["running.lua"] + }, + queued: { + keys: exports.allKeys, + headers: ["validate_keys", "validate_client"], + refresh_expiration: false, + code: lua["queued.lua"] + }, + done: { + keys: exports.allKeys, + headers: ["validate_keys", "validate_client", "process_tick"], + refresh_expiration: false, + code: lua["done.lua"] + }, + check: { + keys: exports.allKeys, + headers: ["validate_keys", "validate_client", "process_tick", "conditions_check"], + refresh_expiration: false, + code: lua["check.lua"] + }, + submit: { + keys: exports.allKeys, + headers: ["validate_keys", "validate_client", "process_tick", "conditions_check"], + refresh_expiration: true, + code: lua["submit.lua"] + }, + register: { + keys: exports.allKeys, + headers: ["validate_keys", "validate_client", "process_tick", "conditions_check"], + refresh_expiration: true, + code: lua["register.lua"] + }, + free: { + keys: exports.allKeys, + headers: ["validate_keys", "validate_client", "process_tick"], + refresh_expiration: true, + code: lua["free.lua"] + }, + current_reservoir: { + keys: exports.allKeys, + headers: ["validate_keys", "validate_client", "process_tick"], + refresh_expiration: false, + code: lua["current_reservoir.lua"] + }, + increment_reservoir: { + keys: exports.allKeys, + headers: ["validate_keys", "validate_client", "process_tick"], + refresh_expiration: true, + code: lua["increment_reservoir.lua"] + } +}; +exports.names = Object.keys(templates); -/* module decorator */ module = __nccwpck_require__.nmd(module); -Object.defineProperty(exports, "__esModule", ({ value: true })); -var is_1 = __nccwpck_require__(92757); -var object_1 = __nccwpck_require__(69249); -/** - * Checks whether we're in the Node.js or Browser environment - * - * @returns Answer to given question - */ -function isNodeEnv() { - return Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]'; -} -exports.isNodeEnv = isNodeEnv; -/** - * Requires a module which is protected against bundler minification. - * - * @param request The module path to resolve - */ -// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types -function dynamicRequire(mod, request) { - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - return mod.require(request); -} -exports.dynamicRequire = dynamicRequire; -/** Default request keys that'll be used to extract data from the request */ -var DEFAULT_REQUEST_KEYS = ['cookies', 'data', 'headers', 'method', 'query_string', 'url']; -/** - * Normalizes data from the request object, accounting for framework differences. - * - * @param req The request object from which to extract data - * @param keys An optional array of keys to include in the normalized data. Defaults to DEFAULT_REQUEST_KEYS if not - * provided. - * @returns An object containing normalized request data - */ -function extractNodeRequestData(req, keys) { - if (keys === void 0) { keys = DEFAULT_REQUEST_KEYS; } - // make sure we can safely use dynamicRequire below - if (!isNodeEnv()) { - throw new Error("Can't get node request data outside of a node environment"); - } - var requestData = {}; - // headers: - // node, express: req.headers - // koa: req.header - var headers = (req.headers || req.header || {}); - // method: - // node, express, koa: req.method - var method = req.method; - // host: - // express: req.hostname in > 4 and req.host in < 4 - // koa: req.host - // node: req.headers.host - var host = req.hostname || req.host || headers.host || ''; - // protocol: - // node: - // express, koa: req.protocol - var protocol = req.protocol === 'https' || req.secure || (req.socket || {}).encrypted - ? 'https' - : 'http'; - // url (including path and query string): - // node, express: req.originalUrl - // koa: req.url - var originalUrl = (req.originalUrl || req.url || ''); - // absolute url - var absoluteUrl = protocol + "://" + host + originalUrl; - keys.forEach(function (key) { - switch (key) { - case 'headers': - requestData.headers = headers; - break; - case 'method': - requestData.method = method; - break; - case 'url': - requestData.url = absoluteUrl; - break; - case 'cookies': - // cookies: - // node, express, koa: req.headers.cookie - // vercel, sails.js, express (w/ cookie middleware): req.cookies - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - requestData.cookies = req.cookies || dynamicRequire(module, 'cookie').parse(headers.cookie || ''); - break; - case 'query_string': - // query string: - // node: req.url (raw) - // express, koa: req.query - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - requestData.query_string = dynamicRequire(module, 'url').parse(originalUrl || '', false).query; - break; - case 'data': - if (method === 'GET' || method === 'HEAD') { - break; - } - // body data: - // node, express, koa: req.body - if (req.body !== undefined) { - requestData.data = is_1.isString(req.body) ? req.body : JSON.stringify(object_1.normalize(req.body)); - } - break; - default: - if ({}.hasOwnProperty.call(req, key)) { - requestData[key] = req[key]; - } - } - }); - return requestData; -} -exports.extractNodeRequestData = extractNodeRequestData; -//# sourceMappingURL=node.js.map +exports.keys = function (name, id) { + return templates[name].keys(id); +}; + +exports.payload = function (name) { + var template; + template = templates[name]; + return Array.prototype.concat(headers.refs, template.headers.map(function (h) { + return headers[h]; + }), template.refresh_expiration ? headers.refresh_expiration : "", template.code).join("\n"); +}; /***/ }), -/***/ 69249: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 2527: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var browser_1 = __nccwpck_require__(30597); -var is_1 = __nccwpck_require__(92757); -var memo_1 = __nccwpck_require__(49515); -var stacktrace_1 = __nccwpck_require__(5986); -var string_1 = __nccwpck_require__(66538); -/** - * Wrap a given object method with a higher-order function - * - * @param source An object that contains a method to be wrapped. - * @param name A name of method to be wrapped. - * @param replacement A function that should be used to wrap a given method. - * @returns void - */ -function fill(source, name, replacement) { - if (!(name in source)) { - return; - } - var original = source[name]; - var wrapped = replacement(original); - // Make sure it's a function first, as we need to attach an empty prototype for `defineProperties` to work - // otherwise it'll throw "TypeError: Object.defineProperties called on non-object" - if (typeof wrapped === 'function') { - try { - wrapped.prototype = wrapped.prototype || {}; - Object.defineProperties(wrapped, { - __sentry_original__: { - enumerable: false, - value: original, - }, - }); - } - catch (_Oo) { - // This can throw if multiple fill happens on a global object like XMLHttpRequest - // Fixes https://github.com/getsentry/sentry-javascript/issues/2043 - } - } - source[name] = wrapped; -} -exports.fill = fill; -/** - * Encodes given object into url-friendly format - * - * @param object An object that contains serializable values - * @returns string Encoded - */ -function urlEncode(object) { - return Object.keys(object) - .map(function (key) { return encodeURIComponent(key) + "=" + encodeURIComponent(object[key]); }) - .join('&'); -} -exports.urlEncode = urlEncode; -/** - * Transforms any object into an object literal with all it's attributes - * attached to it. - * - * @param value Initial source that we have to transform in order to be usable by the serializer - */ -function getWalkSource(value) { - if (is_1.isError(value)) { - var error = value; - var err = { - message: error.message, - name: error.name, - stack: error.stack, - }; - for (var i in error) { - if (Object.prototype.hasOwnProperty.call(error, i)) { - err[i] = error[i]; - } - } - return err; - } - if (is_1.isEvent(value)) { - var event_1 = value; - var source = {}; - source.type = event_1.type; - // Accessing event.target can throw (see getsentry/raven-js#838, #768) - try { - source.target = is_1.isElement(event_1.target) - ? browser_1.htmlTreeAsString(event_1.target) - : Object.prototype.toString.call(event_1.target); - } - catch (_oO) { - source.target = ''; - } - try { - source.currentTarget = is_1.isElement(event_1.currentTarget) - ? browser_1.htmlTreeAsString(event_1.currentTarget) - : Object.prototype.toString.call(event_1.currentTarget); - } - catch (_oO) { - source.currentTarget = ''; - } - if (typeof CustomEvent !== 'undefined' && is_1.isInstanceOf(value, CustomEvent)) { - source.detail = event_1.detail; - } - for (var i in event_1) { - if (Object.prototype.hasOwnProperty.call(event_1, i)) { - source[i] = event_1; - } - } - return source; - } - return value; -} -/** Calculates bytes size of input string */ -function utf8Length(value) { - // eslint-disable-next-line no-bitwise - return ~-encodeURI(value).split(/%..|./).length; -} -/** Calculates bytes size of input object */ -function jsonSize(value) { - return utf8Length(JSON.stringify(value)); -} -/** JSDoc */ -function normalizeToSize(object, -// Default Node.js REPL depth -depth, -// 100kB, as 200kB is max payload size, so half sounds reasonable -maxSize) { - if (depth === void 0) { depth = 3; } - if (maxSize === void 0) { maxSize = 100 * 1024; } - var serialized = normalize(object, depth); - if (jsonSize(serialized) > maxSize) { - return normalizeToSize(object, depth - 1, maxSize); - } - return serialized; -} -exports.normalizeToSize = normalizeToSize; -/** - * Transform any non-primitive, BigInt, or Symbol-type value into a string. Acts as a no-op on strings, numbers, - * booleans, null, and undefined. - * - * @param value The value to stringify - * @returns For non-primitive, BigInt, and Symbol-type values, a string denoting the value's type, type and value, or - * type and `description` property, respectively. For non-BigInt, non-Symbol primitives, returns the original value, - * unchanged. - */ -function serializeValue(value) { - var type = Object.prototype.toString.call(value); - // Node.js REPL notation - if (typeof value === 'string') { - return value; - } - if (type === '[object Object]') { - return '[Object]'; - } - if (type === '[object Array]') { - return '[Array]'; - } - var normalized = normalizeValue(value); - return is_1.isPrimitive(normalized) ? normalized : type; -} -/** - * normalizeValue() - * - * Takes unserializable input and make it serializable friendly - * - * - translates undefined/NaN values to "[undefined]"/"[NaN]" respectively, - * - serializes Error objects - * - filter global objects - */ -function normalizeValue(value, key) { - if (key === 'domain' && value && typeof value === 'object' && value._events) { - return '[Domain]'; - } - if (key === 'domainEmitter') { - return '[DomainEmitter]'; - } - if (typeof global !== 'undefined' && value === global) { - return '[Global]'; - } - if (typeof window !== 'undefined' && value === window) { - return '[Window]'; - } - if (typeof document !== 'undefined' && value === document) { - return '[Document]'; - } - // React's SyntheticEvent thingy - if (is_1.isSyntheticEvent(value)) { - return '[SyntheticEvent]'; - } - if (typeof value === 'number' && value !== value) { - return '[NaN]'; - } - if (value === void 0) { - return '[undefined]'; - } - if (typeof value === 'function') { - return "[Function: " + stacktrace_1.getFunctionName(value) + "]"; - } - // symbols and bigints are considered primitives by TS, but aren't natively JSON-serilaizable - if (typeof value === 'symbol') { - return "[" + String(value) + "]"; - } - if (typeof value === 'bigint') { - return "[BigInt: " + String(value) + "]"; - } - return value; -} -/** - * Walks an object to perform a normalization on it - * - * @param key of object that's walked in current iteration - * @param value object to be walked - * @param depth Optional number indicating how deep should walking be performed - * @param memo Optional Memo class handling decycling - */ -// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types -function walk(key, value, depth, memo) { - if (depth === void 0) { depth = +Infinity; } - if (memo === void 0) { memo = new memo_1.Memo(); } - // If we reach the maximum depth, serialize whatever has left - if (depth === 0) { - return serializeValue(value); - } - /* eslint-disable @typescript-eslint/no-unsafe-member-access */ - // If value implements `toJSON` method, call it and return early - if (value !== null && value !== undefined && typeof value.toJSON === 'function') { - return value.toJSON(); - } - /* eslint-enable @typescript-eslint/no-unsafe-member-access */ - // If normalized value is a primitive, there are no branches left to walk, so we can just bail out, as theres no point in going down that branch any further - var normalized = normalizeValue(value, key); - if (is_1.isPrimitive(normalized)) { - return normalized; +"use strict"; + + +var BottleneckError, States; +BottleneckError = __nccwpck_require__(93529); +States = class States { + constructor(status1) { + this.status = status1; + this.jobs = {}; + this.counts = this.status.map(function () { + return 0; + }); + } + + next(id) { + var current, next; + current = this.jobs[id]; + next = current + 1; + + if (current != null && next < this.status.length) { + this.counts[current]--; + this.counts[next]++; + return this.jobs[id]++; + } else if (current != null) { + this.counts[current]--; + return delete this.jobs[id]; } - // Create source that we will use for next itterations, either objectified error object (Error type with extracted keys:value pairs) or the input itself - var source = getWalkSource(value); - // Create an accumulator that will act as a parent for all future itterations of that branch - var acc = Array.isArray(value) ? [] : {}; - // If we already walked that branch, bail out, as it's circular reference - if (memo.memoize(value)) { - return '[Circular ~]'; + } + + start(id) { + var initial; + initial = 0; + this.jobs[id] = initial; + return this.counts[initial]++; + } + + remove(id) { + var current; + current = this.jobs[id]; + + if (current != null) { + this.counts[current]--; + delete this.jobs[id]; } - // Walk all keys of the source - for (var innerKey in source) { - // Avoid iterating over fields in the prototype if they've somehow been exposed to enumeration. - if (!Object.prototype.hasOwnProperty.call(source, innerKey)) { - continue; + + return current != null; + } + + jobStatus(id) { + var ref; + return (ref = this.status[this.jobs[id]]) != null ? ref : null; + } + + statusJobs(status) { + var k, pos, ref, results, v; + + if (status != null) { + pos = this.status.indexOf(status); + + if (pos < 0) { + throw new BottleneckError(`status must be one of ${this.status.join(', ')}`); + } + + ref = this.jobs; + results = []; + + for (k in ref) { + v = ref[k]; + + if (v === pos) { + results.push(k); } - // Recursively walk through all the child nodes - acc[innerKey] = walk(innerKey, source[innerKey], depth - 1, memo); - } - // Once walked through all the branches, remove the parent from memo storage - memo.unmemoize(value); - // Return accumulated values - return acc; -} -exports.walk = walk; -/** - * normalize() - * - * - Creates a copy to prevent original input mutation - * - Skip non-enumerablers - * - Calls `toJSON` if implemented - * - Removes circular references - * - Translates non-serializeable values (undefined/NaN/Functions) to serializable format - * - Translates known global objects/Classes to a string representations - * - Takes care of Error objects serialization - * - Optionally limit depth of final output - */ -// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types -function normalize(input, depth) { - try { - return JSON.parse(JSON.stringify(input, function (key, value) { return walk(key, value, depth); })); - } - catch (_oO) { - return '**non-serializable**'; - } -} -exports.normalize = normalize; -/** - * Given any captured exception, extract its keys and create a sorted - * and truncated list that will be used inside the event message. - * eg. `Non-error exception captured with keys: foo, bar, baz` - */ -// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types -function extractExceptionKeysForMessage(exception, maxLength) { - if (maxLength === void 0) { maxLength = 40; } - var keys = Object.keys(getWalkSource(exception)); - keys.sort(); - if (!keys.length) { - return '[object has no keys]'; + } + + return results; + } else { + return Object.keys(this.jobs); } - if (keys[0].length >= maxLength) { - return string_1.truncate(keys[0], maxLength); + } + + statusCounts() { + return this.counts.reduce((acc, v, i) => { + acc[this.status[i]] = v; + return acc; + }, {}); + } + +}; +module.exports = States; + +/***/ }), + +/***/ 56029: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } + +function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } + +function _toArray(arr) { return _arrayWithHoles(arr) || _iterableToArray(arr) || _nonIterableRest(); } + +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } + +function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } + +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } + +var DLList, + Sync, + splice = [].splice; +DLList = __nccwpck_require__(38579); +Sync = class Sync { + constructor(name, Promise) { + this.submit = this.submit.bind(this); + this.name = name; + this.Promise = Promise; + this._running = 0; + this._queue = new DLList(); + } + + isEmpty() { + return this._queue.length === 0; + } + + _tryToRun() { + var next; + + if (this._running < 1 && this._queue.length > 0) { + this._running++; + next = this._queue.shift(); + return next.task(...next.args, (...args) => { + this._running--; + + this._tryToRun(); + + return typeof next.cb === "function" ? next.cb(...args) : void 0; + }); } - for (var includedKeys = keys.length; includedKeys > 0; includedKeys--) { - var serialized = keys.slice(0, includedKeys).join(', '); - if (serialized.length > maxLength) { - continue; - } - if (includedKeys === keys.length) { - return serialized; - } - return string_1.truncate(serialized, maxLength); + } + + submit(task, ...args) { + var _ref, _ref2, _splice$call, _splice$call2; + + var cb, ref; + ref = args, (_ref = ref, _ref2 = _toArray(_ref), args = _ref2.slice(0), _ref), (_splice$call = splice.call(args, -1), _splice$call2 = _slicedToArray(_splice$call, 1), cb = _splice$call2[0], _splice$call); + + this._queue.push({ + task, + args, + cb + }); + + return this._tryToRun(); + } + + schedule(task, ...args) { + var wrapped; + + wrapped = function wrapped(...args) { + var _ref3, _ref4, _splice$call3, _splice$call4; + + var cb, ref; + ref = args, (_ref3 = ref, _ref4 = _toArray(_ref3), args = _ref4.slice(0), _ref3), (_splice$call3 = splice.call(args, -1), _splice$call4 = _slicedToArray(_splice$call3, 1), cb = _splice$call4[0], _splice$call3); + return task(...args).then(function (...args) { + return cb(null, ...args); + }).catch(function (...args) { + return cb(...args); + }); + }; + + return new this.Promise((resolve, reject) => { + return this.submit(wrapped, ...args, function (...args) { + return (args[0] != null ? reject : (args.shift(), resolve))(...args); + }); + }); + } + +}; +module.exports = Sync; + +/***/ }), + +/***/ 27356: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +module.exports = __nccwpck_require__(83911); + +/***/ }), + +/***/ 67823: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +exports.load = function (received, defaults, onto = {}) { + var k, ref, v; + + for (k in defaults) { + v = defaults[k]; + onto[k] = (ref = received[k]) != null ? ref : v; + } + + return onto; +}; + +exports.overwrite = function (received, defaults, onto = {}) { + var k, v; + + for (k in received) { + v = received[k]; + + if (defaults[k] !== void 0) { + onto[k] = v; } - return ''; -} -exports.extractExceptionKeysForMessage = extractExceptionKeysForMessage; + } + + return onto; +}; + +/***/ }), + +/***/ 11174: +/***/ (function(module) { + /** - * Given any object, return the new object with removed keys that value was `undefined`. - * Works recursively on objects and arrays. - */ -function dropUndefinedKeys(val) { - var e_1, _a; - if (is_1.isPlainObject(val)) { - var obj = val; - var rv = {}; - try { - for (var _b = tslib_1.__values(Object.keys(obj)), _c = _b.next(); !_c.done; _c = _b.next()) { - var key = _c.value; - if (typeof obj[key] !== 'undefined') { - rv[key] = dropUndefinedKeys(obj[key]); - } - } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (_c && !_c.done && (_a = _b.return)) _a.call(_b); - } - finally { if (e_1) throw e_1.error; } - } - return rv; - } - if (Array.isArray(val)) { - return val.map(dropUndefinedKeys); - } - return val; -} -exports.dropUndefinedKeys = dropUndefinedKeys; -//# sourceMappingURL=object.js.map + * This file contains the Bottleneck library (MIT), compiled to ES2017, and without Clustering support. + * https://github.com/SGrondin/bottleneck + */ +(function (global, factory) { + true ? module.exports = factory() : + 0; +}(this, (function () { 'use strict'; + + var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + + function getCjsExportFromNamespace (n) { + return n && n.default || n; + } + + var load = function(received, defaults, onto = {}) { + var k, ref, v; + for (k in defaults) { + v = defaults[k]; + onto[k] = (ref = received[k]) != null ? ref : v; + } + return onto; + }; + + var overwrite = function(received, defaults, onto = {}) { + var k, v; + for (k in received) { + v = received[k]; + if (defaults[k] !== void 0) { + onto[k] = v; + } + } + return onto; + }; + + var parser = { + load: load, + overwrite: overwrite + }; + + var DLList; + + DLList = class DLList { + constructor(_queues) { + this._queues = _queues; + this._first = null; + this._last = null; + this.length = 0; + } + + push(value) { + var node, ref1; + this.length++; + if ((ref1 = this._queues) != null) { + ref1.incr(); + } + node = { + value, + next: null + }; + if (this._last != null) { + this._last.next = node; + this._last = node; + } else { + this._first = this._last = node; + } + return void 0; + } + + shift() { + var ref1, ref2, value; + if (this._first == null) { + return void 0; + } else { + this.length--; + if ((ref1 = this._queues) != null) { + ref1.decr(); + } + } + value = this._first.value; + this._first = (ref2 = this._first.next) != null ? ref2 : (this._last = null); + return value; + } + + first() { + if (this._first != null) { + return this._first.value; + } + } + + getArray() { + var node, ref, results; + node = this._first; + results = []; + while (node != null) { + results.push((ref = node, node = node.next, ref.value)); + } + return results; + } + + forEachShift(cb) { + var node; + node = this.shift(); + while (node != null) { + (cb(node), node = this.shift()); + } + return void 0; + } + + }; + + var DLList_1 = DLList; + + var Events; + + Events = class Events { + constructor(instance) { + this.instance = instance; + this._events = {}; + if ((this.instance.on != null) || (this.instance.once != null) || (this.instance.removeAllListeners != null)) { + throw new Error("An Emitter already exists for this object"); + } + this.instance.on = (name, cb) => { + return this._addListener(name, "many", cb); + }; + this.instance.once = (name, cb) => { + return this._addListener(name, "once", cb); + }; + this.instance.removeAllListeners = (name = null) => { + if (name != null) { + return delete this._events[name]; + } else { + return this._events = {}; + } + }; + } + + _addListener(name, status, cb) { + var base; + if ((base = this._events)[name] == null) { + base[name] = []; + } + this._events[name].push({cb, status}); + return this.instance; + } + + listenerCount(name) { + if (this._events[name] != null) { + return this._events[name].length; + } else { + return 0; + } + } + + async trigger(name, ...args) { + var e, promises; + try { + if (name !== "debug") { + this.trigger("debug", `Event triggered: ${name}`, args); + } + if (this._events[name] == null) { + return; + } + this._events[name] = this._events[name].filter(function(listener) { + return listener.status !== "none"; + }); + promises = this._events[name].map(async(listener) => { + var e, returned; + if (listener.status === "none") { + return; + } + if (listener.status === "once") { + listener.status = "none"; + } + try { + returned = typeof listener.cb === "function" ? listener.cb(...args) : void 0; + if (typeof (returned != null ? returned.then : void 0) === "function") { + return (await returned); + } else { + return returned; + } + } catch (error) { + e = error; + { + this.trigger("error", e); + } + return null; + } + }); + return ((await Promise.all(promises))).find(function(x) { + return x != null; + }); + } catch (error) { + e = error; + { + this.trigger("error", e); + } + return null; + } + } -/***/ }), + }; -/***/ 39188: -/***/ ((__unused_webpack_module, exports) => { + var Events_1 = Events; -// Slightly modified (no IE8 support, ES6) and transcribed to TypeScript -// https://raw.githubusercontent.com/calvinmetcalf/rollup-plugin-node-builtins/master/src/es6/path.js -Object.defineProperty(exports, "__esModule", ({ value: true })); -/** JSDoc */ -function normalizeArray(parts, allowAboveRoot) { - // if the path tries to go above the root, `up` ends up > 0 - var up = 0; - for (var i = parts.length - 1; i >= 0; i--) { - var last = parts[i]; - if (last === '.') { - parts.splice(i, 1); - } - else if (last === '..') { - parts.splice(i, 1); - // eslint-disable-next-line no-plusplus - up++; - } - else if (up) { - parts.splice(i, 1); - // eslint-disable-next-line no-plusplus - up--; - } - } - // if the path is allowed to go above the root, restore leading ..s - if (allowAboveRoot) { - // eslint-disable-next-line no-plusplus - for (; up--; up) { - parts.unshift('..'); - } - } - return parts; -} -// Split a filename into [root, dir, basename, ext], unix version -// 'root' is just a slash, or nothing. -var splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^/]+?|)(\.[^./]*|))(?:[/]*)$/; -/** JSDoc */ -function splitPath(filename) { - var parts = splitPathRe.exec(filename); - return parts ? parts.slice(1) : []; -} -// path.resolve([from ...], to) -// posix version -/** JSDoc */ -function resolve() { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - var resolvedPath = ''; - var resolvedAbsolute = false; - for (var i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) { - var path = i >= 0 ? args[i] : '/'; - // Skip empty entries - if (!path) { - continue; - } - resolvedPath = path + "/" + resolvedPath; - resolvedAbsolute = path.charAt(0) === '/'; - } - // At this point the path should be resolved to a full absolute path, but - // handle relative paths to be safe (might happen when process.cwd() fails) - // Normalize the path - resolvedPath = normalizeArray(resolvedPath.split('/').filter(function (p) { return !!p; }), !resolvedAbsolute).join('/'); - return (resolvedAbsolute ? '/' : '') + resolvedPath || '.'; -} -exports.resolve = resolve; -/** JSDoc */ -function trim(arr) { - var start = 0; - for (; start < arr.length; start++) { - if (arr[start] !== '') { - break; - } - } - var end = arr.length - 1; - for (; end >= 0; end--) { - if (arr[end] !== '') { - break; - } - } - if (start > end) { - return []; - } - return arr.slice(start, end - start + 1); -} -// path.relative(from, to) -// posix version -/** JSDoc */ -function relative(from, to) { - /* eslint-disable no-param-reassign */ - from = resolve(from).substr(1); - to = resolve(to).substr(1); - /* eslint-enable no-param-reassign */ - var fromParts = trim(from.split('/')); - var toParts = trim(to.split('/')); - var length = Math.min(fromParts.length, toParts.length); - var samePartsLength = length; - for (var i = 0; i < length; i++) { - if (fromParts[i] !== toParts[i]) { - samePartsLength = i; - break; - } - } - var outputParts = []; - for (var i = samePartsLength; i < fromParts.length; i++) { - outputParts.push('..'); - } - outputParts = outputParts.concat(toParts.slice(samePartsLength)); - return outputParts.join('/'); -} -exports.relative = relative; -// path.normalize(path) -// posix version -/** JSDoc */ -function normalizePath(path) { - var isPathAbsolute = isAbsolute(path); - var trailingSlash = path.substr(-1) === '/'; - // Normalize the path - var normalizedPath = normalizeArray(path.split('/').filter(function (p) { return !!p; }), !isPathAbsolute).join('/'); - if (!normalizedPath && !isPathAbsolute) { - normalizedPath = '.'; - } - if (normalizedPath && trailingSlash) { - normalizedPath += '/'; - } - return (isPathAbsolute ? '/' : '') + normalizedPath; -} -exports.normalizePath = normalizePath; -// posix version -/** JSDoc */ -function isAbsolute(path) { - return path.charAt(0) === '/'; -} -exports.isAbsolute = isAbsolute; -// posix version -/** JSDoc */ -function join() { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - return normalizePath(args.join('/')); -} -exports.join = join; -/** JSDoc */ -function dirname(path) { - var result = splitPath(path); - var root = result[0]; - var dir = result[1]; - if (!root && !dir) { - // No dirname whatsoever - return '.'; - } - if (dir) { - // It has a dirname, strip trailing slash - dir = dir.substr(0, dir.length - 1); - } - return root + dir; -} -exports.dirname = dirname; -/** JSDoc */ -function basename(path, ext) { - var f = splitPath(path)[2]; - if (ext && f.substr(ext.length * -1) === ext) { - f = f.substr(0, f.length - ext.length); - } - return f; -} -exports.basename = basename; -//# sourceMappingURL=path.js.map + var DLList$1, Events$1, Queues; -/***/ }), + DLList$1 = DLList_1; -/***/ 1243: -/***/ ((__unused_webpack_module, exports) => { + Events$1 = Events_1; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.setPrototypeOf = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array ? setProtoOf : mixinProperties); -/** - * setPrototypeOf polyfill using __proto__ - */ -// eslint-disable-next-line @typescript-eslint/ban-types -function setProtoOf(obj, proto) { - // @ts-ignore __proto__ does not exist on obj - obj.__proto__ = proto; - return obj; -} -/** - * setPrototypeOf polyfill using mixin - */ -// eslint-disable-next-line @typescript-eslint/ban-types -function mixinProperties(obj, proto) { - for (var prop in proto) { - // eslint-disable-next-line no-prototype-builtins - if (!obj.hasOwnProperty(prop)) { - // @ts-ignore typescript complains about indexing so we remove - obj[prop] = proto[prop]; - } - } - return obj; -} -//# sourceMappingURL=polyfill.js.map + Queues = class Queues { + constructor(num_priorities) { + var i; + this.Events = new Events$1(this); + this._length = 0; + this._lists = (function() { + var j, ref, results; + results = []; + for (i = j = 1, ref = num_priorities; (1 <= ref ? j <= ref : j >= ref); i = 1 <= ref ? ++j : --j) { + results.push(new DLList$1(this)); + } + return results; + }).call(this); + } -/***/ }), + incr() { + if (this._length++ === 0) { + return this.Events.trigger("leftzero"); + } + } -/***/ 31811: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + decr() { + if (--this._length === 0) { + return this.Events.trigger("zero"); + } + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -var error_1 = __nccwpck_require__(66238); -var syncpromise_1 = __nccwpck_require__(87833); -/** A simple queue that holds promises. */ -var PromiseBuffer = /** @class */ (function () { - function PromiseBuffer(_limit) { - this._limit = _limit; - /** Internal set of queued Promises */ - this._buffer = []; - } - /** - * Says if the buffer is ready to take more requests - */ - PromiseBuffer.prototype.isReady = function () { - return this._limit === undefined || this.length() < this._limit; - }; - /** - * Add a promise to the queue. - * - * @param task Can be any PromiseLike - * @returns The original promise. - */ - PromiseBuffer.prototype.add = function (task) { - var _this = this; - if (!this.isReady()) { - return syncpromise_1.SyncPromise.reject(new error_1.SentryError('Not adding Promise due to buffer limit reached.')); - } - if (this._buffer.indexOf(task) === -1) { - this._buffer.push(task); - } - task - .then(function () { return _this.remove(task); }) - .then(null, function () { - return _this.remove(task).then(null, function () { - // We have to add this catch here otherwise we have an unhandledPromiseRejection - // because it's a new Promise chain. - }); - }); - return task; - }; - /** - * Remove a promise to the queue. - * - * @param task Can be any PromiseLike - * @returns Removed promise. - */ - PromiseBuffer.prototype.remove = function (task) { - var removedTask = this._buffer.splice(this._buffer.indexOf(task), 1)[0]; - return removedTask; - }; - /** - * This function returns the number of unresolved promises in the queue. - */ - PromiseBuffer.prototype.length = function () { - return this._buffer.length; - }; - /** - * This will drain the whole queue, returns true if queue is empty or drained. - * If timeout is provided and the queue takes longer to drain, the promise still resolves but with false. - * - * @param timeout Number in ms to wait until it resolves with false. - */ - PromiseBuffer.prototype.drain = function (timeout) { - var _this = this; - return new syncpromise_1.SyncPromise(function (resolve) { - var capturedSetTimeout = setTimeout(function () { - if (timeout && timeout > 0) { - resolve(false); - } - }, timeout); - syncpromise_1.SyncPromise.all(_this._buffer) - .then(function () { - clearTimeout(capturedSetTimeout); - resolve(true); - }) - .then(null, function () { - resolve(true); - }); - }); - }; - return PromiseBuffer; -}()); -exports.PromiseBuffer = PromiseBuffer; -//# sourceMappingURL=promisebuffer.js.map + push(priority, job) { + return this._lists[priority].push(job); + } -/***/ }), + queued(priority) { + if (priority != null) { + return this._lists[priority].length; + } else { + return this._length; + } + } -/***/ 5986: -/***/ ((__unused_webpack_module, exports) => { + shiftAll(fn) { + return this._lists.forEach(function(list) { + return list.forEachShift(fn); + }); + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -var defaultFunctionName = ''; -/** - * Safely extract function name from itself - */ -function getFunctionName(fn) { - try { - if (!fn || typeof fn !== 'function') { - return defaultFunctionName; - } - return fn.name || defaultFunctionName; - } - catch (e) { - // Just accessing custom props in some Selenium environments - // can cause a "Permission denied" exception (see raven-js#495). - return defaultFunctionName; - } -} -exports.getFunctionName = getFunctionName; -//# sourceMappingURL=stacktrace.js.map + getFirst(arr = this._lists) { + var j, len, list; + for (j = 0, len = arr.length; j < len; j++) { + list = arr[j]; + if (list.length > 0) { + return list; + } + } + return []; + } -/***/ }), + shiftLastFrom(priority) { + return this.getFirst(this._lists.slice(priority).reverse()).shift(); + } -/***/ 66538: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + }; -Object.defineProperty(exports, "__esModule", ({ value: true })); -var is_1 = __nccwpck_require__(92757); -/** - * Truncates given string to the maximum characters count - * - * @param str An object that contains serializable values - * @param max Maximum number of characters in truncated string - * @returns string Encoded - */ -function truncate(str, max) { - if (max === void 0) { max = 0; } - if (typeof str !== 'string' || max === 0) { - return str; - } - return str.length <= max ? str : str.substr(0, max) + "..."; -} -exports.truncate = truncate; -/** - * This is basically just `trim_line` from - * https://github.com/getsentry/sentry/blob/master/src/sentry/lang/javascript/processor.py#L67 - * - * @param str An object that contains serializable values - * @param max Maximum number of characters in truncated string - * @returns string Encoded - */ -function snipLine(line, colno) { - var newLine = line; - var ll = newLine.length; - if (ll <= 150) { - return newLine; - } - if (colno > ll) { - // eslint-disable-next-line no-param-reassign - colno = ll; - } - var start = Math.max(colno - 60, 0); - if (start < 5) { - start = 0; - } - var end = Math.min(start + 140, ll); - if (end > ll - 5) { - end = ll; - } - if (end === ll) { - start = Math.max(end - 140, 0); - } - newLine = newLine.slice(start, end); - if (start > 0) { - newLine = "'{snip} " + newLine; - } - if (end < ll) { - newLine += ' {snip}'; - } - return newLine; -} -exports.snipLine = snipLine; -/** - * Join values in array - * @param input array of values to be joined together - * @param delimiter string to be placed in-between values - * @returns Joined values - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function safeJoin(input, delimiter) { - if (!Array.isArray(input)) { - return ''; - } - var output = []; - // eslint-disable-next-line @typescript-eslint/prefer-for-of - for (var i = 0; i < input.length; i++) { - var value = input[i]; - try { - output.push(String(value)); - } - catch (e) { - output.push('[value cannot be serialized]'); - } - } - return output.join(delimiter); -} -exports.safeJoin = safeJoin; -/** - * Checks if the value matches a regex or includes the string - * @param value The string value to be checked against - * @param pattern Either a regex or a string that must be contained in value - */ -function isMatchingPattern(value, pattern) { - if (!is_1.isString(value)) { - return false; - } - if (is_1.isRegExp(pattern)) { - return pattern.test(value); - } - if (typeof pattern === 'string') { - return value.indexOf(pattern) !== -1; - } - return false; -} -exports.isMatchingPattern = isMatchingPattern; -//# sourceMappingURL=string.js.map + var Queues_1 = Queues; + + var BottleneckError; + + BottleneckError = class BottleneckError extends Error {}; + + var BottleneckError_1 = BottleneckError; + + var BottleneckError$1, LocalDatastore, parser$1; + + parser$1 = parser; + + BottleneckError$1 = BottleneckError_1; + + LocalDatastore = class LocalDatastore { + constructor(instance, storeOptions, storeInstanceOptions) { + this.instance = instance; + this.storeOptions = storeOptions; + this.clientId = this.instance._randomIndex(); + parser$1.load(storeInstanceOptions, storeInstanceOptions, this); + this._nextRequest = this._lastReservoirRefresh = Date.now(); + this._running = 0; + this._done = 0; + this._unblockTime = 0; + this.ready = this.Promise.resolve(); + this.clients = {}; + this._startHeartbeat(); + } + + _startHeartbeat() { + var base; + if ((this.heartbeat == null) && (this.storeOptions.reservoirRefreshInterval != null) && (this.storeOptions.reservoirRefreshAmount != null)) { + return typeof (base = (this.heartbeat = setInterval(() => { + var now; + now = Date.now(); + if (now >= this._lastReservoirRefresh + this.storeOptions.reservoirRefreshInterval) { + this.storeOptions.reservoir = this.storeOptions.reservoirRefreshAmount; + this._lastReservoirRefresh = now; + return this.instance._drainAll(this.computeCapacity()); + } + }, this.heartbeatInterval))).unref === "function" ? base.unref() : void 0; + } else { + return clearInterval(this.heartbeat); + } + } -/***/ }), + async __publish__(message) { + await this.yieldLoop(); + return this.instance.Events.trigger("message", message.toString()); + } -/***/ 88714: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + async __disconnect__(flush) { + await this.yieldLoop(); + clearInterval(this.heartbeat); + return this.Promise.resolve(); + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -var logger_1 = __nccwpck_require__(15577); -var misc_1 = __nccwpck_require__(32154); -/** - * Tells whether current environment supports ErrorEvent objects - * {@link supportsErrorEvent}. - * - * @returns Answer to the given question. - */ -function supportsErrorEvent() { - try { - new ErrorEvent(''); - return true; - } - catch (e) { - return false; - } -} -exports.supportsErrorEvent = supportsErrorEvent; -/** - * Tells whether current environment supports DOMError objects - * {@link supportsDOMError}. - * - * @returns Answer to the given question. - */ -function supportsDOMError() { - try { - // Chrome: VM89:1 Uncaught TypeError: Failed to construct 'DOMError': - // 1 argument required, but only 0 present. - // @ts-ignore It really needs 1 argument, not 0. - new DOMError(''); - return true; - } - catch (e) { - return false; - } -} -exports.supportsDOMError = supportsDOMError; -/** - * Tells whether current environment supports DOMException objects - * {@link supportsDOMException}. - * - * @returns Answer to the given question. - */ -function supportsDOMException() { - try { - new DOMException(''); - return true; - } - catch (e) { - return false; - } -} -exports.supportsDOMException = supportsDOMException; -/** - * Tells whether current environment supports Fetch API - * {@link supportsFetch}. - * - * @returns Answer to the given question. - */ -function supportsFetch() { - if (!('fetch' in misc_1.getGlobalObject())) { - return false; - } - try { - new Headers(); - new Request(''); - new Response(); - return true; - } - catch (e) { - return false; - } -} -exports.supportsFetch = supportsFetch; -/** - * isNativeFetch checks if the given function is a native implementation of fetch() - */ -// eslint-disable-next-line @typescript-eslint/ban-types -function isNativeFetch(func) { - return func && /^function fetch\(\)\s+\{\s+\[native code\]\s+\}$/.test(func.toString()); -} -/** - * Tells whether current environment supports Fetch API natively - * {@link supportsNativeFetch}. - * - * @returns true if `window.fetch` is natively implemented, false otherwise - */ -function supportsNativeFetch() { - if (!supportsFetch()) { - return false; - } - var global = misc_1.getGlobalObject(); - // Fast path to avoid DOM I/O - // eslint-disable-next-line @typescript-eslint/unbound-method - if (isNativeFetch(global.fetch)) { - return true; - } - // window.fetch is implemented, but is polyfilled or already wrapped (e.g: by a chrome extension) - // so create a "pure" iframe to see if that has native fetch - var result = false; - var doc = global.document; - // eslint-disable-next-line deprecation/deprecation - if (doc && typeof doc.createElement === "function") { - try { - var sandbox = doc.createElement('iframe'); - sandbox.hidden = true; - doc.head.appendChild(sandbox); - if (sandbox.contentWindow && sandbox.contentWindow.fetch) { - // eslint-disable-next-line @typescript-eslint/unbound-method - result = isNativeFetch(sandbox.contentWindow.fetch); - } - doc.head.removeChild(sandbox); - } - catch (err) { - logger_1.logger.warn('Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ', err); - } - } - return result; -} -exports.supportsNativeFetch = supportsNativeFetch; -/** - * Tells whether current environment supports ReportingObserver API - * {@link supportsReportingObserver}. - * - * @returns Answer to the given question. - */ -function supportsReportingObserver() { - return 'ReportingObserver' in misc_1.getGlobalObject(); -} -exports.supportsReportingObserver = supportsReportingObserver; -/** - * Tells whether current environment supports Referrer Policy API - * {@link supportsReferrerPolicy}. - * - * @returns Answer to the given question. - */ -function supportsReferrerPolicy() { - // Despite all stars in the sky saying that Edge supports old draft syntax, aka 'never', 'always', 'origin' and 'default - // https://caniuse.com/#feat=referrer-policy - // It doesn't. And it throw exception instead of ignoring this parameter... - // REF: https://github.com/getsentry/raven-js/issues/1233 - if (!supportsFetch()) { - return false; - } - try { - new Request('_', { - referrerPolicy: 'origin', - }); - return true; - } - catch (e) { - return false; - } -} -exports.supportsReferrerPolicy = supportsReferrerPolicy; -/** - * Tells whether current environment supports History API - * {@link supportsHistory}. - * - * @returns Answer to the given question. - */ -function supportsHistory() { - // NOTE: in Chrome App environment, touching history.pushState, *even inside - // a try/catch block*, will cause Chrome to output an error to console.error - // borrowed from: https://github.com/angular/angular.js/pull/13945/files - var global = misc_1.getGlobalObject(); - /* eslint-disable @typescript-eslint/no-unsafe-member-access */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - var chrome = global.chrome; - var isChromePackagedApp = chrome && chrome.app && chrome.app.runtime; - /* eslint-enable @typescript-eslint/no-unsafe-member-access */ - var hasHistoryApi = 'history' in global && !!global.history.pushState && !!global.history.replaceState; - return !isChromePackagedApp && hasHistoryApi; -} -exports.supportsHistory = supportsHistory; -//# sourceMappingURL=supports.js.map + yieldLoop(t = 0) { + return new this.Promise(function(resolve, reject) { + return setTimeout(resolve, t); + }); + } -/***/ }), + computePenalty() { + var ref; + return (ref = this.storeOptions.penalty) != null ? ref : (15 * this.storeOptions.minTime) || 5000; + } -/***/ 87833: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + async __updateSettings__(options) { + await this.yieldLoop(); + parser$1.overwrite(options, options, this.storeOptions); + this._startHeartbeat(); + this.instance._drainAll(this.computeCapacity()); + return true; + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -/* eslint-disable @typescript-eslint/explicit-function-return-type */ -/* eslint-disable @typescript-eslint/typedef */ -/* eslint-disable @typescript-eslint/explicit-module-boundary-types */ -/* eslint-disable @typescript-eslint/no-explicit-any */ -var is_1 = __nccwpck_require__(92757); -/** SyncPromise internal states */ -var States; -(function (States) { - /** Pending */ - States["PENDING"] = "PENDING"; - /** Resolved / OK */ - States["RESOLVED"] = "RESOLVED"; - /** Rejected / Error */ - States["REJECTED"] = "REJECTED"; -})(States || (States = {})); -/** - * Thenable class that behaves like a Promise and follows it's interface - * but is not async internally - */ -var SyncPromise = /** @class */ (function () { - function SyncPromise(executor) { - var _this = this; - this._state = States.PENDING; - this._handlers = []; - /** JSDoc */ - this._resolve = function (value) { - _this._setResult(States.RESOLVED, value); - }; - /** JSDoc */ - this._reject = function (reason) { - _this._setResult(States.REJECTED, reason); - }; - /** JSDoc */ - this._setResult = function (state, value) { - if (_this._state !== States.PENDING) { - return; - } - if (is_1.isThenable(value)) { - value.then(_this._resolve, _this._reject); - return; - } - _this._state = state; - _this._value = value; - _this._executeHandlers(); - }; - // TODO: FIXME - /** JSDoc */ - this._attachHandler = function (handler) { - _this._handlers = _this._handlers.concat(handler); - _this._executeHandlers(); - }; - /** JSDoc */ - this._executeHandlers = function () { - if (_this._state === States.PENDING) { - return; - } - var cachedHandlers = _this._handlers.slice(); - _this._handlers = []; - cachedHandlers.forEach(function (handler) { - if (handler.done) { - return; - } - if (_this._state === States.RESOLVED) { - if (handler.onfulfilled) { - // eslint-disable-next-line @typescript-eslint/no-floating-promises - handler.onfulfilled(_this._value); - } - } - if (_this._state === States.REJECTED) { - if (handler.onrejected) { - handler.onrejected(_this._value); - } - } - handler.done = true; - }); - }; - try { - executor(this._resolve, this._reject); - } - catch (e) { - this._reject(e); - } - } - /** JSDoc */ - SyncPromise.resolve = function (value) { - return new SyncPromise(function (resolve) { - resolve(value); - }); - }; - /** JSDoc */ - SyncPromise.reject = function (reason) { - return new SyncPromise(function (_, reject) { - reject(reason); - }); - }; - /** JSDoc */ - SyncPromise.all = function (collection) { - return new SyncPromise(function (resolve, reject) { - if (!Array.isArray(collection)) { - reject(new TypeError("Promise.all requires an array as input.")); - return; - } - if (collection.length === 0) { - resolve([]); - return; - } - var counter = collection.length; - var resolvedCollection = []; - collection.forEach(function (item, index) { - SyncPromise.resolve(item) - .then(function (value) { - resolvedCollection[index] = value; - counter -= 1; - if (counter !== 0) { - return; - } - resolve(resolvedCollection); - }) - .then(null, reject); - }); - }); - }; - /** JSDoc */ - SyncPromise.prototype.then = function (onfulfilled, onrejected) { - var _this = this; - return new SyncPromise(function (resolve, reject) { - _this._attachHandler({ - done: false, - onfulfilled: function (result) { - if (!onfulfilled) { - // TODO: ¯\_(ツ)_/¯ - // TODO: FIXME - resolve(result); - return; - } - try { - resolve(onfulfilled(result)); - return; - } - catch (e) { - reject(e); - return; - } - }, - onrejected: function (reason) { - if (!onrejected) { - reject(reason); - return; - } - try { - resolve(onrejected(reason)); - return; - } - catch (e) { - reject(e); - return; - } - }, - }); - }); - }; - /** JSDoc */ - SyncPromise.prototype.catch = function (onrejected) { - return this.then(function (val) { return val; }, onrejected); - }; - /** JSDoc */ - SyncPromise.prototype.finally = function (onfinally) { - var _this = this; - return new SyncPromise(function (resolve, reject) { - var val; - var isRejected; - return _this.then(function (value) { - isRejected = false; - val = value; - if (onfinally) { - onfinally(); - } - }, function (reason) { - isRejected = true; - val = reason; - if (onfinally) { - onfinally(); - } - }).then(function () { - if (isRejected) { - reject(val); - return; - } - resolve(val); - }); - }); - }; - /** JSDoc */ - SyncPromise.prototype.toString = function () { - return '[object SyncPromise]'; - }; - return SyncPromise; -}()); -exports.SyncPromise = SyncPromise; -//# sourceMappingURL=syncpromise.js.map + async __running__() { + await this.yieldLoop(); + return this._running; + } + + async __queued__() { + await this.yieldLoop(); + return this.instance.queued(); + } + + async __done__() { + await this.yieldLoop(); + return this._done; + } + + async __groupCheck__(time) { + await this.yieldLoop(); + return (this._nextRequest + this.timeout) < time; + } + + computeCapacity() { + var maxConcurrent, reservoir; + ({maxConcurrent, reservoir} = this.storeOptions); + if ((maxConcurrent != null) && (reservoir != null)) { + return Math.min(maxConcurrent - this._running, reservoir); + } else if (maxConcurrent != null) { + return maxConcurrent - this._running; + } else if (reservoir != null) { + return reservoir; + } else { + return null; + } + } + + conditionsCheck(weight) { + var capacity; + capacity = this.computeCapacity(); + return (capacity == null) || weight <= capacity; + } + + async __incrementReservoir__(incr) { + var reservoir; + await this.yieldLoop(); + reservoir = this.storeOptions.reservoir += incr; + this.instance._drainAll(this.computeCapacity()); + return reservoir; + } + + async __currentReservoir__() { + await this.yieldLoop(); + return this.storeOptions.reservoir; + } + + isBlocked(now) { + return this._unblockTime >= now; + } + + check(weight, now) { + return this.conditionsCheck(weight) && (this._nextRequest - now) <= 0; + } + + async __check__(weight) { + var now; + await this.yieldLoop(); + now = Date.now(); + return this.check(weight, now); + } + + async __register__(index, weight, expiration) { + var now, wait; + await this.yieldLoop(); + now = Date.now(); + if (this.conditionsCheck(weight)) { + this._running += weight; + if (this.storeOptions.reservoir != null) { + this.storeOptions.reservoir -= weight; + } + wait = Math.max(this._nextRequest - now, 0); + this._nextRequest = now + wait + this.storeOptions.minTime; + return { + success: true, + wait, + reservoir: this.storeOptions.reservoir + }; + } else { + return { + success: false + }; + } + } + + strategyIsBlock() { + return this.storeOptions.strategy === 3; + } + + async __submit__(queueLength, weight) { + var blocked, now, reachedHWM; + await this.yieldLoop(); + if ((this.storeOptions.maxConcurrent != null) && weight > this.storeOptions.maxConcurrent) { + throw new BottleneckError$1(`Impossible to add a job having a weight of ${weight} to a limiter having a maxConcurrent setting of ${this.storeOptions.maxConcurrent}`); + } + now = Date.now(); + reachedHWM = (this.storeOptions.highWater != null) && queueLength === this.storeOptions.highWater && !this.check(weight, now); + blocked = this.strategyIsBlock() && (reachedHWM || this.isBlocked(now)); + if (blocked) { + this._unblockTime = now + this.computePenalty(); + this._nextRequest = this._unblockTime + this.storeOptions.minTime; + this.instance._dropAllQueued(); + } + return { + reachedHWM, + blocked, + strategy: this.storeOptions.strategy + }; + } -/***/ }), + async __free__(index, weight) { + await this.yieldLoop(); + this._running -= weight; + this._done += weight; + this.instance._drainAll(this.computeCapacity()); + return { + running: this._running + }; + } -/***/ 1735: -/***/ ((module, exports, __nccwpck_require__) => { + }; -/* module decorator */ module = __nccwpck_require__.nmd(module); -Object.defineProperty(exports, "__esModule", ({ value: true })); -var misc_1 = __nccwpck_require__(32154); -var node_1 = __nccwpck_require__(16411); -/** - * A TimestampSource implementation for environments that do not support the Performance Web API natively. - * - * Note that this TimestampSource does not use a monotonic clock. A call to `nowSeconds` may return a timestamp earlier - * than a previously returned value. We do not try to emulate a monotonic behavior in order to facilitate debugging. It - * is more obvious to explain "why does my span have negative duration" than "why my spans have zero duration". - */ -var dateTimestampSource = { - nowSeconds: function () { return Date.now() / 1000; }, -}; -/** - * Returns a wrapper around the native Performance API browser implementation, or undefined for browsers that do not - * support the API. - * - * Wrapping the native API works around differences in behavior from different browsers. - */ -function getBrowserPerformance() { - var performance = misc_1.getGlobalObject().performance; - if (!performance || !performance.now) { - return undefined; - } - // Replace performance.timeOrigin with our own timeOrigin based on Date.now(). - // - // This is a partial workaround for browsers reporting performance.timeOrigin such that performance.timeOrigin + - // performance.now() gives a date arbitrarily in the past. - // - // Additionally, computing timeOrigin in this way fills the gap for browsers where performance.timeOrigin is - // undefined. - // - // The assumption that performance.timeOrigin + performance.now() ~= Date.now() is flawed, but we depend on it to - // interact with data coming out of performance entries. - // - // Note that despite recommendations against it in the spec, browsers implement the Performance API with a clock that - // might stop when the computer is asleep (and perhaps under other circumstances). Such behavior causes - // performance.timeOrigin + performance.now() to have an arbitrary skew over Date.now(). In laptop computers, we have - // observed skews that can be as long as days, weeks or months. - // - // See https://github.com/getsentry/sentry-javascript/issues/2590. - // - // BUG: despite our best intentions, this workaround has its limitations. It mostly addresses timings of pageload - // transactions, but ignores the skew built up over time that can aversely affect timestamps of navigation - // transactions of long-lived web pages. - var timeOrigin = Date.now() - performance.now(); - return { - now: function () { return performance.now(); }, - timeOrigin: timeOrigin, - }; -} -/** - * Returns the native Performance API implementation from Node.js. Returns undefined in old Node.js versions that don't - * implement the API. - */ -function getNodePerformance() { - try { - var perfHooks = node_1.dynamicRequire(module, 'perf_hooks'); - return perfHooks.performance; - } - catch (_) { - return undefined; - } -} -/** - * The Performance API implementation for the current platform, if available. - */ -var platformPerformance = node_1.isNodeEnv() ? getNodePerformance() : getBrowserPerformance(); -var timestampSource = platformPerformance === undefined - ? dateTimestampSource - : { - nowSeconds: function () { return (platformPerformance.timeOrigin + platformPerformance.now()) / 1000; }, - }; -/** - * Returns a timestamp in seconds since the UNIX epoch using the Date API. - */ -exports.dateTimestampInSeconds = dateTimestampSource.nowSeconds.bind(dateTimestampSource); -/** - * Returns a timestamp in seconds since the UNIX epoch using either the Performance or Date APIs, depending on the - * availability of the Performance API. - * - * See `usingPerformanceAPI` to test whether the Performance API is used. - * - * BUG: Note that because of how browsers implement the Performance API, the clock might stop when the computer is - * asleep. This creates a skew between `dateTimestampInSeconds` and `timestampInSeconds`. The - * skew can grow to arbitrary amounts like days, weeks or months. - * See https://github.com/getsentry/sentry-javascript/issues/2590. - */ -exports.timestampInSeconds = timestampSource.nowSeconds.bind(timestampSource); -// Re-exported with an old name for backwards-compatibility. -exports.timestampWithMs = exports.timestampInSeconds; -/** - * A boolean that is true when timestampInSeconds uses the Performance API to produce monotonic timestamps. - */ -exports.usingPerformanceAPI = platformPerformance !== undefined; -/** - * The number of milliseconds since the UNIX epoch. This value is only usable in a browser, and only when the - * performance API is available. - */ -exports.browserPerformanceTimeOrigin = (function () { - var performance = misc_1.getGlobalObject().performance; - if (!performance) { - return undefined; - } - if (performance.timeOrigin) { - return performance.timeOrigin; - } - // While performance.timing.navigationStart is deprecated in favor of performance.timeOrigin, performance.timeOrigin - // is not as widely supported. Namely, performance.timeOrigin is undefined in Safari as of writing. - // Also as of writing, performance.timing is not available in Web Workers in mainstream browsers, so it is not always - // a valid fallback. In the absence of an initial time provided by the browser, fallback to the current time from the - // Date API. - // eslint-disable-next-line deprecation/deprecation - return (performance.timing && performance.timing.navigationStart) || Date.now(); -})(); -//# sourceMappingURL=time.js.map + var LocalDatastore_1 = LocalDatastore; -/***/ }), + var BottleneckError$2, States; -/***/ 83633: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + BottleneckError$2 = BottleneckError_1; -"use strict"; -/*! - * accepts - * Copyright(c) 2014 Jonathan Ong - * Copyright(c) 2015 Douglas Christopher Wilson - * MIT Licensed - */ + States = class States { + constructor(status1) { + this.status = status1; + this.jobs = {}; + this.counts = this.status.map(function() { + return 0; + }); + } + next(id) { + var current, next; + current = this.jobs[id]; + next = current + 1; + if ((current != null) && next < this.status.length) { + this.counts[current]--; + this.counts[next]++; + return this.jobs[id]++; + } else if (current != null) { + this.counts[current]--; + return delete this.jobs[id]; + } + } + start(id) { + var initial; + initial = 0; + this.jobs[id] = initial; + return this.counts[initial]++; + } -/** - * Module dependencies. - * @private - */ + remove(id) { + var current; + current = this.jobs[id]; + if (current != null) { + this.counts[current]--; + delete this.jobs[id]; + } + return current != null; + } -var Negotiator = __nccwpck_require__(95385) -var mime = __nccwpck_require__(43583) + jobStatus(id) { + var ref; + return (ref = this.status[this.jobs[id]]) != null ? ref : null; + } -/** - * Module exports. - * @public - */ + statusJobs(status) { + var k, pos, ref, results, v; + if (status != null) { + pos = this.status.indexOf(status); + if (pos < 0) { + throw new BottleneckError$2(`status must be one of ${this.status.join(', ')}`); + } + ref = this.jobs; + results = []; + for (k in ref) { + v = ref[k]; + if (v === pos) { + results.push(k); + } + } + return results; + } else { + return Object.keys(this.jobs); + } + } -module.exports = Accepts + statusCounts() { + return this.counts.reduce(((acc, v, i) => { + acc[this.status[i]] = v; + return acc; + }), {}); + } -/** - * Create a new Accepts object for the given req. - * - * @param {object} req - * @public - */ + }; -function Accepts (req) { - if (!(this instanceof Accepts)) { - return new Accepts(req) - } + var States_1 = States; - this.headers = req.headers - this.negotiator = new Negotiator(req) -} + var DLList$2, Sync, + splice = [].splice; -/** - * 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", the extension name - * such as "json" 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 - * this.types('html'); - * // => "html" - * - * // Accept: text/*, application/json - * this.types('html'); - * // => "html" - * this.types('text/html'); - * // => "text/html" - * this.types('json', 'text'); - * // => "json" - * this.types('application/json'); - * // => "application/json" - * - * // Accept: text/*, application/json - * this.types('image/png'); - * this.types('png'); - * // => undefined - * - * // Accept: text/*;q=.5, application/json - * this.types(['html', 'json']); - * this.types('html', 'json'); - * // => "json" - * - * @param {String|Array} types... - * @return {String|Array|Boolean} - * @public - */ + DLList$2 = DLList_1; + + Sync = class Sync { + constructor(name, Promise) { + this.submit = this.submit.bind(this); + this.name = name; + this.Promise = Promise; + this._running = 0; + this._queue = new DLList$2(); + } + + isEmpty() { + return this._queue.length === 0; + } + + _tryToRun() { + var next; + if ((this._running < 1) && this._queue.length > 0) { + this._running++; + next = this._queue.shift(); + return next.task(...next.args, (...args) => { + this._running--; + this._tryToRun(); + return typeof next.cb === "function" ? next.cb(...args) : void 0; + }); + } + } + + submit(task, ...args) { + var cb, ref; + ref = args, [...args] = ref, [cb] = splice.call(args, -1); + this._queue.push({task, args, cb}); + return this._tryToRun(); + } + + schedule(task, ...args) { + var wrapped; + wrapped = function(...args) { + var cb, ref; + ref = args, [...args] = ref, [cb] = splice.call(args, -1); + return (task(...args)).then(function(...args) { + return cb(null, ...args); + }).catch(function(...args) { + return cb(...args); + }); + }; + return new this.Promise((resolve, reject) => { + return this.submit(wrapped, ...args, function(...args) { + return (args[0] != null ? reject : (args.shift(), resolve))(...args); + }); + }); + } + + }; + + var Sync_1 = Sync; + + var version = "2.17.1"; + var version$1 = { + version: version + }; + + var version$2 = /*#__PURE__*/Object.freeze({ + version: version, + default: version$1 + }); + + var require$$2 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); + + var require$$3 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); + + var require$$4 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); + + var Events$2, Group, IORedisConnection$1, RedisConnection$1, Scripts$1, parser$2; + + parser$2 = parser; + + Events$2 = Events_1; + + RedisConnection$1 = require$$2; + + IORedisConnection$1 = require$$3; + + Scripts$1 = require$$4; + + Group = (function() { + class Group { + constructor(limiterOptions = {}) { + this.deleteKey = this.deleteKey.bind(this); + this.updateSettings = this.updateSettings.bind(this); + this.limiterOptions = limiterOptions; + parser$2.load(this.limiterOptions, this.defaults, this); + this.Events = new Events$2(this); + this.instances = {}; + this.Bottleneck = Bottleneck_1; + this._startAutoCleanup(); + this.sharedConnection = this.connection != null; + if (this.connection == null) { + if (this.limiterOptions.datastore === "redis") { + this.connection = new RedisConnection$1(Object.assign({}, this.limiterOptions, {Events: this.Events})); + } else if (this.limiterOptions.datastore === "ioredis") { + this.connection = new IORedisConnection$1(Object.assign({}, this.limiterOptions, {Events: this.Events})); + } + } + } + + key(key = "") { + var ref; + return (ref = this.instances[key]) != null ? ref : (() => { + var limiter; + limiter = this.instances[key] = new this.Bottleneck(Object.assign(this.limiterOptions, { + id: `${this.id}-${key}`, + timeout: this.timeout, + connection: this.connection + })); + this.Events.trigger("created", limiter, key); + return limiter; + })(); + } + + async deleteKey(key = "") { + var deleted, instance; + instance = this.instances[key]; + if (this.connection) { + deleted = (await this.connection.__runCommand__(['del', ...Scripts$1.allKeys(`${this.id}-${key}`)])); + } + if (instance != null) { + delete this.instances[key]; + await instance.disconnect(); + } + return (instance != null) || deleted > 0; + } + + limiters() { + var k, ref, results, v; + ref = this.instances; + results = []; + for (k in ref) { + v = ref[k]; + results.push({ + key: k, + limiter: v + }); + } + return results; + } + + keys() { + return Object.keys(this.instances); + } + + async clusterKeys() { + var cursor, end, found, i, k, keys, len, next, start; + if (this.connection == null) { + return this.Promise.resolve(this.keys()); + } + keys = []; + cursor = null; + start = `b_${this.id}-`.length; + end = "_settings".length; + while (cursor !== 0) { + [next, found] = (await this.connection.__runCommand__(["scan", cursor != null ? cursor : 0, "match", `b_${this.id}-*_settings`, "count", 10000])); + cursor = ~~next; + for (i = 0, len = found.length; i < len; i++) { + k = found[i]; + keys.push(k.slice(start, -end)); + } + } + return keys; + } + + _startAutoCleanup() { + var base; + clearInterval(this.interval); + return typeof (base = (this.interval = setInterval(async() => { + var e, k, ref, results, time, v; + time = Date.now(); + ref = this.instances; + results = []; + for (k in ref) { + v = ref[k]; + try { + if ((await v._store.__groupCheck__(time))) { + results.push(this.deleteKey(k)); + } else { + results.push(void 0); + } + } catch (error) { + e = error; + results.push(v.Events.trigger("error", e)); + } + } + return results; + }, this.timeout / 2))).unref === "function" ? base.unref() : void 0; + } + + updateSettings(options = {}) { + parser$2.overwrite(options, this.defaults, this); + parser$2.overwrite(options, options, this.limiterOptions); + if (options.timeout != null) { + return this._startAutoCleanup(); + } + } + + disconnect(flush = true) { + var ref; + if (!this.sharedConnection) { + return (ref = this.connection) != null ? ref.disconnect(flush) : void 0; + } + } + + } + Group.prototype.defaults = { + timeout: 1000 * 60 * 5, + connection: null, + Promise: Promise, + id: "group-key" + }; -Accepts.prototype.type = -Accepts.prototype.types = function (types_) { - var types = types_ + return Group; - // support flattened arguments - if (types && !Array.isArray(types)) { - types = new Array(arguments.length) - for (var i = 0; i < types.length; i++) { - types[i] = arguments[i] - } - } + }).call(commonjsGlobal); - // no types, return all requested types - if (!types || types.length === 0) { - return this.negotiator.mediaTypes() - } + var Group_1 = Group; - // no accept header, return first given type - if (!this.headers.accept) { - return types[0] - } + var Batcher, Events$3, parser$3; - var mimes = types.map(extToMime) - var accepts = this.negotiator.mediaTypes(mimes.filter(validMime)) - var first = accepts[0] + parser$3 = parser; - return first - ? types[mimes.indexOf(first)] - : false -} + Events$3 = Events_1; -/** - * Return accepted encodings or best fit based on `encodings`. - * - * Given `Accept-Encoding: gzip, deflate` - * an array sorted by quality is returned: - * - * ['gzip', 'deflate'] - * - * @param {String|Array} encodings... - * @return {String|Array} - * @public - */ + Batcher = (function() { + class Batcher { + constructor(options = {}) { + this.options = options; + parser$3.load(this.options, this.defaults, this); + this.Events = new Events$3(this); + this._arr = []; + this._resetPromise(); + this._lastFlush = Date.now(); + } -Accepts.prototype.encoding = -Accepts.prototype.encodings = function (encodings_) { - var encodings = encodings_ + _resetPromise() { + return this._promise = new this.Promise((res, rej) => { + return this._resolve = res; + }); + } - // support flattened arguments - if (encodings && !Array.isArray(encodings)) { - encodings = new Array(arguments.length) - for (var i = 0; i < encodings.length; i++) { - encodings[i] = arguments[i] - } - } + _flush() { + clearTimeout(this._timeout); + this._lastFlush = Date.now(); + this._resolve(); + this.Events.trigger("batch", this._arr); + this._arr = []; + return this._resetPromise(); + } - // no encodings, return all requested encodings - if (!encodings || encodings.length === 0) { - return this.negotiator.encodings() - } + add(data) { + var ret; + this._arr.push(data); + ret = this._promise; + if (this._arr.length === this.maxSize) { + this._flush(); + } else if ((this.maxTime != null) && this._arr.length === 1) { + this._timeout = setTimeout(() => { + return this._flush(); + }, this.maxTime); + } + return ret; + } - return this.negotiator.encodings(encodings)[0] || false -} + } + Batcher.prototype.defaults = { + maxTime: null, + maxSize: null, + Promise: Promise + }; -/** - * Return accepted charsets or best fit based on `charsets`. - * - * Given `Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5` - * an array sorted by quality is returned: - * - * ['utf-8', 'utf-7', 'iso-8859-1'] - * - * @param {String|Array} charsets... - * @return {String|Array} - * @public - */ + return Batcher; -Accepts.prototype.charset = -Accepts.prototype.charsets = function (charsets_) { - var charsets = charsets_ + }).call(commonjsGlobal); - // support flattened arguments - if (charsets && !Array.isArray(charsets)) { - charsets = new Array(arguments.length) - for (var i = 0; i < charsets.length; i++) { - charsets[i] = arguments[i] - } - } + var Batcher_1 = Batcher; - // no charsets, return all requested charsets - if (!charsets || charsets.length === 0) { - return this.negotiator.charsets() - } + var require$$3$1 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); - return this.negotiator.charsets(charsets)[0] || false -} + var require$$7 = getCjsExportFromNamespace(version$2); -/** - * Return accepted languages or best fit based on `langs`. - * - * Given `Accept-Language: en;q=0.8, es, pt` - * an array sorted by quality is returned: - * - * ['es', 'pt', 'en'] - * - * @param {String|Array} langs... - * @return {Array|String} - * @public - */ + var Bottleneck, DEFAULT_PRIORITY, Events$4, LocalDatastore$1, NUM_PRIORITIES, Queues$1, RedisDatastore$1, States$1, Sync$1, parser$4, + splice$1 = [].splice; -Accepts.prototype.lang = -Accepts.prototype.langs = -Accepts.prototype.language = -Accepts.prototype.languages = function (languages_) { - var languages = languages_ + NUM_PRIORITIES = 10; - // support flattened arguments - if (languages && !Array.isArray(languages)) { - languages = new Array(arguments.length) - for (var i = 0; i < languages.length; i++) { - languages[i] = arguments[i] - } - } + DEFAULT_PRIORITY = 5; - // no languages, return all requested languages - if (!languages || languages.length === 0) { - return this.negotiator.languages() - } + parser$4 = parser; - return this.negotiator.languages(languages)[0] || false -} + Queues$1 = Queues_1; -/** - * Convert extnames to mime. - * - * @param {String} type - * @return {String} - * @private - */ + LocalDatastore$1 = LocalDatastore_1; -function extToMime (type) { - return type.indexOf('/') === -1 - ? mime.lookup(type) - : type -} + RedisDatastore$1 = require$$3$1; -/** - * Check if mime is valid. - * - * @param {String} type - * @return {String} - * @private - */ + Events$4 = Events_1; -function validMime (type) { - return typeof type === 'string' -} + States$1 = States_1; + Sync$1 = Sync_1; -/***/ }), + Bottleneck = (function() { + class Bottleneck { + constructor(options = {}, ...invalid) { + var storeInstanceOptions, storeOptions; + this._drainOne = this._drainOne.bind(this); + this.submit = this.submit.bind(this); + this.schedule = this.schedule.bind(this); + this.updateSettings = this.updateSettings.bind(this); + this.incrementReservoir = this.incrementReservoir.bind(this); + this._validateOptions(options, invalid); + parser$4.load(options, this.instanceDefaults, this); + this._queues = new Queues$1(NUM_PRIORITIES); + this._scheduled = {}; + this._states = new States$1(["RECEIVED", "QUEUED", "RUNNING", "EXECUTING"].concat(this.trackDoneStatus ? ["DONE"] : [])); + this._limiter = null; + this.Events = new Events$4(this); + this._submitLock = new Sync$1("submit", this.Promise); + this._registerLock = new Sync$1("register", this.Promise); + storeOptions = parser$4.load(options, this.storeDefaults, {}); + this._store = (function() { + if (this.datastore === "redis" || this.datastore === "ioredis" || (this.connection != null)) { + storeInstanceOptions = parser$4.load(options, this.redisStoreDefaults, {}); + return new RedisDatastore$1(this, storeOptions, storeInstanceOptions); + } else if (this.datastore === "local") { + storeInstanceOptions = parser$4.load(options, this.localStoreDefaults, {}); + return new LocalDatastore$1(this, storeOptions, storeInstanceOptions); + } else { + throw new Bottleneck.prototype.BottleneckError(`Invalid datastore type: ${this.datastore}`); + } + }).call(this); + this._queues.on("leftzero", () => { + var base; + return typeof (base = this._store.heartbeat).ref === "function" ? base.ref() : void 0; + }); + this._queues.on("zero", () => { + var base; + return typeof (base = this._store.heartbeat).unref === "function" ? base.unref() : void 0; + }); + } -/***/ 49690: -/***/ (function(module, __unused_webpack_exports, __nccwpck_require__) { + _validateOptions(options, invalid) { + if (!((options != null) && typeof options === "object" && invalid.length === 0)) { + throw new Bottleneck.prototype.BottleneckError("Bottleneck v2 takes a single object argument. Refer to https://github.com/SGrondin/bottleneck#upgrading-to-v2 if you're upgrading from Bottleneck v1."); + } + } -"use strict"; + ready() { + return this._store.ready; + } -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -const events_1 = __nccwpck_require__(82361); -const debug_1 = __importDefault(__nccwpck_require__(38237)); -const promisify_1 = __importDefault(__nccwpck_require__(66570)); -const debug = debug_1.default('agent-base'); -function isAgent(v) { - return Boolean(v) && typeof v.addRequest === 'function'; -} -function isSecureEndpoint() { - const { stack } = new Error(); - if (typeof stack !== 'string') - return false; - return stack.split('\n').some(l => l.indexOf('(https.js:') !== -1 || l.indexOf('node:https:') !== -1); -} -function createAgent(callback, opts) { - return new createAgent.Agent(callback, opts); -} -(function (createAgent) { - /** - * Base `http.Agent` implementation. - * No pooling/keep-alive is implemented by default. - * - * @param {Function} callback - * @api public - */ - class Agent extends events_1.EventEmitter { - constructor(callback, _opts) { - super(); - let opts = _opts; - if (typeof callback === 'function') { - this.callback = callback; - } - else if (callback) { - opts = callback; - } - // Timeout for the socket to be returned from the callback - this.timeout = null; - if (opts && typeof opts.timeout === 'number') { - this.timeout = opts.timeout; - } - // These aren't actually used by `agent-base`, but are required - // for the TypeScript definition files in `@types/node` :/ - this.maxFreeSockets = 1; - this.maxSockets = 1; - this.maxTotalSockets = Infinity; - this.sockets = {}; - this.freeSockets = {}; - this.requests = {}; - this.options = {}; - } - get defaultPort() { - if (typeof this.explicitDefaultPort === 'number') { - return this.explicitDefaultPort; - } - return isSecureEndpoint() ? 443 : 80; - } - set defaultPort(v) { - this.explicitDefaultPort = v; - } - get protocol() { - if (typeof this.explicitProtocol === 'string') { - return this.explicitProtocol; - } - return isSecureEndpoint() ? 'https:' : 'http:'; - } - set protocol(v) { - this.explicitProtocol = v; - } - callback(req, opts, fn) { - throw new Error('"agent-base" has no default implementation, you must subclass and override `callback()`'); - } - /** - * Called by node-core's "_http_client.js" module when creating - * a new HTTP request with this Agent instance. - * - * @api public - */ - addRequest(req, _opts) { - const opts = Object.assign({}, _opts); - if (typeof opts.secureEndpoint !== 'boolean') { - opts.secureEndpoint = isSecureEndpoint(); - } - if (opts.host == null) { - opts.host = 'localhost'; - } - if (opts.port == null) { - opts.port = opts.secureEndpoint ? 443 : 80; - } - if (opts.protocol == null) { - opts.protocol = opts.secureEndpoint ? 'https:' : 'http:'; - } - if (opts.host && opts.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 opts.path; - } - delete opts.agent; - delete opts.hostname; - delete opts._defaultAgent; - delete opts.defaultPort; - delete opts.createConnection; - // Hint to use "Connection: close" - // XXX: non-documented `http` module API :( - req._last = true; - req.shouldKeepAlive = false; - let timedOut = false; - let timeoutId = null; - const timeoutMs = opts.timeout || this.timeout; - const onerror = (err) => { - if (req._hadError) - return; - req.emit('error', err); - // For Safety. Some additional errors might fire later on - // and we need to make sure we don't double-fire the error event. - req._hadError = true; - }; - const ontimeout = () => { - timeoutId = null; - timedOut = true; - const err = new Error(`A "socket" was not created for HTTP request before ${timeoutMs}ms`); - err.code = 'ETIMEOUT'; - onerror(err); - }; - const callbackError = (err) => { - if (timedOut) - return; - if (timeoutId !== null) { - clearTimeout(timeoutId); - timeoutId = null; - } - onerror(err); - }; - const onsocket = (socket) => { - if (timedOut) - return; - if (timeoutId != null) { - clearTimeout(timeoutId); - timeoutId = null; - } - if (isAgent(socket)) { - // `socket` is actually an `http.Agent` instance, so - // relinquish responsibility for this `req` to the Agent - // from here on - debug('Callback returned another Agent instance %o', socket.constructor.name); - socket.addRequest(req, opts); - return; - } - if (socket) { - socket.once('free', () => { - this.freeSocket(socket, opts); - }); - req.onSocket(socket); - return; - } - const err = new Error(`no Duplex stream was returned to agent-base for \`${req.method} ${req.path}\``); - onerror(err); - }; - if (typeof this.callback !== 'function') { - onerror(new Error('`callback` is not defined')); - return; - } - if (!this.promisifiedCallback) { - if (this.callback.length >= 3) { - debug('Converting legacy callback function to promise'); - this.promisifiedCallback = promisify_1.default(this.callback); - } - else { - this.promisifiedCallback = this.callback; - } - } - if (typeof timeoutMs === 'number' && timeoutMs > 0) { - timeoutId = setTimeout(ontimeout, timeoutMs); - } - if ('port' in opts && typeof opts.port !== 'number') { - opts.port = Number(opts.port); - } - try { - debug('Resolving socket for %o request: %o', opts.protocol, `${req.method} ${req.path}`); - Promise.resolve(this.promisifiedCallback(req, opts)).then(onsocket, callbackError); - } - catch (err) { - Promise.reject(err).catch(callbackError); - } - } - freeSocket(socket, opts) { - debug('Freeing socket %o %o', socket.constructor.name, opts); - socket.destroy(); - } - destroy() { - debug('Destroying agent %o', this.constructor.name); - } - } - createAgent.Agent = Agent; - // So that `instanceof` works correctly - createAgent.prototype = createAgent.Agent.prototype; -})(createAgent || (createAgent = {})); -module.exports = createAgent; -//# sourceMappingURL=index.js.map + clients() { + return this._store.clients; + } -/***/ }), + channel() { + return `b_${this.id}`; + } -/***/ 66570: -/***/ ((__unused_webpack_module, exports) => { + channel_client() { + return `b_${this.id}_${this._store.clientId}`; + } -"use strict"; + publish(message) { + return this._store.__publish__(message); + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -function promisify(fn) { - return function (req, opts) { - return new Promise((resolve, reject) => { - fn.call(this, req, opts, (err, rtn) => { - if (err) { - reject(err); - } - else { - resolve(rtn); - } - }); - }); - }; -} -exports["default"] = promisify; -//# sourceMappingURL=promisify.js.map + disconnect(flush = true) { + return this._store.__disconnect__(flush); + } -/***/ }), + chain(_limiter) { + this._limiter = _limiter; + return this; + } -/***/ 61231: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + queued(priority) { + return this._queues.queued(priority); + } -"use strict"; + clusterQueued() { + return this._store.__queued__(); + } -const indentString = __nccwpck_require__(98043); -const cleanStack = __nccwpck_require__(27972); + empty() { + return this.queued() === 0 && this._submitLock.isEmpty(); + } + + running() { + return this._store.__running__(); + } -const cleanInternalStack = stack => stack.replace(/\s+at .*aggregate-error\/index.js:\d+:\d+\)?/g, ''); + done() { + return this._store.__done__(); + } -class AggregateError extends Error { - constructor(errors) { - if (!Array.isArray(errors)) { - throw new TypeError(`Expected input to be an Array, got ${typeof errors}`); - } + jobStatus(id) { + return this._states.jobStatus(id); + } - errors = [...errors].map(error => { - if (error instanceof Error) { - return error; - } + jobs(status) { + return this._states.statusJobs(status); + } - if (error !== null && typeof error === 'object') { - // Handle plain error objects with message property and/or possibly other metadata - return Object.assign(new Error(error.message), error); - } + counts() { + return this._states.statusCounts(); + } - return new Error(error); - }); + _sanitizePriority(priority) { + var sProperty; + sProperty = ~~priority !== priority ? DEFAULT_PRIORITY : priority; + if (sProperty < 0) { + return 0; + } else if (sProperty > NUM_PRIORITIES - 1) { + return NUM_PRIORITIES - 1; + } else { + return sProperty; + } + } - let message = errors - .map(error => { - // The `stack` property is not standardized, so we can't assume it exists - return typeof error.stack === 'string' ? cleanInternalStack(cleanStack(error.stack)) : String(error); - }) - .join('\n'); - message = '\n' + indentString(message, 4); - super(message); + _randomIndex() { + return Math.random().toString(36).slice(2); + } - this.name = 'AggregateError'; + check(weight = 1) { + return this._store.__check__(weight); + } - Object.defineProperty(this, '_errors', {value: errors}); - } + _run(next, wait, index, retryCount) { + var completed, done; + this.Events.trigger("debug", `Scheduling ${next.options.id}`, { + args: next.args, + options: next.options + }); + done = false; + completed = async(...args) => { + var e, error, eventInfo, retry, retryAfter, running; + if (!done) { + try { + done = true; + clearTimeout(this._scheduled[index].expiration); + delete this._scheduled[index]; + eventInfo = { + args: next.args, + options: next.options, + retryCount + }; + if ((error = args[0]) != null) { + retry = (await this.Events.trigger("failed", error, eventInfo)); + if (retry != null) { + retryAfter = ~~retry; + this.Events.trigger("retry", `Retrying ${next.options.id} after ${retryAfter} ms`, eventInfo); + return this._run(next, retryAfter, index, retryCount + 1); + } + } + this._states.next(next.options.id); // DONE + this.Events.trigger("debug", `Completed ${next.options.id}`, eventInfo); + this.Events.trigger("done", `Completed ${next.options.id}`, eventInfo); + ({running} = (await this._store.__free__(index, next.options.weight))); + this.Events.trigger("debug", `Freed ${next.options.id}`, eventInfo); + if (running === 0 && this.empty()) { + this.Events.trigger("idle"); + } + return typeof next.cb === "function" ? next.cb(...args) : void 0; + } catch (error1) { + e = error1; + return this.Events.trigger("error", e); + } + } + }; + if (retryCount === 0) { // RUNNING + this._states.next(next.options.id); + } + return this._scheduled[index] = { + timeout: setTimeout(() => { + this.Events.trigger("debug", `Executing ${next.options.id}`, { + args: next.args, + options: next.options + }); + if (retryCount === 0) { // EXECUTING + this._states.next(next.options.id); + } + if (this._limiter != null) { + return this._limiter.submit(next.options, next.task, ...next.args, completed); + } else { + return next.task(...next.args, completed); + } + }, wait), + expiration: next.options.expiration != null ? setTimeout(() => { + return completed(new Bottleneck.prototype.BottleneckError(`This job timed out after ${next.options.expiration} ms.`)); + }, wait + next.options.expiration) : void 0, + job: next + }; + } - * [Symbol.iterator]() { - for (const error of this._errors) { - yield error; - } - } -} + _drainOne(capacity) { + return this._registerLock.schedule(() => { + var args, index, next, options, queue; + if (this.queued() === 0) { + return this.Promise.resolve(null); + } + queue = this._queues.getFirst(); + ({options, args} = next = queue.first()); + if ((capacity != null) && options.weight > capacity) { + return this.Promise.resolve(null); + } + this.Events.trigger("debug", `Draining ${options.id}`, {args, options}); + index = this._randomIndex(); + return this._store.__register__(index, options.weight, options.expiration).then(({success, wait, reservoir}) => { + var empty; + this.Events.trigger("debug", `Drained ${options.id}`, {success, args, options}); + if (success) { + queue.shift(); + empty = this.empty(); + if (empty) { + this.Events.trigger("empty"); + } + if (reservoir === 0) { + this.Events.trigger("depleted", empty); + } + this._run(next, wait, index, 0); + return this.Promise.resolve(options.weight); + } else { + return this.Promise.resolve(null); + } + }); + }); + } -module.exports = AggregateError; + _drainAll(capacity, total = 0) { + return this._drainOne(capacity).then((drained) => { + var newCapacity; + if (drained != null) { + newCapacity = capacity != null ? capacity - drained : capacity; + return this._drainAll(newCapacity, total + drained); + } else { + return this.Promise.resolve(total); + } + }).catch((e) => { + return this.Events.trigger("error", e); + }); + } + _drop(job, message = "This job has been dropped by Bottleneck") { + if (this._states.remove(job.options.id)) { + if (this.rejectOnDrop) { + if (typeof job.cb === "function") { + job.cb(new Bottleneck.prototype.BottleneckError(message)); + } + } + return this.Events.trigger("dropped", job); + } + } -/***/ }), + _dropAllQueued(message) { + return this._queues.shiftAll((job) => { + return this._drop(job, message); + }); + } -/***/ 65063: -/***/ ((module) => { + stop(options = {}) { + var done, waitForExecuting; + options = parser$4.load(options, this.stopDefaults); + waitForExecuting = (at) => { + var finished; + finished = () => { + var counts; + counts = this._states.counts; + return (counts[0] + counts[1] + counts[2] + counts[3]) === at; + }; + return new this.Promise((resolve, reject) => { + if (finished()) { + return resolve(); + } else { + return this.on("done", () => { + if (finished()) { + this.removeAllListeners("done"); + return resolve(); + } + }); + } + }); + }; + done = options.dropWaitingJobs ? (this._run = (next) => { + return this._drop(next, options.dropErrorMessage); + }, this._drainOne = () => { + return this.Promise.resolve(null); + }, this._registerLock.schedule(() => { + return this._submitLock.schedule(() => { + var k, ref, v; + ref = this._scheduled; + for (k in ref) { + v = ref[k]; + if (this.jobStatus(v.job.options.id) === "RUNNING") { + clearTimeout(v.timeout); + clearTimeout(v.expiration); + this._drop(v.job, options.dropErrorMessage); + } + } + this._dropAllQueued(options.dropErrorMessage); + return waitForExecuting(0); + }); + })) : this.schedule({ + priority: NUM_PRIORITIES - 1, + weight: 0 + }, () => { + return waitForExecuting(1); + }); + this.submit = (...args) => { + var cb, ref; + ref = args, [...args] = ref, [cb] = splice$1.call(args, -1); + return typeof cb === "function" ? cb(new Bottleneck.prototype.BottleneckError(options.enqueueErrorMessage)) : void 0; + }; + this.stop = () => { + return this.Promise.reject(new Bottleneck.prototype.BottleneckError("stop() has already been called")); + }; + return done; + } -"use strict"; + submit(...args) { + var cb, job, options, ref, ref1, task; + if (typeof args[0] === "function") { + ref = args, [task, ...args] = ref, [cb] = splice$1.call(args, -1); + options = parser$4.load({}, this.jobDefaults, {}); + } else { + ref1 = args, [options, task, ...args] = ref1, [cb] = splice$1.call(args, -1); + options = parser$4.load(options, this.jobDefaults); + } + job = {options, task, args, cb}; + options.priority = this._sanitizePriority(options.priority); + if (options.id === this.jobDefaults.id) { + options.id = `${options.id}-${this._randomIndex()}`; + } + if (this.jobStatus(options.id) != null) { + if (typeof job.cb === "function") { + job.cb(new Bottleneck.prototype.BottleneckError(`A job with the same id already exists (id=${options.id})`)); + } + return false; + } + this._states.start(options.id); // RECEIVED + this.Events.trigger("debug", `Queueing ${options.id}`, {args, options}); + return this._submitLock.schedule(async() => { + var blocked, e, reachedHWM, shifted, strategy; + try { + ({reachedHWM, blocked, strategy} = (await this._store.__submit__(this.queued(), options.weight))); + this.Events.trigger("debug", `Queued ${options.id}`, {args, options, reachedHWM, blocked}); + } catch (error1) { + e = error1; + this._states.remove(options.id); + this.Events.trigger("debug", `Could not queue ${options.id}`, { + args, + options, + error: e + }); + if (typeof job.cb === "function") { + job.cb(e); + } + return false; + } + if (blocked) { + this._drop(job); + return true; + } else if (reachedHWM) { + shifted = strategy === Bottleneck.prototype.strategy.LEAK ? this._queues.shiftLastFrom(options.priority) : strategy === Bottleneck.prototype.strategy.OVERFLOW_PRIORITY ? this._queues.shiftLastFrom(options.priority + 1) : strategy === Bottleneck.prototype.strategy.OVERFLOW ? job : void 0; + if (shifted != null) { + this._drop(shifted); + } + if ((shifted == null) || strategy === Bottleneck.prototype.strategy.OVERFLOW) { + if (shifted == null) { + this._drop(job); + } + return reachedHWM; + } + } + this._states.next(job.options.id); // QUEUED + this._queues.push(options.priority, job); + await this._drainAll(); + return reachedHWM; + }); + } + schedule(...args) { + var options, task, wrapped; + if (typeof args[0] === "function") { + [task, ...args] = args; + options = parser$4.load({}, this.jobDefaults, {}); + } else { + [options, task, ...args] = args; + options = parser$4.load(options, this.jobDefaults); + } + wrapped = (...args) => { + var cb, e, ref, returned; + ref = args, [...args] = ref, [cb] = splice$1.call(args, -1); + returned = (function() { + try { + return task(...args); + } catch (error1) { + e = error1; + return this.Promise.reject(e); + } + }).call(this); + return (!(((returned != null ? returned.then : void 0) != null) && typeof returned.then === "function") ? this.Promise.resolve(returned) : returned).then(function(...args) { + return cb(null, ...args); + }).catch(function(...args) { + return cb(...args); + }); + }; + return new this.Promise((resolve, reject) => { + return this.submit(options, wrapped, ...args, function(...args) { + return (args[0] != null ? reject : (args.shift(), resolve))(...args); + }).catch((e) => { + return this.Events.trigger("error", e); + }); + }); + } -module.exports = ({onlyFirst = false} = {}) => { - const pattern = [ - '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)', - '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))' - ].join('|'); + wrap(fn) { + var schedule, wrapped; + schedule = this.schedule; + wrapped = function(...args) { + return schedule(fn.bind(this), ...args); + }; + wrapped.withOptions = (options, ...args) => { + return schedule(options, fn, ...args); + }; + return wrapped; + } - return new RegExp(pattern, onlyFirst ? undefined : 'g'); -}; + async updateSettings(options = {}) { + await this._store.__updateSettings__(parser$4.overwrite(options, this.storeDefaults)); + parser$4.overwrite(options, this.instanceDefaults, this); + return this; + } + currentReservoir() { + return this._store.__currentReservoir__(); + } -/***/ }), + incrementReservoir(incr = 0) { + return this._store.__incrementReservoir__(incr); + } -/***/ 52068: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + } + Bottleneck.default = Bottleneck; -"use strict"; -/* module decorator */ module = __nccwpck_require__.nmd(module); + Bottleneck.Events = Events$4; + Bottleneck.version = Bottleneck.prototype.version = require$$7.version; -const wrapAnsi16 = (fn, offset) => (...args) => { - const code = fn(...args); - return `\u001B[${code + offset}m`; -}; + Bottleneck.strategy = Bottleneck.prototype.strategy = { + LEAK: 1, + OVERFLOW: 2, + OVERFLOW_PRIORITY: 4, + BLOCK: 3 + }; -const wrapAnsi256 = (fn, offset) => (...args) => { - const code = fn(...args); - return `\u001B[${38 + offset};5;${code}m`; -}; + Bottleneck.BottleneckError = Bottleneck.prototype.BottleneckError = BottleneckError_1; -const wrapAnsi16m = (fn, offset) => (...args) => { - const rgb = fn(...args); - return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; -}; + Bottleneck.Group = Bottleneck.prototype.Group = Group_1; -const ansi2ansi = n => n; -const rgb2rgb = (r, g, b) => [r, g, b]; + Bottleneck.RedisConnection = Bottleneck.prototype.RedisConnection = require$$2; -const setLazyProperty = (object, property, get) => { - Object.defineProperty(object, property, { - get: () => { - const value = get(); + Bottleneck.IORedisConnection = Bottleneck.prototype.IORedisConnection = require$$3; - Object.defineProperty(object, property, { - value, - enumerable: true, - configurable: true - }); + Bottleneck.Batcher = Bottleneck.prototype.Batcher = Batcher_1; - return value; - }, - enumerable: true, - configurable: true - }); -}; + Bottleneck.prototype.jobDefaults = { + priority: DEFAULT_PRIORITY, + weight: 1, + expiration: null, + id: "" + }; -/** @type {typeof import('color-convert')} */ -let colorConvert; -const makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => { - if (colorConvert === undefined) { - colorConvert = __nccwpck_require__(86931); - } + Bottleneck.prototype.storeDefaults = { + maxConcurrent: null, + minTime: 0, + highWater: null, + strategy: Bottleneck.prototype.strategy.LEAK, + penalty: null, + reservoir: null, + reservoirRefreshInterval: null, + reservoirRefreshAmount: null + }; - const offset = isBackground ? 10 : 0; - const styles = {}; + Bottleneck.prototype.localStoreDefaults = { + Promise: Promise, + timeout: null, + heartbeatInterval: 250 + }; - for (const [sourceSpace, suite] of Object.entries(colorConvert)) { - const name = sourceSpace === 'ansi16' ? 'ansi' : sourceSpace; - if (sourceSpace === targetSpace) { - styles[name] = wrap(identity, offset); - } else if (typeof suite === 'object') { - styles[name] = wrap(suite[targetSpace], offset); - } - } + Bottleneck.prototype.redisStoreDefaults = { + Promise: Promise, + timeout: null, + heartbeatInterval: 5000, + clientTimeout: 10000, + clientOptions: {}, + clusterNodes: null, + clearDatastore: false, + connection: null + }; - return styles; -}; + Bottleneck.prototype.instanceDefaults = { + datastore: "local", + connection: null, + id: "", + rejectOnDrop: true, + trackDoneStatus: false, + Promise: Promise + }; -function assembleStyles() { - const codes = new Map(); - const styles = { - modifier: { - reset: [0, 0], - // 21 isn't widely supported and 22 does the same thing - bold: [1, 22], - dim: [2, 22], - italic: [3, 23], - underline: [4, 24], - inverse: [7, 27], - hidden: [8, 28], - strikethrough: [9, 29] - }, - color: { - black: [30, 39], - red: [31, 39], - green: [32, 39], - yellow: [33, 39], - blue: [34, 39], - magenta: [35, 39], - cyan: [36, 39], - white: [37, 39], + Bottleneck.prototype.stopDefaults = { + enqueueErrorMessage: "This limiter has been stopped and cannot accept new jobs.", + dropWaitingJobs: true, + dropErrorMessage: "This limiter has been stopped." + }; + + return Bottleneck; - // Bright color - blackBright: [90, 39], - redBright: [91, 39], - greenBright: [92, 39], - yellowBright: [93, 39], - blueBright: [94, 39], - magentaBright: [95, 39], - cyanBright: [96, 39], - whiteBright: [97, 39] - }, - bgColor: { - bgBlack: [40, 49], - bgRed: [41, 49], - bgGreen: [42, 49], - bgYellow: [43, 49], - bgBlue: [44, 49], - bgMagenta: [45, 49], - bgCyan: [46, 49], - bgWhite: [47, 49], + }).call(commonjsGlobal); - // Bright color - bgBlackBright: [100, 49], - bgRedBright: [101, 49], - bgGreenBright: [102, 49], - bgYellowBright: [103, 49], - bgBlueBright: [104, 49], - bgMagentaBright: [105, 49], - bgCyanBright: [106, 49], - bgWhiteBright: [107, 49] - } - }; + var Bottleneck_1 = Bottleneck; - // Alias bright black as gray (and grey) - styles.color.gray = styles.color.blackBright; - styles.bgColor.bgGray = styles.bgColor.bgBlackBright; - styles.color.grey = styles.color.blackBright; - styles.bgColor.bgGrey = styles.bgColor.bgBlackBright; + var lib = Bottleneck_1; - for (const [groupName, group] of Object.entries(styles)) { - for (const [styleName, style] of Object.entries(group)) { - styles[styleName] = { - open: `\u001B[${style[0]}m`, - close: `\u001B[${style[1]}m` - }; + return lib; - group[styleName] = styles[styleName]; +}))); - codes.set(style[0], style[1]); - } - Object.defineProperty(styles, groupName, { - value: group, - enumerable: false - }); - } +/***/ }), - Object.defineProperty(styles, 'codes', { - value: codes, - enumerable: false - }); +/***/ 9239: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - styles.color.close = '\u001B[39m'; - styles.bgColor.close = '\u001B[49m'; +"use strict"; +/*jshint node:true */ - setLazyProperty(styles.color, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, false)); - setLazyProperty(styles.color, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, false)); - setLazyProperty(styles.color, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, false)); - setLazyProperty(styles.bgColor, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, true)); - setLazyProperty(styles.bgColor, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, true)); - setLazyProperty(styles.bgColor, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, true)); +var Buffer = (__nccwpck_require__(14300).Buffer); // browserify +var SlowBuffer = (__nccwpck_require__(14300).SlowBuffer); - return styles; +module.exports = bufferEq; + +function bufferEq(a, b) { + + // shortcutting on type is necessary for correctness + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + return false; + } + + // buffer sizes should be well-known information, so despite this + // shortcutting, it doesn't leak any information about the *contents* of the + // buffers. + if (a.length !== b.length) { + return false; + } + + var c = 0; + for (var i = 0; i < a.length; i++) { + /*jshint bitwise:false */ + c |= a[i] ^ b[i]; // XOR + } + return c === 0; } -// Make the export immutable -Object.defineProperty(module, 'exports', { - enumerable: true, - get: assembleStyles -}); +bufferEq.install = function() { + Buffer.prototype.equal = SlowBuffer.prototype.equal = function equal(that) { + return bufferEq(this, that); + }; +}; + +var origBufEqual = Buffer.prototype.equal; +var origSlowBufEqual = SlowBuffer.prototype.equal; +bufferEq.restore = function() { + Buffer.prototype.equal = origBufEqual; + SlowBuffer.prototype.equal = origSlowBufEqual; +}; /***/ }), -/***/ 62003: +/***/ 86966: /***/ ((module) => { "use strict"; +/*! + * bytes + * Copyright(c) 2012-2014 TJ Holowaychuk + * Copyright(c) 2015 Jed Watson + * MIT Licensed + */ + /** - * Expose `arrayFlatten`. + * Module exports. + * @public */ -module.exports = arrayFlatten + +module.exports = bytes; +module.exports.format = format; +module.exports.parse = parse; /** - * Recursive flatten function with depth. - * - * @param {Array} array - * @param {Array} result - * @param {Number} depth - * @return {Array} + * Module variables. + * @private */ -function flattenWithDepth (array, result, depth) { - for (var i = 0; i < array.length; i++) { - var value = array[i] - if (depth > 0 && Array.isArray(value)) { - flattenWithDepth(value, result, depth - 1) - } else { - result.push(value) - } - } +var formatThousandsRegExp = /\B(?=(\d{3})+(?!\d))/g; - return result -} +var formatDecimalsRegExp = /(?:\.0*|(\.[^0]+)0+)$/; + +var map = { + b: 1, + kb: 1 << 10, + mb: 1 << 20, + gb: 1 << 30, + tb: Math.pow(1024, 4), + pb: Math.pow(1024, 5), +}; + +var parseRegExp = /^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb|pb)$/i; /** - * Recursive flatten function. Omitting depth is slightly faster. + * Convert the given value in bytes into a string or parse to string to an integer in bytes. * - * @param {Array} array - * @param {Array} result - * @return {Array} + * @param {string|number} value + * @param {{ + * case: [string], + * decimalPlaces: [number] + * fixedDecimals: [boolean] + * thousandsSeparator: [string] + * unitSeparator: [string] + * }} [options] bytes options. + * + * @returns {string|number|null} */ -function flattenForever (array, result) { - for (var i = 0; i < array.length; i++) { - var value = array[i] - if (Array.isArray(value)) { - flattenForever(value, result) - } else { - result.push(value) - } +function bytes(value, options) { + if (typeof value === 'string') { + return parse(value); } - return result + if (typeof value === 'number') { + return format(value, options); + } + + return null; } /** - * Flatten an array, with the ability to define a depth. + * Format the given value in bytes into a string. * - * @param {Array} array - * @param {Number} depth - * @return {Array} + * If the value is negative, it is kept as such. If it is a float, + * it is rounded. + * + * @param {number} value + * @param {object} [options] + * @param {number} [options.decimalPlaces=2] + * @param {number} [options.fixedDecimals=false] + * @param {string} [options.thousandsSeparator=] + * @param {string} [options.unit=] + * @param {string} [options.unitSeparator=] + * + * @returns {string|null} + * @public */ -function arrayFlatten (array, depth) { - if (depth == null) { - return flattenForever(array, []) - } - - return flattenWithDepth(array, [], depth) -} +function format(value, options) { + if (!Number.isFinite(value)) { + return null; + } -/***/ }), + var mag = Math.abs(value); + var thousandsSeparator = (options && options.thousandsSeparator) || ''; + var unitSeparator = (options && options.unitSeparator) || ''; + var decimalPlaces = (options && options.decimalPlaces !== undefined) ? options.decimalPlaces : 2; + var fixedDecimals = Boolean(options && options.fixedDecimals); + var unit = (options && options.unit) || ''; -/***/ 86950: -/***/ ((module) => { + if (!unit || !map[unit.toLowerCase()]) { + if (mag >= map.pb) { + unit = 'PB'; + } else if (mag >= map.tb) { + unit = 'TB'; + } else if (mag >= map.gb) { + unit = 'GB'; + } else if (mag >= map.mb) { + unit = 'MB'; + } else if (mag >= map.kb) { + unit = 'KB'; + } else { + unit = 'B'; + } + } -"use strict"; + var val = value / map[unit.toLowerCase()]; + var str = val.toFixed(decimalPlaces); + if (!fixedDecimals) { + str = str.replace(formatDecimalsRegExp, '$1'); + } -/* global SharedArrayBuffer, Atomics */ + if (thousandsSeparator) { + str = str.replace(formatThousandsRegExp, thousandsSeparator); + } -if (typeof SharedArrayBuffer !== 'undefined' && typeof Atomics !== 'undefined') { - const nil = new Int32Array(new SharedArrayBuffer(4)) + return str + unitSeparator + unit; +} - function sleep (ms) { - // also filters out NaN, non-number types, including empty strings, but allows bigints - const valid = ms > 0 && ms < Infinity - if (valid === false) { - if (typeof ms !== 'number' && typeof ms !== 'bigint') { - throw TypeError('sleep: ms must be a number') - } - throw RangeError('sleep: ms must be a number that is greater than 0 but less than Infinity') - } +/** + * Parse the string value into an integer in bytes. + * + * If no unit is given, it is assumed the value is in bytes. + * + * @param {number|string} val + * + * @returns {number|null} + * @public + */ - Atomics.wait(nil, 0, 0, Number(ms)) +function parse(val) { + if (typeof val === 'number' && !isNaN(val)) { + return val; } - module.exports = sleep -} else { - function sleep (ms) { - // also filters out NaN, non-number types, including empty strings, but allows bigints - const valid = ms > 0 && ms < Infinity - if (valid === false) { - if (typeof ms !== 'number' && typeof ms !== 'bigint') { - throw TypeError('sleep: ms must be a number') - } - throw RangeError('sleep: ms must be a number that is greater than 0 but less than Infinity') - } - const target = Date.now() + Number(ms) - while (target > Date.now()){} + if (typeof val !== 'string') { + return null; } - module.exports = sleep + // Test if the string passed is valid + var results = parseRegExp.exec(val); + var floatValue; + var unit = 'b'; + if (!results) { + // Nothing could be extracted from the given string + floatValue = parseInt(val, 10); + unit = 'b' + } else { + // Retrieve the value and the unit + floatValue = parseFloat(results[1]); + unit = results[4].toLowerCase(); + } + + return Math.floor(map[unit] * floatValue); } /***/ }), -/***/ 83682: +/***/ 78818: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var register = __nccwpck_require__(44670) -var addHook = __nccwpck_require__(5549) -var removeHook = __nccwpck_require__(6819) - -// bind with array of arguments: https://stackoverflow.com/a/21792913 -var bind = Function.bind -var bindable = bind.bind(bind) +"use strict"; -function bindApi (hook, state, name) { - var removeHookRef = bindable(removeHook, null).apply(null, name ? [state, name] : [state]) - hook.api = { remove: removeHookRef } - hook.remove = removeHookRef +const ansiStyles = __nccwpck_require__(52068); +const {stdout: stdoutColor, stderr: stderrColor} = __nccwpck_require__(59318); +const { + stringReplaceAll, + stringEncaseCRLFWithFirstIndex +} = __nccwpck_require__(82415); - ;['before', 'error', 'after', 'wrap'].forEach(function (kind) { - var args = name ? [state, kind, name] : [state, kind] - hook[kind] = hook.api[kind] = bindable(addHook, null).apply(null, args) - }) -} +const {isArray} = Array; -function HookSingular () { - var singularHookName = 'h' - var singularHookState = { - registry: {} - } - var singularHook = register.bind(null, singularHookState, singularHookName) - bindApi(singularHook, singularHookState, singularHookName) - return singularHook -} +// `supportsColor.level` → `ansiStyles.color[name]` mapping +const levelMapping = [ + 'ansi', + 'ansi', + 'ansi256', + 'ansi16m' +]; -function HookCollection () { - var state = { - registry: {} - } +const styles = Object.create(null); - var hook = register.bind(null, state) - bindApi(hook, state) +const applyOptions = (object, options = {}) => { + if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) { + throw new Error('The `level` option should be an integer from 0 to 3'); + } - return hook -} + // Detect level if not set manually + const colorLevel = stdoutColor ? stdoutColor.level : 0; + object.level = options.level === undefined ? colorLevel : options.level; +}; -var collectionHookDeprecationMessageDisplayed = false -function Hook () { - if (!collectionHookDeprecationMessageDisplayed) { - console.warn('[before-after-hook]: "Hook()" repurposing warning, use "Hook.Collection()". Read more: https://git.io/upgrade-before-after-hook-to-1.4') - collectionHookDeprecationMessageDisplayed = true - } - return HookCollection() +class ChalkClass { + constructor(options) { + // eslint-disable-next-line no-constructor-return + return chalkFactory(options); + } } -Hook.Singular = HookSingular.bind() -Hook.Collection = HookCollection.bind() - -module.exports = Hook -// expose constructors as a named property for TypeScript -module.exports.Hook = Hook -module.exports.Singular = Hook.Singular -module.exports.Collection = Hook.Collection - - -/***/ }), - -/***/ 5549: -/***/ ((module) => { +const chalkFactory = options => { + const chalk = {}; + applyOptions(chalk, options); -module.exports = addHook + chalk.template = (...arguments_) => chalkTag(chalk.template, ...arguments_); -function addHook (state, kind, name, hook) { - var orig = hook - if (!state.registry[name]) { - state.registry[name] = [] - } + Object.setPrototypeOf(chalk, Chalk.prototype); + Object.setPrototypeOf(chalk.template, chalk); - if (kind === 'before') { - hook = function (method, options) { - return Promise.resolve() - .then(orig.bind(null, options)) - .then(method.bind(null, options)) - } - } + chalk.template.constructor = () => { + throw new Error('`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.'); + }; - if (kind === 'after') { - hook = function (method, options) { - var result - return Promise.resolve() - .then(method.bind(null, options)) - .then(function (result_) { - result = result_ - return orig(result, options) - }) - .then(function () { - return result - }) - } - } + chalk.template.Instance = ChalkClass; - if (kind === 'error') { - hook = function (method, options) { - return Promise.resolve() - .then(method.bind(null, options)) - .catch(function (error) { - return orig(error, options) - }) - } - } + return chalk.template; +}; - state.registry[name].push({ - hook: hook, - orig: orig - }) +function Chalk(options) { + return chalkFactory(options); } +for (const [styleName, style] of Object.entries(ansiStyles)) { + styles[styleName] = { + get() { + const builder = createBuilder(this, createStyler(style.open, style.close, this._styler), this._isEmpty); + Object.defineProperty(this, styleName, {value: builder}); + return builder; + } + }; +} -/***/ }), - -/***/ 44670: -/***/ ((module) => { - -module.exports = register - -function register (state, name, method, options) { - if (typeof method !== 'function') { - throw new Error('method for before hook must be a function') - } - - if (!options) { - options = {} - } - - if (Array.isArray(name)) { - return name.reverse().reduce(function (callback, name) { - return register.bind(null, state, name, callback, options) - }, method)() - } +styles.visible = { + get() { + const builder = createBuilder(this, this._styler, true); + Object.defineProperty(this, 'visible', {value: builder}); + return builder; + } +}; - return Promise.resolve() - .then(function () { - if (!state.registry[name]) { - return method(options) - } +const usedModels = ['rgb', 'hex', 'keyword', 'hsl', 'hsv', 'hwb', 'ansi', 'ansi256']; - return (state.registry[name]).reduce(function (method, registered) { - return registered.hook.bind(null, method, options) - }, method)() - }) +for (const model of usedModels) { + styles[model] = { + get() { + const {level} = this; + return function (...arguments_) { + const styler = createStyler(ansiStyles.color[levelMapping[level]][model](...arguments_), ansiStyles.color.close, this._styler); + return createBuilder(this, styler, this._isEmpty); + }; + } + }; } +for (const model of usedModels) { + const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); + styles[bgModel] = { + get() { + const {level} = this; + return function (...arguments_) { + const styler = createStyler(ansiStyles.bgColor[levelMapping[level]][model](...arguments_), ansiStyles.bgColor.close, this._styler); + return createBuilder(this, styler, this._isEmpty); + }; + } + }; +} -/***/ }), - -/***/ 6819: -/***/ ((module) => { +const proto = Object.defineProperties(() => {}, { + ...styles, + level: { + enumerable: true, + get() { + return this._generator.level; + }, + set(level) { + this._generator.level = level; + } + } +}); -module.exports = removeHook +const createStyler = (open, close, parent) => { + let openAll; + let closeAll; + if (parent === undefined) { + openAll = open; + closeAll = close; + } else { + openAll = parent.openAll + open; + closeAll = close + parent.closeAll; + } -function removeHook (state, name, method) { - if (!state.registry[name]) { - return - } + return { + open, + close, + openAll, + closeAll, + parent + }; +}; - var index = state.registry[name] - .map(function (registered) { return registered.orig }) - .indexOf(method) +const createBuilder = (self, _styler, _isEmpty) => { + const builder = (...arguments_) => { + if (isArray(arguments_[0]) && isArray(arguments_[0].raw)) { + // Called as a template literal, for example: chalk.red`2 + 3 = {bold ${2+3}}` + return applyStyle(builder, chalkTag(builder, ...arguments_)); + } - if (index === -1) { - return - } + // Single argument is hot path, implicit coercion is faster than anything + // eslint-disable-next-line no-implicit-coercion + return applyStyle(builder, (arguments_.length === 1) ? ('' + arguments_[0]) : arguments_.join(' ')); + }; - state.registry[name].splice(index, 1) -} + // We alter the prototype because we must return a function, but there is + // no way to create a function with a different prototype + Object.setPrototypeOf(builder, proto); + builder._generator = self; + builder._styler = _styler; + builder._isEmpty = _isEmpty; -/***/ }), + return builder; +}; -/***/ 97076: -/***/ ((module, exports, __nccwpck_require__) => { +const applyStyle = (self, string) => { + if (self.level <= 0 || !string) { + return self._isEmpty ? '' : string; + } -"use strict"; -/*! - * body-parser - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ + let styler = self._styler; + if (styler === undefined) { + return string; + } + const {openAll, closeAll} = styler; + if (string.indexOf('\u001B') !== -1) { + while (styler !== undefined) { + // Replace any instances already present with a re-opening code + // otherwise only the part of the string until said closing code + // will be colored, and the rest will simply be 'plain'. + string = stringReplaceAll(string, styler.close, styler.open); -/** - * Module dependencies. - * @private - */ + styler = styler.parent; + } + } -var deprecate = __nccwpck_require__(18883)('body-parser') + // We can move both next actions out of loop, because remaining actions in loop won't have + // any/visible effect on parts we add here. Close the styling before a linebreak and reopen + // after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92 + const lfIndex = string.indexOf('\n'); + if (lfIndex !== -1) { + string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex); + } -/** - * Cache of loaded parsers. - * @private - */ + return openAll + string + closeAll; +}; -var parsers = Object.create(null) +let template; +const chalkTag = (chalk, ...strings) => { + const [firstString] = strings; -/** - * @typedef Parsers - * @type {function} - * @property {function} json - * @property {function} raw - * @property {function} text - * @property {function} urlencoded - */ + if (!isArray(firstString) || !isArray(firstString.raw)) { + // If chalk() was called by itself or with a string, + // return the string itself as a string. + return strings.join(' '); + } -/** - * Module exports. - * @type {Parsers} - */ + const arguments_ = strings.slice(1); + const parts = [firstString.raw[0]]; -exports = module.exports = deprecate.function(bodyParser, - 'bodyParser: use individual json/urlencoded middlewares') + for (let i = 1; i < firstString.length; i++) { + parts.push( + String(arguments_[i - 1]).replace(/[{}\\]/g, '\\$&'), + String(firstString.raw[i]) + ); + } -/** - * JSON parser. - * @public - */ + if (template === undefined) { + template = __nccwpck_require__(20500); + } -Object.defineProperty(exports, "json", ({ - configurable: true, - enumerable: true, - get: createParserGetter('json') -})) + return template(chalk, parts.join('')); +}; -/** - * Raw parser. - * @public - */ +Object.defineProperties(Chalk.prototype, styles); -Object.defineProperty(exports, "raw", ({ - configurable: true, - enumerable: true, - get: createParserGetter('raw') -})) +const chalk = Chalk(); // eslint-disable-line new-cap +chalk.supportsColor = stdoutColor; +chalk.stderr = Chalk({level: stderrColor ? stderrColor.level : 0}); // eslint-disable-line new-cap +chalk.stderr.supportsColor = stderrColor; -/** - * Text parser. - * @public - */ +module.exports = chalk; -Object.defineProperty(exports, "text", ({ - configurable: true, - enumerable: true, - get: createParserGetter('text') -})) -/** - * URL-encoded parser. - * @public - */ +/***/ }), -Object.defineProperty(exports, "urlencoded", ({ - configurable: true, - enumerable: true, - get: createParserGetter('urlencoded') -})) +/***/ 20500: +/***/ ((module) => { -/** - * Create a middleware to parse json and urlencoded bodies. - * - * @param {object} [options] - * @return {function} - * @deprecated - * @public - */ +"use strict"; -function bodyParser (options) { - var opts = {} +const TEMPLATE_REGEX = /(?:\\(u(?:[a-f\d]{4}|\{[a-f\d]{1,6}\})|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi; +const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g; +const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/; +const ESCAPE_REGEX = /\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.)|([^\\])/gi; - // exclude type option - if (options) { - for (var prop in options) { - if (prop !== 'type') { - opts[prop] = options[prop] - } - } - } +const ESCAPES = new Map([ + ['n', '\n'], + ['r', '\r'], + ['t', '\t'], + ['b', '\b'], + ['f', '\f'], + ['v', '\v'], + ['0', '\0'], + ['\\', '\\'], + ['e', '\u001B'], + ['a', '\u0007'] +]); - var _urlencoded = exports.urlencoded(opts) - var _json = exports.json(opts) +function unescape(c) { + const u = c[0] === 'u'; + const bracket = c[1] === '{'; - return function bodyParser (req, res, next) { - _json(req, res, function (err) { - if (err) return next(err) - _urlencoded(req, res, next) - }) - } -} + if ((u && !bracket && c.length === 5) || (c[0] === 'x' && c.length === 3)) { + return String.fromCharCode(parseInt(c.slice(1), 16)); + } -/** - * Create a getter for loading a parser. - * @private - */ + if (u && bracket) { + return String.fromCodePoint(parseInt(c.slice(2, -1), 16)); + } -function createParserGetter (name) { - return function get () { - return loadParser(name) - } + return ESCAPES.get(c) || c; } -/** - * Load a parser module. - * @private - */ - -function loadParser (parserName) { - var parser = parsers[parserName] - - if (parser !== undefined) { - return parser - } +function parseArguments(name, arguments_) { + const results = []; + const chunks = arguments_.trim().split(/\s*,\s*/g); + let matches; - // this uses a switch for static require analysis - switch (parserName) { - case 'json': - parser = __nccwpck_require__(20859) - break - case 'raw': - parser = __nccwpck_require__(49609) - break - case 'text': - parser = __nccwpck_require__(26382) - break - case 'urlencoded': - parser = __nccwpck_require__(76100) - break - } + for (const chunk of chunks) { + const number = Number(chunk); + if (!Number.isNaN(number)) { + results.push(number); + } else if ((matches = chunk.match(STRING_REGEX))) { + results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, character) => escape ? unescape(escape) : character)); + } else { + throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`); + } + } - // store to prevent invoking require() - return (parsers[parserName] = parser) + return results; } +function parseStyle(style) { + STYLE_REGEX.lastIndex = 0; -/***/ }), - -/***/ 88862: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -/*! - * body-parser - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ + const results = []; + let matches; + while ((matches = STYLE_REGEX.exec(style)) !== null) { + const name = matches[1]; + if (matches[2]) { + const args = parseArguments(name, matches[2]); + results.push([name].concat(args)); + } else { + results.push([name]); + } + } -/** - * Module dependencies. - * @private - */ + return results; +} -var createError = __nccwpck_require__(95193) -var getBody = __nccwpck_require__(47742) -var iconv = __nccwpck_require__(19032) -var onFinished = __nccwpck_require__(92098) -var zlib = __nccwpck_require__(59796) +function buildStyle(chalk, styles) { + const enabled = {}; -/** - * Module exports. - */ + for (const layer of styles) { + for (const style of layer.styles) { + enabled[style[0]] = layer.inverse ? null : style.slice(1); + } + } -module.exports = read + let current = chalk; + for (const [styleName, styles] of Object.entries(enabled)) { + if (!Array.isArray(styles)) { + continue; + } -/** - * Read a request into a buffer and parse. - * - * @param {object} req - * @param {object} res - * @param {function} next - * @param {function} parse - * @param {function} debug - * @param {object} options - * @private - */ + if (!(styleName in current)) { + throw new Error(`Unknown Chalk style: ${styleName}`); + } -function read (req, res, next, parse, debug, options) { - var length - var opts = options - var stream + current = styles.length > 0 ? current[styleName](...styles) : current[styleName]; + } - // flag as parsed - req._body = true + return current; +} - // read options - var encoding = opts.encoding !== null - ? opts.encoding - : null - var verify = opts.verify +module.exports = (chalk, temporary) => { + const styles = []; + const chunks = []; + let chunk = []; - try { - // get the content stream - stream = contentstream(req, debug, opts.inflate) - length = stream.length - stream.length = undefined - } catch (err) { - return next(err) - } + // eslint-disable-next-line max-params + temporary.replace(TEMPLATE_REGEX, (m, escapeCharacter, inverse, style, close, character) => { + if (escapeCharacter) { + chunk.push(unescape(escapeCharacter)); + } else if (style) { + const string = chunk.join(''); + chunk = []; + chunks.push(styles.length === 0 ? string : buildStyle(chalk, styles)(string)); + styles.push({inverse, styles: parseStyle(style)}); + } else if (close) { + if (styles.length === 0) { + throw new Error('Found extraneous } in Chalk template literal'); + } - // set raw-body options - opts.length = length - opts.encoding = verify - ? null - : encoding + chunks.push(buildStyle(chalk, styles)(chunk.join(''))); + chunk = []; + styles.pop(); + } else { + chunk.push(character); + } + }); - // assert charset is supported - if (opts.encoding === null && encoding !== null && !iconv.encodingExists(encoding)) { - return next(createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', { - charset: encoding.toLowerCase(), - type: 'charset.unsupported' - })) - } + chunks.push(chunk.join('')); - // read body - debug('read body') - getBody(stream, opts, function (error, body) { - if (error) { - var _error + if (styles.length > 0) { + const errMessage = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`; + throw new Error(errMessage); + } - if (error.type === 'encoding.unsupported') { - // echo back charset - _error = createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', { - charset: encoding.toLowerCase(), - type: 'charset.unsupported' - }) - } else { - // set status code on error - _error = createError(400, error) - } + return chunks.join(''); +}; - // read off entire request - stream.resume() - onFinished(req, function onfinished () { - next(createError(400, _error)) - }) - return - } - // verify - if (verify) { - try { - debug('verify body') - verify(req, res, body, encoding) - } catch (err) { - next(createError(403, err, { - body: body, - type: err.type || 'entity.verify.failed' - })) - return - } - } +/***/ }), - // parse - var str = body - try { - debug('parse body') - str = typeof body !== 'string' && encoding !== null - ? iconv.decode(body, encoding) - : body - req.body = parse(str) - } catch (err) { - next(createError(400, err, { - body: str, - type: err.type || 'entity.parse.failed' - })) - return - } +/***/ 82415: +/***/ ((module) => { - next() - }) -} +"use strict"; -/** - * Get the content stream of the request. - * - * @param {object} req - * @param {function} debug - * @param {boolean} [inflate=true] - * @return {object} - * @api private - */ -function contentstream (req, debug, inflate) { - var encoding = (req.headers['content-encoding'] || 'identity').toLowerCase() - var length = req.headers['content-length'] - var stream +const stringReplaceAll = (string, substring, replacer) => { + let index = string.indexOf(substring); + if (index === -1) { + return string; + } - debug('content-encoding "%s"', encoding) + const substringLength = substring.length; + let endIndex = 0; + let returnValue = ''; + do { + returnValue += string.substr(endIndex, index - endIndex) + substring + replacer; + endIndex = index + substringLength; + index = string.indexOf(substring, endIndex); + } while (index !== -1); - if (inflate === false && encoding !== 'identity') { - throw createError(415, 'content encoding unsupported', { - encoding: encoding, - type: 'encoding.unsupported' - }) - } + returnValue += string.substr(endIndex); + return returnValue; +}; - switch (encoding) { - case 'deflate': - stream = zlib.createInflate() - debug('inflate body') - req.pipe(stream) - break - case 'gzip': - stream = zlib.createGunzip() - debug('gunzip body') - req.pipe(stream) - break - case 'identity': - stream = req - stream.length = length - break - default: - throw createError(415, 'unsupported content encoding "' + encoding + '"', { - encoding: encoding, - type: 'encoding.unsupported' - }) - } +const stringEncaseCRLFWithFirstIndex = (string, prefix, postfix, index) => { + let endIndex = 0; + let returnValue = ''; + do { + const gotCR = string[index - 1] === '\r'; + returnValue += string.substr(endIndex, (gotCR ? index - 1 : index) - endIndex) + prefix + (gotCR ? '\r\n' : '\n') + postfix; + endIndex = index + 1; + index = string.indexOf('\n', endIndex); + } while (index !== -1); - return stream -} + returnValue += string.substr(endIndex); + return returnValue; +}; + +module.exports = { + stringReplaceAll, + stringEncaseCRLFWithFirstIndex +}; /***/ }), -/***/ 20859: +/***/ 27972: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -/*! - * body-parser - * Copyright(c) 2014 Jonathan Ong - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ +const os = __nccwpck_require__(22037); +const extractPathRegex = /\s+at.*(?:\(|\s)(.*)\)?/; +const pathRegex = /^(?:(?:(?:node|(?:internal\/[\w/]*|.*node_modules\/(?:babel-polyfill|pirates)\/.*)?\w+)\.js:\d+:\d+)|native)/; +const homeDir = typeof os.homedir === 'undefined' ? '' : os.homedir(); -/** - * Module dependencies. - * @private - */ +module.exports = (stack, options) => { + options = Object.assign({pretty: false}, options); -var bytes = __nccwpck_require__(86966) -var contentType = __nccwpck_require__(99915) -var createError = __nccwpck_require__(95193) -var debug = __nccwpck_require__(7471)('body-parser:json') -var read = __nccwpck_require__(88862) -var typeis = __nccwpck_require__(71159) + return stack.replace(/\\/g, '/') + .split('\n') + .filter(line => { + const pathMatches = line.match(extractPathRegex); + if (pathMatches === null || !pathMatches[1]) { + return true; + } -/** - * Module exports. - */ + const match = pathMatches[1]; -module.exports = json + // Electron + if ( + match.includes('.app/Contents/Resources/electron.asar') || + match.includes('.app/Contents/Resources/default_app.asar') + ) { + return false; + } -/** - * RegExp to match the first non-space in a string. - * - * Allowed whitespace is defined in RFC 7159: - * - * ws = *( - * %x20 / ; Space - * %x09 / ; Horizontal tab - * %x0A / ; Line feed or New line - * %x0D ) ; Carriage return - */ + return !pathRegex.test(match); + }) + .filter(line => line.trim() !== '') + .map(line => { + if (options.pretty) { + return line.replace(extractPathRegex, (m, p1) => m.replace(p1, p1.replace(homeDir, '~'))); + } -var FIRST_CHAR_REGEXP = /^[\x20\x09\x0a\x0d]*(.)/ // eslint-disable-line no-control-regex + return line; + }) + .join('\n'); +}; -/** - * Create a middleware to parse JSON bodies. - * - * @param {object} [options] - * @return {function} - * @public - */ -function json (options) { - var opts = options || {} +/***/ }), - var limit = typeof opts.limit !== 'number' - ? bytes.parse(opts.limit || '100kb') - : opts.limit - var inflate = opts.inflate !== false - var reviver = opts.reviver - var strict = opts.strict !== false - var type = opts.type || 'application/json' - var verify = opts.verify || false +/***/ 2101: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (verify !== false && typeof verify !== 'function') { - throw new TypeError('option verify must be function') - } +module.exports = __nccwpck_require__(16136); - // create the appropriate type checking function - var shouldParse = typeof type !== 'function' - ? typeChecker(type) - : type +/***/ }), - function parse (body) { - if (body.length === 0) { - // special-case empty json body, as it's a common client-side mistake - // TODO: maybe make this configurable or part of "strict" option - return {} - } +/***/ 66168: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (strict) { - var first = firstchar(body) +const utils = __nccwpck_require__(98911); - if (first !== '{' && first !== '[') { - debug('strict violation') - throw createStrictSyntaxError(body, first) - } - } +class Cell { + /** + * A representation of a cell within the table. + * Implementations must have `init` and `draw` methods, + * as well as `colSpan`, `rowSpan`, `desiredHeight` and `desiredWidth` properties. + * @param options + * @constructor + */ + constructor(options) { + this.setOptions(options); - try { - debug('parse json') - return JSON.parse(body, reviver) - } catch (e) { - throw normalizeJsonSyntaxError(e, { - message: e.message, - stack: e.stack - }) - } + /** + * Each cell will have it's `x` and `y` values set by the `layout-manager` prior to + * `init` being called; + * @type {Number} + */ + this.x = null; + this.y = null; } - return function jsonParser (req, res, next) { - if (req._body) { - debug('body already parsed') - next() - return + setOptions(options) { + if (['boolean', 'number', 'string'].indexOf(typeof options) !== -1) { + options = { content: '' + options }; + } + options = options || {}; + this.options = options; + let content = options.content; + if (['boolean', 'number', 'string'].indexOf(typeof content) !== -1) { + this.content = String(content); + } else if (!content) { + this.content = ''; + } else { + throw new Error('Content needs to be a primitive, got: ' + typeof content); } + this.colSpan = options.colSpan || 1; + this.rowSpan = options.rowSpan || 1; + } - req.body = req.body || {} + mergeTableOptions(tableOptions, cells) { + this.cells = cells; - // skip requests without bodies - if (!typeis.hasBody(req)) { - debug('skip empty body') - next() - return - } + let optionsChars = this.options.chars || {}; + let tableChars = tableOptions.chars; + let chars = (this.chars = {}); + CHAR_NAMES.forEach(function (name) { + setOption(optionsChars, tableChars, name, chars); + }); - debug('content-type %j', req.headers['content-type']) + this.truncate = this.options.truncate || tableOptions.truncate; - // determine if request should be parsed - if (!shouldParse(req)) { - debug('skip parsing') - next() - return - } + let style = (this.options.style = this.options.style || {}); + let tableStyle = tableOptions.style; + setOption(style, tableStyle, 'padding-left', this); + setOption(style, tableStyle, 'padding-right', this); + this.head = style.head || tableStyle.head; + this.border = style.border || tableStyle.border; - // assert charset per RFC 7159 sec 8.1 - var charset = getCharset(req) || 'utf-8' - if (charset.substr(0, 4) !== 'utf-') { - debug('invalid charset') - next(createError(415, 'unsupported charset "' + charset.toUpperCase() + '"', { - charset: charset, - type: 'charset.unsupported' - })) - return + let fixedWidth = tableOptions.colWidths[this.x]; + if (tableOptions.wordWrap && fixedWidth) { + fixedWidth -= this.paddingLeft + this.paddingRight; + if (this.colSpan) { + let i = 1; + while (i < this.colSpan) { + fixedWidth += tableOptions.colWidths[this.x + i]; + i++; + } + } + this.lines = utils.colorizeLines(utils.wordWrap(fixedWidth, this.content)); + } else { + this.lines = utils.colorizeLines(this.content.split('\n')); } - // read - read(req, res, next, parse, debug, { - encoding: charset, - inflate: inflate, - limit: limit, - verify: verify - }) + this.desiredWidth = utils.strlen(this.content) + this.paddingLeft + this.paddingRight; + this.desiredHeight = this.lines.length; } -} -/** - * Create strict violation syntax error matching native error. - * - * @param {string} str - * @param {string} char - * @return {Error} - * @private - */ + /** + * Initializes the Cells data structure. + * + * @param tableOptions - A fully populated set of tableOptions. + * In addition to the standard default values, tableOptions must have fully populated the + * `colWidths` and `rowWidths` arrays. Those arrays must have lengths equal to the number + * of columns or rows (respectively) in this table, and each array item must be a Number. + * + */ + init(tableOptions) { + let x = this.x; + let y = this.y; + this.widths = tableOptions.colWidths.slice(x, x + this.colSpan); + this.heights = tableOptions.rowHeights.slice(y, y + this.rowSpan); + this.width = this.widths.reduce(sumPlusOne, -1); + this.height = this.heights.reduce(sumPlusOne, -1); -function createStrictSyntaxError (str, char) { - var index = str.indexOf(char) - var partial = str.substring(0, index) + '#' + this.hAlign = this.options.hAlign || tableOptions.colAligns[x]; + this.vAlign = this.options.vAlign || tableOptions.rowAligns[y]; - try { - JSON.parse(partial); /* istanbul ignore next */ throw new SyntaxError('strict violation') - } catch (e) { - return normalizeJsonSyntaxError(e, { - message: e.message.replace('#', char), - stack: e.stack - }) + this.drawRight = x + this.colSpan == tableOptions.colWidths.length; } -} -/** - * Get the first non-whitespace character in a string. - * - * @param {string} str - * @return {function} - * @private - */ + /** + * Draws the given line of the cell. + * This default implementation defers to methods `drawTop`, `drawBottom`, `drawLine` and `drawEmpty`. + * @param lineNum - can be `top`, `bottom` or a numerical line number. + * @param spanningCell - will be a number if being called from a RowSpanCell, and will represent how + * many rows below it's being called from. Otherwise it's undefined. + * @returns {String} The representation of this line. + */ + draw(lineNum, spanningCell) { + if (lineNum == 'top') return this.drawTop(this.drawRight); + if (lineNum == 'bottom') return this.drawBottom(this.drawRight); + let padLen = Math.max(this.height - this.lines.length, 0); + let padTop; + switch (this.vAlign) { + case 'center': + padTop = Math.ceil(padLen / 2); + break; + case 'bottom': + padTop = padLen; + break; + default: + padTop = 0; + } + if (lineNum < padTop || lineNum >= padTop + this.lines.length) { + return this.drawEmpty(this.drawRight, spanningCell); + } + let forceTruncation = this.lines.length > this.height && lineNum + 1 >= this.height; + return this.drawLine(lineNum - padTop, this.drawRight, forceTruncation, spanningCell); + } -function firstchar (str) { - return FIRST_CHAR_REGEXP.exec(str)[1] -} + /** + * Renders the top line of the cell. + * @param drawRight - true if this method should render the right edge of the cell. + * @returns {String} + */ + drawTop(drawRight) { + let content = []; + if (this.cells) { + //TODO: cells should always exist - some tests don't fill it in though + this.widths.forEach(function (width, index) { + content.push(this._topLeftChar(index)); + content.push(utils.repeat(this.chars[this.y == 0 ? 'top' : 'mid'], width)); + }, this); + } else { + content.push(this._topLeftChar(0)); + content.push(utils.repeat(this.chars[this.y == 0 ? 'top' : 'mid'], this.width)); + } + if (drawRight) { + content.push(this.chars[this.y == 0 ? 'topRight' : 'rightMid']); + } + return this.wrapWithStyleColors('border', content.join('')); + } -/** - * Get the charset of a request. - * - * @param {object} req - * @api private - */ + _topLeftChar(offset) { + let x = this.x + offset; + let leftChar; + if (this.y == 0) { + leftChar = x == 0 ? 'topLeft' : offset == 0 ? 'topMid' : 'top'; + } else { + if (x == 0) { + leftChar = 'leftMid'; + } else { + leftChar = offset == 0 ? 'midMid' : 'bottomMid'; + if (this.cells) { + //TODO: cells should always exist - some tests don't fill it in though + let spanAbove = this.cells[this.y - 1][x] instanceof Cell.ColSpanCell; + if (spanAbove) { + leftChar = offset == 0 ? 'topMid' : 'mid'; + } + if (offset == 0) { + let i = 1; + while (this.cells[this.y][x - i] instanceof Cell.ColSpanCell) { + i++; + } + if (this.cells[this.y][x - i] instanceof Cell.RowSpanCell) { + leftChar = 'leftMid'; + } + } + } + } + } + return this.chars[leftChar]; + } -function getCharset (req) { - try { - return (contentType.parse(req).parameters.charset || '').toLowerCase() - } catch (e) { - return undefined + wrapWithStyleColors(styleProperty, content) { + if (this[styleProperty] && this[styleProperty].length) { + try { + let colors = __nccwpck_require__(41997); + for (let i = this[styleProperty].length - 1; i >= 0; i--) { + colors = colors[this[styleProperty][i]]; + } + return colors(content); + } catch (e) { + return content; + } + } else { + return content; + } } -} -/** - * Normalize a SyntaxError for JSON.parse. - * - * @param {SyntaxError} error - * @param {object} obj - * @return {SyntaxError} - */ + /** + * Renders a line of text. + * @param lineNum - Which line of text to render. This is not necessarily the line within the cell. + * There may be top-padding above the first line of text. + * @param drawRight - true if this method should render the right edge of the cell. + * @param forceTruncationSymbol - `true` if the rendered text should end with the truncation symbol even + * if the text fits. This is used when the cell is vertically truncated. If `false` the text should + * only include the truncation symbol if the text will not fit horizontally within the cell width. + * @param spanningCell - a number of if being called from a RowSpanCell. (how many rows below). otherwise undefined. + * @returns {String} + */ + drawLine(lineNum, drawRight, forceTruncationSymbol, spanningCell) { + let left = this.chars[this.x == 0 ? 'left' : 'middle']; + if (this.x && spanningCell && this.cells) { + let cellLeft = this.cells[this.y + spanningCell][this.x - 1]; + while (cellLeft instanceof ColSpanCell) { + cellLeft = this.cells[cellLeft.y][cellLeft.x - 1]; + } + if (!(cellLeft instanceof RowSpanCell)) { + left = this.chars['rightMid']; + } + } + let leftPadding = utils.repeat(' ', this.paddingLeft); + let right = drawRight ? this.chars['right'] : ''; + let rightPadding = utils.repeat(' ', this.paddingRight); + let line = this.lines[lineNum]; + let len = this.width - (this.paddingLeft + this.paddingRight); + if (forceTruncationSymbol) line += this.truncate || '…'; + let content = utils.truncate(line, len, this.truncate); + content = utils.pad(content, len, ' ', this.hAlign); + content = leftPadding + content + rightPadding; + return this.stylizeLine(left, content, right); + } -function normalizeJsonSyntaxError (error, obj) { - var keys = Object.getOwnPropertyNames(error) + stylizeLine(left, content, right) { + left = this.wrapWithStyleColors('border', left); + right = this.wrapWithStyleColors('border', right); + if (this.y === 0) { + content = this.wrapWithStyleColors('head', content); + } + return left + content + right; + } - for (var i = 0; i < keys.length; i++) { - var key = keys[i] - if (key !== 'stack' && key !== 'message') { - delete error[key] + /** + * Renders the bottom line of the cell. + * @param drawRight - true if this method should render the right edge of the cell. + * @returns {String} + */ + drawBottom(drawRight) { + let left = this.chars[this.x == 0 ? 'bottomLeft' : 'bottomMid']; + let content = utils.repeat(this.chars.bottom, this.width); + let right = drawRight ? this.chars['bottomRight'] : ''; + return this.wrapWithStyleColors('border', left + content + right); + } + + /** + * Renders a blank line of text within the cell. Used for top and/or bottom padding. + * @param drawRight - true if this method should render the right edge of the cell. + * @param spanningCell - a number of if being called from a RowSpanCell. (how many rows below). otherwise undefined. + * @returns {String} + */ + drawEmpty(drawRight, spanningCell) { + let left = this.chars[this.x == 0 ? 'left' : 'middle']; + if (this.x && spanningCell && this.cells) { + let cellLeft = this.cells[this.y + spanningCell][this.x - 1]; + while (cellLeft instanceof ColSpanCell) { + cellLeft = this.cells[cellLeft.y][cellLeft.x - 1]; + } + if (!(cellLeft instanceof RowSpanCell)) { + left = this.chars['rightMid']; + } } + let right = drawRight ? this.chars['right'] : ''; + let content = utils.repeat(' ', this.width); + return this.stylizeLine(left, content, right); } - - // replace stack before message for Node.js 0.10 and below - error.stack = obj.stack.replace(error.message, obj.message) - error.message = obj.message - - return error } -/** - * Get the simple type checker. - * - * @param {string} type - * @return {function} - */ +class ColSpanCell { + /** + * A Cell that doesn't do anything. It just draws empty lines. + * Used as a placeholder in column spanning. + * @constructor + */ + constructor() {} -function typeChecker (type) { - return function checkType (req) { - return Boolean(typeis(req, type)) + draw() { + return ''; } -} - - -/***/ }), - -/***/ 49609: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -/*! - * body-parser - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ - - - -/** - * Module dependencies. - */ - -var bytes = __nccwpck_require__(86966) -var debug = __nccwpck_require__(7471)('body-parser:raw') -var read = __nccwpck_require__(88862) -var typeis = __nccwpck_require__(71159) - -/** - * Module exports. - */ - -module.exports = raw - -/** - * Create a middleware to parse raw bodies. - * - * @param {object} [options] - * @return {function} - * @api public - */ -function raw (options) { - var opts = options || {} + init() {} - var inflate = opts.inflate !== false - var limit = typeof opts.limit !== 'number' - ? bytes.parse(opts.limit || '100kb') - : opts.limit - var type = opts.type || 'application/octet-stream' - var verify = opts.verify || false + mergeTableOptions() {} +} - if (verify !== false && typeof verify !== 'function') { - throw new TypeError('option verify must be function') +class RowSpanCell { + /** + * A placeholder Cell for a Cell that spans multiple rows. + * It delegates rendering to the original cell, but adds the appropriate offset. + * @param originalCell + * @constructor + */ + constructor(originalCell) { + this.originalCell = originalCell; } - // create the appropriate type checking function - var shouldParse = typeof type !== 'function' - ? typeChecker(type) - : type - - function parse (buf) { - return buf + init(tableOptions) { + let y = this.y; + let originalY = this.originalCell.y; + this.cellOffset = y - originalY; + this.offset = findDimension(tableOptions.rowHeights, originalY, this.cellOffset); } - return function rawParser (req, res, next) { - if (req._body) { - debug('body already parsed') - next() - return + draw(lineNum) { + if (lineNum == 'top') { + return this.originalCell.draw(this.offset, this.cellOffset); } - - req.body = req.body || {} - - // skip requests without bodies - if (!typeis.hasBody(req)) { - debug('skip empty body') - next() - return + if (lineNum == 'bottom') { + return this.originalCell.draw('bottom'); } + return this.originalCell.draw(this.offset + 1 + lineNum); + } - debug('content-type %j', req.headers['content-type']) - - // determine if request should be parsed - if (!shouldParse(req)) { - debug('skip parsing') - next() - return - } + mergeTableOptions() {} +} - // read - read(req, res, next, parse, debug, { - encoding: null, - inflate: inflate, - limit: limit, - verify: verify - }) +// HELPER FUNCTIONS +function setOption(objA, objB, nameB, targetObj) { + let nameA = nameB.split('-'); + if (nameA.length > 1) { + nameA[1] = nameA[1].charAt(0).toUpperCase() + nameA[1].substr(1); + nameA = nameA.join(''); + targetObj[nameA] = objA[nameA] || objA[nameB] || objB[nameA] || objB[nameB]; + } else { + targetObj[nameB] = objA[nameB] || objB[nameB]; } } -/** - * Get the simple type checker. - * - * @param {string} type - * @return {function} - */ - -function typeChecker (type) { - return function checkType (req) { - return Boolean(typeis(req, type)) +function findDimension(dimensionTable, startingIndex, span) { + let ret = dimensionTable[startingIndex]; + for (let i = 1; i < span; i++) { + ret += 1 + dimensionTable[startingIndex + i]; } + return ret; } +function sumPlusOne(a, b) { + return a + b + 1; +} -/***/ }), - -/***/ 26382: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -/*! - * body-parser - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ +let CHAR_NAMES = [ + 'top', + 'top-mid', + 'top-left', + 'top-right', + 'bottom', + 'bottom-mid', + 'bottom-left', + 'bottom-right', + 'left', + 'left-mid', + 'mid', + 'mid-mid', + 'right', + 'right-mid', + 'middle', +]; +module.exports = Cell; +module.exports.ColSpanCell = ColSpanCell; +module.exports.RowSpanCell = RowSpanCell; +/***/ }), -/** - * Module dependencies. - */ +/***/ 93875: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var bytes = __nccwpck_require__(86966) -var contentType = __nccwpck_require__(99915) -var debug = __nccwpck_require__(7471)('body-parser:text') -var read = __nccwpck_require__(88862) -var typeis = __nccwpck_require__(71159) +const Cell = __nccwpck_require__(66168); +const { ColSpanCell, RowSpanCell } = Cell; -/** - * Module exports. - */ +(function () { + function layoutTable(table) { + table.forEach(function (row, rowIndex) { + let prevCell = null; + row.forEach(function (cell, columnIndex) { + cell.y = rowIndex; + cell.x = prevCell ? prevCell.x + 1 : columnIndex; + for (let y = rowIndex; y >= 0; y--) { + let row2 = table[y]; + let xMax = y === rowIndex ? columnIndex : row2.length; + for (let x = 0; x < xMax; x++) { + let cell2 = row2[x]; + while (cellsConflict(cell, cell2)) { + cell.x++; + } + } + prevCell = cell; + } + }); + }); + } -module.exports = text + function maxWidth(table) { + let mw = 0; + table.forEach(function (row) { + row.forEach(function (cell) { + mw = Math.max(mw, cell.x + (cell.colSpan || 1)); + }); + }); + return mw; + } -/** - * Create a middleware to parse text bodies. - * - * @param {object} [options] - * @return {function} - * @api public - */ + function maxHeight(table) { + return table.length; + } -function text (options) { - var opts = options || {} + function cellsConflict(cell1, cell2) { + let yMin1 = cell1.y; + let yMax1 = cell1.y - 1 + (cell1.rowSpan || 1); + let yMin2 = cell2.y; + let yMax2 = cell2.y - 1 + (cell2.rowSpan || 1); + let yConflict = !(yMin1 > yMax2 || yMin2 > yMax1); - var defaultCharset = opts.defaultCharset || 'utf-8' - var inflate = opts.inflate !== false - var limit = typeof opts.limit !== 'number' - ? bytes.parse(opts.limit || '100kb') - : opts.limit - var type = opts.type || 'text/plain' - var verify = opts.verify || false + let xMin1 = cell1.x; + let xMax1 = cell1.x - 1 + (cell1.colSpan || 1); + let xMin2 = cell2.x; + let xMax2 = cell2.x - 1 + (cell2.colSpan || 1); + let xConflict = !(xMin1 > xMax2 || xMin2 > xMax1); - if (verify !== false && typeof verify !== 'function') { - throw new TypeError('option verify must be function') + return yConflict && xConflict; } - // create the appropriate type checking function - var shouldParse = typeof type !== 'function' - ? typeChecker(type) - : type - - function parse (buf) { - return buf + function conflictExists(rows, x, y) { + let i_max = Math.min(rows.length - 1, y); + let cell = { x: x, y: y }; + for (let i = 0; i <= i_max; i++) { + let row = rows[i]; + for (let j = 0; j < row.length; j++) { + if (cellsConflict(cell, row[j])) { + return true; + } + } + } + return false; } - return function textParser (req, res, next) { - if (req._body) { - debug('body already parsed') - next() - return + function allBlank(rows, y, xMin, xMax) { + for (let x = xMin; x < xMax; x++) { + if (conflictExists(rows, x, y)) { + return false; + } } + return true; + } - req.body = req.body || {} + function addRowSpanCells(table) { + table.forEach(function (row, rowIndex) { + row.forEach(function (cell) { + for (let i = 1; i < cell.rowSpan; i++) { + let rowSpanCell = new RowSpanCell(cell); + rowSpanCell.x = cell.x; + rowSpanCell.y = cell.y + i; + rowSpanCell.colSpan = cell.colSpan; + insertCell(rowSpanCell, table[rowIndex + i]); + } + }); + }); + } - // skip requests without bodies - if (!typeis.hasBody(req)) { - debug('skip empty body') - next() - return + function addColSpanCells(cellRows) { + for (let rowIndex = cellRows.length - 1; rowIndex >= 0; rowIndex--) { + let cellColumns = cellRows[rowIndex]; + for (let columnIndex = 0; columnIndex < cellColumns.length; columnIndex++) { + let cell = cellColumns[columnIndex]; + for (let k = 1; k < cell.colSpan; k++) { + let colSpanCell = new ColSpanCell(); + colSpanCell.x = cell.x + k; + colSpanCell.y = cell.y; + cellColumns.splice(columnIndex + 1, 0, colSpanCell); + } + } } + } - debug('content-type %j', req.headers['content-type']) - - // determine if request should be parsed - if (!shouldParse(req)) { - debug('skip parsing') - next() - return + function insertCell(cell, row) { + let x = 0; + while (x < row.length && row[x].x < cell.x) { + x++; } - - // get charset - var charset = getCharset(req) || defaultCharset - - // read - read(req, res, next, parse, debug, { - encoding: charset, - inflate: inflate, - limit: limit, - verify: verify - }) + row.splice(x, 0, cell); } -} -/** - * Get the charset of a request. - * - * @param {object} req - * @api private - */ + function fillInTable(table) { + let h_max = maxHeight(table); + let w_max = maxWidth(table); + for (let y = 0; y < h_max; y++) { + for (let x = 0; x < w_max; x++) { + if (!conflictExists(table, x, y)) { + let opts = { x: x, y: y, colSpan: 1, rowSpan: 1 }; + x++; + while (x < w_max && !conflictExists(table, x, y)) { + opts.colSpan++; + x++; + } + let y2 = y + 1; + while (y2 < h_max && allBlank(table, y2, opts.x, opts.x + opts.colSpan)) { + opts.rowSpan++; + y2++; + } -function getCharset (req) { - try { - return (contentType.parse(req).parameters.charset || '').toLowerCase() - } catch (e) { - return undefined + let cell = new Cell(opts); + cell.x = opts.x; + cell.y = opts.y; + insertCell(cell, table[y]); + } + } + } } -} - -/** - * Get the simple type checker. - * - * @param {string} type - * @return {function} - */ -function typeChecker (type) { - return function checkType (req) { - return Boolean(typeis(req, type)) + function generateCells(rows) { + return rows.map(function (row) { + if (!Array.isArray(row)) { + let key = Object.keys(row)[0]; + row = row[key]; + if (Array.isArray(row)) { + row = row.slice(); + row.unshift(key); + } else { + row = [key, row]; + } + } + return row.map(function (cell) { + return new Cell(cell); + }); + }); } -} - - -/***/ }), - -/***/ 76100: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; -/*! - * body-parser - * Copyright(c) 2014 Jonathan Ong - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ + function makeTableLayout(rows) { + let cellRows = generateCells(rows); + layoutTable(cellRows); + fillInTable(cellRows); + addRowSpanCells(cellRows); + addColSpanCells(cellRows); + return cellRows; + } + module.exports = { + makeTableLayout: makeTableLayout, + layoutTable: layoutTable, + addRowSpanCells: addRowSpanCells, + maxWidth: maxWidth, + fillInTable: fillInTable, + computeWidths: makeComputeWidths('colSpan', 'desiredWidth', 'x', 1), + computeHeights: makeComputeWidths('rowSpan', 'desiredHeight', 'y', 1), + }; +})(); +function makeComputeWidths(colSpan, desiredWidth, x, forcedMin) { + return function (vals, table) { + let result = []; + let spanners = []; + table.forEach(function (row) { + row.forEach(function (cell) { + if ((cell[colSpan] || 1) > 1) { + spanners.push(cell); + } else { + result[cell[x]] = Math.max(result[cell[x]] || 0, cell[desiredWidth] || 0, forcedMin); + } + }); + }); -/** - * Module dependencies. - * @private - */ + vals.forEach(function (val, index) { + if (typeof val === 'number') { + result[index] = val; + } + }); -var bytes = __nccwpck_require__(86966) -var contentType = __nccwpck_require__(99915) -var createError = __nccwpck_require__(95193) -var debug = __nccwpck_require__(7471)('body-parser:urlencoded') -var deprecate = __nccwpck_require__(18883)('body-parser') -var read = __nccwpck_require__(88862) -var typeis = __nccwpck_require__(71159) + //spanners.forEach(function(cell){ + for (let k = spanners.length - 1; k >= 0; k--) { + let cell = spanners[k]; + let span = cell[colSpan]; + let col = cell[x]; + let existingWidth = result[col]; + let editableCols = typeof vals[col] === 'number' ? 0 : 1; + for (let i = 1; i < span; i++) { + existingWidth += 1 + result[col + i]; + if (typeof vals[col + i] !== 'number') { + editableCols++; + } + } + if (cell[desiredWidth] > existingWidth) { + let i = 0; + while (editableCols > 0 && cell[desiredWidth] > existingWidth) { + if (typeof vals[col + i] !== 'number') { + let dif = Math.round((cell[desiredWidth] - existingWidth) / editableCols); + existingWidth += dif; + result[col + i] += dif; + editableCols--; + } + i++; + } + } + } -/** - * Module exports. - */ + Object.assign(vals, result); + for (let j = 0; j < vals.length; j++) { + vals[j] = Math.max(forcedMin, vals[j] || 0); + } + }; +} -module.exports = urlencoded -/** - * Cache of parser modules. - */ +/***/ }), -var parsers = Object.create(null) +/***/ 16136: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * Create a middleware to parse urlencoded bodies. - * - * @param {object} [options] - * @return {function} - * @public - */ +const utils = __nccwpck_require__(98911); +const tableLayout = __nccwpck_require__(93875); -function urlencoded (options) { - var opts = options || {} +class Table extends Array { + constructor(options) { + super(); - // notice because option default will flip in next major - if (opts.extended === undefined) { - deprecate('undefined extended: provide extended option') + this.options = utils.mergeOptions(options); } - var extended = opts.extended !== false - var inflate = opts.inflate !== false - var limit = typeof opts.limit !== 'number' - ? bytes.parse(opts.limit || '100kb') - : opts.limit - var type = opts.type || 'application/x-www-form-urlencoded' - var verify = opts.verify || false + toString() { + let array = this; + let headersPresent = this.options.head && this.options.head.length; + if (headersPresent) { + array = [this.options.head]; + if (this.length) { + array.push.apply(array, this); + } + } else { + this.options.style.head = []; + } - if (verify !== false && typeof verify !== 'function') { - throw new TypeError('option verify must be function') - } + let cells = tableLayout.makeTableLayout(array); - // create the appropriate query parser - var queryparse = extended - ? extendedparser(opts) - : simpleparser(opts) + cells.forEach(function (row) { + row.forEach(function (cell) { + cell.mergeTableOptions(this.options, cells); + }, this); + }, this); - // create the appropriate type checking function - var shouldParse = typeof type !== 'function' - ? typeChecker(type) - : type + tableLayout.computeWidths(this.options.colWidths, cells); + tableLayout.computeHeights(this.options.rowHeights, cells); - function parse (body) { - return body.length - ? queryparse(body) - : {} - } + cells.forEach(function (row) { + row.forEach(function (cell) { + cell.init(this.options); + }, this); + }, this); - return function urlencodedParser (req, res, next) { - if (req._body) { - debug('body already parsed') - next() - return - } + let result = []; - req.body = req.body || {} + for (let rowIndex = 0; rowIndex < cells.length; rowIndex++) { + let row = cells[rowIndex]; + let heightOfRow = this.options.rowHeights[rowIndex]; - // skip requests without bodies - if (!typeis.hasBody(req)) { - debug('skip empty body') - next() - return - } + if (rowIndex === 0 || !this.options.style.compact || (rowIndex == 1 && headersPresent)) { + doDraw(row, 'top', result); + } - debug('content-type %j', req.headers['content-type']) + for (let lineNum = 0; lineNum < heightOfRow; lineNum++) { + doDraw(row, lineNum, result); + } - // determine if request should be parsed - if (!shouldParse(req)) { - debug('skip parsing') - next() - return + if (rowIndex + 1 == cells.length) { + doDraw(row, 'bottom', result); + } } - // assert charset - var charset = getCharset(req) || 'utf-8' - if (charset !== 'utf-8') { - debug('invalid charset') - next(createError(415, 'unsupported charset "' + charset.toUpperCase() + '"', { - charset: charset, - type: 'charset.unsupported' - })) - return - } + return result.join('\n'); + } - // read - read(req, res, next, parse, debug, { - debug: debug, - encoding: charset, - inflate: inflate, - limit: limit, - verify: verify - }) + get width() { + let str = this.toString().split('\n'); + return str[0].length; } } -/** - * Get the extended query parser. - * - * @param {object} options - */ - -function extendedparser (options) { - var parameterLimit = options.parameterLimit !== undefined - ? options.parameterLimit - : 1000 - var parse = parser('qs') +function doDraw(row, lineNum, result) { + let line = []; + row.forEach(function (cell) { + line.push(cell.draw(lineNum)); + }); + let str = line.join(''); + if (str.length) result.push(str); +} - if (isNaN(parameterLimit) || parameterLimit < 1) { - throw new TypeError('option parameterLimit must be a positive number') - } +module.exports = Table; - if (isFinite(parameterLimit)) { - parameterLimit = parameterLimit | 0 - } - return function queryparse (body) { - var paramCount = parameterCount(body, parameterLimit) +/***/ }), - if (paramCount === undefined) { - debug('too many parameters') - throw createError(413, 'too many parameters', { - type: 'parameters.too.many' - }) - } +/***/ 98911: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - var arrayLimit = Math.max(100, paramCount) +const stringWidth = __nccwpck_require__(42577); - debug('parse extended urlencoding') - return parse(body, { - allowPrototypes: true, - arrayLimit: arrayLimit, - depth: Infinity, - parameterLimit: parameterLimit - }) - } +function codeRegex(capture) { + return capture ? /\u001b\[((?:\d*;){0,5}\d*)m/g : /\u001b\[(?:\d*;){0,5}\d*m/g; } -/** - * Get the charset of a request. - * - * @param {object} req - * @api private - */ - -function getCharset (req) { - try { - return (contentType.parse(req).parameters.charset || '').toLowerCase() - } catch (e) { - return undefined - } +function strlen(str) { + let code = codeRegex(); + let stripped = ('' + str).replace(code, ''); + let split = stripped.split('\n'); + return split.reduce(function (memo, s) { + return stringWidth(s) > memo ? stringWidth(s) : memo; + }, 0); } -/** - * Count the number of parameters, stopping once limit reached - * - * @param {string} body - * @param {number} limit - * @api private - */ - -function parameterCount (body, limit) { - var count = 0 - var index = 0 - - while ((index = body.indexOf('&', index)) !== -1) { - count++ - index++ +function repeat(str, times) { + return Array(times + 1).join(str); +} - if (count === limit) { - return undefined +function pad(str, len, pad, dir) { + let length = strlen(str); + if (len + 1 >= length) { + let padlen = len - length; + switch (dir) { + case 'right': { + str = repeat(pad, padlen) + str; + break; + } + case 'center': { + let right = Math.ceil(padlen / 2); + let left = padlen - right; + str = repeat(pad, left) + str + repeat(pad, right); + break; + } + default: { + str = str + repeat(pad, padlen); + break; + } } } - - return count + return str; } -/** - * Get parser for module name dynamically. - * - * @param {string} name - * @return {function} - * @api private - */ - -function parser (name) { - var mod = parsers[name] - - if (mod !== undefined) { - return mod.parse - } - - // this uses a switch for static require analysis - switch (name) { - case 'qs': - mod = __nccwpck_require__(22760) - break - case 'querystring': - mod = __nccwpck_require__(63477) - break - } - - // store to prevent invoking require() - parsers[name] = mod +let codeCache = {}; - return mod.parse +function addToCodeCache(name, on, off) { + on = '\u001b[' + on + 'm'; + off = '\u001b[' + off + 'm'; + codeCache[on] = { set: name, to: true }; + codeCache[off] = { set: name, to: false }; + codeCache[name] = { on: on, off: off }; } -/** - * Get the simple query parser. - * - * @param {object} options - */ - -function simpleparser (options) { - var parameterLimit = options.parameterLimit !== undefined - ? options.parameterLimit - : 1000 - var parse = parser('querystring') +//https://github.com/Marak/colors.js/blob/master/lib/styles.js +addToCodeCache('bold', 1, 22); +addToCodeCache('italics', 3, 23); +addToCodeCache('underline', 4, 24); +addToCodeCache('inverse', 7, 27); +addToCodeCache('strikethrough', 9, 29); - if (isNaN(parameterLimit) || parameterLimit < 1) { - throw new TypeError('option parameterLimit must be a positive number') +function updateState(state, controlChars) { + let controlCode = controlChars[1] ? parseInt(controlChars[1].split(';')[0]) : 0; + if ((controlCode >= 30 && controlCode <= 39) || (controlCode >= 90 && controlCode <= 97)) { + state.lastForegroundAdded = controlChars[0]; + return; } - - if (isFinite(parameterLimit)) { - parameterLimit = parameterLimit | 0 + if ((controlCode >= 40 && controlCode <= 49) || (controlCode >= 100 && controlCode <= 107)) { + state.lastBackgroundAdded = controlChars[0]; + return; } - - return function queryparse (body) { - var paramCount = parameterCount(body, parameterLimit) - - if (paramCount === undefined) { - debug('too many parameters') - throw createError(413, 'too many parameters', { - type: 'parameters.too.many' - }) + if (controlCode === 0) { + for (let i in state) { + /* istanbul ignore else */ + if (Object.prototype.hasOwnProperty.call(state, i)) { + delete state[i]; + } } - - debug('parse urlencoding') - return parse(body, undefined, undefined, { maxKeys: parameterLimit }) + return; + } + let info = codeCache[controlChars[0]]; + if (info) { + state[info.set] = info.to; } } -/** - * Get the simple type checker. - * - * @param {string} type - * @return {function} - */ - -function typeChecker (type) { - return function checkType (req) { - return Boolean(typeis(req, type)) +function readState(line) { + let code = codeRegex(true); + let controlChars = code.exec(line); + let state = {}; + while (controlChars !== null) { + updateState(state, controlChars); + controlChars = code.exec(line); } + return state; } +function unwindState(state, ret) { + let lastBackgroundAdded = state.lastBackgroundAdded; + let lastForegroundAdded = state.lastForegroundAdded; -/***/ }), + delete state.lastBackgroundAdded; + delete state.lastForegroundAdded; -/***/ 15377: -/***/ ((module, exports, __nccwpck_require__) => { + Object.keys(state).forEach(function (key) { + if (state[key]) { + ret += codeCache[key].off; + } + }); -/** - * This is the web browser implementation of `debug()`. - * - * Expose `debug()` as the module. - */ + if (lastBackgroundAdded && lastBackgroundAdded != '\u001b[49m') { + ret += '\u001b[49m'; + } + if (lastForegroundAdded && lastForegroundAdded != '\u001b[39m') { + ret += '\u001b[39m'; + } -exports = module.exports = __nccwpck_require__(22552); -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(); + return ret; +} -/** - * Colors. - */ +function rewindState(state, ret) { + let lastBackgroundAdded = state.lastBackgroundAdded; + let lastForegroundAdded = state.lastForegroundAdded; -exports.colors = [ - 'lightseagreen', - 'forestgreen', - 'goldenrod', - 'dodgerblue', - 'darkorchid', - 'crimson' -]; + delete state.lastBackgroundAdded; + delete state.lastForegroundAdded; -/** - * 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 - */ + Object.keys(state).forEach(function (key) { + if (state[key]) { + ret = codeCache[key].on + ret; + } + }); -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; + if (lastBackgroundAdded && lastBackgroundAdded != '\u001b[49m') { + ret = lastBackgroundAdded + ret; + } + if (lastForegroundAdded && lastForegroundAdded != '\u001b[39m') { + ret = lastForegroundAdded + ret; } - // 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+)/)); + return ret; } -/** - * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. - */ - -exports.formatters.j = function(v) { - try { - return JSON.stringify(v); - } catch (err) { - return '[UnexpectedJSONParseError]: ' + err.message; +function truncateWidth(str, desiredLength) { + if (str.length === strlen(str)) { + return str.substr(0, desiredLength); } -}; - -/** - * Colorize log arguments if enabled. - * - * @api public - */ - -function formatArgs(args) { - var useColors = this.useColors; + while (strlen(str) > desiredLength) { + str = str.slice(0, -1); + } - args[0] = (useColors ? '%c' : '') - + this.namespace - + (useColors ? ' %c' : ' ') - + args[0] - + (useColors ? '%c ' : ' ') - + '+' + exports.humanize(this.diff); + return str; +} - if (!useColors) return; +function truncateWidthWithAnsi(str, desiredLength) { + let code = codeRegex(true); + let split = str.split(codeRegex()); + let splitIndex = 0; + let retLen = 0; + let ret = ''; + let myArray; + let state = {}; - var c = 'color: ' + this.color; - args.splice(1, 0, c, 'color: inherit') + while (retLen < desiredLength) { + myArray = code.exec(str); + let toAdd = split[splitIndex]; + splitIndex++; + if (retLen + strlen(toAdd) > desiredLength) { + toAdd = truncateWidth(toAdd, desiredLength - retLen); + } + ret += toAdd; + retLen += strlen(toAdd); - // 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 (retLen < desiredLength) { + if (!myArray) { + break; + } // full-width chars may cause a whitespace which cannot be filled + ret += myArray[0]; + updateState(state, myArray); } - }); + } - args.splice(lastC, 0, c); + return unwindState(state, ret); } -/** - * Invokes `console.log()` when available. - * No-op when `console.log` is not a "function". - * - * @api public - */ +function truncate(str, desiredLength, truncateChar) { + truncateChar = truncateChar || '…'; + let lengthOfStr = strlen(str); + if (lengthOfStr <= desiredLength) { + return str; + } + desiredLength -= strlen(truncateChar); -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); + let ret = truncateWidthWithAnsi(str, desiredLength); + + return ret + truncateChar; } -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ +function defaultOptions() { + return { + chars: { + top: '─', + 'top-mid': '┬', + 'top-left': '┌', + 'top-right': '┐', + bottom: '─', + 'bottom-mid': '┴', + 'bottom-left': '└', + 'bottom-right': '┘', + left: '│', + 'left-mid': '├', + mid: '─', + 'mid-mid': '┼', + right: '│', + 'right-mid': '┤', + middle: '│', + }, + truncate: '…', + colWidths: [], + rowHeights: [], + colAligns: [], + rowAligns: [], + style: { + 'padding-left': 1, + 'padding-right': 1, + head: ['red'], + border: ['grey'], + compact: false, + }, + head: [], + }; +} -function save(namespaces) { - try { - if (null == namespaces) { - exports.storage.removeItem('debug'); +function mergeOptions(options, defaults) { + options = options || {}; + defaults = defaults || defaultOptions(); + let ret = Object.assign({}, defaults, options); + ret.chars = Object.assign({}, defaults.chars, options.chars); + ret.style = Object.assign({}, defaults.style, options.style); + return ret; +} + +function wordWrap(maxLength, input) { + let lines = []; + let split = input.split(/(\s+)/g); + let line = []; + let lineLength = 0; + let whitespace; + for (let i = 0; i < split.length; i += 2) { + let word = split[i]; + let newLength = lineLength + strlen(word); + if (lineLength > 0 && whitespace) { + newLength += whitespace.length; + } + if (newLength > maxLength) { + if (lineLength !== 0) { + lines.push(line.join('')); + } + line = [word]; + lineLength = strlen(word); } else { - exports.storage.debug = namespaces; + line.push(whitespace || '', word); + lineLength = newLength; } - } catch(e) {} + whitespace = split[i + 1]; + } + if (lineLength) { + lines.push(line.join('')); + } + return lines; } -/** - * 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; +function multiLineWordWrap(maxLength, input) { + let output = []; + input = input.split('\n'); + for (let i = 0; i < input.length; i++) { + output.push.apply(output, wordWrap(maxLength, input[i])); } + return output; +} - return r; +function colorizeLines(input) { + let state = {}; + let output = []; + for (let i = 0; i < input.length; i++) { + let line = rewindState(state, input[i]); + state = readState(line); + let temp = Object.assign({}, state); + output.push(unwindState(temp, line)); + } + return output; } -/** - * Enable namespaces listed in `localStorage.debug` initially. - */ +module.exports = { + strlen: strlen, + repeat: repeat, + pad: pad, + truncate: truncate, + mergeOptions: mergeOptions, + wordWrap: multiLineWordWrap, + colorizeLines: colorizeLines, +}; -exports.enable(load()); -/** - * Localstorage attempts to return the localstorage. +/***/ }), + +/***/ 48481: +/***/ ((module) => { + +/* + * Copyright 2001-2010 Georges Menie (www.menie.org) + * Copyright 2010 Salvatore Sanfilippo (adapted to Redis coding style) + * Copyright 2015 Zihua Li (http://zihua.li) (ported to JavaScript) + * Copyright 2016 Mike Diarmid (http://github.com/salakar) (re-write for performance, ~700% perf inc) + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: * - * This is necessary because safari throws - * when a user disables cookies/localstorage - * and you attempt to access it. + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the University of California, Berkeley nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. * - * @return {LocalStorage} - * @api private + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -function localstorage() { - try { - return window.localStorage; - } catch (e) {} -} +/* CRC16 implementation according to CCITT standards. + * + * Note by @antirez: this is actually the XMODEM CRC 16 algorithm, using the + * following parameters: + * + * Name : "XMODEM", also known as "ZMODEM", "CRC-16/ACORN" + * Width : 16 bit + * Poly : 1021 (That is actually x^16 + x^12 + x^5 + 1) + * Initialization : 0000 + * Reflect Input byte : False + * Reflect Output CRC : False + * Xor constant to output CRC : 0000 + * Output for "123456789" : 31C3 + */ +var lookup = [ + 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7, + 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef, + 0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6, + 0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de, + 0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485, + 0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d, + 0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4, + 0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc, + 0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823, + 0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b, + 0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12, + 0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a, + 0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41, + 0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49, + 0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70, + 0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78, + 0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f, + 0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067, + 0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e, + 0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256, + 0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d, + 0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, + 0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c, + 0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634, + 0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab, + 0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3, + 0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a, + 0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92, + 0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9, + 0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1, + 0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8, + 0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0 +]; -/***/ }), +/** + * Convert a string to a UTF8 array - faster than via buffer + * @param str + * @returns {Array} + */ +var toUTF8Array = function toUTF8Array(str) { + var char; + var i = 0; + var p = 0; + var utf8 = []; + var len = str.length; -/***/ 22552: -/***/ ((module, exports, __nccwpck_require__) => { + for (; i < len; i++) { + char = str.charCodeAt(i); + if (char < 128) { + utf8[p++] = char; + } else if (char < 2048) { + utf8[p++] = (char >> 6) | 192; + utf8[p++] = (char & 63) | 128; + } else if ( + ((char & 0xFC00) === 0xD800) && (i + 1) < str.length && + ((str.charCodeAt(i + 1) & 0xFC00) === 0xDC00)) { + char = 0x10000 + ((char & 0x03FF) << 10) + (str.charCodeAt(++i) & 0x03FF); + utf8[p++] = (char >> 18) | 240; + utf8[p++] = ((char >> 12) & 63) | 128; + utf8[p++] = ((char >> 6) & 63) | 128; + utf8[p++] = (char & 63) | 128; + } else { + utf8[p++] = (char >> 12) | 224; + utf8[p++] = ((char >> 6) & 63) | 128; + utf8[p++] = (char & 63) | 128; + } + } + return utf8; +}; /** - * This is the common logic for both the Node.js and web browser - * implementations of `debug()`. - * - * Expose `debug()` as the module. + * Convert a string into a redis slot hash. + * @param str + * @returns {number} */ +var generate = module.exports = function generate(str) { + var char; + var i = 0; + var start = -1; + var result = 0; + var resultHash = 0; + var utf8 = typeof str === 'string' ? toUTF8Array(str) : str; + var len = utf8.length; -exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; -exports.coerce = coerce; -exports.disable = disable; -exports.enable = enable; -exports.enabled = enabled; -exports.humanize = __nccwpck_require__(73233); + while (i < len) { + char = utf8[i++]; + if (start === -1) { + if (char === 0x7B) { + start = i; + } + } else if (char !== 0x7D) { + resultHash = lookup[(char ^ (resultHash >> 8)) & 0xFF] ^ (resultHash << 8); + } else if (i - 1 !== start) { + return resultHash & 0x3FFF; + } -/** - * The currently active debug mode names, and names to skip. - */ + result = lookup[(char ^ (result >> 8)) & 0xFF] ^ (result << 8); + } -exports.names = []; -exports.skips = []; + return result & 0x3FFF; +}; /** - * 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". + * Convert an array of multiple strings into a redis slot hash. + * Returns -1 if one of the keys is not for the same slot as the others + * @param keys + * @returns {number} */ +module.exports.generateMulti = function generateMulti(keys) { + var i = 1; + var len = keys.length; + var base = generate(keys[0]); -exports.formatters = {}; + while (i < len) { + if (generate(keys[i++]) !== base) return -1; + } -/** - * Previous log timestamp. - */ + return base; +}; -var prevTime; -/** - * Select a color. - * @param {String} namespace - * @return {Number} - * @api private - */ +/***/ }), -function selectColor(namespace) { - var hash = 0, i; +/***/ 97391: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - for (i in namespace) { - hash = ((hash << 5) - hash) + namespace.charCodeAt(i); - hash |= 0; // Convert to 32bit integer - } +/* MIT license */ +/* eslint-disable no-mixed-operators */ +const cssKeywords = __nccwpck_require__(78510); - return exports.colors[Math.abs(hash) % exports.colors.length]; +// NOTE: conversions should only return primitive values (i.e. arrays, or +// values that give correct `typeof` results). +// do not use box values types (i.e. Number(), String(), etc.) + +const reverseKeywords = {}; +for (const key of Object.keys(cssKeywords)) { + reverseKeywords[cssKeywords[key]] = key; } -/** - * Create a debugger with the given `namespace`. - * - * @param {String} namespace - * @return {Function} - * @api public - */ +const convert = { + rgb: {channels: 3, labels: 'rgb'}, + hsl: {channels: 3, labels: 'hsl'}, + hsv: {channels: 3, labels: 'hsv'}, + hwb: {channels: 3, labels: 'hwb'}, + cmyk: {channels: 4, labels: 'cmyk'}, + xyz: {channels: 3, labels: 'xyz'}, + lab: {channels: 3, labels: 'lab'}, + lch: {channels: 3, labels: 'lch'}, + hex: {channels: 1, labels: ['hex']}, + keyword: {channels: 1, labels: ['keyword']}, + ansi16: {channels: 1, labels: ['ansi16']}, + ansi256: {channels: 1, labels: ['ansi256']}, + hcg: {channels: 3, labels: ['h', 'c', 'g']}, + apple: {channels: 3, labels: ['r16', 'g16', 'b16']}, + gray: {channels: 1, labels: ['gray']} +}; -function createDebug(namespace) { +module.exports = convert; - function debug() { - // disabled? - if (!debug.enabled) return; +// Hide .channels and .labels properties +for (const model of Object.keys(convert)) { + if (!('channels' in convert[model])) { + throw new Error('missing channels property: ' + model); + } - var self = debug; + if (!('labels' in convert[model])) { + throw new Error('missing channel labels property: ' + model); + } - // set `diff` timestamp - var curr = +new Date(); - var ms = curr - (prevTime || curr); - self.diff = ms; - self.prev = prevTime; - self.curr = curr; - prevTime = curr; + if (convert[model].labels.length !== convert[model].channels) { + throw new Error('channel and label counts mismatch: ' + model); + } - // 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 {channels, labels} = convert[model]; + delete convert[model].channels; + delete convert[model].labels; + Object.defineProperty(convert[model], 'channels', {value: channels}); + Object.defineProperty(convert[model], 'labels', {value: labels}); +} - args[0] = exports.coerce(args[0]); +convert.rgb.hsl = function (rgb) { + const r = rgb[0] / 255; + const g = rgb[1] / 255; + const b = rgb[2] / 255; + const min = Math.min(r, g, b); + const max = Math.max(r, g, b); + const delta = max - min; + let h; + let s; - if ('string' !== typeof args[0]) { - // anything else let's inspect with %O - args.unshift('%O'); - } + if (max === min) { + h = 0; + } else if (r === max) { + h = (g - b) / delta; + } else if (g === max) { + h = 2 + (b - r) / delta; + } else if (b === max) { + h = 4 + (r - g) / delta; + } - // 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); + h = Math.min(h * 60, 360); - // now we need to remove `args[index]` since it's inlined in the `format` - args.splice(index, 1); - index--; - } - return match; - }); + if (h < 0) { + h += 360; + } - // apply env-specific formatting (colors, etc.) - exports.formatArgs.call(self, args); + const l = (min + max) / 2; - var logFn = debug.log || exports.log || console.log.bind(console); - logFn.apply(self, args); - } + if (max === min) { + s = 0; + } else if (l <= 0.5) { + s = delta / (max + min); + } else { + s = delta / (2 - max - min); + } - debug.namespace = namespace; - debug.enabled = exports.enabled(namespace); - debug.useColors = exports.useColors(); - debug.color = selectColor(namespace); + return [h, s * 100, l * 100]; +}; - // env-specific initialization logic for debug instances - if ('function' === typeof exports.init) { - exports.init(debug); - } +convert.rgb.hsv = function (rgb) { + let rdif; + let gdif; + let bdif; + let h; + let s; - return debug; -} + const r = rgb[0] / 255; + const g = rgb[1] / 255; + const b = rgb[2] / 255; + const v = Math.max(r, g, b); + const diff = v - Math.min(r, g, b); + const diffc = function (c) { + return (v - c) / 6 / diff + 1 / 2; + }; -/** - * Enables a debug mode by namespaces. This can include modes - * separated by a colon and wildcards. - * - * @param {String} namespaces - * @api public - */ + if (diff === 0) { + h = 0; + s = 0; + } else { + s = diff / v; + rdif = diffc(r); + gdif = diffc(g); + bdif = diffc(b); -function enable(namespaces) { - exports.save(namespaces); + if (r === v) { + h = bdif - gdif; + } else if (g === v) { + h = (1 / 3) + rdif - bdif; + } else if (b === v) { + h = (2 / 3) + gdif - rdif; + } - exports.names = []; - exports.skips = []; + if (h < 0) { + h += 1; + } else if (h > 1) { + h -= 1; + } + } - var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); - var len = split.length; + return [ + h * 360, + s * 100, + v * 100 + ]; +}; - 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 + '$')); - } - } -} +convert.rgb.hwb = function (rgb) { + const r = rgb[0]; + const g = rgb[1]; + let b = rgb[2]; + const h = convert.rgb.hsl(rgb)[0]; + const w = 1 / 255 * Math.min(r, Math.min(g, b)); -/** - * Disable debug output. - * - * @api public - */ + b = 1 - 1 / 255 * Math.max(r, Math.max(g, b)); -function disable() { - exports.enable(''); -} + return [h, w * 100, b * 100]; +}; -/** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ +convert.rgb.cmyk = function (rgb) { + const r = rgb[0] / 255; + const g = rgb[1] / 255; + const b = rgb[2] / 255; -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; -} + const k = Math.min(1 - r, 1 - g, 1 - b); + const c = (1 - r - k) / (1 - k) || 0; + const m = (1 - g - k) / (1 - k) || 0; + const y = (1 - b - k) / (1 - k) || 0; -/** - * Coerce `val`. - * - * @param {Mixed} val - * @return {Mixed} - * @api private - */ + return [c * 100, m * 100, y * 100, k * 100]; +}; -function coerce(val) { - if (val instanceof Error) return val.stack || val.message; - return val; +function comparativeDistance(x, y) { + /* + See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance + */ + return ( + ((x[0] - y[0]) ** 2) + + ((x[1] - y[1]) ** 2) + + ((x[2] - y[2]) ** 2) + ); } +convert.rgb.keyword = function (rgb) { + const reversed = reverseKeywords[rgb]; + if (reversed) { + return reversed; + } -/***/ }), - -/***/ 7471: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + let currentClosestDistance = Infinity; + let currentClosestKeyword; -/** - * Detect Electron renderer process, which is node, but we should - * treat as a browser. - */ + for (const keyword of Object.keys(cssKeywords)) { + const value = cssKeywords[keyword]; -if (typeof process !== 'undefined' && process.type === 'renderer') { - module.exports = __nccwpck_require__(15377); -} else { - module.exports = __nccwpck_require__(74117); -} + // Compute comparative distance + const distance = comparativeDistance(rgb, value); + // Check if its less, if so set as closest + if (distance < currentClosestDistance) { + currentClosestDistance = distance; + currentClosestKeyword = keyword; + } + } -/***/ }), + return currentClosestKeyword; +}; -/***/ 74117: -/***/ ((module, exports, __nccwpck_require__) => { +convert.keyword.rgb = function (keyword) { + return cssKeywords[keyword]; +}; -/** - * Module dependencies. - */ +convert.rgb.xyz = function (rgb) { + let r = rgb[0] / 255; + let g = rgb[1] / 255; + let b = rgb[2] / 255; -var tty = __nccwpck_require__(76224); -var util = __nccwpck_require__(73837); + // Assume sRGB + r = r > 0.04045 ? (((r + 0.055) / 1.055) ** 2.4) : (r / 12.92); + g = g > 0.04045 ? (((g + 0.055) / 1.055) ** 2.4) : (g / 12.92); + b = b > 0.04045 ? (((b + 0.055) / 1.055) ** 2.4) : (b / 12.92); -/** - * This is the Node.js implementation of `debug()`. - * - * Expose `debug()` as the module. - */ + const x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805); + const y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722); + const z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505); -exports = module.exports = __nccwpck_require__(22552); -exports.init = init; -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; + return [x * 100, y * 100, z * 100]; +}; -/** - * Colors. - */ +convert.rgb.lab = function (rgb) { + const xyz = convert.rgb.xyz(rgb); + let x = xyz[0]; + let y = xyz[1]; + let z = xyz[2]; -exports.colors = [6, 2, 3, 4, 5, 1]; + x /= 95.047; + y /= 100; + z /= 108.883; -/** - * Build up the default `inspectOpts` object from the environment variables. - * - * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js - */ + x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116); + y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116); + z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116); -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() }); + const l = (116 * y) - 16; + const a = 500 * (x - y); + const b = 200 * (y - z); - // 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 [l, a, b]; +}; - obj[prop] = val; - return obj; -}, {}); +convert.hsl.rgb = function (hsl) { + const h = hsl[0] / 360; + const s = hsl[1] / 100; + const l = hsl[2] / 100; + let t2; + let t3; + let val; -/** - * 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 (s === 0) { + val = l * 255; + return [val, val, val]; + } -var fd = parseInt(process.env.DEBUG_FD, 10) || 2; + if (l < 0.5) { + t2 = l * (1 + s); + } else { + t2 = l + s - l * s; + } -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 t1 = 2 * l - t2; -var stream = 1 === fd ? process.stdout : - 2 === fd ? process.stderr : - createWritableStdioStream(fd); + const rgb = [0, 0, 0]; + for (let i = 0; i < 3; i++) { + t3 = h + 1 / 3 * -(i - 1); + if (t3 < 0) { + t3++; + } -/** - * Is stdout a TTY? Colored output is enabled when `true`. - */ + if (t3 > 1) { + t3--; + } -function useColors() { - return 'colors' in exports.inspectOpts - ? Boolean(exports.inspectOpts.colors) - : tty.isatty(fd); -} + if (6 * t3 < 1) { + val = t1 + (t2 - t1) * 6 * t3; + } else if (2 * t3 < 1) { + val = t2; + } else if (3 * t3 < 2) { + val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; + } else { + val = t1; + } -/** - * Map %o to `util.inspect()`, all on a single line. - */ + rgb[i] = val * 255; + } -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(' '); + return rgb; }; -/** - * Map %o to `util.inspect()`, allowing multiple lines if needed. - */ - -exports.formatters.O = function(v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts); -}; +convert.hsl.hsv = function (hsl) { + const h = hsl[0]; + let s = hsl[1] / 100; + let l = hsl[2] / 100; + let smin = s; + const lmin = Math.max(l, 0.01); -/** - * Adds ANSI color escape codes if enabled. - * - * @api public - */ + l *= 2; + s *= (l <= 1) ? l : 2 - l; + smin *= lmin <= 1 ? lmin : 2 - lmin; + const v = (l + s) / 2; + const sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s); -function formatArgs(args) { - var name = this.namespace; - var useColors = this.useColors; + return [h, sv * 100, v * 100]; +}; - if (useColors) { - var c = this.color; - var prefix = ' \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m'; +convert.hsv.rgb = function (hsv) { + const h = hsv[0] / 60; + const s = hsv[1] / 100; + let v = hsv[2] / 100; + const hi = Math.floor(h) % 6; - 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]; - } -} + const f = h - Math.floor(h); + const p = 255 * v * (1 - s); + const q = 255 * v * (1 - (s * f)); + const t = 255 * v * (1 - (s * (1 - f))); + v *= 255; -/** - * Invokes `util.format()` with the specified arguments and writes to `stream`. - */ + switch (hi) { + case 0: + return [v, t, p]; + case 1: + return [q, v, p]; + case 2: + return [p, v, t]; + case 3: + return [p, q, v]; + case 4: + return [t, p, v]; + case 5: + return [v, p, q]; + } +}; -function log() { - return stream.write(util.format.apply(util, arguments) + '\n'); -} +convert.hsv.hsl = function (hsv) { + const h = hsv[0]; + const s = hsv[1] / 100; + const v = hsv[2] / 100; + const vmin = Math.max(v, 0.01); + let sl; + let l; -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ + l = (2 - s) * v; + const lmin = (2 - s) * vmin; + sl = s * vmin; + sl /= (lmin <= 1) ? lmin : 2 - lmin; + sl = sl || 0; + l /= 2; -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; - } -} + return [h, sl * 100, l * 100]; +}; -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ +// http://dev.w3.org/csswg/css-color/#hwb-to-rgb +convert.hwb.rgb = function (hwb) { + const h = hwb[0] / 360; + let wh = hwb[1] / 100; + let bl = hwb[2] / 100; + const ratio = wh + bl; + let f; -function load() { - return process.env.DEBUG; -} + // Wh + bl cant be > 1 + if (ratio > 1) { + wh /= ratio; + bl /= ratio; + } -/** - * 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. - */ + const i = Math.floor(6 * h); + const v = 1 - bl; + f = 6 * h - i; -function createWritableStdioStream (fd) { - var stream; - var tty_wrap = process.binding('tty_wrap'); + if ((i & 0x01) !== 0) { + f = 1 - f; + } - // Note stream._type is used for test-module-load-list.js + const n = wh + f * (v - wh); // Linear interpolation - switch (tty_wrap.guessHandleType(fd)) { - case 'TTY': - stream = new tty.WriteStream(fd); - stream._type = 'tty'; + let r; + let g; + let b; + /* eslint-disable max-statements-per-line,no-multi-spaces */ + switch (i) { + default: + case 6: + case 0: r = v; g = n; b = wh; break; + case 1: r = n; g = v; b = wh; break; + case 2: r = wh; g = v; b = n; break; + case 3: r = wh; g = n; b = v; break; + case 4: r = n; g = wh; b = v; break; + case 5: r = v; g = wh; b = n; break; + } + /* eslint-enable max-statements-per-line,no-multi-spaces */ - // 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; + return [r * 255, g * 255, b * 255]; +}; - case 'FILE': - var fs = __nccwpck_require__(57147); - stream = new fs.SyncWriteStream(fd, { autoClose: false }); - stream._type = 'fs'; - break; +convert.cmyk.rgb = function (cmyk) { + const c = cmyk[0] / 100; + const m = cmyk[1] / 100; + const y = cmyk[2] / 100; + const k = cmyk[3] / 100; - case 'PIPE': - case 'TCP': - var net = __nccwpck_require__(41808); - stream = new net.Socket({ - fd: fd, - readable: false, - writable: true - }); + const r = 1 - Math.min(1, c * (1 - k) + k); + const g = 1 - Math.min(1, m * (1 - k) + k); + const b = 1 - Math.min(1, y * (1 - k) + k); - // 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 [r * 255, g * 255, b * 255]; +}; - // 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; +convert.xyz.rgb = function (xyz) { + const x = xyz[0] / 100; + const y = xyz[1] / 100; + const z = xyz[2] / 100; + let r; + let g; + let b; - default: - // Probably an error on in uv_guess_handle() - throw new Error('Implement me. Unknown stream file type!'); - } + r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986); + g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415); + b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570); - // For supporting legacy API we put the FD here. - stream.fd = fd; + // Assume sRGB + r = r > 0.0031308 + ? ((1.055 * (r ** (1.0 / 2.4))) - 0.055) + : r * 12.92; - stream._isStdio = true; + g = g > 0.0031308 + ? ((1.055 * (g ** (1.0 / 2.4))) - 0.055) + : g * 12.92; - return stream; -} + b = b > 0.0031308 + ? ((1.055 * (b ** (1.0 / 2.4))) - 0.055) + : b * 12.92; -/** - * Init logic for `debug` instances. - * - * Create a new `inspectOpts` object in case `useColors` is set - * differently for a particular `debug` instance. - */ + r = Math.min(Math.max(0, r), 1); + g = Math.min(Math.max(0, g), 1); + b = Math.min(Math.max(0, b), 1); -function init (debug) { - debug.inspectOpts = {}; + return [r * 255, g * 255, b * 255]; +}; - var keys = Object.keys(exports.inspectOpts); - for (var i = 0; i < keys.length; i++) { - debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; - } -} +convert.xyz.lab = function (xyz) { + let x = xyz[0]; + let y = xyz[1]; + let z = xyz[2]; -/** - * Enable namespaces listed in `process.env.DEBUG` initially. - */ + x /= 95.047; + y /= 100; + z /= 108.883; -exports.enable(load()); + x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116); + y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116); + z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116); + const l = (116 * y) - 16; + const a = 500 * (x - y); + const b = 200 * (y - z); -/***/ }), + return [l, a, b]; +}; -/***/ 73233: -/***/ ((module) => { +convert.lab.xyz = function (lab) { + const l = lab[0]; + const a = lab[1]; + const b = lab[2]; + let x; + let y; + let z; -/** - * Helpers. - */ + y = (l + 16) / 116; + x = a / 500 + y; + z = y - b / 200; -var s = 1000; -var m = s * 60; -var h = m * 60; -var d = h * 24; -var y = d * 365.25; + const y2 = y ** 3; + const x2 = x ** 3; + const z2 = z ** 3; + y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787; + x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787; + z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787; -/** - * 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 - */ + x *= 95.047; + y *= 100; + z *= 108.883; -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 [x, y, z]; }; -/** - * Parse the given `str` and return milliseconds. - * - * @param {String} str - * @return {Number} - * @api private - */ +convert.lab.lch = function (lab) { + const l = lab[0]; + const a = lab[1]; + const b = lab[2]; + let h; -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; - } -} + const hr = Math.atan2(b, a); + h = hr * 360 / 2 / Math.PI; -/** - * Short format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ + if (h < 0) { + h += 360; + } -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'; -} + const c = Math.sqrt(a * a + b * b); -/** - * Long format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ + return [l, c, h]; +}; -function fmtLong(ms) { - return plural(ms, d, 'day') || - plural(ms, h, 'hour') || - plural(ms, m, 'minute') || - plural(ms, s, 'second') || - ms + ' ms'; -} +convert.lch.lab = function (lch) { + const l = lch[0]; + const c = lch[1]; + const h = lch[2]; -/** - * Pluralization helper. - */ + const hr = h / 360 * 2 * Math.PI; + const a = c * Math.cos(hr); + const b = c * Math.sin(hr); -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'; -} + return [l, a, b]; +}; +convert.rgb.ansi16 = function (args, saturation = null) { + const [r, g, b] = args; + let value = saturation === null ? convert.rgb.hsv(args)[2] : saturation; // Hsv -> ansi16 optimization -/***/ }), + value = Math.round(value / 50); -/***/ 85442: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (value === 0) { + return 30; + } -"use strict"; + let ansi = 30 + + ((Math.round(b / 255) << 2) + | (Math.round(g / 255) << 1) + | Math.round(r / 255)); + if (value === 2) { + ansi += 60; + } -var Batcher, Events, parser; -parser = __nccwpck_require__(67823); -Events = __nccwpck_require__(107); + return ansi; +}; -Batcher = function () { - class Batcher { - constructor(options = {}) { - this.options = options; - parser.load(this.options, this.defaults, this); - this.Events = new Events(this); - this._arr = []; +convert.hsv.ansi16 = function (args) { + // Optimization here; we already know the value and don't need to get + // it converted for us. + return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]); +}; - this._resetPromise(); +convert.rgb.ansi256 = function (args) { + const r = args[0]; + const g = args[1]; + const b = args[2]; - this._lastFlush = Date.now(); - } + // We use the extended greyscale palette here, with the exception of + // black and white. normal palette only has 4 greyscale shades. + if (r === g && g === b) { + if (r < 8) { + return 16; + } - _resetPromise() { - return this._promise = new this.Promise((res, rej) => { - return this._resolve = res; - }); - } + if (r > 248) { + return 231; + } - _flush() { - clearTimeout(this._timeout); - this._lastFlush = Date.now(); + return Math.round(((r - 8) / 247) * 24) + 232; + } - this._resolve(); + const ansi = 16 + + (36 * Math.round(r / 255 * 5)) + + (6 * Math.round(g / 255 * 5)) + + Math.round(b / 255 * 5); - this.Events.trigger("batch", this._arr); - this._arr = []; - return this._resetPromise(); - } + return ansi; +}; - add(data) { - var ret; +convert.ansi16.rgb = function (args) { + let color = args % 10; - this._arr.push(data); + // Handle greyscale + if (color === 0 || color === 7) { + if (args > 50) { + color += 3.5; + } - ret = this._promise; + color = color / 10.5 * 255; - if (this._arr.length === this.maxSize) { - this._flush(); - } else if (this.maxTime != null && this._arr.length === 1) { - this._timeout = setTimeout(() => { - return this._flush(); - }, this.maxTime); - } + return [color, color, color]; + } - return ret; - } + const mult = (~~(args > 50) + 1) * 0.5; + const r = ((color & 1) * mult) * 255; + const g = (((color >> 1) & 1) * mult) * 255; + const b = (((color >> 2) & 1) * mult) * 255; - } + return [r, g, b]; +}; - ; - Batcher.prototype.defaults = { - maxTime: null, - maxSize: null, - Promise: Promise - }; - return Batcher; -}.call(void 0); +convert.ansi256.rgb = function (args) { + // Handle greyscale + if (args >= 232) { + const c = (args - 232) * 10 + 8; + return [c, c, c]; + } -module.exports = Batcher; + args -= 16; -/***/ }), + let rem; + const r = Math.floor(args / 36) / 5 * 255; + const g = Math.floor((rem = args % 36) / 6) / 5 * 255; + const b = (rem % 6) / 5 * 255; -/***/ 83911: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return [r, g, b]; +}; -"use strict"; +convert.rgb.hex = function (args) { + const integer = ((Math.round(args[0]) & 0xFF) << 16) + + ((Math.round(args[1]) & 0xFF) << 8) + + (Math.round(args[2]) & 0xFF); + const string = integer.toString(16).toUpperCase(); + return '000000'.substring(string.length) + string; +}; -function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } +convert.hex.rgb = function (args) { + const match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i); + if (!match) { + return [0, 0, 0]; + } -function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } + let colorString = match[0]; -function _toArray(arr) { return _arrayWithHoles(arr) || _iterableToArray(arr) || _nonIterableRest(); } + if (match[0].length === 3) { + colorString = colorString.split('').map(char => { + return char + char; + }).join(''); + } -function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } + const integer = parseInt(colorString, 16); + const r = (integer >> 16) & 0xFF; + const g = (integer >> 8) & 0xFF; + const b = integer & 0xFF; -function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } + return [r, g, b]; +}; -function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } +convert.rgb.hcg = function (rgb) { + const r = rgb[0] / 255; + const g = rgb[1] / 255; + const b = rgb[2] / 255; + const max = Math.max(Math.max(r, g), b); + const min = Math.min(Math.min(r, g), b); + const chroma = (max - min); + let grayscale; + let hue; -function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } + if (chroma < 1) { + grayscale = min / (1 - chroma); + } else { + grayscale = 0; + } -function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } + if (chroma <= 0) { + hue = 0; + } else + if (max === r) { + hue = ((g - b) / chroma) % 6; + } else + if (max === g) { + hue = 2 + (b - r) / chroma; + } else { + hue = 4 + (r - g) / chroma; + } -var Bottleneck, - DEFAULT_PRIORITY, - Events, - LocalDatastore, - NUM_PRIORITIES, - Queues, - RedisDatastore, - States, - Sync, - parser, - splice = [].splice; -NUM_PRIORITIES = 10; -DEFAULT_PRIORITY = 5; -parser = __nccwpck_require__(67823); -Queues = __nccwpck_require__(65893); -LocalDatastore = __nccwpck_require__(38979); -RedisDatastore = __nccwpck_require__(4946); -Events = __nccwpck_require__(107); -States = __nccwpck_require__(2527); -Sync = __nccwpck_require__(56029); + hue /= 6; + hue %= 1; -Bottleneck = function () { - class Bottleneck { - constructor(options = {}, ...invalid) { - var storeInstanceOptions, storeOptions; - this._drainOne = this._drainOne.bind(this); - this.submit = this.submit.bind(this); - this.schedule = this.schedule.bind(this); - this.updateSettings = this.updateSettings.bind(this); - this.incrementReservoir = this.incrementReservoir.bind(this); + return [hue * 360, chroma * 100, grayscale * 100]; +}; - this._validateOptions(options, invalid); +convert.hsl.hcg = function (hsl) { + const s = hsl[1] / 100; + const l = hsl[2] / 100; - parser.load(options, this.instanceDefaults, this); - this._queues = new Queues(NUM_PRIORITIES); - this._scheduled = {}; - this._states = new States(["RECEIVED", "QUEUED", "RUNNING", "EXECUTING"].concat(this.trackDoneStatus ? ["DONE"] : [])); - this._limiter = null; - this.Events = new Events(this); - this._submitLock = new Sync("submit", this.Promise); - this._registerLock = new Sync("register", this.Promise); - storeOptions = parser.load(options, this.storeDefaults, {}); + const c = l < 0.5 ? (2.0 * s * l) : (2.0 * s * (1.0 - l)); - this._store = function () { - if (this.datastore === "redis" || this.datastore === "ioredis" || this.connection != null) { - storeInstanceOptions = parser.load(options, this.redisStoreDefaults, {}); - return new RedisDatastore(this, storeOptions, storeInstanceOptions); - } else if (this.datastore === "local") { - storeInstanceOptions = parser.load(options, this.localStoreDefaults, {}); - return new LocalDatastore(this, storeOptions, storeInstanceOptions); - } else { - throw new Bottleneck.prototype.BottleneckError(`Invalid datastore type: ${this.datastore}`); - } - }.call(this); + let f = 0; + if (c < 1.0) { + f = (l - 0.5 * c) / (1.0 - c); + } - this._queues.on("leftzero", () => { - var base; - return typeof (base = this._store.heartbeat).ref === "function" ? base.ref() : void 0; - }); + return [hsl[0], c * 100, f * 100]; +}; - this._queues.on("zero", () => { - var base; - return typeof (base = this._store.heartbeat).unref === "function" ? base.unref() : void 0; - }); - } +convert.hsv.hcg = function (hsv) { + const s = hsv[1] / 100; + const v = hsv[2] / 100; - _validateOptions(options, invalid) { - if (!(options != null && typeof options === "object" && invalid.length === 0)) { - throw new Bottleneck.prototype.BottleneckError("Bottleneck v2 takes a single object argument. Refer to https://github.com/SGrondin/bottleneck#upgrading-to-v2 if you're upgrading from Bottleneck v1."); - } - } + const c = s * v; + let f = 0; - ready() { - return this._store.ready; - } + if (c < 1.0) { + f = (v - c) / (1 - c); + } + + return [hsv[0], c * 100, f * 100]; +}; - clients() { - return this._store.clients; - } +convert.hcg.rgb = function (hcg) { + const h = hcg[0] / 360; + const c = hcg[1] / 100; + const g = hcg[2] / 100; - channel() { - return `b_${this.id}`; - } + if (c === 0.0) { + return [g * 255, g * 255, g * 255]; + } - channel_client() { - return `b_${this.id}_${this._store.clientId}`; - } + const pure = [0, 0, 0]; + const hi = (h % 1) * 6; + const v = hi % 1; + const w = 1 - v; + let mg = 0; - publish(message) { - return this._store.__publish__(message); - } + /* eslint-disable max-statements-per-line */ + switch (Math.floor(hi)) { + case 0: + pure[0] = 1; pure[1] = v; pure[2] = 0; break; + case 1: + pure[0] = w; pure[1] = 1; pure[2] = 0; break; + case 2: + pure[0] = 0; pure[1] = 1; pure[2] = v; break; + case 3: + pure[0] = 0; pure[1] = w; pure[2] = 1; break; + case 4: + pure[0] = v; pure[1] = 0; pure[2] = 1; break; + default: + pure[0] = 1; pure[1] = 0; pure[2] = w; + } + /* eslint-enable max-statements-per-line */ - disconnect(flush = true) { - return this._store.__disconnect__(flush); - } + mg = (1.0 - c) * g; - chain(_limiter) { - this._limiter = _limiter; - return this; - } + return [ + (c * pure[0] + mg) * 255, + (c * pure[1] + mg) * 255, + (c * pure[2] + mg) * 255 + ]; +}; - queued(priority) { - return this._queues.queued(priority); - } +convert.hcg.hsv = function (hcg) { + const c = hcg[1] / 100; + const g = hcg[2] / 100; - clusterQueued() { - return this._store.__queued__(); - } + const v = c + g * (1.0 - c); + let f = 0; - empty() { - return this.queued() === 0 && this._submitLock.isEmpty(); - } + if (v > 0.0) { + f = c / v; + } - running() { - return this._store.__running__(); - } + return [hcg[0], f * 100, v * 100]; +}; - done() { - return this._store.__done__(); - } +convert.hcg.hsl = function (hcg) { + const c = hcg[1] / 100; + const g = hcg[2] / 100; - jobStatus(id) { - return this._states.jobStatus(id); - } + const l = g * (1.0 - c) + 0.5 * c; + let s = 0; - jobs(status) { - return this._states.statusJobs(status); - } + if (l > 0.0 && l < 0.5) { + s = c / (2 * l); + } else + if (l >= 0.5 && l < 1.0) { + s = c / (2 * (1 - l)); + } - counts() { - return this._states.statusCounts(); - } + return [hcg[0], s * 100, l * 100]; +}; - _sanitizePriority(priority) { - var sProperty; - sProperty = ~~priority !== priority ? DEFAULT_PRIORITY : priority; +convert.hcg.hwb = function (hcg) { + const c = hcg[1] / 100; + const g = hcg[2] / 100; + const v = c + g * (1.0 - c); + return [hcg[0], (v - c) * 100, (1 - v) * 100]; +}; - if (sProperty < 0) { - return 0; - } else if (sProperty > NUM_PRIORITIES - 1) { - return NUM_PRIORITIES - 1; - } else { - return sProperty; - } - } +convert.hwb.hcg = function (hwb) { + const w = hwb[1] / 100; + const b = hwb[2] / 100; + const v = 1 - b; + const c = v - w; + let g = 0; - _randomIndex() { - return Math.random().toString(36).slice(2); - } + if (c < 1) { + g = (v - c) / (1 - c); + } - check(weight = 1) { - return this._store.__check__(weight); - } + return [hwb[0], c * 100, g * 100]; +}; - _run(next, wait, index, retryCount) { - var _this = this; +convert.apple.rgb = function (apple) { + return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255]; +}; - var completed, done; - this.Events.trigger("debug", `Scheduling ${next.options.id}`, { - args: next.args, - options: next.options - }); - done = false; +convert.rgb.apple = function (rgb) { + return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535]; +}; - completed = - /*#__PURE__*/ - function () { - var _ref = _asyncToGenerator(function* (...args) { - var e, error, eventInfo, retry, retryAfter, running; +convert.gray.rgb = function (args) { + return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255]; +}; - if (!done) { - try { - done = true; - clearTimeout(_this._scheduled[index].expiration); - delete _this._scheduled[index]; - eventInfo = { - args: next.args, - options: next.options, - retryCount - }; +convert.gray.hsl = function (args) { + return [0, 0, args[0]]; +}; - if ((error = args[0]) != null) { - retry = yield _this.Events.trigger("failed", error, eventInfo); +convert.gray.hsv = convert.gray.hsl; - if (retry != null) { - retryAfter = ~~retry; +convert.gray.hwb = function (gray) { + return [0, 100, gray[0]]; +}; - _this.Events.trigger("retry", `Retrying ${next.options.id} after ${retryAfter} ms`, eventInfo); +convert.gray.cmyk = function (gray) { + return [0, 0, 0, gray[0]]; +}; - return _this._run(next, retryAfter, index, retryCount + 1); - } - } +convert.gray.lab = function (gray) { + return [gray[0], 0, 0]; +}; - _this._states.next(next.options.id); // DONE +convert.gray.hex = function (gray) { + const val = Math.round(gray[0] / 100 * 255) & 0xFF; + const integer = (val << 16) + (val << 8) + val; + const string = integer.toString(16).toUpperCase(); + return '000000'.substring(string.length) + string; +}; - _this.Events.trigger("debug", `Completed ${next.options.id}`, eventInfo); +convert.rgb.gray = function (rgb) { + const val = (rgb[0] + rgb[1] + rgb[2]) / 3; + return [val / 255 * 100]; +}; - _this.Events.trigger("done", `Completed ${next.options.id}`, eventInfo); - var _ref2 = yield _this._store.__free__(index, next.options.weight); +/***/ }), - running = _ref2.running; +/***/ 86931: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - _this.Events.trigger("debug", `Freed ${next.options.id}`, eventInfo); +const conversions = __nccwpck_require__(97391); +const route = __nccwpck_require__(30880); - if (running === 0 && _this.empty()) { - _this.Events.trigger("idle"); - } +const convert = {}; - return typeof next.cb === "function" ? next.cb(...args) : void 0; - } catch (error1) { - e = error1; - return _this.Events.trigger("error", e); - } - } - }); +const models = Object.keys(conversions); - return function completed() { - return _ref.apply(this, arguments); - }; - }(); +function wrapRaw(fn) { + const wrappedFn = function (...args) { + const arg0 = args[0]; + if (arg0 === undefined || arg0 === null) { + return arg0; + } - if (retryCount === 0) { - // RUNNING - this._states.next(next.options.id); - } + if (arg0.length > 1) { + args = arg0; + } - return this._scheduled[index] = { - timeout: setTimeout(() => { - this.Events.trigger("debug", `Executing ${next.options.id}`, { - args: next.args, - options: next.options - }); + return fn(args); + }; - if (retryCount === 0) { - // EXECUTING - this._states.next(next.options.id); - } + // Preserve .conversion property if there is one + if ('conversion' in fn) { + wrappedFn.conversion = fn.conversion; + } - if (this._limiter != null) { - return this._limiter.submit(next.options, next.task, ...next.args, completed); - } else { - return next.task(...next.args, completed); - } - }, wait), - expiration: next.options.expiration != null ? setTimeout(() => { - return completed(new Bottleneck.prototype.BottleneckError(`This job timed out after ${next.options.expiration} ms.`)); - }, wait + next.options.expiration) : void 0, - job: next - }; - } + return wrappedFn; +} - _drainOne(capacity) { - return this._registerLock.schedule(() => { - var args, index, next, options, queue; +function wrapRounded(fn) { + const wrappedFn = function (...args) { + const arg0 = args[0]; - if (this.queued() === 0) { - return this.Promise.resolve(null); - } + if (arg0 === undefined || arg0 === null) { + return arg0; + } - queue = this._queues.getFirst(); + if (arg0.length > 1) { + args = arg0; + } - var _next2 = next = queue.first(); + const result = fn(args); - options = _next2.options; - args = _next2.args; + // We're assuming the result is an array here. + // see notice in conversions.js; don't use box types + // in conversion functions. + if (typeof result === 'object') { + for (let len = result.length, i = 0; i < len; i++) { + result[i] = Math.round(result[i]); + } + } - if (capacity != null && options.weight > capacity) { - return this.Promise.resolve(null); - } + return result; + }; - this.Events.trigger("debug", `Draining ${options.id}`, { - args, - options - }); - index = this._randomIndex(); - return this._store.__register__(index, options.weight, options.expiration).then(({ - success, - wait, - reservoir - }) => { - var empty; - this.Events.trigger("debug", `Drained ${options.id}`, { - success, - args, - options - }); + // Preserve .conversion property if there is one + if ('conversion' in fn) { + wrappedFn.conversion = fn.conversion; + } - if (success) { - queue.shift(); - empty = this.empty(); + return wrappedFn; +} - if (empty) { - this.Events.trigger("empty"); - } +models.forEach(fromModel => { + convert[fromModel] = {}; - if (reservoir === 0) { - this.Events.trigger("depleted", empty); - } + Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels}); + Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels}); - this._run(next, wait, index, 0); + const routes = route(fromModel); + const routeModels = Object.keys(routes); - return this.Promise.resolve(options.weight); - } else { - return this.Promise.resolve(null); - } - }); - }); - } + routeModels.forEach(toModel => { + const fn = routes[toModel]; - _drainAll(capacity, total = 0) { - return this._drainOne(capacity).then(drained => { - var newCapacity; + convert[fromModel][toModel] = wrapRounded(fn); + convert[fromModel][toModel].raw = wrapRaw(fn); + }); +}); - if (drained != null) { - newCapacity = capacity != null ? capacity - drained : capacity; - return this._drainAll(newCapacity, total + drained); - } else { - return this.Promise.resolve(total); - } - }).catch(e => { - return this.Events.trigger("error", e); - }); - } +module.exports = convert; - _drop(job, message = "This job has been dropped by Bottleneck") { - if (this._states.remove(job.options.id)) { - if (this.rejectOnDrop) { - if (typeof job.cb === "function") { - job.cb(new Bottleneck.prototype.BottleneckError(message)); - } - } - return this.Events.trigger("dropped", job); - } - } +/***/ }), - _dropAllQueued(message) { - return this._queues.shiftAll(job => { - return this._drop(job, message); - }); - } +/***/ 30880: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - stop(options = {}) { - var done, waitForExecuting; - options = parser.load(options, this.stopDefaults); +const conversions = __nccwpck_require__(97391); - waitForExecuting = at => { - var finished; +/* + This function routes a model to all other models. - finished = () => { - var counts; - counts = this._states.counts; - return counts[0] + counts[1] + counts[2] + counts[3] === at; - }; + all functions that are routed have a property `.conversion` attached + to the returned synthetic function. This property is an array + of strings, each with the steps in between the 'from' and 'to' + color models (inclusive). - return new this.Promise((resolve, reject) => { - if (finished()) { - return resolve(); - } else { - return this.on("done", () => { - if (finished()) { - this.removeAllListeners("done"); - return resolve(); - } - }); - } - }); - }; + conversions that are not possible simply are not included. +*/ - done = options.dropWaitingJobs ? (this._run = next => { - return this._drop(next, options.dropErrorMessage); - }, this._drainOne = () => { - return this.Promise.resolve(null); - }, this._registerLock.schedule(() => { - return this._submitLock.schedule(() => { - var k, ref, v; - ref = this._scheduled; +function buildGraph() { + const graph = {}; + // https://jsperf.com/object-keys-vs-for-in-with-closure/3 + const models = Object.keys(conversions); - for (k in ref) { - v = ref[k]; + for (let len = models.length, i = 0; i < len; i++) { + graph[models[i]] = { + // http://jsperf.com/1-vs-infinity + // micro-opt, but this is simple. + distance: -1, + parent: null + }; + } - if (this.jobStatus(v.job.options.id) === "RUNNING") { - clearTimeout(v.timeout); - clearTimeout(v.expiration); + return graph; +} - this._drop(v.job, options.dropErrorMessage); - } - } +// https://en.wikipedia.org/wiki/Breadth-first_search +function deriveBFS(fromModel) { + const graph = buildGraph(); + const queue = [fromModel]; // Unshift -> queue -> pop - this._dropAllQueued(options.dropErrorMessage); + graph[fromModel].distance = 0; - return waitForExecuting(0); - }); - })) : this.schedule({ - priority: NUM_PRIORITIES - 1, - weight: 0 - }, () => { - return waitForExecuting(1); - }); + while (queue.length) { + const current = queue.pop(); + const adjacents = Object.keys(conversions[current]); - this.submit = (...args) => { - var _ref3, _ref4, _splice$call, _splice$call2; + for (let len = adjacents.length, i = 0; i < len; i++) { + const adjacent = adjacents[i]; + const node = graph[adjacent]; - var cb, ref; - ref = args, (_ref3 = ref, _ref4 = _toArray(_ref3), args = _ref4.slice(0), _ref3), (_splice$call = splice.call(args, -1), _splice$call2 = _slicedToArray(_splice$call, 1), cb = _splice$call2[0], _splice$call); - return typeof cb === "function" ? cb(new Bottleneck.prototype.BottleneckError(options.enqueueErrorMessage)) : void 0; - }; + if (node.distance === -1) { + node.distance = graph[current].distance + 1; + node.parent = current; + queue.unshift(adjacent); + } + } + } - this.stop = () => { - return this.Promise.reject(new Bottleneck.prototype.BottleneckError("stop() has already been called")); - }; + return graph; +} - return done; - } +function link(from, to) { + return function (args) { + return to(from(args)); + }; +} - submit(...args) { - var _this2 = this; +function wrapConversion(toModel, graph) { + const path = [graph[toModel].parent, toModel]; + let fn = conversions[graph[toModel].parent][toModel]; - var cb, job, options, ref, ref1, task; + let cur = graph[toModel].parent; + while (graph[cur].parent) { + path.unshift(graph[cur].parent); + fn = link(conversions[graph[cur].parent][cur], fn); + cur = graph[cur].parent; + } - if (typeof args[0] === "function") { - var _ref5, _ref6, _splice$call3, _splice$call4; + fn.conversion = path; + return fn; +} + +module.exports = function (fromModel) { + const graph = deriveBFS(fromModel); + const conversion = {}; - ref = args, (_ref5 = ref, _ref6 = _toArray(_ref5), task = _ref6[0], args = _ref6.slice(1), _ref5), (_splice$call3 = splice.call(args, -1), _splice$call4 = _slicedToArray(_splice$call3, 1), cb = _splice$call4[0], _splice$call3); - options = parser.load({}, this.jobDefaults, {}); - } else { - var _ref7, _ref8, _splice$call5, _splice$call6; + const models = Object.keys(graph); + for (let len = models.length, i = 0; i < len; i++) { + const toModel = models[i]; + const node = graph[toModel]; - ref1 = args, (_ref7 = ref1, _ref8 = _toArray(_ref7), options = _ref8[0], task = _ref8[1], args = _ref8.slice(2), _ref7), (_splice$call5 = splice.call(args, -1), _splice$call6 = _slicedToArray(_splice$call5, 1), cb = _splice$call6[0], _splice$call5); - options = parser.load(options, this.jobDefaults); - } + if (node.parent === null) { + // No possible conversion, or this node is the source model. + continue; + } - job = { - options, - task, - args, - cb - }; - options.priority = this._sanitizePriority(options.priority); + conversion[toModel] = wrapConversion(toModel, graph); + } - if (options.id === this.jobDefaults.id) { - options.id = `${options.id}-${this._randomIndex()}`; - } + return conversion; +}; - if (this.jobStatus(options.id) != null) { - if (typeof job.cb === "function") { - job.cb(new Bottleneck.prototype.BottleneckError(`A job with the same id already exists (id=${options.id})`)); - } - return false; - } - this._states.start(options.id); // RECEIVED +/***/ }), +/***/ 78510: +/***/ ((module) => { - this.Events.trigger("debug", `Queueing ${options.id}`, { - args, - options - }); - return this._submitLock.schedule( - /*#__PURE__*/ - _asyncToGenerator(function* () { - var blocked, e, reachedHWM, shifted, strategy; +"use strict"; - try { - var _ref10 = yield _this2._store.__submit__(_this2.queued(), options.weight); - reachedHWM = _ref10.reachedHWM; - blocked = _ref10.blocked; - strategy = _ref10.strategy; +module.exports = { + "aliceblue": [240, 248, 255], + "antiquewhite": [250, 235, 215], + "aqua": [0, 255, 255], + "aquamarine": [127, 255, 212], + "azure": [240, 255, 255], + "beige": [245, 245, 220], + "bisque": [255, 228, 196], + "black": [0, 0, 0], + "blanchedalmond": [255, 235, 205], + "blue": [0, 0, 255], + "blueviolet": [138, 43, 226], + "brown": [165, 42, 42], + "burlywood": [222, 184, 135], + "cadetblue": [95, 158, 160], + "chartreuse": [127, 255, 0], + "chocolate": [210, 105, 30], + "coral": [255, 127, 80], + "cornflowerblue": [100, 149, 237], + "cornsilk": [255, 248, 220], + "crimson": [220, 20, 60], + "cyan": [0, 255, 255], + "darkblue": [0, 0, 139], + "darkcyan": [0, 139, 139], + "darkgoldenrod": [184, 134, 11], + "darkgray": [169, 169, 169], + "darkgreen": [0, 100, 0], + "darkgrey": [169, 169, 169], + "darkkhaki": [189, 183, 107], + "darkmagenta": [139, 0, 139], + "darkolivegreen": [85, 107, 47], + "darkorange": [255, 140, 0], + "darkorchid": [153, 50, 204], + "darkred": [139, 0, 0], + "darksalmon": [233, 150, 122], + "darkseagreen": [143, 188, 143], + "darkslateblue": [72, 61, 139], + "darkslategray": [47, 79, 79], + "darkslategrey": [47, 79, 79], + "darkturquoise": [0, 206, 209], + "darkviolet": [148, 0, 211], + "deeppink": [255, 20, 147], + "deepskyblue": [0, 191, 255], + "dimgray": [105, 105, 105], + "dimgrey": [105, 105, 105], + "dodgerblue": [30, 144, 255], + "firebrick": [178, 34, 34], + "floralwhite": [255, 250, 240], + "forestgreen": [34, 139, 34], + "fuchsia": [255, 0, 255], + "gainsboro": [220, 220, 220], + "ghostwhite": [248, 248, 255], + "gold": [255, 215, 0], + "goldenrod": [218, 165, 32], + "gray": [128, 128, 128], + "green": [0, 128, 0], + "greenyellow": [173, 255, 47], + "grey": [128, 128, 128], + "honeydew": [240, 255, 240], + "hotpink": [255, 105, 180], + "indianred": [205, 92, 92], + "indigo": [75, 0, 130], + "ivory": [255, 255, 240], + "khaki": [240, 230, 140], + "lavender": [230, 230, 250], + "lavenderblush": [255, 240, 245], + "lawngreen": [124, 252, 0], + "lemonchiffon": [255, 250, 205], + "lightblue": [173, 216, 230], + "lightcoral": [240, 128, 128], + "lightcyan": [224, 255, 255], + "lightgoldenrodyellow": [250, 250, 210], + "lightgray": [211, 211, 211], + "lightgreen": [144, 238, 144], + "lightgrey": [211, 211, 211], + "lightpink": [255, 182, 193], + "lightsalmon": [255, 160, 122], + "lightseagreen": [32, 178, 170], + "lightskyblue": [135, 206, 250], + "lightslategray": [119, 136, 153], + "lightslategrey": [119, 136, 153], + "lightsteelblue": [176, 196, 222], + "lightyellow": [255, 255, 224], + "lime": [0, 255, 0], + "limegreen": [50, 205, 50], + "linen": [250, 240, 230], + "magenta": [255, 0, 255], + "maroon": [128, 0, 0], + "mediumaquamarine": [102, 205, 170], + "mediumblue": [0, 0, 205], + "mediumorchid": [186, 85, 211], + "mediumpurple": [147, 112, 219], + "mediumseagreen": [60, 179, 113], + "mediumslateblue": [123, 104, 238], + "mediumspringgreen": [0, 250, 154], + "mediumturquoise": [72, 209, 204], + "mediumvioletred": [199, 21, 133], + "midnightblue": [25, 25, 112], + "mintcream": [245, 255, 250], + "mistyrose": [255, 228, 225], + "moccasin": [255, 228, 181], + "navajowhite": [255, 222, 173], + "navy": [0, 0, 128], + "oldlace": [253, 245, 230], + "olive": [128, 128, 0], + "olivedrab": [107, 142, 35], + "orange": [255, 165, 0], + "orangered": [255, 69, 0], + "orchid": [218, 112, 214], + "palegoldenrod": [238, 232, 170], + "palegreen": [152, 251, 152], + "paleturquoise": [175, 238, 238], + "palevioletred": [219, 112, 147], + "papayawhip": [255, 239, 213], + "peachpuff": [255, 218, 185], + "peru": [205, 133, 63], + "pink": [255, 192, 203], + "plum": [221, 160, 221], + "powderblue": [176, 224, 230], + "purple": [128, 0, 128], + "rebeccapurple": [102, 51, 153], + "red": [255, 0, 0], + "rosybrown": [188, 143, 143], + "royalblue": [65, 105, 225], + "saddlebrown": [139, 69, 19], + "salmon": [250, 128, 114], + "sandybrown": [244, 164, 96], + "seagreen": [46, 139, 87], + "seashell": [255, 245, 238], + "sienna": [160, 82, 45], + "silver": [192, 192, 192], + "skyblue": [135, 206, 235], + "slateblue": [106, 90, 205], + "slategray": [112, 128, 144], + "slategrey": [112, 128, 144], + "snow": [255, 250, 250], + "springgreen": [0, 255, 127], + "steelblue": [70, 130, 180], + "tan": [210, 180, 140], + "teal": [0, 128, 128], + "thistle": [216, 191, 216], + "tomato": [255, 99, 71], + "turquoise": [64, 224, 208], + "violet": [238, 130, 238], + "wheat": [245, 222, 179], + "white": [255, 255, 255], + "whitesmoke": [245, 245, 245], + "yellow": [255, 255, 0], + "yellowgreen": [154, 205, 50] +}; - _this2.Events.trigger("debug", `Queued ${options.id}`, { - args, - options, - reachedHWM, - blocked - }); - } catch (error1) { - e = error1; - _this2._states.remove(options.id); +/***/ }), - _this2.Events.trigger("debug", `Could not queue ${options.id}`, { - args, - options, - error: e - }); +/***/ 43595: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (typeof job.cb === "function") { - job.cb(e); - } +/* - return false; - } +The MIT License (MIT) - if (blocked) { - _this2._drop(job); +Original Library + - Copyright (c) Marak Squires - return true; - } else if (reachedHWM) { - shifted = strategy === Bottleneck.prototype.strategy.LEAK ? _this2._queues.shiftLastFrom(options.priority) : strategy === Bottleneck.prototype.strategy.OVERFLOW_PRIORITY ? _this2._queues.shiftLastFrom(options.priority + 1) : strategy === Bottleneck.prototype.strategy.OVERFLOW ? job : void 0; +Additional functionality + - Copyright (c) Sindre Sorhus (sindresorhus.com) - if (shifted != null) { - _this2._drop(shifted); - } +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: - if (shifted == null || strategy === Bottleneck.prototype.strategy.OVERFLOW) { - if (shifted == null) { - _this2._drop(job); - } +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. - return reachedHWM; - } - } +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. - _this2._states.next(job.options.id); // QUEUED +*/ +var colors = {}; +module['exports'] = colors; - _this2._queues.push(options.priority, job); +colors.themes = {}; - yield _this2._drainAll(); - return reachedHWM; - })); - } +var util = __nccwpck_require__(73837); +var ansiStyles = colors.styles = __nccwpck_require__(73104); +var defineProps = Object.defineProperties; +var newLineRegex = new RegExp(/[\r\n]+/g); - schedule(...args) { - var options, task, wrapped; +colors.supportsColor = (__nccwpck_require__(10662).supportsColor); - if (typeof args[0] === "function") { - var _args = args; +if (typeof colors.enabled === 'undefined') { + colors.enabled = colors.supportsColor() !== false; +} - var _args2 = _toArray(_args); +colors.enable = function() { + colors.enabled = true; +}; - task = _args2[0]; - args = _args2.slice(1); - options = parser.load({}, this.jobDefaults, {}); - } else { - var _args3 = args; +colors.disable = function() { + colors.enabled = false; +}; - var _args4 = _toArray(_args3); +colors.stripColors = colors.strip = function(str) { + return ('' + str).replace(/\x1B\[\d+m/g, ''); +}; - options = _args4[0]; - task = _args4[1]; - args = _args4.slice(2); - options = parser.load(options, this.jobDefaults); - } +// eslint-disable-next-line no-unused-vars +var stylize = colors.stylize = function stylize(str, style) { + if (!colors.enabled) { + return str+''; + } - wrapped = (...args) => { - var _ref11, _ref12, _splice$call7, _splice$call8; + var styleMap = ansiStyles[style]; - var cb, e, ref, returned; - ref = args, (_ref11 = ref, _ref12 = _toArray(_ref11), args = _ref12.slice(0), _ref11), (_splice$call7 = splice.call(args, -1), _splice$call8 = _slicedToArray(_splice$call7, 1), cb = _splice$call8[0], _splice$call7); + // Stylize should work for non-ANSI styles, too + if(!styleMap && style in colors){ + // Style maps like trap operate as functions on strings; + // they don't have properties like open or close. + return colors[style](str); + } - returned = function () { - try { - return task(...args); - } catch (error1) { - e = error1; - return this.Promise.reject(e); - } - }.call(this); + return styleMap.open + str + styleMap.close; +}; - return (!((returned != null ? returned.then : void 0) != null && typeof returned.then === "function") ? this.Promise.resolve(returned) : returned).then(function (...args) { - return cb(null, ...args); - }).catch(function (...args) { - return cb(...args); - }); - }; +var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; +var escapeStringRegexp = function(str) { + if (typeof str !== 'string') { + throw new TypeError('Expected a string'); + } + return str.replace(matchOperatorsRe, '\\$&'); +}; - return new this.Promise((resolve, reject) => { - return this.submit(options, wrapped, ...args, function (...args) { - return (args[0] != null ? reject : (args.shift(), resolve))(...args); - }).catch(e => { - return this.Events.trigger("error", e); - }); - }); - } +function build(_styles) { + var builder = function builder() { + return applyStyle.apply(builder, arguments); + }; + builder._styles = _styles; + // __proto__ is used because we must return a function, but there is + // no way to create a function with a different prototype. + builder.__proto__ = proto; + return builder; +} - wrap(fn) { - var schedule, wrapped; - schedule = this.schedule; +var styles = (function() { + var ret = {}; + ansiStyles.grey = ansiStyles.gray; + Object.keys(ansiStyles).forEach(function(key) { + ansiStyles[key].closeRe = + new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g'); + ret[key] = { + get: function() { + return build(this._styles.concat(key)); + }, + }; + }); + return ret; +})(); - wrapped = function wrapped(...args) { - return schedule(fn.bind(this), ...args); - }; +var proto = defineProps(function colors() {}, styles); - wrapped.withOptions = (options, ...args) => { - return schedule(options, fn, ...args); - }; +function applyStyle() { + var args = Array.prototype.slice.call(arguments); - return wrapped; + var str = args.map(function(arg) { + // Use weak equality check so we can colorize null/undefined in safe mode + if (arg != null && arg.constructor === String) { + return arg; + } else { + return util.inspect(arg); } + }).join(' '); - updateSettings(options = {}) { - var _this3 = this; + if (!colors.enabled || !str) { + return str; + } - return _asyncToGenerator(function* () { - yield _this3._store.__updateSettings__(parser.overwrite(options, _this3.storeDefaults)); - parser.overwrite(options, _this3.instanceDefaults, _this3); - return _this3; - })(); - } + var newLinesPresent = str.indexOf('\n') != -1; - currentReservoir() { - return this._store.__currentReservoir__(); - } + var nestedStyles = this._styles; - incrementReservoir(incr = 0) { - return this._store.__incrementReservoir__(incr); + var i = nestedStyles.length; + while (i--) { + var code = ansiStyles[nestedStyles[i]]; + str = code.open + str.replace(code.closeRe, code.open) + code.close; + if (newLinesPresent) { + str = str.replace(newLineRegex, function(match) { + return code.close + match + code.open; + }); } + } + + return str; +} +colors.setTheme = function(theme) { + if (typeof theme === 'string') { + console.log('colors.setTheme now only accepts an object, not a string. ' + + 'If you are trying to set a theme from a file, it is now your (the ' + + 'caller\'s) responsibility to require the file. The old syntax ' + + 'looked like colors.setTheme(__dirname + ' + + '\'/../themes/generic-logging.js\'); The new syntax looks like '+ + 'colors.setTheme(require(__dirname + ' + + '\'/../themes/generic-logging.js\'));'); + return; + } + for (var style in theme) { + (function(style) { + colors[style] = function(str) { + if (typeof theme[style] === 'object') { + var out = str; + for (var i in theme[style]) { + out = colors[theme[style][i]](out); + } + return out; + } + return colors[theme[style]](str); + }; + })(style); } +}; - ; - Bottleneck.default = Bottleneck; - Bottleneck.Events = Events; - Bottleneck.version = Bottleneck.prototype.version = (__nccwpck_require__(82636)/* .version */ .i); - Bottleneck.strategy = Bottleneck.prototype.strategy = { - LEAK: 1, - OVERFLOW: 2, - OVERFLOW_PRIORITY: 4, - BLOCK: 3 - }; - Bottleneck.BottleneckError = Bottleneck.prototype.BottleneckError = __nccwpck_require__(93529); - Bottleneck.Group = Bottleneck.prototype.Group = __nccwpck_require__(53068); - Bottleneck.RedisConnection = Bottleneck.prototype.RedisConnection = __nccwpck_require__(29992); - Bottleneck.IORedisConnection = Bottleneck.prototype.IORedisConnection = __nccwpck_require__(47710); - Bottleneck.Batcher = Bottleneck.prototype.Batcher = __nccwpck_require__(85442); - Bottleneck.prototype.jobDefaults = { - priority: DEFAULT_PRIORITY, - weight: 1, - expiration: null, - id: "" - }; - Bottleneck.prototype.storeDefaults = { - maxConcurrent: null, - minTime: 0, - highWater: null, - strategy: Bottleneck.prototype.strategy.LEAK, - penalty: null, - reservoir: null, - reservoirRefreshInterval: null, - reservoirRefreshAmount: null - }; - Bottleneck.prototype.localStoreDefaults = { - Promise: Promise, - timeout: null, - heartbeatInterval: 250 - }; - Bottleneck.prototype.redisStoreDefaults = { - Promise: Promise, - timeout: null, - heartbeatInterval: 5000, - clientTimeout: 10000, - clientOptions: {}, - clusterNodes: null, - clearDatastore: false, - connection: null - }; - Bottleneck.prototype.instanceDefaults = { - datastore: "local", - connection: null, - id: "", - rejectOnDrop: true, - trackDoneStatus: false, - Promise: Promise - }; - Bottleneck.prototype.stopDefaults = { - enqueueErrorMessage: "This limiter has been stopped and cannot accept new jobs.", - dropWaitingJobs: true, - dropErrorMessage: "This limiter has been stopped." - }; - return Bottleneck; -}.call(void 0); +function init() { + var ret = {}; + Object.keys(styles).forEach(function(name) { + ret[name] = { + get: function() { + return build([name]); + }, + }; + }); + return ret; +} -module.exports = Bottleneck; +var sequencer = function sequencer(map, str) { + var exploded = str.split(''); + exploded = exploded.map(map); + return exploded.join(''); +}; -/***/ }), +// custom formatter methods +colors.trap = __nccwpck_require__(31302); +colors.zalgo = __nccwpck_require__(45610); -/***/ 93529: -/***/ ((module) => { +// maps +colors.maps = {}; +colors.maps.america = __nccwpck_require__(76936)(colors); +colors.maps.zebra = __nccwpck_require__(12989)(colors); +colors.maps.rainbow = __nccwpck_require__(75210)(colors); +colors.maps.random = __nccwpck_require__(13441)(colors); -"use strict"; +for (var map in colors.maps) { + (function(map) { + colors[map] = function(str) { + return sequencer(colors.maps[map], str); + }; + })(map); +} +defineProps(colors, init()); -var BottleneckError; -BottleneckError = class BottleneckError extends Error {}; -module.exports = BottleneckError; /***/ }), -/***/ 38579: +/***/ 31302: /***/ ((module) => { -"use strict"; - +module['exports'] = function runTheTrap(text, options) { + var result = ''; + text = text || 'Run the trap, drop the bass'; + text = text.split(''); + var trap = { + a: ['\u0040', '\u0104', '\u023a', '\u0245', '\u0394', '\u039b', '\u0414'], + b: ['\u00df', '\u0181', '\u0243', '\u026e', '\u03b2', '\u0e3f'], + c: ['\u00a9', '\u023b', '\u03fe'], + d: ['\u00d0', '\u018a', '\u0500', '\u0501', '\u0502', '\u0503'], + e: ['\u00cb', '\u0115', '\u018e', '\u0258', '\u03a3', '\u03be', '\u04bc', + '\u0a6c'], + f: ['\u04fa'], + g: ['\u0262'], + h: ['\u0126', '\u0195', '\u04a2', '\u04ba', '\u04c7', '\u050a'], + i: ['\u0f0f'], + j: ['\u0134'], + k: ['\u0138', '\u04a0', '\u04c3', '\u051e'], + l: ['\u0139'], + m: ['\u028d', '\u04cd', '\u04ce', '\u0520', '\u0521', '\u0d69'], + n: ['\u00d1', '\u014b', '\u019d', '\u0376', '\u03a0', '\u048a'], + o: ['\u00d8', '\u00f5', '\u00f8', '\u01fe', '\u0298', '\u047a', '\u05dd', + '\u06dd', '\u0e4f'], + p: ['\u01f7', '\u048e'], + q: ['\u09cd'], + r: ['\u00ae', '\u01a6', '\u0210', '\u024c', '\u0280', '\u042f'], + s: ['\u00a7', '\u03de', '\u03df', '\u03e8'], + t: ['\u0141', '\u0166', '\u0373'], + u: ['\u01b1', '\u054d'], + v: ['\u05d8'], + w: ['\u0428', '\u0460', '\u047c', '\u0d70'], + x: ['\u04b2', '\u04fe', '\u04fc', '\u04fd'], + y: ['\u00a5', '\u04b0', '\u04cb'], + z: ['\u01b5', '\u0240'], + }; + text.forEach(function(c) { + c = c.toLowerCase(); + var chars = trap[c] || [' ']; + var rand = Math.floor(Math.random() * chars.length); + if (typeof trap[c] !== 'undefined') { + result += trap[c][rand]; + } else { + result += c; + } + }); + return result; +}; -var DLList; -DLList = class DLList { - constructor(_queues) { - this._queues = _queues; - this._first = null; - this._last = null; - this.length = 0; - } - push(value) { - var node, ref1; - this.length++; +/***/ }), - if ((ref1 = this._queues) != null) { - ref1.incr(); - } +/***/ 45610: +/***/ ((module) => { - node = { - value, - next: null - }; +// please no +module['exports'] = function zalgo(text, options) { + text = text || ' he is here '; + var soul = { + 'up': [ + '̍', '̎', '̄', '̅', + '̿', '̑', '̆', '̐', + '͒', '͗', '͑', '̇', + '̈', '̊', '͂', '̓', + '̈', '͊', '͋', '͌', + '̃', '̂', '̌', '͐', + '̀', '́', '̋', '̏', + '̒', '̓', '̔', '̽', + '̉', 'ͣ', 'ͤ', 'ͥ', + 'ͦ', 'ͧ', 'ͨ', 'ͩ', + 'ͪ', 'ͫ', 'ͬ', 'ͭ', + 'ͮ', 'ͯ', '̾', '͛', + '͆', '̚', + ], + 'down': [ + '̖', '̗', '̘', '̙', + '̜', '̝', '̞', '̟', + '̠', '̤', '̥', '̦', + '̩', '̪', '̫', '̬', + '̭', '̮', '̯', '̰', + '̱', '̲', '̳', '̹', + '̺', '̻', '̼', 'ͅ', + '͇', '͈', '͉', '͍', + '͎', '͓', '͔', '͕', + '͖', '͙', '͚', '̣', + ], + 'mid': [ + '̕', '̛', '̀', '́', + '͘', '̡', '̢', '̧', + '̨', '̴', '̵', '̶', + '͜', '͝', '͞', + '͟', '͠', '͢', '̸', + '̷', '͡', ' ҉', + ], + }; + var all = [].concat(soul.up, soul.down, soul.mid); - if (this._last != null) { - this._last.next = node; - this._last = node; - } else { - this._first = this._last = node; - } + function randomNumber(range) { + var r = Math.floor(Math.random() * range); + return r; + } - return void 0; + function isChar(character) { + var bool = false; + all.filter(function(i) { + bool = (i === character); + }); + return bool; } - shift() { - var ref1, ref2, value; - if (this._first == null) { - return void 0; - } else { - this.length--; + function heComes(text, options) { + var result = ''; + var counts; + var l; + options = options || {}; + options['up'] = + typeof options['up'] !== 'undefined' ? options['up'] : true; + options['mid'] = + typeof options['mid'] !== 'undefined' ? options['mid'] : true; + options['down'] = + typeof options['down'] !== 'undefined' ? options['down'] : true; + options['size'] = + typeof options['size'] !== 'undefined' ? options['size'] : 'maxi'; + text = text.split(''); + for (l in text) { + if (isChar(l)) { + continue; + } + result = result + text[l]; + counts = {'up': 0, 'down': 0, 'mid': 0}; + switch (options.size) { + case 'mini': + counts.up = randomNumber(8); + counts.mid = randomNumber(2); + counts.down = randomNumber(8); + break; + case 'maxi': + counts.up = randomNumber(16) + 3; + counts.mid = randomNumber(4) + 1; + counts.down = randomNumber(64) + 3; + break; + default: + counts.up = randomNumber(8) + 1; + counts.mid = randomNumber(6) / 2; + counts.down = randomNumber(8) + 1; + break; + } - if ((ref1 = this._queues) != null) { - ref1.decr(); + var arr = ['up', 'mid', 'down']; + for (var d in arr) { + var index = arr[d]; + for (var i = 0; i <= counts[index]; i++) { + if (options[index]) { + result = result + soul[index][randomNumber(soul[index].length)]; + } + } } } - - value = this._first.value; - this._first = (ref2 = this._first.next) != null ? ref2 : this._last = null; - return value; + return result; } + // don't summon him + return heComes(text, options); +}; - first() { - if (this._first != null) { - return this._first.value; - } - } - getArray() { - var node, ref, results; - node = this._first; - results = []; - while (node != null) { - results.push((ref = node, node = node.next, ref.value)); +/***/ }), + +/***/ 76936: +/***/ ((module) => { + +module['exports'] = function(colors) { + return function(letter, i, exploded) { + if (letter === ' ') return letter; + switch (i%3) { + case 0: return colors.red(letter); + case 1: return colors.white(letter); + case 2: return colors.blue(letter); } + }; +}; - return results; - } - forEachShift(cb) { - var node; - node = this.shift(); +/***/ }), - while (node != null) { - cb(node), node = this.shift(); +/***/ 75210: +/***/ ((module) => { + +module['exports'] = function(colors) { + // RoY G BiV + var rainbowColors = ['red', 'yellow', 'green', 'blue', 'magenta']; + return function(letter, i, exploded) { + if (letter === ' ') { + return letter; + } else { + return colors[rainbowColors[i++ % rainbowColors.length]](letter); } + }; +}; - return void 0; - } + +/***/ }), + +/***/ 13441: +/***/ ((module) => { + +module['exports'] = function(colors) { + var available = ['underline', 'inverse', 'grey', 'yellow', 'red', 'green', + 'blue', 'white', 'cyan', 'magenta', 'brightYellow', 'brightRed', + 'brightGreen', 'brightBlue', 'brightWhite', 'brightCyan', 'brightMagenta']; + return function(letter, i, exploded) { + return letter === ' ' ? letter : + colors[ + available[Math.round(Math.random() * (available.length - 2))] + ](letter); + }; }; -module.exports = DLList; + /***/ }), -/***/ 107: +/***/ 12989: /***/ ((module) => { -"use strict"; +module['exports'] = function(colors) { + return function(letter, i, exploded) { + return i % 2 === 0 ? letter : colors.inverse(letter); + }; +}; -function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } +/***/ }), -function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } +/***/ 73104: +/***/ ((module) => { -var Events; -Events = class Events { - constructor(instance) { - this.instance = instance; - this._events = {}; +/* +The MIT License (MIT) - if (this.instance.on != null || this.instance.once != null || this.instance.removeAllListeners != null) { - throw new Error("An Emitter already exists for this object"); - } +Copyright (c) Sindre Sorhus (sindresorhus.com) - this.instance.on = (name, cb) => { - return this._addListener(name, "many", cb); - }; +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: - this.instance.once = (name, cb) => { - return this._addListener(name, "once", cb); - }; +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. - this.instance.removeAllListeners = (name = null) => { - if (name != null) { - return delete this._events[name]; - } else { - return this._events = {}; - } - }; - } +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. - _addListener(name, status, cb) { - var base; +*/ - if ((base = this._events)[name] == null) { - base[name] = []; - } +var styles = {}; +module['exports'] = styles; - this._events[name].push({ - cb, - status - }); +var codes = { + reset: [0, 0], - return this.instance; - } + bold: [1, 22], + dim: [2, 22], + italic: [3, 23], + underline: [4, 24], + inverse: [7, 27], + hidden: [8, 28], + strikethrough: [9, 29], - listenerCount(name) { - if (this._events[name] != null) { - return this._events[name].length; - } else { - return 0; - } - } + black: [30, 39], + red: [31, 39], + green: [32, 39], + yellow: [33, 39], + blue: [34, 39], + magenta: [35, 39], + cyan: [36, 39], + white: [37, 39], + gray: [90, 39], + grey: [90, 39], - trigger(name, ...args) { - var _this = this; + brightRed: [91, 39], + brightGreen: [92, 39], + brightYellow: [93, 39], + brightBlue: [94, 39], + brightMagenta: [95, 39], + brightCyan: [96, 39], + brightWhite: [97, 39], - return _asyncToGenerator(function* () { - var e, promises; + bgBlack: [40, 49], + bgRed: [41, 49], + bgGreen: [42, 49], + bgYellow: [43, 49], + bgBlue: [44, 49], + bgMagenta: [45, 49], + bgCyan: [46, 49], + bgWhite: [47, 49], + bgGray: [100, 49], + bgGrey: [100, 49], - try { - if (name !== "debug") { - _this.trigger("debug", `Event triggered: ${name}`, args); - } + bgBrightRed: [101, 49], + bgBrightGreen: [102, 49], + bgBrightYellow: [103, 49], + bgBrightBlue: [104, 49], + bgBrightMagenta: [105, 49], + bgBrightCyan: [106, 49], + bgBrightWhite: [107, 49], - if (_this._events[name] == null) { - return; - } + // legacy styles for colors pre v1.0.0 + blackBG: [40, 49], + redBG: [41, 49], + greenBG: [42, 49], + yellowBG: [43, 49], + blueBG: [44, 49], + magentaBG: [45, 49], + cyanBG: [46, 49], + whiteBG: [47, 49], - _this._events[name] = _this._events[name].filter(function (listener) { - return listener.status !== "none"; - }); - promises = _this._events[name].map( - /*#__PURE__*/ - function () { - var _ref = _asyncToGenerator(function* (listener) { - var e, returned; +}; - if (listener.status === "none") { - return; - } +Object.keys(codes).forEach(function(key) { + var val = codes[key]; + var style = styles[key] = []; + style.open = '\u001b[' + val[0] + 'm'; + style.close = '\u001b[' + val[1] + 'm'; +}); - if (listener.status === "once") { - listener.status = "none"; - } - try { - returned = typeof listener.cb === "function" ? listener.cb(...args) : void 0; +/***/ }), - if (typeof (returned != null ? returned.then : void 0) === "function") { - return yield returned; - } else { - return returned; - } - } catch (error) { - e = error; +/***/ 10223: +/***/ ((module) => { - if (true) { - _this.trigger("error", e); - } +"use strict"; +/* +MIT License - return null; - } - }); +Copyright (c) Sindre Sorhus (sindresorhus.com) - return function (_x) { - return _ref.apply(this, arguments); - }; - }()); - return (yield Promise.all(promises)).find(function (x) { - return x != null; - }); - } catch (error) { - e = error; +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: - if (true) { - _this.trigger("error", e); - } +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. - return null; - } - })(); - } +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. +*/ + + + +module.exports = function(flag, argv) { + argv = argv || process.argv; + + var terminatorPos = argv.indexOf('--'); + var prefix = /^-{1,2}/.test(flag) ? '' : '--'; + var pos = argv.indexOf(prefix + flag); + return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos); }; -module.exports = Events; + /***/ }), -/***/ 53068: +/***/ 10662: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; +/* +The MIT License (MIT) +Copyright (c) Sindre Sorhus (sindresorhus.com) -function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } +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: -function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. -function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } +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 _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } +*/ -function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } -function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } -var Events, Group, IORedisConnection, RedisConnection, Scripts, parser; -parser = __nccwpck_require__(67823); -Events = __nccwpck_require__(107); -RedisConnection = __nccwpck_require__(29992); -IORedisConnection = __nccwpck_require__(47710); -Scripts = __nccwpck_require__(4169); +var os = __nccwpck_require__(22037); +var hasFlag = __nccwpck_require__(10223); -Group = function () { - class Group { - constructor(limiterOptions = {}) { - this.deleteKey = this.deleteKey.bind(this); - this.updateSettings = this.updateSettings.bind(this); - this.limiterOptions = limiterOptions; - parser.load(this.limiterOptions, this.defaults, this); - this.Events = new Events(this); - this.instances = {}; - this.Bottleneck = __nccwpck_require__(83911); +var env = process.env; - this._startAutoCleanup(); +var forceColor = void 0; +if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false')) { + forceColor = false; +} else if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true') + || hasFlag('color=always')) { + forceColor = true; +} +if ('FORCE_COLOR' in env) { + forceColor = env.FORCE_COLOR.length === 0 + || parseInt(env.FORCE_COLOR, 10) !== 0; +} - this.sharedConnection = this.connection != null; +function translateLevel(level) { + if (level === 0) { + return false; + } - if (this.connection == null) { - if (this.limiterOptions.datastore === "redis") { - this.connection = new RedisConnection(Object.assign({}, this.limiterOptions, { - Events: this.Events - })); - } else if (this.limiterOptions.datastore === "ioredis") { - this.connection = new IORedisConnection(Object.assign({}, this.limiterOptions, { - Events: this.Events - })); - } - } - } + return { + level: level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3, + }; +} - key(key = "") { - var ref; - return (ref = this.instances[key]) != null ? ref : (() => { - var limiter; - limiter = this.instances[key] = new this.Bottleneck(Object.assign(this.limiterOptions, { - id: `${this.id}-${key}`, - timeout: this.timeout, - connection: this.connection - })); - this.Events.trigger("created", limiter, key); - return limiter; - })(); - } +function supportsColor(stream) { + if (forceColor === false) { + return 0; + } - deleteKey(key = "") { - var _this = this; + if (hasFlag('color=16m') || hasFlag('color=full') + || hasFlag('color=truecolor')) { + return 3; + } - return _asyncToGenerator(function* () { - var deleted, instance; - instance = _this.instances[key]; + if (hasFlag('color=256')) { + return 2; + } - if (_this.connection) { - deleted = yield _this.connection.__runCommand__(['del', ...Scripts.allKeys(`${_this.id}-${key}`)]); - } + if (stream && !stream.isTTY && forceColor !== true) { + return 0; + } - if (instance != null) { - delete _this.instances[key]; - yield instance.disconnect(); - } + var min = forceColor ? 1 : 0; - return instance != null || deleted > 0; - })(); + if (process.platform === 'win32') { + // Node.js 7.5.0 is the first version of Node.js to include a patch to + // libuv that enables 256 color output on Windows. Anything earlier and it + // won't work. However, here we target Node.js 8 at minimum as it is an LTS + // release, and Node.js 7 is not. Windows 10 build 10586 is the first + // Windows release that supports 256 colors. Windows 10 build 14931 is the + // first release that supports 16m/TrueColor. + var osRelease = os.release().split('.'); + if (Number(process.versions.node.split('.')[0]) >= 8 + && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) { + return Number(osRelease[2]) >= 14931 ? 3 : 2; } - limiters() { - var k, ref, results, v; - ref = this.instances; - results = []; - - for (k in ref) { - v = ref[k]; - results.push({ - key: k, - limiter: v - }); - } + return 1; + } - return results; + if ('CI' in env) { + if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(function(sign) { + return sign in env; + }) || env.CI_NAME === 'codeship') { + return 1; } - keys() { - return Object.keys(this.instances); + return min; + } + + if ('TEAMCITY_VERSION' in env) { + return (/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0 + ); + } + + if ('TERM_PROGRAM' in env) { + var version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); + + switch (env.TERM_PROGRAM) { + case 'iTerm.app': + return version >= 3 ? 3 : 2; + case 'Hyper': + return 3; + case 'Apple_Terminal': + return 2; + // No default } + } - clusterKeys() { - var _this2 = this; + if (/-256(color)?$/i.test(env.TERM)) { + return 2; + } - return _asyncToGenerator(function* () { - var cursor, end, found, i, k, keys, len, next, start; + if (/^screen|^xterm|^vt100|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { + return 1; + } - if (_this2.connection == null) { - return _this2.Promise.resolve(_this2.keys()); - } + if ('COLORTERM' in env) { + return 1; + } - keys = []; - cursor = null; - start = `b_${_this2.id}-`.length; - end = "_settings".length; + if (env.TERM === 'dumb') { + return min; + } - while (cursor !== 0) { - var _ref = yield _this2.connection.__runCommand__(["scan", cursor != null ? cursor : 0, "match", `b_${_this2.id}-*_settings`, "count", 10000]); + return min; +} - var _ref2 = _slicedToArray(_ref, 2); +function getSupportLevel(stream) { + var level = supportsColor(stream); + return translateLevel(level); +} - next = _ref2[0]; - found = _ref2[1]; - cursor = ~~next; +module.exports = { + supportsColor: getSupportLevel, + stdout: getSupportLevel(process.stdout), + stderr: getSupportLevel(process.stderr), +}; - for (i = 0, len = found.length; i < len; i++) { - k = found[i]; - keys.push(k.slice(start, -end)); - } - } - return keys; - })(); - } +/***/ }), - _startAutoCleanup() { - var _this3 = this; +/***/ 41997: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - var base; - clearInterval(this.interval); - return typeof (base = this.interval = setInterval( - /*#__PURE__*/ - _asyncToGenerator(function* () { - var e, k, ref, results, time, v; - time = Date.now(); - ref = _this3.instances; - results = []; +// +// Remark: Requiring this file will use the "safe" colors API, +// which will not touch String.prototype. +// +// var colors = require('colors/safe'); +// colors.red("foo") +// +// +var colors = __nccwpck_require__(43595); +module['exports'] = colors; - for (k in ref) { - v = ref[k]; - try { - if (yield v._store.__groupCheck__(time)) { - results.push(_this3.deleteKey(k)); - } else { - results.push(void 0); - } - } catch (error) { - e = error; - results.push(v.Events.trigger("error", e)); - } - } +/***/ }), - return results; - }), this.timeout / 2)).unref === "function" ? base.unref() : void 0; - } +/***/ 61904: +/***/ ((module, exports, __nccwpck_require__) => { - updateSettings(options = {}) { - parser.overwrite(options, this.defaults, this); - parser.overwrite(options, options, this.limiterOptions); +/** + * Module dependencies. + */ - if (options.timeout != null) { - return this._startAutoCleanup(); - } +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; + } - disconnect(flush = true) { - var ref; + /** + * Return option name. + * + * @return {string} + * @api private + */ - if (!this.sharedConnection) { - return (ref = this.connection) != null ? ref.disconnect(flush) : void 0; - } + 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 + */ - ; - Group.prototype.defaults = { - timeout: 1000 * 60 * 5, - connection: null, - Promise: Promise, - id: "group-key" + attributeName() { + return camelcase(this.name().replace(/^no-/, '')); }; - return Group; -}.call(void 0); -module.exports = Group; + /** + * 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; + }; +} -/***/ 47710: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/** + * 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; + } +} -"use strict"; +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'; + } -function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } + /** + * 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); + }; -function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } + /** + * 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 + */ -function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } + addCommand(cmd, opts) { + if (!cmd._name) throw new Error('Command passed to .addCommand() must have a name'); -function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } + // 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); -function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } + opts = opts || {}; + if (opts.isDefault) this._defaultCommandName = cmd._name; + if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation -function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } + this.commands.push(cmd); + cmd.parent = this; + return this; + }; -var Events, IORedisConnection, Scripts, parser; -parser = __nccwpck_require__(67823); -Events = __nccwpck_require__(107); -Scripts = __nccwpck_require__(4169); + /** + * Define argument syntax for the command. + * + * @api public + */ -IORedisConnection = function () { - class IORedisConnection { - constructor(options = {}) { - var Redis; - Redis = eval("require")("ioredis"); // Obfuscated or else Webpack/Angular will try to inline the optional ioredis module + arguments(desc) { + return this._parseExpectedArgs(desc.split(/ +/)); + }; - parser.load(options, this.defaults, this); + /** + * 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 + */ - if (this.Events == null) { - this.Events = new Events(this); + 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; + }; - this.terminated = false; + /** + * @return {boolean} + * @api private + */ - if (this.clusterNodes != null) { - this.client = new Redis.Cluster(this.clusterNodes, this.clientOptions); - this.subscriber = new Redis.Cluster(this.clusterNodes, this.clientOptions); - } else { - if (this.client == null) { - this.client = new Redis(this.clientOptions); - } + _lazyHasImplicitHelpCommand() { + if (this._hasImplicitHelpCommand === undefined) { + this._hasImplicitHelpCommand = this.commands.length && !this._actionHandler && !this._findCommand('help'); + } + return this._hasImplicitHelpCommand; + }; - this.subscriber = this.client.duplicate(); - } + /** + * Parse expected `args`. + * + * For example `["[type]"]` becomes `[{ required: false, name: 'type' }]`. + * + * @param {Array} args + * @return {Command} `this` command for chaining + * @api private + */ - this.limiters = {}; - this.ready = this.Promise.all([this._setup(this.client, false), this._setup(this.subscriber, true)]).then(() => { - this._loadScripts(); + _parseExpectedArgs(args) { + if (!args.length) return; + args.forEach((arg) => { + const argDetails = { + required: false, + name: '', + variadic: false + }; - return { - client: this.client, - subscriber: this.subscriber - }; - }); - } + switch (arg[0]) { + case '<': + argDetails.required = true; + argDetails.name = arg.slice(1, -1); + break; + case '[': + argDetails.name = arg.slice(1, -1); + break; + } - _setup(client, sub) { - client.setMaxListeners(0); - return new this.Promise((resolve, reject) => { - client.on("error", e => { - return this.Events.trigger("error", e); - }); + 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; + }; - if (sub) { - client.on("message", (channel, message) => { - var ref; - return (ref = this.limiters[channel]) != null ? ref._store.onMessage(channel, message) : void 0; - }); - } + /** + * 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 + */ - if (client.status === "ready") { - return resolve(); + exitOverride(fn) { + if (fn) { + this._exitCallback = fn; + } else { + this._exitCallback = (err) => { + if (err.code !== 'commander.executeSubCommandAsync') { + throw err; } else { - return client.once("ready", resolve); + // Async callback from spawn events, not useful to throw. } - }); + }; } + return this; + }; - _loadScripts() { - return Scripts.names.forEach(name => { - return this.client.defineCommand(name, { - lua: Scripts.payload(name) - }); - }); + /** + * 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); + }; - __runCommand__(cmd) { - var _this = this; + /** + * 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 + */ - return _asyncToGenerator(function* () { - var _, deleted; + 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)); + } - yield _this.ready; + 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 _ref = yield _this.client.pipeline([cmd]).exec(); + /** + * Internal routine to check whether there is a clash storing option value with a Command property. + * + * @param {Option} option + * @api private + */ - var _ref2 = _slicedToArray(_ref, 1); + _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 _ref2$ = _slicedToArray(_ref2[0], 2); + const commandProperty = this._getOptionValue(option.attributeName()); + if (commandProperty === undefined) { + // no clash + return; + } - _ = _ref2$[0]; - deleted = _ref2$[1]; - return deleted; - })(); + 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); } - __addLimiter__(instance) { - return this.Promise.all([instance.channel(), instance.channel_client()].map(channel => { - return new this.Promise((resolve, reject) => { - return this.subscriber.subscribe(channel, () => { - this.limiters[channel] = instance; - return resolve(); - }); - }); - })); + 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`); } + }; - __removeLimiter__(instance) { - var _this2 = this; + /** + * 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 + */ - return [instance.channel(), instance.channel_client()].forEach( - /*#__PURE__*/ - function () { - var _ref3 = _asyncToGenerator(function* (channel) { - if (!_this2.terminated) { - yield _this2.subscriber.unsubscribe(channel); - } + _optionEx(config, flags, description, fn, defaultValue) { + const option = new Option(flags, description); + const oname = option.name(); + const name = option.attributeName(); + option.mandatory = !!config.mandatory; - return delete _this2.limiters[channel]; - }); + this._checkForOptionNameClash(option); - return function (_x) { - return _ref3.apply(this, arguments); + // 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; + } } - __scriptArgs__(name, id, args, cb) { - var keys; - keys = Scripts.keys(name, id); - return [keys.length].concat(keys, args, cb); + // 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; + } } - __scriptFn__(name) { - return this.client[name].bind(this.client); - } + // register the option + this.options.push(option); - disconnect(flush = true) { - var i, k, len, ref; - ref = Object.keys(this.limiters); + // when it's passed assign the value + // and conditionally invoke the callback + this.on('option:' + oname, (val) => { + const oldValue = this._getOptionValue(name); - for (i = 0, len = ref.length; i < len; i++) { - k = ref[i]; - clearInterval(this.limiters[k]._store.heartbeat); + // 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); + } } - this.limiters = {}; - this.terminated = true; - - if (flush) { - return this.Promise.all([this.client.quit(), this.subscriber.quit()]); - } else { - this.client.disconnect(); - this.subscriber.disconnect(); - return this.Promise.resolve(); + // 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); } - } - - } + }); - ; - IORedisConnection.prototype.datastore = "ioredis"; - IORedisConnection.prototype.defaults = { - clientOptions: {}, - clusterNodes: null, - client: null, - Promise: Promise, - Events: null + return this; }; - return IORedisConnection; -}.call(void 0); -module.exports = IORedisConnection; + /** + * 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); + }; -/***/ 38979: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + /** + * 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 + */ -"use strict"; + 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; + }; -function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } + /** + * 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; + }; -function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } + /** + * 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 + */ -var BottleneckError, LocalDatastore, parser; -parser = __nccwpck_require__(67823); -BottleneckError = __nccwpck_require__(93529); -LocalDatastore = class LocalDatastore { - constructor(instance, storeOptions, storeInstanceOptions) { - this.instance = instance; - this.storeOptions = storeOptions; - this.clientId = this.instance._randomIndex(); - parser.load(storeInstanceOptions, storeInstanceOptions, this); - this._nextRequest = this._lastReservoirRefresh = Date.now(); - this._running = 0; - this._done = 0; - this._unblockTime = 0; - this.ready = this.Promise.resolve(); - this.clients = {}; + storeOptionsAsProperties(value) { + this._storeOptionsAsPropertiesCalled = true; + this._storeOptionsAsProperties = (value === undefined) || value; + if (this.options.length) { + throw new Error('call .storeOptionsAsProperties() before adding options'); + } + return this; + }; - this._startHeartbeat(); - } + /** + * Whether to pass command to action handler, + * or just the options (specify false). + * + * @param {boolean} value + * @return {Command} `this` command for chaining + * @api public + */ - _startHeartbeat() { - var base; + passCommandToAction(value) { + this._passCommandToAction = (value === undefined) || value; + return this; + }; - if (this.heartbeat == null && this.storeOptions.reservoirRefreshInterval != null && this.storeOptions.reservoirRefreshAmount != null) { - return typeof (base = this.heartbeat = setInterval(() => { - var now; - now = Date.now(); + /** + * Store option value + * + * @param {string} key + * @param {Object} value + * @api private + */ - if (now >= this._lastReservoirRefresh + this.storeOptions.reservoirRefreshInterval) { - this.storeOptions.reservoir = this.storeOptions.reservoirRefreshAmount; - this._lastReservoirRefresh = now; - return this.instance._drainAll(this.computeCapacity()); - } - }, this.heartbeatInterval)).unref === "function" ? base.unref() : void 0; + _setOptionValue(key, value) { + if (this._storeOptionsAsProperties) { + this[key] = value; } else { - return clearInterval(this.heartbeat); + this._optionValues[key] = value; } - } - - __publish__(message) { - var _this = this; - - return _asyncToGenerator(function* () { - yield _this.yieldLoop(); - return _this.instance.Events.trigger("message", message.toString()); - })(); - } - - __disconnect__(flush) { - var _this2 = this; + }; - return _asyncToGenerator(function* () { - yield _this2.yieldLoop(); - clearInterval(_this2.heartbeat); - return _this2.Promise.resolve(); - })(); - } + /** + * Retrieve option value + * + * @param {string} key + * @return {Object} value + * @api private + */ - yieldLoop(t = 0) { - return new this.Promise(function (resolve, reject) { - return setTimeout(resolve, t); - }); - } + _getOptionValue(key) { + if (this._storeOptionsAsProperties) { + return this[key]; + } + return this._optionValues[key]; + }; - computePenalty() { - var ref; - return (ref = this.storeOptions.penalty) != null ? ref : 15 * this.storeOptions.minTime || 5000; - } + /** + * 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 + */ - __updateSettings__(options) { - var _this3 = this; + parse(argv, parseOptions) { + if (argv !== undefined && !Array.isArray(argv)) { + throw new Error('first parameter to parse must be array or undefined'); + } + parseOptions = parseOptions || {}; - return _asyncToGenerator(function* () { - yield _this3.yieldLoop(); - parser.overwrite(options, options, _this3.storeOptions); + // 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(); - _this3._startHeartbeat(); + // 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; + } - _this3.instance._drainAll(_this3.computeCapacity()); + // Guess name, used in usage in help. + this._name = this._name || (this._scriptPath && path.basename(this._scriptPath, path.extname(this._scriptPath))); - return true; - })(); - } + // Let's go! + this._parseCommand([], userArgs); - __running__() { - var _this4 = this; + return this; + }; - return _asyncToGenerator(function* () { - yield _this4.yieldLoop(); - return _this4._running; - })(); - } + /** + * 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 + */ - __queued__() { - var _this5 = this; + parseAsync(argv, parseOptions) { + this.parse(argv, parseOptions); + return Promise.all(this._actionResults).then(() => this); + }; - return _asyncToGenerator(function* () { - yield _this5.yieldLoop(); - return _this5.instance.queued(); - })(); - } + /** + * Execute a sub-command executable. + * + * @api private + */ - __done__() { - var _this6 = this; + _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']; - return _asyncToGenerator(function* () { - yield _this6.yieldLoop(); - return _this6._done; - })(); - } + // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command. + this._checkForMissingMandatoryOptions(); - __groupCheck__(time) { - var _this7 = this; + // 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; + } - return _asyncToGenerator(function* () { - yield _this7.yieldLoop(); - return _this7._nextRequest + _this7.timeout < time; - })(); - } + let baseDir; + try { + const resolvedLink = fs.realpathSync(scriptPath); + baseDir = path.dirname(resolvedLink); + } catch (e) { + baseDir = '.'; // dummy, probably not going to find executable! + } - computeCapacity() { - var maxConcurrent, reservoir; - var _this$storeOptions = this.storeOptions; - maxConcurrent = _this$storeOptions.maxConcurrent; - reservoir = _this$storeOptions.reservoir; + // name of the subcommand, like `pm-install` + let bin = path.basename(scriptPath, path.extname(scriptPath)) + '-' + subcommand._name; + if (subcommand._executableFile) { + bin = subcommand._executableFile; + } - if (maxConcurrent != null && reservoir != null) { - return Math.min(maxConcurrent - this._running, reservoir); - } else if (maxConcurrent != null) { - return maxConcurrent - this._running; - } else if (reservoir != null) { - return reservoir; + const localBin = path.join(baseDir, bin); + if (fs.existsSync(localBin)) { + // prefer local `./` to bin in the $PATH + bin = localBin; } else { - return null; + // Look for source files. + sourceExt.forEach((ext) => { + if (fs.existsSync(`${localBin}${ext}`)) { + bin = `${localBin}${ext}`; + } + }); } - } - - conditionsCheck(weight) { - var capacity; - capacity = this.computeCapacity(); - return capacity == null || weight <= capacity; - } - - __incrementReservoir__(incr) { - var _this8 = this; + launchWithNode = sourceExt.includes(path.extname(bin)); - return _asyncToGenerator(function* () { - var reservoir; - yield _this8.yieldLoop(); - reservoir = _this8.storeOptions.reservoir += incr; + let proc; + if (process.platform !== 'win32') { + if (launchWithNode) { + args.unshift(bin); + // add executable arguments to spawn + args = incrementNodeInspectorPort(process.execArgv).concat(args); - _this8.instance._drainAll(_this8.computeCapacity()); + 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' }); + } - return reservoir; - })(); - } + 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); + } + }); + }); - __currentReservoir__() { - var _this9 = this; + // 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); + } + }); - return _asyncToGenerator(function* () { - yield _this9.yieldLoop(); - return _this9.storeOptions.reservoir; - })(); - } + // Store the reference to the child process + this.runningCommand = proc; + }; - isBlocked(now) { - return this._unblockTime >= now; - } + /** + * @api private + */ + _dispatchSubcommand(commandName, operands, unknown) { + const subCommand = this._findCommand(commandName); + if (!subCommand) this._helpAndError(); - check(weight, now) { - return this.conditionsCheck(weight) && this._nextRequest - now <= 0; - } + if (subCommand._executableHandler) { + this._executeSubCommand(subCommand, operands.concat(unknown)); + } else { + subCommand._parseCommand(operands, unknown); + } + }; - __check__(weight) { - var _this10 = this; + /** + * Process arguments in context of this command. + * + * @api private + */ - return _asyncToGenerator(function* () { - var now; - yield _this10.yieldLoop(); - now = Date.now(); - return _this10.check(weight, now); - })(); - } + _parseCommand(operands, unknown) { + const parsed = this.parseOptions(unknown); + operands = operands.concat(parsed.operands); + unknown = parsed.unknown; + this.args = operands.concat(unknown); - __register__(index, weight, expiration) { - var _this11 = this; + 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(); + } - return _asyncToGenerator(function* () { - var now, wait; - yield _this11.yieldLoop(); - now = Date.now(); + outputHelpIfRequested(this, parsed.unknown); + this._checkForMissingMandatoryOptions(); + if (parsed.unknown.length > 0) { + this.unknownOption(parsed.unknown[0]); + } - if (_this11.conditionsCheck(weight)) { - _this11._running += weight; + 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); + } + }); - if (_this11.storeOptions.reservoir != null) { - _this11.storeOptions.reservoir -= weight; + 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(); } - - wait = Math.max(_this11._nextRequest - now, 0); - _this11._nextRequest = now + wait + _this11.storeOptions.minTime; - return { - success: true, - wait, - reservoir: _this11.storeOptions.reservoir - }; + } else if (this.commands.length) { + // This command has subcommands and nothing hooked up at this level, so display help. + this._helpAndError(); } else { - return { - success: false - }; + // fall through for caller to handle after calling .parse() } - })(); - } - - strategyIsBlock() { - return this.storeOptions.strategy === 3; - } + } + }; - __submit__(queueLength, weight) { - var _this12 = this; + /** + * Find matching command. + * + * @api private + */ + _findCommand(name) { + if (!name) return undefined; + return this.commands.find(cmd => cmd._name === name || cmd._aliases.includes(name)); + }; - return _asyncToGenerator(function* () { - var blocked, now, reachedHWM; - yield _this12.yieldLoop(); + /** + * Return an option matching `arg` if any. + * + * @param {string} arg + * @return {Option} + * @api private + */ - if (_this12.storeOptions.maxConcurrent != null && weight > _this12.storeOptions.maxConcurrent) { - throw new BottleneckError(`Impossible to add a job having a weight of ${weight} to a limiter having a maxConcurrent setting of ${_this12.storeOptions.maxConcurrent}`); - } + _findOption(arg) { + return this.options.find(option => option.is(arg)); + }; - now = Date.now(); - reachedHWM = _this12.storeOptions.highWater != null && queueLength === _this12.storeOptions.highWater && !_this12.check(weight, now); - blocked = _this12.strategyIsBlock() && (reachedHWM || _this12.isBlocked(now)); + /** + * 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 + */ - if (blocked) { - _this12._unblockTime = now + _this12.computePenalty(); - _this12._nextRequest = _this12._unblockTime + _this12.storeOptions.minTime; + _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); + } + }); + } + }; - _this12.instance._dropAllQueued(); - } + /** + * 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 + */ - return { - reachedHWM, - blocked, - strategy: _this12.storeOptions.strategy - }; - })(); - } + 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(); - __free__(index, weight) { - var _this13 = this; + function maybeOption(arg) { + return arg.length > 1 && arg[0] === '-'; + } - return _asyncToGenerator(function* () { - yield _this13.yieldLoop(); - _this13._running -= weight; - _this13._done += weight; + // parse options + let activeVariadicOption = null; + while (args.length) { + const arg = args.shift(); - _this13.instance._drainAll(_this13.computeCapacity()); + // literal + if (arg === '--') { + if (dest === unknown) dest.push(arg); + dest.push(...args); + break; + } - return { - running: _this13._running - }; - })(); - } + if (activeVariadicOption && !maybeOption(arg)) { + this.emit(`option:${activeVariadicOption.name()}`, arg); + continue; + } + activeVariadicOption = null; -}; -module.exports = LocalDatastore; + 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; + } + } -/***/ 65893: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // 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; + } + } -"use strict"; + // looks like an option but unknown, unknowns from here + if (arg.length > 1 && arg[0] === '-') { + dest = unknown; + } + // add arg + dest.push(arg); + } -var DLList, Events, Queues; -DLList = __nccwpck_require__(38579); -Events = __nccwpck_require__(107); -Queues = class Queues { - constructor(num_priorities) { - var i; - this.Events = new Events(this); - this._length = 0; + return { operands, unknown }; + }; - this._lists = function () { - var j, ref, results; - results = []; + /** + * 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 (i = j = 1, ref = num_priorities; 1 <= ref ? j <= ref : j >= ref; i = 1 <= ref ? ++j : --j) { - results.push(new DLList(this)); + 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 results; - }.call(this); - } + return this._optionValues; + }; - incr() { - if (this._length++ === 0) { - return this.Events.trigger("leftzero"); - } - } + /** + * Argument `name` is missing. + * + * @param {string} name + * @api private + */ - decr() { - if (--this._length === 0) { - return this.Events.trigger("zero"); - } - } + missingArgument(name) { + const message = `error: missing required argument '${name}'`; + console.error(message); + this._exit(1, 'commander.missingArgument', message); + }; - push(priority, job) { - return this._lists[priority].push(job); - } + /** + * `Option` is missing an argument, but received `flag` or nothing. + * + * @param {Option} option + * @param {string} [flag] + * @api private + */ - queued(priority) { - if (priority != null) { - return this._lists[priority].length; + optionMissingArgument(option, flag) { + let message; + if (flag) { + message = `error: option '${option.flags}' argument missing, got '${flag}'`; } else { - return this._length; + message = `error: option '${option.flags}' argument missing`; } - } + console.error(message); + this._exit(1, 'commander.optionMissingArgument', message); + }; - shiftAll(fn) { - return this._lists.forEach(function (list) { - return list.forEachShift(fn); - }); - } + /** + * `Option` does not have a value, and is a mandatory option. + * + * @param {Option} option + * @api private + */ - getFirst(arr = this._lists) { - var j, len, list; + missingMandatoryOptionValue(option) { + const message = `error: required option '${option.flags}' not specified`; + console.error(message); + this._exit(1, 'commander.missingMandatoryOptionValue', message); + }; - for (j = 0, len = arr.length; j < len; j++) { - list = arr[j]; + /** + * Unknown option `flag`. + * + * @param {string} flag + * @api private + */ - if (list.length > 0) { - return list; - } - } + unknownOption(flag) { + if (this._allowUnknownOption) return; + const message = `error: unknown option '${flag}'`; + console.error(message); + this._exit(1, 'commander.unknownOption', message); + }; - return []; - } + /** + * Unknown command. + * + * @api private + */ - shiftLastFrom(priority) { - return this.getFirst(this._lists.slice(priority).reverse()).shift(); - } + 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); + }; -}; -module.exports = Queues; + /** + * 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; + }; -/***/ 29992: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + /** + * Set the description to `str`. + * + * @param {string} str + * @param {Object} [argsDescription] + * @return {string|Command} + * @api public + */ -"use strict"; + description(str, argsDescription) { + if (str === undefined && argsDescription === undefined) return this._description; + this._description = str; + this._argsDescription = argsDescription; + return this; + }; + /** + * 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 + */ -function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } + alias(alias) { + if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility -function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } + 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]; + } -var Events, RedisConnection, Scripts, parser; -parser = __nccwpck_require__(67823); -Events = __nccwpck_require__(107); -Scripts = __nccwpck_require__(4169); + if (alias === command._name) throw new Error('Command alias can\'t be the same as its name'); -RedisConnection = function () { - class RedisConnection { - constructor(options = {}) { - var Redis; - Redis = eval("require")("redis"); // Obfuscated or else Webpack/Angular will try to inline the optional redis module + command._aliases.push(alias); + return this; + }; - parser.load(options, this.defaults, this); + /** + * Set aliases for the command. + * + * Only the first alias is shown in the auto-generated help. + * + * @param {string[]} [aliases] + * @return {string[]|Command} + * @api public + */ - if (this.Events == null) { - this.Events = new Events(this); - } + 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; - this.terminated = false; + aliases.forEach((alias) => this.alias(alias)); + return this; + }; - if (this.client == null) { - this.client = Redis.createClient(this.clientOptions); - } + /** + * Set / get the command usage `str`. + * + * @param {string} [str] + * @return {String|Command} + * @api public + */ - this.subscriber = this.client.duplicate(); - this.limiters = {}; - this.shas = {}; - this.ready = this.Promise.all([this._setup(this.client, false), this._setup(this.subscriber, true)]).then(() => { - return this._loadScripts(); - }).then(() => { - return { - client: this.client, - subscriber: this.subscriber - }; + 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(' '); } - _setup(client, sub) { - client.setMaxListeners(0); - return new this.Promise((resolve, reject) => { - client.on("error", e => { - return this.Events.trigger("error", e); - }); - - if (sub) { - client.on("message", (channel, message) => { - var ref; - return (ref = this.limiters[channel]) != null ? ref._store.onMessage(channel, message) : void 0; - }); - } + this._usage = str; + return this; + }; - if (client.ready) { - return resolve(); - } else { - return client.once("ready", resolve); - } - }); - } + /** + * Get or set the name of the command + * + * @param {string} [str] + * @return {String|Command} + * @api public + */ - _loadScript(name) { - return new this.Promise((resolve, reject) => { - var payload; - payload = Scripts.payload(name); - return this.client.multi([["script", "load", payload]]).exec((err, replies) => { - if (err != null) { - return reject(err); - } + name(str) { + if (str === undefined) return this._name; + this._name = str; + return this; + }; - this.shas[name] = replies[0]; - return resolve(replies[0]); - }); - }); - } + /** + * Return prepared commands. + * + * @return {Array} + * @api private + */ - _loadScripts() { - return this.Promise.all(Scripts.names.map(k => { - return this._loadScript(k); - })); - } + prepareCommands() { + const commandDetails = this.commands.filter((cmd) => { + return !cmd._hidden; + }).map((cmd) => { + const args = cmd._args.map((arg) => { + return humanReadableArgName(arg); + }).join(' '); - __runCommand__(cmd) { - var _this = this; + return [ + cmd._name + + (cmd._aliases[0] ? '|' + cmd._aliases[0] : '') + + (cmd.options.length ? ' [options]' : '') + + (args ? ' ' + args : ''), + cmd._description + ]; + }); - return _asyncToGenerator(function* () { - yield _this.ready; - return new _this.Promise((resolve, reject) => { - return _this.client.multi([cmd]).exec_atomic(function (err, replies) { - if (err != null) { - return reject(err); - } else { - return resolve(replies[0]); - } - }); - }); - })(); + if (this._lazyHasImplicitHelpCommand()) { + commandDetails.push([this._helpCommandnameAndArgs, this._helpCommandDescription]); } + return commandDetails; + }; + + /** + * Return the largest command length. + * + * @return {number} + * @api private + */ - __addLimiter__(instance) { - return this.Promise.all([instance.channel(), instance.channel_client()].map(channel => { - return new this.Promise((resolve, reject) => { - var handler; + largestCommandLength() { + const commands = this.prepareCommands(); + return commands.reduce((max, command) => { + return Math.max(max, command[0].length); + }, 0); + }; - handler = chan => { - if (chan === channel) { - this.subscriber.removeListener("subscribe", handler); - this.limiters[channel] = instance; - return resolve(); - } - }; + /** + * Return the largest option length. + * + * @return {number} + * @api private + */ - this.subscriber.on("subscribe", handler); - return this.subscriber.subscribe(channel); - }); - })); - } + largestOptionLength() { + const options = [].slice.call(this.options); + options.push({ + flags: this._helpFlags + }); - __removeLimiter__(instance) { - var _this2 = this; + return options.reduce((max, option) => { + return Math.max(max, option.flags.length); + }, 0); + }; - return this.Promise.all([instance.channel(), instance.channel_client()].map( - /*#__PURE__*/ - function () { - var _ref = _asyncToGenerator(function* (channel) { - if (!_this2.terminated) { - yield new _this2.Promise((resolve, reject) => { - return _this2.subscriber.unsubscribe(channel, function (err, chan) { - if (err != null) { - return reject(err); - } + /** + * Return the largest arg length. + * + * @return {number} + * @api private + */ - if (chan === channel) { - return resolve(); - } - }); - }); - } + largestArgLength() { + return this._args.reduce((max, arg) => { + return Math.max(max, arg.name.length); + }, 0); + }; - return delete _this2.limiters[channel]; - }); + /** + * Return the pad width. + * + * @return {number} + * @api private + */ - return function (_x) { - return _ref.apply(this, arguments); - }; - }())); + padWidth() { + let width = this.largestOptionLength(); + if (this._argsDescription && this._args.length) { + if (this.largestArgLength() > width) { + width = this.largestArgLength(); + } } - __scriptArgs__(name, id, args, cb) { - var keys; - keys = Scripts.keys(name, id); - return [this.shas[name], keys.length].concat(keys, args, cb); + if (this.commands && this.commands.length) { + if (this.largestCommandLength() > width) { + width = this.largestCommandLength(); + } } - __scriptFn__(name) { - return this.client.evalsha.bind(this.client); - } + return width; + }; - disconnect(flush = true) { - var i, k, len, ref; - ref = Object.keys(this.limiters); + /** + * Return help for options. + * + * @return {string} + * @api private + */ - for (i = 0, len = ref.length; i < len; i++) { - k = ref[i]; - clearInterval(this.limiters[k]._store.heartbeat); - } + 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); + }; - this.limiters = {}; - this.terminated = true; - this.client.end(flush); - this.subscriber.end(flush); - return this.Promise.resolve(); - } + // 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); + }); - } + // 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)); + } - ; - RedisConnection.prototype.datastore = "redis"; - RedisConnection.prototype.defaults = { - clientOptions: {}, - client: null, - Promise: Promise, - Events: null + return help.join('\n'); }; - return RedisConnection; -}.call(void 0); -module.exports = RedisConnection; + /** + * Return command help documentation. + * + * @return {string} + * @api private + */ -/***/ }), + commandHelp() { + if (!this.commands.length && !this._lazyHasImplicitHelpCommand()) return ''; -/***/ 4946: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + const commands = this.prepareCommands(); + const width = this.padWidth(); -"use strict"; + const columns = process.stdout.columns || 80; + const descriptionWidth = columns - width - 4; + 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'); + }; -function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } + /** + * Return program help documentation. + * + * @return {string} + * @api public + */ -function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } + helpInformation() { + let desc = []; + if (this._description) { + desc = [ + this._description, + '' + ]; -function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } + 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(''); + } + } -function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } + 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(), + '' + ]; -function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } + let cmds = []; + const commandHelp = this.commandHelp(); + if (commandHelp) cmds = [commandHelp]; -function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } + let options = []; + if (this._hasHelpOption || this.options.length > 0) { + options = [ + 'Options:', + '' + this.optionHelp().replace(/^/gm, ' '), + '' + ]; + } -var BottleneckError, IORedisConnection, RedisConnection, RedisDatastore, parser; -parser = __nccwpck_require__(67823); -BottleneckError = __nccwpck_require__(93529); -RedisConnection = __nccwpck_require__(29992); -IORedisConnection = __nccwpck_require__(47710); -RedisDatastore = class RedisDatastore { - constructor(instance, storeOptions, storeInstanceOptions) { - this.instance = instance; - this.storeOptions = storeOptions; - this.originalId = this.instance.id; - this.clientId = this.instance._randomIndex(); - parser.load(storeInstanceOptions, storeInstanceOptions, this); - this.clients = {}; - this.capacityPriorityCounters = {}; - this.sharedConnection = this.connection != null; + return usage + .concat(desc) + .concat(options) + .concat(cmds) + .join('\n'); + }; - if (this.connection == null) { - this.connection = this.instance.datastore === "redis" ? new RedisConnection({ - clientOptions: this.clientOptions, - Promise: this.Promise, - Events: this.instance.Events - }) : this.instance.datastore === "ioredis" ? new IORedisConnection({ - clientOptions: this.clientOptions, - clusterNodes: this.clusterNodes, - Promise: this.Promise, - Events: this.instance.Events - }) : void 0; + /** + * 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); + }; - this.instance.connection = this.connection; - this.instance.datastore = this.connection.datastore; - this.ready = this.connection.ready.then(clients => { - this.clients = clients; - return this.runScript("init", this.prepareInitSettings(this.clearDatastore)); - }).then(() => { - return this.connection.__addLimiter__(this.instance); - }).then(() => { - return this.runScript("register_client", [this.instance.queued()]); - }).then(() => { - var base; + /** + * 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 + */ - if (typeof (base = this.heartbeat = setInterval(() => { - return this.runScript("heartbeat", []).catch(e => { - return this.instance.Events.trigger("error", e); - }); - }, this.heartbeatInterval)).unref === "function") { - base.unref(); - } + helpOption(flags, description) { + if (typeof flags === 'boolean') { + this._hasHelpOption = flags; + return this; + } + this._helpFlags = flags || this._helpFlags; + this._helpDescription = description || this._helpDescription; - return this.clients; - }); - } + const helpFlags = _parseOptionFlags(this._helpFlags); + this._helpShortFlag = helpFlags.shortFlag; + this._helpLongFlag = helpFlags.longFlag; - __publish__(message) { - var _this = this; + return this; + }; - return _asyncToGenerator(function* () { - var client; + /** + * Output help information and exit. + * + * @param {Function} [cb] + * @api public + */ - var _ref = yield _this.ready; + 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)'); + }; - client = _ref.client; - return client.publish(_this.instance.channel(), `message:${message.toString()}`); - })(); - } + /** + * Output help information and exit. Display for error situations. + * + * @api private + */ - onMessage(channel, message) { - var _this2 = this; + _helpAndError() { + this.outputHelp(); + // message: do not have all displayed text available so only passing placeholder. + this._exit(1, 'commander.help', '(outputHelp)'); + }; +}; - return _asyncToGenerator(function* () { - var capacity, counter, data, drained, e, newCapacity, pos, priorityClient, rawCapacity, type; +/** + * Expose the root command. + */ - try { - pos = message.indexOf(":"); - var _ref2 = [message.slice(0, pos), message.slice(pos + 1)]; - type = _ref2[0]; - data = _ref2[1]; +exports = module.exports = new Command(); +exports.program = exports; // More explicit access to global command. - if (type === "capacity") { - return yield _this2.instance._drainAll(data.length > 0 ? ~~data : void 0); - } else if (type === "capacity-priority") { - var _data$split = data.split(":"); +/** + * Expose classes + */ - var _data$split2 = _slicedToArray(_data$split, 3); +exports.Command = Command; +exports.Option = Option; +exports.CommanderError = CommanderError; - rawCapacity = _data$split2[0]; - priorityClient = _data$split2[1]; - counter = _data$split2[2]; - capacity = rawCapacity.length > 0 ? ~~rawCapacity : void 0; +/** + * Camel-case the given `flag` + * + * @param {string} flag + * @return {string} + * @api private + */ - if (priorityClient === _this2.clientId) { - drained = yield _this2.instance._drainAll(capacity); - newCapacity = capacity != null ? capacity - (drained || 0) : ""; - return yield _this2.clients.client.publish(_this2.instance.channel(), `capacity-priority:${newCapacity}::${counter}`); - } else if (priorityClient === "") { - clearTimeout(_this2.capacityPriorityCounters[counter]); - delete _this2.capacityPriorityCounters[counter]; - return _this2.instance._drainAll(capacity); - } else { - return _this2.capacityPriorityCounters[counter] = setTimeout( - /*#__PURE__*/ - _asyncToGenerator(function* () { - var e; +function camelcase(flag) { + return flag.split('-').reduce((str, word) => { + return str + word[0].toUpperCase() + word.slice(1); + }); +} - try { - delete _this2.capacityPriorityCounters[counter]; - yield _this2.runScript("blacklist_client", [priorityClient]); - return yield _this2.instance._drainAll(capacity); - } catch (error) { - e = error; - return _this2.instance.Events.trigger("error", e); - } - }), 1000); - } - } else if (type === "message") { - return _this2.instance.Events.trigger("message", data); - } else if (type === "blocked") { - return yield _this2.instance._dropAllQueued(); - } - } catch (error) { - e = error; - return _this2.instance.Events.trigger("error", e); - } - })(); - } +/** + * Pad `str` to `width`. + * + * @param {string} str + * @param {number} width + * @return {string} + * @api private + */ - __disconnect__(flush) { - clearInterval(this.heartbeat); +function pad(str, width) { + const len = Math.max(0, width - str.length); + return str + Array(len + 1).join(' '); +} - if (this.sharedConnection) { - return this.connection.__removeLimiter__(this.instance); - } else { - return this.connection.disconnect(flush); +/** + * 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'); +} - runScript(name, args) { - var _this3 = this; +/** + * 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; - return _asyncToGenerator(function* () { - if (!(name === "init" || name === "register_client")) { - yield _this3.ready; - } + return wrap(str, width, indent); +} - return new _this3.Promise((resolve, reject) => { - var all_args, arr; - all_args = [Date.now(), _this3.clientId].concat(args); +/** + * 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 + */ - _this3.instance.Events.trigger("debug", `Calling Redis script: ${name}.lua`, all_args); +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)'); + } +} - arr = _this3.connection.__scriptArgs__(name, _this3.originalId, all_args, function (err, replies) { - if (err != null) { - return reject(err); - } +/** + * Takes an argument and returns its human readable equivalent for help usage. + * + * @param {Object} arg + * @return {string} + * @api private + */ - return resolve(replies); - }); - return _this3.connection.__scriptFn__(name)(...arr); - }).catch(e => { - if (e.message === "SETTINGS_KEY_NOT_FOUND") { - if (name === "heartbeat") { - return _this3.Promise.resolve(); - } else { - return _this3.runScript("init", _this3.prepareInitSettings(false)).then(() => { - return _this3.runScript(name, args); - }); - } - } else if (e.message === "UNKNOWN_CLIENT") { - return _this3.runScript("register_client", [_this3.instance.queued()]).then(() => { - return _this3.runScript(name, args); - }); - } else { - return _this3.Promise.reject(e); - } - }); - })(); - } +function humanReadableArgName(arg) { + const nameOutput = arg.name + (arg.variadic === true ? '...' : ''); - prepareArray(arr) { - var i, len, results, x; - results = []; + return arg.required + ? '<' + nameOutput + '>' + : '[' + nameOutput + ']'; +} - for (i = 0, len = arr.length; i < len; i++) { - x = arr[i]; - results.push(x != null ? x.toString() : ""); - } +/** + * Parse the short and long flag out of something like '-m,--mixed ' + * + * @api private + */ - return results; +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 }; +} - prepareObject(obj) { - var arr, k, v; - arr = []; +/** + * 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 + */ - for (k in obj) { - v = obj[k]; - arr.push(k, v != null ? v.toString() : ""); +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]; } - return arr; - } - - prepareInitSettings(clear) { - var args; - args = this.prepareObject(Object.assign({}, this.storeOptions, { - id: this.originalId, - version: this.instance.version, - groupTimeout: this.timeout, - clientTimeout: this.clientTimeout - })); - args.unshift(clear ? 1 : 0, this.instance.version); - return args; - } + if (debugOption && debugPort !== '0') { + return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`; + } + return arg; + }); +} - convertBool(b) { - return !!b; - } - __updateSettings__(options) { - var _this4 = this; +/***/ }), - return _asyncToGenerator(function* () { - yield _this4.runScript("update_settings", _this4.prepareObject(options)); - return parser.overwrite(options, options, _this4.storeOptions); - })(); - } +/***/ 89296: +/***/ (function(module) { - __running__() { - return this.runScript("running", []); - } +/* 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; - __queued__() { - return this.runScript("queued", []); + function indexOrEnd(str, q) { + return str.indexOf(q) === -1 ? str.length : str.indexOf(q); } - __done__() { - return this.runScript("done", []); + 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; } - __groupCheck__() { - var _this5 = this; - - return _asyncToGenerator(function* () { - return _this5.convertBool((yield _this5.runScript("group_check", []))); - })(); + function tryParse(v) { + var n = parseInt(v, 10); + return isNaN(n) ? v : n; } - __incrementReservoir__(incr) { - return this.runScript("increment_reservoir", [incr]); + 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; } - __currentReservoir__() { - return this.runScript("current_reservoir", []); + function forceType(a, b) { + return typeof a !== typeof b ? [String(a), String(b)] : [a, b]; } - __check__(weight) { - var _this6 = this; - - return _asyncToGenerator(function* () { - return _this6.convertBool((yield _this6.runScript("check", _this6.prepareArray([weight])))); - })(); + function compareStrings(a, b) { + var [ap, bp] = forceType(tryParse(a), tryParse(b)); + if (ap > bp) return 1; + if (ap < bp) return -1; + return 0; } - __register__(index, weight, expiration) { - var _this7 = this; - - return _asyncToGenerator(function* () { - var reservoir, success, wait; - - var _ref4 = yield _this7.runScript("register", _this7.prepareArray([index, weight, expiration])); - - var _ref5 = _slicedToArray(_ref4, 3); - - success = _ref5[0]; - wait = _ref5[1]; - reservoir = _ref5[2]; - return { - success: _this7.convertBool(success), - wait, - reservoir - }; - })(); + 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; } - __submit__(queueLength, weight) { - var _this8 = this; + function compareVersions(v1, v2) { + [v1, v2].forEach(validateAndParse); - return _asyncToGenerator(function* () { - var blocked, e, maxConcurrent, overweight, reachedHWM, strategy; + var s1 = split(v1); + var s2 = split(v2); - try { - var _ref6 = yield _this8.runScript("submit", _this8.prepareArray([queueLength, weight])); + 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); - var _ref7 = _slicedToArray(_ref6, 3); + if (n1 > n2) return 1; + if (n2 > n1) return -1; + } - reachedHWM = _ref7[0]; - blocked = _ref7[1]; - strategy = _ref7[2]; - return { - reachedHWM: _this8.convertBool(reachedHWM), - blocked: _this8.convertBool(blocked), - strategy - }; - } catch (error) { - e = error; + var sp1 = s1[s1.length - 1]; + var sp2 = s2[s2.length - 1]; - if (e.message.indexOf("OVERWEIGHT") === 0) { - var _e$message$split = e.message.split(":"); + if (sp1 && sp2) { + var p1 = sp1.split('.').map(tryParse); + var p2 = sp2.split('.').map(tryParse); - var _e$message$split2 = _slicedToArray(_e$message$split, 3); + 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; - overweight = _e$message$split2[0]; - weight = _e$message$split2[1]; - maxConcurrent = _e$message$split2[2]; - throw new BottleneckError(`Impossible to add a job having a weight of ${weight} to a limiter having a maxConcurrent setting of ${maxConcurrent}`); - } else { - throw e; - } + if (p1[i] > p2[i]) return 1; + if (p2[i] > p1[i]) return -1; } - })(); - } - - __free__(index, weight) { - var _this9 = this; + } else if (sp1 || sp2) { + return sp1 ? -1 : 1; + } - return _asyncToGenerator(function* () { - var running; - running = yield _this9.runScript("free", _this9.prepareArray([index])); - return { - running - }; - })(); + return 0; } -}; -module.exports = RedisDatastore; + var allowedOperators = ['>', '>=', '=', '<', '<=']; -/***/ }), + var operatorResMap = { + '>': [1], + '>=': [0, 1], + '=': [0], + '<=': [-1, 0], + '<': [-1], + }; -/***/ 4169: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + 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('|') + ); + } + } -"use strict"; + compareVersions.validate = function (version) { + return typeof version === 'string' && semver.test(version); + }; + compareVersions.compare = function (v1, v2, operator) { + // Validate operator + validateOperator(operator); -var headers, lua, templates; -lua = __nccwpck_require__(31936); -headers = { - refs: lua["refs.lua"], - validate_keys: lua["validate_keys.lua"], - validate_client: lua["validate_client.lua"], - refresh_expiration: lua["refresh_expiration.lua"], - process_tick: lua["process_tick.lua"], - conditions_check: lua["conditions_check.lua"], - get_time: lua["get_time.lua"] -}; + // 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; + }; -exports.allKeys = function (id) { - return [ - /* - HASH - */ - `b_${id}_settings`, - /* - HASH - job index -> weight - */ - `b_${id}_job_weights`, - /* - ZSET - job index -> expiration - */ - `b_${id}_job_expirations`, - /* - HASH - job index -> client - */ - `b_${id}_job_clients`, - /* - ZSET - client -> sum running - */ - `b_${id}_client_running`, - /* - HASH - client -> num queued - */ - `b_${id}_client_num_queued`, - /* - ZSET - client -> last job registered - */ - `b_${id}_client_last_registered`, - /* - ZSET - client -> last seen - */ - `b_${id}_client_last_seen`]; -}; + compareVersions.satisfies = function (v, r) { + // if no range operator then "=" + var match = r.match(/^([<>=~^]+)/); + var op = match ? match[1] : '='; -templates = { - init: { - keys: exports.allKeys, - headers: ["process_tick"], - refresh_expiration: true, - code: lua["init.lua"] - }, - group_check: { - keys: exports.allKeys, - headers: [], - refresh_expiration: false, - code: lua["group_check.lua"] - }, - register_client: { - keys: exports.allKeys, - headers: ["validate_keys"], - refresh_expiration: false, - code: lua["register_client.lua"] - }, - blacklist_client: { - keys: exports.allKeys, - headers: ["validate_keys", "validate_client"], - refresh_expiration: false, - code: lua["blacklist_client.lua"] - }, - heartbeat: { - keys: exports.allKeys, - headers: ["validate_keys", "validate_client", "process_tick"], - refresh_expiration: false, - code: lua["heartbeat.lua"] - }, - update_settings: { - keys: exports.allKeys, - headers: ["validate_keys", "validate_client", "process_tick"], - refresh_expiration: true, - code: lua["update_settings.lua"] - }, - running: { - keys: exports.allKeys, - headers: ["validate_keys", "validate_client", "process_tick"], - refresh_expiration: false, - code: lua["running.lua"] - }, - queued: { - keys: exports.allKeys, - headers: ["validate_keys", "validate_client"], - refresh_expiration: false, - code: lua["queued.lua"] - }, - done: { - keys: exports.allKeys, - headers: ["validate_keys", "validate_client", "process_tick"], - refresh_expiration: false, - code: lua["done.lua"] - }, - check: { - keys: exports.allKeys, - headers: ["validate_keys", "validate_client", "process_tick", "conditions_check"], - refresh_expiration: false, - code: lua["check.lua"] - }, - submit: { - keys: exports.allKeys, - headers: ["validate_keys", "validate_client", "process_tick", "conditions_check"], - refresh_expiration: true, - code: lua["submit.lua"] - }, - register: { - keys: exports.allKeys, - headers: ["validate_keys", "validate_client", "process_tick", "conditions_check"], - refresh_expiration: true, - code: lua["register.lua"] - }, - free: { - keys: exports.allKeys, - headers: ["validate_keys", "validate_client", "process_tick"], - refresh_expiration: true, - code: lua["free.lua"] - }, - current_reservoir: { - keys: exports.allKeys, - headers: ["validate_keys", "validate_client", "process_tick"], - refresh_expiration: false, - code: lua["current_reservoir.lua"] - }, - increment_reservoir: { - keys: exports.allKeys, - headers: ["validate_keys", "validate_client", "process_tick"], - refresh_expiration: true, - code: lua["increment_reservoir.lua"] - } -}; -exports.names = Object.keys(templates); + // 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; + }; -exports.keys = function (name, id) { - return templates[name].keys(id); -}; + return compareVersions; +}); -exports.payload = function (name) { - var template; - template = templates[name]; - return Array.prototype.concat(headers.refs, template.headers.map(function (h) { - return headers[h]; - }), template.refresh_expiration ? headers.refresh_expiration : "", template.code).join("\n"); -}; /***/ }), -/***/ 2527: +/***/ 53921: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; +/*! + * content-disposition + * Copyright(c) 2014-2017 Douglas Christopher Wilson + * MIT Licensed + */ -var BottleneckError, States; -BottleneckError = __nccwpck_require__(93529); -States = class States { - constructor(status1) { - this.status = status1; - this.jobs = {}; - this.counts = this.status.map(function () { - return 0; - }); - } - next(id) { - var current, next; - current = this.jobs[id]; - next = current + 1; +/** + * Module exports. + * @public + */ - if (current != null && next < this.status.length) { - this.counts[current]--; - this.counts[next]++; - return this.jobs[id]++; - } else if (current != null) { - this.counts[current]--; - return delete this.jobs[id]; - } - } +module.exports = contentDisposition +module.exports.parse = parse - start(id) { - var initial; - initial = 0; - this.jobs[id] = initial; - return this.counts[initial]++; - } +/** + * Module dependencies. + * @private + */ - remove(id) { - var current; - current = this.jobs[id]; +var basename = (__nccwpck_require__(71017).basename) +var Buffer = (__nccwpck_require__(21867).Buffer) - if (current != null) { - this.counts[current]--; - delete this.jobs[id]; - } +/** + * RegExp to match non attr-char, *after* encodeURIComponent (i.e. not including "%") + * @private + */ - return current != null; - } +var ENCODE_URL_ATTR_CHAR_REGEXP = /[\x00-\x20"'()*,/:;<=>?@[\\\]{}\x7f]/g // eslint-disable-line no-control-regex - jobStatus(id) { - var ref; - return (ref = this.status[this.jobs[id]]) != null ? ref : null; - } +/** + * RegExp to match percent encoding escape. + * @private + */ - statusJobs(status) { - var k, pos, ref, results, v; +var HEX_ESCAPE_REGEXP = /%[0-9A-Fa-f]{2}/ +var HEX_ESCAPE_REPLACE_REGEXP = /%([0-9A-Fa-f]{2})/g - if (status != null) { - pos = this.status.indexOf(status); +/** + * RegExp to match non-latin1 characters. + * @private + */ - if (pos < 0) { - throw new BottleneckError(`status must be one of ${this.status.join(', ')}`); - } +var NON_LATIN1_REGEXP = /[^\x20-\x7e\xa0-\xff]/g - ref = this.jobs; - results = []; +/** + * RegExp to match quoted-pair in RFC 2616 + * + * quoted-pair = "\" CHAR + * CHAR = + * @private + */ - for (k in ref) { - v = ref[k]; +var QESC_REGEXP = /\\([\u0000-\u007f])/g // eslint-disable-line no-control-regex - if (v === pos) { - results.push(k); - } - } +/** + * RegExp to match chars that must be quoted-pair in RFC 2616 + * @private + */ - return results; - } else { - return Object.keys(this.jobs); - } +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!#$&+.^_`|~-])+)$/ + +/** + * 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 + */ + +var DISPOSITION_TYPE_REGEXP = /^([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*(?:$|;)/ // eslint-disable-line no-control-regex + +/** + * 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 + */ + +function contentDisposition (filename, options) { + var opts = options || {} + + // get type + var type = opts.type || 'attachment' + + // get parameters + var params = createparams(filename, opts.fallback) + + // format into string + return format(new ContentDisposition(type, params)) +} + +/** + * Create parameters object from filename and fallback. + * + * @param {string} [filename] + * @param {string|boolean} [fallback=true] + * @return {object} + * @private + */ + +function createparams (filename, fallback) { + if (filename === undefined) { + return } - statusCounts() { - return this.counts.reduce((acc, v, i) => { - acc[this.status[i]] = v; - return acc; - }, {}); + var params = {} + + if (typeof filename !== 'string') { + throw new TypeError('filename must be a string') } -}; -module.exports = States; + // 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') + } -/***/ 56029: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (typeof fallback === 'string' && NON_LATIN1_REGEXP.test(fallback)) { + throw new TypeError('fallback must be ISO-8859-1 string') + } -"use strict"; + // restrict to file base name + var name = basename(filename) + // determine if name is suitable for quoted string + var isQuotedString = TEXT_REGEXP.test(name) -function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } + // generate fallback name + var fallbackName = typeof fallback !== 'string' + ? fallback && getlatin1(name) + : basename(fallback) + var hasFallback = typeof fallbackName === 'string' && fallbackName !== name -function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } + // set extended filename parameter + if (hasFallback || !isQuotedString || HEX_ESCAPE_REGEXP.test(name)) { + params['filename*'] = name + } -function _toArray(arr) { return _arrayWithHoles(arr) || _iterableToArray(arr) || _nonIterableRest(); } + // set filename parameter + if (isQuotedString || hasFallback) { + params.filename = hasFallback + ? fallbackName + : name + } -function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } + return params +} -function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } +/** + * Format object to Content-Disposition header. + * + * @param {object} obj + * @param {string} obj.type + * @param {object} [obj.parameters] + * @return {string} + * @private + */ -function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } +function format (obj) { + var parameters = obj.parameters + var type = obj.type -var DLList, - Sync, - splice = [].splice; -DLList = __nccwpck_require__(38579); -Sync = class Sync { - constructor(name, Promise) { - this.submit = this.submit.bind(this); - this.name = name; - this.Promise = Promise; - this._running = 0; - this._queue = new DLList(); + if (!type || typeof type !== 'string' || !TOKEN_REGEXP.test(type)) { + throw new TypeError('invalid type') } - isEmpty() { - return this._queue.length === 0; - } + // start with normalized type + var string = String(type).toLowerCase() - _tryToRun() { - var next; + // append parameters + if (parameters && typeof parameters === 'object') { + var param + var params = Object.keys(parameters).sort() - if (this._running < 1 && this._queue.length > 0) { - this._running++; - next = this._queue.shift(); - return next.task(...next.args, (...args) => { - this._running--; + for (var i = 0; i < params.length; i++) { + param = params[i] - this._tryToRun(); + var val = param.substr(-1) === '*' + ? ustring(parameters[param]) + : qstring(parameters[param]) - return typeof next.cb === "function" ? next.cb(...args) : void 0; - }); + string += '; ' + param + '=' + val } } - submit(task, ...args) { - var _ref, _ref2, _splice$call, _splice$call2; + return string +} - var cb, ref; - ref = args, (_ref = ref, _ref2 = _toArray(_ref), args = _ref2.slice(0), _ref), (_splice$call = splice.call(args, -1), _splice$call2 = _slicedToArray(_splice$call, 1), cb = _splice$call2[0], _splice$call); +/** + * Decode a RFC 6987 field value (gracefully). + * + * @param {string} str + * @return {string} + * @private + */ - this._queue.push({ - task, - args, - cb - }); +function decodefield (str) { + var match = EXT_VALUE_REGEXP.exec(str) - return this._tryToRun(); + if (!match) { + throw new TypeError('invalid extended field value') } - schedule(task, ...args) { - var wrapped; + var charset = match[1].toLowerCase() + var encoded = match[2] + var value - wrapped = function wrapped(...args) { - var _ref3, _ref4, _splice$call3, _splice$call4; + // to binary string + var binary = encoded.replace(HEX_ESCAPE_REPLACE_REGEXP, pdecode) - var cb, ref; - ref = args, (_ref3 = ref, _ref4 = _toArray(_ref3), args = _ref4.slice(0), _ref3), (_splice$call3 = splice.call(args, -1), _splice$call4 = _slicedToArray(_splice$call3, 1), cb = _splice$call4[0], _splice$call3); - return task(...args).then(function (...args) { - return cb(null, ...args); - }).catch(function (...args) { - return cb(...args); - }); - }; + 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 new this.Promise((resolve, reject) => { - return this.submit(wrapped, ...args, function (...args) { - return (args[0] != null ? reject : (args.shift(), resolve))(...args); - }); - }); + return value +} + +/** + * Get ISO-8859-1 version of string. + * + * @param {string} val + * @return {string} + * @private + */ + +function getlatin1 (val) { + // simple Unicode -> ISO-8859-1 transformation + return String(val).replace(NON_LATIN1_REGEXP, '?') +} + +/** + * Parse Content-Disposition header string. + * + * @param {string} string + * @return {object} + * @public + */ + +function parse (string) { + if (!string || typeof string !== 'string') { + throw new TypeError('argument string is required') } -}; -module.exports = Sync; + var match = DISPOSITION_TYPE_REGEXP.exec(string) -/***/ }), + if (!match) { + throw new TypeError('invalid type format') + } -/***/ 27356: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // normalize type + var index = match[0].length + var type = match[1].toLowerCase() -"use strict"; + var key + var names = [] + var params = {} + var value + // calculate index to start at + index = PARAM_REGEXP.lastIndex = match[0].substr(-1) === ';' + ? index - 1 + : index -module.exports = __nccwpck_require__(83911); + // 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] -/***/ 67823: -/***/ ((__unused_webpack_module, exports) => { + if (names.indexOf(key) !== -1) { + throw new TypeError('invalid duplicate parameter') + } -"use strict"; + names.push(key) + if (key.indexOf('*') + 1 === key.length) { + // decode extended value + key = key.slice(0, -1) + value = decodefield(value) -exports.load = function (received, defaults, onto = {}) { - var k, ref, v; + // overwrite existing value + params[key] = value + continue + } - for (k in defaults) { - v = defaults[k]; - onto[k] = (ref = received[k]) != null ? ref : v; + 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 } - return onto; -}; + if (index !== -1 && index !== string.length) { + throw new TypeError('invalid parameter format') + } + + return new ContentDisposition(type, params) +} + +/** + * Percent decode a single character. + * + * @param {string} str + * @param {string} hex + * @return {string} + * @private + */ + +function pdecode (str, hex) { + return String.fromCharCode(parseInt(hex, 16)) +} + +/** + * Percent encode a single character. + * + * @param {string} char + * @return {string} + * @private + */ + +function pencode (char) { + return '%' + String(char) + .charCodeAt(0) + .toString(16) + .toUpperCase() +} + +/** + * Quote a string for HTTP. + * + * @param {string} val + * @return {string} + * @private + */ -exports.overwrite = function (received, defaults, onto = {}) { - var k, v; +function qstring (val) { + var str = String(val) - for (k in received) { - v = received[k]; + return '"' + str.replace(QUOTE_REGEXP, '\\$1') + '"' +} - if (defaults[k] !== void 0) { - onto[k] = v; - } - } +/** + * Encode a Unicode string for HTTP (RFC 5987). + * + * @param {string} val + * @return {string} + * @private + */ - return onto; -}; +function ustring (val) { + var str = String(val) -/***/ }), + // percent encode as UTF-8 + var encoded = encodeURIComponent(str) + .replace(ENCODE_URL_ATTR_CHAR_REGEXP, pencode) -/***/ 11174: -/***/ (function(module) { + return 'UTF-8\'\'' + encoded +} /** - * This file contains the Bottleneck library (MIT), compiled to ES2017, and without Clustering support. - * https://github.com/SGrondin/bottleneck - */ -(function (global, factory) { - true ? module.exports = factory() : - 0; -}(this, (function () { 'use strict'; + * Class for parsed Content-Disposition header for v8 optimization + * + * @public + * @param {string} type + * @param {object} parameters + * @constructor + */ - var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; +function ContentDisposition (type, parameters) { + this.type = type + this.parameters = parameters +} - function getCjsExportFromNamespace (n) { - return n && n.default || n; - } - var load = function(received, defaults, onto = {}) { - var k, ref, v; - for (k in defaults) { - v = defaults[k]; - onto[k] = (ref = received[k]) != null ? ref : v; - } - return onto; - }; +/***/ }), - var overwrite = function(received, defaults, onto = {}) { - var k, v; - for (k in received) { - v = received[k]; - if (defaults[k] !== void 0) { - onto[k] = v; - } - } - return onto; - }; +/***/ 99915: +/***/ ((__unused_webpack_module, exports) => { - var parser = { - load: load, - overwrite: overwrite - }; +"use strict"; +/*! + * content-type + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ - var DLList; - DLList = class DLList { - constructor(_queues) { - this._queues = _queues; - this._first = null; - this._last = null; - this.length = 0; - } - push(value) { - var node, ref1; - this.length++; - if ((ref1 = this._queues) != null) { - ref1.incr(); - } - node = { - value, - next: null - }; - if (this._last != null) { - this._last.next = node; - this._last = node; - } else { - this._first = this._last = node; - } - return void 0; - } +/** + * 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-]+$/ - shift() { - var ref1, ref2, value; - if (this._first == null) { - return void 0; - } else { - this.length--; - if ((ref1 = this._queues) != null) { - ref1.decr(); - } - } - value = this._first.value; - this._first = (ref2 = this._first.next) != null ? ref2 : (this._last = null); - return value; - } +/** + * 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 - first() { - if (this._first != null) { - return this._first.value; - } - } +/** + * RegExp to match chars that must be quoted-pair in RFC 7230 sec 3.2.6 + */ +var QUOTE_REGEXP = /([\\"])/g - getArray() { - var node, ref, results; - node = this._first; - results = []; - while (node != null) { - results.push((ref = node, node = node.next, ref.value)); - } - return results; - } +/** + * 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-]+$/ - forEachShift(cb) { - var node; - node = this.shift(); - while (node != null) { - (cb(node), node = this.shift()); - } - return void 0; - } +/** + * Module exports. + * @public + */ - }; +exports.format = format +exports.parse = parse - var DLList_1 = DLList; +/** + * Format object to media type. + * + * @param {object} obj + * @return {string} + * @public + */ - var Events; +function format (obj) { + if (!obj || typeof obj !== 'object') { + throw new TypeError('argument obj is required') + } - Events = class Events { - constructor(instance) { - this.instance = instance; - this._events = {}; - if ((this.instance.on != null) || (this.instance.once != null) || (this.instance.removeAllListeners != null)) { - throw new Error("An Emitter already exists for this object"); - } - this.instance.on = (name, cb) => { - return this._addListener(name, "many", cb); - }; - this.instance.once = (name, cb) => { - return this._addListener(name, "once", cb); - }; - this.instance.removeAllListeners = (name = null) => { - if (name != null) { - return delete this._events[name]; - } else { - return this._events = {}; - } - }; - } + var parameters = obj.parameters + var type = obj.type - _addListener(name, status, cb) { - var base; - if ((base = this._events)[name] == null) { - base[name] = []; - } - this._events[name].push({cb, status}); - return this.instance; - } + if (!type || !TYPE_REGEXP.test(type)) { + throw new TypeError('invalid type') + } - listenerCount(name) { - if (this._events[name] != null) { - return this._events[name].length; - } else { - return 0; - } - } + var string = type - async trigger(name, ...args) { - var e, promises; - try { - if (name !== "debug") { - this.trigger("debug", `Event triggered: ${name}`, args); - } - if (this._events[name] == null) { - return; - } - this._events[name] = this._events[name].filter(function(listener) { - return listener.status !== "none"; - }); - promises = this._events[name].map(async(listener) => { - var e, returned; - if (listener.status === "none") { - return; - } - if (listener.status === "once") { - listener.status = "none"; - } - try { - returned = typeof listener.cb === "function" ? listener.cb(...args) : void 0; - if (typeof (returned != null ? returned.then : void 0) === "function") { - return (await returned); - } else { - return returned; - } - } catch (error) { - e = error; - { - this.trigger("error", e); - } - return null; - } - }); - return ((await Promise.all(promises))).find(function(x) { - return x != null; - }); - } catch (error) { - e = error; - { - this.trigger("error", e); - } - return null; - } - } + // 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] - var Events_1 = Events; + if (!TOKEN_REGEXP.test(param)) { + throw new TypeError('invalid parameter name') + } - var DLList$1, Events$1, Queues; + string += '; ' + param + '=' + qstring(parameters[param]) + } + } - DLList$1 = DLList_1; + return string +} - Events$1 = Events_1; +/** + * Parse media type to object. + * + * @param {string|object} string + * @return {Object} + * @public + */ - Queues = class Queues { - constructor(num_priorities) { - var i; - this.Events = new Events$1(this); - this._length = 0; - this._lists = (function() { - var j, ref, results; - results = []; - for (i = j = 1, ref = num_priorities; (1 <= ref ? j <= ref : j >= ref); i = 1 <= ref ? ++j : --j) { - results.push(new DLList$1(this)); - } - return results; - }).call(this); - } +function parse (string) { + if (!string) { + throw new TypeError('argument string is required') + } - incr() { - if (this._length++ === 0) { - return this.Events.trigger("leftzero"); - } - } + // support req/res-like objects as argument + var header = typeof string === 'object' + ? getcontenttype(string) + : string - decr() { - if (--this._length === 0) { - return this.Events.trigger("zero"); - } - } + if (typeof header !== 'string') { + throw new TypeError('argument string is required to be a string') + } - push(priority, job) { - return this._lists[priority].push(job); - } + var index = header.indexOf(';') + var type = index !== -1 + ? header.substr(0, index).trim() + : header.trim() - queued(priority) { - if (priority != null) { - return this._lists[priority].length; - } else { - return this._length; - } - } + if (!TYPE_REGEXP.test(type)) { + throw new TypeError('invalid media type') + } - shiftAll(fn) { - return this._lists.forEach(function(list) { - return list.forEachShift(fn); - }); - } + var obj = new ContentType(type.toLowerCase()) - getFirst(arr = this._lists) { - var j, len, list; - for (j = 0, len = arr.length; j < len; j++) { - list = arr[j]; - if (list.length > 0) { - return list; - } - } - return []; - } + // parse parameters + if (index !== -1) { + var key + var match + var value - shiftLastFrom(priority) { - return this.getFirst(this._lists.slice(priority).reverse()).shift(); - } + PARAM_REGEXP.lastIndex = index - }; + while ((match = PARAM_REGEXP.exec(header))) { + if (match.index !== index) { + throw new TypeError('invalid parameter format') + } - var Queues_1 = Queues; + index += match[0].length + key = match[1].toLowerCase() + value = match[2] - var BottleneckError; + if (value[0] === '"') { + // remove quotes and escapes + value = value + .substr(1, value.length - 2) + .replace(QESC_REGEXP, '$1') + } - BottleneckError = class BottleneckError extends Error {}; + obj.parameters[key] = value + } - var BottleneckError_1 = BottleneckError; + if (index !== header.length) { + throw new TypeError('invalid parameter format') + } + } - var BottleneckError$1, LocalDatastore, parser$1; + return obj +} - parser$1 = parser; +/** + * Get content-type from req/res objects. + * + * @param {object} + * @return {Object} + * @private + */ - BottleneckError$1 = BottleneckError_1; +function getcontenttype (obj) { + var header - LocalDatastore = class LocalDatastore { - constructor(instance, storeOptions, storeInstanceOptions) { - this.instance = instance; - this.storeOptions = storeOptions; - this.clientId = this.instance._randomIndex(); - parser$1.load(storeInstanceOptions, storeInstanceOptions, this); - this._nextRequest = this._lastReservoirRefresh = Date.now(); - this._running = 0; - this._done = 0; - this._unblockTime = 0; - this.ready = this.Promise.resolve(); - this.clients = {}; - this._startHeartbeat(); - } + 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'] + } - _startHeartbeat() { - var base; - if ((this.heartbeat == null) && (this.storeOptions.reservoirRefreshInterval != null) && (this.storeOptions.reservoirRefreshAmount != null)) { - return typeof (base = (this.heartbeat = setInterval(() => { - var now; - now = Date.now(); - if (now >= this._lastReservoirRefresh + this.storeOptions.reservoirRefreshInterval) { - this.storeOptions.reservoir = this.storeOptions.reservoirRefreshAmount; - this._lastReservoirRefresh = now; - return this.instance._drainAll(this.computeCapacity()); - } - }, this.heartbeatInterval))).unref === "function" ? base.unref() : void 0; - } else { - return clearInterval(this.heartbeat); - } - } + if (typeof header !== 'string') { + throw new TypeError('content-type header is missing from object') + } - async __publish__(message) { - await this.yieldLoop(); - return this.instance.Events.trigger("message", message.toString()); - } + return header +} - async __disconnect__(flush) { - await this.yieldLoop(); - clearInterval(this.heartbeat); - return this.Promise.resolve(); - } +/** + * Quote a string if necessary. + * + * @param {string} val + * @return {string} + * @private + */ - yieldLoop(t = 0) { - return new this.Promise(function(resolve, reject) { - return setTimeout(resolve, t); - }); - } +function qstring (val) { + var str = String(val) - computePenalty() { - var ref; - return (ref = this.storeOptions.penalty) != null ? ref : (15 * this.storeOptions.minTime) || 5000; - } + // 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') + } - async __updateSettings__(options) { - await this.yieldLoop(); - parser$1.overwrite(options, options, this.storeOptions); - this._startHeartbeat(); - this.instance._drainAll(this.computeCapacity()); - return true; - } + return '"' + str.replace(QUOTE_REGEXP, '\\$1') + '"' +} - async __running__() { - await this.yieldLoop(); - return this._running; - } +/** + * Class to represent a content type. + * @private + */ +function ContentType (type) { + this.parameters = Object.create(null) + this.type = type +} - async __queued__() { - await this.yieldLoop(); - return this.instance.queued(); - } - async __done__() { - await this.yieldLoop(); - return this._done; - } +/***/ }), - async __groupCheck__(time) { - await this.yieldLoop(); - return (this._nextRequest + this.timeout) < time; - } +/***/ 61579: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - computeCapacity() { - var maxConcurrent, reservoir; - ({maxConcurrent, reservoir} = this.storeOptions); - if ((maxConcurrent != null) && (reservoir != null)) { - return Math.min(maxConcurrent - this._running, reservoir); - } else if (maxConcurrent != null) { - return maxConcurrent - this._running; - } else if (reservoir != null) { - return reservoir; - } else { - return null; - } - } +/** + * Module dependencies. + */ - conditionsCheck(weight) { - var capacity; - capacity = this.computeCapacity(); - return (capacity == null) || weight <= capacity; - } +var crypto = __nccwpck_require__(6113); - async __incrementReservoir__(incr) { - var reservoir; - await this.yieldLoop(); - reservoir = this.storeOptions.reservoir += incr; - this.instance._drainAll(this.computeCapacity()); - return reservoir; - } +/** + * Sign the given `val` with `secret`. + * + * @param {String} val + * @param {String} secret + * @return {String} + * @api private + */ - async __currentReservoir__() { - await this.yieldLoop(); - return this.storeOptions.reservoir; - } +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(/\=+$/, ''); +}; - isBlocked(now) { - return this._unblockTime >= now; - } +/** + * 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 + */ - check(weight, now) { - return this.conditionsCheck(weight) && (this._nextRequest - now) <= 0; - } +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; +}; - async __check__(weight) { - var now; - await this.yieldLoop(); - now = Date.now(); - return this.check(weight, now); - } +/** + * Private + */ - async __register__(index, weight, expiration) { - var now, wait; - await this.yieldLoop(); - now = Date.now(); - if (this.conditionsCheck(weight)) { - this._running += weight; - if (this.storeOptions.reservoir != null) { - this.storeOptions.reservoir -= weight; - } - wait = Math.max(this._nextRequest - now, 0); - this._nextRequest = now + wait + this.storeOptions.minTime; - return { - success: true, - wait, - reservoir: this.storeOptions.reservoir - }; - } else { - return { - success: false - }; - } - } +function sha1(str){ + return crypto.createHash('sha1').update(str).digest('hex'); +} - strategyIsBlock() { - return this.storeOptions.strategy === 3; - } - async __submit__(queueLength, weight) { - var blocked, now, reachedHWM; - await this.yieldLoop(); - if ((this.storeOptions.maxConcurrent != null) && weight > this.storeOptions.maxConcurrent) { - throw new BottleneckError$1(`Impossible to add a job having a weight of ${weight} to a limiter having a maxConcurrent setting of ${this.storeOptions.maxConcurrent}`); - } - now = Date.now(); - reachedHWM = (this.storeOptions.highWater != null) && queueLength === this.storeOptions.highWater && !this.check(weight, now); - blocked = this.strategyIsBlock() && (reachedHWM || this.isBlocked(now)); - if (blocked) { - this._unblockTime = now + this.computePenalty(); - this._nextRequest = this._unblockTime + this.storeOptions.minTime; - this.instance._dropAllQueued(); - } - return { - reachedHWM, - blocked, - strategy: this.storeOptions.strategy - }; - } +/***/ }), - async __free__(index, weight) { - await this.yieldLoop(); - this._running -= weight; - this._done += weight; - this.instance._drainAll(this.computeCapacity()); - return { - running: this._running - }; - } +/***/ 93658: +/***/ ((__unused_webpack_module, exports) => { - }; +"use strict"; +/*! + * cookie + * Copyright(c) 2012-2014 Roman Shtylman + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ - var LocalDatastore_1 = LocalDatastore; - var BottleneckError$2, States; - BottleneckError$2 = BottleneckError_1; +/** + * Module exports. + * @public + */ - States = class States { - constructor(status1) { - this.status = status1; - this.jobs = {}; - this.counts = this.status.map(function() { - return 0; - }); - } +exports.parse = parse; +exports.serialize = serialize; - next(id) { - var current, next; - current = this.jobs[id]; - next = current + 1; - if ((current != null) && next < this.status.length) { - this.counts[current]--; - this.counts[next]++; - return this.jobs[id]++; - } else if (current != null) { - this.counts[current]--; - return delete this.jobs[id]; - } - } +/** + * Module variables. + * @private + */ - start(id) { - var initial; - initial = 0; - this.jobs[id] = initial; - return this.counts[initial]++; - } +var decode = decodeURIComponent; +var encode = encodeURIComponent; +var pairSplitRegExp = /; */; - remove(id) { - var current; - current = this.jobs[id]; - if (current != null) { - this.counts[current]--; - delete this.jobs[id]; - } - return current != null; - } +/** + * 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 + */ - jobStatus(id) { - var ref; - return (ref = this.status[this.jobs[id]]) != null ? ref : null; - } +var fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/; - statusJobs(status) { - var k, pos, ref, results, v; - if (status != null) { - pos = this.status.indexOf(status); - if (pos < 0) { - throw new BottleneckError$2(`status must be one of ${this.status.join(', ')}`); - } - ref = this.jobs; - results = []; - for (k in ref) { - v = ref[k]; - if (v === pos) { - results.push(k); - } - } - return results; - } else { - return Object.keys(this.jobs); - } - } +/** + * 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 + */ - statusCounts() { - return this.counts.reduce(((acc, v, i) => { - acc[this.status[i]] = v; - return acc; - }), {}); - } +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; - var States_1 = States; + for (var i = 0; i < pairs.length; i++) { + var pair = pairs[i]; + var eq_idx = pair.indexOf('='); - var DLList$2, Sync, - splice = [].splice; + // skip things that don't look like key=value + if (eq_idx < 0) { + continue; + } - DLList$2 = DLList_1; + var key = pair.substr(0, eq_idx).trim() + var val = pair.substr(++eq_idx, pair.length).trim(); - Sync = class Sync { - constructor(name, Promise) { - this.submit = this.submit.bind(this); - this.name = name; - this.Promise = Promise; - this._running = 0; - this._queue = new DLList$2(); - } + // quoted values + if ('"' == val[0]) { + val = val.slice(1, -1); + } - isEmpty() { - return this._queue.length === 0; - } + // only assign once + if (undefined == obj[key]) { + obj[key] = tryDecode(val, dec); + } + } - _tryToRun() { - var next; - if ((this._running < 1) && this._queue.length > 0) { - this._running++; - next = this._queue.shift(); - return next.task(...next.args, (...args) => { - this._running--; - this._tryToRun(); - return typeof next.cb === "function" ? next.cb(...args) : void 0; - }); - } - } + return obj; +} - submit(task, ...args) { - var cb, ref; - ref = args, [...args] = ref, [cb] = splice.call(args, -1); - this._queue.push({task, args, cb}); - return this._tryToRun(); - } +/** + * 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 + */ - schedule(task, ...args) { - var wrapped; - wrapped = function(...args) { - var cb, ref; - ref = args, [...args] = ref, [cb] = splice.call(args, -1); - return (task(...args)).then(function(...args) { - return cb(null, ...args); - }).catch(function(...args) { - return cb(...args); - }); - }; - return new this.Promise((resolve, reject) => { - return this.submit(wrapped, ...args, function(...args) { - return (args[0] != null ? reject : (args.shift(), resolve))(...args); - }); - }); - } +function serialize(name, val, options) { + var opt = options || {}; + var enc = opt.encode || encode; - }; + if (typeof enc !== 'function') { + throw new TypeError('option encode is invalid'); + } - var Sync_1 = Sync; + if (!fieldContentRegExp.test(name)) { + throw new TypeError('argument name is invalid'); + } - var version = "2.17.1"; - var version$1 = { - version: version - }; + var value = enc(val); - var version$2 = /*#__PURE__*/Object.freeze({ - version: version, - default: version$1 - }); + if (value && !fieldContentRegExp.test(value)) { + throw new TypeError('argument val is invalid'); + } - var require$$2 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); + var str = name + '=' + value; - var require$$3 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); + if (null != opt.maxAge) { + var maxAge = opt.maxAge - 0; + if (isNaN(maxAge)) throw new Error('maxAge should be a Number'); + str += '; Max-Age=' + Math.floor(maxAge); + } - var require$$4 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); + if (opt.domain) { + if (!fieldContentRegExp.test(opt.domain)) { + throw new TypeError('option domain is invalid'); + } - var Events$2, Group, IORedisConnection$1, RedisConnection$1, Scripts$1, parser$2; + str += '; Domain=' + opt.domain; + } - parser$2 = parser; + if (opt.path) { + if (!fieldContentRegExp.test(opt.path)) { + throw new TypeError('option path is invalid'); + } - Events$2 = Events_1; + str += '; Path=' + opt.path; + } - RedisConnection$1 = require$$2; + if (opt.expires) { + if (typeof opt.expires.toUTCString !== 'function') { + throw new TypeError('option expires is invalid'); + } - IORedisConnection$1 = require$$3; + str += '; Expires=' + opt.expires.toUTCString(); + } - Scripts$1 = require$$4; + if (opt.httpOnly) { + str += '; HttpOnly'; + } - Group = (function() { - class Group { - constructor(limiterOptions = {}) { - this.deleteKey = this.deleteKey.bind(this); - this.updateSettings = this.updateSettings.bind(this); - this.limiterOptions = limiterOptions; - parser$2.load(this.limiterOptions, this.defaults, this); - this.Events = new Events$2(this); - this.instances = {}; - this.Bottleneck = Bottleneck_1; - this._startAutoCleanup(); - this.sharedConnection = this.connection != null; - if (this.connection == null) { - if (this.limiterOptions.datastore === "redis") { - this.connection = new RedisConnection$1(Object.assign({}, this.limiterOptions, {Events: this.Events})); - } else if (this.limiterOptions.datastore === "ioredis") { - this.connection = new IORedisConnection$1(Object.assign({}, this.limiterOptions, {Events: this.Events})); - } - } - } + if (opt.secure) { + str += '; Secure'; + } - key(key = "") { - var ref; - return (ref = this.instances[key]) != null ? ref : (() => { - var limiter; - limiter = this.instances[key] = new this.Bottleneck(Object.assign(this.limiterOptions, { - id: `${this.id}-${key}`, - timeout: this.timeout, - connection: this.connection - })); - this.Events.trigger("created", limiter, key); - return limiter; - })(); - } + if (opt.sameSite) { + var sameSite = typeof opt.sameSite === 'string' + ? opt.sameSite.toLowerCase() : opt.sameSite; - async deleteKey(key = "") { - var deleted, instance; - instance = this.instances[key]; - if (this.connection) { - deleted = (await this.connection.__runCommand__(['del', ...Scripts$1.allKeys(`${this.id}-${key}`)])); - } - if (instance != null) { - delete this.instances[key]; - await instance.disconnect(); - } - return (instance != null) || deleted > 0; - } + 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 str; +} - limiters() { - var k, ref, results, v; - ref = this.instances; - results = []; - for (k in ref) { - v = ref[k]; - results.push({ - key: k, - limiter: v - }); - } - return results; - } +/** + * Try decoding a string using a decoding function. + * + * @param {string} str + * @param {function} decode + * @private + */ - keys() { - return Object.keys(this.instances); - } +function tryDecode(str, decode) { + try { + return decode(str); + } catch (e) { + return str; + } +} - async clusterKeys() { - var cursor, end, found, i, k, keys, len, next, start; - if (this.connection == null) { - return this.Promise.resolve(this.keys()); - } - keys = []; - cursor = null; - start = `b_${this.id}-`.length; - end = "_settings".length; - while (cursor !== 0) { - [next, found] = (await this.connection.__runCommand__(["scan", cursor != null ? cursor : 0, "match", `b_${this.id}-*_settings`, "count", 10000])); - cursor = ~~next; - for (i = 0, len = found.length; i < len; i++) { - k = found[i]; - keys.push(k.slice(start, -end)); - } - } - return keys; - } - _startAutoCleanup() { - var base; - clearInterval(this.interval); - return typeof (base = (this.interval = setInterval(async() => { - var e, k, ref, results, time, v; - time = Date.now(); - ref = this.instances; - results = []; - for (k in ref) { - v = ref[k]; - try { - if ((await v._store.__groupCheck__(time))) { - results.push(this.deleteKey(k)); - } else { - results.push(void 0); - } - } catch (error) { - e = error; - results.push(v.Events.trigger("error", e)); - } - } - return results; - }, this.timeout / 2))).unref === "function" ? base.unref() : void 0; - } +/***/ }), - updateSettings(options = {}) { - parser$2.overwrite(options, this.defaults, this); - parser$2.overwrite(options, options, this.limiterOptions); - if (options.timeout != null) { - return this._startAutoCleanup(); - } - } +/***/ 51512: +/***/ (function(module) { - disconnect(flush = true) { - var ref; - if (!this.sharedConnection) { - return (ref = this.connection) != null ? ref.disconnect(flush) : void 0; - } - } +/* + * Date Format 1.2.3 + * (c) 2007-2009 Steven Levithan + * MIT license + * + * Includes enhancements by Scott Trenda + * and Kris Kowal + * + * Accepts a date, a mask, or a date and a mask. + * Returns a formatted version of the given date. + * The date defaults to the current date/time. + * The mask defaults to dateFormat.masks.default. + */ - } - Group.prototype.defaults = { - timeout: 1000 * 60 * 5, - connection: null, - Promise: Promise, - id: "group-key" - }; +(function(global) { + 'use strict'; - return Group; + var dateFormat = (function() { + var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZWN]|"[^"]*"|'[^']*'/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; + + // Regexes and supporting functions are cached through closure + return function (date, mask, utc, gmt) { + + // You can't provide utc if you skip other args (use the 'UTC:' mask prefix) + if (arguments.length === 1 && kindOf(date) === 'string' && !/\d/.test(date)) { + mask = date; + date = undefined; + } + + date = 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']); + + // Allow setting the utc/gmt argument via the mask + var maskSlice = mask.slice(0, 4); + if (maskSlice === 'UTC:' || maskSlice === 'GMT:') { + mask = mask.slice(4); + utc = true; + if (maskSlice === 'GMT:') { + gmt = true; + } + } + + var _ = utc ? 'getUTC' : 'get'; + var d = date[_ + 'Date'](); + var D = date[_ + 'Day'](); + var m = date[_ + 'Month'](); + var y = date[_ + 'FullYear'](); + var H = date[_ + 'Hours'](); + var M = date[_ + 'Minutes'](); + var s = date[_ + 'Seconds'](); + var L = date[_ + 'Milliseconds'](); + var o = utc ? 0 : date.getTimezoneOffset(); + var W = getWeek(date); + var N = getDayOfWeek(date); + var flags = { + d: d, + dd: pad(d), + ddd: dateFormat.i18n.dayNames[D], + dddd: dateFormat.i18n.dayNames[D + 7], + m: m + 1, + mm: pad(m + 1), + mmm: dateFormat.i18n.monthNames[m], + mmmm: dateFormat.i18n.monthNames[m + 12], + yy: String(y).slice(2), + yyyy: y, + h: H % 12 || 12, + hh: pad(H % 12 || 12), + H: H, + HH: pad(H), + M: M, + MM: pad(M), + s: s, + ss: pad(s), + l: pad(L, 3), + L: pad(Math.round(L / 10)), + t: H < 12 ? dateFormat.i18n.timeNames[0] : dateFormat.i18n.timeNames[1], + tt: H < 12 ? dateFormat.i18n.timeNames[2] : dateFormat.i18n.timeNames[3], + T: H < 12 ? dateFormat.i18n.timeNames[4] : dateFormat.i18n.timeNames[5], + TT: H < 12 ? dateFormat.i18n.timeNames[6] : dateFormat.i18n.timeNames[7], + Z: gmt ? 'GMT' : utc ? 'UTC' : (String(date).match(timezone) || ['']).pop().replace(timezoneClip, ''), + o: (o > 0 ? '-' : '+') + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4), + S: ['th', 'st', 'nd', 'rd'][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10], + W: W, + N: N + }; + + return mask.replace(token, function (match) { + if (match in flags) { + return flags[match]; + } + return match.slice(1, match.length - 1); + }); + }; + })(); - }).call(commonjsGlobal); + dateFormat.masks = { + 'default': 'ddd mmm dd yyyy HH:MM:ss', + 'shortDate': 'm/d/yy', + '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' + }; - var Group_1 = Group; + // Internationalization strings + 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 Batcher, Events$3, parser$3; +function pad(val, len) { + val = String(val); + len = len || 2; + while (val.length < len) { + val = '0' + val; + } + return val; +} - parser$3 = parser; +/** + * Get the ISO 8601 week number + * Based on comments from + * http://techblog.procurios.nl/k/n618/news/view/33796/14863/Calculate-ISO-8601-week-and-year-in-javascript.html + * + * @param {Object} `date` + * @return {Number} + */ +function getWeek(date) { + // Remove time components of date + var targetThursday = new Date(date.getFullYear(), date.getMonth(), date.getDate()); - Events$3 = Events_1; + // Change date to Thursday same week + targetThursday.setDate(targetThursday.getDate() - ((targetThursday.getDay() + 6) % 7) + 3); - Batcher = (function() { - class Batcher { - constructor(options = {}) { - this.options = options; - parser$3.load(this.options, this.defaults, this); - this.Events = new Events$3(this); - this._arr = []; - this._resetPromise(); - this._lastFlush = Date.now(); - } + // Take January 4th as it is always in week 1 (see ISO 8601) + var firstThursday = new Date(targetThursday.getFullYear(), 0, 4); - _resetPromise() { - return this._promise = new this.Promise((res, rej) => { - return this._resolve = res; - }); - } + // Change date to Thursday same week + firstThursday.setDate(firstThursday.getDate() - ((firstThursday.getDay() + 6) % 7) + 3); - _flush() { - clearTimeout(this._timeout); - this._lastFlush = Date.now(); - this._resolve(); - this.Events.trigger("batch", this._arr); - this._arr = []; - return this._resetPromise(); - } + // Check if daylight-saving-time-switch occurred and correct for it + var ds = targetThursday.getTimezoneOffset() - firstThursday.getTimezoneOffset(); + targetThursday.setHours(targetThursday.getHours() - ds); - add(data) { - var ret; - this._arr.push(data); - ret = this._promise; - if (this._arr.length === this.maxSize) { - this._flush(); - } else if ((this.maxTime != null) && this._arr.length === 1) { - this._timeout = setTimeout(() => { - return this._flush(); - }, this.maxTime); - } - return ret; - } + // Number of weeks between target Thursday and first Thursday + var weekDiff = (targetThursday - firstThursday) / (86400000*7); + return 1 + Math.floor(weekDiff); +} - } - Batcher.prototype.defaults = { - maxTime: null, - maxSize: null, - Promise: Promise - }; +/** + * Get ISO-8601 numeric representation of the day of the week + * 1 (for Monday) through 7 (for Sunday) + * + * @param {Object} `date` + * @return {Number} + */ +function getDayOfWeek(date) { + var dow = date.getDay(); + if(dow === 0) { + dow = 7; + } + return dow; +} - return Batcher; +/** + * kind-of shortcut + * @param {*} val + * @return {String} + */ +function kindOf(val) { + if (val === null) { + return 'null'; + } - }).call(commonjsGlobal); + if (val === undefined) { + return 'undefined'; + } - var Batcher_1 = Batcher; + if (typeof val !== 'object') { + return typeof val; + } - var require$$3$1 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); + if (Array.isArray(val)) { + return 'array'; + } - var require$$7 = getCjsExportFromNamespace(version$2); + return {}.toString.call(val) + .slice(8, -1).toLowerCase(); +}; - var Bottleneck, DEFAULT_PRIORITY, Events$4, LocalDatastore$1, NUM_PRIORITIES, Queues$1, RedisDatastore$1, States$1, Sync$1, parser$4, - splice$1 = [].splice; - NUM_PRIORITIES = 10; - DEFAULT_PRIORITY = 5; + if (typeof define === 'function' && define.amd) { + define(function () { + return dateFormat; + }); + } else if (true) { + module.exports = dateFormat; + } else {} +})(this); - parser$4 = parser; - Queues$1 = Queues_1; +/***/ }), - LocalDatastore$1 = LocalDatastore_1; +/***/ 84697: +/***/ ((module) => { - RedisDatastore$1 = require$$3$1; +/** + * Helpers. + */ - Events$4 = Events_1; +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var w = d * 7; +var y = d * 365.25; - States$1 = States_1; +/** + * 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 + */ - Sync$1 = Sync_1; +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) + ); +}; - Bottleneck = (function() { - class Bottleneck { - constructor(options = {}, ...invalid) { - var storeInstanceOptions, storeOptions; - this._drainOne = this._drainOne.bind(this); - this.submit = this.submit.bind(this); - this.schedule = this.schedule.bind(this); - this.updateSettings = this.updateSettings.bind(this); - this.incrementReservoir = this.incrementReservoir.bind(this); - this._validateOptions(options, invalid); - parser$4.load(options, this.instanceDefaults, this); - this._queues = new Queues$1(NUM_PRIORITIES); - this._scheduled = {}; - this._states = new States$1(["RECEIVED", "QUEUED", "RUNNING", "EXECUTING"].concat(this.trackDoneStatus ? ["DONE"] : [])); - this._limiter = null; - this.Events = new Events$4(this); - this._submitLock = new Sync$1("submit", this.Promise); - this._registerLock = new Sync$1("register", this.Promise); - storeOptions = parser$4.load(options, this.storeDefaults, {}); - this._store = (function() { - if (this.datastore === "redis" || this.datastore === "ioredis" || (this.connection != null)) { - storeInstanceOptions = parser$4.load(options, this.redisStoreDefaults, {}); - return new RedisDatastore$1(this, storeOptions, storeInstanceOptions); - } else if (this.datastore === "local") { - storeInstanceOptions = parser$4.load(options, this.localStoreDefaults, {}); - return new LocalDatastore$1(this, storeOptions, storeInstanceOptions); - } else { - throw new Bottleneck.prototype.BottleneckError(`Invalid datastore type: ${this.datastore}`); - } - }).call(this); - this._queues.on("leftzero", () => { - var base; - return typeof (base = this._store.heartbeat).ref === "function" ? base.ref() : void 0; - }); - this._queues.on("zero", () => { - var base; - return typeof (base = this._store.heartbeat).unref === "function" ? base.unref() : void 0; - }); - } +/** + * 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 + */ - _validateOptions(options, invalid) { - if (!((options != null) && typeof options === "object" && invalid.length === 0)) { - throw new Bottleneck.prototype.BottleneckError("Bottleneck v2 takes a single object argument. Refer to https://github.com/SGrondin/bottleneck#upgrading-to-v2 if you're upgrading from Bottleneck v1."); - } - } +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'; +} - ready() { - return this._store.ready; - } +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ - clients() { - return this._store.clients; - } +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'; +} - channel() { - return `b_${this.id}`; - } +/** + * Pluralization helper. + */ - channel_client() { - return `b_${this.id}_${this._store.clientId}`; - } +function plural(ms, msAbs, n, name) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); +} - publish(message) { - return this._store.__publish__(message); - } - disconnect(flush = true) { - return this._store.__disconnect__(flush); - } +/***/ }), - chain(_limiter) { - this._limiter = _limiter; - return this; - } +/***/ 28222: +/***/ ((module, exports, __nccwpck_require__) => { - queued(priority) { - return this._queues.queued(priority); - } +/* eslint-env browser */ - clusterQueued() { - return this._store.__queued__(); - } +/** + * This is the web browser implementation of `debug()`. + */ - empty() { - return this.queued() === 0 && this._submitLock.isEmpty(); - } +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = localstorage(); +exports.destroy = (() => { + let warned = false; - running() { - return this._store.__running__(); - } + 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`.'); + } + }; +})(); - done() { - return this._store.__done__(); - } +/** + * Colors. + */ - jobStatus(id) { - return this._states.jobStatus(id); - } +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' +]; - jobs(status) { - return this._states.statusJobs(status); - } +/** + * 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 + */ - counts() { - return this._states.statusCounts(); - } +// 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; + } - _sanitizePriority(priority) { - var sProperty; - sProperty = ~~priority !== priority ? DEFAULT_PRIORITY : priority; - if (sProperty < 0) { - return 0; - } else if (sProperty > NUM_PRIORITIES - 1) { - return NUM_PRIORITIES - 1; - } else { - return sProperty; - } - } + // Internet Explorer and Edge do not support colors. + if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; + } - _randomIndex() { - return Math.random().toString(36).slice(2); - } + // 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+)/)); +} - check(weight = 1) { - return this._store.__check__(weight); - } +/** + * Colorize log arguments if enabled. + * + * @api public + */ - _run(next, wait, index, retryCount) { - var completed, done; - this.Events.trigger("debug", `Scheduling ${next.options.id}`, { - args: next.args, - options: next.options - }); - done = false; - completed = async(...args) => { - var e, error, eventInfo, retry, retryAfter, running; - if (!done) { - try { - done = true; - clearTimeout(this._scheduled[index].expiration); - delete this._scheduled[index]; - eventInfo = { - args: next.args, - options: next.options, - retryCount - }; - if ((error = args[0]) != null) { - retry = (await this.Events.trigger("failed", error, eventInfo)); - if (retry != null) { - retryAfter = ~~retry; - this.Events.trigger("retry", `Retrying ${next.options.id} after ${retryAfter} ms`, eventInfo); - return this._run(next, retryAfter, index, retryCount + 1); - } - } - this._states.next(next.options.id); // DONE - this.Events.trigger("debug", `Completed ${next.options.id}`, eventInfo); - this.Events.trigger("done", `Completed ${next.options.id}`, eventInfo); - ({running} = (await this._store.__free__(index, next.options.weight))); - this.Events.trigger("debug", `Freed ${next.options.id}`, eventInfo); - if (running === 0 && this.empty()) { - this.Events.trigger("idle"); - } - return typeof next.cb === "function" ? next.cb(...args) : void 0; - } catch (error1) { - e = error1; - return this.Events.trigger("error", e); - } - } - }; - if (retryCount === 0) { // RUNNING - this._states.next(next.options.id); - } - return this._scheduled[index] = { - timeout: setTimeout(() => { - this.Events.trigger("debug", `Executing ${next.options.id}`, { - args: next.args, - options: next.options - }); - if (retryCount === 0) { // EXECUTING - this._states.next(next.options.id); - } - if (this._limiter != null) { - return this._limiter.submit(next.options, next.task, ...next.args, completed); - } else { - return next.task(...next.args, completed); - } - }, wait), - expiration: next.options.expiration != null ? setTimeout(() => { - return completed(new Bottleneck.prototype.BottleneckError(`This job timed out after ${next.options.expiration} ms.`)); - }, wait + next.options.expiration) : void 0, - job: next - }; - } +function formatArgs(args) { + args[0] = (this.useColors ? '%c' : '') + + this.namespace + + (this.useColors ? ' %c' : ' ') + + args[0] + + (this.useColors ? '%c ' : ' ') + + '+' + module.exports.humanize(this.diff); - _drainOne(capacity) { - return this._registerLock.schedule(() => { - var args, index, next, options, queue; - if (this.queued() === 0) { - return this.Promise.resolve(null); - } - queue = this._queues.getFirst(); - ({options, args} = next = queue.first()); - if ((capacity != null) && options.weight > capacity) { - return this.Promise.resolve(null); - } - this.Events.trigger("debug", `Draining ${options.id}`, {args, options}); - index = this._randomIndex(); - return this._store.__register__(index, options.weight, options.expiration).then(({success, wait, reservoir}) => { - var empty; - this.Events.trigger("debug", `Drained ${options.id}`, {success, args, options}); - if (success) { - queue.shift(); - empty = this.empty(); - if (empty) { - this.Events.trigger("empty"); - } - if (reservoir === 0) { - this.Events.trigger("depleted", empty); - } - this._run(next, wait, index, 0); - return this.Promise.resolve(options.weight); - } else { - return this.Promise.resolve(null); - } - }); - }); - } + if (!this.useColors) { + return; + } - _drainAll(capacity, total = 0) { - return this._drainOne(capacity).then((drained) => { - var newCapacity; - if (drained != null) { - newCapacity = capacity != null ? capacity - drained : capacity; - return this._drainAll(newCapacity, total + drained); - } else { - return this.Promise.resolve(total); - } - }).catch((e) => { - return this.Events.trigger("error", e); - }); - } + const c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit'); - _drop(job, message = "This job has been dropped by Bottleneck") { - if (this._states.remove(job.options.id)) { - if (this.rejectOnDrop) { - if (typeof job.cb === "function") { - job.cb(new Bottleneck.prototype.BottleneckError(message)); - } - } - return this.Events.trigger("dropped", job); - } - } + // 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; + } + }); - _dropAllQueued(message) { - return this._queues.shiftAll((job) => { - return this._drop(job, message); - }); - } + args.splice(lastC, 0, c); +} - stop(options = {}) { - var done, waitForExecuting; - options = parser$4.load(options, this.stopDefaults); - waitForExecuting = (at) => { - var finished; - finished = () => { - var counts; - counts = this._states.counts; - return (counts[0] + counts[1] + counts[2] + counts[3]) === at; - }; - return new this.Promise((resolve, reject) => { - if (finished()) { - return resolve(); - } else { - return this.on("done", () => { - if (finished()) { - this.removeAllListeners("done"); - return resolve(); - } - }); - } - }); - }; - done = options.dropWaitingJobs ? (this._run = (next) => { - return this._drop(next, options.dropErrorMessage); - }, this._drainOne = () => { - return this.Promise.resolve(null); - }, this._registerLock.schedule(() => { - return this._submitLock.schedule(() => { - var k, ref, v; - ref = this._scheduled; - for (k in ref) { - v = ref[k]; - if (this.jobStatus(v.job.options.id) === "RUNNING") { - clearTimeout(v.timeout); - clearTimeout(v.expiration); - this._drop(v.job, options.dropErrorMessage); - } - } - this._dropAllQueued(options.dropErrorMessage); - return waitForExecuting(0); - }); - })) : this.schedule({ - priority: NUM_PRIORITIES - 1, - weight: 0 - }, () => { - return waitForExecuting(1); - }); - this.submit = (...args) => { - var cb, ref; - ref = args, [...args] = ref, [cb] = splice$1.call(args, -1); - return typeof cb === "function" ? cb(new Bottleneck.prototype.BottleneckError(options.enqueueErrorMessage)) : void 0; - }; - this.stop = () => { - return this.Promise.reject(new Bottleneck.prototype.BottleneckError("stop() has already been called")); - }; - return done; - } +/** + * 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 + */ +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 + */ +function load() { + let r; + try { + r = exports.storage.getItem('debug'); + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } - submit(...args) { - var cb, job, options, ref, ref1, task; - if (typeof args[0] === "function") { - ref = args, [task, ...args] = ref, [cb] = splice$1.call(args, -1); - options = parser$4.load({}, this.jobDefaults, {}); - } else { - ref1 = args, [options, task, ...args] = ref1, [cb] = splice$1.call(args, -1); - options = parser$4.load(options, this.jobDefaults); - } - job = {options, task, args, cb}; - options.priority = this._sanitizePriority(options.priority); - if (options.id === this.jobDefaults.id) { - options.id = `${options.id}-${this._randomIndex()}`; - } - if (this.jobStatus(options.id) != null) { - if (typeof job.cb === "function") { - job.cb(new Bottleneck.prototype.BottleneckError(`A job with the same id already exists (id=${options.id})`)); - } - return false; - } - this._states.start(options.id); // RECEIVED - this.Events.trigger("debug", `Queueing ${options.id}`, {args, options}); - return this._submitLock.schedule(async() => { - var blocked, e, reachedHWM, shifted, strategy; - try { - ({reachedHWM, blocked, strategy} = (await this._store.__submit__(this.queued(), options.weight))); - this.Events.trigger("debug", `Queued ${options.id}`, {args, options, reachedHWM, blocked}); - } catch (error1) { - e = error1; - this._states.remove(options.id); - this.Events.trigger("debug", `Could not queue ${options.id}`, { - args, - options, - error: e - }); - if (typeof job.cb === "function") { - job.cb(e); - } - return false; - } - if (blocked) { - this._drop(job); - return true; - } else if (reachedHWM) { - shifted = strategy === Bottleneck.prototype.strategy.LEAK ? this._queues.shiftLastFrom(options.priority) : strategy === Bottleneck.prototype.strategy.OVERFLOW_PRIORITY ? this._queues.shiftLastFrom(options.priority + 1) : strategy === Bottleneck.prototype.strategy.OVERFLOW ? job : void 0; - if (shifted != null) { - this._drop(shifted); - } - if ((shifted == null) || strategy === Bottleneck.prototype.strategy.OVERFLOW) { - if (shifted == null) { - this._drop(job); - } - return reachedHWM; - } - } - this._states.next(job.options.id); // QUEUED - this._queues.push(options.priority, job); - await this._drainAll(); - return reachedHWM; - }); - } + // 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; + } - schedule(...args) { - var options, task, wrapped; - if (typeof args[0] === "function") { - [task, ...args] = args; - options = parser$4.load({}, this.jobDefaults, {}); - } else { - [options, task, ...args] = args; - options = parser$4.load(options, this.jobDefaults); - } - wrapped = (...args) => { - var cb, e, ref, returned; - ref = args, [...args] = ref, [cb] = splice$1.call(args, -1); - returned = (function() { - try { - return task(...args); - } catch (error1) { - e = error1; - return this.Promise.reject(e); - } - }).call(this); - return (!(((returned != null ? returned.then : void 0) != null) && typeof returned.then === "function") ? this.Promise.resolve(returned) : returned).then(function(...args) { - return cb(null, ...args); - }).catch(function(...args) { - return cb(...args); - }); - }; - return new this.Promise((resolve, reject) => { - return this.submit(options, wrapped, ...args, function(...args) { - return (args[0] != null ? reject : (args.shift(), resolve))(...args); - }).catch((e) => { - return this.Events.trigger("error", e); - }); - }); - } + return r; +} - wrap(fn) { - var schedule, wrapped; - schedule = this.schedule; - wrapped = function(...args) { - return schedule(fn.bind(this), ...args); - }; - wrapped.withOptions = (options, ...args) => { - return schedule(options, fn, ...args); - }; - return wrapped; - } +/** + * 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 + */ - async updateSettings(options = {}) { - await this._store.__updateSettings__(parser$4.overwrite(options, this.storeDefaults)); - parser$4.overwrite(options, this.instanceDefaults, this); - return this; - } +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? + } +} - currentReservoir() { - return this._store.__currentReservoir__(); - } +module.exports = __nccwpck_require__(46243)(exports); - incrementReservoir(incr = 0) { - return this._store.__incrementReservoir__(incr); - } +const {formatters} = module.exports; - } - Bottleneck.default = Bottleneck; +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ - Bottleneck.Events = Events$4; +formatters.j = function (v) { + try { + return JSON.stringify(v); + } catch (error) { + return '[UnexpectedJSONParseError]: ' + error.message; + } +}; - Bottleneck.version = Bottleneck.prototype.version = require$$7.version; - Bottleneck.strategy = Bottleneck.prototype.strategy = { - LEAK: 1, - OVERFLOW: 2, - OVERFLOW_PRIORITY: 4, - BLOCK: 3 - }; +/***/ }), - Bottleneck.BottleneckError = Bottleneck.prototype.BottleneckError = BottleneckError_1; +/***/ 46243: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - Bottleneck.Group = Bottleneck.prototype.Group = Group_1; - Bottleneck.RedisConnection = Bottleneck.prototype.RedisConnection = require$$2; +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + */ - Bottleneck.IORedisConnection = Bottleneck.prototype.IORedisConnection = require$$3; +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__(84697); + createDebug.destroy = destroy; - Bottleneck.Batcher = Bottleneck.prototype.Batcher = Batcher_1; + Object.keys(env).forEach(key => { + createDebug[key] = env[key]; + }); - Bottleneck.prototype.jobDefaults = { - priority: DEFAULT_PRIORITY, - weight: 1, - expiration: null, - id: "" - }; + /** + * The currently active debug mode names, and names to skip. + */ - Bottleneck.prototype.storeDefaults = { - maxConcurrent: null, - minTime: 0, - highWater: null, - strategy: Bottleneck.prototype.strategy.LEAK, - penalty: null, - reservoir: null, - reservoirRefreshInterval: null, - reservoirRefreshAmount: null - }; + createDebug.names = []; + createDebug.skips = []; - Bottleneck.prototype.localStoreDefaults = { - Promise: Promise, - timeout: null, - heartbeatInterval: 250 - }; + /** + * 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 = {}; - Bottleneck.prototype.redisStoreDefaults = { - Promise: Promise, - timeout: null, - heartbeatInterval: 5000, - clientTimeout: 10000, - clientOptions: {}, - clusterNodes: null, - clearDatastore: false, - connection: null - }; + /** + * 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; - Bottleneck.prototype.instanceDefaults = { - datastore: "local", - connection: null, - id: "", - rejectOnDrop: true, - trackDoneStatus: false, - Promise: Promise - }; + for (let i = 0; i < namespace.length; i++) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } - Bottleneck.prototype.stopDefaults = { - enqueueErrorMessage: "This limiter has been stopped and cannot accept new jobs.", - dropWaitingJobs: true, - dropErrorMessage: "This limiter has been stopped." - }; + return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; + } + createDebug.selectColor = selectColor; - return Bottleneck; + /** + * 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; - }).call(commonjsGlobal); + function debug(...args) { + // Disabled? + if (!debug.enabled) { + return; + } - var Bottleneck_1 = Bottleneck; + const self = debug; - var lib = Bottleneck_1; + // Set `diff` timestamp + const curr = Number(new Date()); + const ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; - return lib; + args[0] = createDebug.coerce(args[0]); -}))); + if (typeof args[0] !== 'string') { + // Anything else let's inspect with %O + args.unshift('%O'); + } + // 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); -/***/ }), + // Now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); -/***/ 9239: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // Apply env-specific formatting (colors, etc.) + createDebug.formatArgs.call(self, args); -"use strict"; -/*jshint node:true */ + const logFn = self.log || createDebug.log; + logFn.apply(self, args); + } -var Buffer = (__nccwpck_require__(14300).Buffer); // browserify -var SlowBuffer = (__nccwpck_require__(14300).SlowBuffer); + 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. -module.exports = bufferEq; + 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); + } -function bufferEq(a, b) { + return enabledCache; + }, + set: v => { + enableOverride = v; + } + }); - // shortcutting on type is necessary for correctness - if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { - return false; - } + // Env-specific initialization logic for debug instances + if (typeof createDebug.init === 'function') { + createDebug.init(debug); + } - // buffer sizes should be well-known information, so despite this - // shortcutting, it doesn't leak any information about the *contents* of the - // buffers. - if (a.length !== b.length) { - return false; - } + return debug; + } - var c = 0; - for (var i = 0; i < a.length; i++) { - /*jshint bitwise:false */ - c |= a[i] ^ b[i]; // XOR - } - return c === 0; -} + function extend(namespace, delimiter) { + const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); + newDebug.log = this.log; + return newDebug; + } -bufferEq.install = function() { - Buffer.prototype.equal = SlowBuffer.prototype.equal = function equal(that) { - return bufferEq(this, that); - }; -}; + /** + * 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 origBufEqual = Buffer.prototype.equal; -var origSlowBufEqual = SlowBuffer.prototype.equal; -bufferEq.restore = function() { - Buffer.prototype.equal = origBufEqual; - SlowBuffer.prototype.equal = origSlowBufEqual; -}; + createDebug.names = []; + createDebug.skips = []; + let i; + const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + const len = split.length; -/***/ }), + for (i = 0; i < len; i++) { + if (!split[i]) { + // ignore empty strings + continue; + } -/***/ 86966: -/***/ ((module) => { + namespaces = split[i].replace(/\*/g, '.*?'); -"use strict"; -/*! - * bytes - * Copyright(c) 2012-2014 TJ Holowaychuk - * Copyright(c) 2015 Jed Watson - * MIT Licensed - */ + if (namespaces[0] === '-') { + createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); + } else { + createDebug.names.push(new RegExp('^' + namespaces + '$')); + } + } + } + + /** + * 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; + } + + /** + * 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; + } + + let i; + let len; + + 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; + } + + /** + * 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(/\.\*\?$/, '*'); + } + + /** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + function coerce(val) { + if (val instanceof Error) { + return val.stack || val.message; + } + return 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`.'); + } + + createDebug.enable(createDebug.load()); + + return createDebug; +} +module.exports = setup; -/** - * Module exports. - * @public - */ +/***/ }), -module.exports = bytes; -module.exports.format = format; -module.exports.parse = parse; +/***/ 38237: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { /** - * Module variables. - * @private + * Detect Electron renderer / nwjs process, which is node, but we should + * treat as a browser. */ -var formatThousandsRegExp = /\B(?=(\d{3})+(?!\d))/g; +if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { + module.exports = __nccwpck_require__(28222); +} else { + module.exports = __nccwpck_require__(35332); +} -var formatDecimalsRegExp = /(?:\.0*|(\.[^0]+)0+)$/; -var map = { - b: 1, - kb: 1 << 10, - mb: 1 << 20, - gb: 1 << 30, - tb: Math.pow(1024, 4), - pb: Math.pow(1024, 5), -}; +/***/ }), -var parseRegExp = /^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb|pb)$/i; +/***/ 35332: +/***/ ((module, exports, __nccwpck_require__) => { /** - * Convert the given value in bytes into a string or parse to string to an integer in bytes. - * - * @param {string|number} value - * @param {{ - * case: [string], - * decimalPlaces: [number] - * fixedDecimals: [boolean] - * thousandsSeparator: [string] - * unitSeparator: [string] - * }} [options] bytes options. - * - * @returns {string|number|null} + * Module dependencies. */ -function bytes(value, options) { - if (typeof value === 'string') { - return parse(value); - } - - if (typeof value === 'number') { - return format(value, options); - } - - return null; -} +const tty = __nccwpck_require__(76224); +const util = __nccwpck_require__(73837); /** - * Format the given value in bytes into a string. - * - * If the value is negative, it is kept as such. If it is a float, - * it is rounded. - * - * @param {number} value - * @param {object} [options] - * @param {number} [options.decimalPlaces=2] - * @param {number} [options.fixedDecimals=false] - * @param {string} [options.thousandsSeparator=] - * @param {string} [options.unit=] - * @param {string} [options.unitSeparator=] - * - * @returns {string|null} - * @public + * This is the Node.js implementation of `debug()`. */ -function format(value, options) { - if (!Number.isFinite(value)) { - return null; - } - - var mag = Math.abs(value); - var thousandsSeparator = (options && options.thousandsSeparator) || ''; - var unitSeparator = (options && options.unitSeparator) || ''; - var decimalPlaces = (options && options.decimalPlaces !== undefined) ? options.decimalPlaces : 2; - var fixedDecimals = Boolean(options && options.fixedDecimals); - var unit = (options && options.unit) || ''; - - if (!unit || !map[unit.toLowerCase()]) { - if (mag >= map.pb) { - unit = 'PB'; - } else if (mag >= map.tb) { - unit = 'TB'; - } else if (mag >= map.gb) { - unit = 'GB'; - } else if (mag >= map.mb) { - unit = 'MB'; - } else if (mag >= map.kb) { - unit = 'KB'; - } else { - unit = 'B'; - } - } +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 val = value / map[unit.toLowerCase()]; - var str = val.toFixed(decimalPlaces); +/** + * Colors. + */ - if (!fixedDecimals) { - str = str.replace(formatDecimalsRegExp, '$1'); - } +exports.colors = [6, 2, 3, 4, 5, 1]; - if (thousandsSeparator) { - str = str.replace(formatThousandsRegExp, thousandsSeparator); - } +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 str + unitSeparator + unit; + 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 the string value into an integer in bytes. - * - * If no unit is given, it is assumed the value is in bytes. - * - * @param {number|string} val + * Build up the default `inspectOpts` object from the environment variables. * - * @returns {number|null} - * @public + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js */ -function parse(val) { - if (typeof val === 'number' && !isNaN(val)) { - return val; - } +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 (typeof val !== 'string') { - return null; - } + // 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); + } - // Test if the string passed is valid - var results = parseRegExp.exec(val); - var floatValue; - var unit = 'b'; + obj[prop] = val; + return obj; +}, {}); - if (!results) { - // Nothing could be extracted from the given string - floatValue = parseInt(val, 10); - unit = 'b' - } else { - // Retrieve the value and the unit - floatValue = parseFloat(results[1]); - unit = results[4].toLowerCase(); - } +/** + * Is stdout a TTY? Colored output is enabled when `true`. + */ - return Math.floor(map[unit] * floatValue); +function useColors() { + return 'colors' in exports.inspectOpts ? + Boolean(exports.inspectOpts.colors) : + tty.isatty(process.stderr.fd); } +/** + * Adds ANSI color escape codes if enabled. + * + * @api public + */ -/***/ }), - -/***/ 78818: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +function formatArgs(args) { + const {namespace: name, useColors} = this; -"use strict"; + if (useColors) { + const c = this.color; + const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); + const prefix = ` ${colorCode};1m${name} \u001B[0m`; -const ansiStyles = __nccwpck_require__(52068); -const {stdout: stdoutColor, stderr: stderrColor} = __nccwpck_require__(59318); -const { - stringReplaceAll, - stringEncaseCRLFWithFirstIndex -} = __nccwpck_require__(82415); + 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]; + } +} -const {isArray} = Array; +function getDate() { + if (exports.inspectOpts.hideDate) { + return ''; + } + return new Date().toISOString() + ' '; +} -// `supportsColor.level` → `ansiStyles.color[name]` mapping -const levelMapping = [ - 'ansi', - 'ansi', - 'ansi256', - 'ansi16m' -]; +/** + * Invokes `util.format()` with the specified arguments and writes to stderr. + */ -const styles = Object.create(null); +function log(...args) { + return process.stderr.write(util.format(...args) + '\n'); +} -const applyOptions = (object, options = {}) => { - if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) { - throw new Error('The `level` option should be an integer from 0 to 3'); +/** + * 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; } +} - // Detect level if not set manually - const colorLevel = stdoutColor ? stdoutColor.level : 0; - object.level = options.level === undefined ? colorLevel : options.level; -}; +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ -class ChalkClass { - constructor(options) { - // eslint-disable-next-line no-constructor-return - return chalkFactory(options); - } +function load() { + return process.env.DEBUG; } -const chalkFactory = options => { - const chalk = {}; - applyOptions(chalk, options); +/** + * Init logic for `debug` instances. + * + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. + */ - chalk.template = (...arguments_) => chalkTag(chalk.template, ...arguments_); +function init(debug) { + debug.inspectOpts = {}; - Object.setPrototypeOf(chalk, Chalk.prototype); - Object.setPrototypeOf(chalk.template, chalk); + const keys = Object.keys(exports.inspectOpts); + for (let i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } +} - chalk.template.constructor = () => { - throw new Error('`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.'); - }; +module.exports = __nccwpck_require__(46243)(exports); - chalk.template.Instance = ChalkClass; +const {formatters} = module.exports; - return chalk.template; -}; +/** + * Map %o to `util.inspect()`, all on a single line. + */ -function Chalk(options) { - return chalkFactory(options); -} +formatters.o = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts) + .split('\n') + .map(str => str.trim()) + .join(' '); +}; -for (const [styleName, style] of Object.entries(ansiStyles)) { - styles[styleName] = { - get() { - const builder = createBuilder(this, createStyler(style.open, style.close, this._styler), this._isEmpty); - Object.defineProperty(this, styleName, {value: builder}); - return builder; - } - }; -} +/** + * Map %O to `util.inspect()`, allowing multiple lines if needed. + */ -styles.visible = { - get() { - const builder = createBuilder(this, this._styler, true); - Object.defineProperty(this, 'visible', {value: builder}); - return builder; - } +formatters.O = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); }; -const usedModels = ['rgb', 'hex', 'keyword', 'hsl', 'hsv', 'hwb', 'ansi', 'ansi256']; -for (const model of usedModels) { - styles[model] = { - get() { - const {level} = this; - return function (...arguments_) { - const styler = createStyler(ansiStyles.color[levelMapping[level]][model](...arguments_), ansiStyles.color.close, this._styler); - return createBuilder(this, styler, this._isEmpty); - }; - } - }; -} +/***/ }), -for (const model of usedModels) { - const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); - styles[bgModel] = { - get() { - const {level} = this; - return function (...arguments_) { - const styler = createStyler(ansiStyles.bgColor[levelMapping[level]][model](...arguments_), ansiStyles.bgColor.close, this._styler); - return createBuilder(this, styler, this._isEmpty); - }; - } - }; -} +/***/ 56323: +/***/ ((module) => { -const proto = Object.defineProperties(() => {}, { - ...styles, - level: { - enumerable: true, - get() { - return this._generator.level; - }, - set(level) { - this._generator.level = level; - } - } -}); +"use strict"; -const createStyler = (open, close, parent) => { - let openAll; - let closeAll; - if (parent === undefined) { - openAll = open; - closeAll = close; - } else { - openAll = parent.openAll + open; - closeAll = close + parent.closeAll; - } - return { - open, - close, - openAll, - closeAll, - parent - }; +var isMergeableObject = function isMergeableObject(value) { + return isNonNullObject(value) + && !isSpecial(value) }; -const createBuilder = (self, _styler, _isEmpty) => { - const builder = (...arguments_) => { - if (isArray(arguments_[0]) && isArray(arguments_[0].raw)) { - // Called as a template literal, for example: chalk.red`2 + 3 = {bold ${2+3}}` - return applyStyle(builder, chalkTag(builder, ...arguments_)); - } +function isNonNullObject(value) { + return !!value && typeof value === 'object' +} - // Single argument is hot path, implicit coercion is faster than anything - // eslint-disable-next-line no-implicit-coercion - return applyStyle(builder, (arguments_.length === 1) ? ('' + arguments_[0]) : arguments_.join(' ')); - }; +function isSpecial(value) { + var stringValue = Object.prototype.toString.call(value); - // We alter the prototype because we must return a function, but there is - // no way to create a function with a different prototype - Object.setPrototypeOf(builder, proto); + return stringValue === '[object RegExp]' + || stringValue === '[object Date]' + || isReactElement(value) +} - builder._generator = self; - builder._styler = _styler; - builder._isEmpty = _isEmpty; +// 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 builder; -}; +function isReactElement(value) { + return value.$$typeof === REACT_ELEMENT_TYPE +} + +function emptyTarget(val) { + return Array.isArray(val) ? [] : {} +} -const applyStyle = (self, string) => { - if (self.level <= 0 || !string) { - return self._isEmpty ? '' : string; - } +function cloneUnlessOtherwiseSpecified(value, options) { + return (options.clone !== false && options.isMergeableObject(value)) + ? deepmerge(emptyTarget(value), value, options) + : value +} - let styler = self._styler; +function defaultArrayMerge(target, source, options) { + return target.concat(source).map(function(element) { + return cloneUnlessOtherwiseSpecified(element, options) + }) +} - if (styler === undefined) { - return string; +function getMergeFunction(key, options) { + if (!options.customMerge) { + return deepmerge } + var customMerge = options.customMerge(key); + return typeof customMerge === 'function' ? customMerge : deepmerge +} - const {openAll, closeAll} = styler; - if (string.indexOf('\u001B') !== -1) { - while (styler !== undefined) { - // Replace any instances already present with a re-opening code - // otherwise only the part of the string until said closing code - // will be colored, and the rest will simply be 'plain'. - string = stringReplaceAll(string, styler.close, styler.open); +function getEnumerableOwnPropertySymbols(target) { + return Object.getOwnPropertySymbols + ? Object.getOwnPropertySymbols(target).filter(function(symbol) { + return target.propertyIsEnumerable(symbol) + }) + : [] +} - styler = styler.parent; - } - } +function getKeys(target) { + return Object.keys(target).concat(getEnumerableOwnPropertySymbols(target)) +} - // We can move both next actions out of loop, because remaining actions in loop won't have - // any/visible effect on parts we add here. Close the styling before a linebreak and reopen - // after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92 - const lfIndex = string.indexOf('\n'); - if (lfIndex !== -1) { - string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex); +function propertyIsOnObject(object, property) { + try { + return property in object + } catch(_) { + return false } +} - return openAll + string + closeAll; -}; - -let template; -const chalkTag = (chalk, ...strings) => { - const [firstString] = strings; +// 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 (!isArray(firstString) || !isArray(firstString.raw)) { - // If chalk() was called by itself or with a string, - // return the string itself as a string. - return strings.join(' '); +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 + } - const arguments_ = strings.slice(1); - const parts = [firstString.raw[0]]; + 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 +} - for (let i = 1; i < firstString.length; i++) { - parts.push( - String(arguments_[i - 1]).replace(/[{}\\]/g, '\\$&'), - String(firstString.raw[i]) - ); +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; + + var sourceIsArray = Array.isArray(source); + var targetIsArray = Array.isArray(target); + var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray; + + if (!sourceAndTargetTypesMatch) { + return cloneUnlessOtherwiseSpecified(source, options) + } else if (sourceIsArray) { + return options.arrayMerge(target, source, options) + } else { + return mergeObject(target, source, options) } +} - if (template === undefined) { - template = __nccwpck_require__(20500); +deepmerge.all = function deepmergeAll(array, options) { + if (!Array.isArray(array)) { + throw new Error('first argument should be an array') } - return template(chalk, parts.join('')); + return array.reduce(function(prev, next) { + return deepmerge(prev, next, options) + }, {}) }; -Object.defineProperties(Chalk.prototype, styles); - -const chalk = Chalk(); // eslint-disable-line new-cap -chalk.supportsColor = stdoutColor; -chalk.stderr = Chalk({level: stderrColor ? stderrColor.level : 0}); // eslint-disable-line new-cap -chalk.stderr.supportsColor = stderrColor; +var deepmerge_1 = deepmerge; -module.exports = chalk; +module.exports = deepmerge_1; /***/ }), -/***/ 20500: +/***/ 42342: /***/ ((module) => { "use strict"; -const TEMPLATE_REGEX = /(?:\\(u(?:[a-f\d]{4}|\{[a-f\d]{1,6}\})|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi; -const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g; -const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/; -const ESCAPE_REGEX = /\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.)|([^\\])/gi; -const ESCAPES = new Map([ - ['n', '\n'], - ['r', '\r'], - ['t', '\t'], - ['b', '\b'], - ['f', '\f'], - ['v', '\v'], - ['0', '\0'], - ['\\', '\\'], - ['e', '\u001B'], - ['a', '\u0007'] -]); +/** + * Custom implementation of a double ended queue. + */ +function Denque(array) { + this._head = 0; + this._tail = 0; + this._capacityMask = 0x3; + this._list = new Array(4); + if (Array.isArray(array)) { + this._fromArray(array); + } +} -function unescape(c) { - const u = c[0] === 'u'; - const bracket = c[1] === '{'; +/** + * ------------- + * PUBLIC API + * ------------- + */ - if ((u && !bracket && c.length === 5) || (c[0] === 'x' && c.length === 3)) { - return String.fromCharCode(parseInt(c.slice(1), 16)); - } +/** + * 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]; +}; - if (u && bracket) { - return String.fromCodePoint(parseInt(c.slice(2, -1), 16)); - } +/** + * Alias for peakAt() + * @param i + * @returns {*} + */ +Denque.prototype.get = function get(i) { + return this.peekAt(i); +}; - return ESCAPES.get(c) || c; -} +/** + * 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]; +}; -function parseArguments(name, arguments_) { - const results = []; - const chunks = arguments_.trim().split(/\s*,\s*/g); - let matches; +/** + * Alias for peek() + * @returns {*} + */ +Denque.prototype.peekFront = function peekFront() { + return this.peek(); +}; - for (const chunk of chunks) { - const number = Number(chunk); - if (!Number.isNaN(number)) { - results.push(number); - } else if ((matches = chunk.match(STRING_REGEX))) { - results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, character) => escape ? unescape(escape) : character)); - } else { - throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`); - } - } +/** + * 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); +}; - return results; -} +/** + * Returns the current length of the queue + * @return {Number} + */ +Object.defineProperty(Denque.prototype, 'length', { + get: function length() { + return this.size(); + } +}); -function parseStyle(style) { - STYLE_REGEX.lastIndex = 0; +/** + * 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); +}; - const results = []; - let matches; +/** + * 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._head < this._tail) return this._tail - this._head; + else return this._capacityMask + 1 - (this._head - this._tail); +}; - while ((matches = STYLE_REGEX.exec(style)) !== null) { - const name = matches[1]; +/** + * 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; +}; - if (matches[2]) { - const args = parseArguments(name, matches[2]); - results.push([name].concat(args)); - } else { - results.push([name]); - } - } +/** + * 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(); + } - return results; -} + if (this._head < this._tail) return this._tail - this._head; + else return this._capacityMask + 1 - (this._head - this._tail); +}; + +/** + * 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; +}; + +/** + * 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; +}; + +/** + * 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 (index < 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--; + } + } 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; +}; + +/** + * 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 buildStyle(chalk, styles) { - const enabled = {}; +/** + * Soft clear - does not reset capacity. + */ +Denque.prototype.clear = function clear() { + this._head = 0; + this._tail = 0; +}; - for (const layer of styles) { - for (const style of layer.styles) { - enabled[style[0]] = layer.inverse ? null : style.slice(1); - } - } +/** + * Returns true or false whether the list is empty. + * @returns {boolean} + */ +Denque.prototype.isEmpty = function isEmpty() { + return this._head === this._tail; +}; - let current = chalk; - for (const [styleName, styles] of Object.entries(enabled)) { - if (!Array.isArray(styles)) { - continue; - } +/** + * Returns an array of all queue items. + * @returns {Array} + */ +Denque.prototype.toArray = function toArray() { + return this._copyArray(false); +}; - if (!(styleName in current)) { - throw new Error(`Unknown Chalk style: ${styleName}`); - } +/** + * ------------- + * INTERNALS + * ------------- + */ - current = styles.length > 0 ? current[styleName](...styles) : current[styleName]; - } +/** + * 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 current; -} +/** + * + * @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; +}; -module.exports = (chalk, temporary) => { - const styles = []; - const chunks = []; - let chunk = []; +/** + * 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; + } - // eslint-disable-next-line max-params - temporary.replace(TEMPLATE_REGEX, (m, escapeCharacter, inverse, style, close, character) => { - if (escapeCharacter) { - chunk.push(unescape(escapeCharacter)); - } else if (style) { - const string = chunk.join(''); - chunk = []; - chunks.push(styles.length === 0 ? string : buildStyle(chalk, styles)(string)); - styles.push({inverse, styles: parseStyle(style)}); - } else if (close) { - if (styles.length === 0) { - throw new Error('Found extraneous } in Chalk template literal'); - } + // head is at 0 and array is now full, safe to extend + this._tail = this._list.length; - chunks.push(buildStyle(chalk, styles)(chunk.join(''))); - chunk = []; - styles.pop(); - } else { - chunk.push(character); - } - }); + this._list.length *= 2; + this._capacityMask = (this._capacityMask << 1) | 1; +}; - chunks.push(chunk.join('')); +/** + * Shrinks the internal list array. + * @private + */ +Denque.prototype._shrinkArray = function _shrinkArray() { + this._list.length >>>= 1; + this._capacityMask >>>= 1; +}; - if (styles.length > 0) { - const errMessage = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`; - throw new Error(errMessage); - } - return chunks.join(''); -}; +module.exports = Denque; /***/ }), -/***/ 82415: -/***/ ((module) => { +/***/ 18883: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +/*! + * depd + * Copyright(c) 2014-2017 Douglas Christopher Wilson + * MIT Licensed + */ +/** + * Module dependencies. + */ -const stringReplaceAll = (string, substring, replacer) => { - let index = string.indexOf(substring); - if (index === -1) { - return string; - } +var callSiteToString = (__nccwpck_require__(69829).callSiteToString) +var eventListenerCount = (__nccwpck_require__(69829).eventListenerCount) +var relative = (__nccwpck_require__(71017).relative) - const substringLength = substring.length; - let endIndex = 0; - let returnValue = ''; - do { - returnValue += string.substr(endIndex, index - endIndex) + substring + replacer; - endIndex = index + substringLength; - index = string.indexOf(substring, endIndex); - } while (index !== -1); +/** + * Module exports. + */ - returnValue += string.substr(endIndex); - return returnValue; -}; +module.exports = depd -const stringEncaseCRLFWithFirstIndex = (string, prefix, postfix, index) => { - let endIndex = 0; - let returnValue = ''; - do { - const gotCR = string[index - 1] === '\r'; - returnValue += string.substr(endIndex, (gotCR ? index - 1 : index) - endIndex) + prefix + (gotCR ? '\r\n' : '\n') + postfix; - endIndex = index + 1; - index = string.indexOf('\n', endIndex); - } while (index !== -1); +/** + * Get the path to base files on. + */ - returnValue += string.substr(endIndex); - return returnValue; -}; +var basePath = process.cwd() -module.exports = { - stringReplaceAll, - stringEncaseCRLFWithFirstIndex -}; +/** + * Determine if namespace is contained in the string. + */ +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] -/***/ 27972: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // namespace contained + if (val && (val === '*' || val.toLowerCase() === ns)) { + return true + } + } -"use strict"; + return false +} -const os = __nccwpck_require__(22037); +/** + * Convert a data descriptor to accessor descriptor. + */ -const extractPathRegex = /\s+at.*(?:\(|\s)(.*)\)?/; -const pathRegex = /^(?:(?:(?:node|(?:internal\/[\w/]*|.*node_modules\/(?:babel-polyfill|pirates)\/.*)?\w+)\.js:\d+:\d+)|native)/; -const homeDir = typeof os.homedir === 'undefined' ? '' : os.homedir(); +function convertDataDescriptorToAccessor (obj, prop, message) { + var descriptor = Object.getOwnPropertyDescriptor(obj, prop) + var value = descriptor.value -module.exports = (stack, options) => { - options = Object.assign({pretty: false}, options); + descriptor.get = function getter () { return value } - return stack.replace(/\\/g, '/') - .split('\n') - .filter(line => { - const pathMatches = line.match(extractPathRegex); - if (pathMatches === null || !pathMatches[1]) { - return true; - } + if (descriptor.writable) { + descriptor.set = function setter (val) { return (value = val) } + } - const match = pathMatches[1]; + delete descriptor.value + delete descriptor.writable - // Electron - if ( - match.includes('.app/Contents/Resources/electron.asar') || - match.includes('.app/Contents/Resources/default_app.asar') - ) { - return false; - } + Object.defineProperty(obj, prop, descriptor) - return !pathRegex.test(match); - }) - .filter(line => line.trim() !== '') - .map(line => { - if (options.pretty) { - return line.replace(extractPathRegex, (m, p1) => m.replace(p1, p1.replace(homeDir, '~'))); - } + return descriptor +} - return line; - }) - .join('\n'); -}; +/** + * Create arguments string to keep arity. + */ +function createArgumentsString (arity) { + var str = '' -/***/ }), + for (var i = 0; i < arity; i++) { + str += ', arg' + i + } -/***/ 2101: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return str.substr(2) +} -module.exports = __nccwpck_require__(16136); +/** + * Create stack string from stack. + */ -/***/ }), +function createStackString (stack) { + var str = this.name + ': ' + this.namespace -/***/ 66168: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (this.message) { + str += ' deprecated ' + this.message + } -const utils = __nccwpck_require__(98911); + for (var i = 0; i < stack.length; i++) { + str += '\n at ' + callSiteToString(stack[i]) + } -class Cell { - /** - * A representation of a cell within the table. - * Implementations must have `init` and `draw` methods, - * as well as `colSpan`, `rowSpan`, `desiredHeight` and `desiredWidth` properties. - * @param options - * @constructor - */ - constructor(options) { - this.setOptions(options); + return str +} - /** - * Each cell will have it's `x` and `y` values set by the `layout-manager` prior to - * `init` being called; - * @type {Number} - */ - this.x = null; - this.y = null; - } +/** + * Create deprecate for namespace in caller. + */ - setOptions(options) { - if (['boolean', 'number', 'string'].indexOf(typeof options) !== -1) { - options = { content: '' + options }; - } - options = options || {}; - this.options = options; - let content = options.content; - if (['boolean', 'number', 'string'].indexOf(typeof content) !== -1) { - this.content = String(content); - } else if (!content) { - this.content = ''; - } else { - throw new Error('Content needs to be a primitive, got: ' + typeof content); - } - this.colSpan = options.colSpan || 1; - this.rowSpan = options.rowSpan || 1; +function depd (namespace) { + if (!namespace) { + throw new TypeError('argument namespace is required') } - mergeTableOptions(tableOptions, cells) { - this.cells = cells; + var stack = getStack() + var site = callSiteLocation(stack[1]) + var file = site[0] - let optionsChars = this.options.chars || {}; - let tableChars = tableOptions.chars; - let chars = (this.chars = {}); - CHAR_NAMES.forEach(function (name) { - setOption(optionsChars, tableChars, name, chars); - }); + function deprecate (message) { + // call to self as log + log.call(deprecate, message) + } - this.truncate = this.options.truncate || tableOptions.truncate; + deprecate._file = file + deprecate._ignored = isignored(namespace) + deprecate._namespace = namespace + deprecate._traced = istraced(namespace) + deprecate._warned = Object.create(null) - let style = (this.options.style = this.options.style || {}); - let tableStyle = tableOptions.style; - setOption(style, tableStyle, 'padding-left', this); - setOption(style, tableStyle, 'padding-right', this); - this.head = style.head || tableStyle.head; - this.border = style.border || tableStyle.border; + deprecate.function = wrapfunction + deprecate.property = wrapproperty - let fixedWidth = tableOptions.colWidths[this.x]; - if (tableOptions.wordWrap && fixedWidth) { - fixedWidth -= this.paddingLeft + this.paddingRight; - if (this.colSpan) { - let i = 1; - while (i < this.colSpan) { - fixedWidth += tableOptions.colWidths[this.x + i]; - i++; - } - } - this.lines = utils.colorizeLines(utils.wordWrap(fixedWidth, this.content)); - } else { - this.lines = utils.colorizeLines(this.content.split('\n')); - } + return deprecate +} - this.desiredWidth = utils.strlen(this.content) + this.paddingLeft + this.paddingRight; - this.desiredHeight = this.lines.length; +/** + * Determine if namespace is ignored. + */ + +function isignored (namespace) { + /* istanbul ignore next: tested in a child processs */ + if (process.noDeprecation) { + // --no-deprecation support + return true } - /** - * Initializes the Cells data structure. - * - * @param tableOptions - A fully populated set of tableOptions. - * In addition to the standard default values, tableOptions must have fully populated the - * `colWidths` and `rowWidths` arrays. Those arrays must have lengths equal to the number - * of columns or rows (respectively) in this table, and each array item must be a Number. - * - */ - init(tableOptions) { - let x = this.x; - let y = this.y; - this.widths = tableOptions.colWidths.slice(x, x + this.colSpan); - this.heights = tableOptions.rowHeights.slice(y, y + this.rowSpan); - this.width = this.widths.reduce(sumPlusOne, -1); - this.height = this.heights.reduce(sumPlusOne, -1); + var str = process.env.NO_DEPRECATION || '' - this.hAlign = this.options.hAlign || tableOptions.colAligns[x]; - this.vAlign = this.options.vAlign || tableOptions.rowAligns[y]; + // namespace ignored + return containsNamespace(str, namespace) +} - this.drawRight = x + this.colSpan == tableOptions.colWidths.length; - } +/** + * Determine if namespace is traced. + */ - /** - * Draws the given line of the cell. - * This default implementation defers to methods `drawTop`, `drawBottom`, `drawLine` and `drawEmpty`. - * @param lineNum - can be `top`, `bottom` or a numerical line number. - * @param spanningCell - will be a number if being called from a RowSpanCell, and will represent how - * many rows below it's being called from. Otherwise it's undefined. - * @returns {String} The representation of this line. - */ - draw(lineNum, spanningCell) { - if (lineNum == 'top') return this.drawTop(this.drawRight); - if (lineNum == 'bottom') return this.drawBottom(this.drawRight); - let padLen = Math.max(this.height - this.lines.length, 0); - let padTop; - switch (this.vAlign) { - case 'center': - padTop = Math.ceil(padLen / 2); - break; - case 'bottom': - padTop = padLen; - break; - default: - padTop = 0; - } - if (lineNum < padTop || lineNum >= padTop + this.lines.length) { - return this.drawEmpty(this.drawRight, spanningCell); - } - let forceTruncation = this.lines.length > this.height && lineNum + 1 >= this.height; - return this.drawLine(lineNum - padTop, this.drawRight, forceTruncation, spanningCell); +function istraced (namespace) { + /* istanbul ignore next: tested in a child processs */ + if (process.traceDeprecation) { + // --trace-deprecation support + return true } - /** - * Renders the top line of the cell. - * @param drawRight - true if this method should render the right edge of the cell. - * @returns {String} - */ - drawTop(drawRight) { - let content = []; - if (this.cells) { - //TODO: cells should always exist - some tests don't fill it in though - this.widths.forEach(function (width, index) { - content.push(this._topLeftChar(index)); - content.push(utils.repeat(this.chars[this.y == 0 ? 'top' : 'mid'], width)); - }, this); - } else { - content.push(this._topLeftChar(0)); - content.push(utils.repeat(this.chars[this.y == 0 ? 'top' : 'mid'], this.width)); - } - if (drawRight) { - content.push(this.chars[this.y == 0 ? 'topRight' : 'rightMid']); - } - return this.wrapWithStyleColors('border', content.join('')); - } + var str = process.env.TRACE_DEPRECATION || '' - _topLeftChar(offset) { - let x = this.x + offset; - let leftChar; - if (this.y == 0) { - leftChar = x == 0 ? 'topLeft' : offset == 0 ? 'topMid' : 'top'; - } else { - if (x == 0) { - leftChar = 'leftMid'; - } else { - leftChar = offset == 0 ? 'midMid' : 'bottomMid'; - if (this.cells) { - //TODO: cells should always exist - some tests don't fill it in though - let spanAbove = this.cells[this.y - 1][x] instanceof Cell.ColSpanCell; - if (spanAbove) { - leftChar = offset == 0 ? 'topMid' : 'mid'; - } - if (offset == 0) { - let i = 1; - while (this.cells[this.y][x - i] instanceof Cell.ColSpanCell) { - i++; - } - if (this.cells[this.y][x - i] instanceof Cell.RowSpanCell) { - leftChar = 'leftMid'; - } - } - } - } - } - return this.chars[leftChar]; + // namespace traced + return containsNamespace(str, namespace) +} + +/** + * Display deprecation message. + */ + +function log (message, site) { + var haslisteners = eventListenerCount(process, 'deprecation') !== 0 + + // abort early if no destination + if (!haslisteners && this._ignored) { + return } - wrapWithStyleColors(styleProperty, content) { - if (this[styleProperty] && this[styleProperty].length) { - try { - let colors = __nccwpck_require__(41997); - for (let i = this[styleProperty].length - 1; i >= 0; i--) { - colors = colors[this[styleProperty][i]]; - } - return colors(content); - } catch (e) { - return content; - } - } else { - return content; - } + 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 } - /** - * Renders a line of text. - * @param lineNum - Which line of text to render. This is not necessarily the line within the cell. - * There may be top-padding above the first line of text. - * @param drawRight - true if this method should render the right edge of the cell. - * @param forceTruncationSymbol - `true` if the rendered text should end with the truncation symbol even - * if the text fits. This is used when the cell is vertically truncated. If `false` the text should - * only include the truncation symbol if the text will not fit horizontally within the cell width. - * @param spanningCell - a number of if being called from a RowSpanCell. (how many rows below). otherwise undefined. - * @returns {String} - */ - drawLine(lineNum, drawRight, forceTruncationSymbol, spanningCell) { - let left = this.chars[this.x == 0 ? 'left' : 'middle']; - if (this.x && spanningCell && this.cells) { - let cellLeft = this.cells[this.y + spanningCell][this.x - 1]; - while (cellLeft instanceof ColSpanCell) { - cellLeft = this.cells[cellLeft.y][cellLeft.x - 1]; - } - if (!(cellLeft instanceof RowSpanCell)) { - left = this.chars['rightMid']; - } + // get caller of deprecated thing in relation to file + for (; i < stack.length; i++) { + caller = callSiteLocation(stack[i]) + callFile = caller[0] + + if (callFile === file) { + seen = true + } else if (callFile === this._file) { + file = this._file + } else if (seen) { + break } - let leftPadding = utils.repeat(' ', this.paddingLeft); - let right = drawRight ? this.chars['right'] : ''; - let rightPadding = utils.repeat(' ', this.paddingRight); - let line = this.lines[lineNum]; - let len = this.width - (this.paddingLeft + this.paddingRight); - if (forceTruncationSymbol) line += this.truncate || '…'; - let content = utils.truncate(line, len, this.truncate); - content = utils.pad(content, len, ' ', this.hAlign); - content = leftPadding + content + rightPadding; - return this.stylizeLine(left, content, right); } - stylizeLine(left, content, right) { - left = this.wrapWithStyleColors('border', left); - right = this.wrapWithStyleColors('border', right); - if (this.y === 0) { - content = this.wrapWithStyleColors('head', content); - } - return left + content + right; + var key = caller + ? depSite.join(':') + '__' + caller.join(':') + : undefined + + if (key !== undefined && key in this._warned) { + // already warned + return } - /** - * Renders the bottom line of the cell. - * @param drawRight - true if this method should render the right edge of the cell. - * @returns {String} - */ - drawBottom(drawRight) { - let left = this.chars[this.x == 0 ? 'bottomLeft' : 'bottomMid']; - let content = utils.repeat(this.chars.bottom, this.width); - let right = drawRight ? this.chars['bottomRight'] : ''; - return this.wrapWithStyleColors('border', left + content + right); + this._warned[key] = true + + // generate automatic message from call site + var msg = message + if (!msg) { + msg = callSite === depSite || !callSite.name + ? defaultMessage(depSite) + : defaultMessage(callSite) } - /** - * Renders a blank line of text within the cell. Used for top and/or bottom padding. - * @param drawRight - true if this method should render the right edge of the cell. - * @param spanningCell - a number of if being called from a RowSpanCell. (how many rows below). otherwise undefined. - * @returns {String} - */ - drawEmpty(drawRight, spanningCell) { - let left = this.chars[this.x == 0 ? 'left' : 'middle']; - if (this.x && spanningCell && this.cells) { - let cellLeft = this.cells[this.y + spanningCell][this.x - 1]; - while (cellLeft instanceof ColSpanCell) { - cellLeft = this.cells[cellLeft.y][cellLeft.x - 1]; - } - if (!(cellLeft instanceof RowSpanCell)) { - left = this.chars['rightMid']; - } - } - let right = drawRight ? this.chars['right'] : ''; - let content = utils.repeat(' ', this.width); - return this.stylizeLine(left, content, right); + // 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') } -class ColSpanCell { - /** - * A Cell that doesn't do anything. It just draws empty lines. - * Used as a placeholder in column spanning. - * @constructor - */ - constructor() {} +/** + * Get call site location as array. + */ - draw() { - return ''; +function callSiteLocation (callSite) { + var file = callSite.getFileName() || '' + var line = callSite.getLineNumber() + var colm = callSite.getColumnNumber() + + if (callSite.isEval()) { + file = callSite.getEvalOrigin() + ', ' + file } - init() {} + var site = [file, line, colm] - mergeTableOptions() {} + site.callSite = callSite + site.name = callSite.getFunctionName() + + return site } -class RowSpanCell { - /** - * A placeholder Cell for a Cell that spans multiple rows. - * It delegates rendering to the original cell, but adds the appropriate offset. - * @param originalCell - * @constructor - */ - constructor(originalCell) { - this.originalCell = originalCell; +/** + * Generate a default message from the site. + */ + +function defaultMessage (site) { + var callSite = site.callSite + var funcName = site.name + + // make useful anonymous name + if (!funcName) { + funcName = '' } - init(tableOptions) { - let y = this.y; - let originalY = this.originalCell.y; - this.cellOffset = y - originalY; - this.offset = findDimension(tableOptions.rowHeights, originalY, this.cellOffset); + var context = callSite.getThis() + var typeName = context && callSite.getTypeName() + + // ignore useless type name + if (typeName === 'Object') { + typeName = undefined } - draw(lineNum) { - if (lineNum == 'top') { - return this.originalCell.draw(this.offset, this.cellOffset); - } - if (lineNum == 'bottom') { - return this.originalCell.draw('bottom'); - } - return this.originalCell.draw(this.offset + 1 + lineNum); + // make useful type name + if (typeName === 'Function') { + typeName = context.name || typeName } - mergeTableOptions() {} + return typeName && callSite.getMethodName() + ? typeName + '.' + funcName + : funcName } -// HELPER FUNCTIONS -function setOption(objA, objB, nameB, targetObj) { - let nameA = nameB.split('-'); - if (nameA.length > 1) { - nameA[1] = nameA[1].charAt(0).toUpperCase() + nameA[1].substr(1); - nameA = nameA.join(''); - targetObj[nameA] = objA[nameA] || objA[nameB] || objB[nameA] || objB[nameB]; - } else { - targetObj[nameB] = objA[nameB] || objB[nameB]; +/** + * Format deprecation message without color. + */ + +function formatPlain (msg, caller, stack) { + var timestamp = new Date().toUTCString() + + var formatted = timestamp + + ' ' + this._namespace + + ' deprecated ' + msg + + // add stack trace + if (this._traced) { + for (var i = 0; i < stack.length; i++) { + formatted += '\n at ' + callSiteToString(stack[i]) + } + + return formatted + } + + if (caller) { + formatted += ' at ' + formatLocation(caller) } + + return formatted } -function findDimension(dimensionTable, startingIndex, span) { - let ret = dimensionTable[startingIndex]; - for (let i = 1; i < span; i++) { - ret += 1 + dimensionTable[startingIndex + i]; +/** + * Format deprecation message with color. + */ + +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 + + // add stack trace + if (this._traced) { + for (var i = 0; i < stack.length; i++) { + formatted += '\n \x1b[36mat ' + callSiteToString(stack[i]) + '\x1b[39m' // cyan + } + + return formatted } - return ret; + + if (caller) { + formatted += ' \x1b[36m' + formatLocation(caller) + '\x1b[39m' // cyan + } + + return formatted } -function sumPlusOne(a, b) { - return a + b + 1; +/** + * Format call site location. + */ + +function formatLocation (callSite) { + return relative(basePath, callSite[0]) + + ':' + callSite[1] + + ':' + callSite[2] } -let CHAR_NAMES = [ - 'top', - 'top-mid', - 'top-left', - 'top-right', - 'bottom', - 'bottom-mid', - 'bottom-left', - 'bottom-right', - 'left', - 'left-mid', - 'mid', - 'mid-mid', - 'right', - 'right-mid', - 'middle', -]; -module.exports = Cell; -module.exports.ColSpanCell = ColSpanCell; -module.exports.RowSpanCell = RowSpanCell; +/** + * 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) -/***/ 93875: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // capture the stack + Error.captureStackTrace(obj) -const Cell = __nccwpck_require__(66168); -const { ColSpanCell, RowSpanCell } = Cell; + // slice this function off the top + var stack = obj.stack.slice(1) -(function () { - function layoutTable(table) { - table.forEach(function (row, rowIndex) { - let prevCell = null; - row.forEach(function (cell, columnIndex) { - cell.y = rowIndex; - cell.x = prevCell ? prevCell.x + 1 : columnIndex; - for (let y = rowIndex; y >= 0; y--) { - let row2 = table[y]; - let xMax = y === rowIndex ? columnIndex : row2.length; - for (let x = 0; x < xMax; x++) { - let cell2 = row2[x]; - while (cellsConflict(cell, cell2)) { - cell.x++; - } - } - prevCell = cell; - } - }); - }); - } + Error.prepareStackTrace = prep + Error.stackTraceLimit = limit - function maxWidth(table) { - let mw = 0; - table.forEach(function (row) { - row.forEach(function (cell) { - mw = Math.max(mw, cell.x + (cell.colSpan || 1)); - }); - }); - return mw; - } + return stack +} - function maxHeight(table) { - return table.length; - } +/** + * Capture call site stack from v8. + */ - function cellsConflict(cell1, cell2) { - let yMin1 = cell1.y; - let yMax1 = cell1.y - 1 + (cell1.rowSpan || 1); - let yMin2 = cell2.y; - let yMax2 = cell2.y - 1 + (cell2.rowSpan || 1); - let yConflict = !(yMin1 > yMax2 || yMin2 > yMax1); +function prepareObjectStackTrace (obj, stack) { + return stack +} - let xMin1 = cell1.x; - let xMax1 = cell1.x - 1 + (cell1.colSpan || 1); - let xMin2 = cell2.x; - let xMax2 = cell2.x - 1 + (cell2.colSpan || 1); - let xConflict = !(xMin1 > xMax2 || xMin2 > xMax1); +/** + * Return a wrapped function in a deprecation message. + */ - return yConflict && xConflict; +function wrapfunction (fn, message) { + if (typeof fn !== 'function') { + throw new TypeError('argument fn must be a function') } - function conflictExists(rows, x, y) { - let i_max = Math.min(rows.length - 1, y); - let cell = { x: x, y: y }; - for (let i = 0; i <= i_max; i++) { - let row = rows[i]; - for (let j = 0; j < row.length; j++) { - if (cellsConflict(cell, row[j])) { - return true; - } - } - } - return false; + 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 +} + +/** + * 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') } - function allBlank(rows, y, xMin, xMax) { - for (let x = xMin; x < xMax; x++) { - if (conflictExists(rows, x, y)) { - return false; - } - } - return true; + var descriptor = Object.getOwnPropertyDescriptor(obj, prop) + + if (!descriptor) { + throw new TypeError('must call property on owner object') } - function addRowSpanCells(table) { - table.forEach(function (row, rowIndex) { - row.forEach(function (cell) { - for (let i = 1; i < cell.rowSpan; i++) { - let rowSpanCell = new RowSpanCell(cell); - rowSpanCell.x = cell.x; - rowSpanCell.y = cell.y + i; - rowSpanCell.colSpan = cell.colSpan; - insertCell(rowSpanCell, table[rowIndex + i]); - } - }); - }); + if (!descriptor.configurable) { + throw new TypeError('property must be configurable') } - function addColSpanCells(cellRows) { - for (let rowIndex = cellRows.length - 1; rowIndex >= 0; rowIndex--) { - let cellColumns = cellRows[rowIndex]; - for (let columnIndex = 0; columnIndex < cellColumns.length; columnIndex++) { - let cell = cellColumns[columnIndex]; - for (let k = 1; k < cell.colSpan; k++) { - let colSpanCell = new ColSpanCell(); - colSpanCell.x = cell.x + k; - colSpanCell.y = cell.y; - cellColumns.splice(columnIndex + 1, 0, colSpanCell); - } - } - } + var deprecate = this + var stack = getStack() + var site = callSiteLocation(stack[1]) + + // set site name + site.name = prop + + // convert data descriptor + if ('value' in descriptor) { + descriptor = convertDataDescriptorToAccessor(obj, prop, message) } - function insertCell(cell, row) { - let x = 0; - while (x < row.length && row[x].x < cell.x) { - x++; + var get = descriptor.get + var set = descriptor.set + + // wrap getter + if (typeof get === 'function') { + descriptor.get = function getter () { + log.call(deprecate, message, site) + return get.apply(this, arguments) } - row.splice(x, 0, cell); } - function fillInTable(table) { - let h_max = maxHeight(table); - let w_max = maxWidth(table); - for (let y = 0; y < h_max; y++) { - for (let x = 0; x < w_max; x++) { - if (!conflictExists(table, x, y)) { - let opts = { x: x, y: y, colSpan: 1, rowSpan: 1 }; - x++; - while (x < w_max && !conflictExists(table, x, y)) { - opts.colSpan++; - x++; - } - let y2 = y + 1; - while (y2 < h_max && allBlank(table, y2, opts.x, opts.x + opts.colSpan)) { - opts.rowSpan++; - y2++; - } - - let cell = new Cell(opts); - cell.x = opts.x; - cell.y = opts.y; - insertCell(cell, table[y]); - } - } + // wrap setter + if (typeof set === 'function') { + descriptor.set = function setter () { + log.call(deprecate, message, site) + return set.apply(this, arguments) } } - function generateCells(rows) { - return rows.map(function (row) { - if (!Array.isArray(row)) { - let key = Object.keys(row)[0]; - row = row[key]; - if (Array.isArray(row)) { - row = row.slice(); - row.unshift(key); - } else { - row = [key, row]; - } - } - return row.map(function (cell) { - return new Cell(cell); - }); - }); - } + Object.defineProperty(obj, prop, descriptor) +} - function makeTableLayout(rows) { - let cellRows = generateCells(rows); - layoutTable(cellRows); - fillInTable(cellRows); - addRowSpanCells(cellRows); - addColSpanCells(cellRows); - return cellRows; - } +/** + * Create DeprecationError for deprecation + */ - module.exports = { - makeTableLayout: makeTableLayout, - layoutTable: layoutTable, - addRowSpanCells: addRowSpanCells, - maxWidth: maxWidth, - fillInTable: fillInTable, - computeWidths: makeComputeWidths('colSpan', 'desiredWidth', 'x', 1), - computeHeights: makeComputeWidths('rowSpan', 'desiredHeight', 'y', 1), - }; -})(); +function DeprecationError (namespace, message, stack) { + var error = new Error() + var stackString -function makeComputeWidths(colSpan, desiredWidth, x, forcedMin) { - return function (vals, table) { - let result = []; - let spanners = []; - table.forEach(function (row) { - row.forEach(function (cell) { - if ((cell[colSpan] || 1) > 1) { - spanners.push(cell); - } else { - result[cell[x]] = Math.max(result[cell[x]] || 0, cell[desiredWidth] || 0, forcedMin); - } - }); - }); + Object.defineProperty(error, 'constructor', { + value: DeprecationError + }) - vals.forEach(function (val, index) { - if (typeof val === 'number') { - result[index] = val; - } - }); + Object.defineProperty(error, 'message', { + configurable: true, + enumerable: false, + value: message, + writable: true + }) - //spanners.forEach(function(cell){ - for (let k = spanners.length - 1; k >= 0; k--) { - let cell = spanners[k]; - let span = cell[colSpan]; - let col = cell[x]; - let existingWidth = result[col]; - let editableCols = typeof vals[col] === 'number' ? 0 : 1; - for (let i = 1; i < span; i++) { - existingWidth += 1 + result[col + i]; - if (typeof vals[col + i] !== 'number') { - editableCols++; - } - } - if (cell[desiredWidth] > existingWidth) { - let i = 0; - while (editableCols > 0 && cell[desiredWidth] > existingWidth) { - if (typeof vals[col + i] !== 'number') { - let dif = Math.round((cell[desiredWidth] - existingWidth) / editableCols); - existingWidth += dif; - result[col + i] += dif; - editableCols--; - } - i++; - } + 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 } - } - Object.assign(vals, result); - for (let j = 0; j < vals.length; j++) { - vals[j] = Math.max(forcedMin, vals[j] || 0); + // prepare stack trace + return (stackString = createStackString.call(this, stack)) + }, + set: function setter (val) { + stackString = val } - }; + }) + + return error } /***/ }), -/***/ 16136: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 35554: +/***/ ((module) => { -const utils = __nccwpck_require__(98911); -const tableLayout = __nccwpck_require__(93875); +"use strict"; +/*! + * depd + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ -class Table extends Array { - constructor(options) { - super(); - this.options = utils.mergeOptions(options); - } - toString() { - let array = this; - let headersPresent = this.options.head && this.options.head.length; - if (headersPresent) { - array = [this.options.head]; - if (this.length) { - array.push.apply(array, this); - } - } else { - this.options.style.head = []; - } +/** + * Module exports. + */ - let cells = tableLayout.makeTableLayout(array); +module.exports = callSiteToString - cells.forEach(function (row) { - row.forEach(function (cell) { - cell.mergeTableOptions(this.options, cells); - }, this); - }, this); +/** + * Format a CallSite file location to a string. + */ - tableLayout.computeWidths(this.options.colWidths, cells); - tableLayout.computeHeights(this.options.rowHeights, cells); +function callSiteFileLocation (callSite) { + var fileName + var fileLocation = '' - cells.forEach(function (row) { - row.forEach(function (cell) { - cell.init(this.options); - }, this); - }, this); + if (callSite.isNative()) { + fileLocation = 'native' + } else if (callSite.isEval()) { + fileName = callSite.getScriptNameOrSourceURL() + if (!fileName) { + fileLocation = callSite.getEvalOrigin() + } + } else { + fileName = callSite.getFileName() + } - let result = []; + if (fileName) { + fileLocation += fileName - for (let rowIndex = 0; rowIndex < cells.length; rowIndex++) { - let row = cells[rowIndex]; - let heightOfRow = this.options.rowHeights[rowIndex]; + var lineNumber = callSite.getLineNumber() + if (lineNumber != null) { + fileLocation += ':' + lineNumber - if (rowIndex === 0 || !this.options.style.compact || (rowIndex == 1 && headersPresent)) { - doDraw(row, 'top', result); + var columnNumber = callSite.getColumnNumber() + if (columnNumber) { + fileLocation += ':' + columnNumber } + } + } - for (let lineNum = 0; lineNum < heightOfRow; lineNum++) { - doDraw(row, lineNum, result); + return fileLocation || 'unknown source' +} + +/** + * Format a CallSite to a string. + */ + +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 + '.' } - if (rowIndex + 1 == cells.length) { - doDraw(row, 'bottom', result); + line += functionName + + if (methodName && functionName.lastIndexOf('.' + methodName) !== functionName.length - methodName.length - 1) { + line += ' [as ' + methodName + ']' } + } else { + line += typeName + '.' + (methodName || '') } - - return result.join('\n'); + } else if (isConstructor) { + line += 'new ' + (functionName || '') + } else if (functionName) { + line += functionName + } else { + addSuffix = false + line += fileLocation } - get width() { - let str = this.toString().split('\n'); - return str[0].length; + if (addSuffix) { + line += ' (' + fileLocation + ')' } -} -function doDraw(row, lineNum, result) { - let line = []; - row.forEach(function (cell) { - line.push(cell.draw(lineNum)); - }); - let str = line.join(''); - if (str.length) result.push(str); + return line } -module.exports = Table; +/** + * Get constructor name of reviver. + */ + +function getConstructorName (obj) { + var receiver = obj.receiver + return (receiver.constructor && receiver.constructor.name) || null +} /***/ }), -/***/ 98911: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 12078: +/***/ ((module) => { -const stringWidth = __nccwpck_require__(42577); +"use strict"; +/*! + * depd + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ -function codeRegex(capture) { - return capture ? /\u001b\[((?:\d*;){0,5}\d*)m/g : /\u001b\[(?:\d*;){0,5}\d*m/g; -} -function strlen(str) { - let code = codeRegex(); - let stripped = ('' + str).replace(code, ''); - let split = stripped.split('\n'); - return split.reduce(function (memo, s) { - return stringWidth(s) > memo ? stringWidth(s) : memo; - }, 0); -} -function repeat(str, times) { - return Array(times + 1).join(str); -} +/** + * Module exports. + * @public + */ -function pad(str, len, pad, dir) { - let length = strlen(str); - if (len + 1 >= length) { - let padlen = len - length; - switch (dir) { - case 'right': { - str = repeat(pad, padlen) + str; - break; - } - case 'center': { - let right = Math.ceil(padlen / 2); - let left = padlen - right; - str = repeat(pad, left) + str + repeat(pad, right); - break; - } - default: { - str = str + repeat(pad, padlen); - break; - } - } - } - return str; -} +module.exports = eventListenerCount -let codeCache = {}; +/** + * Get the count of listeners on an event emitter of a specific type. + */ -function addToCodeCache(name, on, off) { - on = '\u001b[' + on + 'm'; - off = '\u001b[' + off + 'm'; - codeCache[on] = { set: name, to: true }; - codeCache[off] = { set: name, to: false }; - codeCache[name] = { on: on, off: off }; +function eventListenerCount (emitter, type) { + return emitter.listeners(type).length } -//https://github.com/Marak/colors.js/blob/master/lib/styles.js -addToCodeCache('bold', 1, 22); -addToCodeCache('italics', 3, 23); -addToCodeCache('underline', 4, 24); -addToCodeCache('inverse', 7, 27); -addToCodeCache('strikethrough', 9, 29); -function updateState(state, controlChars) { - let controlCode = controlChars[1] ? parseInt(controlChars[1].split(';')[0]) : 0; - if ((controlCode >= 30 && controlCode <= 39) || (controlCode >= 90 && controlCode <= 97)) { - state.lastForegroundAdded = controlChars[0]; - return; - } - if ((controlCode >= 40 && controlCode <= 49) || (controlCode >= 100 && controlCode <= 107)) { - state.lastBackgroundAdded = controlChars[0]; - return; - } - if (controlCode === 0) { - for (let i in state) { - /* istanbul ignore else */ - if (Object.prototype.hasOwnProperty.call(state, i)) { - delete state[i]; - } - } - return; - } - let info = codeCache[controlChars[0]]; - if (info) { - state[info.set] = info.to; - } -} +/***/ }), -function readState(line) { - let code = codeRegex(true); - let controlChars = code.exec(line); - let state = {}; - while (controlChars !== null) { - updateState(state, controlChars); - controlChars = code.exec(line); - } - return state; -} +/***/ 69829: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -function unwindState(state, ret) { - let lastBackgroundAdded = state.lastBackgroundAdded; - let lastForegroundAdded = state.lastForegroundAdded; +"use strict"; +/*! + * depd + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ - delete state.lastBackgroundAdded; - delete state.lastForegroundAdded; - Object.keys(state).forEach(function (key) { - if (state[key]) { - ret += codeCache[key].off; - } - }); - if (lastBackgroundAdded && lastBackgroundAdded != '\u001b[49m') { - ret += '\u001b[49m'; - } - if (lastForegroundAdded && lastForegroundAdded != '\u001b[39m') { - ret += '\u001b[39m'; +/** + * 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 } - return ret; -} + Error.prepareStackTrace = prepareObjectStackTrace + Error.stackTraceLimit = 2 -function rewindState(state, ret) { - let lastBackgroundAdded = state.lastBackgroundAdded; - let lastForegroundAdded = state.lastForegroundAdded; + // capture the stack + Error.captureStackTrace(obj) - delete state.lastBackgroundAdded; - delete state.lastForegroundAdded; + // slice the stack + var stack = obj.stack.slice() - Object.keys(state).forEach(function (key) { - if (state[key]) { - ret = codeCache[key].on + ret; - } - }); + Error.prepareStackTrace = prep + Error.stackTraceLimit = limit - if (lastBackgroundAdded && lastBackgroundAdded != '\u001b[49m') { - ret = lastBackgroundAdded + ret; - } - if (lastForegroundAdded && lastForegroundAdded != '\u001b[39m') { - ret = lastForegroundAdded + ret; - } + return stack[0].toString ? toString : __nccwpck_require__(35554) +}) - return ret; -} +lazyProperty(module.exports, 'eventListenerCount', function eventListenerCount () { + return EventEmitter.listenerCount || __nccwpck_require__(12078) +}) -function truncateWidth(str, desiredLength) { - if (str.length === strlen(str)) { - return str.substr(0, desiredLength); - } +/** + * Define a lazy property. + */ - while (strlen(str) > desiredLength) { - str = str.slice(0, -1); +function lazyProperty (obj, prop, getter) { + function get () { + var val = getter() + + Object.defineProperty(obj, prop, { + configurable: true, + enumerable: true, + value: val + }) + + return val } - return str; + Object.defineProperty(obj, prop, { + configurable: true, + enumerable: true, + get: get + }) } -function truncateWidthWithAnsi(str, desiredLength) { - let code = codeRegex(true); - let split = str.split(codeRegex()); - let splitIndex = 0; - let retLen = 0; - let ret = ''; - let myArray; - let state = {}; +/** + * Call toString() on the obj + */ - while (retLen < desiredLength) { - myArray = code.exec(str); - let toAdd = split[splitIndex]; - splitIndex++; - if (retLen + strlen(toAdd) > desiredLength) { - toAdd = truncateWidth(toAdd, desiredLength - retLen); - } - ret += toAdd; - retLen += strlen(toAdd); +function toString (obj) { + return obj.toString() +} - if (retLen < desiredLength) { - if (!myArray) { - break; - } // full-width chars may cause a whitespace which cannot be filled - ret += myArray[0]; - updateState(state, myArray); - } - } - return unwindState(state, ret); -} +/***/ }), + +/***/ 58932: +/***/ ((__unused_webpack_module, exports) => { -function truncate(str, desiredLength, truncateChar) { - truncateChar = truncateChar || '…'; - let lengthOfStr = strlen(str); - if (lengthOfStr <= desiredLength) { - return str; - } - desiredLength -= strlen(truncateChar); +"use strict"; - let ret = truncateWidthWithAnsi(str, desiredLength); - return ret + truncateChar; -} +Object.defineProperty(exports, "__esModule", ({ value: true })); -function defaultOptions() { - return { - chars: { - top: '─', - 'top-mid': '┬', - 'top-left': '┌', - 'top-right': '┐', - bottom: '─', - 'bottom-mid': '┴', - 'bottom-left': '└', - 'bottom-right': '┘', - left: '│', - 'left-mid': '├', - mid: '─', - 'mid-mid': '┼', - right: '│', - 'right-mid': '┤', - middle: '│', - }, - truncate: '…', - colWidths: [], - rowHeights: [], - colAligns: [], - rowAligns: [], - style: { - 'padding-left': 1, - 'padding-right': 1, - head: ['red'], - border: ['grey'], - compact: false, - }, - head: [], - }; -} +class Deprecation extends Error { + constructor(message) { + super(message); // Maintains proper stack trace (only available on V8) -function mergeOptions(options, defaults) { - options = options || {}; - defaults = defaults || defaultOptions(); - let ret = Object.assign({}, defaults, options); - ret.chars = Object.assign({}, defaults.chars, options.chars); - ret.style = Object.assign({}, defaults.style, options.style); - return ret; -} + /* istanbul ignore next */ -function wordWrap(maxLength, input) { - let lines = []; - let split = input.split(/(\s+)/g); - let line = []; - let lineLength = 0; - let whitespace; - for (let i = 0; i < split.length; i += 2) { - let word = split[i]; - let newLength = lineLength + strlen(word); - if (lineLength > 0 && whitespace) { - newLength += whitespace.length; - } - if (newLength > maxLength) { - if (lineLength !== 0) { - lines.push(line.join('')); - } - line = [word]; - lineLength = strlen(word); - } else { - line.push(whitespace || '', word); - lineLength = newLength; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); } - whitespace = split[i + 1]; - } - if (lineLength) { - lines.push(line.join('')); - } - return lines; -} -function multiLineWordWrap(maxLength, input) { - let output = []; - input = input.split('\n'); - for (let i = 0; i < input.length; i++) { - output.push.apply(output, wordWrap(maxLength, input[i])); + this.name = 'Deprecation'; } - return output; -} -function colorizeLines(input) { - let state = {}; - let output = []; - for (let i = 0; i < input.length; i++) { - let line = rewindState(state, input[i]); - state = readState(line); - let temp = Object.assign({}, state); - output.push(unwindState(temp, line)); - } - return output; } -module.exports = { - strlen: strlen, - repeat: repeat, - pad: pad, - truncate: truncate, - mergeOptions: mergeOptions, - wordWrap: multiLineWordWrap, - colorizeLines: colorizeLines, -}; +exports.Deprecation = Deprecation; /***/ }), -/***/ 48481: -/***/ ((module) => { +/***/ 43225: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/* - * Copyright 2001-2010 Georges Menie (www.menie.org) - * Copyright 2010 Salvatore Sanfilippo (adapted to Redis coding style) - * Copyright 2015 Zihua Li (http://zihua.li) (ported to JavaScript) - * Copyright 2016 Mike Diarmid (http://github.com/salakar) (re-write for performance, ~700% perf inc) - * All rights reserved. - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the University of California, Berkeley nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +"use strict"; +/*! + * destroy + * Copyright(c) 2014 Jonathan Ong + * MIT Licensed */ -/* CRC16 implementation according to CCITT standards. - * - * Note by @antirez: this is actually the XMODEM CRC 16 algorithm, using the - * following parameters: - * - * Name : "XMODEM", also known as "ZMODEM", "CRC-16/ACORN" - * Width : 16 bit - * Poly : 1021 (That is actually x^16 + x^12 + x^5 + 1) - * Initialization : 0000 - * Reflect Input byte : False - * Reflect Output CRC : False - * Xor constant to output CRC : 0000 - * Output for "123456789" : 31C3 + + +/** + * Module dependencies. + * @private */ -var lookup = [ - 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7, - 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef, - 0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6, - 0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de, - 0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485, - 0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d, - 0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4, - 0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc, - 0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823, - 0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b, - 0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12, - 0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a, - 0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41, - 0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49, - 0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70, - 0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78, - 0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f, - 0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067, - 0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e, - 0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256, - 0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d, - 0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, - 0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c, - 0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634, - 0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab, - 0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3, - 0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a, - 0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92, - 0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9, - 0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1, - 0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8, - 0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0 -]; +var ReadStream = (__nccwpck_require__(57147).ReadStream) +var Stream = __nccwpck_require__(12781) /** - * Convert a string to a UTF8 array - faster than via buffer - * @param str - * @returns {Array} + * Module exports. + * @public */ -var toUTF8Array = function toUTF8Array(str) { - var char; - var i = 0; - var p = 0; - var utf8 = []; - var len = str.length; - for (; i < len; i++) { - char = str.charCodeAt(i); - if (char < 128) { - utf8[p++] = char; - } else if (char < 2048) { - utf8[p++] = (char >> 6) | 192; - utf8[p++] = (char & 63) | 128; - } else if ( - ((char & 0xFC00) === 0xD800) && (i + 1) < str.length && - ((str.charCodeAt(i + 1) & 0xFC00) === 0xDC00)) { - char = 0x10000 + ((char & 0x03FF) << 10) + (str.charCodeAt(++i) & 0x03FF); - utf8[p++] = (char >> 18) | 240; - utf8[p++] = ((char >> 12) & 63) | 128; - utf8[p++] = ((char >> 6) & 63) | 128; - utf8[p++] = (char & 63) | 128; - } else { - utf8[p++] = (char >> 12) | 224; - utf8[p++] = ((char >> 6) & 63) | 128; - utf8[p++] = (char & 63) | 128; - } +module.exports = destroy + +/** + * Destroy a stream. + * + * @param {object} stream + * @public + */ + +function destroy(stream) { + if (stream instanceof ReadStream) { + return destroyReadStream(stream) } - return utf8; -}; + if (!(stream instanceof Stream)) { + return stream + } + + if (typeof stream.destroy === 'function') { + stream.destroy() + } + + return stream +} /** - * Convert a string into a redis slot hash. - * @param str - * @returns {number} + * Destroy a ReadStream. + * + * @param {object} stream + * @private */ -var generate = module.exports = function generate(str) { - var char; - var i = 0; - var start = -1; - var result = 0; - var resultHash = 0; - var utf8 = typeof str === 'string' ? toUTF8Array(str) : str; - var len = utf8.length; - while (i < len) { - char = utf8[i++]; - if (start === -1) { - if (char === 0x7B) { - start = i; - } - } else if (char !== 0x7D) { - resultHash = lookup[(char ^ (resultHash >> 8)) & 0xFF] ^ (resultHash << 8); - } else if (i - 1 !== start) { - return resultHash & 0x3FFF; - } +function destroyReadStream(stream) { + stream.destroy() - result = lookup[(char ^ (result >> 8)) & 0xFF] ^ (result << 8); + if (typeof stream.close === 'function') { + // node.js core bug work-around + stream.on('open', onOpenClose) } - return result & 0x3FFF; -}; + return stream +} /** - * Convert an array of multiple strings into a redis slot hash. - * Returns -1 if one of the keys is not for the same slot as the others - * @param keys - * @returns {number} + * On open handler to close stream. + * @private */ -module.exports.generateMulti = function generateMulti(keys) { - var i = 1; - var len = keys.length; - var base = generate(keys[0]); - while (i < len) { - if (generate(keys[i++]) !== base) return -1; +function onOpenClose() { + if (typeof this.fd === 'number') { + // actually close down the fd + this.close() } - - return base; -}; +} /***/ }), -/***/ 97391: +/***/ 12437: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/* MIT license */ -/* eslint-disable no-mixed-operators */ -const cssKeywords = __nccwpck_require__(78510); +/* @flow */ +/*:: -// NOTE: conversions should only return primitive values (i.e. arrays, or -// values that give correct `typeof` results). -// do not use box values types (i.e. Number(), String(), etc.) +type DotenvParseOptions = { + debug?: boolean +} -const reverseKeywords = {}; -for (const key of Object.keys(cssKeywords)) { - reverseKeywords[cssKeywords[key]] = key; +// 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 } -const convert = { - rgb: {channels: 3, labels: 'rgb'}, - hsl: {channels: 3, labels: 'hsl'}, - hsv: {channels: 3, labels: 'hsv'}, - hwb: {channels: 3, labels: 'hwb'}, - cmyk: {channels: 4, labels: 'cmyk'}, - xyz: {channels: 3, labels: 'xyz'}, - lab: {channels: 3, labels: 'lab'}, - lch: {channels: 3, labels: 'lch'}, - hex: {channels: 1, labels: ['hex']}, - keyword: {channels: 1, labels: ['keyword']}, - ansi16: {channels: 1, labels: ['ansi16']}, - ansi256: {channels: 1, labels: ['ansi256']}, - hcg: {channels: 3, labels: ['h', 'c', 'g']}, - apple: {channels: 3, labels: ['r16', 'g16', 'b16']}, - gray: {channels: 1, labels: ['gray']} -}; +type DotenvConfigOutput = { + parsed?: DotenvParseOutput, + error?: Error +} -module.exports = convert; +*/ -// Hide .channels and .labels properties -for (const model of Object.keys(convert)) { - if (!('channels' in convert[model])) { - throw new Error('missing channels property: ' + model); - } +const fs = __nccwpck_require__(57147) +const path = __nccwpck_require__(71017) - if (!('labels' in convert[model])) { - throw new Error('missing channel labels property: ' + model); - } +function log (message /*: string */) { + console.log(`[dotenv][DEBUG] ${message}`) +} - if (convert[model].labels.length !== convert[model].channels) { - throw new Error('channel and label counts mismatch: ' + model); - } +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/ - const {channels, labels} = convert[model]; - delete convert[model].channels; - delete convert[model].labels; - Object.defineProperty(convert[model], 'channels', {value: channels}); - Object.defineProperty(convert[model], 'labels', {value: labels}); +// 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] === "'" + + // if single or double quoted, remove quotes + if (isSingleQuoted || isDoubleQuoted) { + val = val.substring(1, end) + + // 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 } -convert.rgb.hsl = function (rgb) { - const r = rgb[0] / 255; - const g = rgb[1] / 255; - const b = rgb[2] / 255; - const min = Math.min(r, g, b); - const max = Math.max(r, g, b); - const delta = max - min; - let h; - let s; +// 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 (max === min) { - h = 0; - } else if (r === max) { - h = (g - b) / delta; - } else if (g === max) { - h = 2 + (b - r) / delta; - } else if (b === max) { - h = 4 + (r - g) / delta; - } + if (options) { + if (options.path != null) { + dotenvPath = options.path + } + if (options.encoding != null) { + encoding = options.encoding + } + if (options.debug != null) { + debug = true + } + } - h = Math.min(h * 60, 360); + 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 } + } +} + +module.exports.config = config +module.exports.parse = parse + + +/***/ }), + +/***/ 11728: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +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); + +function base64Url(base64) { + return base64 + .replace(/=/g, '') + .replace(/\+/g, '-') + .replace(/\//g, '_'); +} - if (h < 0) { - h += 360; +function signatureAsBuffer(signature) { + if (Buffer.isBuffer(signature)) { + return signature; + } else if ('string' === typeof signature) { + return Buffer.from(signature, 'base64'); } - const l = (min + max) / 2; - - if (max === min) { - s = 0; - } else if (l <= 0.5) { - s = delta / (max + min); - } else { - s = delta / (2 - max - min); - } + throw new TypeError('ECDSA signature must be a Base64 string or a Buffer'); +} - return [h, s * 100, l * 100]; -}; +function derToJose(signature, alg) { + signature = signatureAsBuffer(signature); + var paramBytes = getParamBytesForAlg(alg); -convert.rgb.hsv = function (rgb) { - let rdif; - let gdif; - let bdif; - let h; - let s; + // 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; - const r = rgb[0] / 255; - const g = rgb[1] / 255; - const b = rgb[2] / 255; - const v = Math.max(r, g, b); - const diff = v - Math.min(r, g, b); - const diffc = function (c) { - return (v - c) / 6 / diff + 1 / 2; - }; + var inputLength = signature.length; - if (diff === 0) { - h = 0; - s = 0; - } else { - s = diff / v; - rdif = diffc(r); - gdif = diffc(g); - bdif = diffc(b); + var offset = 0; + if (signature[offset++] !== ENCODED_TAG_SEQ) { + throw new Error('Could not find expected "seq"'); + } - if (r === v) { - h = bdif - gdif; - } else if (g === v) { - h = (1 / 3) + rdif - bdif; - } else if (b === v) { - h = (2 / 3) + gdif - rdif; - } + var seqLength = signature[offset++]; + if (seqLength === (MAX_OCTET | 1)) { + seqLength = signature[offset++]; + } - if (h < 0) { - h += 1; - } else if (h > 1) { - h -= 1; - } + if (inputLength - offset < seqLength) { + throw new Error('"seq" specified length of "' + seqLength + '", only "' + (inputLength - offset) + '" remaining'); } - return [ - h * 360, - s * 100, - v * 100 - ]; -}; + if (signature[offset++] !== ENCODED_TAG_INT) { + throw new Error('Could not find expected "int" for "r"'); + } -convert.rgb.hwb = function (rgb) { - const r = rgb[0]; - const g = rgb[1]; - let b = rgb[2]; - const h = convert.rgb.hsl(rgb)[0]; - const w = 1 / 255 * Math.min(r, Math.min(g, b)); + var rLength = signature[offset++]; - b = 1 - 1 / 255 * Math.max(r, Math.max(g, b)); + if (inputLength - offset - 2 < rLength) { + throw new Error('"r" specified length of "' + rLength + '", only "' + (inputLength - offset - 2) + '" available'); + } - return [h, w * 100, b * 100]; -}; + if (maxEncodedParamLength < rLength) { + throw new Error('"r" specified length of "' + rLength + '", max of "' + maxEncodedParamLength + '" is acceptable'); + } -convert.rgb.cmyk = function (rgb) { - const r = rgb[0] / 255; - const g = rgb[1] / 255; - const b = rgb[2] / 255; + var rOffset = offset; + offset += rLength; - const k = Math.min(1 - r, 1 - g, 1 - b); - const c = (1 - r - k) / (1 - k) || 0; - const m = (1 - g - k) / (1 - k) || 0; - const y = (1 - b - k) / (1 - k) || 0; + if (signature[offset++] !== ENCODED_TAG_INT) { + throw new Error('Could not find expected "int" for "s"'); + } - return [c * 100, m * 100, y * 100, k * 100]; -}; + var sLength = signature[offset++]; -function comparativeDistance(x, y) { - /* - See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance - */ - return ( - ((x[0] - y[0]) ** 2) + - ((x[1] - y[1]) ** 2) + - ((x[2] - y[2]) ** 2) - ); -} + if (inputLength - offset !== sLength) { + throw new Error('"s" specified length of "' + sLength + '", expected "' + (inputLength - offset) + '"'); + } -convert.rgb.keyword = function (rgb) { - const reversed = reverseKeywords[rgb]; - if (reversed) { - return reversed; + if (maxEncodedParamLength < sLength) { + throw new Error('"s" specified length of "' + sLength + '", max of "' + maxEncodedParamLength + '" is acceptable'); } - let currentClosestDistance = Infinity; - let currentClosestKeyword; + var sOffset = offset; + offset += sLength; - for (const keyword of Object.keys(cssKeywords)) { - const value = cssKeywords[keyword]; + if (offset !== inputLength) { + throw new Error('Expected to consume entire buffer, but "' + (inputLength - offset) + '" bytes remain'); + } - // Compute comparative distance - const distance = comparativeDistance(rgb, value); + var rPadding = paramBytes - rLength, + sPadding = paramBytes - sLength; - // Check if its less, if so set as closest - if (distance < currentClosestDistance) { - currentClosestDistance = distance; - currentClosestKeyword = keyword; - } + var dst = Buffer.allocUnsafe(rPadding + rLength + sPadding + sLength); + + for (offset = 0; offset < rPadding; ++offset) { + dst[offset] = 0; } + signature.copy(dst, offset, rOffset + Math.max(-rPadding, 0), rOffset + rLength); - return currentClosestKeyword; -}; + offset = paramBytes; -convert.keyword.rgb = function (keyword) { - return cssKeywords[keyword]; -}; + for (var o = offset; offset < o + sPadding; ++offset) { + dst[offset] = 0; + } + signature.copy(dst, offset, sOffset + Math.max(-sPadding, 0), sOffset + sLength); -convert.rgb.xyz = function (rgb) { - let r = rgb[0] / 255; - let g = rgb[1] / 255; - let b = rgb[2] / 255; + dst = dst.toString('base64'); + dst = base64Url(dst); - // Assume sRGB - r = r > 0.04045 ? (((r + 0.055) / 1.055) ** 2.4) : (r / 12.92); - g = g > 0.04045 ? (((g + 0.055) / 1.055) ** 2.4) : (g / 12.92); - b = b > 0.04045 ? (((b + 0.055) / 1.055) ** 2.4) : (b / 12.92); + return dst; +} - const x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805); - const y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722); - const z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505); +function countPadding(buf, start, stop) { + var padding = 0; + while (start + padding < stop && buf[start + padding] === 0) { + ++padding; + } - return [x * 100, y * 100, z * 100]; -}; + var needsSign = buf[start + padding] >= MAX_OCTET; + if (needsSign) { + --padding; + } -convert.rgb.lab = function (rgb) { - const xyz = convert.rgb.xyz(rgb); - let x = xyz[0]; - let y = xyz[1]; - let z = xyz[2]; + return padding; +} - x /= 95.047; - y /= 100; - z /= 108.883; +function joseToDer(signature, alg) { + signature = signatureAsBuffer(signature); + var paramBytes = getParamBytesForAlg(alg); - x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116); - y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116); - z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116); + var signatureBytes = signature.length; + if (signatureBytes !== paramBytes * 2) { + throw new TypeError('"' + alg + '" signatures must be "' + paramBytes * 2 + '" bytes, saw "' + signatureBytes + '"'); + } - const l = (116 * y) - 16; - const a = 500 * (x - y); - const b = 200 * (y - z); + var rPadding = countPadding(signature, 0, paramBytes); + var sPadding = countPadding(signature, paramBytes, signature.length); + var rLength = paramBytes - rPadding; + var sLength = paramBytes - sPadding; - return [l, a, b]; -}; + var rsBytes = 1 + 1 + rLength + 1 + 1 + sLength; -convert.hsl.rgb = function (hsl) { - const h = hsl[0] / 360; - const s = hsl[1] / 100; - const l = hsl[2] / 100; - let t2; - let t3; - let val; + var shortLength = rsBytes < MAX_OCTET; - if (s === 0) { - val = l * 255; - return [val, val, val]; - } + var dst = Buffer.allocUnsafe((shortLength ? 2 : 3) + rsBytes); - if (l < 0.5) { - t2 = l * (1 + s); + 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 { - t2 = l + s - l * s; + // 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); } - const t1 = 2 * l - t2; + return dst; +} - const rgb = [0, 0, 0]; - for (let i = 0; i < 3; i++) { - t3 = h + 1 / 3 * -(i - 1); - if (t3 < 0) { - t3++; - } +module.exports = { + derToJose: derToJose, + joseToDer: joseToDer +}; - if (t3 > 1) { - t3--; - } - if (6 * t3 < 1) { - val = t1 + (t2 - t1) * 6 * t3; - } else if (2 * t3 < 1) { - val = t2; - } else if (3 * t3 < 2) { - val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; - } else { - val = t1; - } +/***/ }), - rgb[i] = val * 255; - } +/***/ 30528: +/***/ ((module) => { - return rgb; -}; +"use strict"; -convert.hsl.hsv = function (hsl) { - const h = hsl[0]; - let s = hsl[1] / 100; - let l = hsl[2] / 100; - let smin = s; - const lmin = Math.max(l, 0.01); - l *= 2; - s *= (l <= 1) ? l : 2 - l; - smin *= lmin <= 1 ? lmin : 2 - lmin; - const v = (l + s) / 2; - const sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s); +function getParamSize(keySize) { + var result = ((keySize / 8) | 0) + (keySize % 8 === 0 ? 0 : 1); + return result; +} - return [h, sv * 100, v * 100]; +var paramBytesForAlg = { + ES256: getParamSize(256), + ES384: getParamSize(384), + ES512: getParamSize(521) }; -convert.hsv.rgb = function (hsv) { - const h = hsv[0] / 60; - const s = hsv[1] / 100; - let v = hsv[2] / 100; - const hi = Math.floor(h) % 6; +function getParamBytesForAlg(alg) { + var paramBytes = paramBytesForAlg[alg]; + if (paramBytes) { + return paramBytes; + } - const f = h - Math.floor(h); - const p = 255 * v * (1 - s); - const q = 255 * v * (1 - (s * f)); - const t = 255 * v * (1 - (s * (1 - f))); - v *= 255; + throw new Error('Unknown algorithm "' + alg + '"'); +} - switch (hi) { - case 0: - return [v, t, p]; - case 1: - return [q, v, p]; - case 2: - return [p, v, t]; - case 3: - return [p, q, v]; - case 4: - return [t, p, v]; - case 5: - return [v, p, q]; - } -}; +module.exports = getParamBytesForAlg; -convert.hsv.hsl = function (hsv) { - const h = hsv[0]; - const s = hsv[1] / 100; - const v = hsv[2] / 100; - const vmin = Math.max(v, 0.01); - let sl; - let l; - l = (2 - s) * v; - const lmin = (2 - s) * vmin; - sl = s * vmin; - sl /= (lmin <= 1) ? lmin : 2 - lmin; - sl = sl || 0; - l /= 2; +/***/ }), - return [h, sl * 100, l * 100]; -}; +/***/ 14401: +/***/ ((module) => { -// http://dev.w3.org/csswg/css-color/#hwb-to-rgb -convert.hwb.rgb = function (hwb) { - const h = hwb[0] / 360; - let wh = hwb[1] / 100; - let bl = hwb[2] / 100; - const ratio = wh + bl; - let f; +"use strict"; +/*! + * ee-first + * Copyright(c) 2014 Jonathan Ong + * MIT Licensed + */ - // Wh + bl cant be > 1 - if (ratio > 1) { - wh /= ratio; - bl /= ratio; - } - const i = Math.floor(6 * h); - const v = 1 - bl; - f = 6 * h - i; - if ((i & 0x01) !== 0) { - f = 1 - f; - } +/** + * Module exports. + * @public + */ - const n = wh + f * (v - wh); // Linear interpolation +module.exports = first - let r; - let g; - let b; - /* eslint-disable max-statements-per-line,no-multi-spaces */ - switch (i) { - default: - case 6: - case 0: r = v; g = n; b = wh; break; - case 1: r = n; g = v; b = wh; break; - case 2: r = wh; g = v; b = n; break; - case 3: r = wh; g = n; b = v; break; - case 4: r = n; g = wh; b = v; break; - case 5: r = v; g = wh; b = n; break; - } - /* eslint-enable max-statements-per-line,no-multi-spaces */ +/** + * Get the first event in a set of event emitters and event pairs. + * + * @param {array} stuff + * @param {function} done + * @public + */ - return [r * 255, g * 255, b * 255]; -}; +function first(stuff, done) { + if (!Array.isArray(stuff)) + throw new TypeError('arg must be an array of [ee, events...] arrays') -convert.cmyk.rgb = function (cmyk) { - const c = cmyk[0] / 100; - const m = cmyk[1] / 100; - const y = cmyk[2] / 100; - const k = cmyk[3] / 100; + var cleanups = [] - const r = 1 - Math.min(1, c * (1 - k) + k); - const g = 1 - Math.min(1, m * (1 - k) + k); - const b = 1 - Math.min(1, y * (1 - k) + k); + for (var i = 0; i < stuff.length; i++) { + var arr = stuff[i] - return [r * 255, g * 255, b * 255]; -}; + if (!Array.isArray(arr) || arr.length < 2) + throw new TypeError('each array member must be [ee, events...]') -convert.xyz.rgb = function (xyz) { - const x = xyz[0] / 100; - const y = xyz[1] / 100; - const z = xyz[2] / 100; - let r; - let g; - let b; + var ee = arr[0] - r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986); - g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415); - b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570); + for (var j = 1; j < arr.length; j++) { + var event = arr[j] + var fn = listener(event, callback) - // Assume sRGB - r = r > 0.0031308 - ? ((1.055 * (r ** (1.0 / 2.4))) - 0.055) - : r * 12.92; + // listen to the event + ee.on(event, fn) + // push this listener to the list of cleanups + cleanups.push({ + ee: ee, + event: event, + fn: fn, + }) + } + } - g = g > 0.0031308 - ? ((1.055 * (g ** (1.0 / 2.4))) - 0.055) - : g * 12.92; + function callback() { + cleanup() + done.apply(null, arguments) + } - b = b > 0.0031308 - ? ((1.055 * (b ** (1.0 / 2.4))) - 0.055) - : b * 12.92; + function cleanup() { + var x + for (var i = 0; i < cleanups.length; i++) { + x = cleanups[i] + x.ee.removeListener(x.event, x.fn) + } + } - r = Math.min(Math.max(0, r), 1); - g = Math.min(Math.max(0, g), 1); - b = Math.min(Math.max(0, b), 1); + function thunk(fn) { + done = fn + } - return [r * 255, g * 255, b * 255]; -}; + thunk.cancel = cleanup -convert.xyz.lab = function (xyz) { - let x = xyz[0]; - let y = xyz[1]; - let z = xyz[2]; + return thunk +} - x /= 95.047; - y /= 100; - z /= 108.883; +/** + * Create the event listener. + * @private + */ + +function listener(event, done) { + return function onevent(arg1) { + var args = new Array(arguments.length) + var ee = this + var err = event === 'error' + ? arg1 + : null - x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116); - y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116); - z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116); + // copy args to prevent arguments escaping scope + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i] + } - const l = (116 * y) - 16; - const a = 500 * (x - y); - const b = 200 * (y - z); + done(err, ee, event, args) + } +} - return [l, a, b]; -}; -convert.lab.xyz = function (lab) { - const l = lab[0]; - const a = lab[1]; - const b = lab[2]; - let x; - let y; - let z; +/***/ }), - y = (l + 16) / 116; - x = a / 500 + y; - z = y - b / 200; +/***/ 18212: +/***/ ((module) => { - const y2 = y ** 3; - const x2 = x ** 3; - const z2 = z ** 3; - y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787; - x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787; - z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787; +"use strict"; - x *= 95.047; - y *= 100; - z *= 108.883; - return [x, y, z]; +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; }; -convert.lab.lch = function (lab) { - const l = lab[0]; - const a = lab[1]; - const b = lab[2]; - let h; - - const hr = Math.atan2(b, a); - h = hr * 360 / 2 / Math.PI; - - if (h < 0) { - h += 360; - } - const c = Math.sqrt(a * a + b * b); +/***/ }), - return [l, c, h]; -}; +/***/ 16592: +/***/ ((module) => { -convert.lch.lab = function (lch) { - const l = lch[0]; - const c = lch[1]; - const h = lch[2]; +"use strict"; +/*! + * encodeurl + * Copyright(c) 2016 Douglas Christopher Wilson + * MIT Licensed + */ - const hr = h / 360 * 2 * Math.PI; - const a = c * Math.cos(hr); - const b = c * Math.sin(hr); - return [l, a, b]; -}; -convert.rgb.ansi16 = function (args, saturation = null) { - const [r, g, b] = args; - let value = saturation === null ? convert.rgb.hsv(args)[2] : saturation; // Hsv -> ansi16 optimization +/** + * Module exports. + * @public + */ - value = Math.round(value / 50); +module.exports = encodeUrl - if (value === 0) { - return 30; - } +/** + * RegExp to match non-URL code points, *after* encoding (i.e. not including "%") + * and including invalid escape sequences. + * @private + */ - let ansi = 30 - + ((Math.round(b / 255) << 2) - | (Math.round(g / 255) << 1) - | Math.round(r / 255)); +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 - if (value === 2) { - ansi += 60; - } +/** + * RegExp to match unmatched surrogate pair. + * @private + */ - return ansi; -}; +var UNMATCHED_SURROGATE_PAIR_REGEXP = /(^|[^\uD800-\uDBFF])[\uDC00-\uDFFF]|[\uD800-\uDBFF]([^\uDC00-\uDFFF]|$)/g -convert.hsv.ansi16 = function (args) { - // Optimization here; we already know the value and don't need to get - // it converted for us. - return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]); -}; +/** + * String to replace unmatched surrogate pair with. + * @private + */ -convert.rgb.ansi256 = function (args) { - const r = args[0]; - const g = args[1]; - const b = args[2]; +var UNMATCHED_SURROGATE_PAIR_REPLACE = '$1\uFFFD$2' - // We use the extended greyscale palette here, with the exception of - // black and white. normal palette only has 4 greyscale shades. - if (r === g && g === b) { - if (r < 8) { - return 16; - } +/** + * 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 + */ - if (r > 248) { - return 231; - } +function encodeUrl (url) { + return String(url) + .replace(UNMATCHED_SURROGATE_PAIR_REGEXP, UNMATCHED_SURROGATE_PAIR_REPLACE) + .replace(ENCODE_CHARS_REGEXP, encodeURI) +} - return Math.round(((r - 8) / 247) * 24) + 232; - } - const ansi = 16 - + (36 * Math.round(r / 255 * 5)) - + (6 * Math.round(g / 255 * 5)) - + Math.round(b / 255 * 5); +/***/ }), - return ansi; -}; +/***/ 23505: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -convert.ansi16.rgb = function (args) { - let color = args % 10; +"use strict"; - // Handle greyscale - if (color === 0 || color === 7) { - if (args > 50) { - color += 3.5; - } - color = color / 10.5 * 255; +var util = __nccwpck_require__(73837); +var isArrayish = __nccwpck_require__(7604); - return [color, color, color]; +var errorEx = function errorEx(name, properties) { + if (!name || name.constructor !== String) { + properties = name || {}; + name = Error.name; } - const mult = (~~(args > 50) + 1) * 0.5; - const r = ((color & 1) * mult) * 255; - const g = (((color >> 1) & 1) * mult) * 255; - const b = (((color >> 2) & 1) * mult) * 255; + var errorExError = function ErrorEXError(message) { + if (!this) { + return new ErrorEXError(message); + } - return [r, g, b]; -}; + message = message instanceof Error + ? message.message + : (message || this.message); -convert.ansi256.rgb = function (args) { - // Handle greyscale - if (args >= 232) { - const c = (args - 232) * 10 + 8; - return [c, c, c]; - } + Error.call(this, message); + Error.captureStackTrace(this, errorExError); - args -= 16; + this.name = name; - let rem; - const r = Math.floor(args / 36) / 5 * 255; - const g = Math.floor((rem = args % 36) / 6) / 5 * 255; - const b = (rem % 6) / 5 * 255; + Object.defineProperty(this, 'message', { + configurable: true, + enumerable: false, + get: function () { + var newMessage = message.split(/\r?\n/g); - return [r, g, b]; -}; + for (var key in properties) { + if (!properties.hasOwnProperty(key)) { + continue; + } -convert.rgb.hex = function (args) { - const integer = ((Math.round(args[0]) & 0xFF) << 16) - + ((Math.round(args[1]) & 0xFF) << 8) - + (Math.round(args[2]) & 0xFF); + var modifier = properties[key]; - const string = integer.toString(16).toUpperCase(); - return '000000'.substring(string.length) + string; -}; + if ('message' in modifier) { + newMessage = modifier.message(this[key], newMessage) || newMessage; + if (!isArrayish(newMessage)) { + newMessage = [newMessage]; + } + } + } -convert.hex.rgb = function (args) { - const match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i); - if (!match) { - return [0, 0, 0]; - } + return newMessage.join('\n'); + }, + set: function (v) { + message = v; + } + }); - let colorString = match[0]; + var overwrittenStack = null; - if (match[0].length === 3) { - colorString = colorString.split('').map(char => { - return char + char; - }).join(''); - } + var stackDescriptor = Object.getOwnPropertyDescriptor(this, 'stack'); + var stackGetter = stackDescriptor.get; + var stackValue = stackDescriptor.value; + delete stackDescriptor.value; + delete stackDescriptor.writable; - const integer = parseInt(colorString, 16); - const r = (integer >> 16) & 0xFF; - const g = (integer >> 8) & 0xFF; - const b = integer & 0xFF; + stackDescriptor.set = function (newstack) { + overwrittenStack = newstack; + }; - return [r, g, b]; -}; + stackDescriptor.get = function () { + var stack = (overwrittenStack || ((stackGetter) + ? stackGetter.call(this) + : stackValue)).split(/\r?\n+/g); -convert.rgb.hcg = function (rgb) { - const r = rgb[0] / 255; - const g = rgb[1] / 255; - const b = rgb[2] / 255; - const max = Math.max(Math.max(r, g), b); - const min = Math.min(Math.min(r, g), b); - const chroma = (max - min); - let grayscale; - let hue; + // starting in Node 7, the stack builder caches the message. + // just replace it. + if (!overwrittenStack) { + stack[0] = this.name + ': ' + this.message; + } - if (chroma < 1) { - grayscale = min / (1 - chroma); - } else { - grayscale = 0; - } + var lineCount = 1; + for (var key in properties) { + if (!properties.hasOwnProperty(key)) { + continue; + } - if (chroma <= 0) { - hue = 0; - } else - if (max === r) { - hue = ((g - b) / chroma) % 6; - } else - if (max === g) { - hue = 2 + (b - r) / chroma; - } else { - hue = 4 + (r - g) / chroma; - } + var modifier = properties[key]; - hue /= 6; - hue %= 1; + if ('line' in modifier) { + var line = modifier.line(this[key]); + if (line) { + stack.splice(lineCount++, 0, ' ' + line); + } + } - return [hue * 360, chroma * 100, grayscale * 100]; -}; + if ('stack' in modifier) { + modifier.stack(this[key], stack); + } + } -convert.hsl.hcg = function (hsl) { - const s = hsl[1] / 100; - const l = hsl[2] / 100; + return stack.join('\n'); + }; - const c = l < 0.5 ? (2.0 * s * l) : (2.0 * s * (1.0 - l)); + Object.defineProperty(this, 'stack', stackDescriptor); + }; - let f = 0; - if (c < 1.0) { - f = (l - 0.5 * c) / (1.0 - c); + if (Object.setPrototypeOf) { + Object.setPrototypeOf(errorExError.prototype, Error.prototype); + Object.setPrototypeOf(errorExError, Error); + } else { + util.inherits(errorExError, Error); } - return [hsl[0], c * 100, f * 100]; + return errorExError; }; -convert.hsv.hcg = function (hsv) { - const s = hsv[1] / 100; - const v = hsv[2] / 100; - - const c = s * v; - let f = 0; +errorEx.append = function (str, def) { + return { + message: function (v, message) { + v = v || def; - if (c < 1.0) { - f = (v - c) / (1 - c); - } + if (v) { + message[0] += ' ' + str.replace('%s', v.toString()); + } - return [hsv[0], c * 100, f * 100]; + return message; + } + }; }; -convert.hcg.rgb = function (hcg) { - const h = hcg[0] / 360; - const c = hcg[1] / 100; - const g = hcg[2] / 100; +errorEx.line = function (str, def) { + return { + line: function (v) { + v = v || def; - if (c === 0.0) { - return [g * 255, g * 255, g * 255]; - } + if (v) { + return str.replace('%s', v.toString()); + } - const pure = [0, 0, 0]; - const hi = (h % 1) * 6; - const v = hi % 1; - const w = 1 - v; - let mg = 0; + return null; + } + }; +}; - /* eslint-disable max-statements-per-line */ - switch (Math.floor(hi)) { - case 0: - pure[0] = 1; pure[1] = v; pure[2] = 0; break; - case 1: - pure[0] = w; pure[1] = 1; pure[2] = 0; break; - case 2: - pure[0] = 0; pure[1] = 1; pure[2] = v; break; - case 3: - pure[0] = 0; pure[1] = w; pure[2] = 1; break; - case 4: - pure[0] = v; pure[1] = 0; pure[2] = 1; break; - default: - pure[0] = 1; pure[1] = 0; pure[2] = w; - } - /* eslint-enable max-statements-per-line */ +module.exports = errorEx; - mg = (1.0 - c) * g; - return [ - (c * pure[0] + mg) * 255, - (c * pure[1] + mg) * 255, - (c * pure[2] + mg) * 255 - ]; -}; +/***/ }), -convert.hcg.hsv = function (hcg) { - const c = hcg[1] / 100; - const g = hcg[2] / 100; +/***/ 94070: +/***/ ((module) => { - const v = c + g * (1.0 - c); - let f = 0; +"use strict"; +/*! + * escape-html + * Copyright(c) 2012-2013 TJ Holowaychuk + * Copyright(c) 2015 Andreas Lubbe + * Copyright(c) 2015 Tiancheng "Timothy" Gu + * MIT Licensed + */ - if (v > 0.0) { - f = c / v; - } - return [hcg[0], f * 100, v * 100]; -}; -convert.hcg.hsl = function (hcg) { - const c = hcg[1] / 100; - const g = hcg[2] / 100; +/** + * Module variables. + * @private + */ - const l = g * (1.0 - c) + 0.5 * c; - let s = 0; +var matchHtmlRegExp = /["'&<>]/; - if (l > 0.0 && l < 0.5) { - s = c / (2 * l); - } else - if (l >= 0.5 && l < 1.0) { - s = c / (2 * (1 - l)); - } +/** + * Module exports. + * @public + */ - return [hcg[0], s * 100, l * 100]; -}; +module.exports = escapeHtml; -convert.hcg.hwb = function (hcg) { - const c = hcg[1] / 100; - const g = hcg[2] / 100; - const v = c + g * (1.0 - c); - return [hcg[0], (v - c) * 100, (1 - v) * 100]; -}; +/** + * Escape special characters in the given string of html. + * + * @param {string} string The string to escape for inserting into HTML + * @return {string} + * @public + */ -convert.hwb.hcg = function (hwb) { - const w = hwb[1] / 100; - const b = hwb[2] / 100; - const v = 1 - b; - const c = v - w; - let g = 0; +function escapeHtml(string) { + var str = '' + string; + var match = matchHtmlRegExp.exec(str); - if (c < 1) { - g = (v - c) / (1 - c); - } + if (!match) { + return str; + } - return [hwb[0], c * 100, g * 100]; -}; + var escape; + var html = ''; + var index = 0; + var lastIndex = 0; -convert.apple.rgb = function (apple) { - return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255]; -}; + 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; + } -convert.rgb.apple = function (rgb) { - return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535]; -}; + if (lastIndex !== index) { + html += str.substring(lastIndex, index); + } -convert.gray.rgb = function (args) { - return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255]; -}; + lastIndex = index + 1; + html += escape; + } -convert.gray.hsl = function (args) { - return [0, 0, args[0]]; -}; + return lastIndex !== index + ? html + str.substring(lastIndex, index) + : html; +} -convert.gray.hsv = convert.gray.hsl; -convert.gray.hwb = function (gray) { - return [0, 100, gray[0]]; -}; +/***/ }), -convert.gray.cmyk = function (gray) { - return [0, 0, 0, gray[0]]; -}; +/***/ 98691: +/***/ ((module) => { -convert.gray.lab = function (gray) { - return [gray[0], 0, 0]; -}; +"use strict"; -convert.gray.hex = function (gray) { - const val = Math.round(gray[0] / 100 * 255) & 0xFF; - const integer = (val << 16) + (val << 8) + val; - const string = integer.toString(16).toUpperCase(); - return '000000'.substring(string.length) + string; -}; +module.exports = string => { + if (typeof string !== 'string') { + throw new TypeError('Expected a string'); + } -convert.rgb.gray = function (rgb) { - const val = (rgb[0] + rgb[1] + rgb[2]) / 3; - return [val / 255 * 100]; + // 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'); }; /***/ }), -/***/ 86931: +/***/ 69972: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -const conversions = __nccwpck_require__(97391); -const route = __nccwpck_require__(30880); - -const convert = {}; - -const models = Object.keys(conversions); +"use strict"; +/*! + * etag + * Copyright(c) 2014-2016 Douglas Christopher Wilson + * MIT Licensed + */ -function wrapRaw(fn) { - const wrappedFn = function (...args) { - const arg0 = args[0]; - if (arg0 === undefined || arg0 === null) { - return arg0; - } - if (arg0.length > 1) { - args = arg0; - } - return fn(args); - }; +/** + * Module exports. + * @public + */ - // Preserve .conversion property if there is one - if ('conversion' in fn) { - wrappedFn.conversion = fn.conversion; - } +module.exports = etag - return wrappedFn; -} +/** + * Module dependencies. + * @private + */ -function wrapRounded(fn) { - const wrappedFn = function (...args) { - const arg0 = args[0]; +var crypto = __nccwpck_require__(6113) +var Stats = (__nccwpck_require__(57147).Stats) - if (arg0 === undefined || arg0 === null) { - return arg0; - } +/** + * Module variables. + * @private + */ - if (arg0.length > 1) { - args = arg0; - } +var toString = Object.prototype.toString - const result = fn(args); +/** + * Generate an entity tag. + * + * @param {Buffer|string} entity + * @return {string} + * @private + */ - // We're assuming the result is an array here. - // see notice in conversions.js; don't use box types - // in conversion functions. - if (typeof result === 'object') { - for (let len = result.length, i = 0; i < len; i++) { - result[i] = Math.round(result[i]); - } - } +function entitytag (entity) { + if (entity.length === 0) { + // fast-path empty + return '"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk"' + } - return result; - }; + // compute hash of entity + var hash = crypto + .createHash('sha1') + .update(entity, 'utf8') + .digest('base64') + .substring(0, 27) - // Preserve .conversion property if there is one - if ('conversion' in fn) { - wrappedFn.conversion = fn.conversion; - } + // compute length of entity + var len = typeof entity === 'string' + ? Buffer.byteLength(entity, 'utf8') + : entity.length - return wrappedFn; + return '"' + len.toString(16) + '-' + hash + '"' } -models.forEach(fromModel => { - convert[fromModel] = {}; - - Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels}); - Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels}); - - const routes = route(fromModel); - const routeModels = Object.keys(routes); - - routeModels.forEach(toModel => { - const fn = routes[toModel]; - - convert[fromModel][toModel] = wrapRounded(fn); - convert[fromModel][toModel].raw = wrapRaw(fn); - }); -}); +/** + * Create a simple ETag. + * + * @param {string|Buffer|Stats} entity + * @param {object} [options] + * @param {boolean} [options.weak] + * @return {String} + * @public + */ -module.exports = convert; +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 -/***/ }), + // validate argument + if (!isStats && typeof entity !== 'string' && !Buffer.isBuffer(entity)) { + throw new TypeError('argument entity must be string, Buffer, or fs.Stats') + } -/***/ 30880: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // generate entity tag + var tag = isStats + ? stattag(entity) + : entitytag(entity) -const conversions = __nccwpck_require__(97391); + return weak + ? 'W/' + tag + : tag +} -/* - This function routes a model to all other models. +/** + * Determine if object is a Stats object. + * + * @param {object} obj + * @return {boolean} + * @api private + */ - all functions that are routed have a property `.conversion` attached - to the returned synthetic function. This property is an array - of strings, each with the steps in between the 'from' and 'to' - color models (inclusive). +function isstats (obj) { + // genuine fs.Stats + if (typeof Stats === 'function' && obj instanceof Stats) { + return true + } - conversions that are not possible simply are not included. -*/ + // 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' +} -function buildGraph() { - const graph = {}; - // https://jsperf.com/object-keys-vs-for-in-with-closure/3 - const models = Object.keys(conversions); +/** + * Generate a tag for a stat. + * + * @param {object} stat + * @return {string} + * @private + */ - for (let len = models.length, i = 0; i < len; i++) { - graph[models[i]] = { - // http://jsperf.com/1-vs-infinity - // micro-opt, but this is simple. - distance: -1, - parent: null - }; - } +function stattag (stat) { + var mtime = stat.mtime.getTime().toString(16) + var size = stat.size.toString(16) - return graph; + return '"' + size + '-' + mtime + '"' } -// https://en.wikipedia.org/wiki/Breadth-first_search -function deriveBFS(fromModel) { - const graph = buildGraph(); - const queue = [fromModel]; // Unshift -> queue -> pop - - graph[fromModel].distance = 0; - - while (queue.length) { - const current = queue.pop(); - const adjacents = Object.keys(conversions[current]); - for (let len = adjacents.length, i = 0; i < len; i++) { - const adjacent = adjacents[i]; - const node = graph[adjacent]; +/***/ }), - if (node.distance === -1) { - node.distance = graph[current].distance + 1; - node.parent = current; - queue.unshift(adjacent); - } - } - } +/***/ 71204: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return graph; -} +"use strict"; +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ -function link(from, to) { - return function (args) { - return to(from(args)); - }; -} -function wrapConversion(toModel, graph) { - const path = [graph[toModel].parent, toModel]; - let fn = conversions[graph[toModel].parent][toModel]; - let cur = graph[toModel].parent; - while (graph[cur].parent) { - path.unshift(graph[cur].parent); - fn = link(conversions[graph[cur].parent][cur], fn); - cur = graph[cur].parent; - } +module.exports = __nccwpck_require__(22587); - fn.conversion = path; - return fn; -} -module.exports = function (fromModel) { - const graph = deriveBFS(fromModel); - const conversion = {}; +/***/ }), - const models = Object.keys(graph); - for (let len = models.length, i = 0; i < len; i++) { - const toModel = models[i]; - const node = graph[toModel]; +/***/ 313: +/***/ ((module, exports, __nccwpck_require__) => { - if (node.parent === null) { - // No possible conversion, or this node is the source model. - continue; - } +"use strict"; +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ - conversion[toModel] = wrapConversion(toModel, graph); - } - return conversion; -}; +/** + * Module dependencies. + * @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 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; -/***/ }), +/** + * Application prototype. + */ -/***/ 78510: -/***/ ((module) => { +var app = exports = module.exports = {}; -"use strict"; +/** + * Variable for trust proxy inheritance back-compat + * @private + */ +var trustProxyDefaultSymbol = '@@symbol:trust_proxy_default'; -module.exports = { - "aliceblue": [240, 248, 255], - "antiquewhite": [250, 235, 215], - "aqua": [0, 255, 255], - "aquamarine": [127, 255, 212], - "azure": [240, 255, 255], - "beige": [245, 245, 220], - "bisque": [255, 228, 196], - "black": [0, 0, 0], - "blanchedalmond": [255, 235, 205], - "blue": [0, 0, 255], - "blueviolet": [138, 43, 226], - "brown": [165, 42, 42], - "burlywood": [222, 184, 135], - "cadetblue": [95, 158, 160], - "chartreuse": [127, 255, 0], - "chocolate": [210, 105, 30], - "coral": [255, 127, 80], - "cornflowerblue": [100, 149, 237], - "cornsilk": [255, 248, 220], - "crimson": [220, 20, 60], - "cyan": [0, 255, 255], - "darkblue": [0, 0, 139], - "darkcyan": [0, 139, 139], - "darkgoldenrod": [184, 134, 11], - "darkgray": [169, 169, 169], - "darkgreen": [0, 100, 0], - "darkgrey": [169, 169, 169], - "darkkhaki": [189, 183, 107], - "darkmagenta": [139, 0, 139], - "darkolivegreen": [85, 107, 47], - "darkorange": [255, 140, 0], - "darkorchid": [153, 50, 204], - "darkred": [139, 0, 0], - "darksalmon": [233, 150, 122], - "darkseagreen": [143, 188, 143], - "darkslateblue": [72, 61, 139], - "darkslategray": [47, 79, 79], - "darkslategrey": [47, 79, 79], - "darkturquoise": [0, 206, 209], - "darkviolet": [148, 0, 211], - "deeppink": [255, 20, 147], - "deepskyblue": [0, 191, 255], - "dimgray": [105, 105, 105], - "dimgrey": [105, 105, 105], - "dodgerblue": [30, 144, 255], - "firebrick": [178, 34, 34], - "floralwhite": [255, 250, 240], - "forestgreen": [34, 139, 34], - "fuchsia": [255, 0, 255], - "gainsboro": [220, 220, 220], - "ghostwhite": [248, 248, 255], - "gold": [255, 215, 0], - "goldenrod": [218, 165, 32], - "gray": [128, 128, 128], - "green": [0, 128, 0], - "greenyellow": [173, 255, 47], - "grey": [128, 128, 128], - "honeydew": [240, 255, 240], - "hotpink": [255, 105, 180], - "indianred": [205, 92, 92], - "indigo": [75, 0, 130], - "ivory": [255, 255, 240], - "khaki": [240, 230, 140], - "lavender": [230, 230, 250], - "lavenderblush": [255, 240, 245], - "lawngreen": [124, 252, 0], - "lemonchiffon": [255, 250, 205], - "lightblue": [173, 216, 230], - "lightcoral": [240, 128, 128], - "lightcyan": [224, 255, 255], - "lightgoldenrodyellow": [250, 250, 210], - "lightgray": [211, 211, 211], - "lightgreen": [144, 238, 144], - "lightgrey": [211, 211, 211], - "lightpink": [255, 182, 193], - "lightsalmon": [255, 160, 122], - "lightseagreen": [32, 178, 170], - "lightskyblue": [135, 206, 250], - "lightslategray": [119, 136, 153], - "lightslategrey": [119, 136, 153], - "lightsteelblue": [176, 196, 222], - "lightyellow": [255, 255, 224], - "lime": [0, 255, 0], - "limegreen": [50, 205, 50], - "linen": [250, 240, 230], - "magenta": [255, 0, 255], - "maroon": [128, 0, 0], - "mediumaquamarine": [102, 205, 170], - "mediumblue": [0, 0, 205], - "mediumorchid": [186, 85, 211], - "mediumpurple": [147, 112, 219], - "mediumseagreen": [60, 179, 113], - "mediumslateblue": [123, 104, 238], - "mediumspringgreen": [0, 250, 154], - "mediumturquoise": [72, 209, 204], - "mediumvioletred": [199, 21, 133], - "midnightblue": [25, 25, 112], - "mintcream": [245, 255, 250], - "mistyrose": [255, 228, 225], - "moccasin": [255, 228, 181], - "navajowhite": [255, 222, 173], - "navy": [0, 0, 128], - "oldlace": [253, 245, 230], - "olive": [128, 128, 0], - "olivedrab": [107, 142, 35], - "orange": [255, 165, 0], - "orangered": [255, 69, 0], - "orchid": [218, 112, 214], - "palegoldenrod": [238, 232, 170], - "palegreen": [152, 251, 152], - "paleturquoise": [175, 238, 238], - "palevioletred": [219, 112, 147], - "papayawhip": [255, 239, 213], - "peachpuff": [255, 218, 185], - "peru": [205, 133, 63], - "pink": [255, 192, 203], - "plum": [221, 160, 221], - "powderblue": [176, 224, 230], - "purple": [128, 0, 128], - "rebeccapurple": [102, 51, 153], - "red": [255, 0, 0], - "rosybrown": [188, 143, 143], - "royalblue": [65, 105, 225], - "saddlebrown": [139, 69, 19], - "salmon": [250, 128, 114], - "sandybrown": [244, 164, 96], - "seagreen": [46, 139, 87], - "seashell": [255, 245, 238], - "sienna": [160, 82, 45], - "silver": [192, 192, 192], - "skyblue": [135, 206, 235], - "slateblue": [106, 90, 205], - "slategray": [112, 128, 144], - "slategrey": [112, 128, 144], - "snow": [255, 250, 250], - "springgreen": [0, 255, 127], - "steelblue": [70, 130, 180], - "tan": [210, 180, 140], - "teal": [0, 128, 128], - "thistle": [216, 191, 216], - "tomato": [255, 99, 71], - "turquoise": [64, 224, 208], - "violet": [238, 130, 238], - "wheat": [245, 222, 179], - "white": [255, 255, 255], - "whitesmoke": [245, 245, 245], - "yellow": [255, 255, 0], - "yellowgreen": [154, 205, 50] -}; +/** + * 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(); +}; -/***/ 43595: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/** + * Initialize application configuration. + * @private + */ -/* +app.defaultConfiguration = function defaultConfiguration() { + var env = process.env.NODE_ENV || 'development'; -The MIT License (MIT) + // 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); -Original Library - - Copyright (c) Marak Squires + // trust proxy inherit back-compat + Object.defineProperty(this.settings, trustProxyDefaultSymbol, { + configurable: true, + value: true + }); -Additional functionality - - Copyright (c) Sindre Sorhus (sindresorhus.com) + debug('booting in %s mode', env); -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: + 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']; + } -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. + // inherit protos + setPrototypeOf(this.request, parent.request) + setPrototypeOf(this.response, parent.response) + setPrototypeOf(this.engines, parent.engines) + setPrototypeOf(this.settings, parent.settings) + }); -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. + // setup locals + this.locals = Object.create(null); -*/ + // top-most app is mounted at / + this.mountpath = '/'; -var colors = {}; -module['exports'] = colors; + // default locals + this.locals.settings = this.settings; -colors.themes = {}; + // default configuration + this.set('view', View); + this.set('views', resolve('views')); + this.set('jsonp callback name', 'callback'); -var util = __nccwpck_require__(73837); -var ansiStyles = colors.styles = __nccwpck_require__(73104); -var defineProps = Object.defineProperties; -var newLineRegex = new RegExp(/[\r\n]+/g); + if (env === 'production') { + this.enable('view cache'); + } -colors.supportsColor = (__nccwpck_require__(10662).supportsColor); + 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.'); + } + }); +}; -if (typeof colors.enabled === 'undefined') { - colors.enabled = colors.supportsColor() !== false; -} +/** + * 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') + }); -colors.enable = function() { - colors.enabled = true; + this._router.use(query(this.get('query parser fn'))); + this._router.use(middleware.init(this)); + } }; -colors.disable = function() { - colors.enabled = false; -}; +/** + * 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 + */ -colors.stripColors = colors.strip = function(str) { - return ('' + str).replace(/\x1B\[\d+m/g, ''); +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); }; -// eslint-disable-next-line no-unused-vars -var stylize = colors.stylize = function stylize(str, style) { - if (!colors.enabled) { - return str+''; +/** + * 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 = '/'; + + // 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 styleMap = ansiStyles[style]; + var fns = flatten(slice.call(arguments, offset)); - // Stylize should work for non-ANSI styles, too - if(!styleMap && style in colors){ - // Style maps like trap operate as functions on strings; - // they don't have properties like open or close. - return colors[style](str); + if (fns.length === 0) { + throw new TypeError('app.use() requires a middleware function') } - return styleMap.open + str + styleMap.close; + // 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; }; -var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; -var escapeStringRegexp = function(str) { - if (typeof str !== 'string') { - throw new TypeError('Expected a string'); - } - return str.replace(matchOperatorsRe, '\\$&'); +/** + * 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 + */ + +app.route = function route(path) { + this.lazyrouter(); + return this._router.route(path); }; -function build(_styles) { - var builder = function builder() { - return applyStyle.apply(builder, arguments); - }; - builder._styles = _styles; - // __proto__ is used because we must return a function, but there is - // no way to create a function with a different prototype. - builder.__proto__ = proto; - return builder; -} +/** + * 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 dont 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 + */ -var styles = (function() { - var ret = {}; - ansiStyles.grey = ansiStyles.gray; - Object.keys(ansiStyles).forEach(function(key) { - ansiStyles[key].closeRe = - new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g'); - ret[key] = { - get: function() { - return build(this._styles.concat(key)); - }, - }; - }); - return ret; -})(); +app.engine = function engine(ext, fn) { + if (typeof fn !== 'function') { + throw new Error('callback function required'); + } -var proto = defineProps(function colors() {}, styles); + // get file extension + var extension = ext[0] !== '.' + ? '.' + ext + : ext; -function applyStyle() { - var args = Array.prototype.slice.call(arguments); + // store engine + this.engines[extension] = fn; - var str = args.map(function(arg) { - // Use weak equality check so we can colorize null/undefined in safe mode - if (arg != null && arg.constructor === String) { - return arg; - } else { - return util.inspect(arg); + return this; +}; + +/** + * 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 + */ + +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); } - }).join(' '); - if (!colors.enabled || !str) { - return str; + return this; } - var newLinesPresent = str.indexOf('\n') != -1; + this._router.param(name, fn); - var nestedStyles = this._styles; + return this; +}; - var i = nestedStyles.length; - while (i--) { - var code = ansiStyles[nestedStyles[i]]; - str = code.open + str.replace(code.closeRe, code.open) + code.close; - if (newLinesPresent) { - str = str.replace(newLineRegex, function(match) { - return code.close + match + code.open; - }); - } +/** + * 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]; } - return str; -} + debug('set "%s" to %o', setting, val); -colors.setTheme = function(theme) { - if (typeof theme === 'string') { - console.log('colors.setTheme now only accepts an object, not a string. ' + - 'If you are trying to set a theme from a file, it is now your (the ' + - 'caller\'s) responsibility to require the file. The old syntax ' + - 'looked like colors.setTheme(__dirname + ' + - '\'/../themes/generic-logging.js\'); The new syntax looks like '+ - 'colors.setTheme(require(__dirname + ' + - '\'/../themes/generic-logging.js\'));'); - return; - } - for (var style in theme) { - (function(style) { - colors[style] = function(str) { - if (typeof theme[style] === 'object') { - var out = str; - for (var i in theme[style]) { - out = colors[theme[style][i]](out); - } - return out; - } - return colors[theme[style]](str); - }; - })(style); + // 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; }; -function init() { - var ret = {}; - Object.keys(styles).forEach(function(name) { - ret[name] = { - get: function() { - return build([name]); - }, - }; - }); - return ret; -} +/** + * 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 + */ -var sequencer = function sequencer(map, str) { - var exploded = str.split(''); - exploded = exploded.map(map); - return exploded.join(''); +app.path = function path() { + return this.parent + ? this.parent.path() + this.mountpath + : ''; }; -// custom formatter methods -colors.trap = __nccwpck_require__(31302); -colors.zalgo = __nccwpck_require__(45610); +/** + * 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)); +}; + +/** + * Check if `setting` is disabled. + * + * app.disabled('foo') + * // => true + * + * app.enable('foo') + * app.disabled('foo') + * // => false + * + * @param {String} setting + * @return {Boolean} + * @public + */ + +app.disabled = function disabled(setting) { + return !this.set(setting); +}; + +/** + * Enable `setting`. + * + * @param {String} setting + * @return {app} for chaining + * @public + */ + +app.enable = function enable(setting) { + return this.set(setting, true); +}; + +/** + * Disable `setting`. + * + * @param {String} setting + * @return {app} for chaining + * @public + */ + +app.disable = function disable(setting) { + return this.set(setting, false); +}; + +/** + * Delegate `.VERB(...)` calls to `router.VERB(...)`. + */ + +methods.forEach(function(method){ + app[method] = function(path){ + if (method === 'get' && arguments.length === 1) { + // app.get(setting) + return this.set(path); + } -// maps -colors.maps = {}; -colors.maps.america = __nccwpck_require__(76936)(colors); -colors.maps.zebra = __nccwpck_require__(12989)(colors); -colors.maps.rainbow = __nccwpck_require__(75210)(colors); -colors.maps.random = __nccwpck_require__(13441)(colors); + this.lazyrouter(); -for (var map in colors.maps) { - (function(map) { - colors[map] = function(str) { - return sequencer(colors.maps[map], str); - }; - })(map); -} + var route = this._router.route(path); + route[method].apply(route, slice.call(arguments, 1)); + return this; + }; +}); -defineProps(colors, init()); +/** + * 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 + */ +app.all = function all(path) { + this.lazyrouter(); -/***/ }), + var route = this._router.route(path); + var args = slice.call(arguments, 1); -/***/ 31302: -/***/ ((module) => { + for (var i = 0; i < methods.length; i++) { + route[methods[i]].apply(route, args); + } -module['exports'] = function runTheTrap(text, options) { - var result = ''; - text = text || 'Run the trap, drop the bass'; - text = text.split(''); - var trap = { - a: ['\u0040', '\u0104', '\u023a', '\u0245', '\u0394', '\u039b', '\u0414'], - b: ['\u00df', '\u0181', '\u0243', '\u026e', '\u03b2', '\u0e3f'], - c: ['\u00a9', '\u023b', '\u03fe'], - d: ['\u00d0', '\u018a', '\u0500', '\u0501', '\u0502', '\u0503'], - e: ['\u00cb', '\u0115', '\u018e', '\u0258', '\u03a3', '\u03be', '\u04bc', - '\u0a6c'], - f: ['\u04fa'], - g: ['\u0262'], - h: ['\u0126', '\u0195', '\u04a2', '\u04ba', '\u04c7', '\u050a'], - i: ['\u0f0f'], - j: ['\u0134'], - k: ['\u0138', '\u04a0', '\u04c3', '\u051e'], - l: ['\u0139'], - m: ['\u028d', '\u04cd', '\u04ce', '\u0520', '\u0521', '\u0d69'], - n: ['\u00d1', '\u014b', '\u019d', '\u0376', '\u03a0', '\u048a'], - o: ['\u00d8', '\u00f5', '\u00f8', '\u01fe', '\u0298', '\u047a', '\u05dd', - '\u06dd', '\u0e4f'], - p: ['\u01f7', '\u048e'], - q: ['\u09cd'], - r: ['\u00ae', '\u01a6', '\u0210', '\u024c', '\u0280', '\u042f'], - s: ['\u00a7', '\u03de', '\u03df', '\u03e8'], - t: ['\u0141', '\u0166', '\u0373'], - u: ['\u01b1', '\u054d'], - v: ['\u05d8'], - w: ['\u0428', '\u0460', '\u047c', '\u0d70'], - x: ['\u04b2', '\u04fe', '\u04fc', '\u04fd'], - y: ['\u00a5', '\u04b0', '\u04cb'], - z: ['\u01b5', '\u0240'], - }; - text.forEach(function(c) { - c = c.toLowerCase(); - var chars = trap[c] || [' ']; - var rand = Math.floor(Math.random() * chars.length); - if (typeof trap[c] !== 'undefined') { - result += trap[c][rand]; - } else { - result += c; - } - }); - return result; + return this; }; +// del -> delete alias -/***/ }), +app.del = deprecate.function(app.delete, 'app.del: Use app.delete instead'); -/***/ 45610: -/***/ ((module) => { +/** + * 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 + */ -// please no -module['exports'] = function zalgo(text, options) { - text = text || ' he is here '; - var soul = { - 'up': [ - '̍', '̎', '̄', '̅', - '̿', '̑', '̆', '̐', - '͒', '͗', '͑', '̇', - '̈', '̊', '͂', '̓', - '̈', '͊', '͋', '͌', - '̃', '̂', '̌', '͐', - '̀', '́', '̋', '̏', - '̒', '̓', '̔', '̽', - '̉', 'ͣ', 'ͤ', 'ͥ', - 'ͦ', 'ͧ', 'ͨ', 'ͩ', - 'ͪ', 'ͫ', 'ͬ', 'ͭ', - 'ͮ', 'ͯ', '̾', '͛', - '͆', '̚', - ], - 'down': [ - '̖', '̗', '̘', '̙', - '̜', '̝', '̞', '̟', - '̠', '̤', '̥', '̦', - '̩', '̪', '̫', '̬', - '̭', '̮', '̯', '̰', - '̱', '̲', '̳', '̹', - '̺', '̻', '̼', 'ͅ', - '͇', '͈', '͉', '͍', - '͎', '͓', '͔', '͕', - '͖', '͙', '͚', '̣', - ], - 'mid': [ - '̕', '̛', '̀', '́', - '͘', '̡', '̢', '̧', - '̨', '̴', '̵', '̶', - '͜', '͝', '͞', - '͟', '͠', '͢', '̸', - '̷', '͡', ' ҉', - ], - }; - var all = [].concat(soul.up, soul.down, soul.mid); +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 randomNumber(range) { - var r = Math.floor(Math.random() * range); - return r; + // support callback function as second arg + if (typeof options === 'function') { + done = options; + opts = {}; } - function isChar(character) { - var bool = false; - all.filter(function(i) { - bool = (i === character); - }); - return bool; - } + // merge app.locals + merge(renderOptions, this.locals); + // merge options._locals + if (opts._locals) { + merge(renderOptions, opts._locals); + } - function heComes(text, options) { - var result = ''; - var counts; - var l; - options = options || {}; - options['up'] = - typeof options['up'] !== 'undefined' ? options['up'] : true; - options['mid'] = - typeof options['mid'] !== 'undefined' ? options['mid'] : true; - options['down'] = - typeof options['down'] !== 'undefined' ? options['down'] : true; - options['size'] = - typeof options['size'] !== 'undefined' ? options['size'] : 'maxi'; - text = text.split(''); - for (l in text) { - if (isChar(l)) { - continue; - } - result = result + text[l]; - counts = {'up': 0, 'down': 0, 'mid': 0}; - switch (options.size) { - case 'mini': - counts.up = randomNumber(8); - counts.mid = randomNumber(2); - counts.down = randomNumber(8); - break; - case 'maxi': - counts.up = randomNumber(16) + 3; - counts.mid = randomNumber(4) + 1; - counts.down = randomNumber(64) + 3; - break; - default: - counts.up = randomNumber(8) + 1; - counts.mid = randomNumber(6) / 2; - counts.down = randomNumber(8) + 1; - break; - } + // merge options + merge(renderOptions, opts); - var arr = ['up', 'mid', 'down']; - for (var d in arr) { - var index = arr[d]; - for (var i = 0; i <= counts[index]; i++) { - if (options[index]) { - result = result + soul[index][randomNumber(soul[index].length)]; - } - } - } - } - return result; + // set .cache unless explicitly provided + if (renderOptions.cache == null) { + renderOptions.cache = this.enabled('view cache'); } - // don't summon him - return heComes(text, options); -}; - + // primed cache + if (renderOptions.cache) { + view = cache[name]; + } -/***/ }), + // view + if (!view) { + var View = this.get('view'); -/***/ 76936: -/***/ ((module) => { + view = new View(name, { + defaultEngine: this.get('view engine'), + root: this.get('views'), + engines: engines + }); -module['exports'] = function(colors) { - return function(letter, i, exploded) { - if (letter === ' ') return letter; - switch (i%3) { - case 0: return colors.red(letter); - case 1: return colors.white(letter); - case 2: return colors.blue(letter); + 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); } - }; -}; + // prime the cache + if (renderOptions.cache) { + cache[name] = view; + } + } -/***/ }), + // render + tryRender(view, renderOptions, done); +}; -/***/ 75210: -/***/ ((module) => { +/** + * 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 + */ -module['exports'] = function(colors) { - // RoY G BiV - var rainbowColors = ['red', 'yellow', 'green', 'blue', 'magenta']; - return function(letter, i, exploded) { - if (letter === ' ') { - return letter; - } else { - return colors[rainbowColors[i++ % rainbowColors.length]](letter); - } - }; +app.listen = function listen() { + var server = http.createServer(this); + return server.listen.apply(server, arguments); }; +/** + * Log error using console.error. + * + * @param {Error} err + * @private + */ +function logerror(err) { + /* istanbul ignore next */ + if (this.get('env') !== 'test') console.error(err.stack || err.toString()); +} -/***/ }), - -/***/ 13441: -/***/ ((module) => { +/** + * Try rendering a view. + * @private + */ -module['exports'] = function(colors) { - var available = ['underline', 'inverse', 'grey', 'yellow', 'red', 'green', - 'blue', 'white', 'cyan', 'magenta', 'brightYellow', 'brightRed', - 'brightGreen', 'brightBlue', 'brightWhite', 'brightCyan', 'brightMagenta']; - return function(letter, i, exploded) { - return letter === ' ' ? letter : - colors[ - available[Math.round(Math.random() * (available.length - 2))] - ](letter); - }; -}; +function tryRender(view, options, callback) { + try { + view.render(options, callback); + } catch (err) { + callback(err); + } +} /***/ }), -/***/ 12989: -/***/ ((module) => { +/***/ 22587: +/***/ ((module, exports, __nccwpck_require__) => { -module['exports'] = function(colors) { - return function(letter, i, exploded) { - return i % 2 === 0 ? letter : colors.inverse(letter); - }; -}; +"use strict"; +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ -/***/ }), -/***/ 73104: -/***/ ((module) => { +/** + * Module dependencies. + */ -/* -The MIT License (MIT) +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); -Copyright (c) Sindre Sorhus (sindresorhus.com) +/** + * Expose `createApplication()`. + */ -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 = module.exports = createApplication; -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. +/** + * Create an express application. + * + * @return {Function} + * @api public + */ -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 createApplication() { + var app = function(req, res, next) { + app.handle(req, res, next); + }; -*/ + mixin(app, EventEmitter.prototype, false); + mixin(app, proto, false); -var styles = {}; -module['exports'] = styles; + // expose the prototype that will get set on requests + app.request = Object.create(req, { + app: { configurable: true, enumerable: true, writable: true, value: app } + }) -var codes = { - reset: [0, 0], + // expose the prototype that will get set on responses + app.response = Object.create(res, { + app: { configurable: true, enumerable: true, writable: true, value: app } + }) - bold: [1, 22], - dim: [2, 22], - italic: [3, 23], - underline: [4, 24], - inverse: [7, 27], - hidden: [8, 28], - strikethrough: [9, 29], + app.init(); + return app; +} - black: [30, 39], - red: [31, 39], - green: [32, 39], - yellow: [33, 39], - blue: [34, 39], - magenta: [35, 39], - cyan: [36, 39], - white: [37, 39], - gray: [90, 39], - grey: [90, 39], +/** + * Expose the prototypes. + */ - brightRed: [91, 39], - brightGreen: [92, 39], - brightYellow: [93, 39], - brightBlue: [94, 39], - brightMagenta: [95, 39], - brightCyan: [96, 39], - brightWhite: [97, 39], +exports.application = proto; +exports.request = req; +exports.response = res; - bgBlack: [40, 49], - bgRed: [41, 49], - bgGreen: [42, 49], - bgYellow: [43, 49], - bgBlue: [44, 49], - bgMagenta: [45, 49], - bgCyan: [46, 49], - bgWhite: [47, 49], - bgGray: [100, 49], - bgGrey: [100, 49], +/** + * Expose constructors. + */ - bgBrightRed: [101, 49], - bgBrightGreen: [102, 49], - bgBrightYellow: [103, 49], - bgBrightBlue: [104, 49], - bgBrightMagenta: [105, 49], - bgBrightCyan: [106, 49], - bgBrightWhite: [107, 49], +exports.Route = Route; +exports.Router = Router; - // legacy styles for colors pre v1.0.0 - blackBG: [40, 49], - redBG: [41, 49], - greenBG: [42, 49], - yellowBG: [43, 49], - blueBG: [44, 49], - magentaBG: [45, 49], - cyanBG: [46, 49], - whiteBG: [47, 49], +/** + * Expose middleware + */ -}; +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 + +/** + * Replace removed middleware with an appropriate error message. + */ + +var removedMiddlewares = [ + 'bodyParser', + 'compress', + 'cookieSession', + 'session', + 'logger', + 'cookieParser', + 'favicon', + 'responseTime', + 'errorHandler', + 'timeout', + 'methodOverride', + 'vhost', + 'csrf', + 'directory', + 'limit', + 'multipart', + 'staticCache' +] -Object.keys(codes).forEach(function(key) { - var val = codes[key]; - var style = styles[key] = []; - style.open = '\u001b[' + val[0] + 'm'; - style.close = '\u001b[' + val[1] + 'm'; +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 + }); }); /***/ }), -/***/ 10223: -/***/ ((module) => { +/***/ 92636: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -/* -MIT License +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ -Copyright (c) Sindre Sorhus (sindresorhus.com) -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: -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. +/** + * Module dependencies. + * @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. -*/ +var setPrototypeOf = __nccwpck_require__(40414) +/** + * 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 + */ +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; -module.exports = function(flag, argv) { - argv = argv || process.argv; + setPrototypeOf(req, app.request) + setPrototypeOf(res, app.response) - var terminatorPos = argv.indexOf('--'); - var prefix = /^-{1,2}/.test(flag) ? '' : '--'; - var pos = argv.indexOf(prefix + flag); + res.locals = res.locals || Object.create(null); - return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos); + next(); + }; }; + /***/ }), -/***/ 10662: +/***/ 79768: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -/* -The MIT License (MIT) - -Copyright (c) Sindre Sorhus (sindresorhus.com) - -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: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ -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. -*/ +/** + * Module dependencies. + */ +var merge = __nccwpck_require__(44429) +var parseUrl = __nccwpck_require__(89808); +var qs = __nccwpck_require__(22760); -var os = __nccwpck_require__(22037); -var hasFlag = __nccwpck_require__(10223); +/** + * @param {Object} options + * @return {Function} + * @api public + */ -var env = process.env; +module.exports = function query(options) { + var opts = merge({}, options) + var queryparse = qs.parse; -var forceColor = void 0; -if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false')) { - forceColor = false; -} else if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true') - || hasFlag('color=always')) { - forceColor = true; -} -if ('FORCE_COLOR' in env) { - forceColor = env.FORCE_COLOR.length === 0 - || parseInt(env.FORCE_COLOR, 10) !== 0; -} + if (typeof options === 'function') { + queryparse = options; + opts = undefined; + } -function translateLevel(level) { - if (level === 0) { - return false; + if (opts !== undefined && opts.allowPrototypes === undefined) { + // back-compat for qs module + opts.allowPrototypes = true; } - return { - level: level, - hasBasic: true, - has256: level >= 2, - has16m: level >= 3, + return function query(req, res, next){ + if (!req.query) { + var val = parseUrl(req).query; + req.query = queryparse(val, opts); + } + + next(); }; -} +}; -function supportsColor(stream) { - if (forceColor === false) { - return 0; - } - if (hasFlag('color=16m') || hasFlag('color=full') - || hasFlag('color=truecolor')) { - return 3; - } +/***/ }), - if (hasFlag('color=256')) { - return 2; - } +/***/ 71260: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (stream && !stream.isTTY && forceColor !== true) { - return 0; - } +"use strict"; +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ - var min = forceColor ? 1 : 0; - if (process.platform === 'win32') { - // Node.js 7.5.0 is the first version of Node.js to include a patch to - // libuv that enables 256 color output on Windows. Anything earlier and it - // won't work. However, here we target Node.js 8 at minimum as it is an LTS - // release, and Node.js 7 is not. Windows 10 build 10586 is the first - // Windows release that supports 256 colors. Windows 10 build 14931 is the - // first release that supports 16m/TrueColor. - var osRelease = os.release().split('.'); - if (Number(process.versions.node.split('.')[0]) >= 8 - && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) { - return Number(osRelease[2]) >= 14931 ? 3 : 2; - } - return 1; - } +/** + * Module dependencies. + * @private + */ - if ('CI' in env) { - if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(function(sign) { - return sign in env; - }) || env.CI_NAME === 'codeship') { - return 1; - } +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 min; - } +/** + * Request prototype. + * @public + */ - if ('TEAMCITY_VERSION' in env) { - return (/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0 - ); - } +var req = Object.create(http.IncomingMessage.prototype) - if ('TERM_PROGRAM' in env) { - var version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); +/** + * Module exports. + * @public + */ - switch (env.TERM_PROGRAM) { - case 'iTerm.app': - return version >= 3 ? 3 : 2; - case 'Hyper': - return 3; - case 'Apple_Terminal': - return 2; - // No default - } - } +module.exports = req - if (/-256(color)?$/i.test(env.TERM)) { - return 2; - } +/** + * Return request header. + * + * 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()`. + * + * @param {String} name + * @return {String} + * @public + */ - if (/^screen|^xterm|^vt100|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { - return 1; +req.get = +req.header = function header(name) { + if (!name) { + throw new TypeError('name argument is required to req.get'); } - if ('COLORTERM' in env) { - return 1; + if (typeof name !== 'string') { + throw new TypeError('name must be a string to req.get'); } - if (env.TERM === 'dumb') { - return min; - } + var lc = name.toLowerCase(); - return min; -} + switch (lc) { + case 'referer': + case 'referrer': + return this.headers.referrer + || this.headers.referer; + default: + return this.headers[lc]; + } +}; -function getSupportLevel(stream) { - var level = supportsColor(stream); - return translateLevel(level); -} +/** + * 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 + * + * // 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 + */ -module.exports = { - supportsColor: getSupportLevel, - stdout: getSupportLevel(process.stdout), - stderr: getSupportLevel(process.stderr), +req.accepts = function(){ + var accept = accepts(this); + return accept.types.apply(accept, arguments); }; +/** + * Check if the given `encoding`s are accepted. + * + * @param {String} ...encoding + * @return {String|Array} + * @public + */ -/***/ }), - -/***/ 41997: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +req.acceptsEncodings = function(){ + var accept = accepts(this); + return accept.encodings.apply(accept, arguments); +}; -// -// Remark: Requiring this file will use the "safe" colors API, -// which will not touch String.prototype. -// -// var colors = require('colors/safe'); -// colors.red("foo") -// -// -var colors = __nccwpck_require__(43595); -module['exports'] = colors; +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 + */ -/***/ }), +req.acceptsCharsets = function(){ + var accept = accepts(this); + return accept.charsets.apply(accept, arguments); +}; -/***/ 61904: -/***/ ((module, exports, __nccwpck_require__) => { +req.acceptsCharset = deprecate.function(req.acceptsCharsets, + 'req.acceptsCharset: Use acceptsCharsets instead'); /** - * Module dependencies. + * Check if the given `lang`s are acceptable, + * otherwise you should respond with 406 "Not Acceptable". + * + * @param {String} ...lang + * @return {String|Array} + * @public */ -const EventEmitter = (__nccwpck_require__(82361).EventEmitter); -const spawn = (__nccwpck_require__(32081).spawn); -const path = __nccwpck_require__(71017); -const fs = __nccwpck_require__(57147); - -// @ts-check +req.acceptsLanguages = function(){ + var accept = accepts(this); + return accept.languages.apply(accept, arguments); +}; -class Option { - /** - * Initialize a new `Option` with the given `flags` and `description`. - * - * @param {string} flags - * @param {string} description - * @api public - */ +req.acceptsLanguage = deprecate.function(req.acceptsLanguages, + 'req.acceptsLanguage: Use acceptsLanguages instead'); - 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; - } +/** + * 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. + * + * 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 + */ - /** - * Return option name. - * - * @return {string} - * @api private - */ +req.range = function range(size, options) { + var range = this.get('Range'); + if (!range) return; + return parseRange(size, range, options); +}; - name() { - if (this.long) { - return this.long.replace(/^--/, ''); - } - return this.short.replace(/^-/, ''); - }; +/** + * 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 + */ - /** - * Return option name, in a camelcase format that can be used - * as a object attribute key. - * - * @return {string} - * @api private - */ +req.param = function param(name, defaultValue) { + var params = this.params || {}; + var body = this.body || {}; + var query = this.query || {}; - attributeName() { - return camelcase(this.name().replace(/^no-/, '')); - }; + var args = arguments.length === 1 + ? 'name' + : 'name, default'; + deprecate('req.param(' + args + '): Use req.params, req.body, or req.query instead'); - /** - * Check if `arg` matches the short or long flag. - * - * @param {string} arg - * @return {boolean} - * @api private - */ + if (null != params[name] && params.hasOwnProperty(name)) return params[name]; + if (null != body[name]) return body[name]; + if (null != query[name]) return query[name]; - is(arg) { - return this.short === arg || this.long === arg; - }; -} + return defaultValue; +}; /** - * CommanderError class - * @class + * Check if the incoming request contains the "Content-Type" + * header field, and it contains the give 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 + * + * req.is('html'); + * // => false + * + * @param {String|Array} types... + * @return {String|false|null} + * @public */ -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; +req.is = function is(types) { + var arr = types; - 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'; + // support flattened arguments + if (!Array.isArray(types)) { + arr = new Array(arguments.length); + for (var i = 0; i < arr.length; i++) { + arr[i] = arguments[i]; + } } - /** - * 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 - */ + return typeis(this, arr); +}; - 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()); +/** + * 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. + * + * If you're running behind a reverse proxy that + * supplies https for you this may be enabled. + * + * @return {String} + * @public + */ - if (desc) { - cmd.description(desc); - cmd._executableHandler = true; - } - if (opts.isDefault) this._defaultCommandName = cmd._name; +defineGetter(req, 'protocol', function protocol(){ + var proto = this.connection.encrypted + ? 'https' + : 'http'; + var trust = this.app.get('trust proxy fn'); - 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; + if (!trust(this.connection.remoteAddress, 0)) { + return proto; + } - 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; + // 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(',') - if (desc) return this; - return cmd; - }; + return index !== -1 + ? header.substring(0, index).trim() + : header.trim() +}); - /** - * 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 - */ +/** + * Short-hand for: + * + * req.protocol === 'https' + * + * @return {Boolean} + * @public + */ - createCommand(name) { - return new Command(name); - }; +defineGetter(req, 'secure', function secure(){ + return this.protocol === 'https'; +}); - /** - * 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 - */ +/** + * Return the remote address from the trusted proxy. + * + * The is the remote address on the socket unless + * "trust proxy" is set. + * + * @return {String} + * @public + */ - addCommand(cmd, opts) { - if (!cmd._name) throw new Error('Command passed to .addCommand() must have a name'); +defineGetter(req, 'ip', function ip(){ + var trust = this.app.get('trust proxy fn'); + return proxyaddr(this, trust); +}); - // 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); +/** + * When "trust proxy" is set, trusted proxy addresses + client. + * + * 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 + */ - opts = opts || {}; - if (opts.isDefault) this._defaultCommandName = cmd._name; - if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation +defineGetter(req, 'ips', function ips() { + var trust = this.app.get('trust proxy fn'); + var addrs = proxyaddr.all(this, trust); - this.commands.push(cmd); - cmd.parent = this; - return this; - }; + // reverse the order (to farthest -> closest) + // and remove socket address + addrs.reverse().pop() - /** - * Define argument syntax for the command. - * - * @api public - */ + return addrs +}); - arguments(desc) { - return this._parseExpectedArgs(desc.split(/ +/)); - }; +/** + * 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"]`. + * + * @return {Array} + * @public + */ - /** - * 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 - */ +defineGetter(req, 'subdomains', function subdomains() { + var hostname = this.hostname; - 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; - }; + if (!hostname) return []; - /** - * @return {boolean} - * @api private - */ + var offset = this.app.get('subdomain offset'); + var subdomains = !isIP(hostname) + ? hostname.split('.').reverse() + : [hostname]; - _lazyHasImplicitHelpCommand() { - if (this._hasImplicitHelpCommand === undefined) { - this._hasImplicitHelpCommand = this.commands.length && !this._actionHandler && !this._findCommand('help'); - } - return this._hasImplicitHelpCommand; - }; + return subdomains.slice(offset); +}); - /** - * Parse expected `args`. - * - * For example `["[type]"]` becomes `[{ required: false, name: 'type' }]`. - * - * @param {Array} args - * @return {Command} `this` command for chaining - * @api private - */ +/** + * Short-hand for `url.parse(req.url).pathname`. + * + * @return {String} + * @public + */ - _parseExpectedArgs(args) { - if (!args.length) return; - args.forEach((arg) => { - const argDetails = { - required: false, - name: '', - variadic: false - }; +defineGetter(req, 'path', function path() { + return parse(this).pathname; +}); - switch (arg[0]) { - case '<': - argDetails.required = true; - argDetails.name = arg.slice(1, -1); - break; - case '[': - argDetails.name = arg.slice(1, -1); - break; - } +/** + * 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. + * + * @return {String} + * @public + */ - 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; - }; +defineGetter(req, 'hostname', function hostname(){ + var trust = this.app.get('trust proxy fn'); + var host = this.get('X-Forwarded-Host'); - /** - * 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 - */ + 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() + } - 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; - }; + if (!host) return; - /** - * 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 - */ + // IPv6 literal support + var offset = host[0] === '[' + ? host.indexOf(']') + 1 + : 0; + var index = host.indexOf(':', offset); - _exit(exitCode, code, message) { - if (this._exitCallback) { - this._exitCallback(new CommanderError(exitCode, code, message)); - // Expecting this line is not reached. - } - process.exit(exitCode); - }; + return index !== -1 + ? host.substring(0, index) + : host; +}); - /** - * 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 - */ +// TODO: change req.host to return host in next major + +defineGetter(req, 'host', deprecate.function(function host(){ + return this.hostname; +}, 'req.host: Use req.hostname instead')); + +/** + * Check if the request is fresh, aka + * Last-Modified and/or the ETag + * still match. + * + * @return {Boolean} + * @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)); - } +defineGetter(req, 'fresh', function(){ + var method = this.method; + var res = this.res + var status = res.statusCode - 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 or HEAD for weak freshness validation only + if ('GET' !== method && 'HEAD' !== method) return false; - /** - * Internal routine to check whether there is a clash storing option value with a Command property. - * - * @param {Option} option - * @api private - */ + // 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') + }) + } - _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; - } + return false; +}); - const commandProperty = this._getOptionValue(option.attributeName()); - if (commandProperty === undefined) { - // no clash - return; - } +/** + * Check if the request is stale, aka + * "Last-Modified" and / or the "ETag" for the + * resource has changed. + * + * @return {Boolean} + * @public + */ - 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); - } +defineGetter(req, 'stale', function stale(){ + return !this.fresh; +}); - 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 +/** + * Check if the request was an _XMLHttpRequest_. + * + * @return {Boolean} + * @public + */ -Read more on https://git.io/JJc0W`); - } - }; +defineGetter(req, 'xhr', function xhr(){ + var val = this.get('X-Requested-With') || ''; + return val.toLowerCase() === 'xmlhttprequest'; +}); - /** - * 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 - */ +/** + * Helper function for creating a getter on an object. + * + * @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 + }); +} - _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; - } - } +/***/ 64934: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // 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; - } - } +"use strict"; +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ - // 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); - } - } +/** + * Module dependencies. + * @private + */ - // 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); - } - }); +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__(92098); +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); - return this; - }; +/** + * Response prototype. + * @public + */ - /** - * 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 - */ +var res = Object.create(http.ServerResponse.prototype) - option(flags, description, fn, defaultValue) { - return this._optionEx({}, flags, description, fn, defaultValue); - }; +/** + * Module exports. + * @public + */ - /** - * 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 - */ +module.exports = res - requiredOption(flags, description, fn, defaultValue) { - return this._optionEx({ mandatory: true }, flags, description, fn, defaultValue); - }; +/** + * Module variables. + * @private + */ - /** - * 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; - }; +var charsetRegExp = /;\s*charset\s*=/; - /** - * 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; - }; +/** + * Set status `code`. + * + * @param {Number} code + * @return {ServerResponse} + * @public + */ - /** - * 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 - */ +res.status = function status(code) { + this.statusCode = code; + return this; +}; - storeOptionsAsProperties(value) { - this._storeOptionsAsPropertiesCalled = true; - this._storeOptionsAsProperties = (value === undefined) || value; - if (this.options.length) { - throw new Error('call .storeOptionsAsProperties() before adding options'); - } - return this; - }; +/** + * 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 + */ - /** - * Whether to pass command to action handler, - * or just the options (specify false). - * - * @param {boolean} value - * @return {Command} `this` command for chaining - * @api 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(', ')); +}; - passCommandToAction(value) { - this._passCommandToAction = (value === undefined) || value; - return this; - }; +/** + * 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 + */ - /** - * Store option value - * - * @param {string} key - * @param {Object} value - * @api private - */ +res.send = function send(body) { + var chunk = body; + var encoding; + var req = this.req; + var type; - _setOptionValue(key, value) { - if (this._storeOptionsAsProperties) { - this[key] = value; + // 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 { - this._optionValues[key] = value; + deprecate('res.send(status, body): Use res.status(status).send(body) instead'); + this.statusCode = arguments[0]; + chunk = arguments[1]; } - }; - - /** - * Retrieve option value - * - * @param {string} key - * @return {Object} value - * @api private - */ + } - _getOptionValue(key) { - if (this._storeOptionsAsProperties) { - return this[key]; + // 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'); } - 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 || {}; + deprecate('res.send(status): Use res.sendStatus(status) instead'); + this.statusCode = chunk; + chunk = statuses[chunk] + } - // Default to using process.argv - if (argv === undefined) { - argv = process.argv; - // @ts-ignore - if (process.versions && process.versions.electron) { - parseOptions.from = 'electron'; + 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); } - } - this.rawArgs = argv.slice(); + break; + } - // 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}' }`); + // 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')); } - if (!this._scriptPath && process.mainModule) { - this._scriptPath = process.mainModule.filename; + } + + // determine if ETag should be generated + var etagFn = app.get('etag fn') + var generateETag = !this.get('ETag') && typeof etagFn === 'function' + + // 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 } - // Guess name, used in usage in help. - this._name = this._name || (this._scriptPath && path.basename(this._scriptPath, path.extname(this._scriptPath))); + this.set('Content-Length', len); + } - // Let's go! - this._parseCommand([], userArgs); + // populate ETag + var etag; + if (generateETag && len !== undefined) { + if ((etag = etagFn(chunk, encoding))) { + this.set('ETag', etag); + } + } - return this; - }; + // freshness + if (req.fresh) this.statusCode = 304; - /** - * 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 - */ + // strip irrelevant headers + if (204 === this.statusCode || 304 === this.statusCode) { + this.removeHeader('Content-Type'); + this.removeHeader('Content-Length'); + this.removeHeader('Transfer-Encoding'); + chunk = ''; + } - parseAsync(argv, parseOptions) { - this.parse(argv, parseOptions); - return Promise.all(this._actionResults).then(() => this); - }; + if (req.method === 'HEAD') { + // skip body for HEAD + this.end(); + } else { + // respond + this.end(chunk, encoding); + } - /** - * Execute a sub-command executable. - * - * @api private - */ + return this; +}; - _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']; +/** + * Send JSON response. + * + * Examples: + * + * res.json(null); + * res.json({ user: 'tj' }); + * + * @param {string|number|boolean|object} obj + * @public + */ - // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command. - this._checkForMissingMandatoryOptions(); +res.json = function json(obj) { + var val = obj; - // 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; + // 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]; } + } - let baseDir; - try { - const resolvedLink = fs.realpathSync(scriptPath); - baseDir = path.dirname(resolvedLink); - } catch (e) { - baseDir = '.'; // dummy, probably not going to find executable! - } + // 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) - // name of the subcommand, like `pm-install` - let bin = path.basename(scriptPath, path.extname(scriptPath)) + '-' + subcommand._name; - if (subcommand._executableFile) { - bin = subcommand._executableFile; - } + // content-type + if (!this.get('Content-Type')) { + this.set('Content-Type', 'application/json'); + } - 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)); + return this.send(body); +}; - let proc; - if (process.platform !== 'win32') { - if (launchWithNode) { - args.unshift(bin); - // add executable arguments to spawn - args = incrementNodeInspectorPort(process.execArgv).concat(args); +/** + * Send JSON response with JSONP callback support. + * + * Examples: + * + * res.jsonp(null); + * res.jsonp({ user: 'tj' }); + * + * @param {string|number|boolean|object} obj + * @public + */ - proc = spawn(process.argv[0], args, { stdio: 'inherit' }); - } else { - proc = spawn(bin, args, { stdio: 'inherit' }); - } +res.jsonp = function jsonp(obj) { + var val = obj; + + // allow status / body + if (arguments.length === 2) { + // res.json(body, status) backwards compat + if (typeof arguments[1] === 'number') { + deprecate('res.jsonp(obj, status): Use res.status(status).json(obj) instead'); + this.statusCode = arguments[1]; } else { - args.unshift(bin); - // add executable arguments to spawn - args = incrementNodeInspectorPort(process.execArgv).concat(args); - proc = spawn(process.execPath, args, { stdio: 'inherit' }); + deprecate('res.jsonp(status, obj): Use res.status(status).jsonp(obj) instead'); + this.statusCode = arguments[0]; + val = arguments[1]; } + } - 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); - } - }); - }); + // 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')]; - // 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); - } - }); + // content-type + if (!this.get('Content-Type')) { + this.set('X-Content-Type-Options', 'nosniff'); + this.set('Content-Type', 'application/json'); + } - // Store the reference to the child process - this.runningCommand = proc; - }; + // fixup callback + if (Array.isArray(callback)) { + callback = callback[0]; + } - /** - * @api private - */ - _dispatchSubcommand(commandName, operands, unknown) { - const subCommand = this._findCommand(commandName); - if (!subCommand) this._helpAndError(); + // jsonp + if (typeof callback === 'string' && callback.length !== 0) { + this.set('X-Content-Type-Options', 'nosniff'); + this.set('Content-Type', 'text/javascript'); - if (subCommand._executableHandler) { - this._executeSubCommand(subCommand, operands.concat(unknown)); - } else { - subCommand._parseCommand(operands, unknown); - } - }; + // restrict callback charset + callback = callback.replace(/[^\[\]\w$.]/g, ''); - /** - * Process arguments in context of this command. - * - * @api private - */ + // replace chars not allowed in JavaScript that are in JSON + body = body + .replace(/\u2028/g, '\\u2028') + .replace(/\u2029/g, '\\u2029'); - _parseCommand(operands, unknown) { - const parsed = this.parseOptions(unknown); - operands = operands.concat(parsed.operands); - unknown = parsed.unknown; - this.args = operands.concat(unknown); + // 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 + ');'; + } - 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(); - } + return this.send(body); +}; - outputHelpIfRequested(this, parsed.unknown); - this._checkForMissingMandatoryOptions(); - if (parsed.unknown.length > 0) { - this.unknownOption(parsed.unknown[0]); - } +/** + * 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 + */ - 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); - } - }); +res.sendStatus = function sendStatus(statusCode) { + var body = statuses[statusCode] || String(statusCode) - 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() - } - } - }; + this.statusCode = statusCode; + this.type('txt'); - /** - * Find matching command. - * - * @api private - */ - _findCommand(name) { - if (!name) return undefined; - return this.commands.find(cmd => cmd._name === name || cmd._aliases.includes(name)); - }; + return this.send(body); +}; - /** - * Return an option matching `arg` if any. - * - * @param {string} arg - * @return {Option} - * @api 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.sentHeader` + * 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 + */ - _findOption(arg) { - return this.options.find(option => option.is(arg)); - }; +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 path !== 'string') { + throw new TypeError('path must be a string to res.sendFile') + } + + // support function as second arg + if (typeof options === 'function') { + done = options; + opts = {}; + } + + 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); + } + }); +}; + +/** + * 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.sentHeader` + * 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 + */ - /** - * 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 - */ +res.sendfile = function (path, options, callback) { + var done = callback; + var req = this.req; + var res = this; + var next = req.next; + var opts = options || {}; - _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); - } - }); - } - }; + // support function as second arg + if (typeof options === 'function') { + done = options; + opts = {}; + } - /** - * 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 - */ + // create file stream + var file = send(req, path, opts); - 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(); + // transfer + sendfile(res, file, opts, function (err) { + if (done) return done(err); + if (err && err.code === 'EISDIR') return next(); - function maybeOption(arg) { - return arg.length > 1 && arg[0] === '-'; + // next() all but write errors + if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') { + next(err); } + }); +}; - // 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; - } +res.sendfile = deprecate.function(res.sendfile, + 'res.sendfile: Use res.sendFile instead'); - if (activeVariadicOption && !maybeOption(arg)) { - this.emit(`option:${activeVariadicOption.name()}`, arg); - continue; - } - activeVariadicOption = null; +/** + * 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 + */ - 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; - } - } +res.download = function download (path, filename, options, callback) { + var done = callback; + var name = filename; + var opts = options || null - // 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; - } - } + // 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 + } - // 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; - } - } + // set Content-Disposition when file is sent + var headers = { + 'Content-Disposition': contentDisposition(name || path) + }; - // looks like an option but unknown, unknowns from here - if (arg.length > 1 && arg[0] === '-') { - dest = unknown; + // 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 arg - dest.push(arg); } + } - return { operands, unknown }; - }; + // merge user-provided options + opts = Object.create(opts) + opts.headers = headers - /** - * 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; + // Resolve the full path for sendFile + var fullPath = resolve(path); - for (let i = 0; i < len; i++) { - const key = this.options[i].attributeName(); - result[key] = key === this._versionOptionName ? this._version : this[key]; - } - return result; - } + // send file + return this.sendFile(fullPath, opts, done) +}; - return this._optionValues; - }; +/** + * 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 + */ - /** - * Argument `name` is missing. - * - * @param {string} name - * @api private - */ +res.contentType = +res.type = function contentType(type) { + var ct = type.indexOf('/') === -1 + ? mime.lookup(type) + : type; - missingArgument(name) { - const message = `error: missing required argument '${name}'`; - console.error(message); - this._exit(1, 'commander.missingArgument', message); - }; + return this.set('Content-Type', ct); +}; - /** - * `Option` is missing an argument, but received `flag` or nothing. - * - * @param {Option} option - * @param {string} [flag] - * @api private - */ +/** + * 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

'); + * }, + * + * 'appliation/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 + */ - 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); - }; +res.format = function(obj){ + var req = this.req; + var next = req.next; - /** - * `Option` does not have a value, and is a mandatory option. - * - * @param {Option} option - * @api private - */ + var fn = obj.default; + if (fn) delete obj.default; + var keys = Object.keys(obj); - missingMandatoryOptionValue(option) { - const message = `error: required option '${option.flags}' not specified`; - console.error(message); - this._exit(1, 'commander.missingMandatoryOptionValue', message); - }; + var key = keys.length > 0 + ? req.accepts(keys) + : false; - /** - * Unknown option `flag`. - * - * @param {string} flag - * @api private - */ + this.vary("Accept"); - unknownOption(flag) { - if (this._allowUnknownOption) return; - const message = `error: unknown option '${flag}'`; - console.error(message); - this._exit(1, 'commander.unknownOption', message); - }; + 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); + } - /** - * Unknown command. - * - * @api private - */ + return this; +}; - 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 _Content-Disposition_ header to _attachment_ with optional `filename`. + * + * @param {String} filename + * @return {ServerResponse} + * @public + */ - /** - * 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 - */ +res.attachment = function attachment(filename) { + if (filename) { + this.type(extname(filename)); + } - 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; - }; + this.set('Content-Disposition', contentDisposition(filename)); - /** - * Set the description to `str`. - * - * @param {string} str - * @param {Object} [argsDescription] - * @return {string|Command} - * @api public - */ + return this; +}; - description(str, argsDescription) { - if (str === undefined && argsDescription === undefined) return this._description; - this._description = str; - this._argsDescription = argsDescription; - return this; - }; +/** + * 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 + */ - /** - * 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 - */ +res.append = function append(field, val) { + var prev = this.get(field); + var value = val; - alias(alias) { - if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility + if (prev) { + // concat the new and prev vals + value = Array.isArray(prev) ? prev.concat(val) + : Array.isArray(val) ? [prev].concat(val) + : [prev, val]; + } - 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 this.set(field, value); +}; - if (alias === command._name) throw new Error('Command alias can\'t be the same as its name'); +/** + * 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 + */ - command._aliases.push(alias); - return this; - }; +res.set = +res.header = function header(field, val) { + if (arguments.length === 2) { + var value = Array.isArray(val) + ? val.map(String) + : String(val); - /** - * Set aliases for the command. - * - * Only the first alias is shown in the auto-generated help. - * - * @param {string[]} [aliases] - * @return {string[]|Command} - * @api public - */ + // 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(); + } + } - 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; + this.setHeader(field, value); + } else { + for (var key in field) { + this.set(key, field[key]); + } + } + return this; +}; - aliases.forEach((alias) => this.alias(alias)); - return this; - }; +/** + * Get value for header `field`. + * + * @param {String} field + * @return {String} + * @public + */ - /** - * Set / get the command usage `str`. - * - * @param {string} [str] - * @return {String|Command} - * @api public - */ +res.get = function(field){ + return this.getHeader(field); +}; - usage(str) { - if (str === undefined) { - if (this._usage) return this._usage; +/** + * Clear cookie `name`. + * + * @param {String} name + * @param {Object} [options] + * @return {ServerResponse} for chaining + * @public + */ - 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(' '); - } +res.clearCookie = function clearCookie(name, options) { + var opts = merge({ expires: new Date(1), path: '/' }, options); - this._usage = str; - return this; - }; + return this.cookie(name, '', opts); +}; - /** - * Get or set the name of the command - * - * @param {string} [str] - * @return {String|Command} - * @api public - */ +/** + * 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 + */ - name(str) { - if (str === undefined) return this._name; - this._name = str; - return this; - }; +res.cookie = function (name, value, options) { + var opts = merge({}, options); + var secret = this.req.secret; + var signed = opts.signed; - /** - * Return prepared commands. - * - * @return {Array} - * @api private - */ + if (signed && !secret) { + throw new Error('cookieParser("secret") required for signed cookies'); + } - prepareCommands() { - const commandDetails = this.commands.filter((cmd) => { - return !cmd._hidden; - }).map((cmd) => { - const args = cmd._args.map((arg) => { - return humanReadableArgName(arg); - }).join(' '); + var val = typeof value === 'object' + ? 'j:' + JSON.stringify(value) + : String(value); - return [ - cmd._name + - (cmd._aliases[0] ? '|' + cmd._aliases[0] : '') + - (cmd.options.length ? ' [options]' : '') + - (args ? ' ' + args : ''), - cmd._description - ]; - }); + if (signed) { + val = 's:' + sign(val, secret); + } - if (this._lazyHasImplicitHelpCommand()) { - commandDetails.push([this._helpCommandnameAndArgs, this._helpCommandDescription]); - } - return commandDetails; - }; + if ('maxAge' in opts) { + opts.expires = new Date(Date.now() + opts.maxAge); + opts.maxAge /= 1000; + } - /** - * Return the largest command length. - * - * @return {number} - * @api private - */ + if (opts.path == null) { + opts.path = '/'; + } - largestCommandLength() { - const commands = this.prepareCommands(); - return commands.reduce((max, command) => { - return Math.max(max, command[0].length); - }, 0); - }; + this.append('Set-Cookie', cookie.serialize(name, String(val), opts)); - /** - * Return the largest option length. - * - * @return {number} - * @api private - */ + return this; +}; - largestOptionLength() { - const options = [].slice.call(this.options); - options.push({ - flags: this._helpFlags - }); +/** + * 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 + */ - return options.reduce((max, option) => { - return Math.max(max, option.flags.length); - }, 0); - }; +res.location = function location(url) { + var loc = url; - /** - * Return the largest arg length. - * - * @return {number} - * @api private - */ + // "back" is an alias for the referrer + if (url === 'back') { + loc = this.req.get('Referrer') || '/'; + } - largestArgLength() { - return this._args.reduce((max, arg) => { - return Math.max(max, arg.name.length); - }, 0); - }; + // set location + return this.set('Location', encodeUrl(loc)); +}; - /** - * Return the pad width. - * - * @return {number} - * @api private - */ +/** + * 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.redirect('/foo/bar'); + * res.redirect('http://example.com'); + * res.redirect(301, 'http://example.com'); + * res.redirect('../login'); // /blog/post/1 -> /blog/login + * + * @public + */ - padWidth() { - let width = this.largestOptionLength(); - if (this._argsDescription && this._args.length) { - if (this.largestArgLength() > width) { - width = this.largestArgLength(); - } - } +res.redirect = function redirect(url) { + var address = url; + var body; + var status = 302; - if (this.commands && this.commands.length) { - if (this.largestCommandLength() > width) { - width = this.largestCommandLength(); - } + // 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]; } + } - return width; - }; - - /** - * Return help for options. - * - * @return {string} - * @api private - */ + // Set location header + address = this.location(address).get('Location'); - 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); - }; + // Support text/{plain,html} by default + this.format({ + text: function(){ + body = statuses[status] + '. Redirecting to ' + address + }, - // 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); - }); + html: function(){ + var u = escapeHtml(address); + body = '

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

' + }, - // 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)); + default: function(){ + body = ''; } + }); - return help.join('\n'); - }; - - /** - * Return command help documentation. - * - * @return {string} - * @api private - */ - - commandHelp() { - if (!this.commands.length && !this._lazyHasImplicitHelpCommand()) return ''; + // Respond + this.statusCode = status; + this.set('Content-Length', Buffer.byteLength(body)); - const commands = this.prepareCommands(); - const width = this.padWidth(); + if (this.req.method === 'HEAD') { + this.end(); + } else { + this.end(body); + } +}; - const columns = process.stdout.columns || 80; - const descriptionWidth = columns - width - 4; +/** + * 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 + */ - 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'); - }; +res.vary = function(field){ + // checks for back-compat + if (!field || (Array.isArray(field) && !field.length)) { + deprecate('res.vary(): Provide a field name'); + return this; + } - /** - * Return program help documentation. - * - * @return {string} - * @api public - */ + vary(this, field); - helpInformation() { - let desc = []; - if (this._description) { - desc = [ - this._description, - '' - ]; + return this; +}; - 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(''); - } - } +/** + * 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 + */ - 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(), - '' - ]; +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; - let cmds = []; - const commandHelp = this.commandHelp(); - if (commandHelp) cmds = [commandHelp]; + // support callback function as second arg + if (typeof options === 'function') { + done = options; + opts = {}; + } - let options = []; - if (this._hasHelpOption || this.options.length > 0) { - options = [ - 'Options:', - '' + this.optionHelp().replace(/^/gm, ' '), - '' - ]; - } + // merge res.locals + opts._locals = self.locals; - return usage - .concat(desc) - .concat(options) - .concat(cmds) - .join('\n'); + // default callback to respond + done = done || function (err, str) { + if (err) return req.next(err); + self.send(str); }; - /** - * Output help information for this command. - * - * When listener(s) are available for the helpLongFlag - * those callbacks are invoked. - * - * @api public - */ + // render + app.render(view, opts, done); +}; - 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); - }; +// pipe the send file stream +function sendfile(res, file, options, callback) { + var done = false; + var streaming; - /** - * 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 - */ + // request aborted + function onaborted() { + if (done) return; + done = true; - helpOption(flags, description) { - if (typeof flags === 'boolean') { - this._hasHelpOption = flags; - return this; - } - this._helpFlags = flags || this._helpFlags; - this._helpDescription = description || this._helpDescription; + var err = new Error('Request aborted'); + err.code = 'ECONNABORTED'; + callback(err); + } + + // directory + function ondirectory() { + if (done) return; + done = true; - const helpFlags = _parseOptionFlags(this._helpFlags); - this._helpShortFlag = helpFlags.shortFlag; - this._helpLongFlag = helpFlags.longFlag; + var err = new Error('EISDIR, read'); + err.code = 'EISDIR'; + callback(err); + } - return this; - }; + // errors + function onerror(err) { + if (done) return; + done = true; + callback(err); + } - /** - * Output help information and exit. - * - * @param {Function} [cb] - * @api public - */ + // ended + function onend() { + if (done) return; + done = true; + callback(); + } - 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)'); - }; + // file + function onfile() { + streaming = false; + } - /** - * Output help information and exit. Display for error situations. - * - * @api private - */ + // finished + function onfinish(err) { + if (err && err.code === 'ECONNRESET') return onaborted(); + if (err) return onerror(err); + if (done) return; - _helpAndError() { - this.outputHelp(); - // message: do not have all displayed text available so only passing placeholder. - this._exit(1, 'commander.help', '(outputHelp)'); - }; -}; + setImmediate(function () { + if (streaming !== false && !done) { + onaborted(); + return; + } -/** - * Expose the root command. - */ + if (done) return; + done = true; + callback(); + }); + } -exports = module.exports = new Command(); -exports.program = exports; // More explicit access to global command. + // streaming + function onstream() { + streaming = true; + } -/** - * Expose classes - */ + file.on('directory', ondirectory); + file.on('end', onend); + file.on('error', onerror); + file.on('file', onfile); + file.on('stream', onstream); + onFinished(res, onfinish); -exports.Command = Command; -exports.Option = Option; -exports.CommanderError = CommanderError; + if (options.headers) { + // set headers on successful transfer + file.on('headers', function headers(res) { + var obj = options.headers; + var keys = Object.keys(obj); -/** - * Camel-case the given `flag` - * - * @param {string} flag - * @return {string} - * @api private - */ + for (var i = 0; i < keys.length; i++) { + var k = keys[i]; + res.setHeader(k, obj[k]); + } + }); + } -function camelcase(flag) { - return flag.split('-').reduce((str, word) => { - return str + word[0].toUpperCase() + word.slice(1); - }); + // pipe + file.pipe(res); } /** - * Pad `str` to `width`. + * Stringify JSON, like JSON.stringify, but v8 optimized, with the + * ability to escape characters that can trigger HTML sniffing. * - * @param {string} str - * @param {number} width - * @return {string} - * @api private + * @param {*} value + * @param {function} replaces + * @param {number} spaces + * @param {boolean} escape + * @returns {string} + * @private */ -function pad(str, width) { - const len = Math.max(0, width - str.length); - return str + Array(len + 1).join(' '); -} +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); -/** - * 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'); + if (escape) { + 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 } -/** - * 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; - return wrap(str, width, indent); -} +/***/ }), -/** - * 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 +/***/ 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 */ -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)'); - } -} + /** - * Takes an argument and returns its human readable equivalent for help usage. - * - * @param {Object} arg - * @return {string} - * @api private + * Module dependencies. + * @private */ -function humanReadableArgName(arg) { - const nameOutput = arg.name + (arg.variadic === true ? '...' : ''); - - return arg.required - ? '<' + nameOutput + '>' - : '[' + nameOutput + ']'; -} +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) /** - * Parse the short and long flag out of something like '-m,--mixed ' - * - * @api private + * Module variables. + * @private */ -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 objectRegExp = /^\[object (\S+)\]$/; +var slice = Array.prototype.slice; +var toString = Object.prototype.toString; /** - * Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command). + * Initialize a new `Router` with the given `options`. * - * @param {string[]} args - array of arguments from node.execArgv - * @returns {string[]} - * @api private + * @param {Object} [options] + * @return {Router} which is an callable function + * @public */ -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]; - } +var proto = module.exports = function(options) { + var opts = options || {}; - if (debugOption && debugPort !== '0') { - return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`; - } - return arg; - }); -} + function router(req, res, next) { + router.handle(req, res, next); + } + // mixin Router class functions + setPrototypeOf(router, proto) -/***/ }), + router.params = {}; + router._params = []; + router.caseSensitive = opts.caseSensitive; + router.mergeParams = opts.mergeParams; + router.strict = opts.strict; + router.stack = []; -/***/ 89296: -/***/ (function(module) { + return router; +}; -/* 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; +/** + * 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 + */ - function indexOrEnd(str, q) { - return str.indexOf(q) === -1 ? str.length : str.indexOf(q); +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; } - 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; - } + // apply param functions + var params = this._params; + var len = params.length; + var ret; - function tryParse(v) { - var n = parseInt(v, 10); - return isNaN(n) ? v : n; + if (name[0] === ':') { + deprecate('router.param(' + JSON.stringify(name) + ', fn): Use router.param(' + JSON.stringify(name.substr(1)) + ', fn) instead'); + name = name.substr(1); } - 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)" - ); + for (var i = 0; i < len; ++i) { + if (ret = params[i](name, fn)) { + fn = ret; } - 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; + // ensure we end up with a + // middleware function + if ('function' !== typeof fn) { + throw new Error('invalid param() call for ' + name + ', got ' + fn); } - 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); + (this.params[name] = this.params[name] || []).push(fn); + return this; +}; - if (n1 > n2) return 1; - if (n2 > n1) return -1; - } +/** + * Dispatch a req, res into the router. + * @private + */ - var sp1 = s1[s1.length - 1]; - var sp2 = s2[s2.length - 1]; +proto.handle = function handle(req, res, out) { + var self = this; - if (sp1 && sp2) { - var p1 = sp1.split('.').map(tryParse); - var p2 = sp2.split('.').map(tryParse); + debug('dispatching %s %s', req.method, req.url); - 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; + var idx = 0; + var protohost = getProtohost(req.url) || '' + var removed = ''; + var slashAdded = false; + var paramcalled = {}; - if (p1[i] > p2[i]) return 1; - if (p2[i] > p1[i]) return -1; - } - } else if (sp1 || sp2) { - return sp1 ? -1 : 1; - } + // store options for OPTIONS request + // only used if OPTIONS request + var options = []; - return 0; - } + // middleware and routes + var stack = self.stack; - var allowedOperators = ['>', '>=', '=', '<', '<=']; + // manage inter-router variables + var parentParams = req.params; + var parentUrl = req.baseUrl || ''; + var done = restore(out, req, 'baseUrl', 'next', 'params'); - var operatorResMap = { - '>': [1], - '>=': [0, 1], - '=': [0], - '<=': [-1, 0], - '<': [-1], - }; + // setup next layer + req.next = next; - 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('|') - ); - } + // 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); + }); } - compareVersions.validate = function (version) { - return typeof version === 'string' && semver.test(version); - }; - - compareVersions.compare = function (v1, v2, operator) { - // Validate operator - validateOperator(operator); + // setup basic req values + req.baseUrl = parentUrl; + req.originalUrl = req.originalUrl || req.url; - // 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; - }; + next(); - compareVersions.satisfies = function (v, r) { - // if no range operator then "=" - var match = r.match(/^([<>=~^]+)/); - var op = match ? match[1] : '='; + function next(err) { + var layerError = err === 'route' + ? null + : err; - // if gt/lt/eq then operator compare - if (op !== '^' && op !== '~') return compareVersions.compare(v, r, op); + // remove added slash + if (slashAdded) { + req.url = req.url.substr(1); + slashAdded = false; + } - // 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; + // restore altered req.url + if (removed.length !== 0) { + req.baseUrl = parentUrl; + req.url = protohost + removed + req.url.substr(protohost.length); + removed = ''; } - if (compareStrings(v2, m2) !== 0) return false; - return compareStrings(v3, m3) >= 0; - }; - return compareVersions; -}); + // signal to exit router + if (layerError === 'router') { + setImmediate(done, null) + return + } + // no more matching layers + if (idx >= stack.length) { + setImmediate(done, layerError); + return; + } -/***/ }), + // get pathname of request + var path = getPathname(req); -/***/ 53921: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (path == null) { + return done(layerError); + } -"use strict"; -/*! - * content-disposition - * Copyright(c) 2014-2017 Douglas Christopher Wilson - * MIT Licensed - */ + // 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; + } -/** - * Module exports. - * @public - */ + if (match !== true) { + continue; + } -module.exports = contentDisposition -module.exports.parse = parse + if (!route) { + // process non-route handlers normally + continue; + } -/** - * Module dependencies. - * @private - */ + if (layerError) { + // routes do not match with a pending error + match = false; + continue; + } -var basename = (__nccwpck_require__(71017).basename) -var Buffer = (__nccwpck_require__(21867).Buffer) + var method = req.method; + var has_method = route._handles_method(method); -/** - * RegExp to match non attr-char, *after* encodeURIComponent (i.e. not including "%") - * @private - */ + // build up automatic options response + if (!has_method && method === 'OPTIONS') { + appendMethods(options, route._options()); + } -var ENCODE_URL_ATTR_CHAR_REGEXP = /[\x00-\x20"'()*,/:;<=>?@[\\\]{}\x7f]/g // eslint-disable-line no-control-regex + // don't even bother matching route + if (!has_method && method !== 'HEAD') { + match = false; + continue; + } + } -/** - * RegExp to match percent encoding escape. - * @private - */ + // no match + if (match !== true) { + return done(layerError); + } -var HEX_ESCAPE_REGEXP = /%[0-9A-Fa-f]{2}/ -var HEX_ESCAPE_REPLACE_REGEXP = /%([0-9A-Fa-f]{2})/g + // store route for dispatch on change + if (route) { + req.route = route; + } -/** - * RegExp to match non-latin1 characters. - * @private - */ + // Capture one-time layer values + req.params = self.mergeParams + ? mergeParams(layer.params, parentParams) + : layer.params; + var layerPath = layer.path; -var NON_LATIN1_REGEXP = /[^\x20-\x7e\xa0-\xff]/g + // this should be done for the layer + self.process_params(layer, paramcalled, req, res, function (err) { + if (err) { + return next(layerError || err); + } -/** - * RegExp to match quoted-pair in RFC 2616 - * - * quoted-pair = "\" CHAR - * CHAR = - * @private - */ + if (route) { + return layer.handle_request(req, res, next); + } -var QESC_REGEXP = /\\([\u0000-\u007f])/g // eslint-disable-line no-control-regex + trim_prefix(layer, layerError, layerPath, path); + }); + } -/** - * RegExp to match chars that must be quoted-pair in RFC 2616 - * @private - */ + function trim_prefix(layer, layerError, layerPath, path) { + if (layerPath.length !== 0) { + // Validate path breaks on a path separator + var c = path[layerPath.length] + if (c && c !== '/' && c !== '.') return next(layerError) -var QUOTE_REGEXP = /([\\"])/g + // 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); -/** - * 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 - */ + // Ensure leading slash + if (!protohost && req.url[0] !== '/') { + req.url = '/' + req.url; + slashAdded = true; + } -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|~-]+$/ + // Setup base URL (no trailing slash) + req.baseUrl = parentUrl + (removed[removed.length - 1] === '/' + ? removed.substring(0, removed.length - 1) + : removed); + } -/** - * 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 - */ + debug('%s %s : %s', layer.name, layerPath, req.originalUrl); -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!#$&+.^_`|~-])+)$/ + if (layerError) { + layer.handle_error(layerError, req, res, next); + } else { + layer.handle_request(req, res, next); + } + } +}; /** - * 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 = + * Process any parameters for the layer. * @private */ -var DISPOSITION_TYPE_REGEXP = /^([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*(?:$|;)/ // eslint-disable-line no-control-regex - -/** - * 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 - */ +proto.process_params = function process_params(layer, called, req, res, done) { + var params = this.params; -function contentDisposition (filename, options) { - var opts = options || {} + // captured parameters from the layer, keys and values + var keys = layer.keys; - // get type - var type = opts.type || 'attachment' + // fast track + if (!keys || keys.length === 0) { + return done(); + } - // get parameters - var params = createparams(filename, opts.fallback) + var i = 0; + var name; + var paramIndex = 0; + var key; + var paramVal; + var paramCallbacks; + var paramCalled; - // format into string - return format(new ContentDisposition(type, params)) -} + // process params in order + // param callbacks can be async + function param(err) { + if (err) { + return done(err); + } -/** - * Create parameters object from filename and fallback. - * - * @param {string} [filename] - * @param {string|boolean} [fallback=true] - * @return {object} - * @private - */ + if (i >= keys.length ) { + return done(); + } -function createparams (filename, fallback) { - if (filename === undefined) { - return - } + paramIndex = 0; + key = keys[i++]; + name = key.name; + paramVal = req.params[name]; + paramCallbacks = params[name]; + paramCalled = called[name]; - var params = {} + if (paramVal === undefined || !paramCallbacks) { + return param(); + } - if (typeof filename !== 'string') { - throw new TypeError('filename must be a string') - } + // 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; - // fallback defaults to true - if (fallback === undefined) { - fallback = true - } + // next param + return param(paramCalled.error); + } - if (typeof fallback !== 'string' && typeof fallback !== 'boolean') { - throw new TypeError('fallback must be a string or boolean') - } + called[name] = paramCalled = { + error: null, + match: paramVal, + value: paramVal + }; - if (typeof fallback === 'string' && NON_LATIN1_REGEXP.test(fallback)) { - throw new TypeError('fallback must be ISO-8859-1 string') + paramCallback(); } - // restrict to file base name - var name = basename(filename) + // single param callbacks + function paramCallback(err) { + var fn = paramCallbacks[paramIndex++]; - // determine if name is suitable for quoted string - var isQuotedString = TEXT_REGEXP.test(name) + // store updated value + paramCalled.value = req.params[key.name]; - // generate fallback name - var fallbackName = typeof fallback !== 'string' - ? fallback && getlatin1(name) - : basename(fallback) - var hasFallback = typeof fallbackName === 'string' && fallbackName !== name + if (err) { + // store error + paramCalled.error = err; + param(err); + return; + } - // set extended filename parameter - if (hasFallback || !isQuotedString || HEX_ESCAPE_REGEXP.test(name)) { - params['filename*'] = name - } + if (!fn) return param(); - // set filename parameter - if (isQuotedString || hasFallback) { - params.filename = hasFallback - ? fallbackName - : name + try { + fn(req, res, paramCallback, paramVal, key.name); + } catch (e) { + paramCallback(e); + } } - return params -} + param(); +}; /** - * Format object to Content-Disposition header. + * Use the given middleware function, with optional path, defaulting to "/". * - * @param {object} obj - * @param {string} obj.type - * @param {object} [obj.parameters] - * @return {string} - * @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 */ -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') - } - - // start with normalized type - var string = String(type).toLowerCase() - - // append parameters - if (parameters && typeof parameters === 'object') { - var param - var params = Object.keys(parameters).sort() +proto.use = function use(fn) { + var offset = 0; + var path = '/'; - for (var i = 0; i < params.length; i++) { - param = params[i] + // default path to '/' + // disambiguate router.use([fn]) + if (typeof fn !== 'function') { + var arg = fn; - var val = param.substr(-1) === '*' - ? ustring(parameters[param]) - : qstring(parameters[param]) + while (Array.isArray(arg) && arg.length !== 0) { + arg = arg[0]; + } - string += '; ' + param + '=' + val + // first arg is the path + if (typeof arg !== 'function') { + offset = 1; + path = fn; } } - return string -} + var callbacks = flatten(slice.call(arguments, offset)); -/** - * Decode a RFC 6987 field value (gracefully). - * - * @param {string} str - * @return {string} - * @private - */ + if (callbacks.length === 0) { + throw new TypeError('Router.use() requires a middleware function') + } -function decodefield (str) { - var match = EXT_VALUE_REGEXP.exec(str) + for (var i = 0; i < callbacks.length; i++) { + var fn = callbacks[i]; - if (!match) { - throw new TypeError('invalid extended field value') - } + if (typeof fn !== 'function') { + throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn)) + } - var charset = match[1].toLowerCase() - var encoded = match[2] - var value + // add the middleware + debug('use %o %s', path, fn.name || '') - // to binary string - var binary = encoded.replace(HEX_ESCAPE_REPLACE_REGEXP, pdecode) + var layer = new Layer(path, { + sensitive: this.caseSensitive, + strict: false, + end: false + }, fn); - 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') + layer.route = undefined; + + this.stack.push(layer); } - return value -} + return this; +}; /** - * Get ISO-8859-1 version of string. + * Create a new Route for the given path. * - * @param {string} val - * @return {string} - * @private - */ - -function getlatin1 (val) { - // simple Unicode -> ISO-8859-1 transformation - return String(val).replace(NON_LATIN1_REGEXP, '?') -} - -/** - * Parse Content-Disposition header string. + * 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} string - * @return {object} + * @param {String} path + * @return {Route} * @public */ -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') - } - - // normalize type - var index = match[0].length - var type = match[1].toLowerCase() +proto.route = function route(path) { + var route = new Route(path); - var key - var names = [] - var params = {} - var value + var layer = new Layer(path, { + sensitive: this.caseSensitive, + strict: this.strict, + end: true + }, route.dispatch.bind(route)); - // calculate index to start at - index = PARAM_REGEXP.lastIndex = match[0].substr(-1) === ';' - ? index - 1 - : index + layer.route = route; - // match parameters - while ((match = PARAM_REGEXP.exec(string))) { - if (match.index !== index) { - throw new TypeError('invalid parameter format') - } + this.stack.push(layer); + return route; +}; - index += match[0].length - key = match[1].toLowerCase() - value = match[2] +// 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; + }; +}); - if (names.indexOf(key) !== -1) { - throw new TypeError('invalid duplicate parameter') +// 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); } + } +} - names.push(key) - - if (key.indexOf('*') + 1 === key.length) { - // decode extended value - key = key.slice(0, -1) - value = decodefield(value) +// get pathname of request +function getPathname(req) { + try { + return parseUrl(req).pathname; + } catch (err) { + return undefined; + } +} - // overwrite existing value - params[key] = value - continue - } +// Get get protocol + host for a URL +function getProtohost(url) { + if (typeof url !== 'string' || url.length === 0 || url[0] === '/') { + return undefined + } - if (typeof params[key] === 'string') { - continue - } + var searchIndex = url.indexOf('?') + var pathLength = searchIndex !== -1 + ? searchIndex + : url.length + var fqdnIndex = url.substr(0, pathLength).indexOf('://') - if (value[0] === '"') { - // remove quotes and escapes - value = value - .substr(1, value.length - 2) - .replace(QESC_REGEXP, '$1') - } + return fqdnIndex !== -1 + ? url.substr(0, url.indexOf('/', 3 + fqdnIndex)) + : undefined +} - params[key] = value - } +// get type for error message +function gettype(obj) { + var type = typeof obj; - if (index !== -1 && index !== string.length) { - throw new TypeError('invalid parameter format') + if (type !== 'object') { + return type; } - return new ContentDisposition(type, params) + // inspect [[Class]] for objects + return toString.call(obj) + .replace(objectRegExp, '$1'); } /** - * Percent decode a single character. + * Match path to a layer. * - * @param {string} str - * @param {string} hex - * @return {string} + * @param {Layer} layer + * @param {string} path * @private */ -function pdecode (str, hex) { - return String.fromCharCode(parseInt(hex, 16)) +function matchLayer(layer, path) { + try { + return layer.match(path); + } catch (err) { + return err; + } } -/** - * Percent encode a single character. - * - * @param {string} char - * @return {string} - * @private - */ +// merge params with parent params +function mergeParams(params, parent) { + if (typeof parent !== 'object' || !parent) { + return params; + } -function pencode (char) { - return '%' + String(char) - .charCodeAt(0) - .toString(16) - .toUpperCase() -} + // make copy of parent for base + var obj = mixin({}, parent); -/** - * Quote a string for HTTP. - * - * @param {string} val - * @return {string} - * @private - */ + // simple non-numeric merging + if (!(0 in params) || !(0 in parent)) { + return mixin(obj, params); + } -function qstring (val) { - var str = String(val) + var i = 0; + var o = 0; - return '"' + str.replace(QUOTE_REGEXP, '\\$1') + '"' + // determine numeric gaps + while (i in params) { + i++; + } + + while (o in parent) { + o++; + } + + // 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]; + } + } + + return mixin(obj, params); } -/** - * Encode a Unicode string for HTTP (RFC 5987). - * - * @param {string} val - * @return {string} - * @private - */ +// restore obj props after function +function restore(fn, obj) { + var props = new Array(arguments.length - 2); + var vals = new Array(arguments.length - 2); -function ustring (val) { - var str = String(val) + for (var i = 0; i < props.length; i++) { + props[i] = arguments[i + 2]; + vals[i] = obj[props[i]]; + } - // percent encode as UTF-8 - var encoded = encodeURIComponent(str) - .replace(ENCODE_URL_ATTR_CHAR_REGEXP, pencode) + return function () { + // restore vals + for (var i = 0; i < props.length; i++) { + obj[props[i]] = vals[i]; + } - return 'UTF-8\'\'' + encoded + return fn.apply(this, arguments); + }; } -/** - * Class for parsed Content-Disposition header for v8 optimization - * - * @public - * @param {string} type - * @param {object} parameters - * @constructor - */ +// 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 ContentDisposition (type, parameters) { - this.type = type - this.parameters = parameters +// 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]; + } + + fn.apply(this, args); + }; } /***/ }), -/***/ 99915: -/***/ ((__unused_webpack_module, exports) => { +/***/ 25624: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /*! - * content-type - * Copyright(c) 2015 Douglas Christopher Wilson + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson * MIT Licensed */ /** - * 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. + * @private */ -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 +var pathRegexp = __nccwpck_require__(37819); +var debug = __nccwpck_require__(52529)('express:router:layer'); /** - * RegExp to match chars that must be quoted-pair in RFC 7230 sec 3.2.6 + * Module variables. + * @private */ -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-]+$/ +var hasOwnProperty = Object.prototype.hasOwnProperty; /** * Module exports. * @public */ -exports.format = format -exports.parse = parse - -/** - * Format object to media type. - * - * @param {object} obj - * @return {string} - * @public - */ - -function format (obj) { - if (!obj || typeof obj !== 'object') { - throw new TypeError('argument obj is required') - } - - var parameters = obj.parameters - var type = obj.type +module.exports = Layer; - if (!type || !TYPE_REGEXP.test(type)) { - throw new TypeError('invalid type') +function Layer(path, options, fn) { + if (!(this instanceof Layer)) { + return new Layer(path, options, fn); } - 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') - } + debug('new %o', path) + var opts = options || {}; - string += '; ' + param + '=' + qstring(parameters[param]) - } - } + this.handle = fn; + this.name = fn.name || ''; + this.params = undefined; + this.path = undefined; + this.regexp = pathRegexp(path, this.keys = [], opts); - return string + // set fast path flags + this.regexp.fast_star = path === '*' + this.regexp.fast_slash = path === '/' && opts.end === false } /** - * Parse media type to object. + * Handle the error for the layer. * - * @param {string|object} string - * @return {Object} - * @public + * @param {Error} error + * @param {Request} req + * @param {Response} res + * @param {function} next + * @api private */ -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() +Layer.prototype.handle_error = function handle_error(error, req, res, next) { + var fn = this.handle; - if (!TYPE_REGEXP.test(type)) { - throw new TypeError('invalid media type') + if (fn.length !== 4) { + // not a standard error handler + return next(error); } - 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 - } - - if (index !== header.length) { - throw new TypeError('invalid parameter format') - } + try { + fn(error, req, res, next); + } catch (err) { + next(err); } - - return obj -} +}; /** - * Get content-type from req/res objects. + * Handle the request for the layer. * - * @param {object} - * @return {Object} - * @private + * @param {Request} req + * @param {Response} res + * @param {function} next + * @api private */ -function getcontenttype (obj) { - var header +Layer.prototype.handle_request = function handle(req, res, next) { + var fn = this.handle; - 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 (fn.length > 3) { + // not a standard request handler + return next(); } - if (typeof header !== 'string') { - throw new TypeError('content-type header is missing from object') + try { + fn(req, res, next); + } catch (err) { + next(err); } - - return header -} +}; /** - * Quote a string if necessary. + * Check if this route matches `path`, if so + * populate `.params`. * - * @param {string} val - * @return {string} - * @private + * @param {String} path + * @return {Boolean} + * @api private */ -function qstring (val) { - var str = String(val) - - // 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') - } +Layer.prototype.match = function match(path) { + var match - return '"' + str.replace(QUOTE_REGEXP, '\\$1') + '"' -} + if (path != null) { + // fast path non-ending match for / (any path matches) + if (this.regexp.fast_slash) { + this.params = {} + this.path = '' + return true + } -/** - * Class to represent a content type. - * @private - */ -function ContentType (type) { - this.parameters = Object.create(null) - this.type = type -} + // fast path for * (everything matched in a param) + if (this.regexp.fast_star) { + this.params = {'0': decode_param(path)} + this.path = path + return true + } + // match the path + match = this.regexp.exec(path) + } -/***/ }), + if (!match) { + this.params = undefined; + this.path = undefined; + return false; + } -/***/ 61579: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + // store values + this.params = {}; + this.path = match[0] -/** - * Module dependencies. - */ + var keys = this.keys; + var params = this.params; -var crypto = __nccwpck_require__(6113); + for (var i = 1; i < match.length; i++) { + var key = keys[i - 1]; + var prop = key.name; + var val = decode_param(match[i]) -/** - * Sign the given `val` with `secret`. - * - * @param {String} val - * @param {String} secret - * @return {String} - * @api private - */ + if (val !== undefined || !(hasOwnProperty.call(params, prop))) { + params[prop] = val; + } + } -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(/\=+$/, ''); + return true; }; /** - * Unsign and decode the given `val` with `secret`, - * returning `false` if the signature is invalid. + * Decode param value. * - * @param {String} val - * @param {String} secret - * @return {String|Boolean} - * @api private + * @param {string} val + * @return {string} + * @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 decode_param(val) { + if (typeof val !== 'string' || val.length === 0) { + return val; + } -/** - * Private - */ + try { + return decodeURIComponent(val); + } catch (err) { + if (err instanceof URIError) { + err.message = 'Failed to decode param \'' + val + '\''; + err.status = err.statusCode = 400; + } -function sha1(str){ - return crypto.createHash('sha1').update(str).digest('hex'); + throw err; + } } /***/ }), -/***/ 93658: -/***/ ((__unused_webpack_module, exports) => { +/***/ 23699: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /*! - * cookie - * Copyright(c) 2012-2014 Roman Shtylman - * Copyright(c) 2015 Douglas Christopher Wilson + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson * MIT Licensed */ /** - * Module exports. - * @public + * Module dependencies. + * @private */ -exports.parse = parse; -exports.serialize = serialize; +var debug = __nccwpck_require__(52529)('express:router:route'); +var flatten = __nccwpck_require__(62003); +var Layer = __nccwpck_require__(25624); +var methods = __nccwpck_require__(58752); /** * Module variables. * @private */ -var decode = decodeURIComponent; -var encode = encodeURIComponent; -var pairSplitRegExp = /; */; +var slice = Array.prototype.slice; +var toString = Object.prototype.toString; /** - * 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 + * Module exports. + * @public */ -var fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/; +module.exports = Route; /** - * Parse a cookie header. - * - * Parse the given cookie header string into an object - * The object has the various cookies as keys(names) => values + * Initialize `Route` with the given `path`, * - * @param {string} str - * @param {object} [options] - * @return {object} + * @param {String} path * @public */ -function parse(str, options) { - if (typeof str !== 'string') { - throw new TypeError('argument str must be a string'); - } +function Route(path) { + this.path = path; + this.stack = []; - var obj = {} - var opt = options || {}; - var pairs = str.split(pairSplitRegExp); - var dec = opt.decode || decode; + debug('new %o', path) - for (var i = 0; i < pairs.length; i++) { - var pair = pairs[i]; - var eq_idx = pair.indexOf('='); + // route handlers for various http methods + this.methods = {}; +} - // skip things that don't look like key=value - if (eq_idx < 0) { - continue; - } +/** + * Determine if the route handles a given method. + * @private + */ - var key = pair.substr(0, eq_idx).trim() - var val = pair.substr(++eq_idx, pair.length).trim(); +Route.prototype._handles_method = function _handles_method(method) { + if (this.methods._all) { + return true; + } - // quoted values - if ('"' == val[0]) { - val = val.slice(1, -1); - } + var name = method.toLowerCase(); - // only assign once - if (undefined == obj[key]) { - obj[key] = tryDecode(val, dec); - } + if (name === 'head' && !this.methods['head']) { + name = 'get'; } - return obj; -} + return Boolean(this.methods[name]); +}; /** - * 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 + * @return {Array} supported HTTP methods + * @private */ -function serialize(name, val, options) { - var opt = options || {}; - var enc = opt.encode || encode; +Route.prototype._options = function _options() { + var methods = Object.keys(this.methods); - if (typeof enc !== 'function') { - throw new TypeError('option encode is invalid'); + // append automatic head + if (this.methods.get && !this.methods.head) { + methods.push('head'); } - if (!fieldContentRegExp.test(name)) { - throw new TypeError('argument name is invalid'); + for (var i = 0; i < methods.length; i++) { + // make upper case + methods[i] = methods[i].toUpperCase(); } - var value = enc(val); - - if (value && !fieldContentRegExp.test(value)) { - throw new TypeError('argument val is invalid'); - } + return methods; +}; - var str = name + '=' + value; +/** + * dispatch req, res into this route + * @private + */ - if (null != opt.maxAge) { - var maxAge = opt.maxAge - 0; - if (isNaN(maxAge)) throw new Error('maxAge should be a Number'); - str += '; Max-Age=' + Math.floor(maxAge); +Route.prototype.dispatch = function dispatch(req, res, done) { + var idx = 0; + var stack = this.stack; + if (stack.length === 0) { + return done(); } - if (opt.domain) { - if (!fieldContentRegExp.test(opt.domain)) { - throw new TypeError('option domain is invalid'); - } - - str += '; Domain=' + opt.domain; + var method = req.method.toLowerCase(); + if (method === 'head' && !this.methods['head']) { + method = 'get'; } - if (opt.path) { - if (!fieldContentRegExp.test(opt.path)) { - throw new TypeError('option path is invalid'); - } + req.route = this; - str += '; Path=' + opt.path; - } + next(); - if (opt.expires) { - if (typeof opt.expires.toUTCString !== 'function') { - throw new TypeError('option expires is invalid'); + function next(err) { + // signal to exit route + if (err && err === 'route') { + return done(); } - str += '; Expires=' + opt.expires.toUTCString(); - } - - if (opt.httpOnly) { - str += '; HttpOnly'; - } + // signal to exit router + if (err && err === 'router') { + return done(err) + } - if (opt.secure) { - str += '; Secure'; - } + var layer = stack[idx++]; + if (!layer) { + return done(err); + } - if (opt.sameSite) { - var sameSite = typeof opt.sameSite === 'string' - ? opt.sameSite.toLowerCase() : opt.sameSite; + if (layer.method && layer.method !== method) { + return next(err); + } - 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'); + if (err) { + layer.handle_error(err, req, res, next); + } else { + layer.handle_request(req, res, next); } } - - return str; -} +}; /** - * Try decoding a string using a decoding function. + * Add a handler for all HTTP verbs to this route. * - * @param {string} str - * @param {function} decode - * @private - */ - -function tryDecode(str, decode) { - try { - return decode(str); - } catch (e) { - return str; - } -} - - -/***/ }), - -/***/ 51512: -/***/ (function(module) { - -/* - * Date Format 1.2.3 - * (c) 2007-2009 Steven Levithan - * MIT license + * Behaves just like middleware and can respond or call `next` + * to continue processing. * - * Includes enhancements by Scott Trenda - * and Kris Kowal + * You can use multiple `.all` call to add multiple handlers. * - * Accepts a date, a mask, or a date and a mask. - * Returns a formatted version of the given date. - * The date defaults to the current date/time. - * The mask defaults to dateFormat.masks.default. - */ - -(function(global) { - 'use strict'; - - var dateFormat = (function() { - var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZWN]|"[^"]*"|'[^']*'/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; - - // Regexes and supporting functions are cached through closure - return function (date, mask, utc, gmt) { - - // You can't provide utc if you skip other args (use the 'UTC:' mask prefix) - if (arguments.length === 1 && kindOf(date) === 'string' && !/\d/.test(date)) { - mask = date; - date = undefined; - } - - date = 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']); - - // Allow setting the utc/gmt argument via the mask - var maskSlice = mask.slice(0, 4); - if (maskSlice === 'UTC:' || maskSlice === 'GMT:') { - mask = mask.slice(4); - utc = true; - if (maskSlice === 'GMT:') { - gmt = true; - } - } - - var _ = utc ? 'getUTC' : 'get'; - var d = date[_ + 'Date'](); - var D = date[_ + 'Day'](); - var m = date[_ + 'Month'](); - var y = date[_ + 'FullYear'](); - var H = date[_ + 'Hours'](); - var M = date[_ + 'Minutes'](); - var s = date[_ + 'Seconds'](); - var L = date[_ + 'Milliseconds'](); - var o = utc ? 0 : date.getTimezoneOffset(); - var W = getWeek(date); - var N = getDayOfWeek(date); - var flags = { - d: d, - dd: pad(d), - ddd: dateFormat.i18n.dayNames[D], - dddd: dateFormat.i18n.dayNames[D + 7], - m: m + 1, - mm: pad(m + 1), - mmm: dateFormat.i18n.monthNames[m], - mmmm: dateFormat.i18n.monthNames[m + 12], - yy: String(y).slice(2), - yyyy: y, - h: H % 12 || 12, - hh: pad(H % 12 || 12), - H: H, - HH: pad(H), - M: M, - MM: pad(M), - s: s, - ss: pad(s), - l: pad(L, 3), - L: pad(Math.round(L / 10)), - t: H < 12 ? dateFormat.i18n.timeNames[0] : dateFormat.i18n.timeNames[1], - tt: H < 12 ? dateFormat.i18n.timeNames[2] : dateFormat.i18n.timeNames[3], - T: H < 12 ? dateFormat.i18n.timeNames[4] : dateFormat.i18n.timeNames[5], - TT: H < 12 ? dateFormat.i18n.timeNames[6] : dateFormat.i18n.timeNames[7], - Z: gmt ? 'GMT' : utc ? 'UTC' : (String(date).match(timezone) || ['']).pop().replace(timezoneClip, ''), - o: (o > 0 ? '-' : '+') + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4), - S: ['th', 'st', 'nd', 'rd'][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10], - W: W, - N: 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', - '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' - }; - - // Internationalization strings - 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' - ] - }; - -function pad(val, len) { - val = String(val); - len = len || 2; - while (val.length < len) { - val = '0' + val; - } - return val; -} - -/** - * Get the ISO 8601 week number - * Based on comments from - * http://techblog.procurios.nl/k/n618/news/view/33796/14863/Calculate-ISO-8601-week-and-year-in-javascript.html + * function check_something(req, res, next){ + * next(); + * }; * - * @param {Object} `date` - * @return {Number} - */ -function getWeek(date) { - // Remove time components of date - var targetThursday = new Date(date.getFullYear(), date.getMonth(), date.getDate()); - - // Change date to Thursday same week - targetThursday.setDate(targetThursday.getDate() - ((targetThursday.getDay() + 6) % 7) + 3); - - // Take January 4th as it is always in week 1 (see ISO 8601) - var firstThursday = new Date(targetThursday.getFullYear(), 0, 4); - - // Change date to Thursday same week - firstThursday.setDate(firstThursday.getDate() - ((firstThursday.getDay() + 6) % 7) + 3); - - // Check if daylight-saving-time-switch occurred and correct for it - var ds = targetThursday.getTimezoneOffset() - firstThursday.getTimezoneOffset(); - targetThursday.setHours(targetThursday.getHours() - ds); - - // Number of weeks between target Thursday and first Thursday - var weekDiff = (targetThursday - firstThursday) / (86400000*7); - return 1 + Math.floor(weekDiff); -} - -/** - * Get ISO-8601 numeric representation of the day of the week - * 1 (for Monday) through 7 (for Sunday) - * - * @param {Object} `date` - * @return {Number} - */ -function getDayOfWeek(date) { - var dow = date.getDay(); - if(dow === 0) { - dow = 7; - } - return dow; -} - -/** - * kind-of shortcut - * @param {*} val - * @return {String} + * 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 kindOf(val) { - if (val === null) { - return 'null'; - } - if (val === undefined) { - return 'undefined'; - } +Route.prototype.all = function all() { + var handles = flatten(slice.call(arguments)); - if (typeof val !== 'object') { - return typeof val; - } + for (var i = 0; i < handles.length; i++) { + var handle = handles[i]; - if (Array.isArray(val)) { - return 'array'; + 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 {}.toString.call(val) - .slice(8, -1).toLowerCase(); + return this; }; +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 define === 'function' && define.amd) { - define(function () { - return dateFormat; - }); - } else if (true) { - module.exports = dateFormat; - } else {} -})(this); + 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); + } + + return this; + }; +}); /***/ }), -/***/ 84697: -/***/ ((module) => { +/***/ 53561: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -/** - * Helpers. +"use strict"; +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * 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 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 dependencies. + * @api 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' && 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) - ); -}; +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); /** - * Parse the given `str` and return milliseconds. + * Return strong ETag for `body`. * - * @param {String} str - * @return {Number} + * @param {String|Buffer} body + * @param {String} [encoding] + * @return {String} * @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; - } -} +exports.etag = createETagGenerator({ weak: false }) /** - * Short format for `ms`. + * Return weak ETag for `body`. * - * @param {Number} ms + * @param {String|Buffer} body + * @param {String} [encoding] * @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'; -} +exports.wetag = createETagGenerator({ weak: true }) /** - * Long format for `ms`. + * Check if `path` looks absolute. * - * @param {Number} ms - * @return {String} + * @param {String} path + * @return {Boolean} * @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'; -} +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 +}; /** - * Pluralization helper. + * Flatten the given `arr`. + * + * @param {Array} arr + * @return {Array} + * @api private */ -function plural(ms, msAbs, n, name) { - var isPlural = msAbs >= n * 1.5; - return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); -} - - -/***/ }), +exports.flatten = deprecate.function(flatten, + 'utils.flatten: use array-flatten npm module instead'); -/***/ 28222: -/***/ ((module, exports, __nccwpck_require__) => { +/** + * Normalize the given `type`, for example "html" becomes "text/html". + * + * @param {String} type + * @return {Object} + * @api private + */ -/* eslint-env browser */ +exports.normalizeType = function(type){ + return ~type.indexOf('/') + ? acceptParams(type) + : { value: mime.lookup(type), params: {} }; +}; /** - * This is the web browser implementation of `debug()`. + * Normalize `types`, for example "html" becomes "text/html". + * + * @param {Array} types + * @return {Array} + * @api private */ -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.storage = localstorage(); -exports.destroy = (() => { - let warned = false; +exports.normalizeTypes = function(types){ + var ret = []; - 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`.'); - } - }; -})(); + for (var i = 0; i < types.length; ++i) { + ret.push(exports.normalizeType(types[i])); + } + + return ret; +}; /** - * Colors. + * 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.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' -]; +exports.contentDisposition = deprecate.function(contentDisposition, + 'utils.contentDisposition: use content-disposition npm module instead'); /** - * Currently only WebKit-based Web Inspectors, Firefox >= v31, - * and the Firebug extension (any Firefox version) are known - * to support "%c" CSS customizations. + * Parse accept params `str` returning an + * object with `.value`, `.quality` and `.params`. + * also includes `.originalIndex` for stable sorting * - * TODO: add a `localStorage` variable to explicitly enable/disable colors + * @param {String} str + * @return {Object} + * @api private */ -// 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; - } +function acceptParams(str, index) { + var parts = str.split(/ *; */); + var ret = { value: parts[0], quality: 1, params: {}, originalIndex: index }; - // Internet Explorer and Edge do not support colors. - if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { - return false; - } + 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]; + } + } - // 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+)/)); + return ret; } /** - * Colorize log arguments if enabled. + * Compile "etag" value to function. * - * @api public + * @param {Boolean|String|Function} val + * @return {Function} + * @api private */ -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; - } +exports.compileETag = function(val) { + var fn; - const c = 'color: ' + this.color; - args.splice(1, 0, c, 'color: inherit'); + if (typeof val === 'function') { + return val; + } - // 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; - } - }); + switch (val) { + case true: + fn = exports.wetag; + break; + case false: + break; + case 'strong': + fn = exports.etag; + break; + case 'weak': + fn = exports.wetag; + break; + default: + throw new TypeError('unknown value for etag function: ' + val); + } - args.splice(lastC, 0, c); + return fn; } /** - * 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`. + * Compile "query parser" value to function. * - * @api public + * @param {String|Function} val + * @return {Function} + * @api private */ -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? - } +exports.compileQueryParser = function compileQueryParser(val) { + var fn; + + if (typeof val === 'function') { + return val; + } + + switch (val) { + case true: + fn = querystring.parse; + break; + case false: + fn = newObject; + break; + case 'extended': + fn = parseExtendedQueryString; + break; + case 'simple': + fn = querystring.parse; + break; + default: + throw new TypeError('unknown value for query parser function: ' + val); + } + + return fn; } /** - * Load `namespaces`. + * Compile "proxy trust" value to function. * - * @return {String} returns the previously persisted debug modes + * @param {Boolean|String|Number|Array|Function} val + * @return {Function} * @api private */ -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; - } +exports.compileTrust = function(val) { + if (typeof val === 'function') return val; - return r; + if (val === true) { + // Support plain true/false + return function(){ return true }; + } + + 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 || []); } /** - * Localstorage attempts to return the localstorage. - * - * This is necessary because safari throws - * when a user disables cookies/localstorage - * and you attempt to access it. + * Set the charset in a given Content-Type string. * - * @return {LocalStorage} + * @param {String} type + * @param {String} charset + * @return {String} * @api 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? - } -} - -module.exports = __nccwpck_require__(46243)(exports); +exports.setCharset = function setCharset(type, charset) { + if (!type || !charset) { + return type; + } -const {formatters} = module.exports; + // parse type + var parsed = contentType.parse(type); -/** - * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. - */ + // set charset + parsed.parameters.charset = charset; -formatters.j = function (v) { - try { - return JSON.stringify(v); - } catch (error) { - return '[UnexpectedJSONParseError]: ' + error.message; - } + // format type + return contentType.format(parsed); }; +/** + * Create an ETag generator function, generating ETags with + * the given options. + * + * @param {object} options + * @return {function} + * @private + */ -/***/ }), - -/***/ 46243: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +function createETagGenerator (options) { + return function generateETag (body, encoding) { + var buf = !Buffer.isBuffer(body) + ? Buffer.from(body, encoding) + : body + return etag(buf, options) + } +} /** - * This is the common logic for both the Node.js and web browser - * implementations of `debug()`. + * Parse an extended query string with qs. + * + * @return {Object} + * @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__(84697); - createDebug.destroy = destroy; - - Object.keys(env).forEach(key => { - createDebug[key] = env[key]; - }); - - /** - * The currently active debug mode names, and names to skip. - */ +function parseExtendedQueryString(str) { + return qs.parse(str, { + allowPrototypes: true + }); +} - createDebug.names = []; - createDebug.skips = []; +/** + * Return new empty object. + * + * @return {Object} + * @api private + */ - /** - * 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 = {}; +function newObject() { + return {}; +} - /** - * 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; - for (let i = 0; i < namespace.length; i++) { - hash = ((hash << 5) - hash) + namespace.charCodeAt(i); - hash |= 0; // Convert to 32bit integer - } +/***/ }), - return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; - } - createDebug.selectColor = selectColor; +/***/ 99209: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /** - * 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; +"use strict"; +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ - function debug(...args) { - // Disabled? - if (!debug.enabled) { - return; - } - const self = debug; - // Set `diff` timestamp - const curr = Number(new Date()); - const ms = curr - (prevTime || curr); - self.diff = ms; - self.prev = prevTime; - self.curr = curr; - prevTime = curr; +/** + * Module dependencies. + * @private + */ - args[0] = createDebug.coerce(args[0]); +var debug = __nccwpck_require__(52529)('express:view'); +var path = __nccwpck_require__(71017); +var fs = __nccwpck_require__(57147); - if (typeof args[0] !== 'string') { - // Anything else let's inspect with %O - args.unshift('%O'); - } +/** + * Module variables. + * @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); +var dirname = path.dirname; +var basename = path.basename; +var extname = path.extname; +var join = path.join; +var resolve = path.resolve; - // Now we need to remove `args[index]` since it's inlined in the `format` - args.splice(index, 1); - index--; - } - return match; - }); +/** + * Module exports. + * @public + */ - // Apply env-specific formatting (colors, etc.) - createDebug.formatArgs.call(self, args); +module.exports = View; - const logFn = self.log || createDebug.log; - logFn.apply(self, args); - } +/** + * 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 + */ - 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. +function View(name, options) { + var opts = options || {}; - 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); - } + this.defaultEngine = opts.defaultEngine; + this.ext = extname(name); + this.name = name; + this.root = opts.root; - return enabledCache; - }, - set: v => { - enableOverride = v; - } - }); + if (!this.ext && !this.defaultEngine) { + throw new Error('No default engine was specified and no extension was provided.'); + } - // Env-specific initialization logic for debug instances - if (typeof createDebug.init === 'function') { - createDebug.init(debug); - } + var fileName = name; - return debug; - } + if (!this.ext) { + // get extension from default engine name + this.ext = this.defaultEngine[0] !== '.' + ? '.' + this.defaultEngine + : this.defaultEngine; - function extend(namespace, delimiter) { - const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); - newDebug.log = this.log; - return newDebug; - } + fileName += this.ext; + } - /** - * 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 (!opts.engines[this.ext]) { + // load engine + var mod = this.ext.substr(1) + debug('require "%s"', mod) - createDebug.names = []; - createDebug.skips = []; + // default engine export + var fn = require(mod).__express - let i; - const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); - const len = split.length; + if (typeof fn !== 'function') { + throw new Error('Module "' + mod + '" does not provide a view engine.') + } - for (i = 0; i < len; i++) { - if (!split[i]) { - // ignore empty strings - continue; - } + opts.engines[this.ext] = fn + } - namespaces = split[i].replace(/\*/g, '.*?'); + // store loaded engine + this.engine = opts.engines[this.ext]; - if (namespaces[0] === '-') { - createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); - } else { - createDebug.names.push(new RegExp('^' + namespaces + '$')); - } - } - } + // lookup path + this.path = this.lookup(fileName); +} - /** - * 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; - } +/** + * Lookup view by the given `name` + * + * @param {string} name + * @private + */ - /** - * 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; - } +View.prototype.lookup = function lookup(name) { + var path; + var roots = [].concat(this.root); - let i; - let len; + debug('lookup "%s"', name); - for (i = 0, len = createDebug.skips.length; i < len; i++) { - if (createDebug.skips[i].test(name)) { - return false; - } - } + for (var i = 0; i < roots.length && !path; i++) { + var root = roots[i]; - for (i = 0, len = createDebug.names.length; i < len; i++) { - if (createDebug.names[i].test(name)) { - return true; - } - } + // resolve the path + var loc = resolve(root, name); + var dir = dirname(loc); + var file = basename(loc); - return false; - } + // resolve the file + path = this.resolve(dir, file); + } - /** - * 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(/\.\*\?$/, '*'); - } + return path; +}; - /** - * Coerce `val`. - * - * @param {Mixed} val - * @return {Mixed} - * @api private - */ - function coerce(val) { - if (val instanceof Error) { - return val.stack || val.message; - } - return val; - } +/** + * Render with the given options. + * + * @param {object} options + * @param {function} callback + * @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`.'); - } +View.prototype.render = function render(options, callback) { + debug('render "%s"', this.path); + this.engine(this.path, options, callback); +}; - createDebug.enable(createDebug.load()); +/** + * Resolve the file within the given directory. + * + * @param {string} dir + * @param {string} file + * @private + */ - return createDebug; -} +View.prototype.resolve = function resolve(dir, file) { + var ext = this.ext; -module.exports = setup; + // . + 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); -/***/ 38237: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (stat && stat.isFile()) { + return path; + } +}; /** - * Detect Electron renderer / nwjs process, which is node, but we should - * treat as a browser. + * Return a stat, maybe. + * + * @param {string} path + * @return {fs.Stats} + * @private */ -if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { - module.exports = __nccwpck_require__(28222); -} else { - module.exports = __nccwpck_require__(35332); +function tryStat(path) { + debug('stat "%s"', path); + + try { + return fs.statSync(path); + } catch (e) { + return undefined; + } } /***/ }), -/***/ 35332: +/***/ 36654: /***/ ((module, exports, __nccwpck_require__) => { /** - * Module dependencies. - */ - -const tty = __nccwpck_require__(76224); -const util = __nccwpck_require__(73837); - -/** - * This is the Node.js implementation of `debug()`. + * This is the web browser implementation of `debug()`. + * + * Expose `debug()` as the module. */ -exports.init = init; +exports = module.exports = __nccwpck_require__(86991); 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`.' -); +exports.storage = 'undefined' != typeof chrome + && 'undefined' != typeof chrome.storage + ? chrome.storage.local + : localstorage(); /** * Colors. */ -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); - - 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. -} +exports.colors = [ + 'lightseagreen', + 'forestgreen', + 'goldenrod', + 'dodgerblue', + 'darkorchid', + 'crimson' +]; /** - * Build up the default `inspectOpts` object from the environment variables. + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. * - * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + * TODO: add a `localStorage` variable to explicitly enable/disable colors */ -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); - } +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; + } - obj[prop] = val; - return obj; -}, {}); + // 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+)/)); +} /** - * Is stdout a TTY? Colored output is enabled when `true`. + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. */ -function useColors() { - return 'colors' in exports.inspectOpts ? - Boolean(exports.inspectOpts.colors) : - tty.isatty(process.stderr.fd); -} +exports.formatters.j = function(v) { + try { + return JSON.stringify(v); + } catch (err) { + return '[UnexpectedJSONParseError]: ' + err.message; + } +}; + /** - * Adds ANSI color escape codes if enabled. + * Colorize log arguments if enabled. * * @api public */ function formatArgs(args) { - const {namespace: name, useColors} = this; + var useColors = this.useColors; - 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] = (useColors ? '%c' : '') + + this.namespace + + (useColors ? ' %c' : ' ') + + args[0] + + (useColors ? '%c ' : ' ') + + '+' + exports.humanize(this.diff); - 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]; - } -} + if (!useColors) return; -function getDate() { - if (exports.inspectOpts.hideDate) { - return ''; - } - return new Date().toISOString() + ' '; + 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); } /** - * Invokes `util.format()` with the specified arguments and writes to stderr. + * Invokes `console.log()` when available. + * No-op when `console.log` is not a "function". + * + * @api public */ -function log(...args) { - return process.stderr.write(util.format(...args) + '\n'); +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); } /** @@ -44693,14 +45208,15 @@ function log(...args) { * @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; - } + try { + if (null == namespaces) { + exports.storage.removeItem('debug'); + } else { + exports.storage.debug = namespaces; + } + } catch(e) {} } /** @@ -44711,1430 +45227,2451 @@ function save(namespaces) { */ function load() { - return process.env.DEBUG; -} - -/** - * Init logic for `debug` instances. - * - * Create a new `inspectOpts` object in case `useColors` is set - * differently for a particular `debug` instance. - */ + var r; + try { + r = exports.storage.debug; + } catch(e) {} -function init(debug) { - debug.inspectOpts = {}; + // 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 keys = Object.keys(exports.inspectOpts); - for (let i = 0; i < keys.length; i++) { - debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; - } + return r; } -module.exports = __nccwpck_require__(46243)(exports); - -const {formatters} = module.exports; - /** - * Map %o to `util.inspect()`, all on a single line. + * Enable namespaces listed in `localStorage.debug` initially. */ -formatters.o = function (v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts) - .split('\n') - .map(str => str.trim()) - .join(' '); -}; +exports.enable(load()); /** - * Map %O to `util.inspect()`, allowing multiple lines if needed. + * 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 */ -formatters.O = function (v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts); -}; +function localstorage() { + try { + return window.localStorage; + } catch (e) {} +} /***/ }), -/***/ 56323: -/***/ ((module) => { +/***/ 86991: +/***/ ((module, exports, __nccwpck_require__) => { -"use strict"; +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + * + * Expose `debug()` as the module. + */ -var isMergeableObject = function isMergeableObject(value) { - return isNonNullObject(value) - && !isSpecial(value) -}; +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 isNonNullObject(value) { - return !!value && typeof value === 'object' -} +/** + * The currently active debug mode names, and names to skip. + */ -function isSpecial(value) { - var stringValue = Object.prototype.toString.call(value); +exports.names = []; +exports.skips = []; - return stringValue === '[object RegExp]' - || stringValue === '[object Date]' - || isReactElement(value) -} +/** + * 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". + */ -// 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; +exports.formatters = {}; -function isReactElement(value) { - return value.$$typeof === REACT_ELEMENT_TYPE -} +/** + * Previous log timestamp. + */ -function emptyTarget(val) { - return Array.isArray(val) ? [] : {} -} +var prevTime; -function cloneUnlessOtherwiseSpecified(value, options) { - return (options.clone !== false && options.isMergeableObject(value)) - ? deepmerge(emptyTarget(value), value, options) - : value -} +/** + * Select a color. + * @param {String} namespace + * @return {Number} + * @api private + */ -function defaultArrayMerge(target, source, options) { - return target.concat(source).map(function(element) { - return cloneUnlessOtherwiseSpecified(element, options) - }) -} +function selectColor(namespace) { + var hash = 0, i; -function getMergeFunction(key, options) { - if (!options.customMerge) { - return deepmerge - } - var customMerge = options.customMerge(key); - return typeof customMerge === 'function' ? customMerge : deepmerge -} + for (i in namespace) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } -function getEnumerableOwnPropertySymbols(target) { - return Object.getOwnPropertySymbols - ? Object.getOwnPropertySymbols(target).filter(function(symbol) { - return target.propertyIsEnumerable(symbol) - }) - : [] + return exports.colors[Math.abs(hash) % exports.colors.length]; } -function getKeys(target) { - return Object.keys(target).concat(getEnumerableOwnPropertySymbols(target)) -} +/** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ -function propertyIsOnObject(object, property) { - try { - return property in object - } catch(_) { - return false - } -} +function createDebug(namespace) { -// 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. -} + function debug() { + // disabled? + if (!debug.enabled) return; -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 - } + var self = debug; - 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 -} + // set `diff` timestamp + var curr = +new Date(); + var ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; -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; + // 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 sourceIsArray = Array.isArray(source); - var targetIsArray = Array.isArray(target); - var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray; + args[0] = exports.coerce(args[0]); - if (!sourceAndTargetTypesMatch) { - return cloneUnlessOtherwiseSpecified(source, options) - } else if (sourceIsArray) { - return options.arrayMerge(target, source, options) - } else { - return mergeObject(target, source, options) - } -} + 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; + }); -deepmerge.all = function deepmergeAll(array, options) { - if (!Array.isArray(array)) { - throw new Error('first argument should be an array') - } + // apply env-specific formatting (colors, etc.) + exports.formatArgs.call(self, args); - return array.reduce(function(prev, next) { - return deepmerge(prev, next, options) - }, {}) -}; + var logFn = debug.log || exports.log || console.log.bind(console); + logFn.apply(self, args); + } -var deepmerge_1 = deepmerge; + debug.namespace = namespace; + debug.enabled = exports.enabled(namespace); + debug.useColors = exports.useColors(); + debug.color = selectColor(namespace); -module.exports = deepmerge_1; + // env-specific initialization logic for debug instances + if ('function' === typeof exports.init) { + exports.init(debug); + } + return debug; +} -/***/ }), +/** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ -/***/ 42342: -/***/ ((module) => { +function enable(namespaces) { + exports.save(namespaces); -"use strict"; + exports.names = []; + exports.skips = []; + var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + var len = split.length; -/** - * Custom implementation of a double ended queue. - */ -function Denque(array) { - this._head = 0; - this._tail = 0; - this._capacityMask = 0x3; - this._list = new Array(4); - if (Array.isArray(array)) { - this._fromArray(array); + 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 + '$')); + } } } /** - * ------------- - * PUBLIC API - * ------------- + * Disable debug output. + * + * @api public */ +function disable() { + exports.enable(''); +} + /** - * 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 {*} + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public */ -Denque.prototype.peekAt = function peekAt(index) { - var i = index; - // expect a number or return undefined - if ((i !== (i | 0))) { - return void 0; + +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 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]; -}; + for (i = 0, len = exports.names.length; i < len; i++) { + if (exports.names[i].test(name)) { + return true; + } + } + return false; +} /** - * Alias for peakAt() - * @param i - * @returns {*} + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private */ -Denque.prototype.get = function get(i) { - return this.peekAt(i); -}; + +function coerce(val) { + if (val instanceof Error) return val.stack || val.message; + return val; +} + + +/***/ }), + +/***/ 52529: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { /** - * Returns the first item in the list without removing it. - * @returns {*} + * Detect Electron renderer process, which is node, but we should + * treat as a browser. */ -Denque.prototype.peek = function peek() { - if (this._head === this._tail) return undefined; - return this._list[this._head]; -}; + +if (typeof process !== 'undefined' && process.type === 'renderer') { + module.exports = __nccwpck_require__(36654); +} else { + module.exports = __nccwpck_require__(25696); +} + + +/***/ }), + +/***/ 25696: +/***/ ((module, exports, __nccwpck_require__) => { /** - * Alias for peek() - * @returns {*} + * Module dependencies. */ -Denque.prototype.peekFront = function peekFront() { - return this.peek(); -}; + +var tty = __nccwpck_require__(76224); +var util = __nccwpck_require__(73837); /** - * Returns the item that is at the back of the queue without removing it. - * Uses peekAt(-1) + * This is the Node.js implementation of `debug()`. + * + * Expose `debug()` as the module. */ -Denque.prototype.peekBack = function peekBack() { - return this.peekAt(-1); -}; + +exports = module.exports = __nccwpck_require__(86991); +exports.init = init; +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; /** - * Returns the current length of the queue - * @return {Number} + * Colors. */ -Object.defineProperty(Denque.prototype, 'length', { - get: function length() { - return this.size(); - } -}); + +exports.colors = [6, 2, 3, 4, 5, 1]; /** - * Return the number of items on the list, or 0 if empty. - * @returns {number} + * Build up the default `inspectOpts` object from the environment variables. + * + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js */ -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); -}; + +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; +}, {}); /** - * Add an item at the beginning of the list. - * @param item + * 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 */ -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._head < this._tail) return this._tail - this._head; - else return this._capacityMask + 1 - (this._head - this._tail); -}; + +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); /** - * Remove and return the first item on the list, - * Returns undefined if the list is empty. - * @returns {*} + * Is stdout a TTY? Colored output is enabled when `true`. */ -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 useColors() { + return 'colors' in exports.inspectOpts + ? Boolean(exports.inspectOpts.colors) + : tty.isatty(fd); +} /** - * Add an item to the bottom of the list. - * @param item + * Map %o to `util.inspect()`, all on a single line. */ -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._head < this._tail) return this._tail - this._head; - else return this._capacityMask + 1 - (this._head - this._tail); +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(' '); }; /** - * Remove and return the last item on the list. - * Returns undefined if the list is empty. - * @returns {*} + * Map %o to `util.inspect()`, allowing multiple lines if needed. */ -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; + +exports.formatters.O = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); }; /** - * Remove and return the item at the specified index from the list. - * Returns undefined if the list is empty. - * @param index - * @returns {*} + * Adds ANSI color escape codes if enabled. + * + * @api 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; + +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 { - 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; + args[0] = new Date().toUTCString() + + ' ' + name + ' ' + args[0]; } - 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} + * Invokes `util.format()` with the specified arguments and writes to `stream`. */ -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 (index < 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--; - } + +function log() { + return stream.write(util.format.apply(util, arguments) + '\n'); +} + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @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 { - 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--; - } + process.env.DEBUG = namespaces; } - 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. + * Load `namespaces`. * - * @param index - * @param count - * @param {...*} [elements] - * @returns {array} + * @return {String} returns the previously persisted debug modes + * @api private */ -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++]); + +function load() { + return process.env.DEBUG; +} + +/** + * 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. + */ + +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(); } - for (k = 0; k < leng; k++) { - this.push(temp[k]); + 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(); } - } - return removed; - } else { - return this.remove(i, count); + break; + + default: + // Probably an error on in uv_guess_handle() + throw new Error('Implement me. Unknown stream file type!'); } -}; -/** - * Soft clear - does not reset capacity. - */ -Denque.prototype.clear = function clear() { - this._head = 0; - this._tail = 0; -}; + // For supporting legacy API we put the FD here. + stream.fd = fd; + + stream._isStdio = true; + + return stream; +} /** - * Returns true or false whether the list is empty. - * @returns {boolean} + * Init logic for `debug` instances. + * + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. */ -Denque.prototype.isEmpty = function isEmpty() { - return this._head === this._tail; -}; + +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]]; + } +} /** - * Returns an array of all queue items. - * @returns {Array} + * Enable namespaces listed in `process.env.DEBUG` initially. */ -Denque.prototype.toArray = function toArray() { - return this._copyArray(false); -}; + +exports.enable(load()); + + +/***/ }), + +/***/ 27025: +/***/ ((module) => { /** - * ------------- - * INTERNALS - * ------------- + * Helpers. */ +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var y = d * 365.25; + /** - * Fills the queue with items from an array - * For use in the constructor - * @param array - * @private + * 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 */ -Denque.prototype._fromArray = function _fromArray(array) { - for (var i = 0; i < array.length; i++) this.push(array[i]); + +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 fullCopy - * @returns {Array} - * @private + * @param {String} str + * @return {Number} + * @api 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]); + +function parse(str) { + str = String(str); + if (str.length > 100) { + return; } - return newArray; -}; + 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; + } +} /** - * Grows the internal list array. - * @private + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api 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 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'; +} - // head is at 0 and array is now full, safe to extend - this._tail = this._list.length; +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ - this._list.length *= 2; - this._capacityMask = (this._capacityMask << 1) | 1; -}; +function fmtLong(ms) { + return plural(ms, d, 'day') || + plural(ms, h, 'hour') || + plural(ms, m, 'minute') || + plural(ms, s, 'second') || + ms + ' ms'; +} /** - * Shrinks the internal list array. - * @private + * Pluralization helper. */ -Denque.prototype._shrinkArray = function _shrinkArray() { - this._list.length >>>= 1; - this._capacityMask >>>= 1; -}; + +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'; +} -module.exports = Denque; +/***/ }), + +/***/ 24826: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"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 + + return redactor({ secret, wcLen, serialize, strict, isCensorFct, censorFctTakesPath }, state({ + secret, + censor, + compileRestore, + serialize, + groupRedact, + nestedRedact, + wildcards, + wcLen + })) +} + + +/***/ }), + +/***/ 54865: +/***/ ((module) => { + +"use strict"; + + +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] + } +} + +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 } +} + +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 } +} /***/ }), -/***/ 18883: +/***/ 17333: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/*! - * depd - * Copyright(c) 2014-2017 Douglas Christopher Wilson - * MIT Licensed - */ +"use strict"; -/** - * Module dependencies. - */ -var callSiteToString = (__nccwpck_require__(69829).callSiteToString) -var eventListenerCount = (__nccwpck_require__(69829).eventListenerCount) -var relative = (__nccwpck_require__(71017).relative) +const rx = __nccwpck_require__(9158) -/** - * Module exports. - */ +module.exports = redactor -module.exports = depd +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) -/** - * Get the path to base files on. - */ + if (serialize === false) { + redact.restore = (o) => state.restore(o) + } -var basePath = process.cwd() + return redact +} -/** - * Determine if namespace is contained in the string. - */ +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` -function containsNamespace (str, namespace) { - var vals = str.split(/[ ,]+/) - var ns = String(namespace).toLowerCase() + const circularDetection = ` + switch (true) { + ${hops.reverse().map((p) => ` + case o${delim}${p} === censor: + secret[${escPath}].circle = ${JSON.stringify(p)} + break + `).join('\n')} + } + ` - for (var i = 0; i < vals.length; i++) { - var val = vals[i] + const censorArgs = censorFctTakesPath + ? `val, ${JSON.stringify(arrPath)}` + : `val` - // namespace contained - if (val && (val === '*' || val.toLowerCase() === ns)) { - return true + 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}) + } } - } + ` : '' +} - return false +function resultTmpl (serialize) { + return serialize === false ? `return o` : ` + var s = this.serialize(o) + this.restore(o) + return s + ` } -/** - * Convert a data descriptor to accessor descriptor. - */ +function strictImpl (strict, serialize) { + return strict === true + ? `throw Error('fast-redact: primitives cannot be redacted')` + : serialize === false ? `return o` : `return this.serialize(o)` +} -function convertDataDescriptorToAccessor (obj, prop, message) { - var descriptor = Object.getOwnPropertyDescriptor(obj, prop) - var value = descriptor.value - descriptor.get = function getter () { return value } +/***/ }), - if (descriptor.writable) { - descriptor.set = function setter (val) { return (value = val) } - } +/***/ 98806: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - delete descriptor.value - delete descriptor.writable +"use strict"; - Object.defineProperty(obj, prop, descriptor) - return descriptor +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) + .filter((path) => secret[path].precensored === false) + 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) + } } /** - * Create arguments string to keep arity. + * 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('') +} -function createArgumentsString (arity) { - var str = '' - - for (var i = 0; i < arity; i++) { - str += ', arg' + i - } +function restoreTmpl (resetters, paths, hasWildcards) { + const dynamicReset = hasWildcards === true ? ` + const keys = Object.keys(secret) + const len = keys.length + for (var i = ${paths.length}; i < len; i++) { + const k = keys[i] + const o = secret[k] + if (o.flat === true) this.groupRestore(o) + else this.nestedRestore(o) + secret[k] = null + } + ` : '' - return str.substr(2) + return ` + const secret = this.secret + ${resetters} + ${dynamicReset} + return o + ` } -/** - * Create stack string from stack. - */ -function createStackString (stack) { - var str = this.name + ': ' + this.namespace +/***/ }), - if (this.message) { - str += ' deprecated ' + this.message - } +/***/ 9158: +/***/ ((module) => { - for (var i = 0; i < stack.length; i++) { - str += '\n at ' + callSiteToString(stack[i]) - } +"use strict"; - return str -} -/** - * Create deprecate for namespace in caller. - */ +module.exports = /[^.[\]]+|\[((?:.)*?)\]/g -function depd (namespace) { - if (!namespace) { - throw new TypeError('argument namespace is required') - } +/* +Regular expression explanation: - var stack = getStack() - var site = callSiteLocation(stack[1]) - var file = site[0] +Alt 1: /[^.[\]]+/ - Match one or more characters that are *not* a dot (.) + opening square bracket ([) or closing square bracket (]) - function deprecate (message) { - // call to self as log - log.call(deprecate, message) - } +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). +*/ - 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 +/***/ }), - return deprecate -} +/***/ 41012: +/***/ ((module) => { -/** - * Determine if namespace is ignored. - */ +"use strict"; -function isignored (namespace) { - /* istanbul ignore next: tested in a child processs */ - if (process.noDeprecation) { - // --no-deprecation support - return true - } - var str = process.env.NO_DEPRECATION || '' +module.exports = state - // namespace ignored - return containsNamespace(str, namespace) +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) } -/** - * Determine if namespace is traced. - */ -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 || '' +/***/ 74174: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // namespace traced - return containsNamespace(str, namespace) -} +"use strict"; -/** - * Display deprecation message. - */ -function log (message, site) { - var haslisteners = eventListenerCount(process, 'deprecation') !== 0 +const { createContext, runInContext } = __nccwpck_require__(26144) - // abort early if no destination - if (!haslisteners && this._ignored) { - return +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)) + } + }) } +} - 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] +/***/ }), + +/***/ 17676: +/***/ ((module) => { + +module.exports = stringify +stringify.default = stringify +stringify.stable = deterministicStringify +stringify.stableStringify = deterministicStringify + +var arr = [] +var replacerStack = [] + +// Regular stringify +function stringify (obj, replacer, spacer) { + decirc(obj, '', [], undefined) + var res + if (replacerStack.length === 0) { + res = JSON.stringify(obj, replacer, spacer) } else { - // get call site - i = 2 - depSite = callSiteLocation(stack[i]) - callSite = depSite + res = JSON.stringify(obj, replaceGetterValues(replacer), spacer) + } + 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 +} +function decirc (val, k, stack, parent) { + var i + if (typeof val === 'object' && val !== null) { + for (i = 0; i < stack.length; i++) { + if (stack[i] === val) { + var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k) + if (propertyDescriptor.get !== undefined) { + if (propertyDescriptor.configurable) { + Object.defineProperty(parent, k, { value: '[Circular]' }) + arr.push([parent, k, val, propertyDescriptor]) + } else { + replacerStack.push([val, k]) + } + } else { + parent[k] = '[Circular]' + arr.push([parent, k, val]) + } + 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, stack, val) + } + } else { + var keys = Object.keys(val) + for (i = 0; i < keys.length; i++) { + var key = keys[i] + decirc(val[key], key, stack, val) + } + } + stack.pop() } +} - // get caller of deprecated thing in relation to file - for (; i < stack.length; i++) { - caller = callSiteLocation(stack[i]) - callFile = caller[0] +// Stable-stringify +function compareFunction (a, b) { + if (a < b) { + return -1 + } + if (a > b) { + return 1 + } + return 0 +} - if (callFile === file) { - seen = true - } else if (callFile === this._file) { - file = this._file - } else if (seen) { - break +function deterministicStringify (obj, replacer, spacer) { + var tmp = deterministicDecirc(obj, '', [], undefined) || obj + var res + if (replacerStack.length === 0) { + res = JSON.stringify(tmp, replacer, spacer) + } else { + res = JSON.stringify(tmp, replaceGetterValues(replacer), spacer) + } + 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 +} + +function deterministicDecirc (val, k, stack, parent) { + var i + if (typeof val === 'object' && val !== null) { + for (i = 0; i < stack.length; i++) { + if (stack[i] === val) { + var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k) + if (propertyDescriptor.get !== undefined) { + if (propertyDescriptor.configurable) { + Object.defineProperty(parent, k, { value: '[Circular]' }) + arr.push([parent, k, val, propertyDescriptor]) + } else { + replacerStack.push([val, k]) + } + } else { + parent[k] = '[Circular]' + arr.push([parent, k, val]) + } + return + } + } + if (typeof val.toJSON === 'function') { + 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++) { + deterministicDecirc(val[i], i, stack, val) + } + } 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, stack, val) + tmp[key] = val[key] + } + if (parent !== undefined) { + arr.push([parent, k, val]) + parent[k] = tmp + } else { + return tmp + } } + stack.pop() } +} - var key = caller - ? depSite.join(':') + '__' + caller.join(':') - : undefined - - if (key !== undefined && key in this._warned) { - // already warned - return +// wraps replacer function to handle values we couldn't replace +// and mark them as [Circular] +function replaceGetterValues (replacer) { + replacer = 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 = '[Circular]' + replacerStack.splice(i, 1) + break + } + } + } + return replacer.call(this, key, val) } +} - 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 - } +/***/ 34578: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // 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') -} +"use strict"; -/** - * Get call site location as array. - */ +/* +Copyright (c) 2014 Petka Antonov -function callSiteLocation (callSite) { - var file = callSite.getFileName() || '' - var line = callSite.getLineNumber() - var colm = callSite.getColumnNumber() +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: - if (callSite.isEval()) { - file = callSite.getEvalOrigin() + ', ' + file - } +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. - var site = [file, line, colm] +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; - site.callSite = callSite - site.name = callSite.getFunctionName() + this.auth = null; + this.slashes = null; + this.host = null; + this.hostname = null; + this.hash = null; + this.search = null; + this.pathname = null; - return site + this._prependSlash = false; } -/** - * Generate a default message from the site. - */ - -function defaultMessage (site) { - var callSite = site.callSite - var funcName = site.name +var querystring = __nccwpck_require__(63477); - // make useful anonymous name - if (!funcName) { - funcName = '' - } +Url.queryString = querystring; - var context = callSite.getThis() - var typeName = context && callSite.getTypeName() +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; - // ignore useless type name - if (typeName === 'Object') { - typeName = undefined - } + //Trim leading and trailing ws + while (str.charCodeAt(start) <= 0x20 /*' '*/) start++; + while (str.charCodeAt(end) <= 0x20 /*' '*/) end--; - // make useful type name - if (typeName === 'Function') { - typeName = context.name || typeName - } + start = this._parseProtocol(str, start, end); - return typeName && callSite.getMethodName() - ? typeName + '.' + funcName - : funcName -} + //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 = ""; + } + } -/** - * Format deprecation message without color. - */ + if (start <= end) { + var ch = str.charCodeAt(start); -function formatPlain (msg, caller, stack) { - var timestamp = new Date().toUTCString() + 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 ); + } - var formatted = timestamp + - ' ' + this._namespace + - ' deprecated ' + msg + } - // add stack trace - if (this._traced) { - for (var i = 0; i < stack.length; i++) { - formatted += '\n at ' + callSiteToString(stack[i]) + if (!this.pathname && this.hostname && + this._slashProtocols[this._protocol]) { + this.pathname = "/"; } - return formatted - } + 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); + } +}; - if (caller) { - formatted += ' at ' + formatLocation(caller) - } +Url.prototype.resolve = function Url$resolve(relative) { + return this.resolveObject(Url.parse(relative, false, true)).format(); +}; - return formatted -} +Url.prototype.format = function Url$format() { + var auth = this.auth || ""; -/** - * Format deprecation message with color. - */ + if (auth) { + auth = encodeURIComponent(auth); + auth = auth.replace(/%3A/i, ":"); + auth += "@"; + } -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 + 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 = ""; - // add stack trace - if (this._traced) { - for (var i = 0; i < stack.length; i++) { - formatted += '\n \x1b[36mat ' + callSiteToString(stack[i]) + '\x1b[39m' // cyan + //Cache the result of the getter function + var q = this.query; + if (q && typeof q === "object") { + query = Url.queryString.stringify(q); } - return formatted - } - - if (caller) { - formatted += ' \x1b[36m' + formatLocation(caller) + '\x1b[39m' // cyan - } + if (!search) { + search = query ? "?" + query : ""; + } - return formatted -} + if (protocol && protocol.charCodeAt(protocol.length - 1) !== 0x3A /*':'*/) + protocol += ":"; -/** - * Format call site location. - */ + if (this.host) { + host = auth + this.host; + } + else if (hostname) { + var ip6 = hostname.indexOf(":") > -1; + if (ip6) hostname = "[" + hostname + "]"; + host = auth + hostname + (port ? ":" + port : ""); + } -function formatLocation (callSite) { - return relative(basePath, callSite[0]) + - ':' + callSite[1] + - ':' + callSite[2] -} + var slashes = this.slashes || + ((!protocol || + slashProtocols[protocol]) && host !== false); -/** - * Get the stack as array of call sites. - */ -function getStack () { - var limit = Error.stackTraceLimit - var obj = {} - var prep = Error.prepareStackTrace + if (protocol) scheme = protocol + (slashes ? "//" : ""); + else if (slashes) scheme = "//"; - Error.prepareStackTrace = prepareObjectStackTrace - Error.stackTraceLimit = Math.max(10, limit) + 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; - // capture the stack - Error.captureStackTrace(obj) + pathname = escapePathName(pathname); + search = escapeSearch(search); - // slice this function off the top - var stack = obj.stack.slice(1) + return scheme + (host === false ? "" : host) + pathname + search + hash; +}; - Error.prepareStackTrace = prep - Error.stackTraceLimit = limit +Url.prototype.resolveObject = function Url$resolveObject(relative) { + if (typeof relative === "string") + relative = Url.parse(relative, false, true); - return stack -} + var result = this._clone(); -/** - * Capture call site stack from v8. - */ + // hash is always overridden, no matter what. + // even href="" will remove it. + result.hash = relative.hash; -function prepareObjectStackTrace (obj, stack) { - return stack -} + // if the relative url is empty, then there"s nothing left to do here. + if (!relative.href) { + result._href = ""; + return result; + } -/** - * Return a wrapped function in a deprecation message. - */ + // hrefs like //foo/bar always cut to the protocol. + if (relative.slashes && !relative._protocol) { + relative._copyPropsTo(result, true); -function wrapfunction (fn, message) { - if (typeof fn !== 'function') { - throw new TypeError('argument fn must be a function') - } + if (slashProtocols[result._protocol] && + result.hostname && !result.pathname) { + result.pathname = "/"; + } + result._href = ""; + return result; + } - var args = createArgumentsString(fn.length) - var deprecate = this // eslint-disable-line no-unused-vars - var stack = getStack() - var site = callSiteLocation(stack[1]) + 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; + } - site.name = fn.name + 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; + } - // 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' + - '})') + 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; + } - return deprecatedfn -} + 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)); -/** - * Wrap property in a deprecation message. - */ + var removeAllDots = mustEndAbs; -function wrapproperty (obj, prop, message) { - if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { - throw new TypeError('argument obj must be object') - } + var srcPath = result.pathname && result.pathname.split("/") || []; + var relPath = relative.pathname && relative.pathname.split("/") || []; + var psychotic = result._protocol && !slashProtocols[result._protocol]; - var descriptor = Object.getOwnPropertyDescriptor(obj, prop) + // 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] === ""); + } - if (!descriptor) { - throw new TypeError('must call property on owner object') - } + 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; + } - if (!descriptor.configurable) { - throw new TypeError('property must be configurable') - } + if (!srcPath.length) { + // no path at all. easy. + // we"ve already handled the other stuff above. + result.pathname = null; + result._href = ""; + return result; + } - var deprecate = this - var stack = getStack() - var site = callSiteLocation(stack[1]) + // 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 === ""); - // set site name - site.name = prop + // 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--; + } + } - // convert data descriptor - if ('value' in descriptor) { - descriptor = convertDataDescriptorToAccessor(obj, prop, message) - } + // if the path is allowed to go above the root, restore leading ..s + if (!mustEndAbs && !removeAllDots) { + for (; up--; up) { + srcPath.unshift(".."); + } + } - var get = descriptor.get - var set = descriptor.set + if (mustEndAbs && srcPath[0] !== "" && + (!srcPath[0] || srcPath[0].charCodeAt(0) !== 0x2F /*'/'*/)) { + srcPath.unshift(""); + } - // wrap getter - if (typeof get === 'function') { - descriptor.get = function getter () { - log.call(deprecate, message, site) - return get.apply(this, arguments) + if (hasTrailingSlash && (srcPath.join("/").substr(-1) !== "/")) { + srcPath.push(""); } - } - // wrap setter - if (typeof set === 'function') { - descriptor.set = function setter () { - log.call(deprecate, message, site) - return set.apply(this, arguments) + var isAbsolute = srcPath[0] === "" || + (srcPath[0] && srcPath[0].charCodeAt(0) === 0x2F /*'/'*/); + + // 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(); + } } - } - Object.defineProperty(obj, prop, descriptor) -} + mustEndAbs = mustEndAbs || (result.host && srcPath.length); -/** - * Create DeprecationError for deprecation - */ + if (mustEndAbs && !isAbsolute) { + srcPath.unshift(""); + } -function DeprecationError (namespace, message, stack) { - var error = new Error() - var stackString + result.pathname = srcPath.length === 0 ? null : srcPath.join("/"); + result.auth = relative.auth || result.auth; + result.slashes = result.slashes || relative.slashes; + result._href = ""; + return result; +}; - Object.defineProperty(error, 'constructor', { - value: DeprecationError - }) +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); +}; - Object.defineProperty(error, 'message', { - configurable: true, - enumerable: false, - value: message, - writable: true - }) +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); +}; - Object.defineProperty(error, 'name', { - enumerable: false, - configurable: true, - value: 'DeprecationError', - writable: true - }) +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); +}; - Object.defineProperty(error, 'namespace', { - configurable: true, - enumerable: false, - value: namespace, - writable: true - }) +Url.prototype._parseProtocol = function Url$_parseProtocol(str, start, end) { + var doLowerCase = false; + var protocolCharacters = this._protocolCharacters; - Object.defineProperty(error, 'stack', { - configurable: true, - enumerable: false, - get: function () { - if (stackString !== undefined) { - return stackString - } + for (var i = start; i <= end; ++i) { + var ch = str.charCodeAt(i); + + 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; + } - // prepare stack trace - return (stackString = createStackString.call(this, stack)) - }, - set: function setter (val) { - stackString = val } - }) + return start; +}; - return error -} +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; +}; +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; -/***/ }), + for (var i = start; i <= end; ++i) { + var ch = str.charCodeAt(i); -/***/ 35554: -/***/ ((module) => { + 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; + } -"use strict"; -/*! - * depd - * Copyright(c) 2014 Douglas Christopher Wilson - * MIT Licensed - */ + } + if ((port === 0 && !hadChars) || !validPort) { + if (!validPort) { + this._port = -2; + } + return 0; + } + 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; -/** - * Module exports. - */ + //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; + } -module.exports = callSiteToString + var doLowerCase = false; + var idna = false; + var hostNameStart = start; + var hostNameEnd = end; + var lastCh = -1; + var portLength = 0; + var charsAfterDot = 0; + var authNeedsDecoding = false; -/** - * Format a CallSite file location to a string. - */ + var j = -1; -function callSiteFileLocation (callSite) { - var fileName - var fileLocation = '' + //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); - if (callSite.isNative()) { - fileLocation = 'native' - } else if (callSite.isEval()) { - fileName = callSite.getScriptNameOrSourceURL() - if (!fileName) { - fileLocation = callSite.getEvalOrigin() + 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; + } } - } else { - fileName = callSite.getFileName() - } - if (fileName) { - fileLocation += fileName + //@-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; + } - var lineNumber = callSite.getLineNumber() - if (lineNumber != null) { - fileLocation += ':' + lineNumber + //Host name is starting with a [ + if (str.charCodeAt(start) === 0x5B /*'['*/) { + for (var i = start + 1; i <= end; ++i) { + var ch = str.charCodeAt(i); - var columnNumber = callSite.getColumnNumber() - if (columnNumber) { - fileLocation += ':' + columnNumber - } + //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; } - } - return fileLocation || 'unknown source' -} + 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); -/** - * Format a CallSite to a string. - */ + 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++; + } -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 = '' + //Node.js ignores this error + /* + if (lastCh === DOT) { + hostNameEnd--; + } + */ - if (isMethodCall) { - var methodName = callSite.getMethodName() - var typeName = getConstructorName(callSite) + 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; + } - if (functionName) { - if (typeName && functionName.indexOf(typeName) !== 0) { - line += typeName + '.' - } + return hostNameEnd + 1 + portLength; - line += functionName +}; - if (methodName && functionName.lastIndexOf('.' + methodName) !== functionName.length - methodName.length - 1) { - line += ' [as ' + methodName + ']' - } - } else { - line += typeName + '.' + (methodName || '') +Url.prototype._copyPropsTo = function Url$_copyPropsTo(input, noProtocol) { + if (!noProtocol) { + input._protocol = this._protocol; } - } else if (isConstructor) { - line += 'new ' + (functionName || '') - } else if (functionName) { - line += functionName - } else { - addSuffix = false - line += fileLocation - } + 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; +}; - if (addSuffix) { - line += ' (' + fileLocation + ')' - } +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; +}; - return line -} +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]; -/** - * Get constructor name of reviver. - */ + 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; +}; -function getConstructorName (obj) { - var receiver = obj.receiver - return (receiver.constructor && receiver.constructor.name) || null -} +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 ? "/:" : ""; + 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; + } + } -/***/ }), + if (pathStart > pathEnd) { + this.pathname = prePath === "" ? "/" : prePath; + return; + } -/***/ 12078: -/***/ ((module) => { + 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; +}; -"use strict"; -/*! - * depd - * Copyright(c) 2015 Douglas Christopher Wilson - * MIT Licensed - */ +Url.prototype._parseQuery = function Url$_parseQuery(str, start, end, disableAutoEscapeChars) { + var queryStart = start; + var queryEnd = end; + var escape = false; + var autoEscapeCharacters = this._autoEscapeCharacters; + + for (var i = start; i <= end; ++i) { + var ch = str.charCodeAt(i); + + if (ch === 0x23 /*'#'*/) { + this._parseHash(str, i, end, disableAutoEscapeChars); + queryEnd = i - 1; + break; + } + else if (!disableAutoEscapeChars && !escape && autoEscapeCharacters[ch] === 1) { + escape = true; + } + } + if (queryStart > queryEnd) { + this.search = ""; + return; + } + var query; + if (escape) { + query = this._getComponentEscaped(str, queryStart, queryEnd, true); + } + else { + query = str.slice(queryStart, queryEnd + 1); + } + this.search = query; +}; -/** - * Module exports. - * @public - */ +Url.prototype._parseHash = function Url$_parseHash(str, start, end, disableAutoEscapeChars) { + if (start > end) { + this.hash = ""; + return; + } -module.exports = eventListenerCount + this.hash = disableAutoEscapeChars ? + str.slice(start, end + 1) : this._getComponentEscaped(str, start, end, true); +}; -/** - * Get the count of listeners on an event emitter of a specific type. - */ +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); + } + } +}); -function eventListenerCount (emitter, type) { - return emitter.listeners(type).length -} +Object.defineProperty(Url.prototype, "query", { + get: function() { + var query = this._query; + if (query != null) { + return query; + } + var search = this.search; + 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; + } +}); -/***/ }), +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() {} +}); -/***/ 69829: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +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; + } + } +}); -"use strict"; -/*! - * depd - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ +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; +}; +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(); +}; -/** - * Module dependencies. - * @private - */ +Url.resolve = function Url$Resolve(source, relative) { + return Url.parse(source, false, true).resolve(relative); +}; -var EventEmitter = (__nccwpck_require__(82361).EventEmitter) +Url.resolveObject = function Url$ResolveObject(source, relative) { + if (!source) return relative; + return Url.parse(source, false, true).resolveObject(relative); +}; -/** - * Module exports. - * @public - */ +function _escapePath(pathname) { + return pathname.replace(/[?#]/g, function(match) { + return encodeURIComponent(match); + }); +} -lazyProperty(module.exports, 'callSiteToString', function callSiteToString () { - var limit = Error.stackTraceLimit - var obj = {} - var prep = Error.prepareStackTrace +function _escapeSearch(search) { + return search.replace(/#/g, function(match) { + return encodeURIComponent(match); + }); +} - function prepareObjectStackTrace (obj, stack) { - return stack - } +//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); - Error.prepareStackTrace = prepareObjectStackTrace - Error.stackTraceLimit = 2 + if (ch === char1) { + return true; + } + else if (stopCharacterTable[ch] === 1) { + return false; + } + } + return false; +} - // capture the stack - Error.captureStackTrace(obj) +//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; +} - // slice the stack - var stack = obj.stack.slice() +//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] - Error.prepareStackTrace = prep - Error.stackTraceLimit = limit +//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; + } + } + }); - return stack[0].toString ? toString : __nccwpck_require__(35554) -}) + return ret; +} -lazyProperty(module.exports, 'eventListenerCount', function eventListenerCount () { - return EventEmitter.listenerCount || __nccwpck_require__(12078) -}) -/** - * Define a lazy property. - */ +var autoEscape = ["<", ">", "\"", "`", " ", "\r", "\n", + "\t", "{", "}", "|", "\\", "^", "`", "'"]; -function lazyProperty (obj, prop, getter) { - function get () { - var val = getter() +var autoEscapeMap = new Array(128); - Object.defineProperty(obj, prop, { - configurable: true, - enumerable: true, - value: val - }) - return val - } - Object.defineProperty(obj, prop, { - configurable: true, - enumerable: true, - get: get - }) +for (var i = 0, len = autoEscapeMap.length; i < len; ++i) { + autoEscapeMap[i] = ""; } -/** - * Call toString() on the obj - */ - -function toString (obj) { - return obj.toString() +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 /*'\'*/] = "/"; +var slashProtocols = Url.prototype._slashProtocols = { + http: true, + https: true, + gopher: true, + file: true, + ftp: true, -/***/ }), - -/***/ 58932: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; + "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; -Object.defineProperty(exports, "__esModule", ({ value: true })); +Url.prototype._protocolCharacters = makeAsciiTable([ + [0x61 /*'a'*/, 0x7A /*'z'*/], + [0x41 /*'A'*/, 0x5A /*'Z'*/], + 0x2E /*'.'*/, 0x2B /*'+'*/, 0x2D /*'-'*/ +]); -class Deprecation extends Error { - constructor(message) { - super(message); // Maintains proper stack trace (only available on V8) +Url.prototype._hostEndingCharacters = makeAsciiTable([ + 0x23 /*'#'*/, 0x3F /*'?'*/, 0x2F /*'/'*/, 0x5C /*'\'*/ +]); - /* istanbul ignore next */ +Url.prototype._autoEscapeCharacters = makeAsciiTable( + autoEscape.map(function(v) { + return v.charCodeAt(0); + }) +); - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } +//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); + }) +); - this.name = 'Deprecation'; - } +Url.prototype._autoEscapeMap = autoEscapeMap; +Url.prototype._afterQueryAutoEscapeMap = afterQueryAutoEscapeMap; -} +module.exports = Url; -exports.Deprecation = Deprecation; +Url.replace = function Url$Replace() { + require.cache.url = { + exports: Url + }; +}; /***/ }), -/***/ 43225: +/***/ 30810: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /*! - * destroy - * Copyright(c) 2014 Jonathan Ong + * finalhandler + * Copyright(c) 2014-2017 Douglas Christopher Wilson * MIT Licensed */ @@ -46145,21172 +47682,24286 @@ exports.Deprecation = Deprecation; * @private */ -var ReadStream = (__nccwpck_require__(57147).ReadStream) -var Stream = __nccwpck_require__(12781) - -/** - * Module exports. - * @public - */ - -module.exports = destroy +var debug = __nccwpck_require__(65612)('finalhandler') +var encodeUrl = __nccwpck_require__(16592) +var escapeHtml = __nccwpck_require__(94070) +var onFinished = __nccwpck_require__(92098) +var parseUrl = __nccwpck_require__(89808) +var statuses = __nccwpck_require__(57415) +var unpipe = __nccwpck_require__(3124) /** - * Destroy a stream. - * - * @param {object} stream - * @public + * Module variables. + * @private */ -function destroy(stream) { - if (stream instanceof ReadStream) { - return destroyReadStream(stream) - } - - if (!(stream instanceof Stream)) { - return stream - } - - if (typeof stream.destroy === 'function') { - stream.destroy() - } +var DOUBLE_SPACE_REGEXP = /\x20{2}/g +var NEWLINE_REGEXP = /\n/g - return stream -} +/* istanbul ignore next */ +var defer = typeof setImmediate === 'function' + ? setImmediate + : function (fn) { process.nextTick(fn.bind.apply(fn, arguments)) } +var isFinished = onFinished.isFinished /** - * Destroy a ReadStream. + * Create a minimal HTML document. * - * @param {object} stream + * @param {string} message * @private */ -function destroyReadStream(stream) { - stream.destroy() - - if (typeof stream.close === 'function') { - // node.js core bug work-around - stream.on('open', onOpenClose) - } +function createHtmlDocument (message) { + var body = escapeHtml(message) + .replace(NEWLINE_REGEXP, '
') + .replace(DOUBLE_SPACE_REGEXP, '  ') - return stream + return '\n' + + '\n' + + '\n' + + '\n' + + 'Error\n' + + '\n' + + '\n' + + '
' + body + '
\n' + + '\n' + + '\n' } /** - * On open handler to close stream. - * @private + * Module exports. + * @public */ -function onOpenClose() { - if (typeof this.fd === 'number') { - // actually close down the fd - this.close() - } -} - - -/***/ }), - -/***/ 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 -} - -type DotenvConfigOutput = { - parsed?: DotenvParseOutput, - error?: Error -} +module.exports = finalhandler -*/ +/** + * Create a function to handle the final response. + * + * @param {Request} req + * @param {Response} res + * @param {Object} [options] + * @return {Function} + * @public + */ -const fs = __nccwpck_require__(57147) -const path = __nccwpck_require__(71017) +function finalhandler (req, res, options) { + var opts = options || {} -function log (message /*: string */) { - console.log(`[dotenv][DEBUG] ${message}`) -} + // get environment + var env = opts.env || process.env.NODE_ENV || 'development' -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/ + // get error callback + var onerror = opts.onerror -// Parses src into an Object -function parse (src /*: string | Buffer */, options /*: ?DotenvParseOptions */) /*: DotenvParseOutput */ { - const debug = Boolean(options && options.debug) - const obj = {} + return function (err) { + var headers + var msg + var status - // 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] === "'" + // ignore 404 on in-flight response + if (!err && headersSent(res)) { + debug('cannot 404 after headers sent') + return + } - // if single or double quoted, remove quotes - if (isSingleQuoted || isDoubleQuoted) { - val = val.substring(1, end) + // unhandled error + if (err) { + // respect status code from error + status = getErrorStatusCode(err) - // if double quoted, expand newlines - if (isDoubleQuoted) { - val = val.replace(RE_NEWLINES, NEWLINE) - } + if (status === undefined) { + // fallback to status code on response + status = getResponseStatusCode(res) } else { - // remove surrounding whitespace - val = val.trim() + // respect headers from error + headers = getErrorHeaders(err) } - obj[key] = val - } else if (debug) { - log(`did not match key and value when parsing line ${idx + 1}: ${line}`) + // get error message + msg = getErrorMessage(err, status, env) + } else { + // not found + status = 404 + msg = 'Cannot ' + req.method + ' ' + encodeUrl(getResourceName(req)) } - }) - - return obj -} -// 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 + debug('default %s', status) - if (options) { - if (options.path != null) { - dotenvPath = options.path - } - if (options.encoding != null) { - encoding = options.encoding - } - if (options.debug != null) { - debug = true + // schedule onerror callback + if (err && onerror) { + defer(onerror, err, req, res) } - } - - 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`) - } - }) + // cannot actually respond + if (headersSent(res)) { + debug('cannot %d after headers sent', status) + req.socket.destroy() + return + } - return { parsed } - } catch (e) { - return { error: e } + // send response + send(req, res, status, headers, msg) } } -module.exports.config = config -module.exports.parse = parse +/** + * Get headers from Error object. + * + * @param {Error} err + * @return {object} + * @private + */ +function getErrorHeaders (err) { + if (!err.headers || typeof err.headers !== 'object') { + return undefined + } -/***/ }), + var headers = Object.create(null) + var keys = Object.keys(err.headers) -/***/ 11728: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + for (var i = 0; i < keys.length; i++) { + var key = keys[i] + headers[key] = err.headers[key] + } -"use strict"; + return headers +} +/** + * Get message from Error object, fallback to status message. + * + * @param {Error} err + * @param {number} status + * @param {string} env + * @return {string} + * @private + */ -var Buffer = (__nccwpck_require__(21867).Buffer); +function getErrorMessage (err, status, env) { + var msg -var getParamBytesForAlg = __nccwpck_require__(30528); + if (env !== 'production') { + // use err.stack, which typically includes err.message + msg = err.stack -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); + // fallback to err.toString() when possible + if (!msg && typeof err.toString === 'function') { + msg = err.toString() + } + } -function base64Url(base64) { - return base64 - .replace(/=/g, '') - .replace(/\+/g, '-') - .replace(/\//g, '_'); + return msg || statuses[status] } -function signatureAsBuffer(signature) { - if (Buffer.isBuffer(signature)) { - return signature; - } else if ('string' === typeof signature) { - return Buffer.from(signature, 'base64'); - } +/** + * Get status code from Error object. + * + * @param {Error} err + * @return {number} + * @private + */ - throw new TypeError('ECDSA signature must be a Base64 string or a Buffer'); -} +function getErrorStatusCode (err) { + // check err.status + if (typeof err.status === 'number' && err.status >= 400 && err.status < 600) { + return err.status + } -function derToJose(signature, alg) { - signature = signatureAsBuffer(signature); - var paramBytes = getParamBytesForAlg(alg); + // check err.statusCode + if (typeof err.statusCode === 'number' && err.statusCode >= 400 && err.statusCode < 600) { + return err.statusCode + } - // 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; + return undefined +} - var inputLength = signature.length; +/** + * 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 + */ - var offset = 0; - if (signature[offset++] !== ENCODED_TAG_SEQ) { - throw new Error('Could not find expected "seq"'); - } +function getResourceName (req) { + try { + return parseUrl.original(req).pathname + } catch (e) { + return 'resource' + } +} - var seqLength = signature[offset++]; - if (seqLength === (MAX_OCTET | 1)) { - seqLength = signature[offset++]; - } +/** + * Get status code from response. + * + * @param {OutgoingMessage} res + * @return {number} + * @private + */ - if (inputLength - offset < seqLength) { - throw new Error('"seq" specified length of "' + seqLength + '", only "' + (inputLength - offset) + '" remaining'); - } +function getResponseStatusCode (res) { + var status = res.statusCode - if (signature[offset++] !== ENCODED_TAG_INT) { - throw new Error('Could not find expected "int" for "r"'); - } + // default status code to 500 if outside valid range + if (typeof status !== 'number' || status < 400 || status > 599) { + status = 500 + } - var rLength = signature[offset++]; + return status +} - if (inputLength - offset - 2 < rLength) { - throw new Error('"r" specified length of "' + rLength + '", only "' + (inputLength - offset - 2) + '" available'); - } +/** + * Determine if the response headers have been sent. + * + * @param {object} res + * @returns {boolean} + * @private + */ - if (maxEncodedParamLength < rLength) { - throw new Error('"r" specified length of "' + rLength + '", max of "' + maxEncodedParamLength + '" is acceptable'); - } +function headersSent (res) { + return typeof res.headersSent !== 'boolean' + ? Boolean(res._header) + : res.headersSent +} - var rOffset = offset; - offset += rLength; +/** + * Send response. + * + * @param {IncomingMessage} req + * @param {OutgoingMessage} res + * @param {number} status + * @param {object} headers + * @param {string} message + * @private + */ - if (signature[offset++] !== ENCODED_TAG_INT) { - throw new Error('Could not find expected "int" for "s"'); - } +function send (req, res, status, headers, message) { + function write () { + // response body + var body = createHtmlDocument(message) - var sLength = signature[offset++]; + // response status + res.statusCode = status + res.statusMessage = statuses[status] - if (inputLength - offset !== sLength) { - throw new Error('"s" specified length of "' + sLength + '", expected "' + (inputLength - offset) + '"'); - } + // response headers + setHeaders(res, headers) - if (maxEncodedParamLength < sLength) { - throw new Error('"s" specified length of "' + sLength + '", max of "' + maxEncodedParamLength + '" is acceptable'); - } + // security headers + res.setHeader('Content-Security-Policy', "default-src 'none'") + res.setHeader('X-Content-Type-Options', 'nosniff') - var sOffset = offset; - offset += sLength; + // standard headers + res.setHeader('Content-Type', 'text/html; charset=utf-8') + res.setHeader('Content-Length', Buffer.byteLength(body, 'utf8')) - if (offset !== inputLength) { - throw new Error('Expected to consume entire buffer, but "' + (inputLength - offset) + '" bytes remain'); - } + if (req.method === 'HEAD') { + res.end() + return + } - var rPadding = paramBytes - rLength, - sPadding = paramBytes - sLength; + res.end(body, 'utf8') + } - var dst = Buffer.allocUnsafe(rPadding + rLength + sPadding + sLength); + if (isFinished(req)) { + write() + return + } - for (offset = 0; offset < rPadding; ++offset) { - dst[offset] = 0; - } - signature.copy(dst, offset, rOffset + Math.max(-rPadding, 0), rOffset + rLength); + // unpipe everything from the request + unpipe(req) - offset = paramBytes; + // flush the request + onFinished(req, write) + req.resume() +} - for (var o = offset; offset < o + sPadding; ++offset) { - dst[offset] = 0; - } - signature.copy(dst, offset, sOffset + Math.max(-sPadding, 0), sOffset + sLength); +/** + * Set response headers from an object. + * + * @param {OutgoingMessage} res + * @param {object} headers + * @private + */ - dst = dst.toString('base64'); - dst = base64Url(dst); +function setHeaders (res, headers) { + if (!headers) { + return + } - return dst; + var keys = Object.keys(headers) + for (var i = 0; i < keys.length; i++) { + var key = keys[i] + res.setHeader(key, headers[key]) + } } -function countPadding(buf, start, stop) { - var padding = 0; - while (start + padding < stop && buf[start + padding] === 0) { - ++padding; - } - - var needsSign = buf[start + padding] >= MAX_OCTET; - if (needsSign) { - --padding; - } - return padding; -} +/***/ }), -function joseToDer(signature, alg) { - signature = signatureAsBuffer(signature); - var paramBytes = getParamBytesForAlg(alg); +/***/ 56401: +/***/ ((module, exports, __nccwpck_require__) => { - var signatureBytes = signature.length; - if (signatureBytes !== paramBytes * 2) { - throw new TypeError('"' + alg + '" signatures must be "' + paramBytes * 2 + '" bytes, saw "' + signatureBytes + '"'); - } +/** + * This is the web browser implementation of `debug()`. + * + * Expose `debug()` as the module. + */ - var rPadding = countPadding(signature, 0, paramBytes); - var sPadding = countPadding(signature, paramBytes, signature.length); - var rLength = paramBytes - rPadding; - var sLength = paramBytes - sPadding; +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(); - var rsBytes = 1 + 1 + rLength + 1 + 1 + sLength; +/** + * Colors. + */ - var shortLength = rsBytes < MAX_OCTET; +exports.colors = [ + 'lightseagreen', + 'forestgreen', + 'goldenrod', + 'dodgerblue', + 'darkorchid', + 'crimson' +]; - var dst = Buffer.allocUnsafe((shortLength ? 2 : 3) + rsBytes); +/** + * 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 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 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 dst; + // 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 = { - derToJose: derToJose, - joseToDer: joseToDer -}; +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ +exports.formatters.j = function(v) { + try { + return JSON.stringify(v); + } catch (err) { + return '[UnexpectedJSONParseError]: ' + err.message; + } +}; -/***/ }), -/***/ 30528: -/***/ ((module) => { +/** + * Colorize log arguments if enabled. + * + * @api public + */ -"use strict"; +function formatArgs(args) { + var useColors = this.useColors; + args[0] = (useColors ? '%c' : '') + + this.namespace + + (useColors ? ' %c' : ' ') + + args[0] + + (useColors ? '%c ' : ' ') + + '+' + exports.humanize(this.diff); -function getParamSize(keySize) { - var result = ((keySize / 8) | 0) + (keySize % 8 === 0 ? 0 : 1); - return result; -} + if (!useColors) return; -var paramBytesForAlg = { - ES256: getParamSize(256), - ES384: getParamSize(384), - ES512: getParamSize(521) -}; + var c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit') -function getParamBytesForAlg(alg) { - var paramBytes = paramBytesForAlg[alg]; - if (paramBytes) { - return paramBytes; - } + // 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; + } + }); - throw new Error('Unknown algorithm "' + alg + '"'); + args.splice(lastC, 0, c); } -module.exports = getParamBytesForAlg; - - -/***/ }), - -/***/ 14401: -/***/ ((module) => { - -"use strict"; -/*! - * ee-first - * Copyright(c) 2014 Jonathan Ong - * MIT Licensed +/** + * Invokes `console.log()` when available. + * No-op when `console.log` is not a "function". + * + * @api public */ - +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); +} /** - * Module exports. - * @public + * Save `namespaces`. + * + * @param {String} namespaces + * @api private */ -module.exports = first +function save(namespaces) { + try { + if (null == namespaces) { + exports.storage.removeItem('debug'); + } else { + exports.storage.debug = namespaces; + } + } catch(e) {} +} /** - * Get the first event in a set of event emitters and event pairs. + * Load `namespaces`. * - * @param {array} stuff - * @param {function} done - * @public + * @return {String} returns the previously persisted debug modes + * @api private */ -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, - }) - } - } - - function callback() { - cleanup() - done.apply(null, arguments) - } - - function cleanup() { - var x - for (var i = 0; i < cleanups.length; i++) { - x = cleanups[i] - x.ee.removeListener(x.event, x.fn) - } - } +function load() { + var r; + try { + r = exports.storage.debug; + } catch(e) {} - function thunk(fn) { - done = fn + // 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; } - thunk.cancel = cleanup - - return thunk + return r; } /** - * Create the event listener. - * @private + * Enable namespaces listed in `localStorage.debug` initially. */ -function listener(event, done) { - return function onevent(arg1) { - var args = new Array(arguments.length) - var ee = this - var err = event === 'error' - ? arg1 - : null +exports.enable(load()); - // copy args to prevent arguments escaping scope - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i] - } +/** + * 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 + */ - done(err, ee, event, args) - } +function localstorage() { + try { + return window.localStorage; + } catch (e) {} } /***/ }), -/***/ 18212: -/***/ ((module) => { - -"use strict"; - - -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; -}; - - -/***/ }), +/***/ 60545: +/***/ ((module, exports, __nccwpck_require__) => { -/***/ 16592: -/***/ ((module) => { -"use strict"; -/*! - * encodeurl - * Copyright(c) 2016 Douglas Christopher Wilson - * MIT Licensed +/** + * 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__(80761); /** - * Module exports. - * @public + * The currently active debug mode names, and names to skip. */ -module.exports = encodeUrl +exports.names = []; +exports.skips = []; /** - * RegExp to match non-URL code points, *after* encoding (i.e. not including "%") - * and including invalid escape sequences. - * @private + * 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". */ -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 +exports.formatters = {}; /** - * RegExp to match unmatched surrogate pair. - * @private + * Previous log timestamp. */ -var UNMATCHED_SURROGATE_PAIR_REGEXP = /(^|[^\uD800-\uDBFF])[\uDC00-\uDFFF]|[\uD800-\uDBFF]([^\uDC00-\uDFFF]|$)/g +var prevTime; /** - * String to replace unmatched surrogate pair with. - * @private + * Select a color. + * @param {String} namespace + * @return {Number} + * @api private */ -var UNMATCHED_SURROGATE_PAIR_REPLACE = '$1\uFFFD$2' +function selectColor(namespace) { + var hash = 0, i; + + for (i in namespace) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } + + return exports.colors[Math.abs(hash) % exports.colors.length]; +} /** - * 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. + * Create a debugger with the given `namespace`. * - * @param {string} url - * @return {string} - * @public + * @param {String} namespace + * @return {Function} + * @api public */ -function encodeUrl (url) { - return String(url) - .replace(UNMATCHED_SURROGATE_PAIR_REGEXP, UNMATCHED_SURROGATE_PAIR_REPLACE) - .replace(ENCODE_CHARS_REGEXP, encodeURI) -} +function createDebug(namespace) { + function debug() { + // disabled? + if (!debug.enabled) return; -/***/ }), + var self = debug; -/***/ 23505: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // 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]); -var util = __nccwpck_require__(73837); -var isArrayish = __nccwpck_require__(7604); + if ('string' !== typeof args[0]) { + // anything else let's inspect with %O + args.unshift('%O'); + } -var errorEx = function errorEx(name, properties) { - if (!name || name.constructor !== String) { - properties = name || {}; - name = Error.name; - } + // 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); - var errorExError = function ErrorEXError(message) { - if (!this) { - return new ErrorEXError(message); - } + // now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); - message = message instanceof Error - ? message.message - : (message || this.message); + // apply env-specific formatting (colors, etc.) + exports.formatArgs.call(self, args); - Error.call(this, message); - Error.captureStackTrace(this, errorExError); + var logFn = debug.log || exports.log || console.log.bind(console); + logFn.apply(self, args); + } - this.name = name; + debug.namespace = namespace; + debug.enabled = exports.enabled(namespace); + debug.useColors = exports.useColors(); + debug.color = selectColor(namespace); - Object.defineProperty(this, 'message', { - configurable: true, - enumerable: false, - get: function () { - var newMessage = message.split(/\r?\n/g); + // env-specific initialization logic for debug instances + if ('function' === typeof exports.init) { + exports.init(debug); + } - for (var key in properties) { - if (!properties.hasOwnProperty(key)) { - continue; - } + return debug; +} - var modifier = properties[key]; +/** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ - if ('message' in modifier) { - newMessage = modifier.message(this[key], newMessage) || newMessage; - if (!isArrayish(newMessage)) { - newMessage = [newMessage]; - } - } - } +function enable(namespaces) { + exports.save(namespaces); - return newMessage.join('\n'); - }, - set: function (v) { - message = v; - } - }); + exports.names = []; + exports.skips = []; - var overwrittenStack = null; + var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + var len = split.length; - var stackDescriptor = Object.getOwnPropertyDescriptor(this, 'stack'); - var stackGetter = stackDescriptor.get; - var stackValue = stackDescriptor.value; - delete stackDescriptor.value; - delete stackDescriptor.writable; + 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 + '$')); + } + } +} - stackDescriptor.set = function (newstack) { - overwrittenStack = newstack; - }; +/** + * Disable debug output. + * + * @api public + */ - stackDescriptor.get = function () { - var stack = (overwrittenStack || ((stackGetter) - ? stackGetter.call(this) - : stackValue)).split(/\r?\n+/g); +function disable() { + exports.enable(''); +} - // starting in Node 7, the stack builder caches the message. - // just replace it. - if (!overwrittenStack) { - stack[0] = this.name + ': ' + this.message; - } +/** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ - var lineCount = 1; - for (var key in properties) { - if (!properties.hasOwnProperty(key)) { - continue; - } +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; +} - var modifier = properties[key]; +/** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ - if ('line' in modifier) { - var line = modifier.line(this[key]); - if (line) { - stack.splice(lineCount++, 0, ' ' + line); - } - } +function coerce(val) { + if (val instanceof Error) return val.stack || val.message; + return val; +} - if ('stack' in modifier) { - modifier.stack(this[key], stack); - } - } - return stack.join('\n'); - }; +/***/ }), - Object.defineProperty(this, 'stack', stackDescriptor); - }; +/***/ 65612: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (Object.setPrototypeOf) { - Object.setPrototypeOf(errorExError.prototype, Error.prototype); - Object.setPrototypeOf(errorExError, Error); - } else { - util.inherits(errorExError, Error); - } +/** + * Detect Electron renderer process, which is node, but we should + * treat as a browser. + */ - return errorExError; -}; +if (typeof process !== 'undefined' && process.type === 'renderer') { + module.exports = __nccwpck_require__(56401); +} else { + module.exports = __nccwpck_require__(4706); +} -errorEx.append = function (str, def) { - return { - message: function (v, message) { - v = v || def; - if (v) { - message[0] += ' ' + str.replace('%s', v.toString()); - } +/***/ }), - return message; - } - }; -}; +/***/ 4706: +/***/ ((module, exports, __nccwpck_require__) => { -errorEx.line = function (str, def) { - return { - line: function (v) { - v = v || def; +/** + * Module dependencies. + */ - if (v) { - return str.replace('%s', v.toString()); - } +var tty = __nccwpck_require__(76224); +var util = __nccwpck_require__(73837); - return null; - } - }; -}; +/** + * This is the Node.js implementation of `debug()`. + * + * Expose `debug()` as the module. + */ -module.exports = errorEx; +exports = module.exports = __nccwpck_require__(60545); +exports.init = init; +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +/** + * Colors. + */ -/***/ }), +exports.colors = [6, 2, 3, 4, 5, 1]; -/***/ 94070: -/***/ ((module) => { +/** + * Build up the default `inspectOpts` object from the environment variables. + * + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + */ -"use strict"; -/*! - * escape-html - * Copyright(c) 2012-2013 TJ Holowaychuk - * Copyright(c) 2015 Andreas Lubbe - * Copyright(c) 2015 Tiancheng "Timothy" Gu - * MIT Licensed +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; +}, {}); + +/** + * 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 */ +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); + +/** + * Is stdout a TTY? Colored output is enabled when `true`. + */ +function useColors() { + return 'colors' in exports.inspectOpts + ? Boolean(exports.inspectOpts.colors) + : tty.isatty(fd); +} /** - * Module variables. - * @private + * Map %o to `util.inspect()`, all on a single line. */ -var matchHtmlRegExp = /["'&<>]/; +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(' '); +}; /** - * Module exports. - * @public + * Map %o to `util.inspect()`, allowing multiple lines if needed. */ -module.exports = escapeHtml; +exports.formatters.O = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); +}; /** - * Escape special characters in the given string of html. + * Adds ANSI color escape codes if enabled. * - * @param {string} string The string to escape for inserting into HTML - * @return {string} - * @public + * @api public */ -function escapeHtml(string) { - var str = '' + string; - var match = matchHtmlRegExp.exec(str); +function formatArgs(args) { + var name = this.namespace; + var useColors = this.useColors; - if (!match) { - return str; + 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]; } +} - var escape; - var html = ''; - var index = 0; - var lastIndex = 0; +/** + * Invokes `util.format()` with the specified arguments and writes to `stream`. + */ - 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; - } +function log() { + return stream.write(util.format.apply(util, arguments) + '\n'); +} - if (lastIndex !== index) { - html += str.substring(lastIndex, index); - } +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ - lastIndex = index + 1; - html += escape; +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; } +} - return lastIndex !== index - ? html + str.substring(lastIndex, index) - : html; +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + +function load() { + return process.env.DEBUG; } +/** + * 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. + */ -/***/ }), +function createWritableStdioStream (fd) { + var stream; + var tty_wrap = process.binding('tty_wrap'); -/***/ 98691: -/***/ ((module) => { + // Note stream._type is used for test-module-load-list.js -"use strict"; + 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; -module.exports = string => { - if (typeof string !== 'string') { - throw new TypeError('Expected a string'); - } + case 'FILE': + var fs = __nccwpck_require__(57147); + stream = new fs.SyncWriteStream(fd, { autoClose: false }); + stream._type = 'fs'; + break; - // 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'); -}; + 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; -/***/ 69972: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + default: + // Probably an error on in uv_guess_handle() + throw new Error('Implement me. Unknown stream file type!'); + } -"use strict"; -/*! - * etag - * Copyright(c) 2014-2016 Douglas Christopher Wilson - * MIT Licensed - */ + // For supporting legacy API we put the FD here. + stream.fd = fd; + stream._isStdio = true; + return stream; +} /** - * Module exports. - * @public + * Init logic for `debug` instances. + * + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. */ -module.exports = etag +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]]; + } +} /** - * Module dependencies. - * @private + * Enable namespaces listed in `process.env.DEBUG` initially. */ -var crypto = __nccwpck_require__(6113) -var Stats = (__nccwpck_require__(57147).Stats) +exports.enable(load()); + + +/***/ }), + +/***/ 80761: +/***/ ((module) => { /** - * Module variables. - * @private + * Helpers. */ -var toString = Object.prototype.toString +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var y = d * 365.25; /** - * Generate an entity tag. + * Parse or format the given `val`. * - * @param {Buffer|string} entity - * @return {string} - * @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 */ -function entitytag (entity) { - if (entity.length === 0) { - // fast-path empty - return '"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk"' +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) + ); +}; - // 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 +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ - return '"' + len.toString(16) + '-' + hash + '"' +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; + } } /** - * Create a simple ETag. + * Short format for `ms`. * - * @param {string|Buffer|Stats} entity - * @param {object} [options] - * @param {boolean} [options.weak] + * @param {Number} ms * @return {String} - * @public + * @api private */ -function etag (entity, options) { - if (entity == null) { - throw new TypeError('argument entity is required') +function fmtShort(ms) { + if (ms >= d) { + return Math.round(ms / d) + 'd'; } - - // 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') + if (ms >= h) { + return Math.round(ms / h) + 'h'; } - - // generate entity tag - var tag = isStats - ? stattag(entity) - : entitytag(entity) - - return weak - ? 'W/' + tag - : tag + if (ms >= m) { + return Math.round(ms / m) + 'm'; + } + if (ms >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; } /** - * Determine if object is a Stats object. + * Long format for `ms`. * - * @param {object} obj - * @return {boolean} + * @param {Number} ms + * @return {String} * @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' +function fmtLong(ms) { + return plural(ms, d, 'day') || + plural(ms, h, 'hour') || + plural(ms, m, 'minute') || + plural(ms, s, 'second') || + ms + ' ms'; } /** - * Generate a tag for a stat. - * - * @param {object} stat - * @return {string} - * @private + * Pluralization helper. */ -function stattag (stat) { - var mtime = stat.mtime.getTime().toString(16) - var size = stat.size.toString(16) +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'; +} - return '"' + size + '-' + mtime + '"' + +/***/ }), + +/***/ 35298: +/***/ ((module) => { + +"use strict"; + + +// 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. + +function flatstr (s) { + s | 0 + return s } +module.exports = flatstr /***/ }), -/***/ 71204: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 46868: +/***/ ((module) => { "use strict"; /*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2013 Roman Shtylman - * Copyright(c) 2014-2015 Douglas Christopher Wilson + * forwarded + * Copyright(c) 2014-2017 Douglas Christopher Wilson * MIT Licensed */ -module.exports = __nccwpck_require__(22587); +/** + * Module exports. + * @public + */ + +module.exports = forwarded + +/** + * 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 = req.connection.remoteAddress + var addrs = [socketAddr].concat(proxyAddrs) + + // return all addresses + return addrs +} + +/** + * Parse the X-Forwarded-For header. + * + * @param {string} header + * @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 + } + } + + // final address + if (start !== end) { + list.push(header.substring(start, end)) + } + + return list +} /***/ }), -/***/ 313: -/***/ ((module, exports, __nccwpck_require__) => { +/***/ 83136: +/***/ ((module) => { "use strict"; /*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2013 Roman Shtylman - * Copyright(c) 2014-2015 Douglas Christopher Wilson + * fresh + * Copyright(c) 2012 TJ Holowaychuk + * Copyright(c) 2016-2017 Douglas Christopher Wilson * MIT Licensed */ /** - * Module dependencies. + * RegExp to check for no-cache token in Cache-Control. * @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 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 CACHE_CONTROL_NO_CACHE_REGEXP = /(?:^|,)\s*?no-cache\s*?(?:,|$)/ /** - * Application prototype. + * Module exports. + * @public */ -var app = exports = module.exports = {}; +module.exports = fresh /** - * Variable for trust proxy inheritance back-compat - * @private + * Check freshness of the response using request and response headers. + * + * @param {Object} reqHeaders + * @param {Object} resHeaders + * @return {Boolean} + * @public */ -var trustProxyDefaultSymbol = '@@symbol:trust_proxy_default'; +function fresh (reqHeaders, resHeaders) { + // fields + var modifiedSince = reqHeaders['if-modified-since'] + var noneMatch = reqHeaders['if-none-match'] + + // unconditional request + if (!modifiedSince && !noneMatch) { + return false + } + + // 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 + } + + // if-none-match + if (noneMatch && noneMatch !== '*') { + var etag = resHeaders['etag'] + + if (!etag) { + return false + } + + 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 (etagStale) { + return false + } + } + + // if-modified-since + if (modifiedSince) { + var lastModified = resHeaders['last-modified'] + var modifiedStale = !lastModified || !(parseHttpDate(lastModified) <= parseHttpDate(modifiedSince)) + + if (modifiedStale) { + return false + } + } + + return true +} /** - * Initialize the server. - * - * - setup default configuration - * - setup default middleware - * - setup route reflection methods + * Parse an HTTP Date into a number. * + * @param {string} date * @private */ -app.init = function init() { - this.cache = {}; - this.engines = {}; - this.settings = {}; +function parseHttpDate (date) { + var timestamp = date && Date.parse(date) - this.defaultConfiguration(); -}; + // istanbul ignore next: guard against date.js Date.parse patching + return typeof timestamp === 'number' + ? timestamp + : NaN +} /** - * Initialize application configuration. + * Parse a HTTP token list. + * + * @param {string} str * @private */ -app.defaultConfiguration = function defaultConfiguration() { - var env = process.env.NODE_ENV || 'development'; +function parseTokenList (str) { + var end = 0 + var list = [] + var start = 0 - // 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); + // 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 + } + } - // trust proxy inherit back-compat - Object.defineProperty(this.settings, trustProxyDefaultSymbol, { - configurable: true, - value: true - }); + // final token + list.push(str.substring(start, end)) - debug('booting in %s mode', env); + return list +} - 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); +/***/ 19320: +/***/ ((module) => { - // top-most app is mounted at / - this.mountpath = '/'; +"use strict"; - // default locals - this.locals.settings = this.settings; - // default configuration - this.set('view', View); - this.set('views', resolve('views')); - this.set('jsonp callback name', 'callback'); +/* eslint no-invalid-this: 1 */ - if (env === 'production') { - this.enable('view cache'); - } +var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; +var slice = Array.prototype.slice; +var toStr = Object.prototype.toString; +var funcType = '[object Function]'; - 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.'); +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); -/** - * 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 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)) + ); + } + }; - this._router.use(query(this.get('query parser fn'))); - this._router.use(middleware.init(this)); - } + var boundLength = Math.max(0, target.length - args.length); + var boundArgs = []; + for (var i = 0; i < boundLength; i++) { + boundArgs.push('$' + i); + } + + bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder); + + if (target.prototype) { + var Empty = function Empty() {}; + Empty.prototype = target.prototype; + bound.prototype = new Empty(); + Empty.prototype = null; + } + + return bound; }; -/** - * 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 - */ -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) - }); +/***/ 88334: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // no routes - if (!router) { - debug('no routes defined on app'); - done(); - return; - } +"use strict"; - router.handle(req, res, done); + +var implementation = __nccwpck_require__(19320); + +module.exports = Function.prototype.bind || implementation; + + +/***/ }), + +/***/ 31621: +/***/ ((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); }; -/** - * 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 = '/'; +/***/ }), - // default path to '/' - // disambiguate app.use([fn]) - if (typeof fn !== 'function') { - var arg = fn; +/***/ 76339: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - while (Array.isArray(arg) && arg.length !== 0) { - arg = arg[0]; - } +"use strict"; - // first arg is the path - if (typeof arg !== 'function') { - offset = 1; - path = fn; - } - } - var fns = flatten(slice.call(arguments, offset)); +var bind = __nccwpck_require__(88334); - if (fns.length === 0) { - throw new TypeError('app.use() requires a middleware function') - } +module.exports = bind.call(Function.call, Object.prototype.hasOwnProperty); - // 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; +/***/ 95193: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // 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); - }); - }); +"use strict"; +/*! + * http-errors + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2016 Douglas Christopher Wilson + * MIT Licensed + */ - // mounted an app - fn.emit('mount', this); - }, this); - return this; -}; /** - * 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 dependencies. + * @private */ -app.route = function route(path) { - this.lazyrouter(); - return this._router.route(path); -}; +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) /** - * 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 dont 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 + * Module exports. * @public */ -app.engine = function engine(ext, fn) { - if (typeof fn !== 'function') { - throw new Error('callback function required'); - } +module.exports = createError +module.exports.HttpError = createHttpErrorConstructor() - // get file extension - var extension = ext[0] !== '.' - ? '.' + ext - : ext; +// Populate exports for all constructors +populateConstructorExports(module.exports, statuses.codes, module.exports.HttpError) - // store engine - this.engines[extension] = fn; +/** + * Get the code class of a status code. + * @private + */ - return this; -}; +function codeClass (status) { + return Number(String(status).charAt(0) + '00') +} /** - * 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. + * Create a new HTTP Error. * - * @param {String|Array} name - * @param {Function} fn - * @return {app} for chaining + * @returns {Error} * @public */ -app.param = function param(name, fn) { - this.lazyrouter(); +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 + } + } + + if (typeof status === 'number' && (status < 400 || status >= 600)) { + deprecate('non-error status code; use only 4xx or 5xx status codes') + } + + if (typeof status !== 'number' || + (!statuses[status] && (status < 400 || status >= 600))) { + status = 500 + } + + // 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 + } - if (Array.isArray(name)) { - for (var i = 0; i < name.length; i++) { - this.param(name[i], fn); + for (var key in props) { + if (key !== 'status' && key !== 'statusCode') { + err[key] = props[key] } + } - return this; + return err +} + +/** + * Create HTTP error abstract base class. + * @private + */ + +function createHttpErrorConstructor () { + function HttpError () { + throw new TypeError('cannot construct abstract class') } - this._router.param(name, fn); + inherits(HttpError, Error) - return this; -}; + return HttpError +} /** - * 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 + * Create a constructor for a client error. + * @private */ -app.set = function set(setting, val) { - if (arguments.length === 1) { - // app.get(setting) - return this.settings[setting]; - } +function createClientErrorConstructor (HttpError, name, code) { + var className = name.match(/Error$/) ? name : name + 'Error' - debug('set "%s" to %o', setting, val); + function ClientError (message) { + // create the error object + var msg = message != null ? message : statuses[code] + var err = new Error(msg) - // set value - this.settings[setting] = val; + // capture a stack trace to the construction point + Error.captureStackTrace(err, ClientError) - // 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)); + // adjust the [[Prototype]] + setPrototypeOf(err, ClientError.prototype) - // trust proxy inherit back-compat - Object.defineProperty(this.settings, trustProxyDefaultSymbol, { - configurable: true, - value: false - }); + // redefine the error message + Object.defineProperty(err, 'message', { + enumerable: true, + configurable: true, + value: msg, + writable: true + }) - break; + // redefine the error name + Object.defineProperty(err, 'name', { + enumerable: false, + configurable: true, + value: className, + writable: true + }) + + return err } - return this; -}; + inherits(ClientError, HttpError) + nameFunc(ClientError, className) + + ClientError.prototype.status = code + ClientError.prototype.statusCode = code + ClientError.prototype.expose = true + + return ClientError +} /** - * 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} + * Create a constructor for a server error. * @private */ -app.path = function path() { - return this.parent - ? this.parent.path() + this.mountpath - : ''; -}; +function createServerErrorConstructor (HttpError, name, code) { + var className = name.match(/Error$/) ? name : name + 'Error' -/** - * Check if `setting` is enabled (truthy). - * - * app.enabled('foo') - * // => false - * - * app.enable('foo') - * app.enabled('foo') - * // => true - * - * @param {String} setting - * @return {Boolean} - * @public - */ + function ServerError (message) { + // create the error object + var msg = message != null ? message : statuses[code] + var err = new Error(msg) -app.enabled = function enabled(setting) { - return Boolean(this.set(setting)); -}; + // capture a stack trace to the construction point + Error.captureStackTrace(err, ServerError) -/** - * Check if `setting` is disabled. - * - * app.disabled('foo') - * // => true - * - * app.enable('foo') - * app.disabled('foo') - * // => false - * - * @param {String} setting - * @return {Boolean} - * @public - */ + // adjust the [[Prototype]] + setPrototypeOf(err, ServerError.prototype) -app.disabled = function disabled(setting) { - return !this.set(setting); -}; + // redefine the error message + Object.defineProperty(err, 'message', { + enumerable: true, + configurable: true, + value: msg, + writable: true + }) -/** - * Enable `setting`. - * - * @param {String} setting - * @return {app} for chaining - * @public - */ + // redefine the error name + Object.defineProperty(err, 'name', { + enumerable: false, + configurable: true, + value: className, + writable: true + }) -app.enable = function enable(setting) { - return this.set(setting, true); -}; + return err + } -/** - * Disable `setting`. - * - * @param {String} setting - * @return {app} for chaining - * @public - */ + inherits(ServerError, HttpError) + nameFunc(ServerError, className) -app.disable = function disable(setting) { - return this.set(setting, false); -}; + ServerError.prototype.status = code + ServerError.prototype.statusCode = code + ServerError.prototype.expose = false + + return ServerError +} /** - * Delegate `.VERB(...)` calls to `router.VERB(...)`. + * Set the name of a function, if possible. + * @private */ -methods.forEach(function(method){ - app[method] = function(path){ - if (method === 'get' && arguments.length === 1) { - // app.get(setting) - return this.set(path); - } - - this.lazyrouter(); +function nameFunc (func, name) { + var desc = Object.getOwnPropertyDescriptor(func, 'name') - var route = this._router.route(path); - route[method].apply(route, slice.call(arguments, 1)); - return this; - }; -}); + if (desc && desc.configurable) { + desc.value = name + Object.defineProperty(func, 'name', desc) + } +} /** - * 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 + * Populate the exports object with constructors for every error class. + * @private */ -app.all = function all(path) { - this.lazyrouter(); +function populateConstructorExports (exports, codes, HttpError) { + codes.forEach(function forEachCode (code) { + var CodeError + var name = toIdentifier(statuses[code]) - var route = this._router.route(path); - var args = slice.call(arguments, 1); + switch (codeClass(code)) { + case 400: + CodeError = createClientErrorConstructor(HttpError, name, code) + break + case 500: + CodeError = createServerErrorConstructor(HttpError, name, code) + break + } - for (var i = 0; i < methods.length; i++) { - route[methods[i]].apply(route, args); - } + if (CodeError) { + // export the constructor + exports[code] = CodeError + exports[name] = CodeError + } + }) - return this; -}; + // backwards-compatibility + exports["I'mateapot"] = deprecate.function(exports.ImATeapot, + '"I\'mateapot"; use "ImATeapot" instead') +} -// del -> delete alias -app.del = deprecate.function(app.delete, 'app.del: Use app.delete instead'); +/***/ }), + +/***/ 15098: +/***/ (function(__unused_webpack_module, 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()); + }); +}; +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'); /** - * Render the given view `name` name with `options` - * and a callback accepting an error and the - * rendered template string. + * The `HttpsProxyAgent` implements an HTTP Agent subclass that connects to + * the specified "HTTP(s) proxy server" in order to proxy HTTPS requests. * - * Example: + * 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. * - * app.render('email', { name: 'Tobi' }, function(err, html){ - * // ... - * }) + * `https:` requests have their socket connection upgraded to TLS once + * the connection to the proxy server has been established. * - * @param {String} name - * @param {Object|Function} options or fn - * @param {Function} callback - * @public + * @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 -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; - - // support callback function as second arg - if (typeof options === 'function') { - done = options; - opts = {}; - } - - // merge app.locals - merge(renderOptions, this.locals); - - // merge options._locals - if (opts._locals) { - merge(renderOptions, opts._locals); - } - - // merge options - merge(renderOptions, opts); +/***/ }), - // set .cache unless explicitly provided - if (renderOptions.cache == null) { - renderOptions.cache = this.enabled('view cache'); - } +/***/ 77219: +/***/ (function(module, __unused_webpack_exports, __nccwpck_require__) { - // primed cache - if (renderOptions.cache) { - view = cache[name]; - } +"use strict"; - // view - if (!view) { - var View = this.get('view'); +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 - 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); - } +/***/ 595: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - // prime the cache - if (renderOptions.cache) { - cache[name] = view; - } - } +"use strict"; - // render - tryRender(view, renderOptions, done); +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 -/** - * 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 - */ +/***/ }), -app.listen = function listen() { - var server = http.createServer(this); - return server.listen.apply(server, arguments); -}; +/***/ 39695: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -/** - * Log error using console.error. - * - * @param {Error} err - * @private - */ +"use strict"; -function logerror(err) { - /* istanbul ignore next */ - if (this.get('env') !== 'test') console.error(err.stack || err.toString()); -} +var Buffer = (__nccwpck_require__(15118).Buffer); -/** - * Try rendering a view. - * @private - */ +// 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. -function tryRender(view, options, callback) { - try { - view.render(options, callback); - } catch (err) { - callback(err); - } -} +exports._dbcs = DBCSCodec; +var UNASSIGNED = -1, + GB18030_CODE = -2, + SEQ_START = -10, + NODE_START = -1000, + UNASSIGNED_NODE = new Array(0x100), + DEF_CHAR = -1; -/***/ }), +for (var i = 0; i < 0x100; i++) + UNASSIGNED_NODE[i] = UNASSIGNED; -/***/ 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 - */ +// 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."); + // Load tables. + var mappingTable = codecOptions.table(); -/** - * Module dependencies. - */ + // Decode tables: MBCS -> Unicode. -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); + // 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. -/** - * Expose `createApplication()`. - */ + // Sometimes a MBCS char corresponds to a sequence of unicode chars. We store them as arrays of integers here. + this.decodeTableSeq = []; -exports = module.exports = createApplication; + // 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]); -/** - * Create an express application. - * - * @return {Function} - * @api public - */ + this.defaultCharUnicode = iconv.defaultCharUnicode; -function createApplication() { - var app = function(req, res, next) { - app.handle(req, res, next); - }; + + // Encode tables: Unicode -> DBCS. - mixin(app, EventEmitter.prototype, false); - mixin(app, proto, false); + // `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 = []; - // expose the prototype that will get set on requests - app.request = Object.create(req, { - app: { configurable: true, enumerable: true, writable: true, value: app } - }) + // 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); - // expose the prototype that will get set on responses - app.response = Object.create(res, { - app: { configurable: true, enumerable: true, writable: true, value: app } - }) + // 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]); + } - app.init(); - return app; -} + 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); -/** - * Expose the prototypes. - */ -exports.application = proto; -exports.request = req; -exports.response = res; + // Load & create GB18030 tables when needed. + if (typeof codecOptions.gb18030 === 'function') { + this.gb18030 = codecOptions.gb18030(); // Load GB18030 ranges. -/** - * Expose constructors. - */ + // Add GB18030 decode tables. + var thirdByteNodeIdx = this.decodeTables.length; + var thirdByteNode = this.decodeTables[thirdByteNodeIdx] = UNASSIGNED_NODE.slice(0); -exports.Route = Route; -exports.Router = Router; + var fourthByteNodeIdx = this.decodeTables.length; + var fourthByteNode = this.decodeTables[fourthByteNodeIdx] = UNASSIGNED_NODE.slice(0); -/** - * Expose middleware - */ + 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 + } +} -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 +DBCSCodec.prototype.encoder = DBCSEncoder; +DBCSCodec.prototype.decoder = DBCSDecoder; -/** - * Replace removed middleware with an appropriate error message. - */ +// 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); -var removedMiddlewares = [ - 'bodyParser', - 'compress', - 'cookieSession', - 'session', - 'logger', - 'cookieParser', - 'favicon', - 'responseTime', - 'errorHandler', - 'timeout', - 'methodOverride', - 'vhost', - 'csrf', - 'directory', - 'limit', - 'multipart', - 'staticCache' -] + 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]]; -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 (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; +} -/***/ }), +DBCSCodec.prototype._addDecodeChunk = function(chunk) { + // First element of chunk is the hex mbcs code where we start. + var curAddr = parseInt(chunk[0], 16); -/***/ 92636: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + // Choose the decoding node where we'll write our chars. + var writeTable = this._getDecodeTrieNode(curAddr); + curAddr = curAddr & 0xFF; -"use strict"; -/*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2013 Roman Shtylman - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ + // 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. + 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); +} +// 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]; +} -/** - * Module dependencies. - * @private - */ +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 setPrototypeOf = __nccwpck_require__(40414) +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; -/** - * 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 - */ + 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); + } -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; + // 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 { + node = node[uCode] = {} + if (oldVal !== undefined) + node[DEF_CHAR] = oldVal + } + } - setPrototypeOf(req, app.request) - setPrototypeOf(res, app.response) + // Set the leaf to given dbcsCode. + uCode = seq[seq.length-1]; + node[uCode] = dbcsCode; +} - res.locals = res.locals || Object.create(null); +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; - next(); - }; -}; + 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); + } +} -/***/ }), +// == Encoder ================================================================== -/***/ 79768: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +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; +} -"use strict"; -/*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2013 Roman Shtylman - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ +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; + } -/** - * Module dependencies. - */ + // 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 merge = __nccwpck_require__(44429) -var parseUrl = __nccwpck_require__(89808); -var qs = __nccwpck_require__(22760); + } else if (typeof resCode == 'number') { // Sequence finished. Write it. + dbcsCode = resCode; -/** - * @param {Object} options - * @return {Function} - * @api public - */ + } else if (resCode == undefined) { // Current character is not part of the sequence. -module.exports = function query(options) { - var opts = merge({}, options) - var queryparse = qs.parse; + // 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. - if (typeof options === 'function') { - queryparse = options; - opts = undefined; - } + } 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 (opts !== undefined && opts.allowPrototypes === undefined) { - // back-compat for qs module - opts.allowPrototypes = true; - } + 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; + } + } + } - return function query(req, res, next){ - if (!req.query) { - var val = parseUrl(req).query; - req.query = queryparse(val, opts); + // 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; + } } - next(); - }; -}; + this.seqObj = seqObj; + this.leadSurrogate = leadSurrogate; + return newBuf.slice(0, j); +} +DBCSEncoder.prototype.end = function() { + if (this.leadSurrogate === -1 && this.seqObj === undefined) + return; // All clean. Most often case. -/***/ }), + var newBuf = Buffer.alloc(10), j = 0; -/***/ 71260: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + 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; + } -"use strict"; -/*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2013 Roman Shtylman - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ + if (this.leadSurrogate !== -1) { + // Incomplete surrogate pair - only lead surrogate found. + newBuf[j++] = this.defaultCharSingleByte; + this.leadSurrogate = -1; + } + + return newBuf.slice(0, j); +} +// Export for testing +DBCSEncoder.prototype.findIdx = findIdx; -/** - * Module dependencies. - * @private - */ +// == Decoder ================================================================== -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); +function DBCSDecoder(options, codec) { + // Decoder state + this.nodeIdx = 0; + this.prevBuf = Buffer.alloc(0); -/** - * Request prototype. - * @public - */ + // Static data + this.decodeTables = codec.decodeTables; + this.decodeTableSeq = codec.decodeTableSeq; + this.defaultCharUnicode = codec.defaultCharUnicode; + this.gb18030 = codec.gb18030; +} -var req = Object.create(http.IncomingMessage.prototype) +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; -/** - * Module exports. - * @public - */ + 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]; -module.exports = req + // Lookup in current trie node. + var uCode = this.decodeTables[nodeIdx][curByte]; -/** - * Return request header. - * - * 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()`. - * - * @param {String} name - * @return {String} - * @public - */ + 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); -req.get = -req.header = function header(name) { - if (!name) { - throw new TypeError('name argument is required to req.get'); - } + // 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; - if (typeof name !== 'string') { - throw new TypeError('name must be a string to req.get'); - } + uCode = 0xDC00 + uCode % 0x400; + } + newBuf[j++] = uCode & 0xFF; + newBuf[j++] = uCode >> 8; - var lc = name.toLowerCase(); + // Reset trie node. + nodeIdx = 0; seqStart = i+1; + } - switch (lc) { - case 'referer': - case 'referrer': - return this.headers.referrer - || this.headers.referer; - default: - return this.headers[lc]; - } -}; + this.nodeIdx = nodeIdx; + this.prevBuf = (seqStart >= 0) ? buf.slice(seqStart) : prevBuf.slice(seqStart + prevBufOffset); + return newBuf.slice(0, j).toString('ucs2'); +} -/** - * 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 - * - * // 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 - */ +DBCSDecoder.prototype.end = function() { + var ret = ''; -req.accepts = function(){ - var accept = accepts(this); - return accept.types.apply(accept, arguments); -}; + // 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); -/** - * Check if the given `encoding`s are accepted. - * - * @param {String} ...encoding - * @return {String|Array} - * @public - */ + // Parse remaining as usual. + this.prevBuf = Buffer.alloc(0); + this.nodeIdx = 0; + if (buf.length > 0) + ret += this.write(buf); + } -req.acceptsEncodings = function(){ - var accept = accepts(this); - return accept.encodings.apply(accept, arguments); -}; + this.nodeIdx = 0; + return ret; +} -req.acceptsEncoding = deprecate.function(req.acceptsEncodings, - 'req.acceptsEncoding: Use acceptsEncodings instead'); +// Binary search for GB18030. Returns largest i such that table[i] <= val. +function findIdx(table, val) { + if (table[0] > val) + return -1; -/** - * Check if the given `charset`s are acceptable, - * otherwise you should respond with 406 "Not Acceptable". - * - * @param {String} ...charset - * @return {String|Array} - * @public - */ + 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 l; +} -req.acceptsCharsets = function(){ - var accept = accepts(this); - return accept.charsets.apply(accept, arguments); -}; -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". - * - * @param {String} ...lang - * @return {String|Array} - * @public - */ +/***/ }), -req.acceptsLanguages = function(){ - var accept = accepts(this); - return accept.languages.apply(accept, arguments); -}; +/***/ 91386: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -req.acceptsLanguage = deprecate.function(req.acceptsLanguages, - 'req.acceptsLanguage: Use acceptsLanguages instead'); +"use strict"; -/** - * 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. - * - * 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 - */ -req.range = function range(size, options) { - var range = this.get('Range'); - if (!range) return; - return parseRange(size, range, options); -}; +// 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. -/** - * 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 - */ +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) -req.param = function param(name, defaultValue) { - var params = this.params || {}; - var body = this.body || {}; - var query = this.query || {}; + // 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 args = arguments.length === 1 - ? 'name' - : 'name, default'; - deprecate('req.param(' + args + '): Use req.params, req.body, or req.query instead'); + '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', - if (null != params[name] && params.hasOwnProperty(name)) return params[name]; - if (null != body[name]) return body[name]; - if (null != query[name]) return query[name]; + 'eucjp': { + type: '_dbcs', + table: function() { return __nccwpck_require__(31532) }, + encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E}, + }, - return defaultValue; -}; + // 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. -/** - * Check if the incoming request contains the "Content-Type" - * header field, and it contains the give 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 - * - * req.is('html'); - * // => false - * - * @param {String|Array} types... - * @return {String|false|null} - * @public - */ -req.is = function is(types) { - var arr = types; + // == Chinese/GBK ========================================================== + // http://en.wikipedia.org/wiki/GBK + // We mostly implement W3C recommendation: https://www.w3.org/TR/encoding/#gbk-encoder - // support flattened arguments - if (!Array.isArray(types)) { - arr = new Array(arguments.length); - for (var i = 0; i < arr.length; i++) { - arr[i] = arguments[i]; - } - } + // Oldest GB2312 (1981, ~7600 chars) is a subset of CP936 + 'gb2312': 'cp936', + 'gb231280': 'cp936', + 'gb23121980': 'cp936', + 'csgb2312': 'cp936', + 'csiso58gb231280': 'cp936', + 'euccn': 'cp936', - return typeis(this, arr); -}; + // 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) }, + }, -/** - * 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. - * - * If you're running behind a reverse proxy that - * supplies https for you this may be enabled. - * - * @return {String} - * @public - */ + // 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', -defineGetter(req, 'protocol', function protocol(){ - var proto = this.connection.encrypted - ? 'https' - : 'http'; - var trust = this.app.get('trust proxy fn'); + // 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}, + }, - if (!trust(this.connection.remoteAddress, 0)) { - return proto; - } + 'chinese': 'gb18030', - // 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() -}); + // == 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) }, + }, -/** - * Short-hand for: - * - * req.protocol === 'https' - * - * @return {Boolean} - * @public - */ + 'cseuckr': 'cp949', + 'csksc56011987': 'cp949', + 'euckr': 'cp949', + 'isoir149': 'cp949', + 'korean': 'cp949', + 'ksc56011987': 'cp949', + 'ksc56011989': 'cp949', + 'ksc5601': 'cp949', -defineGetter(req, 'secure', function secure(){ - return this.protocol === 'https'; -}); -/** - * Return the remote address from the trusted proxy. - * - * The is the remote address on the socket unless - * "trust proxy" is set. - * - * @return {String} - * @public - */ + // == 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. -defineGetter(req, 'ip', function ip(){ - var trust = this.app.get('trust proxy fn'); - return proxyaddr(this, trust); -}); + 'windows950': 'cp950', + 'ms950': 'cp950', + '950': 'cp950', + 'cp950': { + type: '_dbcs', + table: function() { return __nccwpck_require__(74284) }, + }, -/** - * When "trust proxy" is set, trusted proxy addresses + client. - * - * 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 - */ + // 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], + }, -defineGetter(req, 'ips', function ips() { - var trust = this.app.get('trust proxy fn'); - var addrs = proxyaddr.all(this, trust); + 'cnbig5': 'big5hkscs', + 'csbig5': 'big5hkscs', + 'xxbig5': 'big5hkscs', +}; - // reverse the order (to farthest -> closest) - // and remove socket address - addrs.reverse().pop() - return addrs -}); +/***/ }), -/** - * 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"]`. - * - * @return {Array} - * @public - */ +/***/ 82733: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -defineGetter(req, 'subdomains', function subdomains() { - var hostname = this.hostname; +"use strict"; - if (!hostname) return []; - var offset = this.app.get('subdomain offset'); - var subdomains = !isIP(hostname) - ? hostname.split('.').reverse() - : [hostname]; +// 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), +]; - return subdomains.slice(offset); -}); +// 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]; +} -/** - * Short-hand for `url.parse(req.url).pathname`. - * - * @return {String} - * @public - */ -defineGetter(req, 'path', function path() { - return parse(this).pathname; -}); +/***/ }), -/** - * 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. - * - * @return {String} - * @public - */ +/***/ 12376: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -defineGetter(req, 'hostname', function hostname(){ - var trust = this.app.get('trust proxy fn'); - var host = this.get('X-Forwarded-Host'); +"use strict"; - 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() - } +var Buffer = (__nccwpck_require__(15118).Buffer); - if (!host) return; +// Export Node.js internal encodings. - // IPv6 literal support - var offset = host[0] === '[' - ? host.indexOf(']') + 1 - : 0; - var index = host.indexOf(':', offset); +module.exports = { + // Encodings + utf8: { type: "_internal", bomAware: true}, + cesu8: { type: "_internal", bomAware: true}, + unicode11utf8: "utf8", - return index !== -1 - ? host.substring(0, index) - : host; -}); + ucs2: { type: "_internal", bomAware: true}, + utf16le: "ucs2", -// TODO: change req.host to return host in next major + binary: { type: "_internal" }, + base64: { type: "_internal" }, + hex: { type: "_internal" }, -defineGetter(req, 'host', deprecate.function(function host(){ - return this.hostname; -}, 'req.host: Use req.hostname instead')); + // Codec. + _internal: InternalCodec, +}; -/** - * Check if the request is fresh, aka - * Last-Modified and/or the ETag - * still match. - * - * @return {Boolean} - * @public - */ +//------------------------------------------------------------------------------ -defineGetter(req, 'fresh', function(){ - var method = this.method; - var res = this.res - var status = res.statusCode +function InternalCodec(codecOptions, iconv) { + this.enc = codecOptions.encodingName; + this.bomAware = codecOptions.bomAware; - // GET or HEAD for weak freshness validation only - if ('GET' !== method && 'HEAD' !== method) return false; + if (this.enc === "base64") + this.encoder = InternalEncoderBase64; + else if (this.enc === "cesu8") { + this.enc = "utf8"; // Use utf8 for decoding. + this.encoder = InternalEncoderCesu8; - // 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') - }) - } + // Add decoder for versions of Node not supporting CESU-8 + if (Buffer.from('eda0bdedb2a9', 'hex').toString() !== '💩') { + this.decoder = InternalDecoderCesu8; + this.defaultCharUnicode = iconv.defaultCharUnicode; + } + } +} - return false; -}); +InternalCodec.prototype.encoder = InternalEncoder; +InternalCodec.prototype.decoder = InternalDecoder; -/** - * Check if the request is stale, aka - * "Last-Modified" and / or the "ETag" for the - * resource has changed. - * - * @return {Boolean} - * @public - */ +//------------------------------------------------------------------------------ -defineGetter(req, 'stale', function stale(){ - return !this.fresh; -}); +// We use node.js internal decoder. Its signature is the same as ours. +var StringDecoder = (__nccwpck_require__(71576).StringDecoder); -/** - * Check if the request was an _XMLHttpRequest_. - * - * @return {Boolean} - * @public - */ +if (!StringDecoder.prototype.end) // Node v0.8 doesn't have this method. + StringDecoder.prototype.end = function() {}; -defineGetter(req, 'xhr', function xhr(){ - var val = this.get('X-Requested-With') || ''; - return val.toLowerCase() === 'xmlhttprequest'; -}); -/** - * Helper function for creating a getter on an object. - * - * @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 - }); +function InternalDecoder(options, codec) { + StringDecoder.call(this, codec.enc); } +InternalDecoder.prototype = StringDecoder.prototype; -/***/ }), - -/***/ 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 - */ +//------------------------------------------------------------------------------ +// Encoder is mostly trivial +function InternalEncoder(options, codec) { + this.enc = codec.enc; +} +InternalEncoder.prototype.write = function(str) { + return Buffer.from(str, this.enc); +} -/** - * Module dependencies. - * @private - */ +InternalEncoder.prototype.end = function() { +} -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__(92098); -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. - * @public - */ +//------------------------------------------------------------------------------ +// Except base64 encoder, which must keep its state. -var res = Object.create(http.ServerResponse.prototype) +function InternalEncoderBase64(options, codec) { + this.prevStr = ''; +} -/** - * Module exports. - * @public - */ +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); -module.exports = res + return Buffer.from(str, "base64"); +} -/** - * Module variables. - * @private - */ +InternalEncoderBase64.prototype.end = function() { + return Buffer.from(this.prevStr, "base64"); +} -var charsetRegExp = /;\s*charset\s*=/; -/** - * Set status `code`. - * - * @param {Number} code - * @return {ServerResponse} - * @public - */ +//------------------------------------------------------------------------------ +// CESU-8 encoder is also special. -res.status = function status(code) { - this.statusCode = code; - return this; -}; +function InternalEncoderCesu8(options, codec) { +} -/** - * 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 - */ +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); +} -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(', ')); -}; +InternalEncoderCesu8.prototype.end = function() { +} -/** - * 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 - */ +//------------------------------------------------------------------------------ +// CESU-8 decoder is not implemented in Node v4.0+ -res.send = function send(body) { - var chunk = body; - var encoding; - var req = this.req; - var type; +function InternalDecoderCesu8(options, codec) { + this.acc = 0; + this.contBytes = 0; + this.accBytes = 0; + this.defaultCharUnicode = codec.defaultCharUnicode; +} - // settings - var app = this.app; +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; + } - // 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]; + 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; + } + } } - } + this.acc = acc; this.contBytes = contBytes; this.accBytes = accBytes; + return res; +} - // 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'); - } +InternalDecoderCesu8.prototype.end = function() { + var res = 0; + if (this.contBytes > 0) + res += this.defaultCharUnicode; + return res; +} - 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'); +/***/ 26657: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // reflect this in content-type - if (typeof type === 'string') { - this.set('Content-Type', setCharset(type, 'utf-8')); - } - } +"use strict"; - // determine if ETag should be generated - var etagFn = app.get('etag fn') - var generateETag = !this.get('ETag') && typeof etagFn === 'function' +var Buffer = (__nccwpck_require__(15118).Buffer); - // 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 +// 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._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; } - this.set('Content-Length', len); - } + this.decodeBuf = Buffer.from(codecOptions.chars, 'ucs2'); + + // Encoding buffer. + var encodeBuf = Buffer.alloc(65536, iconv.defaultCharSingleByte.charCodeAt(0)); - // populate ETag - var etag; - if (generateETag && len !== undefined) { - if ((etag = etagFn(chunk, encoding))) { - this.set('ETag', etag); - } - } + for (var i = 0; i < codecOptions.chars.length; i++) + encodeBuf[codecOptions.chars.charCodeAt(i)] = i; - // freshness - if (req.fresh) this.statusCode = 304; + this.encodeBuf = encodeBuf; +} - // strip irrelevant headers - if (204 === this.statusCode || 304 === this.statusCode) { - this.removeHeader('Content-Type'); - this.removeHeader('Content-Length'); - this.removeHeader('Transfer-Encoding'); - chunk = ''; - } +SBCSCodec.prototype.encoder = SBCSEncoder; +SBCSCodec.prototype.decoder = SBCSDecoder; - if (req.method === 'HEAD') { - // skip body for HEAD - this.end(); - } else { - // respond - this.end(chunk, encoding); - } - return this; -}; +function SBCSEncoder(options, codec) { + this.encodeBuf = codec.encodeBuf; +} -/** - * Send JSON response. - * - * Examples: - * - * res.json(null); - * res.json({ user: 'tj' }); - * - * @param {string|number|boolean|object} obj - * @public - */ +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; +} -res.json = function json(obj) { - var val = obj; +SBCSEncoder.prototype.end = function() { +} - // 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) +function SBCSDecoder(options, codec) { + this.decodeBuf = codec.decodeBuf; +} - // content-type - if (!this.get('Content-Type')) { - this.set('Content-Type', 'application/json'); - } +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'); +} - return this.send(body); -}; +SBCSDecoder.prototype.end = function() { +} -/** - * Send JSON response with JSONP callback support. - * - * Examples: - * - * res.jsonp(null); - * res.jsonp({ user: 'tj' }); - * - * @param {string|number|boolean|object} obj - * @public - */ -res.jsonp = function jsonp(obj) { - var val = obj; +/***/ }), - // allow status / body - if (arguments.length === 2) { - // res.json(body, status) backwards compat - if (typeof arguments[1] === 'number') { - deprecate('res.jsonp(obj, status): Use res.status(status).json(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]; - } - } +/***/ 21012: +/***/ ((module) => { - // 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')]; +"use strict"; - // content-type - if (!this.get('Content-Type')) { - this.set('X-Content-Type-Options', 'nosniff'); - this.set('Content-Type', 'application/json'); - } - // fixup callback - if (Array.isArray(callback)) { - callback = callback[0]; +// 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": "���������������������������������กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" } +} - // 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, ''); - - // 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 + ');'; - } +/***/ }), - return this.send(body); -}; +/***/ 41080: +/***/ ((module) => { -/** - * 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 - */ +"use strict"; -res.sendStatus = function sendStatus(statusCode) { - var body = statuses[statusCode] || String(statusCode) - this.statusCode = statusCode; - this.type('txt'); +// Manually added data to be used by sbcs codec in addition to generated one. - return this.send(body); -}; +module.exports = { + // Not supported by iconv, not sure why. + "10029": "maccenteuro", + "maccenteuro": { + "type": "_sbcs", + "chars": "ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ" + }, -/** - * 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.sentHeader` - * 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 - */ + "808": "cp808", + "ibm808": "cp808", + "cp808": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№€■ " + }, -res.sendFile = function sendFile(path, options, callback) { - var done = callback; - var req = this.req; - var res = this; - var next = req.next; - var opts = options || {}; + "mik": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя└┴┬├─┼╣║╚╔╩╦╠═╬┐░▒▓│┤№§╗╝┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, - if (!path) { - throw new TypeError('path argument is required to res.sendFile'); - } + // 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", - if (typeof path !== 'string') { - throw new TypeError('path must be a string to res.sendFile') - } + "latin1": "iso88591", + "latin2": "iso88592", + "latin3": "iso88593", + "latin4": "iso88594", + "latin5": "iso88599", + "latin6": "iso885910", + "latin7": "iso885913", + "latin8": "iso885914", + "latin9": "iso885915", + "latin10": "iso885916", - // support function as second arg - if (typeof options === 'function') { - done = options; - opts = {}; - } + "csisolatin1": "iso88591", + "csisolatin2": "iso88592", + "csisolatin3": "iso88593", + "csisolatin4": "iso88594", + "csisolatincyrillic": "iso88595", + "csisolatinarabic": "iso88596", + "csisolatingreek" : "iso88597", + "csisolatinhebrew": "iso88598", + "csisolatin5": "iso88599", + "csisolatin6": "iso885910", - if (!opts.root && !isAbsolute(path)) { - throw new TypeError('path must be absolute or specify root to res.sendFile'); - } + "l1": "iso88591", + "l2": "iso88592", + "l3": "iso88593", + "l4": "iso88594", + "l5": "iso88599", + "l6": "iso885910", + "l7": "iso885913", + "l8": "iso885914", + "l9": "iso885915", + "l10": "iso885916", - // create file stream - var pathname = encodeURI(path); - var file = send(req, pathname, opts); + "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", - // transfer - sendfile(res, file, opts, function (err) { - if (done) return done(err); - if (err && err.code === 'EISDIR') return next(); + "cp819": "iso88591", + "ibm819": "iso88591", - // next() all but write errors - if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') { - next(err); - } - }); -}; + "cyrillic": "iso88595", -/** - * 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.sentHeader` - * 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 - */ + "arabic": "iso88596", + "arabic8": "iso88596", + "ecma114": "iso88596", + "asmo708": "iso88596", -res.sendfile = function (path, options, callback) { - var done = callback; - var req = this.req; - var res = this; - var next = req.next; - var opts = options || {}; + "greek" : "iso88597", + "greek8" : "iso88597", + "ecma118" : "iso88597", + "elot928" : "iso88597", - // support function as second arg - if (typeof options === 'function') { - done = options; - opts = {}; - } + "hebrew": "iso88598", + "hebrew8": "iso88598", - // create file stream - var file = send(req, path, opts); + "turkish": "iso88599", + "turkish8": "iso88599", - // transfer - sendfile(res, file, opts, function (err) { - if (done) return done(err); - if (err && err.code === 'EISDIR') return next(); + "thai": "iso885911", + "thai8": "iso885911", - // next() all but write errors - if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') { - next(err); - } - }); -}; + "celtic": "iso885914", + "celtic8": "iso885914", + "isoceltic": "iso885914", -res.sendfile = deprecate.function(res.sendfile, - 'res.sendfile: Use res.sendFile instead'); + "tis6200": "tis620", + "tis62025291": "tis620", + "tis62025330": "tis620", -/** - * 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 - */ + "10000": "macroman", + "10006": "macgreek", + "10007": "maccyrillic", + "10079": "maciceland", + "10081": "macturkish", -res.download = function download (path, filename, options, callback) { - var done = callback; - var name = filename; - var opts = options || null + "cspc8codepage437": "cp437", + "cspc775baltic": "cp775", + "cspc850multilingual": "cp850", + "cspcp852": "cp852", + "cspc862latinhebrew": "cp862", + "cpgr": "cp869", - // 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 - } + "msee": "cp1250", + "mscyrl": "cp1251", + "msansi": "cp1252", + "msgreek": "cp1253", + "msturk": "cp1254", + "mshebr": "cp1255", + "msarab": "cp1256", + "winbaltrim": "cp1257", - // set Content-Disposition when file is sent - var headers = { - 'Content-Disposition': contentDisposition(name || path) - }; + "cp20866": "koi8r", + "20866": "koi8r", + "ibm878": "koi8r", + "cskoi8r": "koi8r", - // 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] - } - } - } + "cp21866": "koi8u", + "21866": "koi8u", + "ibm1168": "koi8u", - // merge user-provided options - opts = Object.create(opts) - opts.headers = headers + "strk10482002": "rk1048", - // Resolve the full path for sendFile - var fullPath = resolve(path); + "tcvn5712": "tcvn", + "tcvn57121": "tcvn", - // send file - return this.sendFile(fullPath, opts, done) -}; + "gb198880": "iso646cn", + "cn": "iso646cn", -/** - * 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 - */ + "csiso14jisc6220ro": "iso646jp", + "jisc62201969ro": "iso646jp", + "jp": "iso646jp", -res.contentType = -res.type = function contentType(type) { - var ct = type.indexOf('/') === -1 - ? mime.lookup(type) - : type; + "cshproman8": "hproman8", + "r8": "hproman8", + "roman8": "hproman8", + "xroman8": "hproman8", + "ibm1051": "hproman8", - return this.set('Content-Type', ct); + "mac": "macintosh", + "csmacintosh": "macintosh", }; -/** - * 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

'); - * }, - * - * 'appliation/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 - */ -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; +/***/ 11155: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - this.vary("Accept"); +"use strict"; - 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 Buffer = (__nccwpck_require__(15118).Buffer); - return this; -}; +// Note: UTF16-LE (or UCS2) codec is Node.js native. See encodings/internal.js -/** - * Set _Content-Disposition_ header to _attachment_ with optional `filename`. - * - * @param {String} filename - * @return {ServerResponse} - * @public - */ +// == UTF16-BE codec. ========================================================== -res.attachment = function attachment(filename) { - if (filename) { - this.type(extname(filename)); - } +exports.utf16be = Utf16BECodec; +function Utf16BECodec() { +} - this.set('Content-Disposition', contentDisposition(filename)); +Utf16BECodec.prototype.encoder = Utf16BEEncoder; +Utf16BECodec.prototype.decoder = Utf16BEDecoder; +Utf16BECodec.prototype.bomAware = true; - return this; -}; -/** - * 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 - */ +// -- Encoding -res.append = function append(field, val) { - var prev = this.get(field); - var value = val; +function Utf16BEEncoder() { +} - if (prev) { - // concat the new and prev vals - value = Array.isArray(prev) ? prev.concat(val) - : Array.isArray(val) ? [prev].concat(val) - : [prev, val]; - } +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; +} - return this.set(field, value); -}; +Utf16BEEncoder.prototype.end = function() { +} -/** - * 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 - */ -res.set = -res.header = function header(field, val) { - if (arguments.length === 2) { - var value = Array.isArray(val) - ? val.map(String) - : String(val); +// -- Decoding - // 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(); - } - } +function Utf16BEDecoder() { + this.overflowByte = -1; +} - this.setHeader(field, value); - } else { - for (var key in field) { - this.set(key, field[key]); - } - } - return this; -}; +Utf16BEDecoder.prototype.write = function(buf) { + if (buf.length == 0) + return ''; -/** - * Get value for header `field`. - * - * @param {String} field - * @return {String} - * @public - */ + var buf2 = Buffer.alloc(buf.length + 1), + i = 0, j = 0; -res.get = function(field){ - return this.getHeader(field); -}; + if (this.overflowByte !== -1) { + buf2[0] = buf[0]; + buf2[1] = this.overflowByte; + i = 1; j = 2; + } -/** - * Clear cookie `name`. - * - * @param {String} name - * @param {Object} [options] - * @return {ServerResponse} for chaining - * @public - */ + for (; i < buf.length-1; i += 2, j+= 2) { + buf2[j] = buf[i+1]; + buf2[j+1] = buf[i]; + } -res.clearCookie = function clearCookie(name, options) { - var opts = merge({ expires: new Date(1), path: '/' }, options); + this.overflowByte = (i == buf.length-1) ? buf[buf.length-1] : -1; - return this.cookie(name, '', opts); -}; + return buf2.slice(0, j).toString('ucs2'); +} -/** - * 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 - */ +Utf16BEDecoder.prototype.end = function() { +} -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'); - } +// == 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'}); - var val = typeof value === 'object' - ? 'j:' + JSON.stringify(value) - : String(value); +// Encoder uses UTF-16LE and prepends BOM (which can be overridden with addBOM: false). - if (signed) { - val = 's:' + sign(val, secret); - } +exports.utf16 = Utf16Codec; +function Utf16Codec(codecOptions, iconv) { + this.iconv = iconv; +} - if ('maxAge' in opts) { - opts.expires = new Date(Date.now() + opts.maxAge); - opts.maxAge /= 1000; - } +Utf16Codec.prototype.encoder = Utf16Encoder; +Utf16Codec.prototype.decoder = Utf16Decoder; - if (opts.path == null) { - opts.path = '/'; - } - this.append('Set-Cookie', cookie.serialize(name, String(val), opts)); +// -- Encoding (pass-through) - return this; -}; +function Utf16Encoder(options, codec) { + options = options || {}; + if (options.addBOM === undefined) + options.addBOM = true; + this.encoder = codec.iconv.getEncoder('utf-16le', options); +} -/** - * 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 - */ +Utf16Encoder.prototype.write = function(str) { + return this.encoder.write(str); +} -res.location = function location(url) { - var loc = url; +Utf16Encoder.prototype.end = function() { + return this.encoder.end(); +} - // "back" is an alias for the referrer - if (url === 'back') { - loc = this.req.get('Referrer') || '/'; - } - // set location - return this.set('Location', encodeUrl(loc)); -}; +// -- Decoding -/** - * 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.redirect('/foo/bar'); - * res.redirect('http://example.com'); - * res.redirect(301, 'http://example.com'); - * res.redirect('../login'); // /blog/post/1 -> /blog/login - * - * @public - */ +function Utf16Decoder(options, codec) { + this.decoder = null; + this.initialBytes = []; + this.initialBytesLen = 0; -res.redirect = function redirect(url) { - var address = url; - var body; - var status = 302; + this.options = options || {}; + this.iconv = codec.iconv; +} - // 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]; +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; } - } - // Set location header - address = this.location(address).get('Location'); + return this.decoder.write(buf); +} - // Support text/{plain,html} by default - this.format({ - text: function(){ - body = statuses[status] + '. Redirecting to ' + address - }, +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); - html: function(){ - var u = escapeHtml(address); - body = '

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

' - }, + var res = this.decoder.write(buf), + trail = this.decoder.end(); - default: function(){ - body = ''; + return trail ? (res + trail) : res; } - }); + return this.decoder.end(); +} - // Respond - this.statusCode = status; - this.set('Content-Length', Buffer.byteLength(body)); +function detectEncoding(buf, defaultEncoding) { + var enc = defaultEncoding || 'utf-16le'; - if (this.req.method === 'HEAD') { - this.end(); - } else { - this.end(body); - } -}; + 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. -/** - * 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 - */ + 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++; + } -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 (asciiCharsBE > asciiCharsLE) + enc = 'utf-16be'; + else if (asciiCharsBE < asciiCharsLE) + enc = 'utf-16le'; + } + } - vary(this, field); + return enc; +} - 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; +/***/ 51644: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // default callback to respond - done = done || function (err, str) { - if (err) return req.next(err); - self.send(str); - }; +"use strict"; - // render - app.render(view, opts, done); -}; +var Buffer = (__nccwpck_require__(15118).Buffer); -// pipe the send file stream -function sendfile(res, file, options, callback) { - var done = false; - var streaming; +// 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 - // request aborted - function onaborted() { - if (done) return; - done = true; +exports.utf7 = Utf7Codec; +exports.unicode11utf7 = 'utf7'; // Alias UNICODE-1-1-UTF-7 +function Utf7Codec(codecOptions, iconv) { + this.iconv = iconv; +}; - var err = new Error('Request aborted'); - err.code = 'ECONNABORTED'; - callback(err); - } +Utf7Codec.prototype.encoder = Utf7Encoder; +Utf7Codec.prototype.decoder = Utf7Decoder; +Utf7Codec.prototype.bomAware = true; - // directory - function ondirectory() { - if (done) return; - done = true; - var err = new Error('EISDIR, read'); - err.code = 'EISDIR'; - callback(err); - } +// -- Encoding - // errors - function onerror(err) { - if (done) return; - done = true; - callback(err); - } +var nonDirectChars = /[^A-Za-z0-9'\(\),-\.\/:\? \n\r\t]+/g; - // ended - function onend() { - if (done) return; - done = true; - callback(); - } +function Utf7Encoder(options, codec) { + this.iconv = codec.iconv; +} - // file - function onfile() { - streaming = false; - } +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))); +} - // finished - function onfinish(err) { - if (err && err.code === 'ECONNRESET') return onaborted(); - if (err) return onerror(err); - if (done) return; +Utf7Encoder.prototype.end = function() { +} - setImmediate(function () { - if (streaming !== false && !done) { - onaborted(); - return; - } - if (done) return; - done = true; - callback(); - }); - } +// -- Decoding - // streaming - function onstream() { - streaming = true; - } +function Utf7Decoder(options, codec) { + this.iconv = codec.iconv; + this.inBase64 = false; + this.base64Accum = ''; +} - file.on('directory', ondirectory); - file.on('end', onend); - file.on('error', onerror); - file.on('file', onfile); - file.on('stream', onstream); - onFinished(res, onfinish); +var base64Regex = /[A-Za-z0-9\/+]/; +var base64Chars = []; +for (var i = 0; i < 256; i++) + base64Chars[i] = base64Regex.test(String.fromCharCode(i)); - if (options.headers) { - // set headers on successful transfer - file.on('headers', function headers(res) { - var obj = options.headers; - var keys = Object.keys(obj); +var plusChar = '+'.charCodeAt(0), + minusChar = '-'.charCodeAt(0), + andChar = '&'.charCodeAt(0); - for (var i = 0; i < keys.length; i++) { - var k = keys[i]; - res.setHeader(k, obj[k]); - } - }); - } +Utf7Decoder.prototype.write = function(buf) { + var res = "", lastI = 0, + inBase64 = this.inBase64, + base64Accum = this.base64Accum; - // pipe - file.pipe(res); -} + // The decoder is more involved as we must handle chunks in stream. -/** - * 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 - */ + 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; + } + } 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"); + } -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 (buf[i] != minusChar) // Minus is absorbed after base64. + i--; - if (escape) { - 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 - } - }) - } + lastI = i+1; + inBase64 = false; + base64Accum = ''; + } + } + } - return json -} + 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"); + } -/***/ 24963: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + this.inBase64 = inBase64; + this.base64Accum = base64Accum; -"use strict"; -/*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2013 Roman Shtylman - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ + 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; +} -/** - * Module dependencies. - * @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) +// 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. -/** - * Module variables. - * @private - */ -var objectRegExp = /^\[object (\S+)\]$/; -var slice = Array.prototype.slice; -var toString = Object.prototype.toString; +exports.utf7imap = Utf7IMAPCodec; +function Utf7IMAPCodec(codecOptions, iconv) { + this.iconv = iconv; +}; -/** - * Initialize a new `Router` with the given `options`. - * - * @param {Object} [options] - * @return {Router} which is an callable function - * @public - */ +Utf7IMAPCodec.prototype.encoder = Utf7IMAPEncoder; +Utf7IMAPCodec.prototype.decoder = Utf7IMAPDecoder; +Utf7IMAPCodec.prototype.bomAware = true; -var proto = module.exports = function(options) { - var opts = options || {}; - function router(req, res, next) { - router.handle(req, res, next); - } +// -- Encoding - // mixin Router class functions - setPrototypeOf(router, proto) +function Utf7IMAPEncoder(options, codec) { + this.iconv = codec.iconv; + this.inBase64 = false; + this.base64Accum = Buffer.alloc(6); + this.base64AccumIdx = 0; +} - router.params = {}; - router._params = []; - router.caseSensitive = opts.caseSensitive; - router.mergeParams = opts.mergeParams; - router.strict = opts.strict; - router.stack = []; +Utf7IMAPEncoder.prototype.write = function(str) { + var inBase64 = this.inBase64, + base64Accum = this.base64Accum, + base64AccumIdx = this.base64AccumIdx, + buf = Buffer.alloc(str.length*5 + 10), bufIdx = 0; - return router; -}; + 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; + } -/** - * 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 - */ + buf[bufIdx++] = minusChar; // Write '-', then go to direct mode. + inBase64 = false; + } -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; - } + if (!inBase64) { + buf[bufIdx++] = uChar; // Write direct character - // apply param functions - var params = this._params; - var len = params.length; - var ret; + if (uChar === andChar) // Ampersand -> '&-' + buf[bufIdx++] = minusChar; + } - if (name[0] === ':') { - deprecate('router.param(' + JSON.stringify(name) + ', fn): Use router.param(' + JSON.stringify(name.substr(1)) + ', fn) instead'); - name = name.substr(1); - } + } 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; - for (var i = 0; i < len; ++i) { - if (ret = params[i](name, fn)) { - fn = ret; + if (base64AccumIdx == base64Accum.length) { + bufIdx += buf.write(base64Accum.toString('base64').replace(/\//g, ','), bufIdx); + base64AccumIdx = 0; + } + } + } } - } - - // 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; -}; + this.inBase64 = inBase64; + this.base64AccumIdx = base64AccumIdx; -/** - * Dispatch a req, res into the router. - * @private - */ + return buf.slice(0, bufIdx); +} -proto.handle = function handle(req, res, out) { - var self = this; +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; + } - debug('dispatching %s %s', req.method, req.url); + buf[bufIdx++] = minusChar; // Write '-', then go to direct mode. + this.inBase64 = false; + } - var idx = 0; - var protohost = getProtohost(req.url) || '' - var removed = ''; - var slashAdded = false; - var paramcalled = {}; + return buf.slice(0, bufIdx); +} - // store options for OPTIONS request - // only used if OPTIONS request - var options = []; - // middleware and routes - var stack = self.stack; +// -- Decoding - // manage inter-router variables - var parentParams = req.params; - var parentUrl = req.baseUrl || ''; - var done = restore(out, req, 'baseUrl', 'next', 'params'); +function Utf7IMAPDecoder(options, codec) { + this.iconv = codec.iconv; + this.inBase64 = false; + this.base64Accum = ''; +} - // setup next layer - req.next = next; +var base64IMAPChars = base64Chars.slice(); +base64IMAPChars[','.charCodeAt(0)] = true; - // 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); - }); - } +Utf7IMAPDecoder.prototype.write = function(buf) { + var res = "", lastI = 0, + inBase64 = this.inBase64, + base64Accum = this.base64Accum; - // setup basic req values - req.baseUrl = parentUrl; - req.originalUrl = req.originalUrl || req.url; + // 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). - next(); + 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"); + } - function next(err) { - var layerError = err === 'route' - ? null - : err; + if (buf[i] != minusChar) // Minus may be absorbed after base64. + i--; - // remove added slash - if (slashAdded) { - req.url = req.url.substr(1); - slashAdded = false; + lastI = i+1; + inBase64 = false; + base64Accum = ''; + } + } } - // restore altered req.url - if (removed.length !== 0) { - req.baseUrl = parentUrl; - req.url = protohost + removed + req.url.substr(protohost.length); - removed = ''; - } + if (!inBase64) { + res += this.iconv.decode(buf.slice(lastI), "ascii"); // Write direct chars. + } else { + var b64str = base64Accum + buf.slice(lastI).toString().replace(/,/g, '/'); - // signal to exit router - if (layerError === 'router') { - setImmediate(done, null) - return - } + 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); - // no more matching layers - if (idx >= stack.length) { - setImmediate(done, layerError); - return; + res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); } - // get pathname of request - var path = getPathname(req); + this.inBase64 = inBase64; + this.base64Accum = base64Accum; - if (path == null) { - return done(layerError); - } + return res; +} - // find next matching layer - var layer; - var match; - var route; +Utf7IMAPDecoder.prototype.end = function() { + var res = ""; + if (this.inBase64 && this.base64Accum.length > 0) + res = this.iconv.decode(Buffer.from(this.base64Accum, 'base64'), "utf16-be"); - while (match !== true && idx < stack.length) { - layer = stack[idx++]; - match = matchLayer(layer, path); - route = layer.route; + this.inBase64 = false; + this.base64Accum = ''; + return res; +} - if (typeof match !== 'boolean') { - // hold on to layerError - layerError = layerError || match; - } - if (match !== true) { - continue; - } - if (!route) { - // process non-route handlers normally - continue; - } - if (layerError) { - // routes do not match with a pending error - match = false; - continue; - } +/***/ }), - var method = req.method; - var has_method = route._handles_method(method); +/***/ 67961: +/***/ ((__unused_webpack_module, exports) => { - // build up automatic options response - if (!has_method && method === 'OPTIONS') { - appendMethods(options, route._options()); - } +"use strict"; - // don't even bother matching route - if (!has_method && method !== 'HEAD') { - match = false; - continue; - } - } - // no match - if (match !== true) { - return done(layerError); +var BOMChar = '\uFEFF'; + +exports.PrependBOM = PrependBOMWrapper +function PrependBOMWrapper(encoder, options) { + this.encoder = encoder; + this.addBOM = true; +} + +PrependBOMWrapper.prototype.write = function(str) { + if (this.addBOM) { + str = BOMChar + str; + this.addBOM = false; } - // store route for dispatch on change - if (route) { - req.route = route; + 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(); } - // Capture one-time layer values - req.params = self.mergeParams - ? mergeParams(layer.params, parentParams) - : layer.params; - var layerPath = layer.path; + this.pass = true; + return res; +} - // this should be done for the layer - self.process_params(layer, paramcalled, req, res, function (err) { - if (err) { - return next(layerError || err); - } +StripBOMWrapper.prototype.end = function() { + return this.decoder.end(); +} - if (route) { - return layer.handle_request(req, res, next); - } - trim_prefix(layer, layerError, layerPath, path); - }); - } - function trim_prefix(layer, layerError, layerPath, path) { - if (layerPath.length !== 0) { - // 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); +/***/ 30393: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // Ensure leading slash - if (!protohost && req.url[0] !== '/') { - req.url = '/' + req.url; - slashAdded = true; - } +"use strict"; - // Setup base URL (no trailing slash) - req.baseUrl = parentUrl + (removed[removed.length - 1] === '/' - ? removed.substring(0, removed.length - 1) - : removed); - } +var Buffer = (__nccwpck_require__(14300).Buffer); +// Note: not polyfilled with safer-buffer on a purpose, as overrides Buffer - debug('%s %s : %s', layer.name, layerPath, req.originalUrl); +// == Extend Node primitives to use iconv-lite ================================= - if (layerError) { - layer.handle_error(layerError, req, res, next); - } else { - layer.handle_request(req, res, next); - } - } -}; +module.exports = function (iconv) { + var original = undefined; // Place to keep original methods. -/** - * Process any parameters for the layer. - * @private - */ + // 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); -proto.process_params = function process_params(layer, called, req, res, done) { - var params = this.params; + iconv.extendNodeEncodings = function extendNodeEncodings() { + if (original) return; + original = {}; - // captured parameters from the layer, keys and values - var keys = layer.keys; + 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; + } - // fast track - if (!keys || keys.length === 0) { - return done(); - } + 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, + }; - var i = 0; - var name; - var paramIndex = 0; - var key; - var paramVal; - var paramCallbacks; - var paramCalled; + Buffer.isNativeEncoding = function(enc) { + return enc && nodeNativeEncodings[enc.toLowerCase()]; + } - // process params in order - // param callbacks can be async - function param(err) { - if (err) { - return done(err); - } + // -- SlowBuffer ----------------------------------------------------------- + var SlowBuffer = (__nccwpck_require__(14300).SlowBuffer); - if (i >= keys.length ) { - return done(); - } + original.SlowBufferToString = SlowBuffer.prototype.toString; + SlowBuffer.prototype.toString = function(encoding, start, end) { + encoding = String(encoding || 'utf8').toLowerCase(); - paramIndex = 0; - key = keys[i++]; - name = key.name; - paramVal = req.params[name]; - paramCallbacks = params[name]; - paramCalled = called[name]; + // Use native conversion when possible + if (Buffer.isNativeEncoding(encoding)) + return original.SlowBufferToString.call(this, encoding, start, end); - if (paramVal === undefined || !paramCallbacks) { - return param(); - } + // 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); + } - // 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; + 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; + } - // next param - return param(paramCalled.error); - } + 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(); - called[name] = paramCalled = { - error: null, - match: paramVal, - value: paramVal - }; + // Use native conversion when possible + if (Buffer.isNativeEncoding(encoding)) + return original.SlowBufferWrite.call(this, string, offset, length, encoding); - paramCallback(); - } + if (string.length > 0 && (length < 0 || offset < 0)) + throw new RangeError('attempt to write beyond buffer bounds'); - // single param callbacks - function paramCallback(err) { - var fn = paramCallbacks[paramIndex++]; + // 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; + } - // store updated value - paramCalled.value = req.params[key.name]; + // -- Buffer --------------------------------------------------------------- - if (err) { - // store error - paramCalled.error = err; - param(err); - return; - } + original.BufferIsEncoding = Buffer.isEncoding; + Buffer.isEncoding = function(encoding) { + return Buffer.isNativeEncoding(encoding) || iconv.encodingExists(encoding); + } - if (!fn) return param(); + original.BufferByteLength = Buffer.byteLength; + Buffer.byteLength = SlowBuffer.byteLength = function(str, encoding) { + encoding = String(encoding || 'utf8').toLowerCase(); - try { - fn(req, res, paramCallback, paramVal, key.name); - } catch (e) { - paramCallback(e); - } - } + // Use native conversion when possible + if (Buffer.isNativeEncoding(encoding)) + return original.BufferByteLength.call(this, str, encoding); - param(); -}; + // Slow, I know, but we don't have a better way yet. + return iconv.encode(str, encoding).length; + } -/** - * Use the given middleware function, with optional path, defaulting to "/". - * - * 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 - */ + original.BufferToString = Buffer.prototype.toString; + Buffer.prototype.toString = function(encoding, start, end) { + encoding = String(encoding || 'utf8').toLowerCase(); -proto.use = function use(fn) { - var offset = 0; - var path = '/'; + // Use native conversion when possible + if (Buffer.isNativeEncoding(encoding)) + return original.BufferToString.call(this, encoding, start, end); - // default path to '/' - // disambiguate router.use([fn]) - if (typeof fn !== 'function') { - var arg = fn; + // 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; + } - while (Array.isArray(arg) && arg.length !== 0) { - arg = arg[0]; - } + encoding = String(encoding || 'utf8').toLowerCase(); - // first arg is the path - if (typeof arg !== 'function') { - offset = 1; - path = fn; - } - } + // Use native conversion when possible + if (Buffer.isNativeEncoding(encoding)) + return original.BufferWrite.call(this, string, _offset, _length, _encoding); - var callbacks = flatten(slice.call(arguments, offset)); + offset = +offset || 0; + var remaining = this.length - offset; + if (!length) { + length = remaining; + } else { + length = +length; + if (length > remaining) { + length = remaining; + } + } - if (callbacks.length === 0) { - throw new TypeError('Router.use() requires a middleware function') - } + if (string.length > 0 && (length < 0 || offset < 0)) + throw new RangeError('attempt to write beyond buffer bounds'); - for (var i = 0; i < callbacks.length; i++) { - var fn = callbacks[i]; + // 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; - if (typeof fn !== 'function') { - throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn)) - } + // TODO: Set _charsWritten. + } - // add the middleware - debug('use %o %s', path, fn.name || '') - var layer = new Layer(path, { - sensitive: this.caseSensitive, - strict: false, - end: false - }, fn); + // -- Readable ------------------------------------------------------------- + if (iconv.supportsStreams) { + var Readable = (__nccwpck_require__(12781).Readable); - layer.route = undefined; + 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; + } - this.stack.push(layer); - } + Readable.prototype.collect = iconv._collect; + } + } - return this; -}; + // 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.") -/** - * Create a new Route for the given path. - * - * 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 - */ + delete Buffer.isNativeEncoding; -proto.route = function route(path) { - var route = new Route(path); + var SlowBuffer = (__nccwpck_require__(14300).SlowBuffer); - var layer = new Layer(path, { - sensitive: this.caseSensitive, - strict: this.strict, - end: true - }, route.dispatch.bind(route)); + SlowBuffer.prototype.toString = original.SlowBufferToString; + SlowBuffer.prototype.write = original.SlowBufferWrite; - layer.route = route; + Buffer.isEncoding = original.BufferIsEncoding; + Buffer.byteLength = original.BufferByteLength; + Buffer.prototype.toString = original.BufferToString; + Buffer.prototype.write = original.BufferWrite; - this.stack.push(layer); - return route; -}; + if (iconv.supportsStreams) { + var Readable = (__nccwpck_require__(12781).Readable); -// 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; - }; -}); + Readable.prototype.setEncoding = original.ReadableSetEncoding; + delete Readable.prototype.collect; + } -// 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); + original = undefined; } - } -} - -// get pathname of request -function getPathname(req) { - try { - return parseUrl(req).pathname; - } catch (err) { - return undefined; - } } -// Get get protocol + host for a URL -function getProtohost(url) { - if (typeof url !== 'string' || url.length === 0 || url[0] === '/') { - return undefined - } - - 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; - } +/***/ 19032: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // inspect [[Class]] for objects - return toString.call(obj) - .replace(objectRegExp, '$1'); -} +"use strict"; -/** - * 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; - } -} +// 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); -// merge params with parent params -function mergeParams(params, parent) { - if (typeof parent !== 'object' || !parent) { - return params; - } +var bomHandling = __nccwpck_require__(67961), + iconv = module.exports; - // make copy of parent for base - var obj = mixin({}, parent); +// 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; - // simple non-numeric merging - if (!(0 in params) || !(0 in parent)) { - return mixin(obj, params); - } +// Characters emitted in case of error. +iconv.defaultCharUnicode = '�'; +iconv.defaultCharSingleByte = '?'; - var i = 0; - var o = 0; +// Public API. +iconv.encode = function encode(str, encoding, options) { + str = "" + (str || ""); // Ensure string. - // determine numeric gaps - while (i in params) { - i++; - } + var encoder = iconv.getEncoder(encoding, options); - while (o in parent) { - o++; - } + var res = encoder.write(str); + var trail = encoder.end(); + + return (trail && trail.length > 0) ? Buffer.concat([res, trail]) : res; +} - // offset numeric indices in params before merge - for (i--; i >= 0; i--) { - params[i + o] = params[i]; +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; + } - // create holes for the merge when necessary - if (i < o) { - delete params[i]; + buf = Buffer.from("" + (buf || ""), "binary"); // Ensure buffer. } - } - return mixin(obj, params); -} + var decoder = iconv.getDecoder(encoding, options); -// restore obj props after function -function restore(fn, obj) { - var props = new Array(arguments.length - 2); - var vals = new Array(arguments.length - 2); + var res = decoder.write(buf); + var trail = decoder.end(); - for (var i = 0; i < props.length; i++) { - props[i] = arguments[i + 2]; - vals[i] = obj[props[i]]; - } + return trail ? (res + trail) : res; +} - return function () { - // restore vals - for (var i = 0; i < props.length; i++) { - obj[props[i]] = vals[i]; +iconv.encodingExists = function encodingExists(enc) { + try { + iconv.getCodec(enc); + return true; + } catch (e) { + return false; } - - 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); - } -} +// Legacy aliases to convert functions +iconv.toEncoding = iconv.encode; +iconv.fromEncoding = iconv.decode; -// wrap a function -function wrap(old, fn) { - return function proxy() { - var args = new Array(arguments.length + 1); +// 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); - args[0] = old; - for (var i = 0, len = arguments.length; i < len; i++) { - args[i + 1] = arguments[i]; - } + // Traverse iconv.encodings to find actual codec. + var codecOptions = {}; + while (true) { + var codec = iconv._codecDataCache[enc]; + if (codec) + return codec; - fn.apply(this, args); - }; -} + 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]; -/***/ 25624: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (!codecOptions.encodingName) + codecOptions.encodingName = enc; + + enc = codecDef.type; + break; -"use strict"; -/*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2013 Roman Shtylman - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ + 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; -/** - * Module dependencies. - * @private - */ + default: + throw new Error("Encoding not recognized: '" + encoding + "' (searched as: '"+enc+"')"); + } + } +} -var pathRegexp = __nccwpck_require__(37819); -var debug = __nccwpck_require__(52529)('express:router:layer'); +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, ""); +} -/** - * Module variables. - * @private - */ +iconv.getEncoder = function getEncoder(encoding, options) { + var codec = iconv.getCodec(encoding), + encoder = new codec.encoder(options, codec); -var hasOwnProperty = Object.prototype.hasOwnProperty; + if (codec.bomAware && options && options.addBOM) + encoder = new bomHandling.PrependBOM(encoder, options); -/** - * Module exports. - * @public - */ + return encoder; +} -module.exports = Layer; +iconv.getDecoder = function getDecoder(encoding, options) { + var codec = iconv.getCodec(encoding), + decoder = new codec.decoder(options, codec); -function Layer(path, options, fn) { - if (!(this instanceof Layer)) { - return new Layer(path, options, fn); - } + if (codec.bomAware && !(options && options.stripBOM === false)) + decoder = new bomHandling.StripBOM(decoder, options); - debug('new %o', path) - var opts = options || {}; + return decoder; +} - 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 -} +// 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) { -/** - * Handle the error for the layer. - * - * @param {Error} error - * @param {Request} req - * @param {Response} res - * @param {function} next - * @api private - */ + // Load streaming support in Node v0.10+ + var nodeVerArr = nodeVer.split(".").map(Number); + if (nodeVerArr[0] > 0 || nodeVerArr[1] >= 10) { + __nccwpck_require__(76409)(iconv); + } -Layer.prototype.handle_error = function handle_error(error, req, res, next) { - var fn = this.handle; + // Load Node primitive extensions. + __nccwpck_require__(30393)(iconv); +} - if (fn.length !== 4) { - // not a standard error handler - return next(error); - } +if (false) {} - try { - fn(error, req, res, next); - } catch (err) { - next(err); - } -}; -/** - * 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; +/***/ 76409: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (fn.length > 3) { - // not a standard request handler - return next(); - } +"use strict"; - try { - fn(req, res, next); - } catch (err) { - next(err); - } -}; -/** - * Check if this route matches `path`, if so - * populate `.params`. - * - * @param {String} path - * @return {Boolean} - * @api private - */ +var Buffer = (__nccwpck_require__(14300).Buffer), + Transform = (__nccwpck_require__(12781).Transform); -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 +// == Exports ================================================================== +module.exports = function(iconv) { + + // Additional Public API. + iconv.encodeStream = function encodeStream(encoding, options) { + return new IconvLiteEncoderStream(iconv.getEncoder(encoding, options), options); } - // fast path for * (everything matched in a param) - if (this.regexp.fast_star) { - this.params = {'0': decode_param(path)} - this.path = path - return true + iconv.decodeStream = function decodeStream(encoding, options) { + return new IconvLiteDecoderStream(iconv.getDecoder(encoding, options), options); } - // match the path - match = this.regexp.exec(path) - } + iconv.supportsStreams = true; - if (!match) { - this.params = undefined; - this.path = undefined; - return false; - } - // store values - this.params = {}; - this.path = match[0] + // Not published yet. + iconv.IconvLiteEncoderStream = IconvLiteEncoderStream; + iconv.IconvLiteDecoderStream = IconvLiteDecoderStream; + iconv._collect = IconvLiteDecoderStream.prototype.collect; +}; - 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]) +// == 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); +} + +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(); + } + catch (e) { + done(e); + } +} - if (val !== undefined || !(hasOwnProperty.call(params, prop))) { - params[prop] = val; +IconvLiteEncoderStream.prototype._flush = function(done) { + try { + var res = this.conv.end(); + if (res && res.length) this.push(res); + done(); } - } + catch (e) { + done(e); + } +} - return true; -}; +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; +} -/** - * Decode param value. - * - * @param {string} val - * @return {string} - * @private - */ -function decode_param(val) { - if (typeof val !== 'string' || val.length === 0) { - return val; - } +// == Decoder stream ======================================================= +function IconvLiteDecoderStream(conv, options) { + this.conv = conv; + options = options || {}; + options.encoding = this.encoding = 'utf8'; // We output strings. + Transform.call(this, options); +} - try { - return decodeURIComponent(val); - } catch (err) { - if (err instanceof URIError) { - err.message = 'Failed to decode param \'' + val + '\''; - err.status = err.statusCode = 400; +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); } +} - throw err; - } +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); + } } +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; +} -/***/ }), -/***/ 23699: -/***/ ((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 - */ +/***/ }), +/***/ 91230: +/***/ ((module) => { +// A simple implementation of make-array +function makeArray (subject) { + return Array.isArray(subject) + ? subject + : [subject] +} -/** - * Module dependencies. - * @private - */ +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 = /^\.*\/|^\.+$/ -var debug = __nccwpck_require__(52529)('express:router:route'); -var flatten = __nccwpck_require__(62003); -var Layer = __nccwpck_require__(25624); -var methods = __nccwpck_require__(58752); +const SLASH = '/' +const KEY_IGNORE = typeof Symbol !== 'undefined' + ? Symbol.for('node-ignore') + /* istanbul ignore next */ + : 'node-ignore' -/** - * Module variables. - * @private - */ +const define = (object, key, value) => + Object.defineProperty(object, key, {value}) -var slice = Array.prototype.slice; -var toString = Object.prototype.toString; +const REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g -/** - * Module exports. - * @public - */ +const RETURN_FALSE = () => false -module.exports = Route; +// 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 +) -/** - * Initialize `Route` with the given `path`, - * - * @param {String} path - * @public - */ +// See fixtures #59 +const cleanRangeBackSlash = slashes => { + const {length} = slashes + return slashes.slice(0, length - length % 2) +} -function Route(path) { - this.path = path; - this.stack = []; +// > 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` - debug('new %o', path) +// '`foo/`' should not continue with the '`..`' +const REPLACERS = [ - // route handlers for various http methods - this.methods = {}; -} + // > Trailing spaces are ignored unless they are quoted with backslash ("\") + [ + // (a\ ) -> (a ) + // (a ) -> (a) + // (a \ ) -> (a ) + /\\?\s+$/, + match => match.indexOf('\\') === 0 + ? SPACE + : EMPTY + ], -/** - * Determine if the route handles a given method. - * @private - */ + // replace (\ ) with ' ' + [ + /\\\s/g, + () => SPACE + ], -Route.prototype._handles_method = function _handles_method(method) { - if (this.methods._all) { - return true; - } + // Escape metacharacters + // which is written down by users but means special for regular expressions. - var name = method.toLowerCase(); + // > 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}` + ], - if (name === 'head' && !this.methods['head']) { - name = 'get'; - } + [ + // > a question mark (?) matches a single character + /(?!\\)\?/g, + () => '[^/]' + ], - return Boolean(this.methods[name]); -}; + // leading slash + [ -/** - * @return {Array} supported HTTP methods - * @private - */ + // > 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 + /^\//, + () => '^' + ], -Route.prototype._options = function _options() { - var methods = Object.keys(this.methods); + // replace special metacharacter slash after the leading slash + [ + /\//g, + () => '\\/' + ], - // append automatic head - if (this.methods.get && !this.methods.head) { - methods.push('head'); - } + [ + // > 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 '\\*' + /^\^*\\\*\\\*\\\//, - for (var i = 0; i < methods.length; i++) { - // make upper case - methods[i] = methods[i].toUpperCase(); - } + // '**/foo' <-> 'foo' + () => '^(?:.*\\/)?' + ], - return methods; -}; + // 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 -/** - * dispatch req, res into this route - * @private - */ + // 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. + ? '(?:^|\\/)' -Route.prototype.dispatch = function dispatch(req, res, done) { - var idx = 0; - var stack = this.stack; - if (stack.length === 0) { - return done(); - } + // > Otherwise, Git treats the pattern as a shell glob suitable for + // > consumption by fnmatch(3) + : '^' + } + ], - var method = req.method.toLowerCase(); - if (method === 'head' && !this.methods['head']) { - method = 'get'; - } + // two globstars + [ + // Use lookahead assertions so that we could match more than one `'/**'` + /\\\/\\\*\\\*(?=\\\/|$)/g, - req.route = this; + // Zero, one or several directories + // should not use '*', or it will be replaced by the next replacer - next(); + // Check if it is not the last `'/**'` + (_, index, str) => index + 6 < str.length - function next(err) { - // signal to exit route - if (err && err === 'route') { - return done(); - } + // 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. + // '/**/' + ? '(?:\\/[^\\/]+)*' - // signal to exit router - if (err && err === 'router') { - return done(err) - } + // case: /** + // > A trailing `"/**"` matches everything inside. - var layer = stack[idx++]; - if (!layer) { - return done(err); - } + // #21: everything inside but it should not include the current folder + : '\\/.+' + ], - if (layer.method && layer.method !== method) { - return next(err); - } + // intermediate wildcards + [ + // Never replace escaped '*' + // ignore rule '\*' will match the path '*' - if (err) { - layer.handle_error(err, req, res, next); - } else { - layer.handle_request(req, res, next); - } - } -}; + // 'abc.*/' -> go + // 'abc.*' -> skip this rule + /(^|[^\\]+)\\\*(?=.+)/g, -/** - * 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 - */ + // '*.js' matches '.js' + // '*.js' doesn't match 'abc' + (_, p1) => `${p1}[^\\/]*` + ], -Route.prototype.all = function all() { - var handles = flatten(slice.call(arguments)); + [ + // unescape, revert step 3 except for back slash + // For example, if a user escape a '\\*', + // after step 3, the result will be '\\\\\\*' + /\\\\\\(?=[$.|*+(){^])/g, + () => ESCAPE + ], - for (var i = 0; i < handles.length; i++) { - var handle = handles[i]; + [ + // '\\\\' -> '\\' + /\\\\/g, + () => ESCAPE + ], - 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); - } + [ + // > The range notation, e.g. [a-zA-Z], + // > can be used to match one of the characters in a range. - var layer = Layer('/', {}, handle); - layer.method = undefined; + // `\` 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\\\\]' + : '[]' + : '[]' + ], - this.methods._all = true; - this.stack.push(layer); - } + // ending + [ + // 'js' will not match 'js.' + // 'ab' will not match 'abc' + /(?:[^*])$/, - return this; -}; + // 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 -methods.forEach(function(method){ - Route.prototype[method] = function(){ - var handles = flatten(slice.call(arguments)); + // > 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. - for (var i = 0; i < handles.length; i++) { - var handle = handles[i]; + // '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}(?=$|\\/$)` + ], - 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); - } + // trailing wildcard + [ + /(\^|\\\/)?\\\*$/, + (_, p1) => { + const prefix = p1 + // '\^': + // '/*' does not match EMPTY + // '/*' does not match everything - debug('%s %o', method, this.path) + // '\\\/': + // 'abc/*' does not match 'abc/' + ? `${p1}[^/]+` - var layer = Layer('/', {}, handle); - layer.method = method; + // 'a*' matches 'a' + // 'a*' matches 'aa' + : '[^/]*' - this.methods[method] = true; - this.stack.push(layer); + return `${prefix}(?=$|\\/$)` } + ], +] - return this; - }; -}); +// 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 + } -/***/ 53561: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + return ignoreCase + ? new RegExp(source, 'i') + : new RegExp(source) +} -"use strict"; -/*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ +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 -/** - * Module dependencies. - * @api private - */ +const splitPattern = pattern => pattern.split(REGEX_SPLITALL_CRLF) -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); +class IgnoreRule { + constructor ( + origin, + pattern, + negative, + regex + ) { + this.origin = origin + this.pattern = pattern + this.negative = negative + this.regex = regex + } +} -/** - * Return strong ETag for `body`. - * - * @param {String|Buffer} body - * @param {String} [encoding] - * @return {String} - * @api private - */ +const createRule = (pattern, ignoreCase) => { + const origin = pattern + let negative = false -exports.etag = createETagGenerator({ weak: false }) + // > An optional prefix "!" which negates the pattern; + if (pattern.indexOf('!') === 0) { + negative = true + pattern = pattern.substr(1) + } -/** - * Return weak ETag for `body`. - * - * @param {String|Buffer} body - * @param {String} [encoding] - * @return {String} - * @api private - */ + 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, '#') -exports.wetag = createETagGenerator({ weak: true }) + const regex = makeRegex(pattern, ignoreCase) -/** - * Check if `path` looks absolute. - * - * @param {String} path - * @return {Boolean} - * @api private - */ + return new IgnoreRule( + origin, + pattern, + negative, + regex + ) +} -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 -}; +const throwError = (message, Ctor) => { + throw new Ctor(message) +} -/** - * Flatten the given `arr`. - * - * @param {Array} arr - * @return {Array} - * @api private - */ +const checkPath = (path, originalPath, doThrow) => { + if (!isString(path)) { + return doThrow( + `path must be a string, but got \`${originalPath}\``, + TypeError + ) + } -exports.flatten = deprecate.function(flatten, - 'utils.flatten: use array-flatten npm module instead'); + // We don't know if we should ignore EMPTY, so throw + if (!path) { + return doThrow(`path must not be empty`, TypeError) + } -/** - * Normalize the given `type`, for example "html" becomes "text/html". - * - * @param {String} type - * @return {Object} - * @api private - */ + // 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 + ) + } -exports.normalizeType = function(type){ - return ~type.indexOf('/') - ? acceptParams(type) - : { value: mime.lookup(type), params: {} }; -}; + return true +} -/** - * Normalize `types`, for example "html" becomes "text/html". - * - * @param {Array} types - * @return {Array} - * @api private - */ +const isNotRelative = path => REGEX_TEST_INVALID_PATH.test(path) -exports.normalizeTypes = function(types){ - var ret = []; +checkPath.isNotRelative = isNotRelative +checkPath.convert = p => p - for (var i = 0; i < types.length; ++i) { - ret.push(exports.normalizeType(types[i])); +class Ignore { + constructor ({ + ignorecase = true, + ignoreCase = ignorecase, + allowRelativePaths = false + } = {}) { + define(this, KEY_IGNORE, true) + + this._rules = [] + this._ignoreCase = ignoreCase + this._allowRelativePaths = allowRelativePaths + this._initCache() } - return ret; -}; + _initCache () { + this._ignoreCache = Object.create(null) + this._testCache = Object.create(null) + } -/** - * 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 - */ + _addPattern (pattern) { + // #32 + if (pattern && pattern[KEY_IGNORE]) { + this._rules = this._rules.concat(pattern._rules) + this._added = true + return + } -exports.contentDisposition = deprecate.function(contentDisposition, - 'utils.contentDisposition: use content-disposition npm module instead'); + if (checkPattern(pattern)) { + const rule = createRule(pattern, this._ignoreCase) + this._added = true + this._rules.push(rule) + } + } -/** - * 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 - */ + // @param {Array | string | Ignore} pattern + add (pattern) { + this._added = false -function acceptParams(str, index) { - var parts = str.split(/ *; */); - var ret = { value: parts[0], quality: 1, params: {}, originalIndex: index }; + makeArray( + isString(pattern) + ? splitPattern(pattern) + : pattern + ).forEach(this._addPattern, this) - 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]; + // Some rules have just added to the ignore, + // making the behavior changed. + if (this._added) { + this._initCache() } + + return this } - return ret; -} + // legacy + addPattern (pattern) { + return this.add(pattern) + } -/** - * Compile "etag" value to function. - * - * @param {Boolean|String|Function} val - * @return {Function} - * @api private - */ + // | ignored : unignored + // negative | 0:0 | 0:1 | 1:0 | 1:1 + // -------- | ------- | ------- | ------- | -------- + // 0 | TEST | TEST | SKIP | X + // 1 | TESTIF | SKIP | TEST | X -exports.compileETag = function(val) { - var fn; + // - SKIP: always skip + // - TEST: always test + // - TESTIF: only test if checkUnignored + // - X: that never happen - if (typeof val === 'function') { - return val; - } + // @param {boolean} whether should check if the path is unignored, + // setting `checkUnignored` to `false` could reduce additional + // path matching. - switch (val) { - case true: - fn = exports.wetag; - break; - case false: - break; - case 'strong': - fn = exports.etag; - break; - case 'weak': - fn = exports.wetag; - break; - default: - throw new TypeError('unknown value for etag function: ' + val); - } + // @returns {TestResult} true if a file is ignored + _testOne (path, checkUnignored) { + let ignored = false + let unignored = false - return fn; -} + this._rules.forEach(rule => { + const {negative} = rule + if ( + unignored === negative && ignored !== unignored + || negative && !ignored && !unignored && !checkUnignored + ) { + return + } -/** - * Compile "query parser" value to function. - * - * @param {String|Function} val - * @return {Function} - * @api private - */ + const matched = rule.regex.test(path) -exports.compileQueryParser = function compileQueryParser(val) { - var fn; + if (matched) { + ignored = !negative + unignored = negative + } + }) - if (typeof val === 'function') { - return val; + return { + ignored, + unignored + } } - switch (val) { - case true: - fn = querystring.parse; - break; - case false: - fn = newObject; - break; - case 'extended': - fn = parseExtendedQueryString; - break; - case 'simple': - fn = querystring.parse; - break; - default: - throw new TypeError('unknown value for query parser function: ' + val); + // @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) } - return fn; -} + _t (path, cache, checkUnignored, slices) { + if (path in cache) { + return cache[path] + } -/** - * Compile "proxy trust" value to function. - * - * @param {Boolean|String|Number|Array|Function} val - * @return {Function} - * @api private - */ + if (!slices) { + // path/to/a.js + // ['path', 'to', 'a.js'] + slices = path.split(SLASH) + } -exports.compileTrust = function(val) { - if (typeof val === 'function') return val; + slices.pop() - if (val === true) { - // Support plain true/false - return function(){ return true }; - } + // If the path has no parent directory, just test it + if (!slices.length) { + return cache[path] = this._testOne(path, checkUnignored) + } - if (typeof val === 'number') { - // Support trusting hop count - return function(a, i){ return i < val }; - } + const parent = this._t( + slices.join(SLASH) + SLASH, + cache, + checkUnignored, + slices + ) - if (typeof val === 'string') { - // Support comma-separated values - val = val.split(/ *, */); + // 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) } - return proxyaddr.compile(val || []); -} - -/** - * Set the charset in a given Content-Type string. - * - * @param {String} type - * @param {String} charset - * @return {String} - * @api private - */ + ignores (path) { + return this._test(path, this._ignoreCache, false).ignored + } -exports.setCharset = function setCharset(type, charset) { - if (!type || !charset) { - return type; + createFilter () { + return path => !this.ignores(path) } - // parse type - var parsed = contentType.parse(type); + filter (paths) { + return makeArray(paths).filter(this.createFilter()) + } - // set charset - parsed.parameters.charset = charset; + // @returns {TestResult} + test (path) { + return this._test(path, this._testCache, true) + } +} - // format type - return contentType.format(parsed); -}; +const factory = options => new Ignore(options) -/** - * Create an ETag generator function, generating ETags with - * the given options. - * - * @param {object} options - * @return {function} - * @private - */ +const isPathValid = path => + checkPath(path && checkPath.convert(path), path, RETURN_FALSE) -function createETagGenerator (options) { - return function generateETag (body, encoding) { - var buf = !Buffer.isBuffer(body) - ? Buffer.from(body, encoding) - : body +factory.isPathValid = isPathValid - return etag(buf, options) - } -} +// Fixes typescript +factory.default = factory -/** - * Parse an extended query string with qs. - * - * @return {Object} - * @private - */ +module.exports = factory -function parseExtendedQueryString(str) { - return qs.parse(str, { - allowPrototypes: true - }); -} +// 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, '/') -/** - * Return new empty object. - * - * @return {Object} - * @api private - */ + checkPath.convert = makePosix -function newObject() { - return {}; + // '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) } /***/ }), -/***/ 99209: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 98043: +/***/ ((module) => { "use strict"; -/*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2013 Roman Shtylman - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ +module.exports = (string, count = 1, options) => { + options = { + indent: ' ', + includeEmptyLines: false, + ...options + }; -/** - * Module dependencies. - * @private - */ + if (typeof string !== 'string') { + throw new TypeError( + `Expected \`input\` to be a \`string\`, got \`${typeof string}\`` + ); + } -var debug = __nccwpck_require__(52529)('express:view'); -var path = __nccwpck_require__(71017); -var fs = __nccwpck_require__(57147); + if (typeof count !== 'number') { + throw new TypeError( + `Expected \`count\` to be a \`number\`, got \`${typeof count}\`` + ); + } -/** - * Module variables. - * @private - */ + if (typeof options.indent !== 'string') { + throw new TypeError( + `Expected \`options.indent\` to be a \`string\`, got \`${typeof options.indent}\`` + ); + } -var dirname = path.dirname; -var basename = path.basename; -var extname = path.extname; -var join = path.join; -var resolve = path.resolve; + if (count === 0) { + return string; + } -/** - * Module exports. - * @public - */ + const regex = options.includeEmptyLines ? /^/gm : /^(?!\s*$)/gm; -module.exports = View; + return string.replace(regex, options.indent.repeat(count)); +}; -/** - * 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 || {}; +/***/ }), - this.defaultEngine = opts.defaultEngine; - this.ext = extname(name); - this.name = name; - this.root = opts.root; +/***/ 44124: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (!this.ext && !this.defaultEngine) { - throw new Error('No default engine was specified and no extension was provided.'); - } +try { + var util = __nccwpck_require__(73837); + if (typeof util.inherits !== 'function') throw ''; + module.exports = util.inherits; +} catch (e) { + module.exports = __nccwpck_require__(8544); +} - var fileName = name; - if (!this.ext) { - // get extension from default engine name - this.ext = this.defaultEngine[0] !== '.' - ? '.' + this.defaultEngine - : this.defaultEngine; +/***/ }), - fileName += this.ext; +/***/ 8544: +/***/ ((module) => { + +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, 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) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor } +} - 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.') +/***/ 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].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; +} - opts.engines[this.ext] = fn - } - // store loaded engine - this.engine = opts.engines[this.ext]; +/***/ }), - // lookup path - this.path = this.lookup(fileName); -} +/***/ 6134: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const stream_1 = __nccwpck_require__(12781); /** - * Lookup view by the given `name` + * Convenient class to convert the process of scaning keys to a readable stream. * - * @param {string} name - * @private + * @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; -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]; - // resolve the path - var loc = resolve(root, name); - var dir = dirname(loc); - var file = basename(loc); +/***/ }), - // resolve the file - path = this.resolve(dir, file); - } +/***/ 73527: +/***/ ((__unused_webpack_module, exports) => { - return path; -}; +"use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); /** - * Render with the given options. + * Tiny class to simplify dealing with subscription set * - * @param {object} options - * @param {function} callback - * @private + * @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; +} -View.prototype.render = function render(options, callback) { - debug('render "%s"', this.path); - this.engine(this.path, options, callback); -}; +/***/ }), + +/***/ 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; /** - * Resolve the file within the given directory. - * - * @param {string} dir - * @param {string} file * @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; -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; - } +/***/ 35835: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // /index. - path = join(dir, basename(file, ext), 'index' + ext); - stat = tryStat(path); +"use strict"; - if (stat && stat.isFile()) { - return path; - } +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, }; -/** - * 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; - } -} - /***/ }), -/***/ 36654: -/***/ ((module, exports, __nccwpck_require__) => { +/***/ 18394: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -/** - * This is the web browser implementation of `debug()`. - * - * Expose `debug()` as the module. - */ +"use strict"; -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(); +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; -/** - * Colors. - */ -exports.colors = [ - 'lightseagreen', - 'forestgreen', - 'goldenrod', - 'dodgerblue', - 'darkorchid', - 'crimson' -]; +/***/ }), -/** - * 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 - */ +/***/ 34589: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -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; - } +"use strict"; - // 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+)/)); +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; -/** - * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. - */ -exports.formatters.j = function(v) { - try { - return JSON.stringify(v); - } catch (err) { - return '[UnexpectedJSONParseError]: ' + err.message; - } -}; +/***/ }), + +/***/ 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"); /** - * Colorize log arguments if enabled. + * Queue that runs items after specified duration * - * @api public + * @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; -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; +/***/ 17208: +/***/ ((__unused_webpack_module, 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; +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); + } } - }); - - args.splice(lastC, 0, c); -} - -/** - * Invokes `console.log()` when available. - * No-op when `console.log` is not a "function". - * - * @api public - */ - -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 - */ - -function save(namespaces) { - try { - if (null == namespaces) { - exports.storage.removeItem('debug'); - } else { - exports.storage.debug = namespaces; + 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); + } + } } - } catch(e) {} -} - -/** - * 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; - } - - 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 - */ - -function localstorage() { - try { - return window.localStorage; - } catch (e) {} -} - - -/***/ }), - -/***/ 86991: -/***/ ((module, exports, __nccwpck_require__) => { - - -/** - * 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 - } - - 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) { - - 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]; + 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; } - - args[0] = exports.coerce(args[0]); - - if ('string' !== typeof args[0]) { - // anything else let's inspect with %O - args.unshift('%O'); + 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; } - - // 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; - }); - - // 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); - - // env-specific initialization logic for debug instances - if ('function' === typeof exports.init) { - exports.init(debug); - } - - 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 = []; - - 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 + '$')); + 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)); } - } -} - -/** - * Disable debug output. - * - * @api public - */ - -function disable() { - exports.enable(''); -} - -/** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ - -function enabled(name) { - var i, len; - for (i = 0, len = exports.skips.length; i < len; i++) { - if (exports.skips[i].test(name)) { - return false; + invokeReadyDelayedCallbacks(err) { + for (const c of this._readyDelayedCallbacks) { + process.nextTick(c, err); + } + this._readyDelayedCallbacks = []; } - } - for (i = 0, len = exports.names.length; i < len; i++) { - if (exports.names[i].test(name)) { - return true; + /** + * 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 }); + } + }); + }); } - } - 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; -} - - -/***/ }), - -/***/ 52529: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -/** - * Detect Electron renderer process, which is node, but we should - * treat as a browser. - */ - -if (typeof process !== 'undefined' && process.type === 'renderer') { - module.exports = __nccwpck_require__(36654); -} else { - module.exports = __nccwpck_require__(25696); } +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; /***/ }), -/***/ 25696: -/***/ ((module, exports, __nccwpck_require__) => { - -/** - * Module dependencies. - */ - -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; - -/** - * Colors. - */ - -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 - */ - -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; -}, {}); - -/** - * 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 - */ +/***/ 94582: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -var fd = parseInt(process.env.DEBUG_FD, 10) || 2; +"use strict"; -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)')() +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 stream = 1 === fd ? process.stdout : - 2 === fd ? process.stderr : - createWritableStdioStream(fd); - -/** - * Is stdout a TTY? Colored output is enabled when `true`. - */ - -function useColors() { - return 'colors' in exports.inspectOpts - ? Boolean(exports.inspectOpts.colors) - : tty.isatty(fd); +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)), + }; } - -/** - * 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. - */ - -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]; - } +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); + }); } - -/** - * Invokes `util.format()` with the specified arguments and writes to `stream`. - */ - -function log() { - return stream.write(util.format.apply(util, arguments) + '\n'); +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)); } - -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @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.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; } - -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ - -function load() { - return process.env.DEBUG; +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; + } + } } - -/** - * 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. - */ - -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(); - } - 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; +exports.weightSrvRecords = weightSrvRecords; +function getConnectionName(component, nodeConnectionName) { + const prefix = `ioredis-cluster(${component})`; + return nodeConnectionName ? `${prefix}:${nodeConnectionName}` : prefix; } +exports.getConnectionName = getConnectionName; -/** - * Init logic for `debug` instances. - * - * Create a new `inspectOpts` object in case `useColors` is set - * differently for a particular `debug` instance. - */ -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]]; - } -} +/***/ 90803: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; +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); /** - * Enable namespaces listed in `process.env.DEBUG` initially. + * 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 */ - -exports.enable(load()); +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; + } + getKeys() { + return this._iterateKeys(); + } + /** + * 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; + } + /** + * 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(); + } + else { + result = commandStr; + for (const arg of this.args) { + result += + "$" + + Buffer.byteLength(arg) + + "\r\n" + + arg + + "\r\n"; + } + } + 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); + } + } + } + /** + * 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; + }; + } + /** + * 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")); + } + }, ms); + } + } +} +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])); + } + } + 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 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; + } +} /***/ }), -/***/ 27025: -/***/ ((module) => { - -/** - * Helpers. - */ +/***/ 33642: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -var s = 1000; -var m = s * 60; -var h = m * 60; -var d = h * 24; -var y = d * 365.25; +"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."; /** - * Parse or format the given `val`. + * Commander * - * Options: + * This is the base class of Redis, Redis.Cluster and Pipeline * - * - `long` verbose formatting [false] + * @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 * - * @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 + * @return {string[]} command list + * @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) - ); +Commander.prototype.getBuiltinCommands = function () { + return commands.slice(0); }; - /** - * Parse the given `str` and return milliseconds. + * Create a builtin command * - * @param {String} str - * @return {Number} - * @api private + * @param {string} commandName - command name + * @return {object} functions + * @public */ - -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; - } -} - +Commander.prototype.createBuiltinCommand = function (commandName) { + return { + string: generateFunction(null, commandName, "utf8"), + buffer: generateFunction(null, commandName, null), + }; +}; /** - * Short format for `ms`. + * Create add builtin command * - * @param {Number} ms - * @return {String} - * @api private + * @param {string} commandName - command name + * @return {object} functions + * @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'; -} - +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; /** - * Long format for `ms`. + * Define a custom command using lua script * - * @param {Number} ms - * @return {String} - * @api private + * @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 */ - -function fmtLong(ms) { - return plural(ms, d, 'day') || - plural(ms, h, 'hour') || - plural(ms, m, 'minute') || - plural(ms, s, 'second') || - ms + ' ms'; -} - +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); +}; /** - * Pluralization helper. + * Send a command + * + * @abstract + * @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'; +Commander.prototype.sendCommand = function () { }; +function generateFunction(functionName, _commandName, _encoding) { + if (typeof _encoding === "undefined") { + _encoding = _commandName; + _commandName = null; + } + 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); + }; } /***/ }), -/***/ 24826: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 72712: +/***/ ((__unused_webpack_module, 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; + } + 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; -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 }) +/***/ 22913: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - const compileRestore = restorer({ secret, wcLen }) - const strict = 'strict' in opts ? opts.strict : true +"use strict"; - return redactor({ secret, wcLen, serialize, strict, isCensorFct, censorFctTakesPath }, state({ - secret, - censor, - compileRestore, - serialize, - groupRedact, - nestedRedact, - wildcards, - wcLen - })) +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); + }); + } + 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.FailoverDetector = FailoverDetector; /***/ }), -/***/ 54865: -/***/ ((module) => { +/***/ 72225: +/***/ ((__unused_webpack_module, exports) => { "use strict"; - -module.exports = { - groupRedact, - groupRestore, - nestedRedact, - nestedRestore +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 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] - } +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 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 +/***/ 10379: +/***/ (function(__unused_webpack_module, 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 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); + }); } - } - 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 - } -} - -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 }) + 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"); + }); } - } - 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 +exports["default"] = SentinelConnector; +function selectPreferredSentinel(availableSlaves, preferredSlaves) { + if (availableSlaves.length === 0) { + return null; } - 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 } + 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); } - -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 addressResponseToAddress(input) { + return { host: input.ip, port: Number(input.port) }; } +function noop() { } /***/ }), -/***/ 96214: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 8774: +/***/ ((__unused_webpack_module, 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 - } +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); + }); + }); } - return o - }, {}) - - return { wildcards, wcLen, secret } } +exports["default"] = StandaloneConnector; /***/ }), -/***/ 17333: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 72340: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; +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; -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` +/***/ 61823: +/***/ ((__unused_webpack_module, exports) => { - const circularDetection = ` - switch (true) { - ${hops.reverse().map((p) => ` - case o${delim}${p} === censor: - secret[${escPath}].circle = ${JSON.stringify(p)} - break - `).join('\n')} - } - ` +"use strict"; - const censorArgs = censorFctTakesPath - ? `val, ${JSON.stringify(arrPath)}` - : `val` +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", + }, +}; - 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}) - } +/***/ }), + +/***/ 97282: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +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; -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)` +/***/ }), + +/***/ 90735: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +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; /***/ }), -/***/ 98806: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 23961: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const MaxRetriesPerRequestError_1 = __nccwpck_require__(90735); +exports.MaxRetriesPerRequestError = MaxRetriesPerRequestError_1.default; -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) - .filter((path) => secret[path].precensored === false) - 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) - } -} +/***/ 45069: +/***/ ((module, exports, __nccwpck_require__) => { -/** - * 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('') +"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; -function restoreTmpl (resetters, paths, hasWildcards) { - const dynamicReset = hasWildcards === true ? ` - const keys = Object.keys(secret) - const len = keys.length - for (var i = ${paths.length}; i < len; i++) { - const k = keys[i] - const o = secret[k] - if (o.flat === true) this.groupRestore(o) - else this.nestedRestore(o) - secret[k] = null + +/***/ }), + +/***/ 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; + } + } + } + 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; + } + 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; + } + 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; } - ` : '' - - return ` - const secret = this.secret - ${resetters} - ${dynamicReset} - 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) => { +/***/ 71475: +/***/ ((__unused_webpack_module, exports) => { "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) +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; /***/ }), -/***/ 74174: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 1422: +/***/ ((__unused_webpack_module, exports) => { "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)) - } - }) - } -} +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, +}; /***/ }), -/***/ 17676: -/***/ ((module) => { - -module.exports = stringify -stringify.default = stringify -stringify.stable = deterministicStringify -stringify.stableStringify = deterministicStringify +/***/ 74276: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -var arr = [] -var replacerStack = [] +"use strict"; -// Regular stringify -function stringify (obj, replacer, spacer) { - decirc(obj, '', [], undefined) - var res - if (replacerStack.length === 0) { - res = JSON.stringify(obj, replacer, spacer) - } else { - res = JSON.stringify(obj, replaceGetterValues(replacer), spacer) - } - 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 -} -function decirc (val, k, stack, parent) { - var i - if (typeof val === 'object' && val !== null) { - for (i = 0; i < stack.length; i++) { - if (stack[i] === val) { - var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k) - if (propertyDescriptor.get !== undefined) { - if (propertyDescriptor.configurable) { - Object.defineProperty(parent, k, { value: '[Circular]' }) - arr.push([parent, k, val, propertyDescriptor]) - } else { - replacerStack.push([val, k]) - } - } else { - parent[k] = '[Circular]' - arr.push([parent, k, val]) +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); + } + } + }); } - 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, stack, val) - } - } else { - var keys = Object.keys(val) - for (i = 0; i < keys.length; i++) { - var key = keys[i] - decirc(val[key], key, stack, val) - } - } - stack.pop() - } + 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); + } + } + }); + } + }; } - -// Stable-stringify -function compareFunction (a, b) { - if (a < b) { - return -1 - } - if (a > b) { - return 1 - } - return 0 +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; } - -function deterministicStringify (obj, replacer, spacer) { - var tmp = deterministicDecirc(obj, '', [], undefined) || obj - var res - if (replacerStack.length === 0) { - res = JSON.stringify(tmp, replacer, spacer) - } else { - res = JSON.stringify(tmp, replaceGetterValues(replacer), spacer) - } - 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] +// 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++; } - } - return res } - -function deterministicDecirc (val, k, stack, parent) { - var i - if (typeof val === 'object' && val !== null) { - for (i = 0; i < stack.length; i++) { - if (stack[i] === val) { - var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k) - if (propertyDescriptor.get !== undefined) { - if (propertyDescriptor.configurable) { - Object.defineProperty(parent, k, { value: '[Circular]' }) - arr.push([parent, k, val, propertyDescriptor]) - } else { - replacerStack.push([val, k]) - } - } else { - parent[k] = '[Circular]' - arr.push([parent, k, val]) +// 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++; } - return - } - } - if (typeof val.toJSON === 'function') { - 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++) { - deterministicDecirc(val[i], i, stack, val) - } - } 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, stack, val) - tmp[key] = val[key] - } - if (parent !== undefined) { - arr.push([parent, k, val]) - parent[k] = tmp - } else { - return tmp - } } - stack.pop() - } } - -// wraps replacer function to handle values we couldn't replace -// and mark them as [Circular] -function replaceGetterValues (replacer) { - replacer = 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 = '[Circular]' - replacerStack.splice(i, 1) - break +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)); } - return replacer.call(this, key, val) - } } +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; + } + 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); + } + }; +} +exports.readyHandler = readyHandler; /***/ }), -/***/ 34578: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 83609: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -/* -Copyright (c) 2014 Petka Antonov - -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: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -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; - - this.auth = null; - this.slashes = null; - this.host = null; - this.hostname = null; - this.hash = null; - this.search = null; - this.pathname = null; +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. - this._prependSlash = false; + * // 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); + } } - -var querystring = __nccwpck_require__(63477); - -Url.queryString = querystring; - -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); +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; + } + if (typeof arg === "object") { + lodash_1.defaults(this.options, arg); + } + else if (typeof arg === "string") { + lodash_1.defaults(this.options, utils_1.parseURL(arg)); + if (arg.startsWith("rediss://")) { + isTls = true; + } + } + else if (typeof arg === "number") { + this.options.port = arg; + } + else { + throw new Error("Invalid argument " + arg); + } } - var start = 0; - var end = str.length - 1; - - //Trim leading and trailing ws - while (str.charCodeAt(start) <= 0x20 /*' '*/) start++; - while (str.charCodeAt(end) <= 0x20 /*' '*/) end--; - - start = this._parseProtocol(str, start, end); - - //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 (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; } + // 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 (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.reconnectTimeout && !reconnect) { + clearTimeout(this.reconnectTimeout); + this.reconnectTimeout = null; } - - if (!this.pathname && this.hostname && - this._slashProtocols[this._protocol]) { - this.pathname = "/"; + if (this.status === "wait") { + eventHandler.closeHandler(this)(); } - - 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); + else { + this.connector.disconnect(); } }; - -Url.prototype.resolve = function Url$resolve(relative) { - return this.resolveObject(Url.parse(relative, false, true)).format(); +/** + * Disconnect from Redis. + * + * @deprecated + */ +Redis.prototype.end = function () { + this.disconnect(); }; - -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 : ""; - } - - if (protocol && protocol.charCodeAt(protocol.length - 1) !== 0x3A /*':'*/) - protocol += ":"; - - if (this.host) { - host = auth + this.host; - } - else if (hostname) { - var ip6 = hostname.indexOf(":") > -1; - if (ip6) hostname = "[" + hostname + "]"; - host = auth + hostname + (port ? ":" + port : ""); +/** + * 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); } - - var slashes = this.slashes || - ((!protocol || - slashProtocols[protocol]) && host !== false); - - - if (protocol) scheme = protocol + (slashes ? "//" : ""); - else if (slashes) scheme = "//"; - - if (slashes && pathname && pathname.charCodeAt(0) !== 0x2F /*'/'*/) { - pathname = "/" + pathname; + 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); } - if (search && search.charCodeAt(0) !== 0x3F /*'?'*/) - search = "?" + search; - if (hash && hash.charCodeAt(0) !== 0x23 /*'#'*/) - hash = "#" + hash; - - pathname = escapePathName(pathname); - search = escapeSearch(search); - - return scheme + (host === false ? "" : host) + pathname + search + hash; }; - -Url.prototype.resolveObject = function Url$resolveObject(relative) { - if (typeof relative === "string") - relative = Url.parse(relative, false, true); - - var result = this._clone(); - - // hash is always overridden, no matter what. - // even href="" will remove it. - result.hash = relative.hash; - - // if the relative url is empty, then there"s nothing left to do here. - if (!relative.href) { - result._href = ""; - return result; - } - - // 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 = "/"; +/** + * 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); } - 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; - } - - 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; + 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); + } } - - 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; } - - 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)); - - var removeAllDots = mustEndAbs; - - var srcPath = result.pathname && result.pathname.split("/") || []; - var relPath = relative.pathname && relative.pathname.split("/") || []; - var psychotic = result._protocol && !slashProtocols[result._protocol]; - - // 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); +}; +/** + * 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); } - 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); + 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; } - relative.host = ""; } - mustEndAbs = mustEndAbs && (relPath[0] === "" || srcPath[0] === ""); - } - - 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(); + if (!info.loading || info.loading === "0") { + callback(null, info); + } + 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); + } + }); +}; +/** + * 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.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; } } - result.search = relative.search; - result._href = ""; - return result; } - - if (!srcPath.length) { - // no path at all. easy. - // we"ve already handled the other stuff above. - result.pathname = null; - result._href = ""; - return result; + 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); + }); + }), 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 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 === ""); - - // 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--; - } + 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 the path is allowed to go above the root, restore leading ..s - if (!mustEndAbs && !removeAllDots) { - for (; up--; up) { - srcPath.unshift(".."); - } + if (typeof this.options.commandTimeout === "number") { + command.setTimeout(this.options.commandTimeout); } - - if (mustEndAbs && srcPath[0] !== "" && - (!srcPath[0] || srcPath[0].charCodeAt(0) !== 0x2F /*'/'*/)) { - srcPath.unshift(""); + if (command.name === "quit") { + clearInterval(this._addedScriptHashesCleanInterval); + this._addedScriptHashesCleanInterval = null; } - - if (hasTrailingSlash && (srcPath.join("/").substr(-1) !== "/")) { - srcPath.push(""); + let writable = this.status === "ready" || + (!stream && + this.status === "connect" && + commands.exists(command.name) && + commands.hasFlag(command.name, "loading")); + if (!this.stream) { + writable = false; } - - var isAbsolute = srcPath[0] === "" || - (srcPath[0] && srcPath[0].charCodeAt(0) === 0x2F /*'/'*/); - - // 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(); - } + else if (!this.stream.writable) { + writable = false; } - - mustEndAbs = mustEndAbs || (result.host && srcPath.length); - - if (mustEndAbs && !isAbsolute) { - srcPath.unshift(""); + else if (this.stream._writableState && this.stream._writableState.ended) { + // https://github.com/iojs/io.js/pull/1217 + writable = false; } - - result.pathname = srcPath.length === 0 ? null : srcPath.join("/"); - result.auth = relative.auth || result.auth; - result.slashes = result.slashes || relative.slashes; - result._href = ""; - return result; -}; - -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 escapePathName = Url.prototype._escapePathName = -function Url$_escapePathName(pathname) { - if (!containsCharacter2(pathname, 0x23 /*'#'*/, 0x3F /*'?'*/)) { - return pathname; + if (!writable && !this.options.enableOfflineQueue) { + command.reject(new Error("Stream isn't writeable and enableOfflineQueue options is false")); + return command.promise; } - //Avoid closure creation to keep this inlinable - return _escapePath(pathname); -}; - -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); -}; - -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); - - 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; + 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); } - else { - return start; + (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 start; -}; - -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; -}; - -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; - - for (var i = start; i <= end; ++i) { - var ch = str.charCodeAt(i); - - 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; + 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); } - + this.offlineQueue.push({ + command: command, + stream: stream, + select: this.condition.select, + }); } - if ((port === 0 && !hadChars) || !validPort) { - if (!validPort) { - this._port = -2; + 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 0; } - - this._port = port; - return i - start; + return command.promise; }; - -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; +/** + * Get description of the connection. Used for debugging. + * @private + */ +Redis.prototype._getDescription = function () { + let description; + if (this.options.path) { + description = this.options.path; } - //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; + 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)); + }; +}); - var doLowerCase = false; - var idna = false; - var hostNameStart = start; - var hostNameEnd = end; - var lastCh = -1; - var portLength = 0; - var charsAfterDot = 0; - var authNeedsDecoding = false; - 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); +/***/ 88540: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (ch === 0x40 /*'@'*/) { - j = i; +"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); } - //This check is very, very cheap. Unneeded decodeURIComponent is very - //very expensive - else if (ch === 0x25 /*'%'*/) { - authNeedsDecoding = true; + if (this.keyPrefix) { + options.keyPrefix = this.keyPrefix; } - else if (hostEndingCharacters[ch] === 1) { - break; + 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; - //@-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; - } +/***/ 14645: +/***/ ((__unused_webpack_module, 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); +"use strict"; - if (ch === 0x3A /*':'*/) { - portLength = this._parsePort(str, i + 1, end) + 1; - hostNameEnd = i - 1; - break; +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); } - 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; + return pipeline; + }; + 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 if (0x41 /*'A'*/ <= ch && ch <= 0x5A /*'Z'*/) { - doLowerCase = true; + if (this._transactions > 0) { + exec.call(pipeline); } - //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; + // Returns directly when the pipeline + // has been called multiple times (retries). + if (this.nodeifiedPromise) { + return exec.call(pipeline); } - } - else if (ch >= 0x7B /*'{'*/) { - if (ch <= 0x7E /*'~'*/) { - if (this._noPrependSlashHostEnders[ch] === 0) { - this._prependSlash = true; + 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."); } - hostNameEnd = i - 1; - break; + 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); } - idna = true; - } - lastCh = ch; - charsAfterDot++; - } - - //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; + 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); + }; +} +exports.addTransactionSupport = addTransactionSupport; -}; -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; -}; +/***/ 85356: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -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; - } +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; } - 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 ? "/:" : ""; - - 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; + 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 } - else if (!disableAutoEscapeChars && !escape && autoEscapeCharacters[ch] === 1) { - escape = true; + // 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 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; - if (pathStart > pathEnd) { - this.pathname = prePath === "" ? "/" : prePath; - return; - } - - 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; -}; -Url.prototype._parseQuery = function Url$_parseQuery(str, start, end, disableAutoEscapeChars) { - var queryStart = start; - var queryEnd = end; - var escape = false; - var autoEscapeCharacters = this._autoEscapeCharacters; +/***/ }), - for (var i = start; i <= end; ++i) { - var ch = str.charCodeAt(i); +/***/ 94832: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (ch === 0x23 /*'#'*/) { - this._parseHash(str, i, end, disableAutoEscapeChars); - queryEnd = i - 1; - break; - } - else if (!disableAutoEscapeChars && !escape && autoEscapeCharacters[ch] === 1) { - escape = true; - } - } +"use strict"; - if (queryStart > queryEnd) { - this.search = ""; - return; +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); } - - var query; - if (escape) { - query = this._getComponentEscaped(str, queryStart, queryEnd, true); + if (a.length !== b.length) { + return false; } - else { - query = str.slice(queryStart, queryEnd + 1); + for (let i = 0; i < a.length; ++i) { + if (a[i] !== b[i]) { + return false; + } } - this.search = query; -}; - -Url.prototype._parseHash = function Url$_parseHash(str, start, end, disableAutoEscapeChars) { - if (start > end) { - this.hash = ""; - return; + 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); } - - 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); + 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; - }, - set: function(v) { - if (v == null) { - this._port = -1; + } + 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 { - this._port = parseInt(v, 10); + result.push([null, item]); } } -}); - -Object.defineProperty(Url.prototype, "query", { - get: function() { - var query = this._query; - if (query != null) { - return query; + 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); } - var search = this.search; - - if (search) { - if (search.charCodeAt(0) === 0x3F /*'?'*/) { - search = search.slice(1); - } - if (search !== "") { - this._query = search; - return search; - } + }; + 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; } - return search; - }, - set: function(v) { - this._query = v; } -}); - -Object.defineProperty(Url.prototype, "path", { - get: function() { - var p = this.pathname || ""; - var s = this.search || ""; - if (p || s) { - return p + s; + 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); } - 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; + 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 if (v == null) { - this._protocol = null; - } - } -}); - -Object.defineProperty(Url.prototype, "href", { - get: function() { - var href = this._href; - if (!href) { - href = this._href = this.format(); + else { + result.path = parsed.pathname; } - 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; -}; - -Url.format = function Url$Format(obj) { - if (typeof obj === "string") { - obj = Url.parse(obj); + if (parsed.host) { + result.host = parsed.hostname; } - if (!(obj instanceof Url)) { - return Url.prototype.format.call(obj); + if (parsed.port) { + result.port = parsed.port; } - 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); -}; - -function _escapePath(pathname) { - return pathname.replace(/[?#]/g, function(match) { - return encodeURIComponent(match); - }); + lodash_1.defaults(result, options); + return result; } - -function _escapeSearch(search) { - return search.replace(/#/g, function(match) { - return encodeURIComponent(match); - }); +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; } - -//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); - - if (ch === char1) { - return true; - } - else if (stopCharacterTable[ch] === 1) { - return false; - } +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 false; + return array[from + Math.floor(Math.random() * (length - from))]; } - -//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; +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 false; + 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; -//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] -//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; - } - } - }); +/***/ }), - return ret; -} +/***/ 20961: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +"use strict"; -var autoEscape = ["<", ">", "\"", "`", " ", "\r", "\n", - "\t", "{", "}", "|", "\\", "^", "`", "'"]; +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; -var autoEscapeMap = new Array(128); +/***/ }), +/***/ 37263: +/***/ (function(module, __unused_webpack_exports, __nccwpck_require__) { -for (var i = 0, len = autoEscapeMap.length; i < len; ++i) { - autoEscapeMap[i] = ""; -} +/* module decorator */ module = __nccwpck_require__.nmd(module); +(function() { + var expandIPv6, ipaddr, ipv4Part, ipv4Regexes, ipv6Part, ipv6Regexes, matchCIDR, root, zoneIndex; -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 /*'\'*/] = "/"; + ipaddr = {}; -var slashProtocols = Url.prototype._slashProtocols = { - http: true, - https: true, - gopher: true, - file: true, - ftp: true, + root = this; - "http:": true, - "https:": true, - "gopher:": true, - "file:": true, - "ftp:": true -}; + if (( true && module !== null) && module.exports) { + module.exports = ipaddr; + } else { + root['ipaddr'] = ipaddr; + } -//Optimize back from normalized object caused by non-identifier keys -function f(){} -f.prototype = slashProtocols; + 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"); + } + 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; + }; -Url.prototype._protocolCharacters = makeAsciiTable([ - [0x61 /*'a'*/, 0x7A /*'z'*/], - [0x41 /*'A'*/, 0x5A /*'Z'*/], - 0x2E /*'.'*/, 0x2B /*'+'*/, 0x2D /*'-'*/ -]); + ipaddr.subnetMatch = function(address, rangeList, defaultName) { + var k, len, rangeName, rangeSubnets, subnet; + if (defaultName == null) { + defaultName = 'unicast'; + } + 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; + } + } + } + } + return defaultName; + }; -Url.prototype._hostEndingCharacters = makeAsciiTable([ - 0x23 /*'#'*/, 0x3F /*'?'*/, 0x2F /*'/'*/, 0x5C /*'\'*/ -]); + 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; + } -Url.prototype._autoEscapeCharacters = makeAsciiTable( - autoEscape.map(function(v) { - return v.charCodeAt(0); - }) -); + IPv4.prototype.kind = function() { + return 'ipv4'; + }; -//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); - }) -); + IPv4.prototype.toString = function() { + return this.octets.join("."); + }; -Url.prototype._autoEscapeMap = autoEscapeMap; -Url.prototype._afterQueryAutoEscapeMap = afterQueryAutoEscapeMap; + IPv4.prototype.toNormalizedString = function() { + return this.toString(); + }; -module.exports = Url; + IPv4.prototype.toByteArray = function() { + return this.octets.slice(0); + }; -Url.replace = function Url$Replace() { - require.cache.url = { - exports: Url + 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); + }; -/***/ 30810: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + IPv4.prototype.toIPv4MappedAddress = function() { + return ipaddr.IPv6.parse("::ffff:" + (this.toString())); + }; -"use strict"; -/*! - * finalhandler - * Copyright(c) 2014-2017 Douglas Christopher Wilson - * MIT Licensed - */ + 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 IPv4; + })(); -/** - * Module dependencies. - * @private - */ + ipv4Part = "(0?\\d+|0x[a-f0-9]+)"; -var debug = __nccwpck_require__(65612)('finalhandler') -var encodeUrl = __nccwpck_require__(16592) -var escapeHtml = __nccwpck_require__(94070) -var onFinished = __nccwpck_require__(92098) -var parseUrl = __nccwpck_require__(89808) -var statuses = __nccwpck_require__(57415) -var unpipe = __nccwpck_require__(3124) + ipv4Regexes = { + fourOctet: new RegExp("^" + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "$", 'i'), + longValue: new RegExp("^" + ipv4Part + "$", 'i') + }; -/** - * Module variables. - * @private - */ + 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)); + } + 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; + } + }; + + 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; + } + } -var DOUBLE_SPACE_REGEXP = /\x20{2}/g -var NEWLINE_REGEXP = /\n/g + IPv6.prototype.kind = function() { + return 'ipv6'; + }; -/* istanbul ignore next */ -var defer = typeof setImmediate === 'function' - ? setImmediate - : function (fn) { process.nextTick(fn.bind.apply(fn, arguments)) } -var isFinished = onFinished.isFinished + IPv6.prototype.toString = function() { + return this.toNormalizedString().replace(/((^|:)(0(:|$))+)/, '::'); + }; -/** - * Create a minimal HTML document. - * - * @param {string} message - * @private - */ + 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); + }; -function createHtmlDocument (message) { - var body = escapeHtml(message) - .replace(NEWLINE_REGEXP, '
') - .replace(DOUBLE_SPACE_REGEXP, '  ') + 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; + }; - return '\n' + - '\n' + - '\n' + - '\n' + - 'Error\n' + - '\n' + - '\n' + - '
' + body + '
\n' + - '\n' + - '\n' -} + 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; + }; -/** - * Module exports. - * @public - */ + 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; + }; -module.exports = finalhandler + 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); + }; -/** - * Create a function to handle the final response. - * - * @param {Request} req - * @param {Response} res - * @param {Object} [options] - * @return {Function} - * @public - */ + 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]] + }; -function finalhandler (req, res, options) { - var opts = options || {} + IPv6.prototype.range = function() { + return ipaddr.subnetMatch(this, this.SpecialRanges); + }; - // get environment - var env = opts.env || process.env.NODE_ENV || 'development' + IPv6.prototype.isIPv4MappedAddress = function() { + return this.range() === 'ipv4Mapped'; + }; - // get error callback - var onerror = opts.onerror + 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]); + }; - return function (err) { - var headers - var msg - var status + 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; + }; - // ignore 404 on in-flight response - if (!err && headersSent(res)) { - debug('cannot 404 after headers sent') - return - } + return IPv6; - // unhandled error - if (err) { - // respect status code from error - status = getErrorStatusCode(err) + })(); - if (status === undefined) { - // fallback to status code on response - status = getResponseStatusCode(res) - } else { - // respect headers from error - headers = getErrorHeaders(err) - } + ipv6Part = "(?:[0-9a-f]+::?)+"; - // get error message - msg = getErrorMessage(err, status, env) - } else { - // not found - status = 404 - msg = 'Cannot ' + req.method + ' ' + encodeUrl(getResourceName(req)) - } + zoneIndex = "%[0-9a-z]{1,}"; - debug('default %s', status) + 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') + }; - // schedule onerror callback - if (err && onerror) { - defer(onerror, err, req, res) + expandIPv6 = function(string, parts) { + var colonCount, lastColon, part, replacement, replacementCount, zoneId; + if (string.indexOf('::') !== string.lastIndexOf('::')) { + return null; } - - // cannot actually respond - if (headersSent(res)) { - debug('cannot %d after headers sent', status) - req.socket.destroy() - return + zoneId = (string.match(ipv6Regexes['zoneIndex']) || [])[0]; + if (zoneId) { + zoneId = zoneId.substring(1); + string = string.replace(/%.+$/, ''); } + colonCount = 0; + lastColon = -1; + while ((lastColon = string.indexOf(':', lastColon + 1)) >= 0) { + colonCount++; + } + if (string.substr(0, 2) === '::') { + colonCount--; + } + if (string.substr(-2, 2) === '::') { + colonCount--; + } + if (colonCount > parts) { + return null; + } + 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 + }; + }; - // send response - send(req, res, status, headers, msg) - } -} - -/** - * Get headers from Error object. - * - * @param {Error} err - * @return {object} - * @private - */ + 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; + } + } + 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; + }; -function getErrorHeaders (err) { - if (!err.headers || typeof err.headers !== 'object') { - return undefined - } + ipaddr.IPv4.isIPv4 = ipaddr.IPv6.isIPv6 = function(string) { + return this.parser(string) !== null; + }; - var headers = Object.create(null) - var keys = Object.keys(err.headers) + ipaddr.IPv4.isValid = function(string) { + var e; + try { + new this(this.parser(string)); + return true; + } catch (error1) { + e = error1; + return false; + } + }; - for (var i = 0; i < keys.length; i++) { - var key = keys[i] - headers[key] = err.headers[key] - } + 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; + } + }; - return headers -} + ipaddr.IPv6.isValid = function(string) { + var addr, e; + if (typeof string === "string" && string.indexOf(":") === -1) { + return false; + } + try { + addr = this.parser(string); + new this(addr.parts, addr.zoneId); + return true; + } catch (error1) { + e = error1; + return false; + } + }; -/** - * Get message from Error object, fallback to status message. - * - * @param {Error} err - * @param {number} status - * @param {string} env - * @return {string} - * @private - */ + 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); + }; -function getErrorMessage (err, status, env) { - var msg + 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); + }; - if (env !== 'production') { - // use err.stack, which typically includes err.message - msg = err.stack + 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"); + }; - // fallback to err.toString() when possible - if (!msg && typeof err.toString === 'function') { - msg = err.toString() + 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); + }; - return msg || statuses[status] -} + 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'); + } + }; -/** - * Get status code from Error object. - * - * @param {Error} err - * @return {number} - * @private - */ + 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'); + } + }; -function getErrorStatusCode (err) { - // check err.status - if (typeof err.status === 'number' && err.status >= 400 && err.status < 600) { - return err.status - } + 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"); + }; - // check err.statusCode - if (typeof err.statusCode === 'number' && err.statusCode >= 400 && err.statusCode < 600) { - return err.statusCode - } + ipaddr.isValid = function(string) { + return ipaddr.IPv6.isValid(string) || ipaddr.IPv4.isValid(string); + }; - return undefined -} + 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"); + } + }; -/** - * 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 - */ + 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"); + } + } + }; -function getResourceName (req) { - try { - return parseUrl.original(req).pathname - } catch (e) { - return 'resource' - } -} + 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"); + } + }; -/** - * Get status code from response. - * - * @param {OutgoingMessage} res - * @return {number} - * @private - */ + ipaddr.process = function(string) { + var addr; + addr = this.parse(string); + if (addr.kind() === 'ipv6' && addr.isIPv4MappedAddress()) { + return addr.toIPv4Address(); + } else { + return addr; + } + }; -function getResponseStatusCode (res) { - var status = res.statusCode +}).call(this); - // default status code to 500 if outside valid range - if (typeof status !== 'number' || status < 400 || status > 599) { - status = 500 - } - return status -} +/***/ }), -/** - * Determine if the response headers have been sent. - * - * @param {object} res - * @returns {boolean} - * @private - */ +/***/ 7604: +/***/ ((module) => { -function headersSent (res) { - return typeof res.headersSent !== 'boolean' - ? Boolean(res._header) - : res.headersSent -} +"use strict"; -/** - * 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) +module.exports = function isArrayish(obj) { + if (!obj) { + return false; + } - // response status - res.statusCode = status - res.statusMessage = statuses[status] + return obj instanceof Array || Array.isArray(obj) || + (obj.length >= 0 && obj.splice instanceof Function); +}; - // 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')) +/***/ 31310: +/***/ (function(module, exports) { - if (req.method === 'HEAD') { - res.end() - return +;(function(root) { + 'use strict'; + + function isBase64(v, opts) { + if (v instanceof Boolean || typeof v === 'boolean') { + return false } - res.end(body, 'utf8') - } + if (!(opts instanceof Object)) { + opts = {} + } - if (isFinished(req)) { - write() - return - } + if (opts.allowEmpty === false && v === '') { + return false + } - // unpipe everything from the request - unpipe(req) + 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,)' - // flush the request - onFinished(req, write) - req.resume() -} + if (opts.mimeRequired === true) { + regex = mimeRegex + regex + } else if (opts.allowMime === true) { + regex = mimeRegex + '?' + regex + } -/** - * Set response headers from an object. - * - * @param {OutgoingMessage} res - * @param {object} headers - * @private - */ + if (opts.paddingRequired === false) { + regex = '(?:[A-Za-z0-9+\\/]{4})*(?:[A-Za-z0-9+\\/]{2}(==)?|[A-Za-z0-9+\\/]{3}=?)?' + } -function setHeaders (res, headers) { - if (!headers) { - return + return (new RegExp('^' + regex + '$', 'gi')).test(v) } - var keys = Object.keys(headers) - for (var i = 0; i < keys.length; i++) { - var key = keys[i] - res.setHeader(key, headers[key]) - } -} + if (true) { + if ( true && module.exports) { + exports = module.exports = isBase64 + } + exports.isBase64 = isBase64 + } else {} +})(this); /***/ }), -/***/ 56401: -/***/ ((module, exports, __nccwpck_require__) => { - -/** - * 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(); +/***/ 56873: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * Colors. - */ +"use strict"; -exports.colors = [ - 'lightseagreen', - 'forestgreen', - 'goldenrod', - 'dodgerblue', - 'darkorchid', - 'crimson' -]; -/** - * 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 has = __nccwpck_require__(76339); -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; - } +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('.'); - // 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+)/)); + 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 === '>='; } -/** - * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. - */ - -exports.formatters.j = function(v) { - try { - return JSON.stringify(v); - } catch (err) { - return '[UnexpectedJSONParseError]: ' + err.message; - } -}; - - -/** - * Colorize log arguments if enabled. - * - * @api public - */ - -function formatArgs(args) { - var useColors = this.useColors; - - args[0] = (useColors ? '%c' : '') - + this.namespace - + (useColors ? ' %c' : ' ') - + args[0] - + (useColors ? '%c ' : ' ') - + '+' + exports.humanize(this.diff); +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; +} - if (!useColors) return; +function versionIncluded(nodeVersion, specifierValue) { + if (typeof specifierValue === 'boolean') { + return specifierValue; + } - var c = 'color: ' + this.color; - args.splice(1, 0, c, 'color: inherit') + var current = typeof nodeVersion === 'undefined' + ? process.versions && process.versions.node && process.versions.node + : nodeVersion; - // 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 (typeof current !== 'string') { + throw new TypeError(typeof nodeVersion === 'undefined' ? 'Unable to determine current node version' : 'If provided, a valid node version is required'); + } - args.splice(lastC, 0, c); + 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); } -/** - * Invokes `console.log()` when available. - * No-op when `console.log` is not a "function". - * - * @api public - */ - -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); -} +var data = __nccwpck_require__(66151); -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ +module.exports = function isCore(x, nodeVersion) { + return has(data, x) && versionIncluded(nodeVersion, data[x]); +}; -function save(namespaces) { - try { - if (null == namespaces) { - exports.storage.removeItem('debug'); - } else { - exports.storage.debug = namespaces; - } - } catch(e) {} -} -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ +/***/ }), -function load() { - var r; - try { - r = exports.storage.debug; - } catch(e) {} +/***/ 64882: +/***/ ((module) => { - // 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; - } +"use strict"; +/* eslint-disable yoda */ - return r; -} -/** - * Enable namespaces listed in `localStorage.debug` initially. - */ +const isFullwidthCodePoint = codePoint => { + if (Number.isNaN(codePoint)) { + return false; + } -exports.enable(load()); + // 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; + } -/** - * 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 false; +}; -function localstorage() { - try { - return window.localStorage; - } catch (e) {} -} +module.exports = isFullwidthCodePoint; +module.exports["default"] = isFullwidthCodePoint; /***/ }), -/***/ 60545: -/***/ ((module, exports, __nccwpck_require__) => { - - -/** - * This is the common logic for both the Node.js and web browser - * implementations of `debug()`. - * - * Expose `debug()` as the module. - */ +/***/ 63287: +/***/ ((__unused_webpack_module, exports) => { -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); +"use strict"; -/** - * The currently active debug mode names, and names to skip. - */ -exports.names = []; -exports.skips = []; +Object.defineProperty(exports, "__esModule", ({ value: true })); -/** - * Map of special "%n" handling functions, for the debug "format" argument. +/*! + * is-plain-object * - * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". - */ - -exports.formatters = {}; - -/** - * Previous log timestamp. + * Copyright (c) 2014-2017, Jon Schlinkert. + * Released under the MIT License. */ -var prevTime; +function isObject(o) { + return Object.prototype.toString.call(o) === '[object Object]'; +} -/** - * Select a color. - * @param {String} namespace - * @return {Number} - * @api private - */ +function isPlainObject(o) { + var ctor,prot; -function selectColor(namespace) { - var hash = 0, i; + if (isObject(o) === false) return false; - for (i in namespace) { - hash = ((hash << 5) - hash) + namespace.charCodeAt(i); - hash |= 0; // Convert to 32bit integer + // 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; } - return exports.colors[Math.abs(hash) % exports.colors.length]; + // Most likely a plain Object + return true; } -/** - * Create a debugger with the given `namespace`. - * - * @param {String} namespace - * @return {Function} - * @api public - */ +exports.isPlainObject = isPlainObject; -function createDebug(namespace) { - function debug() { - // disabled? - if (!debug.enabled) return; +/***/ }), - var self = debug; +/***/ 87783: +/***/ ((__unused_webpack_module, exports) => { - // set `diff` timestamp - var curr = +new Date(); - var ms = curr - (prevTime || curr); - self.diff = ms; - self.prev = prevTime; - self.curr = curr; - prevTime = curr; +(function(exports) { + "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]; + function isArray(obj) { + if (obj !== null) { + return Object.prototype.toString.call(obj) === "[object Array]"; + } else { + return false; } + } - args[0] = exports.coerce(args[0]); - - if ('string' !== typeof args[0]) { - // anything else let's inspect with %O - args.unshift('%O'); + function isObject(obj) { + if (obj !== null) { + return Object.prototype.toString.call(obj) === "[object Object]"; + } else { + return false; } + } - // 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); + function strictDeepEqual(first, second) { + // Check the scalar case first. + if (first === second) { + return true; + } - // now we need to remove `args[index]` since it's inlined in the `format` - args.splice(index, 1); - index--; + // 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; } - return match; - }); + 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; + } - // apply env-specific formatting (colors, etc.) - exports.formatArgs.call(self, args); + function isFalse(obj) { + // From the spec: + // A false value corresponds to the following values: + // Empty list + // Empty object + // Empty string + // False boolean + // null value - var logFn = debug.log || exports.log || console.log.bind(console); - logFn.apply(self, args); + // 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; + } } - debug.namespace = namespace; - debug.enabled = exports.enabled(namespace); - debug.useColors = exports.useColors(); - debug.color = selectColor(namespace); + 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; + } - // env-specific initialization logic for debug instances - if ('function' === typeof exports.init) { - exports.init(debug); + 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; } - return debug; -} + var trimLeft; + if (typeof String.prototype.trimLeft === "function") { + trimLeft = function(str) { + return str.trimLeft(); + }; + } else { + trimLeft = function(str) { + return str.match(/^\s*(.*)/)[1]; + }; + } -/** - * Enables a debug mode by namespaces. This can include modes - * separated by a colon and wildcards. - * - * @param {String} namespaces - * @api public - */ + // 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; -function enable(namespaces) { - exports.save(namespaces); + 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"; - exports.names = []; - exports.skips = []; + // The "&", "[", "<", ">" tokens + // are not in basicToken because + // there are two token variants + // ("&&", "[?", "<=", ">="). This is specially handled + // below. - var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); - var len = split.length; + var basicTokens = { + ".": TOK_DOT, + "*": TOK_STAR, + ",": TOK_COMMA, + ":": TOK_COLON, + "{": TOK_LBRACE, + "}": TOK_RBRACE, + "]": TOK_RBRACKET, + "(": TOK_LPAREN, + ")": TOK_RPAREN, + "@": TOK_CURRENT + }; - 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 operatorStartToken = { + "<": true, + ">": true, + "=": true, + "!": true + }; -/** - * Disable debug output. - * - * @api public - */ + var skipChars = { + " ": true, + "\t": true, + "\n": true + }; -function disable() { - exports.enable(''); -} -/** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ + function isAlpha(ch) { + return (ch >= "a" && ch <= "z") || + (ch >= "A" && ch <= "Z") || + ch === "_"; + } -function enabled(name) { - var i, len; - for (i = 0, len = exports.skips.length; i < len; i++) { - if (exports.skips[i].test(name)) { - return false; - } + function isNum(ch) { + return (ch >= "0" && ch <= "9") || + ch === "-"; } - for (i = 0, len = exports.names.length; i < len; i++) { - if (exports.names[i].test(name)) { - return true; - } + function isAlphaNum(ch) { + return (ch >= "a" && ch <= "z") || + (ch >= "A" && ch <= "Z") || + (ch >= "0" && ch <= "9") || + ch === "_"; } - return false; -} -/** - * Coerce `val`. - * - * @param {Mixed} val - * @return {Mixed} - * @api private - */ + 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; + }, -function coerce(val) { - if (val instanceof Error) return val.stack || val.message; - return val; -} + _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("\\'", "'"); + }, + + _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}; + }, + + _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}; + } + }, + _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; + }, -/***/ 65612: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + _looksLikeJSON: function(literalString) { + var startingChars = "[{\""; + var jsonLiterals = ["true", "false", "null"]; + var numberLooking = "-0123456789"; -/** - * Detect Electron renderer process, which is node, but we should - * treat as a browser. - */ + 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; + } + } + }; -if (typeof process !== 'undefined' && process.type === 'renderer') { - module.exports = __nccwpck_require__(56401); -} else { - module.exports = __nccwpck_require__(4706); -} + 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; + 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; + }, -/***/ 4706: -/***/ ((module, exports, __nccwpck_require__) => { + _loadTokens: function(expression) { + var lexer = new Lexer(); + var tokens = lexer.tokenize(expression); + tokens.push({type: TOK_EOF, value: "", start: expression.length}); + this.tokens = tokens; + }, -/** - * Module dependencies. - */ + 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; + }, -var tty = __nccwpck_require__(76224); -var util = __nccwpck_require__(73837); + _lookahead: function(number) { + return this.tokens[this.index + number].type; + }, -/** - * This is the Node.js implementation of `debug()`. - * - * Expose `debug()` as the module. - */ + _lookaheadToken: function(number) { + return this.tokens[this.index + number]; + }, -exports = module.exports = __nccwpck_require__(60545); -exports.init = init; -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; + _advance: function() { + this.index++; + }, -/** - * Colors. - */ + 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); + } + }, -exports.colors = [6, 2, 3, 4, 5, 1]; + 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); + } + 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); + } + 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)); + } + }, -/** - * Build up the default `inspectOpts` object from the environment variables. - * - * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js - */ + _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; + } + }, -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() }); + _errorToken: function(token) { + var error = new Error("Invalid token (" + + token.type + "): \"" + + token.value + "\""); + error.name = "ParserError"; + throw error; + }, - // 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; -}, {}); + _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; + } + }, -/** - * 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 - */ + _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; + } + }, -var fd = parseInt(process.env.DEBUG_FD, 10) || 2; + _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 + }; + }, -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)')() -} + _parseComparator: function(left, comparator) { + var right = this.expression(bindingPower[comparator]); + return {type: "Comparator", name: comparator, children: [left, right]}; + }, -var stream = 1 === fd ? process.stdout : - 2 === fd ? process.stderr : - createWritableStdioStream(fd); + _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(); + } + }, -/** - * Is stdout a TTY? Colored output is enabled when `true`. - */ + _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; + }, -function useColors() { - return 'colors' in exports.inspectOpts - ? Boolean(exports.inspectOpts.colors) - : tty.isatty(fd); -} + _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}; + }, -/** - * Map %o to `util.inspect()`, all on a single line. - */ + _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}; + } + }; -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. - */ + function TreeInterpreter(runtime) { + this.runtime = runtime; + } -exports.formatters.O = function(v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts); -}; + TreeInterpreter.prototype = { + search: function(node, value) { + return this.visit(node, value); + }, -/** - * Adds ANSI color escape codes if enabled. - * - * @api public - */ + 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); -function formatArgs(args) { - var name = this.namespace; - var useColors = this.useColors; + 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); + } + }, - if (useColors) { - var c = this.color; - var prefix = ' \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m'; + 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; - 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 (start === null) { + start = stepValueNegative ? arrayLength - 1 : 0; + } else { + start = this.capSliceRange(arrayLength, start, step); + } -/** - * Invokes `util.format()` with the specified arguments and writes to `stream`. - */ + 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; + }, -function log() { - return stream.write(util.format.apply(util, arguments) + '\n'); -} + 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; + } -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @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; + 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}] + } + }; } -} -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ + 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); + }, -function load() { - return process.env.DEBUG; -} + _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); + } + 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."); + } + } + }, + + _typeMatches: function(actual, expected, argValue) { + if (expected === TYPE_ANY) { + return true; + } + 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; + } + } 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; + } + } + }, -/** - * 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. - */ + _functionStartsWith: function(resolvedArgs) { + return resolvedArgs[0].lastIndexOf(resolvedArgs[1]) === 0; + }, -function createWritableStdioStream (fd) { - var stream; - var tty_wrap = process.binding('tty_wrap'); + _functionEndsWith: function(resolvedArgs) { + var searchStr = resolvedArgs[0]; + var suffix = resolvedArgs[1]; + return searchStr.indexOf(suffix, searchStr.length - suffix.length) !== -1; + }, - // Note stream._type is used for test-module-load-list.js + _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; + } + }, - switch (tty_wrap.guessHandleType(fd)) { - case 'TTY': - stream = new tty.WriteStream(fd); - stream._type = 'tty'; + _functionAbs: function(resolvedArgs) { + return Math.abs(resolvedArgs[0]); + }, - // 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; + _functionCeil: function(resolvedArgs) { + return Math.ceil(resolvedArgs[0]); + }, - case 'FILE': - var fs = __nccwpck_require__(57147); - stream = new fs.SyncWriteStream(fd, { autoClose: false }); - stream._type = 'fs'; - break; + _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; + }, - case 'PIPE': - case 'TCP': - var net = __nccwpck_require__(41808); - stream = new net.Socket({ - fd: fd, - readable: false, - writable: true - }); + _functionContains: function(resolvedArgs) { + return resolvedArgs[0].indexOf(resolvedArgs[1]) >= 0; + }, - // 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'; + _functionFloor: function(resolvedArgs) { + return Math.floor(resolvedArgs[0]); + }, - // 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; + _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; + } + }, - default: - // Probably an error on in uv_guess_handle() - throw new Error('Implement me. Unknown stream file type!'); - } + _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; + }, - // For supporting legacy API we put the FD here. - stream.fd = fd; + _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; + }, - stream._isStdio = true; + _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; + } + }, - return stream; -} + _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; + } + }, -/** - * Init logic for `debug` instances. - * - * Create a new `inspectOpts` object in case `useColors` is set - * differently for a particular `debug` instance. - */ + _functionSum: function(resolvedArgs) { + var sum = 0; + var listToSum = resolvedArgs[0]; + for (var i = 0; i < listToSum.length; i++) { + sum += listToSum[i]; + } + return sum; + }, -function init (debug) { - debug.inspectOpts = {}; + _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"; + } + }, - var keys = Object.keys(exports.inspectOpts); - for (var i = 0; i < keys.length; i++) { - debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; - } -} + _functionKeys: function(resolvedArgs) { + return Object.keys(resolvedArgs[0]); + }, -/** - * Enable namespaces listed in `process.env.DEBUG` initially. - */ + _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; + }, -exports.enable(load()); + _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]]; + } + }, -/***/ }), + _functionToString: function(resolvedArgs) { + if (this._getTypeName(resolvedArgs[0]) === TYPE_STRING) { + return resolvedArgs[0]; + } else { + return JSON.stringify(resolvedArgs[0]); + } + }, -/***/ 80761: -/***/ ((module) => { + _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; + }, -/** - * Helpers. - */ + _functionNotNull: function(resolvedArgs) { + for (var i = 0; i < resolvedArgs.length; i++) { + if (this._getTypeName(resolvedArgs[i]) !== TYPE_NULL) { + return resolvedArgs[i]; + } + } + return null; + }, -var s = 1000; -var m = s * 60; -var h = m * 60; -var d = h * 24; -var y = d * 365.25; + _functionSort: function(resolvedArgs) { + var sortedArray = resolvedArgs[0].slice(0); + sortedArray.sort(); + return sortedArray; + }, -/** - * 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 - */ + _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; + }, -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) - ); -}; + _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; + }, -/** - * Parse the given `str` and return milliseconds. - * - * @param {String} str - * @return {Number} - * @api private - */ + _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; + }, -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; - } -} + 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; + } -/** - * Short format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ + }; -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'; + function compile(stream) { + var parser = new Parser(); + var ast = parser.parse(stream); + return ast; } - return ms + 'ms'; -} - -/** - * Long format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ - -function fmtLong(ms) { - return plural(ms, d, 'day') || - plural(ms, h, 'hour') || - plural(ms, m, 'minute') || - plural(ms, s, 'second') || - ms + ' ms'; -} - -/** - * Pluralization helper. - */ -function plural(ms, n, name) { - if (ms < n) { - return; + function tokenize(stream) { + var lexer = new Lexer(); + return lexer.tokenize(stream); } - if (ms < n * 1.5) { - return Math.floor(ms / n) + ' ' + name; + + 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 Math.ceil(ms / n) + ' ' + name + 's'; -} + + exports.tokenize = tokenize; + exports.compile = compile; + exports.search = search; + exports.strictDeepEqual = strictDeepEqual; +})( false ? 0 : exports); /***/ }), -/***/ 35298: -/***/ ((module) => { +/***/ 46014: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -// 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. +const Clone = __nccwpck_require__(85578); -function flatstr (s) { - s | 0 - return s -} +const Common = __nccwpck_require__(72448); -module.exports = flatstr -/***/ }), +const internals = { + annotations: Symbol('annotations') +}; -/***/ 46868: -/***/ ((module) => { -"use strict"; -/*! - * forwarded - * Copyright(c) 2014-2017 Douglas Christopher Wilson - * MIT Licensed - */ +exports.error = function (stripColorCodes) { + if (!this._original || + typeof this._original !== 'object') { + return this.details[0].message; + } -/** - * Module exports. - * @public - */ + const redFgEscape = stripColorCodes ? '' : '\u001b[31m'; + const redBgEscape = stripColorCodes ? '' : '\u001b[41m'; + const endColor = stripColorCodes ? '' : '\u001b[0m'; -module.exports = forwarded + const obj = Clone(this._original); -/** - * Get all addresses in the request, using the `X-Forwarded-For` header. - * - * @param {object} req - * @return {array} - * @public - */ + 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]; -function forwarded (req) { - if (!req) { - throw new TypeError('argument req is required') - } + if (Common.isSchema(node)) { + node = node.clone(); // joi schemas are not cloned by hoek, we have to take this extra step + } - // simple header parsing - var proxyAddrs = parse(req.headers['x-forwarded-for'] || '') - var socketAddr = req.connection.remoteAddress - var addrs = [socketAddr].concat(proxyAddrs) + if (j + 1 < path.length && + typeof node[seg] !== 'string') { - // return all addresses - return addrs -} + node = node[seg]; + } + else { + const refAnnotations = node[internals.annotations] || { errors: {}, missing: {} }; + node[internals.annotations] = refAnnotations; -/** - * Parse the X-Forwarded-For header. - * - * @param {string} header - * @private - */ + const cacheKey = seg || error.context.key; -function parse (header) { - var end = header.length - var list = [] - var start = header.length + if (node[seg] !== undefined) { + refAnnotations.errors[cacheKey] = refAnnotations.errors[cacheKey] || []; + refAnnotations.errors[cacheKey].push(pos); + } + else { + refAnnotations.missing[cacheKey] = pos; + } - // 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)) + break; + } } - start = end = i - break - default: - start = i - break } - } - // final address - if (start !== end) { - list.push(header.substring(start, end)) - } + 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 + }; - return list -} + 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}`; + } -/***/ 83136: -/***/ ((module) => { + message = message + endColor; -"use strict"; -/*! - * fresh - * Copyright(c) 2012 TJ Holowaychuk - * Copyright(c) 2016-2017 Douglas Christopher Wilson - * MIT Licensed - */ + return message; +}; +// Inspired by json-stringify-safe -/** - * RegExp to check for no-cache token in Cache-Control. - * @private - */ +internals.safeStringify = function (obj, spaces) { -var CACHE_CONTROL_NO_CACHE_REGEXP = /(?:^|,)\s*?no-cache\s*?(?:,|$)/ + return JSON.stringify(obj, internals.serializer(), spaces); +}; -/** - * Module exports. - * @public - */ -module.exports = fresh +internals.serializer = function () { -/** - * Check freshness of the response using request and response headers. - * - * @param {Object} reqHeaders - * @param {Object} resHeaders - * @return {Boolean} - * @public - */ + const keys = []; + const stack = []; -function fresh (reqHeaders, resHeaders) { - // fields - var modifiedSince = reqHeaders['if-modified-since'] - var noneMatch = reqHeaders['if-none-match'] + const cycleReplacer = (key, value) => { - // unconditional request - if (!modifiedSince && !noneMatch) { - return false - } + if (stack[0] === value) { + return '[Circular ~]'; + } - // 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 - } + return '[Circular ~.' + keys.slice(0, stack.indexOf(value)).join('.') + ']'; + }; - // if-none-match - if (noneMatch && noneMatch !== '*') { - var etag = resHeaders['etag'] + return function (key, value) { - if (!etag) { - return false - } + 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); + } - 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 (~stack.indexOf(value)) { + value = cycleReplacer.call(this, key, value); + } + } + else { + stack.push(value); + } - if (etagStale) { - return false - } - } + if (value) { + const annotations = value[internals.annotations]; + if (annotations) { + if (Array.isArray(value)) { + const annotated = []; - // if-modified-since - if (modifiedSince) { - var lastModified = resHeaders['last-modified'] - var modifiedStale = !lastModified || !(parseHttpDate(lastModified) <= parseHttpDate(modifiedSince)) + for (let i = 0; i < value.length; ++i) { + if (annotations.errors[i]) { + annotated.push(`_$idx$_${annotations.errors[i].sort().join(', ')}_$end$_`); + } - if (modifiedStale) { - return false - } - } + annotated.push(value[i]); + } - return true -} + value = annotated; + } + else { + for (const errorKey in annotations.errors) { + value[`${errorKey}_$key$_${annotations.errors[errorKey].sort().join(', ')}_$end$_`] = value[errorKey]; + value[errorKey] = undefined; + } -/** - * Parse an HTTP Date into a number. - * - * @param {string} date - * @private - */ + for (const missingKey in annotations.missing) { + value[`_$miss$_${missingKey}|${annotations.missing[missingKey]}_$end$_`] = '__missing__'; + } + } -function parseHttpDate (date) { - var timestamp = date && Date.parse(date) + return value; + } + } - // istanbul ignore next: guard against date.js Date.parse patching - return typeof timestamp === 'number' - ? timestamp - : NaN -} + if (value === Infinity || + value === -Infinity || + Number.isNaN(value) || + typeof value === 'function' || + typeof value === 'symbol') { -/** - * Parse a HTTP token list. - * - * @param {string} str - * @private - */ + return '[' + value.toString() + ']'; + } -function parseTokenList (str) { - var end = 0 - var list = [] - var start = 0 + return value; + }; +}; - // 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 + +/***/ }), + +/***/ 95184: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +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 { + + constructor(type) { + + // Naming: public, _private, $_extension, $_mutate{action} + + this.type = type; + + this.$_root = null; + this._definition = {}; + this._reset(); } - } - // final token - list.push(str.substring(start, end)) + _reset() { - return list -} + this._ids = new Modify.Ids(); + this._preferences = null; + this._refs = new Ref.Manager(); + this._cache = null; + this._valids = null; + this._invalids = null; -/***/ }), + this._flags = {}; + this._rules = []; + this._singleRules = new Map(); // The rule options passed for non-multi rules -/***/ 19320: -/***/ ((module) => { + this.$_terms = {}; // Hash of arrays of immutable objects (extended by other types) -"use strict"; + this.$_temp = { // Runtime state (not cloned) + ruleset: null, // null: use last, false: error, number: start position + whens: {} // Runtime cache of generated whens + }; + } + // Manifest -/* eslint no-invalid-this: 1 */ + describe() { -var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; -var slice = Array.prototype.slice; -var toStr = Object.prototype.toString; -var funcType = '[object Function]'; + Assert(typeof Manifest.describe === 'function', 'Manifest functionality disabled'); + return Manifest.describe(this); + } -module.exports = function bind(that) { - var target = this; - if (typeof target !== 'function' || toStr.call(target) !== funcType) { - throw new TypeError(ERROR_MESSAGE + target); + // Rules + + allow(...values) { + + Common.verifyFlat(values, 'allow'); + return this._values(values, '_valids'); } - var args = slice.call(arguments, 1); - 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)) - ); + 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 }); } - }; - var boundLength = Math.max(0, target.length - args.length); - var boundArgs = []; - for (var i = 0; i < boundLength; i++) { - boundArgs.push('$' + i); + obj.$_temp.ruleset = false; + return obj; } - bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder); + artifact(id) { - if (target.prototype) { - var Empty = function Empty() {}; - Empty.prototype = target.prototype; - bound.prototype = new Empty(); - Empty.prototype = null; + Assert(id !== undefined, 'Artifact cannot be undefined'); + Assert(!this._cache, 'Cannot set an artifact with a rule cache'); + + return this.$_setFlag('artifact', id); } - return bound; -}; + 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); + } -/***/ 88334: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + default(value, options) { -"use strict"; + return this._default('default', value, options); + } + description(desc) { -var implementation = __nccwpck_require__(19320); + Assert(desc && typeof desc === 'string', 'Description must be a non-empty string'); -module.exports = Function.prototype.bind || implementation; + return this.$_setFlag('description', desc); + } + empty(schema) { -/***/ }), + const obj = this.clone(); -/***/ 31621: -/***/ ((module) => { + if (schema !== undefined) { + schema = obj.$_compile(schema, { override: false }); + } -"use strict"; + return obj.$_setFlag('empty', schema, { clone: false }); + } + error(err) { -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); -}; + 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 = {}) { -/***/ 76339: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + Assert(example !== undefined, 'Missing example'); + Common.assertOptions(options, ['override']); -"use strict"; + return this._inner('examples', example, { single: true, override: options.override }); + } + external(method, description) { -var bind = __nccwpck_require__(88334); + if (typeof method === 'object') { + Assert(!description, 'Cannot combine options with description'); + description = method.description; + method = method.method; + } -module.exports = bind.call(Function.call, Object.prototype.hasOwnProperty); + 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 }); + } -/***/ }), + failover(value, options) { -/***/ 95193: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return this._default('failover', value, options); + } -"use strict"; -/*! - * http-errors - * Copyright(c) 2014 Jonathan Ong - * Copyright(c) 2016 Douglas Christopher Wilson - * MIT Licensed - */ + forbidden() { + return this.presence('forbidden'); + } + id(id) { -/** - * Module dependencies. - * @private - */ + if (!id) { + return this.$_setFlag('id', undefined); + } -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) + Assert(typeof id === 'string', 'id must be a non-empty string'); + Assert(/^[^\.]+$/.test(id), 'id cannot contain period character'); -/** - * Module exports. - * @public - */ + return this.$_setFlag('id', id); + } -module.exports = createError -module.exports.HttpError = createHttpErrorConstructor() + invalid(...values) { -// Populate exports for all constructors -populateConstructorExports(module.exports, statuses.codes, module.exports.HttpError) + return this._values(values, '_invalids'); + } -/** - * Get the code class of a status code. - * @private - */ + label(name) { -function codeClass (status) { - return Number(String(status).charAt(0) + '00') -} + Assert(name && typeof name === 'string', 'Label name must be a non-empty string'); -/** - * Create a new HTTP Error. - * - * @returns {Error} - * @public - */ + return this.$_setFlag('label', name); + } -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 + meta(meta) { + + Assert(meta !== undefined, 'Meta cannot be undefined'); + + return this._inner('metas', meta, { single: true }); } - 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 + ', ...)') + + note(...notes) { + + Assert(notes.length, 'Missing notes'); + for (const note of notes) { + Assert(note && typeof note === 'string', 'Notes must be non-empty strings'); } - break - case 'object': - props = arg - break + + return this._inner('notes', notes); } - } - if (typeof status === 'number' && (status < 400 || status >= 600)) { - deprecate('non-error status code; use only 4xx or 5xx status codes') - } + only(mode = true) { - if (typeof status !== 'number' || - (!statuses[status] && (status < 400 || status >= 600))) { - status = 500 - } + Assert(typeof mode === 'boolean', 'Invalid mode:', mode); - // constructor - var HttpError = createError[status] || createError[codeClass(status)] + return this.$_setFlag('only', mode); + } - if (!err) { - // create error - err = HttpError - ? new HttpError(msg) - : new Error(msg || statuses[status]) - Error.captureStackTrace(err, createError) - } + optional() { - if (!HttpError || !(err instanceof HttpError) || err.status !== status) { - // add properties to generic error - err.expose = status < 500 - err.status = err.statusCode = status - } + return this.presence('optional'); + } - for (var key in props) { - if (key !== 'status' && key !== 'statusCode') { - err[key] = props[key] + prefs(prefs) { + + 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'); + + Common.checkPreferences(prefs); + + const obj = this.clone(); + obj._preferences = Common.preferences(obj._preferences, prefs); + return obj; } - } - return err -} + presence(mode) { -/** - * Create HTTP error abstract base class. - * @private - */ + Assert(['optional', 'required', 'forbidden'].includes(mode), 'Unknown presence mode', mode); -function createHttpErrorConstructor () { - function HttpError () { - throw new TypeError('cannot construct abstract class') - } + return this.$_setFlag('presence', mode); + } - inherits(HttpError, Error) + raw(enabled = true) { - return HttpError -} + return this.$_setFlag('result', enabled ? 'raw' : undefined); + } -/** - * Create a constructor for a client error. - * @private - */ + result(mode) { -function createClientErrorConstructor (HttpError, name, code) { - var className = name.match(/Error$/) ? name : name + 'Error' + Assert(['raw', 'strip'].includes(mode), 'Unknown result mode', mode); - function ClientError (message) { - // create the error object - var msg = message != null ? message : statuses[code] - var err = new Error(msg) + return this.$_setFlag('result', mode); + } - // capture a stack trace to the construction point - Error.captureStackTrace(err, ClientError) + required() { - // adjust the [[Prototype]] - setPrototypeOf(err, ClientError.prototype) + return this.presence('required'); + } - // redefine the error message - Object.defineProperty(err, 'message', { - enumerable: true, - configurable: true, - value: msg, - writable: true - }) + strict(enabled) { - // redefine the error name - Object.defineProperty(err, 'name', { - enumerable: false, - configurable: true, - value: className, - writable: true - }) + const obj = this.clone(); - return err - } + const convert = enabled === undefined ? false : !enabled; + obj._preferences = Common.preferences(obj._preferences, { convert }); + return obj; + } - inherits(ClientError, HttpError) - nameFunc(ClientError, className) + strip(enabled = true) { - ClientError.prototype.status = code - ClientError.prototype.statusCode = code - ClientError.prototype.expose = true + return this.$_setFlag('result', enabled ? 'strip' : undefined); + } - return ClientError -} + tag(...tags) { -/** - * Create a constructor for a server error. - * @private - */ + Assert(tags.length, 'Missing tags'); + for (const tag of tags) { + Assert(tag && typeof tag === 'string', 'Tags must be non-empty strings'); + } -function createServerErrorConstructor (HttpError, name, code) { - var className = name.match(/Error$/) ? name : name + 'Error' + return this._inner('tags', tags); + } - function ServerError (message) { - // create the error object - var msg = message != null ? message : statuses[code] - var err = new Error(msg) + unit(name) { - // capture a stack trace to the construction point - Error.captureStackTrace(err, ServerError) + Assert(name && typeof name === 'string', 'Unit name must be a non-empty string'); - // adjust the [[Prototype]] - setPrototypeOf(err, ServerError.prototype) + return this.$_setFlag('unit', name); + } - // redefine the error message - Object.defineProperty(err, 'message', { - enumerable: true, - configurable: true, - value: msg, - writable: true - }) + valid(...values) { - // redefine the error name - Object.defineProperty(err, 'name', { - enumerable: false, - configurable: true, - value: className, - writable: true - }) + Common.verifyFlat(values, 'valid'); - return err - } + const obj = this.allow(...values); + obj.$_setFlag('only', !!obj._valids, { clone: false }); + return obj; + } - inherits(ServerError, HttpError) - nameFunc(ServerError, className) + when(condition, options) { - ServerError.prototype.status = code - ServerError.prototype.statusCode = code - ServerError.prototype.expose = false + const obj = this.clone(); - return ServerError -} + if (!obj.$_terms.whens) { + obj.$_terms.whens = []; + } -/** - * Set the name of a function, if possible. - * @private - */ + 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); -function nameFunc (func, name) { - var desc = Object.getOwnPropertyDescriptor(func, 'name') + } + } - if (desc && desc.configurable) { - desc.value = name - Object.defineProperty(func, 'name', desc) - } -} + obj.$_terms.whens.push(when); + return obj.$_mutateRebuild(); + } -/** - * Populate the exports object with constructors for every error class. - * @private - */ + // Helpers -function populateConstructorExports (exports, codes, HttpError) { - codes.forEach(function forEachCode (code) { - var CodeError - var name = toIdentifier(statuses[code]) + cache(cache) { - switch (codeClass(code)) { - case 400: - CodeError = createClientErrorConstructor(HttpError, name, code) - break - case 500: - CodeError = createServerErrorConstructor(HttpError, name, code) - break + 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; } - if (CodeError) { - // export the constructor - exports[code] = CodeError - exports[name] = CodeError + clone() { + + const obj = Object.create(Object.getPrototypeOf(this)); + return this._assign(obj); } - }) - // backwards-compatibility - exports["I'mateapot"] = deprecate.function(exports.ImATeapot, - '"I\'mateapot"; use "ImATeapot" instead') -} + 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(); -/***/ 15098: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + if (this.type === 'any' && + source.type !== 'any') { -"use strict"; + // Change obj to match source type -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; + const tmpObj = source.clone(); + for (const key of Object.keys(obj)) { + if (key !== 'type') { + tmpObj[key] = obj[key]; + } + } + + obj = tmpObj; } - if (!opts) { - throw new Error('an HTTP(S) proxy server `host` and `port` must be specified!'); + + 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); + } } - 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); + + // Rules + + for (const test of source._rules) { + if (!source._definition.rules[test.method].multi) { + obj._singleRules.set(test.name, test); + } + + obj._rules.push(test); } - if (!proxy.port && proxy.host) { - proxy.port = this.secureProxy ? 443 : 80; + + // 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); } - // 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']; + else if (source._flags.empty) { + obj._flags.empty = source._flags.empty; + const flags = Object.assign({}, source._flags); + delete flags.empty; + Merge(obj._flags, flags); } - 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; + else { + Merge(obj._flags, source._flags); } - 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 })); + + // Terms + + for (const key in source.$_terms) { + const terms = source.$_terms[key]; + if (!terms) { + if (!obj.$_terms[key]) { + obj.$_terms[key] = terms; } - return socket; + + continue; } - // 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]; + + 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(); } - return ret; -} -//# sourceMappingURL=agent.js.map -/***/ }), + extend(options) { -/***/ 77219: -/***/ (function(module, __unused_webpack_exports, __nccwpck_require__) { + Assert(!options.base, 'Cannot extend type with another base'); -"use strict"; + return Extend.type(this, options); + } -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 + extract(path) { -/***/ }), + path = Array.isArray(path) ? path : path.split('.'); + return this._ids.reach(path); + } -/***/ 595: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + fork(paths, adjuster) { -"use strict"; + Assert(!this._inRuleset(), 'Cannot fork inside a ruleset'); -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'); + 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); } - function onerror(err) { - cleanup(); - debug('onerror %o', err); - reject(err); + + obj.$_temp.ruleset = false; + return obj; + } + + rule(options) { + + 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'); + + const obj = this.clone(); + + for (let i = start; i < obj._rules.length; ++i) { + const original = obj._rules[i]; + const rule = Clone(original); + + for (const name in options) { + def.modifiers[name](rule, options[name]); + Assert(rule.name === original.name, 'Cannot change rule name'); + } + + obj._rules[i] = rule; + + if (obj._singleRules.get(rule.name) === original) { + obj._singleRules.set(rule.name, rule); + } } - 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; + + obj.$_temp.ruleset = false; + return obj.$_mutateRebuild(); + } + + get ruleset() { + + Assert(!this._inRuleset(), 'Cannot start a new ruleset without closing the previous one'); + + const obj = this.clone(); + obj.$_temp.ruleset = obj._rules.length; + return obj; + } + + get $() { + + return this.ruleset; + } + + tailor(targets) { + + targets = [].concat(targets); + + Assert(!this._inRuleset(), 'Cannot tailor inside a ruleset'); + + let obj = this; // eslint-disable-line consistent-this + + 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'); + } } - 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 -/***/ }), + obj = obj.$_modify({ each: (item) => item.tailor(targets), ref: false }); + obj.$_temp.ruleset = false; + return obj.$_mutateRebuild(); + } + + tracer() { + + return Trace.location ? Trace.location(this) : this; // $lab:coverage:ignore$ + } + + validate(value, options) { -/***/ 39695: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + return Validator.entry(value, this, options); + } -"use strict"; + validateAsync(value, options) { -var Buffer = (__nccwpck_require__(15118).Buffer); + return Validator.entryAsync(value, this, options); + } -// 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. + // Extensions -exports._dbcs = DBCSCodec; + $_addRule(options) { -var UNASSIGNED = -1, - GB18030_CODE = -2, - SEQ_START = -10, - NODE_START = -1000, - UNASSIGNED_NODE = new Array(0x100), - DEF_CHAR = -1; + // Normalize rule -for (var i = 0; i < 0x100; i++) - UNASSIGNED_NODE[i] = UNASSIGNED; + if (typeof options === 'string') { + options = { name: options }; + } + Assert(options && typeof options === 'object', 'Invalid options'); + Assert(options.name && typeof options.name === 'string', 'Invalid rule name'); -// 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."); + for (const key in options) { + Assert(key[0] !== '_', 'Cannot set private rule properties'); + } - // Load tables. - var mappingTable = codecOptions.table(); + 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; - // Decode tables: MBCS -> Unicode. + Assert(definition, 'Unknown rule', rule.method); - // 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. + // Args - // Sometimes a MBCS char corresponds to a sequence of unicode chars. We store them as arrays of integers here. - this.decodeTableSeq = []; + const obj = this.clone(); - // 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]); + 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); - this.defaultCharUnicode = iconv.defaultCharUnicode; + for (const key in args) { + let arg = args[key]; + if (arg === undefined) { + delete args[key]; + continue; + } - - // Encode tables: Unicode -> DBCS. + if (definition.argsByName) { + const resolver = definition.argsByName.get(key); - // `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 (resolver.ref && + Common.isResolvable(arg)) { - // 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; + rule._resolve.push(key); + obj.$_mutateRegister(arg); + } + else { + if (resolver.normalize) { + arg = resolver.normalize(arg); + args[key] = arg; + } + + if (resolver.assert) { + const error = Common.validateArg(arg, key, resolver); + Assert(!error, error, 'or reference'); + } + } + } + + args[key] = arg; + } } - - // 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]); + // 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; + } + + if (definition.priority) { + obj._rules.unshift(rule); + } + else { + obj._rules.push(rule); + } + + return obj; } - 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); + $_compile(schema, options) { + return Compile.schema(this.$_root, schema, options); + } - // Load & create GB18030 tables when needed. - if (typeof codecOptions.gb18030 === 'function') { - this.gb18030 = codecOptions.gb18030(); // Load GB18030 ranges. + $_createError(code, value, local, state, prefs, options = {}) { - // Add GB18030 decode tables. - var thirdByteNodeIdx = this.decodeTables.length; - var thirdByteNode = this.decodeTables[thirdByteNodeIdx] = UNASSIGNED_NODE.slice(0); + 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); + } - var fourthByteNodeIdx = this.decodeTables.length; - var fourthByteNode = this.decodeTables[fourthByteNodeIdx] = UNASSIGNED_NODE.slice(0); + $_getFlag(name) { - 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 - } -} + return this._flags[name]; + } -DBCSCodec.prototype.encoder = DBCSEncoder; -DBCSCodec.prototype.decoder = DBCSDecoder; + $_getRule(name) { -// 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 this._singleRules.get(name); + } - 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]]; + $_mapLabels(path) { - 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)); + path = Array.isArray(path) ? path : path.split('.'); + return this._ids.labels(path); } - return node; -} + $_match(value, state, prefs, overrides) { -DBCSCodec.prototype._addDecodeChunk = function(chunk) { - // First element of chunk is the hex mbcs code where we start. - var curAddr = parseInt(chunk[0], 16); + prefs = Object.assign({}, prefs); // Shallow cloned + prefs.abortEarly = true; + prefs._externals = false; - // Choose the decoding node where we'll write our chars. - var writeTable = this._getDecodeTrieNode(curAddr); - curAddr = curAddr & 0xFF; + state.snapshot(); + const result = !Validator.validate(value, this, state, prefs, overrides).errors; + state.restore(); - // 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. + return result; + } - writeTable[curAddr++] = SEQ_START - this.decodeTableSeq.length; - this.decodeTableSeq.push(seq); - } - else - writeTable[curAddr++] = code; // Basic char + $_modify(options) { + + Common.assertOptions(options, ['each', 'once', 'ref', 'schema']); + return Modify.schema(this, options) || this; + } + + $_mutateRebuild() { + + Assert(!this._inRuleset(), 'Cannot add this rule inside a ruleset'); + + this._refs.reset(); + this._ids.reset(); + + 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 }); } - } - 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++; + }; + + this.$_modify({ each }); + + if (this._definition.rebuild) { + this._definition.rebuild(this); } - else - throw new Error("Incorrect type '" + typeof part + "' given in " + this.encodingName + " at chunk " + chunk[0]); + + this.$_temp.ruleset = false; + return this; } - if (curAddr > 0xFF) - throw new Error("Incorrect chunk in " + this.encodingName + " at addr " + chunk[0] + ": too long" + curAddr); -} -// 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]; -} + $_mutateRegister(schema, { family, key } = {}) { -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; -} + this._refs.register(schema, family); + this._ids.register(schema, { key }); + } -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; + $_property(name) { - var node; - if (bucket[low] <= SEQ_START) { - // There's already a sequence with - use it. - node = this.encodeTableSeq[SEQ_START-bucket[low]]; + return this._definition.properties[name]; } - 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); + + $_reach(path) { + + return this._ids.reach(path); } - // 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; + $_rootReferences() { + + return this._refs.roots(); + } + + $_setFlag(name, value, options = {}) { + + Assert(name[0] === '_' || !this._inRuleset(), 'Cannot set flag inside a ruleset'); + + const flag = this._definition.flags[name] || {}; + if (DeepEqual(value, flag.default)) { + value = undefined; + } + + if (DeepEqual(value, this._flags[name])) { + return this; + } + + const obj = options.clone !== false ? this.clone() : this; + + if (value !== undefined) { + obj._flags[name] = value; + obj.$_mutateRegister(value); + } else { - node = node[uCode] = {} - if (oldVal !== undefined) - node[DEF_CHAR] = oldVal + delete obj._flags[name]; } + + if (name[0] !== '_') { + obj.$_temp.ruleset = false; + } + + return obj; } - // Set the leaf to given dbcsCode. - uCode = seq[seq.length-1]; - node[uCode] = dbcsCode; -} + $_parent(method, ...args) { -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; + return this[method][Common.symbols.parent].call(this, ...args); + } - 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); + $_validate(value, state, prefs) { + + return Validator.validate(value, this, state, prefs); } -} + // Internals + _assign(target) { -// == Encoder ================================================================== + target.type = this.type; -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; -} + target.$_root = this.$_root; -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; + target.$_temp = Object.assign({}, this.$_temp); + target.$_temp.whens = {}; - 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; + 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; + + target.$_terms = {}; + for (const key in this.$_terms) { + target.$_terms[key] = this.$_terms[key] ? this.$_terms[key].slice() : null; } - // 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; - } - - } + // Backwards compatibility + + target.$_super = {}; + for (const override in this.$_super) { + target.$_super[override] = this._super[override].bind(target); } - else if (leadSurrogate !== -1) { - // Incomplete surrogate pair - only lead surrogate found. - nextChar = uCode; uCode = UNASSIGNED; // Write an error, then current char. - leadSurrogate = -1; + + return target; + } + + _bare() { + + const obj = this.clone(); + obj._reset(); + + const terms = obj._definition.terms; + for (const name in terms) { + const term = terms[name]; + obj.$_terms[name] = term.init; } - // 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; + return obj.$_mutateRebuild(); + } - } else if (typeof resCode == 'number') { // Sequence finished. Write it. - dbcsCode = resCode; + _default(flag, value, options = {}) { - } else if (resCode == undefined) { // Current character is not part of the sequence. + Common.assertOptions(options, 'literal'); - // 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. + Assert(value !== undefined, 'Missing', flag, 'value'); + Assert(typeof value === 'function' || !options.literal, 'Only function value supports literal option'); - } 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; + if (typeof value === 'function' && + options.literal) { + + value = { + [Common.symbols.literal]: true, + literal: value + }; } - 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]; + + const obj = this.$_setFlag(flag, value); + return obj; + } + + _generate(value, state, prefs) { + + if (!this.$_terms.whens) { + return { schema: this }; + } + + // 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; } - 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; + 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; } } + + if (when.break && + ids.length > before) { // Something matched + + break; + } } - // 3. Write dbcsCode character. - if (dbcsCode === UNASSIGNED) - dbcsCode = this.defaultCharSingleByte; - - if (dbcsCode < 0x100) { - newBuf[j++] = dbcsCode; + // Check cache + + const id = ids.join(', '); + state.mainstay.tracer.debug(state, 'rule', 'when', id); + + if (!id) { + return { schema: this }; } - else if (dbcsCode < 0x10000) { - newBuf[j++] = dbcsCode >> 8; // high byte - newBuf[j++] = dbcsCode & 0xFF; // low byte + + if (!state.mainstay.tracer.active && + this.$_temp.whens[id]) { + + return { schema: this.$_temp.whens[id], id }; } - else { - newBuf[j++] = dbcsCode >> 16; - newBuf[j++] = (dbcsCode >> 8) & 0xFF; - newBuf[j++] = dbcsCode & 0xFF; + + // 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 }; } - this.seqObj = seqObj; - this.leadSurrogate = leadSurrogate; - return newBuf.slice(0, j); -} + _inner(type, values, options = {}) { -DBCSEncoder.prototype.end = function() { - if (this.leadSurrogate === -1 && this.seqObj === undefined) - return; // All clean. Most often case. + Assert(!this._inRuleset(), `Cannot set ${type} inside a ruleset`); - var newBuf = Buffer.alloc(10), j = 0; + const obj = this.clone(); + if (!obj.$_terms[type] || + options.override) { - 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. + obj.$_terms[type] = []; } - this.seqObj = undefined; + + if (options.single) { + obj.$_terms[type].push(values); + } + else { + obj.$_terms[type].push(...values); + } + + obj.$_temp.ruleset = false; + return obj; } - if (this.leadSurrogate !== -1) { - // Incomplete surrogate pair - only lead surrogate found. - newBuf[j++] = this.defaultCharSingleByte; - this.leadSurrogate = -1; + _inRuleset() { + + return this.$_temp.ruleset !== null && this.$_temp.ruleset !== false; } - - return newBuf.slice(0, j); -} -// Export for testing -DBCSEncoder.prototype.findIdx = findIdx; + _ruleRemove(name, options = {}) { + if (!this._singleRules.has(name)) { + return this; + } -// == Decoder ================================================================== + const obj = options.clone !== false ? this.clone() : this; -function DBCSDecoder(options, codec) { - // Decoder state - this.nodeIdx = 0; - this.prevBuf = Buffer.alloc(0); + obj._singleRules.delete(name); - // Static data - this.decodeTables = codec.decodeTables; - this.decodeTableSeq = codec.decodeTableSeq; - this.defaultCharUnicode = codec.defaultCharUnicode; - this.gb18030 = codec.gb18030; -} + const filtered = []; + for (let i = 0; i < obj._rules.length; ++i) { + const test = obj._rules[i]; + if (test.name === name && + !test.keep) { -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 (obj._inRuleset() && + i < obj.$_temp.ruleset) { - 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]; + --obj.$_temp.ruleset; + } - // Lookup in current trie node. - var uCode = this.decodeTables[nodeIdx][curByte]; + continue; + } - if (uCode >= 0) { - // Normal character, just use it. + filtered.push(test); + } + + obj._rules = filtered; + return obj; + } + + _values(values, key) { + + Common.verifyFlat(values, key.slice(1, -1)); + + const obj = this.clone(); + + const override = values[0] === Common.symbols.override; + if (override) { + values = values.slice(1); } - 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); + + if (!obj[key] && + values.length) { + + obj[key] = new Values(); } - 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 (override) { + obj[key] = values.length ? new Values() : null; + obj.$_mutateRebuild(); } - else if (uCode <= NODE_START) { // Go to next trie node. - nodeIdx = NODE_START - uCode; - continue; + + if (!obj[key]) { + return obj; } - 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]; + + if (override) { + obj[key].override(); } - 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; + 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'); - uCode = 0xDC00 + uCode % 0x400; + 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; + } + } + + obj[key].add(value, obj._refs); } - newBuf[j++] = uCode & 0xFF; - newBuf[j++] = uCode >> 8; - // Reset trie node. - nodeIdx = 0; seqStart = i+1; + return obj; } +}; - 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 = ''; +internals.Base.prototype[Common.symbols.any] = { + version: Common.version, + compile: Compile.compile, + root: '$_root' +}; - // 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); - // Parse remaining as usual. - this.prevBuf = Buffer.alloc(0); - this.nodeIdx = 0; - if (buf.length > 0) - ret += this.write(buf); - } +internals.Base.prototype.isImmutable = true; // Prevents Hoek from deep cloning schema objects (must be on prototype) - 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; +// Aliases - 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 l; -} +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(); + /***/ }), -/***/ 91386: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 63355: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -// 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. +const Assert = __nccwpck_require__(32718); +const Clone = __nccwpck_require__(85578); -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) +const Common = __nccwpck_require__(72448); - // 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 - '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', +const internals = { + max: 1000, + supported: new Set(['undefined', 'boolean', 'number', 'string']) +}; - 'eucjp': { - type: '_dbcs', - table: function() { return __nccwpck_require__(31532) }, - encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E}, - }, - // 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. +exports.provider = { + provision(options) { - // == Chinese/GBK ========================================================== - // http://en.wikipedia.org/wiki/GBK - // We mostly implement W3C recommendation: https://www.w3.org/TR/encoding/#gbk-encoder + return new internals.Cache(options); + } +}; - // 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) }, - }, +// Least Recently Used (LRU) Cache - // 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', +internals.Cache = class { - // 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}, - }, + constructor(options = {}) { - 'chinese': 'gb18030', + Common.assertOptions(options, ['max']); + Assert(options.max === undefined || options.max && options.max > 0 && isFinite(options.max), 'Invalid max cache size'); + this._max = options.max || internals.max; - // == 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) }, - }, + this._map = new Map(); // Map of nodes by key + this._list = new internals.List(); // List of nodes (most recently used in head) + } - 'cseuckr': 'cp949', - 'csksc56011987': 'cp949', - 'euckr': 'cp949', - 'isoir149': 'cp949', - 'korean': 'cp949', - 'ksc56011987': 'cp949', - 'ksc56011989': 'cp949', - 'ksc5601': 'cp949', + get length() { + return this._map.size; + } - // == 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. + set(key, value) { - 'windows950': 'cp950', - 'ms950': 'cp950', - '950': 'cp950', - 'cp950': { - type: '_dbcs', - table: function() { return __nccwpck_require__(74284) }, - }, + if (key !== null && + !internals.supported.has(typeof key)) { - // 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], - }, + return; + } - 'cnbig5': 'big5hkscs', - 'csbig5': 'big5hkscs', - 'xxbig5': 'big5hkscs', -}; + let node = this._map.get(key); + if (node) { + node.value = value; + this._list.first(node); + return; + } + node = this._list.unshift({ key, value }); + this._map.set(key, node); + this._compact(); + } -/***/ }), + get(key) { -/***/ 82733: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + const node = this._map.get(key); + if (node) { + this._list.first(node); + return Clone(node.value); + } + } -"use strict"; + _compact() { + if (this._map.size > this._max) { + const node = this._list.pop(); + this._map.delete(node.key); + } + } +}; -// 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), -]; -// 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]; -} +internals.List = class { + constructor() { -/***/ }), + this.tail = null; + this.head = null; + } -/***/ 12376: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + unshift(node) { -"use strict"; + node.next = null; + node.prev = this.head; -var Buffer = (__nccwpck_require__(15118).Buffer); + if (this.head) { + this.head.next = node; + } -// Export Node.js internal encodings. + this.head = node; -module.exports = { - // Encodings - utf8: { type: "_internal", bomAware: true}, - cesu8: { type: "_internal", bomAware: true}, - unicode11utf8: "utf8", + if (!this.tail) { + this.tail = node; + } - ucs2: { type: "_internal", bomAware: true}, - utf16le: "ucs2", + return node; + } - binary: { type: "_internal" }, - base64: { type: "_internal" }, - hex: { type: "_internal" }, + first(node) { - // Codec. - _internal: InternalCodec, -}; + if (node === this.head) { + return; + } -//------------------------------------------------------------------------------ + this._remove(node); + this.unshift(node); + } -function InternalCodec(codecOptions, iconv) { - this.enc = codecOptions.encodingName; - this.bomAware = codecOptions.bomAware; + pop() { - if (this.enc === "base64") - this.encoder = InternalEncoderBase64; - else if (this.enc === "cesu8") { - this.enc = "utf8"; // Use utf8 for decoding. - this.encoder = InternalEncoderCesu8; + return this._remove(this.tail); + } - // Add decoder for versions of Node not supporting CESU-8 - if (Buffer.from('eda0bdedb2a9', 'hex').toString() !== '💩') { - this.decoder = InternalDecoderCesu8; - this.defaultCharUnicode = iconv.defaultCharUnicode; + _remove(node) { + + const { next, prev } = node; + + next.prev = prev; + + if (prev) { + prev.next = next; } + + if (node === this.tail) { + this.tail = next; + } + + node.prev = null; + node.next = null; + + return node; } -} +}; -InternalCodec.prototype.encoder = InternalEncoder; -InternalCodec.prototype.decoder = InternalDecoder; -//------------------------------------------------------------------------------ +/***/ }), -// We use node.js internal decoder. Its signature is the same as ours. -var StringDecoder = (__nccwpck_require__(71576).StringDecoder); +/***/ 72448: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -if (!StringDecoder.prototype.end) // Node v0.8 doesn't have this method. - StringDecoder.prototype.end = function() {}; +"use strict"; -function InternalDecoder(options, codec) { - StringDecoder.call(this, codec.enc); -} +const Assert = __nccwpck_require__(32718); +const AssertError = __nccwpck_require__(35563); -InternalDecoder.prototype = StringDecoder.prototype; +const Pkg = __nccwpck_require__(77045); +let Messages; +let Schemas; -//------------------------------------------------------------------------------ -// Encoder is mostly trivial -function InternalEncoder(options, codec) { - this.enc = codec.enc; -} +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)?)?)?)?$/ +}; -InternalEncoder.prototype.write = function(str) { - return Buffer.from(str, this.enc); -} -InternalEncoder.prototype.end = function() { -} +exports.version = Pkg.version; -//------------------------------------------------------------------------------ -// Except base64 encoder, which must keep its state. +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 +}; -function InternalEncoderBase64(options, codec) { - this.prevStr = ''; -} -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); +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') +}; - return Buffer.from(str, "base64"); -} -InternalEncoderBase64.prototype.end = function() { - return Buffer.from(this.prevStr, "base64"); -} +exports.assertOptions = function (options, keys, name = 'Options') { + 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}`); +}; -//------------------------------------------------------------------------------ -// CESU-8 encoder is also special. -function InternalEncoderCesu8(options, codec) { -} +exports.checkPreferences = function (prefs) { -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); -} + Schemas = Schemas || __nccwpck_require__(85614); -InternalEncoderCesu8.prototype.end = function() { -} + const result = Schemas.preferences.validate(prefs); -//------------------------------------------------------------------------------ -// CESU-8 decoder is not implemented in Node v4.0+ + if (result.error) { + throw new AssertError([result.error.details[0].message]); + } +}; -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; - } +exports.compare = function (a, b, operator) { - 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; - } - } + switch (operator) { + case '=': return a === b; + case '>': return a > b; + case '<': return a < b; + case '>=': return a >= b; + case '<=': return a <= b; } - 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; -} +exports["default"] = function (value, defaultValue) { -/***/ }), + return value === undefined ? defaultValue : value; +}; -/***/ 26657: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; +exports.isIsoDate = function (date) { -var Buffer = (__nccwpck_require__(15118).Buffer); + return internals.isoDate.test(date); +}; -// 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._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; +exports.isNumber = function (value) { + + return typeof value === 'number' && !isNaN(value); +}; + + +exports.isResolvable = function (obj) { + + if (!obj) { + return false; + } + + return obj[exports.symbols.ref] || obj[exports.symbols.template]; +}; + + +exports.isSchema = function (schema, options = {}) { + + const any = schema && schema[exports.symbols.any]; + if (!any) { + return false; } - this.decodeBuf = Buffer.from(codecOptions.chars, 'ucs2'); - - // Encoding buffer. - var encodeBuf = Buffer.alloc(65536, iconv.defaultCharSingleByte.charCodeAt(0)); + Assert(options.legacy || any.version === exports.version, 'Cannot mix different versions of joi schemas'); + return true; +}; + + +exports.isValues = function (obj) { + + return obj[exports.symbols.values]; +}; + - for (var i = 0; i < codecOptions.chars.length; i++) - encodeBuf[codecOptions.chars.charCodeAt(i)] = i; +exports.limit = function (value) { - this.encodeBuf = encodeBuf; -} + return Number.isSafeInteger(value) && value >= 0; +}; -SBCSCodec.prototype.encoder = SBCSEncoder; -SBCSCodec.prototype.decoder = SBCSDecoder; +exports.preferences = function (target, source) { -function SBCSEncoder(options, codec) { - this.encodeBuf = codec.encodeBuf; -} + Messages = Messages || __nccwpck_require__(86103); -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; -} + target = target || {}; + source = source || {}; -SBCSEncoder.prototype.end = function() { -} + const merged = Object.assign({}, target, source); + if (source.errors && + target.errors) { + merged.errors = Object.assign({}, target.errors, source.errors); + merged.errors.wrap = Object.assign({}, target.errors.wrap, source.errors.wrap); + } -function SBCSDecoder(options, codec) { - this.decodeBuf = codec.decodeBuf; -} + if (source.messages) { + merged.messages = Messages.compile(source.messages, target.messages); + } -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]; + delete merged[exports.symbols.prefs]; + return merged; +}; + + +exports.tryWithPath = function (fn, key, options = {}) { + + try { + return fn(); } - return newBuf.toString('ucs2'); -} + catch (err) { + if (err.path !== undefined) { + err.path = key + '.' + err.path; + } + else { + err.path = key; + } -SBCSDecoder.prototype.end = function() { -} + if (options.append) { + err.message = `${err.message} (${err.path})`; + } + throw err; + } +}; -/***/ }), -/***/ 21012: -/***/ ((module) => { +exports.validateArg = function (value, label, { assert, message }) { -"use strict"; + if (exports.isSchema(assert)) { + const result = assert.validate(value); + if (!result.error) { + return; + } + return result.error.message; + } + else if (!assert(value)) { + return label ? `${label} ${message}` : message; + } +}; + + +exports.verifyFlat = function (args, method) { + + for (const arg of args) { + Assert(!Array.isArray(arg), 'Method no longer accepts array arguments:', method); + } +}; -// 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": "���������������������������������กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" - } -} /***/ }), -/***/ 41080: -/***/ ((module) => { +/***/ 3038: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -// Manually added data to be used by sbcs codec in addition to generated one. +const Assert = __nccwpck_require__(32718); -module.exports = { - // Not supported by iconv, not sure why. - "10029": "maccenteuro", - "maccenteuro": { - "type": "_sbcs", - "chars": "ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ" - }, +const Common = __nccwpck_require__(72448); +const Ref = __nccwpck_require__(73838); - "808": "cp808", - "ibm808": "cp808", - "cp808": { - "type": "_sbcs", - "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№€■ " - }, - "mik": { - "type": "_sbcs", - "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя└┴┬├─┼╣║╚╔╩╦╠═╬┐░▒▓│┤№§╗╝┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " - }, +const internals = {}; - // 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", - "latin1": "iso88591", - "latin2": "iso88592", - "latin3": "iso88593", - "latin4": "iso88594", - "latin5": "iso88599", - "latin6": "iso885910", - "latin7": "iso885913", - "latin8": "iso885914", - "latin9": "iso885915", - "latin10": "iso885916", +exports.schema = function (Joi, config, options = {}) { - "csisolatin1": "iso88591", - "csisolatin2": "iso88592", - "csisolatin3": "iso88593", - "csisolatin4": "iso88594", - "csisolatincyrillic": "iso88595", - "csisolatinarabic": "iso88596", - "csisolatingreek" : "iso88597", - "csisolatinhebrew": "iso88598", - "csisolatin5": "iso88599", - "csisolatin6": "iso885910", + Common.assertOptions(options, ['appendPath', 'override']); - "l1": "iso88591", - "l2": "iso88592", - "l3": "iso88593", - "l4": "iso88594", - "l5": "iso88599", - "l6": "iso885910", - "l7": "iso885913", - "l8": "iso885914", - "l9": "iso885915", - "l10": "iso885916", + try { + return internals.schema(Joi, config, options); + } + catch (err) { + if (options.appendPath && + err.path !== undefined) { - "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", + err.message = `${err.message} (${err.path})`; + } - "cp819": "iso88591", - "ibm819": "iso88591", + throw err; + } +}; - "cyrillic": "iso88595", - "arabic": "iso88596", - "arabic8": "iso88596", - "ecma114": "iso88596", - "asmo708": "iso88596", +internals.schema = function (Joi, config, options) { - "greek" : "iso88597", - "greek8" : "iso88597", - "ecma118" : "iso88597", - "elot928" : "iso88597", + Assert(config !== undefined, 'Invalid undefined schema'); - "hebrew": "iso88598", - "hebrew8": "iso88598", + if (Array.isArray(config)) { + Assert(config.length, 'Invalid empty array schema'); - "turkish": "iso88599", - "turkish8": "iso88599", + if (config.length === 1) { + config = config[0]; + } + } - "thai": "iso885911", - "thai8": "iso885911", + const valid = (base, ...values) => { - "celtic": "iso885914", - "celtic8": "iso885914", - "isoceltic": "iso885914", + if (options.override !== false) { + return base.valid(Joi.override, ...values); + } - "tis6200": "tis620", - "tis62025291": "tis620", - "tis62025330": "tis620", + return base.valid(...values); + }; - "10000": "macroman", - "10006": "macgreek", - "10007": "maccyrillic", - "10079": "maciceland", - "10081": "macturkish", + if (internals.simple(config)) { + return valid(Joi, config); + } - "cspc8codepage437": "cp437", - "cspc775baltic": "cp775", - "cspc850multilingual": "cp850", - "cspcp852": "cp852", - "cspc862latinhebrew": "cp862", - "cpgr": "cp869", + if (typeof config === 'function') { + return Joi.custom(config); + } - "msee": "cp1250", - "mscyrl": "cp1251", - "msansi": "cp1252", - "msgreek": "cp1253", - "msturk": "cp1254", - "mshebr": "cp1255", - "msarab": "cp1256", - "winbaltrim": "cp1257", + Assert(typeof config === 'object', 'Invalid schema content:', typeof config); - "cp20866": "koi8r", - "20866": "koi8r", - "ibm878": "koi8r", - "cskoi8r": "koi8r", + if (Common.isResolvable(config)) { + return valid(Joi, config); + } - "cp21866": "koi8u", - "21866": "koi8u", - "ibm1168": "koi8u", + if (Common.isSchema(config)) { + return config; + } - "strk10482002": "rk1048", + if (Array.isArray(config)) { + for (const item of config) { + if (!internals.simple(item)) { + return Joi.alternatives().try(...config); + } + } - "tcvn5712": "tcvn", - "tcvn57121": "tcvn", + return valid(Joi, ...config); + } - "gb198880": "iso646cn", - "cn": "iso646cn", + if (config instanceof RegExp) { + return Joi.string().regex(config); + } - "csiso14jisc6220ro": "iso646jp", - "jisc62201969ro": "iso646jp", - "jp": "iso646jp", + if (config instanceof Date) { + return valid(Joi.date(), config); + } - "cshproman8": "hproman8", - "r8": "hproman8", - "roman8": "hproman8", - "xroman8": "hproman8", - "ibm1051": "hproman8", + Assert(Object.getPrototypeOf(config) === Object.getPrototypeOf({}), 'Schema can only contain plain objects'); - "mac": "macintosh", - "csmacintosh": "macintosh", + return Joi.object().keys(config); }; +exports.ref = function (id, options) { -/***/ }), - -/***/ 11155: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + return Ref.isRef(id) ? id : Ref.create(id, options); +}; -"use strict"; -var Buffer = (__nccwpck_require__(15118).Buffer); +exports.compile = function (root, schema, options = {}) { -// Note: UTF16-LE (or UCS2) codec is Node.js native. See encodings/internal.js + Common.assertOptions(options, ['legacy']); -// == UTF16-BE codec. ========================================================== + // Compiled by any supported version -exports.utf16be = Utf16BECodec; -function Utf16BECodec() { -} + 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; + } -Utf16BECodec.prototype.encoder = Utf16BEEncoder; -Utf16BECodec.prototype.decoder = Utf16BEDecoder; -Utf16BECodec.prototype.bomAware = true; + // Uncompiled root + if (typeof schema !== 'object' || + !options.legacy) { -// -- Encoding + return exports.schema(root, schema, { appendPath: true }); // Will error if schema contains other versions + } -function Utf16BEEncoder() { -} + // Scan schema for compiled parts -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; + const compiler = internals.walk(schema); + if (!compiler) { + return exports.schema(root, schema, { appendPath: true }); } - return buf; -} -Utf16BEEncoder.prototype.end = function() { -} + return compiler.compile(compiler.root, schema); +}; -// -- Decoding +internals.walk = function (schema) { -function Utf16BEDecoder() { - this.overflowByte = -1; -} + if (typeof schema !== 'object') { + return null; + } -Utf16BEDecoder.prototype.write = function(buf) { - if (buf.length == 0) - return ''; + if (Array.isArray(schema)) { + for (const item of schema) { + const compiler = internals.walk(item); + if (compiler) { + return compiler; + } + } - var buf2 = Buffer.alloc(buf.length + 1), - i = 0, j = 0; + return null; + } - if (this.overflowByte !== -1) { - buf2[0] = buf[0]; - buf2[1] = this.overflowByte; - i = 1; j = 2; + const any = schema[Common.symbols.any]; + if (any) { + return { root: schema[any.root], compile: any.compile }; } - for (; i < buf.length-1; i += 2, j+= 2) { - buf2[j] = buf[i+1]; - buf2[j+1] = buf[i]; + Assert(Object.getPrototypeOf(schema) === Object.getPrototypeOf({}), 'Schema can only contain plain objects'); + + for (const key in schema) { + const compiler = internals.walk(schema[key]); + if (compiler) { + return compiler; + } } - this.overflowByte = (i == buf.length-1) ? buf[buf.length-1] : -1; + return null; +}; - return buf2.slice(0, j).toString('ucs2'); -} -Utf16BEDecoder.prototype.end = function() { -} +internals.simple = function (value) { + return value === null || ['boolean', 'string', 'number'].includes(typeof value); +}; -// == 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'}); -// Encoder uses UTF-16LE and prepends BOM (which can be overridden with addBOM: false). +exports.when = function (schema, condition, options) { -exports.utf16 = Utf16Codec; -function Utf16Codec(codecOptions, iconv) { - this.iconv = iconv; -} + if (options === undefined) { + Assert(condition && typeof condition === 'object', 'Missing options'); -Utf16Codec.prototype.encoder = Utf16Encoder; -Utf16Codec.prototype.decoder = Utf16Decoder; + options = condition; + condition = Ref.create('.'); + } + if (Array.isArray(options)) { + options = { switch: options }; + } -// -- Encoding (pass-through) + Common.assertOptions(options, ['is', 'not', 'then', 'otherwise', 'switch', 'break']); -function Utf16Encoder(options, codec) { - options = options || {}; - if (options.addBOM === undefined) - options.addBOM = true; - this.encoder = codec.iconv.getEncoder('utf-16le', options); -} + // Schema condition -Utf16Encoder.prototype.write = function(str) { - return this.encoder.write(str); -} + 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'); -Utf16Encoder.prototype.end = function() { - return this.encoder.end(); -} + return internals.condition(schema, { is: condition, then: options.then, otherwise: options.otherwise, break: options.break }); + } + // Single condition -// -- Decoding + Assert(Ref.isRef(condition) || typeof condition === 'string', 'Invalid condition:', condition); + Assert(options.not === undefined || options.is === undefined, 'Cannot combine "is" with "not"'); -function Utf16Decoder(options, codec) { - this.decoder = null; - this.initialBytes = []; - this.initialBytesLen = 0; + if (options.switch === undefined) { + let rule = options; + if (options.not !== undefined) { + rule = { is: options.not, then: options.otherwise, otherwise: options.then, break: options.break }; + } - this.options = options || {}; - this.iconv = codec.iconv; -} + 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'); -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 ''; + if (options.is !== undefined && + !Ref.isRef(options.is) && + !Common.isSchema(options.is)) { - // 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; + is = is.required(); // Only apply required if this wasn't already a schema or a ref + } + + return internals.condition(schema, { ref: exports.ref(condition), is, then: rule.then, otherwise: rule.otherwise, break: rule.break }); } - return this.decoder.write(buf); -} + // Switch statement -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); + 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"'); - var res = this.decoder.write(buf), - trail = this.decoder.end(); + const rule = { + ref: exports.ref(condition), + switch: [], + break: options.break + }; - return trail ? (res + trail) : res; - } - return this.decoder.end(); -} + for (let i = 0; i < options.switch.length; ++i) { + const test = options.switch[i]; + const last = i === options.switch.length - 1; -function detectEncoding(buf, defaultEncoding) { - var enc = defaultEncoding || 'utf-16le'; + Common.assertOptions(test, last ? ['is', 'then', 'otherwise'] : ['is', 'then']); - 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. + Assert(test.is !== undefined, 'Switch statement missing "is"'); + Assert(test.then !== undefined, 'Switch statement missing "then"'); - 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++; - } + const item = { + is: schema.$_compile(test.is), + then: schema.$_compile(test.then) + }; - if (asciiCharsBE > asciiCharsLE) - enc = 'utf-16be'; - else if (asciiCharsBE < asciiCharsLE) - enc = 'utf-16le'; + if (!Ref.isRef(test.is) && + !Common.isSchema(test.is)) { + + item.is = item.is.required(); // Only apply required if this wasn't already a schema or a ref } + + 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); + } + } + + rule.switch.push(item); } - return enc; -} + return rule; +}; + +internals.condition = function (schema, condition) { + + for (const key of ['then', 'otherwise']) { + if (condition[key] === undefined) { + delete condition[key]; + } + else { + condition[key] = schema.$_compile(condition[key]); + } + } + return condition; +}; /***/ }), -/***/ 51644: +/***/ 69490: /***/ ((__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; -}; +const Annotate = __nccwpck_require__(46014); +const Common = __nccwpck_require__(72448); +const Template = __nccwpck_require__(51396); -Utf7Codec.prototype.encoder = Utf7Encoder; -Utf7Codec.prototype.decoder = Utf7Decoder; -Utf7Codec.prototype.bomAware = true; +const internals = {}; -// -- Encoding -var nonDirectChars = /[^A-Za-z0-9'\(\),-\.\/:\? \n\r\t]+/g; +exports.Report = class { -function Utf7Encoder(options, codec) { - this.iconv = codec.iconv; -} + constructor(code, value, local, flags, messages, state, prefs) { -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))); -} + this.code = code; + this.flags = flags; + this.messages = messages; + this.path = state.path; + this.prefs = prefs; + this.state = state; + this.value = value; -Utf7Encoder.prototype.end = function() { -} + this.message = null; + this.template = null; + this.local = local || {}; + this.local.label = exports.label(this.flags, this.state, this.prefs, this.messages); -// -- Decoding + if (this.value !== undefined && + !this.local.hasOwnProperty('value')) { -function Utf7Decoder(options, codec) { - this.iconv = codec.iconv; - this.inBase64 = false; - this.base64Accum = ''; -} + this.local.value = this.value; + } -var base64Regex = /[A-Za-z0-9\/+]/; -var base64Chars = []; -for (var i = 0; i < 256; i++) - base64Chars[i] = base64Regex.test(String.fromCharCode(i)); + if (this.path.length) { + const key = this.path[this.path.length - 1]; + if (typeof key !== 'object') { + this.local.key = key; + } + } + } -var plusChar = '+'.charCodeAt(0), - minusChar = '-'.charCodeAt(0), - andChar = '&'.charCodeAt(0); + _setTemplate(template) { -Utf7Decoder.prototype.write = function(buf) { - var res = "", lastI = 0, - inBase64 = this.inBase64, - base64Accum = this.base64Accum; + this.template = template; - // The decoder is more involved as we must handle chunks in stream. + if (!this.flags.label && + this.path.length === 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; + const localized = this._template(this.template, 'root'); + if (localized) { + this.local.label = localized; } - } 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--; + toString() { - lastI = i+1; - inBase64 = false; - base64Accum = ''; + if (this.message) { + return this.message; + } + + const code = this.code; + + if (!this.prefs.errors.render) { + return this.code; + } + + const template = this._template(this.template) || + this._template(this.prefs.messages) || + this._template(this.messages); + + if (template === undefined) { + return `Error code "${code}" is not defined, your custom type is missing the correct messages definition`; + } + + // Render and cache result + + 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 this.message; + } + + _template(messages, code) { + + return exports.template(this.value, messages, code || this.code, this.state, this.prefs); + } +}; + + +exports.path = function (path) { + + let label = ''; + for (const segment of path) { + if (typeof segment === 'object') { // Exclude array single path segment + continue; + } + + if (typeof segment === 'string') { + if (label) { + label += '.'; } + + label += segment; + } + else { + label += `[${segment}]`; } } - if (!inBase64) { - res += this.iconv.decode(buf.slice(lastI), "ascii"); // Write direct chars. - } else { - var b64str = base64Accum + buf.slice(lastI).toString(); + return label; +}; + + +exports.template = function (value, messages, code, state, prefs) { + + if (!messages) { + return; + } + + if (Template.isTemplate(messages)) { + return code !== 'root' ? messages : null; + } + + let lang = prefs.errors.language; + if (Common.isResolvable(lang)) { + lang = lang.resolve(value, state, prefs); + } + + if (lang && + messages[lang]) { + + if (messages[lang][code] !== undefined) { + return messages[lang][code]; + } + + if (messages[lang]['*'] !== undefined) { + return messages[lang]['*']; + } + } + + if (!messages[code]) { + return messages['*']; + } + + return messages[code]; +}; + + +exports.label = function (flags, state, prefs, messages) { + + if (flags.label) { + return flags.label; + } + + if (!prefs.errors.label) { + return ''; + } + + let path = state.path; + if (prefs.errors.label === 'key' && + state.path.length > 1) { + + path = state.path.slice(-1); + } + + const normalized = exports.path(path); + if (normalized) { + return normalized; + } + + return exports.template(null, prefs.messages, 'root', state, prefs) || + messages && exports.template(null, messages, 'root', state, prefs) || + '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.details = function (errors, options = {}) { + + let messages = []; + const details = []; + + for (const item of errors) { + + // Override + + if (item instanceof Error) { + if (options.override !== false) { + return { override: item }; + } + + const message = item.toString(); + messages.push(message); + + details.push({ + message, + type: 'override', + context: { error: item } + }); + + continue; + } - 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); + // Report - res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); + const message = item.toString(); + messages.push(message); + + details.push({ + message, + path: item.path.filter((v) => typeof v !== 'object'), + type: item.code, + context: item.local + }); } - this.inBase64 = inBase64; - this.base64Accum = base64Accum; + if (messages.length > 1) { + messages = [...new Set(messages)]; + } - return res; -} + return { message: messages.join('. '), details }; +}; -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; -} +exports.ValidationError = class extends Error { + constructor(message, details, original) { -// 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. + super(message); + this._original = original; + this.details = details; + } + static isError(err) { -exports.utf7imap = Utf7IMAPCodec; -function Utf7IMAPCodec(codecOptions, iconv) { - this.iconv = iconv; + return err instanceof exports.ValidationError; + } }; -Utf7IMAPCodec.prototype.encoder = Utf7IMAPEncoder; -Utf7IMAPCodec.prototype.decoder = Utf7IMAPDecoder; -Utf7IMAPCodec.prototype.bomAware = true; - -// -- Encoding +exports.ValidationError.prototype.isJoi = true; -function Utf7IMAPEncoder(options, codec) { - this.iconv = codec.iconv; - this.inBase64 = false; - this.base64Accum = Buffer.alloc(6); - this.base64AccumIdx = 0; -} +exports.ValidationError.prototype.name = 'ValidationError'; -Utf7IMAPEncoder.prototype.write = function(str) { - var inBase64 = this.inBase64, - base64Accum = this.base64Accum, - base64AccumIdx = this.base64AccumIdx, - buf = Buffer.alloc(str.length*5 + 10), bufIdx = 0; +exports.ValidationError.prototype.annotate = Annotate.error; - 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; - } - buf[bufIdx++] = minusChar; // Write '-', then go to direct mode. - inBase64 = false; - } +/***/ }), - if (!inBase64) { - buf[bufIdx++] = uChar; // Write direct character +/***/ 86680: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (uChar === andChar) // Ampersand -> '&-' - buf[bufIdx++] = minusChar; - } +"use strict"; - } 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; - } - } - } - } +const Assert = __nccwpck_require__(32718); +const Clone = __nccwpck_require__(85578); - this.inBase64 = inBase64; - this.base64AccumIdx = base64AccumIdx; +const Common = __nccwpck_require__(72448); +const Messages = __nccwpck_require__(86103); - return buf.slice(0, bufIdx); -} -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; - } +const internals = {}; - buf[bufIdx++] = minusChar; // Write '-', then go to direct mode. - this.inBase64 = false; - } - return buf.slice(0, bufIdx); -} +exports.type = function (from, 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; -// -- Decoding + prototype._definition = def; -function Utf7IMAPDecoder(options, codec) { - this.iconv = codec.iconv; - this.inBase64 = false; - this.base64Accum = ''; -} + const parent = base._definition || {}; + def.messages = Messages.merge(parent.messages, def.messages); + def.properties = Object.assign({}, parent.properties, def.properties); -var base64IMAPChars = base64Chars.slice(); -base64IMAPChars[','.charCodeAt(0)] = true; + // Type -Utf7IMAPDecoder.prototype.write = function(buf) { - var res = "", lastI = 0, - inBase64 = this.inBase64, - base64Accum = this.base64Accum; + schema.type = def.type; - // 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). + // Flags - 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"); - } + def.flags = Object.assign({}, parent.flags, def.flags); - if (buf[i] != minusChar) // Minus may be absorbed after base64. - i--; + // Terms - lastI = i+1; - inBase64 = false; - base64Accum = ''; - } + 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 (!inBase64) { - res += this.iconv.decode(buf.slice(lastI), "ascii"); // Write direct chars. - } else { - var b64str = base64Accum + buf.slice(lastI).toString().replace(/,/g, '/'); + def.terms = terms; - 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); + // Constructor arguments - res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); + if (!def.args) { + def.args = parent.args; } - this.inBase64 = inBase64; - this.base64Accum = base64Accum; + // Prepare - return res; -} + def.prepare = internals.prepare(def.prepare, parent.prepare); -Utf7IMAPDecoder.prototype.end = function() { - var res = ""; - if (this.inBase64 && this.base64Accum.length > 0) - res = this.iconv.decode(Buffer.from(this.base64Accum, 'base64'), "utf16-be"); + // Coerce - this.inBase64 = false; - this.base64Accum = ''; - return res; -} + if (def.coerce) { + if (typeof def.coerce === 'function') { + def.coerce = { method: def.coerce }; + } + if (def.coerce.from && + !Array.isArray(def.coerce.from)) { + def.coerce = { method: def.coerce.method, from: [].concat(def.coerce.from) }; + } + } + def.coerce = internals.coerce(def.coerce, parent.coerce); -/***/ }), + // Validate -/***/ 67961: -/***/ ((__unused_webpack_module, exports) => { + def.validate = internals.validate(def.validate, parent.validate); -"use strict"; + // Rules + 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); -var BOMChar = '\uFEFF'; + let method = rule.method; + if (method === undefined) { + method = function () { -exports.PrependBOM = PrependBOMWrapper -function PrependBOMWrapper(encoder, options) { - this.encoder = encoder; - this.addBOM = true; -} + return this.$_addRule(name); + }; + } -PrependBOMWrapper.prototype.write = function(str) { - if (this.addBOM) { - str = BOMChar + str; - this.addBOM = false; - } + if (method) { + Assert(!prototype[name], 'Rule conflict in', def.type, name); + prototype[name] = method; + } - return this.encoder.write(str); -} + Assert(!rules[name], 'Rule conflict in', def.type, name); + rules[name] = rule; -PrependBOMWrapper.prototype.end = function() { - return this.encoder.end(); -} + if (rule.alias) { + const aliases = [].concat(rule.alias); + for (const alias of aliases) { + prototype[alias] = rule.method; + } + } + if (rule.args) { + rule.argsByName = new Map(); + rule.args = rule.args.map((arg) => { -//------------------------------------------------------------------------------ + if (typeof arg === 'string') { + arg = { name: arg }; + } -exports.StripBOM = StripBOMWrapper; -function StripBOMWrapper(decoder, options) { - this.decoder = decoder; - this.pass = false; - this.options = options || {}; -} + Assert(!rule.argsByName.has(arg.name), 'Duplicated argument name', arg.name); -StripBOMWrapper.prototype.write = function(buf) { - var res = this.decoder.write(buf); - if (this.pass || !res) - return res; + if (Common.isSchema(arg.assert)) { + arg.assert = arg.assert.strict().label(arg.name); + } - if (res[0] === BOMChar) { - res = res.slice(1); - if (typeof this.options.stripBOM === 'function') - this.options.stripBOM(); + rule.argsByName.set(arg.name, arg); + return arg; + }); + } + } } - this.pass = true; - return res; -} + def.rules = rules; -StripBOMWrapper.prototype.end = function() { - return this.decoder.end(); -} + // 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); + const modifier = def.modifiers[name]; + Assert(typeof modifier === 'function', 'Invalid modifier definition for', def.type, name); -/***/ }), + const method = function (arg) { -/***/ 30393: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return this.rule({ [name]: arg }); + }; -"use strict"; + prototype[name] = method; + modifiers[name] = modifier; + } + } -var Buffer = (__nccwpck_require__(14300).Buffer); -// Note: not polyfilled with safer-buffer on a purpose, as overrides Buffer + def.modifiers = modifiers; -// == Extend Node primitives to use iconv-lite ================================= + // Overrides -module.exports = function (iconv) { - var original = undefined; // Place to keep original methods. + 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 + } - // 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); + Object.assign(prototype, def.overrides); + } - iconv.extendNodeEncodings = function extendNodeEncodings() { - if (original) return; - original = {}; + // Casts - 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; - } + def.cast = Object.assign({}, parent.cast, def.cast); - 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, - }; + // Manifest - Buffer.isNativeEncoding = function(enc) { - return enc && nodeNativeEncodings[enc.toLowerCase()]; - } + 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; - // -- SlowBuffer ----------------------------------------------------------- - var SlowBuffer = (__nccwpck_require__(14300).SlowBuffer); + // Rebuild - original.SlowBufferToString = SlowBuffer.prototype.toString; - SlowBuffer.prototype.toString = function(encoding, start, end) { - encoding = String(encoding || 'utf8').toLowerCase(); + def.rebuild = internals.rebuild(def.rebuild, parent.rebuild); - // Use native conversion when possible - if (Buffer.isNativeEncoding(encoding)) - return original.SlowBufferToString.call(this, encoding, start, end); + return schema; +}; - // 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.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; - } +// Helpers - 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(); +internals.build = function (child, parent) { - // Use native conversion when possible - if (Buffer.isNativeEncoding(encoding)) - return original.SlowBufferWrite.call(this, string, offset, length, encoding); + if (!child || + !parent) { - if (string.length > 0 && (length < 0 || offset < 0)) - throw new RangeError('attempt to write beyond buffer bounds'); + return child || parent; + } - // 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; - } + return function (obj, desc) { - // -- Buffer --------------------------------------------------------------- + return parent(child(obj, desc), desc); + }; +}; - 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(); +internals.coerce = function (child, parent) { - // Use native conversion when possible - if (Buffer.isNativeEncoding(encoding)) - return original.BufferByteLength.call(this, str, encoding); + if (!child || + !parent) { - // Slow, I know, but we don't have a better way yet. - return iconv.encode(str, encoding).length; - } + return child || parent; + } - original.BufferToString = Buffer.prototype.toString; - Buffer.prototype.toString = function(encoding, start, end) { - encoding = String(encoding || 'utf8').toLowerCase(); + return { + from: child.from && parent.from ? [...new Set([...child.from, ...parent.from])] : null, + method(value, helpers) { - // Use native conversion when possible - if (Buffer.isNativeEncoding(encoding)) - return original.BufferToString.call(this, encoding, start, end); + let coerced; + if (!parent.from || + parent.from.includes(typeof value)) { - // 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); - } + coerced = parent.method(value, helpers); + if (coerced) { + if (coerced.errors || + coerced.value === undefined) { - 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; + return coerced; + } + + value = coerced.value; } - } 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); + if (!child.from || + child.from.includes(typeof value)) { - offset = +offset || 0; - var remaining = this.length - offset; - if (!length) { - length = remaining; - } else { - length = +length; - if (length > remaining) { - length = remaining; + const own = child.method(value, helpers); + if (own) { + return own; } } - if (string.length > 0 && (length < 0 || offset < 0)) - throw new RangeError('attempt to write beyond buffer bounds'); + return coerced; + } + }; +}; - // 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. - } +internals.prepare = function (child, parent) { + if (!child || + !parent) { - // -- Readable ------------------------------------------------------------- - if (iconv.supportsStreams) { - var Readable = (__nccwpck_require__(12781).Readable); + return child || parent; + } - 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; + return function (value, helpers) { + + const prepared = child(value, helpers); + if (prepared) { + if (prepared.errors || + prepared.value === undefined) { + + return prepared; } - Readable.prototype.collect = iconv._collect; + value = prepared.value; } + + return parent(value, helpers) || prepared; + }; +}; + + +internals.rebuild = function (child, parent) { + + if (!child || + !parent) { + + return child || parent; } - // 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.") + return function (schema) { - delete Buffer.isNativeEncoding; + parent(schema); + child(schema); + }; +}; - var SlowBuffer = (__nccwpck_require__(14300).SlowBuffer); - SlowBuffer.prototype.toString = original.SlowBufferToString; - SlowBuffer.prototype.write = original.SlowBufferWrite; +internals.validate = function (child, parent) { - Buffer.isEncoding = original.BufferIsEncoding; - Buffer.byteLength = original.BufferByteLength; - Buffer.prototype.toString = original.BufferToString; - Buffer.prototype.write = original.BufferWrite; + if (!child || + !parent) { - if (iconv.supportsStreams) { - var Readable = (__nccwpck_require__(12781).Readable); + return child || parent; + } - Readable.prototype.setEncoding = original.ReadableSetEncoding; - delete Readable.prototype.collect; + return function (value, helpers) { + + const result = parent(value, helpers); + if (result) { + if (result.errors && + (!Array.isArray(result.errors) || result.errors.length)) { + + return result; + } + + value = result.value; } - original = undefined; - } -} + return child(value, helpers) || result; + }; +}; /***/ }), -/***/ 19032: +/***/ 20918: /***/ ((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); +const Assert = __nccwpck_require__(32718); +const Clone = __nccwpck_require__(85578); -var bomHandling = __nccwpck_require__(67961), - iconv = module.exports; +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); -// 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; +let Schemas; -// Characters emitted in case of error. -iconv.defaultCharUnicode = '�'; -iconv.defaultCharSingleByte = '?'; -// Public API. -iconv.encode = function encode(str, encoding, options) { - str = "" + (str || ""); // Ensure string. +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' + } +}; - 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; +if (Buffer) { // $lab:coverage:ignore$ + internals.types.binary = __nccwpck_require__(34288); } -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. - } +internals.root = function () { - var decoder = iconv.getDecoder(encoding, options); + const root = { + _types: new Set(Object.keys(internals.types)) + }; - var res = decoder.write(buf); - var trail = decoder.end(); + // Types - return trail ? (res + trail) : res; -} + for (const type of root._types) { + root[type] = function (...args) { -iconv.encodingExists = function encodingExists(enc) { - try { - iconv.getCodec(enc); - return true; - } catch (e) { - return false; + Assert(!args.length || ['alternatives', 'link', 'object'].includes(type), 'The', type, 'type does not allow arguments'); + return internals.generate(this, internals.types[type], args); + }; } -} -// 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); + // Shortcuts - // Traverse iconv.encodings to find actual codec. - var codecOptions = {}; - while (true) { - var codec = iconv._codecDataCache[enc]; - if (codec) - return codec; + 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) { - var codecDef = iconv.encodings[enc]; + return this.any()[method](...args); + }; + } - switch (typeof codecDef) { - case "string": // Direct alias to other encoding. - enc = codecDef; - break; + // Methods - case "object": // Alias with options. Can be layered. - for (var key in codecDef) - codecOptions[key] = codecDef[key]; + Object.assign(root, internals.methods); - if (!codecOptions.encodingName) - codecOptions.encodingName = enc; - - enc = codecDef.type; - break; + // Aliases - case "function": // Codec itself. - if (!codecOptions.encodingName) - codecOptions.encodingName = enc; + for (const alias in internals.aliases) { + const target = internals.aliases[alias]; + root[alias] = root[target]; + } - // 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); + root.x = root.expression; - iconv._codecDataCache[codecOptions.encodingName] = codec; // Save it to be reused later. - return codec; + // Trace - default: - throw new Error("Encoding not recognized: '" + encoding + "' (searched as: '"+enc+"')"); - } + if (Trace.setup) { // $lab:coverage:ignore$ + Trace.setup(root); } -} -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, ""); -} + return root; +}; -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); +internals.methods = { - return encoder; -} + ValidationError: Errors.ValidationError, + version: Common.version, + cache: Cache.provider, -iconv.getDecoder = function getDecoder(encoding, options) { - var codec = iconv.getCodec(encoding), - decoder = new codec.decoder(options, codec); + assert(value, schema, ...args /* [message], [options] */) { - if (codec.bomAware && !(options && options.stripBOM === false)) - decoder = new bomHandling.StripBOM(decoder, options); + internals.assert(value, schema, true, args); + }, - return decoder; -} + attempt(value, schema, ...args /* [message], [options] */) { + return internals.assert(value, schema, false, args); + }, -// 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) { + build(desc) { - // Load streaming support in Node v0.10+ - var nodeVerArr = nodeVer.split(".").map(Number); - if (nodeVerArr[0] > 0 || nodeVerArr[1] >= 10) { - __nccwpck_require__(76409)(iconv); - } + Assert(typeof Manifest.build === 'function', 'Manifest functionality disabled'); + return Manifest.build(this, desc); + }, - // Load Node primitive extensions. - __nccwpck_require__(30393)(iconv); -} + checkPreferences(prefs) { -if (false) {} + Common.checkPreferences(prefs); + }, + compile(schema, options) { -/***/ }), + return Compile.compile(this, schema, options); + }, -/***/ 76409: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + defaults(modifier) { -"use strict"; + Assert(typeof modifier === 'function', 'modifier must be a function'); + 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'); -var Buffer = (__nccwpck_require__(14300).Buffer), - Transform = (__nccwpck_require__(12781).Transform); + joi[type] = function (...args) { + return internals.generate(this, schema, args); + }; + } -// == Exports ================================================================== -module.exports = function(iconv) { - - // Additional Public API. - iconv.encodeStream = function encodeStream(encoding, options) { - return new IconvLiteEncoderStream(iconv.getEncoder(encoding, options), options); - } + return joi; + }, - iconv.decodeStream = function decodeStream(encoding, options) { - return new IconvLiteDecoderStream(iconv.getDecoder(encoding, options), options); - } + expression(...args) { - iconv.supportsStreams = true; + return new Template(...args); + }, + extend(...extensions) { - // Not published yet. - iconv.IconvLiteEncoderStream = IconvLiteEncoderStream; - iconv.IconvLiteDecoderStream = IconvLiteDecoderStream; - iconv._collect = IconvLiteDecoderStream.prototype.collect; -}; + Common.verifyFlat(extensions, 'extend'); + Schemas = Schemas || __nccwpck_require__(85614); -// == 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); -} + Assert(extensions.length, 'You need to provide at least one extension'); + this.assert(extensions, Schemas.extensions); -IconvLiteEncoderStream.prototype = Object.create(Transform.prototype, { - constructor: { value: IconvLiteEncoderStream } -}); + const joi = Object.assign({}, this); + joi._types = new Set(joi._types); -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); - } -} + for (let extension of extensions) { + if (typeof extension === 'function') { + extension = extension(joi); + } -IconvLiteEncoderStream.prototype._flush = function(done) { - try { - var res = this.conv.end(); - if (res && res.length) this.push(res); - done(); - } - catch (e) { - done(e); - } -} + this.assert(extension, Schemas.extension); -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; -} + 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); + const base = item.base || this.any(); + const schema = Extend.type(base, item); -// == Decoder stream ======================================================= -function IconvLiteDecoderStream(conv, options) { - this.conv = conv; - options = options || {}; - options.encoding = this.encoding = 'utf8'; // We output strings. - Transform.call(this, options); -} + joi._types.add(item.type); + joi[item.type] = function (...args) { -IconvLiteDecoderStream.prototype = Object.create(Transform.prototype, { - constructor: { value: IconvLiteDecoderStream } -}); + return internals.generate(this, schema, args); + }; + } + } -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); - } -} + return joi; + }, -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); - } -} + isError: Errors.ValidationError.isError, + isExpression: Template.isTemplate, + isRef: Ref.isRef, + isSchema: Common.isSchema, -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; -} + in(...args) { + return Ref.in(...args); + }, + override: Common.symbols.override, -/***/ }), + ref(...args) { -/***/ 91230: -/***/ ((module) => { + return Ref.create(...args); + }, -// A simple implementation of make-array -function makeArray (subject) { - return Array.isArray(subject) - ? subject - : [subject] -} + types() { -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 types = {}; + for (const type of this._types) { + types[type] = this[type](); + } -const SLASH = '/' -const KEY_IGNORE = typeof Symbol !== 'undefined' - ? Symbol.for('node-ignore') - /* istanbul ignore next */ - : 'node-ignore' + for (const target in internals.aliases) { + types[target] = this[target](); + } -const define = (object, key, value) => - Object.defineProperty(object, key, {value}) + return types; + } +}; -const REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g -const RETURN_FALSE = () => false +// Helpers -// 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 -) +internals.assert = function (value, schema, annotate, args /* [message], [options] */) { -// See fixtures #59 -const cleanRangeBackSlash = slashes => { - const {length} = slashes - return slashes.slice(0, length - length % 2) -} + 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 || {})); -// > 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` + let error = result.error; + if (!error) { + return result.value; + } -// '`foo/`' should not continue with the '`..`' -const REPLACERS = [ + if (message instanceof Error) { + throw message; + } - // > Trailing spaces are ignored unless they are quoted with backslash ("\") - [ - // (a\ ) -> (a ) - // (a ) -> (a) - // (a \ ) -> (a ) - /\\?\s+$/, - match => match.indexOf('\\') === 0 - ? SPACE - : EMPTY - ], + const display = annotate && typeof error.annotate === 'function' ? error.annotate() : error.message; - // replace (\ ) with ' ' - [ - /\\\s/g, - () => SPACE - ], + if (error instanceof Errors.ValidationError === false) { + error = Clone(error); + } - // Escape metacharacters - // which is written down by users but means special for regular expressions. + error.message = message ? `${message} ${display}` : display; + throw error; +}; - // > 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, - () => '[^/]' - ], +internals.generate = function (root, schema, args) { - // leading slash - [ + Assert(root, 'Must be invoked on a Joi instance.'); - // > 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 - /^\//, - () => '^' - ], + schema.$_root = root; - // replace special metacharacter slash after the leading slash - [ - /\//g, - () => '\\/' - ], + if (!schema._definition.args || + !args.length) { - [ - // > 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 '\\*' - /^\^*\\\*\\\*\\\//, + return schema; + } - // '**/foo' <-> 'foo' - () => '^(?:.*\\/)?' - ], + return schema._definition.args(schema, ...args); +}; - // 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. - ? '(?:^|\\/)' +internals.expandExtension = function (extension, joi) { - // > Otherwise, Git treats the pattern as a shell glob suitable for - // > consumption by fnmatch(3) - : '^' + if (typeof extension.type === 'string') { + return [extension]; } - ], - // two globstars - [ - // Use lookahead assertions so that we could match more than one `'/**'` - /\\\/\\\*\\\*(?=\\\/|$)/g, + 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); + } + } - // Zero, one or several directories - // should not use '*', or it will be replaced by the next replacer + return extended; +}; - // 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. - // '/**/' - ? '(?:\\/[^\\/]+)*' +module.exports = internals.root(); - // 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 '*' +/***/ 87997: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // 'abc.*/' -> go - // 'abc.*' -> skip this rule - /(^|[^\\]+)\\\*(?=.+)/g, +"use strict"; - // '*.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 - ], +const Assert = __nccwpck_require__(32718); +const Clone = __nccwpck_require__(85578); - [ - // '\\\\' -> '\\' - /\\\\/g, - () => ESCAPE - ], +const Common = __nccwpck_require__(72448); +const Messages = __nccwpck_require__(86103); +const Ref = __nccwpck_require__(73838); +const Template = __nccwpck_require__(51396); - [ - // > The range notation, e.g. [a-zA-Z], - // > can be used to match one of the characters in a range. +let Schemas; - // `\` 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' - /(?:[^*])$/, +const internals = {}; - // 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. +exports.describe = function (schema) { - // '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}(?=$|\\/$)` - ], + const def = schema._definition; - // trailing wildcard - [ - /(\^|\\\/)?\\\*$/, - (_, p1) => { - const prefix = p1 - // '\^': - // '/*' does not match EMPTY - // '/*' does not match everything + // Type - // '\\\/': - // 'abc/*' does not match 'abc/' - ? `${p1}[^/]+` + const desc = { + type: schema.type, + flags: {}, + rules: [] + }; - // 'a*' matches 'a' - // 'a*' matches 'aa' - : '[^/]*' + // Flags - return `${prefix}(?=$|\\/$)` + for (const flag in schema._flags) { + if (flag[0] !== '_') { + desc.flags[flag] = internals.describe(schema._flags[flag]); + } } - ], -] -// A simple cache, because an ignore rule only has only one certain meaning -const regexCache = Object.create(null) + if (!Object.keys(desc.flags).length) { + delete desc.flags; + } -// @param {pattern} -const makeRegex = (pattern, ignoreCase) => { - let source = regexCache[pattern] + // Preferences - if (!source) { - source = REPLACERS.reduce( - (prev, current) => prev.replace(current[0], current[1].bind(pattern)), - pattern - ) - regexCache[pattern] = source - } + 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 ignoreCase - ? new RegExp(source, 'i') - : new RegExp(source) -} + // Allow / Invalid -const isString = subject => typeof subject === 'string' + if (schema._valids) { + desc.allow = schema._valids.describe(); + } -// > 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) + if (schema._invalids) { + desc.invalid = schema._invalids.describe(); + } - // > A line starting with # serves as a comment. - && pattern.indexOf('#') !== 0 + // Rules -const splitPattern = pattern => pattern.split(REGEX_SPLITALL_CRLF) + for (const rule of schema._rules) { + const ruleDef = def.rules[rule.name]; + if (ruleDef.manifest === false) { // Defaults to true + continue; + } -class IgnoreRule { - constructor ( - origin, - pattern, - negative, - regex - ) { - this.origin = origin - this.pattern = pattern - this.negative = negative - this.regex = regex - } -} + const item = { name: rule.name }; -const createRule = (pattern, ignoreCase) => { - const origin = pattern - let negative = false + for (const custom in def.modifiers) { + if (rule[custom] !== undefined) { + item[custom] = internals.describe(rule[custom]); + } + } - // > An optional prefix "!" which negates the pattern; - if (pattern.indexOf('!') === 0) { - negative = true - pattern = pattern.substr(1) - } + if (rule.args) { + item.args = {}; + for (const key in rule.args) { + const arg = rule.args[key]; + if (key === 'options' && + !Object.keys(arg).length) { - 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, '#') + continue; + } - const regex = makeRegex(pattern, ignoreCase) + item.args[key] = internals.describe(arg, { assign: key }); + } - return new IgnoreRule( - origin, - pattern, - negative, - regex - ) -} + if (!Object.keys(item.args).length) { + delete item.args; + } + } + + desc.rules.push(item); + } + + if (!desc.rules.length) { + delete desc.rules; + } + + // Terms (must be last to verify no name conflicts) -const throwError = (message, Ctor) => { - throw new Ctor(message) -} + for (const term in schema.$_terms) { + if (term[0] === '_') { + continue; + } -const checkPath = (path, originalPath, doThrow) => { - if (!isString(path)) { - return doThrow( - `path must be a string, but got \`${originalPath}\``, - TypeError - ) - } + Assert(!desc[term], 'Cannot describe schema due to internal name conflict with', term); - // We don't know if we should ignore EMPTY, so throw - if (!path) { - return doThrow(`path must not be empty`, TypeError) - } + const items = schema.$_terms[term]; + if (!items) { + continue; + } - // 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 - ) - } + if (items instanceof Map) { + if (items.size) { + desc[term] = [...items.entries()]; + } - return true -} + continue; + } -const isNotRelative = path => REGEX_TEST_INVALID_PATH.test(path) + if (Common.isValues(items)) { + desc[term] = items.describe(); + continue; + } -checkPath.isNotRelative = isNotRelative -checkPath.convert = p => p + Assert(def.terms[term], 'Term', term, 'missing configuration'); + const manifest = def.terms[term].manifest; + const mapped = typeof manifest === 'object'; + if (!items.length && + !mapped) { -class Ignore { - constructor ({ - ignorecase = true, - ignoreCase = ignorecase, - allowRelativePaths = false - } = {}) { - define(this, KEY_IGNORE, true) + continue; + } - this._rules = [] - this._ignoreCase = ignoreCase - this._allowRelativePaths = allowRelativePaths - this._initCache() - } + const normalized = []; + for (const item of items) { + normalized.push(internals.describe(item)); + } - _initCache () { - this._ignoreCache = Object.create(null) - this._testCache = Object.create(null) - } + // Mapped - _addPattern (pattern) { - // #32 - if (pattern && pattern[KEY_IGNORE]) { - this._rules = this._rules.concat(pattern._rules) - this._added = true - return - } + if (mapped) { + const { from, to } = manifest.mapped; + desc[term] = {}; + for (const item of normalized) { + desc[term][item[to]] = item[from]; + } - if (checkPattern(pattern)) { - const rule = createRule(pattern, this._ignoreCase) - this._added = true - this._rules.push(rule) - } - } + continue; + } - // @param {Array | string | Ignore} pattern - add (pattern) { - this._added = false + // Single - makeArray( - isString(pattern) - ? splitPattern(pattern) - : pattern - ).forEach(this._addPattern, this) + if (manifest === 'single') { + Assert(normalized.length === 1, 'Term', term, 'contains more than one item'); + desc[term] = normalized[0]; + continue; + } - // Some rules have just added to the ignore, - // making the behavior changed. - if (this._added) { - this._initCache() - } + // Array - return this - } + desc[term] = normalized; + } - // legacy - addPattern (pattern) { - return this.add(pattern) - } + internals.validate(schema.$_root, desc); + return desc; +}; - // | 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 +internals.describe = function (item, options = {}) { - // @param {boolean} whether should check if the path is unignored, - // setting `checkUnignored` to `false` could reduce additional - // path matching. + if (Array.isArray(item)) { + return item.map(internals.describe); + } - // @returns {TestResult} true if a file is ignored - _testOne (path, checkUnignored) { - let ignored = false - let unignored = false + if (item === Common.symbols.deepDefault) { + return { special: 'deep' }; + } - this._rules.forEach(rule => { - const {negative} = rule - if ( - unignored === negative && ignored !== unignored - || negative && !ignored && !unignored && !checkUnignored - ) { - return - } + if (typeof item !== 'object' || + item === null) { - const matched = rule.regex.test(path) + return item; + } - if (matched) { - ignored = !negative - unignored = negative - } - }) + if (options.assign === 'options') { + return Clone(item); + } - return { - ignored, - unignored + if (Buffer && Buffer.isBuffer(item)) { // $lab:coverage:ignore$ + return { buffer: item.toString('binary') }; } - } - // @returns {TestResult} - _test (originalPath, cache, checkUnignored, slices) { - const path = originalPath - // Supports nullable path - && checkPath.convert(originalPath) + if (item instanceof Date) { + return item.toISOString(); + } - checkPath( - path, - originalPath, - this._allowRelativePaths - ? RETURN_FALSE - : throwError - ) + if (item instanceof Error) { + return item; + } - return this._t(path, cache, checkUnignored, slices) - } + if (item instanceof RegExp) { + if (options.assign === 'regex') { + return item.toString(); + } - _t (path, cache, checkUnignored, slices) { - if (path in cache) { - return cache[path] + return { regex: item.toString() }; } - if (!slices) { - // path/to/a.js - // ['path', 'to', 'a.js'] - slices = path.split(SLASH) + if (item[Common.symbols.literal]) { + return { function: item.literal }; } - slices.pop() + if (typeof item.describe === 'function') { + if (options.assign === 'ref') { + return item.describe().ref; + } - // If the path has no parent directory, just test it - if (!slices.length) { - return cache[path] = this._testOne(path, checkUnignored) + return item.describe(); } - const parent = this._t( - slices.join(SLASH) + SLASH, - cache, - checkUnignored, - slices - ) + const normalized = {}; + for (const key in item) { + const value = item[key]; + if (value === undefined) { + continue; + } - // 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) - } + normalized[key] = internals.describe(value, { assign: key }); + } - ignores (path) { - return this._test(path, this._ignoreCache, false).ignored - } + return normalized; +}; - createFilter () { - return path => !this.ignores(path) - } - filter (paths) { - return makeArray(paths).filter(this.createFilter()) - } +exports.build = function (joi, desc) { - // @returns {TestResult} - test (path) { - return this._test(path, this._testCache, true) - } -} + const builder = new internals.Builder(joi); + return builder.parse(desc); +}; -const factory = options => new Ignore(options) -const isPathValid = path => - checkPath(path && checkPath.convert(path), path, RETURN_FALSE) +internals.Builder = class { -factory.isPathValid = isPathValid + constructor(joi) { -// Fixes typescript -factory.default = factory + this.joi = joi; + } -module.exports = factory + parse(desc) { -// 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, '/') + internals.validate(this.joi, desc); - checkPath.convert = makePosix + // Type - // '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) -} + let schema = this.joi[desc.type]()._bare(); + const def = schema._definition; + // 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])); + } + } -/***/ 98043: -/***/ ((module) => { + // Preferences -"use strict"; + if (desc.preferences) { + schema = schema.preferences(this.build(desc.preferences)); + } + // Allow / Invalid -module.exports = (string, count = 1, options) => { - options = { - indent: ' ', - includeEmptyLines: false, - ...options - }; + if (desc.allow) { + schema = schema.allow(...this.build(desc.allow)); + } - if (typeof string !== 'string') { - throw new TypeError( - `Expected \`input\` to be a \`string\`, got \`${typeof string}\`` - ); - } + if (desc.invalid) { + schema = schema.invalid(...this.build(desc.invalid)); + } - if (typeof count !== 'number') { - throw new TypeError( - `Expected \`count\` to be a \`number\`, got \`${typeof count}\`` - ); - } + // Rules - if (typeof options.indent !== 'string') { - throw new TypeError( - `Expected \`options.indent\` to be a \`string\`, got \`${typeof options.indent}\`` - ); - } + if (desc.rules) { + for (const rule of desc.rules) { + Assert(typeof schema[rule.name] === 'function', 'Invalid rule', rule.name, 'for type', desc.type); - if (count === 0) { - return string; - } + const args = []; + if (rule.args) { + const built = {}; + for (const key in rule.args) { + built[key] = this.build(rule.args[key], { assign: key }); + } - const regex = options.includeEmptyLines ? /^/gm : /^(?!\s*$)/gm; + 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]]); + } + } - return string.replace(regex, options.indent.repeat(count)); -}; + // Apply + schema = schema[rule.name](...args); -/***/ }), + // Ruleset -/***/ 44124: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + const options = {}; + for (const custom in def.modifiers) { + if (rule[custom] !== undefined) { + options[custom] = this.build(rule[custom]); + } + } -try { - var util = __nccwpck_require__(73837); - if (typeof util.inherits !== 'function') throw ''; - module.exports = util.inherits; -} catch (e) { - module.exports = __nccwpck_require__(8544); -} + 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; + } -/***/ 8544: -/***/ ((module) => { + Assert(def.terms[key], 'Term', key, 'missing configuration'); + const manifest = def.terms[key].manifest; -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, 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) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor - } -} + 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; + } -/***/ }), + if (manifest === 'single') { + terms[key] = this.build(desc[key]); + continue; + } -/***/ 30545: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + if (typeof manifest === 'object') { + terms[key] = {}; + for (const name in desc[key]) { + const value = desc[key][name]; + terms[key][name] = this.parse(value); + } -"use strict"; + continue; + } -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; + terms[key] = this.build(desc[key]); } - err.command = { - name: item.command.name, - args: item.command.args, - }; - this.redis.handleReconnection(err, item); + + if (desc.whens) { + terms.whens = desc.whens.map((when) => this.build(when)); + } + + schema = def.manifest.build(schema, terms); + schema.$_temp.ruleset = false; + return schema; } - returnReply(reply) { - if (this.handleMonitorReply(reply)) { - return; + + build(desc, options = {}) { + + if (desc === null) { + return null; } - if (this.handleSubscriberReply(reply)) { - return; + + if (Array.isArray(desc)) { + return desc.map((item) => this.build(item)); } - const item = this.shiftCommand(reply); - if (!item) { - return; + + if (desc instanceof Error) { + return desc; } - 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); - } + + if (options.assign === 'options') { + return Clone(desc); } - else if (command_1.default.checkFlag("EXIT_SUBSCRIBER_MODE", item.command.name)) { - if (!fillUnsubCommand(item.command, reply[2])) { - this.redis.commandQueue.unshift(item); - } + + if (options.assign === 'regex') { + return internals.regex(desc); } - else { - item.command.resolve(reply); + + if (options.assign === 'ref') { + return Ref.build(desc); } - } - handleSubscriberReply(reply) { - if (!this.redis.condition.subscriber) { - return false; + + if (typeof desc !== 'object') { + return desc; } - 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].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; + + 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$ } - 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 (desc.function) { + return { [Common.symbols.literal]: true, literal: desc.function }; } - 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 (desc.override) { + return Common.symbols.override; } - default: { - const item = this.shiftCommand(reply); - if (!item) { - return; - } - item.command.resolve(reply); + + if (desc.ref) { + return Ref.build(desc.ref); + } + + 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; + } + + if (desc.value) { + return Clone(desc.value); + } + } + + if (desc.type) { + return this.parse(desc); + } + + if (desc.template) { + return Template.build(desc); + } + + const normalized = {}; + for (const key in desc) { + normalized[key] = this.build(desc[key], { assign: key }); + } + + return normalized; + } +}; + + +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); +}; + + +internals.validate = function (joi, desc) { + + Schemas = Schemas || __nccwpck_require__(85614); + + joi.assert(desc, Schemas.description); +}; + + +/***/ }), + +/***/ 86103: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +const Assert = __nccwpck_require__(32718); +const Clone = __nccwpck_require__(85578); + +const Template = __nccwpck_require__(51396); + + +const internals = {}; + + +exports.compile = function (messages, target) { + + // Single value string ('plain error message', 'template {error} message') + + if (typeof messages === 'string') { + Assert(!target, 'Cannot set single message string'); + return new Template(messages); + } + + // Single value template + + if (Template.isTemplate(messages)) { + Assert(!target, 'Cannot set single message template'); + return messages; + } + + // By error code { 'number.min': } + + Assert(typeof messages === 'object' && !Array.isArray(messages), 'Invalid message options'); + + target = target ? Clone(target) : {}; + + for (let code in messages) { + const message = messages[code]; + + if (code === 'root' || + Template.isTemplate(message)) { + + target[code] = message; + continue; + } + + if (typeof message === 'string') { + target[code] = new Template(message); + continue; + } + + // 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]; + + if (code === 'root' || + Template.isTemplate(localized)) { + + target[language][code] = localized; + continue; } + + Assert(typeof localized === 'string', 'Invalid message for', code, 'in', language); + target[language][code] = new Template(localized); } - return true; } - handleMonitorReply(reply) { - if (this.redis.status !== "monitoring") { - return false; + + return target; +}; + + +exports.decompile = function (messages) { + + // By error code { 'number.min': } + + const target = {}; + for (let code in messages) { + const message = messages[code]; + + if (code === 'root') { + target.root = message; + continue; } - 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; + + if (Template.isTemplate(message)) { + target[code] = message.describe({ compact: true }); + continue; } - // 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; + + // By language { english: { 'number.min': } } + + const language = code; + target[language] = {}; + + for (code in message) { + const localized = message[code]; + + if (code === 'root') { + target[language].root = localized; + continue; + } + + target[language][code] = localized.describe({ compact: true }); } - return item; } -} -exports["default"] = DataHandler; -function fillSubCommand(command, count) { - // TODO: use WeakMap here - if (typeof command.remainReplies === "undefined") { - command.remainReplies = command.args.length; + + return target; +}; + + +exports.merge = function (base, extended) { + + if (!base) { + return exports.compile(extended); } - if (--command.remainReplies === 0) { - command.resolve(count); - return true; + + if (!extended) { + return base; } - return false; -} -function fillUnsubCommand(command, count) { - if (typeof command.remainReplies === "undefined") { - command.remainReplies = command.args.length; + + // Single value string + + if (typeof extended === 'string') { + return new Template(extended); } - if (command.remainReplies === 0) { - if (count === 0) { - command.resolve(count); - return true; - } - return false; + + // Single value template + + if (Template.isTemplate(extended)) { + return extended; } - if (--command.remainReplies === 0) { - command.resolve(count); - return true; + + // By error code { 'number.min': } + + const target = Clone(base); + + for (let code in extended) { + const message = extended[code]; + + if (code === 'root' || + Template.isTemplate(message)) { + + target[code] = message; + continue; + } + + if (typeof message === 'string') { + target[code] = new Template(message); + continue; + } + + // 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]; + + if (code === 'root' || + Template.isTemplate(localized)) { + + target[language][code] = localized; + continue; + } + + Assert(typeof localized === 'string', 'Invalid message for', code, 'in', language); + target[language][code] = new Template(localized); + } } - return false; -} + + return target; +}; /***/ }), -/***/ 6134: +/***/ 81290: /***/ ((__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; + +const Assert = __nccwpck_require__(32718); + +const Common = __nccwpck_require__(72448); +const Ref = __nccwpck_require__(73838); + + +const internals = {}; + + + +exports.Ids = internals.Ids = class { + + constructor() { + + this._byId = new Map(); + this._byKey = new Map(); + this._schemaChain = false; } - _read() { - if (this._redisDrained) { - this.push(null); - return; + + clone() { + + const clone = new internals.Ids(); + clone._byId = new Map(this._byId); + clone._byKey = new Map(this._byKey); + clone._schemaChain = this._schemaChain; + return clone; + } + + concat(source) { + + if (source._schemaChain) { + this._schemaChain = true; } - const args = [this._redisCursor]; - if (this.opt.key) { - args.unshift(this.opt.key); + + 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.opt.match) { - args.push("MATCH", this.opt.match); + + 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); } - if (this.opt.type) { - args.push("TYPE", this.opt.type); + } + + 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.opt.count) { - args.push("COUNT", String(this.opt.count)); + + return adjusted.schema; + } + + labels(path, behind = []) { + + const current = path[0]; + const node = this._get(current); + if (!node) { + return [...behind, ...path].join('.'); } - 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]); - }); + + 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); } - close() { - this._redisDrained = true; + + reach(path, behind = []) { + + const current = path[0]; + const node = this._get(current); + Assert(node, 'Schema does not contain path', [...behind, ...path].join('.')); + + const forward = path.slice(1); + if (!forward.length) { + return node.schema; + } + + return node.schema._ids.reach(forward, [...behind, current]); } -} -exports["default"] = ScanStream; + register(schema, { key } = {}) { -/***/ }), + if (!schema || + !Common.isSchema(schema)) { -/***/ 73527: -/***/ ((__unused_webpack_module, exports) => { + return; + } -"use strict"; + if (schema.$_property('schemaChain') || + schema._ids._schemaChain) { -Object.defineProperty(exports, "__esModule", ({ value: true })); -/** - * Tiny class to simplify dealing with subscription set - * - * @export - * @class SubscriptionSet - */ -class SubscriptionSet { - constructor() { - this.set = { - subscribe: {}, - psubscribe: {}, - }; + 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); + + this._byId.set(id, { schema, id }); + } + + if (key) { + Assert(!this._byKey.has(key), 'Schema already contains key:', key); + Assert(!this._byId.has(key), 'Schema key conflicts with existing id:', key); + + this._byKey.set(key, { schema, id: key }); + } } - add(set, channel) { - this.set[mapSet(set)][channel] = true; + + reset() { + + this._byId = new Map(); + this._byKey = new Map(); + this._schemaChain = false; } - del(set, channel) { - delete this.set[mapSet(set)][channel]; + + _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]; + + const forward = path.slice(1); + if (!forward.length) { + return nodes; + } + + return node.schema._ids._collect(forward, [...behind, current], nodes); } - channels(set) { - return Object.keys(this.set[mapSet(set)]); + + _get(id) { + + return this._byId.get(id) || this._byKey.get(id); } - isEmpty() { - return (this.channels("subscribe").length === 0 && - this.channels("psubscribe").length === 0); +}; + + +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; + + for (const name in schema._flags) { + if (name[0] === '_') { + continue; + } + + const result = internals.scan(schema._flags[name], { source: 'flags', name }, options); + if (result !== undefined) { + obj = obj || schema.clone(); + obj._flags[name] = result; + } } -} -exports["default"] = SubscriptionSet; -function mapSet(set) { - if (set === "unsubscribe") { - return "subscribe"; + + 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 (set === "punsubscribe") { - return "psubscribe"; + + for (const name in schema.$_terms) { + if (name[0] === '_') { + continue; + } + + const result = internals.scan(schema.$_terms[name], { source: 'terms', name }, options); + if (result !== undefined) { + obj = obj || schema.clone(); + obj.$_terms[name] = result; + } } - return set; -} + return obj; +}; -/***/ }), -/***/ 97873: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +internals.scan = function (item, source, options, _path, _key) { -"use strict"; + const path = _path || []; + + if (item === null || + typeof item !== 'object') { -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); + + 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; } } - else { - for (let i = 0; i < callbacks.length; i++) { - process.nextTick(callbacks[i], ...results[i]); - } + + return clone; + } + + if (options.schema !== false && Common.isSchema(item) || + options.ref !== false && Ref.isRef(item)) { + + const result = options.each(item, { ...source, path, key: _key }); + if (result === item) { + return; } - // 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 result; + } + + for (const key in item) { + if (key[0] === '_') { + continue; } - }); -} -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; + + const result = internals.scan(item[key], source, options, [key, ...path], _key); + if (result !== undefined) { + clone = clone || Object.assign({}, item); + clone[key] = result; } - else if (Array.isArray(arg) || lodash_1.isArguments(arg)) { - if (arg.length === 0) { - continue; + } + + return clone; +}; + + +/***/ }), + +/***/ 73838: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +const Assert = __nccwpck_require__(32718); +const Clone = __nccwpck_require__(85578); +const Reach = __nccwpck_require__(18891); + +const Common = __nccwpck_require__(72448); + +let Template; + + +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.create = function (key, 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'); + + const ref = Object.assign({}, internals.defaults, options); + delete ref.prefix; + + 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; } - return arg[0]; } - const flattened = lodash_1.flatten([arg]); - if (flattened.length > 0) { - return flattened[0]; + + if (separator && + separator === key) { + + key = null; + ref.ancestor = 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; + 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; + } } - 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; + + ref.ancestor = ancestor; } - resolve(value); - }); - pipeline[functionName](...args); - }); - return standard_as_callback_1.default(autoPipelinePromise, callback); -} -exports.executeWithAutoPipelining = executeWithAutoPipelining; + } + } + + ref.path = separator ? (key === null ? [] : key.split(separator)) : [key]; + + return new internals.Ref(ref); +}; + + +exports["in"] = function (key, options = {}) { + + return exports.create(key, { ...options, in: true }); +}; + + +exports.isRef = function (ref) { + + return ref ? !!ref[Common.symbols.ref] : false; +}; + + +internals.Ref = class { + + 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 + ]); -/***/ }), + 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'); -/***/ 35835: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + Object.assign(this, internals.defaults, options); -"use strict"; + Assert(this.type === 'value' || this.ancestor === undefined, 'Non-value references cannot reference ancestors'); -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, -}; + if (Array.isArray(this.map)) { + this.map = new Map(this.map); + } + this.depth = this.path.length; + this.key = this.path.length ? this.path.join(this.separator) : null; + this.root = this.path[0]; -/***/ }), + this.updateDisplay(); + } -/***/ 18394: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + resolve(value, state, prefs, local, options = {}) { -"use strict"; + Assert(!this.in || options.in, 'Invalid in() reference usage'); -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; + if (this.type === 'global') { + return this._resolve(prefs.context, state, options); + } + + if (this.type === 'local') { + return this._resolve(local, state, options); + } + + if (!this.ancestor) { + return this._resolve(value, state, options); + } + + if (this.ancestor === 'root') { + return this._resolve(state.ancestors[state.ancestors.length - 1], state, 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); + } + + _resolve(target, state, options) { + + let resolved; + + if (this.type === 'value' && + state.mainstay.shadow && + options.shadow !== false) { + + resolved = state.mainstay.shadow.get(this.absolute(state)); + } + + if (resolved === undefined) { + resolved = Reach(target, this.path, { iterables: this.iterables, functions: true }); + } + + if (this.adjust) { + resolved = this.adjust(resolved); + } + + if (this.map) { + const mapped = this.map.get(resolved); + if (mapped !== undefined) { + resolved = mapped; } - debug("a new node is discovered and there is no subscriber, selecting a new one..."); - this.selectSubscriber(); - }); + } + + if (state.mainstay) { + state.mainstay.tracer.resolve(state, this, resolved); + } + + return resolved; } - getInstance() { - return this.subscriber; + + toString() { + + return this.display; } - selectSubscriber() { - const lastActiveSubscriber = this.lastActiveSubscriber; - // Disconnect the previous subscriber even if there - // will not be a new one. - if (lastActiveSubscriber) { - lastActiveSubscriber.disconnect(); + + absolute(state) { + + return [...state.path.slice(0, -this.ancestor), ...this.path]; + } + + clone() { + + return new internals.Ref(this); + } + + describe() { + + const ref = { path: this.path }; + + if (this.type !== 'value') { + ref.type = this.type; } - if (this.subscriber) { - this.subscriber.disconnect(); + + if (this.separator !== '.') { + ref.separator = this.separator; } - 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; + + if (this.type === 'value' && + this.ancestor !== 1) { + + ref.ancestor = this.ancestor; } - 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 (this.map) { + ref.map = [...this.map]; } - 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); - }); - } + + for (const key of ['adjust', 'iterables', 'render']) { + if (this[key] !== null && + this[key] !== undefined) { + + ref[key] = this[key]; } } - else { - this.lastActiveSubscriber = this.subscriber; + + if (this.in !== false) { + ref.in = true; } - for (const event of ["message", "messageBuffer"]) { - this.subscriber.on(event, (arg1, arg2) => { - this.emitter.emit(event, arg1, arg2); - }); + + return { ref }; + } + + updateDisplay() { + + const key = this.key !== null ? this.key : ''; + if (this.type !== 'value') { + this.display = `ref:${this.type}:${key}`; + return; } - for (const event of ["pmessage", "pmessageBuffer"]) { - this.subscriber.on(event, (arg1, arg2, arg3) => { - this.emitter.emit(event, arg1, arg2, arg3); - }); + + if (!this.separator) { + this.display = `ref:${key}`; + return; + } + + if (!this.ancestor) { + this.display = `ref:${this.separator}${key}`; + return; + } + + if (this.ancestor === 'root') { + this.display = `ref:root:${key}`; + return; + } + + if (this.ancestor === 1) { + this.display = `ref:${key || '..'}`; + return; } + + const lead = new Array(this.ancestor + 1).fill(this.separator).join(''); + this.display = `ref:${lead}${key || ''}`; } - start() { - this.started = true; - this.selectSubscriber(); - debug("started"); +}; + + +internals.Ref.prototype[Common.symbols.ref] = true; + + +exports.build = function (desc) { + + desc = Object.assign({}, internals.defaults, desc); + if (desc.type === 'value' && + desc.ancestor === undefined) { + + desc.ancestor = 1; } - stop() { - this.started = false; - if (this.subscriber) { - this.subscriber.disconnect(); - this.subscriber = null; + + return new internals.Ref(desc); +}; + + +internals.context = function (key, separator, prefix = {}) { + + key = key.trim(); + + if (prefix) { + const globalp = prefix.global === undefined ? '$' : prefix.global; + if (globalp !== separator && + key.startsWith(globalp)) { + + return { key: key.slice(globalp.length), type: 'global' }; + } + + const local = prefix.local === undefined ? '#' : prefix.local; + if (local !== separator && + key.startsWith(local)) { + + return { key: key.slice(local.length), type: 'local' }; + } + + const root = prefix.root === undefined ? '/' : prefix.root; + if (root !== separator && + key.startsWith(root)) { + + return { key: key.slice(root.length), type: 'value', root: true }; } - debug("stopped"); } -} -exports["default"] = ClusterSubscriber; + return { key, type: 'value' }; +}; -/***/ }), -/***/ 34589: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +internals.ancestor = function (key, separator) { -"use strict"; + if (!separator) { + return [1, 0]; // 'a_b' -> 1 (parent) + } -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 = {}; + if (key[0] !== separator) { // 'a.b' -> 1 (parent) + return [1, 0]; } - getNodes(role = "all") { - const nodes = this.nodes[role]; - return Object.keys(nodes).map((key) => nodes[key]); + + if (key[1] !== separator) { // '.a.b' -> 0 (self) + return [0, 1]; } - getInstanceByKey(key) { - return this.nodes.all[key]; + + let i = 2; + while (key[i] === separator) { + ++i; } - getSampleInstance(role) { - const keys = Object.keys(this.nodes[role]); - const sampleKey = utils_1.sample(keys); - return this.nodes[role][sampleKey]; + + return [i - 1, i]; // '...a.b.' -> 2 (grandparent) +}; + + +exports.toSibling = 0; + +exports.toParent = 1; + + +exports.Manager = class { + + constructor() { + + this.refs = []; // 0: [self refs], 1: [parent refs], 2: [grandparent refs], ... } - /** - * 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]); + + register(source, target) { + + if (!source) { + return; } - else { - this.specifiedOptions[key] = node; + + target = target === undefined ? exports.toParent : target; + + // Array + + if (Array.isArray(source)) { + for (const ref of source) { + this.register(ref, target); + } + + return; } - 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; + + // 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 }); } } + + return; } - 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); - }); + + // Reference + + if (exports.isRef(source) && + source.type === 'value' && + source.ancestor - target >= 0) { + + this.refs.push({ ancestor: source.ancestor - target, root: source.root }); } - 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]; + + // Template + + Template = Template || __nccwpck_require__(51396); + + if (Template.isTemplate(source)) { + this.register(source.refs(), target); } - 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); + + get length() { + + return this.refs.length; + } + + clone() { + + const copy = new exports.Manager(); + copy.refs = Clone(this.refs); + return copy; + } + + reset() { + + this.refs = []; + } + + roots() { + + return this.refs.filter((ref) => !ref.ancestor).map((ref) => ref.root); + } +}; + + +/***/ }), + +/***/ 85614: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +const Joi = __nccwpck_require__(20918); + + +const internals = {}; + + +// Preferences + +internals.wrap = Joi.string() + .min(1) + .max(2) + .allow(false); + + +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(); + + +// Extensions + +internals.nameRx = /^[a-zA-Z0-9]\w*$/; + + +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() +}); + + +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(); + + +exports.extensions = Joi.array().items(Joi.object(), Joi.function().arity(1)).strict(); + + +// Manifest + +internals.desc = { + + buffer: Joi.object({ + buffer: Joi.string() + }), + + func: Joi.object({ + function: Joi.function().required(), + options: { + literal: true + } + }), + + override: Joi.object({ + override: true + }), + + 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() + }), + + regex: Joi.object({ + regex: Joi.string().min(3) + }), + + special: Joi.object({ + special: Joi.valid('deep').required() + }), + + template: Joi.object({ + template: Joi.string().required(), + options: Joi.object() + }), + + value: Joi.object({ + value: Joi.alternatives([Joi.object(), Joi.array()]).required() + }) +}; + + +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.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 + ); + + +internals.desc.messages = Joi.object() + .pattern(/.+/, [ + Joi.string(), + internals.desc.template, + Joi.object().pattern(/.+/, [Joi.string(), internals.desc.template]) + ]); + + +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 } - }); - Object.keys(newNodes).forEach((key) => { - const node = newNodes[key]; - this.findOrCreate(node, node.readOnly); - }); + }, + 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() + }), + + // Terms + + keys: Joi.object().pattern(/.*/, Joi.link('/')), + link: internals.desc.ref +}) + .pattern(/^[a-z]\w*$/, Joi.any()); + + +/***/ }), + +/***/ 73634: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const Clone = __nccwpck_require__(85578); +const Reach = __nccwpck_require__(18891); + +const Common = __nccwpck_require__(72448); + + +const internals = { + value: Symbol('value') +}; + + +module.exports = internals.State = class { + + constructor(path, ancestors, state) { + + this.path = path; + this.ancestors = ancestors; // [parent, ..., root] + + this.mainstay = state.mainstay; + this.schemas = state.schemas; // [current, ..., root] + this.debug = null; } -} -exports["default"] = ConnectionPool; + localize(path, ancestors = null, schema = null) { + + const state = new internals.State(path, ancestors, this); + + if (schema && + state.schemas) { + + state.schemas = [internals.schemas(schema), ...state.schemas]; + } + + return state; + } -/***/ }), + nest(schema, debug) { -/***/ 12770: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + const state = new internals.State(this.path, this.ancestors, this); + state.schemas = state.schemas && [internals.schemas(schema), ...state.schemas]; + state.debug = debug; + return state; + } -"use strict"; + shadow(value, reason) { -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 = {}; + this.mainstay.shadow = this.mainstay.shadow || new internals.Shadow(); + this.mainstay.shadow.set(this.path, value, reason); } - /** - * 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); + + snapshot() { + + if (this.mainstay.shadow) { + this._snapshot = Clone(this.mainstay.shadow.node(this.path)); } } - 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()(); + + restore() { + + if (this.mainstay.shadow) { + this.mainstay.shadow.override(this.path, this._snapshot); + this._snapshot = undefined; } } -} -exports["default"] = DelayQueue; +}; -/***/ }), +internals.schemas = function (schema) { -/***/ 17208: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + if (Common.isSchema(schema)) { + return { schema }; + } -"use strict"; + return schema; +}; -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(); + +internals.Shadow = class { + + constructor() { + + this._values = null; } - clearNodesRefreshInterval() { - if (this.slotsTimer) { - clearTimeout(this.slotsTimer); - this.slotsTimer = null; + + set(path, value, reason) { + + if (!path.length) { // No need to store root value + return; } - } - resetNodesRefreshInterval() { - if (this.slotsTimer) { + + if (reason === 'strip' && + typeof path[path.length - 1] === 'number') { // Cannot store stripped array values (due to shift) + 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; + + this._values = this._values || new Map(); + + 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); } - // 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")); + + node = next; } + + node[internals.value] = value; } - /** - * 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(); + + get(path) { + + const node = this.node(path); + if (node) { + return node[internals.value]; } - else { - this.connectionPool.reset([]); + } + + node(path) { + + if (!this._values) { + return; } + + return Reach(this._values, path, { iterables: true }); } - /** - * 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; + + override(path, node) { + + if (!this._values) { + return; } - 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; + + const parents = path.slice(0, -1); + const own = path[path.length - 1]; + const parent = Reach(this._values, parents, { iterables: true }); + + if (node) { + parent.set(own, node); + return; } - 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"'); + + if (parent) { + parent.delete(own); } - 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; +}; + + +/***/ }), + +/***/ 51396: +/***/ ((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 Ref = __nccwpck_require__(73838); + + +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 } - /** - * 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); - }); +}; + + +module.exports = exports = internals.Template = class { + + constructor(source, options) { + + Assert(typeof source === 'string', 'Template source must be a string'); + Assert(!source.includes('\u0000') && !source.includes('\u0001'), 'Template source cannot contain reserved control characters'); + + this.source = source; + this.rendered = source; + + this._template = null; + this._settings = Clone(options); + + this._parse(); } - /** - * Refresh the slot cache - * - * @private - * @param {CallbackFunction} [callback] - * @memberof Cluster - */ - refreshSlotsCache(callback) { - if (this.isRefreshing) { - if (typeof callback === "function") { - process.nextTick(callback); - } + + _parse() { + + // 'text {raw} {{ref}} \\{{ignore}} {{ignore\\}} {{ignore {{ignore}' + + if (!this.source.includes('{')) { return; } - this.isRefreshing = true; - const _this = this; - const wrapper = function (error) { - _this.isRefreshing = false; - if (typeof callback === "function") { - callback(error); + + // Encode escaped \\{{{{{ + + const encoded = internals.encode(this.source); + + // Split on first { in each set + + const parts = internals.split(encoded); + + // Process parts + + let refs = false; + const processed = []; + const head = parts.shift(); + if (head) { + processed.push(head); + } + + 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 { + + processed.push(`{${internals.decode(part)}`); + continue; } - }; - 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); + + let variable = part.slice(raw ? 0 : 1, end); + const wrapped = variable[0] === ':'; + if (wrapped) { + variable = variable.slice(1); + } + + const dynamic = this._ref(internals.decode(variable), { raw, wrapped }); + processed.push(dynamic); + if (typeof dynamic !== 'string') { + refs = true; + } + + const rest = part.slice(end + ender.length); + if (rest) { + processed.push(internals.decode(rest)); } - 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); + + if (!refs) { + this.rendered = processed.join(''); + return; } + + this._template = processed; } - 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); - } + + static date(date, prefs) { + + return internals.dateFormat[prefs.dateFormat].call(date); + } + + describe(options = {}) { + + if (!this._settings && + options.compact) { + + return this.source; } + + const desc = { template: this.source }; + if (this._settings) { + desc.options = this._settings; + } + + return desc; } - 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); + + 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() { + + if (!this._template) { + return; + } + + const refs = []; + for (const part of this._template) { + if (typeof part !== 'string') { + refs.push(...part.refs); } } - return typeof nodeKey === "string" - ? util_1.nodeKeyToRedisOptions(nodeKey) - : nodeKey; + + return refs; } - 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; + + resolve(value, state, prefs, local) { + + if (this._template && + this._template.length === 1) { + + return this._part(this._template[0], /* context -> [*/ value, state, prefs, local, {} /*] */); } - 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 this.render(value, state, prefs, local); + } + + _part(part, ...args) { + + if (part.ref) { + return part.ref.resolve(...args); } - 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); - }, - }); - }; + + return part.formula.evaluate(args); + } + + render(value, state, prefs, local, options = {}) { + + if (!this.isDynamic()) { + return this.rendered; } - tryConnection(); - function tryConnection(random, asking) { - if (_this.status === "end") { - command.reject(new redis_errors_1.AbortError("Cluster is ended.")); - return; + + const parts = []; + for (const part of this._template) { + if (typeof part === 'string') { + parts.push(part); } - 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; + 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)); } } - 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 parts.join(''); + } + + _ref(content, { raw, wrapped }) { + + const refs = []; + const reference = (variable) => { + + const ref = Ref.create(variable, this._settings); + refs.push(ref); + return (context) => ref.resolve(...context); + }; + + 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 (formula.single) { + if (formula.single.type === 'reference') { + const ref = refs[0]; + return { ref, raw, refs, wrapped: wrapped || ref.type === 'local' && ref.key === 'label' }; } + + return internals.stringify(formula.single.value); } - return command.promise; + + return { formula, raw, refs }; } - handleError(error, ttl, handlers) { - if (typeof ttl.value === "undefined") { - ttl.value = this.options.maxRedirections; + + toString() { + + return this.source; + } +}; + + +internals.Template.prototype[Common.symbols.template] = true; +internals.Template.prototype.isImmutable = true; // Prevents Hoek from deep cloning schema objects + + +internals.encode = function (string) { + + return string + .replace(/\\(\{+)/g, ($0, $1) => { + + return internals.opens.slice(0, $1.length); + }) + .replace(/\\(\}+)/g, ($0, $1) => { + + return internals.closes.slice(0, $1.length); + }); +}; + + +internals.decode = function (string) { + + return string + .replace(/\u0000/g, '{') + .replace(/\u0001/g, '}'); +}; + + +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 { - ttl.value -= 1; + current += char; } - if (ttl.value <= 0) { - handlers.maxRedirections(new Error("Too many Cluster redirections. Last error: " + error)); - return; + } + + parts.push(current); + return parts; +}; + + +internals.wrap = function (value, ends) { + + if (!ends) { + return value; + } + + if (ends.length === 1) { + return `${ends}${value}${ends}`; + } + + return `${ends[0]}${value}${ends[1]}`; +}; + + +internals.stringify = function (value, original, state, prefs, local, options = {}) { + + const type = typeof value; + const wrap = prefs && prefs.errors && prefs.errors.wrap || {}; + + let skipWrap = false; + if (Ref.isRef(value) && + value.render) { + + skipWrap = value.in; + value = value.resolve(original, state, prefs, local, { in: value.in, ...options }); + } + + if (value === null) { + return 'null'; + } + + if (type === 'string') { + return internals.wrap(value, options.arrayItems && wrap.string); + } + + if (type === 'number' || + type === 'function' || + type === 'symbol') { + + return value.toString(); + } + + 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()}`); } - 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]); - } + + value = pairs; + } + + 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 })); + } + + return internals.wrap(values.join(', '), !skipWrap && wrap.array); +}; + + +internals.constants = { + + true: true, + false: false, + null: null, + + second: 1000, + minute: 60 * 1000, + hour: 60 * 60 * 1000, + day: 24 * 60 * 60 * 1000 +}; + + +internals.functions = { + + if(condition, then, otherwise) { + + return condition ? then : otherwise; + }, + + msg(code) { + + const [value, state, prefs, local, options] = this; + const messages = options.messages; + if (!messages) { + return ''; } - else if (errv[0] === "ASK") { - handlers.ask(errv[1], errv[2]); + + const template = Errors.template(value, messages[0], code, state, prefs) || Errors.template(value, messages[1], code, state, prefs); + if (!template) { + return ''; } - else if (errv[0] === "TRYAGAIN") { - this.delayQueue.push("tryagain", handlers.tryagain, { - timeout: this.options.retryDelayOnTryAgain, - }); + + return template.render(value, state, prefs, local, options); + }, + + number(value) { + + if (typeof value === 'number') { + return value; } - else if (errv[0] === "CLUSTERDOWN" && - this.options.retryDelayOnClusterDown > 0) { - this.delayQueue.push("clusterdown", handlers.connectionClosed, { - timeout: this.options.retryDelayOnClusterDown, - callback: this.refreshSlotsCache.bind(this), - }); + + if (typeof value === 'string') { + return parseFloat(value); } - 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), - }); + + if (typeof value === 'boolean') { + return value ? 1 : 0; } - else { - handlers.defaults(); + + if (value instanceof Date) { + return value.getTime(); } + + return null; } - getInfoFromNode(redis, callback) { - if (!redis) { - return callback(new Error("Node is disconnected")); +}; + + +/***/ }), + +/***/ 43171: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +const DeepEqual = __nccwpck_require__(55801); +const Pinpoint = __nccwpck_require__(75604); + +const Errors = __nccwpck_require__(69490); + + +const internals = { + codes: { + error: 1, + pass: 2, + full: 3 + }, + labels: { + 0: 'never used', + 1: 'always error', + 2: 'always pass' + } +}; + + +exports.setup = function (root) { + + const trace = function () { + + root._tracer = root._tracer || new internals.Tracer(); + return root._tracer; + }; + + root.trace = trace; + root[Symbol.for('@hapi/lab/coverage/initialize')] = trace; + + root.untrace = () => { + + root._tracer = null; + }; +}; + + +exports.location = function (schema) { + + return schema.$_setFlag('_tracerLocation', Pinpoint.location(2)); // base.tracer(), caller +}; + + +internals.Tracer = class { + + constructor() { + + this.name = 'Joi'; + this._schemas = new Map(); + } + + _register(schema) { + + const existing = this._schemas.get(schema); + if (existing) { + return existing.store; } - // 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)); + + 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; } - invokeReadyDelayedCallbacks(err) { - for (const c of this._readyDelayedCallbacks) { - process.nextTick(c, err); + + _combine(merged, sources) { + + for (const { store } of this._schemas.values()) { + store._combine(merged, sources); } - 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(); + + report(file) { + + const coverage = []; + + // Process each registered schema + + for (const { filename, line, store } of this._schemas.values()) { + if (file && + file !== filename) { + + continue; } - 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; + + // Process sub schemas of the registered root + + const missing = []; + const skipped = []; + + for (const [schema, log] of store._sources.entries()) { + + // Check if sub schema parent skipped + + if (internals.sub(log.paths, skipped)) { + continue; } - } - 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); + + // Check if sub schema reached + + if (!log.entry) { + missing.push({ + status: 'never reached', + paths: [...log.paths] + }); + + skipped.push(...log.paths); + continue; } - 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); + + // Check values + + for (const type of ['valid', 'invalid']) { + const set = schema[`_${type}s`]; + if (!set) { + continue; } - const key = sortedKeys[0], group = groupedRecords[key], record = util_1.weightSrvRecords(group); - if (!group.records.length) { - sortedKeys.shift(); + + 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 (values.size || + refs.size) { + + missing.push({ + status: [...values, ...[...refs].map((ref) => ref.display)], + rule: `${type}s` + }); } - 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); + + // 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); + } } - else { - debug("resolved hostname %s to IP %s", hostname, address); - resolve(address); + + 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); + } } - }); - }); - } - /** - * 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); + } + + if (missing.length) { + coverage.push({ + filename, + line, + missing, + severity: 'error', + message: `Schema missing tests for ${missing.map(internals.message).join(', ')}` + }); + } } - 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 }); - } - }); - }); + + return coverage.length ? coverage : null; } -} -Object.getOwnPropertyNames(commander_1.default.prototype).forEach((name) => { - if (!Cluster.prototype.hasOwnProperty(name)) { - Cluster.prototype[name] = commander_1.default.prototype[name]; +}; + + +internals.Store = class { + + constructor(schema) { + + this.active = true; + this._sources = new Map(); // schema -> { paths, entry, rule, valid, invalid } + this._combos = new Map(); // merged -> [sources] + this._scan(schema); } -}); -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; + debug(state, source, name, result) { -/***/ }), + state.mainstay.debug && state.mainstay.debug.push({ type: source, name, result, path: state.path }); + } -/***/ 94582: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + entry(schema, state) { -"use strict"; + internals.debug(state, { type: 'entry' }); -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}`); + this._record(schema, (log) => { + + log.entry = true; + }); } - return { - host: nodeKey.slice(0, portIndex), - port: Number(nodeKey.slice(portIndex + 1)), - }; -} -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; + + filter(schema, state, source, value) { + + internals.debug(state, { type: source, ...value }); + + this._record(schema, (log) => { + + log[source].add(value); + }); + } + + log(schema, state, source, name, result) { + + internals.debug(state, { type: source, name, result: result === 'full' ? 'pass' : result }); + + this._record(schema, (log) => { + + log[source][name] = log[source][name] || 0; + log[source][name] |= internals.codes[result]; + }); + } + + resolve(state, ref, to) { + + if (!state.mainstay.debug) { + return; } - else { - throw new Error("Invalid argument " + node); + + const log = { type: 'resolve', ref: ref.display, to, path: state.path }; + state.mainstay.debug.push(log); + } + + value(state, by, from, to, name) { + + if (!state.mainstay.debug || + DeepEqual(from, to)) { + + return; } - if (typeof options.port === "string") { - options.port = parseInt(options.port, 10); + + const log = { type: 'value', by, from, to, path: state.path }; + if (name) { + log.name = name; } - // Cluster mode only support db 0 - delete options.db; - if (!options.port) { - options.port = 6379; + + state.mainstay.debug.push(log); + } + + _record(schema, each) { + + const log = this._sources.get(schema); + if (log) { + each(log); + return; } - if (!options.host) { - options.host = "127.0.0.1"; + + const sources = this._combos.get(schema); + for (const source of sources) { + this._record(source, each); } - 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], + } + + _scan(schema, _path) { + + const path = _path || []; + + 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); } - else { - recordsByPriority[record.priority].totalWeight += record.weight; - recordsByPriority[record.priority].records.push(record); + + if (path.length) { + log.paths.add(path); } + + const each = (sub, source) => { + + const subId = internals.id(sub, source); + this._scan(sub, path.concat(subId)); + }; + + schema.$_modify({ each, ref: false }); } - 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; - } + + _combine(merged, sources) { + + this._combos.set(merged, sources); } -} -exports.weightSrvRecords = weightSrvRecords; -function getConnectionName(component, nodeConnectionName) { - const prefix = `ioredis-cluster(${component})`; - return nodeConnectionName ? `${prefix}:${nodeConnectionName}` : prefix; -} -exports.getConnectionName = getConnectionName; +}; -/***/ }), +internals.message = function (item) { -/***/ 90803: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + const path = item.paths ? Errors.path(item.paths[0]) + (item.rule ? ':' : '') : ''; + return `${path}${item.rule || ''} (${item.status})`; +}; -"use strict"; -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; - } +internals.id = function (schema, { source, name, path, key }) { + + if (schema._flags.id) { + return schema._flags.id; } - 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; + + if (key) { + return key; } - /** - * Check whether the command has the flag - * - * @param {string} flagName - * @param {string} commandName - * @return {boolean} - */ - static checkFlag(flagName, commandName) { - return !!this.getFlagMap()[flagName][commandName]; + + name = `@${name}`; + + if (source === 'terms') { + return [name, path[Math.min(path.length - 1, 1)]]; } - static setArgumentTransformer(name, func) { - this._transformer.argument[name] = func; + + return name; +}; + + +internals.sub = function (paths, skipped) { + + for (const path of paths) { + for (const skip of skipped) { + if (DeepEqual(path.slice(0, skip.length), skip)) { + return true; + } + } } - static setReplyTransformer(name, func) { - this._transformer.reply[name] = func; + + return false; +}; + + +internals.debug = function (state, event) { + + if (state.mainstay.debug) { + event.path = state.debug ? [...state.path, state.debug] : state.path; + state.mainstay.debug.push(event); } - 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); +}; + + +/***/ }), + +/***/ 26867: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const Assert = __nccwpck_require__(32718); +const Merge = __nccwpck_require__(60445); + +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 = Any.extend({ + + type: 'alternatives', + + flags: { + + match: { default: 'any' } // 'any', 'one', 'all' + }, + + terms: { + + matches: { init: [], register: Ref.toSibling } + }, + + args(schema, ...schemas) { + + if (schemas.length === 1) { + if (Array.isArray(schemas[0])) { + return schema.try(...schemas[0]); + } + } + + return schema.try(...schemas); + }, + + validate(value, helpers) { + + const { schema, error, state, prefs } = helpers; + + // Match all or one + + if (schema._flags.match) { + const matched = []; + const failed = []; + + 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 result = item.schema.$_validate(value, localState, prefs); + if (!result.errors) { + matched.push(result.value); + } + else { + failed.push(result.errors); + localState.restore(); } - this.stringifyArguments(); } - this.resolve = this._convertValue(resolve); - if (this.errorStack) { - this.reject = (err) => { - reject(utils_1.optimizeErrorStack(err, this.errorStack.stack, __dirname)); + + if (matched.length === 0) { + const context = { + details: failed.map((f) => Errors.details(f, { override: false })) }; + + return { errors: error('alternatives.any', context) }; } - else { - this.reject = reject; + + // Match one + + if (schema._flags.match === 'one') { + return matched.length === 1 ? { value: matched[0] } : { errors: error('alternatives.one') }; } - }); - 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; - } - getKeys() { - return this._iterateKeys(); - } - /** - * 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]); - } + + // Match all + + if (matched.length !== schema.$_terms.matches.length) { + const context = { + details: failed.map((f) => Errors.details(f, { override: false })) + }; + + return { errors: error('alternatives.all', context) }; } + + const isAnyObj = (alternative) => { + + return alternative.$_terms.matches.some((v) => { + + return v.schema.type === 'object' || + (v.schema.type === 'alternatives' && isAnyObj(v.schema)); + }); + }; + + return isAnyObj(schema) ? { value: matched.reduce((acc, v) => Merge(acc, v, { mergeArrays: false })) } : { value: matched[matched.length - 1] }; } - 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; + + // Match any + + const errors = []; + for (let i = 0; i < schema.$_terms.matches.length; ++i) { + const item = schema.$_terms.matches[i]; + + // Try + + 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; + } + + localState.restore(); + errors.push({ schema: item.schema, reports: result.errors }); + continue; } - } - 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"); + + // Conditional + + const input = item.ref ? item.ref.resolve(value, state, prefs) : value; + const tests = item.is ? [item] : item.switch; + + for (let j = 0; j < tests.length; ++j) { + const test = tests[j]; + const { is, then, otherwise } = test; + + 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 { - buffers.push("$" + - Buffer.byteLength(arg) + - "\r\n" + - arg + - "\r\n"); + else if (then) { + return then.$_validate(value, state.nest(then, `${id}.then`), prefs); } } - result = buffers.toBuffer(); - } - else { - result = commandStr; - for (const arg of this.args) { - result += - "$" + - Buffer.byteLength(arg) + - "\r\n" + - arg + - "\r\n"; - } } - 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); + + return internals.errors(errors, helpers); + }, + + rules: { + + 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(); + + const match = Compile.when(obj, condition, options); + const conditions = match.is ? [match] : match.switch; + for (const item of conditions) { + if (item.then && + item.otherwise) { + + obj.$_setFlag('_endedSwitch', true, { clone: false }); + break; + } + } + + obj.$_terms.matches.push(match); + return obj.$_mutateRebuild(); } - } - } - /** - * 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; + }, + + match: { + method(mode) { + + Assert(['any', 'one', 'all'].includes(mode), 'Invalid alternatives match mode', mode); + + if (mode !== 'any') { + for (const match of this.$_terms.matches) { + Assert(match.schema, 'Cannot combine match mode', mode, 'with conditional rules'); + } } - resolve(this.transformReply(value)); - this.isResolved = true; + + return this.$_setFlag('match', mode); } - catch (err) { - this.reject(err); + }, + + try: { + method(...schemas) { + + Assert(schemas.length, 'Missing alternative schemas'); + Common.verifyFlat(schemas, 'try'); + + Assert(!this._flags._endedSwitch, 'Unreachable condition'); + + const obj = this.clone(); + for (const schema of schemas) { + obj.$_terms.matches.push({ schema: obj.$_compile(schema) }); + } + + return obj.$_mutateRebuild(); } - 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); + }, + + overrides: { + + label(name) { + + const obj = this.$_parent('label', name); + const each = (item, source) => (source.path[0] !== 'is' ? item.label(name) : undefined); + return obj.$_modify({ each, ref: false }); } - 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")); + }, + + rebuild(schema) { + + // Flag when an alternative type is an array + + const each = (item) => { + + if (Common.isSchema(item) && + item.type === 'array') { + + schema.$_setFlag('_arrayItems', true, { clone: false }); + } + }; + + schema.$_modify({ each }); + }, + + manifest: { + + build(obj, desc) { + + 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 }); + } } - }, ms); + } + + return obj; } + }, + + 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}}' } -} -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]); - } +}); + + +// Helpers + +internals.errors = function (failures, { error, state }) { + + // Nothing matched due to type criteria rules + + if (!failures.length) { + return { errors: error('alternatives.any') }; } - 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])); + + // Single error + + if (failures.length === 1) { + return { errors: failures[0].reports }; + } + + // Analyze reasons + + const valids = new Set(); + const complex = []; + + for (const { reports, schema } of failures) { + + // Multiple errors (!abortEarly) + + if (reports.length > 1) { + return internals.unmatched(failures, error); } - if (typeof args[1] === "object" && args[1] !== null) { - return [args[0]].concat(utils_1.convertObjectToArray(args[1])); + + // Custom error + + const report = reports[0]; + if (report instanceof Errors.Report === false) { + return internals.unmatched(failures, error); } - } - 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; + + // Internal object or array error + + if (report.state.path.length !== state.path.length) { + complex.push({ type: schema.type, report }); + continue; + } + + // Valids + + if (report.code === 'any.only') { + for (const valid of report.local.valids) { + valids.add(valid); } + + continue; } - return obj; + + // Base type + + const [type, code] = report.code.split('.'); + if (code !== 'base') { + complex.push({ type: schema.type, report }); + continue; + } + + valids.add(type); } - return result; -}); -class MixedBuffers { - constructor() { - this.length = 0; - this.items = []; + + // All errors are base types or valids + + if (!complex.length) { + return { errors: error('alternatives.types', { types: [...valids] }) }; } - push(x) { - this.length += Buffer.byteLength(x); - this.items.push(x); + + // Single complex error + + if (complex.length === 1) { + return { errors: complex[0].report }; } - 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; + + return internals.unmatched(failures, error); +}; + + +internals.unmatched = function (failures, error) { + + const errors = []; + for (const failure of failures) { + errors.push(...failure.reports); } -} + + return { errors: error('alternatives.match', Errors.details(errors, { override: false })) }; +}; /***/ }), -/***/ 33642: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 9512: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "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(); -} -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; - } - 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); + +const Assert = __nccwpck_require__(32718); + +const Base = __nccwpck_require__(95184); +const Common = __nccwpck_require__(72448); +const Messages = __nccwpck_require__(86103); + + +const internals = {}; + + +module.exports = Base.extend({ + + type: 'any', + + flags: { + + only: { default: false } + }, + + terms: { + + alterations: { init: null }, + examples: { init: null }, + externals: { init: null }, + metas: { init: [] }, + notes: { init: [] }, + shared: { init: null }, + tags: { init: [] }, + whens: { init: null } + }, + + rules: { + + 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'); + + 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 + }, + + messages: { + method(messages) { + + return this.prefs({ messages }); } - options = { replyEncoding: null }; - } - else { - options = { replyEncoding: encoding }; + }, + + shared: { + method(schema) { + + 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; + } + }, + + warning: { + method(code, local) { + + Assert(code && typeof code === 'string', 'Invalid warning code'); + + return this.$_addRule({ name: 'warning', args: { code, local }, warn: true }); + }, + validate(value, helpers, { code, local }) { + + return helpers.error(code, local); + }, + args: ['code', 'local'], + multi: true } - if (this.options.showFriendlyErrorStack) { - options.errorStack = new Error(); + }, + + modifiers: { + + keep(rule, enabled = true) { + + rule.keep = enabled; + }, + + message(rule, message) { + + rule.message = Messages.compile(message); + }, + + warn(rule, enabled = true) { + + rule.warn = enabled; } - // No auto pipeline, use regular command sending - if (!autoPipelining_1.shouldUseAutoPipelining(this, functionName, commandName)) { - return script.execute(this, args, options, callback); + }, + + manifest: { + + build(obj, desc) { + + for (const key in desc) { + const values = desc[key]; + + if (['examples', 'externals', 'metas', 'notes', 'tags'].includes(key)) { + for (const value of values) { + obj = obj[key.slice(0, -1)](value); + } + + continue; + } + + if (key === 'alterations') { + const alter = {}; + for (const { target, adjuster } of values) { + alter[target] = adjuster; + } + + 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 }); + } + } + + continue; + } + + if (key === 'shared') { + for (const value of values) { + obj = obj.shared(value); + } + } + } + + return obj; } - // Create a new pipeline and make sure it's scheduled - return autoPipelining_1.executeWithAutoPipelining(this, functionName, commandName, args, callback); - }; -} + }, + + 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' + } +}); /***/ }), -/***/ 72712: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 20270: +/***/ ((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; - } - 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; +const Assert = __nccwpck_require__(32718); +const DeepEqual = __nccwpck_require__(55801); +const Reach = __nccwpck_require__(18891); -/***/ }), +const Any = __nccwpck_require__(9512); +const Common = __nccwpck_require__(72448); +const Compile = __nccwpck_require__(3038); -/***/ 22913: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { -"use strict"; +const internals = {}; -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); - }); - } - 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.FailoverDetector = FailoverDetector; +module.exports = Any.extend({ -/***/ }), + type: 'array', -/***/ 72225: -/***/ ((__unused_webpack_module, exports) => { + flags: { -"use strict"; + single: { default: false }, + sparse: { default: false } + }, -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)); -} -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; + terms: { + items: { init: [], manifest: 'schema' }, + ordered: { init: [], manifest: 'schema' }, -/***/ }), + _exclusions: { init: [] }, + _inclusions: { init: [] }, + _requireds: { init: [] } + }, -/***/ 10379: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + coerce: { + from: 'object', + method(value, { schema, state, prefs }) { -"use strict"; + if (!Array.isArray(value)) { + return; + } -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."); + const sort = schema.$_getRule('sort'); + if (!sort) { + return; + } + + return internals.sort(schema, value, sort.args.options, state, prefs); } - 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); + }, + + validate(value, { schema, error }) { + + if (!Array.isArray(value)) { + if (schema._flags.single) { + const single = [value]; + single[Common.symbols.arraySingle] = true; + return { value: single }; + } + + return { errors: error('array.base') }; } - return roleMatches; - } - disconnect() { - super.disconnect(); - if (this.failoverDetector) { - this.failoverDetector.cleanup(); + + if (!schema.$_getRule('items') && + !schema.$_terms.externals) { + + return; } - } - 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}`; + + return { value: value.slice() }; // Clone the array so that we don't modify the original + }, + + rules: { + + 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 }) { + + 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; + } } - debug(errorMsg); - const error = new Error(errorMsg); - if (typeof retryDelay === "number") { - eventEmitter("error", error); - yield new Promise((resolve) => setTimeout(resolve, retryDelay)); - return connectToNext(); + + const patternLabel = has._flags.label; + if (patternLabel) { + return error('array.hasKnown', { patternLabel }); } - else { - throw error; + + return error('array.hasUnknown', null); + }, + multi: true + }, + + items: { + method(...schemas) { + + Common.verifyFlat(schemas, 'items'); + + const obj = this.$_addRule('items'); + + 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 }) { + + 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]; + + const errors = errorsArray(); + + let il = value.length; + for (let i = 0; i < il; ++i) { + const item = value[i]; + + let errored = false; + let isValid = false; + + const key = wasArray ? i : new Number(i); // eslint-disable-line no-new-wrappers + const path = [...state.path, key]; + + // Sparse + + if (!schema._flags.sparse && + item === undefined) { + + errors.push(error('array.sparse', { key, path, pos: i, value: undefined }, state.localize(path))); + if (prefs.abortEarly) { + return errors; + } + + ordereds.shift(); + continue; + } + + // Exclusions + + const ancestors = [value, ...state.ancestors]; + + for (const exclusion of schema.$_terms._exclusions) { + if (!exclusion.$_match(item, state.localize(path, ancestors, exclusion), prefs, { presence: 'ignore' })) { + continue; + } + + errors.push(error('array.excludes', { pos: i, value: item }, state.localize(path))); + if (prefs.abortEarly) { + return errors; + } + + errored = true; + ordereds.shift(); + break; + } + + if (errored) { + continue; + } + + // Ordered + + 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; + } + } + + 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 + } + } + + // Requireds + + const requiredChecks = []; + let jl = requireds.length; + for (let j = 0; j < jl; ++j) { + const localState = state.localize(path, ancestors, requireds[j]); + localState.snapshot(); + + const res = requireds[j].$_validate(item, localState, prefs); + requiredChecks[j] = res; + + if (!res.errors) { + value[i] = res.value; + isValid = true; + internals.fastSplice(requireds, j); + --j; + --jl; + + 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; + } + + localState.restore(); + } + + if (isValid) { + continue; + } + + // Inclusions + + const stripUnknown = prefs.stripUnknown && !!prefs.stripUnknown.arrays || false; + + jl = inclusions.length; + for (const inclusion of inclusions) { + + // Avoid re-running requireds that already didn't match in the previous loop + + 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) { + + errors.push(error('array.sparse', { key, path, pos: i, value: undefined }, state.localize(path))); + errored = true; + } + else { + value[i] = res.value; + } + + isValid = true; + break; + } + + localState.restore(); + } + + // Return the actual error if only one inclusion defined + + if (jl === 1) { + if (stripUnknown) { + internals.fastSplice(value, i); + --i; + --il; + isValid = true; + break; + } + + errors.push(...res.errors); + if (prefs.abortEarly) { + return errors; + } + + errored = true; + break; + } + } + + if (errored) { + continue; + } + + if ((schema.$_terms._inclusions.length || schema.$_terms._requireds.length) && + !isValid) { + + if (stripUnknown) { + internals.fastSplice(value, i); + --i; + --il; + continue; + } + + errors.push(error('array.includes', { pos: i, value: item }, state.localize(path))); + if (prefs.abortEarly) { + return errors; + } + } + } + + if (requireds.length) { + internals.fillMissedErrors(schema, errors, requireds, value, state, prefs); + } + + if (ordereds.length) { + internals.fillOrderedErrors(schema, errors, ordereds, value, state, prefs); + + if (!errors.length) { + internals.fillDefault(ordereds, value, state, prefs); + } + } + + return errors.length ? errors : value; + }, + + priority: true, + manifest: false + }, + + length: { + method(limit) { + + return this.$_addRule({ name: 'length', args: { limit }, operator: '=' }); + }, + validate(value, helpers, { limit }, { name, operator, args }) { + + if (Common.compare(value.length, limit, operator)) { + return value; } + + 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) { + + return this.$_addRule({ name: 'max', method: 'length', args: { limit }, operator: '<=' }); } - let resolved = null; - let err = null; - try { - resolved = yield this.resolve(endpoint.value); + }, + + min: { + method(limit) { + + return this.$_addRule({ name: 'min', method: 'length', args: { limit }, operator: '>=' }); } - catch (error) { - err = error; + }, + + ordered: { + method(...schemas) { + + Common.verifyFlat(schemas, 'ordered'); + + const obj = this.$_addRule('items'); + + for (let i = 0; i < schemas.length; ++i) { + const type = Common.tryWithPath(() => this.$_compile(schemas[i]), i, { append: true }); + internals.validateSingle(type, obj); + + obj.$_mutateRegister(type); + obj.$_terms.ordered.push(type); + } + + return obj.$_mutateRebuild(); } - if (!this.connecting) { - throw new Error(utils_1.CONNECTION_CLOSED_ERROR_MSG); + }, + + single: { + method(enabled) { + + const value = enabled === undefined ? true : !!enabled; + Assert(!value || !this._flags._arrayItems, 'Cannot specify single rule when array has array items'); + + return this.$_setFlag('single', value); } - 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); + }, + + sort: { + method(options = {}) { + + Common.assertOptions(options, ['by', 'order']); + + 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'); } - else { - this.stream = net_1.createConnection(resolved); + + 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; } - this.stream.once("connect", () => this.initFailoverDetector()); - this.stream.once("error", (err) => { - this.firstError = err; - }); - return this.stream; + + 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' }); + } + } + + return value; + }, + convert: true + }, + + sparse: { + method(enabled) { + + 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 }); } - 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; + }, + + unique: { + method(comparator, options = {}) { + + 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 } }; + + if (comparator) { + if (typeof comparator === 'string') { + const separator = Common.default(options.separator, '.'); + rule.path = separator ? comparator.split(separator) : [comparator]; + } + else { + rule.comparator = comparator; + } } - return connectToNext(); + + 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 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]] + }; + + if (path) { + context.path = raw; + } + + return error('array.unique', context, localState); + } + } + + records.set(item, i); + } + else { + if ((!ignoreUndefined || item !== undefined) && + records[item] !== undefined) { + + const context = { + pos: i, + value: value[i], + dupePos: records[item], + dupeValue: value[records[item]] + }; + + if (path) { + context.path = raw; + } + + const localState = state.localize([...state.path, i], [value, ...state.ancestors]); + return error('array.unique', context, localState); + } + + records[item] = i; + } + } + + return value; + }, + args: ['comparator', 'options'], + multi: true + } + }, + + cast: { + set: { + from: Array.isArray, + to(value, helpers) { + + return new Set(value); + } + } + }, + + rebuild(schema) { + + schema.$_terms._inclusions = []; + schema.$_terms._exclusions = []; + schema.$_terms._requireds = []; + + for (const type of schema.$_terms.items) { + internals.validateSingle(type, schema); + + if (type._flags.presence === 'required') { + schema.$_terms._requireds.push(type); } - }); - return connectToNext(); - } - updateSentinels(client) { - return __awaiter(this, void 0, void 0, function* () { - if (!this.options.updateSentinels) { - return; + else if (type._flags.presence === 'forbidden') { + schema.$_terms._exclusions.push(type); } - const result = yield client.sentinel("sentinels", this.options.name); - if (!Array.isArray(result)) { - return; + else { + schema.$_terms._inclusions.push(type); } - 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); - }); + } + + for (const type of schema.$_terms.ordered) { + internals.validateSingle(type, schema); + } + }, + + manifest: { + + build(obj, desc) { + + if (desc.items) { + obj = obj.items(...desc.items); + } + + if (desc.ordered) { + obj = obj.ordered(...desc.ordered); + } + + 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' } - 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); - }); +}); + + +// Helpers + +internals.fillMissedErrors = function (schema, errors, requireds, value, state, prefs) { + + const knownMisses = []; + let unknownMisses = 0; + for (const required of requireds) { + const label = required._flags.label; + if (label) { + knownMisses.push(label); + } + else { + ++unknownMisses; + } } - 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)); - }); + + 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)); + } } - sentinelNatResolve(item) { - if (!item || !this.options.natMap) - return item; - return this.options.natMap[`${item.host}:${item.port}`] || item; + else { + errors.push(schema.$_createError('array.includesRequiredUnknowns', value, { unknownMisses }, state, prefs)); } - 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)); +}; + + +internals.fillOrderedErrors = function (schema, errors, ordereds, value, state, prefs) { + + const requiredOrdereds = []; + + for (const ordered of ordereds) { + if (ordered._flags.presence === 'required') { + requiredOrdereds.push(ordered); + } } - 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(); - } - }); + + if (requiredOrdereds.length) { + internals.fillMissedErrors(schema, errors, requiredOrdereds, value, state, prefs); } - 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(); +}; + + +internals.fillDefault = function (ordereds, value, state, prefs) { + + const overrides = []; + let trailingUndefined = true; + + 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 (trailingUndefined) { + if (override === undefined) { + continue; } - 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"); - }); + + trailingUndefined = false; + } + + overrides.unshift(override); } -} -exports["default"] = SentinelConnector; -function selectPreferredSentinel(availableSlaves, preferredSlaves) { - if (availableSlaves.length === 0) { - return null; + + if (overrides.length) { + value.push(...overrides); } - let selectedSlave; - if (typeof preferredSlaves === "function") { - selectedSlave = preferredSlaves(availableSlaves); +}; + + +internals.fastSplice = function (arr, i) { + + let pos = i; + while (pos < arr.length) { + arr[pos++] = arr[pos]; } - 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; - } + + --arr.length; +}; + + +internals.validateSingle = function (type, obj) { + + if (type.type === 'array' || + type._flags._arrayItems) { + + Assert(!obj._flags.single, 'Cannot specify array item with single rule enabled'); + obj.$_setFlag('_arrayItems', true, { clone: false }); + } +}; + + +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) => { + + 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); + } + + compare = internals.compare(a, b, aFirst, bFirst); + if (compare !== null) { + return compare; + } + + const type = typeof a; + if (type !== typeof b) { + throw schema.$_createError('array.sort.mismatching', value, null, state, prefs); + } + + if (type !== 'number' && + type !== 'string') { + + throw schema.$_createError('array.sort.unsupported', value, { type }, state, prefs); + } + + if (type === 'number') { + return (a - b) * order; } + + return a < b ? aFirst : bFirst; + }; + + try { + return { value: value.slice().sort(sort) }; } - // if none of the preferred slaves are available, a random available slave is returned - if (!selectedSlave) { - selectedSlave = utils_1.sample(availableSlaves); + catch (err) { + return { errors: err }; + } +}; + + +internals.compare = function (a, b, aFirst, bFirst) { + + if (a === b) { + return 0; } - return addressResponseToAddress(selectedSlave); -} -function addressResponseToAddress(input) { - return { host: input.ip, port: Number(input.port) }; -} -function noop() { } + + if (a === undefined) { + return 1; // Always last regardless of sort order + } + + if (b === undefined) { + return -1; // Always last regardless of sort order + } + + if (a === null) { + return bFirst; + } + + if (b === null) { + return aFirst; + } + + return null; +}; /***/ }), -/***/ 8774: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 34288: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -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, - }; + +const Assert = __nccwpck_require__(32718); + +const Any = __nccwpck_require__(9512); +const Common = __nccwpck_require__(72448); + + +const internals = {}; + + +module.exports = Any.extend({ + + type: 'binary', + + coerce: { + from: 'string', + method(value, { schema }) { + + try { + return { value: Buffer.from(value, schema._flags.encoding) }; + } + catch (ignoreErr) { } } - else { - connectionOptions = {}; - if (options.port != null) { - connectionOptions.port = options.port; + }, + + validate(value, { error }) { + + if (!Buffer.isBuffer(value)) { + return { value, errors: error('binary.base') }; + } + }, + + rules: { + encoding: { + method(encoding) { + + Assert(Buffer.isEncoding(encoding), 'Invalid encoding:', encoding); + + return this.$_setFlag('encoding', encoding); } - if (options.host != null) { - connectionOptions.host = options.host; + }, + + length: { + method(limit) { + + 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; + } + + return helpers.error('binary.' + name, { limit: args.limit, value }); + }, + args: [ + { + name: 'limit', + ref: true, + assert: Common.limit, + message: 'must be a positive integer' + } + ] + }, + + max: { + method(limit) { + + return this.$_addRule({ name: 'max', method: 'length', args: { limit }, operator: '<=' }); } - if (options.family != null) { - connectionOptions.family = options.family; + }, + + min: { + method(limit) { + + return this.$_addRule({ name: 'min', method: 'length', args: { limit }, operator: '>=' }); } } - if (options.tls) { - Object.assign(connectionOptions, options.tls); + }, + + cast: { + string: { + from: (value) => Buffer.isBuffer(value), + to(value, helpers) { + + return value.toString(); + } } - // 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); - }); - }); + }, + + 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' } -} -exports["default"] = StandaloneConnector; +}); /***/ }), -/***/ 72340: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 47489: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -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; +const Assert = __nccwpck_require__(32718); -/***/ }), +const Any = __nccwpck_require__(9512); +const Common = __nccwpck_require__(72448); +const Values = __nccwpck_require__(71944); -/***/ 61823: -/***/ ((__unused_webpack_module, exports) => { -"use strict"; +const internals = {}; -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", + +internals.isBool = function (value) { + + return typeof value === 'boolean'; +}; + + +module.exports = Any.extend({ + + type: 'boolean', + + flags: { + + sensitive: { default: false } }, - /** - * 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", + + terms: { + + falsy: { + init: null, + manifest: 'values' + }, + + truthy: { + init: null, + manifest: 'values' + } }, -}; + coerce(value, { schema }) { -/***/ }), + if (typeof value === 'boolean') { + return; + } -/***/ 97282: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + if (typeof value === 'string') { + const normalized = schema._flags.sensitive ? value : value.toLowerCase(); + value = normalized === 'true' ? true : (normalized === 'false' ? false : value); + } -"use strict"; + 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); + } -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; + return { value }; + }, + validate(value, { error }) { -/***/ }), + if (typeof value !== 'boolean') { + return { value, errors: error('boolean.base') }; + } + }, -/***/ 90735: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + rules: { + truthy: { + method(...values) { -"use strict"; + Common.verifyFlat(values, 'truthy'); -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; + 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); + } -/***/ 23961: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + return obj; + } + }, -"use strict"; + falsy: { + method(...values) { -Object.defineProperty(exports, "__esModule", ({ value: true })); -const MaxRetriesPerRequestError_1 = __nccwpck_require__(90735); -exports.MaxRetriesPerRequestError = MaxRetriesPerRequestError_1.default; + Common.verifyFlat(values, 'falsy'); + const obj = this.clone(); + obj.$_terms.falsy = obj.$_terms.falsy || new Values(); -/***/ }), + for (let i = 0; i < values.length; ++i) { + const value = values[i]; -/***/ 45069: -/***/ ((module, exports, __nccwpck_require__) => { + Assert(value !== undefined, 'Cannot call falsy with undefined'); + obj.$_terms.falsy.add(value); + } -"use strict"; + return obj; + } + }, -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(); + sensitive: { + method(enabled = true) { + + return this.$_setFlag('sensitive', enabled); + } + } }, - set(lib) { - PromiseContainer.set(lib); + + cast: { + number: { + from: internals.isBool, + to(value, helpers) { + + return value ? 1 : 0; + } + }, + string: { + from: internals.isBool, + to(value, helpers) { + + return value ? 'true' : 'false'; + } + } }, -})); -function print(err, reply) { - if (err) { - console.log("Error: " + err); - } - else { - console.log("Reply: " + reply); + + manifest: { + + build(obj, desc) { + + if (desc.truthy) { + obj = obj.truthy(...desc.truthy); + } + + if (desc.falsy) { + obj = obj.falsy(...desc.falsy); + } + + return obj; + } + }, + + messages: { + 'boolean.base': '{{#label}} must be a boolean' } -} -exports.print = print; +}); /***/ }), -/***/ 42803: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 6624: +/***/ ((module, __unused_webpack_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; + +const Assert = __nccwpck_require__(32718); + +const Any = __nccwpck_require__(9512); +const Common = __nccwpck_require__(72448); +const Template = __nccwpck_require__(51396); + + +const internals = {}; + + +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 }; } - } - 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; - } + }, + + validate(value, { schema, error, prefs }) { + + if (value instanceof Date && + !isNaN(value.getTime())) { + + return; } - } - 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; + + 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; } - } - else if (!command.inTransaction) { - const isReadOnly = redis_commands_1.exists(command.name) && redis_commands_1.hasFlag(command.name, "readonly"); - if (!isReadOnly) { - retriable = false; - break; + + 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); } - } - 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; + }, + + greater: { + method(date) { + + return this.$_addRule({ name: 'greater', method: 'compare', args: { date }, operator: '>' }); } - let matched = true; - if (typeof this.leftRedirections === "undefined") { - this.leftRedirections = {}; + }, + + iso: { + method() { + + return this.format('iso'); } - 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; + }, + + less: { + method(date) { + + return this.$_addRule({ name: 'less', method: 'compare', args: { date }, operator: '<' }); } - } - } - 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; + }, + + max: { + method(date) { + + return this.$_addRule({ name: 'max', method: 'compare', args: { date }, operator: '<=' }); } - 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]); + }, + + min: { + method(date) { + + return this.$_addRule({ name: 'min', method: 'compare', args: { date }, operator: '>=' }); } - // 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; + }, + + timestamp: { + method(type = 'javascript') { + + Assert(['javascript', 'unix'].includes(type), '"type" must be one of "javascript, unix"'); + + return this.format(type); } } - 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; + }, + + cast: { + number: { + from: internals.isDate, + to(value, helpers) { + + return value.getTime(); + } + }, + string: { + from: internals.isDate, + to(value, { prefs }) { + + return Template.date(value, prefs); } } - else { - // Send the pipeline to a random node - pipelineSlot = (Math.random() * 16384) | 0; - } + }, + + 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' } - // 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); +}); + + +// Helpers + +internals.parse = function (value, format) { + + if (value instanceof Date) { + return value; } - const _this = this; - if (!scripts.length) { - return execPipeline(); + + if (typeof value !== 'string' && + (isNaN(value) || !isFinite(value))) { + + return null; } - // 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; + + if (/^\s*$/.test(value)) { + return null; } - 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]); - } + + // ISO + + if (format === 'iso') { + if (!Common.isIsoDate(value)) { + return null; } - 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; + + return internals.date(value.toString()); + } + + // Normalize number string + + const original = value; + if (typeof value === 'string' && + /^[+-]?\d+(\.\d+)?$/.test(value)) { + + value = parseFloat(value); + } + + // Timestamp + + if (format) { + if (format === 'javascript') { + return internals.date(1 * value); // Casting to number } - }) - .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], - }; + + if (format === 'unix') { + return internals.date(1000 * value); } - 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); + + if (typeof original === 'string') { + return null; + } + } + + // Plain + + return internals.date(value); +}; + + +internals.date = function (value) { + + const date = new Date(value); + if (!isNaN(date.getTime())) { + return date; + } + + return null; +}; + + +/***/ }), + +/***/ 62269: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const Assert = __nccwpck_require__(32718); + +const Keys = __nccwpck_require__(79130); + + +const internals = {}; + + +module.exports = Keys.extend({ + + type: 'function', + + properties: { + typeof: 'function' + }, + + rules: { + arity: { + method(n) { + + 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; } - else { - data += writable; + + return helpers.error('function.arity', { n }); + } + }, + + class: { + method() { + + return this.$_addRule('class'); + }, + validate(value, helpers) { + + if ((/^\s*class\s/).test(value.toString())) { + return value; } - 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; + + return helpers.error('function.class', { value }); + } + }, + + minArity: { + method(n) { + + Assert(Number.isSafeInteger(n) && n > 0, 'n must be a strict positive integer'); + + return this.$_addRule({ name: 'minArity', args: { n } }); + }, + validate(value, helpers, { n }) { + + if (value.length >= n) { + return value; } + + return helpers.error('function.minArity', { n }); + } + }, + + maxArity: { + method(n) { + + Assert(Number.isSafeInteger(n) && n >= 0, 'n must be a positive integer'); + + return this.$_addRule({ name: 'maxArity', args: { n } }); }, - }; - for (let i = 0; i < _this._queue.length; ++i) { - _this.redis.sendCommand(_this._queue[i], stream, node); + validate(value, helpers, { n }) { + + if (value.length <= n) { + return value; + } + + return helpers.error('function.maxArity', { n }); + } } - return _this.promise; + }, + + 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}}' } -}; +}); /***/ }), -/***/ 71475: -/***/ ((__unused_webpack_module, exports) => { +/***/ 79130: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -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}`); + +const ApplyToDefaults = __nccwpck_require__(85545); +const Assert = __nccwpck_require__(32718); +const Clone = __nccwpck_require__(85578); +const Topo = __nccwpck_require__(88392); + +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); + + +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 } - promise = lib; -} -exports.set = set; +}; -/***/ }), +module.exports = Any.extend({ -/***/ 1422: -/***/ ((__unused_webpack_module, exports) => { + type: '_keys', -"use strict"; + properties: { -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); + typeof: 'object' }, - keepAlive: 0, - noDelay: true, - connectionName: null, - // Sentinel - sentinels: null, - name: null, - role: "master", - sentinelRetryStrategy: function (times) { - return Math.min(times * 10, 1000); + + flags: { + + unknown: { default: false } }, - 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; + + terms: { + + dependencies: { init: null }, + keys: { init: null, manifest: { mapped: { from: 'schema', to: 'key' } } }, + patterns: { init: null }, + renames: { init: null } }, - 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, -}; + args(schema, keys) { -/***/ }), + return schema.keys(keys); + }, -/***/ 74276: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + validate(value, { schema, error, state, prefs }) { -"use strict"; + if (!value || + typeof value !== schema.$_property('typeof') || + Array.isArray(value)) { -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.`); + return { value, errors: error('object.base', { type: schema.$_property('typeof') }) }; + } + + // Skip if there are no other rules to test + + if (!schema.$_terms.renames && + !schema.$_terms.dependencies && + !schema.$_terms.keys && // null allows any keys + !schema.$_terms.patterns && + !schema.$_terms.externals) { + + return; + } + + // Shallow clone value + + value = internals.clone(value, prefs); + const errors = []; + + // Rename keys + + if (schema.$_terms.renames && + !internals.rename(schema, value, state, prefs, errors)) { + + return { value, errors }; + } + + // Anything allowed + + if (!schema.$_terms.keys && // null allows any keys + !schema.$_terms.patterns && + !schema.$_terms.dependencies) { + + return { value, errors }; + } + + // Defined keys + + const unprocessed = new Set(Object.keys(value)); + + if (schema.$_terms.keys) { + const ancestors = [value, ...state.ancestors]; + + for (const child of schema.$_terms.keys) { + const key = child.key; + const item = value[key]; + + 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 }; } - else { - flushed = true; - self.recoverFromFatalError(err, err); + + if (result.value !== undefined) { + value[key] = result.value; } + + errors.push(...result.errors); } - }); - } - 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); - }); + else if (child.schema._flags.result === 'strip' || + result.value === undefined && item !== undefined) { + + delete value[key]; + } + else if (result.value !== undefined) { + value[key] = result.value; + } + } } - if (!self.options.enableReadyCheck) { - exports.readyHandler(self)(); + + // Unknown keys + + if (unprocessed.size || + schema._flags._hasPatternMatch) { + + const early = internals.unknown(schema, value, unprocessed, errors, state, prefs); + if (early) { + return early; + } } - /* - 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; + + // Validate dependencies + + if (schema.$_terms.dependencies) { + for (const dep of schema.$_terms.dependencies) { + if (dep.key && + dep.key.resolve(value, state, prefs, null, { shadow: false }) === undefined) { + + continue; } - if (err) { - if (!flushed) { - self.recoverFromFatalError(new Error("Ready check failed: " + err.message), err); + + 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 }; } + + errors.push(report); + } + } + } + + return { value, errors }; + }, + + rules: { + + and: { + method(...peers /*, [options] */) { + + Common.verifyFlat(peers, 'and'); + + return internals.dependency(this, 'and', null, peers); + } + }, + + append: { + method(schema) { + + if (schema === null || + schema === undefined || + Object.keys(schema).length === 0) { + + return this; + } + + return this.keys(schema); + } + }, + + assert: { + method(subject, schema, message) { + + if (!Template.isTemplate(subject)) { + subject = Compile.ref(subject); + } + + Assert(message === undefined || typeof message === 'string', 'Message must be a string'); + + schema = this.$_compile(schema, { appendPath: true }); + + 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 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; + } + + return error('object.assert', { subject, message }); + }, + args: ['subject', 'schema', 'message'], + multi: true + }, + + instance: { + method(constructor, name) { + + Assert(typeof constructor === 'function', 'constructor must be a function'); + + name = name || constructor.name; + + return this.$_addRule({ name: 'instance', args: { constructor, name } }); + }, + validate(value, helpers, { constructor, name }) { + + if (value instanceof constructor) { + return value; + } + + return helpers.error('object.instance', { type: name, value }); + }, + args: ['constructor', 'name'] + }, + + keys: { + method(schema) { + + Assert(schema === undefined || typeof schema === 'object', 'Object schema must be a valid object'); + Assert(!Common.isSchema(schema), 'Object schema cannot be a joi schema'); + + 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 { - self.serverInfo = info; - if (self.connector.check(info)) { - exports.readyHandler(self)(); - } - else { - self.disconnect(true); + 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); } } - }); - } - }; -} -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..."); + + return obj.$_mutateRebuild(); + } + }, + + length: { + method(limit) { + + 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; + } + + return helpers.error('object.' + name, { limit: args.limit, value }); + }, + args: [ + { + name: 'limit', + ref: true, + assert: Common.limit, + message: 'must be a positive integer' + } + ] + }, + + max: { + method(limit) { + + return this.$_addRule({ name: 'max', method: 'length', args: { limit }, operator: '<=' }); + } + }, + + min: { + method(limit) { + + return this.$_addRule({ name: 'min', method: 'length', args: { limit }, operator: '>=' }); + } + }, + + nand: { + method(...peers /*, [options] */) { + + Common.verifyFlat(peers, 'nand'); + + return internals.dependency(this, 'nand', null, peers); + } + }, + + or: { + method(...peers /*, [options] */) { + + Common.verifyFlat(peers, 'or'); + + return internals.dependency(this, 'or', null, peers); } - else { - const remainder = self.retryAttempts % (maxRetriesPerRequest + 1); - if (remainder === 0) { - debug("reach maxRetriesPerRequest limitation, flushing command queue..."); - self.flushQueue(new errors_1.MaxRetriesPerRequestError(maxRetriesPerRequest)); - } + }, + + oxor: { + method(...peers /*, [options] */) { + + return internals.dependency(this, 'oxor', null, peers); } - } - }; - 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); + }, + + pattern: { + method(pattern, schema, options = {}) { + + const isRegExp = pattern instanceof RegExp; + if (!isRegExp) { + pattern = this.$_compile(pattern, { appendPath: true }); } - 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); + + 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'); } - const subscribeChannels = condition.subscriber.channels("subscribe"); - if (subscribeChannels.length) { - debug("subscribe %d channels", subscribeChannels.length); - self.subscribe(subscribeChannels); + + schema = this.$_compile(schema, { appendPath: true }); + + 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); + } + + obj.$_mutateRegister(config.matches); + obj.$_setFlag('_hasPatternMatch', true, { clone: false }); } - const psubscribeChannels = condition.subscriber.channels("psubscribe"); - if (psubscribeChannels.length) { - debug("psubscribe %d channels", psubscribeChannels.length); - self.psubscribe(psubscribeChannels); + + if (options.fallthrough) { + config.fallthrough = true; } + + obj.$_terms.patterns.push(config); + obj.$_mutateRegister(schema); + return obj; } - } - 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); + }, + + ref: { + method() { + + return this.$_addRule('ref'); + }, + validate(value, helpers) { + + if (Ref.isRef(value)) { + return value; } + + return helpers.error('object.refType', { value }); } - else { - self.prevCommandQueue = null; + }, + + regex: { + method() { + + return this.$_addRule('regex'); + }, + validate(value, helpers) { + + if (value instanceof RegExp) { + return value; + } + + return helpers.error('object.regex', { value }); } - } - 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); + }, + + 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); + + Common.assertOptions(options, ['alias', 'ignoreUndefined', 'override', 'multiple']); + + 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'); } - self.sendCommand(item.command, item.stream); + + if (to instanceof Template) { + obj.$_mutateRegister(to); + } + + obj.$_terms.renames.push({ + from, + to, + options: ApplyToDefaults(internals.renameDefaults, options) + }); + + return obj; } - } - if (self.condition.select !== finalSelect) { - debug("connect to db [%d]", finalSelect); - self.select(finalSelect); - } - }; -} -exports.readyHandler = readyHandler; + }, + schema: { + method(type = 'any') { -/***/ }), + return this.$_addRule({ name: 'schema', args: { type } }); + }, + validate(value, helpers, { type }) { -/***/ 83609: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + if (Common.isSchema(value) && + (type === 'any' || value.type === type)) { -"use strict"; + return value; + } -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. + return helpers.error('object.schema', { type }); + } + }, - * // 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; + unknown: { + method(allow) { + + return this.$_setFlag('unknown', allow !== false); } - 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; - } - if (typeof arg === "object") { - lodash_1.defaults(this.options, arg); - } - else if (typeof arg === "string") { - lodash_1.defaults(this.options, utils_1.parseURL(arg)); - if (arg.startsWith("rediss://")) { - isTls = true; + + with: { + method(key, peers, options = {}) { + + return internals.dependency(this, 'with', key, peers, options); } - } - else if (typeof arg === "number") { - this.options.port = arg; - } - else { - throw new Error("Invalid argument " + arg); - } - } - 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; - } - // 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; + }, + + without: { + method(key, peers, options = {}) { + + return internals.dependency(this, 'without', key, peers, options); } - let CONNECT_EVENT = options.tls ? "secureConnect" : "connect"; - if (options.sentinels && !options.enableTLSForSentinelMode) { - CONNECT_EVENT = "connect"; + }, + + xor: { + method(...peers /*, [options] */) { + + Common.verifyFlat(peers, 'xor'); + + return internals.dependency(this, 'xor', null, peers); } - _this.stream = stream; - if (typeof options.keepAlive === "number") { - stream.setKeepAlive(true, options.keepAlive); + } + }, + + overrides: { + + default(value, options) { + + if (value === undefined) { + value = Common.symbols.deepDefault; } - 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); - }); - } + + return this.$_parent('default', value, options); + } + }, + + rebuild(schema) { + + 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); } - else if (stream.destroyed) { - const firstError = _this.connector.firstError; - if (firstError) { - process.nextTick(() => { - eventHandler.errorHandler(_this)(firstError); - }); - } - process.nextTick(eventHandler.closeHandler(_this)); + + schema.$_terms.keys = new internals.Keys(...topo.nodes); + } + }, + + manifest: { + + build(obj, desc) { + + if (desc.keys) { + obj = obj.keys(desc.keys); } - else { - process.nextTick(eventHandler.connectHandler(_this)); + + if (desc.dependencies) { + for (const { rel, key = null, peers, options } of desc.dependencies) { + obj = internals.dependency(obj, rel, key, peers, options); + } } - if (!stream.destroyed) { - stream.once("error", eventHandler.errorHandler(_this)); - stream.once("close", eventHandler.closeHandler(_this)); + + if (desc.patterns) { + for (const { regex, schema, rule, fallthrough, matches } of desc.patterns) { + obj = obj.pattern(regex || schema, rule, { fallthrough, matches }); + } } - if (options.noDelay) { - stream.setNoDelay(true); + + if (desc.renames) { + for (const { from, to, options } of desc.renames) { + obj = obj.rename(from, to, options); + } } - 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 obj; + } + }, + + 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 (this.reconnectTimeout && !reconnect) { - clearTimeout(this.reconnectTimeout); - this.reconnectTimeout = null; +}); + + +// Helpers + +internals.clone = function (value, prefs) { + + // Object + + if (typeof value === 'object') { + if (prefs.nonEnumerables) { + return Clone(value, { shallow: true }); + } + + const clone = Object.create(Object.getPrototypeOf(value)); + Object.assign(clone, value); + return clone; } - if (this.status === "wait") { - eventHandler.closeHandler(this)(); + + // Function + + const clone = function (...args) { + + return value.apply(this, args); + }; + + 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; +}; + + +internals.dependency = function (schema, rel, key, peers, options) { + + Assert(key === null || typeof key === 'string', rel, 'key must be a strings'); + + // Extract options from peers array + + if (!options) { + options = peers.length > 1 && typeof peers[peers.length - 1] === 'object' ? peers.pop() : {}; } - else { - this.connector.disconnect(); + + Common.assertOptions(options, ['separator']); + + peers = [].concat(peers); + + // Cast peer paths + + 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 })); } -}; -/** - * 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); + + // Cast key + + if (key !== null) { + key = Compile.ref(key, { separator, ancestor: 0, prefix: false }); } - switch (needReconnect) { - case 1: - case true: - if (this.status !== "reconnecting") { - this.disconnect(true); + + // Add rule + + const obj = schema.clone(); + obj.$_terms.dependencies = obj.$_terms.dependencies || []; + obj.$_terms.dependencies.push(new internals.Dependency(rel, key, paths, peers)); + return obj; +}; + + +internals.dependencies = { + + and(schema, dep, value, state, prefs) { + + 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); } - item.command.reject(err); - break; - case 2: - if (this.status !== "reconnecting") { - this.disconnect(true); + else { + present.push(peer.key); } - if (this.condition.select !== item.select && - item.command.name !== "select") { - this.select(item.select); + } + + if (missing.length !== count && + present.length !== count) { + + return { + code: 'object.and', + context: { + present, + presentWithLabels: internals.keysToLabels(schema, present), + missing, + missingWithLabels: internals.keysToLabels(schema, missing) + } + }; + } + }, + + nand(schema, dep, value, state, prefs) { + + const present = []; + for (const peer of dep.peers) { + if (peer.resolve(value, state, prefs, null, { shadow: false }) !== undefined) { + present.push(peer.key); } - 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); } - } - if (options.commandQueue) { - if (this.commandQueue.length > 0) { - if (this.stream) { - this.stream.removeAllListeners("data"); + + 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) } - while (this.commandQueue.length > 0) { - item = this.commandQueue.shift(); - item.command.reject(error); + }; + }, + + or(schema, dep, value, state, prefs) { + + for (const peer of dep.peers) { + if (peer.resolve(value, state, prefs, null, { shadow: false }) !== undefined) { + return; } } - } -}; -/** - * 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); + + return { + code: 'object.missing', + context: { + peers: dep.paths, + peersWithLabels: internals.keysToLabels(schema, dep.paths) + } + }; + }, + + oxor(schema, dep, value, state, prefs) { + + const present = []; + for (const peer of dep.peers) { + if (peer.resolve(value, state, prefs, null, { shadow: false }) !== undefined) { + present.push(peer.key); + } } - if (typeof res !== "string") { - return callback(null, res); + + if (!present.length || + present.length === 1) { + + 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 context = { peers: dep.paths, peersWithLabels: internals.keysToLabels(schema, dep.paths) }; + context.present = present; + context.presentWithLabels = internals.keysToLabels(schema, present); + return { code: 'object.oxor', context }; + }, + + with(schema, dep, value, state, prefs) { + + 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 (!info.loading || info.loading === "0") { - callback(null, info); + }, + + without(schema, dep, value, state, prefs) { + + 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) + } + }; + } } - 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); + }, + + xor(schema, dep, value, state, prefs) { + + const present = []; + for (const peer of dep.peers) { + if (peer.resolve(value, state, prefs, null, { shadow: false }) !== undefined) { + present.push(peer.key); + } } - }); -}; -/** - * 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") { + + if (present.length === 1) { return; } - 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; - } + + 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 }; } - if (this.listeners(eventName).length > 0) { - return this.emit.apply(this, arguments); +}; + + +internals.keysToLabels = function (schema, keys) { + + if (Array.isArray(keys)) { + return keys.map((key) => schema.$_mapLabels(key)); } - if (error && error instanceof Error) { - console.error("[ioredis] Unhandled error event:", error.stack); + + return schema.$_mapLabels(keys); +}; + + +internals.rename = function (schema, value, state, prefs, errors) { + + const renamed = {}; + for (const rename of schema.$_terms.renames) { + const matches = []; + const pattern = typeof rename.from !== 'string'; + + if (!pattern) { + if (Object.prototype.hasOwnProperty.call(value, rename.from) && + (value[rename.from] !== undefined || !rename.options.ignoreUndefined)) { + + matches.push(rename); + } + } + else { + for (const from in value) { + if (value[from] === undefined && + rename.options.ignoreUndefined) { + + continue; + } + + if (from === rename.to) { + continue; + } + + const match = rename.from.exec(from); + if (!match) { + continue; + } + + matches.push({ from, to: rename.to, match }); + } + } + + 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 (from === to) { + continue; + } + + if (!rename.options.multiple && + renamed[to]) { + + errors.push(schema.$_createError('object.rename.multiple', value, { from, to, pattern }, state, prefs)); + if (prefs.abortEarly) { + return false; + } + } + + 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; + } + } + + if (value[from] === undefined) { + delete value[to]; + } + else { + value[to] = value[from]; + } + + renamed[to] = true; + + if (!rename.options.alias) { + delete value[from]; + } + } } - return false; + + return true; }; -/** - * 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); + + +internals.unknown = function (schema, value, unprocessed, errors, state, prefs) { + + if (schema.$_terms.patterns) { + let hasMatches = false; + const matches = schema.$_terms.patterns.map((pattern) => { + + if (pattern.matches) { + hasMatches = true; + return []; + } }); - }), 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); + + const ancestors = [value, ...state.ancestors]; + + for (const key of unprocessed) { + const item = value[key]; + const path = [...state.path, key]; + + 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; + } + } + + unprocessed.delete(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 }; + } + + errors.push(...result.errors); + } + + if (pattern.matches) { + matches[i].push(key); + } + + value[key] = result.value; + if (!pattern.fallthrough) { + break; + } + } } - (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; + + // 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); + } + } } } - 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); + + if (!unprocessed.size || + !schema.$_terms.keys && !schema.$_terms.patterns) { // If no keys or patterns specified, unknown keys allowed + + return; + } + + if (prefs.stripUnknown && !schema._flags.unknown || + prefs.skipFunctions) { + + 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); + } } - 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); + + 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 }; + } + + errors.push(report); } } - 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; + + +internals.Dependency = class { + + constructor(rel, key, peers, paths) { + + this.rel = rel; + this.key = key; + this.peers = peers; + this.paths = paths; } - if (this.options.connectionName) { - description += ` (${this.options.connectionName})`; + + describe() { + + const desc = { + rel: this.rel, + peers: this.paths + }; + + if (this.key !== null) { + desc.key = this.key.key; + } + + if (this.peers[0].separator !== '.') { + desc.options = { separator: this.peers[0].separator }; + } + + return desc; } - 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; + + +internals.Keys = class extends Array { + + concat(source) { + + const result = this.slice(); + + const keys = new Map(); + for (let i = 0; i < result.length; ++i) { + keys.set(result[i].key, i); + } + + 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) }; + } + else { + result.push(item); + } } - return new ScanStream_1.default(lodash_1.defaults({ - objectMode: true, - key: key, - redis: this, - command: command, - }, options)); - }; -}); + + return result; + } +}; /***/ }), -/***/ 88540: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 69869: +/***/ ((module, __unused_webpack_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); + +const Assert = __nccwpck_require__(32718); + +const Any = __nccwpck_require__(9512); +const Common = __nccwpck_require__(72448); +const Compile = __nccwpck_require__(3038); +const Errors = __nccwpck_require__(69490); + + +const internals = {}; + + +module.exports = Any.extend({ + + type: 'link', + + properties: { + schemaChain: true + }, + + terms: { + + link: { init: null, manifest: 'single', register: false } + }, + + args(schema, ref) { + + return schema.ref(ref); + }, + + validate(value, { schema, 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); + }, + + generate(schema, value, state, prefs) { + + return internals.generate(schema, value, state, prefs); + }, + + rules: { + + ref: { + method(ref) { + + Assert(!this.$_terms.link, 'Cannot reinitialize schema'); + + ref = Compile.ref(ref); + + 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); + } } - if (this.keyPrefix) { - options.keyPrefix = this.keyPrefix; + }, + + 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(); } - if (this.readOnly) { - options.readOnly = true; + }, + + manifest: { + + build(obj, desc) { + + Assert(desc.link, 'Invalid link description missing link'); + return obj.ref(desc.link); } - 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; + } +}); + + +// Helpers + +internals.generate = function (schema, value, state, prefs) { + + let linked = state.mainstay.links.get(schema); + if (linked) { + return linked._generate(value, state, prefs).schema; + } + + 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 { + linked = path.length ? perspective.$_reach(path) : perspective; + } + catch (ignoreErr) { + internals.assert(false, 'to non-existing schema', ref, schema, state, prefs); + } + + internals.assert(linked.type !== 'link', 'which is another link', ref, schema, state, prefs); + + if (!schema._flags.relative) { + state.mainstay.links.set(schema, linked); + } + + 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) }; + } } - 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; + + return { perspective: null, path: null }; } -} -exports["default"] = Script; + + if (ref.ancestor === 'root') { + return { perspective: state.schemas[state.schemas.length - 1].schema, path: ref.path }; + } + + return { perspective: state.schemas[ref.ancestor] && state.schemas[ref.ancestor].schema, path: ref.path }; +}; + + +internals.assert = function (condition, message, ref, schema, state, prefs) { + + 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}`); +}; /***/ }), -/***/ 14645: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 15855: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -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); + +const Assert = __nccwpck_require__(32718); + +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+))?$/ +}; + + +module.exports = Any.extend({ + + type: 'number', + + flags: { + + unsafe: { default: false } + }, + + 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; + } + + if (string !== internals.normalizeDecimal(value)) { + result.errors = error('number.unsafe'); + return result; + } + } + } + + return result; } - return pipeline; - }; - const { multi } = redis; - redis.multi = function (commands, options) { - if (typeof options === "undefined" && !Array.isArray(commands)) { - options = commands; - commands = null; + }, + + validate(value, { schema, error, prefs }) { + + if (value === Infinity || + value === -Infinity) { + + return { value, errors: error('number.infinity') }; } - if (options && options.pipeline === false) { - return multi.call(this); + + if (!Common.isNumber(value)) { + return { value, errors: error('number.base') }; } - const pipeline = new pipeline_1.default(this); - pipeline.multi(); - if (Array.isArray(commands)) { - pipeline.addBatch(commands); + + const result = { value }; + + 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; + } } - 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); + + 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: { + + compare: { + method: false, + validate(value, helpers, { limit }, { name, operator, args }) { + + if (Common.compare(value, limit, operator)) { + return value; + } + + return helpers.error('number.' + name, { limit: args.limit, value }); + }, + args: [ + { + name: 'limit', + ref: true, + assert: Common.isNumber, + message: 'must be a number' + } + ] + }, + + greater: { + method(limit) { + + return this.$_addRule({ name: 'greater', method: 'compare', args: { limit }, operator: '>' }); } - if (this._transactions > 0) { - exec.call(pipeline); + }, + + integer: { + method() { + + return this.$_addRule('integer'); + }, + validate(value, helpers) { + + if (Math.trunc(value) - value === 0) { + return value; + } + + return helpers.error('number.integer'); } - // Returns directly when the pipeline - // has been called multiple times (retries). - if (this.nodeifiedPromise) { - return exec.call(pipeline); + }, + + less: { + method(limit) { + + return this.$_addRule({ name: 'less', method: 'compare', args: { limit }, operator: '<' }); } - 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."); + }, + + max: { + method(limit) { + + return this.$_addRule({ name: 'max', method: 'compare', args: { limit }, operator: '<=' }); + } + }, + + min: { + method(limit) { + + return this.$_addRule({ name: 'min', method: 'compare', args: { limit }, operator: '>=' }); + } + }, + + multiple: { + method(base) { + + return this.$_addRule({ name: 'multiple', args: { base } }); + }, + validate(value, helpers, { base }, options) { + + if (value * (1 / base) % 1 === 0) { + return value; } - 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 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' } - return utils_1.wrapMultiResult(execResult[1]); - }), callback); - }; - const { execBuffer } = pipeline; - pipeline.execBuffer = function (callback) { - if (this._transactions > 0) { - execBuffer.call(pipeline); + ], + multi: true + }, + + negative: { + method() { + + return this.sign('negative'); } - 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); + }, + + port: { + method() { + + return this.$_addRule('port'); + }, + validate(value, helpers) { + + if (Number.isSafeInteger(value) && + value >= 0 && + value <= 65535) { + + return value; + } + + return helpers.error('number.port'); } - return results; - }), callback); - }; -} -exports.addTransactionSupport = addTransactionSupport; + }, + + positive: { + method() { + + return this.sign('positive'); + } + }, + + precision: { + method(limit) { + + Assert(Number.isSafeInteger(limit), 'limit must be an integer'); + + return this.$_addRule({ name: 'precision', args: { limit } }); + }, + validate(value, helpers, { limit }) { + + 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; + } + + 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}`); + } + }, + + unsafe: { + method(enabled = true) { + + Assert(typeof enabled === 'boolean', 'enabled must be a boolean'); + + return this.$_setFlag('unsafe', enabled); + } + } + }, + + cast: { + string: { + from: (value) => typeof value === 'number', + to(value, helpers) { + + return value.toString(); + } + } + }, + + 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' + } +}); + + +// Helpers + +internals.normalizeExponent = function (str) { + + 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'); +}; + + +internals.normalizeDecimal = function (str) { + + 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'); + + if (str.includes('.') && + str.endsWith('0')) { + + str = str.replace(/0+$/, ''); + } + + if (str === '-0') { + return '0'; + } + + return str; +}; + + +/***/ }), + +/***/ 46878: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const Keys = __nccwpck_require__(79130); + + +const internals = {}; + + +module.exports = Keys.extend({ + + type: 'object', + + cast: { + map: { + from: (value) => value && typeof value === 'object', + to(value, helpers) { + + return new Map(Object.entries(value)); + } + } + } +}); + + +/***/ }), + +/***/ 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); + +const Any = __nccwpck_require__(9512); +const Common = __nccwpck_require__(72448); + + +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)?)?$/, + + guidBrackets: { + '{': '}', '[': ']', '(': ')', '': '' + }, + guidVersions: { + uuidv1: '1', + uuidv2: '2', + uuidv3: '3', + uuidv4: '4', + uuidv5: '5' + }, + guidSeparators: new Set([undefined, true, false, '-', ':']), + + normalizationForms: ['NFC', 'NFD', 'NFKC', 'NFKD'] +}; + + +module.exports = Any.extend({ + + type: 'string', + flags: { -/***/ }), + insensitive: { default: false }, + truncate: { default: false } + }, -/***/ 85356: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + terms: { -"use strict"; + replacements: { init: null } + }, -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"); + coerce: { + from: 'string', + method(value, { schema, state, prefs }) { + + const normalize = schema.$_getRule('normalize'); + if (normalize) { + value = value.normalize(normalize.args.form); } - if (Array.isArray(v)) { - return v.join(","); + + const casing = schema.$_getRule('case'); + if (casing) { + value = casing.args.direction === 'upper' ? value.toLocaleUpperCase() : value.toLocaleLowerCase(); } - try { - return JSON.stringify(v); + + const trim = schema.$_getRule('trim'); + if (trim && + trim.args.enabled) { + + value = value.trim(); } - catch (e) { - return; + + if (schema.$_terms.replacements) { + for (const replacement of schema.$_terms.replacements) { + value = value.replace(replacement.pattern, replacement.replacement); + } } - 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 + + const hex = schema.$_getRule('hex'); + if (hex && + hex.args.options.byteAligned && + value.length % 2 !== 0) { + + value = `0${value}`; + } + + 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) }; + } + } + + value = value.slice(0, limit); + } + } + + return { value }; } - // 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); + }, + + validate(value, { schema, error }) { + + if (typeof value !== 'string') { + return { value, errors: error('string.base') }; + } + + if (value === '') { + const min = schema.$_getRule('min'); + if (min && + min.args.limit === 0) { + + return; } + + return { value, errors: error('string.empty') }; } - 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; + }, + + rules: { + + alphanum: { + method() { + + return this.$_addRule('alphanum'); }, + validate(value, helpers) { + + if (/^[a-zA-Z0-9]+$/.test(value)) { + return value; + } + + return helpers.error('string.alphanum'); + } }, - }); - return wrappedDebug; -} -exports["default"] = genDebugFunction; + base64: { + method(options = {}) { -/***/ }), + Common.assertOptions(options, ['paddingRequired', 'urlSafe']); -/***/ 94832: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + options = { urlSafe: false, paddingRequired: true, ...options }; + Assert(typeof options.paddingRequired === 'boolean', 'paddingRequired must be boolean'); + Assert(typeof options.urlSafe === 'boolean', 'urlSafe must be boolean'); -"use strict"; + return this.$_addRule({ name: 'base64', args: { options } }); + }, + validate(value, helpers, { options }) { -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 regex = internals.base64Regex[options.paddingRequired][options.urlSafe]; + if (regex.test(value)) { + return value; + } + return helpers.error('string.base64'); + } + }, -/***/ }), + case: { + method(direction) { -/***/ 20961: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + Assert(['lower', 'upper'].includes(direction), 'Invalid case:', direction); -"use strict"; + return this.$_addRule({ name: 'case', args: { direction } }); + }, + validate(value, helpers, { direction }) { -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; + if (direction === 'lower' && value === value.toLocaleLowerCase() || + direction === 'upper' && value === value.toLocaleUpperCase()) { + return value; + } -/***/ }), + return helpers.error(`string.${direction}case`); + }, + convert: true + }, -/***/ 37263: -/***/ (function(module, __unused_webpack_exports, __nccwpck_require__) { + creditCard: { + method() { -/* module decorator */ module = __nccwpck_require__.nmd(module); -(function() { - var expandIPv6, ipaddr, ipv4Part, ipv4Regexes, ipv6Part, ipv6Regexes, matchCIDR, root, zoneIndex; + return this.$_addRule('creditCard'); + }, + validate(value, helpers) { - ipaddr = {}; + let i = value.length; + let sum = 0; + let mul = 1; - root = this; + while (i--) { + const char = value.charAt(i) * mul; + sum = sum + (char - (char > 9) * 9); + mul = mul ^ 3; + } - if (( true && module !== null) && module.exports) { - module.exports = ipaddr; - } else { - root['ipaddr'] = ipaddr; - } + if (sum > 0 && + sum % 10 === 0) { - 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"); - } - 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; - }; + return value; + } - ipaddr.subnetMatch = function(address, rangeList, defaultName) { - var k, len, rangeName, rangeSubnets, subnet; - if (defaultName == null) { - defaultName = 'unicast'; - } - 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; - } - } - } - } - return defaultName; - }; + return helpers.error('string.creditCard'); + } + }, - 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; - } + dataUri: { + method(options = {}) { - IPv4.prototype.kind = function() { - return 'ipv4'; - }; + Common.assertOptions(options, ['paddingRequired']); - IPv4.prototype.toString = function() { - return this.octets.join("."); - }; + options = { paddingRequired: true, ...options }; + Assert(typeof options.paddingRequired === 'boolean', 'paddingRequired must be boolean'); - IPv4.prototype.toNormalizedString = function() { - return this.toString(); - }; + return this.$_addRule({ name: 'dataUri', args: { options } }); + }, + validate(value, helpers, { options }) { - IPv4.prototype.toByteArray = function() { - return this.octets.slice(0); - }; + const matches = value.match(internals.dataUriRegex); - 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); - }; + if (matches) { + if (!matches[2]) { + return value; + } - 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]] - }; + if (matches[2] !== 'base64') { + return value; + } - IPv4.prototype.range = function() { - return ipaddr.subnetMatch(this, this.SpecialRanges); - }; + const base64regex = internals.base64Regex[options.paddingRequired].false; + if (base64regex.test(matches[3])) { + return value; + } + } - IPv4.prototype.toIPv4MappedAddress = function() { - return ipaddr.IPv6.parse("::ffff:" + (this.toString())); - }; + return helpers.error('string.dataUri'); + } + }, - 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; - }; + domain: { + method(options) { - return IPv4; + if (options) { + Common.assertOptions(options, ['allowFullyQualified', 'allowUnicode', 'maxDomainSegments', 'minDomainSegments', 'tlds']); + } - })(); + const address = internals.addressOptions(options); + return this.$_addRule({ name: 'domain', args: { options }, address }); + }, + validate(value, helpers, args, { address }) { - ipv4Part = "(0?\\d+|0x[a-f0-9]+)"; + if (Domain.isValid(value, address)) { + return value; + } - ipv4Regexes = { - fourOctet: new RegExp("^" + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "$", 'i'), - longValue: new RegExp("^" + ipv4Part + "$", 'i') - }; + return helpers.error('string.domain'); + } + }, - 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)); - } - 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; - } - }; + email: { + method(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; - } - } + 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'); - IPv6.prototype.kind = function() { - return 'ipv6'; - }; + const address = internals.addressOptions(options); + const regex = new RegExp(`\\s*[${options.separator ? EscapeRegex(options.separator) : ','}]\\s*`); - IPv6.prototype.toString = function() { - return this.toNormalizedString().replace(/((^|:)(0(:|$))+)/, '::'); - }; + return this.$_addRule({ name: 'email', args: { options }, regex, address }); + }, + validate(value, helpers, { options }, { regex, address }) { - 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); - }; + const emails = options.multiple ? value.split(regex) : [value]; + const invalids = []; + for (const email of emails) { + if (!Email.isValid(email, address)) { + invalids.push(email); + } + } - 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; - }; + if (!invalids.length) { + return value; + } - 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; - }; + return helpers.error('string.email', { value, invalids }); + } + }, - 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; - }; + guid: { + alias: 'uuid', + method(options = {}) { - 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); - }; + Common.assertOptions(options, ['version', 'separator']); - 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]] - }; + let versionNumbers = ''; - IPv6.prototype.range = function() { - return ipaddr.subnetMatch(this, this.SpecialRanges); - }; + if (options.version) { + const versions = [].concat(options.version); - IPv6.prototype.isIPv4MappedAddress = function() { - return this.range() === 'ipv4Mapped'; - }; + Assert(versions.length >= 1, 'version must have at least 1 valid version specified'); + const set = new Set(); - 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]); - }; + 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'); - 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; - }; + versionNumbers += versionNumber; + set.add(versionNumber); + } + } - return IPv6; + 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}`; - })(); + 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'); - ipv6Part = "(?:[0-9a-f]+::?)+"; + return this.$_addRule({ name: 'guid', args: { options }, regex }); + }, + validate(value, helpers, args, { regex }) { - zoneIndex = "%[0-9a-z]{1,}"; + const results = regex.exec(value); - 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') - }; + if (!results) { + return helpers.error('string.guid'); + } - expandIPv6 = function(string, parts) { - var colonCount, lastColon, part, replacement, replacementCount, zoneId; - if (string.indexOf('::') !== string.lastIndexOf('::')) { - return null; - } - zoneId = (string.match(ipv6Regexes['zoneIndex']) || [])[0]; - if (zoneId) { - zoneId = zoneId.substring(1); - string = string.replace(/%.+$/, ''); - } - colonCount = 0; - lastColon = -1; - while ((lastColon = string.indexOf(':', lastColon + 1)) >= 0) { - colonCount++; - } - if (string.substr(0, 2) === '::') { - colonCount--; - } - if (string.substr(-2, 2) === '::') { - colonCount--; - } - if (colonCount > parts) { - return null; - } - 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 - }; - }; + // Matching braces - 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; - } - } - 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; - }; + if (internals.guidBrackets[results[1]] !== results[results.length - 1]) { + return helpers.error('string.guid'); + } - ipaddr.IPv4.isIPv4 = ipaddr.IPv6.isIPv6 = function(string) { - return this.parser(string) !== null; - }; + return value; + } + }, - ipaddr.IPv4.isValid = function(string) { - var e; - try { - new this(this.parser(string)); - return true; - } catch (error1) { - e = error1; - return false; - } - }; + hex: { + method(options = {}) { - 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; - } - }; + Common.assertOptions(options, ['byteAligned']); - ipaddr.IPv6.isValid = function(string) { - var addr, e; - if (typeof string === "string" && string.indexOf(":") === -1) { - return false; - } - try { - addr = this.parser(string); - new this(addr.parts, addr.zoneId); - return true; - } catch (error1) { - e = error1; - return false; - } - }; + options = { byteAligned: false, ...options }; + Assert(typeof options.byteAligned === 'boolean', 'byteAligned must be boolean'); + + return this.$_addRule({ name: 'hex', args: { options } }); + }, + validate(value, helpers, { options }) { + + if (!internals.hexRegex.test(value)) { + return helpers.error('string.hex'); + } - 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); - }; + if (options.byteAligned && + value.length % 2 !== 0) { - 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); - }; + return helpers.error('string.hexAlign'); + } - 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"); - }; + return value; + } + }, - 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); - }; + hostname: { + method() { - 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 this.$_addRule('hostname'); + }, + validate(value, helpers) { - 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'); - } - }; + if (Domain.isValid(value, { minDomainSegments: 1 }) || + internals.ipRegex.test(value)) { - 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"); - }; + return value; + } - ipaddr.isValid = function(string) { - return ipaddr.IPv6.isValid(string) || ipaddr.IPv4.isValid(string); - }; + return helpers.error('string.hostname'); + } + }, - 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"); - } - }; + insensitive: { + method() { - 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"); - } - } - }; + return this.$_setFlag('insensitive', true); + } + }, - 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"); - } - }; + ip: { + method(options = {}) { - ipaddr.process = function(string) { - var addr; - addr = this.parse(string); - if (addr.kind() === 'ipv6' && addr.isIPv4MappedAddress()) { - return addr.toIPv4Address(); - } else { - return addr; - } - }; + Common.assertOptions(options, ['cidr', 'version']); -}).call(this); + 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 }) { + if (regex.test(value)) { + return value; + } -/***/ }), + if (options.version) { + return helpers.error('string.ipVersion', { value, cidr: options.cidr, version: options.version }); + } -/***/ 7604: -/***/ ((module) => { + return helpers.error('string.ip', { value, cidr: options.cidr }); + } + }, -"use strict"; + isoDate: { + method() { + return this.$_addRule('isoDate'); + }, + validate(value, { error }) { -module.exports = function isArrayish(obj) { - if (!obj) { - return false; - } + if (internals.isoDate(value)) { + return value; + } - return obj instanceof Array || Array.isArray(obj) || - (obj.length >= 0 && obj.splice instanceof Function); -}; + return error('string.isoDate'); + } + }, + isoDuration: { + method() { -/***/ }), + return this.$_addRule('isoDuration'); + }, + validate(value, helpers) { -/***/ 31310: -/***/ (function(module, exports) { + if (internals.isoDurationRegex.test(value)) { + return value; + } -;(function(root) { - 'use strict'; + return helpers.error('string.isoDuration'); + } + }, - function isBase64(v, opts) { - if (v instanceof Boolean || typeof v === 'boolean') { - return false - } + length: { + method(limit, encoding) { - if (!(opts instanceof Object)) { - opts = {} - } + return internals.length(this, 'length', limit, '=', encoding); + }, + validate(value, helpers, { limit, encoding }, { name, operator, args }) { - if (opts.allowEmpty === false && v === '') { - return false - } + const length = encoding ? Buffer && Buffer.byteLength(value, encoding) : value.length; // $lab:coverage:ignore$ + if (Common.compare(length, limit, operator)) { + return value; + } - 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 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 (opts.mimeRequired === true) { - regex = mimeRegex + regex - } else if (opts.allowMime === true) { - regex = mimeRegex + '?' + regex - } + lowercase: { + method() { - if (opts.paddingRequired === false) { - regex = '(?:[A-Za-z0-9+\\/]{4})*(?:[A-Za-z0-9+\\/]{2}(==)?|[A-Za-z0-9+\\/]{3}=?)?' - } + return this.case('lower'); + } + }, - return (new RegExp('^' + regex + '$', 'gi')).test(v) - } + max: { + method(limit, encoding) { - if (true) { - if ( true && module.exports) { - exports = module.exports = isBase64 - } - exports.isBase64 = isBase64 - } else {} -})(this); + return internals.length(this, 'max', limit, '<=', encoding); + }, + args: ['limit', 'encoding'] + }, + min: { + method(limit, encoding) { -/***/ }), + return internals.length(this, 'min', limit, '>=', encoding); + }, + args: ['limit', 'encoding'] + }, -/***/ 56873: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + normalize: { + method(form = 'NFC') { -"use strict"; + Assert(internals.normalizationForms.includes(form), 'normalization form must be one of ' + internals.normalizationForms.join(', ')); + return this.$_addRule({ name: 'normalize', args: { form } }); + }, + validate(value, { error }, { form }) { -var has = __nccwpck_require__(76339); + if (value === value.normalize(form)) { + return value; + } -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('.'); + return error('string.normalize', { value, form }); + }, + convert: true + }, - 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 === '>='; -} + pattern: { + alias: 'regex', + method(regex, options = {}) { -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; -} + 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'); -function versionIncluded(nodeVersion, specifierValue) { - if (typeof specifierValue === 'boolean') { - return specifierValue; - } + if (typeof options === 'string') { + options = { name: options }; + } - var current = typeof nodeVersion === 'undefined' - ? process.versions && process.versions.node && process.versions.node - : nodeVersion; + Common.assertOptions(options, ['invert', 'name']); - if (typeof current !== 'string') { - throw new TypeError(typeof nodeVersion === 'undefined' ? 'Unable to determine current node version' : 'If provided, a valid node version is required'); - } + 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 (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); -} + const patternMatch = regex.test(value); -var data = __nccwpck_require__(66151); + if (patternMatch ^ options.invert) { + return value; + } -module.exports = function isCore(x, nodeVersion) { - return has(data, x) && versionIncluded(nodeVersion, data[x]); -}; + return helpers.error(errorCode, { name: options.name, regex, value }); + }, + args: ['regex', 'options'], + multi: true + }, + replace: { + method(pattern, replacement) { -/***/ }), + if (typeof pattern === 'string') { + pattern = new RegExp(EscapeRegex(pattern), 'g'); + } -/***/ 64882: -/***/ ((module) => { + Assert(pattern instanceof RegExp, 'pattern must be a RegExp'); + Assert(typeof replacement === 'string', 'replacement must be a String'); -"use strict"; -/* eslint-disable yoda */ + const obj = this.clone(); + if (!obj.$_terms.replacements) { + obj.$_terms.replacements = []; + } -const isFullwidthCodePoint = codePoint => { - if (Number.isNaN(codePoint)) { - return false; - } + obj.$_terms.replacements.push({ pattern, replacement }); + return obj; + } + }, - // 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; - } + token: { + method() { - return false; -}; + return this.$_addRule('token'); + }, + validate(value, helpers) { -module.exports = isFullwidthCodePoint; -module.exports["default"] = isFullwidthCodePoint; + if (/^\w+$/.test(value)) { + return value; + } + return helpers.error('string.token'); + } + }, -/***/ }), + trim: { + method(enabled = true) { -/***/ 63287: -/***/ ((__unused_webpack_module, exports) => { + Assert(typeof enabled === 'boolean', 'enabled must be a boolean'); -"use strict"; + return this.$_addRule({ name: 'trim', args: { enabled } }); + }, + validate(value, helpers, { enabled }) { + if (!enabled || + value === value.trim()) { -Object.defineProperty(exports, "__esModule", ({ value: true })); + return value; + } -/*! - * is-plain-object - * - * Copyright (c) 2014-2017, Jon Schlinkert. - * Released under the MIT License. - */ + return helpers.error('string.trim'); + }, + convert: true + }, -function isObject(o) { - return Object.prototype.toString.call(o) === '[object Object]'; -} + truncate: { + method(enabled = true) { -function isPlainObject(o) { - var ctor,prot; + Assert(typeof enabled === 'boolean', 'enabled must be a boolean'); - if (isObject(o) === false) return false; + return this.$_setFlag('truncate', enabled); + } + }, - // If has modified constructor - ctor = o.constructor; - if (ctor === undefined) return true; + uppercase: { + method() { - // If has modified prototype - prot = ctor.prototype; - if (isObject(prot) === false) return false; + return this.case('upper'); + } + }, - // If constructor does not have an Object-specific method - if (prot.hasOwnProperty('isPrototypeOf') === false) { - return false; - } + uri: { + method(options = {}) { - // Most likely a plain Object - return true; -} + Common.assertOptions(options, ['allowRelative', 'allowQuerySquareBrackets', 'domain', 'relativeOnly', 'scheme']); -exports.isPlainObject = isPlainObject; + 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 }); + }, + 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'); + } -/***/ 87783: -/***/ ((__unused_webpack_module, exports) => { + const match = regex.exec(value); + if (match) { + const matched = match[1] || match[2]; + if (domain && + (!options.allowRelative || matched) && + !Domain.isValid(matched, domain)) { -(function(exports) { - "use strict"; + return helpers.error('string.domain', { value: matched }); + } - function isArray(obj) { - if (obj !== null) { - return Object.prototype.toString.call(obj) === "[object Array]"; - } else { - return false; - } - } + return value; + } - function isObject(obj) { - if (obj !== null) { - return Object.prototype.toString.call(obj) === "[object Object]"; - } else { - return false; - } - } + if (options.relativeOnly) { + return helpers.error('string.uriRelativeOnly'); + } - function strictDeepEqual(first, second) { - // Check the scalar case first. - if (first === second) { - return true; - } + if (options.scheme) { + return helpers.error('string.uriCustomScheme', { scheme, value }); + } - // 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; - } - 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 helpers.error('string.uri'); + } } - } - 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 + manifest: { - // 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; + build(obj, desc) { + + if (desc.replacements) { + for (const { pattern, replacement } of desc.replacements) { + obj = obj.replace(pattern, replacement); + } } + + return obj; } - return true; - } else { - return false; + }, + + 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' } - } +}); - function objValues(obj) { - var keys = Object.keys(obj); - var values = []; - for (var i = 0; i < keys.length; i++) { - values.push(obj[keys[i]]); + +// Helpers + +internals.addressOptions = function (options) { + + if (!options) { + return options; } - 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; - } + // minDomainSegments - var trimLeft; - if (typeof String.prototype.trimLeft === "function") { - trimLeft = function(str) { - return str.trimLeft(); - }; - } else { - trimLeft = function(str) { - return str.match(/^\s*(.*)/)[1]; - }; - } + Assert(options.minDomainSegments === undefined || + Number.isSafeInteger(options.minDomainSegments) && options.minDomainSegments > 0, 'minDomainSegments must be a positive integer'); - // 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; + // maxDomainSegments - 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"; + Assert(options.maxDomainSegments === undefined || + Number.isSafeInteger(options.maxDomainSegments) && options.maxDomainSegments > 0, 'maxDomainSegments must be a positive integer'); - // The "&", "[", "<", ">" tokens - // are not in basicToken because - // there are two token variants - // ("&&", "[?", "<=", ">="). This is specially handled - // below. + // tlds - var basicTokens = { - ".": TOK_DOT, - "*": TOK_STAR, - ",": TOK_COMMA, - ":": TOK_COLON, - "{": TOK_LBRACE, - "}": TOK_RBRACE, - "]": TOK_RBRACKET, - "(": TOK_LPAREN, - ")": TOK_RPAREN, - "@": TOK_CURRENT - }; + if (options.tlds === false) { + return options; + } - var operatorStartToken = { - "<": true, - ">": true, - "=": true, - "!": true - }; + if (options.tlds === true || + options.tlds === undefined) { - var skipChars = { - " ": true, - "\t": true, - "\n": true - }; + 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'); - function isAlpha(ch) { - return (ch >= "a" && ch <= "z") || - (ch >= "A" && ch <= "Z") || - ch === "_"; - } + const deny = options.tlds.deny; + if (deny) { + if (Array.isArray(deny)) { + options = Object.assign({}, options, { tlds: { deny: new Set(deny) } }); + } - 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 === "_"; - } + 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; + } - 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; - }, + const allow = options.tlds.allow; + if (!allow) { + return options; + } - _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); - }, + if (allow === true) { + Assert(internals.tlds, 'Built-in TLD list disabled'); + return Object.assign({}, options, internals.tlds); + } - _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)); - }, + if (Array.isArray(allow)) { + options = Object.assign({}, options, { tlds: { allow: new Set(allow) } }); + } - _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("\\'", "'"); - }, + Assert(options.tlds.allow instanceof Set, 'tlds.allow must be an array, Set, or boolean'); + internals.validateTlds(options.tlds.allow, 'tlds.allow'); + return options; +}; - _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}; - }, - _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}; - } - }, +internals.validateTlds = function (set, source) { - _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}; - } - } - }, + for (const tld of set) { + Assert(Domain.isValid(tld, { minDomainSegments: 1, maxDomainSegments: 1 }), `${source} must contain valid top level domain names`); + } +}; - _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"; +internals.isoDate = function (value) { - 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; - } - } - }; + if (!Common.isIsoDate(value)) { + return null; + } - 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; + if (/.*T.*[+-]\d\d$/.test(value)) { // Add missing trailing zeros to timeshift + value += '00'; + } - function Parser() { - } + const date = new Date(value); + if (isNaN(date.getTime())) { + return null; + } - 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; - }, + return date.toISOString(); +}; - _loadTokens: function(expression) { - var lexer = new Lexer(); - var tokens = lexer.tokenize(expression); - tokens.push({type: TOK_EOF, value: "", start: expression.length}); - this.tokens = tokens; - }, - 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; - }, +internals.length = function (schema, name, limit, operator, encoding) { - _lookahead: function(number) { - return this.tokens[this.index + number].type; - }, + Assert(!encoding || Buffer && Buffer.isEncoding(encoding), 'Invalid encoding:', encoding); // $lab:coverage:ignore$ - _lookaheadToken: function(number) { - return this.tokens[this.index + number]; - }, + return schema.$_addRule({ name, method: 'length', args: { limit, encoding }, operator }); +}; - _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; - } - 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(); +/***/ }), + +/***/ 40971: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const Assert = __nccwpck_require__(32718); + +const Any = __nccwpck_require__(9512); + + +const internals = {}; + + +internals.Map = class extends Map { + + slice() { + + return new internals.Map(this); + } +}; + + +module.exports = Any.extend({ + + type: 'symbol', + + terms: { + + map: { init: new internals.Map() } + }, + + coerce: { + method(value, { schema, error }) { + + const lookup = schema.$_terms.map.get(value); + if (lookup) { + value = lookup; } - 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); + + if (!schema._flags.only || + typeof value === 'symbol') { + + return { value }; } - this._match(TOK_RPAREN); - return args[0]; - default: - this._errorToken(token); + + return { value, errors: error('symbol.map', { map: schema.$_terms.map }) }; } - }, + }, - 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); - } - 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); + validate(value, { error }) { + + if (typeof value !== 'symbol') { + return { value, errors: error('symbol.base') }; + } + }, + + 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'); + + 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; + + 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'); + + obj.$_terms.map.set(key, value); + symbols.push(value); + } + + return obj.valid(...symbols); } - 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]}; + } + }, + + manifest: { + + build(obj, desc) { + + if (desc.map) { + obj = obj.map(desc.map); } - break; - default: - this._errorToken(this._lookaheadToken(0)); + + return obj; } - }, + }, - _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; - } - }, + messages: { + 'symbol.base': '{{#label}} must be a symbol', + 'symbol.map': '{{#label}} must be one of {{#map}}' + } +}); - _errorToken: function(token) { - var error = new Error("Invalid token (" + - token.type + "): \"" + - token.value + "\""); - error.name = "ParserError"; - throw error; - }, +/***/ }), - _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; - } - }, +/***/ 91804: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - _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; - } - }, +"use strict"; - _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]}; - }, +const Assert = __nccwpck_require__(32718); +const Clone = __nccwpck_require__(85578); +const Ignore = __nccwpck_require__(12887); +const Reach = __nccwpck_require__(18891); - _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(); - } - }, +const Common = __nccwpck_require__(72448); +const Errors = __nccwpck_require__(69490); +const State = __nccwpck_require__(73634); - _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; - }, - _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}; - }, +const internals = { + result: Symbol('result') +}; - _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; - } + +exports.entry = function (value, schema, 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); + } + + 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 (result.error) { + outcome.error = result.error; + } + + if (result.mainstay.warnings.length) { + outcome.warning = Errors.details(result.mainstay.warnings); + } + + if (result.mainstay.debug) { + outcome.debug = result.mainstay.debug; + } + + if (result.mainstay.artifacts) { + outcome.artifacts = result.mainstay.artifacts; + } + + return outcome; +}; + + +exports.entryAsync = async function (value, schema, prefs) { + + let settings = Common.defaults; + if (prefs) { + settings = Common.preferences(Common.defaults, prefs); + } + + const result = internals.entry(value, schema, settings); + const mainstay = result.mainstay; + if (result.error) { + if (mainstay.debug) { + result.error.debug = mainstay.debug; } - return {type: "MultiSelectHash", children: pairs}; - } - }; + throw result.error; + } - function TreeInterpreter(runtime) { - this.runtime = runtime; - } + if (mainstay.externals.length) { + let root = result.value; + for (const { method, path, label } of mainstay.externals) { + let node = root; + let key; + let parent; - TreeInterpreter.prototype = { - search: function(node, value) { - return this.visit(node, value); - }, + if (path.length) { + key = path[path.length - 1]; + parent = Reach(root, path.slice(0, -1)); + node = parent[key]; + } - 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]); + try { + const output = await method(node, { prefs }); + if (output === undefined || + output === node) { + + continue; } - } - for (var j = 0; j < filtered.length; j++) { - current = this.visit(node.children[1], filtered[j]); - if (current !== null) { - finalResults.push(current); + + if (parent) { + parent[key] = output; } - } - 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 { + root = output; + } + } + catch (err) { + if (settings.errors.label) { + err.message += ` (${label})`; // Change message to include path } - } - 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); - } - }, + throw err; + } + } - 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; + result.value = root; + } + + if (!settings.warnings && + !settings.debug && + !settings.artifacts) { + + return result.value; + } + + const outcome = { value: result.value }; + if (mainstay.warnings.length) { + outcome.warning = Errors.details(mainstay.warnings); + } + + if (mainstay.debug) { + outcome.debug = mainstay.debug; + } + + if (mainstay.artifacts) { + outcome.artifacts = mainstay.artifacts; + } + + return outcome; +}; + + +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 + + if (cleanup) { + schema.$_root.untrace(); + } + + const error = Errors.process(result.errors, value, prefs); + return { value: result.value, error, mainstay }; +}; + + +internals.tracer = function (schema, prefs) { + + 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 }; + } + + return { tracer: internals.ignore }; +}; + + +exports.validate = function (value, schema, state, prefs, overrides = {}) { + + if (schema.$_terms.whens) { + schema = schema._generate(value, state, prefs).schema; + } + + // Setup state and settings + + if (schema._preferences) { + prefs = internals.prefs(schema, prefs); + } + + // Cache + + if (schema._cache && + prefs.cache) { + + const result = schema._cache.get(value); + state.mainstay.tracer.debug(state, 'validate', 'cached', !!result); + if (result) { + return result; } - var stepValueNegative = step < 0 ? true : false; + } - if (start === null) { - start = stepValueNegative ? arrayLength - 1 : 0; - } else { - start = this.capSliceRange(arrayLength, start, step); + // 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 }) + }; + + // Prepare + + state.mainstay.tracer.entry(schema, state); + + const def = schema._definition; + if (def.prepare && + value !== undefined && + prefs.convert) { + + 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 + } + + value = prepared.value; } + } - if (stop === null) { - stop = stepValueNegative ? -1 : arrayLength; - } else { - stop = this.capSliceRange(arrayLength, stop, step); + // 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; } - 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; - } + // Empty value - }; + const empty = schema._flags.empty; + if (empty && + empty.$_match(internals.trim(value, schema), state.nest(empty), Common.defaults)) { - 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}] + state.mainstay.tracer.value(state, 'empty', value, undefined); + value = undefined; + } + + // Presence requirements (required, optional, forbidden) + + 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); } - }; - } - 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); - }, + if (presence === 'required') { + return internals.finalize(value, [schema.$_createError('any.required', value, null, state, prefs)], helpers); + } - _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); + if (presence === 'optional') { + if (schema._flags.default !== Common.symbols.deepDefault) { + return internals.finalize(value, null, helpers); } - } 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); + + state.mainstay.tracer.value(state, 'default', value, {}); + value = {}; } - 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; - } + } + else if (presence === 'forbidden') { + return internals.finalize(value, [schema.$_createError('any.unknown', value, null, state, prefs)], helpers); + } + + // Allowed values + + const errors = []; + + 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 (!typeMatched) { - throw new Error("TypeError: " + name + "() " + - "expected argument " + (i + 1) + - " to be type " + currentSpec + - " but received type " + actualType + - " instead."); + + state.mainstay.tracer.filter(schema, state, 'valid', match); + return internals.finalize(value, null, helpers); + } + + 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); } + + errors.push(report); } - }, + } - _typeMatches: function(actual, expected, argValue) { - if (expected === TYPE_ANY) { - return true; + // Denied values + + 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 (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; + } + + // 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 } - for (var i = 0; i < argValue.length; i++) { - if (!this._typeMatches( - this._getTypeName(argValue[i]), subtype, - argValue[i])) { - return false; - } + + if (base.errors.length) { + errors.push(...base.errors); + return internals.finalize(value, errors, helpers); // Base error always aborts early } - return true; } - } 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; - } + } + + // Validate tests + + if (!schema._rules.length) { + return internals.finalize(value, errors, helpers); + } + + return internals.rules(value, errors, helpers); +}; + + +internals.rules = function (value, errors, helpers) { + + const { schema, state, prefs } = helpers; + + for (const rule of schema._rules) { + const definition = schema._definition.rules[rule.method]; + + // Skip rules that are also applied in coerce step + + if (definition.convert && + prefs.convert) { + + state.mainstay.tracer.log(schema, state, 'rule', rule.name, 'full'); + continue; } - }, - _functionStartsWith: function(resolvedArgs) { - return resolvedArgs[0].lastIndexOf(resolvedArgs[1]) === 0; - }, + // Resolve references + + 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 resolved = args[key].resolve(value, state, prefs); + const normalized = resolver.normalize ? resolver.normalize(resolved) : resolved; + + 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; + } + + args[key] = normalized; + } + } + + // Test rule + + ret = ret || definition.validate(value, helpers, args, rule); // Use ret if already set to reference error + + const result = internals.rule(ret, rule); + if (result.errors) { + state.mainstay.tracer.log(schema, state, 'rule', rule.name, 'error'); + + if (rule.warn) { + state.mainstay.warnings.push(...result.errors); + continue; + } + + if (prefs.abortEarly) { + return internals.finalize(value, result.errors, helpers); + } + + 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; + } + } + + 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 }; + } + + if (Array.isArray(ret) && + ret[Common.symbols.errors]) { + + ret.forEach((report) => internals.error(report, rule)); + return { errors: ret, value: null }; + } + + return { errors: null, value: ret }; +}; + + +internals.error = function (report, rule) { + + if (rule.message) { + report._setTemplate(rule.message); + } + + return report; +}; + + +internals.finalize = function (value, errors, helpers) { + + 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 = []; + } + } + + // 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 error of errors) { + Assert(error instanceof Error || error instanceof Errors.Report, 'error() must return an Error object'); + } + } + else { + errors = [schema._flags.error]; + } + } + + // Default + + if (value === undefined) { + const defaulted = internals.default('default', value, errors, helpers); + state.mainstay.tracer.value(state, 'default', value, defaulted); + value = defaulted; + } + + // Cast + + if (schema._flags.cast && + value !== undefined) { + + 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 + + if (schema.$_terms.externals && + prefs.externals && + prefs._externals !== false) { // Disabled for matching + + for (const { method } of schema.$_terms.externals) { + state.mainstay.externals.push({ method, path: state.path, label: Errors.label(schema._flags, state, prefs) }); + } + } + + // Result + + 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); + } + + // Cache + + if (schema._cache && + prefs.cache !== false && + !schema._refs.length) { + + schema._cache.set(helpers.original, result); + } + + // Artifacts + + if (value !== undefined && + !result.errors && + schema._flags.artifact !== undefined) { + + state.mainstay.artifacts = state.mainstay.artifacts || new Map(); + if (!state.mainstay.artifacts.has(schema._flags.artifact)) { + state.mainstay.artifacts.set(schema._flags.artifact, []); + } + + state.mainstay.artifacts.get(schema._flags.artifact).push(state.path); + } + + return result; +}; + + +internals.prefs = function (schema, prefs) { + + const isDefaultOptions = prefs === Common.defaults; + if (isDefaultOptions && + schema._preferences[Common.symbols.prefs]) { + + return schema._preferences[Common.symbols.prefs]; + } + + prefs = Common.preferences(prefs, schema._preferences); + if (isDefaultOptions) { + schema._preferences[Common.symbols.prefs] = prefs; + } + + return prefs; +}; + + +internals.default = function (flag, value, errors, helpers) { + + const { schema, state, prefs } = helpers; + const source = schema._flags[flag]; + if (prefs.noDefaults || + source === undefined) { + + return value; + } + + state.mainstay.tracer.log(schema, state, 'rule', flag, 'full'); + + if (!source) { + return source; + } + + if (typeof source === 'function') { + const args = source.length ? [Clone(state.ancestors[0]), helpers] : []; + + try { + return source(...args); + } + catch (err) { + errors.push(schema.$_createError(`any.${flag}`, null, { error: err }, state, prefs)); + return; + } + } + + if (typeof source !== 'object') { + return source; + } + + if (source[Common.symbols.literal]) { + return source.literal; + } + + if (Common.isResolvable(source)) { + return source.resolve(value, state, prefs); + } + + return Clone(source); +}; + + +internals.trim = function (value, schema) { + + if (typeof value !== 'string') { + return value; + } + + const trim = schema.$_getRule('trim'); + if (!trim || + !trim.args.enabled) { + + return value; + } + + return value.trim(); +}; + + +internals.ignore = { + active: false, + debug: Ignore, + entry: Ignore, + filter: Ignore, + log: Ignore, + resolve: Ignore, + value: Ignore +}; + + +internals.errorsArray = function () { + + const errors = []; + errors[Common.symbols.errors] = true; + return errors; +}; + + +/***/ }), + +/***/ 71944: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const Assert = __nccwpck_require__(32718); +const DeepEqual = __nccwpck_require__(55801); + +const Common = __nccwpck_require__(72448); + + +const internals = {}; + + +module.exports = internals.Values = class { - _functionEndsWith: function(resolvedArgs) { - var searchStr = resolvedArgs[0]; - var suffix = resolvedArgs[1]; - return searchStr.indexOf(suffix, searchStr.length - suffix.length) !== -1; - }, + constructor(values, refs) { - _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; + this._values = new Set(values); + this._refs = new Set(refs); + this._lowercase = internals.lowercases(values); + + this._override = false; + } + + get length() { + + return this._values.size + this._refs.size; + } + + add(value, refs) { + + // Reference + + if (Common.isResolvable(value)) { + if (!this._refs.has(value)) { + this._refs.add(value); + + if (refs) { // Skipped in a merge + refs.register(value); + } + } + + return; } - }, - _functionAbs: function(resolvedArgs) { - return Math.abs(resolvedArgs[0]); - }, + // Value - _functionCeil: function(resolvedArgs) { - return Math.ceil(resolvedArgs[0]); - }, + if (!this.has(value, null, null, false)) { + this._values.add(value); - _functionAvg: function(resolvedArgs) { - var sum = 0; - var inputArray = resolvedArgs[0]; - for (var i = 0; i < inputArray.length; i++) { - sum += inputArray[i]; + if (typeof value === 'string') { + this._lowercase.set(value.toLowerCase(), value); + } } - return sum / inputArray.length; - }, + } - _functionContains: function(resolvedArgs) { - return resolvedArgs[0].indexOf(resolvedArgs[1]) >= 0; - }, + static merge(target, source, remove) { - _functionFloor: function(resolvedArgs) { - return Math.floor(resolvedArgs[0]); - }, + target = target || new internals.Values(); - _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 (source) { + if (source._override) { + return source.clone(); + } - _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; - }, + for (const item of [...source._values, ...source._refs]) { + target.add(item); + } + } - _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]; + if (remove) { + for (const item of [...remove._values, ...remove._refs]) { + target.remove(item); + } } - } - 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; + return target.length ? target : null; + } + + remove(value) { + + // Reference + + if (Common.isResolvable(value)) { + this._refs.delete(value); + return; } - } 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; + // Value + + this._values.delete(value); + + if (typeof value === 'string') { + this._lowercase.delete(value.toLowerCase()); } - } 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; - }, + has(value, state, prefs, insensitive) { - _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"; + return !!this.get(value, state, prefs, insensitive); + } + + get(value, state, prefs, insensitive) { + + if (!this.length) { + return false; } - }, - _functionKeys: function(resolvedArgs) { - return Object.keys(resolvedArgs[0]); - }, + // Simple match - _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]]); + if (this._values.has(value)) { + return { value }; } - return values; - }, - _functionJoin: function(resolvedArgs) { - var joinChar = resolvedArgs[0]; - var listJoin = resolvedArgs[1]; - return listJoin.join(joinChar); - }, + // Case insensitive string match - _functionToArray: function(resolvedArgs) { - if (this._getTypeName(resolvedArgs[0]) === TYPE_ARRAY) { - return resolvedArgs[0]; - } else { - return [resolvedArgs[0]]; + if (typeof value === 'string' && + value && + insensitive) { + + const found = this._lowercase.get(value.toLowerCase()); + if (found) { + return { value: found }; + } } - }, - _functionToString: function(resolvedArgs) { - if (this._getTypeName(resolvedArgs[0]) === TYPE_STRING) { - return resolvedArgs[0]; - } else { - return JSON.stringify(resolvedArgs[0]); + if (!this._refs.size && + typeof value !== 'object') { + + return false; } - }, - _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; + // Objects + + if (typeof value === 'object') { + for (const item of this._values) { + if (DeepEqual(item, value)) { + return { value: item }; + } } } - return null; - }, - _functionNotNull: function(resolvedArgs) { - for (var i = 0; i < resolvedArgs.length; i++) { - if (this._getTypeName(resolvedArgs[i]) !== TYPE_NULL) { - return resolvedArgs[i]; + // References + + if (state) { + for (const ref of this._refs) { + const resolved = ref.resolve(value, state, prefs, null, { in: true }); + if (resolved === undefined) { + continue; + } + + const items = !ref.in || typeof resolved !== 'object' + ? [resolved] + : Array.isArray(resolved) ? resolved : Object.keys(resolved); + + for (const item of items) { + if (typeof item !== typeof value) { + continue; + } + + if (insensitive && + value && + typeof value === 'string') { + + if (item.toLowerCase() === value.toLowerCase()) { + return { value: item, ref }; + } + } + else { + if (DeepEqual(item, value)) { + return { value: item, ref }; + } + } + } } } - return null; - }, - _functionSort: function(resolvedArgs) { - var sortedArray = resolvedArgs[0].slice(0); - sortedArray.sort(); - return sortedArray; - }, + return false; + } - _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]; + override() { + + this._override = true; + } + + values(options) { + + if (options && + options.display) { + + const values = []; + + for (const item of [...this._values, ...this._refs]) { + if (item !== undefined) { + values.push(item); + } + } + + return values; } - 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]; + return Array.from([...this._values, ...this._refs]); + } + + clone() { + + const set = new internals.Values(this._values, this._refs); + set._override = this._override; + return set; + } + + concat(source) { + + Assert(!source._override, 'Cannot concat override set of values'); + + const set = new internals.Values([...this._values, ...source._values], [...this._refs, ...source._refs]); + set._override = this._override; + return set; + } + + describe() { + + const normalized = []; + + if (this._override) { + normalized.push({ override: 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]; + for (const value of this._values.values()) { + normalized.push(value && typeof value === 'object' ? { value } : value); } - } - 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); + for (const value of this._refs.values()) { + normalized.push(value.describe()); } - return current; - }; - return keyFunc; + + return normalized; } +}; - }; - function compile(stream) { - var parser = new Parser(); - var ast = parser.parse(stream); - return ast; - } +internals.Values.prototype[Common.symbols.values] = true; - 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); - } +// Aliases - exports.tokenize = tokenize; - exports.compile = compile; - exports.search = search; - exports.strictDeepEqual = strictDeepEqual; -})( false ? 0 : exports); +internals.Values.prototype.slice = internals.Values.prototype.clone; + + +// Helpers + +internals.lowercases = function (from) { + + const map = new Map(); + + if (from) { + for (const value of from) { + if (typeof value === 'string') { + map.set(value.toLowerCase(), value); + } + } + } + + return map; +}; /***/ }), @@ -99111,7 +103762,7 @@ const { prettifyTime } = __nccwpck_require__(24694) -const bourne = __nccwpck_require__(97151) +const bourne = __nccwpck_require__(97174) const jsonParser = input => { try { return { value: bourne.parse(input, { protoAction: 'remove' }) } @@ -99776,101 +104427,6 @@ function prettifyTime ({ log, timestampKey = TIMESTAMP_KEY, translateFormat = un } -/***/ }), - -/***/ 97151: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - - -const internals = { - suspectRx: /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*\:/ -}; - - -exports.parse = function (text, ...args) { - - // Normalize arguments - - const firstOptions = typeof args[0] === 'object' && args[0]; - const reviver = args.length > 1 || !firstOptions ? args[0] : undefined; - const options = (args.length > 1 && args[1]) || firstOptions || {}; - - // Parse normally, allowing exceptions - - const obj = JSON.parse(text, reviver); - - // options.protoAction: 'error' (default) / 'remove' / 'ignore' - - if (options.protoAction === 'ignore') { - return obj; - } - - // Ignore null and non-objects - - if (!obj || - typeof obj !== 'object') { - - return obj; - } - - // Check original string for potential exploit - - if (!text.match(internals.suspectRx)) { - return obj; - } - - // Scan result for proto keys - - exports.scan(obj, options); - - return obj; -}; - - -exports.scan = function (obj, options = {}) { - - let next = [obj]; - - while (next.length) { - const nodes = next; - next = []; - - for (const node of nodes) { - if (Object.prototype.hasOwnProperty.call(node, '__proto__')) { // Avoid calling node.hasOwnProperty directly - if (options.protoAction !== 'remove') { - throw new SyntaxError('Object contains forbidden prototype property'); - } - - delete node.__proto__; - } - - for (const key in node) { - const value = node[key]; - if (value && - typeof value === 'object') { - - next.push(node[key]); - } - } - } - } -}; - - -exports.safeParse = function (text, reviver) { - - try { - return exports.parse(text, reviver); - } - catch (ignoreError) { - return null; - } -}; - - /***/ }), /***/ 72571: @@ -118434,7 +122990,7 @@ exports.updateRelease = updateRelease /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { const _ = __nccwpck_require__(90250) -const Joi = __nccwpck_require__(44010) +const Joi = __nccwpck_require__(20918) const { SORT_BY, SORT_DIRECTIONS } = __nccwpck_require__(11940) const { DEFAULT_CONFIG } = __nccwpck_require__(85869) const { @@ -118516,7 +123072,9 @@ const schema = (context) => { search: Joi.string() .required() .error( - () => '"search" is required and must be a regexp or a string' + new Error( + '"search" is required and must be a regexp or a string' + ) ), replace: Joi.string().allow('').required(), }) @@ -118958,14 +123516,6 @@ const getVersionInfo = ( exports.getVersionInfo = getVersionInfo -/***/ }), - -/***/ 86251: -/***/ ((module) => { - -"use strict"; -module.exports = JSON.parse('{"name":"@hapi/joi","description":"Object schema validation","version":"15.1.1","homepage":"https://github.com/hapijs/joi","repository":"git://github.com/hapijs/joi","main":"lib/index.js","keywords":["schema","validation"],"dependencies":{"@hapi/address":"2.x.x","@hapi/bourne":"1.x.x","@hapi/hoek":"8.x.x","@hapi/topo":"3.x.x"},"devDependencies":{"@hapi/code":"6.x.x","@hapi/lab":"20.x.x"},"scripts":{"test":"lab -t 100 -a @hapi/code -L","test-cov-html":"lab -r html -o coverage.html -a @hapi/code"},"license":"BSD-3-Clause"}'); - /***/ }), /***/ 31936: @@ -119056,6 +123606,14 @@ module.exports = JSON.parse('{"assert":true,"assert/strict":">= 15","async_hooks /***/ }), +/***/ 77045: +/***/ ((module) => { + +"use strict"; +module.exports = JSON.parse('{"name":"joi","description":"Object schema validation","version":"17.5.0","repository":"git://github.com/sideway/joi","main":"lib/index.js","types":"lib/index.d.ts","browser":"dist/joi-browser.min.js","files":["lib/**/*","dist/*"],"keywords":["schema","validation"],"dependencies":{"@hapi/hoek":"^9.0.0","@hapi/topo":"^5.0.0","@sideway/address":"^4.1.3","@sideway/formula":"^3.0.0","@sideway/pinpoint":"^2.0.0"},"devDependencies":{"@hapi/bourne":"2.x.x","@hapi/code":"8.x.x","@hapi/joi-legacy-test":"npm:@hapi/joi@15.x.x","@hapi/lab":"24.x.x","typescript":"4.3.x"},"scripts":{"prepublishOnly":"cd browser && npm install && npm run build","test":"lab -t 100 -a @hapi/code -L -Y","test-cov-html":"lab -r html -o coverage.html -a @hapi/code"},"license":"BSD-3-Clause"}'); + +/***/ }), + /***/ 53765: /***/ ((module) => { diff --git a/lib/schema.js b/lib/schema.js index 6bbfde658..849816265 100644 --- a/lib/schema.js +++ b/lib/schema.js @@ -1,5 +1,5 @@ const _ = require('lodash') -const Joi = require('@hapi/joi') +const Joi = require('joi') const { SORT_BY, SORT_DIRECTIONS } = require('./sort-pull-requests') const { DEFAULT_CONFIG } = require('./default-config') const { @@ -81,7 +81,9 @@ const schema = (context) => { search: Joi.string() .required() .error( - () => '"search" is required and must be a regexp or a string' + new Error( + '"search" is required and must be a regexp or a string' + ) ), replace: Joi.string().allow('').required(), }) diff --git a/package.json b/package.json index b7922dd08..0ea86011f 100644 --- a/package.json +++ b/package.json @@ -23,19 +23,20 @@ }, "dependencies": { "@actions/core": "1.6.0", - "@hapi/joi": "15.1.1", "@probot/adapter-github-actions": "3.1.0", "cli-table3": "0.6.1", "compare-versions": "4.1.3", "deepmerge": "4.2.2", "escape-string-regexp": "4.0.0", "ignore": "5.2.0", + "joi": "17.5.0", "lodash": "4.17.21", "probot": "12.2.0", "regex-parser": "2.2.11", "semver": "7.3.5" }, "devDependencies": { + "@koa-lite/joi-schema": "0.0.1", "@vercel/ncc": "0.33.1", "eslint": "8.7.0", "eslint-config-prettier": "8.3.0", @@ -43,7 +44,6 @@ "eslint-plugin-unicorn": "^40.0.0", "husky": "7.0.4", "jest": "27.4.7", - "joi-to-json-schema": "^5.1.0", "lint-staged": "12.2.0", "mocked-env": "^1.3.5", "nock": "13.2.2", diff --git a/test/schema.test.js b/test/schema.test.js index 75ac33999..8a69c766f 100644 --- a/test/schema.test.js +++ b/test/schema.test.js @@ -49,7 +49,7 @@ describe('schema', () => { const { error, value } = schema(context).validate(example, { abortEarly: false, }) - expect(error).toBeNull() + expect(error).toBeUndefined() expect(value).toMatchObject(expected) if (value.replacers) { for (const [index, arrayValue] of value.replacers.entries()) diff --git a/yarn.lock b/yarn.lock index b39e45fa6..410cb7546 100644 --- a/yarn.lock +++ b/yarn.lock @@ -484,42 +484,22 @@ minimatch "^3.0.4" strip-json-comments "^3.1.1" -"@hapi/address@2.x.x": - version "2.1.4" - resolved "https://registry.yarnpkg.com/@hapi/address/-/address-2.1.4.tgz#5d67ed43f3fd41a69d4b9ff7b56e7c0d1d0a81e5" - integrity sha512-QD1PhQk+s31P1ixsX0H0Suoupp3VMXzIVMSwobR3F3MSUO2YCV0B7xqLcUw/Bh8yuvd3LhpyqLQWTNcRmp6IdQ== - -"@hapi/bourne@1.x.x": - version "1.3.2" - resolved "https://registry.yarnpkg.com/@hapi/bourne/-/bourne-1.3.2.tgz#0a7095adea067243ce3283e1b56b8a8f453b242a" - integrity sha512-1dVNHT76Uu5N3eJNTYcvxee+jzX4Z9lfciqRRHCU27ihbUcYi+iSc2iml5Ke1LXe1SyJCLA0+14Jh4tXJgOppA== - "@hapi/bourne@^2.0.0": version "2.0.0" resolved "https://registry.yarnpkg.com/@hapi/bourne/-/bourne-2.0.0.tgz#5bb2193eb685c0007540ca61d166d4e1edaf918d" integrity sha512-WEezM1FWztfbzqIUbsDzFRVMxSoLy3HugVcux6KDDtTqzPsLE8NDRHfXvev66aH1i2oOKKar3/XDjbvh/OUBdg== -"@hapi/hoek@8.x.x", "@hapi/hoek@^8.3.0": - version "8.5.0" - resolved "https://registry.yarnpkg.com/@hapi/hoek/-/hoek-8.5.0.tgz#2f9ce301c8898e1c3248b0a8564696b24d1a9a5a" - integrity sha512-7XYT10CZfPsH7j9F1Jmg1+d0ezOux2oM2GfArAzLwWe4mE2Dr3hVjsAL6+TFY49RRJlCdJDMw3nJsLFroTc8Kw== - -"@hapi/joi@15.1.1": - version "15.1.1" - resolved "https://registry.yarnpkg.com/@hapi/joi/-/joi-15.1.1.tgz#c675b8a71296f02833f8d6d243b34c57b8ce19d7" - integrity sha512-entf8ZMOK8sc+8YfeOlM8pCfg3b5+WZIKBfUaaJT8UsjAAPjartzxIYm3TIbjvA4u+u++KbcXD38k682nVHDAQ== - dependencies: - "@hapi/address" "2.x.x" - "@hapi/bourne" "1.x.x" - "@hapi/hoek" "8.x.x" - "@hapi/topo" "3.x.x" +"@hapi/hoek@^9.0.0": + version "9.2.1" + resolved "https://registry.yarnpkg.com/@hapi/hoek/-/hoek-9.2.1.tgz#9551142a1980503752536b5050fd99f4a7f13b17" + integrity sha512-gfta+H8aziZsm8pZa0vj04KO6biEiisppNgA1kbJvFrrWu9Vm7eaUEy76DIxsuTaWvti5fkJVhllWc6ZTE+Mdw== -"@hapi/topo@3.x.x": - version "3.1.6" - resolved "https://registry.yarnpkg.com/@hapi/topo/-/topo-3.1.6.tgz#68d935fa3eae7fdd5ab0d7f953f3205d8b2bfc29" - integrity sha512-tAag0jEcjwH+P2quUfipd7liWCNX2F8NvYjQp2wtInsZxnMlypdw0FtAOLxtvvkO+GSRRbmNi8m/5y42PQJYCQ== +"@hapi/topo@^5.0.0": + version "5.1.0" + resolved "https://registry.yarnpkg.com/@hapi/topo/-/topo-5.1.0.tgz#dc448e332c6c6e37a4dc02fd84ba8d44b9afb012" + integrity sha512-foQZKJig7Ob0BMAYBfcJk8d77QtOe7Wo4ox7ff1lQYoNNAb6jwcY1ncdoy2e9wQZzvNy7ODZCYJkK8kzmcAnAg== dependencies: - "@hapi/hoek" "^8.3.0" + "@hapi/hoek" "^9.0.0" "@humanwhocodes/config-array@^0.9.2": version "0.9.2" @@ -719,6 +699,13 @@ "@types/yargs" "^16.0.0" chalk "^4.0.0" +"@koa-lite/joi-schema@0.0.1": + version "0.0.1" + resolved "https://registry.yarnpkg.com/@koa-lite/joi-schema/-/joi-schema-0.0.1.tgz#3f7dd083af81b082b895aad8804ea75cff3cda09" + integrity sha512-t7PcCPAz6pThH8SiaKBJXG/V97Yg9Yuhx6zJ7xLFM7fqHaw6oE8RCvD06t9yfF/mrDuoliYrvrmqY6luNm/XkA== + dependencies: + joi "^17.4.0" + "@octokit/auth-app@^2.10.4": version "2.10.5" resolved "https://registry.yarnpkg.com/@octokit/auth-app/-/auth-app-2.10.5.tgz#85d69cb96818f5da34bf0b81bb637d3675ad4e9a" @@ -990,6 +977,23 @@ "@sentry/types" "5.29.2" tslib "^1.9.3" +"@sideway/address@^4.1.3": + version "4.1.3" + resolved "https://registry.yarnpkg.com/@sideway/address/-/address-4.1.3.tgz#d93cce5d45c5daec92ad76db492cc2ee3c64ab27" + integrity sha512-8ncEUtmnTsMmL7z1YPB47kPUq7LpKWJNFPsRzHiIajGC5uXlWGn+AmkYPcHNl8S4tcEGx+cnORnNYaw2wvL+LQ== + dependencies: + "@hapi/hoek" "^9.0.0" + +"@sideway/formula@^3.0.0": + version "3.0.0" + resolved "https://registry.yarnpkg.com/@sideway/formula/-/formula-3.0.0.tgz#fe158aee32e6bd5de85044be615bc08478a0a13c" + integrity sha512-vHe7wZ4NOXVfkoRb8T5otiENVlT7a3IAiw7H5M2+GO+9CDgcVUUsX1zalAztCmwyOr2RUTGJdgB+ZvSVqmdHmg== + +"@sideway/pinpoint@^2.0.0": + version "2.0.0" + resolved "https://registry.yarnpkg.com/@sideway/pinpoint/-/pinpoint-2.0.0.tgz#cff8ffadc372ad29fd3f78277aeb29e632cc70df" + integrity sha512-RNiOoTPkptFtSVzQevY/yWtZwf/RxyVnPy/OcA9HBM3MlGDnBEYL5B41H0MTn0Uec8Hi+2qUtTfG2WWZBmMejQ== + "@sindresorhus/is@^0.14.0": version "0.14.0" resolved "https://registry.yarnpkg.com/@sindresorhus/is/-/is-0.14.0.tgz#9fb3a3cf3132328151f353de4632e01e52102bea" @@ -3558,10 +3562,16 @@ jmespath@^0.15.0: resolved "https://registry.yarnpkg.com/jmespath/-/jmespath-0.15.0.tgz#a3f222a9aae9f966f5d27c796510e28091764217" integrity sha1-o/Iiqarp+Wb10nx5ZRDigJF2Qhc= -joi-to-json-schema@^5.1.0: - version "5.1.0" - resolved "https://registry.yarnpkg.com/joi-to-json-schema/-/joi-to-json-schema-5.1.0.tgz#5cf2aa05c8d63a0a0a480661b7c4f3c65fa5707d" - integrity sha512-suSQS0zGdkIgnxKuc9huX+J/+RGtADNmp7Uh6HdCpkguN0Lxhy+7MT7d/BtQW4IBaYv/5AeR4uADN3m6BijQtw== +joi@17.5.0, joi@^17.4.0: + version "17.5.0" + resolved "https://registry.yarnpkg.com/joi/-/joi-17.5.0.tgz#7e66d0004b5045d971cf416a55fb61d33ac6e011" + integrity sha512-R7hR50COp7StzLnDi4ywOXHrBrgNXuUUfJWIR5lPY5Bm/pOD3jZaTwpluUXVLRWcoWZxkrHBBJ5hLxgnlehbdw== + dependencies: + "@hapi/hoek" "^9.0.0" + "@hapi/topo" "^5.0.0" + "@sideway/address" "^4.1.3" + "@sideway/formula" "^3.0.0" + "@sideway/pinpoint" "^2.0.0" joycon@^2.2.5: version "2.2.5"