diff --git a/dist/index.js b/dist/index.js index 7e2f93f63..ddf95a593 100644 --- a/dist/index.js +++ b/dist/index.js @@ -1275,1963 +1275,2192 @@ exports.checkBypass = checkBypass; /***/ }), -/***/ 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*\:/ -}; - +/***/ 14175: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -exports.parse = function (text, ...args) { +/* - // Normalize arguments +The MIT License (MIT) - 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 || {}; +Original Library + - Copyright (c) Marak Squires - // Parse normally, allowing exceptions +Additional functionality + - Copyright (c) Sindre Sorhus (sindresorhus.com) - const obj = JSON.parse(text, reviver); +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: - // options.protoAction: 'error' (default) / 'remove' / 'ignore' +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. - if (options.protoAction === 'ignore') { - return obj; - } +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. - // Ignore null and non-objects +*/ - if (!obj || - typeof obj !== 'object') { +var colors = {}; +module['exports'] = colors; - return obj; - } +colors.themes = {}; - // Check original string for potential exploit +var util = __nccwpck_require__(73837); +var ansiStyles = colors.styles = __nccwpck_require__(95691); +var defineProps = Object.defineProperties; +var newLineRegex = new RegExp(/[\r\n]+/g); - if (!text.match(internals.suspectRx)) { - return obj; - } +colors.supportsColor = (__nccwpck_require__(21959).supportsColor); - // Scan result for proto keys +if (typeof colors.enabled === 'undefined') { + colors.enabled = colors.supportsColor() !== false; +} - exports.scan(obj, options); +colors.enable = function() { + colors.enabled = true; +}; - return obj; +colors.disable = function() { + colors.enabled = false; }; +colors.stripColors = colors.strip = function(str) { + return ('' + str).replace(/\x1B\[\d+m/g, ''); +}; -exports.scan = function (obj, options = {}) { +// eslint-disable-next-line no-unused-vars +var stylize = colors.stylize = function stylize(str, style) { + if (!colors.enabled) { + return str+''; + } - let next = [obj]; + var styleMap = ansiStyles[style]; - while (next.length) { - const nodes = next; - next = []; + // 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); + } - 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'); - } + return styleMap.open + str + styleMap.close; +}; - delete node.__proto__; - } +var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; +var escapeStringRegexp = function(str) { + if (typeof str !== 'string') { + throw new TypeError('Expected a string'); + } + return str.replace(matchOperatorsRe, '\\$&'); +}; - for (const key in node) { - const value = node[key]; - if (value && - typeof value === 'object') { +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; +} - next.push(node[key]); - } - } - } - } -}; +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; +})(); +var proto = defineProps(function colors() {}, styles); -exports.safeParse = function (text, reviver) { +function applyStyle() { + var args = Array.prototype.slice.call(arguments); - try { - return exports.parse(text, reviver); - } - catch (ignoreError) { - return null; + 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(' '); -/***/ }), + if (!colors.enabled || !str) { + return str; + } -/***/ 85545: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + var newLinesPresent = str.indexOf('\n') != -1; -"use strict"; + var nestedStyles = this._styles; + 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; + }); + } + } -const Assert = __nccwpck_require__(32718); -const Clone = __nccwpck_require__(85578); -const Merge = __nccwpck_require__(60445); -const Reach = __nccwpck_require__(18891); + 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); + } +}; -const internals = {}; +function init() { + var ret = {}; + Object.keys(styles).forEach(function(name) { + ret[name] = { + get: function() { + return build([name]); + }, + }; + }); + return ret; +} +var sequencer = function sequencer(map, str) { + var exploded = str.split(''); + exploded = exploded.map(map); + return exploded.join(''); +}; -module.exports = function (defaults, source, options = {}) { +// custom formatter methods +colors.trap = __nccwpck_require__(29493); +colors.zalgo = __nccwpck_require__(80090); - 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'); +// maps +colors.maps = {}; +colors.maps.america = __nccwpck_require__(29337)(colors); +colors.maps.zebra = __nccwpck_require__(3792)(colors); +colors.maps.rainbow = __nccwpck_require__(19565)(colors); +colors.maps.random = __nccwpck_require__(78212)(colors); - if (!source) { // If no source, return null - return null; - } +for (var map in colors.maps) { + (function(map) { + colors[map] = function(str) { + return sequencer(colors.maps[map], str); + }; + })(map); +} - if (options.shallow) { - return internals.applyToDefaultsWithShallow(defaults, source, options); - } +defineProps(colors, init()); - 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 }); -}; +/***/ 29493: +/***/ ((module) => { +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; +}; -internals.applyToDefaultsWithShallow = function (defaults, source, options) { - const keys = options.shallow; - Assert(Array.isArray(keys), 'Invalid keys'); +/***/ }), - const seen = new Map(); - const merge = source === true ? null : new Set(); +/***/ 80090: +/***/ ((module) => { - for (let key of keys) { - key = Array.isArray(key) ? key : key.split('.'); // Pre-split optimization +// 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); - const ref = Reach(defaults, key); - if (ref && - typeof ref === 'object') { + function randomNumber(range) { + var r = Math.floor(Math.random() * range); + return r; + } - seen.set(ref, merge && Reach(source, key) || ref); - } - else if (merge) { - merge.add(key); - } - } + function isChar(character) { + var bool = false; + all.filter(function(i) { + bool = (i === character); + }); + return bool; + } - const copy = Clone(defaults, {}, seen); - if (!merge) { - return copy; - } + 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; + } - for (const key of merge) { - internals.reachCopy(copy, source, key); + 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)]; + } + } + } } - - const nullOverride = options.nullOverride !== undefined ? options.nullOverride : false; - return Merge(copy, source, { nullOverride, mergeArrays: false }); + return result; + } + // don't summon him + return heComes(text, options); }; -internals.reachCopy = function (dst, src, path) { - - for (const segment of path) { - if (!(segment in src)) { - return; - } - - const val = src[segment]; - - if (typeof val !== 'object' || val === null) { - return; - } - src = val; - } +/***/ }), - 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] = {}; - } +/***/ 29337: +/***/ ((module) => { - ref = ref[segment]; +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); } - - ref[path[path.length - 1]] = value; + }; }; /***/ }), -/***/ 32718: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 19565: +/***/ ((module) => { -"use strict"; +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); + } + }; +}; -const AssertError = __nccwpck_require__(35563); -const internals = {}; +/***/ }), +/***/ 78212: +/***/ ((module) => { -module.exports = function (condition, ...args) { +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); + }; +}; - if (condition) { - return; - } - if (args.length === 1 && - args[0] instanceof Error) { +/***/ }), - throw args[0]; - } +/***/ 3792: +/***/ ((module) => { - throw new AssertError(args); +module['exports'] = function(colors) { + return function(letter, i, exploded) { + return i % 2 === 0 ? letter : colors.inverse(letter); + }; }; /***/ }), -/***/ 85578: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 95691: +/***/ ((module) => { -"use strict"; +/* +The MIT License (MIT) +Copyright (c) Sindre Sorhus (sindresorhus.com) -const Reach = __nccwpck_require__(18891); -const Types = __nccwpck_require__(84340); -const Utils = __nccwpck_require__(30417); +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. -const internals = { - needsProtoHack: new Set([Types.set, Types.map, Types.weakSet, Types.weakMap]) -}; +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 = internals.clone = function (obj, options = {}, _seen = null) { +var styles = {}; +module['exports'] = styles; - if (typeof obj !== 'object' || - obj === null) { +var codes = { + reset: [0, 0], - return obj; - } + bold: [1, 22], + dim: [2, 22], + italic: [3, 23], + underline: [4, 24], + inverse: [7, 27], + hidden: [8, 28], + strikethrough: [9, 29], - let clone = internals.clone; - let seen = _seen; + 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], - if (options.shallow) { - if (options.shallow !== true) { - return internals.cloneWithShallow(obj, options); - } + brightRed: [91, 39], + brightGreen: [92, 39], + brightYellow: [93, 39], + brightBlue: [94, 39], + brightMagenta: [95, 39], + brightCyan: [96, 39], + brightWhite: [97, 39], - clone = (value) => value; - } - else if (seen) { - const lookup = seen.get(obj); - if (lookup) { - return lookup; - } - } - else { - seen = new Map(); - } + 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], - // Built-in object types + bgBrightRed: [101, 49], + bgBrightGreen: [102, 49], + bgBrightYellow: [103, 49], + bgBrightBlue: [104, 49], + bgBrightMagenta: [105, 49], + bgBrightCyan: [106, 49], + bgBrightWhite: [107, 49], - const baseProto = Types.getInternalProto(obj); - if (baseProto === Types.buffer) { - return Buffer && Buffer.from(obj); // $lab:coverage:ignore$ - } + // 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], - if (baseProto === Types.date) { - return new Date(obj.getTime()); - } +}; - if (baseProto === Types.regex) { - return new RegExp(obj); - } +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'; +}); - // 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 - } +/***/ 63680: +/***/ ((module) => { - 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)); - } - } +"use strict"; +/* +MIT License - const keys = Utils.keys(obj, options); - for (const key of keys) { - if (key === '__proto__') { - continue; - } +Copyright (c) Sindre Sorhus (sindresorhus.com) - if (baseProto === Types.array && - key === 'length') { +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: - newObj.length = obj.length; - continue; - } +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. - const descriptor = Object.getOwnPropertyDescriptor(obj, key); - if (descriptor) { - if (descriptor.get || - descriptor.set) { +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. +*/ - 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; -}; +module.exports = function(flag, argv) { + argv = argv || process.argv; -internals.cloneWithShallow = function (source, options) { + var terminatorPos = argv.indexOf('--'); + var prefix = /^-{1,2}/.test(flag) ? '' : '--'; + var pos = argv.indexOf(prefix + flag); - const keys = options.shallow; - options = Object.assign({}, options); - options.shallow = false; + return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos); +}; - const seen = new Map(); - for (const key of keys) { - const ref = Reach(source, key); - if (typeof ref === 'object' || - typeof ref === 'function') { +/***/ }), - seen.set(ref, ref); - } - } +/***/ 21959: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return internals.clone(source, options, seen); -}; +"use strict"; +/* +The MIT License (MIT) +Copyright (c) Sindre Sorhus (sindresorhus.com) -internals.base = function (obj, baseProto, options) { +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 (options.prototype === false) { // Defaults to true - if (internals.needsProtoHack.has(baseProto)) { - return new baseProto.constructor(); - } +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. - return baseProto === Types.array ? [] : {}; - } +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. - const proto = Object.getPrototypeOf(obj); - if (proto && - proto.isImmutable) { +*/ - return obj; - } - if (baseProto === Types.array) { - const newObj = []; - if (proto !== baseProto) { - Object.setPrototypeOf(newObj, proto); - } - return newObj; - } +var os = __nccwpck_require__(22037); +var hasFlag = __nccwpck_require__(63680); - if (internals.needsProtoHack.has(baseProto)) { - const newObj = new proto.constructor(); - if (proto !== baseProto) { - Object.setPrototypeOf(newObj, proto); - } +var env = process.env; - return newObj; +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; +} + +function translateLevel(level) { + if (level === 0) { + return false; + } + + return { + level: level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3, + }; +} + +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; + } + + if (stream && !stream.isTTY && forceColor !== true) { + return 0; + } + + 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 Object.create(proto); -}; + return 1; + } + if ('CI' in env) { + if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(function(sign) { + return sign in env; + }) || env.CI_NAME === 'codeship') { + return 1; + } -/***/ }), + return min; + } -/***/ 55801: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if ('TEAMCITY_VERSION' in env) { + return (/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0 + ); + } -"use strict"; + 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 + } + } -const Types = __nccwpck_require__(84340); + if (/-256(color)?$/i.test(env.TERM)) { + return 2; + } + if (/^screen|^xterm|^vt100|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { + return 1; + } -const internals = { - mismatched: null -}; + if ('COLORTERM' in env) { + return 1; + } + if (env.TERM === 'dumb') { + return min; + } -module.exports = function (obj, ref, options) { + return min; +} - options = Object.assign({ prototype: true }, options); +function getSupportLevel(stream) { + var level = supportsColor(stream); + return translateLevel(level); +} - return !!internals.isDeepEqual(obj, ref, options, []); +module.exports = { + supportsColor: getSupportLevel, + stdout: getSupportLevel(process.stdout), + stderr: getSupportLevel(process.stderr), }; -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; - } +/***/ 59256: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - const type = typeof obj; +// +// 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__(14175); +module['exports'] = colors; - if (type !== typeof ref) { - return false; - } - if (obj === null || - ref === null) { +/***/ }), - return false; - } +/***/ 97174: +/***/ ((__unused_webpack_module, exports) => { - if (type === 'function') { - if (!options.deepFunction || - obj.toString() !== ref.toString()) { +"use strict"; - 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; - } +const internals = { + suspectRx: /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*\:/ +}; - 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)); +exports.parse = function (text, ...args) { - try { - return !!internals.isDeepEqualObj(instanceType, obj, ref, options, seen); - } - finally { - seen.pop(); - } -}; + // 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 || {}; -internals.getSharedType = function (obj, ref, checkPrototype) { + // Parse normally, allowing exceptions - if (checkPrototype) { - if (Object.getPrototypeOf(obj) !== Object.getPrototypeOf(ref)) { - return internals.mismatched; - } + const obj = JSON.parse(text, reviver); - return Types.getInternalProto(obj); - } + // options.protoAction: 'error' (default) / 'remove' / 'ignore' - const type = Types.getInternalProto(obj); - if (type !== Types.getInternalProto(ref)) { - return internals.mismatched; + if (options.protoAction === 'ignore') { + return obj; } - return type; -}; - + // Ignore null and non-objects -internals.valueOf = function (obj) { + if (!obj || + typeof obj !== 'object') { - const objValueOf = obj.valueOf; - if (objValueOf === undefined) { return obj; } - try { - return objValueOf.call(obj); - } - catch (err) { - return err; + // Check original string for potential exploit + + if (!text.match(internals.suspectRx)) { + return obj; } -}; + // Scan result for proto keys -internals.hasOwnEnumerableProperty = function (obj, key) { + exports.scan(obj, options); - return Object.prototype.propertyIsEnumerable.call(obj, key); + return obj; }; -internals.isSetSimpleEqual = function (obj, ref) { +exports.scan = function (obj, options = {}) { - for (const entry of Set.prototype.values.call(obj)) { - if (!Set.prototype.has.call(ref, entry)) { - return false; - } - } + let next = [obj]; - return true; -}; + 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'); + } -internals.isDeepEqualObj = function (instanceType, obj, ref, options, seen) { + delete node.__proto__; + } - 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 key in node) { + const value = node[key]; + if (value && + typeof value === 'object') { - for (const objValue of obj) { - for (const refValue of ref) { - if (isDeepEqual(objValue, refValue, options, seen)) { - return true; - } + next.push(node[key]); } } } - 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; - } +exports.safeParse = function (text, reviver) { + + try { + return exports.parse(text, reviver); } - else if (instanceType === Types.set) { - if (obj.size !== ref.size) { - return false; - } + catch (ignoreError) { + return null; + } +}; - if (!internals.isSetSimpleEqual(obj, ref)) { - // Check for deep equality +/***/ }), - const ref2 = new Set(Set.prototype.values.call(ref)); - for (const objEntry of Set.prototype.values.call(obj)) { - if (ref2.delete(objEntry)) { - continue; - } +/***/ 85545: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - let found = false; - for (const refEntry of ref2) { - if (isDeepEqual(objEntry, refEntry, options, seen)) { - ref2.delete(refEntry); - found = true; - break; - } - } +"use strict"; - if (!found) { - return false; - } - } - } - } - else if (instanceType === Types.map) { - if (obj.size !== ref.size) { - return false; - } - for (const [key, value] of Map.prototype.entries.call(obj)) { - if (value === undefined && !Map.prototype.has.call(ref, key)) { - return false; - } +const Assert = __nccwpck_require__(32718); +const Clone = __nccwpck_require__(85578); +const Merge = __nccwpck_require__(60445); +const Reach = __nccwpck_require__(18891); - if (!isDeepEqual(value, Map.prototype.get.call(ref, key), options, seen)) { - return false; - } - } - } - else if (instanceType === Types.error) { - // Always check name and message +const internals = {}; - if (obj.name !== ref.name || - obj.message !== ref.message) { - return false; - } +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; } - // Check .valueOf() + if (options.shallow) { + return internals.applyToDefaultsWithShallow(defaults, source, options); + } - const valueOfObj = valueOf(obj); - const valueOfRef = valueOf(ref); - if ((obj !== valueOfObj || ref !== valueOfRef) && - !isDeepEqual(valueOfObj, valueOfRef, options, seen)) { + const copy = Clone(defaults); - return false; + if (source === true) { // If source is set to true, use defaults + return copy; } - // Check properties + const nullOverride = options.nullOverride !== undefined ? options.nullOverride : false; + return Merge(copy, source, { nullOverride, mergeArrays: false }); +}; - const objKeys = keys(obj); - if (!options.part && - objKeys.length !== keys(ref).length && - !options.skip) { - return false; - } +internals.applyToDefaultsWithShallow = function (defaults, source, options) { - let skipped = 0; - for (const key of objKeys) { - if (options.skip && - options.skip.includes(key)) { + const keys = options.shallow; + Assert(Array.isArray(keys), 'Invalid keys'); - if (ref[key] === undefined) { - ++skipped; - } + const seen = new Map(); + const merge = source === true ? null : new Set(); - continue; - } + for (let key of keys) { + key = Array.isArray(key) ? key : key.split('.'); // Pre-split optimization - if (!hasOwnEnumerableProperty(ref, key)) { - return false; - } + const ref = Reach(defaults, key); + if (ref && + typeof ref === 'object') { - if (!isDeepEqual(obj[key], ref[key], options, seen)) { - return false; + seen.set(ref, merge && Reach(source, key) || ref); + } + else if (merge) { + merge.add(key); } } - if (!options.part && - objKeys.length - skipped !== keys(ref).length) { + const copy = Clone(defaults, {}, seen); - return false; + if (!merge) { + return copy; } - // 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)) { + for (const key of merge) { + internals.reachCopy(copy, source, key); + } - if (hasOwnEnumerableProperty(obj, key)) { - if (!hasOwnEnumerableProperty(ref, key)) { - return false; - } + const nullOverride = options.nullOverride !== undefined ? options.nullOverride : false; + return Merge(copy, source, { nullOverride, mergeArrays: false }); +}; - if (!isDeepEqual(obj[key], ref[key], options, seen)) { - return false; - } - } - else if (hasOwnEnumerableProperty(ref, key)) { - return false; - } - } - refSymbols.delete(key); - } +internals.reachCopy = function (dst, src, path) { - for (const key of refSymbols) { - if (hasOwnEnumerableProperty(ref, key)) { - return false; - } + for (const segment of path) { + if (!(segment in src)) { + return; } - } - return true; -}; - - -internals.SeenEntry = class { + const val = src[segment]; - constructor(obj, ref) { + if (typeof val !== 'object' || val === null) { + return; + } - this.obj = obj; - this.ref = ref; + src = val; } - isSame(obj, ref) { + 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] = {}; + } - return this.obj === obj && this.ref === ref; + ref = ref[segment]; } + + ref[path[path.length - 1]] = value; }; /***/ }), -/***/ 35563: -/***/ ((module, exports, __nccwpck_require__) => { +/***/ 32718: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const Stringify = __nccwpck_require__(37577); - +const AssertError = __nccwpck_require__(35563); const internals = {}; -module.exports = class extends Error { - - constructor(args) { - - const msgs = args - .filter((arg) => arg !== '') - .map((arg) => { +module.exports = function (condition, ...args) { - return typeof arg === 'string' ? arg : arg instanceof Error ? arg.message : Stringify(arg); - }); + if (condition) { + return; + } - super(msgs.join(' ') || 'Unknown error'); + if (args.length === 1 && + args[0] instanceof Error) { - if (typeof Error.captureStackTrace === 'function') { // $lab:coverage:ignore$ - Error.captureStackTrace(this, exports.assert); - } + throw args[0]; } + + throw new AssertError(args); }; /***/ }), -/***/ 24752: -/***/ ((module) => { +/***/ 85578: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const internals = {}; - +const Reach = __nccwpck_require__(18891); +const Types = __nccwpck_require__(84340); +const Utils = __nccwpck_require__(30417); -module.exports = function (input) { - if (!input) { - return ''; - } +const internals = { + needsProtoHack: new Set([Types.set, Types.map, Types.weakSet, Types.weakMap]) +}; - let escaped = ''; - for (let i = 0; i < input.length; ++i) { +module.exports = internals.clone = function (obj, options = {}, _seen = null) { - const charCode = input.charCodeAt(i); + if (typeof obj !== 'object' || + obj === null) { - if (internals.isSafe(charCode)) { - escaped += input[i]; + return obj; + } + + let clone = internals.clone; + let seen = _seen; + + if (options.shallow) { + if (options.shallow !== true) { + return internals.cloneWithShallow(obj, options); } - else { - escaped += internals.escapeHtmlChar(charCode); + + clone = (value) => value; + } + else if (seen) { + const lookup = seen.get(obj); + if (lookup) { + return lookup; } } + else { + seen = new Map(); + } - return escaped; -}; + // Built-in object types + const baseProto = Types.getInternalProto(obj); + if (baseProto === Types.buffer) { + return Buffer && Buffer.from(obj); // $lab:coverage:ignore$ + } -internals.escapeHtmlChar = function (charCode) { + if (baseProto === Types.date) { + return new Date(obj.getTime()); + } - const namedEscape = internals.namedHtml[charCode]; - if (typeof namedEscape !== 'undefined') { - return namedEscape; + if (baseProto === Types.regex) { + return new RegExp(obj); } - if (charCode >= 256) { - return '&#' + charCode + ';'; + // Generic objects + + const newObj = internals.base(obj, baseProto, options); + if (newObj === obj) { + return obj; } - const hexValue = charCode.toString(16).padStart(2, '0'); - return `&#x${hexValue};`; -}; + 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)); + } + } -internals.isSafe = function (charCode) { + const keys = Utils.keys(obj, options); + for (const key of keys) { + if (key === '__proto__') { + continue; + } - return (typeof internals.safeCharCodes[charCode] !== 'undefined'); -}; + if (baseProto === Types.array && + key === 'length') { + newObj.length = obj.length; + continue; + } -internals.namedHtml = { - '38': '&', - '60': '<', - '62': '>', - '34': '"', - '160': ' ', - '162': '¢', - '163': '£', - '164': '¤', - '169': '©', - '174': '®' + 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.safeCharCodes = (function () { +internals.cloneWithShallow = function (source, options) { - const safe = {}; + const keys = options.shallow; + options = Object.assign({}, options); + options.shallow = false; - for (let i = 32; i < 123; ++i) { + const seen = new Map(); - 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) { // _ + for (const key of keys) { + const ref = Reach(source, key); + if (typeof ref === 'object' || + typeof ref === 'function') { - safe[i] = null; + seen.set(ref, ref); } } - return safe; -}()); + return internals.clone(source, options, seen); +}; -/***/ }), +internals.base = function (obj, baseProto, options) { -/***/ 91965: -/***/ ((module) => { + if (options.prototype === false) { // Defaults to true + if (internals.needsProtoHack.has(baseProto)) { + return new baseProto.constructor(); + } -"use strict"; + return baseProto === Types.array ? [] : {}; + } + const proto = Object.getPrototypeOf(obj); + if (proto && + proto.isImmutable) { -const internals = {}; + return obj; + } + if (baseProto === Types.array) { + const newObj = []; + if (proto !== baseProto) { + Object.setPrototypeOf(newObj, proto); + } -module.exports = function (string) { + return newObj; + } - // Escape ^$.*+-?=!:|\/()[]{}, + if (internals.needsProtoHack.has(baseProto)) { + const newObj = new proto.constructor(); + if (proto !== baseProto) { + Object.setPrototypeOf(newObj, proto); + } - return string.replace(/[\^\$\.\*\+\-\?\=\!\:\|\\\/\(\)\[\]\{\}\,]/g, '\\$&'); + return newObj; + } + + return Object.create(proto); }; /***/ }), -/***/ 12887: -/***/ ((module) => { +/***/ 55801: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const internals = {}; - +const Types = __nccwpck_require__(84340); -module.exports = function () { }; +const internals = { + mismatched: null +}; -/***/ }), -/***/ 60445: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +module.exports = function (obj, ref, options) { -"use strict"; + options = Object.assign({ prototype: true }, options); + return !!internals.isDeepEqual(obj, ref, options, []); +}; -const Assert = __nccwpck_require__(32718); -const Clone = __nccwpck_require__(85578); -const Utils = __nccwpck_require__(30417); +internals.isDeepEqual = function (obj, ref, options, seen) { -const internals = {}; + 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; -module.exports = internals.merge = function (target, source, options) { + if (type !== typeof ref) { + return false; + } - 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 (obj === null || + ref === null) { - if (!source) { - return target; + return false; } - options = Object.assign({ nullOverride: true, mergeArrays: true }, options); + if (type === 'function') { + if (!options.deepFunction || + obj.toString() !== ref.toString()) { - 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 + return false; } - for (let i = 0; i < source.length; ++i) { - target.push(Clone(source[i], { symbols: options.symbols })); - } + // Continue as object + } + else if (type !== 'object') { + return obj !== obj && ref !== ref; // NaN + } - return target; + 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; } - 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; + 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 } + } - const value = source[key]; - if (value && - typeof value === 'object') { + seen.push(new internals.SeenEntry(obj, ref)); - if (target[key] === value) { - continue; // Can occur for shallow merges - } + try { + return !!internals.isDeepEqualObj(instanceType, obj, ref, options, seen); + } + finally { + seen.pop(); + } +}; - 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 +internals.getSharedType = function (obj, ref, checkPrototype) { - target[key] = value; - } - else if (options.nullOverride) { - target[key] = value; - } + if (checkPrototype) { + if (Object.getPrototypeOf(obj) !== Object.getPrototypeOf(ref)) { + return internals.mismatched; } - } - return target; -}; + return Types.getInternalProto(obj); + } + const type = Types.getInternalProto(obj); + if (type !== Types.getInternalProto(ref)) { + return internals.mismatched; + } -/***/ }), + return type; +}; -/***/ 18891: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +internals.valueOf = function (obj) { + const objValueOf = obj.valueOf; + if (objValueOf === undefined) { + return obj; + } -const Assert = __nccwpck_require__(32718); + try { + return objValueOf.call(obj); + } + catch (err) { + return err; + } +}; -const internals = {}; +internals.hasOwnEnumerableProperty = function (obj, key) { + return Object.prototype.propertyIsEnumerable.call(obj, key); +}; -module.exports = function (obj, chain, options) { - if (chain === false || - chain === null || - chain === undefined) { +internals.isSetSimpleEqual = function (obj, ref) { - return obj; + for (const entry of Set.prototype.values.call(obj)) { + if (!Set.prototype.has.call(ref, entry)) { + return false; + } } - options = options || {}; - if (typeof options === 'string') { - options = { separator: options }; - } + return true; +}; - const isChainArray = Array.isArray(chain); - Assert(!isChainArray || !options.separator, 'Separator option no valid for array-based chain'); +internals.isDeepEqualObj = function (instanceType, obj, ref, options, seen) { - 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); + const { isDeepEqual, valueOf, hasOwnEnumerableProperty } = internals; + const { keys, getOwnPropertySymbols } = Object; - if (Array.isArray(ref) || - type === 'set') { + if (instanceType === Types.array) { + if (options.part) { - const number = Number(key); - if (Number.isInteger(number)) { - key = number < 0 ? ref.length + number : number; + // 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; + } - 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; - } + for (let i = 0; i < obj.length; ++i) { + if (!isDeepEqual(obj[i], ref[i], options, seen)) { + return false; + } + } - if (!type) { - ref = ref[key]; - } - else if (type === 'set') { - ref = [...ref][key]; - } - else { // type === 'map' - ref = ref.get(key); + return true; } } + else if (instanceType === Types.set) { + if (obj.size !== ref.size) { + return false; + } - return ref; -}; + if (!internals.isSetSimpleEqual(obj, ref)) { + // Check for deep equality -internals.iterables = function (ref) { + const ref2 = new Set(Set.prototype.values.call(ref)); + for (const objEntry of Set.prototype.values.call(obj)) { + if (ref2.delete(objEntry)) { + continue; + } - if (ref instanceof Set) { - return 'set'; + 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; + } - if (ref instanceof Map) { - return 'map'; + for (const [key, value] of Map.prototype.entries.call(obj)) { + if (value === undefined && !Map.prototype.has.call(ref, key)) { + return false; + } + + if (!isDeepEqual(value, Map.prototype.get.call(ref, key), options, seen)) { + return false; + } + } } -}; + else if (instanceType === Types.error) { + // Always check name and message -/***/ }), + if (obj.name !== ref.name || + obj.message !== ref.message) { -/***/ 37577: -/***/ ((module) => { + return false; + } + } -"use strict"; + // Check .valueOf() + const valueOfObj = valueOf(obj); + const valueOfRef = valueOf(ref); + if ((obj !== valueOfObj || ref !== valueOfRef) && + !isDeepEqual(valueOfObj, valueOfRef, options, seen)) { -const internals = {}; + return false; + } + // Check properties -module.exports = function (...args) { + const objKeys = keys(obj); + if (!options.part && + objKeys.length !== keys(ref).length && + !options.skip) { - try { - return JSON.stringify.apply(null, args); - } - catch (err) { - return '[Cannot display object: ' + err.message + ']'; + return false; } -}; + let skipped = 0; + for (const key of objKeys) { + if (options.skip && + options.skip.includes(key)) { -/***/ }), + if (ref[key] === undefined) { + ++skipped; + } -/***/ 84340: -/***/ ((module, exports) => { + continue; + } -"use strict"; + if (!hasOwnEnumerableProperty(ref, key)) { + return false; + } + if (!isDeepEqual(obj[key], ref[key], options, seen)) { + return false; + } + } -const internals = {}; + if (!options.part && + objKeys.length - skipped !== keys(ref).length) { + return false; + } -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 -}; + // Check symbols + if (options.symbols !== false) { // Defaults to true + const objSymbols = getOwnPropertySymbols(obj); + const refSymbols = new Set(getOwnPropertySymbols(ref)); -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] -]); + for (const key of objSymbols) { + if (!options.skip || + !options.skip.includes(key)) { + if (hasOwnEnumerableProperty(obj, key)) { + if (!hasOwnEnumerableProperty(ref, key)) { + return false; + } -exports.getInternalProto = function (obj) { + if (!isDeepEqual(obj[key], ref[key], options, seen)) { + return false; + } + } + else if (hasOwnEnumerableProperty(ref, key)) { + return false; + } + } - if (Array.isArray(obj)) { - return exports.array; - } + refSymbols.delete(key); + } - if (Buffer && obj instanceof Buffer) { // $lab:coverage:ignore$ - return exports.buffer; + for (const key of refSymbols) { + if (hasOwnEnumerableProperty(ref, key)) { + return false; + } + } } - if (obj instanceof Date) { - return exports.date; - } + return true; +}; - if (obj instanceof RegExp) { - return exports.regex; - } - if (obj instanceof Error) { - return exports.error; +internals.SeenEntry = class { + + constructor(obj, ref) { + + this.obj = obj; + this.ref = ref; } - const objName = Object.prototype.toString.call(obj); - return internals.typeMap.get(objName) || exports.generic; + isSame(obj, ref) { + + return this.obj === obj && this.ref === ref; + } }; /***/ }), -/***/ 30417: -/***/ ((__unused_webpack_module, exports) => { +/***/ 35563: +/***/ ((module, exports, __nccwpck_require__) => { "use strict"; +const Stringify = __nccwpck_require__(37577); + + const internals = {}; -exports.keys = function (obj, options = {}) { +module.exports = class extends Error { - return options.symbols !== false ? Reflect.ownKeys(obj) : Object.getOwnPropertyNames(obj); // Defaults to true + 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); + } + } }; /***/ }), -/***/ 88392: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 24752: +/***/ ((module) => { "use strict"; -const Assert = __nccwpck_require__(32718); +const internals = {}; -const internals = {}; +module.exports = function (input) { + + if (!input) { + return ''; + } + let escaped = ''; -exports.Sorter = class { + for (let i = 0; i < input.length; ++i) { - constructor() { + const charCode = input.charCodeAt(i); - this._items = []; - this.nodes = []; + if (internals.isSafe(charCode)) { + escaped += input[i]; + } + else { + escaped += internals.escapeHtmlChar(charCode); + } } - add(nodes, options) { + return escaped; +}; - options = options || {}; - // Validate rules +internals.escapeHtmlChar = function (charCode) { - const before = [].concat(options.before || []); - const after = [].concat(options.after || []); - const group = options.group || '?'; - const sort = options.sort || 0; // Used for merging only + const namedEscape = internals.namedHtml[charCode]; + if (typeof namedEscape !== 'undefined') { + return namedEscape; + } - 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 (charCode >= 256) { + return '&#' + charCode + ';'; + } - if (!Array.isArray(nodes)) { - nodes = [nodes]; - } + const hexValue = charCode.toString(16).padStart(2, '0'); + return `&#x${hexValue};`; +}; - for (const node of nodes) { - const item = { - seq: this._items.length, - sort, - before, - after, - group, - node - }; - this._items.push(item); - } +internals.isSafe = function (charCode) { - // Insert event + return (typeof internals.safeCharCodes[charCode] !== 'undefined'); +}; - if (!options.manual) { - const valid = this._sort(); - Assert(valid, 'item', group !== '?' ? `added into group ${group}` : '', 'created a dependencies error'); - } - return this.nodes; - } +internals.namedHtml = { + '38': '&', + '60': '<', + '62': '>', + '34': '"', + '160': ' ', + '162': '¢', + '163': '£', + '164': '¤', + '169': '©', + '174': '®' +}; - merge(others) { - if (!Array.isArray(others)) { - others = [others]; - } +internals.safeCharCodes = (function () { - for (const other of others) { - if (other) { - for (const item of other._items) { - this._items.push(Object.assign({}, item)); // Shallow cloned - } - } - } + const safe = {}; - // Sort items + for (let i = 32; i < 123; ++i) { - this._items.sort(internals.mergeSort); - for (let i = 0; i < this._items.length; ++i) { - this._items[i].seq = 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; } + } - const valid = this._sort(); - Assert(valid, 'merge created a dependencies error'); + return safe; +}()); - return this.nodes; - } - sort() { +/***/ }), - const valid = this._sort(); - Assert(valid, 'sort created a dependencies error'); +/***/ 91965: +/***/ ((module) => { - return this.nodes; - } +"use strict"; - _sort() { - // Construct graph +const internals = {}; - const graph = {}; - const graphAfters = Object.create(null); // A prototype can bungle lookups w/ false positives - const groups = Object.create(null); - for (const item of this._items) { - const seq = item.seq; // Unique across all items - const group = item.group; +module.exports = function (string) { - // Determine Groups + // Escape ^$.*+-?=!:|\/()[]{}, - groups[group] = groups[group] || []; - groups[group].push(seq); + return string.replace(/[\^\$\.\*\+\-\?\=\!\:\|\\\/\(\)\[\]\{\}\,]/g, '\\$&'); +}; - // Build intermediary graph using 'before' - graph[seq] = item.before; +/***/ }), - // Build second intermediary graph with 'after' +/***/ 12887: +/***/ ((module) => { - for (const after of item.after) { - graphAfters[after] = graphAfters[after] || []; - graphAfters[after].push(seq); - } - } +"use strict"; - // Expand intermediary graph - for (const node in graph) { - const expandedGroups = []; +const internals = {}; - for (const graphNodeItem in graph[node]) { - const group = graph[node][graphNodeItem]; - groups[group] = groups[group] || []; - expandedGroups.push(...groups[group]); - } - graph[node] = expandedGroups; - } +module.exports = function () { }; - // 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]); - } - } - } +/***/ }), - // Compile ancestors +/***/ 60445: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - const ancestors = {}; - for (const node in graph) { - const children = graph[node]; - for (const child of children) { - ancestors[child] = ancestors[child] || []; - ancestors[child].push(node); - } - } +"use strict"; - // Topo sort - const visited = {}; - const sorted = []; +const Assert = __nccwpck_require__(32718); +const Clone = __nccwpck_require__(85578); +const Utils = __nccwpck_require__(30417); - 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; - } +const internals = {}; - if (!ancestors[j]) { - ancestors[j] = []; - } - const shouldSeeCount = ancestors[j].length; - let seenCount = 0; - for (let k = 0; k < shouldSeeCount; ++k) { - if (visited[ancestors[j][k]]) { - ++seenCount; - } - } +module.exports = internals.merge = function (target, source, options) { - if (seenCount === shouldSeeCount) { - next = j; - break; - } - } - } + 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 (next !== null) { - visited[next] = true; - sorted.push(next); - } - } + if (!source) { + return target; + } - if (sorted.length !== this._items.length) { - return false; + 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 } - const seqIndex = {}; - for (const item of this._items) { - seqIndex[item.seq] = item; + for (let i = 0; i < source.length; ++i) { + target.push(Clone(source[i], { symbols: options.symbols })); } - this._items = []; - this.nodes = []; + return target; + } - for (const value of sorted) { - const sortedItem = seqIndex[value]; - this.nodes.push(sortedItem.node); - this._items.push(sortedItem); + 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; } - return true; - } -}; + const value = source[key]; + if (value && + typeof value === 'object') { + if (target[key] === value) { + continue; // Can occur for shallow merges + } -internals.mergeSort = (a, b) => { + 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) { - return a.sort === b.sort ? 0 : (a.sort < b.sort ? -1 : 1); + 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; }; /***/ }), -/***/ 47541: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 18891: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); +const Assert = __nccwpck_require__(32718); -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } -var universalUserAgent = __nccwpck_require__(45030); -var request = __nccwpck_require__(36234); -var authOauthApp = __nccwpck_require__(58459); -var deprecation = __nccwpck_require__(58932); -var universalGithubAppJwt = __nccwpck_require__(84419); -var LRU = _interopDefault(__nccwpck_require__(7129)); -var authOauthUser = __nccwpck_require__(11591); +const internals = {}; -function ownKeys(object, enumerableOnly) { - var keys = Object.keys(object); - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(object); +module.exports = function (obj, chain, options) { - if (enumerableOnly) { - symbols = symbols.filter(function (sym) { - return Object.getOwnPropertyDescriptor(object, sym).enumerable; - }); + if (chain === false || + chain === null || + chain === undefined) { + + return obj; } - keys.push.apply(keys, symbols); - } + options = options || {}; + if (typeof options === 'string') { + options = { separator: options }; + } - return keys; -} + const isChainArray = Array.isArray(chain); -function _objectSpread2(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? arguments[i] : {}; + Assert(!isChainArray || !options.separator, 'Separator option no valid for array-based chain'); - 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)); - }); - } - } + 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 target; -} + if (Array.isArray(ref) || + type === 'set') { -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 number = Number(key); + if (Number.isInteger(number)) { + key = number < 0 ? ref.length + number : number; + } + } - return obj; -} + if (!ref || + typeof ref === 'function' && options.functions === false || // Defaults to true + !type && ref[key] === undefined) { -function _objectWithoutPropertiesLoose(source, excluded) { - if (source == null) return {}; - var target = {}; - var sourceKeys = Object.keys(source); - var key, i; + 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; + } - for (i = 0; i < sourceKeys.length; i++) { - key = sourceKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - target[key] = source[key]; - } + if (!type) { + ref = ref[key]; + } + else if (type === 'set') { + ref = [...ref][key]; + } + else { // type === 'map' + ref = ref.get(key); + } + } - return target; -} + return ref; +}; -function _objectWithoutProperties(source, excluded) { - if (source == null) return {}; - var target = _objectWithoutPropertiesLoose(source, excluded); +internals.iterables = function (ref) { - var key, i; + if (ref instanceof Set) { + return 'set'; + } - 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 (ref instanceof Map) { + return 'map'; } - } +}; - return target; -} -async function getAppAuthentication({ - appId, - privateKey, - timeDifference -}) { - try { - 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() - }; - } catch (error) { - if (privateKey === "-----BEGIN RSA PRIVATE KEY-----") { - throw new Error("The 'privateKey` option contains only the first line '-----BEGIN RSA PRIVATE KEY-----'. If you are setting it using a `.env` file, make sure it is set on a single line with newlines replaced by '\n'"); - } else { - throw error; - } - } -} +/***/ }), -// 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); +/***/ 37577: +/***/ ((module) => { - if (!result) { - return; - } +"use strict"; - 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"; + +const internals = {}; + + +module.exports = function (...args) { + + try { + return JSON.stringify.apply(null, args); + } + catch (err) { + return '[Cannot display object: ' + err.message + ']'; } +}; - return permissions; - }, {}); - return { - token, - createdAt, - expiresAt, - permissions, - repositoryIds: options.repositoryIds, - repositoryNames: options.repositoryNames, - 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); -} -function optionsToCacheKey({ - installationId, - permissions = {}, - repositoryIds = [], - repositoryNames = [] -}) { - const permissionsString = Object.keys(permissions).sort().map(name => permissions[name] === "read" ? name : `${name}!`).join(","); - const repositoryIdsString = repositoryIds.sort().join(","); - const repositoryNamesString = repositoryNames.join(","); - return [installationId, repositoryIdsString, repositoryNamesString, permissionsString].filter(Boolean).join("|"); -} +/***/ }), -function toTokenAuthentication({ - installationId, - token, - createdAt, - expiresAt, - repositorySelection, - permissions, - repositoryIds, - repositoryNames, - singleFileName -}) { - return Object.assign({ - type: "token", - tokenType: "installation", - token, - installationId, - permissions, - createdAt, - expiresAt, - repositorySelection - }, repositoryIds ? { - repositoryIds - } : null, repositoryNames ? { - repositoryNames - } : null, singleFileName ? { - singleFileName - } : null); -} +/***/ 84340: +/***/ ((module, exports) => { -const _excluded = ["type", "factory", "oauthApp"]; -async function getInstallationAuthentication(state, options, customRequest) { - const installationId = Number(options.installationId || state.installationId); +"use strict"; - if (!installationId) { - throw new Error("[@octokit/auth-app] installationId option is required for installation authentication."); - } - if (options.factory) { - const _state$options = _objectSpread2(_objectSpread2({}, state), options), - { - type, - factory, - oauthApp - } = _state$options, - factoryAuthOptions = _objectWithoutProperties(_state$options, _excluded); // @ts-expect-error if `options.factory` is set, the return type for `auth()` should be `Promise>` +const internals = {}; - return factory(factoryAuthOptions); - } +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 optionsWithInstallationTokenFromState = Object.assign({ - installationId - }, options); - if (!options.refresh) { - const result = await get(state.cache, optionsWithInstallationTokenFromState); +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] +]); - if (result) { - const { - token, - createdAt, - expiresAt, - permissions, - repositoryIds, - repositoryNames, - singleFileName, - repositorySelection - } = result; - return toTokenAuthentication({ - installationId, - token, - createdAt, - expiresAt, - permissions, - repositorySelection, - repositoryIds, - repositoryNames, - singleFileName - }); + +exports.getInternalProto = function (obj) { + + if (Array.isArray(obj)) { + return exports.array; } - } - const appAuthentication = await getAppAuthentication(state); - const request = customRequest || state.request; - const { - data: { - token, - expires_at: expiresAt, - repositories, - permissions: permissionsOptional, - repository_selection: repositorySelectionOptional, - single_file: singleFileName + if (Buffer && obj instanceof Buffer) { // $lab:coverage:ignore$ + return exports.buffer; } - } = await request("POST /app/installations/{installation_id}/access_tokens", { - installation_id: installationId, - repository_ids: options.repositoryIds, - repositories: options.repositoryNames, - permissions: options.permissions, - mediaType: { - previews: ["machine-man"] - }, - headers: { - authorization: `bearer ${appAuthentication.token}` + + if (obj instanceof Date) { + return exports.date; } - }); - /* istanbul ignore next - permissions are optional per OpenAPI spec, but we think that is incorrect */ - const permissions = permissionsOptional || {}; - /* istanbul ignore next - repositorySelection are optional per OpenAPI spec, but we think that is incorrect */ + if (obj instanceof RegExp) { + return exports.regex; + } - const repositorySelection = repositorySelectionOptional || "all"; - const repositoryIds = repositories ? repositories.map(r => r.id) : void 0; - const repositoryNames = repositories ? repositories.map(repo => repo.name) : void 0; - const createdAt = new Date().toISOString(); - await set(state.cache, optionsWithInstallationTokenFromState, { - token, - createdAt, - expiresAt, - repositorySelection, - permissions, - repositoryIds, - repositoryNames, - singleFileName - }); - return toTokenAuthentication({ - installationId, - token, - createdAt, - expiresAt, - repositorySelection, - permissions, - repositoryIds, - repositoryNames, - singleFileName - }); -} - -async function auth(state, authOptions) { - switch (authOptions.type) { - case "app": - return getAppAuthentication(state); - // @ts-expect-error "oauth" is not supperted in types + if (obj instanceof Error) { + return exports.error; + } - case "oauth": - state.log.warn( // @ts-expect-error `log.warn()` expects string - new deprecation.Deprecation(`[@octokit/auth-app] {type: "oauth"} is deprecated. Use {type: "oauth-app"} instead`)); + const objName = Object.prototype.toString.call(obj); + return internals.typeMap.get(objName) || exports.generic; +}; - case "oauth-app": - return state.oauthApp({ - type: "oauth-app" - }); - case "installation": - return getInstallationAuthentication(state, _objectSpread2(_objectSpread2({}, authOptions), {}, { - type: "installation" - })); +/***/ }), - case "oauth-user": - // @ts-expect-error TODO: infer correct auth options type based on type. authOptions should be typed as "WebFlowAuthOptions | OAuthAppDeviceFlowAuthOptions | GitHubAppDeviceFlowAuthOptions" - return state.oauthApp(authOptions); +/***/ 30417: +/***/ ((__unused_webpack_module, exports) => { - default: - // @ts-expect-error type is "never" at this point - throw new Error(`Invalid auth type: ${authOptions.type}`); - } -} +"use strict"; -const PATHS = ["/app", "/app/hook/config", "/app/hook/deliveries", "/app/hook/deliveries/{delivery_id}", "/app/hook/deliveries/{delivery_id}/attempts", "/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 routeMatcher(paths) { - // EXAMPLE. For the following paths: +const internals = {}; - /* [ - "/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/(?:.+?)' - ] */ +exports.keys = function (obj, options = {}) { - const regex = `^(?:${regexes.map(r => `(?:${r})`).join("|")})[^/]*$`; // 'regex' would contain: + return options.symbols !== false ? Reflect.ownKeys(obj) : Object.getOwnPropertyNames(obj); // Defaults to true +}; - /* - ^(?:(?:\/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(PATHS); -function requiresAppAuth(url) { - return !!url && REGEX.test(url); -} +/***/ 88392: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -const FIVE_SECONDS_IN_MS = 5 * 1000; +"use strict"; -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/)); -} -async function hook(state, request, route, parameters) { - const endpoint = request.endpoint.merge(route, parameters); - const url = endpoint.url; // Do not intercept request to retrieve a new token +const Assert = __nccwpck_require__(32718); - if (/\/login\/oauth\/access_token$/.test(url)) { - return request(endpoint); - } - if (requiresAppAuth(url.replace(request.endpoint.DEFAULTS.baseUrl, ""))) { - const { - token - } = await getAppAuthentication(state); - endpoint.headers.authorization = `bearer ${token}`; - let response; +const internals = {}; - 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. +exports.Sorter = class { - if (typeof error.response.headers.date === "undefined") { - throw error; - } + constructor() { - const diff = Math.floor((Date.parse(error.response.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); + this._items = []; + this.nodes = []; } - return response; - } - - if (authOauthUser.requiresBasicAuth(url)) { - const authentication = await state.oauthApp({ - type: "oauth-app" - }); - endpoint.headers.authorization = authentication.headers.authorization; - return request(endpoint); - } - - const { - token, - createdAt - } = await getInstallationAuthentication(state, // @ts-expect-error TBD - {}, 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 - */ + add(nodes, options) { -async function sendRequestWithRetries(state, request, options, createdAt, retries = 0) { - const timeSinceTokenCreationInMs = +new Date() - +new Date(createdAt); + options = options || {}; - try { - return await request(options); - } catch (error) { - if (error.status !== 401) { - throw error; - } + // Validate rules - 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`; - } + const before = [].concat(options.before || []); + const after = [].concat(options.after || []); + const group = options.group || '?'; + const sort = options.sort || 0; // Used for merging only - 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'); - ++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(nodes)) { + nodes = [nodes]; + } -const VERSION = "3.6.1"; + for (const node of nodes) { + const item = { + seq: this._items.length, + sort, + before, + after, + group, + node + }; -function createAppAuth(options) { - if (!options.appId) { - throw new Error("[@octokit/auth-app] appId option is required"); - } + this._items.push(item); + } - if (!options.privateKey) { - throw new Error("[@octokit/auth-app] privateKey option is required"); - } + // Insert event - if ("installationId" in options && !options.installationId) { - throw new Error("[@octokit/auth-app] installationId is set to a falsy value"); - } + if (!options.manual) { + const valid = this._sort(); + Assert(valid, 'item', group !== '?' ? `added into group ${group}` : '', 'created a dependencies error'); + } - const log = Object.assign({ - warn: console.warn.bind(console) - }, options.log); - const request$1 = options.request || request.request.defaults({ - headers: { - "user-agent": `octokit-auth-app.js/${VERSION} ${universalUserAgent.getUserAgent()}` + return this.nodes; } - }); - const state = Object.assign({ - request: request$1, - cache: getCache() - }, options, options.installationId ? { - installationId: Number(options.installationId) - } : {}, { - log, - oauthApp: authOauthApp.createOAuthAppAuth({ - clientType: "github-app", - clientId: options.clientId || "", - clientSecret: options.clientSecret || "", - request: request$1 - }) - }); // @ts-expect-error not worth the extra code to appease TS - return Object.assign(auth.bind(null, state), { - hook: hook.bind(null, state) - }); -} + merge(others) { -Object.defineProperty(exports, "createOAuthUserAuth", ({ - enumerable: true, - get: function () { - return authOauthUser.createOAuthUserAuth; - } -})); -exports.createAppAuth = createAppAuth; -//# sourceMappingURL=index.js.map + if (!Array.isArray(others)) { + others = [others]; + } + for (const other of others) { + if (other) { + for (const item of other._items) { + this._items.push(Object.assign({}, item)); // Shallow cloned + } + } + } -/***/ }), + // Sort items -/***/ 58459: + this._items.sort(internals.mergeSort); + for (let i = 0; i < this._items.length; ++i) { + this._items[i].seq = i; + } + + const valid = this._sort(); + Assert(valid, 'merge created a dependencies error'); + + return this.nodes; + } + + sort() { + + const valid = this._sort(); + Assert(valid, 'sort created a dependencies error'); + + return this.nodes; + } + + _sort() { + + // Construct graph + + const graph = {}; + const graphAfters = Object.create(null); // A prototype can bungle lookups w/ false positives + const groups = Object.create(null); + + for (const item of this._items) { + const seq = item.seq; // Unique across all items + const group = item.group; + + // Determine Groups + + groups[group] = groups[group] || []; + groups[group].push(seq); + + // Build intermediary graph using 'before' + + graph[seq] = item.before; + + // Build second intermediary graph with 'after' + + for (const after of item.after) { + graphAfters[after] = graphAfters[after] || []; + graphAfters[after].push(seq); + } + } + + // Expand intermediary graph + + for (const node in graph) { + const expandedGroups = []; + + for (const graphNodeItem in graph[node]) { + const group = graph[node][graphNodeItem]; + groups[group] = groups[group] || []; + expandedGroups.push(...groups[group]); + } + + 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]); + } + } + } + + // 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); + } + } + + // Topo sort + + 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; + } + + if (!ancestors[j]) { + ancestors[j] = []; + } + + 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; + } + } + } + + if (next !== null) { + visited[next] = true; + sorted.push(next); + } + } + + if (sorted.length !== this._items.length) { + return false; + } + + const seqIndex = {}; + for (const item of this._items) { + seqIndex[item.seq] = item; + } + + this._items = []; + this.nodes = []; + + for (const value of sorted) { + const sortedItem = seqIndex[value]; + this.nodes.push(sortedItem.node); + this._items.push(sortedItem); + } + + return true; + } +}; + + +internals.mergeSort = (a, b) => { + + return a.sort === b.sort ? 0 : (a.sort < b.sort ? -1 : 1); +}; + + +/***/ }), + +/***/ 47541: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -3243,7 +3472,10 @@ function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'defau var universalUserAgent = __nccwpck_require__(45030); var request = __nccwpck_require__(36234); -var btoa = _interopDefault(__nccwpck_require__(72358)); +var authOauthApp = __nccwpck_require__(58459); +var deprecation = __nccwpck_require__(58932); +var universalGithubAppJwt = __nccwpck_require__(84419); +var LRU = _interopDefault(__nccwpck_require__(7129)); var authOauthUser = __nccwpck_require__(11591); function ownKeys(object, enumerableOnly) { @@ -3335,346 +3567,446 @@ function _objectWithoutProperties(source, excluded) { return target; } -const _excluded = ["type"]; -async function auth(state, authOptions) { - if (authOptions.type === "oauth-app") { +async function getAppAuthentication({ + appId, + privateKey, + timeDifference +}) { + try { + const appAuthentication = await universalGithubAppJwt.githubAppJwt({ + id: +appId, + privateKey, + now: timeDifference && Math.floor(Date.now() / 1000) + timeDifference + }); return { - type: "oauth-app", - clientId: state.clientId, - clientSecret: state.clientSecret, - clientType: state.clientType, - headers: { - authorization: `basic ${btoa(`${state.clientId}:${state.clientSecret}`)}` - } + type: "app", + token: appAuthentication.token, + appId: appAuthentication.appId, + expiresAt: new Date(appAuthentication.expiration * 1000).toISOString() }; + } catch (error) { + if (privateKey === "-----BEGIN RSA PRIVATE KEY-----") { + throw new Error("The 'privateKey` option contains only the first line '-----BEGIN RSA PRIVATE KEY-----'. If you are setting it using a `.env` file, make sure it is set on a single line with newlines replaced by '\n'"); + } else { + throw error; + } } +} - if ("factory" in authOptions) { - const _authOptions$state = _objectSpread2(_objectSpread2({}, authOptions), state), - options = _objectWithoutProperties(_authOptions$state, _excluded); // @ts-expect-error TODO: `option` cannot be never, is this a bug? - +// 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); - return authOptions.factory(options); + if (!result) { + return; } - const common = _objectSpread2({ - clientId: state.clientId, - clientSecret: state.clientSecret, - request: state.request - }, authOptions); // TS: Look what you made me do - + 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"; + } - const userAuth = state.clientType === "oauth-app" ? await authOauthUser.createOAuthUserAuth(_objectSpread2(_objectSpread2({}, common), {}, { - clientType: state.clientType - })) : await authOauthUser.createOAuthUserAuth(_objectSpread2(_objectSpread2({}, common), {}, { - clientType: state.clientType - })); - return userAuth(); + return permissions; + }, {}); + return { + token, + createdAt, + expiresAt, + permissions, + repositoryIds: options.repositoryIds, + repositoryNames: options.repositoryNames, + 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); } -async function hook(state, request, route, parameters) { - let endpoint = request.endpoint.merge(route, parameters); // Do not intercept OAuth Web/Device flow request - - if (/\/login\/(oauth\/access_token|device\/code)$/.test(endpoint.url)) { - return request(endpoint); - } +function optionsToCacheKey({ + installationId, + permissions = {}, + repositoryIds = [], + repositoryNames = [] +}) { + const permissionsString = Object.keys(permissions).sort().map(name => permissions[name] === "read" ? name : `${name}!`).join(","); + const repositoryIdsString = repositoryIds.sort().join(","); + const repositoryNamesString = repositoryNames.join(","); + return [installationId, repositoryIdsString, repositoryNamesString, permissionsString].filter(Boolean).join("|"); +} - if (state.clientType === "github-app" && !authOauthUser.requiresBasicAuth(endpoint.url)) { - throw new Error(`[@octokit/auth-oauth-app] GitHub Apps cannot use their client ID/secret for basic authentication for endpoints other than "/applications/{client_id}/**". "${endpoint.method} ${endpoint.url}" is not supported.`); - } +function toTokenAuthentication({ + installationId, + token, + createdAt, + expiresAt, + repositorySelection, + permissions, + repositoryIds, + repositoryNames, + singleFileName +}) { + return Object.assign({ + type: "token", + tokenType: "installation", + token, + installationId, + permissions, + createdAt, + expiresAt, + repositorySelection + }, repositoryIds ? { + repositoryIds + } : null, repositoryNames ? { + repositoryNames + } : null, singleFileName ? { + singleFileName + } : null); +} - const credentials = btoa(`${state.clientId}:${state.clientSecret}`); - endpoint.headers.authorization = `basic ${credentials}`; +const _excluded = ["type", "factory", "oauthApp"]; +async function getInstallationAuthentication(state, options, customRequest) { + const installationId = Number(options.installationId || state.installationId); - try { - return await request(endpoint); - } catch (error) { - /* istanbul ignore if */ - if (error.status !== 401) throw error; - error.message = `[@octokit/auth-oauth-app] "${endpoint.method} ${endpoint.url}" does not support clientId/clientSecret basic authentication.`; - throw error; + if (!installationId) { + throw new Error("[@octokit/auth-app] installationId option is required for installation authentication."); } -} - -const VERSION = "4.3.0"; -function createOAuthAppAuth(options) { - const state = Object.assign({ - request: request.request.defaults({ - headers: { - "user-agent": `octokit-auth-oauth-app.js/${VERSION} ${universalUserAgent.getUserAgent()}` - } - }), - clientType: "oauth-app" - }, options); // @ts-expect-error not worth the extra code to appease TS + if (options.factory) { + const _state$options = _objectSpread2(_objectSpread2({}, state), options), + { + type, + factory, + oauthApp + } = _state$options, + factoryAuthOptions = _objectWithoutProperties(_state$options, _excluded); // @ts-expect-error if `options.factory` is set, the return type for `auth()` should be `Promise>` - return Object.assign(auth.bind(null, state), { - hook: hook.bind(null, state) - }); -} -Object.defineProperty(exports, "createOAuthUserAuth", ({ - enumerable: true, - get: function () { - return authOauthUser.createOAuthUserAuth; + return factory(factoryAuthOptions); } -})); -exports.createOAuthAppAuth = createOAuthAppAuth; -//# sourceMappingURL=index.js.map + const optionsWithInstallationTokenFromState = Object.assign({ + installationId + }, options); -/***/ }), - -/***/ 44344: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + if (!options.refresh) { + const result = await get(state.cache, optionsWithInstallationTokenFromState); -"use strict"; + if (result) { + const { + token, + createdAt, + expiresAt, + permissions, + repositoryIds, + repositoryNames, + singleFileName, + repositorySelection + } = result; + return toTokenAuthentication({ + installationId, + token, + createdAt, + expiresAt, + permissions, + repositorySelection, + repositoryIds, + repositoryNames, + singleFileName + }); + } + } + const appAuthentication = await getAppAuthentication(state); + const request = customRequest || state.request; + const { + data: { + token, + expires_at: expiresAt, + repositories, + permissions: permissionsOptional, + repository_selection: repositorySelectionOptional, + single_file: singleFileName + } + } = await request("POST /app/installations/{installation_id}/access_tokens", { + installation_id: installationId, + repository_ids: options.repositoryIds, + repositories: options.repositoryNames, + permissions: options.permissions, + mediaType: { + previews: ["machine-man"] + }, + headers: { + authorization: `bearer ${appAuthentication.token}` + } + }); + /* istanbul ignore next - permissions are optional per OpenAPI spec, but we think that is incorrect */ -Object.defineProperty(exports, "__esModule", ({ value: true })); + const permissions = permissionsOptional || {}; + /* istanbul ignore next - repositorySelection are optional per OpenAPI spec, but we think that is incorrect */ -var universalUserAgent = __nccwpck_require__(45030); -var request = __nccwpck_require__(36234); -var oauthMethods = __nccwpck_require__(88445); + const repositorySelection = repositorySelectionOptional || "all"; + const repositoryIds = repositories ? repositories.map(r => r.id) : void 0; + const repositoryNames = repositories ? repositories.map(repo => repo.name) : void 0; + const createdAt = new Date().toISOString(); + await set(state.cache, optionsWithInstallationTokenFromState, { + token, + createdAt, + expiresAt, + repositorySelection, + permissions, + repositoryIds, + repositoryNames, + singleFileName + }); + return toTokenAuthentication({ + installationId, + token, + createdAt, + expiresAt, + repositorySelection, + permissions, + repositoryIds, + repositoryNames, + singleFileName + }); +} -function ownKeys(object, enumerableOnly) { - var keys = Object.keys(object); +async function auth(state, authOptions) { + switch (authOptions.type) { + case "app": + return getAppAuthentication(state); + // @ts-expect-error "oauth" is not supperted in types - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(object); + case "oauth": + state.log.warn( // @ts-expect-error `log.warn()` expects string + new deprecation.Deprecation(`[@octokit/auth-app] {type: "oauth"} is deprecated. Use {type: "oauth-app"} instead`)); - if (enumerableOnly) { - symbols = symbols.filter(function (sym) { - return Object.getOwnPropertyDescriptor(object, sym).enumerable; + case "oauth-app": + return state.oauthApp({ + type: "oauth-app" }); - } - - keys.push.apply(keys, symbols); - } - return keys; -} + case "installation": + return getInstallationAuthentication(state, _objectSpread2(_objectSpread2({}, authOptions), {}, { + type: "installation" + })); -function _objectSpread2(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? arguments[i] : {}; + case "oauth-user": + // @ts-expect-error TODO: infer correct auth options type based on type. authOptions should be typed as "WebFlowAuthOptions | OAuthAppDeviceFlowAuthOptions | GitHubAppDeviceFlowAuthOptions" + return state.oauthApp(authOptions); - 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)); - }); - } + default: + // @ts-expect-error type is "never" at this point + throw new Error(`Invalid auth type: ${authOptions.type}`); } - - 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 PATHS = ["/app", "/app/hook/config", "/app/hook/deliveries", "/app/hook/deliveries/{delivery_id}", "/app/hook/deliveries/{delivery_id}/attempts", "/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 - return obj; -} +function routeMatcher(paths) { + // EXAMPLE. For the following paths: -function _objectWithoutPropertiesLoose(source, excluded) { - if (source == null) return {}; - var target = {}; - var sourceKeys = Object.keys(source); - var key, i; + /* [ + "/orgs/{org}/invitations", + "/repos/{owner}/{repo}/collaborators/{username}" + ] */ + const regexes = paths.map(p => p.split("/").map(c => c.startsWith("{") ? "(?:.+?)" : c).join("/")); // 'regexes' would contain: - for (i = 0; i < sourceKeys.length; i++) { - key = sourceKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - target[key] = source[key]; - } + /* [ + '/orgs/(?:.+?)/invitations', + '/repos/(?:.+?)/(?:.+?)/collaborators/(?:.+?)' + ] */ - return target; + 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"); } -function _objectWithoutProperties(source, excluded) { - if (source == null) return {}; +const REGEX = routeMatcher(PATHS); +function requiresAppAuth(url) { + return !!url && REGEX.test(url); +} - var target = _objectWithoutPropertiesLoose(source, excluded); +const FIVE_SECONDS_IN_MS = 5 * 1000; - var key, i; +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 (Object.getOwnPropertySymbols) { - var sourceSymbolKeys = Object.getOwnPropertySymbols(source); +async function hook(state, request, route, parameters) { + const endpoint = request.endpoint.merge(route, parameters); + const url = endpoint.url; // Do not intercept request to retrieve a new token - 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 (/\/login\/oauth\/access_token$/.test(url)) { + return request(endpoint); } - return target; -} + if (requiresAppAuth(url.replace(request.endpoint.DEFAULTS.baseUrl, ""))) { + const { + token + } = await getAppAuthentication(state); + endpoint.headers.authorization = `bearer ${token}`; + let response; -async function getOAuthAccessToken(state, options) { - const cachedAuthentication = getCachedAuthentication(state, options.auth); - if (cachedAuthentication) return cachedAuthentication; // Step 1: Request device and user codes - // https://docs.github.com/en/developers/apps/authorizing-oauth-apps#step-1-app-requests-the-device-and-user-verification-codes-from-github + 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. - const { - data: verification - } = await oauthMethods.createDeviceCode({ - clientType: state.clientType, - clientId: state.clientId, - request: options.request || state.request, - // @ts-expect-error the extra code to make TS happy is not worth it - scopes: options.auth.scopes || state.scopes - }); // Step 2: User must enter the user code on https://github.com/login/device - // See https://docs.github.com/en/developers/apps/authorizing-oauth-apps#step-2-prompt-the-user-to-enter-the-user-code-in-a-browser - await state.onVerification(verification); // Step 3: Exchange device code for access token - // See https://docs.github.com/en/developers/apps/authorizing-oauth-apps#step-3-app-polls-github-to-check-if-the-user-authorized-the-device + if (typeof error.response.headers.date === "undefined") { + throw error; + } - const authentication = await waitForAccessToken(options.request || state.request, state.clientId, state.clientType, verification); - state.authentication = authentication; - return authentication; -} + const diff = Math.floor((Date.parse(error.response.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); + } -function getCachedAuthentication(state, auth) { - if (auth.refresh === true) return false; - if (!state.authentication) return false; + return response; + } - if (state.clientType === "github-app") { - return state.authentication; + if (authOauthUser.requiresBasicAuth(url)) { + const authentication = await state.oauthApp({ + type: "oauth-app" + }); + endpoint.headers.authorization = authentication.headers.authorization; + return request(endpoint); } - const authentication = state.authentication; - const newScope = ("scopes" in auth && auth.scopes || state.scopes).join(" "); - const currentScope = authentication.scopes.join(" "); - return newScope === currentScope ? authentication : false; + const { + token, + createdAt + } = await getInstallationAuthentication(state, // @ts-expect-error TBD + {}, 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 + */ -async function wait(seconds) { - await new Promise(resolve => setTimeout(resolve, seconds * 1000)); -} +async function sendRequestWithRetries(state, request, options, createdAt, retries = 0) { + const timeSinceTokenCreationInMs = +new Date() - +new Date(createdAt); -async function waitForAccessToken(request, clientId, clientType, verification) { try { - const options = { - clientId, - request, - code: verification.device_code - }; // WHY TYPESCRIPT WHY ARE YOU DOING THIS TO ME - - const { - authentication - } = clientType === "oauth-app" ? await oauthMethods.exchangeDeviceCode(_objectSpread2(_objectSpread2({}, options), {}, { - clientType: "oauth-app" - })) : await oauthMethods.exchangeDeviceCode(_objectSpread2(_objectSpread2({}, options), {}, { - clientType: "github-app" - })); - return _objectSpread2({ - type: "token", - tokenType: "oauth" - }, authentication); + return await request(options); } catch (error) { - // istanbul ignore if - if (!error.response) throw error; - const errorType = error.response.data.error; - - if (errorType === "authorization_pending") { - await wait(verification.interval); - return waitForAccessToken(request, clientId, clientType, verification); + if (error.status !== 401) { + throw error; } - if (errorType === "slow_down") { - await wait(verification.interval + 5); - return waitForAccessToken(request, clientId, clientType, verification); + 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`; + } + + throw error; } - throw error; + ++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); } } -async function auth(state, authOptions) { - return getOAuthAccessToken(state, { - auth: authOptions - }); -} - -async function hook(state, request, route, parameters) { - let endpoint = request.endpoint.merge(route, parameters); // Do not intercept request to retrieve codes or token +const VERSION = "3.6.1"; - if (/\/login\/(oauth\/access_token|device\/code)$/.test(endpoint.url)) { - return request(endpoint); +function createAppAuth(options) { + if (!options.appId) { + throw new Error("[@octokit/auth-app] appId option is required"); } - const { - token - } = await getOAuthAccessToken(state, { - request, - auth: { - type: "oauth" - } - }); - endpoint.headers.authorization = `token ${token}`; - return request(endpoint); -} + if (!options.privateKey) { + throw new Error("[@octokit/auth-app] privateKey option is required"); + } -const VERSION = "3.1.2"; + if ("installationId" in options && !options.installationId) { + throw new Error("[@octokit/auth-app] installationId is set to a falsy value"); + } -function createOAuthDeviceAuth(options) { - const requestWithDefaults = options.request || request.request.defaults({ + const log = Object.assign({ + warn: console.warn.bind(console) + }, options.log); + const request$1 = options.request || request.request.defaults({ headers: { - "user-agent": `octokit-auth-oauth-device.js/${VERSION} ${universalUserAgent.getUserAgent()}` + "user-agent": `octokit-auth-app.js/${VERSION} ${universalUserAgent.getUserAgent()}` } }); - - const { - request: request$1 = requestWithDefaults - } = options, - otherOptions = _objectWithoutProperties(options, ["request"]); - - const state = options.clientType === "github-app" ? _objectSpread2(_objectSpread2({}, otherOptions), {}, { - clientType: "github-app", - request: request$1 - }) : _objectSpread2(_objectSpread2({}, otherOptions), {}, { - clientType: "oauth-app", + const state = Object.assign({ request: request$1, - scopes: options.scopes || [] - }); - - if (!options.clientId) { - throw new Error('[@octokit/auth-oauth-device] "clientId" option must be set (https://github.com/octokit/auth-oauth-device.js#usage)'); - } - - if (!options.onVerification) { - throw new Error('[@octokit/auth-oauth-device] "onVerification" option must be a function (https://github.com/octokit/auth-oauth-device.js#usage)'); - } // @ts-ignore too much for tsc / ts-jest ¯\_(ツ)_/¯ - + cache: getCache() + }, options, options.installationId ? { + installationId: Number(options.installationId) + } : {}, { + log, + oauthApp: authOauthApp.createOAuthAppAuth({ + clientType: "github-app", + clientId: options.clientId || "", + clientSecret: options.clientSecret || "", + request: request$1 + }) + }); // @ts-expect-error not worth the extra code to appease TS return Object.assign(auth.bind(null, state), { hook: hook.bind(null, state) }); } -exports.createOAuthDeviceAuth = createOAuthDeviceAuth; +Object.defineProperty(exports, "createOAuthUserAuth", ({ + enumerable: true, + get: function () { + return authOauthUser.createOAuthUserAuth; + } +})); +exports.createAppAuth = createAppAuth; //# sourceMappingURL=index.js.map /***/ }), -/***/ 11591: +/***/ 58459: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -3686,9 +4018,8 @@ function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'defau var universalUserAgent = __nccwpck_require__(45030); var request = __nccwpck_require__(36234); -var authOauthDevice = __nccwpck_require__(44344); -var oauthMethods = __nccwpck_require__(88445); var btoa = _interopDefault(__nccwpck_require__(72358)); +var authOauthUser = __nccwpck_require__(11591); function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); @@ -3779,397 +4110,160 @@ function _objectWithoutProperties(source, excluded) { return target; } -const VERSION = "1.3.0"; - -async function getAuthentication(state) { - // handle code exchange form OAuth Web Flow - if ("code" in state.strategyOptions) { - const { - authentication - } = await oauthMethods.exchangeWebFlowCode(_objectSpread2(_objectSpread2({ +const _excluded = ["type"]; +async function auth(state, authOptions) { + if (authOptions.type === "oauth-app") { + return { + type: "oauth-app", clientId: state.clientId, clientSecret: state.clientSecret, - clientType: state.clientType - }, state.strategyOptions), {}, { - request: state.request - })); - return _objectSpread2({ - type: "token", - tokenType: "oauth" - }, authentication); - } // handle OAuth device flow - - - if ("onVerification" in state.strategyOptions) { - const deviceAuth = authOauthDevice.createOAuthDeviceAuth(_objectSpread2(_objectSpread2({ clientType: state.clientType, - clientId: state.clientId - }, state.strategyOptions), {}, { - request: state.request - })); - const authentication = await deviceAuth({ - type: "oauth" - }); - return _objectSpread2({ - clientSecret: state.clientSecret - }, authentication); - } // use existing authentication - - - if ("token" in state.strategyOptions) { - return _objectSpread2({ - type: "token", - tokenType: "oauth", - clientId: state.clientId, - clientSecret: state.clientSecret, - clientType: state.clientType - }, state.strategyOptions); + headers: { + authorization: `basic ${btoa(`${state.clientId}:${state.clientSecret}`)}` + } + }; } - throw new Error("[@octokit/auth-oauth-user] Invalid strategy options"); -} + if ("factory" in authOptions) { + const _authOptions$state = _objectSpread2(_objectSpread2({}, authOptions), state), + options = _objectWithoutProperties(_authOptions$state, _excluded); // @ts-expect-error TODO: `option` cannot be never, is this a bug? -async function auth(state, options = {}) { - if (!state.authentication) { - // This is what TS makes us do ¯\_(ツ)_/¯ - state.authentication = state.clientType === "oauth-app" ? await getAuthentication(state) : await getAuthentication(state); - } - if (state.authentication.invalid) { - throw new Error("[@octokit/auth-oauth-user] Token is invalid"); + return authOptions.factory(options); } - const currentAuthentication = state.authentication; // (auto) refresh for user-to-server tokens - - if ("expiresAt" in currentAuthentication) { - if (options.type === "refresh" || new Date(currentAuthentication.expiresAt) < new Date()) { - const { - authentication - } = await oauthMethods.refreshToken({ - clientType: "github-app", - clientId: state.clientId, - clientSecret: state.clientSecret, - refreshToken: currentAuthentication.refreshToken, - request: state.request - }); - state.authentication = _objectSpread2({ - tokenType: "oauth", - type: "token" - }, authentication); - } - } // throw error for invalid refresh call - - - if (options.type === "refresh") { - if (state.clientType === "oauth-app") { - throw new Error("[@octokit/auth-oauth-user] OAuth Apps do not support expiring tokens"); - } - - if (!currentAuthentication.hasOwnProperty("expiresAt")) { - throw new Error("[@octokit/auth-oauth-user] Refresh token missing"); - } - } // check or reset token - - - if (options.type === "check" || options.type === "reset") { - const method = options.type === "check" ? oauthMethods.checkToken : oauthMethods.resetToken; - - try { - const { - authentication - } = await method({ - // @ts-expect-error making TS happy would require unnecessary code so no - clientType: state.clientType, - clientId: state.clientId, - clientSecret: state.clientSecret, - token: state.authentication.token, - request: state.request - }); - state.authentication = _objectSpread2({ - tokenType: "oauth", - type: "token" - }, authentication); - return state.authentication; - } catch (error) { - // istanbul ignore else - if (error.status === 404) { - error.message = "[@octokit/auth-oauth-user] Token is invalid"; // @ts-expect-error TBD - - state.authentication.invalid = true; - } - - throw error; - } - } // invalidate - - - if (options.type === "delete" || options.type === "deleteAuthorization") { - const method = options.type === "delete" ? oauthMethods.deleteToken : oauthMethods.deleteAuthorization; - - try { - await method({ - // @ts-expect-error making TS happy would require unnecessary code so no - clientType: state.clientType, - clientId: state.clientId, - clientSecret: state.clientSecret, - token: state.authentication.token, - request: state.request - }); - } catch (error) { - // istanbul ignore if - if (error.status !== 404) throw error; - } - - state.authentication.invalid = true; - return state.authentication; - } + const common = _objectSpread2({ + clientId: state.clientId, + clientSecret: state.clientSecret, + request: state.request + }, authOptions); // TS: Look what you made me do - return state.authentication; -} -/** - * The following endpoints require an OAuth App to authenticate using its client_id and client_secret. - * - * - [`POST /applications/{client_id}/token`](https://docs.github.com/en/rest/reference/apps#check-a-token) - Check a token - * - [`PATCH /applications/{client_id}/token`](https://docs.github.com/en/rest/reference/apps#reset-a-token) - Reset a token - * - [`POST /applications/{client_id}/token/scoped`](https://docs.github.com/en/rest/reference/apps#create-a-scoped-access-token) - Create a scoped access token - * - [`DELETE /applications/{client_id}/token`](https://docs.github.com/en/rest/reference/apps#delete-an-app-token) - Delete an app token - * - [`DELETE /applications/{client_id}/grant`](https://docs.github.com/en/rest/reference/apps#delete-an-app-authorization) - Delete an app authorization - * - * deprecated: - * - * - [`GET /applications/{client_id}/tokens/{access_token}`](https://docs.github.com/en/rest/reference/apps#check-an-authorization) - Check an authorization - * - [`POST /applications/{client_id}/tokens/{access_token}`](https://docs.github.com/en/rest/reference/apps#reset-an-authorization) - Reset an authorization - * - [`DELETE /applications/{client_id}/tokens/{access_token}`](https://docs.github.com/en/rest/reference/apps#revoke-an-authorization-for-an-application) - Revoke an authorization for an application - * - [`DELETE /applications/{client_id}/grants/{access_token}`](https://docs.github.com/en/rest/reference/apps#revoke-a-grant-for-an-application) - Revoke a grant for an application - */ -const ROUTES_REQUIRING_BASIC_AUTH = /\/applications\/[^/]+\/(token|grant)s?/; -function requiresBasicAuth(url) { - return url && ROUTES_REQUIRING_BASIC_AUTH.test(url); + const userAuth = state.clientType === "oauth-app" ? await authOauthUser.createOAuthUserAuth(_objectSpread2(_objectSpread2({}, common), {}, { + clientType: state.clientType + })) : await authOauthUser.createOAuthUserAuth(_objectSpread2(_objectSpread2({}, common), {}, { + clientType: state.clientType + })); + return userAuth(); } -async function hook(state, request, route, parameters = {}) { - const endpoint = request.endpoint.merge(route, parameters); // Do not intercept OAuth Web/Device flow request +async function hook(state, request, route, parameters) { + let endpoint = request.endpoint.merge(route, parameters); // Do not intercept OAuth Web/Device flow request if (/\/login\/(oauth\/access_token|device\/code)$/.test(endpoint.url)) { return request(endpoint); } - if (requiresBasicAuth(endpoint.url)) { - const credentials = btoa(`${state.clientId}:${state.clientSecret}`); - endpoint.headers.authorization = `basic ${credentials}`; - return request(endpoint); - } // TS makes us do this ¯\_(ツ)_/¯ + if (state.clientType === "github-app" && !authOauthUser.requiresBasicAuth(endpoint.url)) { + throw new Error(`[@octokit/auth-oauth-app] GitHub Apps cannot use their client ID/secret for basic authentication for endpoints other than "/applications/{client_id}/**". "${endpoint.method} ${endpoint.url}" is not supported.`); + } + const credentials = btoa(`${state.clientId}:${state.clientSecret}`); + endpoint.headers.authorization = `basic ${credentials}`; - const { - token - } = state.clientType === "oauth-app" ? await auth(_objectSpread2(_objectSpread2({}, state), {}, { - request - })) : await auth(_objectSpread2(_objectSpread2({}, state), {}, { - request - })); - endpoint.headers.authorization = "token " + token; - return request(endpoint); + try { + return await request(endpoint); + } catch (error) { + /* istanbul ignore if */ + if (error.status !== 401) throw error; + error.message = `[@octokit/auth-oauth-app] "${endpoint.method} ${endpoint.url}" does not support clientId/clientSecret basic authentication.`; + throw error; + } } -const _excluded = ["clientId", "clientSecret", "clientType", "request"]; -function createOAuthUserAuth(_ref) { - let { - clientId, - clientSecret, - clientType = "oauth-app", - request: request$1 = request.request.defaults({ +const VERSION = "4.3.0"; + +function createOAuthAppAuth(options) { + const state = Object.assign({ + request: request.request.defaults({ headers: { "user-agent": `octokit-auth-oauth-app.js/${VERSION} ${universalUserAgent.getUserAgent()}` } - }) - } = _ref, - strategyOptions = _objectWithoutProperties(_ref, _excluded); - - const state = Object.assign({ - clientType, - clientId, - clientSecret, - strategyOptions, - request: request$1 - }); // @ts-expect-error not worth the extra code needed to appease TS + }), + clientType: "oauth-app" + }, options); // @ts-expect-error not worth the extra code to appease TS return Object.assign(auth.bind(null, state), { - // @ts-expect-error not worth the extra code needed to appease TS hook: hook.bind(null, state) }); } -createOAuthUserAuth.VERSION = VERSION; -exports.createOAuthUserAuth = createOAuthUserAuth; -exports.requiresBasicAuth = requiresBasicAuth; +Object.defineProperty(exports, "createOAuthUserAuth", ({ + enumerable: true, + get: function () { + return authOauthUser.createOAuthUserAuth; + } +})); +exports.createOAuthAppAuth = createOAuthAppAuth; //# sourceMappingURL=index.js.map /***/ }), -/***/ 40334: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ value: true })); - -const REGEX_IS_INSTALLATION_LEGACY = /^v1\./; -const REGEX_IS_INSTALLATION = /^ghs_/; -const REGEX_IS_USER_TO_SERVER = /^ghu_/; -async function auth(token) { - const isApp = token.split(/\./).length === 3; - const isInstallation = REGEX_IS_INSTALLATION_LEGACY.test(token) || REGEX_IS_INSTALLATION.test(token); - const isUserToServer = REGEX_IS_USER_TO_SERVER.test(token); - const tokenType = isApp ? "app" : isInstallation ? "installation" : isUserToServer ? "user-to-server" : "oauth"; - return { - type: "token", - token: token, - tokenType - }; -} - -/** - * 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}`; -} - -async function hook(token, request, route, parameters) { - const endpoint = request.endpoint.merge(route, parameters); - endpoint.headers.authorization = withAuthorizationPrefix(token); - return request(endpoint); -} - -const createTokenAuth = function createTokenAuth(token) { - if (!token) { - throw new Error("[@octokit/auth-token] No token passed to createTokenAuth"); - } - - if (typeof token !== "string") { - throw new Error("[@octokit/auth-token] Token passed to createTokenAuth is not a string"); - } - - token = token.replace(/^(token|bearer) +/i, ""); - return Object.assign(auth.bind(null, token), { - hook: hook.bind(null, token) - }); -}; - -exports.createTokenAuth = createTokenAuth; -//# sourceMappingURL=index.js.map - - -/***/ }), - -/***/ 79567: -/***/ ((__unused_webpack_module, exports) => { +/***/ 44344: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -async function auth(reason) { - return { - type: "unauthenticated", - reason - }; -} - -function isRateLimitError(error) { - if (error.status !== 403) { - return false; - } - /* istanbul ignore if */ +var universalUserAgent = __nccwpck_require__(45030); +var request = __nccwpck_require__(36234); +var oauthMethods = __nccwpck_require__(88445); +function ownKeys(object, enumerableOnly) { + var keys = Object.keys(object); - if (!error.response) { - return false; - } + if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(object); - return error.response.headers["x-ratelimit-remaining"] === "0"; -} + if (enumerableOnly) { + symbols = symbols.filter(function (sym) { + return Object.getOwnPropertyDescriptor(object, sym).enumerable; + }); + } -const REGEX_ABUSE_LIMIT_MESSAGE = /\babuse\b/i; -function isAbuseLimitError(error) { - if (error.status !== 403) { - return false; + keys.push.apply(keys, symbols); } - return REGEX_ABUSE_LIMIT_MESSAGE.test(error.message); + return keys; } -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; - } - - if (isRateLimitError(error)) { - error.message = `API rate limit exceeded. This maybe caused by the lack of authentication. Reason: ${reason}`; - throw error; - } - - if (isAbuseLimitError(error)) { - error.message = `You have triggered an abuse detection mechanism. This maybe caused by the lack of authentication. Reason: ${reason}`; - throw error; - } - - if (error.status === 401) { - error.message = `Unauthorized. "${endpoint.method} ${endpoint.url}" failed most likely due to lack of authentication. Reason: ${reason}`; - throw error; - } +function _objectSpread2(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i] != null ? arguments[i] : {}; - if (error.status >= 400 && error.status < 500) { - error.message = error.message.replace(/\.?$/, `. May be caused by lack of authentication (${reason}).`); + 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)); + }); } + } - throw error; - }); + return target; } -const createUnauthenticatedAuth = function createUnauthenticatedAuth(options) { - if (!options || !options.reason) { - throw new Error("[@octokit/auth-unauthenticated] No reason passed to createUnauthenticatedAuth"); +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 Object.assign(auth.bind(null, options.reason), { - hook: hook.bind(null, options.reason) - }); -}; - -exports.createUnauthenticatedAuth = createUnauthenticatedAuth; -//# sourceMappingURL=index.js.map - - -/***/ }), - -/***/ 76762: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -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); + return obj; +} function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; @@ -4207,141 +4301,155 @@ function _objectWithoutProperties(source, excluded) { return target; } -const VERSION = "3.5.1"; +async function getOAuthAccessToken(state, options) { + const cachedAuthentication = getCachedAuthentication(state, options.auth); + if (cachedAuthentication) return cachedAuthentication; // Step 1: Request device and user codes + // https://docs.github.com/en/developers/apps/authorizing-oauth-apps#step-1-app-requests-the-device-and-user-verification-codes-from-github -const _excluded = ["authStrategy"]; -class Octokit { - constructor(options = {}) { - const hook = new beforeAfterHook.Collection(); - const requestDefaults = { - baseUrl: request.request.endpoint.DEFAULTS.baseUrl, - headers: {}, - request: Object.assign({}, options.request, { - // @ts-ignore internal usage only, no need to type - hook: hook.bind(null, "request") - }), - mediaType: { - previews: [], - format: "" - } - }; // prepend default user agent with `options.userAgent` if set + const { + data: verification + } = await oauthMethods.createDeviceCode({ + clientType: state.clientType, + clientId: state.clientId, + request: options.request || state.request, + // @ts-expect-error the extra code to make TS happy is not worth it + scopes: options.auth.scopes || state.scopes + }); // Step 2: User must enter the user code on https://github.com/login/device + // See https://docs.github.com/en/developers/apps/authorizing-oauth-apps#step-2-prompt-the-user-to-enter-the-user-code-in-a-browser - requestDefaults.headers["user-agent"] = [options.userAgent, `octokit-core.js/${VERSION} ${universalUserAgent.getUserAgent()}`].filter(Boolean).join(" "); + await state.onVerification(verification); // Step 3: Exchange device code for access token + // See https://docs.github.com/en/developers/apps/authorizing-oauth-apps#step-3-app-polls-github-to-check-if-the-user-authorized-the-device - if (options.baseUrl) { - requestDefaults.baseUrl = options.baseUrl; - } + const authentication = await waitForAccessToken(options.request || state.request, state.clientId, state.clientType, verification); + state.authentication = authentication; + return authentication; +} - if (options.previews) { - requestDefaults.mediaType.previews = options.previews; - } +function getCachedAuthentication(state, auth) { + if (auth.refresh === true) return false; + if (!state.authentication) return false; - if (options.timeZone) { - requestDefaults.headers["time-zone"] = options.timeZone; - } + if (state.clientType === "github-app") { + return state.authentication; + } - 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`. + const authentication = state.authentication; + const newScope = ("scopes" in auth && auth.scopes || state.scopes).join(" "); + const currentScope = authentication.scopes.join(" "); + return newScope === currentScope ? authentication : false; +} - if (!options.authStrategy) { - if (!options.auth) { - // (1) - this.auth = async () => ({ - type: "unauthenticated" - }); - } else { - // (2) - const auth = authToken.createTokenAuth(options.auth); // @ts-ignore ¯\_(ツ)_/¯ +async function wait(seconds) { + await new Promise(resolve => setTimeout(resolve, seconds * 1000)); +} - hook.wrap("request", auth.hook); - this.auth = auth; - } - } else { - const { - authStrategy - } = options, - otherOptions = _objectWithoutProperties(options, _excluded); +async function waitForAccessToken(request, clientId, clientType, verification) { + try { + const options = { + clientId, + request, + code: verification.device_code + }; // WHY TYPESCRIPT WHY ARE YOU DOING THIS TO ME - 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 ¯\_(ツ)_/¯ + const { + authentication + } = clientType === "oauth-app" ? await oauthMethods.exchangeDeviceCode(_objectSpread2(_objectSpread2({}, options), {}, { + clientType: "oauth-app" + })) : await oauthMethods.exchangeDeviceCode(_objectSpread2(_objectSpread2({}, options), {}, { + clientType: "github-app" + })); + return _objectSpread2({ + type: "token", + tokenType: "oauth" + }, authentication); + } catch (error) { + // istanbul ignore if + if (!error.response) throw error; + const errorType = error.response.data.error; - hook.wrap("request", auth.hook); - this.auth = auth; - } // apply plugins - // https://stackoverflow.com/a/16345172 + if (errorType === "authorization_pending") { + await wait(verification.interval); + return waitForAccessToken(request, clientId, clientType, verification); + } + if (errorType === "slow_down") { + await wait(verification.interval + 5); + return waitForAccessToken(request, clientId, clientType, verification); + } - const classConstructor = this.constructor; - classConstructor.plugins.forEach(plugin => { - Object.assign(this, plugin(this, options)); - }); + throw error; } +} - static defaults(defaults) { - const OctokitWithDefaults = class extends this { - constructor(...args) { - const options = args[0] || {}; - - if (typeof defaults === "function") { - super(defaults(options)); - return; - } +async function auth(state, authOptions) { + return getOAuthAccessToken(state, { + auth: authOptions + }); +} - super(Object.assign({}, defaults, options, options.userAgent && defaults.userAgent ? { - userAgent: `${options.userAgent} ${defaults.userAgent}` - } : null)); - } +async function hook(state, request, route, parameters) { + let endpoint = request.endpoint.merge(route, parameters); // Do not intercept request to retrieve codes or token - }; - return OctokitWithDefaults; + if (/\/login\/(oauth\/access_token|device\/code)$/.test(endpoint.url)) { + return request(endpoint); } - /** - * Attach a plugin (or many) to your Octokit instance. - * - * @example - * const API = Octokit.plugin(plugin1, plugin2, plugin3, ...) - */ + const { + token + } = await getOAuthAccessToken(state, { + request, + auth: { + type: "oauth" + } + }); + endpoint.headers.authorization = `token ${token}`; + return request(endpoint); +} - static plugin(...newPlugins) { - var _a; +const VERSION = "3.1.2"; - const currentPlugins = this.plugins; - const NewOctokit = (_a = class extends this {}, _a.plugins = currentPlugins.concat(newPlugins.filter(plugin => !currentPlugins.includes(plugin))), _a); - return NewOctokit; +function createOAuthDeviceAuth(options) { + const requestWithDefaults = options.request || request.request.defaults({ + headers: { + "user-agent": `octokit-auth-oauth-device.js/${VERSION} ${universalUserAgent.getUserAgent()}` + } + }); + + const { + request: request$1 = requestWithDefaults + } = options, + otherOptions = _objectWithoutProperties(options, ["request"]); + + const state = options.clientType === "github-app" ? _objectSpread2(_objectSpread2({}, otherOptions), {}, { + clientType: "github-app", + request: request$1 + }) : _objectSpread2(_objectSpread2({}, otherOptions), {}, { + clientType: "oauth-app", + request: request$1, + scopes: options.scopes || [] + }); + + if (!options.clientId) { + throw new Error('[@octokit/auth-oauth-device] "clientId" option must be set (https://github.com/octokit/auth-oauth-device.js#usage)'); } + if (!options.onVerification) { + throw new Error('[@octokit/auth-oauth-device] "onVerification" option must be a function (https://github.com/octokit/auth-oauth-device.js#usage)'); + } // @ts-ignore too much for tsc / ts-jest ¯\_(ツ)_/¯ + + + return Object.assign(auth.bind(null, state), { + hook: hook.bind(null, state) + }); } -Octokit.VERSION = VERSION; -Octokit.plugins = []; -exports.Octokit = Octokit; +exports.createOAuthDeviceAuth = createOAuthDeviceAuth; //# sourceMappingURL=index.js.map /***/ }), -/***/ 59440: +/***/ 11591: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -4349,585 +4457,482 @@ exports.Octokit = Octokit; Object.defineProperty(exports, "__esModule", ({ value: true })); -var isPlainObject = __nccwpck_require__(63287); +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } + var universalUserAgent = __nccwpck_require__(45030); +var request = __nccwpck_require__(36234); +var authOauthDevice = __nccwpck_require__(44344); +var oauthMethods = __nccwpck_require__(88445); +var btoa = _interopDefault(__nccwpck_require__(72358)); -function lowercaseKeys(object) { - if (!object) { - return {}; - } +function ownKeys(object, enumerableOnly) { + var keys = Object.keys(object); - return Object.keys(object).reduce((newObj, key) => { - newObj[key.toLowerCase()] = object[key]; - return newObj; - }, {}); -} + if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(object); -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] + if (enumerableOnly) { + symbols = symbols.filter(function (sym) { + return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } - }); - return result; + + keys.push.apply(keys, symbols); + } + + return keys; } -function removeUndefinedProperties(obj) { - for (const key in obj) { - if (obj[key] === undefined) { - delete obj[key]; +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 obj; + return target; } -function merge(defaults, route, options) { - if (typeof route === "string") { - let [method, url] = route.split(" "); - options = Object.assign(url ? { - method, - url - } : { - url: method - }, options); +function _defineProperty(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); } else { - options = Object.assign({}, route); - } // lowercase header names before merging with defaults to avoid duplicates - + obj[key] = value; + } - options.headers = lowercaseKeys(options.headers); // remove properties with undefined values before merging + return obj; +} - removeUndefinedProperties(options); - removeUndefinedProperties(options.headers); - const mergedOptions = mergeDeep(defaults || {}, options); // mediaType.previews arrays are merged, instead of overwritten +function _objectWithoutPropertiesLoose(source, excluded) { + if (source == null) return {}; + var target = {}; + var sourceKeys = Object.keys(source); + var key, i; - if (defaults && defaults.mediaType.previews.length) { - mergedOptions.mediaType.previews = defaults.mediaType.previews.filter(preview => !mergedOptions.mediaType.previews.includes(preview)).concat(mergedOptions.mediaType.previews); + for (i = 0; i < sourceKeys.length; i++) { + key = sourceKeys[i]; + if (excluded.indexOf(key) >= 0) continue; + target[key] = source[key]; } - mergedOptions.mediaType.previews = mergedOptions.mediaType.previews.map(preview => preview.replace(/-preview/, "")); - return mergedOptions; + return target; } -function addQueryParameters(url, parameters) { - const separator = /\?/.test(url) ? "&" : "?"; - const names = Object.keys(parameters); - - if (names.length === 0) { - return url; - } - - return url + separator + names.map(name => { - if (name === "q") { - return "q=" + parameters.q.split("+").map(encodeURIComponent).join("+"); - } - - return `${name}=${encodeURIComponent(parameters[name])}`; - }).join("&"); -} +function _objectWithoutProperties(source, excluded) { + if (source == null) return {}; -const urlVariableRegex = /\{[^}]+\}/g; + var target = _objectWithoutPropertiesLoose(source, excluded); -function removeNonChars(variableName) { - return variableName.replace(/^\W+|\W+$/g, "").split(/,/); -} + var key, i; -function extractUrlVariableNames(url) { - const matches = url.match(urlVariableRegex); + if (Object.getOwnPropertySymbols) { + var sourceSymbolKeys = Object.getOwnPropertySymbols(source); - if (!matches) { - return []; + 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]; + } } - 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; - }, {}); + return target; } -// 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. +const VERSION = "1.3.0"; -/* 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, "]"); - } +async function getAuthentication(state) { + // handle code exchange form OAuth Web Flow + if ("code" in state.strategyOptions) { + const { + authentication + } = await oauthMethods.exchangeWebFlowCode(_objectSpread2(_objectSpread2({ + clientId: state.clientId, + clientSecret: state.clientSecret, + clientType: state.clientType + }, state.strategyOptions), {}, { + request: state.request + })); + return _objectSpread2({ + type: "token", + tokenType: "oauth" + }, authentication); + } // handle OAuth device flow - return part; - }).join(""); -} -function encodeUnreserved(str) { - return encodeURIComponent(str).replace(/[!'()*]/g, function (c) { - return "%" + c.charCodeAt(0).toString(16).toUpperCase(); - }); -} + if ("onVerification" in state.strategyOptions) { + const deviceAuth = authOauthDevice.createOAuthDeviceAuth(_objectSpread2(_objectSpread2({ + clientType: state.clientType, + clientId: state.clientId + }, state.strategyOptions), {}, { + request: state.request + })); + const authentication = await deviceAuth({ + type: "oauth" + }); + return _objectSpread2({ + clientSecret: state.clientSecret + }, authentication); + } // use existing authentication -function encodeValue(operator, value, key) { - value = operator === "+" || operator === "#" ? encodeReserved(value) : encodeUnreserved(value); - if (key) { - return encodeUnreserved(key) + "=" + value; - } else { - return value; + if ("token" in state.strategyOptions) { + return _objectSpread2({ + type: "token", + tokenType: "oauth", + clientId: state.clientId, + clientSecret: state.clientSecret, + clientType: state.clientType + }, state.strategyOptions); } -} - -function isDefined(value) { - return value !== undefined && value !== null; -} -function isKeyOperator(operator) { - return operator === ";" || operator === "&" || operator === "?"; + throw new Error("[@octokit/auth-oauth-user] Invalid strategy options"); } -function getValues(context, operator, key, modifier) { - var value = context[key], - result = []; +async function auth(state, options = {}) { + if (!state.authentication) { + // This is what TS makes us do ¯\_(ツ)_/¯ + state.authentication = state.clientType === "oauth-app" ? await getAuthentication(state) : await getAuthentication(state); + } - if (isDefined(value) && value !== "") { - if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") { - value = value.toString(); + if (state.authentication.invalid) { + throw new Error("[@octokit/auth-oauth-user] Token is invalid"); + } - if (modifier && modifier !== "*") { - value = value.substring(0, parseInt(modifier, 10)); - } + const currentAuthentication = state.authentication; // (auto) refresh for user-to-server tokens - 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 = []; + if ("expiresAt" in currentAuthentication) { + if (options.type === "refresh" || new Date(currentAuthentication.expiresAt) < new Date()) { + const { + authentication + } = await oauthMethods.refreshToken({ + clientType: "github-app", + clientId: state.clientId, + clientSecret: state.clientSecret, + refreshToken: currentAuthentication.refreshToken, + request: state.request + }); + state.authentication = _objectSpread2({ + tokenType: "oauth", + type: "token" + }, authentication); + } + } // throw error for invalid refresh call - 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(""); + if (options.type === "refresh") { + if (state.clientType === "oauth-app") { + throw new Error("[@octokit/auth-oauth-user] OAuth Apps do not support expiring tokens"); } - } - - return result; -} -function parseUrl(template) { - return { - expand: expand.bind(null, template) - }; -} + if (!currentAuthentication.hasOwnProperty("expiresAt")) { + throw new Error("[@octokit/auth-oauth-user] Refresh token missing"); + } + } // check or reset token -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); - } + if (options.type === "check" || options.type === "reset") { + const method = options.type === "check" ? oauthMethods.checkToken : oauthMethods.resetToken; - expression.split(/,/g).forEach(function (variable) { - var tmp = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable); - values.push(getValues(context, operator, tmp[1], tmp[2] || tmp[3])); + try { + const { + authentication + } = await method({ + // @ts-expect-error making TS happy would require unnecessary code so no + clientType: state.clientType, + clientId: state.clientId, + clientSecret: state.clientSecret, + token: state.authentication.token, + request: state.request }); + state.authentication = _objectSpread2({ + tokenType: "oauth", + type: "token" + }, authentication); + return state.authentication; + } catch (error) { + // istanbul ignore else + if (error.status === 404) { + error.message = "[@octokit/auth-oauth-user] Token is invalid"; // @ts-expect-error TBD - 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(","); + state.authentication.invalid = true; } - } else { - return encodeReserved(literal); + + throw error; } - }); -} + } // invalidate -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 + if (options.type === "delete" || options.type === "deleteAuthorization") { + const method = options.type === "delete" ? oauthMethods.deleteToken : oauthMethods.deleteAuthorization; - const urlVariableNames = extractUrlVariableNames(url); - url = parseUrl(url).expand(parameters); + try { + await method({ + // @ts-expect-error making TS happy would require unnecessary code so no + clientType: state.clientType, + clientId: state.clientId, + clientSecret: state.clientSecret, + token: state.authentication.token, + request: state.request + }); + } catch (error) { + // istanbul ignore if + if (error.status !== 404) throw error; + } - if (!/^http/.test(url)) { - url = options.baseUrl + url; + state.authentication.invalid = true; + return state.authentication; } - 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); + return state.authentication; +} - 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(","); - } +/** + * The following endpoints require an OAuth App to authenticate using its client_id and client_secret. + * + * - [`POST /applications/{client_id}/token`](https://docs.github.com/en/rest/reference/apps#check-a-token) - Check a token + * - [`PATCH /applications/{client_id}/token`](https://docs.github.com/en/rest/reference/apps#reset-a-token) - Reset a token + * - [`POST /applications/{client_id}/token/scoped`](https://docs.github.com/en/rest/reference/apps#create-a-scoped-access-token) - Create a scoped access token + * - [`DELETE /applications/{client_id}/token`](https://docs.github.com/en/rest/reference/apps#delete-an-app-token) - Delete an app token + * - [`DELETE /applications/{client_id}/grant`](https://docs.github.com/en/rest/reference/apps#delete-an-app-authorization) - Delete an app authorization + * + * deprecated: + * + * - [`GET /applications/{client_id}/tokens/{access_token}`](https://docs.github.com/en/rest/reference/apps#check-an-authorization) - Check an authorization + * - [`POST /applications/{client_id}/tokens/{access_token}`](https://docs.github.com/en/rest/reference/apps#reset-an-authorization) - Reset an authorization + * - [`DELETE /applications/{client_id}/tokens/{access_token}`](https://docs.github.com/en/rest/reference/apps#revoke-an-authorization-for-an-application) - Revoke an authorization for an application + * - [`DELETE /applications/{client_id}/grants/{access_token}`](https://docs.github.com/en/rest/reference/apps#revoke-a-grant-for-an-application) - Revoke a grant for an application + */ +const ROUTES_REQUIRING_BASIC_AUTH = /\/applications\/[^/]+\/(token|grant)s?/; +function requiresBasicAuth(url) { + return url && ROUTES_REQUIRING_BASIC_AUTH.test(url); +} - 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 +async function hook(state, request, route, parameters = {}) { + const endpoint = request.endpoint.merge(route, parameters); // Do not intercept OAuth Web/Device flow request + if (/\/login\/(oauth\/access_token|device\/code)$/.test(endpoint.url)) { + return request(endpoint); + } - 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; + if (requiresBasicAuth(endpoint.url)) { + const credentials = btoa(`${state.clientId}:${state.clientSecret}`); + endpoint.headers.authorization = `basic ${credentials}`; + return request(endpoint); + } // TS makes us do this ¯\_(ツ)_/¯ + + + const { + token + } = state.clientType === "oauth-app" ? await auth(_objectSpread2(_objectSpread2({}, state), {}, { + request + })) : await auth(_objectSpread2(_objectSpread2({}, state), {}, { + request + })); + endpoint.headers.authorization = "token " + token; + return request(endpoint); +} + +const _excluded = ["clientId", "clientSecret", "clientType", "request"]; +function createOAuthUserAuth(_ref) { + let { + clientId, + clientSecret, + clientType = "oauth-app", + request: request$1 = request.request.defaults({ + headers: { + "user-agent": `octokit-auth-oauth-app.js/${VERSION} ${universalUserAgent.getUserAgent()}` } - } - } // default content-type for JSON if body is set + }) + } = _ref, + strategyOptions = _objectWithoutProperties(_ref, _excluded); + + const state = Object.assign({ + clientType, + clientId, + clientSecret, + strategyOptions, + request: request$1 + }); // @ts-expect-error not worth the extra code needed to appease TS + return Object.assign(auth.bind(null, state), { + // @ts-expect-error not worth the extra code needed to appease TS + hook: hook.bind(null, state) + }); +} +createOAuthUserAuth.VERSION = VERSION; - 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 +exports.createOAuthUserAuth = createOAuthUserAuth; +exports.requiresBasicAuth = requiresBasicAuth; +//# sourceMappingURL=index.js.map - if (["PATCH", "PUT"].includes(method) && typeof body === "undefined") { - body = ""; - } // Only return body/request keys if present +/***/ }), +/***/ 40334: +/***/ ((__unused_webpack_module, exports) => { - return Object.assign({ - method, - url, - headers - }, typeof body !== "undefined" ? { - body - } : null, options.request ? { - request: options.request - } : null); -} +"use strict"; -function endpointWithDefaults(defaults, route, options) { - return parse(merge(defaults, route, options)); + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +const REGEX_IS_INSTALLATION_LEGACY = /^v1\./; +const REGEX_IS_INSTALLATION = /^ghs_/; +const REGEX_IS_USER_TO_SERVER = /^ghu_/; +async function auth(token) { + const isApp = token.split(/\./).length === 3; + const isInstallation = REGEX_IS_INSTALLATION_LEGACY.test(token) || REGEX_IS_INSTALLATION.test(token); + const isUserToServer = REGEX_IS_USER_TO_SERVER.test(token); + const tokenType = isApp ? "app" : isInstallation ? "installation" : isUserToServer ? "user-to-server" : "oauth"; + return { + type: "token", + token: token, + tokenType + }; } -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 - }); +/** + * 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}`; } -const VERSION = "6.0.12"; +async function hook(token, request, route, parameters) { + const endpoint = request.endpoint.merge(route, parameters); + endpoint.headers.authorization = withAuthorizationPrefix(token); + return request(endpoint); +} -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 createTokenAuth = function createTokenAuth(token) { + if (!token) { + throw new Error("[@octokit/auth-token] No token passed to createTokenAuth"); + } -const DEFAULTS = { - method: "GET", - baseUrl: "https://api.github.com", - headers: { - accept: "application/vnd.github.v3+json", - "user-agent": userAgent - }, - mediaType: { - format: "", - previews: [] + if (typeof token !== "string") { + throw new Error("[@octokit/auth-token] Token passed to createTokenAuth is not a string"); } -}; -const endpoint = withDefaults(null, DEFAULTS); + token = token.replace(/^(token|bearer) +/i, ""); + return Object.assign(auth.bind(null, token), { + hook: hook.bind(null, token) + }); +}; -exports.endpoint = endpoint; +exports.createTokenAuth = createTokenAuth; //# sourceMappingURL=index.js.map /***/ }), -/***/ 88467: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 79567: +/***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -var request = __nccwpck_require__(36234); -var universalUserAgent = __nccwpck_require__(45030); - -const VERSION = "4.8.0"; - -function _buildMessageForResponseErrors(data) { - return `Request failed due to following response errors:\n` + data.errors.map(e => ` - ${e.message}`).join("\n"); +async function auth(reason) { + return { + type: "unauthenticated", + reason + }; } -class GraphqlResponseError extends Error { - constructor(request, headers, response) { - super(_buildMessageForResponseErrors(response)); - this.request = request; - this.headers = headers; - this.response = response; - this.name = "GraphqlResponseError"; // Expose the errors and response data in their shorthand properties. +function isRateLimitError(error) { + if (error.status !== 403) { + return false; + } + /* istanbul ignore if */ - this.errors = response.errors; - this.data = response.data; // Maintains proper stack trace (only available on V8) - /* istanbul ignore next */ + if (!error.response) { + return false; + } - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } + return error.response.headers["x-ratelimit-remaining"] === "0"; +} + +const REGEX_ABUSE_LIMIT_MESSAGE = /\babuse\b/i; +function isAbuseLimitError(error) { + if (error.status !== 403) { + return false; } + return REGEX_ABUSE_LIMIT_MESSAGE.test(error.message); } -const NON_VARIABLE_OPTIONS = ["method", "baseUrl", "url", "headers", "request", "query", "mediaType"]; -const FORBIDDEN_VARIABLE_OPTIONS = ["query", "method", "url"]; -const GHES_V3_SUFFIX_REGEX = /\/api\/v3\/?$/; -function graphql(request, query, options) { - if (options) { - if (typeof query === "string" && "query" in options) { - return Promise.reject(new Error(`[@octokit/graphql] "query" cannot be used as variable name`)); +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; } - for (const key in options) { - if (!FORBIDDEN_VARIABLE_OPTIONS.includes(key)) continue; - return Promise.reject(new Error(`[@octokit/graphql] "${key}" cannot be used as variable name`)); + if (isRateLimitError(error)) { + error.message = `API rate limit exceeded. This maybe caused by the 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 (isAbuseLimitError(error)) { + error.message = `You have triggered an abuse detection mechanism. This maybe caused by the lack of authentication. Reason: ${reason}`; + throw error; } - if (!result.variables) { - result.variables = {}; + if (error.status === 401) { + error.message = `Unauthorized. "${endpoint.method} ${endpoint.url}" failed most likely due to 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 - - 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 = {}; - - for (const key of Object.keys(response.headers)) { - headers[key] = response.headers[key]; - } - - throw new GraphqlResponseError(requestOptions, headers, response.data); + if (error.status >= 400 && error.status < 500) { + error.message = error.message.replace(/\.?$/, `. May be caused by lack of authentication (${reason}).`); } - 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" + throw error; }); } -exports.GraphqlResponseError = GraphqlResponseError; -exports.graphql = graphql$1; -exports.withCustomRequest = withCustomRequest; -//# sourceMappingURL=index.js.map - - -/***/ }), - -/***/ 51017: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ value: true })); - -function oauthAuthorizationUrl(options) { - const clientType = options.clientType || "oauth-app"; - const baseUrl = options.baseUrl || "https://github.com"; - const result = { - clientType, - allowSignup: options.allowSignup === false ? false : true, - clientId: options.clientId, - login: options.login || null, - redirectUrl: options.redirectUrl || null, - state: options.state || Math.random().toString(36).substr(2), - url: "" - }; - - if (clientType === "oauth-app") { - const scopes = "scopes" in options ? options.scopes : []; - result.scopes = typeof scopes === "string" ? scopes.split(/[,\s]+/).filter(Boolean) : scopes; +const createUnauthenticatedAuth = function createUnauthenticatedAuth(options) { + if (!options || !options.reason) { + throw new Error("[@octokit/auth-unauthenticated] No reason passed to createUnauthenticatedAuth"); } - result.url = urlBuilderAuthorize(`${baseUrl}/login/oauth/authorize`, result); - return result; -} - -function urlBuilderAuthorize(base, options) { - const map = { - allowSignup: "allow_signup", - clientId: "client_id", - login: "login", - redirectUrl: "redirect_uri", - scopes: "scope", - state: "state" - }; - let url = base; - Object.keys(map) // Filter out keys that are null and remove the url key - .filter(k => options[k] !== null) // Filter out empty scopes array - .filter(k => { - if (k !== "scopes") return true; - if (options.clientType === "github-app") return false; - return !Array.isArray(options[k]) || options[k].length > 0; - }) // Map Array with the proper URL parameter names and change the value to a string using template strings - // @ts-ignore - .map(key => [map[key], `${options[key]}`]) // Finally, build the URL - .forEach(([key, value], index) => { - url += index === 0 ? `?` : "&"; - url += `${key}=${encodeURIComponent(value)}`; + return Object.assign(auth.bind(null, options.reason), { + hook: hook.bind(null, options.reason) }); - return url; -} +}; -exports.oauthAuthorizationUrl = oauthAuthorizationUrl; +exports.createUnauthenticatedAuth = createUnauthenticatedAuth; //# sourceMappingURL=index.js.map /***/ }), -/***/ 88445: +/***/ 76762: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -4935,671 +4940,707 @@ exports.oauthAuthorizationUrl = oauthAuthorizationUrl; Object.defineProperty(exports, "__esModule", ({ value: true })); -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - -var oauthAuthorizationUrl = __nccwpck_require__(51017); +var universalUserAgent = __nccwpck_require__(45030); +var beforeAfterHook = __nccwpck_require__(83682); var request = __nccwpck_require__(36234); -var requestError = __nccwpck_require__(10537); -var btoa = _interopDefault(__nccwpck_require__(72358)); +var graphql = __nccwpck_require__(88467); +var authToken = __nccwpck_require__(40334); -const VERSION = "1.2.6"; +function _objectWithoutPropertiesLoose(source, excluded) { + if (source == null) return {}; + var target = {}; + var sourceKeys = Object.keys(source); + var key, i; -function ownKeys(object, enumerableOnly) { - var keys = Object.keys(object); + for (i = 0; i < sourceKeys.length; i++) { + key = sourceKeys[i]; + if (excluded.indexOf(key) >= 0) continue; + target[key] = source[key]; + } - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(object); + return target; +} - if (enumerableOnly) { - symbols = symbols.filter(function (sym) { - return Object.getOwnPropertyDescriptor(object, sym).enumerable; - }); - } +function _objectWithoutProperties(source, excluded) { + if (source == null) return {}; - keys.push.apply(keys, symbols); - } + var target = _objectWithoutPropertiesLoose(source, excluded); - return keys; -} + var key, i; -function _objectSpread2(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? arguments[i] : {}; + if (Object.getOwnPropertySymbols) { + var sourceSymbolKeys = Object.getOwnPropertySymbols(source); - 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)); - }); + 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]; } } 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.5.1"; - return obj; -} +const _excluded = ["authStrategy"]; +class Octokit { + constructor(options = {}) { + const hook = new beforeAfterHook.Collection(); + const requestDefaults = { + baseUrl: request.request.endpoint.DEFAULTS.baseUrl, + headers: {}, + request: Object.assign({}, options.request, { + // @ts-ignore internal usage only, no need to type + hook: hook.bind(null, "request") + }), + mediaType: { + previews: [], + format: "" + } + }; // prepend default user agent with `options.userAgent` if set -function _objectWithoutPropertiesLoose(source, excluded) { - if (source == null) return {}; - var target = {}; - var sourceKeys = Object.keys(source); - var key, i; + requestDefaults.headers["user-agent"] = [options.userAgent, `octokit-core.js/${VERSION} ${universalUserAgent.getUserAgent()}`].filter(Boolean).join(" "); - for (i = 0; i < sourceKeys.length; i++) { - key = sourceKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - target[key] = source[key]; - } + if (options.baseUrl) { + requestDefaults.baseUrl = options.baseUrl; + } - return target; -} + if (options.previews) { + requestDefaults.mediaType.previews = options.previews; + } -function _objectWithoutProperties(source, excluded) { - if (source == null) return {}; + if (options.timeZone) { + requestDefaults.headers["time-zone"] = options.timeZone; + } - var target = _objectWithoutPropertiesLoose(source, excluded); + 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`. - var key, i; + if (!options.authStrategy) { + if (!options.auth) { + // (1) + this.auth = async () => ({ + type: "unauthenticated" + }); + } else { + // (2) + const auth = authToken.createTokenAuth(options.auth); // @ts-ignore ¯\_(ツ)_/¯ - if (Object.getOwnPropertySymbols) { - var sourceSymbolKeys = Object.getOwnPropertySymbols(source); + hook.wrap("request", auth.hook); + this.auth = auth; + } + } else { + const { + authStrategy + } = options, + otherOptions = _objectWithoutProperties(options, _excluded); - 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]; - } + 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)); + }); } - return target; -} + static defaults(defaults) { + const OctokitWithDefaults = class extends this { + constructor(...args) { + const options = args[0] || {}; -function requestToOAuthBaseUrl(request) { - const endpointDefaults = request.endpoint.DEFAULTS; - return /^https:\/\/(api\.)?github\.com$/.test(endpointDefaults.baseUrl) ? "https://github.com" : endpointDefaults.baseUrl.replace("/api/v3", ""); -} -async function oauthRequest(request, route, parameters) { - const withOAuthParameters = _objectSpread2({ - baseUrl: requestToOAuthBaseUrl(request), - headers: { - accept: "application/json" - } - }, parameters); + if (typeof defaults === "function") { + super(defaults(options)); + return; + } - const response = await request(route, withOAuthParameters); + super(Object.assign({}, defaults, options, options.userAgent && defaults.userAgent ? { + userAgent: `${options.userAgent} ${defaults.userAgent}` + } : null)); + } - if ("error" in response.data) { - const error = new requestError.RequestError(`${response.data.error_description} (${response.data.error}, ${response.data.error_uri})`, 400, { - request: request.endpoint.merge(route, withOAuthParameters), - headers: response.headers - }); // @ts-ignore add custom response property until https://github.com/octokit/request-error.js/issues/169 is resolved + }; + return OctokitWithDefaults; + } + /** + * Attach a plugin (or many) to your Octokit instance. + * + * @example + * const API = Octokit.plugin(plugin1, plugin2, plugin3, ...) + */ - error.response = response; - throw error; + + 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 response; } +Octokit.VERSION = VERSION; +Octokit.plugins = []; -const _excluded = ["request"]; -function getWebFlowAuthorizationUrl(_ref) { - let { - request: request$1 = request.request - } = _ref, - options = _objectWithoutProperties(_ref, _excluded); +exports.Octokit = Octokit; +//# sourceMappingURL=index.js.map - const baseUrl = requestToOAuthBaseUrl(request$1); // @ts-expect-error TypeScript wants `clientType` to be set explicitly ¯\_(ツ)_/¯ - return oauthAuthorizationUrl.oauthAuthorizationUrl(_objectSpread2(_objectSpread2({}, options), {}, { - baseUrl - })); -} +/***/ }), -async function exchangeWebFlowCode(options) { - const request$1 = options.request || - /* istanbul ignore next: we always pass a custom request in tests */ - request.request; - const response = await oauthRequest(request$1, "POST /login/oauth/access_token", { - client_id: options.clientId, - client_secret: options.clientSecret, - code: options.code, - redirect_uri: options.redirectUrl - }); - const authentication = { - clientType: options.clientType, - clientId: options.clientId, - clientSecret: options.clientSecret, - token: response.data.access_token, - scopes: response.data.scope.split(/\s+/).filter(Boolean) - }; +/***/ 59440: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (options.clientType === "github-app") { - if ("refresh_token" in response.data) { - const apiTimeInMs = new Date(response.headers.date).getTime(); - authentication.refreshToken = response.data.refresh_token, authentication.expiresAt = toTimestamp(apiTimeInMs, response.data.expires_in), authentication.refreshTokenExpiresAt = toTimestamp(apiTimeInMs, response.data.refresh_token_expires_in); - } +"use strict"; - delete authentication.scopes; + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +var isPlainObject = __nccwpck_require__(63287); +var universalUserAgent = __nccwpck_require__(45030); + +function lowercaseKeys(object) { + if (!object) { + return {}; } - return _objectSpread2(_objectSpread2({}, response), {}, { - authentication - }); + return Object.keys(object).reduce((newObj, key) => { + newObj[key.toLowerCase()] = object[key]; + return newObj; + }, {}); } -function toTimestamp(apiTimeInMs, expirationInSeconds) { - return new Date(apiTimeInMs + expirationInSeconds * 1000).toISOString(); +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 createDeviceCode(options) { - const request$1 = options.request || - /* istanbul ignore next: we always pass a custom request in tests */ - request.request; - const parameters = { - client_id: options.clientId - }; - - if ("scopes" in options && Array.isArray(options.scopes)) { - parameters.scope = options.scopes.join(" "); +function removeUndefinedProperties(obj) { + for (const key in obj) { + if (obj[key] === undefined) { + delete obj[key]; + } } - return oauthRequest(request$1, "POST /login/device/code", parameters); + return obj; } -async function exchangeDeviceCode(options) { - const request$1 = options.request || - /* istanbul ignore next: we always pass a custom request in tests */ - request.request; - const response = await oauthRequest(request$1, "POST /login/oauth/access_token", { - client_id: options.clientId, - device_code: options.code, - grant_type: "urn:ietf:params:oauth:grant-type:device_code" - }); - const authentication = { - clientType: options.clientType, - clientId: options.clientId, - token: response.data.access_token, - scopes: response.data.scope.split(/\s+/).filter(Boolean) - }; +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 - if ("clientSecret" in options) { - authentication.clientSecret = options.clientSecret; + + options.headers = lowercaseKeys(options.headers); // remove properties with undefined values before merging + + 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); } - if (options.clientType === "github-app") { - if ("refresh_token" in response.data) { - const apiTimeInMs = new Date(response.headers.date).getTime(); - authentication.refreshToken = response.data.refresh_token, authentication.expiresAt = toTimestamp$1(apiTimeInMs, response.data.expires_in), authentication.refreshTokenExpiresAt = toTimestamp$1(apiTimeInMs, response.data.refresh_token_expires_in); - } + mergedOptions.mediaType.previews = mergedOptions.mediaType.previews.map(preview => preview.replace(/-preview/, "")); + return mergedOptions; +} - delete authentication.scopes; +function addQueryParameters(url, parameters) { + const separator = /\?/.test(url) ? "&" : "?"; + const names = Object.keys(parameters); + + if (names.length === 0) { + return url; } - return _objectSpread2(_objectSpread2({}, response), {}, { - authentication - }); + return url + separator + names.map(name => { + if (name === "q") { + return "q=" + parameters.q.split("+").map(encodeURIComponent).join("+"); + } + + return `${name}=${encodeURIComponent(parameters[name])}`; + }).join("&"); } -function toTimestamp$1(apiTimeInMs, expirationInSeconds) { - return new Date(apiTimeInMs + expirationInSeconds * 1000).toISOString(); +const urlVariableRegex = /\{[^}]+\}/g; + +function removeNonChars(variableName) { + return variableName.replace(/^\W+|\W+$/g, "").split(/,/); } -async function checkToken(options) { - const request$1 = options.request || - /* istanbul ignore next: we always pass a custom request in tests */ - request.request; - const response = await request$1("POST /applications/{client_id}/token", { - headers: { - authorization: `basic ${btoa(`${options.clientId}:${options.clientSecret}`)}` - }, - client_id: options.clientId, - access_token: options.token - }); - const authentication = { - clientType: options.clientType, - clientId: options.clientId, - clientSecret: options.clientSecret, - token: options.token, - scopes: response.data.scopes - }; - if (response.data.expires_at) authentication.expiresAt = response.data.expires_at; +function extractUrlVariableNames(url) { + const matches = url.match(urlVariableRegex); - if (options.clientType === "github-app") { - delete authentication.scopes; + if (!matches) { + return []; } - return _objectSpread2(_objectSpread2({}, response), {}, { - authentication - }); + return matches.map(removeNonChars).reduce((a, b) => a.concat(b), []); } -async function refreshToken(options) { - const request$1 = options.request || - /* istanbul ignore next: we always pass a custom request in tests */ - request.request; - const response = await oauthRequest(request$1, "POST /login/oauth/access_token", { - client_id: options.clientId, - client_secret: options.clientSecret, - grant_type: "refresh_token", - refresh_token: options.refreshToken - }); - const apiTimeInMs = new Date(response.headers.date).getTime(); - const authentication = { - clientType: "github-app", - clientId: options.clientId, - clientSecret: options.clientSecret, - token: response.data.access_token, - refreshToken: response.data.refresh_token, - expiresAt: toTimestamp$2(apiTimeInMs, response.data.expires_in), - refreshTokenExpiresAt: toTimestamp$2(apiTimeInMs, response.data.refresh_token_expires_in) - }; - return _objectSpread2(_objectSpread2({}, response), {}, { - authentication - }); +function omit(object, keysToOmit) { + return Object.keys(object).filter(option => !keysToOmit.includes(option)).reduce((obj, key) => { + obj[key] = object[key]; + return obj; + }, {}); } -function toTimestamp$2(apiTimeInMs, expirationInSeconds) { - return new Date(apiTimeInMs + expirationInSeconds * 1000).toISOString(); -} +// 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. -const _excluded$1 = ["request", "clientType", "clientId", "clientSecret", "token"]; -async function scopeToken(options) { - const { - request: request$1, - clientType, - clientId, - clientSecret, - token - } = options, - requestOptions = _objectWithoutProperties(options, _excluded$1); +/* 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, "]"); + } - const response = await (request$1 || - /* istanbul ignore next: we always pass a custom request in tests */ - request.request)("POST /applications/{client_id}/token/scoped", _objectSpread2({ - headers: { - authorization: `basic ${btoa(`${clientId}:${clientSecret}`)}` - }, - client_id: clientId, - access_token: token - }, requestOptions)); - const authentication = Object.assign({ - clientType, - clientId, - clientSecret, - token: response.data.token - }, response.data.expires_at ? { - expiresAt: response.data.expires_at - } : {}); - return _objectSpread2(_objectSpread2({}, response), {}, { - authentication - }); + return part; + }).join(""); } -async function resetToken(options) { - const request$1 = options.request || - /* istanbul ignore next: we always pass a custom request in tests */ - request.request; - const auth = btoa(`${options.clientId}:${options.clientSecret}`); - const response = await request$1("PATCH /applications/{client_id}/token", { - headers: { - authorization: `basic ${auth}` - }, - client_id: options.clientId, - access_token: options.token +function encodeUnreserved(str) { + return encodeURIComponent(str).replace(/[!'()*]/g, function (c) { + return "%" + c.charCodeAt(0).toString(16).toUpperCase(); }); - const authentication = { - clientType: options.clientType, - clientId: options.clientId, - clientSecret: options.clientSecret, - token: response.data.token, - scopes: response.data.scopes - }; - if (response.data.expires_at) authentication.expiresAt = response.data.expires_at; +} - if (options.clientType === "github-app") { - delete authentication.scopes; - } +function encodeValue(operator, value, key) { + value = operator === "+" || operator === "#" ? encodeReserved(value) : encodeUnreserved(value); - return _objectSpread2(_objectSpread2({}, response), {}, { - authentication - }); + if (key) { + return encodeUnreserved(key) + "=" + value; + } else { + return value; + } } -async function deleteToken(options) { - const request$1 = options.request || - /* istanbul ignore next: we always pass a custom request in tests */ - request.request; - const auth = btoa(`${options.clientId}:${options.clientSecret}`); - return request$1("DELETE /applications/{client_id}/token", { - headers: { - authorization: `basic ${auth}` - }, - client_id: options.clientId, - access_token: options.token - }); +function isDefined(value) { + return value !== undefined && value !== null; } -async function deleteAuthorization(options) { - const request$1 = options.request || - /* istanbul ignore next: we always pass a custom request in tests */ - request.request; - const auth = btoa(`${options.clientId}:${options.clientSecret}`); - return request$1("DELETE /applications/{client_id}/grant", { - headers: { - authorization: `basic ${auth}` - }, - client_id: options.clientId, - access_token: options.token - }); +function isKeyOperator(operator) { + return operator === ";" || operator === "&" || operator === "?"; } -exports.VERSION = VERSION; -exports.checkToken = checkToken; -exports.createDeviceCode = createDeviceCode; -exports.deleteAuthorization = deleteAuthorization; -exports.deleteToken = deleteToken; -exports.exchangeDeviceCode = exchangeDeviceCode; -exports.exchangeWebFlowCode = exchangeWebFlowCode; -exports.getWebFlowAuthorizationUrl = getWebFlowAuthorizationUrl; -exports.refreshToken = refreshToken; -exports.resetToken = resetToken; -exports.scopeToken = scopeToken; -//# sourceMappingURL=index.js.map +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 (modifier && modifier !== "*") { + value = value.substring(0, parseInt(modifier, 10)); + } -/***/ 25823: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + 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 = []; -"use strict"; + 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(""); + } + } + return result; +} -Object.defineProperty(exports, "__esModule", ({ value: true })); +function parseUrl(template) { + return { + expand: expand.bind(null, template) + }; +} -var requestError = __nccwpck_require__(10537); +function expand(template, context) { + var operators = ["+", "#", ".", "/", ";", "?", "&"]; + return template.replace(/\{([^\{\}]+)\}|([^\{\}]+)/g, function (_, expression, literal) { + if (expression) { + let operator = ""; + const values = []; -const VERSION = "1.3.0"; + if (operators.indexOf(expression.charAt(0)) !== -1) { + operator = expression.charAt(0); + expression = expression.substr(1); + } -function enterpriseCompatibility(octokit) { - octokit.hook.wrap("request", async (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; - } + expression.split(/,/g).forEach(function (variable) { + var tmp = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable); + values.push(getValues(context, operator, tmp[1], tmp[2] || tmp[3])); + }); - if (!error.response || !error.response.headers["x-github-enterprise-version"]) { - throw error; + if (operator && operator !== "+") { + var separator = ","; + + if (operator === "?") { + separator = "&"; + } else if (operator !== "#") { + separator = operator; } - 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 (values.length !== 0 ? operator : "") + values.join(separator); + } else { + return values.join(","); } + } else { + return encodeReserved(literal); } - - return request(options); }); } -enterpriseCompatibility.VERSION = VERSION; - -exports.enterpriseCompatibility = enterpriseCompatibility; -//# sourceMappingURL=index.js.map +function parse(options) { + // https://fetch.spec.whatwg.org/#methods + let method = options.method.toUpperCase(); // replace :varname with {varname} to make it RFC 6570 compatible -/***/ }), - -/***/ 64193: -/***/ ((__unused_webpack_module, exports) => { + 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 -"use strict"; + const urlVariableNames = extractUrlVariableNames(url); + url = parseUrl(url).expand(parameters); + if (!/^http/.test(url)) { + url = options.baseUrl + url; + } -Object.defineProperty(exports, "__esModule", ({ value: true })); + 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); -const VERSION = "2.17.0"; + 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(","); + } -function ownKeys(object, enumerableOnly) { - var keys = Object.keys(object); + 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 (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(object); - if (enumerableOnly) { - symbols = symbols.filter(function (sym) { - return Object.getOwnPropertyDescriptor(object, sym).enumerable; - }); + 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 - keys.push.apply(keys, symbols); - } - return keys; -} + 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 -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)); - }); - } - } + if (["PATCH", "PUT"].includes(method) && typeof body === "undefined") { + body = ""; + } // Only return body/request keys if present - return target; + + return Object.assign({ + method, + url, + headers + }, typeof body !== "undefined" ? { + body + } : null, options.request ? { + request: options.request + } : null); } -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; - } +function endpointWithDefaults(defaults, route, options) { + return parse(merge(defaults, route, options)); +} - return obj; +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 + }); } -/** - * 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) { - // endpoints can respond with 204 if repository is empty - if (!response.data) { - return _objectSpread2(_objectSpread2({}, response), {}, { - data: [] - }); +const VERSION = "6.0.12"; + +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 + }, + mediaType: { + format: "", + previews: [] } +}; - 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 endpoint = withDefaults(null, DEFAULTS); - 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; +exports.endpoint = endpoint; +//# sourceMappingURL=index.js.map - if (typeof incompleteResults !== "undefined") { - response.data.incomplete_results = incompleteResults; - } - if (typeof repositorySelection !== "undefined") { - response.data.repository_selection = repositorySelection; - } +/***/ }), - response.data.total_count = totalCount; - return response; -} +/***/ 88467: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -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 - }; +"use strict"; - try { - 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 - url = ((normalizedResponse.headers.link || "").match(/<([^>]+)>;\s*rel="next"/) || [])[1]; - return { - value: normalizedResponse - }; - } catch (error) { - if (error.status !== 409) throw error; - url = ""; - return { - value: { - status: 200, - headers: {}, - data: [] - } - }; - } - } +Object.defineProperty(exports, "__esModule", ({ value: true })); - }) - }; +var request = __nccwpck_require__(36234); +var universalUserAgent = __nccwpck_require__(45030); + +const VERSION = "4.8.0"; + +function _buildMessageForResponseErrors(data) { + return `Request failed due to following response errors:\n` + data.errors.map(e => ` - ${e.message}`).join("\n"); } -function paginate(octokit, route, parameters, mapFn) { - if (typeof parameters === "function") { - mapFn = parameters; - parameters = undefined; +class GraphqlResponseError extends Error { + constructor(request, headers, response) { + super(_buildMessageForResponseErrors(response)); + this.request = request; + this.headers = headers; + this.response = response; + this.name = "GraphqlResponseError"; // Expose the errors and response data in their shorthand properties. + + this.errors = response.errors; + this.data = response.data; // Maintains proper stack trace (only available on V8) + + /* istanbul ignore next */ + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } } - 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; +const NON_VARIABLE_OPTIONS = ["method", "baseUrl", "url", "headers", "request", "query", "mediaType"]; +const FORBIDDEN_VARIABLE_OPTIONS = ["query", "method", "url"]; +const GHES_V3_SUFFIX_REGEX = /\/api\/v3\/?$/; +function graphql(request, query, options) { + if (options) { + if (typeof query === "string" && "query" in options) { + return Promise.reject(new Error(`[@octokit/graphql] "query" cannot be used as variable name`)); } - let earlyExit = false; + for (const key in options) { + if (!FORBIDDEN_VARIABLE_OPTIONS.includes(key)) continue; + return Promise.reject(new Error(`[@octokit/graphql] "${key}" cannot be used as variable name`)); + } + } - function done() { - earlyExit = true; + 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; } - results = results.concat(mapFn ? mapFn(result.value, done) : result.value.data); + if (!result.variables) { + result.variables = {}; + } - if (earlyExit) { - return results; + 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 = {}; + + for (const key of Object.keys(response.headers)) { + headers[key] = response.headers[key]; + } + + throw new GraphqlResponseError(requestOptions, headers, response.data); } - return gather(octokit, results, iterator, mapFn); + return response.data.data; }); } -const composePaginateRest = Object.assign(paginate, { - iterator -}); +function withDefaults(request$1, newDefaults) { + const newRequest = request$1.defaults(newDefaults); -const paginatingEndpoints = ["GET /app/hook/deliveries", "GET /app/installations", "GET /applications/grants", "GET /authorizations", "GET /enterprises/{enterprise}/actions/permissions/organizations", "GET /enterprises/{enterprise}/actions/runner-groups", "GET /enterprises/{enterprise}/actions/runner-groups/{runner_group_id}/organizations", "GET /enterprises/{enterprise}/actions/runner-groups/{runner_group_id}/runners", "GET /enterprises/{enterprise}/actions/runners", "GET /enterprises/{enterprise}/actions/runners/downloads", "GET /events", "GET /gists", "GET /gists/public", "GET /gists/starred", "GET /gists/{gist_id}/comments", "GET /gists/{gist_id}/commits", "GET /gists/{gist_id}/forks", "GET /installation/repositories", "GET /issues", "GET /marketplace_listing/plans", "GET /marketplace_listing/plans/{plan_id}/accounts", "GET /marketplace_listing/stubbed/plans", "GET /marketplace_listing/stubbed/plans/{plan_id}/accounts", "GET /networks/{owner}/{repo}/events", "GET /notifications", "GET /organizations", "GET /orgs/{org}/actions/permissions/repositories", "GET /orgs/{org}/actions/runner-groups", "GET /orgs/{org}/actions/runner-groups/{runner_group_id}/repositories", "GET /orgs/{org}/actions/runner-groups/{runner_group_id}/runners", "GET /orgs/{org}/actions/runners", "GET /orgs/{org}/actions/runners/downloads", "GET /orgs/{org}/actions/secrets", "GET /orgs/{org}/actions/secrets/{secret_name}/repositories", "GET /orgs/{org}/blocks", "GET /orgs/{org}/credential-authorizations", "GET /orgs/{org}/events", "GET /orgs/{org}/failed_invitations", "GET /orgs/{org}/hooks", "GET /orgs/{org}/hooks/{hook_id}/deliveries", "GET /orgs/{org}/installations", "GET /orgs/{org}/invitations", "GET /orgs/{org}/invitations/{invitation_id}/teams", "GET /orgs/{org}/issues", "GET /orgs/{org}/members", "GET /orgs/{org}/migrations", "GET /orgs/{org}/migrations/{migration_id}/repositories", "GET /orgs/{org}/outside_collaborators", "GET /orgs/{org}/packages", "GET /orgs/{org}/projects", "GET /orgs/{org}/public_members", "GET /orgs/{org}/repos", "GET /orgs/{org}/secret-scanning/alerts", "GET /orgs/{org}/team-sync/groups", "GET /orgs/{org}/teams", "GET /orgs/{org}/teams/{team_slug}/discussions", "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments", "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions", "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions", "GET /orgs/{org}/teams/{team_slug}/invitations", "GET /orgs/{org}/teams/{team_slug}/members", "GET /orgs/{org}/teams/{team_slug}/projects", "GET /orgs/{org}/teams/{team_slug}/repos", "GET /orgs/{org}/teams/{team_slug}/team-sync/group-mappings", "GET /orgs/{org}/teams/{team_slug}/teams", "GET /projects/columns/{column_id}/cards", "GET /projects/{project_id}/collaborators", "GET /projects/{project_id}/columns", "GET /repos/{owner}/{repo}/actions/artifacts", "GET /repos/{owner}/{repo}/actions/runners", "GET /repos/{owner}/{repo}/actions/runners/downloads", "GET /repos/{owner}/{repo}/actions/runs", "GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts", "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs", "GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs", "GET /repos/{owner}/{repo}/actions/secrets", "GET /repos/{owner}/{repo}/actions/workflows", "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs", "GET /repos/{owner}/{repo}/assignees", "GET /repos/{owner}/{repo}/autolinks", "GET /repos/{owner}/{repo}/branches", "GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations", "GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs", "GET /repos/{owner}/{repo}/code-scanning/alerts", "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances", "GET /repos/{owner}/{repo}/code-scanning/analyses", "GET /repos/{owner}/{repo}/collaborators", "GET /repos/{owner}/{repo}/comments", "GET /repos/{owner}/{repo}/comments/{comment_id}/reactions", "GET /repos/{owner}/{repo}/commits", "GET /repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head", "GET /repos/{owner}/{repo}/commits/{commit_sha}/comments", "GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls", "GET /repos/{owner}/{repo}/commits/{ref}/check-runs", "GET /repos/{owner}/{repo}/commits/{ref}/check-suites", "GET /repos/{owner}/{repo}/commits/{ref}/statuses", "GET /repos/{owner}/{repo}/contributors", "GET /repos/{owner}/{repo}/deployments", "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses", "GET /repos/{owner}/{repo}/events", "GET /repos/{owner}/{repo}/forks", "GET /repos/{owner}/{repo}/git/matching-refs/{ref}", "GET /repos/{owner}/{repo}/hooks", "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries", "GET /repos/{owner}/{repo}/invitations", "GET /repos/{owner}/{repo}/issues", "GET /repos/{owner}/{repo}/issues/comments", "GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions", "GET /repos/{owner}/{repo}/issues/events", "GET /repos/{owner}/{repo}/issues/{issue_number}/comments", "GET /repos/{owner}/{repo}/issues/{issue_number}/events", "GET /repos/{owner}/{repo}/issues/{issue_number}/labels", "GET /repos/{owner}/{repo}/issues/{issue_number}/reactions", "GET /repos/{owner}/{repo}/issues/{issue_number}/timeline", "GET /repos/{owner}/{repo}/keys", "GET /repos/{owner}/{repo}/labels", "GET /repos/{owner}/{repo}/milestones", "GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels", "GET /repos/{owner}/{repo}/notifications", "GET /repos/{owner}/{repo}/pages/builds", "GET /repos/{owner}/{repo}/projects", "GET /repos/{owner}/{repo}/pulls", "GET /repos/{owner}/{repo}/pulls/comments", "GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions", "GET /repos/{owner}/{repo}/pulls/{pull_number}/comments", "GET /repos/{owner}/{repo}/pulls/{pull_number}/commits", "GET /repos/{owner}/{repo}/pulls/{pull_number}/files", "GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers", "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews", "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments", "GET /repos/{owner}/{repo}/releases", "GET /repos/{owner}/{repo}/releases/{release_id}/assets", "GET /repos/{owner}/{repo}/secret-scanning/alerts", "GET /repos/{owner}/{repo}/stargazers", "GET /repos/{owner}/{repo}/subscribers", "GET /repos/{owner}/{repo}/tags", "GET /repos/{owner}/{repo}/teams", "GET /repositories", "GET /repositories/{repository_id}/environments/{environment_name}/secrets", "GET /scim/v2/enterprises/{enterprise}/Groups", "GET /scim/v2/enterprises/{enterprise}/Users", "GET /scim/v2/organizations/{org}/Users", "GET /search/code", "GET /search/commits", "GET /search/issues", "GET /search/labels", "GET /search/repositories", "GET /search/topics", "GET /search/users", "GET /teams/{team_id}/discussions", "GET /teams/{team_id}/discussions/{discussion_number}/comments", "GET /teams/{team_id}/discussions/{discussion_number}/comments/{comment_number}/reactions", "GET /teams/{team_id}/discussions/{discussion_number}/reactions", "GET /teams/{team_id}/invitations", "GET /teams/{team_id}/members", "GET /teams/{team_id}/projects", "GET /teams/{team_id}/repos", "GET /teams/{team_id}/team-sync/group-mappings", "GET /teams/{team_id}/teams", "GET /user/blocks", "GET /user/emails", "GET /user/followers", "GET /user/following", "GET /user/gpg_keys", "GET /user/installations", "GET /user/installations/{installation_id}/repositories", "GET /user/issues", "GET /user/keys", "GET /user/marketplace_purchases", "GET /user/marketplace_purchases/stubbed", "GET /user/memberships/orgs", "GET /user/migrations", "GET /user/migrations/{migration_id}/repositories", "GET /user/orgs", "GET /user/packages", "GET /user/public_emails", "GET /user/repos", "GET /user/repository_invitations", "GET /user/starred", "GET /user/subscriptions", "GET /user/teams", "GET /users", "GET /users/{username}/events", "GET /users/{username}/events/orgs/{org}", "GET /users/{username}/events/public", "GET /users/{username}/followers", "GET /users/{username}/following", "GET /users/{username}/gists", "GET /users/{username}/gpg_keys", "GET /users/{username}/keys", "GET /users/{username}/orgs", "GET /users/{username}/packages", "GET /users/{username}/projects", "GET /users/{username}/received_events", "GET /users/{username}/received_events/public", "GET /users/{username}/repos", "GET /users/{username}/starred", "GET /users/{username}/subscriptions"]; + const newApi = (query, options) => { + return graphql(newRequest, query, options); + }; -function isPaginatingEndpoint(arg) { - if (typeof arg === "string") { - return paginatingEndpoints.includes(arg); - } else { - return false; - } + return Object.assign(newApi, { + defaults: withDefaults.bind(null, newRequest), + endpoint: request.request.endpoint + }); } -/** - * @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) - }) - }; +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" + }); } -paginateRest.VERSION = VERSION; -exports.composePaginateRest = composePaginateRest; -exports.isPaginatingEndpoint = isPaginatingEndpoint; -exports.paginateRest = paginateRest; -exports.paginatingEndpoints = paginatingEndpoints; +exports.GraphqlResponseError = GraphqlResponseError; +exports.graphql = graphql$1; +exports.withCustomRequest = withCustomRequest; //# sourceMappingURL=index.js.map /***/ }), -/***/ 83044: +/***/ 51017: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -5607,17 +5648,88 @@ exports.paginatingEndpoints = paginatingEndpoints; Object.defineProperty(exports, "__esModule", ({ value: true })); -function ownKeys(object, enumerableOnly) { - var keys = Object.keys(object); +function oauthAuthorizationUrl(options) { + const clientType = options.clientType || "oauth-app"; + const baseUrl = options.baseUrl || "https://github.com"; + const result = { + clientType, + allowSignup: options.allowSignup === false ? false : true, + clientId: options.clientId, + login: options.login || null, + redirectUrl: options.redirectUrl || null, + state: options.state || Math.random().toString(36).substr(2), + url: "" + }; - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(object); + if (clientType === "oauth-app") { + const scopes = "scopes" in options ? options.scopes : []; + result.scopes = typeof scopes === "string" ? scopes.split(/[,\s]+/).filter(Boolean) : scopes; + } - if (enumerableOnly) { - symbols = symbols.filter(function (sym) { - return Object.getOwnPropertyDescriptor(object, sym).enumerable; - }); - } + result.url = urlBuilderAuthorize(`${baseUrl}/login/oauth/authorize`, result); + return result; +} + +function urlBuilderAuthorize(base, options) { + const map = { + allowSignup: "allow_signup", + clientId: "client_id", + login: "login", + redirectUrl: "redirect_uri", + scopes: "scope", + state: "state" + }; + let url = base; + Object.keys(map) // Filter out keys that are null and remove the url key + .filter(k => options[k] !== null) // Filter out empty scopes array + .filter(k => { + if (k !== "scopes") return true; + if (options.clientType === "github-app") return false; + return !Array.isArray(options[k]) || options[k].length > 0; + }) // Map Array with the proper URL parameter names and change the value to a string using template strings + // @ts-ignore + .map(key => [map[key], `${options[key]}`]) // Finally, build the URL + .forEach(([key, value], index) => { + url += index === 0 ? `?` : "&"; + url += `${key}=${encodeURIComponent(value)}`; + }); + return url; +} + +exports.oauthAuthorizationUrl = oauthAuthorizationUrl; +//# sourceMappingURL=index.js.map + + +/***/ }), + +/***/ 88445: +/***/ ((__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 oauthAuthorizationUrl = __nccwpck_require__(51017); +var request = __nccwpck_require__(36234); +var requestError = __nccwpck_require__(10537); +var btoa = _interopDefault(__nccwpck_require__(72358)); + +const VERSION = "1.2.6"; + +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); } @@ -5660,20753 +5772,20349 @@ function _defineProperty(obj, key, value) { return obj; } -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"] - } - }], - 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" - } - }] - }, - 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"] - } - }], - 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"] - } - }], - 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"] - } - }], - 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"] - } -}; - -const VERSION = "5.13.0"; - -function endpointsToMethods(octokit, endpointsMap) { - const newMethods = {}; - - 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); - - if (!newMethods[scope]) { - newMethods[scope] = {}; - } - - const scopeMethods = newMethods[scope]; - - if (decorations) { - scopeMethods[methodName] = decorate(octokit, scope, methodName, endpointDefaults, decorations); - continue; - } - - scopeMethods[methodName] = octokit.request.defaults(endpointDefaults); - } - } - - return newMethods; -} - -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` - - if (decorations.mapToData) { - options = Object.assign({}, options, { - data: options[decorations.mapToData], - [decorations.mapToData]: undefined - }); - return requestWithDefaults(options); - } - - if (decorations.renamed) { - const [newScope, newMethodName] = decorations.renamed; - octokit.log.warn(`octokit.${scope}.${methodName}() has been renamed to octokit.${newScope}.${newMethodName}()`); - } - - if (decorations.deprecated) { - octokit.log.warn(decorations.deprecated); - } - - 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 - }; -} -restEndpointMethods.VERSION = VERSION; -function legacyRestEndpointMethods(octokit) { - const api = endpointsToMethods(octokit, Endpoints); - return _objectSpread2(_objectSpread2({}, api), {}, { - rest: api - }); -} -legacyRestEndpointMethods.VERSION = VERSION; - -exports.legacyRestEndpointMethods = legacyRestEndpointMethods; -exports.restEndpointMethods = restEndpointMethods; -//# sourceMappingURL=index.js.map - - -/***/ }), - -/***/ 86298: -/***/ ((__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.9"; -function retry(octokit, octokitOptions) { - const state = Object.assign({ - enabled: true, - retryAfterBaseValue: 1000, - doNotRetry: [400, 401, 403, 404, 422], - retries: 3 - }, octokitOptions.retry); - - if (state.enabled) { - octokit.hook.error("request", errorRequest.bind(null, octokit, state)); - octokit.hook.wrap("request", wrapRequest.bind(null, state)); - } - - return { - retry: { - retryRequest: (error, retries, retryAfter) => { - error.request.request = Object.assign({}, error.request.request, { - retries: retries, - retryAfter: retryAfter - }); - return error; - } - } - }; -} -retry.VERSION = VERSION; - -exports.VERSION = VERSION; -exports.retry = retry; -//# sourceMappingURL=index.js.map - - -/***/ }), - -/***/ 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 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 VERSION = "3.5.2"; - -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 { - pathname - } = new URL(options.url, "http://github.test"); - const isSearch = options.method === "GET" && pathname.startsWith("/search/"); - const isGraphQL = pathname.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(pathname)) { - 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"), { - response: res, - data: res.data - }); - throw error; - } - } - - return req; -} - -var triggersNotificationPaths = ["/orgs/{org}/invitations", "/orgs/{org}/invitations/{invitation_id}", "/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 // @ts-ignore - - } = 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 { - pathname - } = new URL(options.url, "http://github.test"); - const shouldRetryGraphQL = pathname.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 (/\bsecondary rate\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.response.headers["retry-after"], state.minimumAbuseRetryAfter); - const wantRetry = await emitter.trigger("abuse-limit", retryAfter, options, octokit); - return { - wantRetry, - retryAfter - }; - } - - if (error.response.headers != null && error.response.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.response.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)); - return {}; -} -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 logOnceCode = once(deprecation => console.warn(deprecation)); -const logOnceHeaders = 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; - let headers; - - if ("headers" in options && typeof options.headers !== "undefined") { - headers = options.headers; - } - - if ("response" in options) { - this.response = options.response; - headers = options.response.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; // deprecations - - Object.defineProperty(this, "code", { - get() { - logOnceCode(new deprecation.Deprecation("[@octokit/request-error] `error.code` is deprecated, use `error.status`.")); - return statusCode; - } - - }); - Object.defineProperty(this, "headers", { - get() { - logOnceHeaders(new deprecation.Deprecation("[@octokit/request-error] `error.headers` is deprecated, use `error.response.headers`.")); - return headers || {}; - } - - }); - } - -} - -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__(80467)); -var requestError = __nccwpck_require__(10537); - -const VERSION = "5.6.2"; - -function getBufferResponse(response) { - return response.arrayBuffer(); -} - -function fetchWrapper(requestOptions) { - const log = requestOptions.request && requestOptions.request.log ? requestOptions.request.log : console; - - 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.agent` type is incompatible - // see https://github.com/octokit/types.ts/pull/264 - requestOptions.request)).then(async response => { - url = response.url; - status = response.status; - - for (const keyAndValue of response.headers) { - headers[keyAndValue[0]] = keyAndValue[1]; - } - - if ("deprecation" in headers) { - const matches = headers.link && headers.link.match(/<([^>]+)>; rel="deprecation"/); - const deprecationLink = matches && matches.pop(); - log.warn(`[@octokit/request] "${requestOptions.method} ${requestOptions.url}" is deprecated. It is scheduled to be removed on ${headers.sunset}${deprecationLink ? `. See ${deprecationLink}` : ""}`); - } - - 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, { - response: { - url, - status, - headers, - data: undefined - }, - request: requestOptions - }); - } - - if (status === 304) { - throw new requestError.RequestError("Not modified", status, { - response: { - url, - status, - headers, - data: await getResponseData(response) - }, - request: requestOptions - }); - } - - if (status >= 400) { - const data = await getResponseData(response); - const error = new requestError.RequestError(toErrorMessage(data), status, { - response: { - url, - status, - headers, - data - }, - request: requestOptions - }); - throw error; - } - - return getResponseData(response); - }).then(data => { - return { - status, - url, - headers, - data - }; - }).catch(error => { - if (error instanceof requestError.RequestError) throw error; - throw new requestError.RequestError(error.message, 500, { - request: requestOptions - }); - }); -} - -async function getResponseData(response) { - 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); -} - -function toErrorMessage(data) { - if (typeof data === "string") return data; // istanbul ignore else - just in case - - if ("message" in data) { - if (Array.isArray(data.errors)) { - return `${data.message}: ${data.errors.map(JSON.stringify).join(", ")}`; - } - - return data.message; - } // istanbul ignore next - just in case - - - return `Unknown error: ${JSON.stringify(data)}`; -} - -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 - - -/***/ }), - -/***/ 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])); - } - }); - }); -} - -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__(58930); -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); - }); -} - - -/***/ }), - -/***/ 96645: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const { inspect } = __nccwpck_require__(73837); - -const through = __nccwpck_require__(18180); -const core = __nccwpck_require__(42186); -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"; - -const begin = "-----BEGIN RSA PRIVATE KEY-----"; -const end = "-----END RSA PRIVATE KEY-----"; -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(); - } - - if (privateKey.includes(begin) && privateKey.includes(end)) { - // newlines are escaped - if (privateKey.indexOf("\\n") !== -1) { - privateKey = privateKey.replace(/\\n/g, "\n"); - } // newlines are missing - - - if (privateKey.indexOf("\n") === -1) { - privateKey = addNewlines(privateKey); - } - - return privateKey; - } - - 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; -} - -function addNewlines(privateKey) { - const middleLength = privateKey.length - begin.length - end.length - 2; - const middle = privateKey.substr(begin.length + 1, middleLength); - return `${begin}\n${middle.trim().replace(/\s+/g, "\n")}\n${end}`; -} - -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.1.5"; - -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 endpoint = _objectSpread2({ - method: "GET", - url: "/repos/{owner}/{repo}/contents/{path}", - owner, - repo, - path, - mediaType: { - format: "raw" - } - }, ref ? { - ref - } : {}); - - const { - url - } = await octokit.request.endpoint(endpoint); - const emptyConfigResult = { - owner, - repo, - path, - url, - config: null - }; - - try { - const { - data, - headers - } = await octokit.request(endpoint); // 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] ${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 ${url} (invalid JSON)`); - } - - return _objectSpread2(_objectSpread2({}, emptyConfigResult), {}, { - config: data - }); - } - - const config = yaml.load(data) || {}; - - if (typeof config === "string") { - throw new Error(`[@probot/octokit-plugin-config] Configuration could not be parsed from ${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 ${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 - }); - const files = [requestedRepoFile]; // if no configuration file present in selected repository, - // try to load it from the `.github` repository - - if (!requestedRepoFile.config) { - if (repo === ".github") { - return files; - } - - const defaultRepoConfig = await getConfigFile(octokit, { - owner, - repo: ".github", - path - }); - files.push(defaultRepoConfig); - } - - const file = files[files.length - 1]; // if the configuration has no `_extends` key, we are done here. - - if (!file.config || !file.config._extends) { - return files; - } // parse the value of `_extends` into request parameters to - // retrieve the new configuration file - - - let extendConfigOptions = extendsToGetContentParams({ - owner, - path, - url: file.url, - extendsValue: file.config._extends - }); // remove the `_extends` key from the configuration that is returned - - delete file.config._extends; // 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__(67362); -const Sentry = __nccwpck_require__(22783); - -const LEVEL_MAP = { - 10: "trace", - 20: "debug", - 30: "info", - 40: "warn", - 50: "error", - 60: "fatal", -}; - -/** - * 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; - 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", "sentryEventId"].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) { - if (formattingEnabled) { - return cb(null, pretty(line)); - } - - if (levelAsString) { - return cb(null, stringifyLogLevel(JSON.parse(line))); - } - - cb(null, line + "\n"); - return; - } - - 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, - }); - } - - const sentryEventId = Sentry.captureException(toSentryError(data)); - - // reduce logging data and add reference to sentry event instead - if (data.event) { - data.event = { id: data.event.id }; - } - if (data.request) { - data.request = { - method: data.request.method, - url: data.request.url, - }; - } - data.sentryEventId = sentryEventId; - - if (formattingEnabled) { - return cb(null, pretty(data)); - } - - // istanbul ignore if - if (levelAsString) { - return cb(null, stringifyLogLevel(data)); - } - - cb(null, JSON.stringify(data) + "\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, headers and metadata that can be used to form - * different types of requests to Sentry endpoints. - * Supports both envelopes and regular event requests. - **/ -var API = /** @class */ (function () { - /** Create a new instance of API */ - function API(dsn, metadata, tunnel) { - if (metadata === void 0) { metadata = {}; } - this.dsn = dsn; - this._dsnObject = new utils_1.Dsn(dsn); - this.metadata = metadata; - this._tunnel = tunnel; - } - /** Returns the Dsn object. */ - API.prototype.getDsn = function () { - return this._dsnObject; - }; - /** Does this transport force envelopes? */ - API.prototype.forceEnvelope = function () { - return !!this._tunnel; - }; - /** Returns the prefix to construct Sentry ingestion API endpoints. */ - API.prototype.getBaseApiEndpoint = function () { - var dsn = this.getDsn(); - 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 () { - if (this.forceEnvelope()) { - return this._tunnel; - } - return this._getEnvelopeEndpoint() + "?" + this._encodedAuth(); - }; - /** Returns only the path component for the store endpoint. */ - API.prototype.getStoreEndpointPath = function () { - var dsn = this.getDsn(); - 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) { - // CHANGE THIS to use metadata but keep clientName and clientVersion compatible - var dsn = this.getDsn(); - var header = ["Sentry sentry_version=" + SENTRY_API_VERSION]; - header.push("sentry_client=" + clientName + "/" + clientVersion); - header.push("sentry_key=" + dsn.publicKey); - 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.getDsn(); - 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) { - if (this._tunnel) { - return this._tunnel; - } - var base = this.getBaseApiEndpoint(); - var dsn = this.getDsn(); - 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.getDsn(); - var auth = { - // We send only the minimum set of required information. See - // https://github.com/getsentry/sentry-javascript/issues/2572. - sentry_key: dsn.publicKey, - 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) { - void 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; - } - void 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); -var ALREADY_SEEN_ERROR = "Not capturing exception because it's already been captured."; -/** - * 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 calls being processed */ - this._numProcessing = 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; - // ensure we haven't captured this very object before - if (utils_1.checkOrSetAlreadyCaught(exception)) { - utils_1.logger.log(ALREADY_SEEN_ERROR); - return; - } - 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 _a; - // ensure we haven't captured this very object before - if (((_a = hint) === null || _a === void 0 ? void 0 : _a.originalException) && utils_1.checkOrSetAlreadyCaught(hint.originalException)) { - utils_1.logger.log(ALREADY_SEEN_ERROR); - return; - } - 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 (!this._isEnabled()) { - utils_1.logger.warn('SDK not enabled, will not capture session.'); - return; - } - if (!(typeof session.release === 'string')) { - utils_1.logger.warn('Discarded session because of missing or non-string release'); - } - else { - this._sendSession(session); - // After sending, we set init false to indicate it's not the first occurrence - session.update({ init: false }); - } - }; - /** - * @inheritDoc - */ - BaseClient.prototype.getDsn = function () { - return this._dsn; - }; - /** - * @inheritDoc - */ - BaseClient.prototype.getOptions = function () { - return this._options; - }; - /** - * @inheritDoc - */ - BaseClient.prototype.getTransport = function () { - return this._getBackend().getTransport(); - }; - /** - * @inheritDoc - */ - BaseClient.prototype.flush = function (timeout) { - var _this = this; - return this._isClientDoneProcessing(timeout).then(function (clientFinished) { - return _this.getTransport() - .close(timeout) - .then(function (transportFlushed) { return clientFinished && 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.initialized) { - 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 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; } - } - } - // A session is updated and that session update is sent in only one of the two following scenarios: - // 1. Session with non terminal status and 0 errors + an error occurred -> Will set error count to 1 and send update - // 2. Session with non terminal status and 1 error + a crash occurred -> Will set status crashed and send update - var sessionNonTerminal = session.status === types_1.SessionStatus.Ok; - var shouldUpdateAndSend = (sessionNonTerminal && session.errors === 0) || (sessionNonTerminal && crashed); - if (shouldUpdateAndSend) { - session.update(tslib_1.__assign(tslib_1.__assign({}, (crashed && { status: types_1.SessionStatus.Crashed })), { errors: session.errors || Number(errored || crashed) })); - this.captureSession(session); - } - }; - /** Deliver captured session to Sentry */ - BaseClient.prototype._sendSession = function (session) { - this._getBackend().sendSession(session); - }; - /** - * Determine if the client is finished processing. Returns a promise because it will wait `timeout` ms before saying - * "no" (resolving to `false`) in order to give the client a chance to potentially finish first. - * - * @param timeout The time, in ms, after which to resolve to `false` if the client is still busy. Passing `0` (or not - * passing anything) will make the promise wait as long as it takes for processing to finish before resolving to - * `true`. - * @returns A promise which will resolve to `true` if processing is already done or finishes before the timeout, and - * `false` otherwise - */ - BaseClient.prototype._isClientDoneProcessing = function (timeout) { - var _this = this; - return new utils_1.SyncPromise(function (resolve) { - var ticked = 0; - var tick = 1; - var interval = setInterval(function () { - if (_this._numProcessing == 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; - } - var _a = this.getOptions()._experiments, _experiments = _a === void 0 ? {} : _a; - if (_experiments.ensureNoCircularStructures) { - return utils_1.normalize(normalized); - } - 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 event The event that will be filled with all integrations. - */ - BaseClient.prototype._applyIntegrationsMetadata = function (event) { - var integrationsArray = Object.keys(this._integrations); - if (integrationsArray.length > 0) { - event.sdk = event.sdk || {}; - event.sdk.integrations = tslib_1.__spread((event.sdk.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; - var _a, _b; - // eslint-disable-next-line @typescript-eslint/unbound-method - var _c = this.getOptions(), beforeSend = _c.beforeSend, sampleRate = _c.sampleRate; - var transport = this.getTransport(); - if (!this._isEnabled()) { - return utils_1.SyncPromise.reject(new utils_1.SentryError('SDK not enabled, will not capture 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) { - (_b = (_a = transport).recordLostEvent) === null || _b === void 0 ? void 0 : _b.call(_a, types_1.Outcome.SampleRate, 'event'); - return utils_1.SyncPromise.reject(new utils_1.SentryError("Discarding event because it's not included in the random sample (sampling rate = " + sampleRate + ")")); - } - return this._prepareEvent(event, scope, hint) - .then(function (prepared) { - var _a, _b; - if (prepared === null) { - (_b = (_a = transport).recordLostEvent) === null || _b === void 0 ? void 0 : _b.call(_a, types_1.Outcome.EventProcessor, event.type || 'event'); - 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); - return _this._ensureBeforeSendRv(beforeSendResult); - }) - .then(function (processedEvent) { - var _a, _b; - if (processedEvent === null) { - (_b = (_a = transport).recordLostEvent) === null || _b === void 0 ? void 0 : _b.call(_a, types_1.Outcome.BeforeSend, event.type || 'event'); - 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._numProcessing += 1; - void promise.then(function (value) { - _this._numProcessing -= 1; - return value; - }, function (reason) { - _this._numProcessing -= 1; - return reason; - }); - }; - /** - * Verifies that return value of configured `beforeSend` is of expected type. - */ - BaseClient.prototype._ensureBeforeSendRv = function (rv) { - var nullErr = '`beforeSend` method has to return `null` or a valid event.'; - if (utils_1.isThenable(rv)) { - return rv.then(function (event) { - if (!(utils_1.isPlainObject(event) || event === null)) { - throw new utils_1.SentryError(nullErr); - } - return event; - }, function (e) { - throw new utils_1.SentryError("beforeSend rejected with " + e); - }); - } - else if (!(utils_1.isPlainObject(rv) || rv === null)) { - throw new utils_1.SentryError(nullErr); - } - return rv; - }; - 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 version_1 = __nccwpck_require__(33493); -exports.SDK_VERSION = version_1.SDK_VERSION; -var Integrations = __nccwpck_require__(96727); -exports.Integrations = Integrations; -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 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 = []; -/** - * @private - */ -function filterDuplicates(integrations) { - return integrations.reduce(function (acc, integrations) { - if (acc.every(function (accIntegration) { return integrations.name !== accIntegration.name; })) { - acc.push(integrations); - } - return acc; - }, []); -} -/** Gets integration to install */ -function getIntegrationsToSetup(options) { - var defaultIntegrations = (options.defaultIntegrations && tslib_1.__spread(options.defaultIntegrations)) || []; - var userIntegrations = options.integrations; - var integrations = tslib_1.__spread(filterDuplicates(defaultIntegrations)); - if (Array.isArray(userIntegrations)) { - // Filter out integrations that are also included in user options - integrations = tslib_1.__spread(integrations.filter(function (integrations) { - return userIntegrations.every(function (userIntegration) { return userIntegration.name !== integrations.name; }); - }), filterDuplicates(userIntegrations)); - } - else if (typeof userIntegrations === 'function') { - integrations = userIntegrations(integrations); - integrations = Array.isArray(integrations) ? integrations : [integrations]; - } - // 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); - }); - // set the `initialized` flag so we don't run through the process again unecessarily; use `Object.defineProperty` - // because by default it creates a property which is nonenumerable, which we want since `initialized` shouldn't be - // considered a member of the index the way the actual integrations are - Object.defineProperty(integrations, 'initialized', { value: true }); - 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() : {}; - // This checks prevents most of the occurrences of the bug linked below: - // https://github.com/getsentry/sentry-javascript/issues/2622 - // The bug is caused by multiple SDK instances, where one is minified and one is using non-mangled code. - // Unfortunatelly we cannot fix it reliably (thus reserved property in rollup's terser config), - // as we cannot force people using multiple instances in their apps to sync SDK versions. - var options = typeof self._mergeOptions === 'function' ? self._mergeOptions(clientOptions) : {}; - if (typeof self._shouldDropEvent !== 'function') { - return event; - } - return self._shouldDropEvent(event, options) ? null : event; - } - 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._getLastValidUrl = function (frames) { - if (frames === void 0) { frames = []; } - var _a, _b; - for (var i = frames.length - 1; i >= 0; i--) { - var frame = frames[i]; - if (((_a = frame) === null || _a === void 0 ? void 0 : _a.filename) !== '' && ((_b = frame) === null || _b === void 0 ? void 0 : _b.filename) !== '[native code]') { - return frame.filename || null; - } - } - return null; - }; - /** JSDoc */ - InboundFilters.prototype._getEventFilterUrl = function (event) { - try { - if (event.stacktrace) { - var frames_1 = event.stacktrace.frames; - return this._getLastValidUrl(frames_1); - } - if (event.exception) { - var frames_2 = event.exception.values && event.exception.values[0].stacktrace && event.exception.values[0].stacktrace.frames; - return this._getLastValidUrl(frames_2); - } - 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); -/** Extract sdk info from from the API metadata */ -function getSdkMetadataForEnvelopeHeader(api) { - if (!api.metadata || !api.metadata.sdk) { - return; - } - var _a = api.metadata.sdk, name = _a.name, version = _a.version; - return { name: name, version: version }; -} -/** - * Apply SdkInfo (name, version, packages, integrations) to the corresponding event key. - * Merge with existing data if any. - **/ -function enhanceEventWithSdkInfo(event, sdkInfo) { - if (!sdkInfo) { - return event; - } - event.sdk = event.sdk || {}; - event.sdk.name = event.sdk.name || sdkInfo.name; - event.sdk.version = event.sdk.version || sdkInfo.version; - event.sdk.integrations = tslib_1.__spread((event.sdk.integrations || []), (sdkInfo.integrations || [])); - event.sdk.packages = tslib_1.__spread((event.sdk.packages || []), (sdkInfo.packages || [])); - return event; -} -/** Creates a SentryRequest from a Session. */ -function sessionToSentryRequest(session, api) { - var sdkInfo = getSdkMetadataForEnvelopeHeader(api); - var envelopeHeaders = JSON.stringify(tslib_1.__assign(tslib_1.__assign({ sent_at: new Date().toISOString() }, (sdkInfo && { sdk: sdkInfo })), (api.forceEnvelope() && { dsn: api.getDsn().toString() }))); - // I know this is hacky but we don't want to add `session` to request type since it's never rate limited - var type = 'aggregates' in session ? 'sessions' : 'session'; - var itemHeaders = JSON.stringify({ - type: type, - }); - return { - body: envelopeHeaders + "\n" + itemHeaders + "\n" + JSON.stringify(session), - type: type, - url: api.getEnvelopeEndpointWithUrlEncodedAuth(), - }; -} -exports.sessionToSentryRequest = sessionToSentryRequest; -/** Creates a SentryRequest from an event. */ -function eventToSentryRequest(event, api) { - var sdkInfo = getSdkMetadataForEnvelopeHeader(api); - var eventType = event.type || 'event'; - var useEnvelope = eventType === 'transaction' || api.forceEnvelope(); - var _a = event.debug_meta || {}, transactionSampling = _a.transactionSampling, metadata = tslib_1.__rest(_a, ["transactionSampling"]); - var _b = transactionSampling || {}, samplingMethod = _b.method, sampleRate = _b.rate; - if (Object.keys(metadata).length === 0) { - delete event.debug_meta; - } - else { - event.debug_meta = metadata; - } - var req = { - body: JSON.stringify(sdkInfo ? enhanceEventWithSdkInfo(event, api.metadata.sdk) : event), - type: eventType, - 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(tslib_1.__assign(tslib_1.__assign({ event_id: event.event_id, sent_at: new Date().toISOString() }, (sdkInfo && { sdk: sdkInfo })), (api.forceEnvelope() && { dsn: api.getDsn().toString() }))); - var itemHeaders = JSON.stringify({ - type: eventType, - // 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 - -/***/ }), - -/***/ 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); -/** - * 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) { - var _a; - if (options.debug === true) { - utils_1.logger.enable(); - } - var hub = hub_1.getCurrentHub(); - (_a = hub.getScope()) === null || _a === void 0 ? void 0 : _a.update(options.initialScope); - var client = new clientClass(options); - hub.bindClient(client); -} -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 - -/***/ }), - -/***/ 33493: -/***/ ((__unused_webpack_module, exports) => { - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.SDK_VERSION = '6.16.1'; -//# sourceMappingURL=version.js.map - -/***/ }), - -/***/ 53536: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -/* eslint-disable max-lines */ -var types_1 = __nccwpck_require__(83789); -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 = 4; -/** - * Default maximum number of breadcrumbs added to an event. Can be overwritten - * with {@link Options.maxBreadcrumbs}. - */ -var DEFAULT_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; - if (client) { - 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, mimic 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, mimic 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 = utils_1.uuid4(); - if (event.type !== 'transaction') { - this._lastEventId = eventId; - } - 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, maxBreadcrumbs); - }; - /** - * @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.captureSession = function (endSession) { - if (endSession === void 0) { endSession = false; } - // both send the update and pull the session from the scope - if (endSession) { - return this.endSession(); - } - // only send the update - this._sendSessionUpdate(); - }; - /** - * @inheritDoc - */ - Hub.prototype.endSession = function () { - var _a, _b, _c, _d, _e; - (_c = (_b = (_a = this.getStackTop()) === null || _a === void 0 ? void 0 : _a.scope) === null || _b === void 0 ? void 0 : _b.getSession()) === null || _c === void 0 ? void 0 : _c.close(); - this._sendSessionUpdate(); - // the session is over; take it off of the scope - (_e = (_d = this.getStackTop()) === null || _d === void 0 ? void 0 : _d.scope) === null || _e === void 0 ? void 0 : _e.setSession(); - }; - /** - * @inheritDoc - */ - Hub.prototype.startSession = function (context) { - var _a = this.getStackTop(), scope = _a.scope, client = _a.client; - var _b = (client && client.getOptions()) || {}, release = _b.release, environment = _b.environment; - // Will fetch userAgent if called from browser sdk - var global = utils_1.getGlobalObject(); - var userAgent = (global.navigator || {}).userAgent; - var session = new session_1.Session(tslib_1.__assign(tslib_1.__assign(tslib_1.__assign({ release: release, - environment: environment }, (scope && { user: scope.getUser() })), (userAgent && { userAgent: userAgent })), context)); - if (scope) { - // End existing session if there's one - var currentSession = scope.getSession && scope.getSession(); - if (currentSession && currentSession.status === types_1.SessionStatus.Ok) { - currentSession.update({ status: types_1.SessionStatus.Exited }); - } - this.endSession(); - // Afterwards we set the new session on the scope - scope.setSession(session); - } - return session; - }; - /** - * Sends the current Session on the scope - */ - Hub.prototype._sendSessionUpdate = function () { - var _a = this.getStackTop(), scope = _a.scope, client = _a.client; - if (!scope) - return; - var session = scope.getSession && scope.getSession(); - if (session) { - if (client && client.captureSession) { - client.captureSession(session); - } - } - }; - /** - * 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. - * - * FIXME: This function is problematic, because despite always returning a valid Carrier, - * it has an optional `__SENTRY__` property, which then in turn requires us to always perform an unnecessary check - * at the call-site. We always access the carrier through this function, so we can guarantee that `__SENTRY__` is there. - **/ -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 - * @deprecated No longer used; remove in v7 - * @returns The domain, or undefined if there is no active domain - */ -// eslint-disable-next-line deprecation/deprecation -function getActiveDomain() { - utils_1.logger.warn('Function `getActiveDomain` is deprecated and will be removed in a future version.'); - 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) { - var _a, _b, _c; - try { - var activeDomain = (_c = (_b = (_a = getMainCarrier().__SENTRY__) === null || _a === void 0 ? void 0 : _a.extensions) === null || _b === void 0 ? void 0 : _b.domain) === null || _c === void 0 ? void 0 : _c.active; - // 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); - } - 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 - * @returns A boolean indicating success or failure - */ -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 - -/***/ }), - -/***/ 6393: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -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 sessionflusher_1 = __nccwpck_require__(99695); -exports.SessionFlusher = sessionflusher_1.SessionFlusher; -var hub_1 = __nccwpck_require__(53536); -// eslint-disable-next-line deprecation/deprecation -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: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var utils_1 = __nccwpck_require__(1620); -/** - * Absolute maximum number of breadcrumbs added to an event. - * The `maxBreadcrumbs` option cannot be higher than this value. - */ -var MAX_BREADCRUMBS = 100; -/** - * 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 notifying 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 = {}; - } - /** - * 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); - newScope._requestSession = scope._requestSession; - } - 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.getRequestSession = function () { - return this._requestSession; - }; - /** - * @inheritDoc - */ - Scope.prototype.setRequestSession = function (requestSession) { - this._requestSession = requestSession; - return this; - }; - /** - * @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; - } - if (captureContext._requestSession) { - this._requestSession = captureContext._requestSession; - } - } - 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; - } - if (captureContext.requestSession) { - this._requestSession = captureContext.requestSession; - } - } - 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._requestSession = undefined; - this._span = undefined; - this._session = undefined; - this._notifyScopeListeners(); - return this; - }; - /** - * @inheritDoc - */ - Scope.prototype.addBreadcrumb = function (breadcrumb, maxBreadcrumbs) { - var maxCrumbs = typeof maxBreadcrumbs === 'number' ? Math.min(maxBreadcrumbs, MAX_BREADCRUMBS) : MAX_BREADCRUMBS; - // No data has been changed, so don't notify scope listeners - if (maxCrumbs <= 0) { - return this; - } - var mergedBreadcrumb = tslib_1.__assign({ timestamp: utils_1.dateTimestampInSeconds() }, breadcrumb); - this._breadcrumbs = tslib_1.__spread(this._breadcrumbs, [mergedBreadcrumb]).slice(-maxCrumbs); - 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 information 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 relies 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)) { - void result - .then(function (final) { return _this._notifyEventProcessors(processors, final, hint, index + 1).then(resolve); }) - .then(null, reject); - } - else { - void _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; -/** - * Returns 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 */ -} -/** - * Add a EventProcessor to be kept globally. - * @param callback EventProcessor to add - */ -function addGlobalEventProcessor(callback) { - getGlobalEventProcessors().push(callback); -} -exports.addGlobalEventProcessor = addGlobalEventProcessor; -//# sourceMappingURL=scope.js.map - -/***/ }), - -/***/ 12474: -/***/ ((__unused_webpack_module, 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.duration = 0; - this.status = types_1.SessionStatus.Ok; - this.init = true; - this.ignoreDuration = false; - // Both timestamp and started are in seconds since the UNIX epoch. - var startingTime = utils_1.timestampInSeconds(); - this.timestamp = startingTime; - this.started = startingTime; - 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 (!this.ipAddress && context.user.ip_address) { - this.ipAddress = context.user.ip_address; - } - if (!this.did && !context.did) { - this.did = context.user.id || context.user.email || context.user.username; - } - } - this.timestamp = context.timestamp || utils_1.timestampInSeconds(); - if (context.ignoreDuration) { - this.ignoreDuration = context.ignoreDuration; - } - if (context.sid) { - // Good enough uuid validation. — Kamil - this.sid = context.sid.length === 32 ? context.sid : utils_1.uuid4(); - } - if (context.init !== undefined) { - this.init = context.init; - } - if (!this.did && context.did) { - this.did = "" + context.did; - } - if (typeof context.started === 'number') { - this.started = context.started; - } - if (this.ignoreDuration) { - this.duration = undefined; - } - else if (typeof context.duration === 'number') { - this.duration = context.duration; - } - else { - var duration = this.timestamp - this.started; - this.duration = duration >= 0 ? duration : 0; - } - if (context.release) { - this.release = context.release; - } - if (context.environment) { - this.environment = context.environment; - } - if (!this.ipAddress && context.ipAddress) { - this.ipAddress = context.ipAddress; - } - if (!this.userAgent && 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: this.init, - // Make sure that sec is converted to ms for date constructor - started: new Date(this.started * 1000).toISOString(), - timestamp: new Date(this.timestamp * 1000).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 - -/***/ }), - -/***/ 99695: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -Object.defineProperty(exports, "__esModule", ({ value: true })); -var types_1 = __nccwpck_require__(83789); -var utils_1 = __nccwpck_require__(1620); -var hub_1 = __nccwpck_require__(53536); -/** - * @inheritdoc - */ -var SessionFlusher = /** @class */ (function () { - function SessionFlusher(transport, attrs) { - var _this = this; - this.flushTimeout = 60; - this._pendingAggregates = {}; - this._isEnabled = true; - this._transport = transport; - // Call to setInterval, so that flush is called every 60 seconds - this._intervalId = setInterval(function () { return _this.flush(); }, this.flushTimeout * 1000); - this._sessionAttrs = attrs; - } - /** Sends session aggregates to Transport */ - SessionFlusher.prototype.sendSessionAggregates = function (sessionAggregates) { - if (!this._transport.sendSession) { - utils_1.logger.warn("Dropping session because custom transport doesn't implement sendSession"); - return; - } - void this._transport.sendSession(sessionAggregates).then(null, function (reason) { - utils_1.logger.error("Error while sending session: " + reason); - }); - }; - /** Checks if `pendingAggregates` has entries, and if it does flushes them by calling `sendSessions` */ - SessionFlusher.prototype.flush = function () { - var sessionAggregates = this.getSessionAggregates(); - if (sessionAggregates.aggregates.length === 0) { - return; - } - this._pendingAggregates = {}; - this.sendSessionAggregates(sessionAggregates); - }; - /** Massages the entries in `pendingAggregates` and returns aggregated sessions */ - SessionFlusher.prototype.getSessionAggregates = function () { - var _this = this; - var aggregates = Object.keys(this._pendingAggregates).map(function (key) { - return _this._pendingAggregates[parseInt(key)]; - }); - var sessionAggregates = { - attrs: this._sessionAttrs, - aggregates: aggregates, - }; - return utils_1.dropUndefinedKeys(sessionAggregates); - }; - /** JSDoc */ - SessionFlusher.prototype.close = function () { - clearInterval(this._intervalId); - this._isEnabled = false; - this.flush(); - }; - /** - * Wrapper function for _incrementSessionStatusCount that checks if the instance of SessionFlusher is enabled then - * fetches the session status of the request from `Scope.getRequestSession().status` on the scope and passes them to - * `_incrementSessionStatusCount` along with the start date - */ - SessionFlusher.prototype.incrementSessionStatusCount = function () { - var _a, _b; - if (!this._isEnabled) { - return; - } - var scope = hub_1.getCurrentHub().getScope(); - var requestSession = (_a = scope) === null || _a === void 0 ? void 0 : _a.getRequestSession(); - if (requestSession && requestSession.status) { - this._incrementSessionStatusCount(requestSession.status, new Date()); - // This is not entirely necessarily but is added as a safe guard to indicate the bounds of a request and so in - // case captureRequestSession is called more than once to prevent double count - (_b = scope) === null || _b === void 0 ? void 0 : _b.setRequestSession(undefined); - /* eslint-enable @typescript-eslint/no-unsafe-member-access */ - } - }; - /** - * Increments status bucket in pendingAggregates buffer (internal state) corresponding to status of - * the session received - */ - SessionFlusher.prototype._incrementSessionStatusCount = function (status, date) { - // Truncate minutes and seconds on Session Started attribute to have one minute bucket keys - var sessionStartedTrunc = new Date(date).setSeconds(0, 0); - this._pendingAggregates[sessionStartedTrunc] = this._pendingAggregates[sessionStartedTrunc] || {}; - // corresponds to aggregated sessions in one specific minute bucket - // for example, {"started":"2021-03-16T08:00:00.000Z","exited":4, "errored": 1} - var aggregationCounts = this._pendingAggregates[sessionStartedTrunc]; - if (!aggregationCounts.started) { - aggregationCounts.started = new Date(sessionStartedTrunc).toISOString(); - } - switch (status) { - case types_1.RequestSessionStatus.Errored: - aggregationCounts.errored = (aggregationCounts.errored || 0) + 1; - return aggregationCounts.errored; - case types_1.RequestSessionStatus.Ok: - aggregationCounts.exited = (aggregationCounts.exited || 0) + 1; - return aggregationCounts.exited; - case types_1.RequestSessionStatus.Crashed: - aggregationCounts.crashed = (aggregationCounts.crashed || 0) + 1; - return aggregationCounts.crashed; - } - }; - return SessionFlusher; -}()); -exports.SessionFlusher = SessionFlusher; -//# sourceMappingURL=sessionflusher.js.map - -/***/ }), - -/***/ 88455: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -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. - */ -// 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."); -} -/** - * 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'); - } - catch (exception) { - syntheticException = exception; - } - 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); - } - catch (exception) { - syntheticException = exception; - } - // 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); -} -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]; - } - callOnHub.apply(void 0, tslib_1.__spread(['_invokeClient', method], args)); -} -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 - -/***/ }), - -/***/ 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 providedMechanism = hint && hint.data && hint.data.mechanism; - var mechanism = providedMechanism || { - 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) : []; - void 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, tunnel: this._options.tunnel, _metadata: this._options._metadata }); - 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 - -/***/ }), - -/***/ 86147: -/***/ ((__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 hub_1 = __nccwpck_require__(6393); -var types_1 = __nccwpck_require__(83789); -var utils_1 = __nccwpck_require__(1620); -var backend_1 = __nccwpck_require__(40508); -/** - * 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) { - var _this = this; - options._metadata = options._metadata || {}; - options._metadata.sdk = options._metadata.sdk || { - name: 'sentry.javascript.node', - packages: [ - { - name: 'npm:@sentry/node', - version: core_1.SDK_VERSION, - }, - ], - version: core_1.SDK_VERSION, - }; - _this = _super.call(this, backend_1.NodeBackend, options) || this; - return _this; - } - /** - * @inheritDoc - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types - NodeClient.prototype.captureException = function (exception, hint, scope) { - // Check if the flag `autoSessionTracking` is enabled, and if `_sessionFlusher` exists because it is initialised only - // when the `requestHandler` middleware is used, and hence the expectation is to have SessionAggregates payload - // sent to the Server only when the `requestHandler` middleware is used - if (this._options.autoSessionTracking && this._sessionFlusher && scope) { - var requestSession = scope.getRequestSession(); - // Necessary checks to ensure this is code block is executed only within a request - // Should override the status only if `requestSession.status` is `Ok`, which is its initial stage - if (requestSession && requestSession.status === types_1.RequestSessionStatus.Ok) { - requestSession.status = types_1.RequestSessionStatus.Errored; - } - } - return _super.prototype.captureException.call(this, exception, hint, scope); - }; - /** - * @inheritDoc - */ - NodeClient.prototype.captureEvent = function (event, hint, scope) { - // Check if the flag `autoSessionTracking` is enabled, and if `_sessionFlusher` exists because it is initialised only - // when the `requestHandler` middleware is used, and hence the expectation is to have SessionAggregates payload - // sent to the Server only when the `requestHandler` middleware is used - if (this._options.autoSessionTracking && this._sessionFlusher && scope) { - var eventType = event.type || 'exception'; - var isException = eventType === 'exception' && event.exception && event.exception.values && event.exception.values.length > 0; - // If the event is of type Exception, then a request session should be captured - if (isException) { - var requestSession = scope.getRequestSession(); - // Ensure that this is happening within the bounds of a request, and make sure not to override - // Session Status if Errored / Crashed - if (requestSession && requestSession.status === types_1.RequestSessionStatus.Ok) { - requestSession.status = types_1.RequestSessionStatus.Errored; - } - } - } - return _super.prototype.captureEvent.call(this, event, hint, scope); - }; - /** - * - * @inheritdoc - */ - NodeClient.prototype.close = function (timeout) { - var _a; - (_a = this._sessionFlusher) === null || _a === void 0 ? void 0 : _a.close(); - return _super.prototype.close.call(this, timeout); - }; - /** Method that initialises an instance of SessionFlusher on Client */ - NodeClient.prototype.initSessionFlusher = function () { - var _a = this._options, release = _a.release, environment = _a.environment; - if (!release) { - utils_1.logger.warn('Cannot initialise an instance of SessionFlusher if no release is provided!'); - } - else { - this._sessionFlusher = new hub_1.SessionFlusher(this.getTransport(), { - release: release, - environment: environment, - }); - } - }; - /** - * @inheritDoc - */ - NodeClient.prototype._prepareEvent = function (event, scope, hint) { - event.platform = event.platform || 'node'; - if (this.getOptions().serverName) { - event.server_name = this.getOptions().serverName; - } - return _super.prototype._prepareEvent.call(this, event, scope, hint); - }; - /** - * Method responsible for capturing/ending a request session by calling `incrementSessionStatusCount` to increment - * appropriate session aggregates bucket - */ - NodeClient.prototype._captureRequestSession = function () { - if (!this._sessionFlusher) { - utils_1.logger.warn('Discarded request mode session because autoSessionTracking option was disabled'); - } - else { - this._sessionFlusher.incrementSessionStatusCount(); - } - }; - return NodeClient; -}(core_1.BaseClient)); -exports.NodeClient = NodeClient; -//# sourceMappingURL=client.js.map - -/***/ }), - -/***/ 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 types_1 = __nccwpck_require__(83789); -var utils_1 = __nccwpck_require__(1620); -var cookie = __nccwpck_require__(93658); -var domain = __nccwpck_require__(13639); -var os = __nccwpck_require__(22037); -var url = __nccwpck_require__(57310); -var sdk_1 = __nccwpck_require__(38836); -/** - * 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), - // extra context passed to the tracesSampler - { request: extractRequestData(req) }); - // 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; -/** - * Set parameterized as transaction name e.g.: `GET /users/:id` - * Also adds more context data on the transaction from the request - */ -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); -} -/** - * 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) - * - * @returns The fully constructed transaction name - */ -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) { - 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; -} -/** 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 extractRequestData(req, keys) { - if (keys === void 0) { keys = DEFAULT_REQUEST_KEYS; } - var requestData = {}; - // headers: - // node, express, nextjs: req.headers - // koa: req.header - var headers = (req.headers || req.header || {}); - // method: - // node, express, koa, nextjs: req.method - var method = req.method; - // host: - // express: req.hostname in > 4 and req.host in < 4 - // koa: req.host - // node, nextjs: req.headers.host - var host = req.hostname || req.host || headers.host || ''; - // protocol: - // node, nextjs: - // 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, nextjs: 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), nextjs: req.cookies - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - requestData.cookies = req.cookies || cookie.parse(headers.cookie || ''); - break; - case 'query_string': - // query string: - // node: req.url (raw) - // express, koa, nextjs: req.query - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - requestData.query_string = req.query || url.parse(originalUrl || '', false).query; - break; - case 'data': - if (method === 'GET' || method === 'HEAD') { - break; - } - // body data: - // express, koa, nextjs: req.body - // - // when using node by itself, you have to read the incoming stream(see - // https://nodejs.dev/learn/get-http-request-body-data-using-nodejs); if a user is doing that, we can't know - // where they're going to store the final result, so they'll have to capture this data themselves - if (req.body !== undefined) { - requestData.data = utils_1.isString(req.body) ? req.body : JSON.stringify(utils_1.normalize(req.body)); - } - break; - default: - if ({}.hasOwnProperty.call(req, key)) { - requestData[key] = req[key]; - } - } - }); - return requestData; -} -exports.extractRequestData = extractRequestData; -/** - * 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 `extractRequestData()` - var extractedRequestData = Array.isArray(options.request) - ? extractRequestData(req, options.request) - : extractRequestData(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, nextjs: 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) { - // TODO do we even need this anymore? - // TODO make this work for nextjs - event.transaction = extractTransaction(req, options.transaction); - } - return event; -} -exports.parseRequest = parseRequest; -/** - * Express compatible request handler. - * @see Exposed as `Handlers.requestHandler` - */ -function requestHandler(options) { - var currentHub = core_1.getCurrentHub(); - var client = currentHub.getClient(); - // Initialise an instance of SessionFlusher on the client when `autoSessionTracking` is enabled and the - // `requestHandler` middleware is used indicating that we are running in SessionAggregates mode - if (client && sdk_1.isAutoSessionTrackingEnabled(client)) { - client.initSessionFlusher(); - // If Scope contains a Single mode Session, it is removed in favor of using Session Aggregates mode - var scope = currentHub.getScope(); - if (scope && scope.getSession()) { - scope.setSession(); - } - } - 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; - void 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 () { - var currentHub = core_1.getCurrentHub(); - currentHub.configureScope(function (scope) { - scope.addEventProcessor(function (event) { return parseRequest(event, req, options); }); - var client = currentHub.getClient(); - if (sdk_1.isAutoSessionTrackingEnabled(client)) { - var scope_1 = currentHub.getScope(); - if (scope_1) { - // Set `status` of `RequestSession` to Ok, at the beginning of the request - scope_1.setRequestSession({ status: types_1.RequestSessionStatus.Ok }); - } - } - }); - res.once('finish', function () { - var client = currentHub.getClient(); - if (sdk_1.isAutoSessionTrackingEnabled(client)) { - setImmediate(function () { - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - if (client && client._captureRequestSession) { - // Calling _captureRequestSession to capture request session at the end of the request by incrementing - // the correct SessionAggregates bucket i.e. crashed, errored or exited - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - client._captureRequestSession(); - } - }); - } - }); - 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; -} -/** - * Express compatible error handler. - * @see Exposed as `Handlers.errorHandler` - */ -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 client = core_1.getCurrentHub().getClient(); - if (client && sdk_1.isAutoSessionTrackingEnabled(client)) { - // Check if the `SessionFlusher` is instantiated on the client to go into this branch that marks the - // `requestSession.status` as `Crashed`, and this check is necessary because the `SessionFlusher` is only - // instantiated when the the`requestHandler` middleware is initialised, which indicates that we should be - // running in SessionAggregates mode - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - var isSessionAggregatesMode = client._sessionFlusher !== undefined; - if (isSessionAggregatesMode) { - var requestSession = _scope.getRequestSession(); - // If an error bubbles to the `errorHandler`, then this is an unhandled error, and should be reported as a - // Crashed session. The `_requestSession.status` is checked to ensure that this error is happening within - // the bounds of a request, and if so the status is updated - if (requestSession && requestSession.status !== undefined) - requestSession.status = types_1.RequestSessionStatus.Crashed; - } - } - 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; -//# sourceMappingURL=handlers.js.map - -/***/ }), - -/***/ 22783: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -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.SDK_VERSION = core_1.SDK_VERSION; -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; -exports.getSentryRelease = sdk_1.getSentryRelease; -var utils_1 = __nccwpck_require__(27937); -exports.deepReadDirSync = utils_1.deepReadDirSync; -var version_1 = __nccwpck_require__(31271); -exports.SDK_NAME = version_1.SDK_NAME; -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 - -/***/ }), - -/***/ 29552: -/***/ ((__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 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; - 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(console, 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; - } - /* eslint-disable prefer-rest-params */ - 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); - }; - /* eslint-enable prefer-rest-params */ - }; -} -//# sourceMappingURL=console.js.map - -/***/ }), - -/***/ 76280: -/***/ ((__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 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); - // eslint-disable-next-line @typescript-eslint/no-var-requires - 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) { - // eslint-disable-next-line @typescript-eslint/no-var-requires - 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(this, 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: 'http.client', - }); - var sentryTraceHeader = span.toTraceparent(); - utils_1.logger.log("[Tracing] Adding sentry-trace header " + sentryTraceHeader + " to outgoing request to " + requestUrl + ": "); - 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 - -/***/ }), - -/***/ 72310: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -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 - -/***/ }), - -/***/ 70208: -/***/ ((__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 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) { - void _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) { - void parsers_1.getExceptionFromError(error[key]) - .then(function (exception) { - void _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 - -/***/ }), - -/***/ 90046: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -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 paths */ -function getPaths() { - try { - return require.cache ? Object.keys(require.cache) : []; - } - catch (e) { - return []; - } -} -/** Extract information about package.json modules */ -function collectModules() { - var mainPaths = (require.main && require.main.paths) || []; - var paths = getPaths(); - 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 - -/***/ }), - -/***/ 50443: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -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 errorhandling_1 = __nccwpck_require__(5635); -/** 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 = errorhandling_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, - data: { mechanism: { handled: false, type: 'onuncaughtexception' } }, - }); - 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'); - errorhandling_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__) => { - -Object.defineProperty(exports, "__esModule", ({ value: true })); -var core_1 = __nccwpck_require__(79212); -var utils_1 = __nccwpck_require__(1620); -var errorhandling_1 = __nccwpck_require__(5635); -/** 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, - data: { mechanism: { handled: false, type: 'onunhandledrejection' } }, - }); - }); - /* 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); - }); - errorhandling_1.logAndExitProcess(reason); - } - /* eslint-enable no-console */ - }; - /** - * @inheritDoc - */ - OnUnhandledRejection.id = 'OnUnhandledRejection'; - return OnUnhandledRejection; -}()); -exports.OnUnhandledRejection = OnUnhandledRejection; -//# sourceMappingURL=onunhandledrejection.js.map - -/***/ }), - -/***/ 5635: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -Object.defineProperty(exports, "__esModule", ({ value: true })); -var core_1 = __nccwpck_require__(79212); -var utils_1 = __nccwpck_require__(1620); -var DEFAULT_SHUTDOWN_TIMEOUT = 2000; -/** - * @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=errorhandling.js.map - -/***/ }), - -/***/ 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 utils_1 = __nccwpck_require__(1620); -var url_1 = __nccwpck_require__(57310); -var NODE_VERSION = utils_1.parseSemver(process.versions.node); -/** - * 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; -} -exports.isSentryRequest = isSentryRequest; -/** - * Assemble a URL to be used for breadcrumbs and spans. - * - * @param requestOptions RequestOptions object containing the component parts for a URL - * @returns Fully-formed URL - */ -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; -/** - * 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 - * - * @returns The cleaned description - */ -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; -} -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. - * - * See https://github.com/nodejs/node/blob/master/lib/internal/url.js. - */ -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; -/** - * 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. - * - * @returns Equivalent args of the form [ RequestOptions ] or [ RequestOptions, RequestCallback ]. - */ -function normalizeRequestArgs(httpModule, requestArgs) { - var _a, _b, _c, _d, _e, _f, _g, _h; - 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]); - } - // Figure out the protocol if it's currently missing - if (requestOptions.protocol === undefined) { - // Worst case we end up populating protocol with undefined, which it already is - /* eslint-disable @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any */ - // NOTE: Prior to Node 9, `https` used internals of `http` module, thus we don't patch it. - // Because of that, we cannot rely on `httpModule` to provide us with valid protocol, - // as it will always return `http`, even when using `https` module. - // - // See test/integrations/http.test.ts for more details on Node <=v8 protocol issue. - if (NODE_VERSION.major && NODE_VERSION.major > 8) { - requestOptions.protocol = - ((_b = (_a = httpModule) === null || _a === void 0 ? void 0 : _a.globalAgent) === null || _b === void 0 ? void 0 : _b.protocol) || ((_c = requestOptions.agent) === null || _c === void 0 ? void 0 : _c.protocol) || ((_d = requestOptions._defaultAgent) === null || _d === void 0 ? void 0 : _d.protocol); - } - else { - requestOptions.protocol = - ((_e = requestOptions.agent) === null || _e === void 0 ? void 0 : _e.protocol) || ((_f = requestOptions._defaultAgent) === null || _f === void 0 ? void 0 : _f.protocol) || ((_h = (_g = httpModule) === null || _g === void 0 ? void 0 : _g.globalAgent) === null || _h === void 0 ? void 0 : _h.protocol); - } - /* eslint-enable @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any */ - } - // return args in standardized form - if (callback) { - return [requestOptions, callback]; - } - else { - return [requestOptions]; - } -} -exports.normalizeRequestArgs = normalizeRequestArgs; -//# sourceMappingURL=http.js.map - -/***/ }), - -/***/ 19090: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -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(); -} -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; - } - // 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); - } - }); -} -/** - * @hidden - */ -function extractStackFromError(error) { - var stack = stacktrace.parse(error); - if (!stack) { - return []; - } - return stack; -} -exports.extractStackFromError = extractStackFromError; -/** - * @hidden - */ -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 _a; - var parsedFrame = { - colno: frame.columnNumber, - filename: ((_a = frame.fileName) === null || _a === void 0 ? void 0 : _a.startsWith('file://')) ? frame.fileName.substr(7) : 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; -/** - * 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 - */ -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); - }); - }); -} -/** - * @hidden - */ -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); - }); - }); -} -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; -/** - * @hidden - */ -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 - -/***/ }), - -/***/ 38836: -/***/ ((__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 hub_1 = __nccwpck_require__(6393); -var types_1 = __nccwpck_require__(83789); -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 = {}; } - var _a; - var carrier = hub_1.getMainCarrier(); - var autoloadedIntegrations = ((_a = carrier.__SENTRY__) === null || _a === void 0 ? void 0 : _a.integrations) || []; - options.defaultIntegrations = - options.defaultIntegrations === false - ? [] - : tslib_1.__spread((Array.isArray(options.defaultIntegrations) ? options.defaultIntegrations : exports.defaultIntegrations), autoloadedIntegrations); - if (options.dsn === undefined && process.env.SENTRY_DSN) { - options.dsn = process.env.SENTRY_DSN; - } - if (options.tracesSampleRate === undefined && process.env.SENTRY_TRACES_SAMPLE_RATE) { - var tracesSampleRate = parseFloat(process.env.SENTRY_TRACES_SAMPLE_RATE); - if (isFinite(tracesSampleRate)) { - options.tracesSampleRate = tracesSampleRate; - } - } - if (options.release === undefined) { - var detectedRelease = getSentryRelease(); - if (detectedRelease !== undefined) { - options.release = detectedRelease; - } - else { - // If release is not provided, then we should disable autoSessionTracking - options.autoSessionTracking = false; - } - } - if (options.environment === undefined && process.env.SENTRY_ENVIRONMENT) { - options.environment = process.env.SENTRY_ENVIRONMENT; - } - if (options.autoSessionTracking === undefined && options.dsn !== undefined) { - options.autoSessionTracking = true; - } - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any - if (domain.active) { - hub_1.setHubOnCarrier(carrier, core_1.getCurrentHub()); - } - core_1.initAndBind(client_1.NodeClient, options); - if (options.autoSessionTracking) { - startSessionTracking(); - } -} -exports.init = init; -/** - * This is the getter for lastEventId. - * - * @returns The last event id of a captured event. - */ -function lastEventId() { - return core_1.getCurrentHub().lastEventId(); -} -exports.lastEventId = lastEventId; -/** - * Call `flush()` on the current client, if there is one. See {@link Client.flush}. - * - * @param timeout Maximum time in ms the client should wait to flush its event queue. Omitting this parameter will cause - * the client to wait until all events are sent before resolving the promise. - * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it - * doesn't (or if there's no client defined). - */ -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)]; - } - utils_1.logger.warn('Cannot flush events. No client defined.'); - return [2 /*return*/, Promise.resolve(false)]; - }); - }); -} -exports.flush = flush; -/** - * Call `close()` on the current client, if there is one. See {@link Client.close}. - * - * @param timeout Maximum time in ms the client should wait to flush its event queue before shutting down. Omitting this - * parameter will cause the client to wait until all events are sent before disabling itself. - * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it - * doesn't (or if there's no client defined). - */ -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)]; - } - utils_1.logger.warn('Cannot flush events and disable SDK. No client defined.'); - return [2 /*return*/, Promise.resolve(false)]; - }); - }); -} -exports.close = close; -/** - * Function that takes an instance of NodeClient and checks if autoSessionTracking option is enabled for that client - */ -function isAutoSessionTrackingEnabled(client) { - if (client === undefined) { - return false; - } - var clientOptions = client && client.getOptions(); - if (clientOptions && clientOptions.autoSessionTracking !== undefined) { - return clientOptions.autoSessionTracking; - } - return false; -} -exports.isAutoSessionTrackingEnabled = isAutoSessionTrackingEnabled; -/** - * Returns a release dynamically from environment variables. - */ -function getSentryRelease(fallback) { - // Always read first as Sentry takes this as precedence - if (process.env.SENTRY_RELEASE) { - return process.env.SENTRY_RELEASE; - } - // This supports the variable that sentry-webpack-plugin injects - var global = utils_1.getGlobalObject(); - if (global.SENTRY_RELEASE && global.SENTRY_RELEASE.id) { - return global.SENTRY_RELEASE.id; - } - return ( - // GitHub Actions - https://help.github.com/en/actions/configuring-and-managing-workflows/using-environment-variables#default-environment-variables - process.env.GITHUB_SHA || - // Netlify - https://docs.netlify.com/configure-builds/environment-variables/#build-metadata - process.env.COMMIT_REF || - // Vercel - https://vercel.com/docs/v2/build-step#system-environment-variables - process.env.VERCEL_GIT_COMMIT_SHA || - process.env.VERCEL_GITHUB_COMMIT_SHA || - process.env.VERCEL_GITLAB_COMMIT_SHA || - process.env.VERCEL_BITBUCKET_COMMIT_SHA || - // Zeit (now known as Vercel) - process.env.ZEIT_GITHUB_COMMIT_SHA || - process.env.ZEIT_GITLAB_COMMIT_SHA || - process.env.ZEIT_BITBUCKET_COMMIT_SHA || - fallback); -} -exports.getSentryRelease = getSentryRelease; -/** - * Enable automatic Session Tracking for the node process. - */ -function startSessionTracking() { - var hub = core_1.getCurrentHub(); - hub.startSession(); - // Emitted in the case of healthy sessions, error of `mechanism.handled: true` and unhandledrejections because - // The 'beforeExit' event is not emitted for conditions causing explicit termination, - // such as calling process.exit() or uncaught exceptions. - // Ref: https://nodejs.org/api/process.html#process_event_beforeexit - process.on('beforeExit', function () { - var _a; - var session = (_a = hub.getScope()) === null || _a === void 0 ? void 0 : _a.getSession(); - var terminalStates = [types_1.SessionStatus.Exited, types_1.SessionStatus.Crashed]; - // Only call endSession, if the Session exists on Scope and SessionStatus is not a - // Terminal Status i.e. Exited or Crashed because - // "When a session is moved away from ok it must not be updated anymore." - // Ref: https://develop.sentry.dev/sdk/sessions/ - if (session && !terminalStates.includes(session.status)) - hub.endSession(); - }); -} -//# sourceMappingURL=sdk.js.map - -/***/ }), - -/***/ 46276: -/***/ ((__unused_webpack_module, exports) => { - -/** - * 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 - * - * https://github.com/felixge/node-stack-trace/ - * @license MIT - */ -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 - -/***/ }), - -/***/ 41194: -/***/ ((__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 fs = __nccwpck_require__(57147); -var url_1 = __nccwpck_require__(57310); -var version_1 = __nccwpck_require__(31271); -var CATEGORY_MAPPING = { - event: 'error', - transaction: 'transaction', - session: 'session', - attachment: 'attachment', -}; -/** 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 rate limits in a response */ - this._rateLimits = {}; - /** Default function used to parse URLs */ - this.urlParser = function (url) { return new url_1.URL(url); }; - this._api = new core_1.API(options.dsn, options._metadata, options.tunnel); - } - /** - * @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); - }; - /** - * Extracts proxy settings from client options and env variables. - * - * Honors `no_proxy` env variable with the highest priority to allow for hosts exclusion. - * - * An order of priority for available protocols is: - * `http` => `options.httpProxy` | `process.env.http_proxy` - * `https` => `options.httpsProxy` | `options.httpProxy` | `process.env.https_proxy` | `process.env.http_proxy` - */ - BaseTransport.prototype._getProxy = function (protocol) { - var e_1, _a; - var _b = process.env, no_proxy = _b.no_proxy, http_proxy = _b.http_proxy, https_proxy = _b.https_proxy; - var _c = this.options, httpProxy = _c.httpProxy, httpsProxy = _c.httpsProxy; - var proxy = protocol === 'http' ? httpProxy || http_proxy : httpsProxy || httpProxy || https_proxy || http_proxy; - if (!no_proxy) { - return proxy; - } - var _d = this._api.getDsn(), host = _d.host, port = _d.port; - try { - for (var _e = tslib_1.__values(no_proxy.split(',')), _f = _e.next(); !_f.done; _f = _e.next()) { - var np = _f.value; - if (host.endsWith(np) || (host + ":" + port).endsWith(np)) { - return; - } - } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (_f && !_f.done && (_a = _e.return)) _a.call(_e); - } - finally { if (e_1) throw e_1.error; } - } - return proxy; - }; - /** Returns a build request option object used by request */ - BaseTransport.prototype._getRequestOptions = function (urlParts) { - var headers = tslib_1.__assign(tslib_1.__assign({}, this._api.getRequestHeaders(version_1.SDK_NAME, core_1.SDK_VERSION)), this.options.headers); - var hostname = urlParts.hostname, pathname = urlParts.pathname, port = urlParts.port, protocol = urlParts.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), - })); - }; - /** - * Gets the time that given category is disabled until for rate limiting - */ - BaseTransport.prototype._disabledUntil = function (requestType) { - var category = CATEGORY_MAPPING[requestType]; - return this._rateLimits[category] || this._rateLimits.all; - }; - /** - * Checks if a category is rate limited - */ - BaseTransport.prototype._isRateLimited = function (requestType) { - return this._disabledUntil(requestType) > new Date(Date.now()); - }; - /** - * Sets internal _rateLimits from incoming headers. Returns true if headers contains a non-empty rate limiting header. - */ - BaseTransport.prototype._handleRateLimit = function (headers) { - var e_2, _a, e_3, _b; - var now = Date.now(); - var rlHeader = headers['x-sentry-rate-limits']; - var raHeader = headers['retry-after']; - if (rlHeader) { - try { - // rate limit headers are of the form - //
,
,.. - // where each
is of the form - // : : : - // where - // is a delay in ms - // is the event type(s) (error, transaction, etc) being rate limited and is of the form - // ;;... - // is what's being limited (org, project, or key) - ignored by SDK - // is an arbitrary string like "org_quota" - ignored by SDK - for (var _c = tslib_1.__values(rlHeader.trim().split(',')), _d = _c.next(); !_d.done; _d = _c.next()) { - var limit = _d.value; - var parameters = limit.split(':', 2); - var headerDelay = parseInt(parameters[0], 10); - var delay = (!isNaN(headerDelay) ? headerDelay : 60) * 1000; // 60sec default - try { - for (var _e = (e_3 = void 0, tslib_1.__values((parameters[1] && parameters[1].split(';')) || ['all'])), _f = _e.next(); !_f.done; _f = _e.next()) { - var category = _f.value; - // categoriesAllowed is added here to ensure we are only storing rate limits for categories we support in this - // sdk and any categories that are not supported will not be added redundantly to the rateLimits object - var categoriesAllowed = tslib_1.__spread(Object.keys(CATEGORY_MAPPING).map(function (k) { return CATEGORY_MAPPING[k]; }), [ - 'all', - ]); - if (categoriesAllowed.includes(category)) - this._rateLimits[category] = new Date(now + delay); - } - } - catch (e_3_1) { e_3 = { error: e_3_1 }; } - finally { - try { - if (_f && !_f.done && (_b = _e.return)) _b.call(_e); - } - finally { if (e_3) throw e_3.error; } - } - } - } - catch (e_2_1) { e_2 = { error: e_2_1 }; } - finally { - try { - if (_d && !_d.done && (_a = _c.return)) _a.call(_c); - } - finally { if (e_2) throw e_2.error; } - } - return true; - } - else if (raHeader) { - this._rateLimits.all = new Date(now + utils_1.parseRetryAfterHeader(now, raHeader)); - return true; - } - return false; - }; - /** JSDoc */ - BaseTransport.prototype._send = function (sentryRequest, originalPayload) { - return tslib_1.__awaiter(this, void 0, void 0, function () { - var _this = this; - return tslib_1.__generator(this, function (_a) { - if (!this.module) { - throw new utils_1.SentryError('No module available'); - } - if (originalPayload && this._isRateLimited(sentryRequest.type)) { - return [2 /*return*/, Promise.reject({ - payload: originalPayload, - type: sentryRequest.type, - reason: "Transport for " + sentryRequest.type + " requests locked till " + this._disabledUntil(sentryRequest.type) + " due to too many requests.", - status: 429, - })]; - } - return [2 /*return*/, this._buffer.add(function () { - return new Promise(function (resolve, reject) { - if (!_this.module) { - throw new utils_1.SentryError('No module available'); - } - var options = _this._getRequestOptions(_this.urlParser(sentryRequest.url)); - var req = _this.module.request(options, function (res) { - var statusCode = res.statusCode || 500; - var status = types_1.Status.fromHttpCode(statusCode); - res.setEncoding('utf8'); - /** - * "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); - var rlHeader = res.headers ? res.headers['x-sentry-rate-limits'] : ''; - rlHeader = (Array.isArray(rlHeader) ? rlHeader[0] : rlHeader); - var headers = { - 'x-sentry-rate-limits': rlHeader, - 'retry-after': retryAfterHeader, - }; - var limited = _this._handleRateLimit(headers); - if (limited) - utils_1.logger.warn("Too many " + sentryRequest.type + " requests, backing off until: " + _this._disabledUntil(sentryRequest.type)); - if (status === types_1.Status.Success) { - resolve({ status: status }); - } - else { - 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(sentryRequest.body); - }); - })]; - }); - }); - }; - return BaseTransport; -}()); -exports.BaseTransport = BaseTransport; -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 84490: -/***/ ((__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 http = __nccwpck_require__(13685); -var base_1 = __nccwpck_require__(41194); -/** 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 = _this._getProxy('http'); - _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) { - return this._send(core_1.eventToSentryRequest(event, this._api), event); - }; - /** - * @inheritDoc - */ - HTTPTransport.prototype.sendSession = function (session) { - return this._send(core_1.sessionToSentryRequest(session, this._api), session); - }; - return HTTPTransport; -}(base_1.BaseTransport)); -exports.HTTPTransport = HTTPTransport; -//# sourceMappingURL=http.js.map - -/***/ }), - -/***/ 68621: -/***/ ((__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 https = __nccwpck_require__(95687); -var base_1 = __nccwpck_require__(41194); -/** 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 = _this._getProxy('https'); - _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) { - return this._send(core_1.eventToSentryRequest(event, this._api), event); - }; - /** - * @inheritDoc - */ - HTTPSTransport.prototype.sendSession = function (session) { - return this._send(core_1.sessionToSentryRequest(session, this._api), session); - }; - return HTTPSTransport; -}(base_1.BaseTransport)); -exports.HTTPSTransport = HTTPSTransport; -//# sourceMappingURL=https.js.map - -/***/ }), - -/***/ 21437: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -Object.defineProperty(exports, "__esModule", ({ value: true })); -var base_1 = __nccwpck_require__(41194); -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 - -/***/ }), - -/***/ 27937: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var fs = __nccwpck_require__(57147); -var path = __nccwpck_require__(71017); -/** - * Recursively read the contents of a directory. - * - * @param targetDir Absolute or relative path of the directory to scan. All returned paths will be relative to this - * directory. - * @returns Array holding all relative paths - */ -function deepReadDirSync(targetDir) { - var targetDirAbsPath = path.resolve(targetDir); - if (!fs.existsSync(targetDirAbsPath)) { - throw new Error("Cannot read contents of " + targetDirAbsPath + ". Directory does not exist."); - } - if (!fs.statSync(targetDirAbsPath).isDirectory()) { - throw new Error("Cannot read contents of " + targetDirAbsPath + ", because it is not a directory."); - } - // This does the same thing as its containing function, `deepReadDirSync` (except that - purely for convenience - it - // deals in absolute paths rather than relative ones). We need this to be separate from the outer function to preserve - // the difference between `targetDirAbsPath` and `currentDirAbsPath`. - var deepReadCurrentDir = function (currentDirAbsPath) { - return fs.readdirSync(currentDirAbsPath).reduce(function (absPaths, itemName) { - var itemAbsPath = path.join(currentDirAbsPath, itemName); - if (fs.statSync(itemAbsPath).isDirectory()) { - return tslib_1.__spread(absPaths, deepReadCurrentDir(itemAbsPath)); - } - return tslib_1.__spread(absPaths, [itemAbsPath]); - }, []); - }; - return deepReadCurrentDir(targetDirAbsPath).map(function (absPath) { return path.relative(targetDirAbsPath, absPath); }); -} -exports.deepReadDirSync = deepReadDirSync; -//# sourceMappingURL=utils.js.map - -/***/ }), - -/***/ 31271: -/***/ ((__unused_webpack_module, exports) => { - -Object.defineProperty(exports, "__esModule", ({ value: true })); -// TODO: Remove in the next major release and rely only on @sentry/core SDK_VERSION and SdkMetadata -exports.SDK_NAME = 'sentry.javascript.node'; -//# sourceMappingURL=version.js.map - -/***/ }), - -/***/ 81867: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -Object.defineProperty(exports, "__esModule", ({ value: true })); -var utils_1 = __nccwpck_require__(1620); -var constants_1 = __nccwpck_require__(4740); -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.setTag(constants_1.FINISH_REASON_TAG, constants_1.IDLE_TRANSACTION_FINISH_REASONS[2]); - 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 - -/***/ }), - -/***/ 33577: -/***/ ((__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 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.instrumentRoutingWithDefaults, 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._emitOptionsWarning = false; - /** Store configured idle timeout so that it can be added as a tag to transactions */ - this._configuredIdleTimeout = undefined; - var tracingOrigins = request_1.defaultRequestInstrumentationOptions.tracingOrigins; - // NOTE: Logger doesn't work in constructors, as it's initialized after integrations instances - if (_options) { - this._configuredIdleTimeout = _options.idleTimeout; - if (_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 }); - var _metricOptions = this.options._metricOptions; - this._metrics = new metrics_1.MetricsInstrumentation(_metricOptions && _metricOptions._reportAllChanges); - } - /** - * @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, instrumentRouting = _a.routingInstrumentation, startTransactionOnLocationChange = _a.startTransactionOnLocationChange, startTransactionOnPageLoad = _a.startTransactionOnPageLoad, markBackgroundTransactions = _a.markBackgroundTransactions, traceFetch = _a.traceFetch, traceXHR = _a.traceXHR, tracingOrigins = _a.tracingOrigins, shouldCreateSpanForRequest = _a.shouldCreateSpanForRequest; - instrumentRouting(function (context) { return _this._createRouteTransaction(context); }, startTransactionOnPageLoad, startTransactionOnLocationChange); - if (markBackgroundTransactions) { - backgroundtab_1.registerBackgroundTabDetection(); - } - request_1.instrumentOutgoingRequests({ 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."); - } - utils_1.logger.log("[Tracing] Starting " + finalContext.op + " transaction on scope"); - var hub = this._getCurrentHub(); - var location = utils_1.getGlobalObject().location; - var idleTransaction = hubextensions_1.startIdleTransaction(hub, finalContext, idleTimeout, true, { location: location }); - idleTransaction.registerBeforeFinishCallback(function (transaction, endTimestamp) { - _this._metrics.addPerformanceEntries(transaction); - adjustTransactionDuration(utils_2.secToMs(maxTransactionDuration), transaction, endTimestamp); - }); - idleTransaction.setTag('idleTimeout', this._configuredIdleTimeout); - 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 = utils_1.getGlobalObject().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 - -/***/ }), - -/***/ 71425: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -Object.defineProperty(exports, "__esModule", ({ value: true })); -var browsertracing_1 = __nccwpck_require__(33577); -exports.BrowserTracing = browsertracing_1.BrowserTracing; -var request_1 = __nccwpck_require__(27854); -exports.instrumentOutgoingRequests = request_1.instrumentOutgoingRequests; -exports.defaultRequestInstrumentationOptions = request_1.defaultRequestInstrumentationOptions; -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 68451: -/***/ ((__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 utils_2 = __nccwpck_require__(31386); -var getCLS_1 = __nccwpck_require__(56982); -var getFID_1 = __nccwpck_require__(82496); -var getLCP_1 = __nccwpck_require__(99382); -var getVisibilityWatcher_1 = __nccwpck_require__(10522); -var global = utils_1.getGlobalObject(); -/** Class tracking metrics */ -var MetricsInstrumentation = /** @class */ (function () { - function MetricsInstrumentation(_reportAllChanges) { - if (_reportAllChanges === void 0) { _reportAllChanges = false; } - var _a, _b; - this._reportAllChanges = _reportAllChanges; - this._measurements = {}; - this._performanceCursor = 0; - if (!utils_1.isNodeEnv() && ((_a = global) === null || _a === void 0 ? void 0 : _a.performance) && ((_b = global) === null || _b === void 0 ? void 0 : _b.document)) { - if (global.performance.mark) { - global.performance.mark('sentry-tracing-init'); - } - this._trackCLS(); - this._trackLCP(); - this._trackFID(); - } - } - /** 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 && global.document.scripts) { - // eslint-disable-next-line @typescript-eslint/prefer-for-of - for (var i = 0; i < global.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 (global.document.scripts[i].dataset.entry === 'true') { - entryScriptSrc = global.document.scripts[i].src; - break; - } - } - } - var entryScriptStartTimestamp; - var tracingInitMarkStartTime; - var responseStartTimestamp; - var requestStartTimestamp; - 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); - responseStartTimestamp = timeOrigin + utils_2.msToSec(entry.responseStart); - requestStartTimestamp = timeOrigin + utils_2.msToSec(entry.requestStart); - 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 = getVisibilityWatcher_1.getVisibilityWatcher(); - // Only report if the page wasn't hidden prior to the web vital. - var shouldRecord = entry.startTime < firstHidden.firstHiddenTime; - 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(global.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); - // Generate TTFB (Time to First Byte), which measured as the time between the beginning of the transaction and the - // start of the response in milliseconds - if (typeof responseStartTimestamp === 'number') { - utils_1.logger.log('[Measurements] Adding TTFB'); - this._measurements['ttfb'] = { value: (responseStartTimestamp - transaction.startTimestamp) * 1000 }; - if (typeof requestStartTimestamp === 'number' && requestStartTimestamp <= responseStartTimestamp) { - // Capture the time spent making the request and receiving the first byte of the response. - // This is the time between the start of the request and the start of the response in milliseconds. - this._measurements['ttfb.requestTime'] = { value: (responseStartTimestamp - requestStartTimestamp) * 1000 }; - } - } - ['fcp', 'fp', 'lcp'].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, - }); - } - // If FCP is not recorded we should not record the cls value - // according to the new definition of CLS. - if (!('fcp' in this._measurements)) { - delete this._measurements.cls; - } - transaction.setMeasurements(this._measurements); - this._tagMetricInfo(transaction); - transaction.setTag('sentry_reportAllChanges', this._reportAllChanges); - } - }; - /** Add LCP / CLS data to transaction to allow debugging */ - MetricsInstrumentation.prototype._tagMetricInfo = function (transaction) { - if (this._lcpEntry) { - utils_1.logger.log('[Measurements] Adding LCP Data'); - // Capture Properties of the LCP element that contributes to the LCP. - if (this._lcpEntry.element) { - transaction.setTag('lcp.element', utils_1.htmlTreeAsString(this._lcpEntry.element)); - } - if (this._lcpEntry.id) { - transaction.setTag('lcp.id', this._lcpEntry.id); - } - if (this._lcpEntry.url) { - // Trim URL to the first 200 characters. - transaction.setTag('lcp.url', this._lcpEntry.url.trim().slice(0, 200)); - } - transaction.setTag('lcp.size', this._lcpEntry.size); - } - // See: https://developer.mozilla.org/en-US/docs/Web/API/LayoutShift - if (this._clsEntry && this._clsEntry.sources) { - utils_1.logger.log('[Measurements] Adding CLS Data'); - this._clsEntry.sources.forEach(function (source, index) { - return transaction.setTag("cls.source." + (index + 1), utils_1.htmlTreeAsString(source.node)); - }); - } - }; - /** Starts tracking the Cumulative Layout Shift on the current page. */ - MetricsInstrumentation.prototype._trackCLS = function () { - var _this = this; - // See: - // https://web.dev/evolving-cls/ - // https://web.dev/cls-web-tooling/ - 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 }; - _this._clsEntry = entry; - }); - }; - /** - * 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(utils_1.browserPerformanceTimeOrigin); - 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 }; - _this._lcpEntry = entry; - }, this._reportAllChanges); - }; - /** 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(utils_1.browserPerformanceTimeOrigin); - 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 }; - }); - }; - return MetricsInstrumentation; -}()); -exports.MetricsInstrumentation = MetricsInstrumentation; -/** Instrument navigation entries */ -function addNavigationSpans(transaction, entry, timeOrigin) { - addPerformanceNavigationTiming({ transaction: transaction, entry: entry, event: 'unloadEvent', timeOrigin: timeOrigin }); - addPerformanceNavigationTiming({ transaction: transaction, entry: entry, event: 'redirect', timeOrigin: timeOrigin }); - addPerformanceNavigationTiming({ transaction: transaction, entry: entry, event: 'domContentLoadedEvent', timeOrigin: timeOrigin }); - addPerformanceNavigationTiming({ transaction: transaction, entry: entry, event: 'loadEvent', timeOrigin: timeOrigin }); - addPerformanceNavigationTiming({ transaction: transaction, entry: entry, event: 'connect', timeOrigin: timeOrigin }); - addPerformanceNavigationTiming({ - transaction: transaction, - entry: entry, - event: 'secureConnection', - timeOrigin: timeOrigin, - eventEnd: 'connectEnd', - description: 'TLS/SSL', - }); - addPerformanceNavigationTiming({ - transaction: transaction, - entry: entry, - event: 'fetch', - timeOrigin: timeOrigin, - eventEnd: 'domainLookupStart', - description: 'cache', - }); - addPerformanceNavigationTiming({ transaction: transaction, entry: entry, event: 'domainLookup', timeOrigin: timeOrigin, description: 'DNS' }); - 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; -} -/** 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; - } - 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, - }); - return endTimestamp; -} -exports.addResourceSpans = addResourceSpans; -/** Create performance navigation related spans */ -function addPerformanceNavigationTiming(props) { - var transaction = props.transaction, entry = props.entry, event = props.event, timeOrigin = props.timeOrigin, eventEnd = props.eventEnd, description = props.description; - var end = eventEnd ? entry[eventEnd] : entry[event + "End"]; - var start = entry[event + "Start"]; - if (!start || !end) { - return; - } - _startChild(transaction, { - op: 'browser', - description: (description !== null && description !== void 0 ? description : event), - startTimestamp: timeOrigin + utils_2.msToSec(start), - endTimestamp: timeOrigin + utils_2.msToSec(end), - }); -} -/** Create request and response related spans */ -function addRequest(transaction, entry, timeOrigin) { - _startChild(transaction, { - op: 'browser', - description: 'request', - startTimestamp: timeOrigin + utils_2.msToSec(entry.requestStart), - endTimestamp: timeOrigin + utils_2.msToSec(entry.responseEnd), - }); - _startChild(transaction, { - op: 'browser', - description: 'response', - startTimestamp: timeOrigin + utils_2.msToSec(entry.responseStart), - endTimestamp: timeOrigin + utils_2.msToSec(entry.responseEnd), - }); -} -/** - * 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)); -} -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 - -/***/ }), - -/***/ 27854: -/***/ ((__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 spanstatus_1 = __nccwpck_require__(58522); -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 instrumentOutgoingRequests(_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', - }); - } -} -exports.instrumentOutgoingRequests = instrumentOutgoingRequests; -/** - * Create and track fetch request spans - */ -function fetchCallback(handlerData, shouldCreateSpan, spans) { - if (!utils_2.hasTracingEnabled() || !(handlerData.fetchData && shouldCreateSpan(handlerData.fetchData.url))) { - return; - } - if (handlerData.endTimestamp && handlerData.fetchData.__span) { - var span = spans[handlerData.fetchData.__span]; - if (span) { - if (handlerData.response) { - // TODO (kmclb) remove this once types PR goes through - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - span.setHttpStatus(handlerData.response.status); - } - else if (handlerData.error) { - span.setStatus(spanstatus_1.SpanStatus.InternalError); - } - 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.client', - }); - 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; - } -} -exports.fetchCallback = fetchCallback; -/** - * Create and track xhr request spans - */ -function xhrCallback(handlerData, shouldCreateSpan, spans) { - var _a, _b; - if (!utils_2.hasTracingEnabled() || ((_a = handlerData.xhr) === null || _a === void 0 ? void 0 : _a.__sentry_own_request__) || - !(((_b = handlerData.xhr) === null || _b === void 0 ? void 0 : _b.__sentry_xhr__) && shouldCreateSpan(handlerData.xhr.__sentry_xhr__.url))) { - 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.client', - }); - 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 - -/***/ }), - -/***/ 40348: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -Object.defineProperty(exports, "__esModule", ({ value: true })); -var utils_1 = __nccwpck_require__(1620); -var global = utils_1.getGlobalObject(); -/** - * Default function implementing pageload and navigation transactions - */ -function instrumentRoutingWithDefaults(customStartTransaction, 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 = customStartTransaction({ 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 = customStartTransaction({ name: global.location.pathname, op: 'navigation' }); - } - }, - type: 'history', - }); - } -} -exports.instrumentRoutingWithDefaults = instrumentRoutingWithDefaults; -//# sourceMappingURL=router.js.map - -/***/ }), - -/***/ 56982: -/***/ ((__unused_webpack_module, 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 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) { - var metric = initMetric_1.initMetric('CLS', 0); - var report; - var sessionValue = 0; - var sessionEntries = []; - var entryHandler = function (entry) { - // Only count layout shifts without recent user input. - // TODO: Figure out why entry can be undefined - if (entry && !entry.hadRecentInput) { - var firstSessionEntry = sessionEntries[0]; - var lastSessionEntry = sessionEntries[sessionEntries.length - 1]; - // If the entry occurred less than 1 second after the previous entry and - // less than 5 seconds after the first entry in the session, include the - // entry in the current session. Otherwise, start a new session. - if (sessionValue && - sessionEntries.length !== 0 && - entry.startTime - lastSessionEntry.startTime < 1000 && - entry.startTime - firstSessionEntry.startTime < 5000) { - sessionValue += entry.value; - sessionEntries.push(entry); - } - else { - sessionValue = entry.value; - sessionEntries = [entry]; - } - // If the current session value is larger than the current CLS value, - // update CLS and the entries contributing to it. - if (sessionValue > metric.value) { - metric.value = sessionValue; - metric.entries = sessionEntries; - if (report) { - report(); - } - } - } - }; - var po = observe_1.observe('layout-shift', entryHandler); - if (po) { - report = bindReporter_1.bindReporter(onReport, metric, reportAllChanges); - onHidden_1.onHidden(function () { - po.takeRecords().map(entryHandler); - report(true); - }); - } -}; -//# sourceMappingURL=getCLS.js.map - -/***/ }), - -/***/ 82496: -/***/ ((__unused_webpack_module, 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 bindReporter_1 = __nccwpck_require__(54592); -var getVisibilityWatcher_1 = __nccwpck_require__(10522); -var initMetric_1 = __nccwpck_require__(45300); -var observe_1 = __nccwpck_require__(17984); -var onHidden_1 = __nccwpck_require__(9658); -exports.getFID = function (onReport, reportAllChanges) { - var visibilityWatcher = getVisibilityWatcher_1.getVisibilityWatcher(); - var metric = initMetric_1.initMetric('FID'); - var report; - var entryHandler = function (entry) { - // Only report if the page wasn't hidden prior to the first input. - if (report && entry.startTime < visibilityWatcher.firstHiddenTime) { - metric.value = entry.processingStart - entry.startTime; - metric.entries.push(entry); - report(true); - } - }; - var po = observe_1.observe('first-input', entryHandler); - if (po) { - report = bindReporter_1.bindReporter(onReport, metric, reportAllChanges); - onHidden_1.onHidden(function () { - po.takeRecords().map(entryHandler); - po.disconnect(); - }, true); - } -}; -//# sourceMappingURL=getFID.js.map - -/***/ }), - -/***/ 99382: -/***/ ((__unused_webpack_module, 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 bindReporter_1 = __nccwpck_require__(54592); -var getVisibilityWatcher_1 = __nccwpck_require__(10522); -var initMetric_1 = __nccwpck_require__(45300); -var observe_1 = __nccwpck_require__(17984); -var onHidden_1 = __nccwpck_require__(9658); -var reportedMetricIDs = {}; -exports.getLCP = function (onReport, reportAllChanges) { - var visibilityWatcher = getVisibilityWatcher_1.getVisibilityWatcher(); - var metric = initMetric_1.initMetric('LCP'); - 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 < visibilityWatcher.firstHiddenTime) { - metric.value = value; - metric.entries.push(entry); - } - if (report) { - report(); - } - }; - var po = observe_1.observe('largest-contentful-paint', entryHandler); - if (po) { - report = bindReporter_1.bindReporter(onReport, metric, reportAllChanges); - var stopListening_1 = function () { - if (!reportedMetricIDs[metric.id]) { - po.takeRecords().map(entryHandler); - po.disconnect(); - reportedMetricIDs[metric.id] = true; - report(true); - } - }; - // Stop listening after input. Note: while scrolling is an input that - // stop LCP observation, it's unreliable since it can be programmatically - // generated. See: https://github.com/GoogleChrome/web-vitals/issues/75 - ['keydown', 'click'].forEach(function (type) { - addEventListener(type, stopListening_1, { once: true, capture: true }); - }); - onHidden_1.onHidden(stopListening_1, true); - } -}; -//# sourceMappingURL=getLCP.js.map - -/***/ }), - -/***/ 54592: -/***/ ((__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 })); -exports.bindReporter = function (callback, metric, reportAllChanges) { - var prevValue; - return function (forceReport) { - if (metric.value >= 0) { - if (forceReport || reportAllChanges) { - metric.delta = metric.value - (prevValue || 0); - // Report the metric if there's a non-zero delta 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 || prevValue === undefined) { - prevValue = metric.value; - callback(metric); - } - } - } - }; -}; -//# sourceMappingURL=bindReporter.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, 30-char string by combining a version - * number, the current timestamp with a 13-digit number integer. - * @return {string} - */ -exports.generateUniqueID = function () { - return "v2-" + Date.now() + "-" + (Math.floor(Math.random() * (9e12 - 1)) + 1e12); -}; -//# sourceMappingURL=generateUniqueID.js.map - -/***/ }), - -/***/ 10522: -/***/ ((__unused_webpack_module, 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 utils_1 = __nccwpck_require__(1620); -var onHidden_1 = __nccwpck_require__(9658); -var firstHiddenTime = -1; -var initHiddenTime = function () { - return utils_1.getGlobalObject().document.visibilityState === 'hidden' ? 0 : Infinity; -}; -var trackChanges = function () { - // Update the time if/when the document becomes hidden. - onHidden_1.onHidden(function (_a) { - var timeStamp = _a.timeStamp; - firstHiddenTime = timeStamp; - }, true); -}; -exports.getVisibilityWatcher = function () { - if (firstHiddenTime < 0) { - // 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 = initHiddenTime(); - trackChanges(); - } - return { - get firstHiddenTime() { - return firstHiddenTime; - }, - }; -}; -//# sourceMappingURL=getVisibilityWatcher.js.map - -/***/ }), - -/***/ 45300: -/***/ ((__unused_webpack_module, 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) { - return { - name: name, - value: (value !== null && value !== void 0 ? value : -1), - delta: 0, - entries: [], - id: generateUniqueID_1.generateUniqueID(), - }; -}; -//# sourceMappingURL=initMetric.js.map - -/***/ }), - -/***/ 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)) { - // More extensive feature detect needed for Firefox due to: - // https://github.com/GoogleChrome/web-vitals/issues/142 - if (type === 'first-input' && !('PerformanceEventTiming' in self)) { - return; - } - 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 - -/***/ }), - -/***/ 9658: -/***/ ((__unused_webpack_module, 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 utils_1 = __nccwpck_require__(1620); -exports.onHidden = function (cb, once) { - var onHiddenOrPageHide = function (event) { - if (event.type === 'pagehide' || utils_1.getGlobalObject().document.visibilityState === 'hidden') { - cb(event); - if (once) { - removeEventListener('visibilitychange', onHiddenOrPageHide, true); - removeEventListener('pagehide', onHiddenOrPageHide, true); - } - } - }; - addEventListener('visibilitychange', onHiddenOrPageHide, true); - // Some browsers have buggy implementations of visibilitychange, - // so we use pagehide in addition, just to be safe. - addEventListener('pagehide', onHiddenOrPageHide, true); -}; -//# sourceMappingURL=onHidden.js.map - -/***/ }), - -/***/ 4740: -/***/ ((__unused_webpack_module, exports) => { - -Object.defineProperty(exports, "__esModule", ({ value: true })); -// Store finish reasons in tuple to save on bundle size -// Readonly type should enforce that this is not mutated. -exports.FINISH_REASON_TAG = 'finishReason'; -exports.IDLE_TRANSACTION_FINISH_REASONS = ['heartbeatFailed', 'idleTimeout', 'documentHidden']; -//# sourceMappingURL=constants.js.map - -/***/ }), - -/***/ 47906: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -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); - } -} -//# sourceMappingURL=errors.js.map - -/***/ }), - -/***/ 31409: -/***/ ((module, exports, __nccwpck_require__) => { - -/* 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(), - }; - } - } - 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(transaction, options, samplingContext) { - // nothing to do if tracing is not enabled - if (!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.setMetadata({ - transactionSampling: { method: 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); - transaction.setMetadata({ - transactionSampling: { - method: types_1.TransactionSamplingMethod.Sampler, - // cast to number in case it's a boolean - rate: Number(sampleRate), - }, - }); - } - else if (samplingContext.parentSampled !== undefined) { - sampleRate = samplingContext.parentSampled; - transaction.setMetadata({ - transactionSampling: { method: types_1.TransactionSamplingMethod.Inheritance }, - }); - } - else { - sampleRate = options.tracesSampleRate; - transaction.setMetadata({ - transactionSampling: { - method: types_1.TransactionSamplingMethod.Rate, - // cast to number in case it's a boolean - rate: 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; - } - utils_1.logger.log("[Tracing] starting " + transaction.op + " transaction - " + transaction.name); - return transaction; -} -/** - * 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; - } - // 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; -} -/** - * 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 _a, _b; - var options = ((_a = this.getClient()) === null || _a === void 0 ? void 0 : _a.getOptions()) || {}; - var transaction = new transaction_1.Transaction(transactionContext, this); - transaction = sample(transaction, options, tslib_1.__assign({ parentSampled: transactionContext.parentSampled, transactionContext: transactionContext }, customSamplingContext)); - if (transaction.sampled) { - transaction.initSpanRecorder((_b = options._experiments) === null || _b === void 0 ? void 0 : _b.maxSpans); - } - return transaction; -} -/** - * Create new idle transaction. - */ -function startIdleTransaction(hub, transactionContext, idleTimeout, onScope, customSamplingContext) { - var _a, _b; - var options = ((_a = hub.getClient()) === null || _a === void 0 ? void 0 : _a.getOptions()) || {}; - var transaction = new idletransaction_1.IdleTransaction(transactionContext, hub, idleTimeout, onScope); - transaction = sample(transaction, options, tslib_1.__assign({ parentSampled: transactionContext.parentSampled, transactionContext: transactionContext }, customSamplingContext)); - if (transaction.sampled) { - transaction.initSpanRecorder((_b = options._experiments) === null || _b === void 0 ? void 0 : _b.maxSpans); - } - return transaction; -} -exports.startIdleTransaction = startIdleTransaction; -/** - * @private - */ -function _addTracingExtensions() { - var carrier = hub_1.getMainCarrier(); - if (!carrier.__SENTRY__) { - return; - } - 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._addTracingExtensions = _addTracingExtensions; -/** - * @private - */ -function _autoloadDatabaseIntegrations() { - var carrier = hub_1.getMainCarrier(); - if (!carrier.__SENTRY__) { - return; - } - var packageToIntegrationMapping = { - mongodb: function () { - var integration = utils_1.dynamicRequire(module, './integrations/node/mongo'); - return new integration.Mongo(); - }, - mongoose: function () { - var integration = utils_1.dynamicRequire(module, './integrations/node/mongo'); - return new integration.Mongo({ mongoose: true }); - }, - mysql: function () { - var integration = utils_1.dynamicRequire(module, './integrations/node/mysql'); - return new integration.Mysql(); - }, - pg: function () { - var integration = utils_1.dynamicRequire(module, './integrations/node/postgres'); - return new integration.Postgres(); - }, - }; - var mappedPackages = Object.keys(packageToIntegrationMapping) - .filter(function (moduleName) { return !!utils_1.loadModule(moduleName); }) - .map(function (pkg) { - try { - return packageToIntegrationMapping[pkg](); - } - catch (e) { - return undefined; - } - }) - .filter(function (p) { return p; }); - if (mappedPackages.length > 0) { - carrier.__SENTRY__.integrations = tslib_1.__spread((carrier.__SENTRY__.integrations || []), mappedPackages); - } -} -/** - * This patches the global object and injects the Tracing extensions methods - */ -function addExtensionMethods() { - _addTracingExtensions(); - // Detect and automatically load specified integrations. - if (utils_1.isNodeEnv()) { - _autoloadDatabaseIntegrations(); - } - // 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 - -/***/ }), - -/***/ 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 constants_1 = __nccwpck_require__(4740); -var span_1 = __nccwpck_require__(64655); -var spanstatus_1 = __nccwpck_require__(58522); -var transaction_1 = __nccwpck_require__(8186); -exports.DEFAULT_IDLE_TIMEOUT = 1000; -exports.HEARTBEAT_INTERVAL = 5000; -/** - * @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); - } - } - _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 = {}; - // 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); }); - } - _this._initTimeout = setTimeout(function () { - if (!_this._finished) { - _this.finish(); - } - }, _this._idleTimeout); - 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; - }); - utils_1.logger.log('[Tracing] flushing IdleTransaction'); - } - else { - utils_1.logger.log('[Tracing] No active IdleTransaction'); - } - // this._onScope is true if the transaction was previously on the scope. - if (this._onScope) { - clearActiveTransaction(this._idleHub); - } - 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) { - 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.setTag(constants_1.FINISH_REASON_TAG, constants_1.IDLE_TRANSACTION_FINISH_REASONS[1]); - _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 () { - // We should not be running heartbeat if the idle transaction is finished. - if (this._finished) { - return; - } - var heartbeatString = Object.keys(this.activities).join(''); - 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(constants_1.FINISH_REASON_TAG, constants_1.IDLE_TRANSACTION_FINISH_REASONS[0]); - 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); - setTimeout(function () { - _this._beat(); - }, exports.HEARTBEAT_INTERVAL); - }; - 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); - } - } - } -} -//# sourceMappingURL=idletransaction.js.map - -/***/ }), - -/***/ 64358: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -Object.defineProperty(exports, "__esModule", ({ value: true })); -var hubextensions_1 = __nccwpck_require__(31409); -exports.addExtensionMethods = hubextensions_1.addExtensionMethods; -var Integrations = __nccwpck_require__(28502); -exports.Integrations = Integrations; -// This is already exported as part of `Integrations` above (and for the moment will remain so for -// backwards compatibility), but that interferes with treeshaking, so we also export it separately -// here. -// -// Previously we expected users to import tracing integrations like -// -// import { Integrations } from '@sentry/tracing'; -// const instance = new Integrations.BrowserTracing(); -// -// This makes the integrations unable to be treeshaken though. To address this, we now have -// this individual export. We now expect users to consume BrowserTracing like so: -// -// import { BrowserTracing } from '@sentry/tracing'; -// const instance = new BrowserTracing(); -// -// For an example of of the new usage of BrowserTracing, see @sentry/nextjs index.client.ts -var browser_1 = __nccwpck_require__(71425); -exports.BrowserTracing = browser_1.BrowserTracing; -var span_1 = __nccwpck_require__(64655); -exports.Span = span_1.Span; -var transaction_1 = __nccwpck_require__(8186); -exports.Transaction = transaction_1.Transaction; -var browser_2 = __nccwpck_require__(71425); -// TODO deprecate old name in v7 -exports.registerRequestInstrumentation = browser_2.instrumentOutgoingRequests; -exports.defaultRequestInstrumentationOptions = browser_2.defaultRequestInstrumentationOptions; -var spanstatus_1 = __nccwpck_require__(58522); -exports.SpanStatus = spanstatus_1.SpanStatus; -var idletransaction_1 = __nccwpck_require__(2171); -exports.IdleTransaction = idletransaction_1.IdleTransaction; -var hubextensions_2 = __nccwpck_require__(31409); -exports.startIdleTransaction = hubextensions_2.startIdleTransaction; -// 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 - -/***/ }), - -/***/ 28502: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -Object.defineProperty(exports, "__esModule", ({ value: true })); -var express_1 = __nccwpck_require__(42971); -exports.Express = express_1.Express; -var postgres_1 = __nccwpck_require__(19327); -exports.Postgres = postgres_1.Postgres; -var mysql_1 = __nccwpck_require__(57296); -exports.Mysql = mysql_1.Mysql; -var mongo_1 = __nccwpck_require__(33146); -exports.Mongo = mongo_1.Mongo; -// TODO(v7): Remove this export -// Please see `src/index.ts` for more details. -var browser_1 = __nccwpck_require__(71425); -exports.BrowserTracing = browser_1.BrowserTracing; -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 42971: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -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'); - } - /** - * @inheritDoc - */ - Express.prototype.setupOnce = function () { - if (!this._router) { - utils_1.logger.error('ExpressIntegration is missing an Express instance'); - return; - } - 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: "express.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: "express.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: "express.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); - } - } -} -/** - * 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 - -/***/ }), - -/***/ 33146: -/***/ ((__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 OPERATIONS = [ - 'aggregate', - 'bulkWrite', - 'countDocuments', - 'createIndex', - 'createIndexes', - 'deleteMany', - 'deleteOne', - 'distinct', - 'drop', - 'dropIndex', - 'dropIndexes', - 'estimatedDocumentCount', - 'find', - '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'], - find: ['query'], - 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; - this._useMongoose = !!options.useMongoose; - } - /** - * @inheritDoc - */ - Mongo.prototype.setupOnce = function (_, getCurrentHub) { - var moduleName = this._useMongoose ? 'mongoose' : 'mongodb'; - var pkg = utils_1.loadModule(moduleName); - if (!pkg) { - utils_1.logger.error("Mongo Integration was unable to require `" + moduleName + "` package."); - return; - } - this._instrumentOperations(pkg.Collection, this._operations, getCurrentHub); - }; - /** - * Patches original collection methods - */ - Mongo.prototype._instrumentOperations = function (collection, operations, getCurrentHub) { - var _this = this; - operations.forEach(function (operation) { return _this._patchOperation(collection, operation, getCurrentHub); }); - }; - /** - * 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, _d; - 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)); - var maybePromise = orig.call.apply(orig, tslib_1.__spread([this], args)); - if (utils_1.isThenable(maybePromise)) { - return maybePromise.then(function (res) { - var _a; - (_a = span_1) === null || _a === void 0 ? void 0 : _a.finish(); - return res; - }); - } - else { - (_c = span_1) === null || _c === void 0 ? void 0 : _c.finish(); - return maybePromise; - } - } - var span = (_d = parentSpan) === null || _d === void 0 ? void 0 : _d.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); - }])); - }; - }); - }; - /** - * 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; - } - 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 - -/***/ }), - -/***/ 57296: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -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; - } - /** - * @inheritDoc - */ - Mysql.prototype.setupOnce = function (_, getCurrentHub) { - var pkg = utils_1.loadModule('mysql/lib/Connection.js'); - if (!pkg) { - 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(pkg, 'createQuery', 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 - -/***/ }), - -/***/ 19327: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -Object.defineProperty(exports, "__esModule", ({ value: true })); -var utils_1 = __nccwpck_require__(1620); -/** Tracing integration for node-postgres package */ -var Postgres = /** @class */ (function () { - function Postgres(options) { - if (options === void 0) { options = {}; } - /** - * @inheritDoc - */ - this.name = Postgres.id; - this._usePgNative = !!options.usePgNative; - } - /** - * @inheritDoc - */ - Postgres.prototype.setupOnce = function (_, getCurrentHub) { - var _a; - var pkg = utils_1.loadModule('pg'); - if (!pkg) { - utils_1.logger.error('Postgres Integration was unable to require `pg` package.'); - return; - } - if (this._usePgNative && !((_a = pkg.native) === null || _a === void 0 ? void 0 : _a.Client)) { - utils_1.logger.error("Postgres Integration was unable to access 'pg-native' bindings."); - return; - } - var Client = (this._usePgNative ? pkg.native : pkg).Client; - /** - * function (query, callback) => void - * function (query, params, callback) => void - * function (query) => Promise - * function (query, params) => Promise - * function (pg.Cursor) => pg.Cursor - */ - utils_1.fill(Client.prototype, 'query', function (orig) { - return function (config, values, callback) { - var _a, _b, _c; - 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); - }); - } - var rv = typeof values !== 'undefined' ? orig.call(this, config, values) : orig.call(this, config); - if (utils_1.isThenable(rv)) { - return rv.then(function (res) { - var _a; - (_a = span) === null || _a === void 0 ? void 0 : _a.finish(); - return res; - }); - } - (_c = span) === null || _c === void 0 ? void 0 : _c.finish(); - return rv; - }; - }); - }; - /** - * @inheritDoc - */ - Postgres.id = 'Postgres'; - return Postgres; -}()); -exports.Postgres = Postgres; -//# sourceMappingURL=postgres.js.map - -/***/ }), - -/***/ 64655: -/***/ ((__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 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; - } - /** - * 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; - } - } - /** - * @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.toContext = function () { - return utils_1.dropUndefinedKeys({ - data: this.data, - description: this.description, - endTimestamp: this.endTimestamp, - op: this.op, - parentSpanId: this.parentSpanId, - sampled: this.sampled, - spanId: this.spanId, - startTimestamp: this.startTimestamp, - status: this.status, - tags: this.tags, - traceId: this.traceId, - }); - }; - /** - * @inheritDoc - */ - Span.prototype.updateWithContext = function (spanContext) { - var _a, _b, _c, _d, _e; - this.data = (_a = spanContext.data, (_a !== null && _a !== void 0 ? _a : {})); - this.description = spanContext.description; - this.endTimestamp = spanContext.endTimestamp; - this.op = spanContext.op; - this.parentSpanId = spanContext.parentSpanId; - this.sampled = spanContext.sampled; - this.spanId = (_b = spanContext.spanId, (_b !== null && _b !== void 0 ? _b : this.spanId)); - this.startTimestamp = (_c = spanContext.startTimestamp, (_c !== null && _c !== void 0 ? _c : this.startTimestamp)); - this.status = spanContext.status; - this.tags = (_d = spanContext.tags, (_d !== null && _d !== void 0 ? _d : {})); - this.traceId = (_e = spanContext.traceId, (_e !== null && _e !== void 0 ? _e : this.traceId)); - return this; - }; - /** - * @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 - -/***/ }), - -/***/ 58522: -/***/ ((__unused_webpack_module, exports) => { - -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 && httpStatus >= 100) { - 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 - -/***/ }), - -/***/ 8186: -/***/ ((__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 types_1 = __nccwpck_require__(83789); -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 || ''; - _this.metadata = transactionContext.metadata || {}; - _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); - }; - /** - * Set metadata for this transaction. - * @hidden - */ - Transaction.prototype.setMetadata = function (newMetadata) { - this.metadata = tslib_1.__assign(tslib_1.__assign({}, this.metadata), newMetadata); - }; - /** - * @inheritDoc - */ - Transaction.prototype.finish = function (endTimestamp) { - var _this = this; - var _a, _b, _c, _d, _e; - // 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.'); - (_e = (_c = (_a = this._hub - .getClient()) === null || _a === void 0 ? void 0 : (_b = _a).getTransport) === null || _c === void 0 ? void 0 : (_d = _c.call(_b)).recordLostEvent) === null || _e === void 0 ? void 0 : _e.call(_d, types_1.Outcome.SampleRate, 'transaction'); - 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', - debug_meta: this.metadata, - }; - 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; - } - utils_1.logger.log("[Tracing] Finishing " + this.op + " transaction: " + this.name + "."); - return this._hub.captureEvent(transaction); - }; - /** - * @inheritDoc - */ - Transaction.prototype.toContext = function () { - var spanContext = _super.prototype.toContext.call(this); - return utils_1.dropUndefinedKeys(tslib_1.__assign(tslib_1.__assign({}, spanContext), { name: this.name, trimEnd: this._trimEnd })); - }; - /** - * @inheritDoc - */ - Transaction.prototype.updateWithContext = function (transactionContext) { - var _a; - _super.prototype.updateWithContext.call(this, transactionContext); - this.name = (_a = transactionContext.name, (_a !== null && _a !== void 0 ? _a : '')); - this._trimEnd = transactionContext.trimEnd; - return this; - }; - return Transaction; -}(span_1.Span)); -exports.Transaction = Transaction; -//# sourceMappingURL=transaction.js.map - -/***/ }), - -/***/ 31386: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -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) { - if (options === void 0) { options = (_a = hub_1.getCurrentHub() - .getClient()) === null || _a === void 0 ? void 0 : _a.getOptions(); } - var _a; - return !!options && ('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 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 - -/***/ }), - -/***/ 83789: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -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; -exports.RequestSessionStatus = session_1.RequestSessionStatus; -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; -var transport_1 = __nccwpck_require__(36770); -exports.Outcome = transport_1.Outcome; -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 6853: -/***/ ((__unused_webpack_module, exports) => { - -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 - -/***/ }), - -/***/ 84954: -/***/ ((__unused_webpack_module, exports) => { - -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 = {})); -var RequestSessionStatus; -(function (RequestSessionStatus) { - /** JSDoc */ - RequestSessionStatus["Ok"] = "ok"; - /** JSDoc */ - RequestSessionStatus["Errored"] = "errored"; - /** JSDoc */ - RequestSessionStatus["Crashed"] = "crashed"; -})(RequestSessionStatus = exports.RequestSessionStatus || (exports.RequestSessionStatus = {})); -//# sourceMappingURL=session.js.map - -/***/ }), - -/***/ 94124: -/***/ ((__unused_webpack_module, exports) => { - -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 - -/***/ }), - -/***/ 61277: -/***/ ((__unused_webpack_module, exports) => { - -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 occurred 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; - } - return Status.Unknown; - } - Status.fromHttpCode = fromHttpCode; -})(Status = exports.Status || (exports.Status = {})); -//# sourceMappingURL=status.js.map - -/***/ }), - -/***/ 47540: -/***/ ((__unused_webpack_module, exports) => { - -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 - -/***/ }), - -/***/ 36770: -/***/ ((__unused_webpack_module, exports) => { - -Object.defineProperty(exports, "__esModule", ({ value: true })); -var Outcome; -(function (Outcome) { - Outcome["BeforeSend"] = "before_send"; - Outcome["EventProcessor"] = "event_processor"; - Outcome["NetworkError"] = "network_error"; - Outcome["QueueOverflow"] = "queue_overflow"; - Outcome["RateLimitBackoff"] = "ratelimit_backoff"; - Outcome["SampleRate"] = "sample_rate"; -})(Outcome = exports.Outcome || (exports.Outcome = {})); -//# sourceMappingURL=transport.js.map - -/***/ }), - -/***/ 58343: -/***/ ((__unused_webpack_module, exports) => { - -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) { - void 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 - -/***/ }), - -/***/ 30597: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -Object.defineProperty(exports, "__esModule", ({ value: true })); -var global_1 = __nccwpck_require__(68813); -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, keyAttrs) { - // 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, keyAttrs); - // 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, keyAttrs) { - var _a, _b; - 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()); - // Pairs of attribute keys defined in `serializeAttribute` and their values on element. - var keyAttrPairs = ((_a = keyAttrs) === null || _a === void 0 ? void 0 : _a.length) ? keyAttrs.filter(function (keyAttr) { return elem.getAttribute(keyAttr); }).map(function (keyAttr) { return [keyAttr, elem.getAttribute(keyAttr)]; }) - : null; - if ((_b = keyAttrPairs) === null || _b === void 0 ? void 0 : _b.length) { - keyAttrPairs.forEach(function (keyAttrPair) { - out.push("[" + keyAttrPair[0] + "=\"" + keyAttrPair[1] + "\"]"); - }); - } - else { - 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(''); -} -/** - * A safe form of location.href - */ -function getLocationHref() { - var global = global_1.getGlobalObject(); - try { - return global.document.location.href; - } - catch (oO) { - return ''; - } -} -exports.getLocationHref = getLocationHref; -//# sourceMappingURL=browser.js.map - -/***/ }), - -/***/ 3275: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -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, publicKey = _a.publicKey; - return (protocol + "://" + publicKey + (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], publicKey = _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, publicKey: publicKey }); - }; - /** Maps Dsn components into this instance. */ - Dsn.prototype._fromComponents = function (components) { - // TODO this is for backwards compatibility, and can be removed in a future version - if ('user' in components && !('publicKey' in components)) { - components.publicKey = components.user; - } - this.user = components.publicKey || ''; - this.protocol = components.protocol; - this.publicKey = components.publicKey || ''; - 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', 'publicKey', '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 })); -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 - -/***/ }), - -/***/ 68813: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -/** - * NOTE: In order to avoid circular dependencies, if you add a function to this module and it needs to print something, - * you must either a) use `console.log` rather than the logger, or b) put your function elsewhere. - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -var node_1 = __nccwpck_require__(16411); -var fallbackGlobalObject = {}; -/** - * Safely get global scope object - * - * @returns Global scope object - */ -function getGlobalObject() { - return (node_1.isNodeEnv() - ? global - : typeof window !== 'undefined' // eslint-disable-line no-restricted-globals - ? window // eslint-disable-line no-restricted-globals - : typeof self !== 'undefined' - ? self - : fallbackGlobalObject); -} -exports.getGlobalObject = getGlobalObject; -//# sourceMappingURL=global.js.map - -/***/ }), - -/***/ 1620: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -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__(68813), 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__) => { - -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var global_1 = __nccwpck_require__(68813); -var is_1 = __nccwpck_require__(92757); -var logger_1 = __nccwpck_require__(15577); -var object_1 = __nccwpck_require__(69249); -var stacktrace_1 = __nccwpck_require__(5986); -var supports_1 = __nccwpck_require__(88714); -var global = global_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]; - } - if ('Request' in global && is_1.isInstanceOf(fetchArgs[0], Request)) { - return fetchArgs[0].url; - } - return String(fetchArgs[0]); -} -/* 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]; - } - // 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); - }; - }); -} -var lastHref; -/** JSDoc */ -function instrumentHistory() { - if (!supports_1.supportsHistory()) { - return; - } - 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) { - // Apparently this can throw in Firefox when incorrectly implemented plugin is installed. - // https://github.com/getsentry/sentry-javascript/issues/3344 - // https://github.com/bugsnag/bugsnag-js/issues/469 - try { - return oldOnPopState.apply(this, args); - } - catch (_oO) { - // no-empty - } - } - }; - /** @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); - }; - } - object_1.fill(global.history, 'pushState', historyReplacementFunction); - object_1.fill(global.history, 'replaceState', historyReplacementFunction); -} -var debounceDuration = 1000; -var debounceTimerID; -var lastCapturedEvent; -/** - * Decide whether the current event should finish the debounce of previously captured one. - * @param previous previously captured event - * @param current event to be captured - */ -function shouldShortcircuitPreviousDebounce(previous, current) { - // If there was no previous event, it should always be swapped for the new one. - if (!previous) { - return true; - } - // If both events have different type, then user definitely performed two separate actions. e.g. click + keypress. - if (previous.type !== current.type) { - return true; - } - try { - // If both events have the same type, it's still possible that actions were performed on different targets. - // e.g. 2 clicks on different buttons. - if (previous.target !== current.target) { - return true; - } - } - catch (e) { - // just accessing `target` property can throw an exception in some rare circumstances - // see: https://github.com/getsentry/sentry-javascript/issues/838 - } - // If both events have the same type _and_ same `target` (an element which triggered an event, _not necessarily_ - // to which an event listener was attached), we treat them as the same action, as we want to capture - // only one breadcrumb. e.g. multiple clicks on the same button, or typing inside a user input box. - return false; -} -/** - * Decide whether an event should be captured. - * @param event event to be captured - */ -function shouldSkipDOMEvent(event) { - // We are only interested in filtering `keypress` events for now. - if (event.type !== 'keypress') { - return false; - } - try { - var target = event.target; - if (!target || !target.tagName) { - return true; - } - // Only consider keypress events on actual input elements. This will disregard keypresses targeting body - // e.g.tabbing through elements, hotkeys, etc. - if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable) { - return false; - } - } - catch (e) { - // just accessing `target` property can throw an exception in some rare circumstances - // see: https://github.com/getsentry/sentry-javascript/issues/838 - } - return true; -} -/** - * Wraps addEventListener to capture UI breadcrumbs - * @param handler function that will be triggered - * @param globalListener indicates whether event was captured by the global event listener - * @returns wrapped breadcrumb events handler - * @hidden - */ -function makeDOMEventHandler(handler, globalListener) { - if (globalListener === void 0) { globalListener = false; } - return function (event) { - // 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 that event. - if (!event || lastCapturedEvent === event) { - return; - } - // We always want to skip _some_ events. - if (shouldSkipDOMEvent(event)) { - return; - } - var name = event.type === 'keypress' ? 'input' : event.type; - // If there is no debounce timer, it means that we can safely capture the new event and store it for future comparisons. - if (debounceTimerID === undefined) { - handler({ - event: event, - name: name, - global: globalListener, - }); - lastCapturedEvent = event; - } - // If there is a debounce awaiting, see if the new event is different enough to treat it as a unique one. - // If that's the case, emit the previous event and store locally the newly-captured DOM event. - else if (shouldShortcircuitPreviousDebounce(lastCapturedEvent, event)) { - handler({ - event: event, - name: name, - global: globalListener, - }); - lastCapturedEvent = event; - } - // Start a new debounce timer that will prevent us from capturing multiple events that should be grouped together. - clearTimeout(debounceTimerID); - debounceTimerID = global.setTimeout(function () { - debounceTimerID = undefined; - }, debounceDuration); - }; -} -/** JSDoc */ -function instrumentDOM() { - if (!('document' in global)) { - return; - } - // Make it so that any click or keypress that is unhandled / bubbled up all the way to the document triggers our dom - // handlers. (Normally we have only one, which captures a breadcrumb for each click or keypress.) Do this before - // we instrument `addEventListener` so that we don't end up attaching this handler twice. - var triggerDOMHandler = triggerHandlers.bind(null, 'dom'); - var globalDOMEventHandler = makeDOMEventHandler(triggerDOMHandler, true); - global.document.addEventListener('click', globalDOMEventHandler, false); - global.document.addEventListener('keypress', globalDOMEventHandler, false); - // After hooking into click and keypress events bubbled up to `document`, we also hook into user-handled - // clicks & keypresses, by adding an event listener of our own to any element to which they add a listener. That - // way, whenever one of their handlers is triggered, ours will be, too. (This is needed because their handler - // could potentially prevent the event from bubbling up to our global listeners. This way, our handler are still - // guaranteed to fire at least once.) - ['EventTarget', 'Node'].forEach(function (target) { - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - var proto = global[target] && global[target].prototype; - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, no-prototype-builtins - if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty('addEventListener')) { - return; - } - object_1.fill(proto, 'addEventListener', function (originalAddEventListener) { - return function (type, listener, options) { - if (type === 'click' || type == 'keypress') { - try { - var el = this; - var handlers_1 = (el.__sentry_instrumentation_handlers__ = el.__sentry_instrumentation_handlers__ || {}); - var handlerForType = (handlers_1[type] = handlers_1[type] || { refCount: 0 }); - if (!handlerForType.handler) { - var handler = makeDOMEventHandler(triggerDOMHandler); - handlerForType.handler = handler; - originalAddEventListener.call(this, type, handler, options); - } - handlerForType.refCount += 1; - } - catch (e) { - // Accessing dom properties is always fragile. - // Also allows us to skip `addEventListenrs` calls with no proper `this` context. - } - } - return originalAddEventListener.call(this, type, listener, options); - }; - }); - object_1.fill(proto, 'removeEventListener', function (originalRemoveEventListener) { - return function (type, listener, options) { - if (type === 'click' || type == 'keypress') { - try { - var el = this; - var handlers_2 = el.__sentry_instrumentation_handlers__ || {}; - var handlerForType = handlers_2[type]; - if (handlerForType) { - handlerForType.refCount -= 1; - // If there are no longer any custom handlers of the current type on this element, we can remove ours, too. - if (handlerForType.refCount <= 0) { - originalRemoveEventListener.call(this, type, handlerForType.handler, options); - handlerForType.handler = undefined; - delete handlers_2[type]; // eslint-disable-line @typescript-eslint/no-dynamic-delete - } - // If there are no longer any custom handlers of any type on this element, cleanup everything. - if (Object.keys(handlers_2).length === 0) { - delete el.__sentry_instrumentation_handlers__; - } - } - } - catch (e) { - // Accessing dom properties is always fragile. - // Also allows us to skip `addEventListenrs` calls with no proper `this` context. - } - } - return originalRemoveEventListener.call(this, type, listener, options); - }; - }); - }); -} -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 - -/***/ }), - -/***/ 92757: -/***/ ((__unused_webpack_module, exports) => { - -/* 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); - } -} -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; - } - catch (_e) { - return false; - } -} -exports.isInstanceOf = isInstanceOf; -//# sourceMappingURL=is.js.map - -/***/ }), - -/***/ 15577: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -Object.defineProperty(exports, "__esModule", ({ value: true })); -var global_1 = __nccwpck_require__(68813); -// TODO: Implement different loggers for different environments -var global = global_1.getGlobalObject(); -/** Prefix for logging strings */ -var PREFIX = 'Sentry Logger '; -/** - * Temporarily unwrap `console.log` and friends in order to perform the given callback using the original methods. - * Restores wrapping after the callback completes. - * - * @param callback The function to run against the original `console` messages - * @returns The results of the callback - */ -function consoleSandbox(callback) { - var global = global_1.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; -/** JSDoc */ -var Logger = /** @class */ (function () { - /** JSDoc */ - function Logger() { - this._enabled = false; - } - /** 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; - } - consoleSandbox(function () { - global.console.log(PREFIX + "[Log]: " + args.join(' ')); - }); - }; - /** JSDoc */ - Logger.prototype.warn = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - if (!this._enabled) { - return; - } - consoleSandbox(function () { - global.console.warn(PREFIX + "[Warn]: " + args.join(' ')); - }); - }; - /** JSDoc */ - Logger.prototype.error = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - if (!this._enabled) { - return; - } - 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 - -/***/ }), - -/***/ 49515: -/***/ ((__unused_webpack_module, exports) => { - -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() : []; - } - /** - * 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 Memo; -}()); -exports.Memo = Memo; -//# sourceMappingURL=memo.js.map - -/***/ }), - -/***/ 32154: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var global_1 = __nccwpck_require__(68813); -var string_1 = __nccwpck_require__(66538); -/** - * UUID4 generator - * - * @returns string Generated UUID4. - */ -function uuid4() { - var global = global_1.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; -/** - * 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 data to a given event. Uses defaults if the second parameter is not passed. - * - * @param event The event to modify. - * @param newMechanism Mechanism data to add to the event. - * @hidden - */ -function addExceptionMechanism(event, newMechanism) { - var _a; - if (!event.exception || !event.exception.values) { - return; - } - var exceptionValue0 = event.exception.values[0]; - var defaultMechanism = { type: 'generic', handled: true }; - var currentMechanism = exceptionValue0.mechanism; - exceptionValue0.mechanism = tslib_1.__assign(tslib_1.__assign(tslib_1.__assign({}, defaultMechanism), currentMechanism), newMechanism); - if (newMechanism && 'data' in newMechanism) { - var mergedData = tslib_1.__assign(tslib_1.__assign({}, (_a = currentMechanism) === null || _a === void 0 ? void 0 : _a.data), newMechanism.data); - exceptionValue0.mechanism.data = mergedData; - } -} -exports.addExceptionMechanism = addExceptionMechanism; -// 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; -/** - * Checks whether or not we've already captured the given exception (note: not an identical exception - the very object - * in question), and marks it captured if not. - * - * This is useful because it's possible for an error to get captured by more than one mechanism. After we intercept and - * record an error, we rethrow it (assuming we've intercepted it before it's reached the top-level global handlers), so - * that we don't interfere with whatever effects the error might have had were the SDK not there. At that point, because - * the error has been rethrown, it's possible for it to bubble up to some other code we've instrumented. If it's not - * caught after that, it will bubble all the way up to the global handlers (which of course we also instrument). This - * function helps us ensure that even if we encounter the same error more than once, we only record it the first time we - * see it. - * - * Note: It will ignore primitives (always return `false` and not mark them as seen), as properties can't be set on - * them. {@link: Object.objectify} can be used on exceptions to convert any that are primitives into their equivalent - * object wrapper forms so that this check will always work. However, because we need to flag the exact object which - * will get rethrown, and because that rethrowing happens outside of the event processing pipeline, the objectification - * must be done before the exception captured. - * - * @param A thrown exception to check or flag as having been seen - * @returns `true` if the exception has already been captured, `false` if not (with the side effect of marking it seen) - */ -function checkOrSetAlreadyCaught(exception) { - var _a; - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - if ((_a = exception) === null || _a === void 0 ? void 0 : _a.__sentry_captured__) { - return true; - } - try { - // set it this way rather than by assignment so that it's not ennumerable and therefore isn't recorded by the - // `ExtraErrorData` integration - Object.defineProperty(exception, '__sentry_captured__', { - value: true, - }); - } - catch (err) { - // `exception` is a primitive, so we can't mark it seen - } - return false; -} -exports.checkOrSetAlreadyCaught = checkOrSetAlreadyCaught; -//# sourceMappingURL=misc.js.map - -/***/ }), - -/***/ 16411: -/***/ ((module, exports, __nccwpck_require__) => { - -/* module decorator */ module = __nccwpck_require__.nmd(module); -/** - * NOTE: In order to avoid circular dependencies, if you add a function to this module and it needs to print something, - * you must either a) use `console.log` rather than the logger, or b) put your function elsewhere. - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -/** - * 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, @typescript-eslint/no-explicit-any -function dynamicRequire(mod, request) { - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - return mod.require(request); -} -exports.dynamicRequire = dynamicRequire; -/** - * Helper for dynamically loading module that should work with linked dependencies. - * The problem is that we _should_ be using `require(require.resolve(moduleName, { paths: [cwd()] }))` - * However it's _not possible_ to do that with Webpack, as it has to know all the dependencies during - * build time. `require.resolve` is also not available in any other way, so we cannot create, - * a fake helper like we do with `dynamicRequire`. - * - * We always prefer to use local package, thus the value is not returned early from each `try/catch` block. - * That is to mimic the behavior of `require.resolve` exactly. - * - * @param moduleName module name to require - * @returns possibly required module - */ -function loadModule(moduleName) { - var mod; - try { - mod = dynamicRequire(module, moduleName); - } - catch (e) { - // no-empty - } - try { - var cwd = dynamicRequire(module, 'process').cwd; - mod = dynamicRequire(module, cwd() + "/node_modules/" + moduleName); - } - catch (e) { - // no-empty - } - return mod; -} -exports.loadModule = loadModule; -//# 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); -/** - * Replace a method in an object with a wrapped version of itself. - * - * @param source An object that contains a method to be wrapped. - * @param name The name of the method to be wrapped. - * @param replacementFactory A higher-order function that takes the original version of the given method and returns a - * wrapped version. Note: The function returned by `replacementFactory` needs to be a non-arrow function, in order to - * preserve the correct value of `this`, and the original method must be called using `origMethod.call(this, )` or `origMethod.apply(this, [])` (rather than being called directly), again to preserve `this`. - * @returns void - */ -function fill(source, name, replacementFactory) { - if (!(name in source)) { - return; - } - var original = source[name]; - var wrapped = replacementFactory(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 its attributes - * attached to it. - * - * @param value Initial source that we have to transform in order for it 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 = {}; - // Accessing event attributes can throw (see https://github.com/getsentry/sentry-javascript/issues/768 and - // https://github.com/getsentry/sentry-javascript/issues/838), but accessing `type` hasn't been wrapped in a - // try-catch in at least two years and no one's complained, so that's likely not an issue anymore - source.type = event_1.type; - 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 attr in event_1) { - if (Object.prototype.hasOwnProperty.call(event_1, attr)) { - source[attr] = event_1[attr]; - } - } - 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]'; - } - // It's safe to use `window` and `document` here in this manner, as we are asserting using `typeof` first - // which won't throw if they are not present. - // eslint-disable-next-line no-restricted-globals - if (typeof window !== 'undefined' && value === window) { - return '[Window]'; - } - // eslint-disable-next-line no-restricted-globals - 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; - } - // 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; - } - if (includedKeys === keys.length) { - return serialized; - } - 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]); - } - } - } - 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; -/** - * Ensure that something is an object. - * - * Turns `undefined` and `null` into `String`s and all other primitives into instances of their respective wrapper - * classes (String, Boolean, Number, etc.). Acts as the identity function on non-primitives. - * - * @param wat The subject of the objectification - * @returns A version of `wat` which can safely be used with `Object` class methods - */ -function objectify(wat) { - var objectified; - switch (true) { - case wat === undefined || wat === null: - objectified = new String(wat); - break; - // Though symbols and bigints do have wrapper classes (`Symbol` and `BigInt`, respectively), for whatever reason - // those classes don't have constructors which can be used with the `new` keyword. We therefore need to cast each as - // an object in order to wrap it. - case typeof wat === 'symbol' || typeof wat === 'bigint': - objectified = Object(wat); - break; - // this will catch the remaining primitives: `String`, `Number`, and `Boolean` - case is_1.isPrimitive(wat): - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - objectified = new wat.constructor(wat); - break; - // by process of elimination, at this point we know that `wat` must already be an object - default: - objectified = wat; - break; - } - return objectified; -} -exports.objectify = objectify; -//# sourceMappingURL=object.js.map - -/***/ }), - -/***/ 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 })); -/** 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 - -/***/ }), - -/***/ 1243: -/***/ ((__unused_webpack_module, exports) => { - -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) { - if (!Object.prototype.hasOwnProperty.call(obj, prop)) { - // @ts-ignore typescript complains about indexing so we remove - obj[prop] = proto[prop]; - } - } - 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; - }; - /** - * Add a promise (representing an in-flight action) to the queue, and set it to remove itself on fulfillment. - * - * @param taskProducer A function producing any PromiseLike; In previous versions this used to be `task: - * PromiseLike`, but under that model, Promises were instantly created on the call-site and their executor - * functions therefore ran immediately. Thus, even if the buffer was full, the action still happened. By - * requiring the promise to be wrapped in a function, we can defer promise creation until after the buffer - * limit check. - * @returns The original promise. - */ - PromiseBuffer.prototype.add = function (taskProducer) { - var _this = this; - if (!this.isReady()) { - return syncpromise_1.SyncPromise.reject(new error_1.SentryError('Not adding Promise due to buffer limit reached.')); - } - // start the task and add its promise to the queue - var task = taskProducer(); - if (this._buffer.indexOf(task) === -1) { - this._buffer.push(task); - } - void task - .then(function () { return _this.remove(task); }) - // Use `then(null, rejectionHandler)` rather than `catch(rejectionHandler)` so that we can use `PromiseLike` - // rather than `Promise`. `PromiseLike` doesn't have a `.catch` method, making its polyfill smaller. (ES5 didn't - // have promises, so TS has to polyfill when down-compiling.) - .then(null, function () { - return _this.remove(task).then(null, function () { - // We have to add another catch here because `this.remove()` starts a new promise chain. - }); - }); - return task; - }; - /** - * Remove a promise from 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; - }; - /** - * Wait for all promises in the queue to resolve or for timeout to expire, whichever comes first. - * - * @param timeout The time, in ms, after which to resolve to `false` if the queue is still non-empty. Passing `0` (or - * not passing anything) will make the promise wait as long as it takes for the queue to drain before resolving to - * `true`. - * @returns A promise which will resolve to `true` if the queue is already empty or drains before the timeout, and - * `false` otherwise - */ - PromiseBuffer.prototype.drain = function (timeout) { - var _this = this; - return new syncpromise_1.SyncPromise(function (resolve) { - // wait for `timeout` ms and then resolve to `false` (if not cancelled first) - var capturedSetTimeout = setTimeout(function () { - if (timeout && timeout > 0) { - resolve(false); - } - }, timeout); - // if all promises resolve in time, cancel the timer and resolve to `true` - void 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 - -/***/ }), - -/***/ 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 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 (0 = unlimited) - * @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; -/** - * Given a string, escape characters which have meaning in the regex grammar, such that the result is safe to feed to - * `new RegExp()`. - * - * Based on https://github.com/sindresorhus/escape-string-regexp. Vendored to a) reduce the size by skipping the runtime - * type-checking, and b) ensure it gets down-compiled for old versions of Node (the published package only supports Node - * 12+). - * - * @param regexString The string to escape - * @returns An version of the string with all special regex characters escaped - */ -function escapeStringForRegex(regexString) { - // escape the hyphen separately so we can also replace it with a unicode literal hyphen, to avoid the problems - // discussed in https://github.com/sindresorhus/escape-string-regexp/issues/20. - return regexString.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&').replace(/-/g, '\\x2d'); -} -exports.escapeStringForRegex = escapeStringForRegex; -//# sourceMappingURL=string.js.map - -/***/ }), - -/***/ 88714: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -Object.defineProperty(exports, "__esModule", ({ value: true })); -var global_1 = __nccwpck_require__(68813); -var logger_1 = __nccwpck_require__(15577); -/** - * 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 global_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()); -} -exports.isNativeFetch = isNativeFetch; -/** - * 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 = global_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 global_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 = global_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 - -/***/ }), - -/***/ 87833: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -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); -/** - * 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 = "PENDING" /* PENDING */; - this._handlers = []; - /** JSDoc */ - this._resolve = function (value) { - _this._setResult("RESOLVED" /* RESOLVED */, value); - }; - /** JSDoc */ - this._reject = function (reason) { - _this._setResult("REJECTED" /* REJECTED */, reason); - }; - /** JSDoc */ - this._setResult = function (state, value) { - if (_this._state !== "PENDING" /* PENDING */) { - return; - } - if (is_1.isThenable(value)) { - void 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 === "PENDING" /* PENDING */) { - return; - } - var cachedHandlers = _this._handlers.slice(); - _this._handlers = []; - cachedHandlers.forEach(function (handler) { - if (handler.done) { - return; - } - if (_this._state === "RESOLVED" /* RESOLVED */) { - if (handler.onfulfilled) { - // eslint-disable-next-line @typescript-eslint/no-floating-promises - handler.onfulfilled(_this._value); - } - } - if (_this._state === "REJECTED" /* 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) { - void 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 - -/***/ }), - -/***/ 1735: -/***/ ((module, exports, __nccwpck_require__) => { - -/* module decorator */ module = __nccwpck_require__.nmd(module); -Object.defineProperty(exports, "__esModule", ({ value: true })); -var global_1 = __nccwpck_require__(68813); -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 = global_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 () { - // Unfortunately browsers may report an inaccurate time origin data, through either performance.timeOrigin or - // performance.timing.navigationStart, which results in poor results in performance data. We only treat time origin - // data as reliable if they are within a reasonable threshold of the current time. - var performance = global_1.getGlobalObject().performance; - if (!performance || !performance.now) { - exports._browserPerformanceTimeOriginMode = 'none'; - return undefined; - } - var threshold = 3600 * 1000; - var performanceNow = performance.now(); - var dateNow = Date.now(); - // if timeOrigin isn't available set delta to threshold so it isn't used - var timeOriginDelta = performance.timeOrigin - ? Math.abs(performance.timeOrigin + performanceNow - dateNow) - : threshold; - var timeOriginIsReliable = timeOriginDelta < threshold; - // 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 - var navigationStart = performance.timing && performance.timing.navigationStart; - var hasNavigationStart = typeof navigationStart === 'number'; - // if navigationStart isn't available set delta to threshold so it isn't used - var navigationStartDelta = hasNavigationStart ? Math.abs(navigationStart + performanceNow - dateNow) : threshold; - var navigationStartIsReliable = navigationStartDelta < threshold; - if (timeOriginIsReliable || navigationStartIsReliable) { - // Use the more reliable time origin - if (timeOriginDelta <= navigationStartDelta) { - exports._browserPerformanceTimeOriginMode = 'timeOrigin'; - return performance.timeOrigin; - } - else { - exports._browserPerformanceTimeOriginMode = 'navigationStart'; - return navigationStart; - } - } - // Either both timeOrigin and navigationStart are skewed or neither is available, fallback to Date. - exports._browserPerformanceTimeOriginMode = 'dateNow'; - return dateNow; -})(); -//# 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'); - } - - 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'); - } - } - - 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'); - } - } - - for (let i = 0; i < segments.length; ++i) { - const segment = segments[i]; - - if (!segment.length) { - return Errors.code('DOMAIN_EMPTY_SEGMENT'); - } - - if (segment.length > 63) { - return Errors.code('DOMAIN_LONG_SEGMENT'); - } - - if (i < segments.length - 1) { - if (!internals.domainSegmentRx.test(segment)) { - return Errors.code('DOMAIN_INVALID_CHARS'); - } - } - else { - if (!internals.tldSegmentRx.test(segment)) { - return Errors.code('DOMAIN_INVALID_TLDS_CHARS'); - } - } - } - - 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'); - } - - 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'); - } - - 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'); - } - } - - // 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'); - } - - 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]; - } - - 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'); - } - - versions = Array.from(new Set(versions)); - - // Regex - - const parts = versions.map((version) => { - - // Forbidden - - if (cidr === 'forbidden') { - return Uri.ip[version]; - } - - // Required - - const cidrpart = `\\/${version === 'ipv4' ? Uri.ip.v4Cidr : Uri.ip.v6Cidr}`; - - if (cidr === 'required') { - return `${Uri.ip[version]}${cidrpart}`; - } - - // 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' +function _objectWithoutPropertiesLoose(source, excluded) { + if (source == null) return {}; + var target = {}; + var sourceKeys = Object.keys(source); + var key, i; + + for (i = 0; i < sourceKeys.length; i++) { + key = sourceKeys[i]; + if (excluded.indexOf(key) >= 0) continue; + target[key] = source[key]; + } + + 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]; + } + } + + return target; +} + +function requestToOAuthBaseUrl(request) { + const endpointDefaults = request.endpoint.DEFAULTS; + return /^https:\/\/(api\.)?github\.com$/.test(endpointDefaults.baseUrl) ? "https://github.com" : endpointDefaults.baseUrl.replace("/api/v3", ""); +} +async function oauthRequest(request, route, parameters) { + const withOAuthParameters = _objectSpread2({ + baseUrl: requestToOAuthBaseUrl(request), + headers: { + accept: "application/json" + } + }, parameters); + + const response = await request(route, withOAuthParameters); + + if ("error" in response.data) { + const error = new requestError.RequestError(`${response.data.error_description} (${response.data.error}, ${response.data.error_uri})`, 400, { + request: request.endpoint.merge(route, withOAuthParameters), + headers: response.headers + }); // @ts-ignore add custom response property until https://github.com/octokit/request-error.js/issues/169 is resolved + + error.response = response; + throw error; + } + + return response; +} + +const _excluded = ["request"]; +function getWebFlowAuthorizationUrl(_ref) { + let { + request: request$1 = request.request + } = _ref, + options = _objectWithoutProperties(_ref, _excluded); + + const baseUrl = requestToOAuthBaseUrl(request$1); // @ts-expect-error TypeScript wants `clientType` to be set explicitly ¯\_(ツ)_/¯ + + return oauthAuthorizationUrl.oauthAuthorizationUrl(_objectSpread2(_objectSpread2({}, options), {}, { + baseUrl + })); +} + +async function exchangeWebFlowCode(options) { + const request$1 = options.request || + /* istanbul ignore next: we always pass a custom request in tests */ + request.request; + const response = await oauthRequest(request$1, "POST /login/oauth/access_token", { + client_id: options.clientId, + client_secret: options.clientSecret, + code: options.code, + redirect_uri: options.redirectUrl + }); + const authentication = { + clientType: options.clientType, + clientId: options.clientId, + clientSecret: options.clientSecret, + token: response.data.access_token, + scopes: response.data.scope.split(/\s+/).filter(Boolean) + }; + + if (options.clientType === "github-app") { + if ("refresh_token" in response.data) { + const apiTimeInMs = new Date(response.headers.date).getTime(); + authentication.refreshToken = response.data.refresh_token, authentication.expiresAt = toTimestamp(apiTimeInMs, response.data.expires_in), authentication.refreshTokenExpiresAt = toTimestamp(apiTimeInMs, response.data.refresh_token_expires_in); + } + + delete authentication.scopes; + } + + return _objectSpread2(_objectSpread2({}, response), {}, { + authentication + }); +} + +function toTimestamp(apiTimeInMs, expirationInSeconds) { + return new Date(apiTimeInMs + expirationInSeconds * 1000).toISOString(); +} + +async function createDeviceCode(options) { + const request$1 = options.request || + /* istanbul ignore next: we always pass a custom request in tests */ + request.request; + const parameters = { + client_id: options.clientId + }; + + if ("scopes" in options && Array.isArray(options.scopes)) { + parameters.scope = options.scopes.join(" "); + } + + return oauthRequest(request$1, "POST /login/device/code", parameters); +} + +async function exchangeDeviceCode(options) { + const request$1 = options.request || + /* istanbul ignore next: we always pass a custom request in tests */ + request.request; + const response = await oauthRequest(request$1, "POST /login/oauth/access_token", { + client_id: options.clientId, + device_code: options.code, + grant_type: "urn:ietf:params:oauth:grant-type:device_code" + }); + const authentication = { + clientType: options.clientType, + clientId: options.clientId, + token: response.data.access_token, + scopes: response.data.scope.split(/\s+/).filter(Boolean) + }; + + if ("clientSecret" in options) { + authentication.clientSecret = options.clientSecret; + } + + if (options.clientType === "github-app") { + if ("refresh_token" in response.data) { + const apiTimeInMs = new Date(response.headers.date).getTime(); + authentication.refreshToken = response.data.refresh_token, authentication.expiresAt = toTimestamp$1(apiTimeInMs, response.data.expires_in), authentication.refreshTokenExpiresAt = toTimestamp$1(apiTimeInMs, response.data.refresh_token_expires_in); + } + + delete authentication.scopes; + } + + return _objectSpread2(_objectSpread2({}, response), {}, { + authentication + }); +} + +function toTimestamp$1(apiTimeInMs, expirationInSeconds) { + return new Date(apiTimeInMs + expirationInSeconds * 1000).toISOString(); +} + +async function checkToken(options) { + const request$1 = options.request || + /* istanbul ignore next: we always pass a custom request in tests */ + request.request; + const response = await request$1("POST /applications/{client_id}/token", { + headers: { + authorization: `basic ${btoa(`${options.clientId}:${options.clientSecret}`)}` + }, + client_id: options.clientId, + access_token: options.token + }); + const authentication = { + clientType: options.clientType, + clientId: options.clientId, + clientSecret: options.clientSecret, + token: options.token, + scopes: response.data.scopes + }; + if (response.data.expires_at) authentication.expiresAt = response.data.expires_at; + + if (options.clientType === "github-app") { + delete authentication.scopes; + } + + return _objectSpread2(_objectSpread2({}, response), {}, { + authentication + }); +} + +async function refreshToken(options) { + const request$1 = options.request || + /* istanbul ignore next: we always pass a custom request in tests */ + request.request; + const response = await oauthRequest(request$1, "POST /login/oauth/access_token", { + client_id: options.clientId, + client_secret: options.clientSecret, + grant_type: "refresh_token", + refresh_token: options.refreshToken + }); + const apiTimeInMs = new Date(response.headers.date).getTime(); + const authentication = { + clientType: "github-app", + clientId: options.clientId, + clientSecret: options.clientSecret, + token: response.data.access_token, + refreshToken: response.data.refresh_token, + expiresAt: toTimestamp$2(apiTimeInMs, response.data.expires_in), + refreshTokenExpiresAt: toTimestamp$2(apiTimeInMs, response.data.refresh_token_expires_in) + }; + return _objectSpread2(_objectSpread2({}, response), {}, { + authentication + }); +} + +function toTimestamp$2(apiTimeInMs, expirationInSeconds) { + return new Date(apiTimeInMs + expirationInSeconds * 1000).toISOString(); +} + +const _excluded$1 = ["request", "clientType", "clientId", "clientSecret", "token"]; +async function scopeToken(options) { + const { + request: request$1, + clientType, + clientId, + clientSecret, + token + } = options, + requestOptions = _objectWithoutProperties(options, _excluded$1); + + const response = await (request$1 || + /* istanbul ignore next: we always pass a custom request in tests */ + request.request)("POST /applications/{client_id}/token/scoped", _objectSpread2({ + headers: { + authorization: `basic ${btoa(`${clientId}:${clientSecret}`)}` + }, + client_id: clientId, + access_token: token + }, requestOptions)); + const authentication = Object.assign({ + clientType, + clientId, + clientSecret, + token: response.data.token + }, response.data.expires_at ? { + expiresAt: response.data.expires_at + } : {}); + return _objectSpread2(_objectSpread2({}, response), {}, { + authentication + }); +} + +async function resetToken(options) { + const request$1 = options.request || + /* istanbul ignore next: we always pass a custom request in tests */ + request.request; + const auth = btoa(`${options.clientId}:${options.clientSecret}`); + const response = await request$1("PATCH /applications/{client_id}/token", { + headers: { + authorization: `basic ${auth}` + }, + client_id: options.clientId, + access_token: options.token + }); + const authentication = { + clientType: options.clientType, + clientId: options.clientId, + clientSecret: options.clientSecret, + token: response.data.token, + scopes: response.data.scopes + }; + if (response.data.expires_at) authentication.expiresAt = response.data.expires_at; + + if (options.clientType === "github-app") { + delete authentication.scopes; + } + + return _objectSpread2(_objectSpread2({}, response), {}, { + authentication + }); +} + +async function deleteToken(options) { + const request$1 = options.request || + /* istanbul ignore next: we always pass a custom request in tests */ + request.request; + const auth = btoa(`${options.clientId}:${options.clientSecret}`); + return request$1("DELETE /applications/{client_id}/token", { + headers: { + authorization: `basic ${auth}` + }, + client_id: options.clientId, + access_token: options.token + }); +} + +async function deleteAuthorization(options) { + const request$1 = options.request || + /* istanbul ignore next: we always pass a custom request in tests */ + request.request; + const auth = btoa(`${options.clientId}:${options.clientSecret}`); + return request$1("DELETE /applications/{client_id}/grant", { + headers: { + authorization: `basic ${auth}` + }, + client_id: options.clientId, + access_token: options.token + }); +} + +exports.VERSION = VERSION; +exports.checkToken = checkToken; +exports.createDeviceCode = createDeviceCode; +exports.deleteAuthorization = deleteAuthorization; +exports.deleteToken = deleteToken; +exports.exchangeDeviceCode = exchangeDeviceCode; +exports.exchangeWebFlowCode = exchangeWebFlowCode; +exports.getWebFlowAuthorizationUrl = getWebFlowAuthorizationUrl; +exports.refreshToken = refreshToken; +exports.resetToken = resetToken; +exports.scopeToken = scopeToken; +//# sourceMappingURL=index.js.map + + +/***/ }), + +/***/ 25823: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +var requestError = __nccwpck_require__(10537); + +const VERSION = "1.3.0"; + +function enterpriseCompatibility(octokit) { + octokit.hook.wrap("request", async (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.response || !error.response.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); + }); +} +enterpriseCompatibility.VERSION = VERSION; + +exports.enterpriseCompatibility = enterpriseCompatibility; +//# sourceMappingURL=index.js.map + + +/***/ }), + +/***/ 64193: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +const VERSION = "2.17.0"; + +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; +} + +/** + * 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) { + // endpoints can respond with 204 if repository is empty + if (!response.data) { + return _objectSpread2(_objectSpread2({}, response), {}, { + data: [] + }); + } + + 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; + } + + response.data.total_count = totalCount; + return response; +} + +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 + }; + + try { + 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 + + url = ((normalizedResponse.headers.link || "").match(/<([^>]+)>;\s*rel="next"/) || [])[1]; + return { + value: normalizedResponse + }; + } catch (error) { + if (error.status !== 409) throw error; + url = ""; + return { + value: { + status: 200, + headers: {}, + data: [] + } + }; + } + } + + }) + }; +} + +function paginate(octokit, route, parameters, mapFn) { + if (typeof parameters === "function") { + mapFn = parameters; + parameters = undefined; + } + + 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 done() { + earlyExit = true; + } + + results = results.concat(mapFn ? mapFn(result.value, done) : result.value.data); + + if (earlyExit) { + return results; + } + + return gather(octokit, results, iterator, mapFn); + }); +} + +const composePaginateRest = Object.assign(paginate, { + iterator +}); + +const paginatingEndpoints = ["GET /app/hook/deliveries", "GET /app/installations", "GET /applications/grants", "GET /authorizations", "GET /enterprises/{enterprise}/actions/permissions/organizations", "GET /enterprises/{enterprise}/actions/runner-groups", "GET /enterprises/{enterprise}/actions/runner-groups/{runner_group_id}/organizations", "GET /enterprises/{enterprise}/actions/runner-groups/{runner_group_id}/runners", "GET /enterprises/{enterprise}/actions/runners", "GET /enterprises/{enterprise}/actions/runners/downloads", "GET /events", "GET /gists", "GET /gists/public", "GET /gists/starred", "GET /gists/{gist_id}/comments", "GET /gists/{gist_id}/commits", "GET /gists/{gist_id}/forks", "GET /installation/repositories", "GET /issues", "GET /marketplace_listing/plans", "GET /marketplace_listing/plans/{plan_id}/accounts", "GET /marketplace_listing/stubbed/plans", "GET /marketplace_listing/stubbed/plans/{plan_id}/accounts", "GET /networks/{owner}/{repo}/events", "GET /notifications", "GET /organizations", "GET /orgs/{org}/actions/permissions/repositories", "GET /orgs/{org}/actions/runner-groups", "GET /orgs/{org}/actions/runner-groups/{runner_group_id}/repositories", "GET /orgs/{org}/actions/runner-groups/{runner_group_id}/runners", "GET /orgs/{org}/actions/runners", "GET /orgs/{org}/actions/runners/downloads", "GET /orgs/{org}/actions/secrets", "GET /orgs/{org}/actions/secrets/{secret_name}/repositories", "GET /orgs/{org}/blocks", "GET /orgs/{org}/credential-authorizations", "GET /orgs/{org}/events", "GET /orgs/{org}/failed_invitations", "GET /orgs/{org}/hooks", "GET /orgs/{org}/hooks/{hook_id}/deliveries", "GET /orgs/{org}/installations", "GET /orgs/{org}/invitations", "GET /orgs/{org}/invitations/{invitation_id}/teams", "GET /orgs/{org}/issues", "GET /orgs/{org}/members", "GET /orgs/{org}/migrations", "GET /orgs/{org}/migrations/{migration_id}/repositories", "GET /orgs/{org}/outside_collaborators", "GET /orgs/{org}/packages", "GET /orgs/{org}/projects", "GET /orgs/{org}/public_members", "GET /orgs/{org}/repos", "GET /orgs/{org}/secret-scanning/alerts", "GET /orgs/{org}/team-sync/groups", "GET /orgs/{org}/teams", "GET /orgs/{org}/teams/{team_slug}/discussions", "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments", "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions", "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions", "GET /orgs/{org}/teams/{team_slug}/invitations", "GET /orgs/{org}/teams/{team_slug}/members", "GET /orgs/{org}/teams/{team_slug}/projects", "GET /orgs/{org}/teams/{team_slug}/repos", "GET /orgs/{org}/teams/{team_slug}/team-sync/group-mappings", "GET /orgs/{org}/teams/{team_slug}/teams", "GET /projects/columns/{column_id}/cards", "GET /projects/{project_id}/collaborators", "GET /projects/{project_id}/columns", "GET /repos/{owner}/{repo}/actions/artifacts", "GET /repos/{owner}/{repo}/actions/runners", "GET /repos/{owner}/{repo}/actions/runners/downloads", "GET /repos/{owner}/{repo}/actions/runs", "GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts", "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs", "GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs", "GET /repos/{owner}/{repo}/actions/secrets", "GET /repos/{owner}/{repo}/actions/workflows", "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs", "GET /repos/{owner}/{repo}/assignees", "GET /repos/{owner}/{repo}/autolinks", "GET /repos/{owner}/{repo}/branches", "GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations", "GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs", "GET /repos/{owner}/{repo}/code-scanning/alerts", "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances", "GET /repos/{owner}/{repo}/code-scanning/analyses", "GET /repos/{owner}/{repo}/collaborators", "GET /repos/{owner}/{repo}/comments", "GET /repos/{owner}/{repo}/comments/{comment_id}/reactions", "GET /repos/{owner}/{repo}/commits", "GET /repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head", "GET /repos/{owner}/{repo}/commits/{commit_sha}/comments", "GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls", "GET /repos/{owner}/{repo}/commits/{ref}/check-runs", "GET /repos/{owner}/{repo}/commits/{ref}/check-suites", "GET /repos/{owner}/{repo}/commits/{ref}/statuses", "GET /repos/{owner}/{repo}/contributors", "GET /repos/{owner}/{repo}/deployments", "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses", "GET /repos/{owner}/{repo}/events", "GET /repos/{owner}/{repo}/forks", "GET /repos/{owner}/{repo}/git/matching-refs/{ref}", "GET /repos/{owner}/{repo}/hooks", "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries", "GET /repos/{owner}/{repo}/invitations", "GET /repos/{owner}/{repo}/issues", "GET /repos/{owner}/{repo}/issues/comments", "GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions", "GET /repos/{owner}/{repo}/issues/events", "GET /repos/{owner}/{repo}/issues/{issue_number}/comments", "GET /repos/{owner}/{repo}/issues/{issue_number}/events", "GET /repos/{owner}/{repo}/issues/{issue_number}/labels", "GET /repos/{owner}/{repo}/issues/{issue_number}/reactions", "GET /repos/{owner}/{repo}/issues/{issue_number}/timeline", "GET /repos/{owner}/{repo}/keys", "GET /repos/{owner}/{repo}/labels", "GET /repos/{owner}/{repo}/milestones", "GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels", "GET /repos/{owner}/{repo}/notifications", "GET /repos/{owner}/{repo}/pages/builds", "GET /repos/{owner}/{repo}/projects", "GET /repos/{owner}/{repo}/pulls", "GET /repos/{owner}/{repo}/pulls/comments", "GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions", "GET /repos/{owner}/{repo}/pulls/{pull_number}/comments", "GET /repos/{owner}/{repo}/pulls/{pull_number}/commits", "GET /repos/{owner}/{repo}/pulls/{pull_number}/files", "GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers", "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews", "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments", "GET /repos/{owner}/{repo}/releases", "GET /repos/{owner}/{repo}/releases/{release_id}/assets", "GET /repos/{owner}/{repo}/secret-scanning/alerts", "GET /repos/{owner}/{repo}/stargazers", "GET /repos/{owner}/{repo}/subscribers", "GET /repos/{owner}/{repo}/tags", "GET /repos/{owner}/{repo}/teams", "GET /repositories", "GET /repositories/{repository_id}/environments/{environment_name}/secrets", "GET /scim/v2/enterprises/{enterprise}/Groups", "GET /scim/v2/enterprises/{enterprise}/Users", "GET /scim/v2/organizations/{org}/Users", "GET /search/code", "GET /search/commits", "GET /search/issues", "GET /search/labels", "GET /search/repositories", "GET /search/topics", "GET /search/users", "GET /teams/{team_id}/discussions", "GET /teams/{team_id}/discussions/{discussion_number}/comments", "GET /teams/{team_id}/discussions/{discussion_number}/comments/{comment_number}/reactions", "GET /teams/{team_id}/discussions/{discussion_number}/reactions", "GET /teams/{team_id}/invitations", "GET /teams/{team_id}/members", "GET /teams/{team_id}/projects", "GET /teams/{team_id}/repos", "GET /teams/{team_id}/team-sync/group-mappings", "GET /teams/{team_id}/teams", "GET /user/blocks", "GET /user/emails", "GET /user/followers", "GET /user/following", "GET /user/gpg_keys", "GET /user/installations", "GET /user/installations/{installation_id}/repositories", "GET /user/issues", "GET /user/keys", "GET /user/marketplace_purchases", "GET /user/marketplace_purchases/stubbed", "GET /user/memberships/orgs", "GET /user/migrations", "GET /user/migrations/{migration_id}/repositories", "GET /user/orgs", "GET /user/packages", "GET /user/public_emails", "GET /user/repos", "GET /user/repository_invitations", "GET /user/starred", "GET /user/subscriptions", "GET /user/teams", "GET /users", "GET /users/{username}/events", "GET /users/{username}/events/orgs/{org}", "GET /users/{username}/events/public", "GET /users/{username}/followers", "GET /users/{username}/following", "GET /users/{username}/gists", "GET /users/{username}/gpg_keys", "GET /users/{username}/keys", "GET /users/{username}/orgs", "GET /users/{username}/packages", "GET /users/{username}/projects", "GET /users/{username}/received_events", "GET /users/{username}/received_events/public", "GET /users/{username}/repos", "GET /users/{username}/starred", "GET /users/{username}/subscriptions"]; + +function isPaginatingEndpoint(arg) { + if (typeof arg === "string") { + return paginatingEndpoints.includes(arg); + } else { + return false; + } +} + +/** + * @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; + +exports.composePaginateRest = composePaginateRest; +exports.isPaginatingEndpoint = isPaginatingEndpoint; +exports.paginateRest = paginateRest; +exports.paginatingEndpoints = paginatingEndpoints; +//# sourceMappingURL=index.js.map + + +/***/ }), + +/***/ 83044: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +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 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"] + } + }], + 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" + } + }] + }, + 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"] + } + }], + 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"] + } + }], + 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"] + } + }], + 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"] + } +}; + +const VERSION = "5.13.0"; + +function endpointsToMethods(octokit, endpointsMap) { + const newMethods = {}; + + 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); + + if (!newMethods[scope]) { + newMethods[scope] = {}; + } + + const scopeMethods = newMethods[scope]; + + if (decorations) { + scopeMethods[methodName] = decorate(octokit, scope, methodName, endpointDefaults, decorations); + continue; + } + + scopeMethods[methodName] = octokit.request.defaults(endpointDefaults); + } + } + + return newMethods; +} + +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` + + if (decorations.mapToData) { + options = Object.assign({}, options, { + data: options[decorations.mapToData], + [decorations.mapToData]: undefined + }); + return requestWithDefaults(options); + } + + if (decorations.renamed) { + const [newScope, newMethodName] = decorations.renamed; + octokit.log.warn(`octokit.${scope}.${methodName}() has been renamed to octokit.${newScope}.${newMethodName}()`); + } + + if (decorations.deprecated) { + octokit.log.warn(decorations.deprecated); + } + + 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 + }; +} +restEndpointMethods.VERSION = VERSION; +function legacyRestEndpointMethods(octokit) { + const api = endpointsToMethods(octokit, Endpoints); + return _objectSpread2(_objectSpread2({}, api), {}, { + rest: api + }); +} +legacyRestEndpointMethods.VERSION = VERSION; + +exports.legacyRestEndpointMethods = legacyRestEndpointMethods; +exports.restEndpointMethods = restEndpointMethods; +//# sourceMappingURL=index.js.map + + +/***/ }), + +/***/ 86298: +/***/ ((__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.9"; +function retry(octokit, octokitOptions) { + const state = Object.assign({ + enabled: true, + retryAfterBaseValue: 1000, + doNotRetry: [400, 401, 403, 404, 422], + retries: 3 + }, octokitOptions.retry); + + if (state.enabled) { + octokit.hook.error("request", errorRequest.bind(null, octokit, state)); + octokit.hook.wrap("request", wrapRequest.bind(null, state)); + } + + return { + retry: { + retryRequest: (error, retries, retryAfter) => { + error.request.request = Object.assign({}, error.request.request, { + retries: retries, + retryAfter: retryAfter + }); + return error; + } + } + }; +} +retry.VERSION = VERSION; + +exports.VERSION = VERSION; +exports.retry = retry; +//# sourceMappingURL=index.js.map + + +/***/ }), + +/***/ 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 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 VERSION = "3.5.2"; + +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 { + pathname + } = new URL(options.url, "http://github.test"); + const isSearch = options.method === "GET" && pathname.startsWith("/search/"); + const isGraphQL = pathname.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(pathname)) { + 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"), { + response: res, + data: res.data + }); + throw error; + } + } + + return req; +} + +var triggersNotificationPaths = ["/orgs/{org}/invitations", "/orgs/{org}/invitations/{invitation_id}", "/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 // @ts-ignore + + } = 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 { + pathname + } = new URL(options.url, "http://github.test"); + const shouldRetryGraphQL = pathname.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 (/\bsecondary rate\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.response.headers["retry-after"], state.minimumAbuseRetryAfter); + const wantRetry = await emitter.trigger("abuse-limit", retryAfter, options, octokit); + return { + wantRetry, + retryAfter + }; + } + + if (error.response.headers != null && error.response.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.response.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)); + return {}; +} +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 logOnceCode = once(deprecation => console.warn(deprecation)); +const logOnceHeaders = 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; + let headers; + + if ("headers" in options && typeof options.headers !== "undefined") { + headers = options.headers; + } + + if ("response" in options) { + this.response = options.response; + headers = options.response.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; // deprecations + + Object.defineProperty(this, "code", { + get() { + logOnceCode(new deprecation.Deprecation("[@octokit/request-error] `error.code` is deprecated, use `error.status`.")); + return statusCode; + } + + }); + Object.defineProperty(this, "headers", { + get() { + logOnceHeaders(new deprecation.Deprecation("[@octokit/request-error] `error.headers` is deprecated, use `error.response.headers`.")); + return headers || {}; + } + + }); + } + +} + +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__(80467)); +var requestError = __nccwpck_require__(10537); + +const VERSION = "5.6.2"; + +function getBufferResponse(response) { + return response.arrayBuffer(); +} + +function fetchWrapper(requestOptions) { + const log = requestOptions.request && requestOptions.request.log ? requestOptions.request.log : console; + + 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.agent` type is incompatible + // see https://github.com/octokit/types.ts/pull/264 + requestOptions.request)).then(async response => { + url = response.url; + status = response.status; + + for (const keyAndValue of response.headers) { + headers[keyAndValue[0]] = keyAndValue[1]; + } + + if ("deprecation" in headers) { + const matches = headers.link && headers.link.match(/<([^>]+)>; rel="deprecation"/); + const deprecationLink = matches && matches.pop(); + log.warn(`[@octokit/request] "${requestOptions.method} ${requestOptions.url}" is deprecated. It is scheduled to be removed on ${headers.sunset}${deprecationLink ? `. See ${deprecationLink}` : ""}`); + } + + 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, { + response: { + url, + status, + headers, + data: undefined + }, + request: requestOptions + }); + } + + if (status === 304) { + throw new requestError.RequestError("Not modified", status, { + response: { + url, + status, + headers, + data: await getResponseData(response) + }, + request: requestOptions + }); + } + + if (status >= 400) { + const data = await getResponseData(response); + const error = new requestError.RequestError(toErrorMessage(data), status, { + response: { + url, + status, + headers, + data + }, + request: requestOptions + }); + throw error; + } + + return getResponseData(response); + }).then(data => { + return { + status, + url, + headers, + data + }; + }).catch(error => { + if (error instanceof requestError.RequestError) throw error; + throw new requestError.RequestError(error.message, 500, { + request: requestOptions + }); + }); +} + +async function getResponseData(response) { + 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); +} + +function toErrorMessage(data) { + if (typeof data === "string") return data; // istanbul ignore else - just in case + + if ("message" in data) { + if (Array.isArray(data.errors)) { + return `${data.message}: ${data.errors.map(JSON.stringify).join(", ")}`; + } + + return data.message; + } // istanbul ignore next - just in case + + + return `Unknown error: ${JSON.stringify(data)}`; +} + +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 + + +/***/ }), + +/***/ 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])); + } + }); + }); +} + +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__(58930); +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); + }); +} + + +/***/ }), + +/***/ 96645: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +const { inspect } = __nccwpck_require__(73837); + +const through = __nccwpck_require__(18180); +const core = __nccwpck_require__(42186); +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"; + +const begin = "-----BEGIN RSA PRIVATE KEY-----"; +const end = "-----END RSA PRIVATE KEY-----"; +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(); + } + + if (privateKey.includes(begin) && privateKey.includes(end)) { + // newlines are escaped + if (privateKey.indexOf("\\n") !== -1) { + privateKey = privateKey.replace(/\\n/g, "\n"); + } // newlines are missing + + + if (privateKey.indexOf("\n") === -1) { + privateKey = addNewlines(privateKey); + } + + return privateKey; + } + + 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; +} + +function addNewlines(privateKey) { + const middleLength = privateKey.length - begin.length - end.length - 2; + const middle = privateKey.substr(begin.length + 1, middleLength); + return `${begin}\n${middle.trim().replace(/\s+/g, "\n")}\n${end}`; +} + +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.1.5"; + +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 endpoint = _objectSpread2({ + method: "GET", + url: "/repos/{owner}/{repo}/contents/{path}", + owner, + repo, + path, + mediaType: { + format: "raw" + } + }, ref ? { + ref + } : {}); + + const { + url + } = await octokit.request.endpoint(endpoint); + const emptyConfigResult = { + owner, + repo, + path, + url, + config: null + }; + + try { + const { + data, + headers + } = await octokit.request(endpoint); // 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] ${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 ${url} (invalid JSON)`); + } + + return _objectSpread2(_objectSpread2({}, emptyConfigResult), {}, { + config: data + }); + } + + const config = yaml.load(data) || {}; + + if (typeof config === "string") { + throw new Error(`[@probot/octokit-plugin-config] Configuration could not be parsed from ${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 ${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 + }); + const files = [requestedRepoFile]; // if no configuration file present in selected repository, + // try to load it from the `.github` repository + + if (!requestedRepoFile.config) { + if (repo === ".github") { + return files; + } + + const defaultRepoConfig = await getConfigFile(octokit, { + owner, + repo: ".github", + path + }); + files.push(defaultRepoConfig); + } + + const file = files[files.length - 1]; // if the configuration has no `_extends` key, we are done here. + + if (!file.config || !file.config._extends) { + return files; + } // parse the value of `_extends` into request parameters to + // retrieve the new configuration file + + + let extendConfigOptions = extendsToGetContentParams({ + owner, + path, + url: file.url, + extendsValue: file.config._extends + }); // remove the `_extends` key from the configuration that is returned + + delete file.config._extends; // 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__(67362); +const Sentry = __nccwpck_require__(22783); + +const LEVEL_MAP = { + 10: "trace", + 20: "debug", + 30: "info", + 40: "warn", + 50: "error", + 60: "fatal", +}; + +/** + * 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; + 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", "sentryEventId"].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) { + if (formattingEnabled) { + return cb(null, pretty(line)); + } + + if (levelAsString) { + return cb(null, stringifyLogLevel(JSON.parse(line))); + } + + cb(null, line + "\n"); + return; + } + + 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, + }); + } + + const sentryEventId = Sentry.captureException(toSentryError(data)); + + // reduce logging data and add reference to sentry event instead + if (data.event) { + data.event = { id: data.event.id }; + } + if (data.request) { + data.request = { + method: data.request.method, + url: data.request.url, + }; + } + data.sentryEventId = sentryEventId; + + if (formattingEnabled) { + return cb(null, pretty(data)); + } + + // istanbul ignore if + if (levelAsString) { + return cb(null, stringifyLogLevel(data)); + } + + cb(null, JSON.stringify(data) + "\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, headers and metadata that can be used to form + * different types of requests to Sentry endpoints. + * Supports both envelopes and regular event requests. + **/ +var API = /** @class */ (function () { + /** Create a new instance of API */ + function API(dsn, metadata, tunnel) { + if (metadata === void 0) { metadata = {}; } + this.dsn = dsn; + this._dsnObject = new utils_1.Dsn(dsn); + this.metadata = metadata; + this._tunnel = tunnel; + } + /** Returns the Dsn object. */ + API.prototype.getDsn = function () { + return this._dsnObject; + }; + /** Does this transport force envelopes? */ + API.prototype.forceEnvelope = function () { + return !!this._tunnel; + }; + /** Returns the prefix to construct Sentry ingestion API endpoints. */ + API.prototype.getBaseApiEndpoint = function () { + var dsn = this.getDsn(); + 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 () { + if (this.forceEnvelope()) { + return this._tunnel; + } + return this._getEnvelopeEndpoint() + "?" + this._encodedAuth(); + }; + /** Returns only the path component for the store endpoint. */ + API.prototype.getStoreEndpointPath = function () { + var dsn = this.getDsn(); + 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) { + // CHANGE THIS to use metadata but keep clientName and clientVersion compatible + var dsn = this.getDsn(); + var header = ["Sentry sentry_version=" + SENTRY_API_VERSION]; + header.push("sentry_client=" + clientName + "/" + clientVersion); + header.push("sentry_key=" + dsn.publicKey); + 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.getDsn(); + 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) { + if (this._tunnel) { + return this._tunnel; + } + var base = this.getBaseApiEndpoint(); + var dsn = this.getDsn(); + 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.getDsn(); + var auth = { + // We send only the minimum set of required information. See + // https://github.com/getsentry/sentry-javascript/issues/2572. + sentry_key: dsn.publicKey, + 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) { + void 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; + } + void 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); +var ALREADY_SEEN_ERROR = "Not capturing exception because it's already been captured."; +/** + * 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 calls being processed */ + this._numProcessing = 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; + // ensure we haven't captured this very object before + if (utils_1.checkOrSetAlreadyCaught(exception)) { + utils_1.logger.log(ALREADY_SEEN_ERROR); + return; + } + 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 _a; + // ensure we haven't captured this very object before + if (((_a = hint) === null || _a === void 0 ? void 0 : _a.originalException) && utils_1.checkOrSetAlreadyCaught(hint.originalException)) { + utils_1.logger.log(ALREADY_SEEN_ERROR); + return; + } + 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 (!this._isEnabled()) { + utils_1.logger.warn('SDK not enabled, will not capture session.'); + return; + } + if (!(typeof session.release === 'string')) { + utils_1.logger.warn('Discarded session because of missing or non-string release'); + } + else { + this._sendSession(session); + // After sending, we set init false to indicate it's not the first occurrence + session.update({ init: false }); + } + }; + /** + * @inheritDoc + */ + BaseClient.prototype.getDsn = function () { + return this._dsn; + }; + /** + * @inheritDoc + */ + BaseClient.prototype.getOptions = function () { + return this._options; + }; + /** + * @inheritDoc + */ + BaseClient.prototype.getTransport = function () { + return this._getBackend().getTransport(); + }; + /** + * @inheritDoc + */ + BaseClient.prototype.flush = function (timeout) { + var _this = this; + return this._isClientDoneProcessing(timeout).then(function (clientFinished) { + return _this.getTransport() + .close(timeout) + .then(function (transportFlushed) { return clientFinished && 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.initialized) { + 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 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; } + } + } + // A session is updated and that session update is sent in only one of the two following scenarios: + // 1. Session with non terminal status and 0 errors + an error occurred -> Will set error count to 1 and send update + // 2. Session with non terminal status and 1 error + a crash occurred -> Will set status crashed and send update + var sessionNonTerminal = session.status === types_1.SessionStatus.Ok; + var shouldUpdateAndSend = (sessionNonTerminal && session.errors === 0) || (sessionNonTerminal && crashed); + if (shouldUpdateAndSend) { + session.update(tslib_1.__assign(tslib_1.__assign({}, (crashed && { status: types_1.SessionStatus.Crashed })), { errors: session.errors || Number(errored || crashed) })); + this.captureSession(session); + } + }; + /** Deliver captured session to Sentry */ + BaseClient.prototype._sendSession = function (session) { + this._getBackend().sendSession(session); + }; + /** + * Determine if the client is finished processing. Returns a promise because it will wait `timeout` ms before saying + * "no" (resolving to `false`) in order to give the client a chance to potentially finish first. + * + * @param timeout The time, in ms, after which to resolve to `false` if the client is still busy. Passing `0` (or not + * passing anything) will make the promise wait as long as it takes for processing to finish before resolving to + * `true`. + * @returns A promise which will resolve to `true` if processing is already done or finishes before the timeout, and + * `false` otherwise + */ + BaseClient.prototype._isClientDoneProcessing = function (timeout) { + var _this = this; + return new utils_1.SyncPromise(function (resolve) { + var ticked = 0; + var tick = 1; + var interval = setInterval(function () { + if (_this._numProcessing == 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; + } + var _a = this.getOptions()._experiments, _experiments = _a === void 0 ? {} : _a; + if (_experiments.ensureNoCircularStructures) { + return utils_1.normalize(normalized); + } + 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 event The event that will be filled with all integrations. + */ + BaseClient.prototype._applyIntegrationsMetadata = function (event) { + var integrationsArray = Object.keys(this._integrations); + if (integrationsArray.length > 0) { + event.sdk = event.sdk || {}; + event.sdk.integrations = tslib_1.__spread((event.sdk.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; + var _a, _b; + // eslint-disable-next-line @typescript-eslint/unbound-method + var _c = this.getOptions(), beforeSend = _c.beforeSend, sampleRate = _c.sampleRate; + var transport = this.getTransport(); + if (!this._isEnabled()) { + return utils_1.SyncPromise.reject(new utils_1.SentryError('SDK not enabled, will not capture 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) { + (_b = (_a = transport).recordLostEvent) === null || _b === void 0 ? void 0 : _b.call(_a, types_1.Outcome.SampleRate, 'event'); + return utils_1.SyncPromise.reject(new utils_1.SentryError("Discarding event because it's not included in the random sample (sampling rate = " + sampleRate + ")")); + } + return this._prepareEvent(event, scope, hint) + .then(function (prepared) { + var _a, _b; + if (prepared === null) { + (_b = (_a = transport).recordLostEvent) === null || _b === void 0 ? void 0 : _b.call(_a, types_1.Outcome.EventProcessor, event.type || 'event'); + 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); + return _this._ensureBeforeSendRv(beforeSendResult); + }) + .then(function (processedEvent) { + var _a, _b; + if (processedEvent === null) { + (_b = (_a = transport).recordLostEvent) === null || _b === void 0 ? void 0 : _b.call(_a, types_1.Outcome.BeforeSend, event.type || 'event'); + 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._numProcessing += 1; + void promise.then(function (value) { + _this._numProcessing -= 1; + return value; + }, function (reason) { + _this._numProcessing -= 1; + return reason; + }); + }; + /** + * Verifies that return value of configured `beforeSend` is of expected type. + */ + BaseClient.prototype._ensureBeforeSendRv = function (rv) { + var nullErr = '`beforeSend` method has to return `null` or a valid event.'; + if (utils_1.isThenable(rv)) { + return rv.then(function (event) { + if (!(utils_1.isPlainObject(event) || event === null)) { + throw new utils_1.SentryError(nullErr); + } + return event; + }, function (e) { + throw new utils_1.SentryError("beforeSend rejected with " + e); + }); + } + else if (!(utils_1.isPlainObject(rv) || rv === null)) { + throw new utils_1.SentryError(nullErr); + } + return rv; + }; + 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 version_1 = __nccwpck_require__(33493); +exports.SDK_VERSION = version_1.SDK_VERSION; +var Integrations = __nccwpck_require__(96727); +exports.Integrations = Integrations; +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 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 = []; +/** + * @private + */ +function filterDuplicates(integrations) { + return integrations.reduce(function (acc, integrations) { + if (acc.every(function (accIntegration) { return integrations.name !== accIntegration.name; })) { + acc.push(integrations); + } + return acc; + }, []); +} +/** Gets integration to install */ +function getIntegrationsToSetup(options) { + var defaultIntegrations = (options.defaultIntegrations && tslib_1.__spread(options.defaultIntegrations)) || []; + var userIntegrations = options.integrations; + var integrations = tslib_1.__spread(filterDuplicates(defaultIntegrations)); + if (Array.isArray(userIntegrations)) { + // Filter out integrations that are also included in user options + integrations = tslib_1.__spread(integrations.filter(function (integrations) { + return userIntegrations.every(function (userIntegration) { return userIntegration.name !== integrations.name; }); + }), filterDuplicates(userIntegrations)); + } + else if (typeof userIntegrations === 'function') { + integrations = userIntegrations(integrations); + integrations = Array.isArray(integrations) ? integrations : [integrations]; + } + // 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); + }); + // set the `initialized` flag so we don't run through the process again unecessarily; use `Object.defineProperty` + // because by default it creates a property which is nonenumerable, which we want since `initialized` shouldn't be + // considered a member of the index the way the actual integrations are + Object.defineProperty(integrations, 'initialized', { value: true }); + 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() : {}; + // This checks prevents most of the occurrences of the bug linked below: + // https://github.com/getsentry/sentry-javascript/issues/2622 + // The bug is caused by multiple SDK instances, where one is minified and one is using non-mangled code. + // Unfortunatelly we cannot fix it reliably (thus reserved property in rollup's terser config), + // as we cannot force people using multiple instances in their apps to sync SDK versions. + var options = typeof self._mergeOptions === 'function' ? self._mergeOptions(clientOptions) : {}; + if (typeof self._shouldDropEvent !== 'function') { + return event; + } + return self._shouldDropEvent(event, options) ? null : event; + } + 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._getLastValidUrl = function (frames) { + if (frames === void 0) { frames = []; } + var _a, _b; + for (var i = frames.length - 1; i >= 0; i--) { + var frame = frames[i]; + if (((_a = frame) === null || _a === void 0 ? void 0 : _a.filename) !== '' && ((_b = frame) === null || _b === void 0 ? void 0 : _b.filename) !== '[native code]') { + return frame.filename || null; + } + } + return null; + }; + /** JSDoc */ + InboundFilters.prototype._getEventFilterUrl = function (event) { + try { + if (event.stacktrace) { + var frames_1 = event.stacktrace.frames; + return this._getLastValidUrl(frames_1); + } + if (event.exception) { + var frames_2 = event.exception.values && event.exception.values[0].stacktrace && event.exception.values[0].stacktrace.frames; + return this._getLastValidUrl(frames_2); + } + 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); +/** Extract sdk info from from the API metadata */ +function getSdkMetadataForEnvelopeHeader(api) { + if (!api.metadata || !api.metadata.sdk) { + return; + } + var _a = api.metadata.sdk, name = _a.name, version = _a.version; + return { name: name, version: version }; +} +/** + * Apply SdkInfo (name, version, packages, integrations) to the corresponding event key. + * Merge with existing data if any. + **/ +function enhanceEventWithSdkInfo(event, sdkInfo) { + if (!sdkInfo) { + return event; + } + event.sdk = event.sdk || {}; + event.sdk.name = event.sdk.name || sdkInfo.name; + event.sdk.version = event.sdk.version || sdkInfo.version; + event.sdk.integrations = tslib_1.__spread((event.sdk.integrations || []), (sdkInfo.integrations || [])); + event.sdk.packages = tslib_1.__spread((event.sdk.packages || []), (sdkInfo.packages || [])); + return event; +} +/** Creates a SentryRequest from a Session. */ +function sessionToSentryRequest(session, api) { + var sdkInfo = getSdkMetadataForEnvelopeHeader(api); + var envelopeHeaders = JSON.stringify(tslib_1.__assign(tslib_1.__assign({ sent_at: new Date().toISOString() }, (sdkInfo && { sdk: sdkInfo })), (api.forceEnvelope() && { dsn: api.getDsn().toString() }))); + // I know this is hacky but we don't want to add `session` to request type since it's never rate limited + var type = 'aggregates' in session ? 'sessions' : 'session'; + var itemHeaders = JSON.stringify({ + type: type, + }); + return { + body: envelopeHeaders + "\n" + itemHeaders + "\n" + JSON.stringify(session), + type: type, + url: api.getEnvelopeEndpointWithUrlEncodedAuth(), + }; +} +exports.sessionToSentryRequest = sessionToSentryRequest; +/** Creates a SentryRequest from an event. */ +function eventToSentryRequest(event, api) { + var sdkInfo = getSdkMetadataForEnvelopeHeader(api); + var eventType = event.type || 'event'; + var useEnvelope = eventType === 'transaction' || api.forceEnvelope(); + var _a = event.debug_meta || {}, transactionSampling = _a.transactionSampling, metadata = tslib_1.__rest(_a, ["transactionSampling"]); + var _b = transactionSampling || {}, samplingMethod = _b.method, sampleRate = _b.rate; + if (Object.keys(metadata).length === 0) { + delete event.debug_meta; + } + else { + event.debug_meta = metadata; + } + var req = { + body: JSON.stringify(sdkInfo ? enhanceEventWithSdkInfo(event, api.metadata.sdk) : event), + type: eventType, + 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(tslib_1.__assign(tslib_1.__assign({ event_id: event.event_id, sent_at: new Date().toISOString() }, (sdkInfo && { sdk: sdkInfo })), (api.forceEnvelope() && { dsn: api.getDsn().toString() }))); + var itemHeaders = JSON.stringify({ + type: eventType, + // 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 + +/***/ }), + +/***/ 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); +/** + * 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) { + var _a; + if (options.debug === true) { + utils_1.logger.enable(); + } + var hub = hub_1.getCurrentHub(); + (_a = hub.getScope()) === null || _a === void 0 ? void 0 : _a.update(options.initialScope); + var client = new clientClass(options); + hub.bindClient(client); +} +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 + +/***/ }), + +/***/ 33493: +/***/ ((__unused_webpack_module, exports) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SDK_VERSION = '6.16.1'; +//# sourceMappingURL=version.js.map + +/***/ }), + +/***/ 53536: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __nccwpck_require__(4351); +/* eslint-disable max-lines */ +var types_1 = __nccwpck_require__(83789); +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 = 4; +/** + * Default maximum number of breadcrumbs added to an event. Can be overwritten + * with {@link Options.maxBreadcrumbs}. + */ +var DEFAULT_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; + if (client) { + 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, mimic 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, mimic 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 = utils_1.uuid4(); + if (event.type !== 'transaction') { + this._lastEventId = eventId; + } + 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, maxBreadcrumbs); + }; + /** + * @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.captureSession = function (endSession) { + if (endSession === void 0) { endSession = false; } + // both send the update and pull the session from the scope + if (endSession) { + return this.endSession(); + } + // only send the update + this._sendSessionUpdate(); + }; + /** + * @inheritDoc + */ + Hub.prototype.endSession = function () { + var _a, _b, _c, _d, _e; + (_c = (_b = (_a = this.getStackTop()) === null || _a === void 0 ? void 0 : _a.scope) === null || _b === void 0 ? void 0 : _b.getSession()) === null || _c === void 0 ? void 0 : _c.close(); + this._sendSessionUpdate(); + // the session is over; take it off of the scope + (_e = (_d = this.getStackTop()) === null || _d === void 0 ? void 0 : _d.scope) === null || _e === void 0 ? void 0 : _e.setSession(); + }; + /** + * @inheritDoc + */ + Hub.prototype.startSession = function (context) { + var _a = this.getStackTop(), scope = _a.scope, client = _a.client; + var _b = (client && client.getOptions()) || {}, release = _b.release, environment = _b.environment; + // Will fetch userAgent if called from browser sdk + var global = utils_1.getGlobalObject(); + var userAgent = (global.navigator || {}).userAgent; + var session = new session_1.Session(tslib_1.__assign(tslib_1.__assign(tslib_1.__assign({ release: release, + environment: environment }, (scope && { user: scope.getUser() })), (userAgent && { userAgent: userAgent })), context)); + if (scope) { + // End existing session if there's one + var currentSession = scope.getSession && scope.getSession(); + if (currentSession && currentSession.status === types_1.SessionStatus.Ok) { + currentSession.update({ status: types_1.SessionStatus.Exited }); + } + this.endSession(); + // Afterwards we set the new session on the scope + scope.setSession(session); + } + return session; + }; + /** + * Sends the current Session on the scope + */ + Hub.prototype._sendSessionUpdate = function () { + var _a = this.getStackTop(), scope = _a.scope, client = _a.client; + if (!scope) + return; + var session = scope.getSession && scope.getSession(); + if (session) { + if (client && client.captureSession) { + client.captureSession(session); + } + } + }; + /** + * 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. + * + * FIXME: This function is problematic, because despite always returning a valid Carrier, + * it has an optional `__SENTRY__` property, which then in turn requires us to always perform an unnecessary check + * at the call-site. We always access the carrier through this function, so we can guarantee that `__SENTRY__` is there. + **/ +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 + * @deprecated No longer used; remove in v7 + * @returns The domain, or undefined if there is no active domain + */ +// eslint-disable-next-line deprecation/deprecation +function getActiveDomain() { + utils_1.logger.warn('Function `getActiveDomain` is deprecated and will be removed in a future version.'); + 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) { + var _a, _b, _c; + try { + var activeDomain = (_c = (_b = (_a = getMainCarrier().__SENTRY__) === null || _a === void 0 ? void 0 : _a.extensions) === null || _b === void 0 ? void 0 : _b.domain) === null || _c === void 0 ? void 0 : _c.active; + // 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); + } + 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 + * @returns A boolean indicating success or failure + */ +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 + +/***/ }), + +/***/ 6393: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +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 sessionflusher_1 = __nccwpck_require__(99695); +exports.SessionFlusher = sessionflusher_1.SessionFlusher; +var hub_1 = __nccwpck_require__(53536); +// eslint-disable-next-line deprecation/deprecation +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: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __nccwpck_require__(4351); +var utils_1 = __nccwpck_require__(1620); +/** + * Absolute maximum number of breadcrumbs added to an event. + * The `maxBreadcrumbs` option cannot be higher than this value. + */ +var MAX_BREADCRUMBS = 100; +/** + * 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 notifying 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 = {}; + } + /** + * 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); + newScope._requestSession = scope._requestSession; + } + 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.getRequestSession = function () { + return this._requestSession; + }; + /** + * @inheritDoc + */ + Scope.prototype.setRequestSession = function (requestSession) { + this._requestSession = requestSession; + return this; + }; + /** + * @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; + } + if (captureContext._requestSession) { + this._requestSession = captureContext._requestSession; + } + } + 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; + } + if (captureContext.requestSession) { + this._requestSession = captureContext.requestSession; + } + } + 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._requestSession = undefined; + this._span = undefined; + this._session = undefined; + this._notifyScopeListeners(); + return this; + }; + /** + * @inheritDoc + */ + Scope.prototype.addBreadcrumb = function (breadcrumb, maxBreadcrumbs) { + var maxCrumbs = typeof maxBreadcrumbs === 'number' ? Math.min(maxBreadcrumbs, MAX_BREADCRUMBS) : MAX_BREADCRUMBS; + // No data has been changed, so don't notify scope listeners + if (maxCrumbs <= 0) { + return this; + } + var mergedBreadcrumb = tslib_1.__assign({ timestamp: utils_1.dateTimestampInSeconds() }, breadcrumb); + this._breadcrumbs = tslib_1.__spread(this._breadcrumbs, [mergedBreadcrumb]).slice(-maxCrumbs); + 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 information 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 relies 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)) { + void result + .then(function (final) { return _this._notifyEventProcessors(processors, final, hint, index + 1).then(resolve); }) + .then(null, reject); + } + else { + void _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; +/** + * Returns 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 */ +} +/** + * Add a EventProcessor to be kept globally. + * @param callback EventProcessor to add + */ +function addGlobalEventProcessor(callback) { + getGlobalEventProcessors().push(callback); +} +exports.addGlobalEventProcessor = addGlobalEventProcessor; +//# sourceMappingURL=scope.js.map + +/***/ }), + +/***/ 12474: +/***/ ((__unused_webpack_module, 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.duration = 0; + this.status = types_1.SessionStatus.Ok; + this.init = true; + this.ignoreDuration = false; + // Both timestamp and started are in seconds since the UNIX epoch. + var startingTime = utils_1.timestampInSeconds(); + this.timestamp = startingTime; + this.started = startingTime; + 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 (!this.ipAddress && context.user.ip_address) { + this.ipAddress = context.user.ip_address; + } + if (!this.did && !context.did) { + this.did = context.user.id || context.user.email || context.user.username; + } + } + this.timestamp = context.timestamp || utils_1.timestampInSeconds(); + if (context.ignoreDuration) { + this.ignoreDuration = context.ignoreDuration; + } + if (context.sid) { + // Good enough uuid validation. — Kamil + this.sid = context.sid.length === 32 ? context.sid : utils_1.uuid4(); + } + if (context.init !== undefined) { + this.init = context.init; + } + if (!this.did && context.did) { + this.did = "" + context.did; + } + if (typeof context.started === 'number') { + this.started = context.started; + } + if (this.ignoreDuration) { + this.duration = undefined; + } + else if (typeof context.duration === 'number') { + this.duration = context.duration; + } + else { + var duration = this.timestamp - this.started; + this.duration = duration >= 0 ? duration : 0; + } + if (context.release) { + this.release = context.release; + } + if (context.environment) { + this.environment = context.environment; + } + if (!this.ipAddress && context.ipAddress) { + this.ipAddress = context.ipAddress; + } + if (!this.userAgent && 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: this.init, + // Make sure that sec is converted to ms for date constructor + started: new Date(this.started * 1000).toISOString(), + timestamp: new Date(this.timestamp * 1000).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 + +/***/ }), + +/***/ 99695: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); +var types_1 = __nccwpck_require__(83789); +var utils_1 = __nccwpck_require__(1620); +var hub_1 = __nccwpck_require__(53536); +/** + * @inheritdoc + */ +var SessionFlusher = /** @class */ (function () { + function SessionFlusher(transport, attrs) { + var _this = this; + this.flushTimeout = 60; + this._pendingAggregates = {}; + this._isEnabled = true; + this._transport = transport; + // Call to setInterval, so that flush is called every 60 seconds + this._intervalId = setInterval(function () { return _this.flush(); }, this.flushTimeout * 1000); + this._sessionAttrs = attrs; + } + /** Sends session aggregates to Transport */ + SessionFlusher.prototype.sendSessionAggregates = function (sessionAggregates) { + if (!this._transport.sendSession) { + utils_1.logger.warn("Dropping session because custom transport doesn't implement sendSession"); + return; + } + void this._transport.sendSession(sessionAggregates).then(null, function (reason) { + utils_1.logger.error("Error while sending session: " + reason); + }); + }; + /** Checks if `pendingAggregates` has entries, and if it does flushes them by calling `sendSessions` */ + SessionFlusher.prototype.flush = function () { + var sessionAggregates = this.getSessionAggregates(); + if (sessionAggregates.aggregates.length === 0) { + return; + } + this._pendingAggregates = {}; + this.sendSessionAggregates(sessionAggregates); + }; + /** Massages the entries in `pendingAggregates` and returns aggregated sessions */ + SessionFlusher.prototype.getSessionAggregates = function () { + var _this = this; + var aggregates = Object.keys(this._pendingAggregates).map(function (key) { + return _this._pendingAggregates[parseInt(key)]; + }); + var sessionAggregates = { + attrs: this._sessionAttrs, + aggregates: aggregates, + }; + return utils_1.dropUndefinedKeys(sessionAggregates); + }; + /** JSDoc */ + SessionFlusher.prototype.close = function () { + clearInterval(this._intervalId); + this._isEnabled = false; + this.flush(); + }; + /** + * Wrapper function for _incrementSessionStatusCount that checks if the instance of SessionFlusher is enabled then + * fetches the session status of the request from `Scope.getRequestSession().status` on the scope and passes them to + * `_incrementSessionStatusCount` along with the start date + */ + SessionFlusher.prototype.incrementSessionStatusCount = function () { + var _a, _b; + if (!this._isEnabled) { + return; + } + var scope = hub_1.getCurrentHub().getScope(); + var requestSession = (_a = scope) === null || _a === void 0 ? void 0 : _a.getRequestSession(); + if (requestSession && requestSession.status) { + this._incrementSessionStatusCount(requestSession.status, new Date()); + // This is not entirely necessarily but is added as a safe guard to indicate the bounds of a request and so in + // case captureRequestSession is called more than once to prevent double count + (_b = scope) === null || _b === void 0 ? void 0 : _b.setRequestSession(undefined); + /* eslint-enable @typescript-eslint/no-unsafe-member-access */ + } + }; + /** + * Increments status bucket in pendingAggregates buffer (internal state) corresponding to status of + * the session received + */ + SessionFlusher.prototype._incrementSessionStatusCount = function (status, date) { + // Truncate minutes and seconds on Session Started attribute to have one minute bucket keys + var sessionStartedTrunc = new Date(date).setSeconds(0, 0); + this._pendingAggregates[sessionStartedTrunc] = this._pendingAggregates[sessionStartedTrunc] || {}; + // corresponds to aggregated sessions in one specific minute bucket + // for example, {"started":"2021-03-16T08:00:00.000Z","exited":4, "errored": 1} + var aggregationCounts = this._pendingAggregates[sessionStartedTrunc]; + if (!aggregationCounts.started) { + aggregationCounts.started = new Date(sessionStartedTrunc).toISOString(); + } + switch (status) { + case types_1.RequestSessionStatus.Errored: + aggregationCounts.errored = (aggregationCounts.errored || 0) + 1; + return aggregationCounts.errored; + case types_1.RequestSessionStatus.Ok: + aggregationCounts.exited = (aggregationCounts.exited || 0) + 1; + return aggregationCounts.exited; + case types_1.RequestSessionStatus.Crashed: + aggregationCounts.crashed = (aggregationCounts.crashed || 0) + 1; + return aggregationCounts.crashed; + } + }; + return SessionFlusher; +}()); +exports.SessionFlusher = SessionFlusher; +//# sourceMappingURL=sessionflusher.js.map + +/***/ }), + +/***/ 88455: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +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. + */ +// 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."); +} +/** + * 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'); + } + catch (exception) { + syntheticException = exception; + } + 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); + } + catch (exception) { + syntheticException = exception; + } + // 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); +} +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]; + } + callOnHub.apply(void 0, tslib_1.__spread(['_invokeClient', method], args)); +} +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 + +/***/ }), + +/***/ 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 providedMechanism = hint && hint.data && hint.data.mechanism; + var mechanism = providedMechanism || { + 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) : []; + void 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, tunnel: this._options.tunnel, _metadata: this._options._metadata }); + 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 + +/***/ }), + +/***/ 86147: +/***/ ((__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 hub_1 = __nccwpck_require__(6393); +var types_1 = __nccwpck_require__(83789); +var utils_1 = __nccwpck_require__(1620); +var backend_1 = __nccwpck_require__(40508); +/** + * 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) { + var _this = this; + options._metadata = options._metadata || {}; + options._metadata.sdk = options._metadata.sdk || { + name: 'sentry.javascript.node', + packages: [ + { + name: 'npm:@sentry/node', + version: core_1.SDK_VERSION, + }, + ], + version: core_1.SDK_VERSION, + }; + _this = _super.call(this, backend_1.NodeBackend, options) || this; + return _this; + } + /** + * @inheritDoc + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types + NodeClient.prototype.captureException = function (exception, hint, scope) { + // Check if the flag `autoSessionTracking` is enabled, and if `_sessionFlusher` exists because it is initialised only + // when the `requestHandler` middleware is used, and hence the expectation is to have SessionAggregates payload + // sent to the Server only when the `requestHandler` middleware is used + if (this._options.autoSessionTracking && this._sessionFlusher && scope) { + var requestSession = scope.getRequestSession(); + // Necessary checks to ensure this is code block is executed only within a request + // Should override the status only if `requestSession.status` is `Ok`, which is its initial stage + if (requestSession && requestSession.status === types_1.RequestSessionStatus.Ok) { + requestSession.status = types_1.RequestSessionStatus.Errored; + } + } + return _super.prototype.captureException.call(this, exception, hint, scope); + }; + /** + * @inheritDoc + */ + NodeClient.prototype.captureEvent = function (event, hint, scope) { + // Check if the flag `autoSessionTracking` is enabled, and if `_sessionFlusher` exists because it is initialised only + // when the `requestHandler` middleware is used, and hence the expectation is to have SessionAggregates payload + // sent to the Server only when the `requestHandler` middleware is used + if (this._options.autoSessionTracking && this._sessionFlusher && scope) { + var eventType = event.type || 'exception'; + var isException = eventType === 'exception' && event.exception && event.exception.values && event.exception.values.length > 0; + // If the event is of type Exception, then a request session should be captured + if (isException) { + var requestSession = scope.getRequestSession(); + // Ensure that this is happening within the bounds of a request, and make sure not to override + // Session Status if Errored / Crashed + if (requestSession && requestSession.status === types_1.RequestSessionStatus.Ok) { + requestSession.status = types_1.RequestSessionStatus.Errored; + } + } + } + return _super.prototype.captureEvent.call(this, event, hint, scope); + }; + /** + * + * @inheritdoc + */ + NodeClient.prototype.close = function (timeout) { + var _a; + (_a = this._sessionFlusher) === null || _a === void 0 ? void 0 : _a.close(); + return _super.prototype.close.call(this, timeout); + }; + /** Method that initialises an instance of SessionFlusher on Client */ + NodeClient.prototype.initSessionFlusher = function () { + var _a = this._options, release = _a.release, environment = _a.environment; + if (!release) { + utils_1.logger.warn('Cannot initialise an instance of SessionFlusher if no release is provided!'); + } + else { + this._sessionFlusher = new hub_1.SessionFlusher(this.getTransport(), { + release: release, + environment: environment, + }); + } + }; + /** + * @inheritDoc + */ + NodeClient.prototype._prepareEvent = function (event, scope, hint) { + event.platform = event.platform || 'node'; + if (this.getOptions().serverName) { + event.server_name = this.getOptions().serverName; + } + return _super.prototype._prepareEvent.call(this, event, scope, hint); + }; + /** + * Method responsible for capturing/ending a request session by calling `incrementSessionStatusCount` to increment + * appropriate session aggregates bucket + */ + NodeClient.prototype._captureRequestSession = function () { + if (!this._sessionFlusher) { + utils_1.logger.warn('Discarded request mode session because autoSessionTracking option was disabled'); + } + else { + this._sessionFlusher.incrementSessionStatusCount(); + } + }; + return NodeClient; +}(core_1.BaseClient)); +exports.NodeClient = NodeClient; +//# sourceMappingURL=client.js.map + +/***/ }), + +/***/ 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 types_1 = __nccwpck_require__(83789); +var utils_1 = __nccwpck_require__(1620); +var cookie = __nccwpck_require__(93658); +var domain = __nccwpck_require__(13639); +var os = __nccwpck_require__(22037); +var url = __nccwpck_require__(57310); +var sdk_1 = __nccwpck_require__(38836); +/** + * 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), + // extra context passed to the tracesSampler + { request: extractRequestData(req) }); + // 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; +/** + * Set parameterized as transaction name e.g.: `GET /users/:id` + * Also adds more context data on the transaction from the request + */ +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); +} +/** + * 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) + * + * @returns The fully constructed transaction name + */ +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) { + 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; +} +/** 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 extractRequestData(req, keys) { + if (keys === void 0) { keys = DEFAULT_REQUEST_KEYS; } + var requestData = {}; + // headers: + // node, express, nextjs: req.headers + // koa: req.header + var headers = (req.headers || req.header || {}); + // method: + // node, express, koa, nextjs: req.method + var method = req.method; + // host: + // express: req.hostname in > 4 and req.host in < 4 + // koa: req.host + // node, nextjs: req.headers.host + var host = req.hostname || req.host || headers.host || ''; + // protocol: + // node, nextjs: + // 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, nextjs: 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), nextjs: req.cookies + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + requestData.cookies = req.cookies || cookie.parse(headers.cookie || ''); + break; + case 'query_string': + // query string: + // node: req.url (raw) + // express, koa, nextjs: req.query + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + requestData.query_string = req.query || url.parse(originalUrl || '', false).query; + break; + case 'data': + if (method === 'GET' || method === 'HEAD') { + break; + } + // body data: + // express, koa, nextjs: req.body + // + // when using node by itself, you have to read the incoming stream(see + // https://nodejs.dev/learn/get-http-request-body-data-using-nodejs); if a user is doing that, we can't know + // where they're going to store the final result, so they'll have to capture this data themselves + if (req.body !== undefined) { + requestData.data = utils_1.isString(req.body) ? req.body : JSON.stringify(utils_1.normalize(req.body)); + } + break; + default: + if ({}.hasOwnProperty.call(req, key)) { + requestData[key] = req[key]; + } + } + }); + return requestData; +} +exports.extractRequestData = extractRequestData; +/** + * 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 `extractRequestData()` + var extractedRequestData = Array.isArray(options.request) + ? extractRequestData(req, options.request) + : extractRequestData(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, nextjs: 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) { + // TODO do we even need this anymore? + // TODO make this work for nextjs + event.transaction = extractTransaction(req, options.transaction); + } + return event; +} +exports.parseRequest = parseRequest; +/** + * Express compatible request handler. + * @see Exposed as `Handlers.requestHandler` + */ +function requestHandler(options) { + var currentHub = core_1.getCurrentHub(); + var client = currentHub.getClient(); + // Initialise an instance of SessionFlusher on the client when `autoSessionTracking` is enabled and the + // `requestHandler` middleware is used indicating that we are running in SessionAggregates mode + if (client && sdk_1.isAutoSessionTrackingEnabled(client)) { + client.initSessionFlusher(); + // If Scope contains a Single mode Session, it is removed in favor of using Session Aggregates mode + var scope = currentHub.getScope(); + if (scope && scope.getSession()) { + scope.setSession(); + } + } + 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; + void 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 () { + var currentHub = core_1.getCurrentHub(); + currentHub.configureScope(function (scope) { + scope.addEventProcessor(function (event) { return parseRequest(event, req, options); }); + var client = currentHub.getClient(); + if (sdk_1.isAutoSessionTrackingEnabled(client)) { + var scope_1 = currentHub.getScope(); + if (scope_1) { + // Set `status` of `RequestSession` to Ok, at the beginning of the request + scope_1.setRequestSession({ status: types_1.RequestSessionStatus.Ok }); + } + } + }); + res.once('finish', function () { + var client = currentHub.getClient(); + if (sdk_1.isAutoSessionTrackingEnabled(client)) { + setImmediate(function () { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + if (client && client._captureRequestSession) { + // Calling _captureRequestSession to capture request session at the end of the request by incrementing + // the correct SessionAggregates bucket i.e. crashed, errored or exited + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + client._captureRequestSession(); + } + }); + } + }); + 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; +} +/** + * Express compatible error handler. + * @see Exposed as `Handlers.errorHandler` + */ +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 client = core_1.getCurrentHub().getClient(); + if (client && sdk_1.isAutoSessionTrackingEnabled(client)) { + // Check if the `SessionFlusher` is instantiated on the client to go into this branch that marks the + // `requestSession.status` as `Crashed`, and this check is necessary because the `SessionFlusher` is only + // instantiated when the the`requestHandler` middleware is initialised, which indicates that we should be + // running in SessionAggregates mode + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + var isSessionAggregatesMode = client._sessionFlusher !== undefined; + if (isSessionAggregatesMode) { + var requestSession = _scope.getRequestSession(); + // If an error bubbles to the `errorHandler`, then this is an unhandled error, and should be reported as a + // Crashed session. The `_requestSession.status` is checked to ensure that this error is happening within + // the bounds of a request, and if so the status is updated + if (requestSession && requestSession.status !== undefined) + requestSession.status = types_1.RequestSessionStatus.Crashed; + } + } + 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; +//# sourceMappingURL=handlers.js.map + +/***/ }), + +/***/ 22783: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +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.SDK_VERSION = core_1.SDK_VERSION; +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; +exports.getSentryRelease = sdk_1.getSentryRelease; +var utils_1 = __nccwpck_require__(27937); +exports.deepReadDirSync = utils_1.deepReadDirSync; +var version_1 = __nccwpck_require__(31271); +exports.SDK_NAME = version_1.SDK_NAME; +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 + +/***/ }), + +/***/ 29552: +/***/ ((__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 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; + 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(console, 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; + } + /* eslint-disable prefer-rest-params */ + 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); + }; + /* eslint-enable prefer-rest-params */ + }; +} +//# sourceMappingURL=console.js.map + +/***/ }), + +/***/ 76280: +/***/ ((__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 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); + // eslint-disable-next-line @typescript-eslint/no-var-requires + 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) { + // eslint-disable-next-line @typescript-eslint/no-var-requires + 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(this, 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: 'http.client', + }); + var sentryTraceHeader = span.toTraceparent(); + utils_1.logger.log("[Tracing] Adding sentry-trace header " + sentryTraceHeader + " to outgoing request to " + requestUrl + ": "); + 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 + +/***/ }), + +/***/ 72310: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +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 + +/***/ }), + +/***/ 70208: +/***/ ((__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 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) { + void _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) { + void parsers_1.getExceptionFromError(error[key]) + .then(function (exception) { + void _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 + +/***/ }), + +/***/ 90046: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +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 paths */ +function getPaths() { + try { + return require.cache ? Object.keys(require.cache) : []; + } + catch (e) { + return []; + } +} +/** Extract information about package.json modules */ +function collectModules() { + var mainPaths = (require.main && require.main.paths) || []; + var paths = getPaths(); + 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 + +/***/ }), + +/***/ 50443: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +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 errorhandling_1 = __nccwpck_require__(5635); +/** 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 = errorhandling_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, + data: { mechanism: { handled: false, type: 'onuncaughtexception' } }, + }); + 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'); + errorhandling_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__) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); +var core_1 = __nccwpck_require__(79212); +var utils_1 = __nccwpck_require__(1620); +var errorhandling_1 = __nccwpck_require__(5635); +/** 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, + data: { mechanism: { handled: false, type: 'onunhandledrejection' } }, + }); + }); + /* 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); + }); + errorhandling_1.logAndExitProcess(reason); + } + /* eslint-enable no-console */ + }; + /** + * @inheritDoc + */ + OnUnhandledRejection.id = 'OnUnhandledRejection'; + return OnUnhandledRejection; +}()); +exports.OnUnhandledRejection = OnUnhandledRejection; +//# sourceMappingURL=onunhandledrejection.js.map + +/***/ }), + +/***/ 5635: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); +var core_1 = __nccwpck_require__(79212); +var utils_1 = __nccwpck_require__(1620); +var DEFAULT_SHUTDOWN_TIMEOUT = 2000; +/** + * @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=errorhandling.js.map + +/***/ }), + +/***/ 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 utils_1 = __nccwpck_require__(1620); +var url_1 = __nccwpck_require__(57310); +var NODE_VERSION = utils_1.parseSemver(process.versions.node); +/** + * 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; +} +exports.isSentryRequest = isSentryRequest; +/** + * Assemble a URL to be used for breadcrumbs and spans. + * + * @param requestOptions RequestOptions object containing the component parts for a URL + * @returns Fully-formed URL + */ +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; +/** + * 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 + * + * @returns The cleaned description + */ +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; +} +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. + * + * See https://github.com/nodejs/node/blob/master/lib/internal/url.js. + */ +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; +/** + * 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. + * + * @returns Equivalent args of the form [ RequestOptions ] or [ RequestOptions, RequestCallback ]. + */ +function normalizeRequestArgs(httpModule, requestArgs) { + var _a, _b, _c, _d, _e, _f, _g, _h; + 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]); + } + // Figure out the protocol if it's currently missing + if (requestOptions.protocol === undefined) { + // Worst case we end up populating protocol with undefined, which it already is + /* eslint-disable @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any */ + // NOTE: Prior to Node 9, `https` used internals of `http` module, thus we don't patch it. + // Because of that, we cannot rely on `httpModule` to provide us with valid protocol, + // as it will always return `http`, even when using `https` module. + // + // See test/integrations/http.test.ts for more details on Node <=v8 protocol issue. + if (NODE_VERSION.major && NODE_VERSION.major > 8) { + requestOptions.protocol = + ((_b = (_a = httpModule) === null || _a === void 0 ? void 0 : _a.globalAgent) === null || _b === void 0 ? void 0 : _b.protocol) || ((_c = requestOptions.agent) === null || _c === void 0 ? void 0 : _c.protocol) || ((_d = requestOptions._defaultAgent) === null || _d === void 0 ? void 0 : _d.protocol); + } + else { + requestOptions.protocol = + ((_e = requestOptions.agent) === null || _e === void 0 ? void 0 : _e.protocol) || ((_f = requestOptions._defaultAgent) === null || _f === void 0 ? void 0 : _f.protocol) || ((_h = (_g = httpModule) === null || _g === void 0 ? void 0 : _g.globalAgent) === null || _h === void 0 ? void 0 : _h.protocol); + } + /* eslint-enable @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any */ + } + // return args in standardized form + if (callback) { + return [requestOptions, callback]; + } + else { + return [requestOptions]; + } +} +exports.normalizeRequestArgs = normalizeRequestArgs; +//# sourceMappingURL=http.js.map + +/***/ }), + +/***/ 19090: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +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(); +} +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; + } + // 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); + } + }); +} +/** + * @hidden + */ +function extractStackFromError(error) { + var stack = stacktrace.parse(error); + if (!stack) { + return []; + } + return stack; +} +exports.extractStackFromError = extractStackFromError; +/** + * @hidden + */ +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 _a; + var parsedFrame = { + colno: frame.columnNumber, + filename: ((_a = frame.fileName) === null || _a === void 0 ? void 0 : _a.startsWith('file://')) ? frame.fileName.substr(7) : 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; +/** + * 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 + */ +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); + }); + }); +} +/** + * @hidden + */ +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); + }); + }); +} +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; +/** + * @hidden + */ +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 + +/***/ }), + +/***/ 38836: +/***/ ((__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 hub_1 = __nccwpck_require__(6393); +var types_1 = __nccwpck_require__(83789); +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 = {}; } + var _a; + var carrier = hub_1.getMainCarrier(); + var autoloadedIntegrations = ((_a = carrier.__SENTRY__) === null || _a === void 0 ? void 0 : _a.integrations) || []; + options.defaultIntegrations = + options.defaultIntegrations === false + ? [] + : tslib_1.__spread((Array.isArray(options.defaultIntegrations) ? options.defaultIntegrations : exports.defaultIntegrations), autoloadedIntegrations); + if (options.dsn === undefined && process.env.SENTRY_DSN) { + options.dsn = process.env.SENTRY_DSN; + } + if (options.tracesSampleRate === undefined && process.env.SENTRY_TRACES_SAMPLE_RATE) { + var tracesSampleRate = parseFloat(process.env.SENTRY_TRACES_SAMPLE_RATE); + if (isFinite(tracesSampleRate)) { + options.tracesSampleRate = tracesSampleRate; + } + } + if (options.release === undefined) { + var detectedRelease = getSentryRelease(); + if (detectedRelease !== undefined) { + options.release = detectedRelease; + } + else { + // If release is not provided, then we should disable autoSessionTracking + options.autoSessionTracking = false; + } + } + if (options.environment === undefined && process.env.SENTRY_ENVIRONMENT) { + options.environment = process.env.SENTRY_ENVIRONMENT; + } + if (options.autoSessionTracking === undefined && options.dsn !== undefined) { + options.autoSessionTracking = true; + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any + if (domain.active) { + hub_1.setHubOnCarrier(carrier, core_1.getCurrentHub()); + } + core_1.initAndBind(client_1.NodeClient, options); + if (options.autoSessionTracking) { + startSessionTracking(); + } +} +exports.init = init; +/** + * This is the getter for lastEventId. + * + * @returns The last event id of a captured event. + */ +function lastEventId() { + return core_1.getCurrentHub().lastEventId(); +} +exports.lastEventId = lastEventId; +/** + * Call `flush()` on the current client, if there is one. See {@link Client.flush}. + * + * @param timeout Maximum time in ms the client should wait to flush its event queue. Omitting this parameter will cause + * the client to wait until all events are sent before resolving the promise. + * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it + * doesn't (or if there's no client defined). + */ +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)]; + } + utils_1.logger.warn('Cannot flush events. No client defined.'); + return [2 /*return*/, Promise.resolve(false)]; + }); + }); +} +exports.flush = flush; +/** + * Call `close()` on the current client, if there is one. See {@link Client.close}. + * + * @param timeout Maximum time in ms the client should wait to flush its event queue before shutting down. Omitting this + * parameter will cause the client to wait until all events are sent before disabling itself. + * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it + * doesn't (or if there's no client defined). + */ +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)]; + } + utils_1.logger.warn('Cannot flush events and disable SDK. No client defined.'); + return [2 /*return*/, Promise.resolve(false)]; + }); + }); +} +exports.close = close; +/** + * Function that takes an instance of NodeClient and checks if autoSessionTracking option is enabled for that client + */ +function isAutoSessionTrackingEnabled(client) { + if (client === undefined) { + return false; + } + var clientOptions = client && client.getOptions(); + if (clientOptions && clientOptions.autoSessionTracking !== undefined) { + return clientOptions.autoSessionTracking; + } + return false; +} +exports.isAutoSessionTrackingEnabled = isAutoSessionTrackingEnabled; +/** + * Returns a release dynamically from environment variables. + */ +function getSentryRelease(fallback) { + // Always read first as Sentry takes this as precedence + if (process.env.SENTRY_RELEASE) { + return process.env.SENTRY_RELEASE; + } + // This supports the variable that sentry-webpack-plugin injects + var global = utils_1.getGlobalObject(); + if (global.SENTRY_RELEASE && global.SENTRY_RELEASE.id) { + return global.SENTRY_RELEASE.id; + } + return ( + // GitHub Actions - https://help.github.com/en/actions/configuring-and-managing-workflows/using-environment-variables#default-environment-variables + process.env.GITHUB_SHA || + // Netlify - https://docs.netlify.com/configure-builds/environment-variables/#build-metadata + process.env.COMMIT_REF || + // Vercel - https://vercel.com/docs/v2/build-step#system-environment-variables + process.env.VERCEL_GIT_COMMIT_SHA || + process.env.VERCEL_GITHUB_COMMIT_SHA || + process.env.VERCEL_GITLAB_COMMIT_SHA || + process.env.VERCEL_BITBUCKET_COMMIT_SHA || + // Zeit (now known as Vercel) + process.env.ZEIT_GITHUB_COMMIT_SHA || + process.env.ZEIT_GITLAB_COMMIT_SHA || + process.env.ZEIT_BITBUCKET_COMMIT_SHA || + fallback); +} +exports.getSentryRelease = getSentryRelease; +/** + * Enable automatic Session Tracking for the node process. + */ +function startSessionTracking() { + var hub = core_1.getCurrentHub(); + hub.startSession(); + // Emitted in the case of healthy sessions, error of `mechanism.handled: true` and unhandledrejections because + // The 'beforeExit' event is not emitted for conditions causing explicit termination, + // such as calling process.exit() or uncaught exceptions. + // Ref: https://nodejs.org/api/process.html#process_event_beforeexit + process.on('beforeExit', function () { + var _a; + var session = (_a = hub.getScope()) === null || _a === void 0 ? void 0 : _a.getSession(); + var terminalStates = [types_1.SessionStatus.Exited, types_1.SessionStatus.Crashed]; + // Only call endSession, if the Session exists on Scope and SessionStatus is not a + // Terminal Status i.e. Exited or Crashed because + // "When a session is moved away from ok it must not be updated anymore." + // Ref: https://develop.sentry.dev/sdk/sessions/ + if (session && !terminalStates.includes(session.status)) + hub.endSession(); + }); +} +//# sourceMappingURL=sdk.js.map + +/***/ }), + +/***/ 46276: +/***/ ((__unused_webpack_module, exports) => { + +/** + * 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 + * + * https://github.com/felixge/node-stack-trace/ + * @license MIT + */ +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 + +/***/ }), + +/***/ 41194: +/***/ ((__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 fs = __nccwpck_require__(57147); +var url_1 = __nccwpck_require__(57310); +var version_1 = __nccwpck_require__(31271); +var CATEGORY_MAPPING = { + event: 'error', + transaction: 'transaction', + session: 'session', + attachment: 'attachment', +}; +/** 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 rate limits in a response */ + this._rateLimits = {}; + /** Default function used to parse URLs */ + this.urlParser = function (url) { return new url_1.URL(url); }; + this._api = new core_1.API(options.dsn, options._metadata, options.tunnel); + } + /** + * @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); + }; + /** + * Extracts proxy settings from client options and env variables. + * + * Honors `no_proxy` env variable with the highest priority to allow for hosts exclusion. + * + * An order of priority for available protocols is: + * `http` => `options.httpProxy` | `process.env.http_proxy` + * `https` => `options.httpsProxy` | `options.httpProxy` | `process.env.https_proxy` | `process.env.http_proxy` + */ + BaseTransport.prototype._getProxy = function (protocol) { + var e_1, _a; + var _b = process.env, no_proxy = _b.no_proxy, http_proxy = _b.http_proxy, https_proxy = _b.https_proxy; + var _c = this.options, httpProxy = _c.httpProxy, httpsProxy = _c.httpsProxy; + var proxy = protocol === 'http' ? httpProxy || http_proxy : httpsProxy || httpProxy || https_proxy || http_proxy; + if (!no_proxy) { + return proxy; + } + var _d = this._api.getDsn(), host = _d.host, port = _d.port; + try { + for (var _e = tslib_1.__values(no_proxy.split(',')), _f = _e.next(); !_f.done; _f = _e.next()) { + var np = _f.value; + if (host.endsWith(np) || (host + ":" + port).endsWith(np)) { + return; + } + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (_f && !_f.done && (_a = _e.return)) _a.call(_e); + } + finally { if (e_1) throw e_1.error; } + } + return proxy; + }; + /** Returns a build request option object used by request */ + BaseTransport.prototype._getRequestOptions = function (urlParts) { + var headers = tslib_1.__assign(tslib_1.__assign({}, this._api.getRequestHeaders(version_1.SDK_NAME, core_1.SDK_VERSION)), this.options.headers); + var hostname = urlParts.hostname, pathname = urlParts.pathname, port = urlParts.port, protocol = urlParts.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), + })); + }; + /** + * Gets the time that given category is disabled until for rate limiting + */ + BaseTransport.prototype._disabledUntil = function (requestType) { + var category = CATEGORY_MAPPING[requestType]; + return this._rateLimits[category] || this._rateLimits.all; + }; + /** + * Checks if a category is rate limited + */ + BaseTransport.prototype._isRateLimited = function (requestType) { + return this._disabledUntil(requestType) > new Date(Date.now()); + }; + /** + * Sets internal _rateLimits from incoming headers. Returns true if headers contains a non-empty rate limiting header. + */ + BaseTransport.prototype._handleRateLimit = function (headers) { + var e_2, _a, e_3, _b; + var now = Date.now(); + var rlHeader = headers['x-sentry-rate-limits']; + var raHeader = headers['retry-after']; + if (rlHeader) { + try { + // rate limit headers are of the form + //
,
,.. + // where each
is of the form + // : : : + // where + // is a delay in ms + // is the event type(s) (error, transaction, etc) being rate limited and is of the form + // ;;... + // is what's being limited (org, project, or key) - ignored by SDK + // is an arbitrary string like "org_quota" - ignored by SDK + for (var _c = tslib_1.__values(rlHeader.trim().split(',')), _d = _c.next(); !_d.done; _d = _c.next()) { + var limit = _d.value; + var parameters = limit.split(':', 2); + var headerDelay = parseInt(parameters[0], 10); + var delay = (!isNaN(headerDelay) ? headerDelay : 60) * 1000; // 60sec default + try { + for (var _e = (e_3 = void 0, tslib_1.__values((parameters[1] && parameters[1].split(';')) || ['all'])), _f = _e.next(); !_f.done; _f = _e.next()) { + var category = _f.value; + // categoriesAllowed is added here to ensure we are only storing rate limits for categories we support in this + // sdk and any categories that are not supported will not be added redundantly to the rateLimits object + var categoriesAllowed = tslib_1.__spread(Object.keys(CATEGORY_MAPPING).map(function (k) { return CATEGORY_MAPPING[k]; }), [ + 'all', + ]); + if (categoriesAllowed.includes(category)) + this._rateLimits[category] = new Date(now + delay); + } + } + catch (e_3_1) { e_3 = { error: e_3_1 }; } + finally { + try { + if (_f && !_f.done && (_b = _e.return)) _b.call(_e); + } + finally { if (e_3) throw e_3.error; } + } + } + } + catch (e_2_1) { e_2 = { error: e_2_1 }; } + finally { + try { + if (_d && !_d.done && (_a = _c.return)) _a.call(_c); + } + finally { if (e_2) throw e_2.error; } + } + return true; + } + else if (raHeader) { + this._rateLimits.all = new Date(now + utils_1.parseRetryAfterHeader(now, raHeader)); + return true; + } + return false; + }; + /** JSDoc */ + BaseTransport.prototype._send = function (sentryRequest, originalPayload) { + return tslib_1.__awaiter(this, void 0, void 0, function () { + var _this = this; + return tslib_1.__generator(this, function (_a) { + if (!this.module) { + throw new utils_1.SentryError('No module available'); + } + if (originalPayload && this._isRateLimited(sentryRequest.type)) { + return [2 /*return*/, Promise.reject({ + payload: originalPayload, + type: sentryRequest.type, + reason: "Transport for " + sentryRequest.type + " requests locked till " + this._disabledUntil(sentryRequest.type) + " due to too many requests.", + status: 429, + })]; + } + return [2 /*return*/, this._buffer.add(function () { + return new Promise(function (resolve, reject) { + if (!_this.module) { + throw new utils_1.SentryError('No module available'); + } + var options = _this._getRequestOptions(_this.urlParser(sentryRequest.url)); + var req = _this.module.request(options, function (res) { + var statusCode = res.statusCode || 500; + var status = types_1.Status.fromHttpCode(statusCode); + res.setEncoding('utf8'); + /** + * "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); + var rlHeader = res.headers ? res.headers['x-sentry-rate-limits'] : ''; + rlHeader = (Array.isArray(rlHeader) ? rlHeader[0] : rlHeader); + var headers = { + 'x-sentry-rate-limits': rlHeader, + 'retry-after': retryAfterHeader, + }; + var limited = _this._handleRateLimit(headers); + if (limited) + utils_1.logger.warn("Too many " + sentryRequest.type + " requests, backing off until: " + _this._disabledUntil(sentryRequest.type)); + if (status === types_1.Status.Success) { + resolve({ status: status }); + } + else { + 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(sentryRequest.body); + }); + })]; + }); + }); + }; + return BaseTransport; +}()); +exports.BaseTransport = BaseTransport; +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 84490: +/***/ ((__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 http = __nccwpck_require__(13685); +var base_1 = __nccwpck_require__(41194); +/** 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 = _this._getProxy('http'); + _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) { + return this._send(core_1.eventToSentryRequest(event, this._api), event); + }; + /** + * @inheritDoc + */ + HTTPTransport.prototype.sendSession = function (session) { + return this._send(core_1.sessionToSentryRequest(session, this._api), session); + }; + return HTTPTransport; +}(base_1.BaseTransport)); +exports.HTTPTransport = HTTPTransport; +//# sourceMappingURL=http.js.map + +/***/ }), + +/***/ 68621: +/***/ ((__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 https = __nccwpck_require__(95687); +var base_1 = __nccwpck_require__(41194); +/** 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 = _this._getProxy('https'); + _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) { + return this._send(core_1.eventToSentryRequest(event, this._api), event); + }; + /** + * @inheritDoc + */ + HTTPSTransport.prototype.sendSession = function (session) { + return this._send(core_1.sessionToSentryRequest(session, this._api), session); + }; + return HTTPSTransport; +}(base_1.BaseTransport)); +exports.HTTPSTransport = HTTPSTransport; +//# sourceMappingURL=https.js.map + +/***/ }), + +/***/ 21437: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); +var base_1 = __nccwpck_require__(41194); +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 + +/***/ }), + +/***/ 27937: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __nccwpck_require__(4351); +var fs = __nccwpck_require__(57147); +var path = __nccwpck_require__(71017); +/** + * Recursively read the contents of a directory. + * + * @param targetDir Absolute or relative path of the directory to scan. All returned paths will be relative to this + * directory. + * @returns Array holding all relative paths + */ +function deepReadDirSync(targetDir) { + var targetDirAbsPath = path.resolve(targetDir); + if (!fs.existsSync(targetDirAbsPath)) { + throw new Error("Cannot read contents of " + targetDirAbsPath + ". Directory does not exist."); + } + if (!fs.statSync(targetDirAbsPath).isDirectory()) { + throw new Error("Cannot read contents of " + targetDirAbsPath + ", because it is not a directory."); + } + // This does the same thing as its containing function, `deepReadDirSync` (except that - purely for convenience - it + // deals in absolute paths rather than relative ones). We need this to be separate from the outer function to preserve + // the difference between `targetDirAbsPath` and `currentDirAbsPath`. + var deepReadCurrentDir = function (currentDirAbsPath) { + return fs.readdirSync(currentDirAbsPath).reduce(function (absPaths, itemName) { + var itemAbsPath = path.join(currentDirAbsPath, itemName); + if (fs.statSync(itemAbsPath).isDirectory()) { + return tslib_1.__spread(absPaths, deepReadCurrentDir(itemAbsPath)); + } + return tslib_1.__spread(absPaths, [itemAbsPath]); + }, []); + }; + return deepReadCurrentDir(targetDirAbsPath).map(function (absPath) { return path.relative(targetDirAbsPath, absPath); }); +} +exports.deepReadDirSync = deepReadDirSync; +//# sourceMappingURL=utils.js.map + +/***/ }), + +/***/ 31271: +/***/ ((__unused_webpack_module, exports) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); +// TODO: Remove in the next major release and rely only on @sentry/core SDK_VERSION and SdkMetadata +exports.SDK_NAME = 'sentry.javascript.node'; +//# sourceMappingURL=version.js.map + +/***/ }), + +/***/ 81867: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); +var utils_1 = __nccwpck_require__(1620); +var constants_1 = __nccwpck_require__(4740); +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.setTag(constants_1.FINISH_REASON_TAG, constants_1.IDLE_TRANSACTION_FINISH_REASONS[2]); + 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 + +/***/ }), + +/***/ 33577: +/***/ ((__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 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.instrumentRoutingWithDefaults, 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._emitOptionsWarning = false; + /** Store configured idle timeout so that it can be added as a tag to transactions */ + this._configuredIdleTimeout = undefined; + var tracingOrigins = request_1.defaultRequestInstrumentationOptions.tracingOrigins; + // NOTE: Logger doesn't work in constructors, as it's initialized after integrations instances + if (_options) { + this._configuredIdleTimeout = _options.idleTimeout; + if (_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 }); + var _metricOptions = this.options._metricOptions; + this._metrics = new metrics_1.MetricsInstrumentation(_metricOptions && _metricOptions._reportAllChanges); + } + /** + * @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, instrumentRouting = _a.routingInstrumentation, startTransactionOnLocationChange = _a.startTransactionOnLocationChange, startTransactionOnPageLoad = _a.startTransactionOnPageLoad, markBackgroundTransactions = _a.markBackgroundTransactions, traceFetch = _a.traceFetch, traceXHR = _a.traceXHR, tracingOrigins = _a.tracingOrigins, shouldCreateSpanForRequest = _a.shouldCreateSpanForRequest; + instrumentRouting(function (context) { return _this._createRouteTransaction(context); }, startTransactionOnPageLoad, startTransactionOnLocationChange); + if (markBackgroundTransactions) { + backgroundtab_1.registerBackgroundTabDetection(); + } + request_1.instrumentOutgoingRequests({ 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."); + } + utils_1.logger.log("[Tracing] Starting " + finalContext.op + " transaction on scope"); + var hub = this._getCurrentHub(); + var location = utils_1.getGlobalObject().location; + var idleTransaction = hubextensions_1.startIdleTransaction(hub, finalContext, idleTimeout, true, { location: location }); + idleTransaction.registerBeforeFinishCallback(function (transaction, endTimestamp) { + _this._metrics.addPerformanceEntries(transaction); + adjustTransactionDuration(utils_2.secToMs(maxTransactionDuration), transaction, endTimestamp); + }); + idleTransaction.setTag('idleTimeout', this._configuredIdleTimeout); + 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 = utils_1.getGlobalObject().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 + +/***/ }), + +/***/ 71425: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); +var browsertracing_1 = __nccwpck_require__(33577); +exports.BrowserTracing = browsertracing_1.BrowserTracing; +var request_1 = __nccwpck_require__(27854); +exports.instrumentOutgoingRequests = request_1.instrumentOutgoingRequests; +exports.defaultRequestInstrumentationOptions = request_1.defaultRequestInstrumentationOptions; +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 68451: +/***/ ((__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 utils_2 = __nccwpck_require__(31386); +var getCLS_1 = __nccwpck_require__(56982); +var getFID_1 = __nccwpck_require__(82496); +var getLCP_1 = __nccwpck_require__(99382); +var getVisibilityWatcher_1 = __nccwpck_require__(10522); +var global = utils_1.getGlobalObject(); +/** Class tracking metrics */ +var MetricsInstrumentation = /** @class */ (function () { + function MetricsInstrumentation(_reportAllChanges) { + if (_reportAllChanges === void 0) { _reportAllChanges = false; } + var _a, _b; + this._reportAllChanges = _reportAllChanges; + this._measurements = {}; + this._performanceCursor = 0; + if (!utils_1.isNodeEnv() && ((_a = global) === null || _a === void 0 ? void 0 : _a.performance) && ((_b = global) === null || _b === void 0 ? void 0 : _b.document)) { + if (global.performance.mark) { + global.performance.mark('sentry-tracing-init'); + } + this._trackCLS(); + this._trackLCP(); + this._trackFID(); + } + } + /** 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 && global.document.scripts) { + // eslint-disable-next-line @typescript-eslint/prefer-for-of + for (var i = 0; i < global.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 (global.document.scripts[i].dataset.entry === 'true') { + entryScriptSrc = global.document.scripts[i].src; + break; + } + } + } + var entryScriptStartTimestamp; + var tracingInitMarkStartTime; + var responseStartTimestamp; + var requestStartTimestamp; + 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); + responseStartTimestamp = timeOrigin + utils_2.msToSec(entry.responseStart); + requestStartTimestamp = timeOrigin + utils_2.msToSec(entry.requestStart); + 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 = getVisibilityWatcher_1.getVisibilityWatcher(); + // Only report if the page wasn't hidden prior to the web vital. + var shouldRecord = entry.startTime < firstHidden.firstHiddenTime; + 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(global.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); + // Generate TTFB (Time to First Byte), which measured as the time between the beginning of the transaction and the + // start of the response in milliseconds + if (typeof responseStartTimestamp === 'number') { + utils_1.logger.log('[Measurements] Adding TTFB'); + this._measurements['ttfb'] = { value: (responseStartTimestamp - transaction.startTimestamp) * 1000 }; + if (typeof requestStartTimestamp === 'number' && requestStartTimestamp <= responseStartTimestamp) { + // Capture the time spent making the request and receiving the first byte of the response. + // This is the time between the start of the request and the start of the response in milliseconds. + this._measurements['ttfb.requestTime'] = { value: (responseStartTimestamp - requestStartTimestamp) * 1000 }; + } + } + ['fcp', 'fp', 'lcp'].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, + }); + } + // If FCP is not recorded we should not record the cls value + // according to the new definition of CLS. + if (!('fcp' in this._measurements)) { + delete this._measurements.cls; + } + transaction.setMeasurements(this._measurements); + this._tagMetricInfo(transaction); + transaction.setTag('sentry_reportAllChanges', this._reportAllChanges); + } + }; + /** Add LCP / CLS data to transaction to allow debugging */ + MetricsInstrumentation.prototype._tagMetricInfo = function (transaction) { + if (this._lcpEntry) { + utils_1.logger.log('[Measurements] Adding LCP Data'); + // Capture Properties of the LCP element that contributes to the LCP. + if (this._lcpEntry.element) { + transaction.setTag('lcp.element', utils_1.htmlTreeAsString(this._lcpEntry.element)); + } + if (this._lcpEntry.id) { + transaction.setTag('lcp.id', this._lcpEntry.id); + } + if (this._lcpEntry.url) { + // Trim URL to the first 200 characters. + transaction.setTag('lcp.url', this._lcpEntry.url.trim().slice(0, 200)); + } + transaction.setTag('lcp.size', this._lcpEntry.size); + } + // See: https://developer.mozilla.org/en-US/docs/Web/API/LayoutShift + if (this._clsEntry && this._clsEntry.sources) { + utils_1.logger.log('[Measurements] Adding CLS Data'); + this._clsEntry.sources.forEach(function (source, index) { + return transaction.setTag("cls.source." + (index + 1), utils_1.htmlTreeAsString(source.node)); + }); + } + }; + /** Starts tracking the Cumulative Layout Shift on the current page. */ + MetricsInstrumentation.prototype._trackCLS = function () { + var _this = this; + // See: + // https://web.dev/evolving-cls/ + // https://web.dev/cls-web-tooling/ + 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 }; + _this._clsEntry = entry; + }); + }; + /** + * 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(utils_1.browserPerformanceTimeOrigin); + 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 }; + _this._lcpEntry = entry; + }, this._reportAllChanges); + }; + /** 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(utils_1.browserPerformanceTimeOrigin); + 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 }; + }); + }; + return MetricsInstrumentation; +}()); +exports.MetricsInstrumentation = MetricsInstrumentation; +/** Instrument navigation entries */ +function addNavigationSpans(transaction, entry, timeOrigin) { + addPerformanceNavigationTiming({ transaction: transaction, entry: entry, event: 'unloadEvent', timeOrigin: timeOrigin }); + addPerformanceNavigationTiming({ transaction: transaction, entry: entry, event: 'redirect', timeOrigin: timeOrigin }); + addPerformanceNavigationTiming({ transaction: transaction, entry: entry, event: 'domContentLoadedEvent', timeOrigin: timeOrigin }); + addPerformanceNavigationTiming({ transaction: transaction, entry: entry, event: 'loadEvent', timeOrigin: timeOrigin }); + addPerformanceNavigationTiming({ transaction: transaction, entry: entry, event: 'connect', timeOrigin: timeOrigin }); + addPerformanceNavigationTiming({ + transaction: transaction, + entry: entry, + event: 'secureConnection', + timeOrigin: timeOrigin, + eventEnd: 'connectEnd', + description: 'TLS/SSL', + }); + addPerformanceNavigationTiming({ + transaction: transaction, + entry: entry, + event: 'fetch', + timeOrigin: timeOrigin, + eventEnd: 'domainLookupStart', + description: 'cache', + }); + addPerformanceNavigationTiming({ transaction: transaction, entry: entry, event: 'domainLookup', timeOrigin: timeOrigin, description: 'DNS' }); + 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; +} +/** 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; + } + 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, + }); + return endTimestamp; +} +exports.addResourceSpans = addResourceSpans; +/** Create performance navigation related spans */ +function addPerformanceNavigationTiming(props) { + var transaction = props.transaction, entry = props.entry, event = props.event, timeOrigin = props.timeOrigin, eventEnd = props.eventEnd, description = props.description; + var end = eventEnd ? entry[eventEnd] : entry[event + "End"]; + var start = entry[event + "Start"]; + if (!start || !end) { + return; + } + _startChild(transaction, { + op: 'browser', + description: (description !== null && description !== void 0 ? description : event), + startTimestamp: timeOrigin + utils_2.msToSec(start), + endTimestamp: timeOrigin + utils_2.msToSec(end), + }); +} +/** Create request and response related spans */ +function addRequest(transaction, entry, timeOrigin) { + _startChild(transaction, { + op: 'browser', + description: 'request', + startTimestamp: timeOrigin + utils_2.msToSec(entry.requestStart), + endTimestamp: timeOrigin + utils_2.msToSec(entry.responseEnd), + }); + _startChild(transaction, { + op: 'browser', + description: 'response', + startTimestamp: timeOrigin + utils_2.msToSec(entry.responseStart), + endTimestamp: timeOrigin + utils_2.msToSec(entry.responseEnd), + }); +} +/** + * 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)); +} +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 + +/***/ }), + +/***/ 27854: +/***/ ((__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 spanstatus_1 = __nccwpck_require__(58522); +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 instrumentOutgoingRequests(_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', + }); + } +} +exports.instrumentOutgoingRequests = instrumentOutgoingRequests; +/** + * Create and track fetch request spans + */ +function fetchCallback(handlerData, shouldCreateSpan, spans) { + if (!utils_2.hasTracingEnabled() || !(handlerData.fetchData && shouldCreateSpan(handlerData.fetchData.url))) { + return; + } + if (handlerData.endTimestamp && handlerData.fetchData.__span) { + var span = spans[handlerData.fetchData.__span]; + if (span) { + if (handlerData.response) { + // TODO (kmclb) remove this once types PR goes through + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + span.setHttpStatus(handlerData.response.status); + } + else if (handlerData.error) { + span.setStatus(spanstatus_1.SpanStatus.InternalError); + } + 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.client', + }); + 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; + } +} +exports.fetchCallback = fetchCallback; +/** + * Create and track xhr request spans + */ +function xhrCallback(handlerData, shouldCreateSpan, spans) { + var _a, _b; + if (!utils_2.hasTracingEnabled() || ((_a = handlerData.xhr) === null || _a === void 0 ? void 0 : _a.__sentry_own_request__) || + !(((_b = handlerData.xhr) === null || _b === void 0 ? void 0 : _b.__sentry_xhr__) && shouldCreateSpan(handlerData.xhr.__sentry_xhr__.url))) { + 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.client', + }); + 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 + +/***/ }), + +/***/ 40348: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); +var utils_1 = __nccwpck_require__(1620); +var global = utils_1.getGlobalObject(); +/** + * Default function implementing pageload and navigation transactions + */ +function instrumentRoutingWithDefaults(customStartTransaction, 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 = customStartTransaction({ 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 = customStartTransaction({ name: global.location.pathname, op: 'navigation' }); + } + }, + type: 'history', + }); + } +} +exports.instrumentRoutingWithDefaults = instrumentRoutingWithDefaults; +//# sourceMappingURL=router.js.map + +/***/ }), + +/***/ 56982: +/***/ ((__unused_webpack_module, 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 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) { + var metric = initMetric_1.initMetric('CLS', 0); + var report; + var sessionValue = 0; + var sessionEntries = []; + var entryHandler = function (entry) { + // Only count layout shifts without recent user input. + // TODO: Figure out why entry can be undefined + if (entry && !entry.hadRecentInput) { + var firstSessionEntry = sessionEntries[0]; + var lastSessionEntry = sessionEntries[sessionEntries.length - 1]; + // If the entry occurred less than 1 second after the previous entry and + // less than 5 seconds after the first entry in the session, include the + // entry in the current session. Otherwise, start a new session. + if (sessionValue && + sessionEntries.length !== 0 && + entry.startTime - lastSessionEntry.startTime < 1000 && + entry.startTime - firstSessionEntry.startTime < 5000) { + sessionValue += entry.value; + sessionEntries.push(entry); + } + else { + sessionValue = entry.value; + sessionEntries = [entry]; + } + // If the current session value is larger than the current CLS value, + // update CLS and the entries contributing to it. + if (sessionValue > metric.value) { + metric.value = sessionValue; + metric.entries = sessionEntries; + if (report) { + report(); + } + } + } + }; + var po = observe_1.observe('layout-shift', entryHandler); + if (po) { + report = bindReporter_1.bindReporter(onReport, metric, reportAllChanges); + onHidden_1.onHidden(function () { + po.takeRecords().map(entryHandler); + report(true); + }); + } +}; +//# sourceMappingURL=getCLS.js.map + +/***/ }), + +/***/ 82496: +/***/ ((__unused_webpack_module, 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 bindReporter_1 = __nccwpck_require__(54592); +var getVisibilityWatcher_1 = __nccwpck_require__(10522); +var initMetric_1 = __nccwpck_require__(45300); +var observe_1 = __nccwpck_require__(17984); +var onHidden_1 = __nccwpck_require__(9658); +exports.getFID = function (onReport, reportAllChanges) { + var visibilityWatcher = getVisibilityWatcher_1.getVisibilityWatcher(); + var metric = initMetric_1.initMetric('FID'); + var report; + var entryHandler = function (entry) { + // Only report if the page wasn't hidden prior to the first input. + if (report && entry.startTime < visibilityWatcher.firstHiddenTime) { + metric.value = entry.processingStart - entry.startTime; + metric.entries.push(entry); + report(true); + } + }; + var po = observe_1.observe('first-input', entryHandler); + if (po) { + report = bindReporter_1.bindReporter(onReport, metric, reportAllChanges); + onHidden_1.onHidden(function () { + po.takeRecords().map(entryHandler); + po.disconnect(); + }, true); + } +}; +//# sourceMappingURL=getFID.js.map + +/***/ }), + +/***/ 99382: +/***/ ((__unused_webpack_module, 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 bindReporter_1 = __nccwpck_require__(54592); +var getVisibilityWatcher_1 = __nccwpck_require__(10522); +var initMetric_1 = __nccwpck_require__(45300); +var observe_1 = __nccwpck_require__(17984); +var onHidden_1 = __nccwpck_require__(9658); +var reportedMetricIDs = {}; +exports.getLCP = function (onReport, reportAllChanges) { + var visibilityWatcher = getVisibilityWatcher_1.getVisibilityWatcher(); + var metric = initMetric_1.initMetric('LCP'); + 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 < visibilityWatcher.firstHiddenTime) { + metric.value = value; + metric.entries.push(entry); + } + if (report) { + report(); + } + }; + var po = observe_1.observe('largest-contentful-paint', entryHandler); + if (po) { + report = bindReporter_1.bindReporter(onReport, metric, reportAllChanges); + var stopListening_1 = function () { + if (!reportedMetricIDs[metric.id]) { + po.takeRecords().map(entryHandler); + po.disconnect(); + reportedMetricIDs[metric.id] = true; + report(true); + } + }; + // Stop listening after input. Note: while scrolling is an input that + // stop LCP observation, it's unreliable since it can be programmatically + // generated. See: https://github.com/GoogleChrome/web-vitals/issues/75 + ['keydown', 'click'].forEach(function (type) { + addEventListener(type, stopListening_1, { once: true, capture: true }); + }); + onHidden_1.onHidden(stopListening_1, true); + } +}; +//# sourceMappingURL=getLCP.js.map + +/***/ }), + +/***/ 54592: +/***/ ((__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 })); +exports.bindReporter = function (callback, metric, reportAllChanges) { + var prevValue; + return function (forceReport) { + if (metric.value >= 0) { + if (forceReport || reportAllChanges) { + metric.delta = metric.value - (prevValue || 0); + // Report the metric if there's a non-zero delta 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 || prevValue === undefined) { + prevValue = metric.value; + callback(metric); + } + } + } + }; +}; +//# sourceMappingURL=bindReporter.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, 30-char string by combining a version + * number, the current timestamp with a 13-digit number integer. + * @return {string} + */ +exports.generateUniqueID = function () { + return "v2-" + Date.now() + "-" + (Math.floor(Math.random() * (9e12 - 1)) + 1e12); +}; +//# sourceMappingURL=generateUniqueID.js.map + +/***/ }), + +/***/ 10522: +/***/ ((__unused_webpack_module, 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 utils_1 = __nccwpck_require__(1620); +var onHidden_1 = __nccwpck_require__(9658); +var firstHiddenTime = -1; +var initHiddenTime = function () { + return utils_1.getGlobalObject().document.visibilityState === 'hidden' ? 0 : Infinity; +}; +var trackChanges = function () { + // Update the time if/when the document becomes hidden. + onHidden_1.onHidden(function (_a) { + var timeStamp = _a.timeStamp; + firstHiddenTime = timeStamp; + }, true); +}; +exports.getVisibilityWatcher = function () { + if (firstHiddenTime < 0) { + // 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 = initHiddenTime(); + trackChanges(); + } + return { + get firstHiddenTime() { + return firstHiddenTime; + }, + }; +}; +//# sourceMappingURL=getVisibilityWatcher.js.map + +/***/ }), + +/***/ 45300: +/***/ ((__unused_webpack_module, 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) { + return { + name: name, + value: (value !== null && value !== void 0 ? value : -1), + delta: 0, + entries: [], + id: generateUniqueID_1.generateUniqueID(), + }; +}; +//# sourceMappingURL=initMetric.js.map + +/***/ }), + +/***/ 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)) { + // More extensive feature detect needed for Firefox due to: + // https://github.com/GoogleChrome/web-vitals/issues/142 + if (type === 'first-input' && !('PerformanceEventTiming' in self)) { + return; + } + 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 + +/***/ }), + +/***/ 9658: +/***/ ((__unused_webpack_module, 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 utils_1 = __nccwpck_require__(1620); +exports.onHidden = function (cb, once) { + var onHiddenOrPageHide = function (event) { + if (event.type === 'pagehide' || utils_1.getGlobalObject().document.visibilityState === 'hidden') { + cb(event); + if (once) { + removeEventListener('visibilitychange', onHiddenOrPageHide, true); + removeEventListener('pagehide', onHiddenOrPageHide, true); + } + } + }; + addEventListener('visibilitychange', onHiddenOrPageHide, true); + // Some browsers have buggy implementations of visibilitychange, + // so we use pagehide in addition, just to be safe. + addEventListener('pagehide', onHiddenOrPageHide, true); +}; +//# sourceMappingURL=onHidden.js.map + +/***/ }), + +/***/ 4740: +/***/ ((__unused_webpack_module, exports) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); +// Store finish reasons in tuple to save on bundle size +// Readonly type should enforce that this is not mutated. +exports.FINISH_REASON_TAG = 'finishReason'; +exports.IDLE_TRANSACTION_FINISH_REASONS = ['heartbeatFailed', 'idleTimeout', 'documentHidden']; +//# sourceMappingURL=constants.js.map + +/***/ }), + +/***/ 47906: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +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); + } +} +//# sourceMappingURL=errors.js.map + +/***/ }), + +/***/ 31409: +/***/ ((module, exports, __nccwpck_require__) => { + +/* 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(), + }; + } + } + 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(transaction, options, samplingContext) { + // nothing to do if tracing is not enabled + if (!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.setMetadata({ + transactionSampling: { method: 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); + transaction.setMetadata({ + transactionSampling: { + method: types_1.TransactionSamplingMethod.Sampler, + // cast to number in case it's a boolean + rate: Number(sampleRate), + }, + }); + } + else if (samplingContext.parentSampled !== undefined) { + sampleRate = samplingContext.parentSampled; + transaction.setMetadata({ + transactionSampling: { method: types_1.TransactionSamplingMethod.Inheritance }, + }); + } + else { + sampleRate = options.tracesSampleRate; + transaction.setMetadata({ + transactionSampling: { + method: types_1.TransactionSamplingMethod.Rate, + // cast to number in case it's a boolean + rate: 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; + } + utils_1.logger.log("[Tracing] starting " + transaction.op + " transaction - " + transaction.name); + return transaction; +} +/** + * 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; + } + // 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; +} +/** + * 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 _a, _b; + var options = ((_a = this.getClient()) === null || _a === void 0 ? void 0 : _a.getOptions()) || {}; + var transaction = new transaction_1.Transaction(transactionContext, this); + transaction = sample(transaction, options, tslib_1.__assign({ parentSampled: transactionContext.parentSampled, transactionContext: transactionContext }, customSamplingContext)); + if (transaction.sampled) { + transaction.initSpanRecorder((_b = options._experiments) === null || _b === void 0 ? void 0 : _b.maxSpans); + } + return transaction; +} +/** + * Create new idle transaction. + */ +function startIdleTransaction(hub, transactionContext, idleTimeout, onScope, customSamplingContext) { + var _a, _b; + var options = ((_a = hub.getClient()) === null || _a === void 0 ? void 0 : _a.getOptions()) || {}; + var transaction = new idletransaction_1.IdleTransaction(transactionContext, hub, idleTimeout, onScope); + transaction = sample(transaction, options, tslib_1.__assign({ parentSampled: transactionContext.parentSampled, transactionContext: transactionContext }, customSamplingContext)); + if (transaction.sampled) { + transaction.initSpanRecorder((_b = options._experiments) === null || _b === void 0 ? void 0 : _b.maxSpans); + } + return transaction; +} +exports.startIdleTransaction = startIdleTransaction; +/** + * @private + */ +function _addTracingExtensions() { + var carrier = hub_1.getMainCarrier(); + if (!carrier.__SENTRY__) { + return; + } + 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._addTracingExtensions = _addTracingExtensions; +/** + * @private + */ +function _autoloadDatabaseIntegrations() { + var carrier = hub_1.getMainCarrier(); + if (!carrier.__SENTRY__) { + return; + } + var packageToIntegrationMapping = { + mongodb: function () { + var integration = utils_1.dynamicRequire(module, './integrations/node/mongo'); + return new integration.Mongo(); + }, + mongoose: function () { + var integration = utils_1.dynamicRequire(module, './integrations/node/mongo'); + return new integration.Mongo({ mongoose: true }); + }, + mysql: function () { + var integration = utils_1.dynamicRequire(module, './integrations/node/mysql'); + return new integration.Mysql(); + }, + pg: function () { + var integration = utils_1.dynamicRequire(module, './integrations/node/postgres'); + return new integration.Postgres(); + }, + }; + var mappedPackages = Object.keys(packageToIntegrationMapping) + .filter(function (moduleName) { return !!utils_1.loadModule(moduleName); }) + .map(function (pkg) { + try { + return packageToIntegrationMapping[pkg](); + } + catch (e) { + return undefined; + } + }) + .filter(function (p) { return p; }); + if (mappedPackages.length > 0) { + carrier.__SENTRY__.integrations = tslib_1.__spread((carrier.__SENTRY__.integrations || []), mappedPackages); + } +} +/** + * This patches the global object and injects the Tracing extensions methods + */ +function addExtensionMethods() { + _addTracingExtensions(); + // Detect and automatically load specified integrations. + if (utils_1.isNodeEnv()) { + _autoloadDatabaseIntegrations(); + } + // 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 + +/***/ }), + +/***/ 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 constants_1 = __nccwpck_require__(4740); +var span_1 = __nccwpck_require__(64655); +var spanstatus_1 = __nccwpck_require__(58522); +var transaction_1 = __nccwpck_require__(8186); +exports.DEFAULT_IDLE_TIMEOUT = 1000; +exports.HEARTBEAT_INTERVAL = 5000; +/** + * @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); + } + } + _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 = {}; + // 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); }); + } + _this._initTimeout = setTimeout(function () { + if (!_this._finished) { + _this.finish(); + } + }, _this._idleTimeout); + 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; + }); + utils_1.logger.log('[Tracing] flushing IdleTransaction'); + } + else { + utils_1.logger.log('[Tracing] No active IdleTransaction'); + } + // this._onScope is true if the transaction was previously on the scope. + if (this._onScope) { + clearActiveTransaction(this._idleHub); + } + 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) { + 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.setTag(constants_1.FINISH_REASON_TAG, constants_1.IDLE_TRANSACTION_FINISH_REASONS[1]); + _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 () { + // We should not be running heartbeat if the idle transaction is finished. + if (this._finished) { + return; + } + var heartbeatString = Object.keys(this.activities).join(''); + 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(constants_1.FINISH_REASON_TAG, constants_1.IDLE_TRANSACTION_FINISH_REASONS[0]); + 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); + setTimeout(function () { + _this._beat(); + }, exports.HEARTBEAT_INTERVAL); + }; + 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); + } + } + } +} +//# sourceMappingURL=idletransaction.js.map + +/***/ }), + +/***/ 64358: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); +var hubextensions_1 = __nccwpck_require__(31409); +exports.addExtensionMethods = hubextensions_1.addExtensionMethods; +var Integrations = __nccwpck_require__(28502); +exports.Integrations = Integrations; +// This is already exported as part of `Integrations` above (and for the moment will remain so for +// backwards compatibility), but that interferes with treeshaking, so we also export it separately +// here. +// +// Previously we expected users to import tracing integrations like +// +// import { Integrations } from '@sentry/tracing'; +// const instance = new Integrations.BrowserTracing(); +// +// This makes the integrations unable to be treeshaken though. To address this, we now have +// this individual export. We now expect users to consume BrowserTracing like so: +// +// import { BrowserTracing } from '@sentry/tracing'; +// const instance = new BrowserTracing(); +// +// For an example of of the new usage of BrowserTracing, see @sentry/nextjs index.client.ts +var browser_1 = __nccwpck_require__(71425); +exports.BrowserTracing = browser_1.BrowserTracing; +var span_1 = __nccwpck_require__(64655); +exports.Span = span_1.Span; +var transaction_1 = __nccwpck_require__(8186); +exports.Transaction = transaction_1.Transaction; +var browser_2 = __nccwpck_require__(71425); +// TODO deprecate old name in v7 +exports.registerRequestInstrumentation = browser_2.instrumentOutgoingRequests; +exports.defaultRequestInstrumentationOptions = browser_2.defaultRequestInstrumentationOptions; +var spanstatus_1 = __nccwpck_require__(58522); +exports.SpanStatus = spanstatus_1.SpanStatus; +var idletransaction_1 = __nccwpck_require__(2171); +exports.IdleTransaction = idletransaction_1.IdleTransaction; +var hubextensions_2 = __nccwpck_require__(31409); +exports.startIdleTransaction = hubextensions_2.startIdleTransaction; +// 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 + +/***/ }), + +/***/ 28502: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); +var express_1 = __nccwpck_require__(42971); +exports.Express = express_1.Express; +var postgres_1 = __nccwpck_require__(19327); +exports.Postgres = postgres_1.Postgres; +var mysql_1 = __nccwpck_require__(57296); +exports.Mysql = mysql_1.Mysql; +var mongo_1 = __nccwpck_require__(33146); +exports.Mongo = mongo_1.Mongo; +// TODO(v7): Remove this export +// Please see `src/index.ts` for more details. +var browser_1 = __nccwpck_require__(71425); +exports.BrowserTracing = browser_1.BrowserTracing; +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 42971: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +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'); + } + /** + * @inheritDoc + */ + Express.prototype.setupOnce = function () { + if (!this._router) { + utils_1.logger.error('ExpressIntegration is missing an Express instance'); + return; + } + 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: "express.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: "express.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: "express.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); + } + } +} +/** + * 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 + +/***/ }), + +/***/ 33146: +/***/ ((__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 OPERATIONS = [ + 'aggregate', + 'bulkWrite', + 'countDocuments', + 'createIndex', + 'createIndexes', + 'deleteMany', + 'deleteOne', + 'distinct', + 'drop', + 'dropIndex', + 'dropIndexes', + 'estimatedDocumentCount', + 'find', + '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'], + find: ['query'], + 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; + this._useMongoose = !!options.useMongoose; + } + /** + * @inheritDoc + */ + Mongo.prototype.setupOnce = function (_, getCurrentHub) { + var moduleName = this._useMongoose ? 'mongoose' : 'mongodb'; + var pkg = utils_1.loadModule(moduleName); + if (!pkg) { + utils_1.logger.error("Mongo Integration was unable to require `" + moduleName + "` package."); + return; + } + this._instrumentOperations(pkg.Collection, this._operations, getCurrentHub); + }; + /** + * Patches original collection methods + */ + Mongo.prototype._instrumentOperations = function (collection, operations, getCurrentHub) { + var _this = this; + operations.forEach(function (operation) { return _this._patchOperation(collection, operation, getCurrentHub); }); + }; + /** + * 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, _d; + 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)); + var maybePromise = orig.call.apply(orig, tslib_1.__spread([this], args)); + if (utils_1.isThenable(maybePromise)) { + return maybePromise.then(function (res) { + var _a; + (_a = span_1) === null || _a === void 0 ? void 0 : _a.finish(); + return res; + }); + } + else { + (_c = span_1) === null || _c === void 0 ? void 0 : _c.finish(); + return maybePromise; + } + } + var span = (_d = parentSpan) === null || _d === void 0 ? void 0 : _d.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); + }])); + }; + }); + }; + /** + * 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; + } + 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 + +/***/ }), + +/***/ 57296: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +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; + } + /** + * @inheritDoc + */ + Mysql.prototype.setupOnce = function (_, getCurrentHub) { + var pkg = utils_1.loadModule('mysql/lib/Connection.js'); + if (!pkg) { + 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(pkg, 'createQuery', 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 + +/***/ }), + +/***/ 19327: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); +var utils_1 = __nccwpck_require__(1620); +/** Tracing integration for node-postgres package */ +var Postgres = /** @class */ (function () { + function Postgres(options) { + if (options === void 0) { options = {}; } + /** + * @inheritDoc + */ + this.name = Postgres.id; + this._usePgNative = !!options.usePgNative; + } + /** + * @inheritDoc + */ + Postgres.prototype.setupOnce = function (_, getCurrentHub) { + var _a; + var pkg = utils_1.loadModule('pg'); + if (!pkg) { + utils_1.logger.error('Postgres Integration was unable to require `pg` package.'); + return; + } + if (this._usePgNative && !((_a = pkg.native) === null || _a === void 0 ? void 0 : _a.Client)) { + utils_1.logger.error("Postgres Integration was unable to access 'pg-native' bindings."); + return; + } + var Client = (this._usePgNative ? pkg.native : pkg).Client; + /** + * function (query, callback) => void + * function (query, params, callback) => void + * function (query) => Promise + * function (query, params) => Promise + * function (pg.Cursor) => pg.Cursor + */ + utils_1.fill(Client.prototype, 'query', function (orig) { + return function (config, values, callback) { + var _a, _b, _c; + 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); + }); + } + var rv = typeof values !== 'undefined' ? orig.call(this, config, values) : orig.call(this, config); + if (utils_1.isThenable(rv)) { + return rv.then(function (res) { + var _a; + (_a = span) === null || _a === void 0 ? void 0 : _a.finish(); + return res; + }); + } + (_c = span) === null || _c === void 0 ? void 0 : _c.finish(); + return rv; + }; + }); + }; + /** + * @inheritDoc + */ + Postgres.id = 'Postgres'; + return Postgres; +}()); +exports.Postgres = Postgres; +//# sourceMappingURL=postgres.js.map + +/***/ }), + +/***/ 64655: +/***/ ((__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 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; + } + /** + * 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; + } + } + /** + * @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.toContext = function () { + return utils_1.dropUndefinedKeys({ + data: this.data, + description: this.description, + endTimestamp: this.endTimestamp, + op: this.op, + parentSpanId: this.parentSpanId, + sampled: this.sampled, + spanId: this.spanId, + startTimestamp: this.startTimestamp, + status: this.status, + tags: this.tags, + traceId: this.traceId, + }); + }; + /** + * @inheritDoc + */ + Span.prototype.updateWithContext = function (spanContext) { + var _a, _b, _c, _d, _e; + this.data = (_a = spanContext.data, (_a !== null && _a !== void 0 ? _a : {})); + this.description = spanContext.description; + this.endTimestamp = spanContext.endTimestamp; + this.op = spanContext.op; + this.parentSpanId = spanContext.parentSpanId; + this.sampled = spanContext.sampled; + this.spanId = (_b = spanContext.spanId, (_b !== null && _b !== void 0 ? _b : this.spanId)); + this.startTimestamp = (_c = spanContext.startTimestamp, (_c !== null && _c !== void 0 ? _c : this.startTimestamp)); + this.status = spanContext.status; + this.tags = (_d = spanContext.tags, (_d !== null && _d !== void 0 ? _d : {})); + this.traceId = (_e = spanContext.traceId, (_e !== null && _e !== void 0 ? _e : this.traceId)); + return this; + }; + /** + * @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 + +/***/ }), + +/***/ 58522: +/***/ ((__unused_webpack_module, exports) => { + +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 && httpStatus >= 100) { + 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 + +/***/ }), + +/***/ 8186: +/***/ ((__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 types_1 = __nccwpck_require__(83789); +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 || ''; + _this.metadata = transactionContext.metadata || {}; + _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); + }; + /** + * Set metadata for this transaction. + * @hidden + */ + Transaction.prototype.setMetadata = function (newMetadata) { + this.metadata = tslib_1.__assign(tslib_1.__assign({}, this.metadata), newMetadata); + }; + /** + * @inheritDoc + */ + Transaction.prototype.finish = function (endTimestamp) { + var _this = this; + var _a, _b, _c, _d, _e; + // 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.'); + (_e = (_c = (_a = this._hub + .getClient()) === null || _a === void 0 ? void 0 : (_b = _a).getTransport) === null || _c === void 0 ? void 0 : (_d = _c.call(_b)).recordLostEvent) === null || _e === void 0 ? void 0 : _e.call(_d, types_1.Outcome.SampleRate, 'transaction'); + 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', + debug_meta: this.metadata, + }; + 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; + } + utils_1.logger.log("[Tracing] Finishing " + this.op + " transaction: " + this.name + "."); + return this._hub.captureEvent(transaction); + }; + /** + * @inheritDoc + */ + Transaction.prototype.toContext = function () { + var spanContext = _super.prototype.toContext.call(this); + return utils_1.dropUndefinedKeys(tslib_1.__assign(tslib_1.__assign({}, spanContext), { name: this.name, trimEnd: this._trimEnd })); + }; + /** + * @inheritDoc + */ + Transaction.prototype.updateWithContext = function (transactionContext) { + var _a; + _super.prototype.updateWithContext.call(this, transactionContext); + this.name = (_a = transactionContext.name, (_a !== null && _a !== void 0 ? _a : '')); + this._trimEnd = transactionContext.trimEnd; + return this; + }; + return Transaction; +}(span_1.Span)); +exports.Transaction = Transaction; +//# sourceMappingURL=transaction.js.map + +/***/ }), + +/***/ 31386: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +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) { + if (options === void 0) { options = (_a = hub_1.getCurrentHub() + .getClient()) === null || _a === void 0 ? void 0 : _a.getOptions(); } + var _a; + return !!options && ('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 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 + +/***/ }), + +/***/ 83789: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +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; +exports.RequestSessionStatus = session_1.RequestSessionStatus; +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; +var transport_1 = __nccwpck_require__(36770); +exports.Outcome = transport_1.Outcome; +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 6853: +/***/ ((__unused_webpack_module, exports) => { + +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 + +/***/ }), + +/***/ 84954: +/***/ ((__unused_webpack_module, exports) => { + +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 = {})); +var RequestSessionStatus; +(function (RequestSessionStatus) { + /** JSDoc */ + RequestSessionStatus["Ok"] = "ok"; + /** JSDoc */ + RequestSessionStatus["Errored"] = "errored"; + /** JSDoc */ + RequestSessionStatus["Crashed"] = "crashed"; +})(RequestSessionStatus = exports.RequestSessionStatus || (exports.RequestSessionStatus = {})); +//# sourceMappingURL=session.js.map + +/***/ }), + +/***/ 94124: +/***/ ((__unused_webpack_module, exports) => { + +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 + +/***/ }), + +/***/ 61277: +/***/ ((__unused_webpack_module, exports) => { + +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 occurred 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; + } + return Status.Unknown; + } + Status.fromHttpCode = fromHttpCode; +})(Status = exports.Status || (exports.Status = {})); +//# sourceMappingURL=status.js.map + +/***/ }), + +/***/ 47540: +/***/ ((__unused_webpack_module, exports) => { + +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 + +/***/ }), + +/***/ 36770: +/***/ ((__unused_webpack_module, exports) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); +var Outcome; +(function (Outcome) { + Outcome["BeforeSend"] = "before_send"; + Outcome["EventProcessor"] = "event_processor"; + Outcome["NetworkError"] = "network_error"; + Outcome["QueueOverflow"] = "queue_overflow"; + Outcome["RateLimitBackoff"] = "ratelimit_backoff"; + Outcome["SampleRate"] = "sample_rate"; +})(Outcome = exports.Outcome || (exports.Outcome = {})); +//# sourceMappingURL=transport.js.map + +/***/ }), + +/***/ 58343: +/***/ ((__unused_webpack_module, exports) => { + +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) { + void 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 + +/***/ }), + +/***/ 30597: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); +var global_1 = __nccwpck_require__(68813); +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, keyAttrs) { + // 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, keyAttrs); + // 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, keyAttrs) { + var _a, _b; + 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()); + // Pairs of attribute keys defined in `serializeAttribute` and their values on element. + var keyAttrPairs = ((_a = keyAttrs) === null || _a === void 0 ? void 0 : _a.length) ? keyAttrs.filter(function (keyAttr) { return elem.getAttribute(keyAttr); }).map(function (keyAttr) { return [keyAttr, elem.getAttribute(keyAttr)]; }) + : null; + if ((_b = keyAttrPairs) === null || _b === void 0 ? void 0 : _b.length) { + keyAttrPairs.forEach(function (keyAttrPair) { + out.push("[" + keyAttrPair[0] + "=\"" + keyAttrPair[1] + "\"]"); + }); + } + else { + 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(''); +} +/** + * A safe form of location.href + */ +function getLocationHref() { + var global = global_1.getGlobalObject(); + try { + return global.document.location.href; + } + catch (oO) { + return ''; + } +} +exports.getLocationHref = getLocationHref; +//# sourceMappingURL=browser.js.map + +/***/ }), + +/***/ 3275: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +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, publicKey = _a.publicKey; + return (protocol + "://" + publicKey + (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], publicKey = _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, publicKey: publicKey }); + }; + /** Maps Dsn components into this instance. */ + Dsn.prototype._fromComponents = function (components) { + // TODO this is for backwards compatibility, and can be removed in a future version + if ('user' in components && !('publicKey' in components)) { + components.publicKey = components.user; + } + this.user = components.publicKey || ''; + this.protocol = components.protocol; + this.publicKey = components.publicKey || ''; + 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', 'publicKey', '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 })); +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 + +/***/ }), + +/***/ 68813: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +/** + * NOTE: In order to avoid circular dependencies, if you add a function to this module and it needs to print something, + * you must either a) use `console.log` rather than the logger, or b) put your function elsewhere. + */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +var node_1 = __nccwpck_require__(16411); +var fallbackGlobalObject = {}; +/** + * Safely get global scope object + * + * @returns Global scope object + */ +function getGlobalObject() { + return (node_1.isNodeEnv() + ? global + : typeof window !== 'undefined' // eslint-disable-line no-restricted-globals + ? window // eslint-disable-line no-restricted-globals + : typeof self !== 'undefined' + ? self + : fallbackGlobalObject); +} +exports.getGlobalObject = getGlobalObject; +//# sourceMappingURL=global.js.map + +/***/ }), + +/***/ 1620: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +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__(68813), 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__) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __nccwpck_require__(4351); +var global_1 = __nccwpck_require__(68813); +var is_1 = __nccwpck_require__(92757); +var logger_1 = __nccwpck_require__(15577); +var object_1 = __nccwpck_require__(69249); +var stacktrace_1 = __nccwpck_require__(5986); +var supports_1 = __nccwpck_require__(88714); +var global = global_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]; + } + if ('Request' in global && is_1.isInstanceOf(fetchArgs[0], Request)) { + return fetchArgs[0].url; + } + return String(fetchArgs[0]); +} +/* 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]; + } + // 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); + }; + }); +} +var lastHref; +/** JSDoc */ +function instrumentHistory() { + if (!supports_1.supportsHistory()) { + return; + } + 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) { + // Apparently this can throw in Firefox when incorrectly implemented plugin is installed. + // https://github.com/getsentry/sentry-javascript/issues/3344 + // https://github.com/bugsnag/bugsnag-js/issues/469 + try { + return oldOnPopState.apply(this, args); + } + catch (_oO) { + // no-empty + } + } + }; + /** @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); + }; + } + object_1.fill(global.history, 'pushState', historyReplacementFunction); + object_1.fill(global.history, 'replaceState', historyReplacementFunction); +} +var debounceDuration = 1000; +var debounceTimerID; +var lastCapturedEvent; +/** + * Decide whether the current event should finish the debounce of previously captured one. + * @param previous previously captured event + * @param current event to be captured + */ +function shouldShortcircuitPreviousDebounce(previous, current) { + // If there was no previous event, it should always be swapped for the new one. + if (!previous) { + return true; + } + // If both events have different type, then user definitely performed two separate actions. e.g. click + keypress. + if (previous.type !== current.type) { + return true; + } + try { + // If both events have the same type, it's still possible that actions were performed on different targets. + // e.g. 2 clicks on different buttons. + if (previous.target !== current.target) { + return true; + } + } + catch (e) { + // just accessing `target` property can throw an exception in some rare circumstances + // see: https://github.com/getsentry/sentry-javascript/issues/838 + } + // If both events have the same type _and_ same `target` (an element which triggered an event, _not necessarily_ + // to which an event listener was attached), we treat them as the same action, as we want to capture + // only one breadcrumb. e.g. multiple clicks on the same button, or typing inside a user input box. + return false; +} +/** + * Decide whether an event should be captured. + * @param event event to be captured + */ +function shouldSkipDOMEvent(event) { + // We are only interested in filtering `keypress` events for now. + if (event.type !== 'keypress') { + return false; + } + try { + var target = event.target; + if (!target || !target.tagName) { + return true; + } + // Only consider keypress events on actual input elements. This will disregard keypresses targeting body + // e.g.tabbing through elements, hotkeys, etc. + if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable) { + return false; + } + } + catch (e) { + // just accessing `target` property can throw an exception in some rare circumstances + // see: https://github.com/getsentry/sentry-javascript/issues/838 + } + return true; +} +/** + * Wraps addEventListener to capture UI breadcrumbs + * @param handler function that will be triggered + * @param globalListener indicates whether event was captured by the global event listener + * @returns wrapped breadcrumb events handler + * @hidden + */ +function makeDOMEventHandler(handler, globalListener) { + if (globalListener === void 0) { globalListener = false; } + return function (event) { + // 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 that event. + if (!event || lastCapturedEvent === event) { + return; + } + // We always want to skip _some_ events. + if (shouldSkipDOMEvent(event)) { + return; + } + var name = event.type === 'keypress' ? 'input' : event.type; + // If there is no debounce timer, it means that we can safely capture the new event and store it for future comparisons. + if (debounceTimerID === undefined) { + handler({ + event: event, + name: name, + global: globalListener, + }); + lastCapturedEvent = event; + } + // If there is a debounce awaiting, see if the new event is different enough to treat it as a unique one. + // If that's the case, emit the previous event and store locally the newly-captured DOM event. + else if (shouldShortcircuitPreviousDebounce(lastCapturedEvent, event)) { + handler({ + event: event, + name: name, + global: globalListener, + }); + lastCapturedEvent = event; + } + // Start a new debounce timer that will prevent us from capturing multiple events that should be grouped together. + clearTimeout(debounceTimerID); + debounceTimerID = global.setTimeout(function () { + debounceTimerID = undefined; + }, debounceDuration); + }; +} +/** JSDoc */ +function instrumentDOM() { + if (!('document' in global)) { + return; + } + // Make it so that any click or keypress that is unhandled / bubbled up all the way to the document triggers our dom + // handlers. (Normally we have only one, which captures a breadcrumb for each click or keypress.) Do this before + // we instrument `addEventListener` so that we don't end up attaching this handler twice. + var triggerDOMHandler = triggerHandlers.bind(null, 'dom'); + var globalDOMEventHandler = makeDOMEventHandler(triggerDOMHandler, true); + global.document.addEventListener('click', globalDOMEventHandler, false); + global.document.addEventListener('keypress', globalDOMEventHandler, false); + // After hooking into click and keypress events bubbled up to `document`, we also hook into user-handled + // clicks & keypresses, by adding an event listener of our own to any element to which they add a listener. That + // way, whenever one of their handlers is triggered, ours will be, too. (This is needed because their handler + // could potentially prevent the event from bubbling up to our global listeners. This way, our handler are still + // guaranteed to fire at least once.) + ['EventTarget', 'Node'].forEach(function (target) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + var proto = global[target] && global[target].prototype; + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, no-prototype-builtins + if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty('addEventListener')) { + return; + } + object_1.fill(proto, 'addEventListener', function (originalAddEventListener) { + return function (type, listener, options) { + if (type === 'click' || type == 'keypress') { + try { + var el = this; + var handlers_1 = (el.__sentry_instrumentation_handlers__ = el.__sentry_instrumentation_handlers__ || {}); + var handlerForType = (handlers_1[type] = handlers_1[type] || { refCount: 0 }); + if (!handlerForType.handler) { + var handler = makeDOMEventHandler(triggerDOMHandler); + handlerForType.handler = handler; + originalAddEventListener.call(this, type, handler, options); + } + handlerForType.refCount += 1; + } + catch (e) { + // Accessing dom properties is always fragile. + // Also allows us to skip `addEventListenrs` calls with no proper `this` context. + } + } + return originalAddEventListener.call(this, type, listener, options); + }; + }); + object_1.fill(proto, 'removeEventListener', function (originalRemoveEventListener) { + return function (type, listener, options) { + if (type === 'click' || type == 'keypress') { + try { + var el = this; + var handlers_2 = el.__sentry_instrumentation_handlers__ || {}; + var handlerForType = handlers_2[type]; + if (handlerForType) { + handlerForType.refCount -= 1; + // If there are no longer any custom handlers of the current type on this element, we can remove ours, too. + if (handlerForType.refCount <= 0) { + originalRemoveEventListener.call(this, type, handlerForType.handler, options); + handlerForType.handler = undefined; + delete handlers_2[type]; // eslint-disable-line @typescript-eslint/no-dynamic-delete + } + // If there are no longer any custom handlers of any type on this element, cleanup everything. + if (Object.keys(handlers_2).length === 0) { + delete el.__sentry_instrumentation_handlers__; + } + } + } + catch (e) { + // Accessing dom properties is always fragile. + // Also allows us to skip `addEventListenrs` calls with no proper `this` context. + } + } + return originalRemoveEventListener.call(this, type, listener, options); + }; + }); + }); +} +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 + +/***/ }), + +/***/ 92757: +/***/ ((__unused_webpack_module, exports) => { + +/* 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); + } +} +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; + } + catch (_e) { + return false; + } +} +exports.isInstanceOf = isInstanceOf; +//# sourceMappingURL=is.js.map + +/***/ }), + +/***/ 15577: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); +var global_1 = __nccwpck_require__(68813); +// TODO: Implement different loggers for different environments +var global = global_1.getGlobalObject(); +/** Prefix for logging strings */ +var PREFIX = 'Sentry Logger '; +/** + * Temporarily unwrap `console.log` and friends in order to perform the given callback using the original methods. + * Restores wrapping after the callback completes. + * + * @param callback The function to run against the original `console` messages + * @returns The results of the callback + */ +function consoleSandbox(callback) { + var global = global_1.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; +/** JSDoc */ +var Logger = /** @class */ (function () { + /** JSDoc */ + function Logger() { + this._enabled = false; + } + /** 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; + } + consoleSandbox(function () { + global.console.log(PREFIX + "[Log]: " + args.join(' ')); + }); + }; + /** JSDoc */ + Logger.prototype.warn = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + if (!this._enabled) { + return; + } + consoleSandbox(function () { + global.console.warn(PREFIX + "[Warn]: " + args.join(' ')); + }); + }; + /** JSDoc */ + Logger.prototype.error = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + if (!this._enabled) { + return; + } + 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 + +/***/ }), + +/***/ 49515: +/***/ ((__unused_webpack_module, exports) => { + +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() : []; + } + /** + * 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 Memo; +}()); +exports.Memo = Memo; +//# sourceMappingURL=memo.js.map + +/***/ }), + +/***/ 32154: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __nccwpck_require__(4351); +var global_1 = __nccwpck_require__(68813); +var string_1 = __nccwpck_require__(66538); +/** + * UUID4 generator + * + * @returns string Generated UUID4. + */ +function uuid4() { + var global = global_1.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; +/** + * 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 data to a given event. Uses defaults if the second parameter is not passed. + * + * @param event The event to modify. + * @param newMechanism Mechanism data to add to the event. + * @hidden + */ +function addExceptionMechanism(event, newMechanism) { + var _a; + if (!event.exception || !event.exception.values) { + return; + } + var exceptionValue0 = event.exception.values[0]; + var defaultMechanism = { type: 'generic', handled: true }; + var currentMechanism = exceptionValue0.mechanism; + exceptionValue0.mechanism = tslib_1.__assign(tslib_1.__assign(tslib_1.__assign({}, defaultMechanism), currentMechanism), newMechanism); + if (newMechanism && 'data' in newMechanism) { + var mergedData = tslib_1.__assign(tslib_1.__assign({}, (_a = currentMechanism) === null || _a === void 0 ? void 0 : _a.data), newMechanism.data); + exceptionValue0.mechanism.data = mergedData; + } +} +exports.addExceptionMechanism = addExceptionMechanism; +// 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; +/** + * Checks whether or not we've already captured the given exception (note: not an identical exception - the very object + * in question), and marks it captured if not. + * + * This is useful because it's possible for an error to get captured by more than one mechanism. After we intercept and + * record an error, we rethrow it (assuming we've intercepted it before it's reached the top-level global handlers), so + * that we don't interfere with whatever effects the error might have had were the SDK not there. At that point, because + * the error has been rethrown, it's possible for it to bubble up to some other code we've instrumented. If it's not + * caught after that, it will bubble all the way up to the global handlers (which of course we also instrument). This + * function helps us ensure that even if we encounter the same error more than once, we only record it the first time we + * see it. + * + * Note: It will ignore primitives (always return `false` and not mark them as seen), as properties can't be set on + * them. {@link: Object.objectify} can be used on exceptions to convert any that are primitives into their equivalent + * object wrapper forms so that this check will always work. However, because we need to flag the exact object which + * will get rethrown, and because that rethrowing happens outside of the event processing pipeline, the objectification + * must be done before the exception captured. + * + * @param A thrown exception to check or flag as having been seen + * @returns `true` if the exception has already been captured, `false` if not (with the side effect of marking it seen) + */ +function checkOrSetAlreadyCaught(exception) { + var _a; + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + if ((_a = exception) === null || _a === void 0 ? void 0 : _a.__sentry_captured__) { + return true; + } + try { + // set it this way rather than by assignment so that it's not ennumerable and therefore isn't recorded by the + // `ExtraErrorData` integration + Object.defineProperty(exception, '__sentry_captured__', { + value: true, + }); + } + catch (err) { + // `exception` is a primitive, so we can't mark it seen + } + return false; +} +exports.checkOrSetAlreadyCaught = checkOrSetAlreadyCaught; +//# sourceMappingURL=misc.js.map -// Keep as upper-case to make updating from source easier +/***/ }), -module.exports = new Set(internals.tlds.map((tld) => tld.toLowerCase())); +/***/ 16411: +/***/ ((module, exports, __nccwpck_require__) => { +/* module decorator */ module = __nccwpck_require__.nmd(module); +/** + * NOTE: In order to avoid circular dependencies, if you add a function to this module and it needs to print something, + * you must either a) use `console.log` rather than the logger, or b) put your function elsewhere. + */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +/** + * 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, @typescript-eslint/no-explicit-any +function dynamicRequire(mod, request) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + return mod.require(request); +} +exports.dynamicRequire = dynamicRequire; +/** + * Helper for dynamically loading module that should work with linked dependencies. + * The problem is that we _should_ be using `require(require.resolve(moduleName, { paths: [cwd()] }))` + * However it's _not possible_ to do that with Webpack, as it has to know all the dependencies during + * build time. `require.resolve` is also not available in any other way, so we cannot create, + * a fake helper like we do with `dynamicRequire`. + * + * We always prefer to use local package, thus the value is not returned early from each `try/catch` block. + * That is to mimic the behavior of `require.resolve` exactly. + * + * @param moduleName module name to require + * @returns possibly required module + */ +function loadModule(moduleName) { + var mod; + try { + mod = dynamicRequire(module, moduleName); + } + catch (e) { + // no-empty + } + try { + var cwd = dynamicRequire(module, 'process').cwd; + mod = dynamicRequire(module, cwd() + "/node_modules/" + moduleName); + } + catch (e) { + // no-empty + } + return mod; +} +exports.loadModule = loadModule; +//# sourceMappingURL=node.js.map /***/ }), -/***/ 74983: +/***/ 69249: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"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); +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); +/** + * Replace a method in an object with a wrapped version of itself. + * + * @param source An object that contains a method to be wrapped. + * @param name The name of the method to be wrapped. + * @param replacementFactory A higher-order function that takes the original version of the given method and returns a + * wrapped version. Note: The function returned by `replacementFactory` needs to be a non-arrow function, in order to + * preserve the correct value of `this`, and the original method must be called using `origMethod.call(this, )` or `origMethod.apply(this, [])` (rather than being called directly), again to preserve `this`. + * @returns void + */ +function fill(source, name, replacementFactory) { + if (!(name in source)) { + return; + } + var original = source[name]; + var wrapped = replacementFactory(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 its attributes + * attached to it. + * + * @param value Initial source that we have to transform in order for it 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 = {}; + // Accessing event attributes can throw (see https://github.com/getsentry/sentry-javascript/issues/768 and + // https://github.com/getsentry/sentry-javascript/issues/838), but accessing `type` hasn't been wrapped in a + // try-catch in at least two years and no one's complained, so that's likely not an issue anymore + source.type = event_1.type; + 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 attr in event_1) { + if (Object.prototype.hasOwnProperty.call(event_1, attr)) { + source[attr] = event_1[attr]; + } + } + 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]'; + } + // It's safe to use `window` and `document` here in this manner, as we are asserting using `typeof` first + // which won't throw if they are not present. + // eslint-disable-next-line no-restricted-globals + if (typeof window !== 'undefined' && value === window) { + return '[Window]'; + } + // eslint-disable-next-line no-restricted-globals + 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; + } + // 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**'; } - - // 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()); +} +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; + } + if (includedKeys === keys.length) { + return serialized; + } + 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]); + } } - else { - Assert(rfc.schemeRegex.test(scheme), 'scheme at position ' + i + ' must be a valid scheme'); - selections.push(EscapeRegex(scheme)); + } + 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; +/** + * Ensure that something is an object. + * + * Turns `undefined` and `null` into `String`s and all other primitives into instances of their respective wrapper + * classes (String, Boolean, Number, etc.). Acts as the identity function on non-primitives. + * + * @param wat The subject of the objectification + * @returns A version of `wat` which can safely be used with `Object` class methods + */ +function objectify(wat) { + var objectified; + switch (true) { + case wat === undefined || wat === null: + objectified = new String(wat); + break; + // Though symbols and bigints do have wrapper classes (`Symbol` and `BigInt`, respectively), for whatever reason + // those classes don't have constructors which can be used with the `new` keyword. We therefore need to cast each as + // an object in order to wrap it. + case typeof wat === 'symbol' || typeof wat === 'bigint': + objectified = Object(wat); + break; + // this will catch the remaining primitives: `String`, `Number`, and `Boolean` + case is_1.isPrimitive(wat): + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + objectified = new wat.constructor(wat); + break; + // by process of elimination, at this point we know that `wat` must already be an object + default: + objectified = wat; + break; + } + return objectified; +} +exports.objectify = objectify; +//# sourceMappingURL=object.js.map - customScheme = selections.join('|'); +/***/ }), + +/***/ 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 })); +/** 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]; } - - // 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 - }; -}; - - -internals.uriRegex = internals.createRegex({}); - - -exports.regex = function (options = {}) { - - if (options.scheme || - options.allowRelative || - options.relativeOnly || - options.allowQuerySquareBrackets || - options.domain) { - - return internals.createRegex(options); + 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 '.'; } - - return internals.uriRegex; -}; - + 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 /***/ }), -/***/ 34379: +/***/ 1243: /***/ ((__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`); - } - } +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) { + if (!Object.prototype.hasOwnProperty.call(obj, prop)) { + // @ts-ignore typescript complains about indexing so we remove + obj[prop] = proto[prop]; } - - this.settings = options[internals.settings] ? options : Object.assign({ [internals.settings]: true, constants: {}, functions: {} }, options); - this.single = null; - - this._parts = null; - this._parse(string); } + return obj; +} +//# sourceMappingURL=polyfill.js.map - _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 +/***/ 31811: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - 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}`); +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 (representing an in-flight action) to the queue, and set it to remove itself on fulfillment. + * + * @param taskProducer A function producing any PromiseLike; In previous versions this used to be `task: + * PromiseLike`, but under that model, Promises were instantly created on the call-site and their executor + * functions therefore ran immediately. Thus, even if the buffer was full, the action still happened. By + * requiring the promise to be wrapped in a function, we can defer promise creation until after the buffer + * limit check. + * @returns The original promise. + */ + PromiseBuffer.prototype.add = function (taskProducer) { + var _this = this; + if (!this.isReady()) { + return syncpromise_1.SyncPromise.reject(new error_1.SentryError('Not adding Promise due to buffer limit reached.')); + } + // start the task and add its promise to the queue + var task = taskProducer(); + if (this._buffer.indexOf(task) === -1) { + this._buffer.push(task); + } + void task + .then(function () { return _this.remove(task); }) + // Use `then(null, rejectionHandler)` rather than `catch(rejectionHandler)` so that we can use `PromiseLike` + // rather than `Promise`. `PromiseLike` doesn't have a `.catch` method, making its polyfill smaller. (ES5 didn't + // have promises, so TS has to polyfill when down-compiling.) + .then(null, function () { + return _this.remove(task).then(null, function () { + // We have to add another catch here because `this.remove()` starts a new promise chain. + }); + }); + return task; + }; + /** + * Remove a promise from 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; + }; + /** + * Wait for all promises in the queue to resolve or for timeout to expire, whichever comes first. + * + * @param timeout The time, in ms, after which to resolve to `false` if the queue is still non-empty. Passing `0` (or + * not passing anything) will make the promise wait as long as it takes for the queue to drain before resolving to + * `true`. + * @returns A promise which will resolve to `true` if the queue is already empty or drains before the timeout, and + * `false` otherwise + */ + PromiseBuffer.prototype.drain = function (timeout) { + var _this = this; + return new syncpromise_1.SyncPromise(function (resolve) { + // wait for `timeout` ms and then resolve to `false` (if not cancelled first) + var capturedSetTimeout = setTimeout(function () { + if (timeout && timeout > 0) { + resolve(false); } + }, timeout); + // if all promises resolve in time, cancel the timer and resolve to `true` + void 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 - parts.push({ type: 'reference', value: current }); - } +/***/ }), - current = ''; - }; +/***/ 5986: +/***/ ((__unused_webpack_module, exports) => { - 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; - } - } - else if (c in internals.literals) { - literal = internals.literals[c]; - } - else if (c === '(') { - flush(); - ++parenthesis; - } - else if (internals.operatorCharacters.includes(c)) { - flush(); - current = c; - flush(); - } - else if (c !== ' ') { - current += c; - } - else { - flush(); - } +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 - 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' }; - }); +/***/ 66538: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // Validate tokens order +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 (0 = unlimited) + * @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; +/** + * Given a string, escape characters which have meaning in the regex grammar, such that the result is safe to feed to + * `new RegExp()`. + * + * Based on https://github.com/sindresorhus/escape-string-regexp. Vendored to a) reduce the size by skipping the runtime + * type-checking, and b) ensure it gets down-compiled for old versions of Node (the published package only supports Node + * 12+). + * + * @param regexString The string to escape + * @returns An version of the string with all special regex characters escaped + */ +function escapeStringForRegex(regexString) { + // escape the hyphen separately so we can also replace it with a unicode literal hyphen, to avoid the problems + // discussed in https://github.com/sindresorhus/escape-string-regexp/issues/20. + return regexString.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&').replace(/-/g, '\\x2d'); +} +exports.escapeStringForRegex = escapeStringForRegex; +//# sourceMappingURL=string.js.map - 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'); - } +/***/ 88714: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - 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'); +Object.defineProperty(exports, "__esModule", ({ value: true })); +var global_1 = __nccwpck_require__(68813); +var logger_1 = __nccwpck_require__(15577); +/** + * 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 global_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()); +} +exports.isNativeFetch = isNativeFetch; +/** + * 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 = global_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); } - - operator = !operator; - } - - if (!operator) { - throw new Error('Formula contains invalid trailing operator'); + doc.head.removeChild(sandbox); } - - // 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 }; + catch (err) { + logger_1.logger.warn('Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ', err); } - - // 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); + } + 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 global_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 = global_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 - _subFormula(string, name) { - - const method = this.settings.functions[name]; - if (typeof method !== 'function') { - throw new Error(`Formula contains unknown function ${name}`); - } - - 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) { +/***/ 87833: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - flush(); +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); +/** + * 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 = "PENDING" /* PENDING */; + this._handlers = []; + /** JSDoc */ + this._resolve = function (value) { + _this._setResult("RESOLVED" /* RESOLVED */, value); + }; + /** JSDoc */ + this._reject = function (reason) { + _this._setResult("REJECTED" /* REJECTED */, reason); + }; + /** JSDoc */ + this._setResult = function (state, value) { + if (_this._state !== "PENDING" /* PENDING */) { + return; + } + if (is_1.isThenable(value)) { + void 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 === "PENDING" /* PENDING */) { + return; + } + var cachedHandlers = _this._handlers.slice(); + _this._handlers = []; + cachedHandlers.forEach(function (handler) { + if (handler.done) { + return; } - else { - current += c; - if (c === '(') { - ++parenthesis; + if (_this._state === "RESOLVED" /* RESOLVED */) { + if (handler.onfulfilled) { + // eslint-disable-next-line @typescript-eslint/no-floating-promises + handler.onfulfilled(_this._value); } - else if (c === ')') { - --parenthesis; + } + if (_this._state === "REJECTED" /* REJECTED */) { + if (handler.onrejected) { + handler.onrejected(_this._value); } } - } - - flush(); - } - - 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)); - } - - return method.call(context, ...innerValues); + handler.done = true; + }); }; + try { + executor(this._resolve, this._reject); + } + catch (e) { + this._reject(e); + } } - - 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); + /** 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; } - } - - // 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 { - i += 2; - } + if (collection.length === 0) { + resolve([]); + return; } + var counter = collection.length; + var resolvedCollection = []; + collection.forEach(function (item, index) { + void 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); + }); }); - - 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; }; -}; - - -internals.evaluate = function (part, context) { - - if (part === null) { - return null; - } + /** JSDoc */ + SyncPromise.prototype.toString = function () { + return '[object SyncPromise]'; + }; + return SyncPromise; +}()); +exports.SyncPromise = SyncPromise; +//# sourceMappingURL=syncpromise.js.map - if (typeof part === 'function') { - return part(context); - } +/***/ }), - if (part[internals.symbol]) { - return part.evaluate(context); - } +/***/ 1735: +/***/ ((module, exports, __nccwpck_require__) => { - return part; +/* module decorator */ module = __nccwpck_require__.nmd(module); +Object.defineProperty(exports, "__esModule", ({ value: true })); +var global_1 = __nccwpck_require__(68813); +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; }, }; - - -internals.single = function (operator, value) { - - if (operator === '!') { - return value ? false : true; +/** + * 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 = global_1.getGlobalObject().performance; + if (!performance || !performance.now) { + return undefined; } - - // operator === 'n' - - const negative = -value; - if (negative === 0) { // Override -0 - return 0; + // 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; } - - return negative; -}; - - -internals.calculate = function (operator, left, right) { - - if (operator === '??') { - return internals.exists(left) ? left : right; + catch (_) { + return undefined; } - - if (typeof left === 'string' || - typeof right === 'string') { - - if (operator === '+') { - left = internals.exists(left) ? left : ''; - right = internals.exists(right) ? right : ''; - return left + right; - } +} +/** + * 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 () { + // Unfortunately browsers may report an inaccurate time origin data, through either performance.timeOrigin or + // performance.timing.navigationStart, which results in poor results in performance data. We only treat time origin + // data as reliable if they are within a reasonable threshold of the current time. + var performance = global_1.getGlobalObject().performance; + if (!performance || !performance.now) { + exports._browserPerformanceTimeOriginMode = 'none'; + return undefined; } - 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; + var threshold = 3600 * 1000; + var performanceNow = performance.now(); + var dateNow = Date.now(); + // if timeOrigin isn't available set delta to threshold so it isn't used + var timeOriginDelta = performance.timeOrigin + ? Math.abs(performance.timeOrigin + performanceNow - dateNow) + : threshold; + var timeOriginIsReliable = timeOriginDelta < threshold; + // 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 + var navigationStart = performance.timing && performance.timing.navigationStart; + var hasNavigationStart = typeof navigationStart === 'number'; + // if navigationStart isn't available set delta to threshold so it isn't used + var navigationStartDelta = hasNavigationStart ? Math.abs(navigationStart + performanceNow - dateNow) : threshold; + var navigationStartIsReliable = navigationStartDelta < threshold; + if (timeOriginIsReliable || navigationStartIsReliable) { + // Use the more reliable time origin + if (timeOriginDelta <= navigationStartDelta) { + exports._browserPerformanceTimeOriginMode = 'timeOrigin'; + return performance.timeOrigin; + } + else { + exports._browserPerformanceTimeOriginMode = 'navigationStart'; + return navigationStart; } } - - 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; -}; - + // Either both timeOrigin and navigationStart are skewed or neither is available, fallback to Date. + exports._browserPerformanceTimeOriginMode = 'dateNow'; + return dateNow; +})(); +//# sourceMappingURL=time.js.map /***/ }), -/***/ 75604: -/***/ ((__unused_webpack_module, exports) => { +/***/ 97425: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "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() - }; -}; - - -/***/ }), +const Url = __nccwpck_require__(57310); -/***/ 83633: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +const Errors = __nccwpck_require__(91594); -"use strict"; -/*! - * accepts - * Copyright(c) 2014 Jonathan Ong - * Copyright(c) 2015 Douglas Christopher Wilson - * MIT Licensed - */ +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$ +}; -/** - * Module dependencies. - * @private - */ +exports.analyze = function (domain, options = {}) { -var Negotiator = __nccwpck_require__(95385) -var mime = __nccwpck_require__(43583) + if (!domain) { // Catch null / undefined + return Errors.code('DOMAIN_NON_EMPTY_STRING'); + } -/** - * Module exports. - * @public - */ + if (typeof domain !== 'string') { + throw new Error('Invalid input: domain must be a string'); + } -module.exports = Accepts + if (domain.length > 256) { + return Errors.code('DOMAIN_TOO_LONG'); + } -/** - * Create a new Accepts object for the given req. - * - * @param {object} req - * @public - */ + const ascii = !internals.nonAsciiRx.test(domain); + if (!ascii) { + if (options.allowUnicode === false) { // Defaults to true + return Errors.code('DOMAIN_INVALID_UNICODE_CHARS'); + } -function Accepts (req) { - if (!(this instanceof Accepts)) { - return new Accepts(req) - } + domain = domain.normalize('NFC'); + } - this.headers = req.headers - this.negotiator = new Negotiator(req) -} + if (internals.domainControlRx.test(domain)) { + return Errors.code('DOMAIN_INVALID_CHARS'); + } -/** - * 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 - */ + domain = internals.punycode(domain); -Accepts.prototype.type = -Accepts.prototype.types = function (types_) { - var types = types_ + // https://tools.ietf.org/html/rfc1035 section 2.3.1 - // 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] + if (options.allowFullyQualified && + domain[domain.length - 1] === '.') { + + domain = domain.slice(0, -1); } - } - // no types, return all requested types - if (!types || types.length === 0) { - return this.negotiator.mediaTypes() - } + const minDomainSegments = options.minDomainSegments || internals.minDomainSegments; - // no accept header, return first given type - if (!this.headers.accept) { - return types[0] - } + const segments = domain.split('.'); + if (segments.length < minDomainSegments) { + return Errors.code('DOMAIN_SEGMENTS_COUNT'); + } - var mimes = types.map(extToMime) - var accepts = this.negotiator.mediaTypes(mimes.filter(validMime)) - var first = accepts[0] + if (options.maxDomainSegments) { + if (segments.length > options.maxDomainSegments) { + return Errors.code('DOMAIN_SEGMENTS_COUNT_MAX'); + } + } - return first - ? types[mimes.indexOf(first)] - : false -} + 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 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 - */ + return Errors.code('DOMAIN_FORBIDDEN_TLDS'); + } + } -Accepts.prototype.encoding = -Accepts.prototype.encodings = function (encodings_) { - var encodings = encodings_ + for (let i = 0; i < segments.length; ++i) { + const segment = segments[i]; - // 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] + if (!segment.length) { + return Errors.code('DOMAIN_EMPTY_SEGMENT'); + } + + if (segment.length > 63) { + return Errors.code('DOMAIN_LONG_SEGMENT'); + } + + if (i < segments.length - 1) { + if (!internals.domainSegmentRx.test(segment)) { + return Errors.code('DOMAIN_INVALID_CHARS'); + } + } + else { + if (!internals.tldSegmentRx.test(segment)) { + return Errors.code('DOMAIN_INVALID_TLDS_CHARS'); + } + } } - } - // no encodings, return all requested encodings - if (!encodings || encodings.length === 0) { - return this.negotiator.encodings() - } + return null; +}; - 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 - */ +exports.isValid = function (domain, options) { -Accepts.prototype.charset = -Accepts.prototype.charsets = function (charsets_) { - var charsets = charsets_ + return !exports.analyze(domain, options); +}; - // 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] + +internals.punycode = function (domain) { + + if (domain.includes('%')) { + domain = domain.replace(/%/g, '%25'); } - } - // no charsets, return all requested charsets - if (!charsets || charsets.length === 0) { - return this.negotiator.charsets() - } + try { + return new internals.URL(`http://${domain}`).host; + } + catch (err) { + return domain; + } +}; - 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_ +/***/ 3283: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // 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] - } - } +"use strict"; - // no languages, return all requested languages - if (!languages || languages.length === 0) { - return this.negotiator.languages() - } - return this.negotiator.languages(languages)[0] || false -} +const Util = __nccwpck_require__(73837); -/** - * Convert extnames to mime. - * - * @param {String} type - * @return {String} - * @private - */ +const Domain = __nccwpck_require__(97425); +const Errors = __nccwpck_require__(91594); -function extToMime (type) { - return type.indexOf('/') === -1 - ? mime.lookup(type) - : type -} -/** - * Check if mime is valid. - * - * @param {String} type - * @return {String} - * @private - */ +const internals = { + nonAsciiRx: /[^\x00-\x7f]/, + encoder: new (Util.TextEncoder || TextEncoder)() // $lab:coverage:ignore$ +}; -function validMime (type) { - return typeof type === 'string' -} +exports.analyze = function (email, options) { -/***/ }), + return internals.email(email, options); +}; -/***/ 49690: -/***/ (function(module, __unused_webpack_exports, __nccwpck_require__) { -"use strict"; +exports.isValid = function (email, options) { -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; + return !internals.email(email, options); }; -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()`'); + + +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'); } - /** - * 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); + + 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'); + } + + 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'); + } + } + + // 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'); + } + + if (ascii) { + if (!internals.atextRx.test(segment)) { + return Errors.code('INVALID_LOCAL_CHARS'); } - try { - debug('Resolving socket for %o request: %o', opts.protocol, `${req.method} ${req.path}`); - Promise.resolve(this.promisifiedCallback(req, opts)).then(onsocket, callbackError); + + continue; + } + + for (const char of segment) { + if (internals.atextRx.test(char)) { + continue; } - catch (err) { - Promise.reject(err).catch(callbackError); + + const binary = internals.binary(char); + if (!internals.atomRx.test(binary)) { + return Errors.code('INVALID_LOCAL_CHARS'); } } - 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 +}; + + +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('|')); + /***/ }), -/***/ 66570: +/***/ 91594: /***/ ((__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); - } - }); - }); - }; -} -exports["default"] = promisify; -//# sourceMappingURL=promisify.js.map + +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] }; +}; + /***/ }), -/***/ 61231: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 82337: +/***/ ((__unused_webpack_module, 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, ''); +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]; + } + + 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'); + } + + versions = Array.from(new Set(versions)); + + // Regex + + const parts = versions.map((version) => { + + // Forbidden + + if (cidr === 'forbidden') { + return Uri.ip[version]; + } + + // Required + + const cidrpart = `\\/${version === 'ipv4' ? Uri.ip.v4Cidr : Uri.ip.v6Cidr}`; + + if (cidr === 'required') { + return `${Uri.ip[version]}${cidrpart}`; + } + + // Optional + + return `${Uri.ip[version]}(?:${cidrpart})?`; + }); + + const raw = `(?:${parts.join('|')})`; + const regex = new RegExp(`^${raw}$`); + return { cidr, versions, regex, raw }; +}; + + +/***/ }), + +/***/ 53092: +/***/ ((module) => { + +"use strict"; -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; - } +const internals = {}; - 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); - }); +// http://data.iana.org/TLD/tlds-alpha-by-domain.txt +// # Version 2021020700, Last Updated Sun Feb 7 07: 07: 01 2021 UTC - 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'; +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' +]; - Object.defineProperty(this, '_errors', {value: errors}); - } - * [Symbol.iterator]() { - for (const error of this._errors) { - yield error; - } - } -} +// Keep as upper-case to make updating from source easier -module.exports = AggregateError; +module.exports = new Set(internals.tlds.map((tld) => tld.toLowerCase())); /***/ }), -/***/ 65063: -/***/ ((module) => { +/***/ 74983: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "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('|'); +const Assert = __nccwpck_require__(32718); +const EscapeRegex = __nccwpck_require__(91965); - return new RegExp(pattern, onlyFirst ? undefined : 'g'); -}; +const internals = {}; -/***/ }), -/***/ 62003: -/***/ ((module) => { +internals.generate = function () { -"use strict"; + const rfc3986 = {}; + const hexDigit = '\\dA-Fa-f'; // HEXDIG = DIGIT / "A" / "B" / "C" / "D" / "E" / "F" + const hexDigitOnly = '[' + hexDigit + ']'; -/** - * Expose `arrayFlatten`. - */ -module.exports = arrayFlatten + 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 -/** - * Recursive flatten function with depth. - * - * @param {Array} array - * @param {Array} result - * @param {Number} depth - * @return {Array} - */ -function flattenWithDepth (array, result, depth) { - for (var i = 0; i < array.length; i++) { - var value = array[i] + rfc3986.ipv4address = '(?:' + decOctect + '\\.){3}' + decOctect; // IPv4address = dec-octet "." dec-octet "." dec-octet "." dec-octet - if (depth > 0 && Array.isArray(value)) { - flattenWithDepth(value, result, depth - 1) - } else { - result.push(value) - } - } + /* + 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 ] "::" + */ - return result -} + 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 + ')?::'; -/** - * Recursive flatten function. Omitting depth is slightly faster. - * - * @param {Array} array - * @param {Array} result - * @return {Array} - */ -function flattenForever (array, result) { - for (var i = 0; i < array.length; i++) { - var value = array[i] + 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 / ":" ) - if (Array.isArray(value)) { - flattenForever(value, result) - } else { - result.push(value) - } - } + rfc3986.scheme = '[a-zA-Z][a-zA-Z\\d+-\\.]*'; // scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) + rfc3986.schemeRegex = new RegExp(rfc3986.scheme); - return result -} + 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 + ')?'; -/** - * Flatten an array, with the ability to define a depth. - * - * @param {Array} array - * @param {Number} depth - * @return {Array} - */ -function arrayFlatten (array, depth) { - if (depth == null) { - return flattenForever(array, []) - } + /* + 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 ) + */ - return flattenWithDepth(array, [], depth) -} + 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 + ')'; -/***/ 86950: -/***/ ((module) => { + // relative-part = "//" authority path-abempty / path-absolute / path-noscheme / path-empty -"use strict"; + rfc3986.relativeRef = '(?:' + '(?:\\/\\/' + authority + pathAbEmpty + ')' + '|' + pathAbsolute + '|' + pathNoScheme + '|' + pathEmpty + ')'; + rfc3986.relativeRefCapture = '(?:' + '(?:\\/\\/' + authorityCapture + pathAbEmpty + ')' + '|' + pathAbsolute + '|' + pathNoScheme + '|' + pathEmpty + ')'; + // query = *( pchar / "/" / "?" ) + // query = *( pchar / "[" / "]" / "/" / "?" ) -/* global SharedArrayBuffer, Atomics */ + rfc3986.query = '[' + pchar + '\\/\\?]*(?=#|$)'; //Finish matching either at the fragment part '|' end of the line. + rfc3986.queryWithSquareBrackets = '[' + pchar + '\\[\\]\\/\\?]*(?=#|$)'; -if (typeof SharedArrayBuffer !== 'undefined' && typeof Atomics !== 'undefined') { - const nil = new Int32Array(new SharedArrayBuffer(4)) + // fragment = *( pchar / "/" / "?" ) - 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') - } + rfc3986.fragment = '[' + pchar + '\\/\\?]*'; - Atomics.wait(nil, 0, 0, Number(ms)) - } - module.exports = sleep -} else { + return rfc3986; +}; - 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()){} - } +internals.rfc3986 = internals.generate(); - module.exports = sleep -} +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) { -/***/ 9417: -/***/ ((module) => { + const rfc = internals.rfc3986; -"use strict"; + // Construct expression -module.exports = balanced; -function balanced(a, b, str) { - if (a instanceof RegExp) a = maybeMatch(a, str); - if (b instanceof RegExp) b = maybeMatch(b, str); + const query = options.allowQuerySquareBrackets ? rfc.queryWithSquareBrackets : rfc.query; + const suffix = '(?:\\?' + query + ')?' + '(?:#' + rfc.fragment + ')?'; - var r = range(a, b, str); + // relative-ref = relative-part [ "?" query ] [ "#" fragment ] - return r && { - start: r[0], - end: r[1], - pre: str.slice(0, r[0]), - body: str.slice(r[0] + a.length, r[1]), - post: str.slice(r[1] + b.length) - }; -} + const relative = options.domain ? rfc.relativeRefCapture : rfc.relativeRef; -function maybeMatch(reg, str) { - var m = str.match(reg); - return m ? m[0] : null; -} + if (options.relativeOnly) { + return internals.wrap(relative + suffix); + } + + // 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'); -balanced.range = range; -function range(a, b, str) { - var begs, beg, left, right, result; - var ai = str.indexOf(a); - var bi = str.indexOf(b, ai + 1); - var i = ai; + 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)); + } + } - if (ai >= 0 && bi > 0) { - if(a===b) { - return [ai, bi]; + customScheme = selections.join('|'); } - begs = []; - left = str.length; - while (i >= 0 && !result) { - if (i == ai) { - begs.push(i); - ai = str.indexOf(a, i + 1); - } else if (begs.length == 1) { - result = [ begs.pop(), bi ]; - } else { - beg = begs.pop(); - if (beg < left) { - left = beg; - right = bi; - } + // URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ] - bi = str.indexOf(b, i + 1); - } + 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); +}; - i = ai < bi && ai >= 0 ? ai : bi; - } - if (begs.length) { - result = [ left, right ]; - } - } +internals.wrap = function (raw, scheme) { - return result; -} + 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 + }; +}; -/***/ }), -/***/ 83682: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +internals.uriRegex = internals.createRegex({}); -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) +exports.regex = function (options = {}) { -function bindApi (hook, state, name) { - var removeHookRef = bindable(removeHook, null).apply(null, name ? [state, name] : [state]) - hook.api = { remove: removeHookRef } - hook.remove = removeHookRef + if (options.scheme || + options.allowRelative || + options.relativeOnly || + options.allowQuerySquareBrackets || + options.domain) { - ;['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) - }) -} + return internals.createRegex(options); + } -function HookSingular () { - var singularHookName = 'h' - var singularHookState = { - registry: {} - } - var singularHook = register.bind(null, singularHookState, singularHookName) - bindApi(singularHook, singularHookState, singularHookName) - return singularHook -} + return internals.uriRegex; +}; -function HookCollection () { - var state = { - registry: {} - } - var hook = register.bind(null, state) - bindApi(hook, state) +/***/ }), - return hook -} +/***/ 34379: +/***/ ((__unused_webpack_module, exports) => { -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() -} +"use strict"; -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 +const internals = { + operators: ['!', '^', '*', '/', '%', '+', '-', '<', '<=', '>', '>=', '==', '!=', '&&', '||', '??'], + operatorCharacters: ['!', '^', '*', '/', '%', '+', '-', '<', '=', '>', '&', '|', '?'], + operatorsOrder: [['^'], ['*', '/', '%'], ['+', '-'], ['<', '<=', '>', '>='], ['==', '!='], ['&&'], ['||', '??']], + operatorsPrefix: ['!', 'n'], + literals: { + '"': '"', + '`': '`', + '\'': '\'', + '[': ']' + }, -/***/ }), + numberRx: /^(?:[0-9]*\.?[0-9]*){1}$/, + tokenRx: /^[\w\$\#\.\@\:\{\}]+$/, -/***/ 5549: -/***/ ((module) => { + symbol: Symbol('formula'), + settings: Symbol('settings') +}; -module.exports = addHook; -function addHook(state, kind, name, hook) { - var orig = hook; - if (!state.registry[name]) { - state.registry[name] = []; - } +exports.Parser = class { - if (kind === "before") { - hook = function (method, options) { - return Promise.resolve() - .then(orig.bind(null, options)) - .then(method.bind(null, options)); - }; - } + constructor(string, 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 (!options[internals.settings] && + options.constants) { - if (kind === "error") { - hook = function (method, options) { - return Promise.resolve() - .then(method.bind(null, options)) - .catch(function (error) { - return orig(error, options); - }); - }; - } + for (const constant in options.constants) { + const value = options.constants[constant]; + if (value !== null && + !['boolean', 'number', 'string'].includes(typeof value)) { - state.registry[name].push({ - hook: hook, - orig: orig, - }); -} + throw new Error(`Formula constant ${constant} contains invalid ${typeof value} value type`); + } + } + } + this.settings = options[internals.settings] ? options : Object.assign({ [internals.settings]: true, constants: {}, functions: {} }, options); + this.single = null; -/***/ }), + this._parts = null; + this._parse(string); + } -/***/ 44670: -/***/ ((module) => { + _parse(string) { -module.exports = register; + let parts = []; + let current = ''; + let parenthesis = 0; + let literal = false; -function register(state, name, method, options) { - if (typeof method !== "function") { - throw new Error("method for before hook must be a function"); - } + const flush = (inner) => { - if (!options) { - options = {}; - } + if (parenthesis) { + throw new Error('Formula missing closing parenthesis'); + } - if (Array.isArray(name)) { - return name.reverse().reduce(function (callback, name) { - return register.bind(null, state, name, callback, options); - }, method)(); - } + const last = parts.length ? parts[parts.length - 1] : null; - return Promise.resolve().then(function () { - if (!state.registry[name]) { - return method(options); - } + if (!literal && + !current && + !inner) { - return state.registry[name].reduce(function (method, registered) { - return registered.hook.bind(null, method, options); - }, method)(); - }); -} + 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 -/***/ 6819: -/***/ ((module) => { + 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}`); + } -module.exports = removeHook; + parts.push({ type: 'reference', value: current }); + } -function removeHook(state, name, method) { - if (!state.registry[name]) { - return; - } + current = ''; + }; - var index = state.registry[name] - .map(function (registered) { - return registered.orig; - }) - .indexOf(method); + 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; + } + } + else if (c in internals.literals) { + literal = internals.literals[c]; + } + else if (c === '(') { + flush(); + ++parenthesis; + } + else if (internals.operatorCharacters.includes(c)) { + flush(); + current = c; + flush(); + } + else if (c !== ' ') { + current += c; + } + else { + flush(); + } + } - if (index === -1) { - return; - } + flush(); - state.registry[name].splice(index, 1); -} + // Replace prefix - to internal negative operator + parts = parts.map((part, i) => { -/***/ }), + if (part.type !== 'operator' || + part.value !== '-' || + i && parts[i - 1].type !== 'operator') { -/***/ 97076: -/***/ ((module, exports, __nccwpck_require__) => { + return part; + } -"use strict"; -/*! - * body-parser - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ + 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; + } -/** - * Module dependencies. - * @private - */ + if (!operator) { + throw new Error('Formula contains an operator in invalid position'); + } -var deprecate = __nccwpck_require__(18883)('body-parser') + 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'); + } -/** - * Cache of loaded parsers. - * @private - */ + operator = !operator; + } -var parsers = Object.create(null) + if (!operator) { + throw new Error('Formula contains invalid trailing operator'); + } -/** - * @typedef Parsers - * @type {function} - * @property {function} json - * @property {function} raw - * @property {function} text - * @property {function} urlencoded - */ + // Identify single part -/** - * Module exports. - * @type {Parsers} - */ + if (parts.length === 1 && + ['reference', 'literal', 'constant'].includes(parts[0].type)) { -exports = module.exports = deprecate.function(bodyParser, - 'bodyParser: use individual json/urlencoded middlewares') + this.single = { type: parts[0].type === 'reference' ? 'reference' : 'value', value: parts[0].value }; + } -/** - * JSON parser. - * @public - */ + // Process parts -Object.defineProperty(exports, "json", ({ - configurable: true, - enumerable: true, - get: createParserGetter('json') -})) + this._parts = parts.map((part) => { -/** - * Raw parser. - * @public - */ + // Operators -Object.defineProperty(exports, "raw", ({ - configurable: true, - enumerable: true, - get: createParserGetter('raw') -})) + if (part.type === 'operator') { + return internals.operatorsPrefix.includes(part.value) ? part : part.value; + } -/** - * Text parser. - * @public - */ + // Literals, constants, segments -Object.defineProperty(exports, "text", ({ - configurable: true, - enumerable: true, - get: createParserGetter('text') -})) + if (part.type !== 'reference') { + return part.value; + } -/** - * URL-encoded parser. - * @public - */ + // References -Object.defineProperty(exports, "urlencoded", ({ - configurable: true, - enumerable: true, - get: createParserGetter('urlencoded') -})) + if (this.settings.tokenRx && + !this.settings.tokenRx.test(part.value)) { -/** - * Create a middleware to parse json and urlencoded bodies. - * - * @param {object} [options] - * @return {function} - * @deprecated - * @public - */ + throw new Error(`Formula contains invalid reference ${part.value}`); + } -function bodyParser (options) { - var opts = {} + if (this.settings.reference) { + return this.settings.reference(part.value); + } - // exclude type option - if (options) { - for (var prop in options) { - if (prop !== 'type') { - opts[prop] = options[prop] - } + return internals.reference(part.value); + }); } - } - var _urlencoded = exports.urlencoded(opts) - var _json = exports.json(opts) + _subFormula(string, name) { - return function bodyParser (req, res, next) { - _json(req, res, function (err) { - if (err) return next(err) - _urlencoded(req, res, next) - }) - } -} + const method = this.settings.functions[name]; + if (typeof method !== 'function') { + throw new Error(`Formula contains unknown function ${name}`); + } + + let args = []; + if (string) { + let current = ''; + let parenthesis = 0; + let literal = false; -/** - * Create a getter for loading a parser. - * @private - */ + const flush = () => { -function createParserGetter (name) { - return function get () { - return loadParser(name) - } -} + if (!current) { + throw new Error(`Formula contains function ${name} with invalid arguments ${string}`); + } -/** - * Load a parser module. - * @private - */ + args.push(current); + current = ''; + }; -function loadParser (parserName) { - var parser = parsers[parserName] + 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) { - if (parser !== undefined) { - return parser - } + current += c; + literal = internals.literals[c]; + } + else if (c === ',' && + !parenthesis) { - // 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 - } + flush(); + } + else { + current += c; + if (c === '(') { + ++parenthesis; + } + else if (c === ')') { + --parenthesis; + } + } + } - // store to prevent invoking require() - return (parsers[parserName] = parser) -} + flush(); + } + args = args.map((arg) => new exports.Parser(arg, this.settings)); -/***/ }), + return function (context) { -/***/ 88862: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + const innerValues = []; + for (const arg of args) { + innerValues.push(arg.evaluate(context)); + } -"use strict"; -/*! - * body-parser - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ + return method.call(context, ...innerValues); + }; + } + evaluate(context) { + const parts = this._parts.slice(); -/** - * Module dependencies. - * @private - */ + // Prefix operators -var createError = __nccwpck_require__(95193) -var getBody = __nccwpck_require__(47742) -var iconv = __nccwpck_require__(19032) -var onFinished = __nccwpck_require__(24694) -var zlib = __nccwpck_require__(59796) + for (let i = parts.length - 2; i >= 0; --i) { + const part = parts[i]; + if (part && + part.type === 'operator') { -/** - * Module exports. - */ + const current = parts[i + 1]; + parts.splice(i + 1, 1); + const value = internals.evaluate(current, context); + parts[i] = internals.single(part.value, value); + } + } -module.exports = read + // Left-right operators -/** - * 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 - */ + internals.operatorsOrder.forEach((set) => { -function read (req, res, next, parse, debug, options) { - var length - var opts = options - var stream + 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); - // flag as parsed - req._body = true + parts.splice(i, 2); + const result = internals.calculate(operator, left, right); + parts[i - 1] = result === 0 ? 0 : result; // Convert -0 + } + else { + i += 2; + } + } + }); - // read options - var encoding = opts.encoding !== null - ? opts.encoding - : null - var verify = opts.verify + return internals.evaluate(parts[0], context); + } +}; - 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 +exports.Parser.prototype[internals.symbol] = true; - // 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 +internals.reference = function (name) { - 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 function (context) { - // read off entire request - stream.resume() - onFinished(req, function onfinished () { - next(createError(400, _error)) - }) - return - } + return context && context[name] !== undefined ? context[name] : null; + }; +}; - // 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 +internals.evaluate = function (part, context) { + + if (part === null) { + return null; } - next() - }) -} + if (typeof part === 'function') { + return part(context); + } -/** - * Get the content stream of the request. - * - * @param {object} req - * @param {function} debug - * @param {boolean} [inflate=true] - * @return {object} - * @api private - */ + if (part[internals.symbol]) { + return part.evaluate(context); + } -function contentstream (req, debug, inflate) { - var encoding = (req.headers['content-encoding'] || 'identity').toLowerCase() - var length = req.headers['content-length'] - var stream + return part; +}; - debug('content-encoding "%s"', encoding) - if (inflate === false && encoding !== 'identity') { - throw createError(415, 'content encoding unsupported', { - encoding: encoding, - type: 'encoding.unsupported' - }) - } +internals.single = function (operator, value) { - 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' - }) - } + if (operator === '!') { + return value ? false : true; + } - return stream -} + // operator === 'n' + const negative = -value; + if (negative === 0) { // Override -0 + return 0; + } -/***/ }), + return negative; +}; -/***/ 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 - */ +internals.calculate = function (operator, left, right) { + if (operator === '??') { + return internals.exists(left) ? left : right; + } + if (typeof left === 'string' || + typeof right === 'string') { -/** - * Module dependencies. - * @private - */ + if (operator === '+') { + left = internals.exists(left) ? left : ''; + right = internals.exists(right) ? right : ''; + return left + right; + } + } + 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; + } + } -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) + 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; + } -/** - * Module exports. - */ + return null; +}; -module.exports = json -/** - * 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 - */ +internals.exists = function (value) { -var FIRST_CHAR_REGEXP = /^[\x20\x09\x0a\x0d]*(.)/ // eslint-disable-line no-control-regex + return value !== null && value !== undefined; +}; -/** - * 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 +/***/ 75604: +/***/ ((__unused_webpack_module, exports) => { - if (verify !== false && typeof verify !== 'function') { - throw new TypeError('option verify must be function') - } +"use strict"; - // 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 {} - } +const internals = {}; - if (strict) { - var first = firstchar(body) - if (first !== '{' && first !== '[') { - debug('strict violation') - throw createStrictSyntaxError(body, first) - } - } +exports.location = function (depth = 0) { - try { - debug('parse json') - return JSON.parse(body, reviver) - } catch (e) { - throw normalizeJsonSyntaxError(e, { - message: e.message, - stack: e.stack - }) - } - } + const orig = Error.prepareStackTrace; + Error.prepareStackTrace = (ignore, stack) => stack; - return function jsonParser (req, res, next) { - if (req._body) { - debug('body already parsed') - next() - return - } + const capture = {}; + Error.captureStackTrace(capture, this); + const line = capture.stack[depth + 1]; - req.body = req.body || {} + Error.prepareStackTrace = orig; - // skip requests without bodies - if (!typeis.hasBody(req)) { - debug('skip empty body') - next() - return - } + return { + filename: line.getFileName(), + line: line.getLineNumber() + }; +}; - debug('content-type %j', req.headers['content-type']) - // determine if request should be parsed - if (!shouldParse(req)) { - debug('skip parsing') - next() - return - } +/***/ }), + +/***/ 83633: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; +/*! + * accepts + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ - // 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 - } - // read - read(req, res, next, parse, debug, { - encoding: charset, - inflate: inflate, - limit: limit, - verify: verify - }) - } -} /** - * Create strict violation syntax error matching native error. - * - * @param {string} str - * @param {string} char - * @return {Error} + * Module dependencies. * @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 - }) - } -} +var Negotiator = __nccwpck_require__(95385) +var mime = __nccwpck_require__(43583) /** - * Get the first non-whitespace character in a string. - * - * @param {string} str - * @return {function} - * @private + * Module exports. + * @public */ -function firstchar (str) { - return FIRST_CHAR_REGEXP.exec(str)[1] -} +module.exports = Accepts /** - * Get the charset of a request. + * Create a new Accepts object for the given req. * * @param {object} req - * @api private + * @public */ -function getCharset (req) { - try { - return (contentType.parse(req).parameters.charset || '').toLowerCase() - } catch (e) { - return undefined +function Accepts (req) { + if (!(this instanceof Accepts)) { + return new Accepts(req) } + + this.headers = req.headers + this.negotiator = new Negotiator(req) } /** - * Normalize a SyntaxError for JSON.parse. + * 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". * - * @param {SyntaxError} error - * @param {object} obj - * @return {SyntaxError} + * 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 */ -function normalizeJsonSyntaxError (error, obj) { - var keys = Object.getOwnPropertyNames(error) +Accepts.prototype.type = +Accepts.prototype.types = function (types_) { + var types = types_ - for (var i = 0; i < keys.length; i++) { - var key = keys[i] - if (key !== 'stack' && key !== 'message') { - delete error[key] + // 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] } } - // replace stack before message for Node.js 0.10 and below - error.stack = obj.stack.replace(error.message, obj.message) - error.message = obj.message + // no types, return all requested types + if (!types || types.length === 0) { + return this.negotiator.mediaTypes() + } - return error + // 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 } /** - * Get the simple type checker. + * Return accepted encodings or best fit based on `encodings`. * - * @param {string} type - * @return {function} + * Given `Accept-Encoding: gzip, deflate` + * an array sorted by quality is returned: + * + * ['gzip', 'deflate'] + * + * @param {String|Array} encodings... + * @return {String|Array} + * @public */ -function typeChecker (type) { - return function checkType (req) { - return Boolean(typeis(req, type)) - } -} - - -/***/ }), - -/***/ 49609: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +Accepts.prototype.encoding = +Accepts.prototype.encodings = function (encodings_) { + var encodings = encodings_ -"use strict"; -/*! - * body-parser - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ + // 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 +} /** - * Module dependencies. + * 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 */ -var bytes = __nccwpck_require__(86966) -var debug = __nccwpck_require__(7471)('body-parser:raw') -var read = __nccwpck_require__(88862) -var typeis = __nccwpck_require__(71159) +Accepts.prototype.charset = +Accepts.prototype.charsets = function (charsets_) { + var charsets = charsets_ -/** - * Module exports. - */ + // 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] + } + } -module.exports = raw + // no charsets, return all requested charsets + if (!charsets || charsets.length === 0) { + return this.negotiator.charsets() + } + + return this.negotiator.charsets(charsets)[0] || false +} /** - * Create a middleware to parse raw bodies. + * Return accepted languages or best fit based on `langs`. * - * @param {object} [options] - * @return {function} - * @api public + * 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 */ -function raw (options) { - var opts = options || {} +Accepts.prototype.lang = +Accepts.prototype.langs = +Accepts.prototype.language = +Accepts.prototype.languages = function (languages_) { + var languages = languages_ - 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 + // 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] + } + } - if (verify !== false && typeof verify !== 'function') { - throw new TypeError('option verify must be function') + // no languages, return all requested languages + if (!languages || languages.length === 0) { + return this.negotiator.languages() } - // create the appropriate type checking function - var shouldParse = typeof type !== 'function' - ? typeChecker(type) + return this.negotiator.languages(languages)[0] || false +} + +/** + * Convert extnames to mime. + * + * @param {String} type + * @return {String} + * @private + */ + +function extToMime (type) { + return type.indexOf('/') === -1 + ? mime.lookup(type) : type +} - function parse (buf) { - return buf - } +/** + * Check if mime is valid. + * + * @param {String} type + * @return {String} + * @private + */ - return function rawParser (req, res, next) { - if (req._body) { - debug('body already parsed') - next() - return - } +function validMime (type) { + return typeof type === 'string' +} - 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']) +/***/ 49690: +/***/ (function(module, __unused_webpack_exports, __nccwpck_require__) { - // determine if request should be parsed - if (!shouldParse(req)) { - debug('skip parsing') - next() - return - } +"use strict"; - // read - read(req, res, next, parse, debug, { - encoding: null, - inflate: inflate, - limit: limit, - verify: verify - }) - } +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 -/** - * Get the simple type checker. - * - * @param {string} type - * @return {function} - */ +/***/ }), -function typeChecker (type) { - return function checkType (req) { - return Boolean(typeis(req, type)) - } +/***/ 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); + } + }); + }); + }; } - +exports["default"] = promisify; +//# sourceMappingURL=promisify.js.map /***/ }), -/***/ 26382: +/***/ 61231: /***/ ((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 contentType = __nccwpck_require__(99915) -var debug = __nccwpck_require__(7471)('body-parser:text') -var read = __nccwpck_require__(88862) -var typeis = __nccwpck_require__(71159) - -/** - * Module exports. - */ -module.exports = text +const indentString = __nccwpck_require__(98043); +const cleanStack = __nccwpck_require__(27972); -/** - * Create a middleware to parse text bodies. - * - * @param {object} [options] - * @return {function} - * @api public - */ +const cleanInternalStack = stack => stack.replace(/\s+at .*aggregate-error\/index.js:\d+:\d+\)?/g, ''); -function text (options) { - var opts = options || {} +class AggregateError extends Error { + constructor(errors) { + if (!Array.isArray(errors)) { + throw new TypeError(`Expected input to be an Array, got ${typeof errors}`); + } - 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 + errors = [...errors].map(error => { + if (error instanceof Error) { + return error; + } - if (verify !== false && typeof verify !== 'function') { - throw new TypeError('option verify must be function') - } + 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); + } - // create the appropriate type checking function - var shouldParse = typeof type !== 'function' - ? typeChecker(type) - : type + return new Error(error); + }); - function parse (buf) { - return buf - } + 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); - return function textParser (req, res, next) { - if (req._body) { - debug('body already parsed') - next() - return - } + this.name = 'AggregateError'; - req.body = req.body || {} + Object.defineProperty(this, '_errors', {value: errors}); + } - // skip requests without bodies - if (!typeis.hasBody(req)) { - debug('skip empty body') - next() - return - } + * [Symbol.iterator]() { + for (const error of this._errors) { + yield error; + } + } +} - debug('content-type %j', req.headers['content-type']) +module.exports = AggregateError; - // 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 - }) - } -} +/***/ 65063: +/***/ ((module) => { -/** - * Get the charset of a request. - * - * @param {object} req - * @api private - */ +"use strict"; -function getCharset (req) { - try { - return (contentType.parse(req).parameters.charset || '').toLowerCase() - } catch (e) { - return undefined - } -} -/** - * Get the simple type checker. - * - * @param {string} type - * @return {function} - */ +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('|'); -function typeChecker (type) { - return function checkType (req) { - return Boolean(typeis(req, type)) - } -} + return new RegExp(pattern, onlyFirst ? undefined : 'g'); +}; /***/ }), -/***/ 76100: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 62003: +/***/ ((module) => { "use strict"; -/*! - * body-parser - * Copyright(c) 2014 Jonathan Ong - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ - /** - * Module dependencies. - * @private + * Expose `arrayFlatten`. */ - -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) +module.exports = arrayFlatten /** - * Module exports. + * Recursive flatten function with depth. + * + * @param {Array} array + * @param {Array} result + * @param {Number} depth + * @return {Array} */ +function flattenWithDepth (array, result, depth) { + for (var i = 0; i < array.length; i++) { + var value = array[i] -module.exports = urlencoded + if (depth > 0 && Array.isArray(value)) { + flattenWithDepth(value, result, depth - 1) + } else { + result.push(value) + } + } + + return result +} /** - * Cache of parser modules. + * Recursive flatten function. Omitting depth is slightly faster. + * + * @param {Array} array + * @param {Array} result + * @return {Array} */ +function flattenForever (array, result) { + for (var i = 0; i < array.length; i++) { + var value = array[i] -var parsers = Object.create(null) + if (Array.isArray(value)) { + flattenForever(value, result) + } else { + result.push(value) + } + } + + return result +} /** - * Create a middleware to parse urlencoded bodies. + * Flatten an array, with the ability to define a depth. * - * @param {object} [options] - * @return {function} - * @public + * @param {Array} array + * @param {Number} depth + * @return {Array} */ - -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') +function arrayFlatten (array, depth) { + if (depth == null) { + return flattenForever(array, []) } - 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 + return flattenWithDepth(array, [], depth) +} - 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) +/***/ }), + +/***/ 86950: +/***/ ((module) => { - // create the appropriate type checking function - var shouldParse = typeof type !== 'function' - ? typeChecker(type) - : type +"use strict"; - function parse (body) { - return body.length - ? queryparse(body) - : {} - } - return function urlencodedParser (req, res, next) { - if (req._body) { - debug('body already parsed') - next() - return - } +/* global SharedArrayBuffer, Atomics */ - req.body = req.body || {} +if (typeof SharedArrayBuffer !== 'undefined' && typeof Atomics !== 'undefined') { + const nil = new Int32Array(new SharedArrayBuffer(4)) - // skip requests without bodies - if (!typeis.hasBody(req)) { - debug('skip empty body') - next() - return + 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') } - debug('content-type %j', req.headers['content-type']) + Atomics.wait(nil, 0, 0, Number(ms)) + } + module.exports = sleep +} else { - // determine if request should be parsed - if (!shouldParse(req)) { - debug('skip parsing') - next() - return + 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()){} + } - // 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 - } + module.exports = sleep - // read - read(req, res, next, parse, debug, { - debug: debug, - encoding: charset, - inflate: inflate, - limit: limit, - verify: verify - }) - } } -/** - * Get the extended query parser. - * - * @param {object} options - */ -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') - } +/***/ 9417: +/***/ ((module) => { - if (isFinite(parameterLimit)) { - parameterLimit = parameterLimit | 0 - } +"use strict"; - return function queryparse (body) { - var paramCount = parameterCount(body, parameterLimit) +module.exports = balanced; +function balanced(a, b, str) { + if (a instanceof RegExp) a = maybeMatch(a, str); + if (b instanceof RegExp) b = maybeMatch(b, str); - if (paramCount === undefined) { - debug('too many parameters') - throw createError(413, 'too many parameters', { - type: 'parameters.too.many' - }) - } + var r = range(a, b, str); - var arrayLimit = Math.max(100, paramCount) + return r && { + start: r[0], + end: r[1], + pre: str.slice(0, r[0]), + body: str.slice(r[0] + a.length, r[1]), + post: str.slice(r[1] + b.length) + }; +} - debug('parse extended urlencoding') - return parse(body, { - allowPrototypes: true, - arrayLimit: arrayLimit, - depth: Infinity, - parameterLimit: parameterLimit - }) - } +function maybeMatch(reg, str) { + var m = str.match(reg); + return m ? m[0] : null; } -/** - * Get the charset of a request. - * - * @param {object} req - * @api private - */ +balanced.range = range; +function range(a, b, str) { + var begs, beg, left, right, result; + var ai = str.indexOf(a); + var bi = str.indexOf(b, ai + 1); + var i = ai; -function getCharset (req) { - try { - return (contentType.parse(req).parameters.charset || '').toLowerCase() - } catch (e) { - return undefined - } -} + if (ai >= 0 && bi > 0) { + if(a===b) { + return [ai, bi]; + } + begs = []; + left = str.length; -/** - * Count the number of parameters, stopping once limit reached - * - * @param {string} body - * @param {number} limit - * @api private - */ + while (i >= 0 && !result) { + if (i == ai) { + begs.push(i); + ai = str.indexOf(a, i + 1); + } else if (begs.length == 1) { + result = [ begs.pop(), bi ]; + } else { + beg = begs.pop(); + if (beg < left) { + left = beg; + right = bi; + } -function parameterCount (body, limit) { - var count = 0 - var index = 0 + bi = str.indexOf(b, i + 1); + } - while ((index = body.indexOf('&', index)) !== -1) { - count++ - index++ + i = ai < bi && ai >= 0 ? ai : bi; + } - if (count === limit) { - return undefined + if (begs.length) { + result = [ left, right ]; } } - return count + return result; } -/** - * 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 - } +/***/ 83682: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // store to prevent invoking require() - parsers[name] = mod +var register = __nccwpck_require__(44670) +var addHook = __nccwpck_require__(5549) +var removeHook = __nccwpck_require__(6819) - return mod.parse -} +// bind with array of arguments: https://stackoverflow.com/a/21792913 +var bind = Function.bind +var bindable = bind.bind(bind) -/** - * Get the simple query parser. - * - * @param {object} options - */ +function bindApi (hook, state, name) { + var removeHookRef = bindable(removeHook, null).apply(null, name ? [state, name] : [state]) + hook.api = { remove: removeHookRef } + hook.remove = removeHookRef -function simpleparser (options) { - var parameterLimit = options.parameterLimit !== undefined - ? options.parameterLimit - : 1000 - var parse = parser('querystring') + ;['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) + }) +} - if (isNaN(parameterLimit) || parameterLimit < 1) { - throw new TypeError('option parameterLimit must be a positive number') +function HookSingular () { + var singularHookName = 'h' + var singularHookState = { + registry: {} } - - if (isFinite(parameterLimit)) { - parameterLimit = parameterLimit | 0 + var singularHook = register.bind(null, singularHookState, singularHookName) + bindApi(singularHook, singularHookState, singularHookName) + return singularHook +} + +function HookCollection () { + var state = { + registry: {} } - return function queryparse (body) { - var paramCount = parameterCount(body, parameterLimit) + var hook = register.bind(null, state) + bindApi(hook, state) - if (paramCount === undefined) { - debug('too many parameters') - throw createError(413, 'too many parameters', { - type: 'parameters.too.many' - }) - } + return hook +} - debug('parse urlencoding') - return parse(body, undefined, undefined, { maxKeys: parameterLimit }) +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() } -/** - * Get the simple type checker. - * - * @param {string} type - * @return {function} - */ +Hook.Singular = HookSingular.bind() +Hook.Collection = HookCollection.bind() -function typeChecker (type) { - return function checkType (req) { - return Boolean(typeis(req, type)) - } -} +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 /***/ }), -/***/ 15377: -/***/ ((module, exports, __nccwpck_require__) => { - -/** - * This is the web browser implementation of `debug()`. - * - * Expose `debug()` as the module. - */ +/***/ 5549: +/***/ ((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(); +module.exports = addHook; -/** - * Colors. - */ +function addHook(state, kind, name, hook) { + var orig = hook; + if (!state.registry[name]) { + state.registry[name] = []; + } -exports.colors = [ - 'lightseagreen', - 'forestgreen', - 'goldenrod', - 'dodgerblue', - 'darkorchid', - 'crimson' -]; + if (kind === "before") { + hook = function (method, options) { + return Promise.resolve() + .then(orig.bind(null, options)) + .then(method.bind(null, options)); + }; + } -/** - * Currently only WebKit-based Web Inspectors, Firefox >= v31, - * and the Firebug extension (any Firefox version) are known - * to support "%c" CSS customizations. - * - * TODO: add a `localStorage` variable to explicitly enable/disable colors - */ + if (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; + }); + }; + } -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 (kind === "error") { + hook = function (method, options) { + return Promise.resolve() + .then(method.bind(null, options)) + .catch(function (error) { + return orig(error, options); + }); + }; } - // 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+)/)); + state.registry[name].push({ + hook: hook, + orig: orig, + }); } -/** - * 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 - */ +/***/ 44670: +/***/ ((module) => { -function formatArgs(args) { - var useColors = this.useColors; +module.exports = register; - args[0] = (useColors ? '%c' : '') - + this.namespace - + (useColors ? ' %c' : ' ') - + args[0] - + (useColors ? '%c ' : ' ') - + '+' + exports.humanize(this.diff); +function register(state, name, method, options) { + if (typeof method !== "function") { + throw new Error("method for before hook must be a function"); + } - if (!useColors) return; + if (!options) { + options = {}; + } - var c = 'color: ' + this.color; - args.splice(1, 0, c, 'color: inherit') + if (Array.isArray(name)) { + return name.reverse().reduce(function (callback, name) { + return register.bind(null, state, name, callback, options); + }, method)(); + } - // 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; + return Promise.resolve().then(function () { + if (!state.registry[name]) { + return method(options); } - }); - - 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; - } - } catch(e) {} + return state.registry[name].reduce(function (method, registered) { + return registered.hook.bind(null, method, options); + }, method)(); + }); } -/** - * 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; -} +/***/ 6819: +/***/ ((module) => { -/** - * Enable namespaces listed in `localStorage.debug` initially. - */ +module.exports = removeHook; -exports.enable(load()); +function removeHook(state, name, method) { + if (!state.registry[name]) { + return; + } -/** - * 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 - */ + var index = state.registry[name] + .map(function (registered) { + return registered.orig; + }) + .indexOf(method); -function localstorage() { - try { - return window.localStorage; - } catch (e) {} + if (index === -1) { + return; + } + + state.registry[name].splice(index, 1); } /***/ }), -/***/ 22552: +/***/ 97076: /***/ ((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. +"use strict"; +/*! + * body-parser + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed */ -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); + /** - * The currently active debug mode names, and names to skip. + * Module dependencies. + * @private */ -exports.names = []; -exports.skips = []; +var deprecate = __nccwpck_require__(18883)('body-parser') /** - * 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". + * Cache of loaded parsers. + * @private */ -exports.formatters = {}; +var parsers = Object.create(null) /** - * Previous log timestamp. + * @typedef Parsers + * @type {function} + * @property {function} json + * @property {function} raw + * @property {function} text + * @property {function} urlencoded */ -var prevTime; - /** - * Select a color. - * @param {String} namespace - * @return {Number} - * @api private + * Module exports. + * @type {Parsers} */ -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]; -} +exports = module.exports = deprecate.function(bodyParser, + 'bodyParser: use individual json/urlencoded middlewares') /** - * Create a debugger with the given `namespace`. - * - * @param {String} namespace - * @return {Function} - * @api public + * JSON parser. + * @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]; - } - - args[0] = exports.coerce(args[0]); - - if ('string' !== typeof args[0]) { - // anything else let's inspect with %O - args.unshift('%O'); - } - - // apply any `formatters` transformations - var index = 0; - args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) { - // if we encounter an escaped % then don't increase the array index - if (match === '%%') return match; - index++; - var formatter = exports.formatters[format]; - if ('function' === typeof formatter) { - var val = args[index]; - match = formatter.call(self, val); +Object.defineProperty(exports, "json", ({ + configurable: true, + enumerable: true, + get: createParserGetter('json') +})) - // now we need to remove `args[index]` since it's inlined in the `format` - args.splice(index, 1); - index--; - } - return match; - }); +/** + * Raw parser. + * @public + */ - // apply env-specific formatting (colors, etc.) - exports.formatArgs.call(self, args); +Object.defineProperty(exports, "raw", ({ + configurable: true, + enumerable: true, + get: createParserGetter('raw') +})) - var logFn = debug.log || exports.log || console.log.bind(console); - logFn.apply(self, args); - } +/** + * Text parser. + * @public + */ - debug.namespace = namespace; - debug.enabled = exports.enabled(namespace); - debug.useColors = exports.useColors(); - debug.color = selectColor(namespace); +Object.defineProperty(exports, "text", ({ + configurable: true, + enumerable: true, + get: createParserGetter('text') +})) - // env-specific initialization logic for debug instances - if ('function' === typeof exports.init) { - exports.init(debug); - } +/** + * URL-encoded parser. + * @public + */ - return debug; -} +Object.defineProperty(exports, "urlencoded", ({ + configurable: true, + enumerable: true, + get: createParserGetter('urlencoded') +})) /** - * Enables a debug mode by namespaces. This can include modes - * separated by a colon and wildcards. + * Create a middleware to parse json and urlencoded bodies. * - * @param {String} namespaces - * @api public + * @param {object} [options] + * @return {function} + * @deprecated + * @public */ -function enable(namespaces) { - exports.save(namespaces); - - exports.names = []; - exports.skips = []; - - var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); - var len = split.length; +function bodyParser (options) { + var opts = {} - 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 + '$')); + // exclude type option + if (options) { + for (var prop in options) { + if (prop !== 'type') { + opts[prop] = options[prop] + } } } -} -/** - * Disable debug output. - * - * @api public - */ + var _urlencoded = exports.urlencoded(opts) + var _json = exports.json(opts) -function disable() { - exports.enable(''); + return function bodyParser (req, res, next) { + _json(req, res, function (err) { + if (err) return next(err) + _urlencoded(req, res, next) + }) + } } /** - * 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; - } - } - for (i = 0, len = exports.names.length; i < len; i++) { - if (exports.names[i].test(name)) { - return true; - } + * Create a getter for loading a parser. + * @private + */ + +function createParserGetter (name) { + return function get () { + return loadParser(name) } - return false; } /** - * Coerce `val`. - * - * @param {Mixed} val - * @return {Mixed} - * @api private + * Load a parser module. + * @private */ -function coerce(val) { - if (val instanceof Error) return val.stack || val.message; - return val; +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) } /***/ }), -/***/ 7471: +/***/ 88862: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * Detect Electron renderer process, which is node, but we should - * treat as a browser. +"use strict"; +/*! + * body-parser + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed */ -if (typeof process !== 'undefined' && process.type === 'renderer') { - module.exports = __nccwpck_require__(15377); -} else { - module.exports = __nccwpck_require__(74117); -} - - -/***/ }), -/***/ 74117: -/***/ ((module, exports, __nccwpck_require__) => { /** * Module dependencies. + * @private */ -var tty = __nccwpck_require__(76224); -var util = __nccwpck_require__(73837); +var createError = __nccwpck_require__(95193) +var getBody = __nccwpck_require__(47742) +var iconv = __nccwpck_require__(19032) +var onFinished = __nccwpck_require__(24694) +var zlib = __nccwpck_require__(59796) /** - * This is the Node.js implementation of `debug()`. - * - * Expose `debug()` as the module. + * Module exports. */ -exports = module.exports = __nccwpck_require__(22552); -exports.init = init; -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; +module.exports = read /** - * Colors. + * 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 */ -exports.colors = [6, 2, 3, 4, 5, 1]; +function read (req, res, next, parse, debug, options) { + var length + var opts = options + var stream -/** - * Build up the default `inspectOpts` object from the environment variables. - * - * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js - */ + // flag as parsed + req._body = true -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() }); + // read options + var encoding = opts.encoding !== null + ? opts.encoding + : null + var verify = opts.verify - // 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); + try { + // get the content stream + stream = contentstream(req, debug, opts.inflate) + length = stream.length + stream.length = undefined + } catch (err) { + return next(err) + } - obj[prop] = val; - return obj; -}, {}); + // 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 + } + + // 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() + }) +} /** - * The file descriptor to write the `debug()` calls to. - * Set the `DEBUG_FD` env variable to override with another value. i.e.: + * Get the content stream of the request. * - * $ DEBUG_FD=3 node script.js 3>debug.log + * @param {object} req + * @param {function} debug + * @param {boolean} [inflate=true] + * @return {object} + * @api private */ -var fd = parseInt(process.env.DEBUG_FD, 10) || 2; +function contentstream (req, debug, inflate) { + var encoding = (req.headers['content-encoding'] || 'identity').toLowerCase() + var length = req.headers['content-length'] + var stream -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)')() -} + debug('content-encoding "%s"', encoding) -var stream = 1 === fd ? process.stdout : - 2 === fd ? process.stderr : - createWritableStdioStream(fd); + if (inflate === false && encoding !== 'identity') { + throw createError(415, 'content encoding unsupported', { + encoding: encoding, + type: 'encoding.unsupported' + }) + } -/** - * Is stdout a TTY? Colored output is enabled when `true`. - */ + 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' + }) + } -function useColors() { - return 'colors' in exports.inspectOpts - ? Boolean(exports.inspectOpts.colors) - : tty.isatty(fd); + return stream } -/** - * 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); -}; +/***/ 20859: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * Adds ANSI color escape codes if enabled. - * - * @api public +"use strict"; +/*! + * body-parser + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed */ -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]; - } -} /** - * Invokes `util.format()` with the specified arguments and writes to `stream`. + * Module dependencies. + * @private */ -function log() { - return stream.write(util.format.apply(util, arguments) + '\n'); -} +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) /** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private + * Module exports. */ -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; - } -} +module.exports = json /** - * Load `namespaces`. + * RegExp to match the first non-space in a string. * - * @return {String} returns the previously persisted debug modes - * @api private + * Allowed whitespace is defined in RFC 7159: + * + * ws = *( + * %x20 / ; Space + * %x09 / ; Horizontal tab + * %x0A / ; Line feed or New line + * %x0D ) ; Carriage return */ -function load() { - return process.env.DEBUG; -} +var FIRST_CHAR_REGEXP = /^[\x20\x09\x0a\x0d]*(.)/ // eslint-disable-line no-control-regex /** - * Copied from `node/src/node.js`. + * Create a middleware to parse JSON bodies. * - * XXX: It's lame that node doesn't expose this API out-of-the-box. It also - * relies on the undocumented `tty_wrap.guessHandleType()` which is also lame. + * @param {object} [options] + * @return {function} + * @public */ -function createWritableStdioStream (fd) { - var stream; - var tty_wrap = process.binding('tty_wrap'); - - // Note stream._type is used for test-module-load-list.js +function json (options) { + var opts = options || {} - switch (tty_wrap.guessHandleType(fd)) { - case 'TTY': - stream = new tty.WriteStream(fd); - stream._type = 'tty'; + 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 - // Hack to have stream not keep the event loop alive. - // See https://github.com/joyent/node/issues/1726 - if (stream._handle && stream._handle.unref) { - stream._handle.unref(); - } - break; + if (verify !== false && typeof verify !== 'function') { + throw new TypeError('option verify must be function') + } - case 'FILE': - var fs = __nccwpck_require__(57147); - stream = new fs.SyncWriteStream(fd, { autoClose: false }); - stream._type = 'fs'; - break; + // create the appropriate type checking function + var shouldParse = typeof type !== 'function' + ? typeChecker(type) + : type - case 'PIPE': - case 'TCP': - var net = __nccwpck_require__(41808); - stream = new net.Socket({ - fd: fd, - readable: false, - writable: true - }); + 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 {} + } - // FIXME Should probably have an option in net.Socket to create a - // stream from an existing fd which is writable only. But for now - // we'll just add this hack and set the `readable` member to false. - // Test: ./node test/fixtures/echo.js < /etc/passwd - stream.readable = false; - stream.read = null; - stream._type = 'pipe'; + if (strict) { + var first = firstchar(body) - // 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(); + if (first !== '{' && first !== '[') { + debug('strict violation') + throw createStrictSyntaxError(body, first) } - break; + } - default: - // Probably an error on in uv_guess_handle() - throw new Error('Implement me. Unknown stream file type!'); + try { + debug('parse json') + return JSON.parse(body, reviver) + } catch (e) { + throw normalizeJsonSyntaxError(e, { + message: e.message, + stack: e.stack + }) + } } - // For supporting legacy API we put the FD here. - stream.fd = fd; + return function jsonParser (req, res, next) { + if (req._body) { + debug('body already parsed') + next() + return + } - stream._isStdio = true; + req.body = req.body || {} - return stream; -} + // skip requests without bodies + if (!typeis.hasBody(req)) { + debug('skip empty body') + next() + return + } -/** - * Init logic for `debug` instances. - * - * Create a new `inspectOpts` object in case `useColors` is set - * differently for a particular `debug` instance. - */ + debug('content-type %j', req.headers['content-type']) -function init (debug) { - debug.inspectOpts = {}; + // determine if request should be parsed + if (!shouldParse(req)) { + debug('skip parsing') + next() + return + } - var keys = Object.keys(exports.inspectOpts); - for (var i = 0; i < keys.length; i++) { - debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + // 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 + } + + // read + read(req, res, next, parse, debug, { + encoding: charset, + inflate: inflate, + limit: limit, + verify: verify + }) } } /** - * Enable namespaces listed in `process.env.DEBUG` initially. - */ - -exports.enable(load()); - - -/***/ }), - -/***/ 73233: -/***/ ((module) => { - -/** - * Helpers. - */ - -var s = 1000; -var m = s * 60; -var h = m * 60; -var d = h * 24; -var y = d * 365.25; - -/** - * Parse or format the given `val`. - * - * Options: - * - * - `long` verbose formatting [false] + * Create strict violation syntax error matching native error. * - * @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 + * @param {string} str + * @param {string} char + * @return {Error} + * @private */ -module.exports = function(val, options) { - options = options || {}; - var type = typeof val; - if (type === 'string' && val.length > 0) { - return parse(val); - } else if (type === 'number' && isNaN(val) === false) { - return options.long ? fmtLong(val) : fmtShort(val); +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 + }) } - 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. + * Get the first non-whitespace character in a string. * - * @param {String} str - * @return {Number} - * @api private + * @param {string} str + * @return {function} + * @private */ -function parse(str) { - str = String(str); - if (str.length > 100) { - return; - } - var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec( - str - ); - if (!match) { - return; - } - var n = parseFloat(match[1]); - var type = (match[2] || 'ms').toLowerCase(); - switch (type) { - case 'years': - case 'year': - case 'yrs': - case 'yr': - case 'y': - return n * y; - case 'days': - case 'day': - case 'd': - return n * d; - case 'hours': - case 'hour': - case 'hrs': - case 'hr': - case 'h': - return n * h; - case 'minutes': - case 'minute': - case 'mins': - case 'min': - case 'm': - return n * m; - case 'seconds': - case 'second': - case 'secs': - case 'sec': - case 's': - return n * s; - case 'milliseconds': - case 'millisecond': - case 'msecs': - case 'msec': - case 'ms': - return n; - default: - return undefined; - } +function firstchar (str) { + return FIRST_CHAR_REGEXP.exec(str)[1] } /** - * Short format for `ms`. + * Get the charset of a request. * - * @param {Number} ms - * @return {String} + * @param {object} req * @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 getCharset (req) { + try { + return (contentType.parse(req).parameters.charset || '').toLowerCase() + } catch (e) { + return undefined } - return ms + 'ms'; } /** - * Long format for `ms`. + * Normalize a SyntaxError for JSON.parse. * - * @param {Number} ms - * @return {String} - * @api private + * @param {SyntaxError} error + * @param {object} obj + * @return {SyntaxError} */ -function fmtLong(ms) { - return plural(ms, d, 'day') || - plural(ms, h, 'hour') || - plural(ms, m, 'minute') || - plural(ms, s, 'second') || - ms + ' ms'; +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] + } + } + + // 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 } /** - * Pluralization helper. + * Get the simple type checker. + * + * @param {string} type + * @return {function} */ -function plural(ms, n, name) { - if (ms < n) { - return; - } - if (ms < n * 1.5) { - return Math.floor(ms / n) + ' ' + name; +function typeChecker (type) { + return function checkType (req) { + return Boolean(typeis(req, type)) } - return Math.ceil(ms / n) + ' ' + name + 's'; } /***/ }), -/***/ 85442: +/***/ 49609: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; +/*! + * body-parser + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ -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 = []; +/** + * Module dependencies. + */ - this._resetPromise(); +var bytes = __nccwpck_require__(86966) +var debug = __nccwpck_require__(7471)('body-parser:raw') +var read = __nccwpck_require__(88862) +var typeis = __nccwpck_require__(71159) - this._lastFlush = Date.now(); - } +/** + * Module exports. + */ - _resetPromise() { - return this._promise = new this.Promise((res, rej) => { - return this._resolve = res; - }); - } +module.exports = raw - _flush() { - clearTimeout(this._timeout); - this._lastFlush = Date.now(); +/** + * Create a middleware to parse raw bodies. + * + * @param {object} [options] + * @return {function} + * @api public + */ - this._resolve(); +function raw (options) { + var opts = options || {} - this.Events.trigger("batch", this._arr); - this._arr = []; - return this._resetPromise(); - } + 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 - add(data) { - var ret; + if (verify !== false && typeof verify !== 'function') { + throw new TypeError('option verify must be function') + } - this._arr.push(data); + // create the appropriate type checking function + var shouldParse = typeof type !== 'function' + ? typeChecker(type) + : type - ret = this._promise; + function parse (buf) { + return buf + } + + return function rawParser (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 + } - 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); - } + debug('content-type %j', req.headers['content-type']) - return ret; + // determine if request should be parsed + if (!shouldParse(req)) { + debug('skip parsing') + next() + return } + // read + read(req, res, next, parse, debug, { + encoding: null, + inflate: inflate, + limit: limit, + verify: verify + }) } +} - ; - Batcher.prototype.defaults = { - maxTime: null, - maxSize: null, - Promise: Promise - }; - return Batcher; -}.call(void 0); +/** + * Get the simple type checker. + * + * @param {string} type + * @return {function} + */ + +function typeChecker (type) { + return function checkType (req) { + return Boolean(typeis(req, type)) + } +} -module.exports = Batcher; /***/ }), -/***/ 83911: +/***/ 26382: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; +/*! + * body-parser + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ -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(); } +/** + * Module dependencies. + */ -function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } +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) -function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } +/** + * Module exports. + */ -function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } +module.exports = text -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); } } +/** + * Create a middleware to parse text bodies. + * + * @param {object} [options] + * @return {function} + * @api public + */ -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); }); }; } +function text (options) { + var opts = options || {} -var Bottleneck, - DEFAULT_PRIORITY, - Events, - Job, - LocalDatastore, - NUM_PRIORITIES, - Queues, - RedisDatastore, - States, - Sync, - parser, - splice = [].splice; -NUM_PRIORITIES = 10; -DEFAULT_PRIORITY = 5; -parser = __nccwpck_require__(67823); -Queues = __nccwpck_require__(65893); -Job = __nccwpck_require__(25949); -LocalDatastore = __nccwpck_require__(38979); -RedisDatastore = __nccwpck_require__(4946); -Events = __nccwpck_require__(107); -States = __nccwpck_require__(2527); -Sync = __nccwpck_require__(56029); + 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 -Bottleneck = function () { - class Bottleneck { - constructor(options = {}, ...invalid) { - var storeInstanceOptions, storeOptions; - this._addToQueue = this._addToQueue.bind(this); + if (verify !== false && typeof verify !== 'function') { + throw new TypeError('option verify must be function') + } - this._validateOptions(options, invalid); + // create the appropriate type checking function + var shouldParse = typeof type !== 'function' + ? typeChecker(type) + : type - 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, {}); + function parse (buf) { + return buf + } - 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); + return function textParser (req, res, next) { + if (req._body) { + debug('body already parsed') + next() + return + } - this._queues.on("leftzero", () => { - var ref; - return (ref = this._store.heartbeat) != null ? typeof ref.ref === "function" ? ref.ref() : void 0 : void 0; - }); + req.body = req.body || {} - this._queues.on("zero", () => { - var ref; - return (ref = this._store.heartbeat) != null ? typeof ref.unref === "function" ? ref.unref() : void 0 : void 0; - }); + // skip requests without bodies + if (!typeis.hasBody(req)) { + debug('skip empty body') + next() + return } - _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."); - } - } + debug('content-type %j', req.headers['content-type']) - ready() { - return this._store.ready; + // determine if request should be parsed + if (!shouldParse(req)) { + debug('skip parsing') + next() + return } - clients() { - return this._store.clients; - } + // get charset + var charset = getCharset(req) || defaultCharset - channel() { - return `b_${this.id}`; - } + // read + read(req, res, next, parse, debug, { + encoding: charset, + inflate: inflate, + limit: limit, + verify: verify + }) + } +} - channel_client() { - return `b_${this.id}_${this._store.clientId}`; - } +/** + * Get the charset of a request. + * + * @param {object} req + * @api private + */ - publish(message) { - return this._store.__publish__(message); - } +function getCharset (req) { + try { + return (contentType.parse(req).parameters.charset || '').toLowerCase() + } catch (e) { + return undefined + } +} - disconnect(flush = true) { - return this._store.__disconnect__(flush); - } +/** + * Get the simple type checker. + * + * @param {string} type + * @return {function} + */ - chain(_limiter) { - this._limiter = _limiter; - return this; - } +function typeChecker (type) { + return function checkType (req) { + return Boolean(typeis(req, type)) + } +} + + +/***/ }), + +/***/ 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 + */ + + + +/** + * Module dependencies. + * @private + */ + +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) - queued(priority) { - return this._queues.queued(priority); - } +/** + * Module exports. + */ - clusterQueued() { - return this._store.__queued__(); - } +module.exports = urlencoded - empty() { - return this.queued() === 0 && this._submitLock.isEmpty(); - } +/** + * Cache of parser modules. + */ - running() { - return this._store.__running__(); - } +var parsers = Object.create(null) - done() { - return this._store.__done__(); - } +/** + * Create a middleware to parse urlencoded bodies. + * + * @param {object} [options] + * @return {function} + * @public + */ - jobStatus(id) { - return this._states.jobStatus(id); - } +function urlencoded (options) { + var opts = options || {} - jobs(status) { - return this._states.statusJobs(status); - } + // notice because option default will flip in next major + if (opts.extended === undefined) { + deprecate('undefined extended: provide extended option') + } - counts() { - return this._states.statusCounts(); - } + 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 - _randomIndex() { - return Math.random().toString(36).slice(2); - } + if (verify !== false && typeof verify !== 'function') { + throw new TypeError('option verify must be function') + } - check(weight = 1) { - return this._store.__check__(weight); - } + // create the appropriate query parser + var queryparse = extended + ? extendedparser(opts) + : simpleparser(opts) - _clearGlobalState(index) { - if (this._scheduled[index] != null) { - clearTimeout(this._scheduled[index].expiration); - delete this._scheduled[index]; - return true; - } else { - return false; - } - } + // create the appropriate type checking function + var shouldParse = typeof type !== 'function' + ? typeChecker(type) + : type - _free(index, job, options, eventInfo) { - var _this = this; + function parse (body) { + return body.length + ? queryparse(body) + : {} + } - return _asyncToGenerator(function* () { - var e, running; + return function urlencodedParser (req, res, next) { + if (req._body) { + debug('body already parsed') + next() + return + } - try { - var _ref = yield _this._store.__free__(index, options.weight); + req.body = req.body || {} - running = _ref.running; + // skip requests without bodies + if (!typeis.hasBody(req)) { + debug('skip empty body') + next() + return + } - _this.Events.trigger("debug", `Freed ${options.id}`, eventInfo); + debug('content-type %j', req.headers['content-type']) - if (running === 0 && _this.empty()) { - return _this.Events.trigger("idle"); - } - } catch (error1) { - e = error1; - return _this.Events.trigger("error", e); - } - })(); + // determine if request should be parsed + if (!shouldParse(req)) { + debug('skip parsing') + next() + return } - _run(index, job, wait) { - var clearGlobalState, free, run; - job.doRun(); - clearGlobalState = this._clearGlobalState.bind(this, index); - run = this._run.bind(this, index, job); - free = this._free.bind(this, index, job); - return this._scheduled[index] = { - timeout: setTimeout(() => { - return job.doExecute(this._limiter, clearGlobalState, run, free); - }, wait), - expiration: job.options.expiration != null ? setTimeout(function () { - return job.doExpire(clearGlobalState, run, free); - }, wait + job.options.expiration) : void 0, - job: job - }; + // 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 } - _drainOne(capacity) { - return this._registerLock.schedule(() => { - var args, index, next, options, queue; + // read + read(req, res, next, parse, debug, { + debug: debug, + encoding: charset, + inflate: inflate, + limit: limit, + verify: verify + }) + } +} - if (this.queued() === 0) { - return this.Promise.resolve(null); - } +/** + * Get the extended query parser. + * + * @param {object} options + */ - queue = this._queues.getFirst(); +function extendedparser (options) { + var parameterLimit = options.parameterLimit !== undefined + ? options.parameterLimit + : 1000 + var parse = parser('qs') - var _next2 = next = queue.first(); + if (isNaN(parameterLimit) || parameterLimit < 1) { + throw new TypeError('option parameterLimit must be a positive number') + } - options = _next2.options; - args = _next2.args; + if (isFinite(parameterLimit)) { + parameterLimit = parameterLimit | 0 + } - if (capacity != null && options.weight > capacity) { - return this.Promise.resolve(null); - } + return function queryparse (body) { + var paramCount = parameterCount(body, parameterLimit) - 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 (paramCount === undefined) { + debug('too many parameters') + throw createError(413, 'too many parameters', { + type: 'parameters.too.many' + }) + } - if (success) { - queue.shift(); - empty = this.empty(); + var arrayLimit = Math.max(100, paramCount) - if (empty) { - this.Events.trigger("empty"); - } + debug('parse extended urlencoding') + return parse(body, { + allowPrototypes: true, + arrayLimit: arrayLimit, + depth: Infinity, + parameterLimit: parameterLimit + }) + } +} - if (reservoir === 0) { - this.Events.trigger("depleted", empty); - } +/** + * Get the charset of a request. + * + * @param {object} req + * @api private + */ - this._run(index, next, wait); +function getCharset (req) { + try { + return (contentType.parse(req).parameters.charset || '').toLowerCase() + } catch (e) { + return undefined + } +} - return this.Promise.resolve(options.weight); - } else { - return this.Promise.resolve(null); - } - }); - }); - } +/** + * Count the number of parameters, stopping once limit reached + * + * @param {string} body + * @param {number} limit + * @api private + */ - _drainAll(capacity, total = 0) { - return this._drainOne(capacity).then(drained => { - var newCapacity; +function parameterCount (body, limit) { + var count = 0 + var index = 0 - 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); - }); - } + while ((index = body.indexOf('&', index)) !== -1) { + count++ + index++ - _dropAllQueued(message) { - return this._queues.shiftAll(function (job) { - return job.doDrop({ - message - }); - }); + if (count === limit) { + return undefined } + } - stop(options = {}) { - var done, waitForExecuting; - options = parser.load(options, this.stopDefaults); + return count +} - waitForExecuting = at => { - var finished; +/** + * Get parser for module name dynamically. + * + * @param {string} name + * @return {function} + * @api private + */ - finished = () => { - var counts; - counts = this._states.counts; - return counts[0] + counts[1] + counts[2] + counts[3] === at; - }; +function parser (name) { + var mod = parsers[name] - return new this.Promise((resolve, reject) => { - if (finished()) { - return resolve(); - } else { - return this.on("done", () => { - if (finished()) { - this.removeAllListeners("done"); - return resolve(); - } - }); - } - }); - }; + if (mod !== undefined) { + return mod.parse + } - done = options.dropWaitingJobs ? (this._run = function (index, next) { - return next.doDrop({ - message: options.dropErrorMessage - }); - }, this._drainOne = () => { - return this.Promise.resolve(null); - }, this._registerLock.schedule(() => { - return this._submitLock.schedule(() => { - var k, ref, v; - ref = this._scheduled; + // this uses a switch for static require analysis + switch (name) { + case 'qs': + mod = __nccwpck_require__(22760) + break + case 'querystring': + mod = __nccwpck_require__(63477) + break + } - for (k in ref) { - v = ref[k]; + // store to prevent invoking require() + parsers[name] = mod - if (this.jobStatus(v.job.options.id) === "RUNNING") { - clearTimeout(v.timeout); - clearTimeout(v.expiration); - v.job.doDrop({ - message: options.dropErrorMessage - }); - } - } + return mod.parse +} - this._dropAllQueued(options.dropErrorMessage); +/** + * Get the simple query parser. + * + * @param {object} options + */ - return waitForExecuting(0); - }); - })) : this.schedule({ - priority: NUM_PRIORITIES - 1, - weight: 0 - }, () => { - return waitForExecuting(1); - }); +function simpleparser (options) { + var parameterLimit = options.parameterLimit !== undefined + ? options.parameterLimit + : 1000 + var parse = parser('querystring') - this._receive = function (job) { - return job._reject(new Bottleneck.prototype.BottleneckError(options.enqueueErrorMessage)); - }; + if (isNaN(parameterLimit) || parameterLimit < 1) { + throw new TypeError('option parameterLimit must be a positive number') + } - this.stop = () => { - return this.Promise.reject(new Bottleneck.prototype.BottleneckError("stop() has already been called")); - }; + if (isFinite(parameterLimit)) { + parameterLimit = parameterLimit | 0 + } - return done; - } + return function queryparse (body) { + var paramCount = parameterCount(body, parameterLimit) - _addToQueue(job) { - var _this2 = this; + if (paramCount === undefined) { + debug('too many parameters') + throw createError(413, 'too many parameters', { + type: 'parameters.too.many' + }) + } - return _asyncToGenerator(function* () { - var args, blocked, error, options, reachedHWM, shifted, strategy; - args = job.args; - options = job.options; + debug('parse urlencoding') + return parse(body, undefined, undefined, { maxKeys: parameterLimit }) + } +} - try { - var _ref2 = yield _this2._store.__submit__(_this2.queued(), options.weight); +/** + * Get the simple type checker. + * + * @param {string} type + * @return {function} + */ - reachedHWM = _ref2.reachedHWM; - blocked = _ref2.blocked; - strategy = _ref2.strategy; - } catch (error1) { - error = error1; +function typeChecker (type) { + return function checkType (req) { + return Boolean(typeis(req, type)) + } +} - _this2.Events.trigger("debug", `Could not queue ${options.id}`, { - args, - options, - error - }); - job.doDrop({ - error - }); - return false; - } +/***/ }), - if (blocked) { - job.doDrop(); - 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; +/***/ 15377: +/***/ ((module, exports, __nccwpck_require__) => { - if (shifted != null) { - shifted.doDrop(); - } +/** + * This is the web browser implementation of `debug()`. + * + * Expose `debug()` as the module. + */ - if (shifted == null || strategy === Bottleneck.prototype.strategy.OVERFLOW) { - if (shifted == null) { - job.doDrop(); - } +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 reachedHWM; - } - } +/** + * Colors. + */ - job.doQueue(reachedHWM, blocked); +exports.colors = [ + 'lightseagreen', + 'forestgreen', + 'goldenrod', + 'dodgerblue', + 'darkorchid', + 'crimson' +]; - _this2._queues.push(job); +/** + * 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 + */ - yield _this2._drainAll(); - return reachedHWM; - })(); - } +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; + } - _receive(job) { - if (this._states.jobStatus(job.options.id) != null) { - job._reject(new Bottleneck.prototype.BottleneckError(`A job with the same id already exists (id=${job.options.id})`)); + // 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 false; - } else { - job.doReceive(); - return this._submitLock.schedule(this._addToQueue, job); - } - } +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ - submit(...args) { - var cb, fn, job, options, ref, ref1, task; +exports.formatters.j = function(v) { + try { + return JSON.stringify(v); + } catch (err) { + return '[UnexpectedJSONParseError]: ' + err.message; + } +}; - if (typeof args[0] === "function") { - var _ref3, _ref4, _splice$call, _splice$call2; - ref = args, (_ref3 = ref, _ref4 = _toArray(_ref3), fn = _ref4[0], args = _ref4.slice(1), _ref3), (_splice$call = splice.call(args, -1), _splice$call2 = _slicedToArray(_splice$call, 1), cb = _splice$call2[0], _splice$call); - options = parser.load({}, this.jobDefaults); - } else { - var _ref5, _ref6, _splice$call3, _splice$call4; +/** + * Colorize log arguments if enabled. + * + * @api public + */ - ref1 = args, (_ref5 = ref1, _ref6 = _toArray(_ref5), options = _ref6[0], fn = _ref6[1], args = _ref6.slice(2), _ref5), (_splice$call3 = splice.call(args, -1), _splice$call4 = _slicedToArray(_splice$call3, 1), cb = _splice$call4[0], _splice$call3); - options = parser.load(options, this.jobDefaults); - } +function formatArgs(args) { + var useColors = this.useColors; - task = (...args) => { - return new this.Promise(function (resolve, reject) { - return fn(...args, function (...args) { - return (args[0] != null ? reject : resolve)(args); - }); - }); - }; + args[0] = (useColors ? '%c' : '') + + this.namespace + + (useColors ? ' %c' : ' ') + + args[0] + + (useColors ? '%c ' : ' ') + + '+' + exports.humanize(this.diff); - job = new Job(task, args, options, this.jobDefaults, this.rejectOnDrop, this.Events, this._states, this.Promise); - job.promise.then(function (args) { - return typeof cb === "function" ? cb(...args) : void 0; - }).catch(function (args) { - if (Array.isArray(args)) { - return typeof cb === "function" ? cb(...args) : void 0; - } else { - return typeof cb === "function" ? cb(args) : void 0; - } - }); - return this._receive(job); - } + if (!useColors) return; - schedule(...args) { - var job, options, task; + var c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit') - if (typeof args[0] === "function") { - var _args = args; + // 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; + } + }); - var _args2 = _toArray(_args); + args.splice(lastC, 0, c); +} - task = _args2[0]; - args = _args2.slice(1); - options = {}; - } else { - var _args3 = args; +/** + * Invokes `console.log()` when available. + * No-op when `console.log` is not a "function". + * + * @api public + */ - var _args4 = _toArray(_args3); +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); +} - options = _args4[0]; - task = _args4[1]; - args = _args4.slice(2); - } +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ - job = new Job(task, args, options, this.jobDefaults, this.rejectOnDrop, this.Events, this._states, this.Promise); +function save(namespaces) { + try { + if (null == namespaces) { + exports.storage.removeItem('debug'); + } else { + exports.storage.debug = namespaces; + } + } catch(e) {} +} - this._receive(job); +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ - return job.promise; - } +function load() { + var r; + try { + r = exports.storage.debug; + } catch(e) {} - wrap(fn) { - var schedule, wrapped; - schedule = this.schedule.bind(this); + // 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; + } - wrapped = function wrapped(...args) { - return schedule(fn.bind(this), ...args); - }; + return r; +} - wrapped.withOptions = function (options, ...args) { - return schedule(options, fn, ...args); - }; +/** + * Enable namespaces listed in `localStorage.debug` initially. + */ - return wrapped; - } +exports.enable(load()); - updateSettings(options = {}) { - var _this3 = this; +/** + * 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 _asyncToGenerator(function* () { - yield _this3._store.__updateSettings__(parser.overwrite(options, _this3.storeDefaults)); - parser.overwrite(options, _this3.instanceDefaults, _this3); - return _this3; - })(); - } +function localstorage() { + try { + return window.localStorage; + } catch (e) {} +} - currentReservoir() { - return this._store.__currentReservoir__(); - } - incrementReservoir(incr = 0) { - return this._store.__incrementReservoir__(incr); - } +/***/ }), - } +/***/ 22552: +/***/ ((module, exports, __nccwpck_require__) => { - ; - 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, - reservoirIncreaseInterval: null, - reservoirIncreaseAmount: null, - reservoirIncreaseMaximum: null - }; - Bottleneck.prototype.localStoreDefaults = { - Promise: Promise, - timeout: null, - heartbeatInterval: 250 - }; - Bottleneck.prototype.redisStoreDefaults = { - Promise: Promise, - timeout: null, - heartbeatInterval: 5000, - clientTimeout: 10000, - Redis: null, - 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; +/** + * 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__(73233); -/***/ 93529: -/***/ ((module) => { +/** + * The currently active debug mode names, and names to skip. + */ -"use strict"; +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". + */ -var BottleneckError; -BottleneckError = class BottleneckError extends Error {}; -module.exports = BottleneckError; +exports.formatters = {}; -/***/ }), +/** + * Previous log timestamp. + */ -/***/ 38579: -/***/ ((module) => { +var prevTime; -"use strict"; +/** + * Select a color. + * @param {String} namespace + * @return {Number} + * @api private + */ +function selectColor(namespace) { + var hash = 0, i; -var DLList; -DLList = class DLList { - constructor(incr, decr) { - this.incr = incr; - this.decr = decr; - this._first = null; - this._last = null; - this.length = 0; + for (i in namespace) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer } - push(value) { - var node; - this.length++; + return exports.colors[Math.abs(hash) % exports.colors.length]; +} - if (typeof this.incr === "function") { - this.incr(); +/** + * 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]; } - node = { - value, - prev: this._last, - next: null - }; + args[0] = exports.coerce(args[0]); - if (this._last != null) { - this._last.next = node; - this._last = node; - } else { - this._first = this._last = node; + if ('string' !== typeof args[0]) { + // anything else let's inspect with %O + args.unshift('%O'); } - return void 0; + // 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); } - shift() { - var value; + debug.namespace = namespace; + debug.enabled = exports.enabled(namespace); + debug.useColors = exports.useColors(); + debug.color = selectColor(namespace); - if (this._first == null) { - return; - } else { - this.length--; + // env-specific initialization logic for debug instances + if ('function' === typeof exports.init) { + exports.init(debug); + } - if (typeof this.decr === "function") { - this.decr(); - } - } + return debug; +} - value = this._first.value; +/** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ - if ((this._first = this._first.next) != null) { - this._first.prev = null; +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 { - this._last = null; + exports.names.push(new RegExp('^' + namespaces + '$')); } - - return value; } +} - first() { - if (this._first != null) { - return this._first.value; +/** + * 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; + } + } + for (i = 0, len = exports.names.length; i < len; i++) { + if (exports.names[i].test(name)) { + return true; } } + return false; +} - getArray() { - var node, ref, results; - node = this._first; - results = []; +/** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ - while (node != null) { - results.push((ref = node, node = node.next, ref.value)); - } +function coerce(val) { + if (val instanceof Error) return val.stack || val.message; + return val; +} - return results; - } - forEachShift(cb) { - var node; - node = this.shift(); +/***/ }), - while (node != null) { - cb(node), node = this.shift(); - } +/***/ 7471: +/***/ ((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__(15377); +} else { + module.exports = __nccwpck_require__(74117); +} + + +/***/ }), + +/***/ 74117: +/***/ ((module, exports, __nccwpck_require__) => { - return void 0; - } +/** + * Module dependencies. + */ - debug() { - var node, ref, ref1, ref2, results; - node = this._first; - results = []; +var tty = __nccwpck_require__(76224); +var util = __nccwpck_require__(73837); - while (node != null) { - results.push((ref = node, node = node.next, { - value: ref.value, - prev: (ref1 = ref.prev) != null ? ref1.value : void 0, - next: (ref2 = ref.next) != null ? ref2.value : void 0 - })); - } +/** + * This is the Node.js implementation of `debug()`. + * + * Expose `debug()` as the module. + */ - return results; - } +exports = module.exports = __nccwpck_require__(22552); +exports.init = init; +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; -}; -module.exports = DLList; +/** + * Colors. + */ -/***/ }), +exports.colors = [6, 2, 3, 4, 5, 1]; -/***/ 107: -/***/ ((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"; +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); -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); } } + obj[prop] = val; + return obj; +}, {}); -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); }); }; } +/** + * 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 Events; -Events = class Events { - constructor(instance) { - this.instance = instance; - this._events = {}; +var fd = parseInt(process.env.DEBUG_FD, 10) || 2; - if (this.instance.on != null || this.instance.once != null || this.instance.removeAllListeners != null) { - throw new Error("An Emitter already exists for this object"); - } +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)')() +} - this.instance.on = (name, cb) => { - return this._addListener(name, "many", cb); - }; +var stream = 1 === fd ? process.stdout : + 2 === fd ? process.stderr : + createWritableStdioStream(fd); - this.instance.once = (name, cb) => { - return this._addListener(name, "once", cb); - }; +/** + * Is stdout a TTY? Colored output is enabled when `true`. + */ - this.instance.removeAllListeners = (name = null) => { - if (name != null) { - return delete this._events[name]; - } else { - return this._events = {}; - } - }; - } +function useColors() { + return 'colors' in exports.inspectOpts + ? Boolean(exports.inspectOpts.colors) + : tty.isatty(fd); +} - _addListener(name, status, cb) { - var base; +/** + * Map %o to `util.inspect()`, all on a single line. + */ - if ((base = this._events)[name] == null) { - base[name] = []; - } +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(' '); +}; - this._events[name].push({ - cb, - status - }); +/** + * Map %o to `util.inspect()`, allowing multiple lines if needed. + */ - return this.instance; - } +exports.formatters.O = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); +}; - listenerCount(name) { - if (this._events[name] != null) { - return this._events[name].length; - } else { - return 0; - } - } +/** + * Adds ANSI color escape codes if enabled. + * + * @api public + */ - trigger(name, ...args) { - var _this = this; +function formatArgs(args) { + var name = this.namespace; + var useColors = this.useColors; - return _asyncToGenerator(function* () { - var e, promises; + if (useColors) { + var c = this.color; + var prefix = ' \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m'; - try { - if (name !== "debug") { - _this.trigger("debug", `Event triggered: ${name}`, args); - } + 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 (_this._events[name] == null) { - return; - } +/** + * Invokes `util.format()` with the specified arguments and writes to `stream`. + */ - _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; +function log() { + return stream.write(util.format.apply(util, arguments) + '\n'); +} - if (listener.status === "none") { - return; - } +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ - if (listener.status === "once") { - listener.status = "none"; - } +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; + } +} - try { - returned = typeof listener.cb === "function" ? listener.cb(...args) : void 0; +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ - if (typeof (returned != null ? returned.then : void 0) === "function") { - return yield returned; - } else { - return returned; - } - } catch (error) { - e = error; +function load() { + return process.env.DEBUG; +} - if (true) { - _this.trigger("error", e); - } +/** + * 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. + */ - return null; - } - }); +function createWritableStdioStream (fd) { + var stream; + var tty_wrap = process.binding('tty_wrap'); - return function (_x) { - return _ref.apply(this, arguments); - }; - }()); - return (yield Promise.all(promises)).find(function (x) { - return x != null; - }); - } catch (error) { - e = error; + // Note stream._type is used for test-module-load-list.js - if (true) { - _this.trigger("error", e); - } + switch (tty_wrap.guessHandleType(fd)) { + case 'TTY': + stream = new tty.WriteStream(fd); + stream._type = 'tty'; - return null; + // 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 = Events; + 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 + }); -/***/ 53068: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // 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'; -"use strict"; + // 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!'); + } -function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } + // For supporting legacy API we put the FD here. + stream.fd = fd; -function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } + stream._isStdio = true; -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; } + return stream; +} -function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } +/** + * Init logic for `debug` instances. + * + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. + */ -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 init (debug) { + debug.inspectOpts = {}; -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 keys = Object.keys(exports.inspectOpts); + for (var i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } +} -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); +/** + * Enable namespaces listed in `process.env.DEBUG` initially. + */ -Group = function () { - class Group { - constructor(limiterOptions = {}) { - this.deleteKey = this.deleteKey.bind(this); - this.limiterOptions = limiterOptions; - parser.load(this.limiterOptions, this.defaults, this); - this.Events = new Events(this); - this.instances = {}; - this.Bottleneck = __nccwpck_require__(83911); +exports.enable(load()); - 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 - })); - } - } - } +/***/ 73233: +/***/ ((module) => { - 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; - })(); - } +/** + * Helpers. + */ - deleteKey(key = "") { - var _this = this; +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var y = d * 365.25; - return _asyncToGenerator(function* () { - var deleted, instance; - instance = _this.instances[key]; +/** + * 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 + */ - if (_this.connection) { - deleted = yield _this.connection.__runCommand__(['del', ...Scripts.allKeys(`${_this.id}-${key}`)]); - } +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) + ); +}; - if (instance != null) { - delete _this.instances[key]; - yield instance.disconnect(); - } +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ - return instance != null || deleted > 0; - })(); - } +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; + } +} - limiters() { - var k, ref, results, v; - ref = this.instances; - results = []; +/** + * 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'; + } + return ms + 'ms'; +} - for (k in ref) { - v = ref[k]; - results.push({ - key: k, - limiter: v - }); - } +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ - return results; - } +function fmtLong(ms) { + return plural(ms, d, 'day') || + plural(ms, h, 'hour') || + plural(ms, m, 'minute') || + plural(ms, s, 'second') || + ms + ' ms'; +} - keys() { - return Object.keys(this.instances); - } +/** + * Pluralization helper. + */ - clusterKeys() { - var _this2 = this; +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 _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; +/***/ 85442: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - while (cursor !== 0) { - var _ref = yield _this2.connection.__runCommand__(["scan", cursor != null ? cursor : 0, "match", `b_${_this2.id}-*_settings`, "count", 10000]); +"use strict"; - var _ref2 = _slicedToArray(_ref, 2); - next = _ref2[0]; - found = _ref2[1]; - cursor = ~~next; +var Batcher, Events, parser; +parser = __nccwpck_require__(67823); +Events = __nccwpck_require__(107); - for (i = 0, len = found.length; i < len; i++) { - k = found[i]; - keys.push(k.slice(start, -end)); - } - } +Batcher = function () { + class Batcher { + constructor(options = {}) { + this.options = options; + parser.load(this.options, this.defaults, this); + this.Events = new Events(this); + this._arr = []; - return keys; - })(); - } + this._resetPromise(); - _startAutoCleanup() { - var _this3 = this; + this._lastFlush = Date.now(); + } - 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 = []; + _resetPromise() { + return this._promise = new this.Promise((res, rej) => { + return this._resolve = res; + }); + } - for (k in ref) { - v = ref[k]; + _flush() { + clearTimeout(this._timeout); + this._lastFlush = Date.now(); - 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)); - } - } + this._resolve(); - return results; - }), this.timeout / 2)).unref === "function" ? base.unref() : void 0; + this.Events.trigger("batch", this._arr); + this._arr = []; + return this._resetPromise(); } - updateSettings(options = {}) { - parser.overwrite(options, this.defaults, this); - parser.overwrite(options, options, this.limiterOptions); + add(data) { + var ret; - if (options.timeout != null) { - return this._startAutoCleanup(); - } - } + this._arr.push(data); - disconnect(flush = true) { - var ref; + ret = this._promise; - if (!this.sharedConnection) { - return (ref = this.connection) != null ? ref.disconnect(flush) : void 0; + 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; } } ; - Group.prototype.defaults = { - timeout: 1000 * 60 * 5, - connection: null, - Promise: Promise, - id: "group-key" + Batcher.prototype.defaults = { + maxTime: null, + maxSize: null, + Promise: Promise }; - return Group; + return Batcher; }.call(void 0); -module.exports = Group; +module.exports = Batcher; /***/ }), -/***/ 47710: +/***/ 83911: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -26414,9 +26122,13 @@ module.exports = Group; 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 _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 _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; } @@ -26424,803 +26136,1081 @@ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try 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; +var Bottleneck, + DEFAULT_PRIORITY, + Events, + Job, + LocalDatastore, + NUM_PRIORITIES, + Queues, + RedisDatastore, + States, + Sync, + parser, + splice = [].splice; +NUM_PRIORITIES = 10; +DEFAULT_PRIORITY = 5; parser = __nccwpck_require__(67823); +Queues = __nccwpck_require__(65893); +Job = __nccwpck_require__(25949); +LocalDatastore = __nccwpck_require__(38979); +RedisDatastore = __nccwpck_require__(4946); Events = __nccwpck_require__(107); -Scripts = __nccwpck_require__(4169); +States = __nccwpck_require__(2527); +Sync = __nccwpck_require__(56029); -IORedisConnection = function () { - class IORedisConnection { - constructor(options = {}) { - parser.load(options, this.defaults, this); +Bottleneck = function () { + class Bottleneck { + constructor(options = {}, ...invalid) { + var storeInstanceOptions, storeOptions; + this._addToQueue = this._addToQueue.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}`); + } + }.call(this); + + this._queues.on("leftzero", () => { + var ref; + return (ref = this._store.heartbeat) != null ? typeof ref.ref === "function" ? ref.ref() : void 0 : void 0; + }); + + this._queues.on("zero", () => { + var ref; + return (ref = this._store.heartbeat) != null ? typeof ref.unref === "function" ? ref.unref() : void 0 : void 0; + }); + } + + _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."); + } + } + + ready() { + return this._store.ready; + } + + clients() { + return this._store.clients; + } + + channel() { + return `b_${this.id}`; + } + + channel_client() { + return `b_${this.id}_${this._store.clientId}`; + } + + publish(message) { + return this._store.__publish__(message); + } + + disconnect(flush = true) { + return this._store.__disconnect__(flush); + } - if (this.Redis == null) { - this.Redis = eval("require")("ioredis"); // Obfuscated or else Webpack/Angular will try to inline the optional ioredis module. To override this behavior: pass the ioredis module to Bottleneck as the 'Redis' option. - } + chain(_limiter) { + this._limiter = _limiter; + return this; + } - if (this.Events == null) { - this.Events = new Events(this); - } + queued(priority) { + return this._queues.queued(priority); + } - this.terminated = false; + clusterQueued() { + return this._store.__queued__(); + } - if (this.clusterNodes != null) { - this.client = new this.Redis.Cluster(this.clusterNodes, this.clientOptions); - this.subscriber = new this.Redis.Cluster(this.clusterNodes, this.clientOptions); - } else if (this.client != null && this.client.duplicate == null) { - this.subscriber = new this.Redis.Cluster(this.client.startupNodes, this.client.options); - } else { - if (this.client == null) { - this.client = new this.Redis(this.clientOptions); - } + empty() { + return this.queued() === 0 && this._submitLock.isEmpty(); + } - this.subscriber = this.client.duplicate(); - } + running() { + return this._store.__running__(); + } - this.limiters = {}; - this.ready = this.Promise.all([this._setup(this.client, false), this._setup(this.subscriber, true)]).then(() => { - this._loadScripts(); + done() { + return this._store.__done__(); + } - return { - client: this.client, - subscriber: this.subscriber - }; - }); + jobStatus(id) { + return this._states.jobStatus(id); } - _setup(client, sub) { - client.setMaxListeners(0); - return new this.Promise((resolve, reject) => { - client.on("error", e => { - return this.Events.trigger("error", e); - }); + jobs(status) { + return this._states.statusJobs(status); + } - if (sub) { - client.on("message", (channel, message) => { - var ref; - return (ref = this.limiters[channel]) != null ? ref._store.onMessage(channel, message) : void 0; - }); - } + counts() { + return this._states.statusCounts(); + } - if (client.status === "ready") { - return resolve(); - } else { - return client.once("ready", resolve); - } - }); + _randomIndex() { + return Math.random().toString(36).slice(2); } - _loadScripts() { - return Scripts.names.forEach(name => { - return this.client.defineCommand(name, { - lua: Scripts.payload(name) - }); - }); + check(weight = 1) { + return this._store.__check__(weight); } - __runCommand__(cmd) { + _clearGlobalState(index) { + if (this._scheduled[index] != null) { + clearTimeout(this._scheduled[index].expiration); + delete this._scheduled[index]; + return true; + } else { + return false; + } + } + + _free(index, job, options, eventInfo) { var _this = this; return _asyncToGenerator(function* () { - var _, deleted; - - yield _this.ready; + var e, running; - var _ref = yield _this.client.pipeline([cmd]).exec(); + try { + var _ref = yield _this._store.__free__(index, options.weight); - var _ref2 = _slicedToArray(_ref, 1); + running = _ref.running; - var _ref2$ = _slicedToArray(_ref2[0], 2); + _this.Events.trigger("debug", `Freed ${options.id}`, eventInfo); - _ = _ref2$[0]; - deleted = _ref2$[1]; - return deleted; + if (running === 0 && _this.empty()) { + return _this.Events.trigger("idle"); + } + } catch (error1) { + e = error1; + return _this.Events.trigger("error", e); + } })(); } - __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(); - }); - }); - })); + _run(index, job, wait) { + var clearGlobalState, free, run; + job.doRun(); + clearGlobalState = this._clearGlobalState.bind(this, index); + run = this._run.bind(this, index, job); + free = this._free.bind(this, index, job); + return this._scheduled[index] = { + timeout: setTimeout(() => { + return job.doExecute(this._limiter, clearGlobalState, run, free); + }, wait), + expiration: job.options.expiration != null ? setTimeout(function () { + return job.doExpire(clearGlobalState, run, free); + }, wait + job.options.expiration) : void 0, + job: job + }; } - __removeLimiter__(instance) { - var _this2 = this; + _drainOne(capacity) { + return this._registerLock.schedule(() => { + var args, index, next, options, queue; - return [instance.channel(), instance.channel_client()].forEach( - /*#__PURE__*/ - function () { - var _ref3 = _asyncToGenerator(function* (channel) { - if (!_this2.terminated) { - yield _this2.subscriber.unsubscribe(channel); - } + if (this.queued() === 0) { + return this.Promise.resolve(null); + } - return delete _this2.limiters[channel]; - }); + queue = this._queues.getFirst(); - return function (_x) { - return _ref3.apply(this, arguments); - }; - }()); - } + var _next2 = next = queue.first(); - __scriptArgs__(name, id, args, cb) { - var keys; - keys = Scripts.keys(name, id); - return [keys.length].concat(keys, args, cb); - } + options = _next2.options; + args = _next2.args; - __scriptFn__(name) { - return this.client[name].bind(this.client); - } + if (capacity != null && options.weight > capacity) { + return this.Promise.resolve(null); + } - disconnect(flush = true) { - var i, k, len, ref; - ref = Object.keys(this.limiters); + 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 + }); - for (i = 0, len = ref.length; i < len; i++) { - k = ref[i]; - clearInterval(this.limiters[k]._store.heartbeat); - } + if (success) { + queue.shift(); + empty = this.empty(); - this.limiters = {}; - this.terminated = true; + if (empty) { + this.Events.trigger("empty"); + } - if (flush) { - return this.Promise.all([this.client.quit(), this.subscriber.quit()]); - } else { - this.client.disconnect(); - this.subscriber.disconnect(); - return this.Promise.resolve(); - } + if (reservoir === 0) { + this.Events.trigger("depleted", empty); + } + + this._run(index, next, wait); + + return this.Promise.resolve(options.weight); + } else { + return this.Promise.resolve(null); + } + }); + }); } - } + _drainAll(capacity, total = 0) { + return this._drainOne(capacity).then(drained => { + var newCapacity; - ; - IORedisConnection.prototype.datastore = "ioredis"; - IORedisConnection.prototype.defaults = { - Redis: null, - clientOptions: {}, - clusterNodes: null, - client: null, - Promise: Promise, - Events: null - }; - return IORedisConnection; -}.call(void 0); + 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); + }); + } + + _dropAllQueued(message) { + return this._queues.shiftAll(function (job) { + return job.doDrop({ + message + }); + }); + } -module.exports = IORedisConnection; + stop(options = {}) { + var done, waitForExecuting; + options = parser.load(options, this.stopDefaults); -/***/ }), + waitForExecuting = at => { + var finished; -/***/ 25949: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + finished = () => { + var counts; + counts = this._states.counts; + return counts[0] + counts[1] + counts[2] + counts[3] === at; + }; -"use strict"; + 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 = function (index, next) { + return next.doDrop({ + message: options.dropErrorMessage + }); + }, this._drainOne = () => { + return this.Promise.resolve(null); + }, this._registerLock.schedule(() => { + return this._submitLock.schedule(() => { + var k, ref, v; + ref = this._scheduled; -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); } } + for (k in ref) { + v = ref[k]; -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 (this.jobStatus(v.job.options.id) === "RUNNING") { + clearTimeout(v.timeout); + clearTimeout(v.expiration); + v.job.doDrop({ + message: options.dropErrorMessage + }); + } + } -var BottleneckError, DEFAULT_PRIORITY, Job, NUM_PRIORITIES, parser; -NUM_PRIORITIES = 10; -DEFAULT_PRIORITY = 5; -parser = __nccwpck_require__(67823); -BottleneckError = __nccwpck_require__(93529); -Job = class Job { - constructor(task, args, options, jobDefaults, rejectOnDrop, Events, _states, Promise) { - this.task = task; - this.args = args; - this.rejectOnDrop = rejectOnDrop; - this.Events = Events; - this._states = _states; - this.Promise = Promise; - this.options = parser.load(options, jobDefaults); - this.options.priority = this._sanitizePriority(this.options.priority); + this._dropAllQueued(options.dropErrorMessage); - if (this.options.id === jobDefaults.id) { - this.options.id = `${this.options.id}-${this._randomIndex()}`; - } + return waitForExecuting(0); + }); + })) : this.schedule({ + priority: NUM_PRIORITIES - 1, + weight: 0 + }, () => { + return waitForExecuting(1); + }); - this.promise = new this.Promise((_resolve, _reject) => { - this._resolve = _resolve; - this._reject = _reject; - }); - this.retryCount = 0; - } + this._receive = function (job) { + return job._reject(new Bottleneck.prototype.BottleneckError(options.enqueueErrorMessage)); + }; - _sanitizePriority(priority) { - var sProperty; - sProperty = ~~priority !== priority ? DEFAULT_PRIORITY : priority; + this.stop = () => { + return this.Promise.reject(new Bottleneck.prototype.BottleneckError("stop() has already been called")); + }; - if (sProperty < 0) { - return 0; - } else if (sProperty > NUM_PRIORITIES - 1) { - return NUM_PRIORITIES - 1; - } else { - return sProperty; + return done; } - } - _randomIndex() { - return Math.random().toString(36).slice(2); - } + _addToQueue(job) { + var _this2 = this; - doDrop({ - error, - message = "This job has been dropped by Bottleneck" - } = {}) { - if (this._states.remove(this.options.id)) { - if (this.rejectOnDrop) { - this._reject(error != null ? error : new BottleneckError(message)); - } + return _asyncToGenerator(function* () { + var args, blocked, error, options, reachedHWM, shifted, strategy; + args = job.args; + options = job.options; - this.Events.trigger("dropped", { - args: this.args, - options: this.options, - task: this.task, - promise: this.promise - }); - return true; - } else { - return false; - } - } + try { + var _ref2 = yield _this2._store.__submit__(_this2.queued(), options.weight); - _assertStatus(expected) { - var status; - status = this._states.jobStatus(this.options.id); + reachedHWM = _ref2.reachedHWM; + blocked = _ref2.blocked; + strategy = _ref2.strategy; + } catch (error1) { + error = error1; - if (!(status === expected || expected === "DONE" && status === null)) { - throw new BottleneckError(`Invalid job status ${status}, expected ${expected}. Please open an issue at https://github.com/SGrondin/bottleneck/issues`); - } - } + _this2.Events.trigger("debug", `Could not queue ${options.id}`, { + args, + options, + error + }); - doReceive() { - this._states.start(this.options.id); + job.doDrop({ + error + }); + return false; + } - return this.Events.trigger("received", { - args: this.args, - options: this.options - }); - } + if (blocked) { + job.doDrop(); + 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; - doQueue(reachedHWM, blocked) { - this._assertStatus("RECEIVED"); + if (shifted != null) { + shifted.doDrop(); + } - this._states.next(this.options.id); + if (shifted == null || strategy === Bottleneck.prototype.strategy.OVERFLOW) { + if (shifted == null) { + job.doDrop(); + } - return this.Events.trigger("queued", { - args: this.args, - options: this.options, - reachedHWM, - blocked - }); - } + return reachedHWM; + } + } - doRun() { - if (this.retryCount === 0) { - this._assertStatus("QUEUED"); + job.doQueue(reachedHWM, blocked); - this._states.next(this.options.id); - } else { - this._assertStatus("EXECUTING"); + _this2._queues.push(job); + + yield _this2._drainAll(); + return reachedHWM; + })(); } - return this.Events.trigger("scheduled", { - args: this.args, - options: this.options - }); - } + _receive(job) { + if (this._states.jobStatus(job.options.id) != null) { + job._reject(new Bottleneck.prototype.BottleneckError(`A job with the same id already exists (id=${job.options.id})`)); - doExecute(chained, clearGlobalState, run, free) { - var _this = this; + return false; + } else { + job.doReceive(); + return this._submitLock.schedule(this._addToQueue, job); + } + } - return _asyncToGenerator(function* () { - var error, eventInfo, passed; + submit(...args) { + var cb, fn, job, options, ref, ref1, task; - if (_this.retryCount === 0) { - _this._assertStatus("RUNNING"); + if (typeof args[0] === "function") { + var _ref3, _ref4, _splice$call, _splice$call2; - _this._states.next(_this.options.id); + ref = args, (_ref3 = ref, _ref4 = _toArray(_ref3), fn = _ref4[0], args = _ref4.slice(1), _ref3), (_splice$call = splice.call(args, -1), _splice$call2 = _slicedToArray(_splice$call, 1), cb = _splice$call2[0], _splice$call); + options = parser.load({}, this.jobDefaults); } else { - _this._assertStatus("EXECUTING"); + var _ref5, _ref6, _splice$call3, _splice$call4; + + ref1 = args, (_ref5 = ref1, _ref6 = _toArray(_ref5), options = _ref6[0], fn = _ref6[1], args = _ref6.slice(2), _ref5), (_splice$call3 = splice.call(args, -1), _splice$call4 = _slicedToArray(_splice$call3, 1), cb = _splice$call4[0], _splice$call3); + options = parser.load(options, this.jobDefaults); } - eventInfo = { - args: _this.args, - options: _this.options, - retryCount: _this.retryCount + task = (...args) => { + return new this.Promise(function (resolve, reject) { + return fn(...args, function (...args) { + return (args[0] != null ? reject : resolve)(args); + }); + }); }; - _this.Events.trigger("executing", eventInfo); + job = new Job(task, args, options, this.jobDefaults, this.rejectOnDrop, this.Events, this._states, this.Promise); + job.promise.then(function (args) { + return typeof cb === "function" ? cb(...args) : void 0; + }).catch(function (args) { + if (Array.isArray(args)) { + return typeof cb === "function" ? cb(...args) : void 0; + } else { + return typeof cb === "function" ? cb(args) : void 0; + } + }); + return this._receive(job); + } + + schedule(...args) { + var job, options, task; - try { - passed = yield chained != null ? chained.schedule(_this.options, _this.task, ..._this.args) : _this.task(..._this.args); + if (typeof args[0] === "function") { + var _args = args; - if (clearGlobalState()) { - _this.doDone(eventInfo); + var _args2 = _toArray(_args); - yield free(_this.options, eventInfo); + task = _args2[0]; + args = _args2.slice(1); + options = {}; + } else { + var _args3 = args; - _this._assertStatus("DONE"); + var _args4 = _toArray(_args3); - return _this._resolve(passed); - } - } catch (error1) { - error = error1; - return _this._onFailure(error, eventInfo, clearGlobalState, run, free); + options = _args4[0]; + task = _args4[1]; + args = _args4.slice(2); } - })(); - } - doExpire(clearGlobalState, run, free) { - var error, eventInfo; + job = new Job(task, args, options, this.jobDefaults, this.rejectOnDrop, this.Events, this._states, this.Promise); - if (this._states.jobStatus(this.options.id === "RUNNING")) { - this._states.next(this.options.id); + this._receive(job); + + return job.promise; } - this._assertStatus("EXECUTING"); + wrap(fn) { + var schedule, wrapped; + schedule = this.schedule.bind(this); - eventInfo = { - args: this.args, - options: this.options, - retryCount: this.retryCount - }; - error = new BottleneckError(`This job timed out after ${this.options.expiration} ms.`); - return this._onFailure(error, eventInfo, clearGlobalState, run, free); - } + wrapped = function wrapped(...args) { + return schedule(fn.bind(this), ...args); + }; - _onFailure(error, eventInfo, clearGlobalState, run, free) { - var _this2 = this; + wrapped.withOptions = function (options, ...args) { + return schedule(options, fn, ...args); + }; - return _asyncToGenerator(function* () { - var retry, retryAfter; + return wrapped; + } - if (clearGlobalState()) { - retry = yield _this2.Events.trigger("failed", error, eventInfo); + updateSettings(options = {}) { + var _this3 = this; - if (retry != null) { - retryAfter = ~~retry; + return _asyncToGenerator(function* () { + yield _this3._store.__updateSettings__(parser.overwrite(options, _this3.storeDefaults)); + parser.overwrite(options, _this3.instanceDefaults, _this3); + return _this3; + })(); + } - _this2.Events.trigger("retry", `Retrying ${_this2.options.id} after ${retryAfter} ms`, eventInfo); + currentReservoir() { + return this._store.__currentReservoir__(); + } - _this2.retryCount++; - return run(retryAfter); - } else { - _this2.doDone(eventInfo); + incrementReservoir(incr = 0) { + return this._store.__incrementReservoir__(incr); + } - yield free(_this2.options, eventInfo); + } - _this2._assertStatus("DONE"); + ; + 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, + reservoirIncreaseInterval: null, + reservoirIncreaseAmount: null, + reservoirIncreaseMaximum: null + }; + Bottleneck.prototype.localStoreDefaults = { + Promise: Promise, + timeout: null, + heartbeatInterval: 250 + }; + Bottleneck.prototype.redisStoreDefaults = { + Promise: Promise, + timeout: null, + heartbeatInterval: 5000, + clientTimeout: 10000, + Redis: null, + 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); - return _this2._reject(error); - } - } - })(); - } +module.exports = Bottleneck; - doDone(eventInfo) { - this._assertStatus("EXECUTING"); +/***/ }), - this._states.next(this.options.id); +/***/ 93529: +/***/ ((module) => { - return this.Events.trigger("done", eventInfo); - } +"use strict"; -}; -module.exports = Job; + +var BottleneckError; +BottleneckError = class BottleneckError extends Error {}; +module.exports = BottleneckError; /***/ }), -/***/ 38979: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 38579: +/***/ ((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 DLList; +DLList = class DLList { + constructor(incr, decr) { + this.incr = incr; + this.decr = decr; + this._first = null; + this._last = null; + this.length = 0; + } -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 = this._lastReservoirIncrease = Date.now(); - this._running = 0; - this._done = 0; - this._unblockTime = 0; - this.ready = this.Promise.resolve(); - this.clients = {}; + push(value) { + var node; + this.length++; - this._startHeartbeat(); - } + if (typeof this.incr === "function") { + this.incr(); + } - _startHeartbeat() { - var base; + node = { + value, + prev: this._last, + next: null + }; - if (this.heartbeat == null && (this.storeOptions.reservoirRefreshInterval != null && this.storeOptions.reservoirRefreshAmount != null || this.storeOptions.reservoirIncreaseInterval != null && this.storeOptions.reservoirIncreaseAmount != null)) { - return typeof (base = this.heartbeat = setInterval(() => { - var amount, incr, maximum, now, reservoir; - now = Date.now(); + if (this._last != null) { + this._last.next = node; + this._last = node; + } else { + this._first = this._last = node; + } - if (this.storeOptions.reservoirRefreshInterval != null && now >= this._lastReservoirRefresh + this.storeOptions.reservoirRefreshInterval) { - this._lastReservoirRefresh = now; - this.storeOptions.reservoir = this.storeOptions.reservoirRefreshAmount; + return void 0; + } - this.instance._drainAll(this.computeCapacity()); - } + shift() { + var value; - if (this.storeOptions.reservoirIncreaseInterval != null && now >= this._lastReservoirIncrease + this.storeOptions.reservoirIncreaseInterval) { - var _this$storeOptions = this.storeOptions; - amount = _this$storeOptions.reservoirIncreaseAmount; - maximum = _this$storeOptions.reservoirIncreaseMaximum; - reservoir = _this$storeOptions.reservoir; - this._lastReservoirIncrease = now; - incr = maximum != null ? Math.min(amount, maximum - reservoir) : amount; + if (this._first == null) { + return; + } else { + this.length--; - if (incr > 0) { - this.storeOptions.reservoir += incr; - return this.instance._drainAll(this.computeCapacity()); - } - } - }, this.heartbeatInterval)).unref === "function" ? base.unref() : void 0; + if (typeof this.decr === "function") { + this.decr(); + } + } + + value = this._first.value; + + if ((this._first = this._first.next) != null) { + this._first.prev = null; } else { - return clearInterval(this.heartbeat); + this._last = null; } - } - __publish__(message) { - var _this = this; + return value; + } - return _asyncToGenerator(function* () { - yield _this.yieldLoop(); - return _this.instance.Events.trigger("message", message.toString()); - })(); + first() { + if (this._first != null) { + return this._first.value; + } } - __disconnect__(flush) { - var _this2 = this; + getArray() { + var node, ref, results; + node = this._first; + results = []; - return _asyncToGenerator(function* () { - yield _this2.yieldLoop(); - clearInterval(_this2.heartbeat); - return _this2.Promise.resolve(); - })(); - } + while (node != null) { + results.push((ref = node, node = node.next, ref.value)); + } - yieldLoop(t = 0) { - return new this.Promise(function (resolve, reject) { - return setTimeout(resolve, t); - }); + return results; } - computePenalty() { - var ref; - return (ref = this.storeOptions.penalty) != null ? ref : 15 * this.storeOptions.minTime || 5000; - } + forEachShift(cb) { + var node; + node = this.shift(); - __updateSettings__(options) { - var _this3 = this; + while (node != null) { + cb(node), node = this.shift(); + } - return _asyncToGenerator(function* () { - yield _this3.yieldLoop(); - parser.overwrite(options, options, _this3.storeOptions); + return void 0; + } - _this3._startHeartbeat(); + debug() { + var node, ref, ref1, ref2, results; + node = this._first; + results = []; - _this3.instance._drainAll(_this3.computeCapacity()); + while (node != null) { + results.push((ref = node, node = node.next, { + value: ref.value, + prev: (ref1 = ref.prev) != null ? ref1.value : void 0, + next: (ref2 = ref.next) != null ? ref2.value : void 0 + })); + } - return true; - })(); + return results; } - __running__() { - var _this4 = this; +}; +module.exports = DLList; - return _asyncToGenerator(function* () { - yield _this4.yieldLoop(); - return _this4._running; - })(); - } +/***/ }), - __queued__() { - var _this5 = this; +/***/ 107: +/***/ ((module) => { - return _asyncToGenerator(function* () { - yield _this5.yieldLoop(); - return _this5.instance.queued(); - })(); - } +"use strict"; - __done__() { - var _this6 = this; - return _asyncToGenerator(function* () { - yield _this6.yieldLoop(); - return _this6._done; - })(); - } +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); } } - __groupCheck__(time) { - var _this7 = 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); }); }; } - return _asyncToGenerator(function* () { - yield _this7.yieldLoop(); - return _this7._nextRequest + _this7.timeout < time; - })(); +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 = {}; + } + }; } - computeCapacity() { - var maxConcurrent, reservoir; - var _this$storeOptions2 = this.storeOptions; - maxConcurrent = _this$storeOptions2.maxConcurrent; - reservoir = _this$storeOptions2.reservoir; + _addListener(name, status, cb) { + var base; - 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; + if ((base = this._events)[name] == null) { + base[name] = []; } + + this._events[name].push({ + cb, + status + }); + + return this.instance; } - conditionsCheck(weight) { - var capacity; - capacity = this.computeCapacity(); - return capacity == null || weight <= capacity; + listenerCount(name) { + if (this._events[name] != null) { + return this._events[name].length; + } else { + return 0; + } } - __incrementReservoir__(incr) { - var _this8 = this; + trigger(name, ...args) { + var _this = this; return _asyncToGenerator(function* () { - var reservoir; - yield _this8.yieldLoop(); - reservoir = _this8.storeOptions.reservoir += incr; - - _this8.instance._drainAll(_this8.computeCapacity()); + var e, promises; - return reservoir; - })(); - } + try { + if (name !== "debug") { + _this.trigger("debug", `Event triggered: ${name}`, args); + } - __currentReservoir__() { - var _this9 = this; + if (_this._events[name] == null) { + return; + } - return _asyncToGenerator(function* () { - yield _this9.yieldLoop(); - return _this9.storeOptions.reservoir; - })(); - } + _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; - isBlocked(now) { - return this._unblockTime >= now; - } + if (listener.status === "none") { + return; + } - check(weight, now) { - return this.conditionsCheck(weight) && this._nextRequest - now <= 0; - } + if (listener.status === "once") { + listener.status = "none"; + } - __check__(weight) { - var _this10 = this; + try { + returned = typeof listener.cb === "function" ? listener.cb(...args) : void 0; - return _asyncToGenerator(function* () { - var now; - yield _this10.yieldLoop(); - now = Date.now(); - return _this10.check(weight, now); - })(); - } + if (typeof (returned != null ? returned.then : void 0) === "function") { + return yield returned; + } else { + return returned; + } + } catch (error) { + e = error; - __register__(index, weight, expiration) { - var _this11 = this; + if (true) { + _this.trigger("error", e); + } - return _asyncToGenerator(function* () { - var now, wait; - yield _this11.yieldLoop(); - now = Date.now(); + return null; + } + }); - if (_this11.conditionsCheck(weight)) { - _this11._running += weight; + return function (_x) { + return _ref.apply(this, arguments); + }; + }()); + return (yield Promise.all(promises)).find(function (x) { + return x != null; + }); + } catch (error) { + e = error; - if (_this11.storeOptions.reservoir != null) { - _this11.storeOptions.reservoir -= weight; + if (true) { + _this.trigger("error", e); } - 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 - }; + return null; } })(); } - strategyIsBlock() { - return this.storeOptions.strategy === 3; - } +}; +module.exports = Events; - __submit__(queueLength, weight) { - var _this12 = this; +/***/ }), - return _asyncToGenerator(function* () { - var blocked, now, reachedHWM; - yield _this12.yieldLoop(); +/***/ 53068: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - 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}`); - } +"use strict"; - 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; +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } - _this12.instance._dropAllQueued(); - } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } - return { - reachedHWM, - blocked, - strategy: _this12.storeOptions.strategy - }; - })(); - } +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; } - __free__(index, weight) { - var _this13 = this; +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } - return _asyncToGenerator(function* () { - yield _this13.yieldLoop(); - _this13._running -= weight; - _this13._done += weight; +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); } } - _this13.instance._drainAll(_this13.computeCapacity()); +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); }); }; } - return { - running: _this13._running - }; - })(); - } +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); -}; -module.exports = LocalDatastore; +Group = function () { + class Group { + constructor(limiterOptions = {}) { + this.deleteKey = this.deleteKey.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(); -/***/ 65893: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + this.sharedConnection = this.connection != null; -"use strict"; + 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 + })); + } + } + } + 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; + })(); + } -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; + deleteKey(key = "") { + var _this = this; - this._lists = function () { - var j, ref, results; + return _asyncToGenerator(function* () { + var deleted, instance; + instance = _this.instances[key]; + + if (_this.connection) { + deleted = yield _this.connection.__runCommand__(['del', ...Scripts.allKeys(`${_this.id}-${key}`)]); + } + + if (instance != null) { + delete _this.instances[key]; + yield instance.disconnect(); + } + + return instance != null || deleted > 0; + })(); + } + + limiters() { + var k, ref, results, v; + ref = this.instances; results = []; - for (i = j = 1, ref = num_priorities; 1 <= ref ? j <= ref : j >= ref; i = 1 <= ref ? ++j : --j) { - results.push(new DLList(() => { - return this.incr(); - }, () => { - return this.decr(); - })); + for (k in ref) { + v = ref[k]; + results.push({ + key: k, + limiter: v + }); } return results; - }.call(this); - } + } - incr() { - if (this._length++ === 0) { - return this.Events.trigger("leftzero"); + keys() { + return Object.keys(this.instances); } - } - decr() { - if (--this._length === 0) { - return this.Events.trigger("zero"); + 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; + + while (cursor !== 0) { + var _ref = yield _this2.connection.__runCommand__(["scan", cursor != null ? cursor : 0, "match", `b_${_this2.id}-*_settings`, "count", 10000]); + + 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)); + } + } + + return keys; + })(); } - } - push(job) { - return this._lists[job.options.priority].push(job); - } + _startAutoCleanup() { + var _this3 = this; - queued(priority) { - if (priority != null) { - return this._lists[priority].length; - } else { - return this._length; + 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)); + } + } + + return results; + }), this.timeout / 2)).unref === "function" ? base.unref() : void 0; } - } - shiftAll(fn) { - return this._lists.forEach(function (list) { - return list.forEachShift(fn); - }); - } + updateSettings(options = {}) { + parser.overwrite(options, this.defaults, this); + parser.overwrite(options, options, this.limiterOptions); - getFirst(arr = this._lists) { - var j, len, list; + if (options.timeout != null) { + return this._startAutoCleanup(); + } + } - for (j = 0, len = arr.length; j < len; j++) { - list = arr[j]; + disconnect(flush = true) { + var ref; - if (list.length > 0) { - return list; + if (!this.sharedConnection) { + return (ref = this.connection) != null ? ref.disconnect(flush) : void 0; } } - return []; } - shiftLastFrom(priority) { - return this.getFirst(this._lists.slice(priority).reverse()).shift(); - } + ; + Group.prototype.defaults = { + timeout: 1000 * 60 * 5, + connection: null, + Promise: Promise, + id: "group-key" + }; + return Group; +}.call(void 0); -}; -module.exports = Queues; +module.exports = Group; /***/ }), -/***/ 29992: +/***/ 47710: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "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, RedisConnection, Scripts, parser; +var Events, IORedisConnection, Scripts, parser; parser = __nccwpck_require__(67823); Events = __nccwpck_require__(107); Scripts = __nccwpck_require__(4169); -RedisConnection = function () { - class RedisConnection { +IORedisConnection = function () { + class IORedisConnection { constructor(options = {}) { parser.load(options, this.defaults, this); if (this.Redis == null) { - this.Redis = eval("require")("redis"); // Obfuscated or else Webpack/Angular will try to inline the optional redis module. To override this behavior: pass the redis module to Bottleneck as the 'Redis' option. + this.Redis = eval("require")("ioredis"); // Obfuscated or else Webpack/Angular will try to inline the optional ioredis module. To override this behavior: pass the ioredis module to Bottleneck as the 'Redis' option. } if (this.Events == null) { @@ -27229,16 +27219,23 @@ RedisConnection = function () { this.terminated = false; - if (this.client == null) { - this.client = this.Redis.createClient(this.clientOptions); + if (this.clusterNodes != null) { + this.client = new this.Redis.Cluster(this.clusterNodes, this.clientOptions); + this.subscriber = new this.Redis.Cluster(this.clusterNodes, this.clientOptions); + } else if (this.client != null && this.client.duplicate == null) { + this.subscriber = new this.Redis.Cluster(this.client.startupNodes, this.client.options); + } else { + if (this.client == null) { + this.client = new this.Redis(this.clientOptions); + } + + this.subscriber = this.client.duplicate(); } - 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(() => { + this._loadScripts(); + return { client: this.client, subscriber: this.subscriber @@ -27260,4879 +27257,5036 @@ RedisConnection = function () { }); } - if (client.ready) { + if (client.status === "ready") { return resolve(); } else { return client.once("ready", resolve); } }); - } - - _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); - } - - this.shas[name] = replies[0]; - return resolve(replies[0]); - }); - }); - } - - _loadScripts() { - return this.Promise.all(Scripts.names.map(k => { - return this._loadScript(k); - })); - } - - __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]); - } - }); - }); - })(); - } - - __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 = { - Redis: null, - clientOptions: {}, - client: null, - Promise: Promise, - Events: null - }; - return RedisConnection; -}.call(void 0); - -module.exports = RedisConnection; - -/***/ }), - -/***/ 4946: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"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({ - Redis: this.Redis, - clientOptions: this.clientOptions, - Promise: this.Promise, - Events: this.instance.Events - }) : this.instance.datastore === "ioredis" ? new IORedisConnection({ - Redis: this.Redis, - clientOptions: this.clientOptions, - clusterNodes: this.clusterNodes, - Promise: this.Promise, - Events: this.instance.Events - }) : void 0; - } - - 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); + _loadScripts() { + return Scripts.names.forEach(name => { + return this.client.defineCommand(name, { + lua: Scripts.payload(name) }); - }, this.heartbeatInterval)).unref === "function") { - base.unref(); - } - - return this.clients; - }); - } + }); + } - __publish__(message) { - var _this = this; + __runCommand__(cmd) { + var _this = this; - return _asyncToGenerator(function* () { - var client; + return _asyncToGenerator(function* () { + var _, deleted; - var _ref = yield _this.ready; + yield _this.ready; - client = _ref.client; - return client.publish(_this.instance.channel(), `message:${message.toString()}`); - })(); - } + var _ref = yield _this.client.pipeline([cmd]).exec(); - onMessage(channel, message) { - var _this2 = this; + var _ref2 = _slicedToArray(_ref, 1); - return _asyncToGenerator(function* () { - var capacity, counter, data, drained, e, newCapacity, pos, priorityClient, rawCapacity, type; + var _ref2$ = _slicedToArray(_ref2[0], 2); - try { - pos = message.indexOf(":"); - var _ref2 = [message.slice(0, pos), message.slice(pos + 1)]; - type = _ref2[0]; - data = _ref2[1]; + _ = _ref2$[0]; + deleted = _ref2$[1]; + return deleted; + })(); + } - if (type === "capacity") { - return yield _this2.instance._drainAll(data.length > 0 ? ~~data : void 0); - } else if (type === "capacity-priority") { - var _data$split = data.split(":"); + __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(); + }); + }); + })); + } - var _data$split2 = _slicedToArray(_data$split, 3); + __removeLimiter__(instance) { + var _this2 = this; - rawCapacity = _data$split2[0]; - priorityClient = _data$split2[1]; - counter = _data$split2[2]; - capacity = rawCapacity.length > 0 ? ~~rawCapacity : void 0; + return [instance.channel(), instance.channel_client()].forEach( + /*#__PURE__*/ + function () { + var _ref3 = _asyncToGenerator(function* (channel) { + if (!_this2.terminated) { + yield _this2.subscriber.unsubscribe(channel); + } - 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; + return delete _this2.limiters[channel]; + }); - 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); - } - })(); - } + return function (_x) { + return _ref3.apply(this, arguments); + }; + }()); + } - __disconnect__(flush) { - clearInterval(this.heartbeat); + __scriptArgs__(name, id, args, cb) { + var keys; + keys = Scripts.keys(name, id); + return [keys.length].concat(keys, args, cb); + } - if (this.sharedConnection) { - return this.connection.__removeLimiter__(this.instance); - } else { - return this.connection.disconnect(flush); + __scriptFn__(name) { + return this.client[name].bind(this.client); } - } - runScript(name, args) { - var _this3 = this; + disconnect(flush = true) { + var i, k, len, ref; + ref = Object.keys(this.limiters); - return _asyncToGenerator(function* () { - if (!(name === "init" || name === "register_client")) { - yield _this3.ready; + for (i = 0, len = ref.length; i < len; i++) { + k = ref[i]; + clearInterval(this.limiters[k]._store.heartbeat); } - 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); + this.limiters = {}; + this.terminated = true; - arr = _this3.connection.__scriptArgs__(name, _this3.originalId, all_args, function (err, replies) { - if (err != null) { - return reject(err); - } + if (flush) { + return this.Promise.all([this.client.quit(), this.subscriber.quit()]); + } else { + this.client.disconnect(); + this.subscriber.disconnect(); + return this.Promise.resolve(); + } + } - 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); - } - }); - })(); } - prepareArray(arr) { - var i, len, results, x; - results = []; + ; + IORedisConnection.prototype.datastore = "ioredis"; + IORedisConnection.prototype.defaults = { + Redis: null, + clientOptions: {}, + clusterNodes: null, + client: null, + Promise: Promise, + Events: null + }; + return IORedisConnection; +}.call(void 0); - for (i = 0, len = arr.length; i < len; i++) { - x = arr[i]; - results.push(x != null ? x.toString() : ""); - } +module.exports = IORedisConnection; - return results; - } +/***/ }), - prepareObject(obj) { - var arr, k, v; - arr = []; +/***/ 25949: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - for (k in obj) { - v = obj[k]; - arr.push(k, v != null ? v.toString() : ""); - } +"use strict"; - 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; - } +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); } } - convertBool(b) { - return !!b; +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, DEFAULT_PRIORITY, Job, NUM_PRIORITIES, parser; +NUM_PRIORITIES = 10; +DEFAULT_PRIORITY = 5; +parser = __nccwpck_require__(67823); +BottleneckError = __nccwpck_require__(93529); +Job = class Job { + constructor(task, args, options, jobDefaults, rejectOnDrop, Events, _states, Promise) { + this.task = task; + this.args = args; + this.rejectOnDrop = rejectOnDrop; + this.Events = Events; + this._states = _states; + this.Promise = Promise; + this.options = parser.load(options, jobDefaults); + this.options.priority = this._sanitizePriority(this.options.priority); + + if (this.options.id === jobDefaults.id) { + this.options.id = `${this.options.id}-${this._randomIndex()}`; + } + + this.promise = new this.Promise((_resolve, _reject) => { + this._resolve = _resolve; + this._reject = _reject; + }); + this.retryCount = 0; } - __updateSettings__(options) { - var _this4 = this; + _sanitizePriority(priority) { + var sProperty; + sProperty = ~~priority !== priority ? DEFAULT_PRIORITY : priority; - return _asyncToGenerator(function* () { - yield _this4.runScript("update_settings", _this4.prepareObject(options)); - return parser.overwrite(options, options, _this4.storeOptions); - })(); + if (sProperty < 0) { + return 0; + } else if (sProperty > NUM_PRIORITIES - 1) { + return NUM_PRIORITIES - 1; + } else { + return sProperty; + } } - __running__() { - return this.runScript("running", []); + _randomIndex() { + return Math.random().toString(36).slice(2); } - __queued__() { - return this.runScript("queued", []); - } + doDrop({ + error, + message = "This job has been dropped by Bottleneck" + } = {}) { + if (this._states.remove(this.options.id)) { + if (this.rejectOnDrop) { + this._reject(error != null ? error : new BottleneckError(message)); + } - __done__() { - return this.runScript("done", []); + this.Events.trigger("dropped", { + args: this.args, + options: this.options, + task: this.task, + promise: this.promise + }); + return true; + } else { + return false; + } } - __groupCheck__() { - var _this5 = this; + _assertStatus(expected) { + var status; + status = this._states.jobStatus(this.options.id); - return _asyncToGenerator(function* () { - return _this5.convertBool((yield _this5.runScript("group_check", []))); - })(); + if (!(status === expected || expected === "DONE" && status === null)) { + throw new BottleneckError(`Invalid job status ${status}, expected ${expected}. Please open an issue at https://github.com/SGrondin/bottleneck/issues`); + } } - __incrementReservoir__(incr) { - return this.runScript("increment_reservoir", [incr]); + doReceive() { + this._states.start(this.options.id); + + return this.Events.trigger("received", { + args: this.args, + options: this.options + }); } - __currentReservoir__() { - return this.runScript("current_reservoir", []); + doQueue(reachedHWM, blocked) { + this._assertStatus("RECEIVED"); + + this._states.next(this.options.id); + + return this.Events.trigger("queued", { + args: this.args, + options: this.options, + reachedHWM, + blocked + }); } - __check__(weight) { - var _this6 = this; + doRun() { + if (this.retryCount === 0) { + this._assertStatus("QUEUED"); - return _asyncToGenerator(function* () { - return _this6.convertBool((yield _this6.runScript("check", _this6.prepareArray([weight])))); - })(); + this._states.next(this.options.id); + } else { + this._assertStatus("EXECUTING"); + } + + return this.Events.trigger("scheduled", { + args: this.args, + options: this.options + }); } - __register__(index, weight, expiration) { - var _this7 = this; + doExecute(chained, clearGlobalState, run, free) { + var _this = this; return _asyncToGenerator(function* () { - var reservoir, success, wait; + var error, eventInfo, passed; - var _ref4 = yield _this7.runScript("register", _this7.prepareArray([index, weight, expiration])); + if (_this.retryCount === 0) { + _this._assertStatus("RUNNING"); - var _ref5 = _slicedToArray(_ref4, 3); + _this._states.next(_this.options.id); + } else { + _this._assertStatus("EXECUTING"); + } - success = _ref5[0]; - wait = _ref5[1]; - reservoir = _ref5[2]; - return { - success: _this7.convertBool(success), - wait, - reservoir + eventInfo = { + args: _this.args, + options: _this.options, + retryCount: _this.retryCount }; - })(); - } - - __submit__(queueLength, weight) { - var _this8 = this; - return _asyncToGenerator(function* () { - var blocked, e, maxConcurrent, overweight, reachedHWM, strategy; + _this.Events.trigger("executing", eventInfo); try { - var _ref6 = yield _this8.runScript("submit", _this8.prepareArray([queueLength, weight])); - - var _ref7 = _slicedToArray(_ref6, 3); + passed = yield chained != null ? chained.schedule(_this.options, _this.task, ..._this.args) : _this.task(..._this.args); - reachedHWM = _ref7[0]; - blocked = _ref7[1]; - strategy = _ref7[2]; - return { - reachedHWM: _this8.convertBool(reachedHWM), - blocked: _this8.convertBool(blocked), - strategy - }; - } catch (error) { - e = error; + if (clearGlobalState()) { + _this.doDone(eventInfo); - if (e.message.indexOf("OVERWEIGHT") === 0) { - var _e$message$split = e.message.split(":"); + yield free(_this.options, eventInfo); - var _e$message$split2 = _slicedToArray(_e$message$split, 3); + _this._assertStatus("DONE"); - 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 _this._resolve(passed); } + } catch (error1) { + error = error1; + return _this._onFailure(error, eventInfo, clearGlobalState, run, free); } })(); } - __free__(index, weight) { - var _this9 = this; + doExpire(clearGlobalState, run, free) { + var error, eventInfo; - return _asyncToGenerator(function* () { - var running; - running = yield _this9.runScript("free", _this9.prepareArray([index])); - return { - running - }; - })(); - } + if (this._states.jobStatus(this.options.id === "RUNNING")) { + this._states.next(this.options.id); + } -}; -module.exports = RedisDatastore; + this._assertStatus("EXECUTING"); -/***/ }), + eventInfo = { + args: this.args, + options: this.options, + retryCount: this.retryCount + }; + error = new BottleneckError(`This job timed out after ${this.options.expiration} ms.`); + return this._onFailure(error, eventInfo, clearGlobalState, run, free); + } -/***/ 4169: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + _onFailure(error, eventInfo, clearGlobalState, run, free) { + var _this2 = this; -"use strict"; + return _asyncToGenerator(function* () { + var retry, retryAfter; + if (clearGlobalState()) { + retry = yield _this2.Events.trigger("failed", error, eventInfo); -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"] -}; + if (retry != null) { + retryAfter = ~~retry; -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`]; -}; + _this2.Events.trigger("retry", `Retrying ${_this2.options.id} after ${retryAfter} ms`, eventInfo); + + _this2.retryCount++; + return run(retryAfter); + } else { + _this2.doDone(eventInfo); -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"] + yield free(_this2.options, eventInfo); + + _this2._assertStatus("DONE"); + + return _this2._reject(error); + } + } + })(); } -}; -exports.names = Object.keys(templates); -exports.keys = function (name, id) { - return templates[name].keys(id); -}; + doDone(eventInfo) { + this._assertStatus("EXECUTING"); + + this._states.next(this.options.id); + + return this.Events.trigger("done", eventInfo); + } -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"); }; +module.exports = Job; /***/ }), -/***/ 2527: +/***/ 38979: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -var BottleneckError, States; +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, LocalDatastore, parser; +parser = __nccwpck_require__(67823); BottleneckError = __nccwpck_require__(93529); -States = class States { - constructor(status1) { - this.status = status1; - this._jobs = {}; - this.counts = this.status.map(function () { - return 0; - }); +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 = this._lastReservoirIncrease = Date.now(); + this._running = 0; + this._done = 0; + this._unblockTime = 0; + this.ready = this.Promise.resolve(); + this.clients = {}; + + this._startHeartbeat(); } - next(id) { - var current, next; - current = this._jobs[id]; - next = current + 1; + _startHeartbeat() { + var base; - 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]; + if (this.heartbeat == null && (this.storeOptions.reservoirRefreshInterval != null && this.storeOptions.reservoirRefreshAmount != null || this.storeOptions.reservoirIncreaseInterval != null && this.storeOptions.reservoirIncreaseAmount != null)) { + return typeof (base = this.heartbeat = setInterval(() => { + var amount, incr, maximum, now, reservoir; + now = Date.now(); + + if (this.storeOptions.reservoirRefreshInterval != null && now >= this._lastReservoirRefresh + this.storeOptions.reservoirRefreshInterval) { + this._lastReservoirRefresh = now; + this.storeOptions.reservoir = this.storeOptions.reservoirRefreshAmount; + + this.instance._drainAll(this.computeCapacity()); + } + + if (this.storeOptions.reservoirIncreaseInterval != null && now >= this._lastReservoirIncrease + this.storeOptions.reservoirIncreaseInterval) { + var _this$storeOptions = this.storeOptions; + amount = _this$storeOptions.reservoirIncreaseAmount; + maximum = _this$storeOptions.reservoirIncreaseMaximum; + reservoir = _this$storeOptions.reservoir; + this._lastReservoirIncrease = now; + incr = maximum != null ? Math.min(amount, maximum - reservoir) : amount; + + if (incr > 0) { + this.storeOptions.reservoir += incr; + return this.instance._drainAll(this.computeCapacity()); + } + } + }, this.heartbeatInterval)).unref === "function" ? base.unref() : void 0; + } else { + return clearInterval(this.heartbeat); } } - start(id) { - var initial; - initial = 0; - this._jobs[id] = initial; - return this.counts[initial]++; + __publish__(message) { + var _this = this; + + return _asyncToGenerator(function* () { + yield _this.yieldLoop(); + return _this.instance.Events.trigger("message", message.toString()); + })(); } - remove(id) { - var current; - current = this._jobs[id]; + __disconnect__(flush) { + var _this2 = this; - if (current != null) { - this.counts[current]--; - delete this._jobs[id]; - } + return _asyncToGenerator(function* () { + yield _this2.yieldLoop(); + clearInterval(_this2.heartbeat); + return _this2.Promise.resolve(); + })(); + } - return current != null; + yieldLoop(t = 0) { + return new this.Promise(function (resolve, reject) { + return setTimeout(resolve, t); + }); } - jobStatus(id) { + computePenalty() { var ref; - return (ref = this.status[this._jobs[id]]) != null ? ref : null; + 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; + + return _asyncToGenerator(function* () { + yield _this4.yieldLoop(); + return _this4._running; + })(); + } + + __queued__() { + var _this5 = this; + + return _asyncToGenerator(function* () { + yield _this5.yieldLoop(); + return _this5.instance.queued(); + })(); } - statusJobs(status) { - var k, pos, ref, results, v; - - if (status != null) { - pos = this.status.indexOf(status); + __done__() { + var _this6 = this; - if (pos < 0) { - throw new BottleneckError(`status must be one of ${this.status.join(', ')}`); - } + return _asyncToGenerator(function* () { + yield _this6.yieldLoop(); + return _this6._done; + })(); + } - ref = this._jobs; - results = []; + __groupCheck__(time) { + var _this7 = this; - for (k in ref) { - v = ref[k]; + return _asyncToGenerator(function* () { + yield _this7.yieldLoop(); + return _this7._nextRequest + _this7.timeout < time; + })(); + } - if (v === pos) { - results.push(k); - } - } + computeCapacity() { + var maxConcurrent, reservoir; + var _this$storeOptions2 = this.storeOptions; + maxConcurrent = _this$storeOptions2.maxConcurrent; + reservoir = _this$storeOptions2.reservoir; - return results; + 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 Object.keys(this._jobs); + return null; } } - statusCounts() { - return this.counts.reduce((acc, v, i) => { - acc[this.status[i]] = v; - return acc; - }, {}); + conditionsCheck(weight) { + var capacity; + capacity = this.computeCapacity(); + return capacity == null || weight <= capacity; } -}; -module.exports = States; - -/***/ }), + __incrementReservoir__(incr) { + var _this8 = this; -/***/ 56029: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return _asyncToGenerator(function* () { + var reservoir; + yield _this8.yieldLoop(); + reservoir = _this8.storeOptions.reservoir += incr; -"use strict"; + _this8.instance._drainAll(_this8.computeCapacity()); + return reservoir; + })(); + } -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); } } + __currentReservoir__() { + var _this9 = 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); }); }; } + return _asyncToGenerator(function* () { + yield _this9.yieldLoop(); + return _this9.storeOptions.reservoir; + })(); + } -var DLList, Sync; -DLList = __nccwpck_require__(38579); -Sync = class Sync { - constructor(name, Promise) { - this.schedule = this.schedule.bind(this); - this.name = name; - this.Promise = Promise; - this._running = 0; - this._queue = new DLList(); + isBlocked(now) { + return this._unblockTime >= now; } - isEmpty() { - return this._queue.length === 0; + check(weight, now) { + return this.conditionsCheck(weight) && this._nextRequest - now <= 0; } - _tryToRun() { - var _this = this; + __check__(weight) { + var _this10 = this; return _asyncToGenerator(function* () { - var args, cb, error, reject, resolve, returned, task; + var now; + yield _this10.yieldLoop(); + now = Date.now(); + return _this10.check(weight, now); + })(); + } - if (_this._running < 1 && _this._queue.length > 0) { - _this._running++; + __register__(index, weight, expiration) { + var _this11 = this; - var _this$_queue$shift = _this._queue.shift(); + return _asyncToGenerator(function* () { + var now, wait; + yield _this11.yieldLoop(); + now = Date.now(); - task = _this$_queue$shift.task; - args = _this$_queue$shift.args; - resolve = _this$_queue$shift.resolve; - reject = _this$_queue$shift.reject; - cb = yield _asyncToGenerator(function* () { - try { - returned = yield task(...args); - return function () { - return resolve(returned); - }; - } catch (error1) { - error = error1; - return function () { - return reject(error); - }; - } - })(); - _this._running--; + if (_this11.conditionsCheck(weight)) { + _this11._running += weight; - _this._tryToRun(); + if (_this11.storeOptions.reservoir != null) { + _this11.storeOptions.reservoir -= weight; + } - return cb(); + 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 + }; } })(); } - schedule(task, ...args) { - var promise, reject, resolve; - resolve = reject = null; - promise = new this.Promise(function (_resolve, _reject) { - resolve = _resolve; - return reject = _reject; - }); - - this._queue.push({ - task, - args, - resolve, - reject - }); - - this._tryToRun(); - - return promise; + strategyIsBlock() { + return this.storeOptions.strategy === 3; } -}; -module.exports = Sync; - -/***/ }), - -/***/ 27356: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -module.exports = __nccwpck_require__(83911); + __submit__(queueLength, weight) { + var _this12 = this; -/***/ }), + return _asyncToGenerator(function* () { + var blocked, now, reachedHWM; + yield _this12.yieldLoop(); -/***/ 67823: -/***/ ((__unused_webpack_module, exports) => { + 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}`); + } -"use strict"; + 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; -exports.load = function (received, defaults, onto = {}) { - var k, ref, v; + _this12.instance._dropAllQueued(); + } - for (k in defaults) { - v = defaults[k]; - onto[k] = (ref = received[k]) != null ? ref : v; + return { + reachedHWM, + blocked, + strategy: _this12.storeOptions.strategy + }; + })(); } - return onto; -}; + __free__(index, weight) { + var _this13 = this; -exports.overwrite = function (received, defaults, onto = {}) { - var k, v; + return _asyncToGenerator(function* () { + yield _this13.yieldLoop(); + _this13._running -= weight; + _this13._done += weight; - for (k in received) { - v = received[k]; + _this13.instance._drainAll(_this13.computeCapacity()); - if (defaults[k] !== void 0) { - onto[k] = v; - } + return { + running: _this13._running + }; + })(); } - return onto; -}; - -/***/ }), - -/***/ 11174: -/***/ (function(module) { - -/** - * 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 globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; - - function getCjsExportFromNamespace (n) { - return n && n['default'] || n; - } +}; +module.exports = LocalDatastore; - 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; - }; +/***/ 65893: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - var parser = { - load: load, - overwrite: overwrite - }; +"use strict"; - var DLList; - DLList = class DLList { - constructor(incr, decr) { - this.incr = incr; - this.decr = decr; - this._first = null; - this._last = null; - this.length = 0; - } +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; - push(value) { - var node; - this.length++; - if (typeof this.incr === "function") { - this.incr(); - } - node = { - value, - prev: this._last, - next: null - }; - if (this._last != null) { - this._last.next = node; - this._last = node; - } else { - this._first = this._last = node; - } - return void 0; - } + this._lists = function () { + var j, ref, results; + results = []; - shift() { - var value; - if (this._first == null) { - return; - } else { - this.length--; - if (typeof this.decr === "function") { - this.decr(); - } - } - value = this._first.value; - if ((this._first = this._first.next) != null) { - this._first.prev = null; - } else { - this._last = null; - } - return value; - } + for (i = j = 1, ref = num_priorities; 1 <= ref ? j <= ref : j >= ref; i = 1 <= ref ? ++j : --j) { + results.push(new DLList(() => { + return this.incr(); + }, () => { + return this.decr(); + })); + } - first() { - if (this._first != null) { - return this._first.value; - } - } + return results; + }.call(this); + } - getArray() { - var node, ref, results; - node = this._first; - results = []; - while (node != null) { - results.push((ref = node, node = node.next, ref.value)); - } - return results; - } + incr() { + if (this._length++ === 0) { + return this.Events.trigger("leftzero"); + } + } - forEachShift(cb) { - var node; - node = this.shift(); - while (node != null) { - (cb(node), node = this.shift()); - } - return void 0; - } + decr() { + if (--this._length === 0) { + return this.Events.trigger("zero"); + } + } - debug() { - var node, ref, ref1, ref2, results; - node = this._first; - results = []; - while (node != null) { - results.push((ref = node, node = node.next, { - value: ref.value, - prev: (ref1 = ref.prev) != null ? ref1.value : void 0, - next: (ref2 = ref.next) != null ? ref2.value : void 0 - })); - } - return results; - } + push(job) { + return this._lists[job.options.priority].push(job); + } - }; + queued(priority) { + if (priority != null) { + return this._lists[priority].length; + } else { + return this._length; + } + } - var DLList_1 = DLList; + shiftAll(fn) { + return this._lists.forEach(function (list) { + return list.forEachShift(fn); + }); + } - var Events; + getFirst(arr = this._lists) { + var j, len, list; - 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 = {}; - } - }; - } + for (j = 0, len = arr.length; j < len; j++) { + list = arr[j]; - _addListener(name, status, cb) { - var base; - if ((base = this._events)[name] == null) { - base[name] = []; - } - this._events[name].push({cb, status}); - return this.instance; - } + if (list.length > 0) { + return list; + } + } - listenerCount(name) { - if (this._events[name] != null) { - return this._events[name].length; - } else { - return 0; - } - } + return []; + } - 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; - } - } + shiftLastFrom(priority) { + return this.getFirst(this._lists.slice(priority).reverse()).shift(); + } - }; +}; +module.exports = Queues; - var Events_1 = Events; +/***/ }), - var DLList$1, Events$1, Queues; +/***/ 29992: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - DLList$1 = DLList_1; +"use strict"; - Events$1 = Events_1; - 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((() => { - return this.incr(); - }), (() => { - return this.decr(); - }))); - } - return results; - }).call(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); } } - incr() { - if (this._length++ === 0) { - return this.Events.trigger("leftzero"); - } - } +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); }); }; } - decr() { - if (--this._length === 0) { - return this.Events.trigger("zero"); - } - } +var Events, RedisConnection, Scripts, parser; +parser = __nccwpck_require__(67823); +Events = __nccwpck_require__(107); +Scripts = __nccwpck_require__(4169); - push(job) { - return this._lists[job.options.priority].push(job); - } +RedisConnection = function () { + class RedisConnection { + constructor(options = {}) { + parser.load(options, this.defaults, this); - queued(priority) { - if (priority != null) { - return this._lists[priority].length; - } else { - return this._length; - } - } + if (this.Redis == null) { + this.Redis = eval("require")("redis"); // Obfuscated or else Webpack/Angular will try to inline the optional redis module. To override this behavior: pass the redis module to Bottleneck as the 'Redis' option. + } - shiftAll(fn) { - return this._lists.forEach(function(list) { - return list.forEachShift(fn); - }); - } + if (this.Events == null) { + this.Events = new Events(this); + } - 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 []; - } + this.terminated = false; - shiftLastFrom(priority) { - return this.getFirst(this._lists.slice(priority).reverse()).shift(); - } + if (this.client == null) { + this.client = this.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 + }; + }); + } - var Queues_1 = Queues; + _setup(client, sub) { + client.setMaxListeners(0); + return new this.Promise((resolve, reject) => { + client.on("error", e => { + return this.Events.trigger("error", e); + }); - var BottleneckError; + if (sub) { + client.on("message", (channel, message) => { + var ref; + return (ref = this.limiters[channel]) != null ? ref._store.onMessage(channel, message) : void 0; + }); + } - BottleneckError = class BottleneckError extends Error {}; + if (client.ready) { + return resolve(); + } else { + return client.once("ready", resolve); + } + }); + } - var BottleneckError_1 = BottleneckError; + _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); + } - var BottleneckError$1, DEFAULT_PRIORITY, Job, NUM_PRIORITIES, parser$1; + this.shas[name] = replies[0]; + return resolve(replies[0]); + }); + }); + } - NUM_PRIORITIES = 10; + _loadScripts() { + return this.Promise.all(Scripts.names.map(k => { + return this._loadScript(k); + })); + } - DEFAULT_PRIORITY = 5; + __runCommand__(cmd) { + var _this = this; - parser$1 = parser; + 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]); + } + }); + }); + })(); + } - BottleneckError$1 = BottleneckError_1; + __addLimiter__(instance) { + return this.Promise.all([instance.channel(), instance.channel_client()].map(channel => { + return new this.Promise((resolve, reject) => { + var handler; - Job = class Job { - constructor(task, args, options, jobDefaults, rejectOnDrop, Events, _states, Promise) { - this.task = task; - this.args = args; - this.rejectOnDrop = rejectOnDrop; - this.Events = Events; - this._states = _states; - this.Promise = Promise; - this.options = parser$1.load(options, jobDefaults); - this.options.priority = this._sanitizePriority(this.options.priority); - if (this.options.id === jobDefaults.id) { - this.options.id = `${this.options.id}-${this._randomIndex()}`; - } - this.promise = new this.Promise((_resolve, _reject) => { - this._resolve = _resolve; - this._reject = _reject; - }); - this.retryCount = 0; - } + handler = chan => { + if (chan === channel) { + this.subscriber.removeListener("subscribe", handler); + this.limiters[channel] = instance; + return resolve(); + } + }; - _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; - } - } + this.subscriber.on("subscribe", handler); + return this.subscriber.subscribe(channel); + }); + })); + } - _randomIndex() { - return Math.random().toString(36).slice(2); - } + __removeLimiter__(instance) { + var _this2 = this; - doDrop({error, message = "This job has been dropped by Bottleneck"} = {}) { - if (this._states.remove(this.options.id)) { - if (this.rejectOnDrop) { - this._reject(error != null ? error : new BottleneckError$1(message)); - } - this.Events.trigger("dropped", {args: this.args, options: this.options, task: this.task, promise: this.promise}); - return true; - } else { - return false; - } - } + 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); + } - _assertStatus(expected) { - var status; - status = this._states.jobStatus(this.options.id); - if (!(status === expected || (expected === "DONE" && status === null))) { - throw new BottleneckError$1(`Invalid job status ${status}, expected ${expected}. Please open an issue at https://github.com/SGrondin/bottleneck/issues`); - } - } + if (chan === channel) { + return resolve(); + } + }); + }); + } - doReceive() { - this._states.start(this.options.id); - return this.Events.trigger("received", {args: this.args, options: this.options}); - } + return delete _this2.limiters[channel]; + }); - doQueue(reachedHWM, blocked) { - this._assertStatus("RECEIVED"); - this._states.next(this.options.id); - return this.Events.trigger("queued", {args: this.args, options: this.options, reachedHWM, blocked}); - } + return function (_x) { + return _ref.apply(this, arguments); + }; + }())); + } - doRun() { - if (this.retryCount === 0) { - this._assertStatus("QUEUED"); - this._states.next(this.options.id); - } else { - this._assertStatus("EXECUTING"); - } - return this.Events.trigger("scheduled", {args: this.args, options: this.options}); - } + __scriptArgs__(name, id, args, cb) { + var keys; + keys = Scripts.keys(name, id); + return [this.shas[name], keys.length].concat(keys, args, cb); + } - async doExecute(chained, clearGlobalState, run, free) { - var error, eventInfo, passed; - if (this.retryCount === 0) { - this._assertStatus("RUNNING"); - this._states.next(this.options.id); - } else { - this._assertStatus("EXECUTING"); - } - eventInfo = {args: this.args, options: this.options, retryCount: this.retryCount}; - this.Events.trigger("executing", eventInfo); - try { - passed = (await (chained != null ? chained.schedule(this.options, this.task, ...this.args) : this.task(...this.args))); - if (clearGlobalState()) { - this.doDone(eventInfo); - await free(this.options, eventInfo); - this._assertStatus("DONE"); - return this._resolve(passed); - } - } catch (error1) { - error = error1; - return this._onFailure(error, eventInfo, clearGlobalState, run, free); - } - } + __scriptFn__(name) { + return this.client.evalsha.bind(this.client); + } - doExpire(clearGlobalState, run, free) { - var error, eventInfo; - if (this._states.jobStatus(this.options.id === "RUNNING")) { - this._states.next(this.options.id); - } - this._assertStatus("EXECUTING"); - eventInfo = {args: this.args, options: this.options, retryCount: this.retryCount}; - error = new BottleneckError$1(`This job timed out after ${this.options.expiration} ms.`); - return this._onFailure(error, eventInfo, clearGlobalState, run, free); - } + disconnect(flush = true) { + var i, k, len, ref; + ref = Object.keys(this.limiters); - async _onFailure(error, eventInfo, clearGlobalState, run, free) { - var retry, retryAfter; - if (clearGlobalState()) { - retry = (await this.Events.trigger("failed", error, eventInfo)); - if (retry != null) { - retryAfter = ~~retry; - this.Events.trigger("retry", `Retrying ${this.options.id} after ${retryAfter} ms`, eventInfo); - this.retryCount++; - return run(retryAfter); - } else { - this.doDone(eventInfo); - await free(this.options, eventInfo); - this._assertStatus("DONE"); - return this._reject(error); - } - } - } + for (i = 0, len = ref.length; i < len; i++) { + k = ref[i]; + clearInterval(this.limiters[k]._store.heartbeat); + } - doDone(eventInfo) { - this._assertStatus("EXECUTING"); - this._states.next(this.options.id); - return this.Events.trigger("done", eventInfo); - } + this.limiters = {}; + this.terminated = true; + this.client.end(flush); + this.subscriber.end(flush); + return this.Promise.resolve(); + } - }; + } - var Job_1 = Job; + ; + RedisConnection.prototype.datastore = "redis"; + RedisConnection.prototype.defaults = { + Redis: null, + clientOptions: {}, + client: null, + Promise: Promise, + Events: null + }; + return RedisConnection; +}.call(void 0); - var BottleneckError$2, LocalDatastore, parser$2; +module.exports = RedisConnection; - parser$2 = parser; +/***/ }), - BottleneckError$2 = BottleneckError_1; +/***/ 4946: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - LocalDatastore = class LocalDatastore { - constructor(instance, storeOptions, storeInstanceOptions) { - this.instance = instance; - this.storeOptions = storeOptions; - this.clientId = this.instance._randomIndex(); - parser$2.load(storeInstanceOptions, storeInstanceOptions, this); - this._nextRequest = this._lastReservoirRefresh = this._lastReservoirIncrease = Date.now(); - this._running = 0; - this._done = 0; - this._unblockTime = 0; - this.ready = this.Promise.resolve(); - this.clients = {}; - this._startHeartbeat(); - } +"use strict"; - _startHeartbeat() { - var base; - if ((this.heartbeat == null) && (((this.storeOptions.reservoirRefreshInterval != null) && (this.storeOptions.reservoirRefreshAmount != null)) || ((this.storeOptions.reservoirIncreaseInterval != null) && (this.storeOptions.reservoirIncreaseAmount != null)))) { - return typeof (base = (this.heartbeat = setInterval(() => { - var amount, incr, maximum, now, reservoir; - now = Date.now(); - if ((this.storeOptions.reservoirRefreshInterval != null) && now >= this._lastReservoirRefresh + this.storeOptions.reservoirRefreshInterval) { - this._lastReservoirRefresh = now; - this.storeOptions.reservoir = this.storeOptions.reservoirRefreshAmount; - this.instance._drainAll(this.computeCapacity()); - } - if ((this.storeOptions.reservoirIncreaseInterval != null) && now >= this._lastReservoirIncrease + this.storeOptions.reservoirIncreaseInterval) { - ({ - reservoirIncreaseAmount: amount, - reservoirIncreaseMaximum: maximum, - reservoir - } = this.storeOptions); - this._lastReservoirIncrease = now; - incr = maximum != null ? Math.min(amount, maximum - reservoir) : amount; - if (incr > 0) { - this.storeOptions.reservoir += incr; - 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()); - } +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } - async __disconnect__(flush) { - await this.yieldLoop(); - clearInterval(this.heartbeat); - return this.Promise.resolve(); - } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } - yieldLoop(t = 0) { - return new this.Promise(function(resolve, reject) { - return setTimeout(resolve, t); - }); - } +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; } - computePenalty() { - var ref; - return (ref = this.storeOptions.penalty) != null ? ref : (15 * this.storeOptions.minTime) || 5000; - } +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } - async __updateSettings__(options) { - await this.yieldLoop(); - parser$2.overwrite(options, options, this.storeOptions); - this._startHeartbeat(); - this.instance._drainAll(this.computeCapacity()); - return true; - } +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); } } - async __running__() { - await this.yieldLoop(); - return this._running; - } +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); }); }; } - async __queued__() { - await this.yieldLoop(); - return this.instance.queued(); - } +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; - async __done__() { - await this.yieldLoop(); - return this._done; - } + if (this.connection == null) { + this.connection = this.instance.datastore === "redis" ? new RedisConnection({ + Redis: this.Redis, + clientOptions: this.clientOptions, + Promise: this.Promise, + Events: this.instance.Events + }) : this.instance.datastore === "ioredis" ? new IORedisConnection({ + Redis: this.Redis, + clientOptions: this.clientOptions, + clusterNodes: this.clusterNodes, + Promise: this.Promise, + Events: this.instance.Events + }) : void 0; + } - async __groupCheck__(time) { - await this.yieldLoop(); - return (this._nextRequest + this.timeout) < time; - } + 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; - 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; - } - } + 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(); + } - conditionsCheck(weight) { - var capacity; - capacity = this.computeCapacity(); - return (capacity == null) || weight <= capacity; - } + return this.clients; + }); + } - async __incrementReservoir__(incr) { - var reservoir; - await this.yieldLoop(); - reservoir = this.storeOptions.reservoir += incr; - this.instance._drainAll(this.computeCapacity()); - return reservoir; - } + __publish__(message) { + var _this = this; - async __currentReservoir__() { - await this.yieldLoop(); - return this.storeOptions.reservoir; - } + return _asyncToGenerator(function* () { + var client; - isBlocked(now) { - return this._unblockTime >= now; - } + var _ref = yield _this.ready; - check(weight, now) { - return this.conditionsCheck(weight) && (this._nextRequest - now) <= 0; - } + client = _ref.client; + return client.publish(_this.instance.channel(), `message:${message.toString()}`); + })(); + } - async __check__(weight) { - var now; - await this.yieldLoop(); - now = Date.now(); - return this.check(weight, now); - } + onMessage(channel, message) { + var _this2 = this; - 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 - }; - } - } + return _asyncToGenerator(function* () { + var capacity, counter, data, drained, e, newCapacity, pos, priorityClient, rawCapacity, type; - strategyIsBlock() { - return this.storeOptions.strategy === 3; - } + try { + pos = message.indexOf(":"); + var _ref2 = [message.slice(0, pos), message.slice(pos + 1)]; + type = _ref2[0]; + data = _ref2[1]; - async __submit__(queueLength, weight) { - var blocked, now, reachedHWM; - await this.yieldLoop(); - if ((this.storeOptions.maxConcurrent != null) && weight > this.storeOptions.maxConcurrent) { - throw new BottleneckError$2(`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 - }; - } + if (type === "capacity") { + return yield _this2.instance._drainAll(data.length > 0 ? ~~data : void 0); + } else if (type === "capacity-priority") { + var _data$split = data.split(":"); - async __free__(index, weight) { - await this.yieldLoop(); - this._running -= weight; - this._done += weight; - this.instance._drainAll(this.computeCapacity()); - return { - running: this._running - }; - } + 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; - var LocalDatastore_1 = LocalDatastore; + 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; - var BottleneckError$3, States; + 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); + } + })(); + } - BottleneckError$3 = BottleneckError_1; + __disconnect__(flush) { + clearInterval(this.heartbeat); - States = class States { - constructor(status1) { - this.status = status1; - this._jobs = {}; - this.counts = this.status.map(function() { - return 0; - }); - } + if (this.sharedConnection) { + return this.connection.__removeLimiter__(this.instance); + } else { + return this.connection.disconnect(flush); + } + } - 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]; - } - } + runScript(name, args) { + var _this3 = this; - start(id) { - var initial; - initial = 0; - this._jobs[id] = initial; - return this.counts[initial]++; - } + return _asyncToGenerator(function* () { + if (!(name === "init" || name === "register_client")) { + yield _this3.ready; + } - remove(id) { - var current; - current = this._jobs[id]; - if (current != null) { - this.counts[current]--; - delete this._jobs[id]; - } - return current != null; - } + return new _this3.Promise((resolve, reject) => { + var all_args, arr; + all_args = [Date.now(), _this3.clientId].concat(args); - jobStatus(id) { - var ref; - return (ref = this.status[this._jobs[id]]) != null ? ref : null; - } + _this3.instance.Events.trigger("debug", `Calling Redis script: ${name}.lua`, all_args); - statusJobs(status) { - var k, pos, ref, results, v; - if (status != null) { - pos = this.status.indexOf(status); - if (pos < 0) { - throw new BottleneckError$3(`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); - } - } + arr = _this3.connection.__scriptArgs__(name, _this3.originalId, all_args, function (err, replies) { + if (err != null) { + return reject(err); + } + + 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); + } + }); + })(); + } - statusCounts() { - return this.counts.reduce(((acc, v, i) => { - acc[this.status[i]] = v; - return acc; - }), {}); - } + prepareArray(arr) { + var i, len, results, x; + results = []; - }; + for (i = 0, len = arr.length; i < len; i++) { + x = arr[i]; + results.push(x != null ? x.toString() : ""); + } - var States_1 = States; + return results; + } - var DLList$2, Sync; + prepareObject(obj) { + var arr, k, v; + arr = []; - DLList$2 = DLList_1; + for (k in obj) { + v = obj[k]; + arr.push(k, v != null ? v.toString() : ""); + } - Sync = class Sync { - constructor(name, Promise) { - this.schedule = this.schedule.bind(this); - this.name = name; - this.Promise = Promise; - this._running = 0; - this._queue = new DLList$2(); - } + return arr; + } - isEmpty() { - return this._queue.length === 0; - } + 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; + } - async _tryToRun() { - var args, cb, error, reject, resolve, returned, task; - if ((this._running < 1) && this._queue.length > 0) { - this._running++; - ({task, args, resolve, reject} = this._queue.shift()); - cb = (await (async function() { - try { - returned = (await task(...args)); - return function() { - return resolve(returned); - }; - } catch (error1) { - error = error1; - return function() { - return reject(error); - }; - } - })()); - this._running--; - this._tryToRun(); - return cb(); - } - } + convertBool(b) { + return !!b; + } - schedule(task, ...args) { - var promise, reject, resolve; - resolve = reject = null; - promise = new this.Promise(function(_resolve, _reject) { - resolve = _resolve; - return reject = _reject; - }); - this._queue.push({task, args, resolve, reject}); - this._tryToRun(); - return promise; - } + __updateSettings__(options) { + var _this4 = this; - }; + return _asyncToGenerator(function* () { + yield _this4.runScript("update_settings", _this4.prepareObject(options)); + return parser.overwrite(options, options, _this4.storeOptions); + })(); + } - var Sync_1 = Sync; + __running__() { + return this.runScript("running", []); + } - var version = "2.19.5"; - var version$1 = { - version: version - }; + __queued__() { + return this.runScript("queued", []); + } - var version$2 = /*#__PURE__*/Object.freeze({ - version: version, - default: version$1 - }); + __done__() { + return this.runScript("done", []); + } - var require$$2 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); + __groupCheck__() { + var _this5 = this; - var require$$3 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); + return _asyncToGenerator(function* () { + return _this5.convertBool((yield _this5.runScript("group_check", []))); + })(); + } - var require$$4 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); + __incrementReservoir__(incr) { + return this.runScript("increment_reservoir", [incr]); + } - var Events$2, Group, IORedisConnection$1, RedisConnection$1, Scripts$1, parser$3; + __currentReservoir__() { + return this.runScript("current_reservoir", []); + } - parser$3 = parser; + __check__(weight) { + var _this6 = this; - Events$2 = Events_1; + return _asyncToGenerator(function* () { + return _this6.convertBool((yield _this6.runScript("check", _this6.prepareArray([weight])))); + })(); + } - RedisConnection$1 = require$$2; + __register__(index, weight, expiration) { + var _this7 = this; - IORedisConnection$1 = require$$3; + return _asyncToGenerator(function* () { + var reservoir, success, wait; - Scripts$1 = require$$4; + var _ref4 = yield _this7.runScript("register", _this7.prepareArray([index, weight, expiration])); - Group = (function() { - class Group { - constructor(limiterOptions = {}) { - this.deleteKey = this.deleteKey.bind(this); - this.limiterOptions = limiterOptions; - parser$3.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})); - } - } - } + var _ref5 = _slicedToArray(_ref4, 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; - })(); - } + success = _ref5[0]; + wait = _ref5[1]; + reservoir = _ref5[2]; + return { + success: _this7.convertBool(success), + wait, + reservoir + }; + })(); + } - 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; - } + __submit__(queueLength, weight) { + var _this8 = this; - 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; - } + return _asyncToGenerator(function* () { + var blocked, e, maxConcurrent, overweight, reachedHWM, strategy; - keys() { - return Object.keys(this.instances); - } + try { + var _ref6 = yield _this8.runScript("submit", _this8.prepareArray([queueLength, weight])); - 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; - } + 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; - _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; - } + if (e.message.indexOf("OVERWEIGHT") === 0) { + var _e$message$split = e.message.split(":"); - updateSettings(options = {}) { - parser$3.overwrite(options, this.defaults, this); - parser$3.overwrite(options, options, this.limiterOptions); - if (options.timeout != null) { - return this._startAutoCleanup(); - } - } + var _e$message$split2 = _slicedToArray(_e$message$split, 3); - disconnect(flush = true) { - var ref; - if (!this.sharedConnection) { - return (ref = this.connection) != null ? ref.disconnect(flush) : void 0; - } - } + 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; + } + } + })(); + } - } - Group.prototype.defaults = { - timeout: 1000 * 60 * 5, - connection: null, - Promise: Promise, - id: "group-key" - }; + __free__(index, weight) { + var _this9 = this; - return Group; + return _asyncToGenerator(function* () { + var running; + running = yield _this9.runScript("free", _this9.prepareArray([index])); + return { + running + }; + })(); + } - }).call(commonjsGlobal); +}; +module.exports = RedisDatastore; - var Group_1 = Group; +/***/ }), - var Batcher, Events$3, parser$4; +/***/ 4169: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - parser$4 = parser; +"use strict"; - Events$3 = Events_1; - Batcher = (function() { - class Batcher { - constructor(options = {}) { - this.options = options; - parser$4.load(this.options, this.defaults, this); - this.Events = new Events$3(this); - this._arr = []; - this._resetPromise(); - this._lastFlush = Date.now(); - } +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"] +}; - _resetPromise() { - return this._promise = new this.Promise((res, rej) => { - return this._resolve = res; - }); - } +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`]; +}; - _flush() { - clearTimeout(this._timeout); - this._lastFlush = Date.now(); - this._resolve(); - this.Events.trigger("batch", this._arr); - this._arr = []; - return this._resetPromise(); - } +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); + +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"); +}; - 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 - }; +/***/ 2527: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return Batcher; +"use strict"; - }).call(commonjsGlobal); - var Batcher_1 = Batcher; +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; + }); + } - var require$$4$1 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); + next(id) { + var current, next; + current = this._jobs[id]; + next = current + 1; - var require$$8 = getCjsExportFromNamespace(version$2); + 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]; + } + } - var Bottleneck, DEFAULT_PRIORITY$1, Events$4, Job$1, LocalDatastore$1, NUM_PRIORITIES$1, Queues$1, RedisDatastore$1, States$1, Sync$1, parser$5, - splice = [].splice; + start(id) { + var initial; + initial = 0; + this._jobs[id] = initial; + return this.counts[initial]++; + } - NUM_PRIORITIES$1 = 10; + remove(id) { + var current; + current = this._jobs[id]; - DEFAULT_PRIORITY$1 = 5; + if (current != null) { + this.counts[current]--; + delete this._jobs[id]; + } - parser$5 = parser; + return current != null; + } - Queues$1 = Queues_1; + jobStatus(id) { + var ref; + return (ref = this.status[this._jobs[id]]) != null ? ref : null; + } - Job$1 = Job_1; + statusJobs(status) { + var k, pos, ref, results, v; - LocalDatastore$1 = LocalDatastore_1; + if (status != null) { + pos = this.status.indexOf(status); - RedisDatastore$1 = require$$4$1; + if (pos < 0) { + throw new BottleneckError(`status must be one of ${this.status.join(', ')}`); + } - Events$4 = Events_1; + ref = this._jobs; + results = []; - States$1 = States_1; + for (k in ref) { + v = ref[k]; - Sync$1 = Sync_1; + if (v === pos) { + results.push(k); + } + } - Bottleneck = (function() { - class Bottleneck { - constructor(options = {}, ...invalid) { - var storeInstanceOptions, storeOptions; - this._addToQueue = this._addToQueue.bind(this); - this._validateOptions(options, invalid); - parser$5.load(options, this.instanceDefaults, this); - this._queues = new Queues$1(NUM_PRIORITIES$1); - 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$5.load(options, this.storeDefaults, {}); - this._store = (function() { - if (this.datastore === "redis" || this.datastore === "ioredis" || (this.connection != null)) { - storeInstanceOptions = parser$5.load(options, this.redisStoreDefaults, {}); - return new RedisDatastore$1(this, storeOptions, storeInstanceOptions); - } else if (this.datastore === "local") { - storeInstanceOptions = parser$5.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 ref; - return (ref = this._store.heartbeat) != null ? typeof ref.ref === "function" ? ref.ref() : void 0 : void 0; - }); - this._queues.on("zero", () => { - var ref; - return (ref = this._store.heartbeat) != null ? typeof ref.unref === "function" ? ref.unref() : void 0 : void 0; - }); - } + return results; + } else { + return Object.keys(this._jobs); + } + } - _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."); - } - } + statusCounts() { + return this.counts.reduce((acc, v, i) => { + acc[this.status[i]] = v; + return acc; + }, {}); + } - ready() { - return this._store.ready; - } +}; +module.exports = States; - clients() { - return this._store.clients; - } +/***/ }), - channel() { - return `b_${this.id}`; - } +/***/ 56029: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - channel_client() { - return `b_${this.id}_${this._store.clientId}`; - } +"use strict"; - publish(message) { - return this._store.__publish__(message); - } - disconnect(flush = true) { - return this._store.__disconnect__(flush); - } +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); } } - chain(_limiter) { - this._limiter = _limiter; - 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); }); }; } - queued(priority) { - return this._queues.queued(priority); - } +var DLList, Sync; +DLList = __nccwpck_require__(38579); +Sync = class Sync { + constructor(name, Promise) { + this.schedule = this.schedule.bind(this); + this.name = name; + this.Promise = Promise; + this._running = 0; + this._queue = new DLList(); + } - clusterQueued() { - return this._store.__queued__(); - } + isEmpty() { + return this._queue.length === 0; + } - empty() { - return this.queued() === 0 && this._submitLock.isEmpty(); - } + _tryToRun() { + var _this = this; - running() { - return this._store.__running__(); - } + return _asyncToGenerator(function* () { + var args, cb, error, reject, resolve, returned, task; - done() { - return this._store.__done__(); - } + if (_this._running < 1 && _this._queue.length > 0) { + _this._running++; - jobStatus(id) { - return this._states.jobStatus(id); - } + var _this$_queue$shift = _this._queue.shift(); - jobs(status) { - return this._states.statusJobs(status); - } + task = _this$_queue$shift.task; + args = _this$_queue$shift.args; + resolve = _this$_queue$shift.resolve; + reject = _this$_queue$shift.reject; + cb = yield _asyncToGenerator(function* () { + try { + returned = yield task(...args); + return function () { + return resolve(returned); + }; + } catch (error1) { + error = error1; + return function () { + return reject(error); + }; + } + })(); + _this._running--; - counts() { - return this._states.statusCounts(); - } + _this._tryToRun(); - _randomIndex() { - return Math.random().toString(36).slice(2); - } + return cb(); + } + })(); + } + + schedule(task, ...args) { + var promise, reject, resolve; + resolve = reject = null; + promise = new this.Promise(function (_resolve, _reject) { + resolve = _resolve; + return reject = _reject; + }); - check(weight = 1) { - return this._store.__check__(weight); - } + this._queue.push({ + task, + args, + resolve, + reject + }); - _clearGlobalState(index) { - if (this._scheduled[index] != null) { - clearTimeout(this._scheduled[index].expiration); - delete this._scheduled[index]; - return true; - } else { - return false; - } - } + this._tryToRun(); - async _free(index, job, options, eventInfo) { - var e, running; - try { - ({running} = (await this._store.__free__(index, options.weight))); - this.Events.trigger("debug", `Freed ${options.id}`, eventInfo); - if (running === 0 && this.empty()) { - return this.Events.trigger("idle"); - } - } catch (error1) { - e = error1; - return this.Events.trigger("error", e); - } - } + return promise; + } - _run(index, job, wait) { - var clearGlobalState, free, run; - job.doRun(); - clearGlobalState = this._clearGlobalState.bind(this, index); - run = this._run.bind(this, index, job); - free = this._free.bind(this, index, job); - return this._scheduled[index] = { - timeout: setTimeout(() => { - return job.doExecute(this._limiter, clearGlobalState, run, free); - }, wait), - expiration: job.options.expiration != null ? setTimeout(function() { - return job.doExpire(clearGlobalState, run, free); - }, wait + job.options.expiration) : void 0, - job: job - }; - } +}; +module.exports = Sync; - _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(index, next, wait); - 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); - } - }).catch((e) => { - return this.Events.trigger("error", e); - }); - } +/***/ 27356: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - _dropAllQueued(message) { - return this._queues.shiftAll(function(job) { - return job.doDrop({message}); - }); - } +"use strict"; - stop(options = {}) { - var done, waitForExecuting; - options = parser$5.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 = function(index, next) { - return next.doDrop({ - message: 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); - v.job.doDrop({ - message: options.dropErrorMessage - }); - } - } - this._dropAllQueued(options.dropErrorMessage); - return waitForExecuting(0); - }); - })) : this.schedule({ - priority: NUM_PRIORITIES$1 - 1, - weight: 0 - }, () => { - return waitForExecuting(1); - }); - this._receive = function(job) { - return job._reject(new Bottleneck.prototype.BottleneckError(options.enqueueErrorMessage)); - }; - this.stop = () => { - return this.Promise.reject(new Bottleneck.prototype.BottleneckError("stop() has already been called")); - }; - return done; - } - async _addToQueue(job) { - var args, blocked, error, options, reachedHWM, shifted, strategy; - ({args, options} = job); - try { - ({reachedHWM, blocked, strategy} = (await this._store.__submit__(this.queued(), options.weight))); - } catch (error1) { - error = error1; - this.Events.trigger("debug", `Could not queue ${options.id}`, {args, options, error}); - job.doDrop({error}); - return false; - } - if (blocked) { - job.doDrop(); - 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) { - shifted.doDrop(); - } - if ((shifted == null) || strategy === Bottleneck.prototype.strategy.OVERFLOW) { - if (shifted == null) { - job.doDrop(); - } - return reachedHWM; - } - } - job.doQueue(reachedHWM, blocked); - this._queues.push(job); - await this._drainAll(); - return reachedHWM; - } +module.exports = __nccwpck_require__(83911); - _receive(job) { - if (this._states.jobStatus(job.options.id) != null) { - job._reject(new Bottleneck.prototype.BottleneckError(`A job with the same id already exists (id=${job.options.id})`)); - return false; - } else { - job.doReceive(); - return this._submitLock.schedule(this._addToQueue, job); - } - } +/***/ }), - submit(...args) { - var cb, fn, job, options, ref, ref1, task; - if (typeof args[0] === "function") { - ref = args, [fn, ...args] = ref, [cb] = splice.call(args, -1); - options = parser$5.load({}, this.jobDefaults); - } else { - ref1 = args, [options, fn, ...args] = ref1, [cb] = splice.call(args, -1); - options = parser$5.load(options, this.jobDefaults); - } - task = (...args) => { - return new this.Promise(function(resolve, reject) { - return fn(...args, function(...args) { - return (args[0] != null ? reject : resolve)(args); - }); - }); - }; - job = new Job$1(task, args, options, this.jobDefaults, this.rejectOnDrop, this.Events, this._states, this.Promise); - job.promise.then(function(args) { - return typeof cb === "function" ? cb(...args) : void 0; - }).catch(function(args) { - if (Array.isArray(args)) { - return typeof cb === "function" ? cb(...args) : void 0; - } else { - return typeof cb === "function" ? cb(args) : void 0; - } - }); - return this._receive(job); - } +/***/ 67823: +/***/ ((__unused_webpack_module, exports) => { - schedule(...args) { - var job, options, task; - if (typeof args[0] === "function") { - [task, ...args] = args; - options = {}; - } else { - [options, task, ...args] = args; - } - job = new Job$1(task, args, options, this.jobDefaults, this.rejectOnDrop, this.Events, this._states, this.Promise); - this._receive(job); - return job.promise; - } +"use strict"; - wrap(fn) { - var schedule, wrapped; - schedule = this.schedule.bind(this); - wrapped = function(...args) { - return schedule(fn.bind(this), ...args); - }; - wrapped.withOptions = function(options, ...args) { - return schedule(options, fn, ...args); - }; - return wrapped; - } - async updateSettings(options = {}) { - await this._store.__updateSettings__(parser$5.overwrite(options, this.storeDefaults)); - parser$5.overwrite(options, this.instanceDefaults, this); - return this; - } +exports.load = function (received, defaults, onto = {}) { + var k, ref, v; - currentReservoir() { - return this._store.__currentReservoir__(); - } + for (k in defaults) { + v = defaults[k]; + onto[k] = (ref = received[k]) != null ? ref : v; + } - incrementReservoir(incr = 0) { - return this._store.__incrementReservoir__(incr); - } + return onto; +}; - } - Bottleneck.default = Bottleneck; +exports.overwrite = function (received, defaults, onto = {}) { + var k, v; - Bottleneck.Events = Events$4; + for (k in received) { + v = received[k]; - Bottleneck.version = Bottleneck.prototype.version = require$$8.version; + if (defaults[k] !== void 0) { + onto[k] = v; + } + } - Bottleneck.strategy = Bottleneck.prototype.strategy = { - LEAK: 1, - OVERFLOW: 2, - OVERFLOW_PRIORITY: 4, - BLOCK: 3 - }; + return onto; +}; - Bottleneck.BottleneckError = Bottleneck.prototype.BottleneckError = BottleneckError_1; +/***/ }), - Bottleneck.Group = Bottleneck.prototype.Group = Group_1; +/***/ 11174: +/***/ (function(module) { - Bottleneck.RedisConnection = Bottleneck.prototype.RedisConnection = require$$2; +/** + * 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'; - Bottleneck.IORedisConnection = Bottleneck.prototype.IORedisConnection = require$$3; + var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; - Bottleneck.Batcher = Bottleneck.prototype.Batcher = Batcher_1; + function getCjsExportFromNamespace (n) { + return n && n['default'] || n; + } - Bottleneck.prototype.jobDefaults = { - priority: DEFAULT_PRIORITY$1, - weight: 1, - expiration: null, - id: "" - }; + 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; + }; - Bottleneck.prototype.storeDefaults = { - maxConcurrent: null, - minTime: 0, - highWater: null, - strategy: Bottleneck.prototype.strategy.LEAK, - penalty: null, - reservoir: null, - reservoirRefreshInterval: null, - reservoirRefreshAmount: null, - reservoirIncreaseInterval: null, - reservoirIncreaseAmount: null, - reservoirIncreaseMaximum: null - }; + 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; + }; - Bottleneck.prototype.localStoreDefaults = { - Promise: Promise, - timeout: null, - heartbeatInterval: 250 - }; + var parser = { + load: load, + overwrite: overwrite + }; - Bottleneck.prototype.redisStoreDefaults = { - Promise: Promise, - timeout: null, - heartbeatInterval: 5000, - clientTimeout: 10000, - Redis: null, - clientOptions: {}, - clusterNodes: null, - clearDatastore: false, - connection: null - }; + var DLList; - Bottleneck.prototype.instanceDefaults = { - datastore: "local", - connection: null, - id: "", - rejectOnDrop: true, - trackDoneStatus: false, - Promise: Promise - }; + DLList = class DLList { + constructor(incr, decr) { + this.incr = incr; + this.decr = decr; + this._first = null; + this._last = null; + this.length = 0; + } - Bottleneck.prototype.stopDefaults = { - enqueueErrorMessage: "This limiter has been stopped and cannot accept new jobs.", - dropWaitingJobs: true, - dropErrorMessage: "This limiter has been stopped." - }; + push(value) { + var node; + this.length++; + if (typeof this.incr === "function") { + this.incr(); + } + node = { + value, + prev: this._last, + next: null + }; + if (this._last != null) { + this._last.next = node; + this._last = node; + } else { + this._first = this._last = node; + } + return void 0; + } - return Bottleneck; + shift() { + var value; + if (this._first == null) { + return; + } else { + this.length--; + if (typeof this.decr === "function") { + this.decr(); + } + } + value = this._first.value; + if ((this._first = this._first.next) != null) { + this._first.prev = null; + } else { + this._last = null; + } + return value; + } - }).call(commonjsGlobal); + first() { + if (this._first != null) { + return this._first.value; + } + } - var Bottleneck_1 = Bottleneck; + getArray() { + var node, ref, results; + node = this._first; + results = []; + while (node != null) { + results.push((ref = node, node = node.next, ref.value)); + } + return results; + } - var lib = Bottleneck_1; + forEachShift(cb) { + var node; + node = this.shift(); + while (node != null) { + (cb(node), node = this.shift()); + } + return void 0; + } - return lib; + debug() { + var node, ref, ref1, ref2, results; + node = this._first; + results = []; + while (node != null) { + results.push((ref = node, node = node.next, { + value: ref.value, + prev: (ref1 = ref.prev) != null ? ref1.value : void 0, + next: (ref2 = ref.next) != null ? ref2.value : void 0 + })); + } + return results; + } -}))); + }; + + 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; + } + } -/***/ 33717: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + 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; + } + } -var concatMap = __nccwpck_require__(86891); -var balanced = __nccwpck_require__(9417); + }; -module.exports = expandTop; + var Events_1 = Events; -var escSlash = '\0SLASH'+Math.random()+'\0'; -var escOpen = '\0OPEN'+Math.random()+'\0'; -var escClose = '\0CLOSE'+Math.random()+'\0'; -var escComma = '\0COMMA'+Math.random()+'\0'; -var escPeriod = '\0PERIOD'+Math.random()+'\0'; + var DLList$1, Events$1, Queues; -function numeric(str) { - return parseInt(str, 10) == str - ? parseInt(str, 10) - : str.charCodeAt(0); -} + DLList$1 = DLList_1; -function escapeBraces(str) { - return str.split('\\\\').join(escSlash) - .split('\\{').join(escOpen) - .split('\\}').join(escClose) - .split('\\,').join(escComma) - .split('\\.').join(escPeriod); -} + Events$1 = Events_1; -function unescapeBraces(str) { - return str.split(escSlash).join('\\') - .split(escOpen).join('{') - .split(escClose).join('}') - .split(escComma).join(',') - .split(escPeriod).join('.'); -} + 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((() => { + return this.incr(); + }), (() => { + return this.decr(); + }))); + } + return results; + }).call(this); + } + incr() { + if (this._length++ === 0) { + return this.Events.trigger("leftzero"); + } + } -// Basically just str.split(","), but handling cases -// where we have nested braced sections, which should be -// treated as individual members, like {a,{b,c},d} -function parseCommaParts(str) { - if (!str) - return ['']; + decr() { + if (--this._length === 0) { + return this.Events.trigger("zero"); + } + } - var parts = []; - var m = balanced('{', '}', str); + push(job) { + return this._lists[job.options.priority].push(job); + } - if (!m) - return str.split(','); + queued(priority) { + if (priority != null) { + return this._lists[priority].length; + } else { + return this._length; + } + } - var pre = m.pre; - var body = m.body; - var post = m.post; - var p = pre.split(','); + shiftAll(fn) { + return this._lists.forEach(function(list) { + return list.forEachShift(fn); + }); + } - p[p.length-1] += '{' + body + '}'; - var postParts = parseCommaParts(post); - if (post.length) { - p[p.length-1] += postParts.shift(); - p.push.apply(p, postParts); - } + 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 []; + } - parts.push.apply(parts, p); + shiftLastFrom(priority) { + return this.getFirst(this._lists.slice(priority).reverse()).shift(); + } - return parts; -} + }; -function expandTop(str) { - if (!str) - return []; + var Queues_1 = Queues; - // I don't know why Bash 4.3 does this, but it does. - // Anything starting with {} will have the first two bytes preserved - // but *only* at the top level, so {},a}b will not expand to anything, - // but a{},b}c will be expanded to [a}c,abc]. - // One could argue that this is a bug in Bash, but since the goal of - // this module is to match Bash's rules, we escape a leading {} - if (str.substr(0, 2) === '{}') { - str = '\\{\\}' + str.substr(2); - } + var BottleneckError; - return expand(escapeBraces(str), true).map(unescapeBraces); -} + BottleneckError = class BottleneckError extends Error {}; -function identity(e) { - return e; -} + var BottleneckError_1 = BottleneckError; -function embrace(str) { - return '{' + str + '}'; -} -function isPadded(el) { - return /^-?0\d/.test(el); -} + var BottleneckError$1, DEFAULT_PRIORITY, Job, NUM_PRIORITIES, parser$1; -function lte(i, y) { - return i <= y; -} -function gte(i, y) { - return i >= y; -} + NUM_PRIORITIES = 10; -function expand(str, isTop) { - var expansions = []; + DEFAULT_PRIORITY = 5; - var m = balanced('{', '}', str); - if (!m || /\$$/.test(m.pre)) return [str]; + parser$1 = parser; - var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); - var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); - var isSequence = isNumericSequence || isAlphaSequence; - var isOptions = m.body.indexOf(',') >= 0; - if (!isSequence && !isOptions) { - // {a},b} - if (m.post.match(/,.*\}/)) { - str = m.pre + '{' + m.body + escClose + m.post; - return expand(str); - } - return [str]; - } + BottleneckError$1 = BottleneckError_1; - var n; - if (isSequence) { - n = m.body.split(/\.\./); - } else { - n = parseCommaParts(m.body); - if (n.length === 1) { - // x{{a,b}}y ==> x{a}y x{b}y - n = expand(n[0], false).map(embrace); - if (n.length === 1) { - var post = m.post.length - ? expand(m.post, false) - : ['']; - return post.map(function(p) { - return m.pre + n[0] + p; - }); - } - } - } + Job = class Job { + constructor(task, args, options, jobDefaults, rejectOnDrop, Events, _states, Promise) { + this.task = task; + this.args = args; + this.rejectOnDrop = rejectOnDrop; + this.Events = Events; + this._states = _states; + this.Promise = Promise; + this.options = parser$1.load(options, jobDefaults); + this.options.priority = this._sanitizePriority(this.options.priority); + if (this.options.id === jobDefaults.id) { + this.options.id = `${this.options.id}-${this._randomIndex()}`; + } + this.promise = new this.Promise((_resolve, _reject) => { + this._resolve = _resolve; + this._reject = _reject; + }); + this.retryCount = 0; + } - // at this point, n is the parts, and we know it's not a comma set - // with a single entry. + _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; + } + } - // no need to expand pre, since it is guaranteed to be free of brace-sets - var pre = m.pre; - var post = m.post.length - ? expand(m.post, false) - : ['']; + _randomIndex() { + return Math.random().toString(36).slice(2); + } - var N; + doDrop({error, message = "This job has been dropped by Bottleneck"} = {}) { + if (this._states.remove(this.options.id)) { + if (this.rejectOnDrop) { + this._reject(error != null ? error : new BottleneckError$1(message)); + } + this.Events.trigger("dropped", {args: this.args, options: this.options, task: this.task, promise: this.promise}); + return true; + } else { + return false; + } + } - if (isSequence) { - var x = numeric(n[0]); - var y = numeric(n[1]); - var width = Math.max(n[0].length, n[1].length) - var incr = n.length == 3 - ? Math.abs(numeric(n[2])) - : 1; - var test = lte; - var reverse = y < x; - if (reverse) { - incr *= -1; - test = gte; - } - var pad = n.some(isPadded); + _assertStatus(expected) { + var status; + status = this._states.jobStatus(this.options.id); + if (!(status === expected || (expected === "DONE" && status === null))) { + throw new BottleneckError$1(`Invalid job status ${status}, expected ${expected}. Please open an issue at https://github.com/SGrondin/bottleneck/issues`); + } + } - N = []; + doReceive() { + this._states.start(this.options.id); + return this.Events.trigger("received", {args: this.args, options: this.options}); + } - for (var i = x; test(i, y); i += incr) { - var c; - if (isAlphaSequence) { - c = String.fromCharCode(i); - if (c === '\\') - c = ''; - } else { - c = String(i); - if (pad) { - var need = width - c.length; - if (need > 0) { - var z = new Array(need + 1).join('0'); - if (i < 0) - c = '-' + z + c.slice(1); - else - c = z + c; - } - } - } - N.push(c); - } - } else { - N = concatMap(n, function(el) { return expand(el, false) }); - } + doQueue(reachedHWM, blocked) { + this._assertStatus("RECEIVED"); + this._states.next(this.options.id); + return this.Events.trigger("queued", {args: this.args, options: this.options, reachedHWM, blocked}); + } - for (var j = 0; j < N.length; j++) { - for (var k = 0; k < post.length; k++) { - var expansion = pre + N[j] + post[k]; - if (!isTop || isSequence || expansion) - expansions.push(expansion); - } - } + doRun() { + if (this.retryCount === 0) { + this._assertStatus("QUEUED"); + this._states.next(this.options.id); + } else { + this._assertStatus("EXECUTING"); + } + return this.Events.trigger("scheduled", {args: this.args, options: this.options}); + } - return expansions; -} + async doExecute(chained, clearGlobalState, run, free) { + var error, eventInfo, passed; + if (this.retryCount === 0) { + this._assertStatus("RUNNING"); + this._states.next(this.options.id); + } else { + this._assertStatus("EXECUTING"); + } + eventInfo = {args: this.args, options: this.options, retryCount: this.retryCount}; + this.Events.trigger("executing", eventInfo); + try { + passed = (await (chained != null ? chained.schedule(this.options, this.task, ...this.args) : this.task(...this.args))); + if (clearGlobalState()) { + this.doDone(eventInfo); + await free(this.options, eventInfo); + this._assertStatus("DONE"); + return this._resolve(passed); + } + } catch (error1) { + error = error1; + return this._onFailure(error, eventInfo, clearGlobalState, run, free); + } + } + doExpire(clearGlobalState, run, free) { + var error, eventInfo; + if (this._states.jobStatus(this.options.id === "RUNNING")) { + this._states.next(this.options.id); + } + this._assertStatus("EXECUTING"); + eventInfo = {args: this.args, options: this.options, retryCount: this.retryCount}; + error = new BottleneckError$1(`This job timed out after ${this.options.expiration} ms.`); + return this._onFailure(error, eventInfo, clearGlobalState, run, free); + } + async _onFailure(error, eventInfo, clearGlobalState, run, free) { + var retry, retryAfter; + if (clearGlobalState()) { + retry = (await this.Events.trigger("failed", error, eventInfo)); + if (retry != null) { + retryAfter = ~~retry; + this.Events.trigger("retry", `Retrying ${this.options.id} after ${retryAfter} ms`, eventInfo); + this.retryCount++; + return run(retryAfter); + } else { + this.doDone(eventInfo); + await free(this.options, eventInfo); + this._assertStatus("DONE"); + return this._reject(error); + } + } + } -/***/ }), + doDone(eventInfo) { + this._assertStatus("EXECUTING"); + this._states.next(this.options.id); + return this.Events.trigger("done", eventInfo); + } -/***/ 72358: -/***/ ((module) => { + }; -module.exports = function btoa(str) { - return new Buffer(str).toString('base64') -} + var Job_1 = Job; + var BottleneckError$2, LocalDatastore, parser$2; -/***/ }), + parser$2 = parser; -/***/ 9239: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + BottleneckError$2 = BottleneckError_1; -"use strict"; -/*jshint node:true */ + LocalDatastore = class LocalDatastore { + constructor(instance, storeOptions, storeInstanceOptions) { + this.instance = instance; + this.storeOptions = storeOptions; + this.clientId = this.instance._randomIndex(); + parser$2.load(storeInstanceOptions, storeInstanceOptions, this); + this._nextRequest = this._lastReservoirRefresh = this._lastReservoirIncrease = Date.now(); + this._running = 0; + this._done = 0; + this._unblockTime = 0; + this.ready = this.Promise.resolve(); + this.clients = {}; + this._startHeartbeat(); + } -var Buffer = (__nccwpck_require__(14300).Buffer); // browserify -var SlowBuffer = (__nccwpck_require__(14300).SlowBuffer); + _startHeartbeat() { + var base; + if ((this.heartbeat == null) && (((this.storeOptions.reservoirRefreshInterval != null) && (this.storeOptions.reservoirRefreshAmount != null)) || ((this.storeOptions.reservoirIncreaseInterval != null) && (this.storeOptions.reservoirIncreaseAmount != null)))) { + return typeof (base = (this.heartbeat = setInterval(() => { + var amount, incr, maximum, now, reservoir; + now = Date.now(); + if ((this.storeOptions.reservoirRefreshInterval != null) && now >= this._lastReservoirRefresh + this.storeOptions.reservoirRefreshInterval) { + this._lastReservoirRefresh = now; + this.storeOptions.reservoir = this.storeOptions.reservoirRefreshAmount; + this.instance._drainAll(this.computeCapacity()); + } + if ((this.storeOptions.reservoirIncreaseInterval != null) && now >= this._lastReservoirIncrease + this.storeOptions.reservoirIncreaseInterval) { + ({ + reservoirIncreaseAmount: amount, + reservoirIncreaseMaximum: maximum, + reservoir + } = this.storeOptions); + this._lastReservoirIncrease = now; + incr = maximum != null ? Math.min(amount, maximum - reservoir) : amount; + if (incr > 0) { + this.storeOptions.reservoir += incr; + return this.instance._drainAll(this.computeCapacity()); + } + } + }, this.heartbeatInterval))).unref === "function" ? base.unref() : void 0; + } else { + return clearInterval(this.heartbeat); + } + } -module.exports = bufferEq; + async __publish__(message) { + await this.yieldLoop(); + return this.instance.Events.trigger("message", message.toString()); + } -function bufferEq(a, b) { + async __disconnect__(flush) { + await this.yieldLoop(); + clearInterval(this.heartbeat); + return this.Promise.resolve(); + } - // shortcutting on type is necessary for correctness - if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { - return false; - } + 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; + } - // 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; - } + async __updateSettings__(options) { + await this.yieldLoop(); + parser$2.overwrite(options, options, this.storeOptions); + this._startHeartbeat(); + this.instance._drainAll(this.computeCapacity()); + return true; + } - var c = 0; - for (var i = 0; i < a.length; i++) { - /*jshint bitwise:false */ - c |= a[i] ^ b[i]; // XOR - } - return c === 0; -} + async __running__() { + await this.yieldLoop(); + return this._running; + } -bufferEq.install = function() { - Buffer.prototype.equal = SlowBuffer.prototype.equal = function equal(that) { - return bufferEq(this, that); - }; -}; + async __queued__() { + await this.yieldLoop(); + return this.instance.queued(); + } -var origBufEqual = Buffer.prototype.equal; -var origSlowBufEqual = SlowBuffer.prototype.equal; -bufferEq.restore = function() { - Buffer.prototype.equal = origBufEqual; - SlowBuffer.prototype.equal = origSlowBufEqual; -}; + 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; + } + } -/***/ 86966: -/***/ ((module) => { + conditionsCheck(weight) { + var capacity; + capacity = this.computeCapacity(); + return (capacity == null) || weight <= capacity; + } -"use strict"; -/*! - * bytes - * Copyright(c) 2012-2014 TJ Holowaychuk - * Copyright(c) 2015 Jed Watson - * MIT Licensed - */ + 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; + } -/** - * Module exports. - * @public - */ + check(weight, now) { + return this.conditionsCheck(weight) && (this._nextRequest - now) <= 0; + } -module.exports = bytes; -module.exports.format = format; -module.exports.parse = parse; + async __check__(weight) { + var now; + await this.yieldLoop(); + now = Date.now(); + return this.check(weight, now); + } -/** - * Module variables. - * @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 + }; + } + } -var formatThousandsRegExp = /\B(?=(\d{3})+(?!\d))/g; + strategyIsBlock() { + return this.storeOptions.strategy === 3; + } -var formatDecimalsRegExp = /(?:\.0*|(\.[^0]+)0+)$/; + async __submit__(queueLength, weight) { + var blocked, now, reachedHWM; + await this.yieldLoop(); + if ((this.storeOptions.maxConcurrent != null) && weight > this.storeOptions.maxConcurrent) { + throw new BottleneckError$2(`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 + }; + } -var map = { - b: 1, - kb: 1 << 10, - mb: 1 << 20, - gb: 1 << 30, - tb: Math.pow(1024, 4), - pb: Math.pow(1024, 5), -}; + async __free__(index, weight) { + await this.yieldLoop(); + this._running -= weight; + this._done += weight; + this.instance._drainAll(this.computeCapacity()); + return { + running: this._running + }; + } -var parseRegExp = /^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb|pb)$/i; + }; -/** - * 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} - */ + var LocalDatastore_1 = LocalDatastore; -function bytes(value, options) { - if (typeof value === 'string') { - return parse(value); - } + var BottleneckError$3, States; - if (typeof value === 'number') { - return format(value, options); - } + BottleneckError$3 = BottleneckError_1; - return null; -} + States = class States { + constructor(status1) { + this.status = status1; + this._jobs = {}; + this.counts = this.status.map(function() { + return 0; + }); + } -/** - * 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 - */ + 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]; + } + } -function format(value, options) { - if (!Number.isFinite(value)) { - return null; - } + 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]; + } + return current != 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) || ''; + jobStatus(id) { + var ref; + return (ref = this.status[this._jobs[id]]) != null ? ref : null; + } - 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'; - } - } + statusJobs(status) { + var k, pos, ref, results, v; + if (status != null) { + pos = this.status.indexOf(status); + if (pos < 0) { + throw new BottleneckError$3(`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); + } + } - var val = value / map[unit.toLowerCase()]; - var str = val.toFixed(decimalPlaces); + statusCounts() { + return this.counts.reduce(((acc, v, i) => { + acc[this.status[i]] = v; + return acc; + }), {}); + } - if (!fixedDecimals) { - str = str.replace(formatDecimalsRegExp, '$1'); - } + }; - if (thousandsSeparator) { - str = str.split('.').map(function (s, i) { - return i === 0 - ? s.replace(formatThousandsRegExp, thousandsSeparator) - : s - }).join('.'); - } + var States_1 = States; - return str + unitSeparator + unit; -} + var DLList$2, Sync; -/** - * 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 - */ + DLList$2 = DLList_1; -function parse(val) { - if (typeof val === 'number' && !isNaN(val)) { - return val; - } + Sync = class Sync { + constructor(name, Promise) { + this.schedule = this.schedule.bind(this); + this.name = name; + this.Promise = Promise; + this._running = 0; + this._queue = new DLList$2(); + } - if (typeof val !== 'string') { - return null; - } + isEmpty() { + return this._queue.length === 0; + } - // Test if the string passed is valid - var results = parseRegExp.exec(val); - var floatValue; - var unit = 'b'; + async _tryToRun() { + var args, cb, error, reject, resolve, returned, task; + if ((this._running < 1) && this._queue.length > 0) { + this._running++; + ({task, args, resolve, reject} = this._queue.shift()); + cb = (await (async function() { + try { + returned = (await task(...args)); + return function() { + return resolve(returned); + }; + } catch (error1) { + error = error1; + return function() { + return reject(error); + }; + } + })()); + this._running--; + this._tryToRun(); + return cb(); + } + } - 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(); - } + schedule(task, ...args) { + var promise, reject, resolve; + resolve = reject = null; + promise = new this.Promise(function(_resolve, _reject) { + resolve = _resolve; + return reject = _reject; + }); + this._queue.push({task, args, resolve, reject}); + this._tryToRun(); + return promise; + } - return Math.floor(map[unit] * floatValue); -} + }; + var Sync_1 = Sync; -/***/ }), + var version = "2.19.5"; + var version$1 = { + version: version + }; -/***/ 27972: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + var version$2 = /*#__PURE__*/Object.freeze({ + version: version, + default: version$1 + }); -"use strict"; + var require$$2 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); -const os = __nccwpck_require__(22037); + var require$$3 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); -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(); + var require$$4 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); -module.exports = (stack, options) => { - options = Object.assign({pretty: false}, options); + var Events$2, Group, IORedisConnection$1, RedisConnection$1, Scripts$1, parser$3; - return stack.replace(/\\/g, '/') - .split('\n') - .filter(line => { - const pathMatches = line.match(extractPathRegex); - if (pathMatches === null || !pathMatches[1]) { - return true; - } + parser$3 = parser; - const match = pathMatches[1]; + Events$2 = Events_1; - // Electron - if ( - match.includes('.app/Contents/Resources/electron.asar') || - match.includes('.app/Contents/Resources/default_app.asar') - ) { - return false; - } + RedisConnection$1 = require$$2; - 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, '~'))); - } + IORedisConnection$1 = require$$3; - return line; - }) - .join('\n'); -}; + Scripts$1 = require$$4; + Group = (function() { + class Group { + constructor(limiterOptions = {}) { + this.deleteKey = this.deleteKey.bind(this); + this.limiterOptions = limiterOptions; + parser$3.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; + })(); + } -/***/ 2101: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + 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; + } -module.exports = __nccwpck_require__(16136); + 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); + } -/***/ 66168: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + 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; + } -const utils = __nccwpck_require__(98911); + _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; + } -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); + updateSettings(options = {}) { + parser$3.overwrite(options, this.defaults, this); + parser$3.overwrite(options, options, this.limiterOptions); + if (options.timeout != null) { + return this._startAutoCleanup(); + } + } - /** - * 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; - } + disconnect(flush = true) { + var ref; + if (!this.sharedConnection) { + return (ref = this.connection) != null ? ref.disconnect(flush) : void 0; + } + } - 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; - } + } + Group.prototype.defaults = { + timeout: 1000 * 60 * 5, + connection: null, + Promise: Promise, + id: "group-key" + }; - mergeTableOptions(tableOptions, cells) { - this.cells = cells; + return Group; - let optionsChars = this.options.chars || {}; - let tableChars = tableOptions.chars; - let chars = (this.chars = {}); - CHAR_NAMES.forEach(function (name) { - setOption(optionsChars, tableChars, name, chars); - }); + }).call(commonjsGlobal); - this.truncate = this.options.truncate || tableOptions.truncate; + var Group_1 = Group; - 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; + var Batcher, Events$3, parser$4; - 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')); - } + parser$4 = parser; - this.desiredWidth = utils.strlen(this.content) + this.paddingLeft + this.paddingRight; - this.desiredHeight = this.lines.length; - } + Events$3 = Events_1; - /** - * 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); + Batcher = (function() { + class Batcher { + constructor(options = {}) { + this.options = options; + parser$4.load(this.options, this.defaults, this); + this.Events = new Events$3(this); + this._arr = []; + this._resetPromise(); + this._lastFlush = Date.now(); + } - this.hAlign = this.options.hAlign || tableOptions.colAligns[x]; - this.vAlign = this.options.vAlign || tableOptions.rowAligns[y]; + _resetPromise() { + return this._promise = new this.Promise((res, rej) => { + return this._resolve = res; + }); + } - this.drawRight = x + this.colSpan == tableOptions.colWidths.length; - } + _flush() { + clearTimeout(this._timeout); + this._lastFlush = Date.now(); + this._resolve(); + this.Events.trigger("batch", this._arr); + this._arr = []; + return this._resetPromise(); + } - /** - * 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); - } + 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; + } - /** - * 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('')); - } + } + Batcher.prototype.defaults = { + maxTime: null, + maxSize: null, + Promise: Promise + }; - _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]; - } + return Batcher; - 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; - } - } + }).call(commonjsGlobal); - /** - * 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); - } + var Batcher_1 = Batcher; - 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 require$$4$1 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); - /** - * 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); - } + var require$$8 = getCjsExportFromNamespace(version$2); - /** - * 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); - } -} + var Bottleneck, DEFAULT_PRIORITY$1, Events$4, Job$1, LocalDatastore$1, NUM_PRIORITIES$1, Queues$1, RedisDatastore$1, States$1, Sync$1, parser$5, + splice = [].splice; -class ColSpanCell { - /** - * A Cell that doesn't do anything. It just draws empty lines. - * Used as a placeholder in column spanning. - * @constructor - */ - constructor() {} + NUM_PRIORITIES$1 = 10; - draw() { - return ''; - } + DEFAULT_PRIORITY$1 = 5; - init() {} + parser$5 = parser; - mergeTableOptions() {} -} + Queues$1 = Queues_1; -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; - } + Job$1 = Job_1; - init(tableOptions) { - let y = this.y; - let originalY = this.originalCell.y; - this.cellOffset = y - originalY; - this.offset = findDimension(tableOptions.rowHeights, originalY, this.cellOffset); - } + LocalDatastore$1 = LocalDatastore_1; - 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); - } + RedisDatastore$1 = require$$4$1; - mergeTableOptions() {} -} + Events$4 = Events_1; -// 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]; - } -} + States$1 = States_1; -function findDimension(dimensionTable, startingIndex, span) { - let ret = dimensionTable[startingIndex]; - for (let i = 1; i < span; i++) { - ret += 1 + dimensionTable[startingIndex + i]; - } - return ret; -} + Sync$1 = Sync_1; + + Bottleneck = (function() { + class Bottleneck { + constructor(options = {}, ...invalid) { + var storeInstanceOptions, storeOptions; + this._addToQueue = this._addToQueue.bind(this); + this._validateOptions(options, invalid); + parser$5.load(options, this.instanceDefaults, this); + this._queues = new Queues$1(NUM_PRIORITIES$1); + 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$5.load(options, this.storeDefaults, {}); + this._store = (function() { + if (this.datastore === "redis" || this.datastore === "ioredis" || (this.connection != null)) { + storeInstanceOptions = parser$5.load(options, this.redisStoreDefaults, {}); + return new RedisDatastore$1(this, storeOptions, storeInstanceOptions); + } else if (this.datastore === "local") { + storeInstanceOptions = parser$5.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 ref; + return (ref = this._store.heartbeat) != null ? typeof ref.ref === "function" ? ref.ref() : void 0 : void 0; + }); + this._queues.on("zero", () => { + var ref; + return (ref = this._store.heartbeat) != null ? typeof ref.unref === "function" ? ref.unref() : void 0 : void 0; + }); + } + + _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."); + } + } + + ready() { + return this._store.ready; + } + + clients() { + return this._store.clients; + } + + channel() { + return `b_${this.id}`; + } + + channel_client() { + return `b_${this.id}_${this._store.clientId}`; + } + + publish(message) { + return this._store.__publish__(message); + } + + disconnect(flush = true) { + return this._store.__disconnect__(flush); + } -function sumPlusOne(a, b) { - return a + b + 1; -} + chain(_limiter) { + this._limiter = _limiter; + return this; + } -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; + queued(priority) { + return this._queues.queued(priority); + } + clusterQueued() { + return this._store.__queued__(); + } -/***/ }), + empty() { + return this.queued() === 0 && this._submitLock.isEmpty(); + } -/***/ 93875: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + running() { + return this._store.__running__(); + } -const Cell = __nccwpck_require__(66168); -const { ColSpanCell, RowSpanCell } = Cell; + done() { + return this._store.__done__(); + } -(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; - } - }); - }); - } + jobStatus(id) { + return this._states.jobStatus(id); + } - 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; - } + jobs(status) { + return this._states.statusJobs(status); + } - function maxHeight(table) { - return table.length; - } + counts() { + return this._states.statusCounts(); + } - 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); + _randomIndex() { + return Math.random().toString(36).slice(2); + } - 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); + check(weight = 1) { + return this._store.__check__(weight); + } - return yConflict && xConflict; - } + _clearGlobalState(index) { + if (this._scheduled[index] != null) { + clearTimeout(this._scheduled[index].expiration); + delete this._scheduled[index]; + return true; + } else { + return false; + } + } - 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; - } + async _free(index, job, options, eventInfo) { + var e, running; + try { + ({running} = (await this._store.__free__(index, options.weight))); + this.Events.trigger("debug", `Freed ${options.id}`, eventInfo); + if (running === 0 && this.empty()) { + return this.Events.trigger("idle"); + } + } catch (error1) { + e = error1; + return this.Events.trigger("error", e); + } + } - function allBlank(rows, y, xMin, xMax) { - for (let x = xMin; x < xMax; x++) { - if (conflictExists(rows, x, y)) { - return false; - } - } - return true; - } + _run(index, job, wait) { + var clearGlobalState, free, run; + job.doRun(); + clearGlobalState = this._clearGlobalState.bind(this, index); + run = this._run.bind(this, index, job); + free = this._free.bind(this, index, job); + return this._scheduled[index] = { + timeout: setTimeout(() => { + return job.doExecute(this._limiter, clearGlobalState, run, free); + }, wait), + expiration: job.options.expiration != null ? setTimeout(function() { + return job.doExpire(clearGlobalState, run, free); + }, wait + job.options.expiration) : void 0, + job: job + }; + } - 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]); - } - }); - }); - } + _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(index, next, wait); + return this.Promise.resolve(options.weight); + } else { + return this.Promise.resolve(null); + } + }); + }); + } - 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); - } - } - } - } + _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); + }); + } - function insertCell(cell, row) { - let x = 0; - while (x < row.length && row[x].x < cell.x) { - x++; - } - row.splice(x, 0, cell); - } + _dropAllQueued(message) { + return this._queues.shiftAll(function(job) { + return job.doDrop({message}); + }); + } + + stop(options = {}) { + var done, waitForExecuting; + options = parser$5.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 = function(index, next) { + return next.doDrop({ + message: 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); + v.job.doDrop({ + message: options.dropErrorMessage + }); + } + } + this._dropAllQueued(options.dropErrorMessage); + return waitForExecuting(0); + }); + })) : this.schedule({ + priority: NUM_PRIORITIES$1 - 1, + weight: 0 + }, () => { + return waitForExecuting(1); + }); + this._receive = function(job) { + return job._reject(new Bottleneck.prototype.BottleneckError(options.enqueueErrorMessage)); + }; + this.stop = () => { + return this.Promise.reject(new Bottleneck.prototype.BottleneckError("stop() has already been called")); + }; + return done; + } - 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++; - } + async _addToQueue(job) { + var args, blocked, error, options, reachedHWM, shifted, strategy; + ({args, options} = job); + try { + ({reachedHWM, blocked, strategy} = (await this._store.__submit__(this.queued(), options.weight))); + } catch (error1) { + error = error1; + this.Events.trigger("debug", `Could not queue ${options.id}`, {args, options, error}); + job.doDrop({error}); + return false; + } + if (blocked) { + job.doDrop(); + 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) { + shifted.doDrop(); + } + if ((shifted == null) || strategy === Bottleneck.prototype.strategy.OVERFLOW) { + if (shifted == null) { + job.doDrop(); + } + return reachedHWM; + } + } + job.doQueue(reachedHWM, blocked); + this._queues.push(job); + await this._drainAll(); + return reachedHWM; + } - let cell = new Cell(opts); - cell.x = opts.x; - cell.y = opts.y; - insertCell(cell, table[y]); - } - } - } - } + _receive(job) { + if (this._states.jobStatus(job.options.id) != null) { + job._reject(new Bottleneck.prototype.BottleneckError(`A job with the same id already exists (id=${job.options.id})`)); + return false; + } else { + job.doReceive(); + return this._submitLock.schedule(this._addToQueue, job); + } + } - 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); - }); - }); - } + submit(...args) { + var cb, fn, job, options, ref, ref1, task; + if (typeof args[0] === "function") { + ref = args, [fn, ...args] = ref, [cb] = splice.call(args, -1); + options = parser$5.load({}, this.jobDefaults); + } else { + ref1 = args, [options, fn, ...args] = ref1, [cb] = splice.call(args, -1); + options = parser$5.load(options, this.jobDefaults); + } + task = (...args) => { + return new this.Promise(function(resolve, reject) { + return fn(...args, function(...args) { + return (args[0] != null ? reject : resolve)(args); + }); + }); + }; + job = new Job$1(task, args, options, this.jobDefaults, this.rejectOnDrop, this.Events, this._states, this.Promise); + job.promise.then(function(args) { + return typeof cb === "function" ? cb(...args) : void 0; + }).catch(function(args) { + if (Array.isArray(args)) { + return typeof cb === "function" ? cb(...args) : void 0; + } else { + return typeof cb === "function" ? cb(args) : void 0; + } + }); + return this._receive(job); + } - function makeTableLayout(rows) { - let cellRows = generateCells(rows); - layoutTable(cellRows); - fillInTable(cellRows); - addRowSpanCells(cellRows); - addColSpanCells(cellRows); - return cellRows; - } + schedule(...args) { + var job, options, task; + if (typeof args[0] === "function") { + [task, ...args] = args; + options = {}; + } else { + [options, task, ...args] = args; + } + job = new Job$1(task, args, options, this.jobDefaults, this.rejectOnDrop, this.Events, this._states, this.Promise); + this._receive(job); + return job.promise; + } - module.exports = { - makeTableLayout: makeTableLayout, - layoutTable: layoutTable, - addRowSpanCells: addRowSpanCells, - maxWidth: maxWidth, - fillInTable: fillInTable, - computeWidths: makeComputeWidths('colSpan', 'desiredWidth', 'x', 1), - computeHeights: makeComputeWidths('rowSpan', 'desiredHeight', 'y', 1), - }; -})(); + wrap(fn) { + var schedule, wrapped; + schedule = this.schedule.bind(this); + wrapped = function(...args) { + return schedule(fn.bind(this), ...args); + }; + wrapped.withOptions = function(options, ...args) { + return schedule(options, fn, ...args); + }; + return wrapped; + } -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); - } - }); - }); + async updateSettings(options = {}) { + await this._store.__updateSettings__(parser$5.overwrite(options, this.storeDefaults)); + parser$5.overwrite(options, this.instanceDefaults, this); + return this; + } - vals.forEach(function (val, index) { - if (typeof val === 'number') { - result[index] = val; - } - }); + currentReservoir() { + return this._store.__currentReservoir__(); + } - //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++; - } - } - } + incrementReservoir(incr = 0) { + return this._store.__incrementReservoir__(incr); + } - Object.assign(vals, result); - for (let j = 0; j < vals.length; j++) { - vals[j] = Math.max(forcedMin, vals[j] || 0); - } - }; -} + } + Bottleneck.default = Bottleneck; + Bottleneck.Events = Events$4; -/***/ }), + Bottleneck.version = Bottleneck.prototype.version = require$$8.version; -/***/ 16136: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + Bottleneck.strategy = Bottleneck.prototype.strategy = { + LEAK: 1, + OVERFLOW: 2, + OVERFLOW_PRIORITY: 4, + BLOCK: 3 + }; -const utils = __nccwpck_require__(98911); -const tableLayout = __nccwpck_require__(93875); + Bottleneck.BottleneckError = Bottleneck.prototype.BottleneckError = BottleneckError_1; -class Table extends Array { - constructor(options) { - super(); + Bottleneck.Group = Bottleneck.prototype.Group = Group_1; - this.options = utils.mergeOptions(options); - } + Bottleneck.RedisConnection = Bottleneck.prototype.RedisConnection = require$$2; - 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 = []; - } + Bottleneck.IORedisConnection = Bottleneck.prototype.IORedisConnection = require$$3; - let cells = tableLayout.makeTableLayout(array); + Bottleneck.Batcher = Bottleneck.prototype.Batcher = Batcher_1; - cells.forEach(function (row) { - row.forEach(function (cell) { - cell.mergeTableOptions(this.options, cells); - }, this); - }, this); + Bottleneck.prototype.jobDefaults = { + priority: DEFAULT_PRIORITY$1, + weight: 1, + expiration: null, + id: "" + }; - tableLayout.computeWidths(this.options.colWidths, cells); - tableLayout.computeHeights(this.options.rowHeights, cells); + Bottleneck.prototype.storeDefaults = { + maxConcurrent: null, + minTime: 0, + highWater: null, + strategy: Bottleneck.prototype.strategy.LEAK, + penalty: null, + reservoir: null, + reservoirRefreshInterval: null, + reservoirRefreshAmount: null, + reservoirIncreaseInterval: null, + reservoirIncreaseAmount: null, + reservoirIncreaseMaximum: null + }; - cells.forEach(function (row) { - row.forEach(function (cell) { - cell.init(this.options); - }, this); - }, this); + Bottleneck.prototype.localStoreDefaults = { + Promise: Promise, + timeout: null, + heartbeatInterval: 250 + }; - let result = []; + Bottleneck.prototype.redisStoreDefaults = { + Promise: Promise, + timeout: null, + heartbeatInterval: 5000, + clientTimeout: 10000, + Redis: null, + clientOptions: {}, + clusterNodes: null, + clearDatastore: false, + connection: null + }; - for (let rowIndex = 0; rowIndex < cells.length; rowIndex++) { - let row = cells[rowIndex]; - let heightOfRow = this.options.rowHeights[rowIndex]; + Bottleneck.prototype.instanceDefaults = { + datastore: "local", + connection: null, + id: "", + rejectOnDrop: true, + trackDoneStatus: false, + Promise: Promise + }; - if (rowIndex === 0 || !this.options.style.compact || (rowIndex == 1 && headersPresent)) { - doDraw(row, 'top', result); - } + Bottleneck.prototype.stopDefaults = { + enqueueErrorMessage: "This limiter has been stopped and cannot accept new jobs.", + dropWaitingJobs: true, + dropErrorMessage: "This limiter has been stopped." + }; - for (let lineNum = 0; lineNum < heightOfRow; lineNum++) { - doDraw(row, lineNum, result); - } + return Bottleneck; - if (rowIndex + 1 == cells.length) { - doDraw(row, 'bottom', result); - } - } + }).call(commonjsGlobal); - return result.join('\n'); - } + var Bottleneck_1 = Bottleneck; - get width() { - let str = this.toString().split('\n'); - return str[0].length; - } -} + var lib = Bottleneck_1; -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 lib; -module.exports = Table; +}))); /***/ }), -/***/ 98911: +/***/ 33717: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -const stringWidth = __nccwpck_require__(42577); +var concatMap = __nccwpck_require__(86891); +var balanced = __nccwpck_require__(9417); -function codeRegex(capture) { - return capture ? /\u001b\[((?:\d*;){0,5}\d*)m/g : /\u001b\[(?:\d*;){0,5}\d*m/g; -} +module.exports = expandTop; -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); -} +var escSlash = '\0SLASH'+Math.random()+'\0'; +var escOpen = '\0OPEN'+Math.random()+'\0'; +var escClose = '\0CLOSE'+Math.random()+'\0'; +var escComma = '\0COMMA'+Math.random()+'\0'; +var escPeriod = '\0PERIOD'+Math.random()+'\0'; -function repeat(str, times) { - return Array(times + 1).join(str); +function numeric(str) { + return parseInt(str, 10) == str + ? parseInt(str, 10) + : str.charCodeAt(0); } -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; +function escapeBraces(str) { + return str.split('\\\\').join(escSlash) + .split('\\{').join(escOpen) + .split('\\}').join(escClose) + .split('\\,').join(escComma) + .split('\\.').join(escPeriod); } -let codeCache = {}; - -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 unescapeBraces(str) { + return str.split(escSlash).join('\\') + .split(escOpen).join('{') + .split(escClose).join('}') + .split(escComma).join(',') + .split(escPeriod).join('.'); } -//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; -} +// Basically just str.split(","), but handling cases +// where we have nested braced sections, which should be +// treated as individual members, like {a,{b,c},d} +function parseCommaParts(str) { + if (!str) + return ['']; -function unwindState(state, ret) { - let lastBackgroundAdded = state.lastBackgroundAdded; - let lastForegroundAdded = state.lastForegroundAdded; + var parts = []; + var m = balanced('{', '}', str); - delete state.lastBackgroundAdded; - delete state.lastForegroundAdded; + if (!m) + return str.split(','); - Object.keys(state).forEach(function (key) { - if (state[key]) { - ret += codeCache[key].off; - } - }); + var pre = m.pre; + var body = m.body; + var post = m.post; + var p = pre.split(','); - if (lastBackgroundAdded && lastBackgroundAdded != '\u001b[49m') { - ret += '\u001b[49m'; - } - if (lastForegroundAdded && lastForegroundAdded != '\u001b[39m') { - ret += '\u001b[39m'; + p[p.length-1] += '{' + body + '}'; + var postParts = parseCommaParts(post); + if (post.length) { + p[p.length-1] += postParts.shift(); + p.push.apply(p, postParts); } - return ret; -} - -function rewindState(state, ret) { - let lastBackgroundAdded = state.lastBackgroundAdded; - let lastForegroundAdded = state.lastForegroundAdded; + parts.push.apply(parts, p); - delete state.lastBackgroundAdded; - delete state.lastForegroundAdded; + return parts; +} - Object.keys(state).forEach(function (key) { - if (state[key]) { - ret = codeCache[key].on + ret; - } - }); +function expandTop(str) { + if (!str) + return []; - if (lastBackgroundAdded && lastBackgroundAdded != '\u001b[49m') { - ret = lastBackgroundAdded + ret; - } - if (lastForegroundAdded && lastForegroundAdded != '\u001b[39m') { - ret = lastForegroundAdded + ret; + // I don't know why Bash 4.3 does this, but it does. + // Anything starting with {} will have the first two bytes preserved + // but *only* at the top level, so {},a}b will not expand to anything, + // but a{},b}c will be expanded to [a}c,abc]. + // One could argue that this is a bug in Bash, but since the goal of + // this module is to match Bash's rules, we escape a leading {} + if (str.substr(0, 2) === '{}') { + str = '\\{\\}' + str.substr(2); } - return ret; + return expand(escapeBraces(str), true).map(unescapeBraces); } -function truncateWidth(str, desiredLength) { - if (str.length === strlen(str)) { - return str.substr(0, desiredLength); - } +function identity(e) { + return e; +} - while (strlen(str) > desiredLength) { - str = str.slice(0, -1); - } +function embrace(str) { + return '{' + str + '}'; +} +function isPadded(el) { + return /^-?0\d/.test(el); +} - return str; +function lte(i, y) { + return i <= y; +} +function gte(i, y) { + return i >= y; } -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 = {}; +function expand(str, isTop) { + var expansions = []; - 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); + var m = balanced('{', '}', str); + if (!m || /\$$/.test(m.pre)) return [str]; - if (retLen < desiredLength) { - if (!myArray) { - break; - } // full-width chars may cause a whitespace which cannot be filled - ret += myArray[0]; - updateState(state, myArray); + var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); + var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); + var isSequence = isNumericSequence || isAlphaSequence; + var isOptions = m.body.indexOf(',') >= 0; + if (!isSequence && !isOptions) { + // {a},b} + if (m.post.match(/,.*\}/)) { + str = m.pre + '{' + m.body + escClose + m.post; + return expand(str); } + return [str]; } - return unwindState(state, ret); -} - -function truncate(str, desiredLength, truncateChar) { - truncateChar = truncateChar || '…'; - let lengthOfStr = strlen(str); - if (lengthOfStr <= desiredLength) { - return str; + var n; + if (isSequence) { + n = m.body.split(/\.\./); + } else { + n = parseCommaParts(m.body); + if (n.length === 1) { + // x{{a,b}}y ==> x{a}y x{b}y + n = expand(n[0], false).map(embrace); + if (n.length === 1) { + var post = m.post.length + ? expand(m.post, false) + : ['']; + return post.map(function(p) { + return m.pre + n[0] + p; + }); + } + } } - desiredLength -= strlen(truncateChar); - - let ret = truncateWidthWithAnsi(str, desiredLength); - return ret + truncateChar; -} + // at this point, n is the parts, and we know it's not a comma set + // with a single entry. -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: [], - }; -} + // no need to expand pre, since it is guaranteed to be free of brace-sets + var pre = m.pre; + var post = m.post.length + ? expand(m.post, false) + : ['']; -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; -} + var N; -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 (isSequence) { + var x = numeric(n[0]); + var y = numeric(n[1]); + var width = Math.max(n[0].length, n[1].length) + var incr = n.length == 3 + ? Math.abs(numeric(n[2])) + : 1; + var test = lte; + var reverse = y < x; + if (reverse) { + incr *= -1; + test = gte; } - if (newLength > maxLength) { - if (lineLength !== 0) { - lines.push(line.join('')); + var pad = n.some(isPadded); + + N = []; + + for (var i = x; test(i, y); i += incr) { + var c; + if (isAlphaSequence) { + c = String.fromCharCode(i); + if (c === '\\') + c = ''; + } else { + c = String(i); + if (pad) { + var need = width - c.length; + if (need > 0) { + var z = new Array(need + 1).join('0'); + if (i < 0) + c = '-' + z + c.slice(1); + else + c = z + c; + } + } } - line = [word]; - lineLength = strlen(word); - } else { - line.push(whitespace || '', word); - lineLength = newLength; + N.push(c); } - whitespace = split[i + 1]; + } else { + N = concatMap(n, function(el) { return expand(el, false) }); } - if (lineLength) { - lines.push(line.join('')); + + for (var j = 0; j < N.length; j++) { + for (var k = 0; k < post.length; k++) { + var expansion = pre + N[j] + post[k]; + if (!isTop || isSequence || expansion) + expansions.push(expansion); + } } - return lines; + + return expansions; } -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; + + +/***/ }), + +/***/ 72358: +/***/ ((module) => { + +module.exports = function btoa(str) { + return new Buffer(str).toString('base64') } -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)); + +/***/ }), + +/***/ 9239: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; +/*jshint node:true */ + +var Buffer = (__nccwpck_require__(14300).Buffer); // browserify +var SlowBuffer = (__nccwpck_require__(14300).SlowBuffer); + +module.exports = bufferEq; + +function bufferEq(a, b) { + + // shortcutting on type is necessary for correctness + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + return false; } - return output; + + // 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; } -module.exports = { - strlen: strlen, - repeat: repeat, - pad: pad, - truncate: truncate, - mergeOptions: mergeOptions, - wordWrap: multiLineWordWrap, - colorizeLines: colorizeLines, +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; }; /***/ }), -/***/ 48481: +/***/ 86966: /***/ ((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: - * - * * 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"; +/*! + * bytes + * Copyright(c) 2012-2014 TJ Holowaychuk + * Copyright(c) 2015 Jed Watson + * 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 exports. + * @public */ -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 -]; +module.exports = bytes; +module.exports.format = format; +module.exports.parse = parse; /** - * Convert a string to a UTF8 array - faster than via buffer - * @param str - * @returns {Array} + * Module variables. + * @private */ -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; +var formatThousandsRegExp = /\B(?=(\d{3})+(?!\d))/g; + +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; + +/** + * 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} + */ + +function bytes(value, options) { + if (typeof value === 'string') { + return parse(value); + } + + if (typeof value === 'number') { + return format(value, options); + } + + return null; +} + +/** + * 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 + */ + +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 { - utf8[p++] = (char >> 12) | 224; - utf8[p++] = ((char >> 6) & 63) | 128; - utf8[p++] = (char & 63) | 128; + unit = 'B'; } } - return utf8; -}; - -/** - * 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; + var val = value / map[unit.toLowerCase()]; + var str = val.toFixed(decimalPlaces); - 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; - } + if (!fixedDecimals) { + str = str.replace(formatDecimalsRegExp, '$1'); + } - result = lookup[(char ^ (result >> 8)) & 0xFF] ^ (result << 8); + if (thousandsSeparator) { + str = str.split('.').map(function (s, i) { + return i === 0 + ? s.replace(formatThousandsRegExp, thousandsSeparator) + : s + }).join('.'); } - return result & 0x3FFF; -}; + return str + unitSeparator + unit; +} /** - * 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} + * 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 */ -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 parse(val) { + if (typeof val === 'number' && !isNaN(val)) { + return val; } - return base; + if (typeof val !== 'string') { + return null; + } + + // 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); +} + + +/***/ }), + +/***/ 27972: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + +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.exports = (stack, options) => { + options = Object.assign({pretty: false}, options); + + return stack.replace(/\\/g, '/') + .split('\n') + .filter(line => { + const pathMatches = line.match(extractPathRegex); + if (pathMatches === null || !pathMatches[1]) { + return true; + } + + const match = pathMatches[1]; + + // Electron + if ( + match.includes('.app/Contents/Resources/electron.asar') || + match.includes('.app/Contents/Resources/default_app.asar') + ) { + return false; + } + + 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 line; + }) + .join('\n'); }; /***/ }), -/***/ 43595: +/***/ 2101: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/* +module.exports = __nccwpck_require__(16136); -The MIT License (MIT) +/***/ }), -Original Library - - Copyright (c) Marak Squires +/***/ 66168: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -Additional functionality - - Copyright (c) Sindre Sorhus (sindresorhus.com) +const { info, debug } = __nccwpck_require__(65829); +const utils = __nccwpck_require__(98911); -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: +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); -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. + /** + * 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; + } -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. + 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 = this.options.href || ''; + } else { + throw new Error('Content needs to be a primitive, got: ' + typeof content); + } + this.colSpan = options.colSpan || 1; + this.rowSpan = options.rowSpan || 1; + if (this.options.href) { + Object.defineProperty(this, 'href', { + get() { + return this.options.href; + }, + }); + } + } -*/ + mergeTableOptions(tableOptions, cells) { + this.cells = cells; -var colors = {}; -module['exports'] = colors; + let optionsChars = this.options.chars || {}; + let tableChars = tableOptions.chars; + let chars = (this.chars = {}); + CHAR_NAMES.forEach(function (name) { + setOption(optionsChars, tableChars, name, chars); + }); -colors.themes = {}; + this.truncate = this.options.truncate || tableOptions.truncate; + + 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; + + this.fixedWidth = tableOptions.colWidths[this.x]; + this.lines = this.computeLines(tableOptions); + + this.desiredWidth = utils.strlen(this.content) + this.paddingLeft + this.paddingRight; + this.desiredHeight = this.lines.length; + } + + computeLines(tableOptions) { + if (this.fixedWidth && (tableOptions.wordWrap || tableOptions.textWrap)) { + this.fixedWidth -= this.paddingLeft + this.paddingRight; + if (this.colSpan) { + let i = 1; + while (i < this.colSpan) { + this.fixedWidth += tableOptions.colWidths[this.x + i]; + i++; + } + } + const { wrapOnWordBoundary = true } = tableOptions; + return this.wrapLines(utils.wordWrap(this.fixedWidth, this.content, wrapOnWordBoundary)); + } + return this.wrapLines(this.content.split('\n')); + } -var util = __nccwpck_require__(73837); -var ansiStyles = colors.styles = __nccwpck_require__(73104); -var defineProps = Object.defineProperties; -var newLineRegex = new RegExp(/[\r\n]+/g); + wrapLines(computedLines) { + const lines = utils.colorizeLines(computedLines); + if (this.href) { + return lines.map((line) => utils.hyperlink(this.href, line)); + } + return lines; + } -colors.supportsColor = (__nccwpck_require__(10662).supportsColor); + /** + * 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); -if (typeof colors.enabled === 'undefined') { - colors.enabled = colors.supportsColor() !== false; -} + this.hAlign = this.options.hAlign || tableOptions.colAligns[x]; + this.vAlign = this.options.vAlign || tableOptions.rowAligns[y]; -colors.enable = function() { - colors.enabled = true; -}; + this.drawRight = x + this.colSpan == tableOptions.colWidths.length; + } -colors.disable = function() { - colors.enabled = false; -}; + /** + * 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 content = utils.truncate(this.content, 10, this.truncate); + if (!lineNum) { + info(`${this.y}-${this.x}: ${this.rowSpan - lineNum}x${this.colSpan} Cell ${content}`); + } else { + // debug(`${lineNum}-${this.x}: 1x${this.colSpan} RowSpanCell ${content}`); + } + 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); + } -colors.stripColors = colors.strip = function(str) { - return ('' + str).replace(/\x1B\[\d+m/g, ''); -}; + /** + * 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('')); + } -// eslint-disable-next-line no-unused-vars -var stylize = colors.stylize = function stylize(str, style) { - if (!colors.enabled) { - return str+''; + _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]; } - var styleMap = ansiStyles[style]; + wrapWithStyleColors(styleProperty, content) { + if (this[styleProperty] && this[styleProperty].length) { + try { + let colors = __nccwpck_require__(59256); + 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; + } + } - // 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); + /** + * 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); } - return styleMap.open + str + styleMap.close; -}; + 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 matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; -var escapeStringRegexp = function(str) { - if (typeof str !== 'string') { - throw new TypeError('Expected a string'); + /** + * 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); } - return str.replace(matchOperatorsRe, '\\$&'); -}; -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; + /** + * 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); + } } -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; -})(); +class ColSpanCell { + /** + * A Cell that doesn't do anything. It just draws empty lines. + * Used as a placeholder in column spanning. + * @constructor + */ + constructor() {} -var proto = defineProps(function colors() {}, styles); + draw(lineNum) { + if (typeof lineNum === 'number') { + debug(`${this.y}-${this.x}: 1x1 ColSpanCell`); + } + return ''; + } -function applyStyle() { - var args = Array.prototype.slice.call(arguments); + init() {} - 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(' '); + mergeTableOptions() {} +} - if (!colors.enabled || !str) { - return str; +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; } - var newLinesPresent = str.indexOf('\n') != -1; - - var nestedStyles = this._styles; + init(tableOptions) { + let y = this.y; + let originalY = this.originalCell.y; + this.cellOffset = y - originalY; + this.offset = findDimension(tableOptions.rowHeights, originalY, this.cellOffset); + } - 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; - }); + draw(lineNum) { + if (lineNum == 'top') { + return this.originalCell.draw(this.offset, this.cellOffset); + } + if (lineNum == 'bottom') { + return this.originalCell.draw('bottom'); } + debug(`${this.y}-${this.x}: 1x${this.colSpan} RowSpanCell for ${this.originalCell.content}`); + return this.originalCell.draw(this.offset + 1 + lineNum); } - return str; + mergeTableOptions() {} } -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); +function firstDefined(...args) { + return args.filter((v) => v !== undefined && v !== null).shift(); +} + +// 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] = firstDefined(objA[nameA], objA[nameB], objB[nameA], objB[nameB]); + } else { + targetObj[nameB] = firstDefined(objA[nameB], objB[nameB]); } -}; +} -function init() { - var ret = {}; - Object.keys(styles).forEach(function(name) { - ret[name] = { - get: function() { - return build([name]); - }, - }; - }); +function findDimension(dimensionTable, startingIndex, span) { + let ret = dimensionTable[startingIndex]; + for (let i = 1; i < span; i++) { + ret += 1 + dimensionTable[startingIndex + i]; + } return ret; } -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); - -// 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); - -for (var map in colors.maps) { - (function(map) { - colors[map] = function(str) { - return sequencer(colors.maps[map], str); - }; - })(map); +function sumPlusOne(a, b) { + return a + b + 1; } -defineProps(colors, init()); +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; /***/ }), -/***/ 31302: +/***/ 65829: /***/ ((module) => { -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; +let messages = []; +let level = 0; + +const debug = (msg, min) => { + if (level >= min) { + messages.push(msg); + } }; +debug.WARN = 1; +debug.INFO = 2; +debug.DEBUG = 3; + +debug.reset = () => { + messages = []; +}; + +debug.setDebugLevel = (v) => { + level = v; +}; + +debug.warn = (msg) => debug(msg, debug.WARN); +debug.info = (msg) => debug(msg, debug.INFO); +debug.debug = (msg) => debug(msg, debug.DEBUG); + +debug.debugMessages = () => messages; + +module.exports = debug; + /***/ }), -/***/ 45610: -/***/ ((module) => { +/***/ 93875: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -// 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); +const { warn, debug } = __nccwpck_require__(65829); +const Cell = __nccwpck_require__(66168); +const { ColSpanCell, RowSpanCell } = Cell; - function randomNumber(range) { - var r = Math.floor(Math.random() * range); - return r; +(function () { + function next(alloc, col) { + if (alloc[col] > 0) { + return next(alloc, col + 1); + } + return col; + } + + function layoutTable(table) { + let alloc = {}; + table.forEach(function (row, rowIndex) { + let col = 0; + row.forEach(function (cell) { + cell.y = rowIndex; + // Avoid erroneous call to next() on first row + cell.x = rowIndex ? next(alloc, col) : col; + const rowSpan = cell.rowSpan || 1; + const colSpan = cell.colSpan || 1; + if (rowSpan > 1) { + for (let cs = 0; cs < colSpan; cs++) { + alloc[cell.x + cs] = rowSpan; + } + } + col = cell.x + colSpan; + }); + Object.keys(alloc).forEach((idx) => { + alloc[idx]--; + if (alloc[idx] < 1) delete alloc[idx]; + }); + }); } - function isChar(character) { - var bool = false; - all.filter(function(i) { - bool = (i === character); + function maxWidth(table) { + let mw = 0; + table.forEach(function (row) { + row.forEach(function (cell) { + mw = Math.max(mw, cell.x + (cell.colSpan || 1)); + }); }); - return bool; + return mw; } + function maxHeight(table) { + return table.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; + 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); + + 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 yConflict && xConflict; + } + + 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; + } } - 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; + } + return false; + } + + function allBlank(rows, y, xMin, xMax) { + for (let x = xMin; x < xMax; x++) { + if (conflictExists(rows, x, y)) { + return false; } + } + return true; + } - 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)]; - } + 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]); + } + }); + }); + } + + 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); } } } - return result; } - // don't summon him - return heComes(text, options); -}; + function insertCell(cell, row) { + let x = 0; + while (x < row.length && row[x].x < cell.x) { + x++; + } + row.splice(x, 0, cell); + } + function fillInTable(table) { + let h_max = maxHeight(table); + let w_max = maxWidth(table); + debug(`Max rows: ${h_max}; Max cols: ${w_max}`); + 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; + warn(`Missing cell at ${cell.y}-${cell.x}.`); + insertCell(cell, table[y]); + } + } + } + } -/***/ }), + 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); + }); + }); + } -/***/ 76936: -/***/ ((module) => { + function makeTableLayout(rows) { + let cellRows = generateCells(rows); + layoutTable(cellRows); + fillInTable(cellRows); + addRowSpanCells(cellRows); + addColSpanCells(cellRows); + return cellRows; + } -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); - } + 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 = []; + let auto = {}; + 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); + } + }); + }); -/***/ }), + vals.forEach(function (val, index) { + if (typeof val === 'number') { + result[index] = val; + } + }); -/***/ 75210: -/***/ ((module) => { + //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; + if (typeof existingWidth === 'number') { + for (let i = 1; i < span; i++) { + existingWidth += 1 + result[col + i]; + if (typeof vals[col + i] !== 'number') { + editableCols++; + } + } + } else { + existingWidth = desiredWidth === 'desiredWidth' ? cell.desiredWidth - 1 : 1; + if (!auto[col] || auto[col] < existingWidth) { + auto[col] = existingWidth; + } + } -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); + 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.assign(vals, result, auto); + for (let j = 0; j < vals.length; j++) { + vals[j] = Math.max(forcedMin, vals[j] || 0); + } + }; +} /***/ }), -/***/ 13441: -/***/ ((module) => { +/***/ 16136: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -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); - }; -}; +const debug = __nccwpck_require__(65829); +const utils = __nccwpck_require__(98911); +const tableLayout = __nccwpck_require__(93875); +class Table extends Array { + constructor(opts) { + super(); -/***/ }), + const options = utils.mergeOptions(opts); + Object.defineProperty(this, 'options', { + value: options, + enumerable: options.debug, + }); -/***/ 12989: -/***/ ((module) => { + if (options.debug) { + switch (typeof options.debug) { + case 'boolean': + debug.setDebugLevel(debug.WARN); + break; + case 'number': + debug.setDebugLevel(options.debug); + break; + case 'string': + debug.setDebugLevel(parseInt(options.debug, 10)); + break; + default: + debug.setDebugLevel(debug.WARN); + debug.warn(`Debug option is expected to be boolean, number, or string. Received a ${typeof options.debug}`); + } + Object.defineProperty(this, 'messages', { + get() { + return debug.debugMessages(); + }, + }); + } + } -module['exports'] = function(colors) { - return function(letter, i, exploded) { - return i % 2 === 0 ? letter : colors.inverse(letter); - }; -}; + 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 = []; + } + let cells = tableLayout.makeTableLayout(array); -/***/ }), + cells.forEach(function (row) { + row.forEach(function (cell) { + cell.mergeTableOptions(this.options, cells); + }, this); + }, this); -/***/ 73104: -/***/ ((module) => { + tableLayout.computeWidths(this.options.colWidths, cells); + tableLayout.computeHeights(this.options.rowHeights, cells); -/* -The MIT License (MIT) + cells.forEach(function (row) { + row.forEach(function (cell) { + cell.init(this.options); + }, this); + }, this); -Copyright (c) Sindre Sorhus (sindresorhus.com) + let result = []; -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: + for (let rowIndex = 0; rowIndex < cells.length; rowIndex++) { + let row = cells[rowIndex]; + let heightOfRow = this.options.rowHeights[rowIndex]; -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. + if (rowIndex === 0 || !this.options.style.compact || (rowIndex == 1 && headersPresent)) { + doDraw(row, 'top', result); + } -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. + for (let lineNum = 0; lineNum < heightOfRow; lineNum++) { + doDraw(row, lineNum, result); + } -*/ + if (rowIndex + 1 == cells.length) { + doDraw(row, 'bottom', result); + } + } -var styles = {}; -module['exports'] = styles; + return result.join('\n'); + } -var codes = { - reset: [0, 0], + get width() { + let str = this.toString().split('\n'); + return str[0].length; + } +} - bold: [1, 22], - dim: [2, 22], - italic: [3, 23], - underline: [4, 24], - inverse: [7, 27], - hidden: [8, 28], - strikethrough: [9, 29], +Table.reset = () => debug.reset(); - 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], +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); +} - brightRed: [91, 39], - brightGreen: [92, 39], - brightYellow: [93, 39], - brightBlue: [94, 39], - brightMagenta: [95, 39], - brightCyan: [96, 39], - brightWhite: [97, 39], +module.exports = Table; - 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], - bgBrightRed: [101, 49], - bgBrightGreen: [102, 49], - bgBrightYellow: [103, 49], - bgBrightBlue: [104, 49], - bgBrightMagenta: [105, 49], - bgBrightCyan: [106, 49], - bgBrightWhite: [107, 49], +/***/ }), - // 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], +/***/ 98911: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -}; +const stringWidth = __nccwpck_require__(42577); -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'; -}); +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); +} -/***/ }), +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; +} -/***/ 10223: -/***/ ((module) => { +let codeCache = {}; -"use strict"; -/* -MIT License +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 }; +} -Copyright (c) Sindre Sorhus (sindresorhus.com) +//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; + } +} -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 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; +} -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. +function unwindState(state, ret) { + let lastBackgroundAdded = state.lastBackgroundAdded; + let lastForegroundAdded = state.lastForegroundAdded; -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. -*/ + 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.exports = function(flag, argv) { - argv = argv || process.argv; + return ret; +} - var terminatorPos = argv.indexOf('--'); - var prefix = /^-{1,2}/.test(flag) ? '' : '--'; - var pos = argv.indexOf(prefix + flag); +function rewindState(state, ret) { + let lastBackgroundAdded = state.lastBackgroundAdded; + let lastForegroundAdded = state.lastForegroundAdded; - return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos); -}; + delete state.lastBackgroundAdded; + delete state.lastForegroundAdded; + Object.keys(state).forEach(function (key) { + if (state[key]) { + ret = codeCache[key].on + ret; + } + }); -/***/ }), + if (lastBackgroundAdded && lastBackgroundAdded != '\u001b[49m') { + ret = lastBackgroundAdded + ret; + } + if (lastForegroundAdded && lastForegroundAdded != '\u001b[39m') { + ret = lastForegroundAdded + ret; + } -/***/ 10662: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return ret; +} -"use strict"; -/* -The MIT License (MIT) +function truncateWidth(str, desiredLength) { + if (str.length === strlen(str)) { + return str.substr(0, desiredLength); + } -Copyright (c) Sindre Sorhus (sindresorhus.com) + while (strlen(str) > desiredLength) { + str = str.slice(0, -1); + } -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: + return str; +} -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. +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 = {}; -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. + 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); -*/ + 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); +} +function truncate(str, desiredLength, truncateChar) { + truncateChar = truncateChar || '…'; + let lengthOfStr = strlen(str); + if (lengthOfStr <= desiredLength) { + return str; + } + desiredLength -= strlen(truncateChar); -var os = __nccwpck_require__(22037); -var hasFlag = __nccwpck_require__(10223); + let ret = truncateWidthWithAnsi(str, desiredLength); -var env = process.env; + return ret + truncateChar; +} -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; +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: [], + }; } -if ('FORCE_COLOR' in env) { - forceColor = env.FORCE_COLOR.length === 0 - || parseInt(env.FORCE_COLOR, 10) !== 0; + +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 translateLevel(level) { - if (level === 0) { - return false; +// Wrap on word boundary +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; + } + whitespace = split[i + 1]; } - - return { - level: level, - hasBasic: true, - has256: level >= 2, - has16m: level >= 3, - }; + if (lineLength) { + lines.push(line.join('')); + } + return lines; } -function supportsColor(stream) { - if (forceColor === false) { - return 0; +// Wrap text (ignoring word boundaries) +function textWrap(maxLength, input) { + let lines = []; + let line = ''; + function pushLine(str, ws) { + if (line.length && ws) line += ws; + line += str; + while (line.length > maxLength) { + lines.push(line.slice(0, maxLength)); + line = line.slice(maxLength); + } + } + let split = input.split(/(\s+)/g); + for (let i = 0; i < split.length; i += 2) { + pushLine(split[i], i && split[i - 1]); } + if (line.length) lines.push(line); + return lines; +} - if (hasFlag('color=16m') || hasFlag('color=full') - || hasFlag('color=truecolor')) { - return 3; +function multiLineWordWrap(maxLength, input, wrapOnWordBoundary = true) { + let output = []; + input = input.split('\n'); + const handler = wrapOnWordBoundary ? wordWrap : textWrap; + for (let i = 0; i < input.length; i++) { + output.push.apply(output, handler(maxLength, input[i])); } + return output; +} - if (hasFlag('color=256')) { - return 2; +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; +} - if (stream && !stream.isTTY && forceColor !== true) { - return 0; - } +/** + * Credit: Matheus Sampaio https://github.com/matheussampaio + */ +function hyperlink(url, text) { + const OSC = '\u001B]'; + const BEL = '\u0007'; + const SEP = ';'; - var min = forceColor ? 1 : 0; + return [OSC, '8', SEP, SEP, url || text, BEL, text, OSC, '8', SEP, SEP, BEL].join(''); +} - 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; - } +module.exports = { + strlen: strlen, + repeat: repeat, + pad: pad, + truncate: truncate, + mergeOptions: mergeOptions, + wordWrap: multiLineWordWrap, + colorizeLines: colorizeLines, + hyperlink, +}; - return 1; - } - if ('CI' in env) { - if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(function(sign) { - return sign in env; - }) || env.CI_NAME === 'codeship') { - return 1; - } +/***/ }), - return min; - } +/***/ 48481: +/***/ ((module) => { - if ('TEAMCITY_VERSION' in env) { - return (/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0 - ); - } +/* + * 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. + */ - if ('TERM_PROGRAM' in env) { - var version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); +/* 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 + */ - switch (env.TERM_PROGRAM) { - case 'iTerm.app': - return version >= 3 ? 3 : 2; - case 'Hyper': - return 3; - case 'Apple_Terminal': - return 2; - // No default - } - } +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 +]; - if (/-256(color)?$/i.test(env.TERM)) { - return 2; - } +/** + * 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; - if (/^screen|^xterm|^vt100|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { - return 1; + 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; + } } - if ('COLORTERM' in env) { - return 1; - } + return utf8; +}; - if (env.TERM === 'dumb') { - return min; - } +/** + * 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; - return min; -} + 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 getSupportLevel(stream) { - var level = supportsColor(stream); - return translateLevel(level); -} + result = lookup[(char ^ (result >> 8)) & 0xFF] ^ (result << 8); + } -module.exports = { - supportsColor: getSupportLevel, - stdout: getSupportLevel(process.stdout), - stderr: getSupportLevel(process.stderr), + return result & 0x3FFF; }; +/** + * 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]); -/***/ }), - -/***/ 41997: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + while (i < len) { + if (generate(keys[i++]) !== base) return -1; + } -// -// 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; + return base; +}; /***/ }), diff --git a/package.json b/package.json index 0838e8206..dd934ba45 100644 --- a/package.json +++ b/package.json @@ -23,7 +23,7 @@ "dependencies": { "@actions/core": "1.6.0", "@probot/adapter-github-actions": "3.1.1", - "cli-table3": "0.6.1", + "cli-table3": "0.6.2", "compare-versions": "4.1.3", "deepmerge": "4.2.2", "escape-string-regexp": "4.0.0", diff --git a/yarn.lock b/yarn.lock index b74b4bd7d..3fd7ce459 100644 --- a/yarn.lock +++ b/yarn.lock @@ -300,6 +300,11 @@ resolved "https://registry.yarnpkg.com/@bcoe/v8-coverage/-/v8-coverage-0.2.3.tgz#75a2e8b51cb758a7553d6804a5932d7aace75c39" integrity sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw== +"@colors/colors@1.5.0": + version "1.5.0" + resolved "https://registry.yarnpkg.com/@colors/colors/-/colors-1.5.0.tgz#bb504579c1cae923e6576a4f5da43d25f97bdbd9" + integrity sha512-ooWCrlZP11i8GImSjTHYHLkvFDP48nS4+204nGb1RiX/WXYHmJA2III9/e2DWVabCESdW7hBAEzHRqUn9OUVvQ== + "@eslint/eslintrc@^1.2.1": version "1.2.1" resolved "https://registry.yarnpkg.com/@eslint/eslintrc/-/eslintrc-1.2.1.tgz#8b5e1c49f4077235516bc9ec7d41378c0f69b8c6" @@ -1587,14 +1592,14 @@ cli-cursor@^3.1.0: dependencies: restore-cursor "^3.1.0" -cli-table3@0.6.1: - version "0.6.1" - resolved "https://registry.yarnpkg.com/cli-table3/-/cli-table3-0.6.1.tgz#36ce9b7af4847f288d3cdd081fbd09bf7bd237b8" - integrity sha512-w0q/enDHhPLq44ovMGdQeeDLvwxwavsJX7oQGYt/LrBlYsyaxyDnp6z3QzFut/6kLLKnlcUVJLrpB7KBfgG/RA== +cli-table3@0.6.2: + version "0.6.2" + resolved "https://registry.yarnpkg.com/cli-table3/-/cli-table3-0.6.2.tgz#aaf5df9d8b5bf12634dc8b3040806a0c07120d2a" + integrity sha512-QyavHCaIC80cMivimWu4aWHilIpiDpfm3hGmqAmXVL1UsnbLuBSMd21hTX6VY4ZSDSM73ESLeF8TOYId3rBTbw== dependencies: string-width "^4.2.0" optionalDependencies: - colors "1.4.0" + "@colors/colors" "1.5.0" cli-truncate@^2.1.0: version "2.1.0" @@ -1677,11 +1682,6 @@ colorette@^2.0.16: resolved "https://registry.yarnpkg.com/colorette/-/colorette-2.0.16.tgz#713b9af84fdb000139f04546bd4a93f62a5085da" integrity sha512-hUewv7oMjCp+wkBv5Rm0v87eJhq4woh5rSR+42YSQJKecCqgIqNkZ6lAlQms/BwHPJA5NKMRlpxPRv0n8HQW6g== -colors@1.4.0: - version "1.4.0" - resolved "https://registry.yarnpkg.com/colors/-/colors-1.4.0.tgz#c50491479d4c1bdaed2c9ced32cf7c7dc2360f78" - integrity sha512-a+UqTh4kgZg/SlGvfbzDHpgRu7AAQOmmqRHJnxhRZICKFUT91brVhNNt58CMWU9PsBbv3PDCZUHbVxuDiH2mtA== - combined-stream@^1.0.8: version "1.0.8" resolved "https://registry.yarnpkg.com/combined-stream/-/combined-stream-1.0.8.tgz#c3d45a8b34fd730631a110a8a2520682b31d5a7f"