\n \n \n \n \n \n \n );\n }\n return null;\n }\n}\n\nexport default AnonymousReportInitializerWithPath;\n","'use strict';\n\nfunction _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }\n\nfunction _nonIterableRest() { throw new TypeError(\"Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\n\nfunction _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== \"undefined\" && arr[Symbol.iterator] || arr[\"@@iterator\"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_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; }\n\nfunction _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }\n\nfunction _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== \"undefined\" && o[Symbol.iterator] || o[\"@@iterator\"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === \"number\") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e2) { throw _e2; }, f: F }; } throw new TypeError(\"Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e3) { didErr = true; err = _e3; }, f: function f() { try { if (!normalCompletion && it[\"return\"] != null) it[\"return\"](); } finally { if (didErr) throw err; } } }; }\n\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }, _typeof(obj); }\n\nfunction _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }\n\nfunction _nonIterableSpread() { throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\n\nfunction _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === \"string\") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === \"Object\" && o.constructor) n = o.constructor.name; if (n === \"Map\" || n === \"Set\") return Array.from(o); if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }\n\nfunction _iterableToArray(iter) { if (typeof Symbol !== \"undefined\" && iter[Symbol.iterator] != null || iter[\"@@iterator\"] != null) return Array.from(iter); }\n\nfunction _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }\n\nfunction _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }\n\nvar strictUriEncode = require('strict-uri-encode');\n\nvar decodeComponent = require('decode-uri-component');\n\nvar splitOnFirst = require('split-on-first');\n\nvar filterObject = require('filter-obj');\n\nvar isNullOrUndefined = function isNullOrUndefined(value) {\n return value === null || value === undefined;\n};\n\nfunction encoderForArrayFormat(options) {\n switch (options.arrayFormat) {\n case 'index':\n return function (key) {\n return function (result, value) {\n var index = result.length;\n\n if (value === undefined || options.skipNull && value === null || options.skipEmptyString && value === '') {\n return result;\n }\n\n if (value === null) {\n return [].concat(_toConsumableArray(result), [[encode(key, options), '[', index, ']'].join('')]);\n }\n\n return [].concat(_toConsumableArray(result), [[encode(key, options), '[', encode(index, options), ']=', encode(value, options)].join('')]);\n };\n };\n\n case 'bracket':\n return function (key) {\n return function (result, value) {\n if (value === undefined || options.skipNull && value === null || options.skipEmptyString && value === '') {\n return result;\n }\n\n if (value === null) {\n return [].concat(_toConsumableArray(result), [[encode(key, options), '[]'].join('')]);\n }\n\n return [].concat(_toConsumableArray(result), [[encode(key, options), '[]=', encode(value, options)].join('')]);\n };\n };\n\n case 'comma':\n case 'separator':\n return function (key) {\n return function (result, value) {\n if (value === null || value === undefined || value.length === 0) {\n return result;\n }\n\n if (result.length === 0) {\n return [[encode(key, options), '=', encode(value, options)].join('')];\n }\n\n return [[result, encode(value, options)].join(options.arrayFormatSeparator)];\n };\n };\n\n default:\n return function (key) {\n return function (result, value) {\n if (value === undefined || options.skipNull && value === null || options.skipEmptyString && value === '') {\n return result;\n }\n\n if (value === null) {\n return [].concat(_toConsumableArray(result), [encode(key, options)]);\n }\n\n return [].concat(_toConsumableArray(result), [[encode(key, options), '=', encode(value, options)].join('')]);\n };\n };\n }\n}\n\nfunction parserForArrayFormat(options) {\n var result;\n\n switch (options.arrayFormat) {\n case 'index':\n return function (key, value, accumulator) {\n result = /\\[(\\d*)\\]$/.exec(key);\n key = key.replace(/\\[\\d*\\]$/, '');\n\n if (!result) {\n accumulator[key] = value;\n return;\n }\n\n if (accumulator[key] === undefined) {\n accumulator[key] = {};\n }\n\n accumulator[key][result[1]] = value;\n };\n\n case 'bracket':\n return function (key, value, accumulator) {\n result = /(\\[\\])$/.exec(key);\n key = key.replace(/\\[\\]$/, '');\n\n if (!result) {\n accumulator[key] = value;\n return;\n }\n\n if (accumulator[key] === undefined) {\n accumulator[key] = [value];\n return;\n }\n\n accumulator[key] = [].concat(accumulator[key], value);\n };\n\n case 'comma':\n case 'separator':\n return function (key, value, accumulator) {\n var isArray = typeof value === 'string' && value.includes(options.arrayFormatSeparator);\n var isEncodedArray = typeof value === 'string' && !isArray && decode(value, options).includes(options.arrayFormatSeparator);\n value = isEncodedArray ? decode(value, options) : value;\n var newValue = isArray || isEncodedArray ? value.split(options.arrayFormatSeparator).map(function (item) {\n return decode(item, options);\n }) : value === null ? value : decode(value, options);\n accumulator[key] = newValue;\n };\n\n default:\n return function (key, value, accumulator) {\n if (accumulator[key] === undefined) {\n accumulator[key] = value;\n return;\n }\n\n accumulator[key] = [].concat(accumulator[key], value);\n };\n }\n}\n\nfunction validateArrayFormatSeparator(value) {\n if (typeof value !== 'string' || value.length !== 1) {\n throw new TypeError('arrayFormatSeparator must be single character string');\n }\n}\n\nfunction encode(value, options) {\n if (options.encode) {\n return options.strict ? strictUriEncode(value) : encodeURIComponent(value);\n }\n\n return value;\n}\n\nfunction decode(value, options) {\n if (options.decode) {\n return decodeComponent(value);\n }\n\n return value;\n}\n\nfunction keysSorter(input) {\n if (Array.isArray(input)) {\n return input.sort();\n }\n\n if (_typeof(input) === 'object') {\n return keysSorter(Object.keys(input)).sort(function (a, b) {\n return Number(a) - Number(b);\n }).map(function (key) {\n return input[key];\n });\n }\n\n return input;\n}\n\nfunction removeHash(input) {\n var hashStart = input.indexOf('#');\n\n if (hashStart !== -1) {\n input = input.slice(0, hashStart);\n }\n\n return input;\n}\n\nfunction getHash(url) {\n var hash = '';\n var hashStart = url.indexOf('#');\n\n if (hashStart !== -1) {\n hash = url.slice(hashStart);\n }\n\n return hash;\n}\n\nfunction extract(input) {\n input = removeHash(input);\n var queryStart = input.indexOf('?');\n\n if (queryStart === -1) {\n return '';\n }\n\n return input.slice(queryStart + 1);\n}\n\nfunction parseValue(value, options) {\n if (options.parseNumbers && !Number.isNaN(Number(value)) && typeof value === 'string' && value.trim() !== '') {\n value = Number(value);\n } else if (options.parseBooleans && value !== null && (value.toLowerCase() === 'true' || value.toLowerCase() === 'false')) {\n value = value.toLowerCase() === 'true';\n }\n\n return value;\n}\n\nfunction parse(query, options) {\n options = Object.assign({\n decode: true,\n sort: true,\n arrayFormat: 'none',\n arrayFormatSeparator: ',',\n parseNumbers: false,\n parseBooleans: false\n }, options);\n validateArrayFormatSeparator(options.arrayFormatSeparator);\n var formatter = parserForArrayFormat(options); // Create an object with no prototype\n\n var ret = Object.create(null);\n\n if (typeof query !== 'string') {\n return ret;\n }\n\n query = query.trim().replace(/^[?#&]/, '');\n\n if (!query) {\n return ret;\n }\n\n var _iterator = _createForOfIteratorHelper(query.split('&')),\n _step;\n\n try {\n for (_iterator.s(); !(_step = _iterator.n()).done;) {\n var param = _step.value;\n\n if (param === '') {\n continue;\n }\n\n var _splitOnFirst = splitOnFirst(options.decode ? param.replace(/\\+/g, ' ') : param, '='),\n _splitOnFirst2 = _slicedToArray(_splitOnFirst, 2),\n _key = _splitOnFirst2[0],\n _value = _splitOnFirst2[1]; // Missing `=` should be `null`:\n // http://w3.org/TR/2012/WD-url-20120524/#collect-url-parameters\n\n\n _value = _value === undefined ? null : ['comma', 'separator'].includes(options.arrayFormat) ? _value : decode(_value, options);\n formatter(decode(_key, options), _value, ret);\n }\n } catch (err) {\n _iterator.e(err);\n } finally {\n _iterator.f();\n }\n\n for (var _i = 0, _Object$keys = Object.keys(ret); _i < _Object$keys.length; _i++) {\n var key = _Object$keys[_i];\n var value = ret[key];\n\n if (_typeof(value) === 'object' && value !== null) {\n for (var _i2 = 0, _Object$keys2 = Object.keys(value); _i2 < _Object$keys2.length; _i2++) {\n var k = _Object$keys2[_i2];\n value[k] = parseValue(value[k], options);\n }\n } else {\n ret[key] = parseValue(value, options);\n }\n }\n\n if (options.sort === false) {\n return ret;\n }\n\n return (options.sort === true ? Object.keys(ret).sort() : Object.keys(ret).sort(options.sort)).reduce(function (result, key) {\n var value = ret[key];\n\n if (Boolean(value) && _typeof(value) === 'object' && !Array.isArray(value)) {\n // Sort object keys, not values\n result[key] = keysSorter(value);\n } else {\n result[key] = value;\n }\n\n return result;\n }, Object.create(null));\n}\n\nexports.extract = extract;\nexports.parse = parse;\n\nexports.stringify = function (object, options) {\n if (!object) {\n return '';\n }\n\n options = Object.assign({\n encode: true,\n strict: true,\n arrayFormat: 'none',\n arrayFormatSeparator: ','\n }, options);\n validateArrayFormatSeparator(options.arrayFormatSeparator);\n\n var shouldFilter = function shouldFilter(key) {\n return options.skipNull && isNullOrUndefined(object[key]) || options.skipEmptyString && object[key] === '';\n };\n\n var formatter = encoderForArrayFormat(options);\n var objectCopy = {};\n\n for (var _i3 = 0, _Object$keys3 = Object.keys(object); _i3 < _Object$keys3.length; _i3++) {\n var key = _Object$keys3[_i3];\n\n if (!shouldFilter(key)) {\n objectCopy[key] = object[key];\n }\n }\n\n var keys = Object.keys(objectCopy);\n\n if (options.sort !== false) {\n keys.sort(options.sort);\n }\n\n return keys.map(function (key) {\n var value = object[key];\n\n if (value === undefined) {\n return '';\n }\n\n if (value === null) {\n return encode(key, options);\n }\n\n if (Array.isArray(value)) {\n return value.reduce(formatter(key), []).join('&');\n }\n\n return encode(key, options) + '=' + encode(value, options);\n }).filter(function (x) {\n return x.length > 0;\n }).join('&');\n};\n\nexports.parseUrl = function (url, options) {\n options = Object.assign({\n decode: true\n }, options);\n\n var _splitOnFirst3 = splitOnFirst(url, '#'),\n _splitOnFirst4 = _slicedToArray(_splitOnFirst3, 2),\n url_ = _splitOnFirst4[0],\n hash = _splitOnFirst4[1];\n\n return Object.assign({\n url: url_.split('?')[0] || '',\n query: parse(extract(url), options)\n }, options && options.parseFragmentIdentifier && hash ? {\n fragmentIdentifier: decode(hash, options)\n } : {});\n};\n\nexports.stringifyUrl = function (object, options) {\n options = Object.assign({\n encode: true,\n strict: true\n }, options);\n var url = removeHash(object.url).split('?')[0] || '';\n var queryFromUrl = exports.extract(object.url);\n var parsedQueryFromUrl = exports.parse(queryFromUrl, {\n sort: false\n });\n var query = Object.assign(parsedQueryFromUrl, object.query);\n var queryString = exports.stringify(query, options);\n\n if (queryString) {\n queryString = \"?\".concat(queryString);\n }\n\n var hash = getHash(object.url);\n\n if (object.fragmentIdentifier) {\n hash = \"#\".concat(encode(object.fragmentIdentifier, options));\n }\n\n return \"\".concat(url).concat(queryString).concat(hash);\n};\n\nexports.pick = function (input, filter, options) {\n options = Object.assign({\n parseFragmentIdentifier: true\n }, options);\n\n var _exports$parseUrl = exports.parseUrl(input, options),\n url = _exports$parseUrl.url,\n query = _exports$parseUrl.query,\n fragmentIdentifier = _exports$parseUrl.fragmentIdentifier;\n\n return exports.stringifyUrl({\n url: url,\n query: filterObject(query, filter),\n fragmentIdentifier: fragmentIdentifier\n }, options);\n};\n\nexports.exclude = function (input, filter, options) {\n var exclusionFilter = Array.isArray(filter) ? function (key) {\n return !filter.includes(key);\n } : function (key, value) {\n return !filter(key, value);\n };\n return exports.pick(input, exclusionFilter, options);\n};","'use strict';\n\nmodule.exports = function (str) {\n return encodeURIComponent(str).replace(/[!'()*]/g, function (x) {\n return \"%\".concat(x.charCodeAt(0).toString(16).toUpperCase());\n });\n};","'use strict';\n\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }, _typeof(obj); }\n\nvar token = '%[a-f0-9]{2}';\nvar singleMatcher = new RegExp(token, 'gi');\nvar multiMatcher = new RegExp('(' + token + ')+', 'gi');\n\nfunction decodeComponents(components, split) {\n try {\n // Try to decode the entire string first\n return decodeURIComponent(components.join(''));\n } catch (err) {// Do nothing\n }\n\n if (components.length === 1) {\n return components;\n }\n\n split = split || 1; // Split the array in 2 parts\n\n var left = components.slice(0, split);\n var right = components.slice(split);\n return Array.prototype.concat.call([], decodeComponents(left), decodeComponents(right));\n}\n\nfunction decode(input) {\n try {\n return decodeURIComponent(input);\n } catch (err) {\n var tokens = input.match(singleMatcher);\n\n for (var i = 1; i < tokens.length; i++) {\n input = decodeComponents(tokens, i).join('');\n tokens = input.match(singleMatcher);\n }\n\n return input;\n }\n}\n\nfunction customDecodeURIComponent(input) {\n // Keep track of all the replacements and prefill the map with the `BOM`\n var replaceMap = {\n '%FE%FF': \"\\uFFFD\\uFFFD\",\n '%FF%FE': \"\\uFFFD\\uFFFD\"\n };\n var match = multiMatcher.exec(input);\n\n while (match) {\n try {\n // Decode as big chunks as possible\n replaceMap[match[0]] = decodeURIComponent(match[0]);\n } catch (err) {\n var result = decode(match[0]);\n\n if (result !== match[0]) {\n replaceMap[match[0]] = result;\n }\n }\n\n match = multiMatcher.exec(input);\n } // Add `%C2` at the end of the map to make sure it does not replace the combinator before everything else\n\n\n replaceMap['%C2'] = \"\\uFFFD\";\n var entries = Object.keys(replaceMap);\n\n for (var i = 0; i < entries.length; i++) {\n // Replace all decoded components\n var key = entries[i];\n input = input.replace(new RegExp(key, 'g'), replaceMap[key]);\n }\n\n return input;\n}\n\nmodule.exports = function (encodedURI) {\n if (typeof encodedURI !== 'string') {\n throw new TypeError('Expected `encodedURI` to be of type `string`, got `' + _typeof(encodedURI) + '`');\n }\n\n try {\n encodedURI = encodedURI.replace(/\\+/g, ' '); // Try the built in decoder first\n\n return decodeURIComponent(encodedURI);\n } catch (err) {\n // Fallback to a more advanced decoder\n return customDecodeURIComponent(encodedURI);\n }\n};","'use strict';\n\nmodule.exports = function (string, separator) {\n if (!(typeof string === 'string' && typeof separator === 'string')) {\n throw new TypeError('Expected the arguments to be of type `string`');\n }\n\n if (separator === '') {\n return [string];\n }\n\n var separatorIndex = string.indexOf(separator);\n\n if (separatorIndex === -1) {\n return [string];\n }\n\n return [string.slice(0, separatorIndex), string.slice(separatorIndex + separator.length)];\n};","'use strict';\n\nmodule.exports = function (obj, predicate) {\n var ret = {};\n var keys = Object.keys(obj);\n var isArr = Array.isArray(predicate);\n\n for (var i = 0; i < keys.length; i++) {\n var key = keys[i];\n var val = obj[key];\n\n if (isArr ? predicate.indexOf(key) !== -1 : predicate(key, val, obj)) {\n ret[key] = val;\n }\n }\n\n return ret;\n};","// Application wide JS\n\ndocument.addEventListener(\"turbolinks:load\", () =>\n $('[data-toggle=\"tooltip\"]').tooltip()\n);\n\n$(document).ready(() => {\n // Dropdowns\n $(\".os-dropdown-trigger\").on(\"mouseenter\", function () {\n $(this).addClass(\"over\");\n });\n $(\".os-dropdown-trigger\").on(\"mouseleave\", function () {\n $(this).removeClass(\"over\");\n });\n});\n","/* eslint-disable */\nimport React from \"react\";\nimport ReactDOM from \"react-dom\";\nimport SubscriptionUpdate from \"./subscription_update\";\n\nlet formSubmissionInProcess = false;\nconst stripeTokenHandler = function (token) {\n // Insert the token ID into the form so it gets submitted to the server\n const form = document.getElementById(\"payment_form\");\n const hiddenInput = document.createElement(\"input\");\n hiddenInput.setAttribute(\"type\", \"hidden\");\n hiddenInput.setAttribute(\"name\", \"stripeToken\");\n hiddenInput.setAttribute(\"value\", token.id);\n form.appendChild(hiddenInput);\n [\"brand\", \"exp_month\", \"exp_year\", \"last4\"].forEach((field) =>\n addFieldToPaymentForm(form, token, field)\n );\n // Submit the form\n document.getElementById(\"purchase_btn\").disabled = true;\n formSubmissionInProcess = false;\n return form.submit();\n};\n\nvar addFieldToPaymentForm = function (form, token, field) {\n const hiddenInput = document.createElement(\"input\");\n hiddenInput.setAttribute(\"type\", \"hidden\");\n hiddenInput.setAttribute(\"name\", `card_${field}`);\n hiddenInput.setAttribute(\"value\", token.card[field]);\n return form.appendChild(hiddenInput);\n};\n\n$(document).ready(() => {\n if (document.querySelector(\"#card-element\") !== null) {\n const public_key = AP.stripe_public_key;\n const stripe = Stripe(public_key);\n const elements = stripe.elements();\n // Custom styling can be passed to options when creating an Element.\n const style = {\n base: {\n fontSize: \"16px\",\n color: \"#32325d\",\n },\n };\n // Create an instance of the card Element\n const card = elements.create(\"card\", { style });\n // Add an instance of the card Element into the `card-element`
\n card.mount(\"#card-element\");\n card.addEventListener(\"change\", (event) => {\n const displayError = document.getElementById(\"card-errors\");\n if (event.error) {\n return (displayError.textContent = event.error.message);\n }\n return (displayError.textContent = \"\");\n });\n\n // Create a token or display an error when the form is submitted.\n const form = document.getElementById(\"payment_form\");\n form.addEventListener(\"submit\", (event) => {\n if (!formSubmissionInProcess) {\n formSubmissionInProcess = true;\n document.getElementById(\"purchase_btn\").disabled = true;\n event.preventDefault();\n return stripe.createToken(card).then((result) => {\n if (result.error) {\n // Inform the customer that there was an error\n const errorElement = document.getElementById(\"card-errors\");\n formSubmissionInProcess = false;\n document.getElementById(\"purchase_btn\").disabled = false;\n return (errorElement.textContent = result.error.message);\n }\n // Send the token to your server\n return stripeTokenHandler(result.token);\n });\n }\n });\n }\n\n if (document.getElementById(\"subscription-upgrade\")) {\n ReactDOM.render(\n ,\n document.getElementById(\"subscription-upgrade\")\n );\n }\n\n if (document.getElementById(\"subscription-upgrade-switch\")) {\n ReactDOM.render(\n ,\n document.getElementById(\"subscription-upgrade-switch\")\n );\n }\n\n // confirmation for cancellation\n $(\".btn-cancel-account\").click((e) => {\n if (!window.confirm(\"Are you sure you want to cancel your account?\")) {\n e.preventDefault();\n e.stopPropagation();\n }\n });\n});\n","// Fallback locale.\n// (when not a single one of the supplied \"preferred\" locales is available)\nvar defaultLocale = 'en'; // For all locales added\n// their relative time formatter messages will be stored here.\n\nvar localesData = {}; // According to the spec BCP 47 language tags are case-insensitive.\n// https://tools.ietf.org/html/rfc5646\n\nvar lowercaseLocaleLookup = {};\nexport function getDefaultLocale() {\n return defaultLocale;\n}\nexport function setDefaultLocale(locale) {\n defaultLocale = locale;\n}\n/**\r\n * Gets locale data previously added by `addLocaleData()`.\r\n * @return {object} [localeData]\r\n */\n\nexport function getLocaleData(locale) {\n return localesData[locale];\n}\n/**\r\n * Adds locale data.\r\n * Is called by `RelativeTimeFormat.addLocale(...)`.\r\n * @param {object} localeData\r\n */\n\nexport function addLocaleData(localeData) {\n if (!localeData) {\n throw new Error('No locale data passed');\n } // This locale data is stored in a global variable\n // and later used when calling `.format(time)`.\n\n\n localesData[localeData.locale] = localeData;\n lowercaseLocaleLookup[localeData.locale.toLowerCase()] = localeData.locale;\n}\n/**\r\n * Returns a locale for which locale data has been added\r\n * via `RelativeTimeFormat.addLocale(...)`.\r\n * @param {string} locale\r\n * @return {string} [locale]\r\n */\n\nexport function resolveLocale(locale) {\n if (localesData[locale]) {\n return locale;\n }\n\n if (lowercaseLocaleLookup[locale.toLowerCase()]) {\n return lowercaseLocaleLookup[locale.toLowerCase()];\n }\n}","import { resolveLocale as resolveLocaleForData } from './LocaleDataStore';\n/**\r\n * Resolves a locale to a supported one (if any).\r\n * @param {string} locale\r\n * @param {Object} [options] - An object that may have the following property:\r\n * @param {string} [options.localeMatcher=\"lookup\"] - The locale matching algorithm to use. Possible values are \"lookup\" and \"best fit\". Currently only \"lookup\" is supported.\r\n * @return {string} [locale]\r\n * @example\r\n * // Returns \"sr\"\r\n * resolveLocale(\"sr-Cyrl-BA\")\r\n * // Returns `undefined`\r\n * resolveLocale(\"xx-Latn\")\r\n */\n\nexport default function resolveLocale(locale) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n var localeMatcher = options.localeMatcher || 'lookup';\n\n switch (localeMatcher) {\n case 'lookup':\n return resolveLocaleLookup(locale);\n // \"best fit\" locale matching is not supported.\n // https://github.com/catamphetamine/relative-time-format/issues/2\n\n case 'best fit':\n // return resolveLocaleBestFit(locale)\n return resolveLocaleLookup(locale);\n\n default:\n throw new RangeError(\"Invalid \\\"localeMatcher\\\" option: \".concat(localeMatcher));\n }\n}\n/**\r\n * Resolves a locale to a supported one (if any).\r\n * Starts from the most specific locale and gradually\r\n * falls back to less specific ones.\r\n * This is a basic implementation of the \"lookup\" algorithm.\r\n * https://tools.ietf.org/html/rfc4647#section-3.4\r\n * @param {string} locale\r\n * @return {string} [locale]\r\n * @example\r\n * // Returns \"sr\"\r\n * resolveLocaleLookup(\"sr-Cyrl-BA\")\r\n * // Returns `undefined`\r\n * resolveLocaleLookup(\"xx-Latn\")\r\n */\n\nexport function resolveLocaleLookup(locale) {\n var resolvedLocale = resolveLocaleForData(locale);\n\n if (resolvedLocale) {\n return resolvedLocale;\n } // `sr-Cyrl-BA` -> `sr-Cyrl` -> `sr`.\n\n\n var parts = locale.split('-');\n\n while (locale.length > 1) {\n parts.pop();\n locale = parts.join('-');\n\n var _resolvedLocale = resolveLocaleForData(locale);\n\n if (_resolvedLocale) {\n return _resolvedLocale;\n }\n }\n}","// (this file was autogenerated by `generate-locales`)\n// \"plural rules\" functions are not stored in locale JSON files because they're not strings.\n// This file isn't big — it's about 5 kilobytes in size (minified).\n// Alternatively, the pluralization rules for each locale could be stored\n// in their JSON files in a non-parsed form and later parsed via `make-plural` library.\n// But `make-plural` library itself is relatively big in size:\n// `make-plural.min.js` is about 6 kilobytes (https://unpkg.com/make-plural/).\n// So, it's more practical to bypass runtime `make-plural` pluralization rules compilation\n// and just include the already compiled pluarlization rules for all locales in the library code.\nvar $ = {\n af: function af(n) {\n return n == 1 ? 'one' : 'other';\n },\n am: function am(n) {\n return n >= 0 && n <= 1 ? 'one' : 'other';\n },\n ar: function ar(n) {\n var s = String(n).split('.'),\n t0 = Number(s[0]) == n,\n n100 = t0 && s[0].slice(-2);\n return n == 0 ? 'zero' : n == 1 ? 'one' : n == 2 ? 'two' : n100 >= 3 && n100 <= 10 ? 'few' : n100 >= 11 && n100 <= 99 ? 'many' : 'other';\n },\n ast: function ast(n) {\n var s = String(n).split('.'),\n v0 = !s[1];\n return n == 1 && v0 ? 'one' : 'other';\n },\n be: function be(n) {\n var s = String(n).split('.'),\n t0 = Number(s[0]) == n,\n n10 = t0 && s[0].slice(-1),\n n100 = t0 && s[0].slice(-2);\n return n10 == 1 && n100 != 11 ? 'one' : n10 >= 2 && n10 <= 4 && (n100 < 12 || n100 > 14) ? 'few' : t0 && n10 == 0 || n10 >= 5 && n10 <= 9 || n100 >= 11 && n100 <= 14 ? 'many' : 'other';\n },\n br: function br(n) {\n var s = String(n).split('.'),\n t0 = Number(s[0]) == n,\n n10 = t0 && s[0].slice(-1),\n n100 = t0 && s[0].slice(-2),\n n1000000 = t0 && s[0].slice(-6);\n return n10 == 1 && n100 != 11 && n100 != 71 && n100 != 91 ? 'one' : n10 == 2 && n100 != 12 && n100 != 72 && n100 != 92 ? 'two' : (n10 == 3 || n10 == 4 || n10 == 9) && (n100 < 10 || n100 > 19) && (n100 < 70 || n100 > 79) && (n100 < 90 || n100 > 99) ? 'few' : n != 0 && t0 && n1000000 == 0 ? 'many' : 'other';\n },\n bs: function bs(n) {\n var s = String(n).split('.'),\n i = s[0],\n f = s[1] || '',\n v0 = !s[1],\n i10 = i.slice(-1),\n i100 = i.slice(-2),\n f10 = f.slice(-1),\n f100 = f.slice(-2);\n return v0 && i10 == 1 && i100 != 11 || f10 == 1 && f100 != 11 ? 'one' : v0 && i10 >= 2 && i10 <= 4 && (i100 < 12 || i100 > 14) || f10 >= 2 && f10 <= 4 && (f100 < 12 || f100 > 14) ? 'few' : 'other';\n },\n ceb: function ceb(n) {\n var s = String(n).split('.'),\n i = s[0],\n f = s[1] || '',\n v0 = !s[1],\n i10 = i.slice(-1),\n f10 = f.slice(-1);\n return v0 && (i == 1 || i == 2 || i == 3) || v0 && i10 != 4 && i10 != 6 && i10 != 9 || !v0 && f10 != 4 && f10 != 6 && f10 != 9 ? 'one' : 'other';\n },\n cs: function cs(n) {\n var s = String(n).split('.'),\n i = s[0],\n v0 = !s[1];\n return n == 1 && v0 ? 'one' : i >= 2 && i <= 4 && v0 ? 'few' : !v0 ? 'many' : 'other';\n },\n cy: function cy(n) {\n return n == 0 ? 'zero' : n == 1 ? 'one' : n == 2 ? 'two' : n == 3 ? 'few' : n == 6 ? 'many' : 'other';\n },\n da: function da(n) {\n var s = String(n).split('.'),\n i = s[0],\n t0 = Number(s[0]) == n;\n return n == 1 || !t0 && (i == 0 || i == 1) ? 'one' : 'other';\n },\n dsb: function dsb(n) {\n var s = String(n).split('.'),\n i = s[0],\n f = s[1] || '',\n v0 = !s[1],\n i100 = i.slice(-2),\n f100 = f.slice(-2);\n return v0 && i100 == 1 || f100 == 1 ? 'one' : v0 && i100 == 2 || f100 == 2 ? 'two' : v0 && (i100 == 3 || i100 == 4) || f100 == 3 || f100 == 4 ? 'few' : 'other';\n },\n dz: function dz(n) {\n return 'other';\n },\n ff: function ff(n) {\n return n >= 0 && n < 2 ? 'one' : 'other';\n },\n fr: function fr(n) {\n var s = String(n).split('.'),\n i = s[0],\n v0 = !s[1],\n i1000000 = i.slice(-6);\n return n >= 0 && n < 2 ? 'one' : i != 0 && i1000000 == 0 && v0 ? 'many' : 'other';\n },\n ga: function ga(n) {\n var s = String(n).split('.'),\n t0 = Number(s[0]) == n;\n return n == 1 ? 'one' : n == 2 ? 'two' : t0 && n >= 3 && n <= 6 ? 'few' : t0 && n >= 7 && n <= 10 ? 'many' : 'other';\n },\n gd: function gd(n) {\n var s = String(n).split('.'),\n t0 = Number(s[0]) == n;\n return n == 1 || n == 11 ? 'one' : n == 2 || n == 12 ? 'two' : t0 && n >= 3 && n <= 10 || t0 && n >= 13 && n <= 19 ? 'few' : 'other';\n },\n he: function he(n) {\n var s = String(n).split('.'),\n i = s[0],\n v0 = !s[1],\n t0 = Number(s[0]) == n,\n n10 = t0 && s[0].slice(-1);\n return n == 1 && v0 ? 'one' : i == 2 && v0 ? 'two' : v0 && (n < 0 || n > 10) && t0 && n10 == 0 ? 'many' : 'other';\n },\n is: function is(n) {\n var s = String(n).split('.'),\n i = s[0],\n t0 = Number(s[0]) == n,\n i10 = i.slice(-1),\n i100 = i.slice(-2);\n return t0 && i10 == 1 && i100 != 11 || !t0 ? 'one' : 'other';\n },\n ksh: function ksh(n) {\n return n == 0 ? 'zero' : n == 1 ? 'one' : 'other';\n },\n lt: function lt(n) {\n var s = String(n).split('.'),\n f = s[1] || '',\n t0 = Number(s[0]) == n,\n n10 = t0 && s[0].slice(-1),\n n100 = t0 && s[0].slice(-2);\n return n10 == 1 && (n100 < 11 || n100 > 19) ? 'one' : n10 >= 2 && n10 <= 9 && (n100 < 11 || n100 > 19) ? 'few' : f != 0 ? 'many' : 'other';\n },\n lv: function lv(n) {\n var s = String(n).split('.'),\n f = s[1] || '',\n v = f.length,\n t0 = Number(s[0]) == n,\n n10 = t0 && s[0].slice(-1),\n n100 = t0 && s[0].slice(-2),\n f100 = f.slice(-2),\n f10 = f.slice(-1);\n return t0 && n10 == 0 || n100 >= 11 && n100 <= 19 || v == 2 && f100 >= 11 && f100 <= 19 ? 'zero' : n10 == 1 && n100 != 11 || v == 2 && f10 == 1 && f100 != 11 || v != 2 && f10 == 1 ? 'one' : 'other';\n },\n mk: function mk(n) {\n var s = String(n).split('.'),\n i = s[0],\n f = s[1] || '',\n v0 = !s[1],\n i10 = i.slice(-1),\n i100 = i.slice(-2),\n f10 = f.slice(-1),\n f100 = f.slice(-2);\n return v0 && i10 == 1 && i100 != 11 || f10 == 1 && f100 != 11 ? 'one' : 'other';\n },\n mt: function mt(n) {\n var s = String(n).split('.'),\n t0 = Number(s[0]) == n,\n n100 = t0 && s[0].slice(-2);\n return n == 1 ? 'one' : n == 0 || n100 >= 2 && n100 <= 10 ? 'few' : n100 >= 11 && n100 <= 19 ? 'many' : 'other';\n },\n pa: function pa(n) {\n return n == 0 || n == 1 ? 'one' : 'other';\n },\n pl: function pl(n) {\n var s = String(n).split('.'),\n i = s[0],\n v0 = !s[1],\n i10 = i.slice(-1),\n i100 = i.slice(-2);\n return n == 1 && v0 ? 'one' : v0 && i10 >= 2 && i10 <= 4 && (i100 < 12 || i100 > 14) ? 'few' : v0 && i != 1 && (i10 == 0 || i10 == 1) || v0 && i10 >= 5 && i10 <= 9 || v0 && i100 >= 12 && i100 <= 14 ? 'many' : 'other';\n },\n pt: function pt(n) {\n var s = String(n).split('.'),\n i = s[0];\n return i == 0 || i == 1 ? 'one' : 'other';\n },\n ro: function ro(n) {\n var s = String(n).split('.'),\n v0 = !s[1],\n t0 = Number(s[0]) == n,\n n100 = t0 && s[0].slice(-2);\n return n == 1 && v0 ? 'one' : !v0 || n == 0 || n100 >= 2 && n100 <= 19 ? 'few' : 'other';\n },\n ru: function ru(n) {\n var s = String(n).split('.'),\n i = s[0],\n v0 = !s[1],\n i10 = i.slice(-1),\n i100 = i.slice(-2);\n return v0 && i10 == 1 && i100 != 11 ? 'one' : v0 && i10 >= 2 && i10 <= 4 && (i100 < 12 || i100 > 14) ? 'few' : v0 && i10 == 0 || v0 && i10 >= 5 && i10 <= 9 || v0 && i100 >= 11 && i100 <= 14 ? 'many' : 'other';\n },\n se: function se(n) {\n return n == 1 ? 'one' : n == 2 ? 'two' : 'other';\n },\n si: function si(n) {\n var s = String(n).split('.'),\n i = s[0],\n f = s[1] || '';\n return n == 0 || n == 1 || i == 0 && f == 1 ? 'one' : 'other';\n },\n sl: function sl(n) {\n var s = String(n).split('.'),\n i = s[0],\n v0 = !s[1],\n i100 = i.slice(-2);\n return v0 && i100 == 1 ? 'one' : v0 && i100 == 2 ? 'two' : v0 && (i100 == 3 || i100 == 4) || !v0 ? 'few' : 'other';\n }\n};\n$.as = $.am;\n$.az = $.af;\n$.bg = $.af;\n$.bn = $.am;\n$.ca = $.ast;\n$.ce = $.af;\n$.chr = $.af;\n$.de = $.ast;\n$.ee = $.af;\n$.el = $.af;\n$.en = $.ast;\n$.es = $.af;\n$.et = $.ast;\n$.eu = $.af;\n$.fa = $.am;\n$.fi = $.ast;\n$.fil = $.ceb;\n$.fo = $.af;\n$.fur = $.af;\n$.fy = $.ast;\n$.gl = $.ast;\n$.gu = $.am;\n$.ha = $.af;\n$.hi = $.am;\n$.hr = $.bs;\n$.hsb = $.dsb;\n$.hu = $.af;\n$.hy = $.ff;\n$.ia = $.ast;\n$.id = $.dz;\n$.ig = $.dz;\n$.it = $.ast;\n$.ja = $.dz;\n$.jgo = $.af;\n$.jv = $.dz;\n$.ka = $.af;\n$.kea = $.dz;\n$.kk = $.af;\n$.kl = $.af;\n$.km = $.dz;\n$.kn = $.am;\n$.ko = $.dz;\n$.ku = $.af;\n$.ky = $.af;\n$.lb = $.af;\n$.lkt = $.dz;\n$.lo = $.dz;\n$.ml = $.af;\n$.mn = $.af;\n$.mr = $.af;\n$.ms = $.dz;\n$.my = $.dz;\n$.nb = $.af;\n$.ne = $.af;\n$.nl = $.ast;\n$.nn = $.af;\n$.no = $.af;\n$.or = $.af;\n$.pcm = $.am;\n$.ps = $.af;\n$.rm = $.af;\n$.sah = $.dz;\n$.sd = $.af;\n$.sk = $.cs;\n$.so = $.af;\n$.sq = $.af;\n$.sr = $.bs;\n$.su = $.dz;\n$.sv = $.ast;\n$.sw = $.ast;\n$.ta = $.af;\n$.te = $.af;\n$.th = $.dz;\n$.ti = $.pa;\n$.tk = $.af;\n$.to = $.dz;\n$.tr = $.af;\n$.ug = $.af;\n$.uk = $.ru;\n$.ur = $.ast;\n$.uz = $.af;\n$.vi = $.dz;\n$.wae = $.af;\n$.wo = $.dz;\n$.yi = $.ast;\n$.yo = $.dz;\n$.yue = $.dz;\n$.zh = $.dz;\n$.zu = $.am;\nexport default $;","/**\r\n * Returns a `locale` for which a function exists in `./PluralRuleFunctions.js`.\r\n * @param {string} locale\r\n * @return {string}\r\n * @example\r\n * getPluralRulesLocale(\"ru-RU-Cyrl\") // Returns \"ru\".\r\n */\nexport default function getPluralRulesLocale(locale) {\n // \"pt\" language is the only one having different pluralization rules\n // for the one (\"pt\") (Portuguese) locale and the other (\"pt-PT\") (European Portuguese).\n // http://www.unicode.org/cldr/charts/latest/supplemental/language_plural_rules.html\n // (see the entries for \"pt\" and \"pt_PT\" there)\n if (locale === 'pt-PT') {\n return locale;\n }\n\n return getLanguageFromLanguageTag(locale);\n}\n/**\r\n * Extracts language from an IETF BCP 47 language tag.\r\n * @param {string} languageTag - IETF BCP 47 language tag.\r\n * @return {string}\r\n * @example\r\n * // Returns \"he\"\r\n * getLanguageFromLanguageTag(\"he-IL-u-ca-hebrew-tz-jeruslm\")\r\n * // Returns \"ar\"\r\n * getLanguageFromLanguageTag(\"ar-u-nu-latn\")\r\n */\n\nvar LANGUAGE_REG_EXP = /^([a-z0-9]+)/i;\n\nfunction getLanguageFromLanguageTag(languageTag) {\n var match = languageTag.match(LANGUAGE_REG_EXP);\n\n if (!match) {\n throw new TypeError(\"Invalid locale: \".concat(languageTag));\n }\n\n return match[1];\n}","function _classCallCheck(instance, Constructor) {\n if (!(instance instanceof Constructor)) {\n throw new TypeError(\"Cannot call a class as a function\");\n }\n}\n\nfunction _defineProperties(target, props) {\n for (var i = 0; i < props.length; i++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if (\"value\" in descriptor) descriptor.writable = true;\n Object.defineProperty(target, descriptor.key, descriptor);\n }\n}\n\nfunction _createClass(Constructor, protoProps, staticProps) {\n if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n if (staticProps) _defineProperties(Constructor, staticProps);\n return Constructor;\n} // Importing `PluralRule` polyfill from a separate package\n// results in a bundle that is larger by 1kB for some reason.\n// export { default as default } from 'intl-plural-rules-polyfill/cardinal'\n\n\nimport PluralRuleFunctions from \"./PluralRuleFunctions\";\nimport getPluralRulesLocale from \"./getPluralRulesLocale\";\n/**\r\n * `Intl.PluralRules` polyfill.\r\n * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/PluralRules\r\n */\n\nvar PluralRules = /*#__PURE__*/function () {\n function PluralRules(locale, options) {\n _classCallCheck(this, PluralRules);\n\n var locales = PluralRules.supportedLocalesOf(locale);\n\n if (locales.length === 0) {\n throw new RangeError(\"Unsupported locale: \" + locale);\n }\n\n if (options && options.type !== \"cardinal\") {\n throw new RangeError(\"Only \\\"cardinal\\\" \\\"type\\\" is supported\");\n }\n\n this.$ = PluralRuleFunctions[getPluralRulesLocale(locales[0])];\n }\n\n _createClass(PluralRules, [{\n key: \"select\",\n value: function select(number) {\n return this.$(number);\n }\n }], [{\n key: \"supportedLocalesOf\",\n value: function supportedLocalesOf(locales) {\n if (typeof locales === \"string\") {\n locales = [locales];\n }\n\n return locales.filter(function (locale) {\n return PluralRuleFunctions[getPluralRulesLocale(locale)];\n });\n }\n }]);\n\n return PluralRules;\n}();\n\nexport { PluralRules as default };","function _typeof2(obj) { \"@babel/helpers - typeof\"; return _typeof2 = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }, _typeof2(obj); }\n\nfunction _typeof(obj) {\n if (typeof Symbol === \"function\" && _typeof2(Symbol.iterator) === \"symbol\") {\n _typeof = function _typeof(obj) {\n return _typeof2(obj);\n };\n } else {\n _typeof = function _typeof(obj) {\n return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : _typeof2(obj);\n };\n }\n\n return _typeof(obj);\n}\n\nfunction _objectSpread(target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i] != null ? arguments[i] : {};\n var ownKeys = Object.keys(source);\n\n if (typeof Object.getOwnPropertySymbols === 'function') {\n ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) {\n return Object.getOwnPropertyDescriptor(source, sym).enumerable;\n }));\n }\n\n ownKeys.forEach(function (key) {\n _defineProperty(target, key, source[key]);\n });\n }\n\n return target;\n}\n\nfunction _slicedToArray(arr, i) {\n return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest();\n}\n\nfunction _nonIterableRest() {\n throw new TypeError(\"Invalid attempt to destructure non-iterable instance\");\n}\n\nfunction _iterableToArrayLimit(arr, i) {\n var _arr = [];\n var _n = true;\n var _d = false;\n var _e = undefined;\n\n try {\n for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {\n _arr.push(_s.value);\n\n if (i && _arr.length === i) break;\n }\n } catch (err) {\n _d = true;\n _e = err;\n } finally {\n try {\n if (!_n && _i[\"return\"] != null) _i[\"return\"]();\n } finally {\n if (_d) throw _e;\n }\n }\n\n return _arr;\n}\n\nfunction _arrayWithHoles(arr) {\n if (Array.isArray(arr)) return arr;\n}\n\nfunction _classCallCheck(instance, Constructor) {\n if (!(instance instanceof Constructor)) {\n throw new TypeError(\"Cannot call a class as a function\");\n }\n}\n\nfunction _defineProperties(target, props) {\n for (var i = 0; i < props.length; i++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if (\"value\" in descriptor) descriptor.writable = true;\n Object.defineProperty(target, descriptor.key, descriptor);\n }\n}\n\nfunction _createClass(Constructor, protoProps, staticProps) {\n if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n if (staticProps) _defineProperties(Constructor, staticProps);\n return Constructor;\n}\n\nfunction _defineProperty(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n\n return obj;\n}\n\nimport { getDefaultLocale, setDefaultLocale, getLocaleData, addLocaleData } from './LocaleDataStore';\nimport resolveLocale from './resolveLocale';\nimport PluralRules from './PluralRules'; // Importing `PluralRule` polyfill from a separate package\n// results in a bundle that is larger by 1kB for some reason.\n// import PluralRules from 'intl-plural-rules-polyfill/cardinal'\n// Valid time units.\n\nexport var UNITS = [\"second\", \"minute\", \"hour\", \"day\", \"week\", \"month\", \"quarter\", \"year\"]; // Valid values for the `numeric` option.\n\nvar NUMERIC_VALUES = [\"auto\", \"always\"]; // Valid values for the `style` option.\n\nvar STYLE_VALUES = [\"long\", \"short\", \"narrow\"]; // Valid values for the `localeMatcher` option.\n\nvar LOCALE_MATCHER_VALUES = [\"lookup\", \"best fit\"];\n/**\r\n * Polyfill for `Intl.RelativeTimeFormat` proposal.\r\n * https://github.com/tc39/proposal-intl-relative-time\r\n * https://github.com/tc39/proposal-intl-relative-time/issues/55\r\n */\n\nvar RelativeTimeFormat = /*#__PURE__*/function () {\n /**\r\n * @param {(string|string[])} [locales] - Preferred locales (or locale).\r\n * @param {Object} [options] - Formatting options.\r\n * @param {string} [options.style=\"long\"] - One of: \"long\", \"short\", \"narrow\".\r\n * @param {string} [options.numeric=\"always\"] - (Version >= 2) One of: \"always\", \"auto\".\r\n * @param {string} [options.localeMatcher=\"lookup\"] - One of: \"lookup\", \"best fit\". Currently only \"lookup\" is supported.\r\n * @param {boolean} [options.styleFallback] - If \"style\" is missing from locale data then fall back to an existing one (for example, \"long\"). Is used in `javascript-time-ago`.\r\n */\n function RelativeTimeFormat() {\n var locales = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n\n _classCallCheck(this, RelativeTimeFormat);\n\n _defineProperty(this, \"numeric\", \"always\");\n\n _defineProperty(this, \"style\", \"long\");\n\n _defineProperty(this, \"localeMatcher\", \"lookup\");\n\n var numeric = options.numeric,\n style = options.style,\n styleFallback = options.styleFallback,\n localeMatcher = options.localeMatcher; // Set `numeric` option.\n\n if (numeric !== undefined) {\n if (NUMERIC_VALUES.indexOf(numeric) < 0) {\n throw new RangeError(\"Invalid \\\"numeric\\\" option: \".concat(numeric));\n }\n\n this.numeric = numeric;\n } // Set `style` option.\n\n\n if (style !== undefined) {\n if (STYLE_VALUES.indexOf(style) < 0 && !styleFallback) {\n throw new RangeError(\"Invalid \\\"style\\\" option: \".concat(style));\n }\n\n this.style = style;\n } // Set `localeMatcher` option.\n\n\n if (localeMatcher !== undefined) {\n if (LOCALE_MATCHER_VALUES.indexOf(localeMatcher) < 0) {\n throw new RangeError(\"Invalid \\\"localeMatcher\\\" option: \".concat(localeMatcher));\n }\n\n this.localeMatcher = localeMatcher;\n } // Set `locale`.\n // Convert `locales` to an array.\n\n\n if (typeof locales === 'string') {\n locales = [locales];\n } // Add default locale.\n\n\n locales.push(getDefaultLocale()); // Choose the most appropriate locale.\n\n this.locale = RelativeTimeFormat.supportedLocalesOf(locales, {\n localeMatcher: this.localeMatcher\n })[0];\n\n if (!this.locale) {\n throw new Error(\"No supported locale was found\");\n } // Construct an `Intl.PluralRules` instance (polyfill).\n\n\n if (PluralRules.supportedLocalesOf(this.locale).length > 0) {\n this.pluralRules = new PluralRules(this.locale);\n } else {\n console.warn(\"\\\"\".concat(this.locale, \"\\\" locale is not supported\"));\n } // Use `Intl.NumberFormat` for formatting numbers (when available).\n\n\n if (typeof Intl !== 'undefined' && Intl.NumberFormat) {\n this.numberFormat = new Intl.NumberFormat(this.locale);\n this.numberingSystem = this.numberFormat.resolvedOptions().numberingSystem;\n } else {\n this.numberingSystem = 'latn';\n }\n\n this.locale = resolveLocale(this.locale, {\n localeMatcher: this.localeMatcher\n }); // Fall back to another style if `style` is not supported for the `locale`.\n\n if (styleFallback) {\n var styles = Object.keys(getLocaleData(this.locale));\n\n var _arr = [this.style].concat(STYLE_VALUES, [styles[0]]);\n\n for (var _i = 0; _i < _arr.length; _i++) {\n var _style = _arr[_i];\n\n if (styles.indexOf(_style) >= 0) {\n this.style = _style;\n break;\n }\n }\n }\n }\n /**\r\n * Formats time `number` in `units` (either in past or in future).\r\n * @param {number} number - Time interval value.\r\n * @param {string} unit - Time interval measurement unit.\r\n * @return {string}\r\n * @throws {RangeError} If unit is not one of \"second\", \"minute\", \"hour\", \"day\", \"week\", \"month\", \"quarter\".\r\n * @example\r\n * // Returns \"2 days ago\"\r\n * rtf.format(-2, \"day\")\r\n * // Returns \"in 5 minutes\"\r\n * rtf.format(5, \"minute\")\r\n */\n\n\n _createClass(RelativeTimeFormat, [{\n key: \"format\",\n value: function format() {\n var _parseFormatArgs = parseFormatArgs(arguments),\n _parseFormatArgs2 = _slicedToArray(_parseFormatArgs, 2),\n number = _parseFormatArgs2[0],\n unit = _parseFormatArgs2[1];\n\n return this.getRule(number, unit).replace('{0}', this.formatNumber(Math.abs(number)));\n }\n /**\r\n * Formats time `number` in `units` (either in past or in future).\r\n * @param {number} number - Time interval value.\r\n * @param {string} unit - Time interval measurement unit.\r\n * @return {Object[]} The parts (`{ type, value, unit? }`).\r\n * @throws {RangeError} If unit is not one of \"second\", \"minute\", \"hour\", \"day\", \"week\", \"month\", \"quarter\".\r\n * @example\r\n * // Version 1 (deprecated).\r\n * // Returns [\r\n * // { type: \"literal\", value: \"in \" },\r\n * // { type: \"day\", value: \"100\" },\r\n * // { type: \"literal\", value: \" days\" }\r\n * // ]\r\n * rtf.formatToParts(100, \"day\")\r\n * //\r\n * // Version 2.\r\n * // Returns [\r\n * // { type: \"literal\", value: \"in \" },\r\n * // { type: \"integer\", value: \"100\", unit: \"day\" },\r\n * // { type: \"literal\", value: \" days\" }\r\n * // ]\r\n * rtf.formatToParts(100, \"day\")\r\n */\n\n }, {\n key: \"formatToParts\",\n value: function formatToParts() {\n var _parseFormatArgs3 = parseFormatArgs(arguments),\n _parseFormatArgs4 = _slicedToArray(_parseFormatArgs3, 2),\n number = _parseFormatArgs4[0],\n unit = _parseFormatArgs4[1];\n\n var rule = this.getRule(number, unit);\n var valueIndex = rule.indexOf(\"{0}\"); // \"yesterday\"/\"today\"/\"tomorrow\".\n\n if (valueIndex < 0) {\n return [{\n type: \"literal\",\n value: rule\n }];\n }\n\n var parts = [];\n\n if (valueIndex > 0) {\n parts.push({\n type: \"literal\",\n value: rule.slice(0, valueIndex)\n });\n }\n\n parts = parts.concat(this.formatNumberToParts(Math.abs(number)).map(function (part) {\n return _objectSpread({}, part, {\n unit: unit\n });\n }));\n\n if (valueIndex + \"{0}\".length < rule.length - 1) {\n parts.push({\n type: \"literal\",\n value: rule.slice(valueIndex + \"{0}\".length)\n });\n }\n\n return parts;\n }\n /**\r\n * Returns formatting rule for `value` in `units` (either in past or in future).\r\n * @param {number} value - Time interval value.\r\n * @param {string} unit - Time interval measurement unit.\r\n * @return {string}\r\n * @throws {RangeError} If unit is not one of \"second\", \"minute\", \"hour\", \"day\", \"week\", \"month\", \"quarter\".\r\n * @example\r\n * // Returns \"{0} days ago\"\r\n * getRule(-2, \"day\")\r\n */\n\n }, {\n key: \"getRule\",\n value: function getRule(value, unit) {\n // Get locale-specific time interval formatting rules\n // of a given `style` for the given value of measurement `unit`.\n //\n // E.g.:\n //\n // ```json\n // {\n // \"past\": {\n // \"one\": \"a second ago\",\n // \"other\": \"{0} seconds ago\"\n // },\n // \"future\": {\n // \"one\": \"in a second\",\n // \"other\": \"in {0} seconds\"\n // }\n // }\n // ```\n //\n var unitMessages = getLocaleData(this.locale)[this.style][unit]; // Bundle size optimization technique for styles like\n // \"tiny\" in `javascript-time-ago`: \"1m\", \"2h\", \"3d\"...\n\n if (typeof unitMessages === 'string') {\n return unitMessages;\n } // Special case for \"yesterday\"/\"today\"/\"tomorrow\".\n\n\n if (this.numeric === \"auto\") {\n // \"yesterday\", \"the day before yesterday\", etc.\n if (value === -2 || value === -1) {\n var message = unitMessages[\"previous\".concat(value === -1 ? '' : '-' + Math.abs(value))];\n\n if (message) {\n return message;\n }\n } // \"tomorrow\", \"the day after tomorrow\", etc.\n else if (value === 1 || value === 2) {\n var _message = unitMessages[\"next\".concat(value === 1 ? '' : '-' + Math.abs(value))];\n\n if (_message) {\n return _message;\n }\n } // \"today\"\n else if (value === 0) {\n if (unitMessages.current) {\n return unitMessages.current;\n }\n }\n } // Choose either \"past\" or \"future\" based on time `value` sign.\n // If there's only \"other\" then it's being collapsed.\n // (the resulting bundle size optimization technique)\n\n\n var pluralizedMessages = unitMessages[isNegative(value) ? \"past\" : \"future\"]; // Bundle size optimization technique for styles like \"narrow\"\n // having messages like \"in {0} d.\" or \"{0} d. ago\".\n\n if (typeof pluralizedMessages === \"string\") {\n return pluralizedMessages;\n } // Quantify `value`.\n // There seems to be no such locale in CLDR\n // for which \"plural rules\" function is missing.\n\n\n var quantifier = this.pluralRules && this.pluralRules.select(Math.abs(value)) || 'other'; // \"other\" rule is supposed to be always present.\n // If only \"other\" rule is present then \"rules\" is not an object and is a string.\n\n return pluralizedMessages[quantifier] || pluralizedMessages.other;\n }\n /**\r\n * Formats a number into a string.\r\n * Uses `Intl.NumberFormat` when available.\r\n * @param {number} number\r\n * @return {string}\r\n */\n\n }, {\n key: \"formatNumber\",\n value: function formatNumber(number) {\n return this.numberFormat ? this.numberFormat.format(number) : String(number);\n }\n /**\r\n * Formats a number into a list of parts.\r\n * Uses `Intl.NumberFormat` when available.\r\n * @param {number} number\r\n * @return {object[]}\r\n */\n\n }, {\n key: \"formatNumberToParts\",\n value: function formatNumberToParts(number) {\n // `Intl.NumberFormat.formatToParts()` is not present, for example,\n // in Node.js 8.x while `Intl.NumberFormat` itself is present.\n return this.numberFormat && this.numberFormat.formatToParts ? this.numberFormat.formatToParts(number) : [{\n type: \"integer\",\n value: this.formatNumber(number)\n }];\n }\n /**\r\n * Returns a new object with properties reflecting the locale and date and time formatting options computed during initialization of this DateTimeFormat object.\r\n * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat/resolvedOptions\r\n * @return {Object}\r\n */\n\n }, {\n key: \"resolvedOptions\",\n value: function resolvedOptions() {\n return {\n locale: this.locale,\n style: this.style,\n numeric: this.numeric,\n numberingSystem: this.numberingSystem\n };\n }\n }]);\n\n return RelativeTimeFormat;\n}();\n/**\r\n * Returns an array containing those of the provided locales\r\n * that are supported in collation without having to fall back\r\n * to the runtime's default locale.\r\n * @param {(string|string[])} locale - A string with a BCP 47 language tag, or an array of such strings. For the general form of the locales argument, see the Intl page.\r\n * @param {Object} [options] - An object that may have the following property:\r\n * @param {string} [options.localeMatcher=\"lookup\"] - The locale matching algorithm to use. Possible values are \"lookup\" and \"best fit\". Currently only \"lookup\" is supported.\r\n * @return {string[]} An array of strings representing a subset of the given locale tags that are supported in collation without having to fall back to the runtime's default locale.\r\n * @example\r\n * var locales = ['ban', 'id-u-co-pinyin', 'es-PY']\r\n * var options = { localeMatcher: 'lookup' }\r\n * // Returns [\"id\", \"es-PY\"]\r\n * Intl.RelativeTimeFormat.supportedLocalesOf(locales, options)\r\n */\n\n\nexport { RelativeTimeFormat as default };\n\nRelativeTimeFormat.supportedLocalesOf = function (locales) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; // Convert `locales` to an array.\n\n if (typeof locales === 'string') {\n locales = [locales];\n } else if (!Array.isArray(locales)) {\n throw new TypeError('Invalid \"locales\" argument');\n }\n\n return locales.filter(function (locale) {\n return resolveLocale(locale, options);\n });\n};\n/**\r\n * Adds locale data for a specific locale.\r\n * @param {Object} localeData\r\n */\n\n\nRelativeTimeFormat.addLocale = addLocaleData;\n/**\r\n * Sets default locale.\r\n * @param {string} locale\r\n */\n\nRelativeTimeFormat.setDefaultLocale = setDefaultLocale;\n/**\r\n * Gets default locale.\r\n * @return {string} locale\r\n */\n\nRelativeTimeFormat.getDefaultLocale = getDefaultLocale;\n/**\r\n * Export `Intl.PluralRules` just in case it's used somewhere else.\r\n */\n\nRelativeTimeFormat.PluralRules = PluralRules; // The specification allows units to be in plural form.\n// Convert plural to singular.\n// Example: \"seconds\" -> \"second\".\n\nvar UNIT_ERROR = 'Invalid \"unit\" argument';\n\nfunction parseUnit(unit) {\n if (_typeof(unit) === 'symbol') {\n throw new TypeError(UNIT_ERROR);\n }\n\n if (typeof unit !== 'string') {\n throw new RangeError(\"\".concat(UNIT_ERROR, \": \").concat(unit));\n }\n\n if (unit[unit.length - 1] === 's') {\n unit = unit.slice(0, unit.length - 1);\n }\n\n if (UNITS.indexOf(unit) < 0) {\n throw new RangeError(\"\".concat(UNIT_ERROR, \": \").concat(unit));\n }\n\n return unit;\n} // Converts `value` to a `Number`.\n// The specification allows value to be a non-number.\n// For example, \"-0\" is supposed to be treated as `-0`.\n// Also checks if `value` is a finite number.\n\n\nvar NUMBER_ERROR = 'Invalid \"number\" argument';\n\nfunction parseNumber(value) {\n value = Number(value);\n\n if (Number.isFinite) {\n if (!Number.isFinite(value)) {\n throw new RangeError(\"\".concat(NUMBER_ERROR, \": \").concat(value));\n }\n }\n\n return value;\n}\n/**\r\n * Tells `0` from `-0`.\r\n * https://stackoverflow.com/questions/7223359/are-0-and-0-the-same\r\n * @param {number} number\r\n * @return {Boolean}\r\n * @example\r\n * isNegativeZero(0); // false\r\n * isNegativeZero(-0); // true\r\n */\n\n\nfunction isNegativeZero(number) {\n return 1 / number === -Infinity;\n}\n\nfunction isNegative(number) {\n return number < 0 || number === 0 && isNegativeZero(number);\n}\n\nfunction parseFormatArgs(args) {\n if (args.length < 2) {\n throw new TypeError(\"\\\"unit\\\" argument is required\");\n }\n\n return [parseNumber(args[0]), parseUnit(args[1])];\n}","function _typeof2(obj) { \"@babel/helpers - typeof\"; return _typeof2 = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }, _typeof2(obj); }\n\nfunction _typeof(obj) {\n if (typeof Symbol === \"function\" && _typeof2(Symbol.iterator) === \"symbol\") {\n _typeof = function _typeof(obj) {\n return _typeof2(obj);\n };\n } else {\n _typeof = function _typeof(obj) {\n return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : _typeof2(obj);\n };\n }\n\n return _typeof(obj);\n}\n\nfunction _classCallCheck(instance, Constructor) {\n if (!(instance instanceof Constructor)) {\n throw new TypeError(\"Cannot call a class as a function\");\n }\n}\n\nfunction _defineProperties(target, props) {\n for (var i = 0; i < props.length; i++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if (\"value\" in descriptor) descriptor.writable = true;\n Object.defineProperty(target, descriptor.key, descriptor);\n }\n}\n\nfunction _createClass(Constructor, protoProps, staticProps) {\n if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n if (staticProps) _defineProperties(Constructor, staticProps);\n return Constructor;\n}\n\nfunction _defineProperty(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n\n return obj;\n}\n/**\r\n * A basic in-memory cache.\r\n *\r\n * import Cache from 'javascript-time-ago/Cache'\r\n * const cache = new Cache()\r\n * const object = cache.get('key1', 'key2', ...) || cache.put('key1', 'key2', ..., createObject())\r\n */\n\n\nvar Cache = /*#__PURE__*/function () {\n function Cache() {\n _classCallCheck(this, Cache);\n\n _defineProperty(this, \"cache\", {});\n }\n\n _createClass(Cache, [{\n key: \"get\",\n value: function get() {\n var cache = this.cache;\n\n for (var _len = arguments.length, keys = new Array(_len), _key = 0; _key < _len; _key++) {\n keys[_key] = arguments[_key];\n }\n\n for (var _i = 0; _i < keys.length; _i++) {\n var key = keys[_i];\n\n if (_typeof(cache) !== 'object') {\n return;\n }\n\n cache = cache[key];\n }\n\n return cache;\n }\n }, {\n key: \"put\",\n value: function put() {\n for (var _len2 = arguments.length, keys = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {\n keys[_key2] = arguments[_key2];\n }\n\n var value = keys.pop();\n var lastKey = keys.pop();\n var cache = this.cache;\n\n for (var _i2 = 0; _i2 < keys.length; _i2++) {\n var key = keys[_i2];\n\n if (_typeof(cache[key]) !== 'object') {\n cache[key] = {};\n }\n\n cache = cache[key];\n }\n\n return cache[lastKey] = value;\n }\n }]);\n\n return Cache;\n}();\n\nexport { Cache as default };","function _typeof2(obj) { \"@babel/helpers - typeof\"; return _typeof2 = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }, _typeof2(obj); }\n\nfunction _typeof(obj) {\n if (typeof Symbol === \"function\" && _typeof2(Symbol.iterator) === \"symbol\") {\n _typeof = function _typeof(obj) {\n return _typeof2(obj);\n };\n } else {\n _typeof = function _typeof(obj) {\n return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : _typeof2(obj);\n };\n }\n\n return _typeof(obj);\n}\n/**\r\n * Chooses the most appropriate locale\r\n * (one of the registered ones)\r\n * based on the list of preferred `locales` supplied by the user.\r\n *\r\n * @param {string[]} locales - the list of preferable locales (in [IETF format](https://en.wikipedia.org/wiki/IETF_language_tag)).\r\n * @param {Function} isLocaleDataAvailable - tests if a locale is available.\r\n *\r\n * @returns {string} The most suitable locale.\r\n *\r\n * @example\r\n * // Returns 'en'\r\n * chooseLocale(['en-US'], undefined, (locale) => locale === 'ru' || locale === 'en')\r\n */\n\n\nexport default function chooseLocale(locales, isLocaleDataAvailable) {\n // This is not an intelligent algorithm,\n // but it will do for this library's case.\n // `sr-Cyrl-BA` -> `sr-Cyrl` -> `sr`.\n for (var _iterator = locales, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {\n var _ref;\n\n if (_isArray) {\n if (_i >= _iterator.length) break;\n _ref = _iterator[_i++];\n } else {\n _i = _iterator.next();\n if (_i.done) break;\n _ref = _i.value;\n }\n\n var locale = _ref;\n\n if (isLocaleDataAvailable(locale)) {\n return locale;\n }\n\n var parts = locale.split('-');\n\n while (parts.length > 1) {\n parts.pop();\n locale = parts.join('-');\n\n if (isLocaleDataAvailable(locale)) {\n return locale;\n }\n }\n }\n\n throw new Error(\"No locale data has been registered for any of the locales: \".concat(locales.join(', ')));\n}\n/**\r\n * Whether can use `Intl.DateTimeFormat` for these `locales`.\r\n * Returns the first suitable one.\r\n * @param {(string|string[])} locales\r\n * @return {?string} The first locale that can be used.\r\n */\n\nexport function intlDateTimeFormatSupportedLocale(locales) {\n /* istanbul ignore else */\n if (intlDateTimeFormatSupported()) {\n return Intl.DateTimeFormat.supportedLocalesOf(locales)[0];\n }\n}\n/**\r\n * Whether can use `Intl.DateTimeFormat`.\r\n * @return {boolean}\r\n */\n\nexport function intlDateTimeFormatSupported() {\n // Babel transforms `typeof` into some \"branches\"\n // so istanbul will show this as \"branch not covered\".\n\n /* istanbul ignore next */\n var isIntlAvailable = (typeof Intl === \"undefined\" ? \"undefined\" : _typeof(Intl)) === 'object';\n return isIntlAvailable && typeof Intl.DateTimeFormat === 'function';\n}","export var minute = 60; // in seconds\n\nexport var hour = 60 * minute; // in seconds\n\nexport var day = 24 * hour; // in seconds\n\nexport var week = 7 * day; // in seconds\n// https://www.quora.com/What-is-the-average-number-of-days-in-a-month\n\nexport var month = 30.44 * day; // in seconds\n// \"400 years have 146097 days (taking into account leap year rules)\"\n\nexport var year = 146097 / 400 * day; // in seconds\n\nexport function getSecondsInUnit(unit) {\n switch (unit) {\n case 'second':\n return 1;\n\n case 'minute':\n return minute;\n\n case 'hour':\n return hour;\n\n case 'day':\n return day;\n\n case 'week':\n return week;\n\n case 'month':\n return month;\n\n case 'year':\n return year;\n }\n} // export function getPreviousUnitFor(unit) {\n// \tswitch (unit) {\n// \t\tcase 'second':\n// \t\t\treturn 'now'\n// \t\tcase 'minute':\n// \t\t\treturn 'second'\n// \t\tcase 'hour':\n// \t\t\treturn 'minute'\n// \t\tcase 'day':\n// \t\t\treturn 'hour'\n// \t\tcase 'week':\n// \t\t\treturn 'day'\n// \t\tcase 'month':\n// \t\t\treturn 'week'\n// \t\tcase 'year':\n// \t\t\treturn 'month'\n// \t}\n// }","import { getSecondsInUnit } from './units';\nexport default function getStepDenominator(step) {\n // `factor` is a legacy property.\n if (step.factor !== undefined) {\n return step.factor;\n } // \"unit\" is now called \"formatAs\".\n\n\n return getSecondsInUnit(step.unit || step.formatAs) || 1;\n}","export function getRoundFunction(round) {\n switch (round) {\n case 'floor':\n return Math.floor;\n\n default:\n return Math.round;\n }\n} // For non-negative numbers.\n\nexport function getDiffRatioToNextRoundedNumber(round) {\n switch (round) {\n case 'floor':\n // Math.floor(x) = x\n // Math.floor(x + 1) = x + 1\n return 1;\n\n default:\n // Math.round(x) = x\n // Math.round(x + 0.5) = x + 1\n return 0.5;\n }\n}","function _typeof2(obj) { \"@babel/helpers - typeof\"; return _typeof2 = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }, _typeof2(obj); }\n\nfunction _typeof(obj) {\n if (typeof Symbol === \"function\" && _typeof2(Symbol.iterator) === \"symbol\") {\n _typeof = function _typeof(obj) {\n return _typeof2(obj);\n };\n } else {\n _typeof = function _typeof(obj) {\n return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : _typeof2(obj);\n };\n }\n\n return _typeof(obj);\n}\n\nimport { getSecondsInUnit } from './units';\nimport { getDiffRatioToNextRoundedNumber } from '../round';\nexport default function getStepMinTime(step, _ref) {\n var prevStep = _ref.prevStep,\n timestamp = _ref.timestamp,\n now = _ref.now,\n future = _ref.future,\n round = _ref.round;\n var minTime; // \"threshold_for_xxx\" is a legacy property.\n\n if (prevStep) {\n if (prevStep.id || prevStep.unit) {\n minTime = step[\"threshold_for_\".concat(prevStep.id || prevStep.unit)];\n }\n }\n\n if (minTime === undefined) {\n // \"threshold\" is a legacy property.\n if (step.threshold !== undefined) {\n // \"threshold\" is a legacy name for \"minTime\".\n minTime = step.threshold; // \"threshold\" function is deprecated.\n\n if (typeof minTime === 'function') {\n minTime = minTime(now, future);\n }\n }\n }\n\n if (minTime === undefined) {\n minTime = step.minTime;\n } // A deprecated way of specifying a different threshold\n // depending on the previous step's unit.\n\n\n if (_typeof(minTime) === 'object') {\n if (prevStep && prevStep.id && minTime[prevStep.id] !== undefined) {\n minTime = minTime[prevStep.id];\n } else {\n minTime = minTime[\"default\"];\n }\n }\n\n if (typeof minTime === 'function') {\n minTime = minTime(timestamp, {\n future: future,\n getMinTimeForUnit: function getMinTimeForUnit(toUnit, fromUnit) {\n return _getMinTimeForUnit(toUnit, fromUnit || prevStep && prevStep.formatAs, {\n round: round\n });\n }\n });\n } // Evaluate the `test()` function.\n // `test()` function is deprecated.\n\n\n if (minTime === undefined) {\n if (step.test) {\n if (step.test(timestamp, {\n now: now,\n future: future\n })) {\n // `0` threshold always passes.\n minTime = 0;\n } else {\n // `MAX_SAFE_INTEGER` threshold won't ever pass in real life.\n minTime = 9007199254740991; // Number.MAX_SAFE_INTEGER\n }\n }\n }\n\n if (minTime === undefined) {\n if (prevStep) {\n if (step.formatAs && prevStep.formatAs) {\n minTime = _getMinTimeForUnit(step.formatAs, prevStep.formatAs, {\n round: round\n });\n }\n } else {\n // The first step's `minTime` is `0` by default.\n minTime = 0;\n }\n } // Warn if no `minTime` was defined or could be deduced.\n\n\n if (minTime === undefined) {\n console.warn('[javascript-time-ago] A step should specify `minTime`:\\n' + JSON.stringify(step, null, 2));\n }\n\n return minTime;\n}\n\nfunction _getMinTimeForUnit(toUnit, fromUnit, _ref2) {\n var round = _ref2.round;\n var toUnitAmount = getSecondsInUnit(toUnit); // if (!fromUnit) {\n // \treturn toUnitAmount;\n // }\n // if (!fromUnit) {\n // \tfromUnit = getPreviousUnitFor(toUnit)\n // }\n\n var fromUnitAmount;\n\n if (fromUnit === 'now') {\n fromUnitAmount = getSecondsInUnit(toUnit);\n } else {\n fromUnitAmount = getSecondsInUnit(fromUnit);\n }\n\n if (toUnitAmount !== undefined && fromUnitAmount !== undefined) {\n return toUnitAmount - fromUnitAmount * (1 - getDiffRatioToNextRoundedNumber(round));\n }\n}","function _objectSpread(target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i] != null ? arguments[i] : {};\n var ownKeys = Object.keys(source);\n\n if (typeof Object.getOwnPropertySymbols === 'function') {\n ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) {\n return Object.getOwnPropertyDescriptor(source, sym).enumerable;\n }));\n }\n\n ownKeys.forEach(function (key) {\n _defineProperty(target, key, source[key]);\n });\n }\n\n return target;\n}\n\nfunction _defineProperty(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n\n return obj;\n}\n\nimport getStepDenominator from './getStepDenominator';\nimport getStepMinTime from './getStepMinTime';\nimport { getRoundFunction } from '../round';\n/**\r\n * Finds an appropriate `step` of `steps` for the time interval (in seconds).\r\n *\r\n * @param {Object[]} steps - Time formatting steps.\r\n *\r\n * @param {number} secondsPassed - Time interval (in seconds).\r\n * `< 0` for past dates and `> 0` for future dates.\r\n *\r\n * @param {number} options.now - Current timestamp.\r\n *\r\n * @param {boolean} [options.future] - Whether the date should be formatted as a future one\r\n * instead of a past one.\r\n *\r\n * @param {string} [options.round] - (undocumented) Rounding mechanism.\r\n *\r\n * @param {string[]} [options.units] - A list of allowed time units.\r\n * (Example: ['second', 'minute', 'hour', …])\r\n *\r\n * @param {boolean} [options.getNextStep] - Pass true to return `[step, nextStep]` instead of just `step`.\r\n *\r\n * @return {Object|Object[]} [step] — Either a `step` or `[prevStep, step, nextStep]`.\r\n */\n\nexport default function getStep(steps, secondsPassed, _ref) {\n var now = _ref.now,\n future = _ref.future,\n round = _ref.round,\n units = _ref.units,\n getNextStep = _ref.getNextStep; // Ignore steps having not-supported time units in `formatAs`.\n\n steps = filterStepsByUnits(steps, units);\n\n var step = _getStep(steps, secondsPassed, {\n now: now,\n future: future,\n round: round\n });\n\n if (getNextStep) {\n if (step) {\n var prevStep = steps[steps.indexOf(step) - 1];\n var nextStep = steps[steps.indexOf(step) + 1];\n return [prevStep, step, nextStep];\n }\n\n return [undefined, undefined, steps[0]];\n }\n\n return step;\n}\n\nfunction _getStep(steps, secondsPassed, _ref2) {\n var now = _ref2.now,\n future = _ref2.future,\n round = _ref2.round; // If no steps fit the conditions then return nothing.\n\n if (steps.length === 0) {\n return;\n } // Find the most appropriate step.\n\n\n var i = getStepIndex(steps, secondsPassed, {\n now: now,\n future: future || secondsPassed < 0,\n round: round\n }); // If no step is applicable the return nothing.\n\n if (i === -1) {\n return;\n }\n\n var step = steps[i]; // Apply granularity to the time amount\n // (and fall back to the previous step\n // if the first level of granularity\n // isn't met by this amount)\n\n if (step.granularity) {\n // Recalculate the amount of seconds passed based on `granularity`.\n var secondsPassedGranular = getRoundFunction(round)(Math.abs(secondsPassed) / getStepDenominator(step) / step.granularity) * step.granularity; // If the granularity for this step is too high,\n // then fall back to the previous step.\n // (if there is any previous step)\n\n if (secondsPassedGranular === 0 && i > 0) {\n return steps[i - 1];\n }\n }\n\n return step;\n}\n/**\r\n * Iterates through steps until it finds the maximum one satisfying the `minTime` threshold.\r\n * @param {Object} steps - Steps.\r\n * @param {number} secondsPassed - How much seconds have passed since the date till `now`.\r\n * @param {number} options.now - Current timestamp.\r\n * @param {boolean} options.future - Whether the time interval should be formatted as a future one.\r\n * @param {number} [i] - Gradation step currently being tested.\r\n * @return {number} Gradation step index.\r\n */\n\n\nfunction getStepIndex(steps, secondsPassed, options) {\n var i = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;\n var minTime = getStepMinTime(steps[i], _objectSpread({\n prevStep: steps[i - 1],\n timestamp: options.now - secondsPassed * 1000\n }, options)); // If `minTime` isn't defined or deduceable for this step, then stop.\n\n if (minTime === undefined) {\n return i - 1;\n } // If the `minTime` threshold for moving from previous step\n // to this step is too high then return the previous step.\n\n\n if (Math.abs(secondsPassed) < minTime) {\n return i - 1;\n } // If it's the last step then return it.\n\n\n if (i === steps.length - 1) {\n return i;\n } // Move to the next step.\n\n\n return getStepIndex(steps, secondsPassed, options, i + 1);\n}\n/**\r\n * Leaves only allowed steps.\r\n * @param {Object[]} steps\r\n * @param {string[]} units - Allowed time units.\r\n * @return {Object[]}\r\n */\n\n\nfunction filterStepsByUnits(steps, units) {\n return steps.filter(function (_ref3) {\n var unit = _ref3.unit,\n formatAs = _ref3.formatAs; // \"unit\" is now called \"formatAs\".\n\n unit = unit || formatAs; // If this step has a `unit` defined\n // then this `unit` must be in the list of allowed `units`.\n\n if (unit) {\n return units.indexOf(unit) >= 0;\n } // A step is not required to specify a `unit`:\n // alternatively, it could specify `format()`.\n // (see \"twitter\" style for an example)\n\n\n return true;\n });\n}","import { getSecondsInUnit } from './units';\nimport { getRoundFunction, getDiffRatioToNextRoundedNumber } from '../round';\n/**\r\n * Gets the time to next update for a step with a time unit defined.\r\n * @param {string} unit\r\n * @param {number} date — The date passed to `.format()`, converted to a timestamp.\r\n * @param {number} options.now\r\n * @param {string} [options.round] — (undocumented) Rounding mechanism.\r\n * @return {number} [timeToNextUpdate]\r\n */\n\nexport default function getTimeToNextUpdateForUnit(unit, timestamp, _ref) {\n var now = _ref.now,\n round = _ref.round; // For some units, like \"now\", there's no defined amount of seconds in them.\n\n if (!getSecondsInUnit(unit)) {\n // If there's no amount of seconds defined for this unit\n // then the update interval can't be determined reliably.\n return;\n }\n\n var unitDenominator = getSecondsInUnit(unit) * 1000;\n var future = timestamp > now;\n var preciseAmount = Math.abs(timestamp - now);\n var roundedAmount = getRoundFunction(round)(preciseAmount / unitDenominator) * unitDenominator;\n\n if (future) {\n if (roundedAmount > 0) {\n // Amount decreases with time.\n return preciseAmount - roundedAmount + getDiffToPreviousRoundedNumber(round, unitDenominator);\n } else {\n // Refresh right after the zero point,\n // when \"future\" changes to \"past\".\n return preciseAmount - roundedAmount + 1;\n }\n } // Amount increases with time.\n\n\n return -(preciseAmount - roundedAmount) + getDiffToNextRoundedNumber(round, unitDenominator);\n}\n\nfunction getDiffToNextRoundedNumber(round, unitDenominator) {\n return getDiffRatioToNextRoundedNumber(round) * unitDenominator;\n}\n\nfunction getDiffToPreviousRoundedNumber(round, unitDenominator) {\n return (1 - getDiffRatioToNextRoundedNumber(round)) * unitDenominator + 1;\n}","import _getTimeToNextUpdateForUnit from './getTimeToNextUpdateForUnit';\nimport getStepMinTime from './getStepMinTime';\nimport { getRoundFunction } from '../round'; // A thousand years is practically a metaphor for \"infinity\".\n\nvar YEAR = 365 * 24 * 60 * 60 * 1000;\nexport var INFINITY = 1000 * YEAR;\n/**\r\n * Gets the time to next update for a date and a step.\r\n * @param {number} date — The date passed to `.format()`, converted to a timestamp.\r\n * @param {object} step\r\n * @param {object} [options.previousStep]\r\n * @param {object} [options.nextStep]\r\n * @param {number} options.now\r\n * @param {boolean} options.future\r\n * @param {string} [options.round] - (undocumented) Rounding mechanism.\r\n * @return {number} [timeToNextUpdate]\r\n */\n\nexport default function getTimeToNextUpdate(date, step, _ref) {\n var prevStep = _ref.prevStep,\n nextStep = _ref.nextStep,\n now = _ref.now,\n future = _ref.future,\n round = _ref.round;\n var timestamp = date.getTime ? date.getTime() : date;\n\n var getTimeToNextUpdateForUnit = function getTimeToNextUpdateForUnit(unit) {\n return _getTimeToNextUpdateForUnit(unit, timestamp, {\n now: now,\n round: round\n });\n }; // For future dates, steps move from the last one to the first one,\n // while for past dates, steps move from the first one to the last one,\n // due to the fact that time flows in one direction,\n // and future dates' interval naturally becomes smaller\n // while past dates' interval naturally grows larger.\n //\n // For future dates, it's the transition\n // from the current step to the previous step,\n // therefore check the `minTime` of the current step.\n //\n // For past dates, it's the transition\n // from the current step to the next step,\n // therefore check the `minTime` of the next step.\n //\n\n\n var timeToStepChange = getTimeToStepChange(future ? step : nextStep, timestamp, {\n future: future,\n now: now,\n round: round,\n prevStep: future ? prevStep : step // isFirstStep: future && isFirstStep\n\n });\n\n if (timeToStepChange === undefined) {\n // Can't reliably determine \"time to next update\"\n // if not all of the steps provide `minTime`.\n return;\n }\n\n var timeToNextUpdate;\n\n if (step) {\n if (step.getTimeToNextUpdate) {\n timeToNextUpdate = step.getTimeToNextUpdate(timestamp, {\n getTimeToNextUpdateForUnit: getTimeToNextUpdateForUnit,\n getRoundFunction: getRoundFunction,\n now: now,\n future: future,\n round: round\n });\n }\n\n if (timeToNextUpdate === undefined) {\n // \"unit\" is now called \"formatAs\".\n var unit = step.unit || step.formatAs;\n\n if (unit) {\n // For some units, like \"now\", there's no defined amount of seconds in them.\n // In such cases, `getTimeToNextUpdateForUnit()` returns `undefined`,\n // and the next step's `minTime` could be used to calculate the update interval:\n // it will just assume that the label never changes for this step.\n timeToNextUpdate = getTimeToNextUpdateForUnit(unit);\n }\n }\n }\n\n if (timeToNextUpdate === undefined) {\n return timeToStepChange;\n }\n\n return Math.min(timeToNextUpdate, timeToStepChange);\n}\nexport function getStepChangesAt(currentOrNextStep, timestamp, _ref2) {\n var now = _ref2.now,\n future = _ref2.future,\n round = _ref2.round,\n prevStep = _ref2.prevStep; // The first step's `minTime` is `0` by default.\n // It doesn't \"change\" steps at zero point\n // but it does change the wording when switching\n // from \"future\" to \"past\": \"in ...\" -> \"... ago\".\n // Therefore, the label should be updated at zero-point too.\n\n var minTime = getStepMinTime(currentOrNextStep, {\n timestamp: timestamp,\n now: now,\n future: future,\n round: round,\n prevStep: prevStep\n });\n\n if (minTime === undefined) {\n return;\n }\n\n if (future) {\n // The step changes to the previous step\n // as soon as `timestamp - now` becomes\n // less than the `minTime` of the current step:\n // `timestamp - now === minTime - 1`\n // => `now === timestamp - minTime + 1`.\n return timestamp - minTime * 1000 + 1;\n } else {\n // The step changes to the next step\n // as soon as `now - timestamp` becomes\n // equal to `minTime` of the next step:\n // `now - timestamp === minTime`\n // => `now === timestamp + minTime`.\n // This is a special case when double-update could be skipped.\n if (minTime === 0 && timestamp === now) {\n return INFINITY;\n }\n\n return timestamp + minTime * 1000;\n }\n}\nexport function getTimeToStepChange(step, timestamp, _ref3) {\n var now = _ref3.now,\n future = _ref3.future,\n round = _ref3.round,\n prevStep = _ref3.prevStep;\n\n if (step) {\n var stepChangesAt = getStepChangesAt(step, timestamp, {\n now: now,\n future: future,\n round: round,\n prevStep: prevStep\n });\n\n if (stepChangesAt === undefined) {\n return;\n }\n\n return stepChangesAt - now;\n } else {\n if (future) {\n // No step.\n // Update right after zero point, when it changes from \"future\" to \"past\".\n return timestamp - now + 1;\n } else {\n // The last step doesn't ever change when `date` is in the past.\n return INFINITY;\n }\n }\n}","// For all locales added\n// their relative time formatter messages will be stored here.\nvar localesData = {};\nexport function getLocaleData(locale) {\n return localesData[locale];\n}\nexport function addLocaleData(localeData) {\n if (!localeData) {\n throw new Error('[javascript-time-ago] No locale data passed.');\n } // This locale data is stored in a global variable\n // and later used when calling `.format(time)`.\n\n\n localesData[localeData.locale] = localeData;\n}","// just now\n// 1 second ago\n// 2 seconds ago\n// …\n// 59 seconds ago\n// 1 minute ago\n// 2 minutes ago\n// …\n// 59 minutes ago\n// 1 hour ago\n// 2 hours ago\n// …\n// 24 hours ago\n// 1 day ago\n// 2 days ago\n// …\n// 6 days ago\n// 1 week ago\n// 2 weeks ago\n// …\n// 3 weeks ago\n// 1 month ago\n// 2 months ago\n// …\n// 11 months ago\n// 1 year ago\n// 2 years ago\n// …\nexport default [{\n formatAs: 'now'\n}, {\n formatAs: 'second'\n}, {\n formatAs: 'minute'\n}, {\n formatAs: 'hour'\n}, {\n formatAs: 'day'\n}, {\n formatAs: 'week'\n}, {\n formatAs: 'month'\n}, {\n formatAs: 'year'\n}];","import round from '../steps/round'; // just now\n// 1 second ago\n// 2 seconds ago\n// …\n// 59 seconds ago\n// 1 minute ago\n// 2 minutes ago\n// …\n// 59 minutes ago\n// 1 minute ago\n// 2 minutes ago\n// …\n// 59 minutes ago\n// 1 hour ago\n// 2 hours ago\n// …\n// 24 hours ago\n// 1 day ago\n// 2 days ago\n// …\n// 6 days ago\n// 1 week ago\n// 2 weeks ago\n// 3 weeks ago\n// 4 weeks ago\n// 1 month ago\n// 2 months ago\n// …\n// 11 months ago\n// 1 year ago\n// 2 years ago\n// …\n//\n\nexport default {\n steps: round,\n labels: 'long'\n};","function _objectSpread(target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i] != null ? arguments[i] : {};\n var ownKeys = Object.keys(source);\n\n if (typeof Object.getOwnPropertySymbols === 'function') {\n ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) {\n return Object.getOwnPropertyDescriptor(source, sym).enumerable;\n }));\n }\n\n ownKeys.forEach(function (key) {\n _defineProperty(target, key, source[key]);\n });\n }\n\n return target;\n}\n\nfunction _defineProperty(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n\n return obj;\n}\n\nimport round from './round'; // just now\n// 1 minute ago\n// 2 minutes ago\n// …\n// 59 minutes ago\n// 1 minute ago\n// 2 minutes ago\n// …\n// 59 minutes ago\n// 1 hour ago\n// 2 hours ago\n// …\n// 24 hours ago\n// 1 day ago\n// 2 days ago\n// …\n// 6 days ago\n// 1 week ago\n// 2 weeks ago\n// 3 weeks ago\n// 4 weeks ago\n// 1 month ago\n// 2 months ago\n// …\n// 11 months ago\n// 1 year ago\n// 2 years ago\n// …\n//\n\nexport default _objectSpread({}, round, {\n // Skip \"seconds\".\n steps: round.steps.filter(function (step) {\n return step.formatAs !== 'second';\n })\n});","import { minute, hour, day, week, month, year } from './units'; // \"factor\" is a legacy property.\n// Developers shouldn't need to use it in their custom steps.\n// \"threshold\" is a legacy name of \"min\".\n// Developers should use \"min\" property name instead of \"threshold\".\n// \"threshold_for_idOrUnit: value\" is a legacy way of specifying \"min: { id: value }\".\n// Developers should use \"min\" property instead of \"threshold\".\n// just now\n// 1 minute ago\n// 2 minutes ago\n// 5 minutes ago\n// 10 minutes ago\n// 15 minutes ago\n// 20 minutes ago\n// …\n// 50 minutes ago\n// an hour ago\n// 2 hours ago\n// …\n// 20 hours ago\n// a day ago\n// 2 days ago\n// 5 days ago\n// a week ago\n// 2 weeks ago\n// 3 weeks ago\n// a month ago\n// 2 months ago\n// 4 months ago\n// a year ago\n// 2 years ago\n// …\n\nexport default [{\n // This step returns the amount of seconds\n // by dividing the amount of seconds by `1`.\n factor: 1,\n // \"now\" labels are used for formatting the output.\n unit: 'now'\n}, {\n // When the language doesn't support `now` unit,\n // the first step is ignored, and it uses this `second` unit.\n threshold: 1,\n // `threshold_for_now` should be the same as `threshold` on minutes.\n threshold_for_now: 45.5,\n // This step returns the amount of seconds\n // by dividing the amount of seconds by `1`.\n factor: 1,\n // \"second\" labels are used for formatting the output.\n unit: 'second'\n}, {\n // `threshold` should be the same as `threshold_for_now` on seconds.\n threshold: 45.5,\n // Return the amount of minutes by dividing the amount\n // of seconds by the amount of seconds in a minute.\n factor: minute,\n // \"minute\" labels are used for formatting the output.\n unit: 'minute'\n}, {\n // This step is effective starting from 2.5 minutes.\n threshold: 2.5 * minute,\n // Allow only 5-minute increments of minutes starting from 2.5 minutes.\n // `granularity` — (advanced) Time interval value \"granularity\".\n // For example, it could be set to `5` for minutes to allow only 5-minute increments\n // when formatting time intervals: `0 minutes`, `5 minutes`, `10 minutes`, etc.\n // Perhaps this feature will be removed because there seem to be no use cases\n // of it in the real world.\n granularity: 5,\n // Return the amount of minutes by dividing the amount\n // of seconds by the amount of seconds in a minute.\n factor: minute,\n // \"minute\" labels are used for formatting the output.\n unit: 'minute'\n}, {\n // This step is effective starting from 22.5 minutes.\n threshold: 22.5 * minute,\n // Return the amount of minutes by dividing the amount\n // of seconds by the amount of seconds in half-an-hour.\n factor: 0.5 * hour,\n // \"half-hour\" labels are used for formatting the output.\n // (if available, which is no longer the case)\n unit: 'half-hour'\n}, {\n // This step is effective starting from 42.5 minutes.\n threshold: 42.5 * minute,\n threshold_for_minute: 52.5 * minute,\n // Return the amount of minutes by dividing the amount\n // of seconds by the amount of seconds in an hour.\n factor: hour,\n // \"hour\" labels are used for formatting the output.\n unit: 'hour'\n}, {\n // This step is effective starting from 20.5 hours.\n threshold: 20.5 / 24 * day,\n // Return the amount of minutes by dividing the amount\n // of seconds by the amount of seconds in a day.\n factor: day,\n // \"day\" labels are used for formatting the output.\n unit: 'day'\n}, {\n // This step is effective starting from 5.5 days.\n threshold: 5.5 * day,\n // Return the amount of minutes by dividing the amount\n // of seconds by the amount of seconds in a week.\n factor: week,\n // \"week\" labels are used for formatting the output.\n unit: 'week'\n}, {\n // This step is effective starting from 3.5 weeks.\n threshold: 3.5 * week,\n // Return the amount of minutes by dividing the amount\n // of seconds by the amount of seconds in a month.\n factor: month,\n // \"month\" labels are used for formatting the output.\n unit: 'month'\n}, {\n // This step is effective starting from 10.5 months.\n threshold: 10.5 * month,\n // Return the amount of minutes by dividing the amount\n // of seconds by the amount of seconds in a year.\n factor: year,\n // \"year\" labels are used for formatting the output.\n unit: 'year'\n}];","import approximate from '../steps/approximate'; // \"gradation\" is a legacy name for \"steps\".\n// It's here just for legacy compatibility.\n// Use \"steps\" name instead.\n// \"flavour\" is a legacy name for \"labels\".\n// It's here just for legacy compatibility.\n// Use \"labels\" name instead.\n// \"units\" is a legacy property.\n// It's here just for legacy compatibility.\n// Developers shouldn't need to use it in their custom styles.\n\nexport default {\n gradation: approximate,\n flavour: 'long',\n units: ['now', 'minute', 'hour', 'day', 'week', 'month', 'year']\n};","import approximate from '../steps/approximate'; // \"gradation\" is a legacy name for \"steps\".\n// It's here just for legacy compatibility.\n// Use \"steps\" name instead.\n// \"flavour\" is a legacy name for \"labels\".\n// It's here just for legacy compatibility.\n// Use \"labels\" name instead.\n// \"units\" is a legacy property.\n// It's here just for legacy compatibility.\n// Developers shouldn't need to use it in their custom styles.\n// Similar to the default style but with \"ago\" omitted.\n//\n// just now\n// 5 minutes\n// 10 minutes\n// 15 minutes\n// 20 minutes\n// an hour\n// 2 hours\n// …\n// 20 hours\n// 1 day\n// 2 days\n// a week\n// 2 weeks\n// 3 weeks\n// a month\n// 2 months\n// 3 months\n// 4 months\n// a year\n// 2 years\n//\n\nexport default {\n gradation: approximate,\n flavour: 'long-time',\n units: ['now', 'minute', 'hour', 'day', 'week', 'month', 'year']\n};","// Looks like this one's deprecated.\n// /**\n// * Returns a step corresponding to the unit.\n// * @param {Object[]} steps\n// * @param {string} unit\n// * @return {?Object}\n// */\n// export function getStepForUnit(steps, unit) {\n// \tfor (const step of steps) {\n// \t\tif (step.unit === unit) {\n// \t\t\treturn step\n// \t\t}\n// \t}\n// }\n// Looks like this one won't be used in the next major version.\n\n/**\r\n * Converts value to a `Date`\r\n * @param {(number|Date)} value\r\n * @return {Date}\r\n */\nexport function getDate(value) {\n return value instanceof Date ? value : new Date(value);\n}","import { day, getDate } from '../steps';\nimport { intlDateTimeFormatSupported } from '../locale'; // For compatibility with the old versions of this library.\n\nimport renameLegacyProperties from './renameLegacyProperties'; // Twitter-style relative date/time formatting.\n// (\"1m\", \"2h\", \"Mar 3\", \"Apr 4, 2012\").\n//\n// Seconds, minutes or hours are shown for shorter intervals,\n// and longer intervals are formatted using full date format.\n\nvar steps = [{\n formatAs: 'second'\n}, {\n formatAs: 'minute'\n}, {\n formatAs: 'hour'\n}]; // A cache for `Intl.DateTimeFormat` formatters\n// for various locales (is a global variable).\n\nvar formatters = {}; // Starting from day intervals, output month and day.\n\nvar monthAndDay = {\n minTime: function minTime(timestamp, _ref) {\n var future = _ref.future,\n getMinTimeForUnit = _ref.getMinTimeForUnit; // Returns `23.5 * 60 * 60` when `round` is \"round\",\n // and `24 * 60 * 60` when `round` is \"floor\".\n\n return getMinTimeForUnit('day');\n },\n format: function format(value, locale) {\n /* istanbul ignore else */\n if (!formatters[locale]) {\n formatters[locale] = {};\n }\n /* istanbul ignore else */\n\n\n if (!formatters[locale].dayMonth) {\n // \"Apr 11\" (MMMd)\n formatters[locale].dayMonth = new Intl.DateTimeFormat(locale, {\n month: 'short',\n day: 'numeric'\n });\n } // Output month and day.\n\n\n return formatters[locale].dayMonth.format(getDate(value));\n }\n}; // If the `date` happened/happens outside of current year,\n// then output day, month and year.\n// The interval should be such that the `date` lies outside of the current year.\n\nvar yearMonthAndDay = {\n minTime: function minTime(timestamp, _ref2) {\n var future = _ref2.future;\n\n if (future) {\n // January 1, 00:00, of the `date`'s year is right after\n // the maximum `now` for formatting a future date:\n // When `now` is before that date, the `date` is formatted as \"day/month/year\" (this step),\n // When `now` is equal to or after that date, the `date` is formatted as \"day/month\" (another step).\n // After that, it's hours, minutes, seconds, and after that it's no longer `future`.\n // The date is right after the maximum `now` for formatting a future date,\n // so subtract 1 millisecond from it.\n var maxFittingNow = new Date(new Date(timestamp).getFullYear(), 0).getTime() - 1; // Return `minTime` (in seconds).\n\n return (timestamp - maxFittingNow) / 1000;\n } else {\n // January 1, 00:00, of the year following the `date`'s year\n // is the minimum `now` for formatting a past date:\n // When `now` is before that date, the `date` is formatted as \"day/month\" (another step),\n // When `now` is equal to or after that date, the `date` is formatted as \"day/month/year\" (this step).\n // After that, it's hours, minutes, seconds, and after that it's no longer `future`.\n var minFittingNow = new Date(new Date(timestamp).getFullYear() + 1, 0).getTime(); // Return `minTime` (in seconds).\n\n return (minFittingNow - timestamp) / 1000;\n }\n },\n format: function format(value, locale) {\n /* istanbul ignore if */\n if (!formatters[locale]) {\n formatters[locale] = {};\n }\n /* istanbul ignore else */\n\n\n if (!formatters[locale].dayMonthYear) {\n // \"Apr 11, 2017\" (yMMMd)\n formatters[locale].dayMonthYear = new Intl.DateTimeFormat(locale, {\n year: 'numeric',\n month: 'short',\n day: 'numeric'\n });\n } // Output day, month and year.\n\n\n return formatters[locale].dayMonthYear.format(getDate(value));\n }\n}; // If `Intl.DateTimeFormat` is supported,\n// then longer time intervals will be formatted as dates.\n\n/* istanbul ignore else */\n\nif (intlDateTimeFormatSupported()) {\n steps.push(monthAndDay, yearMonthAndDay);\n} // Otherwise, if `Intl.DateTimeFormat` is not supported,\n// which could be the case when using Internet Explorer,\n// then simply mimick \"round\" steps.\nelse {\n steps.push({\n formatAs: 'day'\n }, {\n formatAs: 'week'\n }, {\n formatAs: 'month'\n }, {\n formatAs: 'year'\n });\n}\n\nexport default {\n steps: steps,\n labels: [// \"mini\" labels are only defined for a few languages.\n 'mini', // \"short-time\" labels are only defined for a few languages.\n 'short-time', // \"narrow\" and \"short\" labels are defined for all languages.\n // \"narrow\" labels can sometimes be weird (like \"+5d.\"),\n // but \"short\" labels have the \" ago\" part, so \"narrow\" seem\n // more appropriate.\n // \"short\" labels would have been more appropriate if they\n // didn't have the \" ago\" part, hence the \"short-time\" above.\n 'narrow', // Since \"narrow\" labels are always present, \"short\" element\n // of this array can be removed.\n 'short']\n};","function _objectSpread(target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i] != null ? arguments[i] : {};\n var ownKeys = Object.keys(source);\n\n if (typeof Object.getOwnPropertySymbols === 'function') {\n ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) {\n return Object.getOwnPropertyDescriptor(source, sym).enumerable;\n }));\n }\n\n ownKeys.forEach(function (key) {\n _defineProperty(target, key, source[key]);\n });\n }\n\n return target;\n}\n\nfunction _defineProperty(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n\n return obj;\n}\n\nimport twitter from './twitter';\nexport default _objectSpread({}, twitter, {\n // Add \"now\".\n steps: [{\n formatAs: 'now'\n }].concat(twitter.steps)\n});","function _objectSpread(target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i] != null ? arguments[i] : {};\n var ownKeys = Object.keys(source);\n\n if (typeof Object.getOwnPropertySymbols === 'function') {\n ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) {\n return Object.getOwnPropertyDescriptor(source, sym).enumerable;\n }));\n }\n\n ownKeys.forEach(function (key) {\n _defineProperty(target, key, source[key]);\n });\n }\n\n return target;\n}\n\nfunction _defineProperty(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n\n return obj;\n}\n\nimport twitter from './twitter';\nexport default _objectSpread({}, twitter, {\n // Skip \"seconds\".\n steps: twitter.steps.filter(function (step) {\n return step.formatAs !== 'second';\n })\n});","function _objectSpread(target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i] != null ? arguments[i] : {};\n var ownKeys = Object.keys(source);\n\n if (typeof Object.getOwnPropertySymbols === 'function') {\n ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) {\n return Object.getOwnPropertyDescriptor(source, sym).enumerable;\n }));\n }\n\n ownKeys.forEach(function (key) {\n _defineProperty(target, key, source[key]);\n });\n }\n\n return target;\n}\n\nfunction _defineProperty(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n\n return obj;\n}\n\nimport twitterMinute from './twitterMinute';\nexport default _objectSpread({}, twitterMinute, {\n // Add \"now\".\n steps: [{\n formatAs: 'now'\n }].concat(twitterMinute.steps)\n});","function _objectSpread(target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i] != null ? arguments[i] : {};\n var ownKeys = Object.keys(source);\n\n if (typeof Object.getOwnPropertySymbols === 'function') {\n ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) {\n return Object.getOwnPropertyDescriptor(source, sym).enumerable;\n }));\n }\n\n ownKeys.forEach(function (key) {\n _defineProperty(target, key, source[key]);\n });\n }\n\n return target;\n}\n\nfunction _defineProperty(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n\n return obj;\n}\n\nimport { minute } from '../steps/units';\nimport twitter from './twitter';\nexport default _objectSpread({}, twitter, {\n // Skip \"seconds\".\n steps: twitter.steps.filter(function (step) {\n return step.formatAs !== 'second';\n }) // Start showing `1m` from the first minute.\n .map(function (step) {\n return step.formatAs === 'minute' ? _objectSpread({}, step, {\n minTime: minute\n }) : step;\n })\n});","export default {\n steps: [{\n formatAs: 'second'\n }, {\n formatAs: 'minute'\n }, {\n formatAs: 'hour'\n }, {\n formatAs: 'day'\n }, {\n formatAs: 'month'\n }, {\n formatAs: 'year'\n }],\n labels: [// \"mini\" labels are only defined for a few languages.\n 'mini', // \"short-time\" labels are only defined for a few languages.\n 'short-time', // \"narrow\" and \"short\" labels are defined for all languages.\n // \"narrow\" labels can sometimes be weird (like \"+5d.\"),\n // but \"short\" labels have the \" ago\" part, so \"narrow\" seem\n // more appropriate.\n // \"short\" labels would have been more appropriate if they\n // didn't have the \" ago\" part, hence the \"short-time\" above.\n 'narrow', // Since \"narrow\" labels are always present, \"short\" element\n // of this array can be removed.\n 'short']\n};","function _objectSpread(target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i] != null ? arguments[i] : {};\n var ownKeys = Object.keys(source);\n\n if (typeof Object.getOwnPropertySymbols === 'function') {\n ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) {\n return Object.getOwnPropertyDescriptor(source, sym).enumerable;\n }));\n }\n\n ownKeys.forEach(function (key) {\n _defineProperty(target, key, source[key]);\n });\n }\n\n return target;\n}\n\nfunction _defineProperty(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n\n return obj;\n}\n\nimport mini from './mini';\nexport default _objectSpread({}, mini, {\n // Add \"now\".\n steps: [{\n formatAs: 'now'\n }].concat(mini.steps)\n});","function _objectSpread(target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i] != null ? arguments[i] : {};\n var ownKeys = Object.keys(source);\n\n if (typeof Object.getOwnPropertySymbols === 'function') {\n ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) {\n return Object.getOwnPropertyDescriptor(source, sym).enumerable;\n }));\n }\n\n ownKeys.forEach(function (key) {\n _defineProperty(target, key, source[key]);\n });\n }\n\n return target;\n}\n\nfunction _defineProperty(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n\n return obj;\n}\n\nimport mini from './mini';\nexport default _objectSpread({}, mini, {\n // Skip \"seconds\".\n steps: mini.steps.filter(function (step) {\n return step.formatAs !== 'second';\n })\n});","function _objectSpread(target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i] != null ? arguments[i] : {};\n var ownKeys = Object.keys(source);\n\n if (typeof Object.getOwnPropertySymbols === 'function') {\n ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) {\n return Object.getOwnPropertyDescriptor(source, sym).enumerable;\n }));\n }\n\n ownKeys.forEach(function (key) {\n _defineProperty(target, key, source[key]);\n });\n }\n\n return target;\n}\n\nfunction _defineProperty(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n\n return obj;\n}\n\nimport miniMinute from './miniMinute';\nexport default _objectSpread({}, miniMinute, {\n // Add \"now\".\n steps: [{\n formatAs: 'now'\n }].concat(miniMinute.steps)\n});","function _typeof2(obj) { \"@babel/helpers - typeof\"; return _typeof2 = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }, _typeof2(obj); }\n\nfunction _typeof(obj) {\n if (typeof Symbol === \"function\" && _typeof2(Symbol.iterator) === \"symbol\") {\n _typeof = function _typeof(obj) {\n return _typeof2(obj);\n };\n } else {\n _typeof = function _typeof(obj) {\n return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : _typeof2(obj);\n };\n }\n\n return _typeof(obj);\n}\n\nfunction _slicedToArray(arr, i) {\n return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest();\n}\n\nfunction _nonIterableRest() {\n throw new TypeError(\"Invalid attempt to destructure non-iterable instance\");\n}\n\nfunction _iterableToArrayLimit(arr, i) {\n var _arr = [];\n var _n = true;\n var _d = false;\n var _e = undefined;\n\n try {\n for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {\n _arr.push(_s.value);\n\n if (i && _arr.length === i) break;\n }\n } catch (err) {\n _d = true;\n _e = err;\n } finally {\n try {\n if (!_n && _i[\"return\"] != null) _i[\"return\"]();\n } finally {\n if (_d) throw _e;\n }\n }\n\n return _arr;\n}\n\nfunction _arrayWithHoles(arr) {\n if (Array.isArray(arr)) return arr;\n}\n\nfunction _classCallCheck(instance, Constructor) {\n if (!(instance instanceof Constructor)) {\n throw new TypeError(\"Cannot call a class as a function\");\n }\n}\n\nfunction _defineProperties(target, props) {\n for (var i = 0; i < props.length; i++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if (\"value\" in descriptor) descriptor.writable = true;\n Object.defineProperty(target, descriptor.key, descriptor);\n }\n}\n\nfunction _createClass(Constructor, protoProps, staticProps) {\n if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n if (staticProps) _defineProperties(Constructor, staticProps);\n return Constructor;\n}\n\nimport RelativeTimeFormatPolyfill from 'relative-time-format';\nimport Cache from './cache';\nimport chooseLocale from './locale';\nimport getStep from './steps/getStep';\nimport getStepDenominator from './steps/getStepDenominator';\nimport getTimeToNextUpdate from './steps/getTimeToNextUpdate';\nimport { addLocaleData, getLocaleData } from './LocaleDataStore';\nimport defaultStyle from './style/roundMinute';\nimport getStyleByName from './style/getStyleByName';\nimport { getRoundFunction } from './round'; // Valid time units.\n\nvar UNITS = ['now', // The rest are the same as in `Intl.RelativeTimeFormat`.\n'second', 'minute', 'hour', 'day', 'week', 'month', 'quarter', 'year'];\n\nvar TimeAgo = /*#__PURE__*/function () {\n /**\r\n * @param {(string|string[])} locales=[] - Preferred locales (or locale).\r\n * @param {boolean} [polyfill] — Pass `false` to use native `Intl.RelativeTimeFormat` and `Intl.PluralRules` instead of the polyfills.\r\n */\n function TimeAgo() {\n var locales = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];\n\n var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},\n polyfill = _ref.polyfill;\n\n _classCallCheck(this, TimeAgo); // Convert `locales` to an array.\n\n\n if (typeof locales === 'string') {\n locales = [locales];\n } // Choose the most appropriate locale\n // from the list of `locales` added by the user.\n // For example, new TimeAgo(\"en-US\") -> \"en\".\n\n\n this.locale = chooseLocale(locales.concat(TimeAgo.getDefaultLocale()), getLocaleData);\n\n if (typeof Intl !== 'undefined') {\n // Use `Intl.NumberFormat` for formatting numbers (when available).\n if (Intl.NumberFormat) {\n this.numberFormat = new Intl.NumberFormat(this.locale);\n }\n } // Some people have requested the ability to use native\n // `Intl.RelativeTimeFormat` and `Intl.PluralRules`\n // instead of the polyfills.\n // https://github.com/catamphetamine/javascript-time-ago/issues/21\n\n\n if (polyfill === false) {\n this.IntlRelativeTimeFormat = Intl.RelativeTimeFormat;\n this.IntlPluralRules = Intl.PluralRules;\n } else {\n this.IntlRelativeTimeFormat = RelativeTimeFormatPolyfill;\n this.IntlPluralRules = RelativeTimeFormatPolyfill.PluralRules;\n } // Cache `Intl.RelativeTimeFormat` instance.\n\n\n this.relativeTimeFormatCache = new Cache(); // Cache `Intl.PluralRules` instance.\n\n this.pluralRulesCache = new Cache();\n }\n /**\r\n * Formats relative date/time.\r\n *\r\n * @param {number} [options.now] - Sets the current date timestamp.\r\n *\r\n * @param {boolean} [options.future] — Tells how to format value `0`:\r\n * as \"future\" (`true`) or \"past\" (`false`).\r\n * Is `false` by default, but should have been `true` actually,\r\n * in order to correspond to `Intl.RelativeTimeFormat`\r\n * that uses `future` formatting for `0` unless `-0` is passed.\r\n *\r\n * @param {string} [options.round] — Rounding method. Overrides the style's one.\r\n *\r\n * @param {boolean} [options.getTimeToNextUpdate] — Pass `true` to return `[formattedDate, timeToNextUpdate]` instead of just `formattedDate`.\r\n *\r\n * @return {string} The formatted relative date/time. If no eligible `step` is found, then an empty string is returned.\r\n */\n\n\n _createClass(TimeAgo, [{\n key: \"format\",\n value: function format(input, style, options) {\n if (!options) {\n if (style && !isStyle(style)) {\n options = style;\n style = undefined;\n } else {\n options = {};\n }\n }\n\n if (!style) {\n style = defaultStyle;\n }\n\n if (typeof style === 'string') {\n style = getStyleByName(style);\n }\n\n var timestamp = getTimestamp(input); // Get locale messages for this type of labels.\n // \"flavour\" is a legacy name for \"labels\".\n\n var _this$getLabels = this.getLabels(style.flavour || style.labels),\n labels = _this$getLabels.labels,\n labelsType = _this$getLabels.labelsType;\n\n var now; // Can pass a custom `now`, e.g. for testing purposes.\n //\n // Legacy way was passing `now` in `style`.\n // That way is deprecated.\n\n if (style.now !== undefined) {\n now = style.now;\n } // The new way is passing `now` option to `.format()`.\n\n\n if (now === undefined && options.now !== undefined) {\n now = options.now;\n }\n\n if (now === undefined) {\n now = Date.now();\n } // how much time has passed (in seconds)\n\n\n var secondsPassed = (now - timestamp) / 1000; // in seconds\n\n var future = options.future || secondsPassed < 0;\n var nowLabel = getNowLabel(labels, getLocaleData(this.locale).now, getLocaleData(this.locale)[\"long\"], future); // `custom` – A function of `{ elapsed, time, date, now, locale }`.\n //\n // Looks like `custom` function is deprecated and will be removed\n // in the next major version.\n //\n // If this function returns a value, then the `.format()` call will return that value.\n // Otherwise the relative date/time is formatted as usual.\n // This feature is currently not used anywhere and is here\n // just for providing the ultimate customization point\n // in case anyone would ever need that. Prefer using\n // `steps[step].format(value, locale)` instead.\n //\n\n if (style.custom) {\n var custom = style.custom({\n now: now,\n date: new Date(timestamp),\n time: timestamp,\n elapsed: secondsPassed,\n locale: this.locale\n });\n\n if (custom !== undefined) {\n // Won't return `timeToNextUpdate` here\n // because `custom()` seems deprecated.\n return custom;\n }\n } // Get the list of available time interval units.\n\n\n var units = getTimeIntervalMeasurementUnits( // Controlling `style.steps` through `style.units` seems to be deprecated:\n // create a new custom `style` instead.\n style.units, labels, nowLabel); // // If no available time unit is suitable, just output an empty string.\n // if (units.length === 0) {\n // \tconsole.error(`None of the \"${units.join(', ')}\" time units have been found in \"${labelsType}\" labels for \"${this.locale}\" locale.`)\n // \treturn ''\n // }\n\n var round = options.round || style.round; // Choose the appropriate time measurement unit\n // and get the corresponding rounded time amount.\n\n var _getStep = getStep( // \"gradation\" is a legacy name for \"steps\".\n // For historical reasons, \"approximate\" steps are used by default.\n // In the next major version, there'll be no default for `steps`.\n style.gradation || style.steps || defaultStyle.steps, secondsPassed, {\n now: now,\n units: units,\n round: round,\n future: future,\n getNextStep: true\n }),\n _getStep2 = _slicedToArray(_getStep, 3),\n prevStep = _getStep2[0],\n step = _getStep2[1],\n nextStep = _getStep2[2];\n\n var formattedDate = this.formatDateForStep(timestamp, step, secondsPassed, {\n labels: labels,\n labelsType: labelsType,\n nowLabel: nowLabel,\n now: now,\n future: future,\n round: round\n }) || '';\n\n if (options.getTimeToNextUpdate) {\n var timeToNextUpdate = getTimeToNextUpdate(timestamp, step, {\n nextStep: nextStep,\n prevStep: prevStep,\n now: now,\n future: future,\n round: round\n });\n return [formattedDate, timeToNextUpdate];\n }\n\n return formattedDate;\n }\n }, {\n key: \"formatDateForStep\",\n value: function formatDateForStep(timestamp, step, secondsPassed, _ref2) {\n var _this = this;\n\n var labels = _ref2.labels,\n labelsType = _ref2.labelsType,\n nowLabel = _ref2.nowLabel,\n now = _ref2.now,\n future = _ref2.future,\n round = _ref2.round; // If no step matches, then output an empty string.\n\n if (!step) {\n return;\n }\n\n if (step.format) {\n return step.format(timestamp, this.locale, {\n formatAs: function formatAs(unit, value) {\n // Mimicks `Intl.RelativeTimeFormat.format()`.\n return _this.formatValue(value, unit, {\n labels: labels,\n future: future\n });\n },\n now: now,\n future: future\n });\n } // \"unit\" is now called \"formatAs\".\n\n\n var unit = step.unit || step.formatAs;\n\n if (!unit) {\n throw new Error(\"[javascript-time-ago] Each step must define either `formatAs` or `format()`. Step: \".concat(JSON.stringify(step)));\n } // `Intl.RelativeTimeFormat` doesn't operate in \"now\" units.\n // Therefore, threat \"now\" as a special case.\n\n\n if (unit === 'now') {\n return nowLabel;\n } // Amount in units.\n\n\n var amount = Math.abs(secondsPassed) / getStepDenominator(step); // Apply granularity to the time amount\n // (and fallback to the previous step\n // if the first level of granularity\n // isn't met by this amount)\n //\n // `granularity` — (advanced) Time interval value \"granularity\".\n // For example, it could be set to `5` for minutes to allow only 5-minute increments\n // when formatting time intervals: `0 minutes`, `5 minutes`, `10 minutes`, etc.\n // Perhaps this feature will be removed because there seem to be no use cases\n // of it in the real world.\n //\n\n if (step.granularity) {\n // Recalculate the amount of seconds passed based on granularity\n amount = getRoundFunction(round)(amount / step.granularity) * step.granularity;\n }\n\n var valueForFormatting = -1 * Math.sign(secondsPassed) * getRoundFunction(round)(amount); // By default, this library formats a `0` in \"past\" mode,\n // unless `future: true` option is passed.\n // This is different to `relative-time-format`'s behavior\n // which formats a `0` in \"future\" mode by default, unless it's a `-0`.\n // So, convert `0` to `-0` if `future: true` option wasn't passed.\n // `=== 0` matches both `0` and `-0`.\n\n if (valueForFormatting === 0) {\n if (future) {\n valueForFormatting = 0;\n } else {\n valueForFormatting = -0;\n }\n }\n\n switch (labelsType) {\n case 'long':\n case 'short':\n case 'narrow':\n // Format the amount using `Intl.RelativeTimeFormat`.\n return this.getFormatter(labelsType).format(valueForFormatting, unit);\n\n default:\n // Format the amount.\n // (mimicks `Intl.RelativeTimeFormat` behavior for other time label styles)\n return this.formatValue(valueForFormatting, unit, {\n labels: labels,\n future: future\n });\n }\n }\n /**\r\n * Mimicks what `Intl.RelativeTimeFormat` does for additional locale styles.\r\n * @param {number} value\r\n * @param {string} unit\r\n * @param {object} options.labels — Relative time labels.\r\n * @param {boolean} [options.future] — Tells how to format value `0`: as \"future\" (`true`) or \"past\" (`false`). Is `false` by default, but should have been `true` actually.\r\n * @return {string}\r\n */\n\n }, {\n key: \"formatValue\",\n value: function formatValue(value, unit, _ref3) {\n var labels = _ref3.labels,\n future = _ref3.future;\n return this.getFormattingRule(labels, unit, value, {\n future: future\n }).replace('{0}', this.formatNumber(Math.abs(value)));\n }\n /**\r\n * Returns formatting rule for `value` in `units` (either in past or in future).\r\n * @param {object} formattingRules — Relative time labels for different units.\r\n * @param {string} unit - Time interval measurement unit.\r\n * @param {number} value - Time interval value.\r\n * @param {boolean} [options.future] — Tells how to format value `0`: as \"future\" (`true`) or \"past\" (`false`). Is `false` by default.\r\n * @return {string}\r\n * @example\r\n * // Returns \"{0} days ago\"\r\n * getFormattingRule(en.long, \"day\", -2, 'en')\r\n */\n\n }, {\n key: \"getFormattingRule\",\n value: function getFormattingRule(formattingRules, unit, value, _ref4) {\n var future = _ref4.future; // Passing the language is required in order to\n // be able to correctly classify the `value` as a number.\n\n var locale = this.locale;\n formattingRules = formattingRules[unit]; // Check for a special \"compacted\" rules case:\n // if formatting rules are the same for \"past\" and \"future\",\n // and also for all possible `value`s, then those rules are\n // stored as a single string.\n\n if (typeof formattingRules === 'string') {\n return formattingRules;\n } // Choose either \"past\" or \"future\" based on time `value` sign.\n // If \"past\" is same as \"future\" then they're stored as \"other\".\n // If there's only \"other\" then it's being collapsed.\n\n\n var pastOrFuture = value === 0 ? future ? 'future' : 'past' : value < 0 ? 'past' : 'future';\n var quantifierRules = formattingRules[pastOrFuture] || formattingRules; // Bundle size optimization technique.\n\n if (typeof quantifierRules === 'string') {\n return quantifierRules;\n } // Quantify `value`.\n\n\n var quantifier = this.getPluralRules().select(Math.abs(value)); // \"other\" rule is supposed to always be present.\n // If only \"other\" rule is present then \"rules\" is not an object and is a string.\n\n return quantifierRules[quantifier] || quantifierRules.other;\n }\n /**\r\n * Formats a number into a string.\r\n * Uses `Intl.NumberFormat` when available.\r\n * @param {number} number\r\n * @return {string}\r\n */\n\n }, {\n key: \"formatNumber\",\n value: function formatNumber(number) {\n return this.numberFormat ? this.numberFormat.format(number) : String(number);\n }\n /**\r\n * Returns an `Intl.RelativeTimeFormat` for a given `labelsType`.\r\n * @param {string} labelsType\r\n * @return {object} `Intl.RelativeTimeFormat` instance\r\n */\n\n }, {\n key: \"getFormatter\",\n value: function getFormatter(labelsType) {\n // `Intl.RelativeTimeFormat` instance creation is (hypothetically) assumed\n // a lengthy operation so the instances are cached and reused.\n return this.relativeTimeFormatCache.get(this.locale, labelsType) || this.relativeTimeFormatCache.put(this.locale, labelsType, new this.IntlRelativeTimeFormat(this.locale, {\n style: labelsType\n }));\n }\n /**\r\n * Returns an `Intl.PluralRules` instance.\r\n * @return {object} `Intl.PluralRules` instance\r\n */\n\n }, {\n key: \"getPluralRules\",\n value: function getPluralRules() {\n // `Intl.PluralRules` instance creation is (hypothetically) assumed\n // a lengthy operation so the instances are cached and reused.\n return this.pluralRulesCache.get(this.locale) || this.pluralRulesCache.put(this.locale, new this.IntlPluralRules(this.locale));\n }\n /**\r\n * Gets localized labels for this type of labels.\r\n *\r\n * @param {(string|string[])} labelsType - Relative date/time labels type.\r\n * If it's an array then all label types are tried\r\n * until a suitable one is found.\r\n *\r\n * @returns {Object} Returns an object of shape { labelsType, labels }\r\n */\n\n }, {\n key: \"getLabels\",\n value: function getLabels() {\n var labelsType = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; // Convert `labels` to an array.\n\n if (typeof labelsType === 'string') {\n labelsType = [labelsType];\n } // Supports legacy \"tiny\" and \"mini-time\" label styles.\n\n\n labelsType = labelsType.map(function (labelsType) {\n switch (labelsType) {\n case 'tiny':\n case 'mini-time':\n return 'mini';\n\n default:\n return labelsType;\n }\n }); // \"long\" labels type is the default one.\n // (it's always present for all languages)\n\n labelsType = labelsType.concat('long'); // Find a suitable labels type.\n\n var localeData = getLocaleData(this.locale);\n\n for (var _iterator = labelsType, _isArray = Array.isArray(_iterator), _i2 = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {\n var _ref5;\n\n if (_isArray) {\n if (_i2 >= _iterator.length) break;\n _ref5 = _iterator[_i2++];\n } else {\n _i2 = _iterator.next();\n if (_i2.done) break;\n _ref5 = _i2.value;\n }\n\n var _labelsType = _ref5;\n\n if (localeData[_labelsType]) {\n return {\n labelsType: _labelsType,\n labels: localeData[_labelsType]\n };\n }\n }\n }\n }]);\n\n return TimeAgo;\n}();\n/**\r\n * Default locale global variable.\r\n */\n\n\nexport { TimeAgo as default };\nvar defaultLocale = 'en';\n/**\r\n * Gets default locale.\r\n * @return {string} locale\r\n */\n\nTimeAgo.getDefaultLocale = function () {\n return defaultLocale;\n};\n/**\r\n * Sets default locale.\r\n * @param {string} locale\r\n */\n\n\nTimeAgo.setDefaultLocale = function (locale) {\n return defaultLocale = locale;\n};\n/**\r\n * Adds locale data for a specific locale and marks the locale as default.\r\n * @param {Object} localeData\r\n */\n\n\nTimeAgo.addDefaultLocale = function (localeData) {\n if (defaultLocaleHasBeenSpecified) {\n return console.error('[javascript-time-ago] `TimeAgo.addDefaultLocale()` can only be called once. To add other locales, use `TimeAgo.addLocale()`.');\n }\n\n defaultLocaleHasBeenSpecified = true;\n TimeAgo.setDefaultLocale(localeData.locale);\n TimeAgo.addLocale(localeData);\n};\n\nvar defaultLocaleHasBeenSpecified;\n/**\r\n * Adds locale data for a specific locale.\r\n * @param {Object} localeData\r\n */\n\nTimeAgo.addLocale = function (localeData) {\n addLocaleData(localeData);\n RelativeTimeFormatPolyfill.addLocale(localeData);\n};\n/**\r\n * (legacy alias)\r\n * Adds locale data for a specific locale.\r\n * @param {Object} localeData\r\n * @deprecated\r\n */\n\n\nTimeAgo.locale = TimeAgo.addLocale;\n/**\r\n * Adds custom labels to locale data.\r\n * @param {string} locale\r\n * @param {string} name\r\n * @param {object} labels\r\n */\n\nTimeAgo.addLabels = function (locale, name, labels) {\n var localeData = getLocaleData(locale);\n\n if (!localeData) {\n addLocaleData({\n locale: locale\n });\n localeData = getLocaleData(locale); // throw new Error(`[javascript-time-ago] No data for locale \"${locale}\"`)\n }\n\n localeData[name] = labels;\n}; // Normalizes `.format()` `time` argument.\n\n\nfunction getTimestamp(input) {\n if (input.constructor === Date || isMockedDate(input)) {\n return input.getTime();\n }\n\n if (typeof input === 'number') {\n return input;\n } // For some weird reason istanbul doesn't see this `throw` covered.\n\n /* istanbul ignore next */\n\n\n throw new Error(\"Unsupported relative time formatter input: \".concat(_typeof(input), \", \").concat(input));\n} // During testing via some testing libraries `Date`s aren't actually `Date`s.\n// https://github.com/catamphetamine/javascript-time-ago/issues/22\n\n\nfunction isMockedDate(object) {\n return _typeof(object) === 'object' && typeof object.getTime === 'function';\n} // Get available time interval measurement units.\n\n\nfunction getTimeIntervalMeasurementUnits(allowedUnits, labels, nowLabel) {\n // Get all time interval measurement units that're available\n // in locale data for a given time labels style.\n var units = Object.keys(labels); // `now` unit is handled separately and is shipped in its own `now.json` file.\n // `now.json` isn't present for all locales, so it could be substituted with\n // \".second.current\".\n // Add `now` unit if it's available in locale data.\n\n if (nowLabel) {\n units.push('now');\n } // If only a specific set of available time measurement units can be used\n // then only those units are allowed (if they're present in locale data).\n\n\n if (allowedUnits) {\n units = allowedUnits.filter(function (unit) {\n return unit === 'now' || units.indexOf(unit) >= 0;\n });\n }\n\n return units;\n}\n\nfunction getNowLabel(labels, nowLabels, longLabels, future) {\n var nowLabel = labels.now || nowLabels && nowLabels.now; // Specific \"now\" message form extended locale data (if present).\n\n if (nowLabel) {\n // Bundle size optimization technique.\n if (typeof nowLabel === 'string') {\n return nowLabel;\n } // Not handling `value === 0` as `localeData.now.current` here\n // because it wouldn't make sense: \"now\" is a moment,\n // so one can't possibly differentiate between a\n // \"previous\" moment, a \"current\" moment and a \"next moment\".\n // It can only be differentiated between \"past\" and \"future\".\n\n\n if (future) {\n return nowLabel.future;\n } else {\n return nowLabel.past;\n }\n } // Use \".second.current\" as \"now\" message.\n\n\n if (longLabels && longLabels.second && longLabels.second.current) {\n return longLabels.second.current;\n }\n}\n\nvar OBJECT_CONSTRUCTOR = {}.constructor;\n\nfunction isObject(object) {\n return _typeof(object) !== undefined && object !== null && object.constructor === OBJECT_CONSTRUCTOR;\n}\n\nfunction isStyle(variable) {\n return typeof variable === 'string' || isStyleObject(variable);\n}\n\nexport function isStyleObject(object) {\n return isObject(object) && (Array.isArray(object.steps) || // `gradation` property is deprecated: it has been renamed to `steps`.\n Array.isArray(object.gradation) || // `flavour` property is deprecated: it has been renamed to `labels`.\n Array.isArray(object.flavour) || typeof object.flavour === 'string' || Array.isArray(object.labels) || typeof object.labels === 'string' || // `units` property is deprecated.\n Array.isArray(object.units) || // `custom` property is deprecated.\n typeof object.custom === 'function');\n}","import round from './round';\nimport roundMinute from './roundMinute'; // `approximate` style is deprecated.\n\nimport approximate from './approximate'; // `approximateTime` style is deprecated.\n\nimport approximateTime from './approximateTime';\nimport twitter from './twitter';\nimport twitterNow from './twitterNow';\nimport twitterMinute from './twitterMinute';\nimport twitterMinuteNow from './twitterMinuteNow';\nimport twitterFirstMinute from './twitterFirstMinute';\nimport mini from './mini';\nimport miniNow from './miniNow';\nimport miniMinute from './miniMinute';\nimport miniMinuteNow from './miniMinuteNow';\nexport default function getStyleByName(style) {\n switch (style) {\n // \"default\" style name is deprecated.\n case 'default':\n case 'round':\n return round;\n\n case 'round-minute':\n return roundMinute;\n\n case 'approximate':\n return approximate;\n // \"time\" style name is deprecated.\n\n case 'time':\n case 'approximate-time':\n return approximateTime;\n\n case 'mini':\n return mini;\n\n case 'mini-now':\n return miniNow;\n\n case 'mini-minute':\n return miniMinute;\n\n case 'mini-minute-now':\n return miniMinuteNow;\n\n case 'twitter':\n return twitter;\n\n case 'twitter-now':\n return twitterNow;\n\n case 'twitter-minute':\n return twitterMinute;\n\n case 'twitter-minute-now':\n return twitterMinuteNow;\n\n case 'twitter-first-minute':\n return twitterFirstMinute;\n\n default:\n // For historical reasons, the default style is \"approximate\".\n return approximate;\n }\n}","var originalFunctionToString;\n/** Patch toString calls to return proper name for wrapped functions */\n\nvar FunctionToString =\n/** @class */\nfunction () {\n function FunctionToString() {\n /**\n * @inheritDoc\n */\n this.name = FunctionToString.id;\n }\n /**\n * @inheritDoc\n */\n\n\n FunctionToString.prototype.setupOnce = function () {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n originalFunctionToString = Function.prototype.toString; // eslint-disable-next-line @typescript-eslint/no-explicit-any\n\n Function.prototype.toString = function () {\n var args = [];\n\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n\n var context = this.__sentry_original__ || this;\n return originalFunctionToString.apply(context, args);\n };\n };\n /**\n * @inheritDoc\n */\n\n\n FunctionToString.id = 'FunctionToString';\n return FunctionToString;\n}();\n\nexport { FunctionToString };","export var SDK_VERSION = '6.16.1';","import { __read, __spread } from \"tslib\";\nimport { addGlobalEventProcessor, getCurrentHub } from '@sentry/hub';\nimport { getEventDescription, isMatchingPattern, logger } from '@sentry/utils'; // \"Script error.\" is hard coded into browsers for errors that it can't read.\n// this is the result of a script being pulled in from an external domain and CORS.\n\nvar DEFAULT_IGNORE_ERRORS = [/^Script error\\.?$/, /^Javascript error: Script error\\.? on line 0$/];\n/** Inbound filters configurable by the user */\n\nvar InboundFilters =\n/** @class */\nfunction () {\n function InboundFilters(_options) {\n if (_options === void 0) {\n _options = {};\n }\n\n this._options = _options;\n /**\n * @inheritDoc\n */\n\n this.name = InboundFilters.id;\n }\n /**\n * @inheritDoc\n */\n\n\n InboundFilters.prototype.setupOnce = function () {\n addGlobalEventProcessor(function (event) {\n var hub = getCurrentHub();\n\n if (!hub) {\n return event;\n }\n\n var self = hub.getIntegration(InboundFilters);\n\n if (self) {\n var client = hub.getClient();\n var clientOptions = client ? client.getOptions() : {}; // This checks prevents most of the occurrences of the bug linked below:\n // https://github.com/getsentry/sentry-javascript/issues/2622\n // The bug is caused by multiple SDK instances, where one is minified and one is using non-mangled code.\n // Unfortunatelly we cannot fix it reliably (thus reserved property in rollup's terser config),\n // as we cannot force people using multiple instances in their apps to sync SDK versions.\n\n var options = typeof self._mergeOptions === 'function' ? self._mergeOptions(clientOptions) : {};\n\n if (typeof self._shouldDropEvent !== 'function') {\n return event;\n }\n\n return self._shouldDropEvent(event, options) ? null : event;\n }\n\n return event;\n });\n };\n /** JSDoc */\n\n\n InboundFilters.prototype._shouldDropEvent = function (event, options) {\n if (this._isSentryError(event, options)) {\n logger.warn(\"Event dropped due to being internal Sentry Error.\\nEvent: \" + getEventDescription(event));\n return true;\n }\n\n if (this._isIgnoredError(event, options)) {\n logger.warn(\"Event dropped due to being matched by `ignoreErrors` option.\\nEvent: \" + getEventDescription(event));\n return true;\n }\n\n if (this._isDeniedUrl(event, options)) {\n logger.warn(\"Event dropped due to being matched by `denyUrls` option.\\nEvent: \" + getEventDescription(event) + \".\\nUrl: \" + this._getEventFilterUrl(event));\n return true;\n }\n\n if (!this._isAllowedUrl(event, options)) {\n logger.warn(\"Event dropped due to not being matched by `allowUrls` option.\\nEvent: \" + getEventDescription(event) + \".\\nUrl: \" + this._getEventFilterUrl(event));\n return true;\n }\n\n return false;\n };\n /** JSDoc */\n\n\n InboundFilters.prototype._isSentryError = function (event, options) {\n if (!options.ignoreInternal) {\n return false;\n }\n\n try {\n return event && event.exception && event.exception.values && event.exception.values[0] && event.exception.values[0].type === 'SentryError' || false;\n } catch (_oO) {\n return false;\n }\n };\n /** JSDoc */\n\n\n InboundFilters.prototype._isIgnoredError = function (event, options) {\n if (!options.ignoreErrors || !options.ignoreErrors.length) {\n return false;\n }\n\n return this._getPossibleEventMessages(event).some(function (message) {\n // Not sure why TypeScript complains here...\n return options.ignoreErrors.some(function (pattern) {\n return isMatchingPattern(message, pattern);\n });\n });\n };\n /** JSDoc */\n\n\n InboundFilters.prototype._isDeniedUrl = function (event, options) {\n // TODO: Use Glob instead?\n if (!options.denyUrls || !options.denyUrls.length) {\n return false;\n }\n\n var url = this._getEventFilterUrl(event);\n\n return !url ? false : options.denyUrls.some(function (pattern) {\n return isMatchingPattern(url, pattern);\n });\n };\n /** JSDoc */\n\n\n InboundFilters.prototype._isAllowedUrl = function (event, options) {\n // TODO: Use Glob instead?\n if (!options.allowUrls || !options.allowUrls.length) {\n return true;\n }\n\n var url = this._getEventFilterUrl(event);\n\n return !url ? true : options.allowUrls.some(function (pattern) {\n return isMatchingPattern(url, pattern);\n });\n };\n /** JSDoc */\n\n\n InboundFilters.prototype._mergeOptions = function (clientOptions) {\n if (clientOptions === void 0) {\n clientOptions = {};\n }\n\n return {\n allowUrls: __spread(this._options.whitelistUrls || [], this._options.allowUrls || [], clientOptions.whitelistUrls || [], clientOptions.allowUrls || []),\n denyUrls: __spread(this._options.blacklistUrls || [], this._options.denyUrls || [], clientOptions.blacklistUrls || [], clientOptions.denyUrls || []),\n ignoreErrors: __spread(this._options.ignoreErrors || [], clientOptions.ignoreErrors || [], DEFAULT_IGNORE_ERRORS),\n ignoreInternal: typeof this._options.ignoreInternal !== 'undefined' ? this._options.ignoreInternal : true\n };\n };\n /** JSDoc */\n\n\n InboundFilters.prototype._getPossibleEventMessages = function (event) {\n if (event.message) {\n return [event.message];\n }\n\n if (event.exception) {\n try {\n var _a = event.exception.values && event.exception.values[0] || {},\n _b = _a.type,\n type = _b === void 0 ? '' : _b,\n _c = _a.value,\n value = _c === void 0 ? '' : _c;\n\n return [\"\" + value, type + \": \" + value];\n } catch (oO) {\n logger.error(\"Cannot extract message for event \" + getEventDescription(event));\n return [];\n }\n }\n\n return [];\n };\n /** JSDoc */\n\n\n InboundFilters.prototype._getLastValidUrl = function (frames) {\n if (frames === void 0) {\n frames = [];\n }\n\n var _a, _b;\n\n for (var i = frames.length - 1; i >= 0; i--) {\n var frame = frames[i];\n\n if (((_a = frame) === null || _a === void 0 ? void 0 : _a.filename) !== '' && ((_b = frame) === null || _b === void 0 ? void 0 : _b.filename) !== '[native code]') {\n return frame.filename || null;\n }\n }\n\n return null;\n };\n /** JSDoc */\n\n\n InboundFilters.prototype._getEventFilterUrl = function (event) {\n try {\n if (event.stacktrace) {\n var frames_1 = event.stacktrace.frames;\n return this._getLastValidUrl(frames_1);\n }\n\n if (event.exception) {\n var frames_2 = event.exception.values && event.exception.values[0].stacktrace && event.exception.values[0].stacktrace.frames;\n return this._getLastValidUrl(frames_2);\n }\n\n return null;\n } catch (oO) {\n logger.error(\"Cannot extract url for event \" + getEventDescription(event));\n return null;\n }\n };\n /**\n * @inheritDoc\n */\n\n\n InboundFilters.id = 'InboundFilters';\n return InboundFilters;\n}();\n\nexport { InboundFilters };","export var setPrototypeOf = Object.setPrototypeOf || ({\n __proto__: []\n} instanceof Array ? setProtoOf : mixinProperties);\n/**\n * setPrototypeOf polyfill using __proto__\n */\n// eslint-disable-next-line @typescript-eslint/ban-types\n\nfunction setProtoOf(obj, proto) {\n // @ts-ignore __proto__ does not exist on obj\n obj.__proto__ = proto;\n return obj;\n}\n/**\n * setPrototypeOf polyfill using mixin\n */\n// eslint-disable-next-line @typescript-eslint/ban-types\n\n\nfunction mixinProperties(obj, proto) {\n for (var prop in proto) {\n if (!Object.prototype.hasOwnProperty.call(obj, prop)) {\n // @ts-ignore typescript complains about indexing so we remove\n obj[prop] = proto[prop];\n }\n }\n\n return obj;\n}","import { __extends } from \"tslib\";\nimport { setPrototypeOf } from './polyfill';\n/** An error emitted by Sentry SDKs and related utilities. */\n\nvar SentryError =\n/** @class */\nfunction (_super) {\n __extends(SentryError, _super);\n\n function SentryError(message) {\n var _newTarget = this.constructor;\n\n var _this = _super.call(this, message) || this;\n\n _this.message = message;\n _this.name = _newTarget.prototype.constructor.name;\n setPrototypeOf(_this, _newTarget.prototype);\n return _this;\n }\n\n return SentryError;\n}(Error);\n\nexport { SentryError };","import { __read } from \"tslib\";\nimport { SentryError } from './error';\n/** Regular expression used to parse a Dsn. */\n\nvar DSN_REGEX = /^(?:(\\w+):)\\/\\/(?:(\\w+)(?::(\\w+))?@)([\\w.-]+)(?::(\\d+))?\\/(.+)/;\n/** Error message */\n\nvar ERROR_MESSAGE = 'Invalid Dsn';\n/** The Sentry Dsn, identifying a Sentry instance and project. */\n\nvar Dsn =\n/** @class */\nfunction () {\n /** Creates a new Dsn component */\n function Dsn(from) {\n if (typeof from === 'string') {\n this._fromString(from);\n } else {\n this._fromComponents(from);\n }\n\n this._validate();\n }\n /**\n * Renders the string representation of this Dsn.\n *\n * By default, this will render the public representation without the password\n * component. To get the deprecated private representation, set `withPassword`\n * to true.\n *\n * @param withPassword When set to true, the password will be included.\n */\n\n\n Dsn.prototype.toString = function (withPassword) {\n if (withPassword === void 0) {\n withPassword = false;\n }\n\n var _a = this,\n host = _a.host,\n path = _a.path,\n pass = _a.pass,\n port = _a.port,\n projectId = _a.projectId,\n protocol = _a.protocol,\n publicKey = _a.publicKey;\n\n return protocol + \"://\" + publicKey + (withPassword && pass ? \":\" + pass : '') + (\"@\" + host + (port ? \":\" + port : '') + \"/\" + (path ? path + \"/\" : path) + projectId);\n };\n /** Parses a string into this Dsn. */\n\n\n Dsn.prototype._fromString = function (str) {\n var match = DSN_REGEX.exec(str);\n\n if (!match) {\n throw new SentryError(ERROR_MESSAGE);\n }\n\n var _a = __read(match.slice(1), 6),\n protocol = _a[0],\n publicKey = _a[1],\n _b = _a[2],\n pass = _b === void 0 ? '' : _b,\n host = _a[3],\n _c = _a[4],\n port = _c === void 0 ? '' : _c,\n lastPath = _a[5];\n\n var path = '';\n var projectId = lastPath;\n var split = projectId.split('/');\n\n if (split.length > 1) {\n path = split.slice(0, -1).join('/');\n projectId = split.pop();\n }\n\n if (projectId) {\n var projectMatch = projectId.match(/^\\d+/);\n\n if (projectMatch) {\n projectId = projectMatch[0];\n }\n }\n\n this._fromComponents({\n host: host,\n pass: pass,\n path: path,\n projectId: projectId,\n port: port,\n protocol: protocol,\n publicKey: publicKey\n });\n };\n /** Maps Dsn components into this instance. */\n\n\n Dsn.prototype._fromComponents = function (components) {\n // TODO this is for backwards compatibility, and can be removed in a future version\n if ('user' in components && !('publicKey' in components)) {\n components.publicKey = components.user;\n }\n\n this.user = components.publicKey || '';\n this.protocol = components.protocol;\n this.publicKey = components.publicKey || '';\n this.pass = components.pass || '';\n this.host = components.host;\n this.port = components.port || '';\n this.path = components.path || '';\n this.projectId = components.projectId;\n };\n /** Validates this Dsn and throws on error. */\n\n\n Dsn.prototype._validate = function () {\n var _this = this;\n\n ['protocol', 'publicKey', 'host', 'projectId'].forEach(function (component) {\n if (!_this[component]) {\n throw new SentryError(ERROR_MESSAGE + \": \" + component + \" missing\");\n }\n });\n\n if (!this.projectId.match(/^\\d+$/)) {\n throw new SentryError(ERROR_MESSAGE + \": Invalid projectId \" + this.projectId);\n }\n\n if (this.protocol !== 'http' && this.protocol !== 'https') {\n throw new SentryError(ERROR_MESSAGE + \": Invalid protocol \" + this.protocol);\n }\n\n if (this.port && isNaN(parseInt(this.port, 10))) {\n throw new SentryError(ERROR_MESSAGE + \": Invalid port \" + this.port);\n }\n };\n\n return Dsn;\n}();\n\nexport { Dsn };","import { __read, __spread } from \"tslib\";\nimport { addGlobalEventProcessor, getCurrentHub } from '@sentry/hub';\nimport { logger } from '@sentry/utils';\nexport var installedIntegrations = [];\n/**\n * @private\n */\n\nfunction filterDuplicates(integrations) {\n return integrations.reduce(function (acc, integrations) {\n if (acc.every(function (accIntegration) {\n return integrations.name !== accIntegration.name;\n })) {\n acc.push(integrations);\n }\n\n return acc;\n }, []);\n}\n/** Gets integration to install */\n\n\nexport function getIntegrationsToSetup(options) {\n var defaultIntegrations = options.defaultIntegrations && __spread(options.defaultIntegrations) || [];\n var userIntegrations = options.integrations;\n\n var integrations = __spread(filterDuplicates(defaultIntegrations));\n\n if (Array.isArray(userIntegrations)) {\n // Filter out integrations that are also included in user options\n integrations = __spread(integrations.filter(function (integrations) {\n return userIntegrations.every(function (userIntegration) {\n return userIntegration.name !== integrations.name;\n });\n }), filterDuplicates(userIntegrations));\n } else if (typeof userIntegrations === 'function') {\n integrations = userIntegrations(integrations);\n integrations = Array.isArray(integrations) ? integrations : [integrations];\n } // Make sure that if present, `Debug` integration will always run last\n\n\n var integrationsNames = integrations.map(function (i) {\n return i.name;\n });\n var alwaysLastToRun = 'Debug';\n\n if (integrationsNames.indexOf(alwaysLastToRun) !== -1) {\n integrations.push.apply(integrations, __spread(integrations.splice(integrationsNames.indexOf(alwaysLastToRun), 1)));\n }\n\n return integrations;\n}\n/** Setup given integration */\n\nexport function setupIntegration(integration) {\n if (installedIntegrations.indexOf(integration.name) !== -1) {\n return;\n }\n\n integration.setupOnce(addGlobalEventProcessor, getCurrentHub);\n installedIntegrations.push(integration.name);\n logger.log(\"Integration installed: \" + integration.name);\n}\n/**\n * Given a list of integration instances this installs them all. When `withDefaults` is set to `true` then all default\n * integrations are added unless they were already provided before.\n * @param integrations array of integration instances\n * @param withDefault should enable default integrations\n */\n\nexport function setupIntegrations(options) {\n var integrations = {};\n getIntegrationsToSetup(options).forEach(function (integration) {\n integrations[integration.name] = integration;\n setupIntegration(integration);\n }); // set the `initialized` flag so we don't run through the process again unecessarily; use `Object.defineProperty`\n // because by default it creates a property which is nonenumerable, which we want since `initialized` shouldn't be\n // considered a member of the index the way the actual integrations are\n\n Object.defineProperty(integrations, 'initialized', {\n value: true\n });\n return integrations;\n}","import { __assign, __read, __spread, __values } from \"tslib\";\n/* eslint-disable max-lines */\n\nimport { Scope } from '@sentry/hub';\nimport { Outcome, SessionStatus } from '@sentry/types';\nimport { checkOrSetAlreadyCaught, dateTimestampInSeconds, Dsn, isPlainObject, isPrimitive, isThenable, logger, normalize, SentryError, SyncPromise, truncate, uuid4 } from '@sentry/utils';\nimport { setupIntegrations } from './integration';\nvar ALREADY_SEEN_ERROR = \"Not capturing exception because it's already been captured.\";\n/**\n * Base implementation for all JavaScript SDK clients.\n *\n * Call the constructor with the corresponding backend constructor and options\n * specific to the client subclass. To access these options later, use\n * {@link Client.getOptions}. Also, the Backend instance is available via\n * {@link Client.getBackend}.\n *\n * If a Dsn is specified in the options, it will be parsed and stored. Use\n * {@link Client.getDsn} to retrieve the Dsn at any moment. In case the Dsn is\n * invalid, the constructor will throw a {@link SentryException}. Note that\n * without a valid Dsn, the SDK will not send any events to Sentry.\n *\n * Before sending an event via the backend, it is passed through\n * {@link BaseClient._prepareEvent} to add SDK information and scope data\n * (breadcrumbs and context). To add more custom information, override this\n * method and extend the resulting prepared event.\n *\n * To issue automatically created events (e.g. via instrumentation), use\n * {@link Client.captureEvent}. It will prepare the event and pass it through\n * the callback lifecycle. To issue auto-breadcrumbs, use\n * {@link Client.addBreadcrumb}.\n *\n * @example\n * class NodeClient extends BaseClient {\n * public constructor(options: NodeOptions) {\n * super(NodeBackend, options);\n * }\n *\n * // ...\n * }\n */\n\nvar BaseClient =\n/** @class */\nfunction () {\n /**\n * Initializes this client instance.\n *\n * @param backendClass A constructor function to create the backend.\n * @param options Options for the client.\n */\n function BaseClient(backendClass, options) {\n /** Array of used integrations. */\n this._integrations = {};\n /** Number of calls being processed */\n\n this._numProcessing = 0;\n this._backend = new backendClass(options);\n this._options = options;\n\n if (options.dsn) {\n this._dsn = new Dsn(options.dsn);\n }\n }\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\n\n\n BaseClient.prototype.captureException = function (exception, hint, scope) {\n var _this = this; // ensure we haven't captured this very object before\n\n\n if (checkOrSetAlreadyCaught(exception)) {\n logger.log(ALREADY_SEEN_ERROR);\n return;\n }\n\n var eventId = hint && hint.event_id;\n\n this._process(this._getBackend().eventFromException(exception, hint).then(function (event) {\n return _this._captureEvent(event, hint, scope);\n }).then(function (result) {\n eventId = result;\n }));\n\n return eventId;\n };\n /**\n * @inheritDoc\n */\n\n\n BaseClient.prototype.captureMessage = function (message, level, hint, scope) {\n var _this = this;\n\n var eventId = hint && hint.event_id;\n var promisedEvent = isPrimitive(message) ? this._getBackend().eventFromMessage(String(message), level, hint) : this._getBackend().eventFromException(message, hint);\n\n this._process(promisedEvent.then(function (event) {\n return _this._captureEvent(event, hint, scope);\n }).then(function (result) {\n eventId = result;\n }));\n\n return eventId;\n };\n /**\n * @inheritDoc\n */\n\n\n BaseClient.prototype.captureEvent = function (event, hint, scope) {\n var _a; // ensure we haven't captured this very object before\n\n\n if (((_a = hint) === null || _a === void 0 ? void 0 : _a.originalException) && checkOrSetAlreadyCaught(hint.originalException)) {\n logger.log(ALREADY_SEEN_ERROR);\n return;\n }\n\n var eventId = hint && hint.event_id;\n\n this._process(this._captureEvent(event, hint, scope).then(function (result) {\n eventId = result;\n }));\n\n return eventId;\n };\n /**\n * @inheritDoc\n */\n\n\n BaseClient.prototype.captureSession = function (session) {\n if (!this._isEnabled()) {\n logger.warn('SDK not enabled, will not capture session.');\n return;\n }\n\n if (!(typeof session.release === 'string')) {\n logger.warn('Discarded session because of missing or non-string release');\n } else {\n this._sendSession(session); // After sending, we set init false to indicate it's not the first occurrence\n\n\n session.update({\n init: false\n });\n }\n };\n /**\n * @inheritDoc\n */\n\n\n BaseClient.prototype.getDsn = function () {\n return this._dsn;\n };\n /**\n * @inheritDoc\n */\n\n\n BaseClient.prototype.getOptions = function () {\n return this._options;\n };\n /**\n * @inheritDoc\n */\n\n\n BaseClient.prototype.getTransport = function () {\n return this._getBackend().getTransport();\n };\n /**\n * @inheritDoc\n */\n\n\n BaseClient.prototype.flush = function (timeout) {\n var _this = this;\n\n return this._isClientDoneProcessing(timeout).then(function (clientFinished) {\n return _this.getTransport().close(timeout).then(function (transportFlushed) {\n return clientFinished && transportFlushed;\n });\n });\n };\n /**\n * @inheritDoc\n */\n\n\n BaseClient.prototype.close = function (timeout) {\n var _this = this;\n\n return this.flush(timeout).then(function (result) {\n _this.getOptions().enabled = false;\n return result;\n });\n };\n /**\n * Sets up the integrations\n */\n\n\n BaseClient.prototype.setupIntegrations = function () {\n if (this._isEnabled() && !this._integrations.initialized) {\n this._integrations = setupIntegrations(this._options);\n }\n };\n /**\n * @inheritDoc\n */\n\n\n BaseClient.prototype.getIntegration = function (integration) {\n try {\n return this._integrations[integration.id] || null;\n } catch (_oO) {\n logger.warn(\"Cannot retrieve integration \" + integration.id + \" from the current Client\");\n return null;\n }\n };\n /** Updates existing session based on the provided event */\n\n\n BaseClient.prototype._updateSessionFromEvent = function (session, event) {\n var e_1, _a;\n\n var crashed = false;\n var errored = false;\n var exceptions = event.exception && event.exception.values;\n\n if (exceptions) {\n errored = true;\n\n try {\n for (var exceptions_1 = __values(exceptions), exceptions_1_1 = exceptions_1.next(); !exceptions_1_1.done; exceptions_1_1 = exceptions_1.next()) {\n var ex = exceptions_1_1.value;\n var mechanism = ex.mechanism;\n\n if (mechanism && mechanism.handled === false) {\n crashed = true;\n break;\n }\n }\n } catch (e_1_1) {\n e_1 = {\n error: e_1_1\n };\n } finally {\n try {\n if (exceptions_1_1 && !exceptions_1_1.done && (_a = exceptions_1[\"return\"])) _a.call(exceptions_1);\n } finally {\n if (e_1) throw e_1.error;\n }\n }\n } // A session is updated and that session update is sent in only one of the two following scenarios:\n // 1. Session with non terminal status and 0 errors + an error occurred -> Will set error count to 1 and send update\n // 2. Session with non terminal status and 1 error + a crash occurred -> Will set status crashed and send update\n\n\n var sessionNonTerminal = session.status === SessionStatus.Ok;\n var shouldUpdateAndSend = sessionNonTerminal && session.errors === 0 || sessionNonTerminal && crashed;\n\n if (shouldUpdateAndSend) {\n session.update(__assign(__assign({}, crashed && {\n status: SessionStatus.Crashed\n }), {\n errors: session.errors || Number(errored || crashed)\n }));\n this.captureSession(session);\n }\n };\n /** Deliver captured session to Sentry */\n\n\n BaseClient.prototype._sendSession = function (session) {\n this._getBackend().sendSession(session);\n };\n /**\n * Determine if the client is finished processing. Returns a promise because it will wait `timeout` ms before saying\n * \"no\" (resolving to `false`) in order to give the client a chance to potentially finish first.\n *\n * @param timeout The time, in ms, after which to resolve to `false` if the client is still busy. Passing `0` (or not\n * passing anything) will make the promise wait as long as it takes for processing to finish before resolving to\n * `true`.\n * @returns A promise which will resolve to `true` if processing is already done or finishes before the timeout, and\n * `false` otherwise\n */\n\n\n BaseClient.prototype._isClientDoneProcessing = function (timeout) {\n var _this = this;\n\n return new SyncPromise(function (resolve) {\n var ticked = 0;\n var tick = 1;\n var interval = setInterval(function () {\n if (_this._numProcessing == 0) {\n clearInterval(interval);\n resolve(true);\n } else {\n ticked += tick;\n\n if (timeout && ticked >= timeout) {\n clearInterval(interval);\n resolve(false);\n }\n }\n }, tick);\n });\n };\n /** Returns the current backend. */\n\n\n BaseClient.prototype._getBackend = function () {\n return this._backend;\n };\n /** Determines whether this SDK is enabled and a valid Dsn is present. */\n\n\n BaseClient.prototype._isEnabled = function () {\n return this.getOptions().enabled !== false && this._dsn !== undefined;\n };\n /**\n * Adds common information to events.\n *\n * The information includes release and environment from `options`,\n * breadcrumbs and context (extra, tags and user) from the scope.\n *\n * Information that is already present in the event is never overwritten. For\n * nested objects, such as the context, keys are merged.\n *\n * @param event The original event.\n * @param hint May contain additional information about the original exception.\n * @param scope A scope containing event metadata.\n * @returns A new event with more information.\n */\n\n\n BaseClient.prototype._prepareEvent = function (event, scope, hint) {\n var _this = this;\n\n var _a = this.getOptions().normalizeDepth,\n normalizeDepth = _a === void 0 ? 3 : _a;\n\n var prepared = __assign(__assign({}, event), {\n event_id: event.event_id || (hint && hint.event_id ? hint.event_id : uuid4()),\n timestamp: event.timestamp || dateTimestampInSeconds()\n });\n\n this._applyClientOptions(prepared);\n\n this._applyIntegrationsMetadata(prepared); // If we have scope given to us, use it as the base for further modifications.\n // This allows us to prevent unnecessary copying of data if `captureContext` is not provided.\n\n\n var finalScope = scope;\n\n if (hint && hint.captureContext) {\n finalScope = Scope.clone(finalScope).update(hint.captureContext);\n } // We prepare the result here with a resolved Event.\n\n\n var result = SyncPromise.resolve(prepared); // This should be the last thing called, since we want that\n // {@link Hub.addEventProcessor} gets the finished prepared event.\n\n if (finalScope) {\n // In case we have a hub we reassign it.\n result = finalScope.applyToEvent(prepared, hint);\n }\n\n return result.then(function (evt) {\n if (typeof normalizeDepth === 'number' && normalizeDepth > 0) {\n return _this._normalizeEvent(evt, normalizeDepth);\n }\n\n return evt;\n });\n };\n /**\n * Applies `normalize` function on necessary `Event` attributes to make them safe for serialization.\n * Normalized keys:\n * - `breadcrumbs.data`\n * - `user`\n * - `contexts`\n * - `extra`\n * @param event Event\n * @returns Normalized event\n */\n\n\n BaseClient.prototype._normalizeEvent = function (event, depth) {\n if (!event) {\n return null;\n }\n\n var normalized = __assign(__assign(__assign(__assign(__assign({}, event), event.breadcrumbs && {\n breadcrumbs: event.breadcrumbs.map(function (b) {\n return __assign(__assign({}, b), b.data && {\n data: normalize(b.data, depth)\n });\n })\n }), event.user && {\n user: normalize(event.user, depth)\n }), event.contexts && {\n contexts: normalize(event.contexts, depth)\n }), event.extra && {\n extra: normalize(event.extra, depth)\n }); // event.contexts.trace stores information about a Transaction. Similarly,\n // event.spans[] stores information about child Spans. Given that a\n // Transaction is conceptually a Span, normalization should apply to both\n // Transactions and Spans consistently.\n // For now the decision is to skip normalization of Transactions and Spans,\n // so this block overwrites the normalized event to add back the original\n // Transaction information prior to normalization.\n\n\n if (event.contexts && event.contexts.trace) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n normalized.contexts.trace = event.contexts.trace;\n }\n\n var _a = this.getOptions()._experiments,\n _experiments = _a === void 0 ? {} : _a;\n\n if (_experiments.ensureNoCircularStructures) {\n return normalize(normalized);\n }\n\n return normalized;\n };\n /**\n * Enhances event using the client configuration.\n * It takes care of all \"static\" values like environment, release and `dist`,\n * as well as truncating overly long values.\n * @param event event instance to be enhanced\n */\n\n\n BaseClient.prototype._applyClientOptions = function (event) {\n var options = this.getOptions();\n var environment = options.environment,\n release = options.release,\n dist = options.dist,\n _a = options.maxValueLength,\n maxValueLength = _a === void 0 ? 250 : _a;\n\n if (!('environment' in event)) {\n event.environment = 'environment' in options ? environment : 'production';\n }\n\n if (event.release === undefined && release !== undefined) {\n event.release = release;\n }\n\n if (event.dist === undefined && dist !== undefined) {\n event.dist = dist;\n }\n\n if (event.message) {\n event.message = truncate(event.message, maxValueLength);\n }\n\n var exception = event.exception && event.exception.values && event.exception.values[0];\n\n if (exception && exception.value) {\n exception.value = truncate(exception.value, maxValueLength);\n }\n\n var request = event.request;\n\n if (request && request.url) {\n request.url = truncate(request.url, maxValueLength);\n }\n };\n /**\n * This function adds all used integrations to the SDK info in the event.\n * @param event The event that will be filled with all integrations.\n */\n\n\n BaseClient.prototype._applyIntegrationsMetadata = function (event) {\n var integrationsArray = Object.keys(this._integrations);\n\n if (integrationsArray.length > 0) {\n event.sdk = event.sdk || {};\n event.sdk.integrations = __spread(event.sdk.integrations || [], integrationsArray);\n }\n };\n /**\n * Tells the backend to send this event\n * @param event The Sentry event to send\n */\n\n\n BaseClient.prototype._sendEvent = function (event) {\n this._getBackend().sendEvent(event);\n };\n /**\n * Processes the event and logs an error in case of rejection\n * @param event\n * @param hint\n * @param scope\n */\n\n\n BaseClient.prototype._captureEvent = function (event, hint, scope) {\n return this._processEvent(event, hint, scope).then(function (finalEvent) {\n return finalEvent.event_id;\n }, function (reason) {\n logger.error(reason);\n return undefined;\n });\n };\n /**\n * Processes an event (either error or message) and sends it to Sentry.\n *\n * This also adds breadcrumbs and context information to the event. However,\n * platform specific meta data (such as the User's IP address) must be added\n * by the SDK implementor.\n *\n *\n * @param event The event to send to Sentry.\n * @param hint May contain additional information about the original exception.\n * @param scope A scope containing event metadata.\n * @returns A SyncPromise that resolves with the event or rejects in case event was/will not be send.\n */\n\n\n BaseClient.prototype._processEvent = function (event, hint, scope) {\n var _this = this;\n\n var _a, _b; // eslint-disable-next-line @typescript-eslint/unbound-method\n\n\n var _c = this.getOptions(),\n beforeSend = _c.beforeSend,\n sampleRate = _c.sampleRate;\n\n var transport = this.getTransport();\n\n if (!this._isEnabled()) {\n return SyncPromise.reject(new SentryError('SDK not enabled, will not capture event.'));\n }\n\n var isTransaction = event.type === 'transaction'; // 1.0 === 100% events are sent\n // 0.0 === 0% events are sent\n // Sampling for transaction happens somewhere else\n\n if (!isTransaction && typeof sampleRate === 'number' && Math.random() > sampleRate) {\n (_b = (_a = transport).recordLostEvent) === null || _b === void 0 ? void 0 : _b.call(_a, Outcome.SampleRate, 'event');\n return SyncPromise.reject(new SentryError(\"Discarding event because it's not included in the random sample (sampling rate = \" + sampleRate + \")\"));\n }\n\n return this._prepareEvent(event, scope, hint).then(function (prepared) {\n var _a, _b;\n\n if (prepared === null) {\n (_b = (_a = transport).recordLostEvent) === null || _b === void 0 ? void 0 : _b.call(_a, Outcome.EventProcessor, event.type || 'event');\n throw new SentryError('An event processor returned null, will not send event.');\n }\n\n var isInternalException = hint && hint.data && hint.data.__sentry__ === true;\n\n if (isInternalException || isTransaction || !beforeSend) {\n return prepared;\n }\n\n var beforeSendResult = beforeSend(prepared, hint);\n return _this._ensureBeforeSendRv(beforeSendResult);\n }).then(function (processedEvent) {\n var _a, _b;\n\n if (processedEvent === null) {\n (_b = (_a = transport).recordLostEvent) === null || _b === void 0 ? void 0 : _b.call(_a, Outcome.BeforeSend, event.type || 'event');\n throw new SentryError('`beforeSend` returned `null`, will not send event.');\n }\n\n var session = scope && scope.getSession && scope.getSession();\n\n if (!isTransaction && session) {\n _this._updateSessionFromEvent(session, processedEvent);\n }\n\n _this._sendEvent(processedEvent);\n\n return processedEvent;\n }).then(null, function (reason) {\n if (reason instanceof SentryError) {\n throw reason;\n }\n\n _this.captureException(reason, {\n data: {\n __sentry__: true\n },\n originalException: reason\n });\n\n throw new SentryError(\"Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.\\nReason: \" + reason);\n });\n };\n /**\n * Occupies the client with processing and event\n */\n\n\n BaseClient.prototype._process = function (promise) {\n var _this = this;\n\n this._numProcessing += 1;\n void promise.then(function (value) {\n _this._numProcessing -= 1;\n return value;\n }, function (reason) {\n _this._numProcessing -= 1;\n return reason;\n });\n };\n /**\n * Verifies that return value of configured `beforeSend` is of expected type.\n */\n\n\n BaseClient.prototype._ensureBeforeSendRv = function (rv) {\n var nullErr = '`beforeSend` method has to return `null` or a valid event.';\n\n if (isThenable(rv)) {\n return rv.then(function (event) {\n if (!(isPlainObject(event) || event === null)) {\n throw new SentryError(nullErr);\n }\n\n return event;\n }, function (e) {\n throw new SentryError(\"beforeSend rejected with \" + e);\n });\n } else if (!(isPlainObject(rv) || rv === null)) {\n throw new SentryError(nullErr);\n }\n\n return rv;\n };\n\n return BaseClient;\n}();\n\nexport { BaseClient };","/** The status of an event. */\n// eslint-disable-next-line import/export\nexport var Status;\n\n(function (Status) {\n /** The status could not be determined. */\n Status[\"Unknown\"] = \"unknown\";\n /** The event was skipped due to configuration or callbacks. */\n\n Status[\"Skipped\"] = \"skipped\";\n /** The event was sent to Sentry successfully. */\n\n Status[\"Success\"] = \"success\";\n /** The client is currently rate limited and will try again later. */\n\n Status[\"RateLimit\"] = \"rate_limit\";\n /** The event could not be processed. */\n\n Status[\"Invalid\"] = \"invalid\";\n /** A server-side error occurred during submission. */\n\n Status[\"Failed\"] = \"failed\";\n})(Status || (Status = {})); // eslint-disable-next-line @typescript-eslint/no-namespace, import/export\n\n\n(function (Status) {\n /**\n * Converts a HTTP status code into a {@link Status}.\n *\n * @param code The HTTP response status code.\n * @returns The send status or {@link Status.Unknown}.\n */\n function fromHttpCode(code) {\n if (code >= 200 && code < 300) {\n return Status.Success;\n }\n\n if (code === 429) {\n return Status.RateLimit;\n }\n\n if (code >= 400 && code < 500) {\n return Status.Invalid;\n }\n\n if (code >= 500) {\n return Status.Failed;\n }\n\n return Status.Unknown;\n }\n\n Status.fromHttpCode = fromHttpCode;\n})(Status || (Status = {}));","import { Status } from '@sentry/types';\nimport { SyncPromise } from '@sentry/utils';\n/** Noop transport */\n\nvar NoopTransport =\n/** @class */\nfunction () {\n function NoopTransport() {}\n /**\n * @inheritDoc\n */\n\n\n NoopTransport.prototype.sendEvent = function (_) {\n return SyncPromise.resolve({\n reason: \"NoopTransport: Event has been skipped because no Dsn is configured.\",\n status: Status.Skipped\n });\n };\n /**\n * @inheritDoc\n */\n\n\n NoopTransport.prototype.close = function (_) {\n return SyncPromise.resolve(true);\n };\n\n return NoopTransport;\n}();\n\nexport { NoopTransport };","/** JSDoc */\n// eslint-disable-next-line import/export\nexport var Severity;\n\n(function (Severity) {\n /** JSDoc */\n Severity[\"Fatal\"] = \"fatal\";\n /** JSDoc */\n\n Severity[\"Error\"] = \"error\";\n /** JSDoc */\n\n Severity[\"Warning\"] = \"warning\";\n /** JSDoc */\n\n Severity[\"Log\"] = \"log\";\n /** JSDoc */\n\n Severity[\"Info\"] = \"info\";\n /** JSDoc */\n\n Severity[\"Debug\"] = \"debug\";\n /** JSDoc */\n\n Severity[\"Critical\"] = \"critical\";\n})(Severity || (Severity = {})); // eslint-disable-next-line @typescript-eslint/no-namespace, import/export\n\n\n(function (Severity) {\n /**\n * Converts a string-based level into a {@link Severity}.\n *\n * @param level string representation of Severity\n * @returns Severity\n */\n function fromString(level) {\n switch (level) {\n case 'debug':\n return Severity.Debug;\n\n case 'info':\n return Severity.Info;\n\n case 'warn':\n case 'warning':\n return Severity.Warning;\n\n case 'error':\n return Severity.Error;\n\n case 'fatal':\n return Severity.Fatal;\n\n case 'critical':\n return Severity.Critical;\n\n case 'log':\n default:\n return Severity.Log;\n }\n }\n\n Severity.fromString = fromString;\n})(Severity || (Severity = {}));","import { logger, SentryError } from '@sentry/utils';\nimport { NoopTransport } from './transports/noop';\n/**\n * This is the base implemention of a Backend.\n * @hidden\n */\n\nvar BaseBackend =\n/** @class */\nfunction () {\n /** Creates a new backend instance. */\n function BaseBackend(options) {\n this._options = options;\n\n if (!this._options.dsn) {\n logger.warn('No DSN provided, backend will not do anything.');\n }\n\n this._transport = this._setupTransport();\n }\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\n\n\n BaseBackend.prototype.eventFromException = function (_exception, _hint) {\n throw new SentryError('Backend has to implement `eventFromException` method');\n };\n /**\n * @inheritDoc\n */\n\n\n BaseBackend.prototype.eventFromMessage = function (_message, _level, _hint) {\n throw new SentryError('Backend has to implement `eventFromMessage` method');\n };\n /**\n * @inheritDoc\n */\n\n\n BaseBackend.prototype.sendEvent = function (event) {\n void this._transport.sendEvent(event).then(null, function (reason) {\n logger.error(\"Error while sending event: \" + reason);\n });\n };\n /**\n * @inheritDoc\n */\n\n\n BaseBackend.prototype.sendSession = function (session) {\n if (!this._transport.sendSession) {\n logger.warn(\"Dropping session because custom transport doesn't implement sendSession\");\n return;\n }\n\n void this._transport.sendSession(session).then(null, function (reason) {\n logger.error(\"Error while sending session: \" + reason);\n });\n };\n /**\n * @inheritDoc\n */\n\n\n BaseBackend.prototype.getTransport = function () {\n return this._transport;\n };\n /**\n * Sets up the transport so it can be used later to send requests.\n */\n\n\n BaseBackend.prototype._setupTransport = function () {\n return new NoopTransport();\n };\n\n return BaseBackend;\n}();\n\nexport { BaseBackend };","/**\n * This was originally forked from https://github.com/occ/TraceKit, but has since been\n * largely modified and is now maintained as part of Sentry JS SDK.\n */\nimport { __assign, __read } from \"tslib\"; // global reference to slice\n\nvar UNKNOWN_FUNCTION = '?'; // Chromium based browsers: Chrome, Brave, new Opera, new Edge\n\nvar chrome = /^\\s*at (?:(.*?) ?\\()?((?:file|https?|blob|chrome-extension|address|native|eval|webpack||[-a-z]+:|.*bundle|\\/).*?)(?::(\\d+))?(?::(\\d+))?\\)?\\s*$/i; // gecko regex: `(?:bundle|\\d+\\.js)`: `bundle` is for react native, `\\d+\\.js` also but specifically for ram bundles because it\n// generates filenames without a prefix like `file://` the filenames in the stacktrace are just 42.js\n// We need this specific case for now because we want no other regex to match.\n\nvar gecko = /^\\s*(.*?)(?:\\((.*?)\\))?(?:^|@)?((?:file|https?|blob|chrome|webpack|resource|moz-extension|capacitor).*?:\\/.*?|\\[native code\\]|[^@]*(?:bundle|\\d+\\.js)|\\/[\\w\\-. /=]+)(?::(\\d+))?(?::(\\d+))?\\s*$/i;\nvar winjs = /^\\s*at (?:((?:\\[object object\\])?.+) )?\\(?((?:file|ms-appx|https?|webpack|blob):.*?):(\\d+)(?::(\\d+))?\\)?\\s*$/i;\nvar geckoEval = /(\\S+) line (\\d+)(?: > eval line \\d+)* > eval/i;\nvar chromeEval = /\\((\\S*)(?::(\\d+))(?::(\\d+))\\)/; // Based on our own mapping pattern - https://github.com/getsentry/sentry/blob/9f08305e09866c8bd6d0c24f5b0aabdd7dd6c59c/src/sentry/lang/javascript/errormapping.py#L83-L108\n\nvar reactMinifiedRegexp = /Minified React error #\\d+;/i;\n/** JSDoc */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\n\nexport function computeStackTrace(ex) {\n var stack = null;\n var popSize = 0;\n\n if (ex) {\n if (typeof ex.framesToPop === 'number') {\n popSize = ex.framesToPop;\n } else if (reactMinifiedRegexp.test(ex.message)) {\n popSize = 1;\n }\n }\n\n try {\n // This must be tried first because Opera 10 *destroys*\n // its stacktrace property if you try to access the stack\n // property first!!\n stack = computeStackTraceFromStacktraceProp(ex);\n\n if (stack) {\n return popFrames(stack, popSize);\n }\n } catch (e) {// no-empty\n }\n\n try {\n stack = computeStackTraceFromStackProp(ex);\n\n if (stack) {\n return popFrames(stack, popSize);\n }\n } catch (e) {// no-empty\n }\n\n return {\n message: extractMessage(ex),\n name: ex && ex.name,\n stack: [],\n failed: true\n };\n}\n/** JSDoc */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any, complexity\n\nfunction computeStackTraceFromStackProp(ex) {\n var _a, _b;\n\n if (!ex || !ex.stack) {\n return null;\n }\n\n var stack = [];\n var lines = ex.stack.split('\\n');\n var isEval;\n var submatch;\n var parts;\n var element;\n\n for (var i = 0; i < lines.length; ++i) {\n if (parts = chrome.exec(lines[i])) {\n var isNative = parts[2] && parts[2].indexOf('native') === 0; // start of line\n\n isEval = parts[2] && parts[2].indexOf('eval') === 0; // start of line\n\n if (isEval && (submatch = chromeEval.exec(parts[2]))) {\n // throw out eval line/column and use top-most line/column number\n parts[2] = submatch[1]; // url\n\n parts[3] = submatch[2]; // line\n\n parts[4] = submatch[3]; // column\n } // Arpad: Working with the regexp above is super painful. it is quite a hack, but just stripping the `address at `\n // prefix here seems like the quickest solution for now.\n\n\n var url = parts[2] && parts[2].indexOf('address at ') === 0 ? parts[2].substr('address at '.length) : parts[2]; // Kamil: One more hack won't hurt us right? Understanding and adding more rules on top of these regexps right now\n // would be way too time consuming. (TODO: Rewrite whole RegExp to be more readable)\n\n var func = parts[1] || UNKNOWN_FUNCTION;\n _a = __read(extractSafariExtensionDetails(func, url), 2), func = _a[0], url = _a[1];\n element = {\n url: url,\n func: func,\n args: isNative ? [parts[2]] : [],\n line: parts[3] ? +parts[3] : null,\n column: parts[4] ? +parts[4] : null\n };\n } else if (parts = winjs.exec(lines[i])) {\n element = {\n url: parts[2],\n func: parts[1] || UNKNOWN_FUNCTION,\n args: [],\n line: +parts[3],\n column: parts[4] ? +parts[4] : null\n };\n } else if (parts = gecko.exec(lines[i])) {\n isEval = parts[3] && parts[3].indexOf(' > eval') > -1;\n\n if (isEval && (submatch = geckoEval.exec(parts[3]))) {\n // throw out eval line/column and use top-most line number\n parts[1] = parts[1] || \"eval\";\n parts[3] = submatch[1];\n parts[4] = submatch[2];\n parts[5] = ''; // no column when eval\n } else if (i === 0 && !parts[5] && ex.columnNumber !== void 0) {\n // FireFox uses this awesome columnNumber property for its top frame\n // Also note, Firefox's column number is 0-based and everything else expects 1-based,\n // so adding 1\n // NOTE: this hack doesn't work if top-most frame is eval\n stack[0].column = ex.columnNumber + 1;\n }\n\n var url = parts[3];\n var func = parts[1] || UNKNOWN_FUNCTION;\n _b = __read(extractSafariExtensionDetails(func, url), 2), func = _b[0], url = _b[1];\n element = {\n url: url,\n func: func,\n args: parts[2] ? parts[2].split(',') : [],\n line: parts[4] ? +parts[4] : null,\n column: parts[5] ? +parts[5] : null\n };\n } else {\n continue;\n }\n\n if (!element.func && element.line) {\n element.func = UNKNOWN_FUNCTION;\n }\n\n stack.push(element);\n }\n\n if (!stack.length) {\n return null;\n }\n\n return {\n message: extractMessage(ex),\n name: ex.name,\n stack: stack\n };\n}\n/** JSDoc */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\n\n\nfunction computeStackTraceFromStacktraceProp(ex) {\n if (!ex || !ex.stacktrace) {\n return null;\n } // Access and store the stacktrace property before doing ANYTHING\n // else to it because Opera is not very good at providing it\n // reliably in other circumstances.\n\n\n var stacktrace = ex.stacktrace;\n var opera10Regex = / line (\\d+).*script (?:in )?(\\S+)(?:: in function (\\S+))?$/i;\n var opera11Regex = / line (\\d+), column (\\d+)\\s*(?:in (?:]+)>|([^)]+))\\((.*)\\))? in (.*):\\s*$/i;\n var lines = stacktrace.split('\\n');\n var stack = [];\n var parts;\n\n for (var line = 0; line < lines.length; line += 2) {\n var element = null;\n\n if (parts = opera10Regex.exec(lines[line])) {\n element = {\n url: parts[2],\n func: parts[3],\n args: [],\n line: +parts[1],\n column: null\n };\n } else if (parts = opera11Regex.exec(lines[line])) {\n element = {\n url: parts[6],\n func: parts[3] || parts[4],\n args: parts[5] ? parts[5].split(',') : [],\n line: +parts[1],\n column: +parts[2]\n };\n }\n\n if (element) {\n if (!element.func && element.line) {\n element.func = UNKNOWN_FUNCTION;\n }\n\n stack.push(element);\n }\n }\n\n if (!stack.length) {\n return null;\n }\n\n return {\n message: extractMessage(ex),\n name: ex.name,\n stack: stack\n };\n}\n/**\n * Safari web extensions, starting version unknown, can produce \"frames-only\" stacktraces.\n * What it means, is that instead of format like:\n *\n * Error: wat\n * at function@url:row:col\n * at function@url:row:col\n * at function@url:row:col\n *\n * it produces something like:\n *\n * function@url:row:col\n * function@url:row:col\n * function@url:row:col\n *\n * Because of that, it won't be captured by `chrome` RegExp and will fall into `Gecko` branch.\n * This function is extracted so that we can use it in both places without duplicating the logic.\n * Unfortunatelly \"just\" changing RegExp is too complicated now and making it pass all tests\n * and fix this case seems like an impossible, or at least way too time-consuming task.\n */\n\n\nvar extractSafariExtensionDetails = function extractSafariExtensionDetails(func, url) {\n var isSafariExtension = func.indexOf('safari-extension') !== -1;\n var isSafariWebExtension = func.indexOf('safari-web-extension') !== -1;\n return isSafariExtension || isSafariWebExtension ? [func.indexOf('@') !== -1 ? func.split('@')[0] : UNKNOWN_FUNCTION, isSafariExtension ? \"safari-extension:\" + url : \"safari-web-extension:\" + url] : [func, url];\n};\n/** Remove N number of frames from the stack */\n\n\nfunction popFrames(stacktrace, popSize) {\n try {\n return __assign(__assign({}, stacktrace), {\n stack: stacktrace.stack.slice(popSize)\n });\n } catch (e) {\n return stacktrace;\n }\n}\n/**\n * There are cases where stacktrace.message is an Event object\n * https://github.com/getsentry/sentry-javascript/issues/1949\n * In this specific case we try to extract stacktrace.message.error.message\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\n\n\nfunction extractMessage(ex) {\n var message = ex && ex.message;\n\n if (!message) {\n return 'No error message';\n }\n\n if (message.error && typeof message.error.message === 'string') {\n return message.error.message;\n }\n\n return message;\n}","import { extractExceptionKeysForMessage, isEvent, normalizeToSize } from '@sentry/utils';\nimport { computeStackTrace } from './tracekit';\nvar STACKTRACE_LIMIT = 50;\n/**\n * This function creates an exception from an TraceKitStackTrace\n * @param stacktrace TraceKitStackTrace that will be converted to an exception\n * @hidden\n */\n\nexport function exceptionFromStacktrace(stacktrace) {\n var frames = prepareFramesForEvent(stacktrace.stack);\n var exception = {\n type: stacktrace.name,\n value: stacktrace.message\n };\n\n if (frames && frames.length) {\n exception.stacktrace = {\n frames: frames\n };\n }\n\n if (exception.type === undefined && exception.value === '') {\n exception.value = 'Unrecoverable error caught';\n }\n\n return exception;\n}\n/**\n * @hidden\n */\n\nexport function eventFromPlainObject(exception, syntheticException, rejection) {\n var event = {\n exception: {\n values: [{\n type: isEvent(exception) ? exception.constructor.name : rejection ? 'UnhandledRejection' : 'Error',\n value: \"Non-Error \" + (rejection ? 'promise rejection' : 'exception') + \" captured with keys: \" + extractExceptionKeysForMessage(exception)\n }]\n },\n extra: {\n __serialized__: normalizeToSize(exception)\n }\n };\n\n if (syntheticException) {\n var stacktrace = computeStackTrace(syntheticException);\n var frames_1 = prepareFramesForEvent(stacktrace.stack);\n event.stacktrace = {\n frames: frames_1\n };\n }\n\n return event;\n}\n/**\n * @hidden\n */\n\nexport function eventFromStacktrace(stacktrace) {\n var exception = exceptionFromStacktrace(stacktrace);\n return {\n exception: {\n values: [exception]\n }\n };\n}\n/**\n * @hidden\n */\n\nexport function prepareFramesForEvent(stack) {\n if (!stack || !stack.length) {\n return [];\n }\n\n var localStack = stack;\n var firstFrameFunction = localStack[0].func || '';\n var lastFrameFunction = localStack[localStack.length - 1].func || ''; // If stack starts with one of our API calls, remove it (starts, meaning it's the top of the stack - aka last call)\n\n if (firstFrameFunction.indexOf('captureMessage') !== -1 || firstFrameFunction.indexOf('captureException') !== -1) {\n localStack = localStack.slice(1);\n } // If stack ends with one of our internal API calls, remove it (ends, meaning it's the bottom of the stack - aka top-most call)\n\n\n if (lastFrameFunction.indexOf('sentryWrapped') !== -1) {\n localStack = localStack.slice(0, -1);\n } // The frame where the crash happened, should be the last entry in the array\n\n\n return localStack.slice(0, STACKTRACE_LIMIT).map(function (frame) {\n return {\n colno: frame.column === null ? undefined : frame.column,\n filename: frame.url || localStack[0].url,\n \"function\": frame.func || '?',\n in_app: true,\n lineno: frame.line === null ? undefined : frame.line\n };\n }).reverse();\n}","import { __assign } from \"tslib\";\nimport { Severity } from '@sentry/types';\nimport { addExceptionMechanism, addExceptionTypeValue, isDOMError, isDOMException, isError, isErrorEvent, isEvent, isPlainObject, SyncPromise } from '@sentry/utils';\nimport { eventFromPlainObject, eventFromStacktrace, prepareFramesForEvent } from './parsers';\nimport { computeStackTrace } from './tracekit';\n/**\n * Builds and Event from a Exception\n * @hidden\n */\n\nexport function eventFromException(options, exception, hint) {\n var syntheticException = hint && hint.syntheticException || undefined;\n var event = eventFromUnknownInput(exception, syntheticException, {\n attachStacktrace: options.attachStacktrace\n });\n addExceptionMechanism(event); // defaults to { type: 'generic', handled: true }\n\n event.level = Severity.Error;\n\n if (hint && hint.event_id) {\n event.event_id = hint.event_id;\n }\n\n return SyncPromise.resolve(event);\n}\n/**\n * Builds and Event from a Message\n * @hidden\n */\n\nexport function eventFromMessage(options, message, level, hint) {\n if (level === void 0) {\n level = Severity.Info;\n }\n\n var syntheticException = hint && hint.syntheticException || undefined;\n var event = eventFromString(message, syntheticException, {\n attachStacktrace: options.attachStacktrace\n });\n event.level = level;\n\n if (hint && hint.event_id) {\n event.event_id = hint.event_id;\n }\n\n return SyncPromise.resolve(event);\n}\n/**\n * @hidden\n */\n\nexport function eventFromUnknownInput(exception, syntheticException, options) {\n if (options === void 0) {\n options = {};\n }\n\n var event;\n\n if (isErrorEvent(exception) && exception.error) {\n // If it is an ErrorEvent with `error` property, extract it to get actual Error\n var errorEvent = exception; // eslint-disable-next-line no-param-reassign\n\n exception = errorEvent.error;\n event = eventFromStacktrace(computeStackTrace(exception));\n return event;\n } // If it is a `DOMError` (which is a legacy API, but still supported in some browsers) then we just extract the name\n // and message, as it doesn't provide anything else. According to the spec, all `DOMExceptions` should also be\n // `Error`s, but that's not the case in IE11, so in that case we treat it the same as we do a `DOMError`.\n //\n // https://developer.mozilla.org/en-US/docs/Web/API/DOMError\n // https://developer.mozilla.org/en-US/docs/Web/API/DOMException\n // https://webidl.spec.whatwg.org/#es-DOMException-specialness\n\n\n if (isDOMError(exception) || isDOMException(exception)) {\n var domException = exception;\n\n if ('stack' in exception) {\n event = eventFromStacktrace(computeStackTrace(exception));\n } else {\n var name_1 = domException.name || (isDOMError(domException) ? 'DOMError' : 'DOMException');\n var message = domException.message ? name_1 + \": \" + domException.message : name_1;\n event = eventFromString(message, syntheticException, options);\n addExceptionTypeValue(event, message);\n }\n\n if ('code' in domException) {\n event.tags = __assign(__assign({}, event.tags), {\n 'DOMException.code': \"\" + domException.code\n });\n }\n\n return event;\n }\n\n if (isError(exception)) {\n // we have a real Error object, do nothing\n event = eventFromStacktrace(computeStackTrace(exception));\n return event;\n }\n\n if (isPlainObject(exception) || isEvent(exception)) {\n // If it is plain Object or Event, serialize it manually and extract options\n // This will allow us to group events based on top-level keys\n // which is much better than creating new group when any key/value change\n var objectException = exception;\n event = eventFromPlainObject(objectException, syntheticException, options.rejection);\n addExceptionMechanism(event, {\n synthetic: true\n });\n return event;\n } // If none of previous checks were valid, then it means that it's not:\n // - an instance of DOMError\n // - an instance of DOMException\n // - an instance of Event\n // - an instance of Error\n // - a valid ErrorEvent (one with an error property)\n // - a plain Object\n //\n // So bail out and capture it as a simple message:\n\n\n event = eventFromString(exception, syntheticException, options);\n addExceptionTypeValue(event, \"\" + exception, undefined);\n addExceptionMechanism(event, {\n synthetic: true\n });\n return event;\n}\n/**\n * @hidden\n */\n\nexport function eventFromString(input, syntheticException, options) {\n if (options === void 0) {\n options = {};\n }\n\n var event = {\n message: input\n };\n\n if (options.attachStacktrace && syntheticException) {\n var stacktrace = computeStackTrace(syntheticException);\n var frames_1 = prepareFramesForEvent(stacktrace.stack);\n event.stacktrace = {\n frames: frames_1\n };\n }\n\n return event;\n}","import { __assign, __read, __rest, __spread } from \"tslib\";\n/** Extract sdk info from from the API metadata */\n\nfunction getSdkMetadataForEnvelopeHeader(api) {\n if (!api.metadata || !api.metadata.sdk) {\n return;\n }\n\n var _a = api.metadata.sdk,\n name = _a.name,\n version = _a.version;\n return {\n name: name,\n version: version\n };\n}\n/**\n * Apply SdkInfo (name, version, packages, integrations) to the corresponding event key.\n * Merge with existing data if any.\n **/\n\n\nfunction enhanceEventWithSdkInfo(event, sdkInfo) {\n if (!sdkInfo) {\n return event;\n }\n\n event.sdk = event.sdk || {};\n event.sdk.name = event.sdk.name || sdkInfo.name;\n event.sdk.version = event.sdk.version || sdkInfo.version;\n event.sdk.integrations = __spread(event.sdk.integrations || [], sdkInfo.integrations || []);\n event.sdk.packages = __spread(event.sdk.packages || [], sdkInfo.packages || []);\n return event;\n}\n/** Creates a SentryRequest from a Session. */\n\n\nexport function sessionToSentryRequest(session, api) {\n var sdkInfo = getSdkMetadataForEnvelopeHeader(api);\n var envelopeHeaders = JSON.stringify(__assign(__assign({\n sent_at: new Date().toISOString()\n }, sdkInfo && {\n sdk: sdkInfo\n }), api.forceEnvelope() && {\n dsn: api.getDsn().toString()\n })); // I know this is hacky but we don't want to add `session` to request type since it's never rate limited\n\n var type = 'aggregates' in session ? 'sessions' : 'session';\n var itemHeaders = JSON.stringify({\n type: type\n });\n return {\n body: envelopeHeaders + \"\\n\" + itemHeaders + \"\\n\" + JSON.stringify(session),\n type: type,\n url: api.getEnvelopeEndpointWithUrlEncodedAuth()\n };\n}\n/** Creates a SentryRequest from an event. */\n\nexport function eventToSentryRequest(event, api) {\n var sdkInfo = getSdkMetadataForEnvelopeHeader(api);\n var eventType = event.type || 'event';\n var useEnvelope = eventType === 'transaction' || api.forceEnvelope();\n\n var _a = event.debug_meta || {},\n transactionSampling = _a.transactionSampling,\n metadata = __rest(_a, [\"transactionSampling\"]);\n\n var _b = transactionSampling || {},\n samplingMethod = _b.method,\n sampleRate = _b.rate;\n\n if (Object.keys(metadata).length === 0) {\n delete event.debug_meta;\n } else {\n event.debug_meta = metadata;\n }\n\n var req = {\n body: JSON.stringify(sdkInfo ? enhanceEventWithSdkInfo(event, api.metadata.sdk) : event),\n type: eventType,\n url: useEnvelope ? api.getEnvelopeEndpointWithUrlEncodedAuth() : api.getStoreEndpointWithUrlEncodedAuth()\n }; // https://develop.sentry.dev/sdk/envelopes/\n // Since we don't need to manipulate envelopes nor store them, there is no\n // exported concept of an Envelope with operations including serialization and\n // deserialization. Instead, we only implement a minimal subset of the spec to\n // serialize events inline here.\n\n if (useEnvelope) {\n var envelopeHeaders = JSON.stringify(__assign(__assign({\n event_id: event.event_id,\n sent_at: new Date().toISOString()\n }, sdkInfo && {\n sdk: sdkInfo\n }), api.forceEnvelope() && {\n dsn: api.getDsn().toString()\n }));\n var itemHeaders = JSON.stringify({\n type: eventType,\n // TODO: Right now, sampleRate may or may not be defined (it won't be in the cases of inheritance and\n // explicitly-set sampling decisions). Are we good with that?\n sample_rates: [{\n id: samplingMethod,\n rate: sampleRate\n }]\n }); // The trailing newline is optional. We intentionally don't send it to avoid\n // sending unnecessary bytes.\n //\n // const envelope = `${envelopeHeaders}\\n${itemHeaders}\\n${req.body}\\n`;\n\n var envelope = envelopeHeaders + \"\\n\" + itemHeaders + \"\\n\" + req.body;\n req.body = envelope;\n }\n\n return req;\n}","import { Dsn, urlEncode } from '@sentry/utils';\nvar SENTRY_API_VERSION = '7';\n/**\n * Helper class to provide urls, headers and metadata that can be used to form\n * different types of requests to Sentry endpoints.\n * Supports both envelopes and regular event requests.\n **/\n\nvar API =\n/** @class */\nfunction () {\n /** Create a new instance of API */\n function API(dsn, metadata, tunnel) {\n if (metadata === void 0) {\n metadata = {};\n }\n\n this.dsn = dsn;\n this._dsnObject = new Dsn(dsn);\n this.metadata = metadata;\n this._tunnel = tunnel;\n }\n /** Returns the Dsn object. */\n\n\n API.prototype.getDsn = function () {\n return this._dsnObject;\n };\n /** Does this transport force envelopes? */\n\n\n API.prototype.forceEnvelope = function () {\n return !!this._tunnel;\n };\n /** Returns the prefix to construct Sentry ingestion API endpoints. */\n\n\n API.prototype.getBaseApiEndpoint = function () {\n var dsn = this.getDsn();\n var protocol = dsn.protocol ? dsn.protocol + \":\" : '';\n var port = dsn.port ? \":\" + dsn.port : '';\n return protocol + \"//\" + dsn.host + port + (dsn.path ? \"/\" + dsn.path : '') + \"/api/\";\n };\n /** Returns the store endpoint URL. */\n\n\n API.prototype.getStoreEndpoint = function () {\n return this._getIngestEndpoint('store');\n };\n /**\n * Returns the store endpoint URL with auth in the query string.\n *\n * Sending auth as part of the query string and not as custom HTTP headers avoids CORS preflight requests.\n */\n\n\n API.prototype.getStoreEndpointWithUrlEncodedAuth = function () {\n return this.getStoreEndpoint() + \"?\" + this._encodedAuth();\n };\n /**\n * Returns the envelope endpoint URL with auth in the query string.\n *\n * Sending auth as part of the query string and not as custom HTTP headers avoids CORS preflight requests.\n */\n\n\n API.prototype.getEnvelopeEndpointWithUrlEncodedAuth = function () {\n if (this.forceEnvelope()) {\n return this._tunnel;\n }\n\n return this._getEnvelopeEndpoint() + \"?\" + this._encodedAuth();\n };\n /** Returns only the path component for the store endpoint. */\n\n\n API.prototype.getStoreEndpointPath = function () {\n var dsn = this.getDsn();\n return (dsn.path ? \"/\" + dsn.path : '') + \"/api/\" + dsn.projectId + \"/store/\";\n };\n /**\n * Returns an object that can be used in request headers.\n * This is needed for node and the old /store endpoint in sentry\n */\n\n\n API.prototype.getRequestHeaders = function (clientName, clientVersion) {\n // CHANGE THIS to use metadata but keep clientName and clientVersion compatible\n var dsn = this.getDsn();\n var header = [\"Sentry sentry_version=\" + SENTRY_API_VERSION];\n header.push(\"sentry_client=\" + clientName + \"/\" + clientVersion);\n header.push(\"sentry_key=\" + dsn.publicKey);\n\n if (dsn.pass) {\n header.push(\"sentry_secret=\" + dsn.pass);\n }\n\n return {\n 'Content-Type': 'application/json',\n 'X-Sentry-Auth': header.join(', ')\n };\n };\n /** Returns the url to the report dialog endpoint. */\n\n\n API.prototype.getReportDialogEndpoint = function (dialogOptions) {\n if (dialogOptions === void 0) {\n dialogOptions = {};\n }\n\n var dsn = this.getDsn();\n var endpoint = this.getBaseApiEndpoint() + \"embed/error-page/\";\n var encodedOptions = [];\n encodedOptions.push(\"dsn=\" + dsn.toString());\n\n for (var key in dialogOptions) {\n if (key === 'dsn') {\n continue;\n }\n\n if (key === 'user') {\n if (!dialogOptions.user) {\n continue;\n }\n\n if (dialogOptions.user.name) {\n encodedOptions.push(\"name=\" + encodeURIComponent(dialogOptions.user.name));\n }\n\n if (dialogOptions.user.email) {\n encodedOptions.push(\"email=\" + encodeURIComponent(dialogOptions.user.email));\n }\n } else {\n encodedOptions.push(encodeURIComponent(key) + \"=\" + encodeURIComponent(dialogOptions[key]));\n }\n }\n\n if (encodedOptions.length) {\n return endpoint + \"?\" + encodedOptions.join('&');\n }\n\n return endpoint;\n };\n /** Returns the envelope endpoint URL. */\n\n\n API.prototype._getEnvelopeEndpoint = function () {\n return this._getIngestEndpoint('envelope');\n };\n /** Returns the ingest API endpoint for target. */\n\n\n API.prototype._getIngestEndpoint = function (target) {\n if (this._tunnel) {\n return this._tunnel;\n }\n\n var base = this.getBaseApiEndpoint();\n var dsn = this.getDsn();\n return \"\" + base + dsn.projectId + \"/\" + target + \"/\";\n };\n /** Returns a URL-encoded string with auth config suitable for a query string. */\n\n\n API.prototype._encodedAuth = function () {\n var dsn = this.getDsn();\n var auth = {\n // We send only the minimum set of required information. See\n // https://github.com/getsentry/sentry-javascript/issues/2572.\n sentry_key: dsn.publicKey,\n sentry_version: SENTRY_API_VERSION\n };\n return urlEncode(auth);\n };\n\n return API;\n}();\n\nexport { API };","import { SentryError } from './error';\nimport { SyncPromise } from './syncpromise';\n/** A simple queue that holds promises. */\n\nvar PromiseBuffer =\n/** @class */\nfunction () {\n function PromiseBuffer(_limit) {\n this._limit = _limit;\n /** Internal set of queued Promises */\n\n this._buffer = [];\n }\n /**\n * Says if the buffer is ready to take more requests\n */\n\n\n PromiseBuffer.prototype.isReady = function () {\n return this._limit === undefined || this.length() < this._limit;\n };\n /**\n * Add a promise (representing an in-flight action) to the queue, and set it to remove itself on fulfillment.\n *\n * @param taskProducer A function producing any PromiseLike; In previous versions this used to be `task:\n * PromiseLike`, but under that model, Promises were instantly created on the call-site and their executor\n * functions therefore ran immediately. Thus, even if the buffer was full, the action still happened. By\n * requiring the promise to be wrapped in a function, we can defer promise creation until after the buffer\n * limit check.\n * @returns The original promise.\n */\n\n\n PromiseBuffer.prototype.add = function (taskProducer) {\n var _this = this;\n\n if (!this.isReady()) {\n return SyncPromise.reject(new SentryError('Not adding Promise due to buffer limit reached.'));\n } // start the task and add its promise to the queue\n\n\n var task = taskProducer();\n\n if (this._buffer.indexOf(task) === -1) {\n this._buffer.push(task);\n }\n\n void task.then(function () {\n return _this.remove(task);\n }) // Use `then(null, rejectionHandler)` rather than `catch(rejectionHandler)` so that we can use `PromiseLike`\n // rather than `Promise`. `PromiseLike` doesn't have a `.catch` method, making its polyfill smaller. (ES5 didn't\n // have promises, so TS has to polyfill when down-compiling.)\n .then(null, function () {\n return _this.remove(task).then(null, function () {// We have to add another catch here because `this.remove()` starts a new promise chain.\n });\n });\n return task;\n };\n /**\n * Remove a promise from the queue.\n *\n * @param task Can be any PromiseLike\n * @returns Removed promise.\n */\n\n\n PromiseBuffer.prototype.remove = function (task) {\n var removedTask = this._buffer.splice(this._buffer.indexOf(task), 1)[0];\n\n return removedTask;\n };\n /**\n * This function returns the number of unresolved promises in the queue.\n */\n\n\n PromiseBuffer.prototype.length = function () {\n return this._buffer.length;\n };\n /**\n * Wait for all promises in the queue to resolve or for timeout to expire, whichever comes first.\n *\n * @param timeout The time, in ms, after which to resolve to `false` if the queue is still non-empty. Passing `0` (or\n * not passing anything) will make the promise wait as long as it takes for the queue to drain before resolving to\n * `true`.\n * @returns A promise which will resolve to `true` if the queue is already empty or drains before the timeout, and\n * `false` otherwise\n */\n\n\n PromiseBuffer.prototype.drain = function (timeout) {\n var _this = this;\n\n return new SyncPromise(function (resolve) {\n // wait for `timeout` ms and then resolve to `false` (if not cancelled first)\n var capturedSetTimeout = setTimeout(function () {\n if (timeout && timeout > 0) {\n resolve(false);\n }\n }, timeout); // if all promises resolve in time, cancel the timer and resolve to `true`\n\n void SyncPromise.all(_this._buffer).then(function () {\n clearTimeout(capturedSetTimeout);\n resolve(true);\n }).then(null, function () {\n resolve(true);\n });\n });\n };\n\n return PromiseBuffer;\n}();\n\nexport { PromiseBuffer };","import { forget, getGlobalObject, isNativeFetch, logger, supportsFetch } from '@sentry/utils';\nvar global = getGlobalObject();\nvar cachedFetchImpl;\n/**\n * A special usecase for incorrectly wrapped Fetch APIs in conjunction with ad-blockers.\n * Whenever someone wraps the Fetch API and returns the wrong promise chain,\n * this chain becomes orphaned and there is no possible way to capture it's rejections\n * other than allowing it bubble up to this very handler. eg.\n *\n * const f = window.fetch;\n * window.fetch = function () {\n * const p = f.apply(this, arguments);\n *\n * p.then(function() {\n * console.log('hi.');\n * });\n *\n * return p;\n * }\n *\n * `p.then(function () { ... })` is producing a completely separate promise chain,\n * however, what's returned is `p` - the result of original `fetch` call.\n *\n * This mean, that whenever we use the Fetch API to send our own requests, _and_\n * some ad-blocker blocks it, this orphaned chain will _always_ reject,\n * effectively causing another event to be captured.\n * This makes a whole process become an infinite loop, which we need to somehow\n * deal with, and break it in one way or another.\n *\n * To deal with this issue, we are making sure that we _always_ use the real\n * browser Fetch API, instead of relying on what `window.fetch` exposes.\n * The only downside to this would be missing our own requests as breadcrumbs,\n * but because we are already not doing this, it should be just fine.\n *\n * Possible failed fetch error messages per-browser:\n *\n * Chrome: Failed to fetch\n * Edge: Failed to Fetch\n * Firefox: NetworkError when attempting to fetch resource\n * Safari: resource blocked by content blocker\n */\n\nexport function getNativeFetchImplementation() {\n var _a, _b;\n\n if (cachedFetchImpl) {\n return cachedFetchImpl;\n }\n /* eslint-disable @typescript-eslint/unbound-method */\n // Fast path to avoid DOM I/O\n\n\n if (isNativeFetch(global.fetch)) {\n return cachedFetchImpl = global.fetch.bind(global);\n }\n\n var document = global.document;\n var fetchImpl = global.fetch; // eslint-disable-next-line deprecation/deprecation\n\n if (typeof ((_a = document) === null || _a === void 0 ? void 0 : _a.createElement) === \"function\") {\n try {\n var sandbox = document.createElement('iframe');\n sandbox.hidden = true;\n document.head.appendChild(sandbox);\n\n if ((_b = sandbox.contentWindow) === null || _b === void 0 ? void 0 : _b.fetch) {\n fetchImpl = sandbox.contentWindow.fetch;\n }\n\n document.head.removeChild(sandbox);\n } catch (e) {\n logger.warn('Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ', e);\n }\n }\n\n return cachedFetchImpl = fetchImpl.bind(global);\n /* eslint-enable @typescript-eslint/unbound-method */\n}\n/**\n * Sends sdk client report using sendBeacon or fetch as a fallback if available\n *\n * @param url report endpoint\n * @param body report payload\n */\n\nexport function sendReport(url, body) {\n var isRealNavigator = Object.prototype.toString.call(global && global.navigator) === '[object Navigator]';\n var hasSendBeacon = isRealNavigator && typeof global.navigator.sendBeacon === 'function';\n\n if (hasSendBeacon) {\n // Prevent illegal invocations - https://xgwang.me/posts/you-may-not-know-beacon/#it-may-throw-error%2C-be-sure-to-catch\n var sendBeacon = global.navigator.sendBeacon.bind(global.navigator);\n return sendBeacon(url, body);\n }\n\n if (supportsFetch()) {\n var fetch_1 = getNativeFetchImplementation();\n return forget(fetch_1(url, {\n body: body,\n method: 'POST',\n credentials: 'omit',\n keepalive: true\n }));\n }\n}","/**\n * Consumes the promise and logs the error when it rejects.\n * @param promise A promise to forget.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function forget(promise) {\n void promise.then(null, function (e) {\n // TODO: Use a better logging mechanism\n // eslint-disable-next-line no-console\n console.error(e);\n });\n}","import { __assign, __read, __values } from \"tslib\";\nimport { API } from '@sentry/core';\nimport { Status } from '@sentry/types';\nimport { dateTimestampInSeconds, getGlobalObject, logger, parseRetryAfterHeader, PromiseBuffer, SentryError } from '@sentry/utils';\nimport { sendReport } from './utils';\nvar CATEGORY_MAPPING = {\n event: 'error',\n transaction: 'transaction',\n session: 'session',\n attachment: 'attachment'\n};\nvar global = getGlobalObject();\n/** Base Transport class implementation */\n\nvar BaseTransport =\n/** @class */\nfunction () {\n function BaseTransport(options) {\n var _this = this;\n\n this.options = options;\n /** A simple buffer holding all requests. */\n\n this._buffer = new PromiseBuffer(30);\n /** Locks transport after receiving rate limits in a response */\n\n this._rateLimits = {};\n this._outcomes = {};\n this._api = new API(options.dsn, options._metadata, options.tunnel); // eslint-disable-next-line deprecation/deprecation\n\n this.url = this._api.getStoreEndpointWithUrlEncodedAuth();\n\n if (this.options.sendClientReports && global.document) {\n global.document.addEventListener('visibilitychange', function () {\n if (global.document.visibilityState === 'hidden') {\n _this._flushOutcomes();\n }\n });\n }\n }\n /**\n * @inheritDoc\n */\n\n\n BaseTransport.prototype.sendEvent = function (_) {\n throw new SentryError('Transport Class has to implement `sendEvent` method');\n };\n /**\n * @inheritDoc\n */\n\n\n BaseTransport.prototype.close = function (timeout) {\n return this._buffer.drain(timeout);\n };\n /**\n * @inheritDoc\n */\n\n\n BaseTransport.prototype.recordLostEvent = function (reason, category) {\n var _a;\n\n if (!this.options.sendClientReports) {\n return;\n } // We want to track each category (event, transaction, session) separately\n // but still keep the distinction between different type of outcomes.\n // We could use nested maps, but it's much easier to read and type this way.\n // A correct type for map-based implementation if we want to go that route\n // would be `Partial>>>`\n\n\n var key = CATEGORY_MAPPING[category] + \":\" + reason;\n logger.log(\"Adding outcome: \" + key);\n this._outcomes[key] = (_a = this._outcomes[key], _a !== null && _a !== void 0 ? _a : 0) + 1;\n };\n /**\n * Send outcomes as an envelope\n */\n\n\n BaseTransport.prototype._flushOutcomes = function () {\n if (!this.options.sendClientReports) {\n return;\n }\n\n var outcomes = this._outcomes;\n this._outcomes = {}; // Nothing to send\n\n if (!Object.keys(outcomes).length) {\n logger.log('No outcomes to flush');\n return;\n }\n\n logger.log(\"Flushing outcomes:\\n\" + JSON.stringify(outcomes, null, 2));\n\n var url = this._api.getEnvelopeEndpointWithUrlEncodedAuth(); // Envelope header is required to be at least an empty object\n\n\n var envelopeHeader = JSON.stringify(__assign({}, this.options.tunnel && {\n dsn: this._api.getDsn().toString()\n }));\n var itemHeaders = JSON.stringify({\n type: 'client_report'\n });\n var item = JSON.stringify({\n timestamp: dateTimestampInSeconds(),\n discarded_events: Object.keys(outcomes).map(function (key) {\n var _a = __read(key.split(':'), 2),\n category = _a[0],\n reason = _a[1];\n\n return {\n reason: reason,\n category: category,\n quantity: outcomes[key]\n };\n })\n });\n var envelope = envelopeHeader + \"\\n\" + itemHeaders + \"\\n\" + item;\n\n try {\n sendReport(url, envelope);\n } catch (e) {\n logger.error(e);\n }\n };\n /**\n * Handle Sentry repsonse for promise-based transports.\n */\n\n\n BaseTransport.prototype._handleResponse = function (_a) {\n var requestType = _a.requestType,\n response = _a.response,\n headers = _a.headers,\n resolve = _a.resolve,\n reject = _a.reject;\n var status = Status.fromHttpCode(response.status);\n /**\n * \"The name is case-insensitive.\"\n * https://developer.mozilla.org/en-US/docs/Web/API/Headers/get\n */\n\n var limited = this._handleRateLimit(headers);\n\n if (limited) logger.warn(\"Too many \" + requestType + \" requests, backing off until: \" + this._disabledUntil(requestType));\n\n if (status === Status.Success) {\n resolve({\n status: status\n });\n return;\n }\n\n reject(response);\n };\n /**\n * Gets the time that given category is disabled until for rate limiting\n */\n\n\n BaseTransport.prototype._disabledUntil = function (requestType) {\n var category = CATEGORY_MAPPING[requestType];\n return this._rateLimits[category] || this._rateLimits.all;\n };\n /**\n * Checks if a category is rate limited\n */\n\n\n BaseTransport.prototype._isRateLimited = function (requestType) {\n return this._disabledUntil(requestType) > new Date(Date.now());\n };\n /**\n * Sets internal _rateLimits from incoming headers. Returns true if headers contains a non-empty rate limiting header.\n */\n\n\n BaseTransport.prototype._handleRateLimit = function (headers) {\n var e_1, _a, e_2, _b;\n\n var now = Date.now();\n var rlHeader = headers['x-sentry-rate-limits'];\n var raHeader = headers['retry-after'];\n\n if (rlHeader) {\n try {\n // rate limit headers are of the form\n // ,,..\n // where each is of the form\n // : : : \n // where\n // is a delay in ms\n // is the event type(s) (error, transaction, etc) being rate limited and is of the form\n // ;;...\n // is what's being limited (org, project, or key) - ignored by SDK\n // is an arbitrary string like \"org_quota\" - ignored by SDK\n for (var _c = __values(rlHeader.trim().split(',')), _d = _c.next(); !_d.done; _d = _c.next()) {\n var limit = _d.value;\n var parameters = limit.split(':', 2);\n var headerDelay = parseInt(parameters[0], 10);\n var delay = (!isNaN(headerDelay) ? headerDelay : 60) * 1000; // 60sec default\n\n try {\n for (var _e = (e_2 = void 0, __values(parameters[1].split(';'))), _f = _e.next(); !_f.done; _f = _e.next()) {\n var category = _f.value;\n this._rateLimits[category || 'all'] = new Date(now + delay);\n }\n } catch (e_2_1) {\n e_2 = {\n error: e_2_1\n };\n } finally {\n try {\n if (_f && !_f.done && (_b = _e[\"return\"])) _b.call(_e);\n } finally {\n if (e_2) throw e_2.error;\n }\n }\n }\n } catch (e_1_1) {\n e_1 = {\n error: e_1_1\n };\n } finally {\n try {\n if (_d && !_d.done && (_a = _c[\"return\"])) _a.call(_c);\n } finally {\n if (e_1) throw e_1.error;\n }\n }\n\n return true;\n } else if (raHeader) {\n this._rateLimits.all = new Date(now + parseRetryAfterHeader(now, raHeader));\n return true;\n }\n\n return false;\n };\n\n return BaseTransport;\n}();\n\nexport { BaseTransport };","import { __extends } from \"tslib\";\nimport { eventToSentryRequest, sessionToSentryRequest } from '@sentry/core';\nimport { Outcome } from '@sentry/types';\nimport { SentryError, supportsReferrerPolicy, SyncPromise } from '@sentry/utils';\nimport { BaseTransport } from './base';\nimport { getNativeFetchImplementation } from './utils';\n/** `fetch` based transport */\n\nvar FetchTransport =\n/** @class */\nfunction (_super) {\n __extends(FetchTransport, _super);\n\n function FetchTransport(options, fetchImpl) {\n if (fetchImpl === void 0) {\n fetchImpl = getNativeFetchImplementation();\n }\n\n var _this = _super.call(this, options) || this;\n\n _this._fetch = fetchImpl;\n return _this;\n }\n /**\n * @inheritDoc\n */\n\n\n FetchTransport.prototype.sendEvent = function (event) {\n return this._sendRequest(eventToSentryRequest(event, this._api), event);\n };\n /**\n * @inheritDoc\n */\n\n\n FetchTransport.prototype.sendSession = function (session) {\n return this._sendRequest(sessionToSentryRequest(session, this._api), session);\n };\n /**\n * @param sentryRequest Prepared SentryRequest to be delivered\n * @param originalPayload Original payload used to create SentryRequest\n */\n\n\n FetchTransport.prototype._sendRequest = function (sentryRequest, originalPayload) {\n var _this = this;\n\n if (this._isRateLimited(sentryRequest.type)) {\n this.recordLostEvent(Outcome.RateLimitBackoff, sentryRequest.type);\n return Promise.reject({\n event: originalPayload,\n type: sentryRequest.type,\n reason: \"Transport for \" + sentryRequest.type + \" requests locked till \" + this._disabledUntil(sentryRequest.type) + \" due to too many requests.\",\n status: 429\n });\n }\n\n var options = {\n body: sentryRequest.body,\n method: 'POST',\n // Despite all stars in the sky saying that Edge supports old draft syntax, aka 'never', 'always', 'origin' and 'default\n // https://caniuse.com/#feat=referrer-policy\n // It doesn't. And it throw exception instead of ignoring this parameter...\n // REF: https://github.com/getsentry/raven-js/issues/1233\n referrerPolicy: supportsReferrerPolicy() ? 'origin' : ''\n };\n\n if (this.options.fetchParameters !== undefined) {\n Object.assign(options, this.options.fetchParameters);\n }\n\n if (this.options.headers !== undefined) {\n options.headers = this.options.headers;\n }\n\n return this._buffer.add(function () {\n return new SyncPromise(function (resolve, reject) {\n void _this._fetch(sentryRequest.url, options).then(function (response) {\n var headers = {\n 'x-sentry-rate-limits': response.headers.get('X-Sentry-Rate-Limits'),\n 'retry-after': response.headers.get('Retry-After')\n };\n\n _this._handleResponse({\n requestType: sentryRequest.type,\n response: response,\n headers: headers,\n resolve: resolve,\n reject: reject\n });\n })[\"catch\"](reject);\n });\n }).then(undefined, function (reason) {\n // It's either buffer rejection or any other xhr/fetch error, which are treated as NetworkError.\n if (reason instanceof SentryError) {\n _this.recordLostEvent(Outcome.QueueOverflow, sentryRequest.type);\n } else {\n _this.recordLostEvent(Outcome.NetworkError, sentryRequest.type);\n }\n\n throw reason;\n });\n };\n\n return FetchTransport;\n}(BaseTransport);\n\nexport { FetchTransport };","import { __extends } from \"tslib\";\nimport { eventToSentryRequest, sessionToSentryRequest } from '@sentry/core';\nimport { Outcome } from '@sentry/types';\nimport { SentryError, SyncPromise } from '@sentry/utils';\nimport { BaseTransport } from './base';\n/** `XHR` based transport */\n\nvar XHRTransport =\n/** @class */\nfunction (_super) {\n __extends(XHRTransport, _super);\n\n function XHRTransport() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * @inheritDoc\n */\n\n\n XHRTransport.prototype.sendEvent = function (event) {\n return this._sendRequest(eventToSentryRequest(event, this._api), event);\n };\n /**\n * @inheritDoc\n */\n\n\n XHRTransport.prototype.sendSession = function (session) {\n return this._sendRequest(sessionToSentryRequest(session, this._api), session);\n };\n /**\n * @param sentryRequest Prepared SentryRequest to be delivered\n * @param originalPayload Original payload used to create SentryRequest\n */\n\n\n XHRTransport.prototype._sendRequest = function (sentryRequest, originalPayload) {\n var _this = this;\n\n if (this._isRateLimited(sentryRequest.type)) {\n this.recordLostEvent(Outcome.RateLimitBackoff, sentryRequest.type);\n return Promise.reject({\n event: originalPayload,\n type: sentryRequest.type,\n reason: \"Transport for \" + sentryRequest.type + \" requests locked till \" + this._disabledUntil(sentryRequest.type) + \" due to too many requests.\",\n status: 429\n });\n }\n\n return this._buffer.add(function () {\n return new SyncPromise(function (resolve, reject) {\n var request = new XMLHttpRequest();\n\n request.onreadystatechange = function () {\n if (request.readyState === 4) {\n var headers = {\n 'x-sentry-rate-limits': request.getResponseHeader('X-Sentry-Rate-Limits'),\n 'retry-after': request.getResponseHeader('Retry-After')\n };\n\n _this._handleResponse({\n requestType: sentryRequest.type,\n response: request,\n headers: headers,\n resolve: resolve,\n reject: reject\n });\n }\n };\n\n request.open('POST', sentryRequest.url);\n\n for (var header in _this.options.headers) {\n if (Object.prototype.hasOwnProperty.call(_this.options.headers, header)) {\n request.setRequestHeader(header, _this.options.headers[header]);\n }\n }\n\n request.send(sentryRequest.body);\n });\n }).then(undefined, function (reason) {\n // It's either buffer rejection or any other xhr/fetch error, which are treated as NetworkError.\n if (reason instanceof SentryError) {\n _this.recordLostEvent(Outcome.QueueOverflow, sentryRequest.type);\n } else {\n _this.recordLostEvent(Outcome.NetworkError, sentryRequest.type);\n }\n\n throw reason;\n });\n };\n\n return XHRTransport;\n}(BaseTransport);\n\nexport { XHRTransport };","import { __assign, __extends } from \"tslib\";\nimport { BaseBackend } from '@sentry/core';\nimport { Severity } from '@sentry/types';\nimport { supportsFetch } from '@sentry/utils';\nimport { eventFromException, eventFromMessage } from './eventbuilder';\nimport { FetchTransport, XHRTransport } from './transports';\n/**\n * The Sentry Browser SDK Backend.\n * @hidden\n */\n\nvar BrowserBackend =\n/** @class */\nfunction (_super) {\n __extends(BrowserBackend, _super);\n\n function BrowserBackend() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * @inheritDoc\n */\n\n\n BrowserBackend.prototype.eventFromException = function (exception, hint) {\n return eventFromException(this._options, exception, hint);\n };\n /**\n * @inheritDoc\n */\n\n\n BrowserBackend.prototype.eventFromMessage = function (message, level, hint) {\n if (level === void 0) {\n level = Severity.Info;\n }\n\n return eventFromMessage(this._options, message, level, hint);\n };\n /**\n * @inheritDoc\n */\n\n\n BrowserBackend.prototype._setupTransport = function () {\n if (!this._options.dsn) {\n // We return the noop transport here in case there is no Dsn.\n return _super.prototype._setupTransport.call(this);\n }\n\n var transportOptions = __assign(__assign({}, this._options.transportOptions), {\n dsn: this._options.dsn,\n tunnel: this._options.tunnel,\n sendClientReports: this._options.sendClientReports,\n _metadata: this._options._metadata\n });\n\n if (this._options.transport) {\n return new this._options.transport(transportOptions);\n }\n\n if (supportsFetch()) {\n return new FetchTransport(transportOptions);\n }\n\n return new XHRTransport(transportOptions);\n };\n\n return BrowserBackend;\n}(BaseBackend);\n\nexport { BrowserBackend };","import { __assign } from \"tslib\";\nimport { API, captureException, withScope } from '@sentry/core';\nimport { addExceptionMechanism, addExceptionTypeValue, getGlobalObject, logger } from '@sentry/utils';\nvar global = getGlobalObject();\nvar ignoreOnError = 0;\n/**\n * @hidden\n */\n\nexport function shouldIgnoreOnError() {\n return ignoreOnError > 0;\n}\n/**\n * @hidden\n */\n\nexport function ignoreNextOnError() {\n // onerror should trigger before setTimeout\n ignoreOnError += 1;\n setTimeout(function () {\n ignoreOnError -= 1;\n });\n}\n/**\n * Instruments the given function and sends an event to Sentry every time the\n * function throws an exception.\n *\n * @param fn A function to wrap.\n * @returns The wrapped function.\n * @hidden\n */\n\nexport function wrap(fn, options, before) {\n if (options === void 0) {\n options = {};\n }\n\n if (typeof fn !== 'function') {\n return fn;\n }\n\n try {\n // We don't wanna wrap it twice\n if (fn.__sentry__) {\n return fn;\n } // If this has already been wrapped in the past, return that wrapped function\n\n\n if (fn.__sentry_wrapped__) {\n return fn.__sentry_wrapped__;\n }\n } catch (e) {\n // Just accessing custom props in some Selenium environments\n // can cause a \"Permission denied\" exception (see raven-js#495).\n // Bail on wrapping and return the function as-is (defers to window.onerror).\n return fn;\n }\n /* eslint-disable prefer-rest-params */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n\n\n var sentryWrapped = function sentryWrapped() {\n var args = Array.prototype.slice.call(arguments);\n\n try {\n if (before && typeof before === 'function') {\n before.apply(this, arguments);\n } // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access\n\n\n var wrappedArguments = args.map(function (arg) {\n return wrap(arg, options);\n });\n\n if (fn.handleEvent) {\n // Attempt to invoke user-land function\n // NOTE: If you are a Sentry user, and you are seeing this stack frame, it\n // means the sentry.javascript SDK caught an error invoking your application code. This\n // is expected behavior and NOT indicative of a bug with sentry.javascript.\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return fn.handleEvent.apply(this, wrappedArguments);\n } // Attempt to invoke user-land function\n // NOTE: If you are a Sentry user, and you are seeing this stack frame, it\n // means the sentry.javascript SDK caught an error invoking your application code. This\n // is expected behavior and NOT indicative of a bug with sentry.javascript.\n\n\n return fn.apply(this, wrappedArguments);\n } catch (ex) {\n ignoreNextOnError();\n withScope(function (scope) {\n scope.addEventProcessor(function (event) {\n var processedEvent = __assign({}, event);\n\n if (options.mechanism) {\n addExceptionTypeValue(processedEvent, undefined, undefined);\n addExceptionMechanism(processedEvent, options.mechanism);\n }\n\n processedEvent.extra = __assign(__assign({}, processedEvent.extra), {\n arguments: args\n });\n return processedEvent;\n });\n captureException(ex);\n });\n throw ex;\n }\n };\n /* eslint-enable prefer-rest-params */\n // Accessing some objects may throw\n // ref: https://github.com/getsentry/sentry-javascript/issues/1168\n\n\n try {\n for (var property in fn) {\n if (Object.prototype.hasOwnProperty.call(fn, property)) {\n sentryWrapped[property] = fn[property];\n }\n }\n } catch (_oO) {} // eslint-disable-line no-empty\n\n\n fn.prototype = fn.prototype || {};\n sentryWrapped.prototype = fn.prototype;\n Object.defineProperty(fn, '__sentry_wrapped__', {\n enumerable: false,\n value: sentryWrapped\n }); // Signal that this function has been wrapped/filled already\n // for both debugging and to prevent it to being wrapped/filled twice\n\n Object.defineProperties(sentryWrapped, {\n __sentry__: {\n enumerable: false,\n value: true\n },\n __sentry_original__: {\n enumerable: false,\n value: fn\n }\n }); // Restore original function name (not all browsers allow that)\n\n try {\n var descriptor = Object.getOwnPropertyDescriptor(sentryWrapped, 'name');\n\n if (descriptor.configurable) {\n Object.defineProperty(sentryWrapped, 'name', {\n get: function get() {\n return fn.name;\n }\n });\n } // eslint-disable-next-line no-empty\n\n } catch (_oO) {}\n\n return sentryWrapped;\n}\n/**\n * Injects the Report Dialog script\n * @hidden\n */\n\nexport function injectReportDialog(options) {\n if (options === void 0) {\n options = {};\n }\n\n if (!global.document) {\n return;\n }\n\n if (!options.eventId) {\n logger.error(\"Missing eventId option in showReportDialog call\");\n return;\n }\n\n if (!options.dsn) {\n logger.error(\"Missing dsn option in showReportDialog call\");\n return;\n }\n\n var script = global.document.createElement('script');\n script.async = true;\n script.src = new API(options.dsn).getReportDialogEndpoint(options);\n\n if (options.onLoad) {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n script.onload = options.onLoad;\n }\n\n var injectionPoint = global.document.head || global.document.body;\n\n if (injectionPoint) {\n injectionPoint.appendChild(script);\n }\n}","function _typeof(obj) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }, _typeof(obj); }\n\nimport { __assign, __read, __spread } from \"tslib\";\n/* eslint-disable @typescript-eslint/no-unsafe-member-access */\n\n/* eslint-disable max-lines */\n\nimport { getCurrentHub } from '@sentry/core';\nimport { Severity } from '@sentry/types';\nimport { addInstrumentationHandler, getEventDescription, getGlobalObject, htmlTreeAsString, parseUrl, safeJoin } from '@sentry/utils';\n/**\n * Default Breadcrumbs instrumentations\n * TODO: Deprecated - with v6, this will be renamed to `Instrument`\n */\n\nvar Breadcrumbs =\n/** @class */\nfunction () {\n /**\n * @inheritDoc\n */\n function Breadcrumbs(options) {\n /**\n * @inheritDoc\n */\n this.name = Breadcrumbs.id;\n this._options = __assign({\n console: true,\n dom: true,\n fetch: true,\n history: true,\n sentry: true,\n xhr: true\n }, options);\n }\n /**\n * Create a breadcrumb of `sentry` from the events themselves\n */\n\n\n Breadcrumbs.prototype.addSentryBreadcrumb = function (event) {\n if (!this._options.sentry) {\n return;\n }\n\n getCurrentHub().addBreadcrumb({\n category: \"sentry.\" + (event.type === 'transaction' ? 'transaction' : 'event'),\n event_id: event.event_id,\n level: event.level,\n message: getEventDescription(event)\n }, {\n event: event\n });\n };\n /**\n * Instrument browser built-ins w/ breadcrumb capturing\n * - Console API\n * - DOM API (click/typing)\n * - XMLHttpRequest API\n * - Fetch API\n * - History API\n */\n\n\n Breadcrumbs.prototype.setupOnce = function () {\n var _this = this;\n\n if (this._options.console) {\n addInstrumentationHandler({\n callback: function callback() {\n var args = [];\n\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n\n _this._consoleBreadcrumb.apply(_this, __spread(args));\n },\n type: 'console'\n });\n }\n\n if (this._options.dom) {\n addInstrumentationHandler({\n callback: function callback() {\n var args = [];\n\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n\n _this._domBreadcrumb.apply(_this, __spread(args));\n },\n type: 'dom'\n });\n }\n\n if (this._options.xhr) {\n addInstrumentationHandler({\n callback: function callback() {\n var args = [];\n\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n\n _this._xhrBreadcrumb.apply(_this, __spread(args));\n },\n type: 'xhr'\n });\n }\n\n if (this._options.fetch) {\n addInstrumentationHandler({\n callback: function callback() {\n var args = [];\n\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n\n _this._fetchBreadcrumb.apply(_this, __spread(args));\n },\n type: 'fetch'\n });\n }\n\n if (this._options.history) {\n addInstrumentationHandler({\n callback: function callback() {\n var args = [];\n\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n\n _this._historyBreadcrumb.apply(_this, __spread(args));\n },\n type: 'history'\n });\n }\n };\n /**\n * Creates breadcrumbs from console API calls\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n\n\n Breadcrumbs.prototype._consoleBreadcrumb = function (handlerData) {\n var breadcrumb = {\n category: 'console',\n data: {\n arguments: handlerData.args,\n logger: 'console'\n },\n level: Severity.fromString(handlerData.level),\n message: safeJoin(handlerData.args, ' ')\n };\n\n if (handlerData.level === 'assert') {\n if (handlerData.args[0] === false) {\n breadcrumb.message = \"Assertion failed: \" + (safeJoin(handlerData.args.slice(1), ' ') || 'console.assert');\n breadcrumb.data.arguments = handlerData.args.slice(1);\n } else {\n // Don't capture a breadcrumb for passed assertions\n return;\n }\n }\n\n getCurrentHub().addBreadcrumb(breadcrumb, {\n input: handlerData.args,\n level: handlerData.level\n });\n };\n /**\n * Creates breadcrumbs from DOM API calls\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n\n\n Breadcrumbs.prototype._domBreadcrumb = function (handlerData) {\n var target;\n var keyAttrs = _typeof(this._options.dom) === 'object' ? this._options.dom.serializeAttribute : undefined;\n\n if (typeof keyAttrs === 'string') {\n keyAttrs = [keyAttrs];\n } // Accessing event.target can throw (see getsentry/raven-js#838, #768)\n\n\n try {\n target = handlerData.event.target ? htmlTreeAsString(handlerData.event.target, keyAttrs) : htmlTreeAsString(handlerData.event, keyAttrs);\n } catch (e) {\n target = '';\n }\n\n if (target.length === 0) {\n return;\n }\n\n getCurrentHub().addBreadcrumb({\n category: \"ui.\" + handlerData.name,\n message: target\n }, {\n event: handlerData.event,\n name: handlerData.name,\n global: handlerData.global\n });\n };\n /**\n * Creates breadcrumbs from XHR API calls\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n\n\n Breadcrumbs.prototype._xhrBreadcrumb = function (handlerData) {\n if (handlerData.endTimestamp) {\n // We only capture complete, non-sentry requests\n if (handlerData.xhr.__sentry_own_request__) {\n return;\n }\n\n var _a = handlerData.xhr.__sentry_xhr__ || {},\n method = _a.method,\n url = _a.url,\n status_code = _a.status_code,\n body = _a.body;\n\n getCurrentHub().addBreadcrumb({\n category: 'xhr',\n data: {\n method: method,\n url: url,\n status_code: status_code\n },\n type: 'http'\n }, {\n xhr: handlerData.xhr,\n input: body\n });\n return;\n }\n };\n /**\n * Creates breadcrumbs from fetch API calls\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n\n\n Breadcrumbs.prototype._fetchBreadcrumb = function (handlerData) {\n // We only capture complete fetch requests\n if (!handlerData.endTimestamp) {\n return;\n }\n\n if (handlerData.fetchData.url.match(/sentry_key/) && handlerData.fetchData.method === 'POST') {\n // We will not create breadcrumbs for fetch requests that contain `sentry_key` (internal sentry requests)\n return;\n }\n\n if (handlerData.error) {\n getCurrentHub().addBreadcrumb({\n category: 'fetch',\n data: handlerData.fetchData,\n level: Severity.Error,\n type: 'http'\n }, {\n data: handlerData.error,\n input: handlerData.args\n });\n } else {\n getCurrentHub().addBreadcrumb({\n category: 'fetch',\n data: __assign(__assign({}, handlerData.fetchData), {\n status_code: handlerData.response.status\n }),\n type: 'http'\n }, {\n input: handlerData.args,\n response: handlerData.response\n });\n }\n };\n /**\n * Creates breadcrumbs from history API calls\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n\n\n Breadcrumbs.prototype._historyBreadcrumb = function (handlerData) {\n var global = getGlobalObject();\n var from = handlerData.from;\n var to = handlerData.to;\n var parsedLoc = parseUrl(global.location.href);\n var parsedFrom = parseUrl(from);\n var parsedTo = parseUrl(to); // Initial pushState doesn't provide `from` information\n\n if (!parsedFrom.path) {\n parsedFrom = parsedLoc;\n } // Use only the path component of the URL if the URL matches the current\n // document (almost all the time when using pushState)\n\n\n if (parsedLoc.protocol === parsedTo.protocol && parsedLoc.host === parsedTo.host) {\n to = parsedTo.relative;\n }\n\n if (parsedLoc.protocol === parsedFrom.protocol && parsedLoc.host === parsedFrom.host) {\n from = parsedFrom.relative;\n }\n\n getCurrentHub().addBreadcrumb({\n category: 'navigation',\n data: {\n from: from,\n to: to\n }\n });\n };\n /**\n * @inheritDoc\n */\n\n\n Breadcrumbs.id = 'Breadcrumbs';\n return Breadcrumbs;\n}();\n\nexport { Breadcrumbs };","import { __assign, __extends } from \"tslib\";\nimport { BaseClient, SDK_VERSION } from '@sentry/core';\nimport { getGlobalObject, logger } from '@sentry/utils';\nimport { BrowserBackend } from './backend';\nimport { injectReportDialog } from './helpers';\nimport { Breadcrumbs } from './integrations';\n/**\n * The Sentry Browser SDK Client.\n *\n * @see BrowserOptions for documentation on configuration options.\n * @see SentryClient for usage documentation.\n */\n\nvar BrowserClient =\n/** @class */\nfunction (_super) {\n __extends(BrowserClient, _super);\n /**\n * Creates a new Browser SDK instance.\n *\n * @param options Configuration options for this SDK.\n */\n\n\n function BrowserClient(options) {\n if (options === void 0) {\n options = {};\n }\n\n var _this = this;\n\n options._metadata = options._metadata || {};\n options._metadata.sdk = options._metadata.sdk || {\n name: 'sentry.javascript.browser',\n packages: [{\n name: 'npm:@sentry/browser',\n version: SDK_VERSION\n }],\n version: SDK_VERSION\n };\n _this = _super.call(this, BrowserBackend, options) || this;\n return _this;\n }\n /**\n * Show a report dialog to the user to send feedback to a specific event.\n *\n * @param options Set individual options for the dialog\n */\n\n\n BrowserClient.prototype.showReportDialog = function (options) {\n if (options === void 0) {\n options = {};\n } // doesn't work without a document (React Native)\n\n\n var document = getGlobalObject().document;\n\n if (!document) {\n return;\n }\n\n if (!this._isEnabled()) {\n logger.error('Trying to call showReportDialog with Sentry Client disabled');\n return;\n }\n\n injectReportDialog(__assign(__assign({}, options), {\n dsn: options.dsn || this.getDsn()\n }));\n };\n /**\n * @inheritDoc\n */\n\n\n BrowserClient.prototype._prepareEvent = function (event, scope, hint) {\n event.platform = event.platform || 'javascript';\n return _super.prototype._prepareEvent.call(this, event, scope, hint);\n };\n /**\n * @inheritDoc\n */\n\n\n BrowserClient.prototype._sendEvent = function (event) {\n var integration = this.getIntegration(Breadcrumbs);\n\n if (integration) {\n integration.addSentryBreadcrumb(event);\n }\n\n _super.prototype._sendEvent.call(this, event);\n };\n\n return BrowserClient;\n}(BaseClient);\n\nexport { BrowserClient };","import { __assign } from \"tslib\";\nimport { fill, getFunctionName, getGlobalObject } from '@sentry/utils';\nimport { wrap } from '../helpers';\nvar DEFAULT_EVENT_TARGET = ['EventTarget', 'Window', 'Node', 'ApplicationCache', 'AudioTrackList', 'ChannelMergerNode', 'CryptoOperation', 'EventSource', 'FileReader', 'HTMLUnknownElement', 'IDBDatabase', 'IDBRequest', 'IDBTransaction', 'KeyOperation', 'MediaController', 'MessagePort', 'ModalWindow', 'Notification', 'SVGElementInstance', 'Screen', 'TextTrack', 'TextTrackCue', 'TextTrackList', 'WebSocket', 'WebSocketWorker', 'Worker', 'XMLHttpRequest', 'XMLHttpRequestEventTarget', 'XMLHttpRequestUpload'];\n/** Wrap timer functions and event targets to catch errors and provide better meta data */\n\nvar TryCatch =\n/** @class */\nfunction () {\n /**\n * @inheritDoc\n */\n function TryCatch(options) {\n /**\n * @inheritDoc\n */\n this.name = TryCatch.id;\n this._options = __assign({\n XMLHttpRequest: true,\n eventTarget: true,\n requestAnimationFrame: true,\n setInterval: true,\n setTimeout: true\n }, options);\n }\n /**\n * Wrap timer functions and event targets to catch errors\n * and provide better metadata.\n */\n\n\n TryCatch.prototype.setupOnce = function () {\n var global = getGlobalObject();\n\n if (this._options.setTimeout) {\n fill(global, 'setTimeout', this._wrapTimeFunction.bind(this));\n }\n\n if (this._options.setInterval) {\n fill(global, 'setInterval', this._wrapTimeFunction.bind(this));\n }\n\n if (this._options.requestAnimationFrame) {\n fill(global, 'requestAnimationFrame', this._wrapRAF.bind(this));\n }\n\n if (this._options.XMLHttpRequest && 'XMLHttpRequest' in global) {\n fill(XMLHttpRequest.prototype, 'send', this._wrapXHR.bind(this));\n }\n\n if (this._options.eventTarget) {\n var eventTarget = Array.isArray(this._options.eventTarget) ? this._options.eventTarget : DEFAULT_EVENT_TARGET;\n eventTarget.forEach(this._wrapEventTarget.bind(this));\n }\n };\n /** JSDoc */\n\n\n TryCatch.prototype._wrapTimeFunction = function (original) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return function () {\n var args = [];\n\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n\n var originalCallback = args[0];\n args[0] = wrap(originalCallback, {\n mechanism: {\n data: {\n \"function\": getFunctionName(original)\n },\n handled: true,\n type: 'instrument'\n }\n });\n return original.apply(this, args);\n };\n };\n /** JSDoc */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n\n\n TryCatch.prototype._wrapRAF = function (original) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return function (callback) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return original.call(this, wrap(callback, {\n mechanism: {\n data: {\n \"function\": 'requestAnimationFrame',\n handler: getFunctionName(original)\n },\n handled: true,\n type: 'instrument'\n }\n }));\n };\n };\n /** JSDoc */\n\n\n TryCatch.prototype._wrapEventTarget = function (target) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n var global = getGlobalObject(); // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n\n var proto = global[target] && global[target].prototype; // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, no-prototype-builtins\n\n if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty('addEventListener')) {\n return;\n }\n\n fill(proto, 'addEventListener', function (original) {\n return function (eventName, fn, options) {\n try {\n if (typeof fn.handleEvent === 'function') {\n fn.handleEvent = wrap(fn.handleEvent.bind(fn), {\n mechanism: {\n data: {\n \"function\": 'handleEvent',\n handler: getFunctionName(fn),\n target: target\n },\n handled: true,\n type: 'instrument'\n }\n });\n }\n } catch (err) {// can sometimes get 'Permission denied to access property \"handle Event'\n }\n\n return original.call(this, eventName, // eslint-disable-next-line @typescript-eslint/no-explicit-any\n wrap(fn, {\n mechanism: {\n data: {\n \"function\": 'addEventListener',\n handler: getFunctionName(fn),\n target: target\n },\n handled: true,\n type: 'instrument'\n }\n }), options);\n };\n });\n fill(proto, 'removeEventListener', function (originalRemoveEventListener) {\n return function (eventName, fn, options) {\n var _a;\n /**\n * There are 2 possible scenarios here:\n *\n * 1. Someone passes a callback, which was attached prior to Sentry initialization, or by using unmodified\n * method, eg. `document.addEventListener.call(el, name, handler). In this case, we treat this function\n * as a pass-through, and call original `removeEventListener` with it.\n *\n * 2. Someone passes a callback, which was attached after Sentry was initialized, which means that it was using\n * our wrapped version of `addEventListener`, which internally calls `wrap` helper.\n * This helper \"wraps\" whole callback inside a try/catch statement, and attached appropriate metadata to it,\n * in order for us to make a distinction between wrapped/non-wrapped functions possible.\n * If a function was wrapped, it has additional property of `__sentry_wrapped__`, holding the handler.\n *\n * When someone adds a handler prior to initialization, and then do it again, but after,\n * then we have to detach both of them. Otherwise, if we'd detach only wrapped one, it'd be impossible\n * to get rid of the initial handler and it'd stick there forever.\n */\n\n\n var wrappedEventHandler = fn;\n\n try {\n var originalEventHandler = (_a = wrappedEventHandler) === null || _a === void 0 ? void 0 : _a.__sentry_wrapped__;\n\n if (originalEventHandler) {\n originalRemoveEventListener.call(this, eventName, originalEventHandler, options);\n }\n } catch (e) {// ignore, accessing __sentry_wrapped__ will throw in some Selenium environments\n }\n\n return originalRemoveEventListener.call(this, eventName, wrappedEventHandler, options);\n };\n });\n };\n /** JSDoc */\n\n\n TryCatch.prototype._wrapXHR = function (originalSend) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return function () {\n var args = [];\n\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n } // eslint-disable-next-line @typescript-eslint/no-this-alias\n\n\n var xhr = this;\n var xmlHttpRequestProps = ['onload', 'onerror', 'onprogress', 'onreadystatechange'];\n xmlHttpRequestProps.forEach(function (prop) {\n if (prop in xhr && typeof xhr[prop] === 'function') {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n fill(xhr, prop, function (original) {\n var wrapOptions = {\n mechanism: {\n data: {\n \"function\": prop,\n handler: getFunctionName(original)\n },\n handled: true,\n type: 'instrument'\n }\n }; // If Instrument integration has been called before TryCatch, get the name of original function\n\n if (original.__sentry_original__) {\n wrapOptions.mechanism.data.handler = getFunctionName(original.__sentry_original__);\n } // Otherwise wrap directly\n\n\n return wrap(original, wrapOptions);\n });\n }\n });\n return originalSend.apply(this, args);\n };\n };\n /**\n * @inheritDoc\n */\n\n\n TryCatch.id = 'TryCatch';\n return TryCatch;\n}();\n\nexport { TryCatch };","import { __assign } from \"tslib\";\n/* eslint-disable @typescript-eslint/no-unsafe-member-access */\n\nimport { getCurrentHub } from '@sentry/core';\nimport { Severity } from '@sentry/types';\nimport { addExceptionMechanism, addInstrumentationHandler, getLocationHref, isErrorEvent, isPrimitive, isString, logger } from '@sentry/utils';\nimport { eventFromUnknownInput } from '../eventbuilder';\nimport { shouldIgnoreOnError } from '../helpers';\n/** Global handlers */\n\nvar GlobalHandlers =\n/** @class */\nfunction () {\n /** JSDoc */\n function GlobalHandlers(options) {\n /**\n * @inheritDoc\n */\n this.name = GlobalHandlers.id;\n /** JSDoc */\n\n this._onErrorHandlerInstalled = false;\n /** JSDoc */\n\n this._onUnhandledRejectionHandlerInstalled = false;\n this._options = __assign({\n onerror: true,\n onunhandledrejection: true\n }, options);\n }\n /**\n * @inheritDoc\n */\n\n\n GlobalHandlers.prototype.setupOnce = function () {\n Error.stackTraceLimit = 50;\n\n if (this._options.onerror) {\n logger.log('Global Handler attached: onerror');\n\n this._installGlobalOnErrorHandler();\n }\n\n if (this._options.onunhandledrejection) {\n logger.log('Global Handler attached: onunhandledrejection');\n\n this._installGlobalOnUnhandledRejectionHandler();\n }\n };\n /** JSDoc */\n\n\n GlobalHandlers.prototype._installGlobalOnErrorHandler = function () {\n var _this = this;\n\n if (this._onErrorHandlerInstalled) {\n return;\n }\n\n addInstrumentationHandler({\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n callback: function callback(data) {\n var error = data.error;\n var currentHub = getCurrentHub();\n var hasIntegration = currentHub.getIntegration(GlobalHandlers);\n var isFailedOwnDelivery = error && error.__sentry_own_request__ === true;\n\n if (!hasIntegration || shouldIgnoreOnError() || isFailedOwnDelivery) {\n return;\n }\n\n var client = currentHub.getClient();\n var event = error === undefined && isString(data.msg) ? _this._eventFromIncompleteOnError(data.msg, data.url, data.line, data.column) : _this._enhanceEventWithInitialFrame(eventFromUnknownInput(error || data.msg, undefined, {\n attachStacktrace: client && client.getOptions().attachStacktrace,\n rejection: false\n }), data.url, data.line, data.column);\n addExceptionMechanism(event, {\n handled: false,\n type: 'onerror'\n });\n currentHub.captureEvent(event, {\n originalException: error\n });\n },\n type: 'error'\n });\n this._onErrorHandlerInstalled = true;\n };\n /** JSDoc */\n\n\n GlobalHandlers.prototype._installGlobalOnUnhandledRejectionHandler = function () {\n var _this = this;\n\n if (this._onUnhandledRejectionHandlerInstalled) {\n return;\n }\n\n addInstrumentationHandler({\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n callback: function callback(e) {\n var error = e; // dig the object of the rejection out of known event types\n\n try {\n // PromiseRejectionEvents store the object of the rejection under 'reason'\n // see https://developer.mozilla.org/en-US/docs/Web/API/PromiseRejectionEvent\n if ('reason' in e) {\n error = e.reason;\n } // something, somewhere, (likely a browser extension) effectively casts PromiseRejectionEvents\n // to CustomEvents, moving the `promise` and `reason` attributes of the PRE into\n // the CustomEvent's `detail` attribute, since they're not part of CustomEvent's spec\n // see https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent and\n // https://github.com/getsentry/sentry-javascript/issues/2380\n else if ('detail' in e && 'reason' in e.detail) {\n error = e.detail.reason;\n }\n } catch (_oO) {// no-empty\n }\n\n var currentHub = getCurrentHub();\n var hasIntegration = currentHub.getIntegration(GlobalHandlers);\n var isFailedOwnDelivery = error && error.__sentry_own_request__ === true;\n\n if (!hasIntegration || shouldIgnoreOnError() || isFailedOwnDelivery) {\n return true;\n }\n\n var client = currentHub.getClient();\n var event = isPrimitive(error) ? _this._eventFromRejectionWithPrimitive(error) : eventFromUnknownInput(error, undefined, {\n attachStacktrace: client && client.getOptions().attachStacktrace,\n rejection: true\n });\n event.level = Severity.Error;\n addExceptionMechanism(event, {\n handled: false,\n type: 'onunhandledrejection'\n });\n currentHub.captureEvent(event, {\n originalException: error\n });\n return;\n },\n type: 'unhandledrejection'\n });\n this._onUnhandledRejectionHandlerInstalled = true;\n };\n /**\n * This function creates a stack from an old, error-less onerror handler.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n\n\n GlobalHandlers.prototype._eventFromIncompleteOnError = function (msg, url, line, column) {\n var ERROR_TYPES_RE = /^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i; // If 'message' is ErrorEvent, get real message from inside\n\n var message = isErrorEvent(msg) ? msg.message : msg;\n var name;\n var groups = message.match(ERROR_TYPES_RE);\n\n if (groups) {\n name = groups[1];\n message = groups[2];\n }\n\n var event = {\n exception: {\n values: [{\n type: name || 'Error',\n value: message\n }]\n }\n };\n return this._enhanceEventWithInitialFrame(event, url, line, column);\n };\n /**\n * Create an event from a promise rejection where the `reason` is a primitive.\n *\n * @param reason: The `reason` property of the promise rejection\n * @returns An Event object with an appropriate `exception` value\n */\n\n\n GlobalHandlers.prototype._eventFromRejectionWithPrimitive = function (reason) {\n return {\n exception: {\n values: [{\n type: 'UnhandledRejection',\n // String() is needed because the Primitive type includes symbols (which can't be automatically stringified)\n value: \"Non-Error promise rejection captured with value: \" + String(reason)\n }]\n }\n };\n };\n /** JSDoc */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n\n\n GlobalHandlers.prototype._enhanceEventWithInitialFrame = function (event, url, line, column) {\n event.exception = event.exception || {};\n event.exception.values = event.exception.values || [];\n event.exception.values[0] = event.exception.values[0] || {};\n event.exception.values[0].stacktrace = event.exception.values[0].stacktrace || {};\n event.exception.values[0].stacktrace.frames = event.exception.values[0].stacktrace.frames || [];\n var colno = isNaN(parseInt(column, 10)) ? undefined : column;\n var lineno = isNaN(parseInt(line, 10)) ? undefined : line;\n var filename = isString(url) && url.length > 0 ? url : getLocationHref();\n\n if (event.exception.values[0].stacktrace.frames.length === 0) {\n event.exception.values[0].stacktrace.frames.push({\n colno: colno,\n filename: filename,\n \"function\": '?',\n in_app: true,\n lineno: lineno\n });\n }\n\n return event;\n };\n /**\n * @inheritDoc\n */\n\n\n GlobalHandlers.id = 'GlobalHandlers';\n return GlobalHandlers;\n}();\n\nexport { GlobalHandlers };","import { __read, __spread } from \"tslib\";\nimport { addGlobalEventProcessor, getCurrentHub } from '@sentry/core';\nimport { isInstanceOf } from '@sentry/utils';\nimport { exceptionFromStacktrace } from '../parsers';\nimport { computeStackTrace } from '../tracekit';\nvar DEFAULT_KEY = 'cause';\nvar DEFAULT_LIMIT = 5;\n/** Adds SDK info to an event. */\n\nvar LinkedErrors =\n/** @class */\nfunction () {\n /**\n * @inheritDoc\n */\n function LinkedErrors(options) {\n if (options === void 0) {\n options = {};\n }\n /**\n * @inheritDoc\n */\n\n\n this.name = LinkedErrors.id;\n this._key = options.key || DEFAULT_KEY;\n this._limit = options.limit || DEFAULT_LIMIT;\n }\n /**\n * @inheritDoc\n */\n\n\n LinkedErrors.prototype.setupOnce = function () {\n addGlobalEventProcessor(function (event, hint) {\n var self = getCurrentHub().getIntegration(LinkedErrors);\n\n if (self) {\n var handler = self._handler && self._handler.bind(self);\n\n return typeof handler === 'function' ? handler(event, hint) : event;\n }\n\n return event;\n });\n };\n /**\n * @inheritDoc\n */\n\n\n LinkedErrors.prototype._handler = function (event, hint) {\n if (!event.exception || !event.exception.values || !hint || !isInstanceOf(hint.originalException, Error)) {\n return event;\n }\n\n var linkedErrors = this._walkErrorTree(hint.originalException, this._key);\n\n event.exception.values = __spread(linkedErrors, event.exception.values);\n return event;\n };\n /**\n * @inheritDoc\n */\n\n\n LinkedErrors.prototype._walkErrorTree = function (error, key, stack) {\n if (stack === void 0) {\n stack = [];\n }\n\n if (!isInstanceOf(error[key], Error) || stack.length + 1 >= this._limit) {\n return stack;\n }\n\n var stacktrace = computeStackTrace(error[key]);\n var exception = exceptionFromStacktrace(stacktrace);\n return this._walkErrorTree(error[key], key, __spread([exception], stack));\n };\n /**\n * @inheritDoc\n */\n\n\n LinkedErrors.id = 'LinkedErrors';\n return LinkedErrors;\n}();\n\nexport { LinkedErrors };","import { logger } from '@sentry/utils';\n/** Deduplication filter */\n\nvar Dedupe =\n/** @class */\nfunction () {\n function Dedupe() {\n /**\n * @inheritDoc\n */\n this.name = Dedupe.id;\n }\n /**\n * @inheritDoc\n */\n\n\n Dedupe.prototype.setupOnce = function (addGlobalEventProcessor, getCurrentHub) {\n addGlobalEventProcessor(function (currentEvent) {\n var self = getCurrentHub().getIntegration(Dedupe);\n\n if (self) {\n // Juuust in case something goes wrong\n try {\n if (self._shouldDropEvent(currentEvent, self._previousEvent)) {\n logger.warn(\"Event dropped due to being a duplicate of previously captured event.\");\n return null;\n }\n } catch (_oO) {\n return self._previousEvent = currentEvent;\n }\n\n return self._previousEvent = currentEvent;\n }\n\n return currentEvent;\n });\n };\n /** JSDoc */\n\n\n Dedupe.prototype._shouldDropEvent = function (currentEvent, previousEvent) {\n if (!previousEvent) {\n return false;\n }\n\n if (this._isSameMessageEvent(currentEvent, previousEvent)) {\n return true;\n }\n\n if (this._isSameExceptionEvent(currentEvent, previousEvent)) {\n return true;\n }\n\n return false;\n };\n /** JSDoc */\n\n\n Dedupe.prototype._isSameMessageEvent = function (currentEvent, previousEvent) {\n var currentMessage = currentEvent.message;\n var previousMessage = previousEvent.message; // If neither event has a message property, they were both exceptions, so bail out\n\n if (!currentMessage && !previousMessage) {\n return false;\n } // If only one event has a stacktrace, but not the other one, they are not the same\n\n\n if (currentMessage && !previousMessage || !currentMessage && previousMessage) {\n return false;\n }\n\n if (currentMessage !== previousMessage) {\n return false;\n }\n\n if (!this._isSameFingerprint(currentEvent, previousEvent)) {\n return false;\n }\n\n if (!this._isSameStacktrace(currentEvent, previousEvent)) {\n return false;\n }\n\n return true;\n };\n /** JSDoc */\n\n\n Dedupe.prototype._getFramesFromEvent = function (event) {\n var exception = event.exception;\n\n if (exception) {\n try {\n // @ts-ignore Object could be undefined\n return exception.values[0].stacktrace.frames;\n } catch (_oO) {\n return undefined;\n }\n } else if (event.stacktrace) {\n return event.stacktrace.frames;\n }\n\n return undefined;\n };\n /** JSDoc */\n\n\n Dedupe.prototype._isSameStacktrace = function (currentEvent, previousEvent) {\n var currentFrames = this._getFramesFromEvent(currentEvent);\n\n var previousFrames = this._getFramesFromEvent(previousEvent); // If neither event has a stacktrace, they are assumed to be the same\n\n\n if (!currentFrames && !previousFrames) {\n return true;\n } // If only one event has a stacktrace, but not the other one, they are not the same\n\n\n if (currentFrames && !previousFrames || !currentFrames && previousFrames) {\n return false;\n }\n\n currentFrames = currentFrames;\n previousFrames = previousFrames; // If number of frames differ, they are not the same\n\n if (previousFrames.length !== currentFrames.length) {\n return false;\n } // Otherwise, compare the two\n\n\n for (var i = 0; i < previousFrames.length; i++) {\n var frameA = previousFrames[i];\n var frameB = currentFrames[i];\n\n if (frameA.filename !== frameB.filename || frameA.lineno !== frameB.lineno || frameA.colno !== frameB.colno || frameA[\"function\"] !== frameB[\"function\"]) {\n return false;\n }\n }\n\n return true;\n };\n /** JSDoc */\n\n\n Dedupe.prototype._getExceptionFromEvent = function (event) {\n return event.exception && event.exception.values && event.exception.values[0];\n };\n /** JSDoc */\n\n\n Dedupe.prototype._isSameExceptionEvent = function (currentEvent, previousEvent) {\n var previousException = this._getExceptionFromEvent(previousEvent);\n\n var currentException = this._getExceptionFromEvent(currentEvent);\n\n if (!previousException || !currentException) {\n return false;\n }\n\n if (previousException.type !== currentException.type || previousException.value !== currentException.value) {\n return false;\n }\n\n if (!this._isSameFingerprint(currentEvent, previousEvent)) {\n return false;\n }\n\n if (!this._isSameStacktrace(currentEvent, previousEvent)) {\n return false;\n }\n\n return true;\n };\n /** JSDoc */\n\n\n Dedupe.prototype._isSameFingerprint = function (currentEvent, previousEvent) {\n var currentFingerprint = currentEvent.fingerprint;\n var previousFingerprint = previousEvent.fingerprint; // If neither event has a fingerprint, they are assumed to be the same\n\n if (!currentFingerprint && !previousFingerprint) {\n return true;\n } // If only one event has a fingerprint, but not the other one, they are not the same\n\n\n if (currentFingerprint && !previousFingerprint || !currentFingerprint && previousFingerprint) {\n return false;\n }\n\n currentFingerprint = currentFingerprint;\n previousFingerprint = previousFingerprint; // Otherwise, compare the two\n\n try {\n return !!(currentFingerprint.join('') === previousFingerprint.join(''));\n } catch (_oO) {\n return false;\n }\n };\n /**\n * @inheritDoc\n */\n\n\n Dedupe.id = 'Dedupe';\n return Dedupe;\n}();\n\nexport { Dedupe };","import { __assign } from \"tslib\";\nimport { addGlobalEventProcessor, getCurrentHub } from '@sentry/core';\nimport { getGlobalObject } from '@sentry/utils';\nvar global = getGlobalObject();\n/** UserAgent */\n\nvar UserAgent =\n/** @class */\nfunction () {\n function UserAgent() {\n /**\n * @inheritDoc\n */\n this.name = UserAgent.id;\n }\n /**\n * @inheritDoc\n */\n\n\n UserAgent.prototype.setupOnce = function () {\n addGlobalEventProcessor(function (event) {\n var _a, _b, _c;\n\n if (getCurrentHub().getIntegration(UserAgent)) {\n // if none of the information we want exists, don't bother\n if (!global.navigator && !global.location && !global.document) {\n return event;\n } // grab as much info as exists and add it to the event\n\n\n var url = ((_a = event.request) === null || _a === void 0 ? void 0 : _a.url) || ((_b = global.location) === null || _b === void 0 ? void 0 : _b.href);\n var referrer = (global.document || {}).referrer;\n var userAgent = (global.navigator || {}).userAgent;\n\n var headers = __assign(__assign(__assign({}, (_c = event.request) === null || _c === void 0 ? void 0 : _c.headers), referrer && {\n Referer: referrer\n }), userAgent && {\n 'User-Agent': userAgent\n });\n\n var request = __assign(__assign({}, url && {\n url: url\n }), {\n headers: headers\n });\n\n return __assign(__assign({}, event), {\n request: request\n });\n }\n\n return event;\n });\n };\n /**\n * @inheritDoc\n */\n\n\n UserAgent.id = 'UserAgent';\n return UserAgent;\n}();\n\nexport { UserAgent };","import { __assign } from \"tslib\";\nimport { getCurrentHub, initAndBind, Integrations as CoreIntegrations } from '@sentry/core';\nimport { addInstrumentationHandler, getGlobalObject, logger, SyncPromise } from '@sentry/utils';\nimport { BrowserClient } from './client';\nimport { wrap as internalWrap } from './helpers';\nimport { Breadcrumbs, Dedupe, GlobalHandlers, LinkedErrors, TryCatch, UserAgent } from './integrations';\nexport var defaultIntegrations = [new CoreIntegrations.InboundFilters(), new CoreIntegrations.FunctionToString(), new TryCatch(), new Breadcrumbs(), new GlobalHandlers(), new LinkedErrors(), new Dedupe(), new UserAgent()];\n/**\n * The Sentry Browser SDK Client.\n *\n * To use this SDK, call the {@link init} function as early as possible when\n * loading the web page. To set context information or send manual events, use\n * the provided methods.\n *\n * @example\n *\n * ```\n *\n * import { init } from '@sentry/browser';\n *\n * init({\n * dsn: '__DSN__',\n * // ...\n * });\n * ```\n *\n * @example\n * ```\n *\n * import { configureScope } from '@sentry/browser';\n * configureScope((scope: Scope) => {\n * scope.setExtra({ battery: 0.7 });\n * scope.setTag({ user_mode: 'admin' });\n * scope.setUser({ id: '4711' });\n * });\n * ```\n *\n * @example\n * ```\n *\n * import { addBreadcrumb } from '@sentry/browser';\n * addBreadcrumb({\n * message: 'My Breadcrumb',\n * // ...\n * });\n * ```\n *\n * @example\n *\n * ```\n *\n * import * as Sentry from '@sentry/browser';\n * Sentry.captureMessage('Hello, world!');\n * Sentry.captureException(new Error('Good bye'));\n * Sentry.captureEvent({\n * message: 'Manual',\n * stacktrace: [\n * // ...\n * ],\n * });\n * ```\n *\n * @see {@link BrowserOptions} for documentation on configuration options.\n */\n\nexport function init(options) {\n if (options === void 0) {\n options = {};\n }\n\n if (options.defaultIntegrations === undefined) {\n options.defaultIntegrations = defaultIntegrations;\n }\n\n if (options.release === undefined) {\n var window_1 = getGlobalObject(); // This supports the variable that sentry-webpack-plugin injects\n\n if (window_1.SENTRY_RELEASE && window_1.SENTRY_RELEASE.id) {\n options.release = window_1.SENTRY_RELEASE.id;\n }\n }\n\n if (options.autoSessionTracking === undefined) {\n options.autoSessionTracking = true;\n }\n\n if (options.sendClientReports === undefined) {\n options.sendClientReports = true;\n }\n\n initAndBind(BrowserClient, options);\n\n if (options.autoSessionTracking) {\n startSessionTracking();\n }\n}\n/**\n * Present the user with a report dialog.\n *\n * @param options Everything is optional, we try to fetch all info need from the global scope.\n */\n\nexport function showReportDialog(options) {\n if (options === void 0) {\n options = {};\n }\n\n var hub = getCurrentHub();\n var scope = hub.getScope();\n\n if (scope) {\n options.user = __assign(__assign({}, scope.getUser()), options.user);\n }\n\n if (!options.eventId) {\n options.eventId = hub.lastEventId();\n }\n\n var client = hub.getClient();\n\n if (client) {\n client.showReportDialog(options);\n }\n}\n/**\n * This is the getter for lastEventId.\n *\n * @returns The last event id of a captured event.\n */\n\nexport function lastEventId() {\n return getCurrentHub().lastEventId();\n}\n/**\n * This function is here to be API compatible with the loader.\n * @hidden\n */\n\nexport function forceLoad() {// Noop\n}\n/**\n * This function is here to be API compatible with the loader.\n * @hidden\n */\n\nexport function onLoad(callback) {\n callback();\n}\n/**\n * Call `flush()` on the current client, if there is one. See {@link Client.flush}.\n *\n * @param timeout Maximum time in ms the client should wait to flush its event queue. Omitting this parameter will cause\n * the client to wait until all events are sent before resolving the promise.\n * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it\n * doesn't (or if there's no client defined).\n */\n\nexport function flush(timeout) {\n var client = getCurrentHub().getClient();\n\n if (client) {\n return client.flush(timeout);\n }\n\n logger.warn('Cannot flush events. No client defined.');\n return SyncPromise.resolve(false);\n}\n/**\n * Call `close()` on the current client, if there is one. See {@link Client.close}.\n *\n * @param timeout Maximum time in ms the client should wait to flush its event queue before shutting down. Omitting this\n * parameter will cause the client to wait until all events are sent before disabling itself.\n * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it\n * doesn't (or if there's no client defined).\n */\n\nexport function close(timeout) {\n var client = getCurrentHub().getClient();\n\n if (client) {\n return client.close(timeout);\n }\n\n logger.warn('Cannot flush events and disable SDK. No client defined.');\n return SyncPromise.resolve(false);\n}\n/**\n * Wrap code within a try/catch block so the SDK is able to capture errors.\n *\n * @param fn A function to wrap.\n *\n * @returns The result of wrapped function call.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\n\nexport function wrap(fn) {\n return internalWrap(fn)();\n}\n/**\n * Enable automatic Session Tracking for the initial page load.\n */\n\nfunction startSessionTracking() {\n var window = getGlobalObject();\n var document = window.document;\n\n if (typeof document === 'undefined') {\n logger.warn('Session tracking in non-browser environment with @sentry/browser is not supported.');\n return;\n }\n\n var hub = getCurrentHub(); // The only way for this to be false is for there to be a version mismatch between @sentry/browser (>= 6.0.0) and\n // @sentry/hub (< 5.27.0). In the simple case, there won't ever be such a mismatch, because the two packages are\n // pinned at the same version in package.json, but there are edge cases where it's possible. See\n // https://github.com/getsentry/sentry-javascript/issues/3207 and\n // https://github.com/getsentry/sentry-javascript/issues/3234 and\n // https://github.com/getsentry/sentry-javascript/issues/3278.\n\n if (typeof hub.startSession !== 'function' || typeof hub.captureSession !== 'function') {\n return;\n } // The session duration for browser sessions does not track a meaningful\n // concept that can be used as a metric.\n // Automatically captured sessions are akin to page views, and thus we\n // discard their duration.\n\n\n hub.startSession({\n ignoreDuration: true\n });\n hub.captureSession(); // We want to create a session for every navigation as well\n\n addInstrumentationHandler({\n callback: function callback(_a) {\n var from = _a.from,\n to = _a.to; // Don't create an additional session for the initial route or if the location did not change\n\n if (from === undefined || from === to) {\n return;\n }\n\n hub.startSession({\n ignoreDuration: true\n });\n hub.captureSession();\n },\n type: 'history'\n });\n}","import { getCurrentHub } from '@sentry/hub';\nimport { logger } from '@sentry/utils';\n/**\n * Internal function to create a new SDK client instance. The client is\n * installed and then bound to the current scope.\n *\n * @param clientClass The client class to instantiate.\n * @param options Options to pass to the client.\n */\n\nexport function initAndBind(clientClass, options) {\n var _a;\n\n if (options.debug === true) {\n logger.enable();\n }\n\n var hub = getCurrentHub();\n (_a = hub.getScope()) === null || _a === void 0 ? void 0 : _a.update(options.initialScope);\n var client = new clientClass(options);\n hub.bindClient(client);\n}","import { __assign } from \"tslib\";\nimport { getGlobalObject } from '@sentry/utils';\nimport hoistNonReactStatics from 'hoist-non-react-statics';\nimport * as React from 'react';\n/* eslint-enable @typescript-eslint/no-explicit-any */\n\nvar global = getGlobalObject();\nvar activeTransaction;\nexport function reactRouterV4Instrumentation(history, routes, matchPath) {\n return createReactRouterInstrumentation(history, 'react-router-v4', routes, matchPath);\n}\nexport function reactRouterV5Instrumentation(history, routes, matchPath) {\n return createReactRouterInstrumentation(history, 'react-router-v5', routes, matchPath);\n}\n\nfunction createReactRouterInstrumentation(history, name, allRoutes, matchPath) {\n if (allRoutes === void 0) {\n allRoutes = [];\n }\n\n function getInitPathName() {\n if (history && history.location) {\n return history.location.pathname;\n }\n\n if (global && global.location) {\n return global.location.pathname;\n }\n\n return undefined;\n }\n\n function getTransactionName(pathname) {\n if (allRoutes.length === 0 || !matchPath) {\n return pathname;\n }\n\n var branches = matchRoutes(allRoutes, pathname, matchPath); // eslint-disable-next-line @typescript-eslint/prefer-for-of\n\n for (var x = 0; x < branches.length; x++) {\n if (branches[x].match.isExact) {\n return branches[x].match.path;\n }\n }\n\n return pathname;\n }\n\n return function (customStartTransaction, startTransactionOnPageLoad, startTransactionOnLocationChange) {\n if (startTransactionOnPageLoad === void 0) {\n startTransactionOnPageLoad = true;\n }\n\n if (startTransactionOnLocationChange === void 0) {\n startTransactionOnLocationChange = true;\n }\n\n var initPathName = getInitPathName();\n\n if (startTransactionOnPageLoad && initPathName) {\n activeTransaction = customStartTransaction({\n name: getTransactionName(initPathName),\n op: 'pageload',\n tags: {\n 'routing.instrumentation': name\n }\n });\n }\n\n if (startTransactionOnLocationChange && history.listen) {\n history.listen(function (location, action) {\n if (action && (action === 'PUSH' || action === 'POP')) {\n if (activeTransaction) {\n activeTransaction.finish();\n }\n\n var tags = {\n 'routing.instrumentation': name\n };\n activeTransaction = customStartTransaction({\n name: getTransactionName(location.pathname),\n op: 'navigation',\n tags: tags\n });\n }\n });\n }\n };\n}\n/**\n * Matches a set of routes to a pathname\n * Based on implementation from\n */\n\n\nfunction matchRoutes(routes, pathname, matchPath, branch) {\n if (branch === void 0) {\n branch = [];\n }\n\n routes.some(function (route) {\n var match = route.path ? matchPath(pathname, route) : branch.length ? branch[branch.length - 1].match // use parent match\n : computeRootMatch(pathname); // use default \"root\" match\n\n if (match) {\n branch.push({\n route: route,\n match: match\n });\n\n if (route.routes) {\n matchRoutes(route.routes, pathname, matchPath, branch);\n }\n }\n\n return !!match;\n });\n return branch;\n}\n\nfunction computeRootMatch(pathname) {\n return {\n path: '/',\n url: '/',\n params: {},\n isExact: pathname === '/'\n };\n}\n/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access */\n\n\nexport function withSentryRouting(Route) {\n var componentDisplayName = Route.displayName || Route.name;\n\n var WrappedRoute = function WrappedRoute(props) {\n if (activeTransaction && props && props.computedMatch && props.computedMatch.isExact) {\n activeTransaction.setName(props.computedMatch.path);\n } // @ts-ignore Setting more specific React Component typing for `R` generic above\n // will break advanced type inference done by react router params:\n // https://github.com/DefinitelyTyped/DefinitelyTyped/blob/13dc4235c069e25fe7ee16e11f529d909f9f3ff8/types/react-router/index.d.ts#L154-L164\n\n\n return React.createElement(Route, __assign({}, props));\n };\n\n WrappedRoute.displayName = \"sentryRoute(\" + componentDisplayName + \")\";\n hoistNonReactStatics(WrappedRoute, Route); // @ts-ignore Setting more specific React Component typing for `R` generic above\n // will break advanced type inference done by react router params:\n // https://github.com/DefinitelyTyped/DefinitelyTyped/blob/13dc4235c069e25fe7ee16e11f529d909f9f3ff8/types/react-router/index.d.ts#L154-L164\n\n return WrappedRoute;\n}\n/* eslint-enable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access */","import { __read, __spread } from \"tslib\";\nimport { logger } from '@sentry/utils';\n/**\n * Express integration\n *\n * Provides an request and error handler for Express framework as well as tracing capabilities\n */\n\nvar Express =\n/** @class */\nfunction () {\n /**\n * @inheritDoc\n */\n function Express(options) {\n if (options === void 0) {\n options = {};\n }\n /**\n * @inheritDoc\n */\n\n\n this.name = Express.id;\n this._router = options.router || options.app;\n this._methods = (Array.isArray(options.methods) ? options.methods : []).concat('use');\n }\n /**\n * @inheritDoc\n */\n\n\n Express.prototype.setupOnce = function () {\n if (!this._router) {\n logger.error('ExpressIntegration is missing an Express instance');\n return;\n }\n\n instrumentMiddlewares(this._router, this._methods);\n };\n /**\n * @inheritDoc\n */\n\n\n Express.id = 'Express';\n return Express;\n}();\n\nexport { Express };\n/**\n * Wraps original middleware function in a tracing call, which stores the info about the call as a span,\n * and finishes it once the middleware is done invoking.\n *\n * Express middlewares have 3 various forms, thus we have to take care of all of them:\n * // sync\n * app.use(function (req, res) { ... })\n * // async\n * app.use(function (req, res, next) { ... })\n * // error handler\n * app.use(function (err, req, res, next) { ... })\n *\n * They all internally delegate to the `router[method]` of the given application instance.\n */\n// eslint-disable-next-line @typescript-eslint/ban-types, @typescript-eslint/no-explicit-any\n\nfunction wrap(fn, method) {\n var arity = fn.length;\n\n switch (arity) {\n case 2:\n {\n return function (req, res) {\n var transaction = res.__sentry_transaction;\n\n if (transaction) {\n var span_1 = transaction.startChild({\n description: fn.name,\n op: \"express.middleware.\" + method\n });\n res.once('finish', function () {\n span_1.finish();\n });\n }\n\n return fn.call(this, req, res);\n };\n }\n\n case 3:\n {\n return function (req, res, next) {\n var _a;\n\n var transaction = res.__sentry_transaction;\n var span = (_a = transaction) === null || _a === void 0 ? void 0 : _a.startChild({\n description: fn.name,\n op: \"express.middleware.\" + method\n });\n fn.call(this, req, res, function () {\n var args = [];\n\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n\n var _a;\n\n (_a = span) === null || _a === void 0 ? void 0 : _a.finish();\n next.call.apply(next, __spread([this], args));\n });\n };\n }\n\n case 4:\n {\n return function (err, req, res, next) {\n var _a;\n\n var transaction = res.__sentry_transaction;\n var span = (_a = transaction) === null || _a === void 0 ? void 0 : _a.startChild({\n description: fn.name,\n op: \"express.middleware.\" + method\n });\n fn.call(this, err, req, res, function () {\n var args = [];\n\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n\n var _a;\n\n (_a = span) === null || _a === void 0 ? void 0 : _a.finish();\n next.call.apply(next, __spread([this], args));\n });\n };\n }\n\n default:\n {\n throw new Error(\"Express middleware takes 2-4 arguments. Got: \" + arity);\n }\n }\n}\n/**\n * Takes all the function arguments passed to the original `app` or `router` method, eg. `app.use` or `router.use`\n * and wraps every function, as well as array of functions with a call to our `wrap` method.\n * We have to take care of the arrays as well as iterate over all of the arguments,\n * as `app.use` can accept middlewares in few various forms.\n *\n * app.use([], )\n * app.use([], , ...)\n * app.use([], ...[])\n */\n\n\nfunction wrapMiddlewareArgs(args, method) {\n return args.map(function (arg) {\n if (typeof arg === 'function') {\n return wrap(arg, method);\n }\n\n if (Array.isArray(arg)) {\n return arg.map(function (a) {\n if (typeof a === 'function') {\n return wrap(a, method);\n }\n\n return a;\n });\n }\n\n return arg;\n });\n}\n/**\n * Patches original router to utilize our tracing functionality\n */\n\n\nfunction patchMiddleware(router, method) {\n var originalCallback = router[method];\n\n router[method] = function () {\n var args = [];\n\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n\n return originalCallback.call.apply(originalCallback, __spread([this], wrapMiddlewareArgs(args, method)));\n };\n\n return router;\n}\n/**\n * Patches original router methods\n */\n\n\nfunction instrumentMiddlewares(router, methods) {\n if (methods === void 0) {\n methods = [];\n }\n\n methods.forEach(function (method) {\n return patchMiddleware(router, method);\n });\n}","import { fill, isThenable, loadModule, logger } from '@sentry/utils';\n/** Tracing integration for node-postgres package */\n\nvar Postgres =\n/** @class */\nfunction () {\n function Postgres(options) {\n if (options === void 0) {\n options = {};\n }\n /**\n * @inheritDoc\n */\n\n\n this.name = Postgres.id;\n this._usePgNative = !!options.usePgNative;\n }\n /**\n * @inheritDoc\n */\n\n\n Postgres.prototype.setupOnce = function (_, getCurrentHub) {\n var _a;\n\n var pkg = loadModule('pg');\n\n if (!pkg) {\n logger.error('Postgres Integration was unable to require `pg` package.');\n return;\n }\n\n if (this._usePgNative && !((_a = pkg[\"native\"]) === null || _a === void 0 ? void 0 : _a.Client)) {\n logger.error(\"Postgres Integration was unable to access 'pg-native' bindings.\");\n return;\n }\n\n var Client = (this._usePgNative ? pkg[\"native\"] : pkg).Client;\n /**\n * function (query, callback) => void\n * function (query, params, callback) => void\n * function (query) => Promise\n * function (query, params) => Promise\n * function (pg.Cursor) => pg.Cursor\n */\n\n fill(Client.prototype, 'query', function (orig) {\n return function (config, values, callback) {\n var _a, _b, _c;\n\n var scope = getCurrentHub().getScope();\n var parentSpan = (_a = scope) === null || _a === void 0 ? void 0 : _a.getSpan();\n var span = (_b = parentSpan) === null || _b === void 0 ? void 0 : _b.startChild({\n description: typeof config === 'string' ? config : config.text,\n op: \"db\"\n });\n\n if (typeof callback === 'function') {\n return orig.call(this, config, values, function (err, result) {\n var _a;\n\n (_a = span) === null || _a === void 0 ? void 0 : _a.finish();\n callback(err, result);\n });\n }\n\n if (typeof values === 'function') {\n return orig.call(this, config, function (err, result) {\n var _a;\n\n (_a = span) === null || _a === void 0 ? void 0 : _a.finish();\n values(err, result);\n });\n }\n\n var rv = typeof values !== 'undefined' ? orig.call(this, config, values) : orig.call(this, config);\n\n if (isThenable(rv)) {\n return rv.then(function (res) {\n var _a;\n\n (_a = span) === null || _a === void 0 ? void 0 : _a.finish();\n return res;\n });\n }\n\n (_c = span) === null || _c === void 0 ? void 0 : _c.finish();\n return rv;\n };\n });\n };\n /**\n * @inheritDoc\n */\n\n\n Postgres.id = 'Postgres';\n return Postgres;\n}();\n\nexport { Postgres };","import { fill, loadModule, logger } from '@sentry/utils';\n/** Tracing integration for node-mysql package */\n\nvar Mysql =\n/** @class */\nfunction () {\n function Mysql() {\n /**\n * @inheritDoc\n */\n this.name = Mysql.id;\n }\n /**\n * @inheritDoc\n */\n\n\n Mysql.prototype.setupOnce = function (_, getCurrentHub) {\n var pkg = loadModule('mysql/lib/Connection.js');\n\n if (!pkg) {\n logger.error('Mysql Integration was unable to require `mysql` package.');\n return;\n } // The original function will have one of these signatures:\n // function (callback) => void\n // function (options, callback) => void\n // function (options, values, callback) => void\n\n\n fill(pkg, 'createQuery', function (orig) {\n return function (options, values, callback) {\n var _a, _b;\n\n var scope = getCurrentHub().getScope();\n var parentSpan = (_a = scope) === null || _a === void 0 ? void 0 : _a.getSpan();\n var span = (_b = parentSpan) === null || _b === void 0 ? void 0 : _b.startChild({\n description: typeof options === 'string' ? options : options.sql,\n op: \"db\"\n });\n\n if (typeof callback === 'function') {\n return orig.call(this, options, values, function (err, result, fields) {\n var _a;\n\n (_a = span) === null || _a === void 0 ? void 0 : _a.finish();\n callback(err, result, fields);\n });\n }\n\n if (typeof values === 'function') {\n return orig.call(this, options, function (err, result, fields) {\n var _a;\n\n (_a = span) === null || _a === void 0 ? void 0 : _a.finish();\n values(err, result, fields);\n });\n }\n\n return orig.call(this, options, values, callback);\n };\n });\n };\n /**\n * @inheritDoc\n */\n\n\n Mysql.id = 'Mysql';\n return Mysql;\n}();\n\nexport { Mysql };","import { __read, __spread } from \"tslib\";\nimport { fill, isThenable, loadModule, logger } from '@sentry/utils';\nvar 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\n// take additional parameters as well. For those operations, this is a map of\n// { : [] }, as a way to know what to call the operation's\n// positional arguments when we add them to the span's `data` object later\n\nvar OPERATION_SIGNATURES = {\n // aggregate intentionally not included because `pipeline` arguments are too complex to serialize well\n // see https://github.com/getsentry/sentry-javascript/pull/3102\n bulkWrite: ['operations'],\n countDocuments: ['query'],\n createIndex: ['fieldOrSpec'],\n createIndexes: ['indexSpecs'],\n deleteMany: ['filter'],\n deleteOne: ['filter'],\n distinct: ['key', 'query'],\n dropIndex: ['indexName'],\n find: ['query'],\n findOne: ['query'],\n findOneAndDelete: ['filter'],\n findOneAndReplace: ['filter', 'replacement'],\n findOneAndUpdate: ['filter', 'update'],\n indexExists: ['indexes'],\n insertMany: ['docs'],\n insertOne: ['doc'],\n mapReduce: ['map', 'reduce'],\n rename: ['newName'],\n replaceOne: ['filter', 'doc'],\n updateMany: ['filter', 'update'],\n updateOne: ['filter', 'update']\n};\n/** Tracing integration for mongo package */\n\nvar Mongo =\n/** @class */\nfunction () {\n /**\n * @inheritDoc\n */\n function Mongo(options) {\n if (options === void 0) {\n options = {};\n }\n /**\n * @inheritDoc\n */\n\n\n this.name = Mongo.id;\n this._operations = Array.isArray(options.operations) ? options.operations : OPERATIONS;\n this._describeOperations = 'describeOperations' in options ? options.describeOperations : true;\n this._useMongoose = !!options.useMongoose;\n }\n /**\n * @inheritDoc\n */\n\n\n Mongo.prototype.setupOnce = function (_, getCurrentHub) {\n var moduleName = this._useMongoose ? 'mongoose' : 'mongodb';\n var pkg = loadModule(moduleName);\n\n if (!pkg) {\n logger.error(\"Mongo Integration was unable to require `\" + moduleName + \"` package.\");\n return;\n }\n\n this._instrumentOperations(pkg.Collection, this._operations, getCurrentHub);\n };\n /**\n * Patches original collection methods\n */\n\n\n Mongo.prototype._instrumentOperations = function (collection, operations, getCurrentHub) {\n var _this = this;\n\n operations.forEach(function (operation) {\n return _this._patchOperation(collection, operation, getCurrentHub);\n });\n };\n /**\n * Patches original collection to utilize our tracing functionality\n */\n\n\n Mongo.prototype._patchOperation = function (collection, operation, getCurrentHub) {\n if (!(operation in collection.prototype)) return;\n\n var getSpanContext = this._getSpanContextFromOperationArguments.bind(this);\n\n fill(collection.prototype, operation, function (orig) {\n return function () {\n var args = [];\n\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n\n var _a, _b, _c, _d;\n\n var lastArg = args[args.length - 1];\n var scope = getCurrentHub().getScope();\n 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\n // its (non-callback) arguments can also be functions.)\n\n if (typeof lastArg !== 'function' || operation === 'mapReduce' && args.length === 2) {\n var span_1 = (_b = parentSpan) === null || _b === void 0 ? void 0 : _b.startChild(getSpanContext(this, operation, args));\n var maybePromise = orig.call.apply(orig, __spread([this], args));\n\n if (isThenable(maybePromise)) {\n return maybePromise.then(function (res) {\n var _a;\n\n (_a = span_1) === null || _a === void 0 ? void 0 : _a.finish();\n return res;\n });\n } else {\n (_c = span_1) === null || _c === void 0 ? void 0 : _c.finish();\n return maybePromise;\n }\n }\n\n var span = (_d = parentSpan) === null || _d === void 0 ? void 0 : _d.startChild(getSpanContext(this, operation, args.slice(0, -1)));\n return orig.call.apply(orig, __spread([this], args.slice(0, -1), [function (err, result) {\n var _a;\n\n (_a = span) === null || _a === void 0 ? void 0 : _a.finish();\n lastArg(err, result);\n }]));\n };\n });\n };\n /**\n * Form a SpanContext based on the user input to a given operation.\n */\n\n\n Mongo.prototype._getSpanContextFromOperationArguments = function (collection, operation, args) {\n var data = {\n collectionName: collection.collectionName,\n dbName: collection.dbName,\n namespace: collection.namespace\n };\n var spanContext = {\n op: \"db\",\n description: operation,\n data: data\n }; // If the operation takes no arguments besides `options` and `callback`, or if argument\n // collection is disabled for this operation, just return early.\n\n var signature = OPERATION_SIGNATURES[operation];\n var shouldDescribe = Array.isArray(this._describeOperations) ? this._describeOperations.includes(operation) : this._describeOperations;\n\n if (!signature || !shouldDescribe) {\n return spanContext;\n }\n\n try {\n // Special case for `mapReduce`, as the only one accepting functions as arguments.\n if (operation === 'mapReduce') {\n var _a = __read(args, 2),\n map = _a[0],\n reduce = _a[1];\n\n data[signature[0]] = typeof map === 'string' ? map : map.name || '';\n data[signature[1]] = typeof reduce === 'string' ? reduce : reduce.name || '';\n } else {\n for (var i = 0; i < signature.length; i++) {\n data[signature[i]] = JSON.stringify(args[i]);\n }\n }\n } catch (_oO) {// no-empty\n }\n\n return spanContext;\n };\n /**\n * @inheritDoc\n */\n\n\n Mongo.id = 'Mongo';\n return Mongo;\n}();\n\nexport { Mongo };","import { getGlobalObject, logger } from '@sentry/utils';\nimport { FINISH_REASON_TAG, IDLE_TRANSACTION_FINISH_REASONS } from '../constants';\nimport { SpanStatus } from '../spanstatus';\nimport { getActiveTransaction } from '../utils';\nvar global = getGlobalObject();\n/**\n * Add a listener that cancels and finishes a transaction when the global\n * document is hidden.\n */\n\nexport function registerBackgroundTabDetection() {\n if (global && global.document) {\n global.document.addEventListener('visibilitychange', function () {\n var activeTransaction = getActiveTransaction();\n\n if (global.document.hidden && activeTransaction) {\n logger.log(\"[Tracing] Transaction: \" + 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\n // error or data loss from being overwritten on transaction.\n\n if (!activeTransaction.status) {\n activeTransaction.setStatus(SpanStatus.Cancelled);\n }\n\n activeTransaction.setTag('visibilitychange', 'document.hidden');\n activeTransaction.setTag(FINISH_REASON_TAG, IDLE_TRANSACTION_FINISH_REASONS[2]);\n activeTransaction.finish();\n }\n });\n } else {\n logger.warn('[Tracing] Could not set up background tab detection due to lack of global document');\n }\n}","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport var bindReporter = function bindReporter(callback, metric, reportAllChanges) {\n var prevValue;\n return function (forceReport) {\n if (metric.value >= 0) {\n if (forceReport || reportAllChanges) {\n metric.delta = metric.value - (prevValue || 0); // Report the metric if there's a non-zero delta or if no previous\n // value exists (which can happen in the case of the document becoming\n // hidden when the metric value is 0).\n // See: https://github.com/GoogleChrome/web-vitals/issues/14\n\n if (metric.delta || prevValue === undefined) {\n prevValue = metric.value;\n callback(metric);\n }\n }\n }\n };\n};","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { generateUniqueID } from './generateUniqueID';\nexport var initMetric = function initMetric(name, value) {\n return {\n name: name,\n value: value !== null && value !== void 0 ? value : -1,\n delta: 0,\n entries: [],\n id: generateUniqueID()\n };\n};","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Performantly generate a unique, 30-char string by combining a version\n * number, the current timestamp with a 13-digit number integer.\n * @return {string}\n */\nexport var generateUniqueID = function generateUniqueID() {\n return \"v2-\" + Date.now() + \"-\" + (Math.floor(Math.random() * (9e12 - 1)) + 1e12);\n};","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Takes a performance entry type and a callback function, and creates a\n * `PerformanceObserver` instance that will observe the specified entry type\n * with buffering enabled and call the callback _for each entry_.\n *\n * This function also feature-detects entry support and wraps the logic in a\n * try/catch to avoid errors in unsupporting browsers.\n */\nexport var observe = function observe(type, callback) {\n try {\n if (PerformanceObserver.supportedEntryTypes.includes(type)) {\n // More extensive feature detect needed for Firefox due to:\n // https://github.com/GoogleChrome/web-vitals/issues/142\n if (type === 'first-input' && !('PerformanceEventTiming' in self)) {\n return;\n }\n\n var po = new PerformanceObserver(function (l) {\n return l.getEntries().map(callback);\n });\n po.observe({\n type: type,\n buffered: true\n });\n return po;\n }\n } catch (e) {// Do nothing.\n }\n\n return;\n};","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { getGlobalObject } from '@sentry/utils';\nexport var onHidden = function onHidden(cb, once) {\n var onHiddenOrPageHide = function onHiddenOrPageHide(event) {\n if (event.type === 'pagehide' || getGlobalObject().document.visibilityState === 'hidden') {\n cb(event);\n\n if (once) {\n removeEventListener('visibilitychange', onHiddenOrPageHide, true);\n removeEventListener('pagehide', onHiddenOrPageHide, true);\n }\n }\n };\n\n addEventListener('visibilitychange', onHiddenOrPageHide, true); // Some browsers have buggy implementations of visibilitychange,\n // so we use pagehide in addition, just to be safe.\n\n addEventListener('pagehide', onHiddenOrPageHide, true);\n};","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { getGlobalObject } from '@sentry/utils';\nimport { onHidden } from './onHidden';\nvar firstHiddenTime = -1;\n\nvar initHiddenTime = function initHiddenTime() {\n return getGlobalObject().document.visibilityState === 'hidden' ? 0 : Infinity;\n};\n\nvar trackChanges = function trackChanges() {\n // Update the time if/when the document becomes hidden.\n onHidden(function (_a) {\n var timeStamp = _a.timeStamp;\n firstHiddenTime = timeStamp;\n }, true);\n};\n\nexport var getVisibilityWatcher = function getVisibilityWatcher() {\n if (firstHiddenTime < 0) {\n // If the document is hidden when this code runs, assume it was hidden\n // since navigation start. This isn't a perfect heuristic, but it's the\n // best we can do until an API is available to support querying past\n // visibilityState.\n firstHiddenTime = initHiddenTime();\n trackChanges();\n }\n\n return {\n get firstHiddenTime() {\n return firstHiddenTime;\n }\n\n };\n};","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { bindReporter } from './lib/bindReporter';\nimport { getVisibilityWatcher } from './lib/getVisibilityWatcher';\nimport { initMetric } from './lib/initMetric';\nimport { observe } from './lib/observe';\nimport { onHidden } from './lib/onHidden';\nvar reportedMetricIDs = {};\nexport var getLCP = function getLCP(onReport, reportAllChanges) {\n var visibilityWatcher = getVisibilityWatcher();\n var metric = initMetric('LCP');\n var report;\n\n var entryHandler = function entryHandler(entry) {\n // The startTime attribute returns the value of the renderTime if it is not 0,\n // and the value of the loadTime otherwise.\n var value = entry.startTime; // If the page was hidden prior to paint time of the entry,\n // ignore it and mark the metric as final, otherwise add the entry.\n\n if (value < visibilityWatcher.firstHiddenTime) {\n metric.value = value;\n metric.entries.push(entry);\n }\n\n if (report) {\n report();\n }\n };\n\n var po = observe('largest-contentful-paint', entryHandler);\n\n if (po) {\n report = bindReporter(onReport, metric, reportAllChanges);\n\n var stopListening_1 = function stopListening_1() {\n if (!reportedMetricIDs[metric.id]) {\n po.takeRecords().map(entryHandler);\n po.disconnect();\n reportedMetricIDs[metric.id] = true;\n report(true);\n }\n }; // Stop listening after input. Note: while scrolling is an input that\n // stop LCP observation, it's unreliable since it can be programmatically\n // generated. See: https://github.com/GoogleChrome/web-vitals/issues/75\n\n\n ['keydown', 'click'].forEach(function (type) {\n addEventListener(type, stopListening_1, {\n once: true,\n capture: true\n });\n });\n onHidden(stopListening_1, true);\n }\n};","import { __assign, __rest } from \"tslib\";\nimport { browserPerformanceTimeOrigin, getGlobalObject, htmlTreeAsString, isNodeEnv, logger } from '@sentry/utils';\nimport { msToSec } from '../utils';\nimport { getCLS } from './web-vitals/getCLS';\nimport { getFID } from './web-vitals/getFID';\nimport { getLCP } from './web-vitals/getLCP';\nimport { getVisibilityWatcher } from './web-vitals/lib/getVisibilityWatcher';\nvar global = getGlobalObject();\n/** Class tracking metrics */\n\nvar MetricsInstrumentation =\n/** @class */\nfunction () {\n function MetricsInstrumentation(_reportAllChanges) {\n if (_reportAllChanges === void 0) {\n _reportAllChanges = false;\n }\n\n var _a, _b;\n\n this._reportAllChanges = _reportAllChanges;\n this._measurements = {};\n this._performanceCursor = 0;\n\n if (!isNodeEnv() && ((_a = global) === null || _a === void 0 ? void 0 : _a.performance) && ((_b = global) === null || _b === void 0 ? void 0 : _b.document)) {\n if (global.performance.mark) {\n global.performance.mark('sentry-tracing-init');\n }\n\n this._trackCLS();\n\n this._trackLCP();\n\n this._trackFID();\n }\n }\n /** Add performance related spans to a transaction */\n\n\n MetricsInstrumentation.prototype.addPerformanceEntries = function (transaction) {\n var _this = this;\n\n if (!global || !global.performance || !global.performance.getEntries || !browserPerformanceTimeOrigin) {\n // Gatekeeper if performance API not available\n return;\n }\n\n logger.log('[Tracing] Adding & adjusting spans using Performance API');\n var timeOrigin = msToSec(browserPerformanceTimeOrigin);\n var entryScriptSrc;\n\n if (global.document && global.document.scripts) {\n // eslint-disable-next-line @typescript-eslint/prefer-for-of\n for (var i = 0; i < global.document.scripts.length; i++) {\n // We go through all scripts on the page and look for 'data-entry'\n // We remember the name and measure the time between this script finished loading and\n // our mark 'sentry-tracing-init'\n if (global.document.scripts[i].dataset.entry === 'true') {\n entryScriptSrc = global.document.scripts[i].src;\n break;\n }\n }\n }\n\n var entryScriptStartTimestamp;\n var tracingInitMarkStartTime;\n var responseStartTimestamp;\n var requestStartTimestamp;\n global.performance.getEntries().slice(this._performanceCursor).forEach(function (entry) {\n var startTime = msToSec(entry.startTime);\n var duration = msToSec(entry.duration);\n\n if (transaction.op === 'navigation' && timeOrigin + startTime < transaction.startTimestamp) {\n return;\n }\n\n switch (entry.entryType) {\n case 'navigation':\n {\n addNavigationSpans(transaction, entry, timeOrigin);\n responseStartTimestamp = timeOrigin + msToSec(entry.responseStart);\n requestStartTimestamp = timeOrigin + msToSec(entry.requestStart);\n break;\n }\n\n case 'mark':\n case 'paint':\n case 'measure':\n {\n var startTimestamp = addMeasureSpans(transaction, entry, startTime, duration, timeOrigin);\n\n if (tracingInitMarkStartTime === undefined && entry.name === 'sentry-tracing-init') {\n tracingInitMarkStartTime = startTimestamp;\n } // capture web vitals\n\n\n var firstHidden = getVisibilityWatcher(); // Only report if the page wasn't hidden prior to the web vital.\n\n var shouldRecord = entry.startTime < firstHidden.firstHiddenTime;\n\n if (entry.name === 'first-paint' && shouldRecord) {\n logger.log('[Measurements] Adding FP');\n _this._measurements['fp'] = {\n value: entry.startTime\n };\n _this._measurements['mark.fp'] = {\n value: startTimestamp\n };\n }\n\n if (entry.name === 'first-contentful-paint' && shouldRecord) {\n logger.log('[Measurements] Adding FCP');\n _this._measurements['fcp'] = {\n value: entry.startTime\n };\n _this._measurements['mark.fcp'] = {\n value: startTimestamp\n };\n }\n\n break;\n }\n\n case 'resource':\n {\n var resourceName = entry.name.replace(global.location.origin, '');\n 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\n\n if (entryScriptStartTimestamp === undefined && (entryScriptSrc || '').indexOf(resourceName) > -1) {\n entryScriptStartTimestamp = endTimestamp;\n }\n\n break;\n }\n\n default: // Ignore other entry types.\n\n }\n });\n\n if (entryScriptStartTimestamp !== undefined && tracingInitMarkStartTime !== undefined) {\n _startChild(transaction, {\n description: 'evaluation',\n endTimestamp: tracingInitMarkStartTime,\n op: 'script',\n startTimestamp: entryScriptStartTimestamp\n });\n }\n\n this._performanceCursor = Math.max(performance.getEntries().length - 1, 0);\n\n this._trackNavigator(transaction); // Measurements are only available for pageload transactions\n\n\n if (transaction.op === 'pageload') {\n // normalize applicable web vital values to be relative to transaction.startTimestamp\n var timeOrigin_1 = msToSec(browserPerformanceTimeOrigin); // Generate TTFB (Time to First Byte), which measured as the time between the beginning of the transaction and the\n // start of the response in milliseconds\n\n if (typeof responseStartTimestamp === 'number') {\n logger.log('[Measurements] Adding TTFB');\n this._measurements['ttfb'] = {\n value: (responseStartTimestamp - transaction.startTimestamp) * 1000\n };\n\n if (typeof requestStartTimestamp === 'number' && requestStartTimestamp <= responseStartTimestamp) {\n // Capture the time spent making the request and receiving the first byte of the response.\n // This is the time between the start of the request and the start of the response in milliseconds.\n this._measurements['ttfb.requestTime'] = {\n value: (responseStartTimestamp - requestStartTimestamp) * 1000\n };\n }\n }\n\n ['fcp', 'fp', 'lcp'].forEach(function (name) {\n if (!_this._measurements[name] || timeOrigin_1 >= transaction.startTimestamp) {\n return;\n } // The web vitals, fcp, fp, lcp, and ttfb, all measure relative to timeOrigin.\n // Unfortunately, timeOrigin is not captured within the transaction span data, so these web vitals will need\n // to be adjusted to be relative to transaction.startTimestamp.\n\n\n var oldValue = _this._measurements[name].value;\n var measurementTimestamp = timeOrigin_1 + msToSec(oldValue); // normalizedValue should be in milliseconds\n\n var normalizedValue = Math.abs((measurementTimestamp - transaction.startTimestamp) * 1000);\n var delta = normalizedValue - oldValue;\n logger.log(\"[Measurements] Normalized \" + name + \" from \" + oldValue + \" to \" + normalizedValue + \" (\" + delta + \")\");\n _this._measurements[name].value = normalizedValue;\n });\n\n if (this._measurements['mark.fid'] && this._measurements['fid']) {\n // create span for FID\n _startChild(transaction, {\n description: 'first input delay',\n endTimestamp: this._measurements['mark.fid'].value + msToSec(this._measurements['fid'].value),\n op: 'web.vitals',\n startTimestamp: this._measurements['mark.fid'].value\n });\n } // If FCP is not recorded we should not record the cls value\n // according to the new definition of CLS.\n\n\n if (!('fcp' in this._measurements)) {\n delete this._measurements.cls;\n }\n\n transaction.setMeasurements(this._measurements);\n\n this._tagMetricInfo(transaction);\n\n transaction.setTag('sentry_reportAllChanges', this._reportAllChanges);\n }\n };\n /** Add LCP / CLS data to transaction to allow debugging */\n\n\n MetricsInstrumentation.prototype._tagMetricInfo = function (transaction) {\n if (this._lcpEntry) {\n logger.log('[Measurements] Adding LCP Data'); // Capture Properties of the LCP element that contributes to the LCP.\n\n if (this._lcpEntry.element) {\n transaction.setTag('lcp.element', htmlTreeAsString(this._lcpEntry.element));\n }\n\n if (this._lcpEntry.id) {\n transaction.setTag('lcp.id', this._lcpEntry.id);\n }\n\n if (this._lcpEntry.url) {\n // Trim URL to the first 200 characters.\n transaction.setTag('lcp.url', this._lcpEntry.url.trim().slice(0, 200));\n }\n\n transaction.setTag('lcp.size', this._lcpEntry.size);\n } // See: https://developer.mozilla.org/en-US/docs/Web/API/LayoutShift\n\n\n if (this._clsEntry && this._clsEntry.sources) {\n logger.log('[Measurements] Adding CLS Data');\n\n this._clsEntry.sources.forEach(function (source, index) {\n return transaction.setTag(\"cls.source.\" + (index + 1), htmlTreeAsString(source.node));\n });\n }\n };\n /** Starts tracking the Cumulative Layout Shift on the current page. */\n\n\n MetricsInstrumentation.prototype._trackCLS = function () {\n var _this = this; // See:\n // https://web.dev/evolving-cls/\n // https://web.dev/cls-web-tooling/\n\n\n getCLS(function (metric) {\n var entry = metric.entries.pop();\n\n if (!entry) {\n return;\n }\n\n logger.log('[Measurements] Adding CLS');\n _this._measurements['cls'] = {\n value: metric.value\n };\n _this._clsEntry = entry;\n });\n };\n /**\n * Capture the information of the user agent.\n */\n\n\n MetricsInstrumentation.prototype._trackNavigator = function (transaction) {\n var navigator = global.navigator;\n\n if (!navigator) {\n return;\n } // track network connectivity\n\n\n var connection = navigator.connection;\n\n if (connection) {\n if (connection.effectiveType) {\n transaction.setTag('effectiveConnectionType', connection.effectiveType);\n }\n\n if (connection.type) {\n transaction.setTag('connectionType', connection.type);\n }\n\n if (isMeasurementValue(connection.rtt)) {\n this._measurements['connection.rtt'] = {\n value: connection.rtt\n };\n }\n\n if (isMeasurementValue(connection.downlink)) {\n this._measurements['connection.downlink'] = {\n value: connection.downlink\n };\n }\n }\n\n if (isMeasurementValue(navigator.deviceMemory)) {\n transaction.setTag('deviceMemory', String(navigator.deviceMemory));\n }\n\n if (isMeasurementValue(navigator.hardwareConcurrency)) {\n transaction.setTag('hardwareConcurrency', String(navigator.hardwareConcurrency));\n }\n };\n /** Starts tracking the Largest Contentful Paint on the current page. */\n\n\n MetricsInstrumentation.prototype._trackLCP = function () {\n var _this = this;\n\n getLCP(function (metric) {\n var entry = metric.entries.pop();\n\n if (!entry) {\n return;\n }\n\n var timeOrigin = msToSec(browserPerformanceTimeOrigin);\n var startTime = msToSec(entry.startTime);\n logger.log('[Measurements] Adding LCP');\n _this._measurements['lcp'] = {\n value: metric.value\n };\n _this._measurements['mark.lcp'] = {\n value: timeOrigin + startTime\n };\n _this._lcpEntry = entry;\n }, this._reportAllChanges);\n };\n /** Starts tracking the First Input Delay on the current page. */\n\n\n MetricsInstrumentation.prototype._trackFID = function () {\n var _this = this;\n\n getFID(function (metric) {\n var entry = metric.entries.pop();\n\n if (!entry) {\n return;\n }\n\n var timeOrigin = msToSec(browserPerformanceTimeOrigin);\n var startTime = msToSec(entry.startTime);\n logger.log('[Measurements] Adding FID');\n _this._measurements['fid'] = {\n value: metric.value\n };\n _this._measurements['mark.fid'] = {\n value: timeOrigin + startTime\n };\n });\n };\n\n return MetricsInstrumentation;\n}();\n\nexport { MetricsInstrumentation };\n/** Instrument navigation entries */\n\nfunction addNavigationSpans(transaction, entry, timeOrigin) {\n addPerformanceNavigationTiming({\n transaction: transaction,\n entry: entry,\n event: 'unloadEvent',\n timeOrigin: timeOrigin\n });\n addPerformanceNavigationTiming({\n transaction: transaction,\n entry: entry,\n event: 'redirect',\n timeOrigin: timeOrigin\n });\n addPerformanceNavigationTiming({\n transaction: transaction,\n entry: entry,\n event: 'domContentLoadedEvent',\n timeOrigin: timeOrigin\n });\n addPerformanceNavigationTiming({\n transaction: transaction,\n entry: entry,\n event: 'loadEvent',\n timeOrigin: timeOrigin\n });\n addPerformanceNavigationTiming({\n transaction: transaction,\n entry: entry,\n event: 'connect',\n timeOrigin: timeOrigin\n });\n addPerformanceNavigationTiming({\n transaction: transaction,\n entry: entry,\n event: 'secureConnection',\n timeOrigin: timeOrigin,\n eventEnd: 'connectEnd',\n description: 'TLS/SSL'\n });\n addPerformanceNavigationTiming({\n transaction: transaction,\n entry: entry,\n event: 'fetch',\n timeOrigin: timeOrigin,\n eventEnd: 'domainLookupStart',\n description: 'cache'\n });\n addPerformanceNavigationTiming({\n transaction: transaction,\n entry: entry,\n event: 'domainLookup',\n timeOrigin: timeOrigin,\n description: 'DNS'\n });\n addRequest(transaction, entry, timeOrigin);\n}\n/** Create measure related spans */\n\n\nfunction addMeasureSpans(transaction, entry, startTime, duration, timeOrigin) {\n var measureStartTimestamp = timeOrigin + startTime;\n var measureEndTimestamp = measureStartTimestamp + duration;\n\n _startChild(transaction, {\n description: entry.name,\n endTimestamp: measureEndTimestamp,\n op: entry.entryType,\n startTimestamp: measureStartTimestamp\n });\n\n return measureStartTimestamp;\n}\n/** Create resource-related spans */\n\n\nexport function addResourceSpans(transaction, entry, resourceName, startTime, duration, timeOrigin) {\n // we already instrument based on fetch and xhr, so we don't need to\n // duplicate spans here.\n if (entry.initiatorType === 'xmlhttprequest' || entry.initiatorType === 'fetch') {\n return undefined;\n }\n\n var data = {};\n\n if ('transferSize' in entry) {\n data['Transfer Size'] = entry.transferSize;\n }\n\n if ('encodedBodySize' in entry) {\n data['Encoded Body Size'] = entry.encodedBodySize;\n }\n\n if ('decodedBodySize' in entry) {\n data['Decoded Body Size'] = entry.decodedBodySize;\n }\n\n var startTimestamp = timeOrigin + startTime;\n var endTimestamp = startTimestamp + duration;\n\n _startChild(transaction, {\n description: resourceName,\n endTimestamp: endTimestamp,\n op: entry.initiatorType ? \"resource.\" + entry.initiatorType : 'resource',\n startTimestamp: startTimestamp,\n data: data\n });\n\n return endTimestamp;\n}\n/** Create performance navigation related spans */\n\nfunction addPerformanceNavigationTiming(props) {\n var transaction = props.transaction,\n entry = props.entry,\n event = props.event,\n timeOrigin = props.timeOrigin,\n eventEnd = props.eventEnd,\n description = props.description;\n var end = eventEnd ? entry[eventEnd] : entry[event + \"End\"];\n var start = entry[event + \"Start\"];\n\n if (!start || !end) {\n return;\n }\n\n _startChild(transaction, {\n op: 'browser',\n description: description !== null && description !== void 0 ? description : event,\n startTimestamp: timeOrigin + msToSec(start),\n endTimestamp: timeOrigin + msToSec(end)\n });\n}\n/** Create request and response related spans */\n\n\nfunction addRequest(transaction, entry, timeOrigin) {\n _startChild(transaction, {\n op: 'browser',\n description: 'request',\n startTimestamp: timeOrigin + msToSec(entry.requestStart),\n endTimestamp: timeOrigin + msToSec(entry.responseEnd)\n });\n\n _startChild(transaction, {\n op: 'browser',\n description: 'response',\n startTimestamp: timeOrigin + msToSec(entry.responseStart),\n endTimestamp: timeOrigin + msToSec(entry.responseEnd)\n });\n}\n/**\n * Helper function to start child on transactions. This function will make sure that the transaction will\n * use the start timestamp of the created child span if it is earlier than the transactions actual\n * start timestamp.\n */\n\n\nexport function _startChild(transaction, _a) {\n var startTimestamp = _a.startTimestamp,\n ctx = __rest(_a, [\"startTimestamp\"]);\n\n if (startTimestamp && transaction.startTimestamp > startTimestamp) {\n transaction.startTimestamp = startTimestamp;\n }\n\n return transaction.startChild(__assign({\n startTimestamp: startTimestamp\n }, ctx));\n}\n/**\n * Checks if a given value is a valid measurement value.\n */\n\nfunction isMeasurementValue(value) {\n return typeof value === 'number' && isFinite(value);\n}","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { bindReporter } from './lib/bindReporter';\nimport { initMetric } from './lib/initMetric';\nimport { observe } from './lib/observe';\nimport { onHidden } from './lib/onHidden';\nexport var getCLS = function getCLS(onReport, reportAllChanges) {\n var metric = initMetric('CLS', 0);\n var report;\n var sessionValue = 0;\n var sessionEntries = [];\n\n var entryHandler = function entryHandler(entry) {\n // Only count layout shifts without recent user input.\n // TODO: Figure out why entry can be undefined\n if (entry && !entry.hadRecentInput) {\n var firstSessionEntry = sessionEntries[0];\n var lastSessionEntry = sessionEntries[sessionEntries.length - 1]; // If the entry occurred less than 1 second after the previous entry and\n // less than 5 seconds after the first entry in the session, include the\n // entry in the current session. Otherwise, start a new session.\n\n if (sessionValue && sessionEntries.length !== 0 && entry.startTime - lastSessionEntry.startTime < 1000 && entry.startTime - firstSessionEntry.startTime < 5000) {\n sessionValue += entry.value;\n sessionEntries.push(entry);\n } else {\n sessionValue = entry.value;\n sessionEntries = [entry];\n } // If the current session value is larger than the current CLS value,\n // update CLS and the entries contributing to it.\n\n\n if (sessionValue > metric.value) {\n metric.value = sessionValue;\n metric.entries = sessionEntries;\n\n if (report) {\n report();\n }\n }\n }\n };\n\n var po = observe('layout-shift', entryHandler);\n\n if (po) {\n report = bindReporter(onReport, metric, reportAllChanges);\n onHidden(function () {\n po.takeRecords().map(entryHandler);\n report(true);\n });\n }\n};","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { bindReporter } from './lib/bindReporter';\nimport { getVisibilityWatcher } from './lib/getVisibilityWatcher';\nimport { initMetric } from './lib/initMetric';\nimport { observe } from './lib/observe';\nimport { onHidden } from './lib/onHidden';\nexport var getFID = function getFID(onReport, reportAllChanges) {\n var visibilityWatcher = getVisibilityWatcher();\n var metric = initMetric('FID');\n var report;\n\n var entryHandler = function entryHandler(entry) {\n // Only report if the page wasn't hidden prior to the first input.\n if (report && entry.startTime < visibilityWatcher.firstHiddenTime) {\n metric.value = entry.processingStart - entry.startTime;\n metric.entries.push(entry);\n report(true);\n }\n };\n\n var po = observe('first-input', entryHandler);\n\n if (po) {\n report = bindReporter(onReport, metric, reportAllChanges);\n onHidden(function () {\n po.takeRecords().map(entryHandler);\n po.disconnect();\n }, true);\n }\n};","import { __assign, __read, __spread } from \"tslib\";\nimport { addInstrumentationHandler, isInstanceOf, isMatchingPattern } from '@sentry/utils';\nimport { SpanStatus } from '../spanstatus';\nimport { getActiveTransaction, hasTracingEnabled } from '../utils';\nexport var DEFAULT_TRACING_ORIGINS = ['localhost', /^\\//];\nexport var defaultRequestInstrumentationOptions = {\n traceFetch: true,\n traceXHR: true,\n tracingOrigins: DEFAULT_TRACING_ORIGINS\n};\n/** Registers span creators for xhr and fetch requests */\n\nexport function instrumentOutgoingRequests(_options) {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n var _a = __assign(__assign({}, defaultRequestInstrumentationOptions), _options),\n traceFetch = _a.traceFetch,\n traceXHR = _a.traceXHR,\n tracingOrigins = _a.tracingOrigins,\n shouldCreateSpanForRequest = _a.shouldCreateSpanForRequest; // We should cache url -> decision so that we don't have to compute\n // regexp everytime we create a request.\n\n\n var urlMap = {};\n\n var defaultShouldCreateSpan = function defaultShouldCreateSpan(url) {\n if (urlMap[url]) {\n return urlMap[url];\n }\n\n var origins = tracingOrigins;\n urlMap[url] = origins.some(function (origin) {\n return isMatchingPattern(url, origin);\n }) && !isMatchingPattern(url, 'sentry_key');\n return urlMap[url];\n }; // We want that our users don't have to re-implement shouldCreateSpanForRequest themselves\n // That's why we filter out already unwanted Spans from tracingOrigins\n\n\n var shouldCreateSpan = defaultShouldCreateSpan;\n\n if (typeof shouldCreateSpanForRequest === 'function') {\n shouldCreateSpan = function shouldCreateSpan(url) {\n return defaultShouldCreateSpan(url) && shouldCreateSpanForRequest(url);\n };\n }\n\n var spans = {};\n\n if (traceFetch) {\n addInstrumentationHandler({\n callback: function callback(handlerData) {\n fetchCallback(handlerData, shouldCreateSpan, spans);\n },\n type: 'fetch'\n });\n }\n\n if (traceXHR) {\n addInstrumentationHandler({\n callback: function callback(handlerData) {\n xhrCallback(handlerData, shouldCreateSpan, spans);\n },\n type: 'xhr'\n });\n }\n}\n/**\n * Create and track fetch request spans\n */\n\nexport function fetchCallback(handlerData, shouldCreateSpan, spans) {\n if (!hasTracingEnabled() || !(handlerData.fetchData && shouldCreateSpan(handlerData.fetchData.url))) {\n return;\n }\n\n if (handlerData.endTimestamp && handlerData.fetchData.__span) {\n var span = spans[handlerData.fetchData.__span];\n\n if (span) {\n if (handlerData.response) {\n // TODO (kmclb) remove this once types PR goes through\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n span.setHttpStatus(handlerData.response.status);\n } else if (handlerData.error) {\n span.setStatus(SpanStatus.InternalError);\n }\n\n span.finish(); // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n\n delete spans[handlerData.fetchData.__span];\n }\n\n return;\n }\n\n var activeTransaction = getActiveTransaction();\n\n if (activeTransaction) {\n var span = activeTransaction.startChild({\n data: __assign(__assign({}, handlerData.fetchData), {\n type: 'fetch'\n }),\n description: handlerData.fetchData.method + \" \" + handlerData.fetchData.url,\n op: 'http.client'\n });\n handlerData.fetchData.__span = span.spanId;\n spans[span.spanId] = span;\n var request = handlerData.args[0] = handlerData.args[0]; // eslint-disable-next-line @typescript-eslint/no-explicit-any\n\n var options = handlerData.args[1] = handlerData.args[1] || {};\n var headers = options.headers;\n\n if (isInstanceOf(request, Request)) {\n headers = request.headers;\n }\n\n if (headers) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if (typeof headers.append === 'function') {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n headers.append('sentry-trace', span.toTraceparent());\n } else if (Array.isArray(headers)) {\n headers = __spread(headers, [['sentry-trace', span.toTraceparent()]]);\n } else {\n headers = __assign(__assign({}, headers), {\n 'sentry-trace': span.toTraceparent()\n });\n }\n } else {\n headers = {\n 'sentry-trace': span.toTraceparent()\n };\n }\n\n options.headers = headers;\n }\n}\n/**\n * Create and track xhr request spans\n */\n\nexport function xhrCallback(handlerData, shouldCreateSpan, spans) {\n var _a, _b;\n\n if (!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))) {\n return;\n }\n\n var xhr = handlerData.xhr.__sentry_xhr__; // check first if the request has finished and is tracked by an existing span which should now end\n\n if (handlerData.endTimestamp && handlerData.xhr.__sentry_xhr_span_id__) {\n var span = spans[handlerData.xhr.__sentry_xhr_span_id__];\n\n if (span) {\n span.setHttpStatus(xhr.status_code);\n span.finish(); // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n\n delete spans[handlerData.xhr.__sentry_xhr_span_id__];\n }\n\n return;\n } // if not, create a new span to track it\n\n\n var activeTransaction = getActiveTransaction();\n\n if (activeTransaction) {\n var span = activeTransaction.startChild({\n data: __assign(__assign({}, xhr.data), {\n type: 'xhr',\n method: xhr.method,\n url: xhr.url\n }),\n description: xhr.method + \" \" + xhr.url,\n op: 'http.client'\n });\n handlerData.xhr.__sentry_xhr_span_id__ = span.spanId;\n spans[handlerData.xhr.__sentry_xhr_span_id__] = span;\n\n if (handlerData.xhr.setRequestHeader) {\n try {\n handlerData.xhr.setRequestHeader('sentry-trace', span.toTraceparent());\n } catch (_) {// Error: InvalidStateError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': The object's state must be OPENED.\n }\n }\n }\n}","import { addInstrumentationHandler, getGlobalObject, logger } from '@sentry/utils';\nvar global = getGlobalObject();\n/**\n * Default function implementing pageload and navigation transactions\n */\n\nexport function instrumentRoutingWithDefaults(customStartTransaction, startTransactionOnPageLoad, startTransactionOnLocationChange) {\n if (startTransactionOnPageLoad === void 0) {\n startTransactionOnPageLoad = true;\n }\n\n if (startTransactionOnLocationChange === void 0) {\n startTransactionOnLocationChange = true;\n }\n\n if (!global || !global.location) {\n logger.warn('Could not initialize routing instrumentation due to invalid location');\n return;\n }\n\n var startingUrl = global.location.href;\n var activeTransaction;\n\n if (startTransactionOnPageLoad) {\n activeTransaction = customStartTransaction({\n name: global.location.pathname,\n op: 'pageload'\n });\n }\n\n if (startTransactionOnLocationChange) {\n addInstrumentationHandler({\n callback: function callback(_a) {\n var to = _a.to,\n from = _a.from;\n /**\n * This early return is there to account for some cases where a navigation transaction starts right after\n * long-running pageload. We make sure that if `from` is undefined and a valid `startingURL` exists, we don't\n * create an uneccessary navigation transaction.\n *\n * This was hard to duplicate, but this behavior stopped as soon as this fix was applied. This issue might also\n * only be caused in certain development environments where the usage of a hot module reloader is causing\n * errors.\n */\n\n if (from === undefined && startingUrl && startingUrl.indexOf(to) !== -1) {\n startingUrl = undefined;\n return;\n }\n\n if (from !== to) {\n startingUrl = undefined;\n\n if (activeTransaction) {\n 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.\n\n activeTransaction.finish();\n }\n\n activeTransaction = customStartTransaction({\n name: global.location.pathname,\n op: 'navigation'\n });\n }\n },\n type: 'history'\n });\n }\n}","import { __assign } from \"tslib\";\nimport { getGlobalObject, logger } from '@sentry/utils';\nimport { startIdleTransaction } from '../hubextensions';\nimport { DEFAULT_IDLE_TIMEOUT } from '../idletransaction';\nimport { SpanStatus } from '../spanstatus';\nimport { extractTraceparentData, secToMs } from '../utils';\nimport { registerBackgroundTabDetection } from './backgroundtab';\nimport { MetricsInstrumentation } from './metrics';\nimport { defaultRequestInstrumentationOptions, instrumentOutgoingRequests } from './request';\nimport { instrumentRoutingWithDefaults } from './router';\nexport var DEFAULT_MAX_TRANSACTION_DURATION_SECONDS = 600;\n\nvar DEFAULT_BROWSER_TRACING_OPTIONS = __assign({\n idleTimeout: DEFAULT_IDLE_TIMEOUT,\n markBackgroundTransactions: true,\n maxTransactionDuration: DEFAULT_MAX_TRANSACTION_DURATION_SECONDS,\n routingInstrumentation: instrumentRoutingWithDefaults,\n startTransactionOnLocationChange: true,\n startTransactionOnPageLoad: true\n}, defaultRequestInstrumentationOptions);\n/**\n * The Browser Tracing integration automatically instruments browser pageload/navigation\n * actions as transactions, and captures requests, metrics and errors as spans.\n *\n * The integration can be configured with a variety of options, and can be extended to use\n * any routing library. This integration uses {@see IdleTransaction} to create transactions.\n */\n\n\nvar BrowserTracing =\n/** @class */\nfunction () {\n function BrowserTracing(_options) {\n /**\n * @inheritDoc\n */\n this.name = BrowserTracing.id;\n this._emitOptionsWarning = false;\n /** Store configured idle timeout so that it can be added as a tag to transactions */\n\n this._configuredIdleTimeout = undefined;\n var tracingOrigins = defaultRequestInstrumentationOptions.tracingOrigins; // NOTE: Logger doesn't work in constructors, as it's initialized after integrations instances\n\n if (_options) {\n this._configuredIdleTimeout = _options.idleTimeout;\n\n if (_options.tracingOrigins && Array.isArray(_options.tracingOrigins) && _options.tracingOrigins.length !== 0) {\n tracingOrigins = _options.tracingOrigins;\n } else {\n this._emitOptionsWarning = true;\n }\n }\n\n this.options = __assign(__assign(__assign({}, DEFAULT_BROWSER_TRACING_OPTIONS), _options), {\n tracingOrigins: tracingOrigins\n });\n var _metricOptions = this.options._metricOptions;\n this._metrics = new MetricsInstrumentation(_metricOptions && _metricOptions._reportAllChanges);\n }\n /**\n * @inheritDoc\n */\n\n\n BrowserTracing.prototype.setupOnce = function (_, getCurrentHub) {\n var _this = this;\n\n this._getCurrentHub = getCurrentHub;\n\n if (this._emitOptionsWarning) {\n logger.warn('[Tracing] You need to define `tracingOrigins` in the options. Set an array of urls or patterns to trace.');\n logger.warn(\"[Tracing] We added a reasonable default for you: \" + defaultRequestInstrumentationOptions.tracingOrigins);\n } // eslint-disable-next-line @typescript-eslint/unbound-method\n\n\n var _a = this.options,\n instrumentRouting = _a.routingInstrumentation,\n startTransactionOnLocationChange = _a.startTransactionOnLocationChange,\n startTransactionOnPageLoad = _a.startTransactionOnPageLoad,\n markBackgroundTransactions = _a.markBackgroundTransactions,\n traceFetch = _a.traceFetch,\n traceXHR = _a.traceXHR,\n tracingOrigins = _a.tracingOrigins,\n shouldCreateSpanForRequest = _a.shouldCreateSpanForRequest;\n instrumentRouting(function (context) {\n return _this._createRouteTransaction(context);\n }, startTransactionOnPageLoad, startTransactionOnLocationChange);\n\n if (markBackgroundTransactions) {\n registerBackgroundTabDetection();\n }\n\n instrumentOutgoingRequests({\n traceFetch: traceFetch,\n traceXHR: traceXHR,\n tracingOrigins: tracingOrigins,\n shouldCreateSpanForRequest: shouldCreateSpanForRequest\n });\n };\n /** Create routing idle transaction. */\n\n\n BrowserTracing.prototype._createRouteTransaction = function (context) {\n var _this = this;\n\n if (!this._getCurrentHub) {\n logger.warn(\"[Tracing] Did not create \" + context.op + \" transaction because _getCurrentHub is invalid.\");\n return undefined;\n } // eslint-disable-next-line @typescript-eslint/unbound-method\n\n\n var _a = this.options,\n beforeNavigate = _a.beforeNavigate,\n idleTimeout = _a.idleTimeout,\n maxTransactionDuration = _a.maxTransactionDuration;\n var parentContextFromHeader = context.op === 'pageload' ? getHeaderContext() : undefined;\n\n var expandedContext = __assign(__assign(__assign({}, context), parentContextFromHeader), {\n trimEnd: true\n });\n\n var modifiedContext = typeof beforeNavigate === 'function' ? beforeNavigate(expandedContext) : expandedContext; // For backwards compatibility reasons, beforeNavigate can return undefined to \"drop\" the transaction (prevent it\n // from being sent to Sentry).\n\n var finalContext = modifiedContext === undefined ? __assign(__assign({}, expandedContext), {\n sampled: false\n }) : modifiedContext;\n\n if (finalContext.sampled === false) {\n logger.log(\"[Tracing] Will not send \" + finalContext.op + \" transaction because of beforeNavigate.\");\n }\n\n logger.log(\"[Tracing] Starting \" + finalContext.op + \" transaction on scope\");\n\n var hub = this._getCurrentHub();\n\n var location = getGlobalObject().location;\n var idleTransaction = startIdleTransaction(hub, finalContext, idleTimeout, true, {\n location: location\n });\n idleTransaction.registerBeforeFinishCallback(function (transaction, endTimestamp) {\n _this._metrics.addPerformanceEntries(transaction);\n\n adjustTransactionDuration(secToMs(maxTransactionDuration), transaction, endTimestamp);\n });\n idleTransaction.setTag('idleTimeout', this._configuredIdleTimeout);\n return idleTransaction;\n };\n /**\n * @inheritDoc\n */\n\n\n BrowserTracing.id = 'BrowserTracing';\n return BrowserTracing;\n}();\n\nexport { BrowserTracing };\n/**\n * Gets transaction context from a sentry-trace meta.\n *\n * @returns Transaction context data from the header or undefined if there's no header or the header is malformed\n */\n\nexport function getHeaderContext() {\n var header = getMetaContent('sentry-trace');\n\n if (header) {\n return extractTraceparentData(header);\n }\n\n return undefined;\n}\n/** Returns the value of a meta tag */\n\nexport function getMetaContent(metaName) {\n var el = getGlobalObject().document.querySelector(\"meta[name=\" + metaName + \"]\");\n return el ? el.getAttribute('content') : null;\n}\n/** Adjusts transaction value based on max transaction duration */\n\nfunction adjustTransactionDuration(maxDuration, transaction, endTimestamp) {\n var diff = endTimestamp - transaction.startTimestamp;\n var isOutdatedTransaction = endTimestamp && (diff > maxDuration || diff < 0);\n\n if (isOutdatedTransaction) {\n transaction.setStatus(SpanStatus.DeadlineExceeded);\n transaction.setTag('maxTransactionDurationExceeded', 'true');\n }\n}","import { addExtensionMethods } from './hubextensions';\nimport * as Integrations from './integrations';\nexport { Integrations }; // This is already exported as part of `Integrations` above (and for the moment will remain so for\n// backwards compatibility), but that interferes with treeshaking, so we also export it separately\n// here.\n//\n// Previously we expected users to import tracing integrations like\n//\n// import { Integrations } from '@sentry/tracing';\n// const instance = new Integrations.BrowserTracing();\n//\n// This makes the integrations unable to be treeshaken though. To address this, we now have\n// this individual export. We now expect users to consume BrowserTracing like so:\n//\n// import { BrowserTracing } from '@sentry/tracing';\n// const instance = new BrowserTracing();\n//\n// For an example of of the new usage of BrowserTracing, see @sentry/nextjs index.client.ts\n\nexport { BrowserTracing } from './browser';\nexport { Span } from './span';\nexport { Transaction } from './transaction';\nexport { // TODO deprecate old name in v7\ninstrumentOutgoingRequests as registerRequestInstrumentation, defaultRequestInstrumentationOptions } from './browser';\nexport { SpanStatus } from './spanstatus';\nexport { IdleTransaction } from './idletransaction';\nexport { startIdleTransaction } from './hubextensions'; // We are patching the global object with our hub extension methods\n\naddExtensionMethods();\nexport { addExtensionMethods };\nexport { extractTraceparentData, getActiveTransaction, hasTracingEnabled, stripUrlQueryAndFragment, TRACEPARENT_REGEXP } from './utils';","import React from \"react\";\nimport Toggle from \"react-toggle\";\nimport _ from \"lodash\";\nimport Loader from \"./loader\";\n\nclass Settings extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n ignoredSites: null,\n error: null,\n siteInput: \"\",\n defaultMode: \"\",\n changeInProgress: false,\n };\n\n this.ignoreSite = this.ignoreSite.bind(this);\n this.restoreSite = this.restoreSite.bind(this);\n this.updateSites = this.updateSites.bind(this);\n this.validate = this.validate.bind(this);\n this.formRef = React.createRef();\n this.changeDefaultMode = this.changeDefaultMode.bind(this);\n }\n\n componentDidMount() {\n const that = this;\n fetch(`/account/ignored_sites`)\n .then((response) => response.json())\n .then((ignoredSites) => {\n if (ignoredSites.error) {\n that.setState({ error: ignoredSites.error });\n } else if (_.isArray(ignoredSites)) {\n that.setState({ ignoredSites });\n }\n });\n if (AP.currentUser.default_mode !== this.state.defaultMode) {\n this.setState({ defaultMode: AP.currentUser.default_mode });\n }\n }\n\n ignoreSite() {\n let oldIgnoredSites = this.state.ignoredSites;\n if (!_.isArray(oldIgnoredSites)) {\n oldIgnoredSites = [];\n }\n const newIgnoredSites = this.state.ignoredSites.concat([\n this.state.siteInput,\n ]);\n this.setState({ ignoredSites: newIgnoredSites, siteInput: \"\" });\n this.updateSites(newIgnoredSites);\n }\n\n restoreSite(site) {\n const newIgnoredSites = _.filter(\n this.state.ignoredSites,\n (asite) => asite !== site\n );\n this.setState({ ignoredSites: newIgnoredSites });\n this.updateSites(newIgnoredSites);\n }\n\n updateSites(ignoredSites) {\n const that = this;\n fetch(\"/account/ignored_sites\", {\n method: \"put\",\n body: JSON.stringify({ ignored_sites: ignoredSites }),\n headers: {\n \"Content-Type\": \"application/json\",\n },\n credentials: \"same-origin\",\n })\n .then((response) => response.json())\n .then((response) => {\n if (response.success) {\n that.setState({ error: null });\n } else {\n that.setState({\n error: \"something went wrong updating the list of ignored sites\",\n });\n }\n });\n }\n\n validate(successFunction, event) {\n event.preventDefault();\n if (this.formRef.current.reportValidity()) {\n // check to see if valid URL\n // accepts URL's without protocol\n const { siteInput } = this.state;\n\n /* eslint-disable no-useless-escape */\n const urlRegex =\n /^(http:\\/\\/www\\.|https:\\/\\/www\\.|http:\\/\\/|https:\\/\\/)?[a-z0-9]+([\\-\\.]{1}[a-z0-9]+)*\\.[a-z]{2,5}(:[0-9]{1,5})?(\\/.*)?$/gi;\n if (urlRegex.test(siteInput)) {\n this.setState({ error: null });\n successFunction(event);\n } else {\n this.setState({ error: \"please enter a valid url\" });\n }\n }\n }\n\n changeDefaultMode() {\n this.setState({ changeInProgress: true }, () => {\n const currentMode = this.state.defaultMode;\n const newMode = currentMode === \"PRIVATE\" ? \"PUBLIC\" : \"PRIVATE\";\n fetch(`/account/default_mode`, {\n method: \"put\",\n body: JSON.stringify({ mode: newMode }),\n headers: {\n \"Content-Type\": \"application/json\",\n },\n credentials: \"same-origin\",\n })\n .then((response) => response.json())\n .then((response) => {\n if (response.error) {\n this.setState({ error: response.error });\n } else {\n this.setState({ defaultMode: newMode, changeInProgress: false });\n }\n });\n });\n }\n\n render() {\n const isLoading = this.state.ignoredSites === null;\n const { ignoredSites, defaultMode, changeInProgress } = this.state;\n return (\n
\n
\n
Sites to Ignore
\n
\n Have a specific site that you want to ignore when creating a content\n brief? Add it here to exclude it from analysis in future content\n briefs.\n
\n
\n Note: This affects all briefs generated by your team.\n
\n Typically, when you create a content brief, it is private by\n default. That means that it can only be accessed by logging into\n Topic with your account. Sharing a brief with a writer requires you\n to manually turn on a sharable link for that specific brief.\n
\n
\n However, this can become tedious if you want all of your content\n briefs to be accessible by your writers.\n
\n
\n This setting allows you to make all new content briefs public{\" \"}\n by default. When this is turned on, new content briefs will\n automatically be sharable via link.\n
\n We asked our customers about their experiences after upgrading.\n Here's what they had to say:\n
\n
\n
\n
\n
\n \n
\n
\n Danny Wong\n \n Senior Editor at Amerisleep\n
\n
\n
\n I love how Topic saves me time in creating SEO-optimized\n outlines and content, especially for longer-form articles.{\" \"}\n We save hundreds of hours{\" \"}\n each month.\n
\n
\n
\n
\n
\n \n
\n
\n Carrie Adkins\n \n VP of Content, wikiHow\n
\n
\n
\n It's been a very positive experience for our team. Optimizing\n our content with Topic is{\" \"}\n double or triple as fast as\n how we did it before.\n
\n
\n
\n
\n
\n \n
\n
\n Naomi Tepper\n \n Senior Manager, Magoosh\n
\n
\n
\n What impressed us the most about Topic is the fact that it\n effectively achieved better rankings without a lot of extra\n work. On one blog post, we{\" \"}\n \n increased new users by over 300%\n {\" \"}\n year-over-year.\n
\n
\n
\n
\n
\n
\n );\n}\n\nexport default UpgradeModal;\n","import React from \"react\";\nimport { getUrlParam } from \"./helpers\";\n\n// This is a slider that slides from the bottom that shows the user how to use Topic\n// it is toggled by a URL parameter \"guide=true\"\nclass IntroSlider extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n status: \"minimized\", // minimized, maximized\n };\n this.loadCalendly = this.loadCalendly.bind(this);\n }\n\n componentDidMount() {\n this.loadCalendly();\n }\n\n componentDidUpdate() {\n this.loadCalendly();\n }\n\n loadCalendly() {\n const calendlyScript = document.createElement(\"script\");\n calendlyScript.async = true;\n calendlyScript.src =\n \"https://assets.calendly.com/assets/external/widget.js\";\n document.head.appendChild(calendlyScript);\n }\n\n render() {\n const guide = getUrlParam(\"guide\"); // true or false\n\n return (\n guide === \"true\" && (\n