`.\r\n * @returns {Function} A `useDispatch` hook bound to the specified context.\r\n */\n\nexport function createDispatchHook(context) {\n if (context === void 0) {\n context = ReactReduxContext;\n }\n\n var useStore = context === ReactReduxContext ? useDefaultStore : createStoreHook(context);\n return function useDispatch() {\n var store = useStore();\n return store.dispatch;\n };\n}\n/**\r\n * A hook to access the redux `dispatch` function.\r\n *\r\n * @returns {any|function} redux store's `dispatch` function\r\n *\r\n * @example\r\n *\r\n * import React, { useCallback } from 'react'\r\n * import { useDispatch } from 'react-redux'\r\n *\r\n * export const CounterComponent = ({ value }) => {\r\n * const dispatch = useDispatch()\r\n * const increaseCounter = useCallback(() => dispatch({ type: 'increase-counter' }), [])\r\n * return (\r\n * \r\n * {value}\r\n * \r\n *
\r\n * )\r\n * }\r\n */\n\nexport var useDispatch = /*#__PURE__*/createDispatchHook();","import { useReducer, useRef, useMemo, useContext, useDebugValue } from 'react';\nimport { useReduxContext as useDefaultReduxContext } from './useReduxContext';\nimport { createSubscription } from '../utils/Subscription';\nimport { useIsomorphicLayoutEffect } from '../utils/useIsomorphicLayoutEffect';\nimport { ReactReduxContext } from '../components/Context';\n\nvar refEquality = function refEquality(a, b) {\n return a === b;\n};\n\nfunction useSelectorWithStoreAndSubscription(selector, equalityFn, store, contextSub) {\n var _useReducer = useReducer(function (s) {\n return s + 1;\n }, 0),\n forceRender = _useReducer[1];\n\n var subscription = useMemo(function () {\n return createSubscription(store, contextSub);\n }, [store, contextSub]);\n var latestSubscriptionCallbackError = useRef();\n var latestSelector = useRef();\n var latestStoreState = useRef();\n var latestSelectedState = useRef();\n var storeState = store.getState();\n var selectedState;\n\n try {\n if (selector !== latestSelector.current || storeState !== latestStoreState.current || latestSubscriptionCallbackError.current) {\n var newSelectedState = selector(storeState); // ensure latest selected state is reused so that a custom equality function can result in identical references\n\n if (latestSelectedState.current === undefined || !equalityFn(newSelectedState, latestSelectedState.current)) {\n selectedState = newSelectedState;\n } else {\n selectedState = latestSelectedState.current;\n }\n } else {\n selectedState = latestSelectedState.current;\n }\n } catch (err) {\n if (latestSubscriptionCallbackError.current) {\n err.message += \"\\nThe error may be correlated with this previous error:\\n\" + latestSubscriptionCallbackError.current.stack + \"\\n\\n\";\n }\n\n throw err;\n }\n\n useIsomorphicLayoutEffect(function () {\n latestSelector.current = selector;\n latestStoreState.current = storeState;\n latestSelectedState.current = selectedState;\n latestSubscriptionCallbackError.current = undefined;\n });\n useIsomorphicLayoutEffect(function () {\n function checkForUpdates() {\n try {\n var newStoreState = store.getState(); // Avoid calling selector multiple times if the store's state has not changed\n\n if (newStoreState === latestStoreState.current) {\n return;\n }\n\n var _newSelectedState = latestSelector.current(newStoreState);\n\n if (equalityFn(_newSelectedState, latestSelectedState.current)) {\n return;\n }\n\n latestSelectedState.current = _newSelectedState;\n latestStoreState.current = newStoreState;\n } catch (err) {\n // we ignore all errors here, since when the component\n // is re-rendered, the selectors are called again, and\n // will throw again, if neither props nor store state\n // changed\n latestSubscriptionCallbackError.current = err;\n }\n\n forceRender();\n }\n\n subscription.onStateChange = checkForUpdates;\n subscription.trySubscribe();\n checkForUpdates();\n return function () {\n return subscription.tryUnsubscribe();\n };\n }, [store, subscription]);\n return selectedState;\n}\n/**\r\n * Hook factory, which creates a `useSelector` hook bound to a given context.\r\n *\r\n * @param {React.Context} [context=ReactReduxContext] Context passed to your ``.\r\n * @returns {Function} A `useSelector` hook bound to the specified context.\r\n */\n\n\nexport function createSelectorHook(context) {\n if (context === void 0) {\n context = ReactReduxContext;\n }\n\n var useReduxContext = context === ReactReduxContext ? useDefaultReduxContext : function () {\n return useContext(context);\n };\n return function useSelector(selector, equalityFn) {\n if (equalityFn === void 0) {\n equalityFn = refEquality;\n }\n\n if (process.env.NODE_ENV !== 'production') {\n if (!selector) {\n throw new Error(\"You must pass a selector to useSelector\");\n }\n\n if (typeof selector !== 'function') {\n throw new Error(\"You must pass a function as a selector to useSelector\");\n }\n\n if (typeof equalityFn !== 'function') {\n throw new Error(\"You must pass a function as an equality function to useSelector\");\n }\n }\n\n var _useReduxContext = useReduxContext(),\n store = _useReduxContext.store,\n contextSub = _useReduxContext.subscription;\n\n var selectedState = useSelectorWithStoreAndSubscription(selector, equalityFn, store, contextSub);\n useDebugValue(selectedState);\n return selectedState;\n };\n}\n/**\r\n * A hook to access the redux store's state. This hook takes a selector function\r\n * as an argument. The selector is called with the store state.\r\n *\r\n * This hook takes an optional equality comparison function as the second parameter\r\n * that allows you to customize the way the selected state is compared to determine\r\n * whether the component needs to be re-rendered.\r\n *\r\n * @param {Function} selector the selector function\r\n * @param {Function=} equalityFn the function that will be used to determine equality\r\n *\r\n * @returns {any} the selected state\r\n *\r\n * @example\r\n *\r\n * import React from 'react'\r\n * import { useSelector } from 'react-redux'\r\n *\r\n * export const CounterComponent = () => {\r\n * const counter = useSelector(state => state.counter)\r\n * return {counter}
\r\n * }\r\n */\n\nexport var useSelector = /*#__PURE__*/createSelectorHook();","export * from './exports';\nimport { unstable_batchedUpdates as batch } from './utils/reactBatchedUpdates';\nimport { setBatch } from './utils/batch'; // Enable batched updates in our subscriptions for use\n// with standard React renderers (ReactDOM, React Native)\n\nsetBatch(batch);\nexport { batch };","/******************************************************************************\nCopyright (c) Microsoft Corporation.\n\nPermission to use, copy, modify, and/or distribute this software for any\npurpose with or without fee is hereby granted.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\nPERFORMANCE OF THIS SOFTWARE.\n***************************************************************************** */\n/* global Reflect, Promise, SuppressedError, Symbol */\n\nvar extendStatics = function(d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\n return extendStatics(d, b);\n};\n\nexport function __extends(d, b) {\n if (typeof b !== \"function\" && b !== null)\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n}\n\nexport var __assign = function() {\n __assign = Object.assign || function __assign(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\n }\n return t;\n }\n return __assign.apply(this, arguments);\n}\n\nexport function __rest(s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n}\n\nexport function __decorate(decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n}\n\nexport function __param(paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n}\n\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\n var _, done = false;\n for (var i = decorators.length - 1; i >= 0; i--) {\n var context = {};\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\n if (kind === \"accessor\") {\n if (result === void 0) continue;\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\n if (_ = accept(result.get)) descriptor.get = _;\n if (_ = accept(result.set)) descriptor.set = _;\n if (_ = accept(result.init)) initializers.unshift(_);\n }\n else if (_ = accept(result)) {\n if (kind === \"field\") initializers.unshift(_);\n else descriptor[key] = _;\n }\n }\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\n done = true;\n};\n\nexport function __runInitializers(thisArg, initializers, value) {\n var useValue = arguments.length > 2;\n for (var i = 0; i < initializers.length; i++) {\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\n }\n return useValue ? value : void 0;\n};\n\nexport function __propKey(x) {\n return typeof x === \"symbol\" ? x : \"\".concat(x);\n};\n\nexport function __setFunctionName(f, name, prefix) {\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\n};\n\nexport function __metadata(metadataKey, metadataValue) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\n}\n\nexport function __awaiter(thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n}\n\nexport function __generator(thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n}\n\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n});\n\nexport function __exportStar(m, o) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\n}\n\nexport function __values(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n}\n\nexport function __read(o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n}\n\n/** @deprecated */\nexport function __spread() {\n for (var ar = [], i = 0; i < arguments.length; i++)\n ar = ar.concat(__read(arguments[i]));\n return ar;\n}\n\n/** @deprecated */\nexport function __spreadArrays() {\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\n r[k] = a[j];\n return r;\n}\n\nexport function __spreadArray(to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n}\n\nexport function __await(v) {\n return this instanceof __await ? (this.v = v, this) : new __await(v);\n}\n\nexport function __asyncGenerator(thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n}\n\nexport function __asyncDelegator(o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\n}\n\nexport function __asyncValues(o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n}\n\nexport function __makeTemplateObject(cooked, raw) {\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\n return cooked;\n};\n\nvar __setModuleDefault = Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n};\n\nexport function __importStar(mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n}\n\nexport function __importDefault(mod) {\n return (mod && mod.__esModule) ? mod : { default: mod };\n}\n\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n}\n\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n}\n\nexport function __classPrivateFieldIn(state, receiver) {\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\n}\n\nexport function __addDisposableResource(env, value, async) {\n if (value !== null && value !== void 0) {\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\n var dispose;\n if (async) {\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\n dispose = value[Symbol.asyncDispose];\n }\n if (dispose === void 0) {\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\n dispose = value[Symbol.dispose];\n }\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\n env.stack.push({ value: value, dispose: dispose, async: async });\n }\n else if (async) {\n env.stack.push({ async: true });\n }\n return value;\n}\n\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\n var e = new Error(message);\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\n};\n\nexport function __disposeResources(env) {\n function fail(e) {\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\n env.hasError = true;\n }\n function next() {\n while (env.stack.length) {\n var rec = env.stack.pop();\n try {\n var result = rec.dispose && rec.dispose.call(rec.value);\n if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\n }\n catch (e) {\n fail(e);\n }\n }\n if (env.hasError) throw env.error;\n }\n return next();\n}\n\nexport default {\n __extends,\n __assign,\n __rest,\n __decorate,\n __param,\n __metadata,\n __awaiter,\n __generator,\n __createBinding,\n __exportStar,\n __values,\n __read,\n __spread,\n __spreadArrays,\n __spreadArray,\n __await,\n __asyncGenerator,\n __asyncDelegator,\n __asyncValues,\n __makeTemplateObject,\n __importStar,\n __importDefault,\n __classPrivateFieldGet,\n __classPrivateFieldSet,\n __classPrivateFieldIn,\n __addDisposableResource,\n __disposeResources,\n};\n","export var ErrorKind;\n(function (ErrorKind) {\n /** Argument is unclosed (e.g. `{0`) */\n ErrorKind[ErrorKind[\"EXPECT_ARGUMENT_CLOSING_BRACE\"] = 1] = \"EXPECT_ARGUMENT_CLOSING_BRACE\";\n /** Argument is empty (e.g. `{}`). */\n ErrorKind[ErrorKind[\"EMPTY_ARGUMENT\"] = 2] = \"EMPTY_ARGUMENT\";\n /** Argument is malformed (e.g. `{foo!}``) */\n ErrorKind[ErrorKind[\"MALFORMED_ARGUMENT\"] = 3] = \"MALFORMED_ARGUMENT\";\n /** Expect an argument type (e.g. `{foo,}`) */\n ErrorKind[ErrorKind[\"EXPECT_ARGUMENT_TYPE\"] = 4] = \"EXPECT_ARGUMENT_TYPE\";\n /** Unsupported argument type (e.g. `{foo,foo}`) */\n ErrorKind[ErrorKind[\"INVALID_ARGUMENT_TYPE\"] = 5] = \"INVALID_ARGUMENT_TYPE\";\n /** Expect an argument style (e.g. `{foo, number, }`) */\n ErrorKind[ErrorKind[\"EXPECT_ARGUMENT_STYLE\"] = 6] = \"EXPECT_ARGUMENT_STYLE\";\n /** The number skeleton is invalid. */\n ErrorKind[ErrorKind[\"INVALID_NUMBER_SKELETON\"] = 7] = \"INVALID_NUMBER_SKELETON\";\n /** The date time skeleton is invalid. */\n ErrorKind[ErrorKind[\"INVALID_DATE_TIME_SKELETON\"] = 8] = \"INVALID_DATE_TIME_SKELETON\";\n /** Exepct a number skeleton following the `::` (e.g. `{foo, number, ::}`) */\n ErrorKind[ErrorKind[\"EXPECT_NUMBER_SKELETON\"] = 9] = \"EXPECT_NUMBER_SKELETON\";\n /** Exepct a date time skeleton following the `::` (e.g. `{foo, date, ::}`) */\n ErrorKind[ErrorKind[\"EXPECT_DATE_TIME_SKELETON\"] = 10] = \"EXPECT_DATE_TIME_SKELETON\";\n /** Unmatched apostrophes in the argument style (e.g. `{foo, number, 'test`) */\n ErrorKind[ErrorKind[\"UNCLOSED_QUOTE_IN_ARGUMENT_STYLE\"] = 11] = \"UNCLOSED_QUOTE_IN_ARGUMENT_STYLE\";\n /** Missing select argument options (e.g. `{foo, select}`) */\n ErrorKind[ErrorKind[\"EXPECT_SELECT_ARGUMENT_OPTIONS\"] = 12] = \"EXPECT_SELECT_ARGUMENT_OPTIONS\";\n /** Expecting an offset value in `plural` or `selectordinal` argument (e.g `{foo, plural, offset}`) */\n ErrorKind[ErrorKind[\"EXPECT_PLURAL_ARGUMENT_OFFSET_VALUE\"] = 13] = \"EXPECT_PLURAL_ARGUMENT_OFFSET_VALUE\";\n /** Offset value in `plural` or `selectordinal` is invalid (e.g. `{foo, plural, offset: x}`) */\n ErrorKind[ErrorKind[\"INVALID_PLURAL_ARGUMENT_OFFSET_VALUE\"] = 14] = \"INVALID_PLURAL_ARGUMENT_OFFSET_VALUE\";\n /** Expecting a selector in `select` argument (e.g `{foo, select}`) */\n ErrorKind[ErrorKind[\"EXPECT_SELECT_ARGUMENT_SELECTOR\"] = 15] = \"EXPECT_SELECT_ARGUMENT_SELECTOR\";\n /** Expecting a selector in `plural` or `selectordinal` argument (e.g `{foo, plural}`) */\n ErrorKind[ErrorKind[\"EXPECT_PLURAL_ARGUMENT_SELECTOR\"] = 16] = \"EXPECT_PLURAL_ARGUMENT_SELECTOR\";\n /** Expecting a message fragment after the `select` selector (e.g. `{foo, select, apple}`) */\n ErrorKind[ErrorKind[\"EXPECT_SELECT_ARGUMENT_SELECTOR_FRAGMENT\"] = 17] = \"EXPECT_SELECT_ARGUMENT_SELECTOR_FRAGMENT\";\n /**\n * Expecting a message fragment after the `plural` or `selectordinal` selector\n * (e.g. `{foo, plural, one}`)\n */\n ErrorKind[ErrorKind[\"EXPECT_PLURAL_ARGUMENT_SELECTOR_FRAGMENT\"] = 18] = \"EXPECT_PLURAL_ARGUMENT_SELECTOR_FRAGMENT\";\n /** Selector in `plural` or `selectordinal` is malformed (e.g. `{foo, plural, =x {#}}`) */\n ErrorKind[ErrorKind[\"INVALID_PLURAL_ARGUMENT_SELECTOR\"] = 19] = \"INVALID_PLURAL_ARGUMENT_SELECTOR\";\n /**\n * Duplicate selectors in `plural` or `selectordinal` argument.\n * (e.g. {foo, plural, one {#} one {#}})\n */\n ErrorKind[ErrorKind[\"DUPLICATE_PLURAL_ARGUMENT_SELECTOR\"] = 20] = \"DUPLICATE_PLURAL_ARGUMENT_SELECTOR\";\n /** Duplicate selectors in `select` argument.\n * (e.g. {foo, select, apple {apple} apple {apple}})\n */\n ErrorKind[ErrorKind[\"DUPLICATE_SELECT_ARGUMENT_SELECTOR\"] = 21] = \"DUPLICATE_SELECT_ARGUMENT_SELECTOR\";\n /** Plural or select argument option must have `other` clause. */\n ErrorKind[ErrorKind[\"MISSING_OTHER_CLAUSE\"] = 22] = \"MISSING_OTHER_CLAUSE\";\n /** The tag is malformed. (e.g. `foo) */\n ErrorKind[ErrorKind[\"INVALID_TAG\"] = 23] = \"INVALID_TAG\";\n /** The tag name is invalid. (e.g. `<123>foo123>`) */\n ErrorKind[ErrorKind[\"INVALID_TAG_NAME\"] = 25] = \"INVALID_TAG_NAME\";\n /** The closing tag does not match the opening tag. (e.g. `foo`) */\n ErrorKind[ErrorKind[\"UNMATCHED_CLOSING_TAG\"] = 26] = \"UNMATCHED_CLOSING_TAG\";\n /** The opening tag has unmatched closing tag. (e.g. `foo`) */\n ErrorKind[ErrorKind[\"UNCLOSED_TAG\"] = 27] = \"UNCLOSED_TAG\";\n})(ErrorKind || (ErrorKind = {}));\n","export var TYPE;\n(function (TYPE) {\n /**\n * Raw text\n */\n TYPE[TYPE[\"literal\"] = 0] = \"literal\";\n /**\n * Variable w/o any format, e.g `var` in `this is a {var}`\n */\n TYPE[TYPE[\"argument\"] = 1] = \"argument\";\n /**\n * Variable w/ number format\n */\n TYPE[TYPE[\"number\"] = 2] = \"number\";\n /**\n * Variable w/ date format\n */\n TYPE[TYPE[\"date\"] = 3] = \"date\";\n /**\n * Variable w/ time format\n */\n TYPE[TYPE[\"time\"] = 4] = \"time\";\n /**\n * Variable w/ select format\n */\n TYPE[TYPE[\"select\"] = 5] = \"select\";\n /**\n * Variable w/ plural format\n */\n TYPE[TYPE[\"plural\"] = 6] = \"plural\";\n /**\n * Only possible within plural argument.\n * This is the `#` symbol that will be substituted with the count.\n */\n TYPE[TYPE[\"pound\"] = 7] = \"pound\";\n /**\n * XML-like tag\n */\n TYPE[TYPE[\"tag\"] = 8] = \"tag\";\n})(TYPE || (TYPE = {}));\nexport var SKELETON_TYPE;\n(function (SKELETON_TYPE) {\n SKELETON_TYPE[SKELETON_TYPE[\"number\"] = 0] = \"number\";\n SKELETON_TYPE[SKELETON_TYPE[\"dateTime\"] = 1] = \"dateTime\";\n})(SKELETON_TYPE || (SKELETON_TYPE = {}));\n/**\n * Type Guards\n */\nexport function isLiteralElement(el) {\n return el.type === TYPE.literal;\n}\nexport function isArgumentElement(el) {\n return el.type === TYPE.argument;\n}\nexport function isNumberElement(el) {\n return el.type === TYPE.number;\n}\nexport function isDateElement(el) {\n return el.type === TYPE.date;\n}\nexport function isTimeElement(el) {\n return el.type === TYPE.time;\n}\nexport function isSelectElement(el) {\n return el.type === TYPE.select;\n}\nexport function isPluralElement(el) {\n return el.type === TYPE.plural;\n}\nexport function isPoundElement(el) {\n return el.type === TYPE.pound;\n}\nexport function isTagElement(el) {\n return el.type === TYPE.tag;\n}\nexport function isNumberSkeleton(el) {\n return !!(el && typeof el === 'object' && el.type === SKELETON_TYPE.number);\n}\nexport function isDateTimeSkeleton(el) {\n return !!(el && typeof el === 'object' && el.type === SKELETON_TYPE.dateTime);\n}\nexport function createLiteralElement(value) {\n return {\n type: TYPE.literal,\n value: value,\n };\n}\nexport function createNumberElement(value, style) {\n return {\n type: TYPE.number,\n value: value,\n style: style,\n };\n}\n","// @generated from regex-gen.ts\nexport var SPACE_SEPARATOR_REGEX = /[ \\xA0\\u1680\\u2000-\\u200A\\u202F\\u205F\\u3000]/;\nexport var WHITE_SPACE_REGEX = /[\\t-\\r \\x85\\u200E\\u200F\\u2028\\u2029]/;\n","/**\n * https://unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table\n * Credit: https://github.com/caridy/intl-datetimeformat-pattern/blob/master/index.js\n * with some tweaks\n */\nvar DATE_TIME_REGEX = /(?:[Eec]{1,6}|G{1,5}|[Qq]{1,5}|(?:[yYur]+|U{1,5})|[ML]{1,5}|d{1,2}|D{1,3}|F{1}|[abB]{1,5}|[hkHK]{1,2}|w{1,2}|W{1}|m{1,2}|s{1,2}|[zZOvVxX]{1,4})(?=([^']*'[^']*')*[^']*$)/g;\n/**\n * Parse Date time skeleton into Intl.DateTimeFormatOptions\n * Ref: https://unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table\n * @public\n * @param skeleton skeleton string\n */\nexport function parseDateTimeSkeleton(skeleton) {\n var result = {};\n skeleton.replace(DATE_TIME_REGEX, function (match) {\n var len = match.length;\n switch (match[0]) {\n // Era\n case 'G':\n result.era = len === 4 ? 'long' : len === 5 ? 'narrow' : 'short';\n break;\n // Year\n case 'y':\n result.year = len === 2 ? '2-digit' : 'numeric';\n break;\n case 'Y':\n case 'u':\n case 'U':\n case 'r':\n throw new RangeError('`Y/u/U/r` (year) patterns are not supported, use `y` instead');\n // Quarter\n case 'q':\n case 'Q':\n throw new RangeError('`q/Q` (quarter) patterns are not supported');\n // Month\n case 'M':\n case 'L':\n result.month = ['numeric', '2-digit', 'short', 'long', 'narrow'][len - 1];\n break;\n // Week\n case 'w':\n case 'W':\n throw new RangeError('`w/W` (week) patterns are not supported');\n case 'd':\n result.day = ['numeric', '2-digit'][len - 1];\n break;\n case 'D':\n case 'F':\n case 'g':\n throw new RangeError('`D/F/g` (day) patterns are not supported, use `d` instead');\n // Weekday\n case 'E':\n result.weekday = len === 4 ? 'long' : len === 5 ? 'narrow' : 'short';\n break;\n case 'e':\n if (len < 4) {\n throw new RangeError('`e..eee` (weekday) patterns are not supported');\n }\n result.weekday = ['short', 'long', 'narrow', 'short'][len - 4];\n break;\n case 'c':\n if (len < 4) {\n throw new RangeError('`c..ccc` (weekday) patterns are not supported');\n }\n result.weekday = ['short', 'long', 'narrow', 'short'][len - 4];\n break;\n // Period\n case 'a': // AM, PM\n result.hour12 = true;\n break;\n case 'b': // am, pm, noon, midnight\n case 'B': // flexible day periods\n throw new RangeError('`b/B` (period) patterns are not supported, use `a` instead');\n // Hour\n case 'h':\n result.hourCycle = 'h12';\n result.hour = ['numeric', '2-digit'][len - 1];\n break;\n case 'H':\n result.hourCycle = 'h23';\n result.hour = ['numeric', '2-digit'][len - 1];\n break;\n case 'K':\n result.hourCycle = 'h11';\n result.hour = ['numeric', '2-digit'][len - 1];\n break;\n case 'k':\n result.hourCycle = 'h24';\n result.hour = ['numeric', '2-digit'][len - 1];\n break;\n case 'j':\n case 'J':\n case 'C':\n throw new RangeError('`j/J/C` (hour) patterns are not supported, use `h/H/K/k` instead');\n // Minute\n case 'm':\n result.minute = ['numeric', '2-digit'][len - 1];\n break;\n // Second\n case 's':\n result.second = ['numeric', '2-digit'][len - 1];\n break;\n case 'S':\n case 'A':\n throw new RangeError('`S/A` (second) patterns are not supported, use `s` instead');\n // Zone\n case 'z': // 1..3, 4: specific non-location format\n result.timeZoneName = len < 4 ? 'short' : 'long';\n break;\n case 'Z': // 1..3, 4, 5: The ISO8601 varios formats\n case 'O': // 1, 4: milliseconds in day short, long\n case 'v': // 1, 4: generic non-location format\n case 'V': // 1, 2, 3, 4: time zone ID or city\n case 'X': // 1, 2, 3, 4: The ISO8601 varios formats\n case 'x': // 1, 2, 3, 4: The ISO8601 varios formats\n throw new RangeError('`Z/O/v/V/X/x` (timeZone) patterns are not supported, use `z` instead');\n }\n return '';\n });\n return result;\n}\n","// @generated from regex-gen.ts\nexport var WHITE_SPACE_REGEX = /[\\t-\\r \\x85\\u200E\\u200F\\u2028\\u2029]/i;\n","import { __assign } from \"tslib\";\nimport { WHITE_SPACE_REGEX } from './regex.generated';\nexport function parseNumberSkeletonFromString(skeleton) {\n if (skeleton.length === 0) {\n throw new Error('Number skeleton cannot be empty');\n }\n // Parse the skeleton\n var stringTokens = skeleton\n .split(WHITE_SPACE_REGEX)\n .filter(function (x) { return x.length > 0; });\n var tokens = [];\n for (var _i = 0, stringTokens_1 = stringTokens; _i < stringTokens_1.length; _i++) {\n var stringToken = stringTokens_1[_i];\n var stemAndOptions = stringToken.split('/');\n if (stemAndOptions.length === 0) {\n throw new Error('Invalid number skeleton');\n }\n var stem = stemAndOptions[0], options = stemAndOptions.slice(1);\n for (var _a = 0, options_1 = options; _a < options_1.length; _a++) {\n var option = options_1[_a];\n if (option.length === 0) {\n throw new Error('Invalid number skeleton');\n }\n }\n tokens.push({ stem: stem, options: options });\n }\n return tokens;\n}\nfunction icuUnitToEcma(unit) {\n return unit.replace(/^(.*?)-/, '');\n}\nvar FRACTION_PRECISION_REGEX = /^\\.(?:(0+)(\\*)?|(#+)|(0+)(#+))$/g;\nvar SIGNIFICANT_PRECISION_REGEX = /^(@+)?(\\+|#+)?[rs]?$/g;\nvar INTEGER_WIDTH_REGEX = /(\\*)(0+)|(#+)(0+)|(0+)/g;\nvar CONCISE_INTEGER_WIDTH_REGEX = /^(0+)$/;\nfunction parseSignificantPrecision(str) {\n var result = {};\n if (str[str.length - 1] === 'r') {\n result.roundingPriority = 'morePrecision';\n }\n else if (str[str.length - 1] === 's') {\n result.roundingPriority = 'lessPrecision';\n }\n str.replace(SIGNIFICANT_PRECISION_REGEX, function (_, g1, g2) {\n // @@@ case\n if (typeof g2 !== 'string') {\n result.minimumSignificantDigits = g1.length;\n result.maximumSignificantDigits = g1.length;\n }\n // @@@+ case\n else if (g2 === '+') {\n result.minimumSignificantDigits = g1.length;\n }\n // .### case\n else if (g1[0] === '#') {\n result.maximumSignificantDigits = g1.length;\n }\n // .@@## or .@@@ case\n else {\n result.minimumSignificantDigits = g1.length;\n result.maximumSignificantDigits =\n g1.length + (typeof g2 === 'string' ? g2.length : 0);\n }\n return '';\n });\n return result;\n}\nfunction parseSign(str) {\n switch (str) {\n case 'sign-auto':\n return {\n signDisplay: 'auto',\n };\n case 'sign-accounting':\n case '()':\n return {\n currencySign: 'accounting',\n };\n case 'sign-always':\n case '+!':\n return {\n signDisplay: 'always',\n };\n case 'sign-accounting-always':\n case '()!':\n return {\n signDisplay: 'always',\n currencySign: 'accounting',\n };\n case 'sign-except-zero':\n case '+?':\n return {\n signDisplay: 'exceptZero',\n };\n case 'sign-accounting-except-zero':\n case '()?':\n return {\n signDisplay: 'exceptZero',\n currencySign: 'accounting',\n };\n case 'sign-never':\n case '+_':\n return {\n signDisplay: 'never',\n };\n }\n}\nfunction parseConciseScientificAndEngineeringStem(stem) {\n // Engineering\n var result;\n if (stem[0] === 'E' && stem[1] === 'E') {\n result = {\n notation: 'engineering',\n };\n stem = stem.slice(2);\n }\n else if (stem[0] === 'E') {\n result = {\n notation: 'scientific',\n };\n stem = stem.slice(1);\n }\n if (result) {\n var signDisplay = stem.slice(0, 2);\n if (signDisplay === '+!') {\n result.signDisplay = 'always';\n stem = stem.slice(2);\n }\n else if (signDisplay === '+?') {\n result.signDisplay = 'exceptZero';\n stem = stem.slice(2);\n }\n if (!CONCISE_INTEGER_WIDTH_REGEX.test(stem)) {\n throw new Error('Malformed concise eng/scientific notation');\n }\n result.minimumIntegerDigits = stem.length;\n }\n return result;\n}\nfunction parseNotationOptions(opt) {\n var result = {};\n var signOpts = parseSign(opt);\n if (signOpts) {\n return signOpts;\n }\n return result;\n}\n/**\n * https://github.com/unicode-org/icu/blob/master/docs/userguide/format_parse/numbers/skeletons.md#skeleton-stems-and-options\n */\nexport function parseNumberSkeleton(tokens) {\n var result = {};\n for (var _i = 0, tokens_1 = tokens; _i < tokens_1.length; _i++) {\n var token = tokens_1[_i];\n switch (token.stem) {\n case 'percent':\n case '%':\n result.style = 'percent';\n continue;\n case '%x100':\n result.style = 'percent';\n result.scale = 100;\n continue;\n case 'currency':\n result.style = 'currency';\n result.currency = token.options[0];\n continue;\n case 'group-off':\n case ',_':\n result.useGrouping = false;\n continue;\n case 'precision-integer':\n case '.':\n result.maximumFractionDigits = 0;\n continue;\n case 'measure-unit':\n case 'unit':\n result.style = 'unit';\n result.unit = icuUnitToEcma(token.options[0]);\n continue;\n case 'compact-short':\n case 'K':\n result.notation = 'compact';\n result.compactDisplay = 'short';\n continue;\n case 'compact-long':\n case 'KK':\n result.notation = 'compact';\n result.compactDisplay = 'long';\n continue;\n case 'scientific':\n result = __assign(__assign(__assign({}, result), { notation: 'scientific' }), token.options.reduce(function (all, opt) { return (__assign(__assign({}, all), parseNotationOptions(opt))); }, {}));\n continue;\n case 'engineering':\n result = __assign(__assign(__assign({}, result), { notation: 'engineering' }), token.options.reduce(function (all, opt) { return (__assign(__assign({}, all), parseNotationOptions(opt))); }, {}));\n continue;\n case 'notation-simple':\n result.notation = 'standard';\n continue;\n // https://github.com/unicode-org/icu/blob/master/icu4c/source/i18n/unicode/unumberformatter.h\n case 'unit-width-narrow':\n result.currencyDisplay = 'narrowSymbol';\n result.unitDisplay = 'narrow';\n continue;\n case 'unit-width-short':\n result.currencyDisplay = 'code';\n result.unitDisplay = 'short';\n continue;\n case 'unit-width-full-name':\n result.currencyDisplay = 'name';\n result.unitDisplay = 'long';\n continue;\n case 'unit-width-iso-code':\n result.currencyDisplay = 'symbol';\n continue;\n case 'scale':\n result.scale = parseFloat(token.options[0]);\n continue;\n case 'rounding-mode-floor':\n result.roundingMode = 'floor';\n continue;\n case 'rounding-mode-ceiling':\n result.roundingMode = 'ceil';\n continue;\n case 'rounding-mode-down':\n result.roundingMode = 'trunc';\n continue;\n case 'rounding-mode-up':\n result.roundingMode = 'expand';\n continue;\n case 'rounding-mode-half-even':\n result.roundingMode = 'halfEven';\n continue;\n case 'rounding-mode-half-down':\n result.roundingMode = 'halfTrunc';\n continue;\n case 'rounding-mode-half-up':\n result.roundingMode = 'halfExpand';\n continue;\n // https://unicode-org.github.io/icu/userguide/format_parse/numbers/skeletons.html#integer-width\n case 'integer-width':\n if (token.options.length > 1) {\n throw new RangeError('integer-width stems only accept a single optional option');\n }\n token.options[0].replace(INTEGER_WIDTH_REGEX, function (_, g1, g2, g3, g4, g5) {\n if (g1) {\n result.minimumIntegerDigits = g2.length;\n }\n else if (g3 && g4) {\n throw new Error('We currently do not support maximum integer digits');\n }\n else if (g5) {\n throw new Error('We currently do not support exact integer digits');\n }\n return '';\n });\n continue;\n }\n // https://unicode-org.github.io/icu/userguide/format_parse/numbers/skeletons.html#integer-width\n if (CONCISE_INTEGER_WIDTH_REGEX.test(token.stem)) {\n result.minimumIntegerDigits = token.stem.length;\n continue;\n }\n if (FRACTION_PRECISION_REGEX.test(token.stem)) {\n // Precision\n // https://unicode-org.github.io/icu/userguide/format_parse/numbers/skeletons.html#fraction-precision\n // precision-integer case\n if (token.options.length > 1) {\n throw new RangeError('Fraction-precision stems only accept a single optional option');\n }\n token.stem.replace(FRACTION_PRECISION_REGEX, function (_, g1, g2, g3, g4, g5) {\n // .000* case (before ICU67 it was .000+)\n if (g2 === '*') {\n result.minimumFractionDigits = g1.length;\n }\n // .### case\n else if (g3 && g3[0] === '#') {\n result.maximumFractionDigits = g3.length;\n }\n // .00## case\n else if (g4 && g5) {\n result.minimumFractionDigits = g4.length;\n result.maximumFractionDigits = g4.length + g5.length;\n }\n else {\n result.minimumFractionDigits = g1.length;\n result.maximumFractionDigits = g1.length;\n }\n return '';\n });\n var opt = token.options[0];\n // https://unicode-org.github.io/icu/userguide/format_parse/numbers/skeletons.html#trailing-zero-display\n if (opt === 'w') {\n result = __assign(__assign({}, result), { trailingZeroDisplay: 'stripIfInteger' });\n }\n else if (opt) {\n result = __assign(__assign({}, result), parseSignificantPrecision(opt));\n }\n continue;\n }\n // https://unicode-org.github.io/icu/userguide/format_parse/numbers/skeletons.html#significant-digits-precision\n if (SIGNIFICANT_PRECISION_REGEX.test(token.stem)) {\n result = __assign(__assign({}, result), parseSignificantPrecision(token.stem));\n continue;\n }\n var signOpts = parseSign(token.stem);\n if (signOpts) {\n result = __assign(__assign({}, result), signOpts);\n }\n var conciseScientificAndEngineeringOpts = parseConciseScientificAndEngineeringStem(token.stem);\n if (conciseScientificAndEngineeringOpts) {\n result = __assign(__assign({}, result), conciseScientificAndEngineeringOpts);\n }\n }\n return result;\n}\n","// @generated from time-data-gen.ts\n// prettier-ignore \nexport var timeData = {\n \"001\": [\n \"H\",\n \"h\"\n ],\n \"AC\": [\n \"H\",\n \"h\",\n \"hb\",\n \"hB\"\n ],\n \"AD\": [\n \"H\",\n \"hB\"\n ],\n \"AE\": [\n \"h\",\n \"hB\",\n \"hb\",\n \"H\"\n ],\n \"AF\": [\n \"H\",\n \"hb\",\n \"hB\",\n \"h\"\n ],\n \"AG\": [\n \"h\",\n \"hb\",\n \"H\",\n \"hB\"\n ],\n \"AI\": [\n \"H\",\n \"h\",\n \"hb\",\n \"hB\"\n ],\n \"AL\": [\n \"h\",\n \"H\",\n \"hB\"\n ],\n \"AM\": [\n \"H\",\n \"hB\"\n ],\n \"AO\": [\n \"H\",\n \"hB\"\n ],\n \"AR\": [\n \"H\",\n \"h\",\n \"hB\",\n \"hb\"\n ],\n \"AS\": [\n \"h\",\n \"H\"\n ],\n \"AT\": [\n \"H\",\n \"hB\"\n ],\n \"AU\": [\n \"h\",\n \"hb\",\n \"H\",\n \"hB\"\n ],\n \"AW\": [\n \"H\",\n \"hB\"\n ],\n \"AX\": [\n \"H\"\n ],\n \"AZ\": [\n \"H\",\n \"hB\",\n \"h\"\n ],\n \"BA\": [\n \"H\",\n \"hB\",\n \"h\"\n ],\n \"BB\": [\n \"h\",\n \"hb\",\n \"H\",\n \"hB\"\n ],\n \"BD\": [\n \"h\",\n \"hB\",\n \"H\"\n ],\n \"BE\": [\n \"H\",\n \"hB\"\n ],\n \"BF\": [\n \"H\",\n \"hB\"\n ],\n \"BG\": [\n \"H\",\n \"hB\",\n \"h\"\n ],\n \"BH\": [\n \"h\",\n \"hB\",\n \"hb\",\n \"H\"\n ],\n \"BI\": [\n \"H\",\n \"h\"\n ],\n \"BJ\": [\n \"H\",\n \"hB\"\n ],\n \"BL\": [\n \"H\",\n \"hB\"\n ],\n \"BM\": [\n \"h\",\n \"hb\",\n \"H\",\n \"hB\"\n ],\n \"BN\": [\n \"hb\",\n \"hB\",\n \"h\",\n \"H\"\n ],\n \"BO\": [\n \"H\",\n \"hB\",\n \"h\",\n \"hb\"\n ],\n \"BQ\": [\n \"H\"\n ],\n \"BR\": [\n \"H\",\n \"hB\"\n ],\n \"BS\": [\n \"h\",\n \"hb\",\n \"H\",\n \"hB\"\n ],\n \"BT\": [\n \"h\",\n \"H\"\n ],\n \"BW\": [\n \"H\",\n \"h\",\n \"hb\",\n \"hB\"\n ],\n \"BY\": [\n \"H\",\n \"h\"\n ],\n \"BZ\": [\n \"H\",\n \"h\",\n \"hb\",\n \"hB\"\n ],\n \"CA\": [\n \"h\",\n \"hb\",\n \"H\",\n \"hB\"\n ],\n \"CC\": [\n \"H\",\n \"h\",\n \"hb\",\n \"hB\"\n ],\n \"CD\": [\n \"hB\",\n \"H\"\n ],\n \"CF\": [\n \"H\",\n \"h\",\n \"hB\"\n ],\n \"CG\": [\n \"H\",\n \"hB\"\n ],\n \"CH\": [\n \"H\",\n \"hB\",\n \"h\"\n ],\n \"CI\": [\n \"H\",\n \"hB\"\n ],\n \"CK\": [\n \"H\",\n \"h\",\n \"hb\",\n \"hB\"\n ],\n \"CL\": [\n \"H\",\n \"h\",\n \"hB\",\n \"hb\"\n ],\n \"CM\": [\n \"H\",\n \"h\",\n \"hB\"\n ],\n \"CN\": [\n \"H\",\n \"hB\",\n \"hb\",\n \"h\"\n ],\n \"CO\": [\n \"h\",\n \"H\",\n \"hB\",\n \"hb\"\n ],\n \"CP\": [\n \"H\"\n ],\n \"CR\": [\n \"H\",\n \"h\",\n \"hB\",\n \"hb\"\n ],\n \"CU\": [\n \"H\",\n \"h\",\n \"hB\",\n \"hb\"\n ],\n \"CV\": [\n \"H\",\n \"hB\"\n ],\n \"CW\": [\n \"H\",\n \"hB\"\n ],\n \"CX\": [\n \"H\",\n \"h\",\n \"hb\",\n \"hB\"\n ],\n \"CY\": [\n \"h\",\n \"H\",\n \"hb\",\n \"hB\"\n ],\n \"CZ\": [\n \"H\"\n ],\n \"DE\": [\n \"H\",\n \"hB\"\n ],\n \"DG\": [\n \"H\",\n \"h\",\n \"hb\",\n \"hB\"\n ],\n \"DJ\": [\n \"h\",\n \"H\"\n ],\n \"DK\": [\n \"H\"\n ],\n \"DM\": [\n \"h\",\n \"hb\",\n \"H\",\n \"hB\"\n ],\n \"DO\": [\n \"h\",\n \"H\",\n \"hB\",\n \"hb\"\n ],\n \"DZ\": [\n \"h\",\n \"hB\",\n \"hb\",\n \"H\"\n ],\n \"EA\": [\n \"H\",\n \"h\",\n \"hB\",\n \"hb\"\n ],\n \"EC\": [\n \"H\",\n \"hB\",\n \"h\",\n \"hb\"\n ],\n \"EE\": [\n \"H\",\n \"hB\"\n ],\n \"EG\": [\n \"h\",\n \"hB\",\n \"hb\",\n \"H\"\n ],\n \"EH\": [\n \"h\",\n \"hB\",\n \"hb\",\n \"H\"\n ],\n \"ER\": [\n \"h\",\n \"H\"\n ],\n \"ES\": [\n \"H\",\n \"hB\",\n \"h\",\n \"hb\"\n ],\n \"ET\": [\n \"hB\",\n \"hb\",\n \"h\",\n \"H\"\n ],\n \"FI\": [\n \"H\"\n ],\n \"FJ\": [\n \"h\",\n \"hb\",\n \"H\",\n \"hB\"\n ],\n \"FK\": [\n \"H\",\n \"h\",\n \"hb\",\n \"hB\"\n ],\n \"FM\": [\n \"h\",\n \"hb\",\n \"H\",\n \"hB\"\n ],\n \"FO\": [\n \"H\",\n \"h\"\n ],\n \"FR\": [\n \"H\",\n \"hB\"\n ],\n \"GA\": [\n \"H\",\n \"hB\"\n ],\n \"GB\": [\n \"H\",\n \"h\",\n \"hb\",\n \"hB\"\n ],\n \"GD\": [\n \"h\",\n \"hb\",\n \"H\",\n \"hB\"\n ],\n \"GE\": [\n \"H\",\n \"hB\",\n \"h\"\n ],\n \"GF\": [\n \"H\",\n \"hB\"\n ],\n \"GG\": [\n \"H\",\n \"h\",\n \"hb\",\n \"hB\"\n ],\n \"GH\": [\n \"h\",\n \"H\"\n ],\n \"GI\": [\n \"H\",\n \"h\",\n \"hb\",\n \"hB\"\n ],\n \"GL\": [\n \"H\",\n \"h\"\n ],\n \"GM\": [\n \"h\",\n \"hb\",\n \"H\",\n \"hB\"\n ],\n \"GN\": [\n \"H\",\n \"hB\"\n ],\n \"GP\": [\n \"H\",\n \"hB\"\n ],\n \"GQ\": [\n \"H\",\n \"hB\",\n \"h\",\n \"hb\"\n ],\n \"GR\": [\n \"h\",\n \"H\",\n \"hb\",\n \"hB\"\n ],\n \"GT\": [\n \"H\",\n \"h\",\n \"hB\",\n \"hb\"\n ],\n \"GU\": [\n \"h\",\n \"hb\",\n \"H\",\n \"hB\"\n ],\n \"GW\": [\n \"H\",\n \"hB\"\n ],\n \"GY\": [\n \"h\",\n \"hb\",\n \"H\",\n \"hB\"\n ],\n \"HK\": [\n \"h\",\n \"hB\",\n \"hb\",\n \"H\"\n ],\n \"HN\": [\n \"H\",\n \"h\",\n \"hB\",\n \"hb\"\n ],\n \"HR\": [\n \"H\",\n \"hB\"\n ],\n \"HU\": [\n \"H\",\n \"h\"\n ],\n \"IC\": [\n \"H\",\n \"h\",\n \"hB\",\n \"hb\"\n ],\n \"ID\": [\n \"H\"\n ],\n \"IE\": [\n \"H\",\n \"h\",\n \"hb\",\n \"hB\"\n ],\n \"IL\": [\n \"H\",\n \"hB\"\n ],\n \"IM\": [\n \"H\",\n \"h\",\n \"hb\",\n \"hB\"\n ],\n \"IN\": [\n \"h\",\n \"H\"\n ],\n \"IO\": [\n \"H\",\n \"h\",\n \"hb\",\n \"hB\"\n ],\n \"IQ\": [\n \"h\",\n \"hB\",\n \"hb\",\n \"H\"\n ],\n \"IR\": [\n \"hB\",\n \"H\"\n ],\n \"IS\": [\n \"H\"\n ],\n \"IT\": [\n \"H\",\n \"hB\"\n ],\n \"JE\": [\n \"H\",\n \"h\",\n \"hb\",\n \"hB\"\n ],\n \"JM\": [\n \"h\",\n \"hb\",\n \"H\",\n \"hB\"\n ],\n \"JO\": [\n \"h\",\n \"hB\",\n \"hb\",\n \"H\"\n ],\n \"JP\": [\n \"H\",\n \"K\",\n \"h\"\n ],\n \"KE\": [\n \"hB\",\n \"hb\",\n \"H\",\n \"h\"\n ],\n \"KG\": [\n \"H\",\n \"h\",\n \"hB\",\n \"hb\"\n ],\n \"KH\": [\n \"hB\",\n \"h\",\n \"H\",\n \"hb\"\n ],\n \"KI\": [\n \"h\",\n \"hb\",\n \"H\",\n \"hB\"\n ],\n \"KM\": [\n \"H\",\n \"h\",\n \"hB\",\n \"hb\"\n ],\n \"KN\": [\n \"h\",\n \"hb\",\n \"H\",\n \"hB\"\n ],\n \"KP\": [\n \"h\",\n \"H\",\n \"hB\",\n \"hb\"\n ],\n \"KR\": [\n \"h\",\n \"H\",\n \"hB\",\n \"hb\"\n ],\n \"KW\": [\n \"h\",\n \"hB\",\n \"hb\",\n \"H\"\n ],\n \"KY\": [\n \"h\",\n \"hb\",\n \"H\",\n \"hB\"\n ],\n \"KZ\": [\n \"H\",\n \"hB\"\n ],\n \"LA\": [\n \"H\",\n \"hb\",\n \"hB\",\n \"h\"\n ],\n \"LB\": [\n \"h\",\n \"hB\",\n \"hb\",\n \"H\"\n ],\n \"LC\": [\n \"h\",\n \"hb\",\n \"H\",\n \"hB\"\n ],\n \"LI\": [\n \"H\",\n \"hB\",\n \"h\"\n ],\n \"LK\": [\n \"H\",\n \"h\",\n \"hB\",\n \"hb\"\n ],\n \"LR\": [\n \"h\",\n \"hb\",\n \"H\",\n \"hB\"\n ],\n \"LS\": [\n \"h\",\n \"H\"\n ],\n \"LT\": [\n \"H\",\n \"h\",\n \"hb\",\n \"hB\"\n ],\n \"LU\": [\n \"H\",\n \"h\",\n \"hB\"\n ],\n \"LV\": [\n \"H\",\n \"hB\",\n \"hb\",\n \"h\"\n ],\n \"LY\": [\n \"h\",\n \"hB\",\n \"hb\",\n \"H\"\n ],\n \"MA\": [\n \"H\",\n \"h\",\n \"hB\",\n \"hb\"\n ],\n \"MC\": [\n \"H\",\n \"hB\"\n ],\n \"MD\": [\n \"H\",\n \"hB\"\n ],\n \"ME\": [\n \"H\",\n \"hB\",\n \"h\"\n ],\n \"MF\": [\n \"H\",\n \"hB\"\n ],\n \"MG\": [\n \"H\",\n \"h\"\n ],\n \"MH\": [\n \"h\",\n \"hb\",\n \"H\",\n \"hB\"\n ],\n \"MK\": [\n \"H\",\n \"h\",\n \"hb\",\n \"hB\"\n ],\n \"ML\": [\n \"H\"\n ],\n \"MM\": [\n \"hB\",\n \"hb\",\n \"H\",\n \"h\"\n ],\n \"MN\": [\n \"H\",\n \"h\",\n \"hb\",\n \"hB\"\n ],\n \"MO\": [\n \"h\",\n \"hB\",\n \"hb\",\n \"H\"\n ],\n \"MP\": [\n \"h\",\n \"hb\",\n \"H\",\n \"hB\"\n ],\n \"MQ\": [\n \"H\",\n \"hB\"\n ],\n \"MR\": [\n \"h\",\n \"hB\",\n \"hb\",\n \"H\"\n ],\n \"MS\": [\n \"H\",\n \"h\",\n \"hb\",\n \"hB\"\n ],\n \"MT\": [\n \"H\",\n \"h\"\n ],\n \"MU\": [\n \"H\",\n \"h\"\n ],\n \"MV\": [\n \"H\",\n \"h\"\n ],\n \"MW\": [\n \"h\",\n \"hb\",\n \"H\",\n \"hB\"\n ],\n \"MX\": [\n \"H\",\n \"h\",\n \"hB\",\n \"hb\"\n ],\n \"MY\": [\n \"hb\",\n \"hB\",\n \"h\",\n \"H\"\n ],\n \"MZ\": [\n \"H\",\n \"hB\"\n ],\n \"NA\": [\n \"h\",\n \"H\",\n \"hB\",\n \"hb\"\n ],\n \"NC\": [\n \"H\",\n \"hB\"\n ],\n \"NE\": [\n \"H\"\n ],\n \"NF\": [\n \"H\",\n \"h\",\n \"hb\",\n \"hB\"\n ],\n \"NG\": [\n \"H\",\n \"h\",\n \"hb\",\n \"hB\"\n ],\n \"NI\": [\n \"H\",\n \"h\",\n \"hB\",\n \"hb\"\n ],\n \"NL\": [\n \"H\",\n \"hB\"\n ],\n \"NO\": [\n \"H\",\n \"h\"\n ],\n \"NP\": [\n \"H\",\n \"h\",\n \"hB\"\n ],\n \"NR\": [\n \"H\",\n \"h\",\n \"hb\",\n \"hB\"\n ],\n \"NU\": [\n \"H\",\n \"h\",\n \"hb\",\n \"hB\"\n ],\n \"NZ\": [\n \"h\",\n \"hb\",\n \"H\",\n \"hB\"\n ],\n \"OM\": [\n \"h\",\n \"hB\",\n \"hb\",\n \"H\"\n ],\n \"PA\": [\n \"h\",\n \"H\",\n \"hB\",\n \"hb\"\n ],\n \"PE\": [\n \"H\",\n \"hB\",\n \"h\",\n \"hb\"\n ],\n \"PF\": [\n \"H\",\n \"h\",\n \"hB\"\n ],\n \"PG\": [\n \"h\",\n \"H\"\n ],\n \"PH\": [\n \"h\",\n \"hB\",\n \"hb\",\n \"H\"\n ],\n \"PK\": [\n \"h\",\n \"hB\",\n \"H\"\n ],\n \"PL\": [\n \"H\",\n \"h\"\n ],\n \"PM\": [\n \"H\",\n \"hB\"\n ],\n \"PN\": [\n \"H\",\n \"h\",\n \"hb\",\n \"hB\"\n ],\n \"PR\": [\n \"h\",\n \"H\",\n \"hB\",\n \"hb\"\n ],\n \"PS\": [\n \"h\",\n \"hB\",\n \"hb\",\n \"H\"\n ],\n \"PT\": [\n \"H\",\n \"hB\"\n ],\n \"PW\": [\n \"h\",\n \"H\"\n ],\n \"PY\": [\n \"H\",\n \"h\",\n \"hB\",\n \"hb\"\n ],\n \"QA\": [\n \"h\",\n \"hB\",\n \"hb\",\n \"H\"\n ],\n \"RE\": [\n \"H\",\n \"hB\"\n ],\n \"RO\": [\n \"H\",\n \"hB\"\n ],\n \"RS\": [\n \"H\",\n \"hB\",\n \"h\"\n ],\n \"RU\": [\n \"H\"\n ],\n \"RW\": [\n \"H\",\n \"h\"\n ],\n \"SA\": [\n \"h\",\n \"hB\",\n \"hb\",\n \"H\"\n ],\n \"SB\": [\n \"h\",\n \"hb\",\n \"H\",\n \"hB\"\n ],\n \"SC\": [\n \"H\",\n \"h\",\n \"hB\"\n ],\n \"SD\": [\n \"h\",\n \"hB\",\n \"hb\",\n \"H\"\n ],\n \"SE\": [\n \"H\"\n ],\n \"SG\": [\n \"h\",\n \"hb\",\n \"H\",\n \"hB\"\n ],\n \"SH\": [\n \"H\",\n \"h\",\n \"hb\",\n \"hB\"\n ],\n \"SI\": [\n \"H\",\n \"hB\"\n ],\n \"SJ\": [\n \"H\"\n ],\n \"SK\": [\n \"H\"\n ],\n \"SL\": [\n \"h\",\n \"hb\",\n \"H\",\n \"hB\"\n ],\n \"SM\": [\n \"H\",\n \"h\",\n \"hB\"\n ],\n \"SN\": [\n \"H\",\n \"h\",\n \"hB\"\n ],\n \"SO\": [\n \"h\",\n \"H\"\n ],\n \"SR\": [\n \"H\",\n \"hB\"\n ],\n \"SS\": [\n \"h\",\n \"hb\",\n \"H\",\n \"hB\"\n ],\n \"ST\": [\n \"H\",\n \"hB\"\n ],\n \"SV\": [\n \"H\",\n \"h\",\n \"hB\",\n \"hb\"\n ],\n \"SX\": [\n \"H\",\n \"h\",\n \"hb\",\n \"hB\"\n ],\n \"SY\": [\n \"h\",\n \"hB\",\n \"hb\",\n \"H\"\n ],\n \"SZ\": [\n \"h\",\n \"hb\",\n \"H\",\n \"hB\"\n ],\n \"TA\": [\n \"H\",\n \"h\",\n \"hb\",\n \"hB\"\n ],\n \"TC\": [\n \"h\",\n \"hb\",\n \"H\",\n \"hB\"\n ],\n \"TD\": [\n \"h\",\n \"H\",\n \"hB\"\n ],\n \"TF\": [\n \"H\",\n \"h\",\n \"hB\"\n ],\n \"TG\": [\n \"H\",\n \"hB\"\n ],\n \"TH\": [\n \"H\",\n \"h\"\n ],\n \"TJ\": [\n \"H\",\n \"h\"\n ],\n \"TL\": [\n \"H\",\n \"hB\",\n \"hb\",\n \"h\"\n ],\n \"TM\": [\n \"H\",\n \"h\"\n ],\n \"TN\": [\n \"h\",\n \"hB\",\n \"hb\",\n \"H\"\n ],\n \"TO\": [\n \"h\",\n \"H\"\n ],\n \"TR\": [\n \"H\",\n \"hB\"\n ],\n \"TT\": [\n \"h\",\n \"hb\",\n \"H\",\n \"hB\"\n ],\n \"TW\": [\n \"hB\",\n \"hb\",\n \"h\",\n \"H\"\n ],\n \"TZ\": [\n \"hB\",\n \"hb\",\n \"H\",\n \"h\"\n ],\n \"UA\": [\n \"H\",\n \"hB\",\n \"h\"\n ],\n \"UG\": [\n \"hB\",\n \"hb\",\n \"H\",\n \"h\"\n ],\n \"UM\": [\n \"h\",\n \"hb\",\n \"H\",\n \"hB\"\n ],\n \"US\": [\n \"h\",\n \"hb\",\n \"H\",\n \"hB\"\n ],\n \"UY\": [\n \"H\",\n \"h\",\n \"hB\",\n \"hb\"\n ],\n \"UZ\": [\n \"H\",\n \"hB\",\n \"h\"\n ],\n \"VA\": [\n \"H\",\n \"h\",\n \"hB\"\n ],\n \"VC\": [\n \"h\",\n \"hb\",\n \"H\",\n \"hB\"\n ],\n \"VE\": [\n \"h\",\n \"H\",\n \"hB\",\n \"hb\"\n ],\n \"VG\": [\n \"h\",\n \"hb\",\n \"H\",\n \"hB\"\n ],\n \"VI\": [\n \"h\",\n \"hb\",\n \"H\",\n \"hB\"\n ],\n \"VN\": [\n \"H\",\n \"h\"\n ],\n \"VU\": [\n \"h\",\n \"H\"\n ],\n \"WF\": [\n \"H\",\n \"hB\"\n ],\n \"WS\": [\n \"h\",\n \"H\"\n ],\n \"XK\": [\n \"H\",\n \"hB\",\n \"h\"\n ],\n \"YE\": [\n \"h\",\n \"hB\",\n \"hb\",\n \"H\"\n ],\n \"YT\": [\n \"H\",\n \"hB\"\n ],\n \"ZA\": [\n \"H\",\n \"h\",\n \"hb\",\n \"hB\"\n ],\n \"ZM\": [\n \"h\",\n \"hb\",\n \"H\",\n \"hB\"\n ],\n \"ZW\": [\n \"H\",\n \"h\"\n ],\n \"af-ZA\": [\n \"H\",\n \"h\",\n \"hB\",\n \"hb\"\n ],\n \"ar-001\": [\n \"h\",\n \"hB\",\n \"hb\",\n \"H\"\n ],\n \"ca-ES\": [\n \"H\",\n \"h\",\n \"hB\"\n ],\n \"en-001\": [\n \"h\",\n \"hb\",\n \"H\",\n \"hB\"\n ],\n \"es-BO\": [\n \"H\",\n \"h\",\n \"hB\",\n \"hb\"\n ],\n \"es-BR\": [\n \"H\",\n \"h\",\n \"hB\",\n \"hb\"\n ],\n \"es-EC\": [\n \"H\",\n \"h\",\n \"hB\",\n \"hb\"\n ],\n \"es-ES\": [\n \"H\",\n \"h\",\n \"hB\",\n \"hb\"\n ],\n \"es-GQ\": [\n \"H\",\n \"h\",\n \"hB\",\n \"hb\"\n ],\n \"es-PE\": [\n \"H\",\n \"h\",\n \"hB\",\n \"hb\"\n ],\n \"fr-CA\": [\n \"H\",\n \"h\",\n \"hB\"\n ],\n \"gl-ES\": [\n \"H\",\n \"h\",\n \"hB\"\n ],\n \"gu-IN\": [\n \"hB\",\n \"hb\",\n \"h\",\n \"H\"\n ],\n \"hi-IN\": [\n \"hB\",\n \"h\",\n \"H\"\n ],\n \"it-CH\": [\n \"H\",\n \"h\",\n \"hB\"\n ],\n \"it-IT\": [\n \"H\",\n \"h\",\n \"hB\"\n ],\n \"kn-IN\": [\n \"hB\",\n \"h\",\n \"H\"\n ],\n \"ml-IN\": [\n \"hB\",\n \"h\",\n \"H\"\n ],\n \"mr-IN\": [\n \"hB\",\n \"hb\",\n \"h\",\n \"H\"\n ],\n \"pa-IN\": [\n \"hB\",\n \"hb\",\n \"h\",\n \"H\"\n ],\n \"ta-IN\": [\n \"hB\",\n \"h\",\n \"hb\",\n \"H\"\n ],\n \"te-IN\": [\n \"hB\",\n \"h\",\n \"H\"\n ],\n \"zu-ZA\": [\n \"H\",\n \"hB\",\n \"hb\",\n \"h\"\n ]\n};\n","var _a;\nimport { __assign } from \"tslib\";\nimport { ErrorKind } from './error';\nimport { SKELETON_TYPE, TYPE, } from './types';\nimport { SPACE_SEPARATOR_REGEX } from './regex.generated';\nimport { parseNumberSkeleton, parseNumberSkeletonFromString, parseDateTimeSkeleton, } from '@formatjs/icu-skeleton-parser';\nimport { getBestPattern } from './date-time-pattern-generator';\nvar SPACE_SEPARATOR_START_REGEX = new RegExp(\"^\".concat(SPACE_SEPARATOR_REGEX.source, \"*\"));\nvar SPACE_SEPARATOR_END_REGEX = new RegExp(\"\".concat(SPACE_SEPARATOR_REGEX.source, \"*$\"));\nfunction createLocation(start, end) {\n return { start: start, end: end };\n}\n// #region Ponyfills\n// Consolidate these variables up top for easier toggling during debugging\nvar hasNativeStartsWith = !!String.prototype.startsWith && '_a'.startsWith('a', 1);\nvar hasNativeFromCodePoint = !!String.fromCodePoint;\nvar hasNativeFromEntries = !!Object.fromEntries;\nvar hasNativeCodePointAt = !!String.prototype.codePointAt;\nvar hasTrimStart = !!String.prototype.trimStart;\nvar hasTrimEnd = !!String.prototype.trimEnd;\nvar hasNativeIsSafeInteger = !!Number.isSafeInteger;\nvar isSafeInteger = hasNativeIsSafeInteger\n ? Number.isSafeInteger\n : function (n) {\n return (typeof n === 'number' &&\n isFinite(n) &&\n Math.floor(n) === n &&\n Math.abs(n) <= 0x1fffffffffffff);\n };\n// IE11 does not support y and u.\nvar REGEX_SUPPORTS_U_AND_Y = true;\ntry {\n var re = RE('([^\\\\p{White_Space}\\\\p{Pattern_Syntax}]*)', 'yu');\n /**\n * legacy Edge or Xbox One browser\n * Unicode flag support: supported\n * Pattern_Syntax support: not supported\n * See https://github.com/formatjs/formatjs/issues/2822\n */\n REGEX_SUPPORTS_U_AND_Y = ((_a = re.exec('a')) === null || _a === void 0 ? void 0 : _a[0]) === 'a';\n}\ncatch (_) {\n REGEX_SUPPORTS_U_AND_Y = false;\n}\nvar startsWith = hasNativeStartsWith\n ? // Native\n function startsWith(s, search, position) {\n return s.startsWith(search, position);\n }\n : // For IE11\n function startsWith(s, search, position) {\n return s.slice(position, position + search.length) === search;\n };\nvar fromCodePoint = hasNativeFromCodePoint\n ? String.fromCodePoint\n : // IE11\n function fromCodePoint() {\n var codePoints = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n codePoints[_i] = arguments[_i];\n }\n var elements = '';\n var length = codePoints.length;\n var i = 0;\n var code;\n while (length > i) {\n code = codePoints[i++];\n if (code > 0x10ffff)\n throw RangeError(code + ' is not a valid code point');\n elements +=\n code < 0x10000\n ? String.fromCharCode(code)\n : String.fromCharCode(((code -= 0x10000) >> 10) + 0xd800, (code % 0x400) + 0xdc00);\n }\n return elements;\n };\nvar fromEntries = \n// native\nhasNativeFromEntries\n ? Object.fromEntries\n : // Ponyfill\n function fromEntries(entries) {\n var obj = {};\n for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {\n var _a = entries_1[_i], k = _a[0], v = _a[1];\n obj[k] = v;\n }\n return obj;\n };\nvar codePointAt = hasNativeCodePointAt\n ? // Native\n function codePointAt(s, index) {\n return s.codePointAt(index);\n }\n : // IE 11\n function codePointAt(s, index) {\n var size = s.length;\n if (index < 0 || index >= size) {\n return undefined;\n }\n var first = s.charCodeAt(index);\n var second;\n return first < 0xd800 ||\n first > 0xdbff ||\n index + 1 === size ||\n (second = s.charCodeAt(index + 1)) < 0xdc00 ||\n second > 0xdfff\n ? first\n : ((first - 0xd800) << 10) + (second - 0xdc00) + 0x10000;\n };\nvar trimStart = hasTrimStart\n ? // Native\n function trimStart(s) {\n return s.trimStart();\n }\n : // Ponyfill\n function trimStart(s) {\n return s.replace(SPACE_SEPARATOR_START_REGEX, '');\n };\nvar trimEnd = hasTrimEnd\n ? // Native\n function trimEnd(s) {\n return s.trimEnd();\n }\n : // Ponyfill\n function trimEnd(s) {\n return s.replace(SPACE_SEPARATOR_END_REGEX, '');\n };\n// Prevent minifier to translate new RegExp to literal form that might cause syntax error on IE11.\nfunction RE(s, flag) {\n return new RegExp(s, flag);\n}\n// #endregion\nvar matchIdentifierAtIndex;\nif (REGEX_SUPPORTS_U_AND_Y) {\n // Native\n var IDENTIFIER_PREFIX_RE_1 = RE('([^\\\\p{White_Space}\\\\p{Pattern_Syntax}]*)', 'yu');\n matchIdentifierAtIndex = function matchIdentifierAtIndex(s, index) {\n var _a;\n IDENTIFIER_PREFIX_RE_1.lastIndex = index;\n var match = IDENTIFIER_PREFIX_RE_1.exec(s);\n return (_a = match[1]) !== null && _a !== void 0 ? _a : '';\n };\n}\nelse {\n // IE11\n matchIdentifierAtIndex = function matchIdentifierAtIndex(s, index) {\n var match = [];\n while (true) {\n var c = codePointAt(s, index);\n if (c === undefined || _isWhiteSpace(c) || _isPatternSyntax(c)) {\n break;\n }\n match.push(c);\n index += c >= 0x10000 ? 2 : 1;\n }\n return fromCodePoint.apply(void 0, match);\n };\n}\nvar Parser = /** @class */ (function () {\n function Parser(message, options) {\n if (options === void 0) { options = {}; }\n this.message = message;\n this.position = { offset: 0, line: 1, column: 1 };\n this.ignoreTag = !!options.ignoreTag;\n this.locale = options.locale;\n this.requiresOtherClause = !!options.requiresOtherClause;\n this.shouldParseSkeletons = !!options.shouldParseSkeletons;\n }\n Parser.prototype.parse = function () {\n if (this.offset() !== 0) {\n throw Error('parser can only be used once');\n }\n return this.parseMessage(0, '', false);\n };\n Parser.prototype.parseMessage = function (nestingLevel, parentArgType, expectingCloseTag) {\n var elements = [];\n while (!this.isEOF()) {\n var char = this.char();\n if (char === 123 /* `{` */) {\n var result = this.parseArgument(nestingLevel, expectingCloseTag);\n if (result.err) {\n return result;\n }\n elements.push(result.val);\n }\n else if (char === 125 /* `}` */ && nestingLevel > 0) {\n break;\n }\n else if (char === 35 /* `#` */ &&\n (parentArgType === 'plural' || parentArgType === 'selectordinal')) {\n var position = this.clonePosition();\n this.bump();\n elements.push({\n type: TYPE.pound,\n location: createLocation(position, this.clonePosition()),\n });\n }\n else if (char === 60 /* `<` */ &&\n !this.ignoreTag &&\n this.peek() === 47 // char code for '/'\n ) {\n if (expectingCloseTag) {\n break;\n }\n else {\n return this.error(ErrorKind.UNMATCHED_CLOSING_TAG, createLocation(this.clonePosition(), this.clonePosition()));\n }\n }\n else if (char === 60 /* `<` */ &&\n !this.ignoreTag &&\n _isAlpha(this.peek() || 0)) {\n var result = this.parseTag(nestingLevel, parentArgType);\n if (result.err) {\n return result;\n }\n elements.push(result.val);\n }\n else {\n var result = this.parseLiteral(nestingLevel, parentArgType);\n if (result.err) {\n return result;\n }\n elements.push(result.val);\n }\n }\n return { val: elements, err: null };\n };\n /**\n * A tag name must start with an ASCII lower/upper case letter. The grammar is based on the\n * [custom element name][] except that a dash is NOT always mandatory and uppercase letters\n * are accepted:\n *\n * ```\n * tag ::= \"<\" tagName (whitespace)* \"/>\" | \"<\" tagName (whitespace)* \">\" message \"\" tagName (whitespace)* \">\"\n * tagName ::= [a-z] (PENChar)*\n * PENChar ::=\n * \"-\" | \".\" | [0-9] | \"_\" | [a-z] | [A-Z] | #xB7 | [#xC0-#xD6] | [#xD8-#xF6] | [#xF8-#x37D] |\n * [#x37F-#x1FFF] | [#x200C-#x200D] | [#x203F-#x2040] | [#x2070-#x218F] | [#x2C00-#x2FEF] |\n * [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] | [#x10000-#xEFFFF]\n * ```\n *\n * [custom element name]: https://html.spec.whatwg.org/multipage/custom-elements.html#valid-custom-element-name\n * NOTE: We're a bit more lax here since HTML technically does not allow uppercase HTML element but we do\n * since other tag-based engines like React allow it\n */\n Parser.prototype.parseTag = function (nestingLevel, parentArgType) {\n var startPosition = this.clonePosition();\n this.bump(); // `<`\n var tagName = this.parseTagName();\n this.bumpSpace();\n if (this.bumpIf('/>')) {\n // Self closing tag\n return {\n val: {\n type: TYPE.literal,\n value: \"<\".concat(tagName, \"/>\"),\n location: createLocation(startPosition, this.clonePosition()),\n },\n err: null,\n };\n }\n else if (this.bumpIf('>')) {\n var childrenResult = this.parseMessage(nestingLevel + 1, parentArgType, true);\n if (childrenResult.err) {\n return childrenResult;\n }\n var children = childrenResult.val;\n // Expecting a close tag\n var endTagStartPosition = this.clonePosition();\n if (this.bumpIf('')) {\n if (this.isEOF() || !_isAlpha(this.char())) {\n return this.error(ErrorKind.INVALID_TAG, createLocation(endTagStartPosition, this.clonePosition()));\n }\n var closingTagNameStartPosition = this.clonePosition();\n var closingTagName = this.parseTagName();\n if (tagName !== closingTagName) {\n return this.error(ErrorKind.UNMATCHED_CLOSING_TAG, createLocation(closingTagNameStartPosition, this.clonePosition()));\n }\n this.bumpSpace();\n if (!this.bumpIf('>')) {\n return this.error(ErrorKind.INVALID_TAG, createLocation(endTagStartPosition, this.clonePosition()));\n }\n return {\n val: {\n type: TYPE.tag,\n value: tagName,\n children: children,\n location: createLocation(startPosition, this.clonePosition()),\n },\n err: null,\n };\n }\n else {\n return this.error(ErrorKind.UNCLOSED_TAG, createLocation(startPosition, this.clonePosition()));\n }\n }\n else {\n return this.error(ErrorKind.INVALID_TAG, createLocation(startPosition, this.clonePosition()));\n }\n };\n /**\n * This method assumes that the caller has peeked ahead for the first tag character.\n */\n Parser.prototype.parseTagName = function () {\n var startOffset = this.offset();\n this.bump(); // the first tag name character\n while (!this.isEOF() && _isPotentialElementNameChar(this.char())) {\n this.bump();\n }\n return this.message.slice(startOffset, this.offset());\n };\n Parser.prototype.parseLiteral = function (nestingLevel, parentArgType) {\n var start = this.clonePosition();\n var value = '';\n while (true) {\n var parseQuoteResult = this.tryParseQuote(parentArgType);\n if (parseQuoteResult) {\n value += parseQuoteResult;\n continue;\n }\n var parseUnquotedResult = this.tryParseUnquoted(nestingLevel, parentArgType);\n if (parseUnquotedResult) {\n value += parseUnquotedResult;\n continue;\n }\n var parseLeftAngleResult = this.tryParseLeftAngleBracket();\n if (parseLeftAngleResult) {\n value += parseLeftAngleResult;\n continue;\n }\n break;\n }\n var location = createLocation(start, this.clonePosition());\n return {\n val: { type: TYPE.literal, value: value, location: location },\n err: null,\n };\n };\n Parser.prototype.tryParseLeftAngleBracket = function () {\n if (!this.isEOF() &&\n this.char() === 60 /* `<` */ &&\n (this.ignoreTag ||\n // If at the opening tag or closing tag position, bail.\n !_isAlphaOrSlash(this.peek() || 0))) {\n this.bump(); // `<`\n return '<';\n }\n return null;\n };\n /**\n * Starting with ICU 4.8, an ASCII apostrophe only starts quoted text if it immediately precedes\n * a character that requires quoting (that is, \"only where needed\"), and works the same in\n * nested messages as on the top level of the pattern. The new behavior is otherwise compatible.\n */\n Parser.prototype.tryParseQuote = function (parentArgType) {\n if (this.isEOF() || this.char() !== 39 /* `'` */) {\n return null;\n }\n // Parse escaped char following the apostrophe, or early return if there is no escaped char.\n // Check if is valid escaped character\n switch (this.peek()) {\n case 39 /* `'` */:\n // double quote, should return as a single quote.\n this.bump();\n this.bump();\n return \"'\";\n // '{', '<', '>', '}'\n case 123:\n case 60:\n case 62:\n case 125:\n break;\n case 35: // '#'\n if (parentArgType === 'plural' || parentArgType === 'selectordinal') {\n break;\n }\n return null;\n default:\n return null;\n }\n this.bump(); // apostrophe\n var codePoints = [this.char()]; // escaped char\n this.bump();\n // read chars until the optional closing apostrophe is found\n while (!this.isEOF()) {\n var ch = this.char();\n if (ch === 39 /* `'` */) {\n if (this.peek() === 39 /* `'` */) {\n codePoints.push(39);\n // Bump one more time because we need to skip 2 characters.\n this.bump();\n }\n else {\n // Optional closing apostrophe.\n this.bump();\n break;\n }\n }\n else {\n codePoints.push(ch);\n }\n this.bump();\n }\n return fromCodePoint.apply(void 0, codePoints);\n };\n Parser.prototype.tryParseUnquoted = function (nestingLevel, parentArgType) {\n if (this.isEOF()) {\n return null;\n }\n var ch = this.char();\n if (ch === 60 /* `<` */ ||\n ch === 123 /* `{` */ ||\n (ch === 35 /* `#` */ &&\n (parentArgType === 'plural' || parentArgType === 'selectordinal')) ||\n (ch === 125 /* `}` */ && nestingLevel > 0)) {\n return null;\n }\n else {\n this.bump();\n return fromCodePoint(ch);\n }\n };\n Parser.prototype.parseArgument = function (nestingLevel, expectingCloseTag) {\n var openingBracePosition = this.clonePosition();\n this.bump(); // `{`\n this.bumpSpace();\n if (this.isEOF()) {\n return this.error(ErrorKind.EXPECT_ARGUMENT_CLOSING_BRACE, createLocation(openingBracePosition, this.clonePosition()));\n }\n if (this.char() === 125 /* `}` */) {\n this.bump();\n return this.error(ErrorKind.EMPTY_ARGUMENT, createLocation(openingBracePosition, this.clonePosition()));\n }\n // argument name\n var value = this.parseIdentifierIfPossible().value;\n if (!value) {\n return this.error(ErrorKind.MALFORMED_ARGUMENT, createLocation(openingBracePosition, this.clonePosition()));\n }\n this.bumpSpace();\n if (this.isEOF()) {\n return this.error(ErrorKind.EXPECT_ARGUMENT_CLOSING_BRACE, createLocation(openingBracePosition, this.clonePosition()));\n }\n switch (this.char()) {\n // Simple argument: `{name}`\n case 125 /* `}` */: {\n this.bump(); // `}`\n return {\n val: {\n type: TYPE.argument,\n // value does not include the opening and closing braces.\n value: value,\n location: createLocation(openingBracePosition, this.clonePosition()),\n },\n err: null,\n };\n }\n // Argument with options: `{name, format, ...}`\n case 44 /* `,` */: {\n this.bump(); // `,`\n this.bumpSpace();\n if (this.isEOF()) {\n return this.error(ErrorKind.EXPECT_ARGUMENT_CLOSING_BRACE, createLocation(openingBracePosition, this.clonePosition()));\n }\n return this.parseArgumentOptions(nestingLevel, expectingCloseTag, value, openingBracePosition);\n }\n default:\n return this.error(ErrorKind.MALFORMED_ARGUMENT, createLocation(openingBracePosition, this.clonePosition()));\n }\n };\n /**\n * Advance the parser until the end of the identifier, if it is currently on\n * an identifier character. Return an empty string otherwise.\n */\n Parser.prototype.parseIdentifierIfPossible = function () {\n var startingPosition = this.clonePosition();\n var startOffset = this.offset();\n var value = matchIdentifierAtIndex(this.message, startOffset);\n var endOffset = startOffset + value.length;\n this.bumpTo(endOffset);\n var endPosition = this.clonePosition();\n var location = createLocation(startingPosition, endPosition);\n return { value: value, location: location };\n };\n Parser.prototype.parseArgumentOptions = function (nestingLevel, expectingCloseTag, value, openingBracePosition) {\n var _a;\n // Parse this range:\n // {name, type, style}\n // ^---^\n var typeStartPosition = this.clonePosition();\n var argType = this.parseIdentifierIfPossible().value;\n var typeEndPosition = this.clonePosition();\n switch (argType) {\n case '':\n // Expecting a style string number, date, time, plural, selectordinal, or select.\n return this.error(ErrorKind.EXPECT_ARGUMENT_TYPE, createLocation(typeStartPosition, typeEndPosition));\n case 'number':\n case 'date':\n case 'time': {\n // Parse this range:\n // {name, number, style}\n // ^-------^\n this.bumpSpace();\n var styleAndLocation = null;\n if (this.bumpIf(',')) {\n this.bumpSpace();\n var styleStartPosition = this.clonePosition();\n var result = this.parseSimpleArgStyleIfPossible();\n if (result.err) {\n return result;\n }\n var style = trimEnd(result.val);\n if (style.length === 0) {\n return this.error(ErrorKind.EXPECT_ARGUMENT_STYLE, createLocation(this.clonePosition(), this.clonePosition()));\n }\n var styleLocation = createLocation(styleStartPosition, this.clonePosition());\n styleAndLocation = { style: style, styleLocation: styleLocation };\n }\n var argCloseResult = this.tryParseArgumentClose(openingBracePosition);\n if (argCloseResult.err) {\n return argCloseResult;\n }\n var location_1 = createLocation(openingBracePosition, this.clonePosition());\n // Extract style or skeleton\n if (styleAndLocation && startsWith(styleAndLocation === null || styleAndLocation === void 0 ? void 0 : styleAndLocation.style, '::', 0)) {\n // Skeleton starts with `::`.\n var skeleton = trimStart(styleAndLocation.style.slice(2));\n if (argType === 'number') {\n var result = this.parseNumberSkeletonFromString(skeleton, styleAndLocation.styleLocation);\n if (result.err) {\n return result;\n }\n return {\n val: { type: TYPE.number, value: value, location: location_1, style: result.val },\n err: null,\n };\n }\n else {\n if (skeleton.length === 0) {\n return this.error(ErrorKind.EXPECT_DATE_TIME_SKELETON, location_1);\n }\n var dateTimePattern = skeleton;\n // Get \"best match\" pattern only if locale is passed, if not, let it\n // pass as-is where `parseDateTimeSkeleton()` will throw an error\n // for unsupported patterns.\n if (this.locale) {\n dateTimePattern = getBestPattern(skeleton, this.locale);\n }\n var style = {\n type: SKELETON_TYPE.dateTime,\n pattern: dateTimePattern,\n location: styleAndLocation.styleLocation,\n parsedOptions: this.shouldParseSkeletons\n ? parseDateTimeSkeleton(dateTimePattern)\n : {},\n };\n var type = argType === 'date' ? TYPE.date : TYPE.time;\n return {\n val: { type: type, value: value, location: location_1, style: style },\n err: null,\n };\n }\n }\n // Regular style or no style.\n return {\n val: {\n type: argType === 'number'\n ? TYPE.number\n : argType === 'date'\n ? TYPE.date\n : TYPE.time,\n value: value,\n location: location_1,\n style: (_a = styleAndLocation === null || styleAndLocation === void 0 ? void 0 : styleAndLocation.style) !== null && _a !== void 0 ? _a : null,\n },\n err: null,\n };\n }\n case 'plural':\n case 'selectordinal':\n case 'select': {\n // Parse this range:\n // {name, plural, options}\n // ^---------^\n var typeEndPosition_1 = this.clonePosition();\n this.bumpSpace();\n if (!this.bumpIf(',')) {\n return this.error(ErrorKind.EXPECT_SELECT_ARGUMENT_OPTIONS, createLocation(typeEndPosition_1, __assign({}, typeEndPosition_1)));\n }\n this.bumpSpace();\n // Parse offset:\n // {name, plural, offset:1, options}\n // ^-----^\n //\n // or the first option:\n //\n // {name, plural, one {...} other {...}}\n // ^--^\n var identifierAndLocation = this.parseIdentifierIfPossible();\n var pluralOffset = 0;\n if (argType !== 'select' && identifierAndLocation.value === 'offset') {\n if (!this.bumpIf(':')) {\n return this.error(ErrorKind.EXPECT_PLURAL_ARGUMENT_OFFSET_VALUE, createLocation(this.clonePosition(), this.clonePosition()));\n }\n this.bumpSpace();\n var result = this.tryParseDecimalInteger(ErrorKind.EXPECT_PLURAL_ARGUMENT_OFFSET_VALUE, ErrorKind.INVALID_PLURAL_ARGUMENT_OFFSET_VALUE);\n if (result.err) {\n return result;\n }\n // Parse another identifier for option parsing\n this.bumpSpace();\n identifierAndLocation = this.parseIdentifierIfPossible();\n pluralOffset = result.val;\n }\n var optionsResult = this.tryParsePluralOrSelectOptions(nestingLevel, argType, expectingCloseTag, identifierAndLocation);\n if (optionsResult.err) {\n return optionsResult;\n }\n var argCloseResult = this.tryParseArgumentClose(openingBracePosition);\n if (argCloseResult.err) {\n return argCloseResult;\n }\n var location_2 = createLocation(openingBracePosition, this.clonePosition());\n if (argType === 'select') {\n return {\n val: {\n type: TYPE.select,\n value: value,\n options: fromEntries(optionsResult.val),\n location: location_2,\n },\n err: null,\n };\n }\n else {\n return {\n val: {\n type: TYPE.plural,\n value: value,\n options: fromEntries(optionsResult.val),\n offset: pluralOffset,\n pluralType: argType === 'plural' ? 'cardinal' : 'ordinal',\n location: location_2,\n },\n err: null,\n };\n }\n }\n default:\n return this.error(ErrorKind.INVALID_ARGUMENT_TYPE, createLocation(typeStartPosition, typeEndPosition));\n }\n };\n Parser.prototype.tryParseArgumentClose = function (openingBracePosition) {\n // Parse: {value, number, ::currency/GBP }\n //\n if (this.isEOF() || this.char() !== 125 /* `}` */) {\n return this.error(ErrorKind.EXPECT_ARGUMENT_CLOSING_BRACE, createLocation(openingBracePosition, this.clonePosition()));\n }\n this.bump(); // `}`\n return { val: true, err: null };\n };\n /**\n * See: https://github.com/unicode-org/icu/blob/af7ed1f6d2298013dc303628438ec4abe1f16479/icu4c/source/common/messagepattern.cpp#L659\n */\n Parser.prototype.parseSimpleArgStyleIfPossible = function () {\n var nestedBraces = 0;\n var startPosition = this.clonePosition();\n while (!this.isEOF()) {\n var ch = this.char();\n switch (ch) {\n case 39 /* `'` */: {\n // Treat apostrophe as quoting but include it in the style part.\n // Find the end of the quoted literal text.\n this.bump();\n var apostrophePosition = this.clonePosition();\n if (!this.bumpUntil(\"'\")) {\n return this.error(ErrorKind.UNCLOSED_QUOTE_IN_ARGUMENT_STYLE, createLocation(apostrophePosition, this.clonePosition()));\n }\n this.bump();\n break;\n }\n case 123 /* `{` */: {\n nestedBraces += 1;\n this.bump();\n break;\n }\n case 125 /* `}` */: {\n if (nestedBraces > 0) {\n nestedBraces -= 1;\n }\n else {\n return {\n val: this.message.slice(startPosition.offset, this.offset()),\n err: null,\n };\n }\n break;\n }\n default:\n this.bump();\n break;\n }\n }\n return {\n val: this.message.slice(startPosition.offset, this.offset()),\n err: null,\n };\n };\n Parser.prototype.parseNumberSkeletonFromString = function (skeleton, location) {\n var tokens = [];\n try {\n tokens = parseNumberSkeletonFromString(skeleton);\n }\n catch (e) {\n return this.error(ErrorKind.INVALID_NUMBER_SKELETON, location);\n }\n return {\n val: {\n type: SKELETON_TYPE.number,\n tokens: tokens,\n location: location,\n parsedOptions: this.shouldParseSkeletons\n ? parseNumberSkeleton(tokens)\n : {},\n },\n err: null,\n };\n };\n /**\n * @param nesting_level The current nesting level of messages.\n * This can be positive when parsing message fragment in select or plural argument options.\n * @param parent_arg_type The parent argument's type.\n * @param parsed_first_identifier If provided, this is the first identifier-like selector of\n * the argument. It is a by-product of a previous parsing attempt.\n * @param expecting_close_tag If true, this message is directly or indirectly nested inside\n * between a pair of opening and closing tags. The nested message will not parse beyond\n * the closing tag boundary.\n */\n Parser.prototype.tryParsePluralOrSelectOptions = function (nestingLevel, parentArgType, expectCloseTag, parsedFirstIdentifier) {\n var _a;\n var hasOtherClause = false;\n var options = [];\n var parsedSelectors = new Set();\n var selector = parsedFirstIdentifier.value, selectorLocation = parsedFirstIdentifier.location;\n // Parse:\n // one {one apple}\n // ^--^\n while (true) {\n if (selector.length === 0) {\n var startPosition = this.clonePosition();\n if (parentArgType !== 'select' && this.bumpIf('=')) {\n // Try parse `={number}` selector\n var result = this.tryParseDecimalInteger(ErrorKind.EXPECT_PLURAL_ARGUMENT_SELECTOR, ErrorKind.INVALID_PLURAL_ARGUMENT_SELECTOR);\n if (result.err) {\n return result;\n }\n selectorLocation = createLocation(startPosition, this.clonePosition());\n selector = this.message.slice(startPosition.offset, this.offset());\n }\n else {\n break;\n }\n }\n // Duplicate selector clauses\n if (parsedSelectors.has(selector)) {\n return this.error(parentArgType === 'select'\n ? ErrorKind.DUPLICATE_SELECT_ARGUMENT_SELECTOR\n : ErrorKind.DUPLICATE_PLURAL_ARGUMENT_SELECTOR, selectorLocation);\n }\n if (selector === 'other') {\n hasOtherClause = true;\n }\n // Parse:\n // one {one apple}\n // ^----------^\n this.bumpSpace();\n var openingBracePosition = this.clonePosition();\n if (!this.bumpIf('{')) {\n return this.error(parentArgType === 'select'\n ? ErrorKind.EXPECT_SELECT_ARGUMENT_SELECTOR_FRAGMENT\n : ErrorKind.EXPECT_PLURAL_ARGUMENT_SELECTOR_FRAGMENT, createLocation(this.clonePosition(), this.clonePosition()));\n }\n var fragmentResult = this.parseMessage(nestingLevel + 1, parentArgType, expectCloseTag);\n if (fragmentResult.err) {\n return fragmentResult;\n }\n var argCloseResult = this.tryParseArgumentClose(openingBracePosition);\n if (argCloseResult.err) {\n return argCloseResult;\n }\n options.push([\n selector,\n {\n value: fragmentResult.val,\n location: createLocation(openingBracePosition, this.clonePosition()),\n },\n ]);\n // Keep track of the existing selectors\n parsedSelectors.add(selector);\n // Prep next selector clause.\n this.bumpSpace();\n (_a = this.parseIdentifierIfPossible(), selector = _a.value, selectorLocation = _a.location);\n }\n if (options.length === 0) {\n return this.error(parentArgType === 'select'\n ? ErrorKind.EXPECT_SELECT_ARGUMENT_SELECTOR\n : ErrorKind.EXPECT_PLURAL_ARGUMENT_SELECTOR, createLocation(this.clonePosition(), this.clonePosition()));\n }\n if (this.requiresOtherClause && !hasOtherClause) {\n return this.error(ErrorKind.MISSING_OTHER_CLAUSE, createLocation(this.clonePosition(), this.clonePosition()));\n }\n return { val: options, err: null };\n };\n Parser.prototype.tryParseDecimalInteger = function (expectNumberError, invalidNumberError) {\n var sign = 1;\n var startingPosition = this.clonePosition();\n if (this.bumpIf('+')) {\n }\n else if (this.bumpIf('-')) {\n sign = -1;\n }\n var hasDigits = false;\n var decimal = 0;\n while (!this.isEOF()) {\n var ch = this.char();\n if (ch >= 48 /* `0` */ && ch <= 57 /* `9` */) {\n hasDigits = true;\n decimal = decimal * 10 + (ch - 48);\n this.bump();\n }\n else {\n break;\n }\n }\n var location = createLocation(startingPosition, this.clonePosition());\n if (!hasDigits) {\n return this.error(expectNumberError, location);\n }\n decimal *= sign;\n if (!isSafeInteger(decimal)) {\n return this.error(invalidNumberError, location);\n }\n return { val: decimal, err: null };\n };\n Parser.prototype.offset = function () {\n return this.position.offset;\n };\n Parser.prototype.isEOF = function () {\n return this.offset() === this.message.length;\n };\n Parser.prototype.clonePosition = function () {\n // This is much faster than `Object.assign` or spread.\n return {\n offset: this.position.offset,\n line: this.position.line,\n column: this.position.column,\n };\n };\n /**\n * Return the code point at the current position of the parser.\n * Throws if the index is out of bound.\n */\n Parser.prototype.char = function () {\n var offset = this.position.offset;\n if (offset >= this.message.length) {\n throw Error('out of bound');\n }\n var code = codePointAt(this.message, offset);\n if (code === undefined) {\n throw Error(\"Offset \".concat(offset, \" is at invalid UTF-16 code unit boundary\"));\n }\n return code;\n };\n Parser.prototype.error = function (kind, location) {\n return {\n val: null,\n err: {\n kind: kind,\n message: this.message,\n location: location,\n },\n };\n };\n /** Bump the parser to the next UTF-16 code unit. */\n Parser.prototype.bump = function () {\n if (this.isEOF()) {\n return;\n }\n var code = this.char();\n if (code === 10 /* '\\n' */) {\n this.position.line += 1;\n this.position.column = 1;\n this.position.offset += 1;\n }\n else {\n this.position.column += 1;\n // 0 ~ 0x10000 -> unicode BMP, otherwise skip the surrogate pair.\n this.position.offset += code < 0x10000 ? 1 : 2;\n }\n };\n /**\n * If the substring starting at the current position of the parser has\n * the given prefix, then bump the parser to the character immediately\n * following the prefix and return true. Otherwise, don't bump the parser\n * and return false.\n */\n Parser.prototype.bumpIf = function (prefix) {\n if (startsWith(this.message, prefix, this.offset())) {\n for (var i = 0; i < prefix.length; i++) {\n this.bump();\n }\n return true;\n }\n return false;\n };\n /**\n * Bump the parser until the pattern character is found and return `true`.\n * Otherwise bump to the end of the file and return `false`.\n */\n Parser.prototype.bumpUntil = function (pattern) {\n var currentOffset = this.offset();\n var index = this.message.indexOf(pattern, currentOffset);\n if (index >= 0) {\n this.bumpTo(index);\n return true;\n }\n else {\n this.bumpTo(this.message.length);\n return false;\n }\n };\n /**\n * Bump the parser to the target offset.\n * If target offset is beyond the end of the input, bump the parser to the end of the input.\n */\n Parser.prototype.bumpTo = function (targetOffset) {\n if (this.offset() > targetOffset) {\n throw Error(\"targetOffset \".concat(targetOffset, \" must be greater than or equal to the current offset \").concat(this.offset()));\n }\n targetOffset = Math.min(targetOffset, this.message.length);\n while (true) {\n var offset = this.offset();\n if (offset === targetOffset) {\n break;\n }\n if (offset > targetOffset) {\n throw Error(\"targetOffset \".concat(targetOffset, \" is at invalid UTF-16 code unit boundary\"));\n }\n this.bump();\n if (this.isEOF()) {\n break;\n }\n }\n };\n /** advance the parser through all whitespace to the next non-whitespace code unit. */\n Parser.prototype.bumpSpace = function () {\n while (!this.isEOF() && _isWhiteSpace(this.char())) {\n this.bump();\n }\n };\n /**\n * Peek at the *next* Unicode codepoint in the input without advancing the parser.\n * If the input has been exhausted, then this returns null.\n */\n Parser.prototype.peek = function () {\n if (this.isEOF()) {\n return null;\n }\n var code = this.char();\n var offset = this.offset();\n var nextCode = this.message.charCodeAt(offset + (code >= 0x10000 ? 2 : 1));\n return nextCode !== null && nextCode !== void 0 ? nextCode : null;\n };\n return Parser;\n}());\nexport { Parser };\n/**\n * This check if codepoint is alphabet (lower & uppercase)\n * @param codepoint\n * @returns\n */\nfunction _isAlpha(codepoint) {\n return ((codepoint >= 97 && codepoint <= 122) ||\n (codepoint >= 65 && codepoint <= 90));\n}\nfunction _isAlphaOrSlash(codepoint) {\n return _isAlpha(codepoint) || codepoint === 47; /* '/' */\n}\n/** See `parseTag` function docs. */\nfunction _isPotentialElementNameChar(c) {\n return (c === 45 /* '-' */ ||\n c === 46 /* '.' */ ||\n (c >= 48 && c <= 57) /* 0..9 */ ||\n c === 95 /* '_' */ ||\n (c >= 97 && c <= 122) /** a..z */ ||\n (c >= 65 && c <= 90) /* A..Z */ ||\n c == 0xb7 ||\n (c >= 0xc0 && c <= 0xd6) ||\n (c >= 0xd8 && c <= 0xf6) ||\n (c >= 0xf8 && c <= 0x37d) ||\n (c >= 0x37f && c <= 0x1fff) ||\n (c >= 0x200c && c <= 0x200d) ||\n (c >= 0x203f && c <= 0x2040) ||\n (c >= 0x2070 && c <= 0x218f) ||\n (c >= 0x2c00 && c <= 0x2fef) ||\n (c >= 0x3001 && c <= 0xd7ff) ||\n (c >= 0xf900 && c <= 0xfdcf) ||\n (c >= 0xfdf0 && c <= 0xfffd) ||\n (c >= 0x10000 && c <= 0xeffff));\n}\n/**\n * Code point equivalent of regex `\\p{White_Space}`.\n * From: https://www.unicode.org/Public/UCD/latest/ucd/PropList.txt\n */\nfunction _isWhiteSpace(c) {\n return ((c >= 0x0009 && c <= 0x000d) ||\n c === 0x0020 ||\n c === 0x0085 ||\n (c >= 0x200e && c <= 0x200f) ||\n c === 0x2028 ||\n c === 0x2029);\n}\n/**\n * Code point equivalent of regex `\\p{Pattern_Syntax}`.\n * See https://www.unicode.org/Public/UCD/latest/ucd/PropList.txt\n */\nfunction _isPatternSyntax(c) {\n return ((c >= 0x0021 && c <= 0x0023) ||\n c === 0x0024 ||\n (c >= 0x0025 && c <= 0x0027) ||\n c === 0x0028 ||\n c === 0x0029 ||\n c === 0x002a ||\n c === 0x002b ||\n c === 0x002c ||\n c === 0x002d ||\n (c >= 0x002e && c <= 0x002f) ||\n (c >= 0x003a && c <= 0x003b) ||\n (c >= 0x003c && c <= 0x003e) ||\n (c >= 0x003f && c <= 0x0040) ||\n c === 0x005b ||\n c === 0x005c ||\n c === 0x005d ||\n c === 0x005e ||\n c === 0x0060 ||\n c === 0x007b ||\n c === 0x007c ||\n c === 0x007d ||\n c === 0x007e ||\n c === 0x00a1 ||\n (c >= 0x00a2 && c <= 0x00a5) ||\n c === 0x00a6 ||\n c === 0x00a7 ||\n c === 0x00a9 ||\n c === 0x00ab ||\n c === 0x00ac ||\n c === 0x00ae ||\n c === 0x00b0 ||\n c === 0x00b1 ||\n c === 0x00b6 ||\n c === 0x00bb ||\n c === 0x00bf ||\n c === 0x00d7 ||\n c === 0x00f7 ||\n (c >= 0x2010 && c <= 0x2015) ||\n (c >= 0x2016 && c <= 0x2017) ||\n c === 0x2018 ||\n c === 0x2019 ||\n c === 0x201a ||\n (c >= 0x201b && c <= 0x201c) ||\n c === 0x201d ||\n c === 0x201e ||\n c === 0x201f ||\n (c >= 0x2020 && c <= 0x2027) ||\n (c >= 0x2030 && c <= 0x2038) ||\n c === 0x2039 ||\n c === 0x203a ||\n (c >= 0x203b && c <= 0x203e) ||\n (c >= 0x2041 && c <= 0x2043) ||\n c === 0x2044 ||\n c === 0x2045 ||\n c === 0x2046 ||\n (c >= 0x2047 && c <= 0x2051) ||\n c === 0x2052 ||\n c === 0x2053 ||\n (c >= 0x2055 && c <= 0x205e) ||\n (c >= 0x2190 && c <= 0x2194) ||\n (c >= 0x2195 && c <= 0x2199) ||\n (c >= 0x219a && c <= 0x219b) ||\n (c >= 0x219c && c <= 0x219f) ||\n c === 0x21a0 ||\n (c >= 0x21a1 && c <= 0x21a2) ||\n c === 0x21a3 ||\n (c >= 0x21a4 && c <= 0x21a5) ||\n c === 0x21a6 ||\n (c >= 0x21a7 && c <= 0x21ad) ||\n c === 0x21ae ||\n (c >= 0x21af && c <= 0x21cd) ||\n (c >= 0x21ce && c <= 0x21cf) ||\n (c >= 0x21d0 && c <= 0x21d1) ||\n c === 0x21d2 ||\n c === 0x21d3 ||\n c === 0x21d4 ||\n (c >= 0x21d5 && c <= 0x21f3) ||\n (c >= 0x21f4 && c <= 0x22ff) ||\n (c >= 0x2300 && c <= 0x2307) ||\n c === 0x2308 ||\n c === 0x2309 ||\n c === 0x230a ||\n c === 0x230b ||\n (c >= 0x230c && c <= 0x231f) ||\n (c >= 0x2320 && c <= 0x2321) ||\n (c >= 0x2322 && c <= 0x2328) ||\n c === 0x2329 ||\n c === 0x232a ||\n (c >= 0x232b && c <= 0x237b) ||\n c === 0x237c ||\n (c >= 0x237d && c <= 0x239a) ||\n (c >= 0x239b && c <= 0x23b3) ||\n (c >= 0x23b4 && c <= 0x23db) ||\n (c >= 0x23dc && c <= 0x23e1) ||\n (c >= 0x23e2 && c <= 0x2426) ||\n (c >= 0x2427 && c <= 0x243f) ||\n (c >= 0x2440 && c <= 0x244a) ||\n (c >= 0x244b && c <= 0x245f) ||\n (c >= 0x2500 && c <= 0x25b6) ||\n c === 0x25b7 ||\n (c >= 0x25b8 && c <= 0x25c0) ||\n c === 0x25c1 ||\n (c >= 0x25c2 && c <= 0x25f7) ||\n (c >= 0x25f8 && c <= 0x25ff) ||\n (c >= 0x2600 && c <= 0x266e) ||\n c === 0x266f ||\n (c >= 0x2670 && c <= 0x2767) ||\n c === 0x2768 ||\n c === 0x2769 ||\n c === 0x276a ||\n c === 0x276b ||\n c === 0x276c ||\n c === 0x276d ||\n c === 0x276e ||\n c === 0x276f ||\n c === 0x2770 ||\n c === 0x2771 ||\n c === 0x2772 ||\n c === 0x2773 ||\n c === 0x2774 ||\n c === 0x2775 ||\n (c >= 0x2794 && c <= 0x27bf) ||\n (c >= 0x27c0 && c <= 0x27c4) ||\n c === 0x27c5 ||\n c === 0x27c6 ||\n (c >= 0x27c7 && c <= 0x27e5) ||\n c === 0x27e6 ||\n c === 0x27e7 ||\n c === 0x27e8 ||\n c === 0x27e9 ||\n c === 0x27ea ||\n c === 0x27eb ||\n c === 0x27ec ||\n c === 0x27ed ||\n c === 0x27ee ||\n c === 0x27ef ||\n (c >= 0x27f0 && c <= 0x27ff) ||\n (c >= 0x2800 && c <= 0x28ff) ||\n (c >= 0x2900 && c <= 0x2982) ||\n c === 0x2983 ||\n c === 0x2984 ||\n c === 0x2985 ||\n c === 0x2986 ||\n c === 0x2987 ||\n c === 0x2988 ||\n c === 0x2989 ||\n c === 0x298a ||\n c === 0x298b ||\n c === 0x298c ||\n c === 0x298d ||\n c === 0x298e ||\n c === 0x298f ||\n c === 0x2990 ||\n c === 0x2991 ||\n c === 0x2992 ||\n c === 0x2993 ||\n c === 0x2994 ||\n c === 0x2995 ||\n c === 0x2996 ||\n c === 0x2997 ||\n c === 0x2998 ||\n (c >= 0x2999 && c <= 0x29d7) ||\n c === 0x29d8 ||\n c === 0x29d9 ||\n c === 0x29da ||\n c === 0x29db ||\n (c >= 0x29dc && c <= 0x29fb) ||\n c === 0x29fc ||\n c === 0x29fd ||\n (c >= 0x29fe && c <= 0x2aff) ||\n (c >= 0x2b00 && c <= 0x2b2f) ||\n (c >= 0x2b30 && c <= 0x2b44) ||\n (c >= 0x2b45 && c <= 0x2b46) ||\n (c >= 0x2b47 && c <= 0x2b4c) ||\n (c >= 0x2b4d && c <= 0x2b73) ||\n (c >= 0x2b74 && c <= 0x2b75) ||\n (c >= 0x2b76 && c <= 0x2b95) ||\n c === 0x2b96 ||\n (c >= 0x2b97 && c <= 0x2bff) ||\n (c >= 0x2e00 && c <= 0x2e01) ||\n c === 0x2e02 ||\n c === 0x2e03 ||\n c === 0x2e04 ||\n c === 0x2e05 ||\n (c >= 0x2e06 && c <= 0x2e08) ||\n c === 0x2e09 ||\n c === 0x2e0a ||\n c === 0x2e0b ||\n c === 0x2e0c ||\n c === 0x2e0d ||\n (c >= 0x2e0e && c <= 0x2e16) ||\n c === 0x2e17 ||\n (c >= 0x2e18 && c <= 0x2e19) ||\n c === 0x2e1a ||\n c === 0x2e1b ||\n c === 0x2e1c ||\n c === 0x2e1d ||\n (c >= 0x2e1e && c <= 0x2e1f) ||\n c === 0x2e20 ||\n c === 0x2e21 ||\n c === 0x2e22 ||\n c === 0x2e23 ||\n c === 0x2e24 ||\n c === 0x2e25 ||\n c === 0x2e26 ||\n c === 0x2e27 ||\n c === 0x2e28 ||\n c === 0x2e29 ||\n (c >= 0x2e2a && c <= 0x2e2e) ||\n c === 0x2e2f ||\n (c >= 0x2e30 && c <= 0x2e39) ||\n (c >= 0x2e3a && c <= 0x2e3b) ||\n (c >= 0x2e3c && c <= 0x2e3f) ||\n c === 0x2e40 ||\n c === 0x2e41 ||\n c === 0x2e42 ||\n (c >= 0x2e43 && c <= 0x2e4f) ||\n (c >= 0x2e50 && c <= 0x2e51) ||\n c === 0x2e52 ||\n (c >= 0x2e53 && c <= 0x2e7f) ||\n (c >= 0x3001 && c <= 0x3003) ||\n c === 0x3008 ||\n c === 0x3009 ||\n c === 0x300a ||\n c === 0x300b ||\n c === 0x300c ||\n c === 0x300d ||\n c === 0x300e ||\n c === 0x300f ||\n c === 0x3010 ||\n c === 0x3011 ||\n (c >= 0x3012 && c <= 0x3013) ||\n c === 0x3014 ||\n c === 0x3015 ||\n c === 0x3016 ||\n c === 0x3017 ||\n c === 0x3018 ||\n c === 0x3019 ||\n c === 0x301a ||\n c === 0x301b ||\n c === 0x301c ||\n c === 0x301d ||\n (c >= 0x301e && c <= 0x301f) ||\n c === 0x3020 ||\n c === 0x3030 ||\n c === 0xfd3e ||\n c === 0xfd3f ||\n (c >= 0xfe45 && c <= 0xfe46));\n}\n","import { timeData } from './time-data.generated';\n/**\n * Returns the best matching date time pattern if a date time skeleton\n * pattern is provided with a locale. Follows the Unicode specification:\n * https://www.unicode.org/reports/tr35/tr35-dates.html#table-mapping-requested-time-skeletons-to-patterns\n * @param skeleton date time skeleton pattern that possibly includes j, J or C\n * @param locale\n */\nexport function getBestPattern(skeleton, locale) {\n var skeletonCopy = '';\n for (var patternPos = 0; patternPos < skeleton.length; patternPos++) {\n var patternChar = skeleton.charAt(patternPos);\n if (patternChar === 'j') {\n var extraLength = 0;\n while (patternPos + 1 < skeleton.length &&\n skeleton.charAt(patternPos + 1) === patternChar) {\n extraLength++;\n patternPos++;\n }\n var hourLen = 1 + (extraLength & 1);\n var dayPeriodLen = extraLength < 2 ? 1 : 3 + (extraLength >> 1);\n var dayPeriodChar = 'a';\n var hourChar = getDefaultHourSymbolFromLocale(locale);\n if (hourChar == 'H' || hourChar == 'k') {\n dayPeriodLen = 0;\n }\n while (dayPeriodLen-- > 0) {\n skeletonCopy += dayPeriodChar;\n }\n while (hourLen-- > 0) {\n skeletonCopy = hourChar + skeletonCopy;\n }\n }\n else if (patternChar === 'J') {\n skeletonCopy += 'H';\n }\n else {\n skeletonCopy += patternChar;\n }\n }\n return skeletonCopy;\n}\n/**\n * Maps the [hour cycle type](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/hourCycle)\n * of the given `locale` to the corresponding time pattern.\n * @param locale\n */\nfunction getDefaultHourSymbolFromLocale(locale) {\n var hourCycle = locale.hourCycle;\n if (hourCycle === undefined &&\n // @ts-ignore hourCycle(s) is not identified yet\n locale.hourCycles &&\n // @ts-ignore\n locale.hourCycles.length) {\n // @ts-ignore\n hourCycle = locale.hourCycles[0];\n }\n if (hourCycle) {\n switch (hourCycle) {\n case 'h24':\n return 'k';\n case 'h23':\n return 'H';\n case 'h12':\n return 'h';\n case 'h11':\n return 'K';\n default:\n throw new Error('Invalid hourCycle');\n }\n }\n // TODO: Once hourCycle is fully supported remove the following with data generation\n var languageTag = locale.language;\n var regionTag;\n if (languageTag !== 'root') {\n regionTag = locale.maximize().region;\n }\n var hourCycles = timeData[regionTag || ''] ||\n timeData[languageTag || ''] ||\n timeData[\"\".concat(languageTag, \"-001\")] ||\n timeData['001'];\n return hourCycles[0];\n}\n","import { __assign } from \"tslib\";\nimport { ErrorKind } from './error';\nimport { Parser } from './parser';\nimport { isDateElement, isDateTimeSkeleton, isNumberElement, isNumberSkeleton, isPluralElement, isSelectElement, isTagElement, isTimeElement, } from './types';\nfunction pruneLocation(els) {\n els.forEach(function (el) {\n delete el.location;\n if (isSelectElement(el) || isPluralElement(el)) {\n for (var k in el.options) {\n delete el.options[k].location;\n pruneLocation(el.options[k].value);\n }\n }\n else if (isNumberElement(el) && isNumberSkeleton(el.style)) {\n delete el.style.location;\n }\n else if ((isDateElement(el) || isTimeElement(el)) &&\n isDateTimeSkeleton(el.style)) {\n delete el.style.location;\n }\n else if (isTagElement(el)) {\n pruneLocation(el.children);\n }\n });\n}\nexport function parse(message, opts) {\n if (opts === void 0) { opts = {}; }\n opts = __assign({ shouldParseSkeletons: true, requiresOtherClause: true }, opts);\n var result = new Parser(message, opts).parse();\n if (result.err) {\n var error = SyntaxError(ErrorKind[result.err.kind]);\n // @ts-expect-error Assign to error object\n error.location = result.err.location;\n // @ts-expect-error Assign to error object\n error.originalMessage = result.err.message;\n throw error;\n }\n if (!(opts === null || opts === void 0 ? void 0 : opts.captureLocation)) {\n pruneLocation(result.val);\n }\n return result.val;\n}\nexport * from './types';\n// only for testing\nexport var _Parser = Parser;\n","//\n// Main\n//\nexport function memoize(fn, options) {\n var cache = options && options.cache ? options.cache : cacheDefault;\n var serializer = options && options.serializer ? options.serializer : serializerDefault;\n var strategy = options && options.strategy ? options.strategy : strategyDefault;\n return strategy(fn, {\n cache: cache,\n serializer: serializer,\n });\n}\n//\n// Strategy\n//\nfunction isPrimitive(value) {\n return (value == null || typeof value === 'number' || typeof value === 'boolean'); // || typeof value === \"string\" 'unsafe' primitive for our needs\n}\nfunction monadic(fn, cache, serializer, arg) {\n var cacheKey = isPrimitive(arg) ? arg : serializer(arg);\n var computedValue = cache.get(cacheKey);\n if (typeof computedValue === 'undefined') {\n computedValue = fn.call(this, arg);\n cache.set(cacheKey, computedValue);\n }\n return computedValue;\n}\nfunction variadic(fn, cache, serializer) {\n var args = Array.prototype.slice.call(arguments, 3);\n var cacheKey = serializer(args);\n var computedValue = cache.get(cacheKey);\n if (typeof computedValue === 'undefined') {\n computedValue = fn.apply(this, args);\n cache.set(cacheKey, computedValue);\n }\n return computedValue;\n}\nfunction assemble(fn, context, strategy, cache, serialize) {\n return strategy.bind(context, fn, cache, serialize);\n}\nfunction strategyDefault(fn, options) {\n var strategy = fn.length === 1 ? monadic : variadic;\n return assemble(fn, this, strategy, options.cache.create(), options.serializer);\n}\nfunction strategyVariadic(fn, options) {\n return assemble(fn, this, variadic, options.cache.create(), options.serializer);\n}\nfunction strategyMonadic(fn, options) {\n return assemble(fn, this, monadic, options.cache.create(), options.serializer);\n}\n//\n// Serializer\n//\nvar serializerDefault = function () {\n return JSON.stringify(arguments);\n};\n//\n// Cache\n//\nfunction ObjectWithoutPrototypeCache() {\n this.cache = Object.create(null);\n}\nObjectWithoutPrototypeCache.prototype.get = function (key) {\n return this.cache[key];\n};\nObjectWithoutPrototypeCache.prototype.set = function (key, value) {\n this.cache[key] = value;\n};\nvar cacheDefault = {\n create: function create() {\n // @ts-ignore\n return new ObjectWithoutPrototypeCache();\n },\n};\nexport var strategies = {\n variadic: strategyVariadic,\n monadic: strategyMonadic,\n};\n","import { __extends } from \"tslib\";\nexport var ErrorCode;\n(function (ErrorCode) {\n // When we have a placeholder but no value to format\n ErrorCode[\"MISSING_VALUE\"] = \"MISSING_VALUE\";\n // When value supplied is invalid\n ErrorCode[\"INVALID_VALUE\"] = \"INVALID_VALUE\";\n // When we need specific Intl API but it's not available\n ErrorCode[\"MISSING_INTL_API\"] = \"MISSING_INTL_API\";\n})(ErrorCode || (ErrorCode = {}));\nvar FormatError = /** @class */ (function (_super) {\n __extends(FormatError, _super);\n function FormatError(msg, code, originalMessage) {\n var _this = _super.call(this, msg) || this;\n _this.code = code;\n _this.originalMessage = originalMessage;\n return _this;\n }\n FormatError.prototype.toString = function () {\n return \"[formatjs Error: \".concat(this.code, \"] \").concat(this.message);\n };\n return FormatError;\n}(Error));\nexport { FormatError };\nvar InvalidValueError = /** @class */ (function (_super) {\n __extends(InvalidValueError, _super);\n function InvalidValueError(variableId, value, options, originalMessage) {\n return _super.call(this, \"Invalid values for \\\"\".concat(variableId, \"\\\": \\\"\").concat(value, \"\\\". Options are \\\"\").concat(Object.keys(options).join('\", \"'), \"\\\"\"), ErrorCode.INVALID_VALUE, originalMessage) || this;\n }\n return InvalidValueError;\n}(FormatError));\nexport { InvalidValueError };\nvar InvalidValueTypeError = /** @class */ (function (_super) {\n __extends(InvalidValueTypeError, _super);\n function InvalidValueTypeError(value, type, originalMessage) {\n return _super.call(this, \"Value for \\\"\".concat(value, \"\\\" must be of type \").concat(type), ErrorCode.INVALID_VALUE, originalMessage) || this;\n }\n return InvalidValueTypeError;\n}(FormatError));\nexport { InvalidValueTypeError };\nvar MissingValueError = /** @class */ (function (_super) {\n __extends(MissingValueError, _super);\n function MissingValueError(variableId, originalMessage) {\n return _super.call(this, \"The intl string context variable \\\"\".concat(variableId, \"\\\" was not provided to the string \\\"\").concat(originalMessage, \"\\\"\"), ErrorCode.MISSING_VALUE, originalMessage) || this;\n }\n return MissingValueError;\n}(FormatError));\nexport { MissingValueError };\n","import { isArgumentElement, isDateElement, isDateTimeSkeleton, isLiteralElement, isNumberElement, isNumberSkeleton, isPluralElement, isPoundElement, isSelectElement, isTimeElement, isTagElement, } from '@formatjs/icu-messageformat-parser';\nimport { MissingValueError, InvalidValueError, ErrorCode, FormatError, InvalidValueTypeError, } from './error';\nexport var PART_TYPE;\n(function (PART_TYPE) {\n PART_TYPE[PART_TYPE[\"literal\"] = 0] = \"literal\";\n PART_TYPE[PART_TYPE[\"object\"] = 1] = \"object\";\n})(PART_TYPE || (PART_TYPE = {}));\nfunction mergeLiteral(parts) {\n if (parts.length < 2) {\n return parts;\n }\n return parts.reduce(function (all, part) {\n var lastPart = all[all.length - 1];\n if (!lastPart ||\n lastPart.type !== PART_TYPE.literal ||\n part.type !== PART_TYPE.literal) {\n all.push(part);\n }\n else {\n lastPart.value += part.value;\n }\n return all;\n }, []);\n}\nexport function isFormatXMLElementFn(el) {\n return typeof el === 'function';\n}\n// TODO(skeleton): add skeleton support\nexport function formatToParts(els, locales, formatters, formats, values, currentPluralValue, \n// For debugging\noriginalMessage) {\n // Hot path for straight simple msg translations\n if (els.length === 1 && isLiteralElement(els[0])) {\n return [\n {\n type: PART_TYPE.literal,\n value: els[0].value,\n },\n ];\n }\n var result = [];\n for (var _i = 0, els_1 = els; _i < els_1.length; _i++) {\n var el = els_1[_i];\n // Exit early for string parts.\n if (isLiteralElement(el)) {\n result.push({\n type: PART_TYPE.literal,\n value: el.value,\n });\n continue;\n }\n // TODO: should this part be literal type?\n // Replace `#` in plural rules with the actual numeric value.\n if (isPoundElement(el)) {\n if (typeof currentPluralValue === 'number') {\n result.push({\n type: PART_TYPE.literal,\n value: formatters.getNumberFormat(locales).format(currentPluralValue),\n });\n }\n continue;\n }\n var varName = el.value;\n // Enforce that all required values are provided by the caller.\n if (!(values && varName in values)) {\n throw new MissingValueError(varName, originalMessage);\n }\n var value = values[varName];\n if (isArgumentElement(el)) {\n if (!value || typeof value === 'string' || typeof value === 'number') {\n value =\n typeof value === 'string' || typeof value === 'number'\n ? String(value)\n : '';\n }\n result.push({\n type: typeof value === 'string' ? PART_TYPE.literal : PART_TYPE.object,\n value: value,\n });\n continue;\n }\n // Recursively format plural and select parts' option — which can be a\n // nested pattern structure. The choosing of the option to use is\n // abstracted-by and delegated-to the part helper object.\n if (isDateElement(el)) {\n var style = typeof el.style === 'string'\n ? formats.date[el.style]\n : isDateTimeSkeleton(el.style)\n ? el.style.parsedOptions\n : undefined;\n result.push({\n type: PART_TYPE.literal,\n value: formatters\n .getDateTimeFormat(locales, style)\n .format(value),\n });\n continue;\n }\n if (isTimeElement(el)) {\n var style = typeof el.style === 'string'\n ? formats.time[el.style]\n : isDateTimeSkeleton(el.style)\n ? el.style.parsedOptions\n : formats.time.medium;\n result.push({\n type: PART_TYPE.literal,\n value: formatters\n .getDateTimeFormat(locales, style)\n .format(value),\n });\n continue;\n }\n if (isNumberElement(el)) {\n var style = typeof el.style === 'string'\n ? formats.number[el.style]\n : isNumberSkeleton(el.style)\n ? el.style.parsedOptions\n : undefined;\n if (style && style.scale) {\n value =\n value *\n (style.scale || 1);\n }\n result.push({\n type: PART_TYPE.literal,\n value: formatters\n .getNumberFormat(locales, style)\n .format(value),\n });\n continue;\n }\n if (isTagElement(el)) {\n var children = el.children, value_1 = el.value;\n var formatFn = values[value_1];\n if (!isFormatXMLElementFn(formatFn)) {\n throw new InvalidValueTypeError(value_1, 'function', originalMessage);\n }\n var parts = formatToParts(children, locales, formatters, formats, values, currentPluralValue);\n var chunks = formatFn(parts.map(function (p) { return p.value; }));\n if (!Array.isArray(chunks)) {\n chunks = [chunks];\n }\n result.push.apply(result, chunks.map(function (c) {\n return {\n type: typeof c === 'string' ? PART_TYPE.literal : PART_TYPE.object,\n value: c,\n };\n }));\n }\n if (isSelectElement(el)) {\n var opt = el.options[value] || el.options.other;\n if (!opt) {\n throw new InvalidValueError(el.value, value, Object.keys(el.options), originalMessage);\n }\n result.push.apply(result, formatToParts(opt.value, locales, formatters, formats, values));\n continue;\n }\n if (isPluralElement(el)) {\n var opt = el.options[\"=\".concat(value)];\n if (!opt) {\n if (!Intl.PluralRules) {\n throw new FormatError(\"Intl.PluralRules is not available in this environment.\\nTry polyfilling it using \\\"@formatjs/intl-pluralrules\\\"\\n\", ErrorCode.MISSING_INTL_API, originalMessage);\n }\n var rule = formatters\n .getPluralRules(locales, { type: el.pluralType })\n .select(value - (el.offset || 0));\n opt = el.options[rule] || el.options.other;\n }\n if (!opt) {\n throw new InvalidValueError(el.value, value, Object.keys(el.options), originalMessage);\n }\n result.push.apply(result, formatToParts(opt.value, locales, formatters, formats, values, value - (el.offset || 0)));\n continue;\n }\n }\n return mergeLiteral(result);\n}\n","/*\nCopyright (c) 2014, Yahoo! Inc. All rights reserved.\nCopyrights licensed under the New BSD License.\nSee the accompanying LICENSE file for terms.\n*/\nimport { __assign, __rest, __spreadArray } from \"tslib\";\nimport { parse, } from '@formatjs/icu-messageformat-parser';\nimport { memoize, strategies } from '@formatjs/fast-memoize';\nimport { formatToParts, PART_TYPE, } from './formatters';\n// -- MessageFormat --------------------------------------------------------\nfunction mergeConfig(c1, c2) {\n if (!c2) {\n return c1;\n }\n return __assign(__assign(__assign({}, (c1 || {})), (c2 || {})), Object.keys(c1).reduce(function (all, k) {\n all[k] = __assign(__assign({}, c1[k]), (c2[k] || {}));\n return all;\n }, {}));\n}\nfunction mergeConfigs(defaultConfig, configs) {\n if (!configs) {\n return defaultConfig;\n }\n return Object.keys(defaultConfig).reduce(function (all, k) {\n all[k] = mergeConfig(defaultConfig[k], configs[k]);\n return all;\n }, __assign({}, defaultConfig));\n}\nfunction createFastMemoizeCache(store) {\n return {\n create: function () {\n return {\n get: function (key) {\n return store[key];\n },\n set: function (key, value) {\n store[key] = value;\n },\n };\n },\n };\n}\nfunction createDefaultFormatters(cache) {\n if (cache === void 0) { cache = {\n number: {},\n dateTime: {},\n pluralRules: {},\n }; }\n return {\n getNumberFormat: memoize(function () {\n var _a;\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n return new ((_a = Intl.NumberFormat).bind.apply(_a, __spreadArray([void 0], args, false)))();\n }, {\n cache: createFastMemoizeCache(cache.number),\n strategy: strategies.variadic,\n }),\n getDateTimeFormat: memoize(function () {\n var _a;\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n return new ((_a = Intl.DateTimeFormat).bind.apply(_a, __spreadArray([void 0], args, false)))();\n }, {\n cache: createFastMemoizeCache(cache.dateTime),\n strategy: strategies.variadic,\n }),\n getPluralRules: memoize(function () {\n var _a;\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n return new ((_a = Intl.PluralRules).bind.apply(_a, __spreadArray([void 0], args, false)))();\n }, {\n cache: createFastMemoizeCache(cache.pluralRules),\n strategy: strategies.variadic,\n }),\n };\n}\nvar IntlMessageFormat = /** @class */ (function () {\n function IntlMessageFormat(message, locales, overrideFormats, opts) {\n var _this = this;\n if (locales === void 0) { locales = IntlMessageFormat.defaultLocale; }\n this.formatterCache = {\n number: {},\n dateTime: {},\n pluralRules: {},\n };\n this.format = function (values) {\n var parts = _this.formatToParts(values);\n // Hot path for straight simple msg translations\n if (parts.length === 1) {\n return parts[0].value;\n }\n var result = parts.reduce(function (all, part) {\n if (!all.length ||\n part.type !== PART_TYPE.literal ||\n typeof all[all.length - 1] !== 'string') {\n all.push(part.value);\n }\n else {\n all[all.length - 1] += part.value;\n }\n return all;\n }, []);\n if (result.length <= 1) {\n return result[0] || '';\n }\n return result;\n };\n this.formatToParts = function (values) {\n return formatToParts(_this.ast, _this.locales, _this.formatters, _this.formats, values, undefined, _this.message);\n };\n this.resolvedOptions = function () {\n var _a;\n return ({\n locale: ((_a = _this.resolvedLocale) === null || _a === void 0 ? void 0 : _a.toString()) ||\n Intl.NumberFormat.supportedLocalesOf(_this.locales)[0],\n });\n };\n this.getAst = function () { return _this.ast; };\n // Defined first because it's used to build the format pattern.\n this.locales = locales;\n this.resolvedLocale = IntlMessageFormat.resolveLocale(locales);\n if (typeof message === 'string') {\n this.message = message;\n if (!IntlMessageFormat.__parse) {\n throw new TypeError('IntlMessageFormat.__parse must be set to process `message` of type `string`');\n }\n var _a = opts || {}, formatters = _a.formatters, parseOpts = __rest(_a, [\"formatters\"]);\n // Parse string messages into an AST.\n this.ast = IntlMessageFormat.__parse(message, __assign(__assign({}, parseOpts), { locale: this.resolvedLocale }));\n }\n else {\n this.ast = message;\n }\n if (!Array.isArray(this.ast)) {\n throw new TypeError('A message must be provided as a String or AST.');\n }\n // Creates a new object with the specified `formats` merged with the default\n // formats.\n this.formats = mergeConfigs(IntlMessageFormat.formats, overrideFormats);\n this.formatters =\n (opts && opts.formatters) || createDefaultFormatters(this.formatterCache);\n }\n Object.defineProperty(IntlMessageFormat, \"defaultLocale\", {\n get: function () {\n if (!IntlMessageFormat.memoizedDefaultLocale) {\n IntlMessageFormat.memoizedDefaultLocale =\n new Intl.NumberFormat().resolvedOptions().locale;\n }\n return IntlMessageFormat.memoizedDefaultLocale;\n },\n enumerable: false,\n configurable: true\n });\n IntlMessageFormat.memoizedDefaultLocale = null;\n IntlMessageFormat.resolveLocale = function (locales) {\n if (typeof Intl.Locale === 'undefined') {\n return;\n }\n var supportedLocales = Intl.NumberFormat.supportedLocalesOf(locales);\n if (supportedLocales.length > 0) {\n return new Intl.Locale(supportedLocales[0]);\n }\n return new Intl.Locale(typeof locales === 'string' ? locales : locales[0]);\n };\n IntlMessageFormat.__parse = parse;\n // Default format options used as the prototype of the `formats` provided to the\n // constructor. These are used when constructing the internal Intl.NumberFormat\n // and Intl.DateTimeFormat instances.\n IntlMessageFormat.formats = {\n number: {\n integer: {\n maximumFractionDigits: 0,\n },\n currency: {\n style: 'currency',\n },\n percent: {\n style: 'percent',\n },\n },\n date: {\n short: {\n month: 'numeric',\n day: 'numeric',\n year: '2-digit',\n },\n medium: {\n month: 'short',\n day: 'numeric',\n year: 'numeric',\n },\n long: {\n month: 'long',\n day: 'numeric',\n year: 'numeric',\n },\n full: {\n weekday: 'long',\n month: 'long',\n day: 'numeric',\n year: 'numeric',\n },\n },\n time: {\n short: {\n hour: 'numeric',\n minute: 'numeric',\n },\n medium: {\n hour: 'numeric',\n minute: 'numeric',\n second: 'numeric',\n },\n long: {\n hour: 'numeric',\n minute: 'numeric',\n second: 'numeric',\n timeZoneName: 'short',\n },\n full: {\n hour: 'numeric',\n minute: 'numeric',\n second: 'numeric',\n timeZoneName: 'short',\n },\n },\n };\n return IntlMessageFormat;\n}());\nexport { IntlMessageFormat };\n","import { __extends } from \"tslib\";\nexport var IntlErrorCode;\n(function (IntlErrorCode) {\n IntlErrorCode[\"FORMAT_ERROR\"] = \"FORMAT_ERROR\";\n IntlErrorCode[\"UNSUPPORTED_FORMATTER\"] = \"UNSUPPORTED_FORMATTER\";\n IntlErrorCode[\"INVALID_CONFIG\"] = \"INVALID_CONFIG\";\n IntlErrorCode[\"MISSING_DATA\"] = \"MISSING_DATA\";\n IntlErrorCode[\"MISSING_TRANSLATION\"] = \"MISSING_TRANSLATION\";\n})(IntlErrorCode || (IntlErrorCode = {}));\nvar IntlError = /** @class */ (function (_super) {\n __extends(IntlError, _super);\n function IntlError(code, message, exception) {\n var _this = this;\n var err = exception\n ? exception instanceof Error\n ? exception\n : new Error(String(exception))\n : undefined;\n _this = _super.call(this, \"[@formatjs/intl Error \".concat(code, \"] \").concat(message, \"\\n\").concat(err ? \"\\n\".concat(err.message, \"\\n\").concat(err.stack) : '')) || this;\n _this.code = code;\n // @ts-ignore just so we don't need to declare dep on @types/node\n if (typeof Error.captureStackTrace === 'function') {\n // @ts-ignore just so we don't need to declare dep on @types/node\n Error.captureStackTrace(_this, IntlError);\n }\n return _this;\n }\n return IntlError;\n}(Error));\nexport { IntlError };\nvar UnsupportedFormatterError = /** @class */ (function (_super) {\n __extends(UnsupportedFormatterError, _super);\n function UnsupportedFormatterError(message, exception) {\n return _super.call(this, IntlErrorCode.UNSUPPORTED_FORMATTER, message, exception) || this;\n }\n return UnsupportedFormatterError;\n}(IntlError));\nexport { UnsupportedFormatterError };\nvar InvalidConfigError = /** @class */ (function (_super) {\n __extends(InvalidConfigError, _super);\n function InvalidConfigError(message, exception) {\n return _super.call(this, IntlErrorCode.INVALID_CONFIG, message, exception) || this;\n }\n return InvalidConfigError;\n}(IntlError));\nexport { InvalidConfigError };\nvar MissingDataError = /** @class */ (function (_super) {\n __extends(MissingDataError, _super);\n function MissingDataError(message, exception) {\n return _super.call(this, IntlErrorCode.MISSING_DATA, message, exception) || this;\n }\n return MissingDataError;\n}(IntlError));\nexport { MissingDataError };\nvar IntlFormatError = /** @class */ (function (_super) {\n __extends(IntlFormatError, _super);\n function IntlFormatError(message, locale, exception) {\n var _this = _super.call(this, IntlErrorCode.FORMAT_ERROR, \"\".concat(message, \"\\nLocale: \").concat(locale, \"\\n\"), exception) || this;\n _this.locale = locale;\n return _this;\n }\n return IntlFormatError;\n}(IntlError));\nexport { IntlFormatError };\nvar MessageFormatError = /** @class */ (function (_super) {\n __extends(MessageFormatError, _super);\n function MessageFormatError(message, locale, descriptor, exception) {\n var _this = _super.call(this, \"\".concat(message, \"\\nMessageID: \").concat(descriptor === null || descriptor === void 0 ? void 0 : descriptor.id, \"\\nDefault Message: \").concat(descriptor === null || descriptor === void 0 ? void 0 : descriptor.defaultMessage, \"\\nDescription: \").concat(descriptor === null || descriptor === void 0 ? void 0 : descriptor.description, \"\\n\"), locale, exception) || this;\n _this.descriptor = descriptor;\n _this.locale = locale;\n return _this;\n }\n return MessageFormatError;\n}(IntlFormatError));\nexport { MessageFormatError };\nvar MissingTranslationError = /** @class */ (function (_super) {\n __extends(MissingTranslationError, _super);\n function MissingTranslationError(descriptor, locale) {\n var _this = _super.call(this, IntlErrorCode.MISSING_TRANSLATION, \"Missing message: \\\"\".concat(descriptor.id, \"\\\" for locale \\\"\").concat(locale, \"\\\", using \").concat(descriptor.defaultMessage\n ? \"default message (\".concat(typeof descriptor.defaultMessage === 'string'\n ? descriptor.defaultMessage\n : descriptor.defaultMessage\n .map(function (e) { var _a; return (_a = e.value) !== null && _a !== void 0 ? _a : JSON.stringify(e); })\n .join(), \")\")\n : 'id', \" as fallback.\")) || this;\n _this.descriptor = descriptor;\n return _this;\n }\n return MissingTranslationError;\n}(IntlError));\nexport { MissingTranslationError };\n","import { __assign, __spreadArray } from \"tslib\";\nimport { IntlMessageFormat } from 'intl-messageformat';\nimport { memoize, strategies } from '@formatjs/fast-memoize';\nimport { UnsupportedFormatterError } from './error';\nexport function filterProps(props, allowlist, defaults) {\n if (defaults === void 0) { defaults = {}; }\n return allowlist.reduce(function (filtered, name) {\n if (name in props) {\n filtered[name] = props[name];\n }\n else if (name in defaults) {\n filtered[name] = defaults[name];\n }\n return filtered;\n }, {});\n}\nvar defaultErrorHandler = function (error) {\n // @ts-ignore just so we don't need to declare dep on @types/node\n if (process.env.NODE_ENV !== 'production') {\n console.error(error);\n }\n};\nvar defaultWarnHandler = function (warning) {\n // @ts-ignore just so we don't need to declare dep on @types/node\n if (process.env.NODE_ENV !== 'production') {\n console.warn(warning);\n }\n};\nexport var DEFAULT_INTL_CONFIG = {\n formats: {},\n messages: {},\n timeZone: undefined,\n defaultLocale: 'en',\n defaultFormats: {},\n fallbackOnEmptyString: true,\n onError: defaultErrorHandler,\n onWarn: defaultWarnHandler,\n};\nexport function createIntlCache() {\n return {\n dateTime: {},\n number: {},\n message: {},\n relativeTime: {},\n pluralRules: {},\n list: {},\n displayNames: {},\n };\n}\nfunction createFastMemoizeCache(store) {\n return {\n create: function () {\n return {\n get: function (key) {\n return store[key];\n },\n set: function (key, value) {\n store[key] = value;\n },\n };\n },\n };\n}\n/**\n * Create intl formatters and populate cache\n * @param cache explicit cache to prevent leaking memory\n */\nexport function createFormatters(cache) {\n if (cache === void 0) { cache = createIntlCache(); }\n var RelativeTimeFormat = Intl.RelativeTimeFormat;\n var ListFormat = Intl.ListFormat;\n var DisplayNames = Intl.DisplayNames;\n var getDateTimeFormat = memoize(function () {\n var _a;\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n return new ((_a = Intl.DateTimeFormat).bind.apply(_a, __spreadArray([void 0], args, false)))();\n }, {\n cache: createFastMemoizeCache(cache.dateTime),\n strategy: strategies.variadic,\n });\n var getNumberFormat = memoize(function () {\n var _a;\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n return new ((_a = Intl.NumberFormat).bind.apply(_a, __spreadArray([void 0], args, false)))();\n }, {\n cache: createFastMemoizeCache(cache.number),\n strategy: strategies.variadic,\n });\n var getPluralRules = memoize(function () {\n var _a;\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n return new ((_a = Intl.PluralRules).bind.apply(_a, __spreadArray([void 0], args, false)))();\n }, {\n cache: createFastMemoizeCache(cache.pluralRules),\n strategy: strategies.variadic,\n });\n return {\n getDateTimeFormat: getDateTimeFormat,\n getNumberFormat: getNumberFormat,\n getMessageFormat: memoize(function (message, locales, overrideFormats, opts) {\n return new IntlMessageFormat(message, locales, overrideFormats, __assign({ formatters: {\n getNumberFormat: getNumberFormat,\n getDateTimeFormat: getDateTimeFormat,\n getPluralRules: getPluralRules,\n } }, (opts || {})));\n }, {\n cache: createFastMemoizeCache(cache.message),\n strategy: strategies.variadic,\n }),\n getRelativeTimeFormat: memoize(function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n return new (RelativeTimeFormat.bind.apply(RelativeTimeFormat, __spreadArray([void 0], args, false)))();\n }, {\n cache: createFastMemoizeCache(cache.relativeTime),\n strategy: strategies.variadic,\n }),\n getPluralRules: getPluralRules,\n getListFormat: memoize(function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n return new (ListFormat.bind.apply(ListFormat, __spreadArray([void 0], args, false)))();\n }, {\n cache: createFastMemoizeCache(cache.list),\n strategy: strategies.variadic,\n }),\n getDisplayNames: memoize(function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n return new (DisplayNames.bind.apply(DisplayNames, __spreadArray([void 0], args, false)))();\n }, {\n cache: createFastMemoizeCache(cache.displayNames),\n strategy: strategies.variadic,\n }),\n };\n}\nexport function getNamedFormat(formats, type, name, onError) {\n var formatType = formats && formats[type];\n var format;\n if (formatType) {\n format = formatType[name];\n }\n if (format) {\n return format;\n }\n onError(new UnsupportedFormatterError(\"No \".concat(type, \" format named: \").concat(name)));\n}\n","/**\n * Cannot do Math.log(x) / Math.log(10) bc if IEEE floating point issue\n * @param x number\n */\nexport function getMagnitude(x) {\n // Cannot count string length via Number.toString because it may use scientific notation\n // for very small or very large numbers.\n return Math.floor(Math.log(x) * Math.LOG10E);\n}\nexport function repeat(s, times) {\n if (typeof s.repeat === 'function') {\n return s.repeat(times);\n }\n var arr = new Array(times);\n for (var i = 0; i < arr.length; i++) {\n arr[i] = s;\n }\n return arr.join('');\n}\nexport function setInternalSlot(map, pl, field, value) {\n if (!map.get(pl)) {\n map.set(pl, Object.create(null));\n }\n var slots = map.get(pl);\n slots[field] = value;\n}\nexport function setMultiInternalSlots(map, pl, props) {\n for (var _i = 0, _a = Object.keys(props); _i < _a.length; _i++) {\n var k = _a[_i];\n setInternalSlot(map, pl, k, props[k]);\n }\n}\nexport function getInternalSlot(map, pl, field) {\n return getMultiInternalSlots(map, pl, field)[field];\n}\nexport function getMultiInternalSlots(map, pl) {\n var fields = [];\n for (var _i = 2; _i < arguments.length; _i++) {\n fields[_i - 2] = arguments[_i];\n }\n var slots = map.get(pl);\n if (!slots) {\n throw new TypeError(\"\".concat(pl, \" InternalSlot has not been initialized\"));\n }\n return fields.reduce(function (all, f) {\n all[f] = slots[f];\n return all;\n }, Object.create(null));\n}\nexport function isLiteralPart(patternPart) {\n return patternPart.type === 'literal';\n}\n/*\n 17 ECMAScript Standard Built-in Objects:\n Every built-in Function object, including constructors, that is not\n identified as an anonymous function has a name property whose value\n is a String.\n\n Unless otherwise specified, the name property of a built-in Function\n object, if it exists, has the attributes { [[Writable]]: false,\n [[Enumerable]]: false, [[Configurable]]: true }.\n*/\nexport function defineProperty(target, name, _a) {\n var value = _a.value;\n Object.defineProperty(target, name, {\n configurable: true,\n enumerable: false,\n writable: true,\n value: value,\n });\n}\nexport var UNICODE_EXTENSION_SEQUENCE_REGEX = /-u(?:-[0-9a-z]{2,8})+/gi;\nexport function invariant(condition, message, Err) {\n if (Err === void 0) { Err = Error; }\n if (!condition) {\n throw new Err(message);\n }\n}\n","import { __assign } from \"tslib\";\nimport * as React from 'react';\nimport { invariant } from '@formatjs/ecma402-abstract';\nimport { DEFAULT_INTL_CONFIG as CORE_DEFAULT_INTL_CONFIG } from '@formatjs/intl';\nexport function invariantIntlContext(intl) {\n invariant(intl, '[React Intl] Could not find required `intl` object. ' +\n ' needs to exist in the component ancestry.');\n}\nexport var DEFAULT_INTL_CONFIG = __assign(__assign({}, CORE_DEFAULT_INTL_CONFIG), { textComponent: React.Fragment });\n/**\n * Takes a `formatXMLElementFn`, and composes it in function, which passes\n * argument `parts` through, assigning unique key to each part, to prevent\n * \"Each child in a list should have a unique \"key\"\" React error.\n * @param formatXMLElementFn\n */\nexport function assignUniqueKeysToParts(formatXMLElementFn) {\n return function (parts) {\n // eslint-disable-next-line prefer-rest-params\n return formatXMLElementFn(React.Children.toArray(parts));\n };\n}\nexport function shallowEqual(objA, objB) {\n if (objA === objB) {\n return true;\n }\n if (!objA || !objB) {\n return false;\n }\n var aKeys = Object.keys(objA);\n var bKeys = Object.keys(objB);\n var len = aKeys.length;\n if (bKeys.length !== len) {\n return false;\n }\n for (var i = 0; i < len; i++) {\n var key = aKeys[i];\n if (objA[key] !== objB[key] ||\n !Object.prototype.hasOwnProperty.call(objB, key)) {\n return false;\n }\n }\n return true;\n}\n","import { __assign } from \"tslib\";\nimport * as React from 'react';\nimport hoistNonReactStatics from 'hoist-non-react-statics';\nimport { invariantIntlContext } from '../utils';\nfunction getDisplayName(Component) {\n return Component.displayName || Component.name || 'Component';\n}\n// This is primarily dealing with packaging systems where multiple copies of react-intl\n// might exist\nvar IntlContext = typeof window !== 'undefined' && !window.__REACT_INTL_BYPASS_GLOBAL_CONTEXT__\n ? window.__REACT_INTL_CONTEXT__ ||\n (window.__REACT_INTL_CONTEXT__ = React.createContext(null))\n : React.createContext(null);\nvar IntlConsumer = IntlContext.Consumer, IntlProvider = IntlContext.Provider;\nexport var Provider = IntlProvider;\nexport var Context = IntlContext;\nexport default function injectIntl(WrappedComponent, options) {\n var _a = options || {}, _b = _a.intlPropName, intlPropName = _b === void 0 ? 'intl' : _b, _c = _a.forwardRef, forwardRef = _c === void 0 ? false : _c, _d = _a.enforceContext, enforceContext = _d === void 0 ? true : _d;\n var WithIntl = function (props) { return (React.createElement(IntlConsumer, null, function (intl) {\n var _a;\n if (enforceContext) {\n invariantIntlContext(intl);\n }\n var intlProp = (_a = {}, _a[intlPropName] = intl, _a);\n return (React.createElement(WrappedComponent, __assign({}, props, intlProp, { ref: forwardRef ? props.forwardedRef : null })));\n })); };\n WithIntl.displayName = \"injectIntl(\".concat(getDisplayName(WrappedComponent), \")\");\n WithIntl.WrappedComponent = WrappedComponent;\n if (forwardRef) {\n return hoistNonReactStatics(React.forwardRef(function (props, ref) { return (React.createElement(WithIntl, __assign({}, props, { forwardedRef: ref }))); }), WrappedComponent);\n }\n return hoistNonReactStatics(WithIntl, WrappedComponent);\n}\n","import { __assign } from \"tslib\";\nimport { invariant } from '@formatjs/ecma402-abstract';\nimport { IntlMessageFormat, } from 'intl-messageformat';\nimport { MissingTranslationError, MessageFormatError } from './error';\nimport { TYPE } from '@formatjs/icu-messageformat-parser';\nfunction setTimeZoneInOptions(opts, timeZone) {\n return Object.keys(opts).reduce(function (all, k) {\n all[k] = __assign({ timeZone: timeZone }, opts[k]);\n return all;\n }, {});\n}\nfunction deepMergeOptions(opts1, opts2) {\n var keys = Object.keys(__assign(__assign({}, opts1), opts2));\n return keys.reduce(function (all, k) {\n all[k] = __assign(__assign({}, (opts1[k] || {})), (opts2[k] || {}));\n return all;\n }, {});\n}\nfunction deepMergeFormatsAndSetTimeZone(f1, timeZone) {\n if (!timeZone) {\n return f1;\n }\n var mfFormats = IntlMessageFormat.formats;\n return __assign(__assign(__assign({}, mfFormats), f1), { date: deepMergeOptions(setTimeZoneInOptions(mfFormats.date, timeZone), setTimeZoneInOptions(f1.date || {}, timeZone)), time: deepMergeOptions(setTimeZoneInOptions(mfFormats.time, timeZone), setTimeZoneInOptions(f1.time || {}, timeZone)) });\n}\nexport var formatMessage = function (_a, state, messageDescriptor, values, opts) {\n var locale = _a.locale, formats = _a.formats, messages = _a.messages, defaultLocale = _a.defaultLocale, defaultFormats = _a.defaultFormats, fallbackOnEmptyString = _a.fallbackOnEmptyString, onError = _a.onError, timeZone = _a.timeZone, defaultRichTextElements = _a.defaultRichTextElements;\n if (messageDescriptor === void 0) { messageDescriptor = { id: '' }; }\n var msgId = messageDescriptor.id, defaultMessage = messageDescriptor.defaultMessage;\n // `id` is a required field of a Message Descriptor.\n invariant(!!msgId, \"[@formatjs/intl] An `id` must be provided to format a message. You can either:\\n1. Configure your build toolchain with [babel-plugin-formatjs](https://formatjs.io/docs/tooling/babel-plugin)\\nor [@formatjs/ts-transformer](https://formatjs.io/docs/tooling/ts-transformer) OR\\n2. Configure your `eslint` config to include [eslint-plugin-formatjs](https://formatjs.io/docs/tooling/linter#enforce-id)\\nto autofix this issue\");\n var id = String(msgId);\n var message = \n // In case messages is Object.create(null)\n // e.g import('foo.json') from webpack)\n // See https://github.com/formatjs/formatjs/issues/1914\n messages &&\n Object.prototype.hasOwnProperty.call(messages, id) &&\n messages[id];\n // IMPORTANT: Hot path if `message` is AST with a single literal node\n if (Array.isArray(message) &&\n message.length === 1 &&\n message[0].type === TYPE.literal) {\n return message[0].value;\n }\n // IMPORTANT: Hot path straight lookup for performance\n if (!values &&\n message &&\n typeof message === 'string' &&\n !defaultRichTextElements) {\n return message.replace(/'\\{(.*?)\\}'/gi, \"{$1}\");\n }\n values = __assign(__assign({}, defaultRichTextElements), (values || {}));\n formats = deepMergeFormatsAndSetTimeZone(formats, timeZone);\n defaultFormats = deepMergeFormatsAndSetTimeZone(defaultFormats, timeZone);\n if (!message) {\n if (fallbackOnEmptyString === false && message === '') {\n return message;\n }\n if (!defaultMessage ||\n (locale && locale.toLowerCase() !== defaultLocale.toLowerCase())) {\n // This prevents warnings from littering the console in development\n // when no `messages` are passed into the for the\n // default locale.\n onError(new MissingTranslationError(messageDescriptor, locale));\n }\n if (defaultMessage) {\n try {\n var formatter = state.getMessageFormat(defaultMessage, defaultLocale, defaultFormats, opts);\n return formatter.format(values);\n }\n catch (e) {\n onError(new MessageFormatError(\"Error formatting default message for: \\\"\".concat(id, \"\\\", rendering default message verbatim\"), locale, messageDescriptor, e));\n return typeof defaultMessage === 'string' ? defaultMessage : id;\n }\n }\n return id;\n }\n // We have the translated message\n try {\n var formatter = state.getMessageFormat(message, locale, formats, __assign({ formatters: state }, (opts || {})));\n return formatter.format(values);\n }\n catch (e) {\n onError(new MessageFormatError(\"Error formatting message: \\\"\".concat(id, \"\\\", using \").concat(defaultMessage ? 'default message' : 'id', \" as fallback.\"), locale, messageDescriptor, e));\n }\n if (defaultMessage) {\n try {\n var formatter = state.getMessageFormat(defaultMessage, defaultLocale, defaultFormats, opts);\n return formatter.format(values);\n }\n catch (e) {\n onError(new MessageFormatError(\"Error formatting the default message for: \\\"\".concat(id, \"\\\", rendering message verbatim\"), locale, messageDescriptor, e));\n }\n }\n if (typeof message === 'string') {\n return message;\n }\n if (typeof defaultMessage === 'string') {\n return defaultMessage;\n }\n return id;\n};\n","import { IntlFormatError } from './error';\nimport { filterProps, getNamedFormat } from './utils';\nvar NUMBER_FORMAT_OPTIONS = [\n 'style',\n 'currency',\n 'unit',\n 'unitDisplay',\n 'useGrouping',\n 'minimumIntegerDigits',\n 'minimumFractionDigits',\n 'maximumFractionDigits',\n 'minimumSignificantDigits',\n 'maximumSignificantDigits',\n // ES2020 NumberFormat\n 'compactDisplay',\n 'currencyDisplay',\n 'currencySign',\n 'notation',\n 'signDisplay',\n 'unit',\n 'unitDisplay',\n 'numberingSystem',\n // ES2023 NumberFormat\n 'trailingZeroDisplay',\n 'roundingPriority',\n 'roundingIncrement',\n 'roundingMode',\n];\nexport function getFormatter(_a, getNumberFormat, options) {\n var locale = _a.locale, formats = _a.formats, onError = _a.onError;\n if (options === void 0) { options = {}; }\n var format = options.format;\n var defaults = ((format &&\n getNamedFormat(formats, 'number', format, onError)) ||\n {});\n var filteredOptions = filterProps(options, NUMBER_FORMAT_OPTIONS, defaults);\n return getNumberFormat(locale, filteredOptions);\n}\nexport function formatNumber(config, getNumberFormat, value, options) {\n if (options === void 0) { options = {}; }\n try {\n return getFormatter(config, getNumberFormat, options).format(value);\n }\n catch (e) {\n config.onError(new IntlFormatError('Error formatting number.', config.locale, e));\n }\n return String(value);\n}\nexport function formatNumberToParts(config, getNumberFormat, value, options) {\n if (options === void 0) { options = {}; }\n try {\n return getFormatter(config, getNumberFormat, options).formatToParts(value);\n }\n catch (e) {\n config.onError(new IntlFormatError('Error formatting number.', config.locale, e));\n }\n return [];\n}\n","import { getNamedFormat, filterProps } from './utils';\nimport { FormatError, ErrorCode } from 'intl-messageformat';\nimport { IntlFormatError } from './error';\nvar RELATIVE_TIME_FORMAT_OPTIONS = ['numeric', 'style'];\nfunction getFormatter(_a, getRelativeTimeFormat, options) {\n var locale = _a.locale, formats = _a.formats, onError = _a.onError;\n if (options === void 0) { options = {}; }\n var format = options.format;\n var defaults = (!!format && getNamedFormat(formats, 'relative', format, onError)) || {};\n var filteredOptions = filterProps(options, RELATIVE_TIME_FORMAT_OPTIONS, defaults);\n return getRelativeTimeFormat(locale, filteredOptions);\n}\nexport function formatRelativeTime(config, getRelativeTimeFormat, value, unit, options) {\n if (options === void 0) { options = {}; }\n if (!unit) {\n unit = 'second';\n }\n var RelativeTimeFormat = Intl.RelativeTimeFormat;\n if (!RelativeTimeFormat) {\n config.onError(new FormatError(\"Intl.RelativeTimeFormat is not available in this environment.\\nTry polyfilling it using \\\"@formatjs/intl-relativetimeformat\\\"\\n\", ErrorCode.MISSING_INTL_API));\n }\n try {\n return getFormatter(config, getRelativeTimeFormat, options).format(value, unit);\n }\n catch (e) {\n config.onError(new IntlFormatError('Error formatting relative time.', config.locale, e));\n }\n return String(value);\n}\n","import { __assign } from \"tslib\";\nimport { filterProps, getNamedFormat } from './utils';\nimport { IntlFormatError } from './error';\nvar DATE_TIME_FORMAT_OPTIONS = [\n 'formatMatcher',\n 'timeZone',\n 'hour12',\n 'weekday',\n 'era',\n 'year',\n 'month',\n 'day',\n 'hour',\n 'minute',\n 'second',\n 'timeZoneName',\n 'hourCycle',\n 'dateStyle',\n 'timeStyle',\n 'calendar',\n // 'dayPeriod',\n 'numberingSystem',\n 'fractionalSecondDigits',\n];\nexport function getFormatter(_a, type, getDateTimeFormat, options) {\n var locale = _a.locale, formats = _a.formats, onError = _a.onError, timeZone = _a.timeZone;\n if (options === void 0) { options = {}; }\n var format = options.format;\n var defaults = __assign(__assign({}, (timeZone && { timeZone: timeZone })), (format && getNamedFormat(formats, type, format, onError)));\n var filteredOptions = filterProps(options, DATE_TIME_FORMAT_OPTIONS, defaults);\n if (type === 'time' &&\n !filteredOptions.hour &&\n !filteredOptions.minute &&\n !filteredOptions.second &&\n !filteredOptions.timeStyle &&\n !filteredOptions.dateStyle) {\n // Add default formatting options if hour, minute, or second isn't defined.\n filteredOptions = __assign(__assign({}, filteredOptions), { hour: 'numeric', minute: 'numeric' });\n }\n return getDateTimeFormat(locale, filteredOptions);\n}\nexport function formatDate(config, getDateTimeFormat) {\n var _a = [];\n for (var _i = 2; _i < arguments.length; _i++) {\n _a[_i - 2] = arguments[_i];\n }\n var value = _a[0], _b = _a[1], options = _b === void 0 ? {} : _b;\n var date = typeof value === 'string' ? new Date(value || 0) : value;\n try {\n return getFormatter(config, 'date', getDateTimeFormat, options).format(date);\n }\n catch (e) {\n config.onError(new IntlFormatError('Error formatting date.', config.locale, e));\n }\n return String(date);\n}\nexport function formatTime(config, getDateTimeFormat) {\n var _a = [];\n for (var _i = 2; _i < arguments.length; _i++) {\n _a[_i - 2] = arguments[_i];\n }\n var value = _a[0], _b = _a[1], options = _b === void 0 ? {} : _b;\n var date = typeof value === 'string' ? new Date(value || 0) : value;\n try {\n return getFormatter(config, 'time', getDateTimeFormat, options).format(date);\n }\n catch (e) {\n config.onError(new IntlFormatError('Error formatting time.', config.locale, e));\n }\n return String(date);\n}\nexport function formatDateTimeRange(config, getDateTimeFormat) {\n var _a = [];\n for (var _i = 2; _i < arguments.length; _i++) {\n _a[_i - 2] = arguments[_i];\n }\n var from = _a[0], to = _a[1], _b = _a[2], options = _b === void 0 ? {} : _b;\n var timeZone = config.timeZone, locale = config.locale, onError = config.onError;\n var filteredOptions = filterProps(options, DATE_TIME_FORMAT_OPTIONS, timeZone ? { timeZone: timeZone } : {});\n try {\n return getDateTimeFormat(locale, filteredOptions).formatRange(from, to);\n }\n catch (e) {\n onError(new IntlFormatError('Error formatting date time range.', config.locale, e));\n }\n return String(from);\n}\nexport function formatDateToParts(config, getDateTimeFormat) {\n var _a = [];\n for (var _i = 2; _i < arguments.length; _i++) {\n _a[_i - 2] = arguments[_i];\n }\n var value = _a[0], _b = _a[1], options = _b === void 0 ? {} : _b;\n var date = typeof value === 'string' ? new Date(value || 0) : value;\n try {\n return getFormatter(config, 'date', getDateTimeFormat, options).formatToParts(date); // TODO: remove this when https://github.com/microsoft/TypeScript/pull/50402 is merged\n }\n catch (e) {\n config.onError(new IntlFormatError('Error formatting date.', config.locale, e));\n }\n return [];\n}\nexport function formatTimeToParts(config, getDateTimeFormat) {\n var _a = [];\n for (var _i = 2; _i < arguments.length; _i++) {\n _a[_i - 2] = arguments[_i];\n }\n var value = _a[0], _b = _a[1], options = _b === void 0 ? {} : _b;\n var date = typeof value === 'string' ? new Date(value || 0) : value;\n try {\n return getFormatter(config, 'time', getDateTimeFormat, options).formatToParts(date); // TODO: remove this when https://github.com/microsoft/TypeScript/pull/50402 is merged\n }\n catch (e) {\n config.onError(new IntlFormatError('Error formatting time.', config.locale, e));\n }\n return [];\n}\n","import { filterProps } from './utils';\nimport { IntlFormatError } from './error';\nimport { ErrorCode, FormatError } from 'intl-messageformat';\nvar PLURAL_FORMAT_OPTIONS = ['type'];\nexport function formatPlural(_a, getPluralRules, value, options) {\n var locale = _a.locale, onError = _a.onError;\n if (options === void 0) { options = {}; }\n if (!Intl.PluralRules) {\n onError(new FormatError(\"Intl.PluralRules is not available in this environment.\\nTry polyfilling it using \\\"@formatjs/intl-pluralrules\\\"\\n\", ErrorCode.MISSING_INTL_API));\n }\n var filteredOptions = filterProps(options, PLURAL_FORMAT_OPTIONS);\n try {\n return getPluralRules(locale, filteredOptions).select(value);\n }\n catch (e) {\n onError(new IntlFormatError('Error formatting plural.', locale, e));\n }\n return 'other';\n}\n","import { __assign } from \"tslib\";\nimport { filterProps } from './utils';\nimport { FormatError, ErrorCode } from 'intl-messageformat';\nimport { IntlFormatError } from './error';\nvar LIST_FORMAT_OPTIONS = [\n 'type',\n 'style',\n];\nvar now = Date.now();\nfunction generateToken(i) {\n return \"\".concat(now, \"_\").concat(i, \"_\").concat(now);\n}\nexport function formatList(opts, getListFormat, values, options) {\n if (options === void 0) { options = {}; }\n var results = formatListToParts(opts, getListFormat, values, options).reduce(function (all, el) {\n var val = el.value;\n if (typeof val !== 'string') {\n all.push(val);\n }\n else if (typeof all[all.length - 1] === 'string') {\n all[all.length - 1] += val;\n }\n else {\n all.push(val);\n }\n return all;\n }, []);\n return results.length === 1 ? results[0] : results.length === 0 ? '' : results;\n}\nexport function formatListToParts(_a, getListFormat, values, options) {\n var locale = _a.locale, onError = _a.onError;\n if (options === void 0) { options = {}; }\n var ListFormat = Intl.ListFormat;\n if (!ListFormat) {\n onError(new FormatError(\"Intl.ListFormat is not available in this environment.\\nTry polyfilling it using \\\"@formatjs/intl-listformat\\\"\\n\", ErrorCode.MISSING_INTL_API));\n }\n var filteredOptions = filterProps(options, LIST_FORMAT_OPTIONS);\n try {\n var richValues_1 = {};\n var serializedValues = values.map(function (v, i) {\n if (typeof v === 'object') {\n var id = generateToken(i);\n richValues_1[id] = v;\n return id;\n }\n return String(v);\n });\n return getListFormat(locale, filteredOptions)\n .formatToParts(serializedValues)\n .map(function (part) {\n return part.type === 'literal'\n ? part\n : __assign(__assign({}, part), { value: richValues_1[part.value] || part.value });\n });\n }\n catch (e) {\n onError(new IntlFormatError('Error formatting list.', locale, e));\n }\n // @ts-ignore\n return values;\n}\n","import { filterProps } from './utils';\nimport { FormatError, ErrorCode } from 'intl-messageformat';\nimport { IntlFormatError } from './error';\nvar DISPLAY_NAMES_OPTONS = [\n 'style',\n 'type',\n 'fallback',\n 'languageDisplay',\n];\nexport function formatDisplayName(_a, getDisplayNames, value, options) {\n var locale = _a.locale, onError = _a.onError;\n var DisplayNames = Intl.DisplayNames;\n if (!DisplayNames) {\n onError(new FormatError(\"Intl.DisplayNames is not available in this environment.\\nTry polyfilling it using \\\"@formatjs/intl-displaynames\\\"\\n\", ErrorCode.MISSING_INTL_API));\n }\n var filteredOptions = filterProps(options, DISPLAY_NAMES_OPTONS);\n try {\n return getDisplayNames(locale, filteredOptions).of(value);\n }\n catch (e) {\n onError(new IntlFormatError('Error formatting display name.', locale, e));\n }\n}\n","import { __assign } from \"tslib\";\nimport { createFormatters, DEFAULT_INTL_CONFIG } from './utils';\nimport { InvalidConfigError, MissingDataError } from './error';\nimport { formatNumber, formatNumberToParts } from './number';\nimport { formatRelativeTime } from './relativeTime';\nimport { formatDate, formatDateToParts, formatTime, formatTimeToParts, formatDateTimeRange, } from './dateTime';\nimport { formatPlural } from './plural';\nimport { formatMessage } from './message';\nimport { formatList, formatListToParts } from './list';\nimport { formatDisplayName } from './displayName';\nfunction messagesContainString(messages) {\n var firstMessage = messages ? messages[Object.keys(messages)[0]] : undefined;\n return typeof firstMessage === 'string';\n}\nfunction verifyConfigMessages(config) {\n if (config.onWarn &&\n config.defaultRichTextElements &&\n messagesContainString(config.messages || {})) {\n config.onWarn(\"[@formatjs/intl] \\\"defaultRichTextElements\\\" was specified but \\\"message\\\" was not pre-compiled. \\nPlease consider using \\\"@formatjs/cli\\\" to pre-compile your messages for performance.\\nFor more details see https://formatjs.io/docs/getting-started/message-distribution\");\n }\n}\n/**\n * Create intl object\n * @param config intl config\n * @param cache cache for formatter instances to prevent memory leak\n */\nexport function createIntl(config, cache) {\n var formatters = createFormatters(cache);\n var resolvedConfig = __assign(__assign({}, DEFAULT_INTL_CONFIG), config);\n var locale = resolvedConfig.locale, defaultLocale = resolvedConfig.defaultLocale, onError = resolvedConfig.onError;\n if (!locale) {\n if (onError) {\n onError(new InvalidConfigError(\"\\\"locale\\\" was not configured, using \\\"\".concat(defaultLocale, \"\\\" as fallback. See https://formatjs.io/docs/react-intl/api#intlshape for more details\")));\n }\n // Since there's no registered locale data for `locale`, this will\n // fallback to the `defaultLocale` to make sure things can render.\n // The `messages` are overridden to the `defaultProps` empty object\n // to maintain referential equality across re-renders. It's assumed\n // each contains a `defaultMessage` prop.\n resolvedConfig.locale = resolvedConfig.defaultLocale || 'en';\n }\n else if (!Intl.NumberFormat.supportedLocalesOf(locale).length && onError) {\n onError(new MissingDataError(\"Missing locale data for locale: \\\"\".concat(locale, \"\\\" in Intl.NumberFormat. Using default locale: \\\"\").concat(defaultLocale, \"\\\" as fallback. See https://formatjs.io/docs/react-intl#runtime-requirements for more details\")));\n }\n else if (!Intl.DateTimeFormat.supportedLocalesOf(locale).length &&\n onError) {\n onError(new MissingDataError(\"Missing locale data for locale: \\\"\".concat(locale, \"\\\" in Intl.DateTimeFormat. Using default locale: \\\"\").concat(defaultLocale, \"\\\" as fallback. See https://formatjs.io/docs/react-intl#runtime-requirements for more details\")));\n }\n verifyConfigMessages(resolvedConfig);\n return __assign(__assign({}, resolvedConfig), { formatters: formatters, formatNumber: formatNumber.bind(null, resolvedConfig, formatters.getNumberFormat), formatNumberToParts: formatNumberToParts.bind(null, resolvedConfig, formatters.getNumberFormat), formatRelativeTime: formatRelativeTime.bind(null, resolvedConfig, formatters.getRelativeTimeFormat), formatDate: formatDate.bind(null, resolvedConfig, formatters.getDateTimeFormat), formatDateToParts: formatDateToParts.bind(null, resolvedConfig, formatters.getDateTimeFormat), formatTime: formatTime.bind(null, resolvedConfig, formatters.getDateTimeFormat), formatDateTimeRange: formatDateTimeRange.bind(null, resolvedConfig, formatters.getDateTimeFormat), formatTimeToParts: formatTimeToParts.bind(null, resolvedConfig, formatters.getDateTimeFormat), formatPlural: formatPlural.bind(null, resolvedConfig, formatters.getPluralRules), \n // @ts-expect-error TODO: will get to this later\n formatMessage: formatMessage.bind(null, resolvedConfig, formatters), \n // @ts-expect-error TODO: will get to this later\n $t: formatMessage.bind(null, resolvedConfig, formatters), formatList: formatList.bind(null, resolvedConfig, formatters.getListFormat), formatListToParts: formatListToParts.bind(null, resolvedConfig, formatters.getListFormat), formatDisplayName: formatDisplayName.bind(null, resolvedConfig, formatters.getDisplayNames) });\n}\n","/*\n * Copyright 2015, Yahoo Inc.\n * Copyrights licensed under the New BSD License.\n * See the accompanying LICENSE file for terms.\n */\nimport { __assign, __rest, __spreadArray } from \"tslib\";\nimport { createIntl as coreCreateIntl, formatMessage as coreFormatMessage, } from '@formatjs/intl';\nimport * as React from 'react';\nimport { DEFAULT_INTL_CONFIG, assignUniqueKeysToParts } from '../utils';\nimport { isFormatXMLElementFn, } from 'intl-messageformat';\nfunction assignUniqueKeysToFormatXMLElementFnArgument(values) {\n if (!values) {\n return values;\n }\n return Object.keys(values).reduce(function (acc, k) {\n var v = values[k];\n acc[k] = isFormatXMLElementFn(v)\n ? assignUniqueKeysToParts(v)\n : v;\n return acc;\n }, {});\n}\nvar formatMessage = function (config, formatters, descriptor, rawValues) {\n var rest = [];\n for (var _i = 4; _i < arguments.length; _i++) {\n rest[_i - 4] = arguments[_i];\n }\n var values = assignUniqueKeysToFormatXMLElementFnArgument(rawValues);\n var chunks = coreFormatMessage.apply(void 0, __spreadArray([config,\n formatters,\n descriptor,\n values], rest, false));\n if (Array.isArray(chunks)) {\n return React.Children.toArray(chunks);\n }\n return chunks;\n};\n/**\n * Create intl object\n * @param config intl config\n * @param cache cache for formatter instances to prevent memory leak\n */\nexport var createIntl = function (_a, cache) {\n var rawDefaultRichTextElements = _a.defaultRichTextElements, config = __rest(_a, [\"defaultRichTextElements\"]);\n var defaultRichTextElements = assignUniqueKeysToFormatXMLElementFnArgument(rawDefaultRichTextElements);\n var coreIntl = coreCreateIntl(__assign(__assign(__assign({}, DEFAULT_INTL_CONFIG), config), { defaultRichTextElements: defaultRichTextElements }), cache);\n var resolvedConfig = {\n locale: coreIntl.locale,\n timeZone: coreIntl.timeZone,\n fallbackOnEmptyString: coreIntl.fallbackOnEmptyString,\n formats: coreIntl.formats,\n defaultLocale: coreIntl.defaultLocale,\n defaultFormats: coreIntl.defaultFormats,\n messages: coreIntl.messages,\n onError: coreIntl.onError,\n defaultRichTextElements: defaultRichTextElements,\n };\n return __assign(__assign({}, coreIntl), { formatMessage: formatMessage.bind(null, resolvedConfig, \n // @ts-expect-error fix this\n coreIntl.formatters), \n // @ts-expect-error fix this\n $t: formatMessage.bind(null, resolvedConfig, coreIntl.formatters) });\n};\n","/*\n * Copyright 2015, Yahoo Inc.\n * Copyrights licensed under the New BSD License.\n * See the accompanying LICENSE file for terms.\n */\nimport { __extends } from \"tslib\";\nimport { createIntlCache } from '@formatjs/intl';\nimport * as React from 'react';\nimport { DEFAULT_INTL_CONFIG, invariantIntlContext, shallowEqual } from '../utils';\nimport { Provider } from './injectIntl';\nimport { createIntl } from './createIntl';\nfunction processIntlConfig(config) {\n return {\n locale: config.locale,\n timeZone: config.timeZone,\n fallbackOnEmptyString: config.fallbackOnEmptyString,\n formats: config.formats,\n textComponent: config.textComponent,\n messages: config.messages,\n defaultLocale: config.defaultLocale,\n defaultFormats: config.defaultFormats,\n onError: config.onError,\n onWarn: config.onWarn,\n wrapRichTextChunksInFragment: config.wrapRichTextChunksInFragment,\n defaultRichTextElements: config.defaultRichTextElements,\n };\n}\nvar IntlProvider = /** @class */ (function (_super) {\n __extends(IntlProvider, _super);\n function IntlProvider() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n _this.cache = createIntlCache();\n _this.state = {\n cache: _this.cache,\n intl: createIntl(processIntlConfig(_this.props), _this.cache),\n prevConfig: processIntlConfig(_this.props),\n };\n return _this;\n }\n IntlProvider.getDerivedStateFromProps = function (props, _a) {\n var prevConfig = _a.prevConfig, cache = _a.cache;\n var config = processIntlConfig(props);\n if (!shallowEqual(prevConfig, config)) {\n return {\n intl: createIntl(config, cache),\n prevConfig: config,\n };\n }\n return null;\n };\n IntlProvider.prototype.render = function () {\n invariantIntlContext(this.state.intl);\n return React.createElement(Provider, { value: this.state.intl }, this.props.children);\n };\n IntlProvider.displayName = 'IntlProvider';\n IntlProvider.defaultProps = DEFAULT_INTL_CONFIG;\n return IntlProvider;\n}(React.PureComponent));\nexport default IntlProvider;\n","export const TAG_PROPERTIES = {\n CHARSET: 'charset',\n CSS_TEXT: 'cssText',\n HREF: 'href',\n HTTPEQUIV: 'http-equiv',\n INNER_HTML: 'innerHTML',\n ITEM_PROP: 'itemprop',\n NAME: 'name',\n PROPERTY: 'property',\n REL: 'rel',\n SRC: 'src',\n};\n\nexport const ATTRIBUTE_NAMES = {\n BODY: 'bodyAttributes',\n HTML: 'htmlAttributes',\n TITLE: 'titleAttributes',\n};\n\nexport const TAG_NAMES = {\n BASE: 'base',\n BODY: 'body',\n HEAD: 'head',\n HTML: 'html',\n LINK: 'link',\n META: 'meta',\n NOSCRIPT: 'noscript',\n SCRIPT: 'script',\n STYLE: 'style',\n TITLE: 'title',\n FRAGMENT: 'Symbol(react.fragment)',\n};\n\nexport const SEO_PRIORITY_TAGS = {\n link: { rel: ['amphtml', 'canonical', 'alternate'] },\n script: { type: ['application/ld+json'] },\n meta: {\n charset: '',\n name: ['robots', 'description'],\n property: [\n 'og:type',\n 'og:title',\n 'og:url',\n 'og:image',\n 'og:image:alt',\n 'og:description',\n 'twitter:url',\n 'twitter:title',\n 'twitter:description',\n 'twitter:image',\n 'twitter:image:alt',\n 'twitter:card',\n 'twitter:site',\n ],\n },\n};\n\nexport const VALID_TAG_NAMES = Object.keys(TAG_NAMES).map(name => TAG_NAMES[name]);\n\nexport const REACT_TAG_MAP = {\n accesskey: 'accessKey',\n charset: 'charSet',\n class: 'className',\n contenteditable: 'contentEditable',\n contextmenu: 'contextMenu',\n 'http-equiv': 'httpEquiv',\n itemprop: 'itemProp',\n tabindex: 'tabIndex',\n};\n\nexport const HTML_TAG_MAP = Object.keys(REACT_TAG_MAP).reduce((obj, key) => {\n obj[REACT_TAG_MAP[key]] = key;\n return obj;\n}, {});\n\nexport const HELMET_ATTRIBUTE = 'data-rh';\n","import { TAG_NAMES, TAG_PROPERTIES, ATTRIBUTE_NAMES } from './constants';\n\nconst HELMET_PROPS = {\n DEFAULT_TITLE: 'defaultTitle',\n DEFER: 'defer',\n ENCODE_SPECIAL_CHARACTERS: 'encodeSpecialCharacters',\n ON_CHANGE_CLIENT_STATE: 'onChangeClientState',\n TITLE_TEMPLATE: 'titleTemplate',\n PRIORITIZE_SEO_TAGS: 'prioritizeSeoTags',\n};\n\nconst getInnermostProperty = (propsList, property) => {\n for (let i = propsList.length - 1; i >= 0; i -= 1) {\n const props = propsList[i];\n\n if (Object.prototype.hasOwnProperty.call(props, property)) {\n return props[property];\n }\n }\n\n return null;\n};\n\nconst getTitleFromPropsList = propsList => {\n let innermostTitle = getInnermostProperty(propsList, TAG_NAMES.TITLE);\n const innermostTemplate = getInnermostProperty(propsList, HELMET_PROPS.TITLE_TEMPLATE);\n if (Array.isArray(innermostTitle)) {\n innermostTitle = innermostTitle.join('');\n }\n if (innermostTemplate && innermostTitle) {\n // use function arg to avoid need to escape $ characters\n return innermostTemplate.replace(/%s/g, () => innermostTitle);\n }\n\n const innermostDefaultTitle = getInnermostProperty(propsList, HELMET_PROPS.DEFAULT_TITLE);\n\n return innermostTitle || innermostDefaultTitle || undefined;\n};\n\nconst getOnChangeClientState = propsList =>\n getInnermostProperty(propsList, HELMET_PROPS.ON_CHANGE_CLIENT_STATE) || (() => {});\n\nconst getAttributesFromPropsList = (tagType, propsList) =>\n propsList\n .filter(props => typeof props[tagType] !== 'undefined')\n .map(props => props[tagType])\n .reduce((tagAttrs, current) => ({ ...tagAttrs, ...current }), {});\n\nconst getBaseTagFromPropsList = (primaryAttributes, propsList) =>\n propsList\n .filter(props => typeof props[TAG_NAMES.BASE] !== 'undefined')\n .map(props => props[TAG_NAMES.BASE])\n .reverse()\n .reduce((innermostBaseTag, tag) => {\n if (!innermostBaseTag.length) {\n const keys = Object.keys(tag);\n\n for (let i = 0; i < keys.length; i += 1) {\n const attributeKey = keys[i];\n const lowerCaseAttributeKey = attributeKey.toLowerCase();\n\n if (\n primaryAttributes.indexOf(lowerCaseAttributeKey) !== -1 &&\n tag[lowerCaseAttributeKey]\n ) {\n return innermostBaseTag.concat(tag);\n }\n }\n }\n\n return innermostBaseTag;\n }, []);\n\n// eslint-disable-next-line no-console\nconst warn = msg => console && typeof console.warn === 'function' && console.warn(msg);\n\nconst getTagsFromPropsList = (tagName, primaryAttributes, propsList) => {\n // Calculate list of tags, giving priority innermost component (end of the propslist)\n const approvedSeenTags = {};\n\n return propsList\n .filter(props => {\n if (Array.isArray(props[tagName])) {\n return true;\n }\n if (typeof props[tagName] !== 'undefined') {\n warn(\n `Helmet: ${tagName} should be of type \"Array\". Instead found type \"${typeof props[\n tagName\n ]}\"`\n );\n }\n return false;\n })\n .map(props => props[tagName])\n .reverse()\n .reduce((approvedTags, instanceTags) => {\n const instanceSeenTags = {};\n\n instanceTags\n .filter(tag => {\n let primaryAttributeKey;\n const keys = Object.keys(tag);\n for (let i = 0; i < keys.length; i += 1) {\n const attributeKey = keys[i];\n const lowerCaseAttributeKey = attributeKey.toLowerCase();\n\n // Special rule with link tags, since rel and href are both primary tags, rel takes priority\n if (\n primaryAttributes.indexOf(lowerCaseAttributeKey) !== -1 &&\n !(\n primaryAttributeKey === TAG_PROPERTIES.REL &&\n tag[primaryAttributeKey].toLowerCase() === 'canonical'\n ) &&\n !(\n lowerCaseAttributeKey === TAG_PROPERTIES.REL &&\n tag[lowerCaseAttributeKey].toLowerCase() === 'stylesheet'\n )\n ) {\n primaryAttributeKey = lowerCaseAttributeKey;\n }\n // Special case for innerHTML which doesn't work lowercased\n if (\n primaryAttributes.indexOf(attributeKey) !== -1 &&\n (attributeKey === TAG_PROPERTIES.INNER_HTML ||\n attributeKey === TAG_PROPERTIES.CSS_TEXT ||\n attributeKey === TAG_PROPERTIES.ITEM_PROP)\n ) {\n primaryAttributeKey = attributeKey;\n }\n }\n\n if (!primaryAttributeKey || !tag[primaryAttributeKey]) {\n return false;\n }\n\n const value = tag[primaryAttributeKey].toLowerCase();\n\n if (!approvedSeenTags[primaryAttributeKey]) {\n approvedSeenTags[primaryAttributeKey] = {};\n }\n\n if (!instanceSeenTags[primaryAttributeKey]) {\n instanceSeenTags[primaryAttributeKey] = {};\n }\n\n if (!approvedSeenTags[primaryAttributeKey][value]) {\n instanceSeenTags[primaryAttributeKey][value] = true;\n return true;\n }\n\n return false;\n })\n .reverse()\n .forEach(tag => approvedTags.push(tag));\n\n // Update seen tags with tags from this instance\n const keys = Object.keys(instanceSeenTags);\n for (let i = 0; i < keys.length; i += 1) {\n const attributeKey = keys[i];\n const tagUnion = {\n ...approvedSeenTags[attributeKey],\n ...instanceSeenTags[attributeKey],\n };\n\n approvedSeenTags[attributeKey] = tagUnion;\n }\n\n return approvedTags;\n }, [])\n .reverse();\n};\n\nconst getAnyTrueFromPropsList = (propsList, checkedTag) => {\n if (Array.isArray(propsList) && propsList.length) {\n for (let index = 0; index < propsList.length; index += 1) {\n const prop = propsList[index];\n if (prop[checkedTag]) {\n return true;\n }\n }\n }\n return false;\n};\n\nconst reducePropsToState = propsList => ({\n baseTag: getBaseTagFromPropsList([TAG_PROPERTIES.HREF], propsList),\n bodyAttributes: getAttributesFromPropsList(ATTRIBUTE_NAMES.BODY, propsList),\n defer: getInnermostProperty(propsList, HELMET_PROPS.DEFER),\n encode: getInnermostProperty(propsList, HELMET_PROPS.ENCODE_SPECIAL_CHARACTERS),\n htmlAttributes: getAttributesFromPropsList(ATTRIBUTE_NAMES.HTML, propsList),\n linkTags: getTagsFromPropsList(\n TAG_NAMES.LINK,\n [TAG_PROPERTIES.REL, TAG_PROPERTIES.HREF],\n propsList\n ),\n metaTags: getTagsFromPropsList(\n TAG_NAMES.META,\n [\n TAG_PROPERTIES.NAME,\n TAG_PROPERTIES.CHARSET,\n TAG_PROPERTIES.HTTPEQUIV,\n TAG_PROPERTIES.PROPERTY,\n TAG_PROPERTIES.ITEM_PROP,\n ],\n propsList\n ),\n noscriptTags: getTagsFromPropsList(TAG_NAMES.NOSCRIPT, [TAG_PROPERTIES.INNER_HTML], propsList),\n onChangeClientState: getOnChangeClientState(propsList),\n scriptTags: getTagsFromPropsList(\n TAG_NAMES.SCRIPT,\n [TAG_PROPERTIES.SRC, TAG_PROPERTIES.INNER_HTML],\n propsList\n ),\n styleTags: getTagsFromPropsList(TAG_NAMES.STYLE, [TAG_PROPERTIES.CSS_TEXT], propsList),\n title: getTitleFromPropsList(propsList),\n titleAttributes: getAttributesFromPropsList(ATTRIBUTE_NAMES.TITLE, propsList),\n prioritizeSeoTags: getAnyTrueFromPropsList(propsList, HELMET_PROPS.PRIORITIZE_SEO_TAGS),\n});\n\nexport const flattenArray = possibleArray =>\n Array.isArray(possibleArray) ? possibleArray.join('') : possibleArray;\n\nexport { reducePropsToState };\n\nconst checkIfPropsMatch = (props, toMatch) => {\n const keys = Object.keys(props);\n for (let i = 0; i < keys.length; i += 1) {\n // e.g. if rel exists in the list of allowed props [amphtml, alternate, etc]\n if (toMatch[keys[i]] && toMatch[keys[i]].includes(props[keys[i]])) {\n return true;\n }\n }\n return false;\n};\n\nexport const prioritizer = (elementsList, propsToMatch) => {\n if (Array.isArray(elementsList)) {\n return elementsList.reduce(\n (acc, elementAttrs) => {\n if (checkIfPropsMatch(elementAttrs, propsToMatch)) {\n acc.priority.push(elementAttrs);\n } else {\n acc.default.push(elementAttrs);\n }\n return acc;\n },\n { priority: [], default: [] }\n );\n }\n return { default: elementsList };\n};\n\nexport const without = (obj, key) => {\n return {\n ...obj,\n [key]: undefined,\n };\n};\n","import React from 'react';\nimport {\n HELMET_ATTRIBUTE,\n TAG_NAMES,\n REACT_TAG_MAP,\n TAG_PROPERTIES,\n ATTRIBUTE_NAMES,\n SEO_PRIORITY_TAGS,\n} from './constants';\nimport { flattenArray, prioritizer } from './utils';\n\nconst SELF_CLOSING_TAGS = [TAG_NAMES.NOSCRIPT, TAG_NAMES.SCRIPT, TAG_NAMES.STYLE];\n\nconst encodeSpecialCharacters = (str, encode = true) => {\n if (encode === false) {\n return String(str);\n }\n\n return String(str)\n .replace(/&/g, '&')\n .replace(//g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''');\n};\n\nconst generateElementAttributesAsString = attributes =>\n Object.keys(attributes).reduce((str, key) => {\n const attr = typeof attributes[key] !== 'undefined' ? `${key}=\"${attributes[key]}\"` : `${key}`;\n return str ? `${str} ${attr}` : attr;\n }, '');\n\nconst generateTitleAsString = (type, title, attributes, encode) => {\n const attributeString = generateElementAttributesAsString(attributes);\n const flattenedTitle = flattenArray(title);\n return attributeString\n ? `<${type} ${HELMET_ATTRIBUTE}=\"true\" ${attributeString}>${encodeSpecialCharacters(\n flattenedTitle,\n encode\n )}${type}>`\n : `<${type} ${HELMET_ATTRIBUTE}=\"true\">${encodeSpecialCharacters(\n flattenedTitle,\n encode\n )}${type}>`;\n};\n\nconst generateTagsAsString = (type, tags, encode) =>\n tags.reduce((str, tag) => {\n const attributeHtml = Object.keys(tag)\n .filter(\n attribute =>\n !(attribute === TAG_PROPERTIES.INNER_HTML || attribute === TAG_PROPERTIES.CSS_TEXT)\n )\n .reduce((string, attribute) => {\n const attr =\n typeof tag[attribute] === 'undefined'\n ? attribute\n : `${attribute}=\"${encodeSpecialCharacters(tag[attribute], encode)}\"`;\n return string ? `${string} ${attr}` : attr;\n }, '');\n\n const tagContent = tag.innerHTML || tag.cssText || '';\n\n const isSelfClosing = SELF_CLOSING_TAGS.indexOf(type) === -1;\n\n return `${str}<${type} ${HELMET_ATTRIBUTE}=\"true\" ${attributeHtml}${\n isSelfClosing ? `/>` : `>${tagContent}${type}>`\n }`;\n }, '');\n\nconst convertElementAttributesToReactProps = (attributes, initProps = {}) =>\n Object.keys(attributes).reduce((obj, key) => {\n obj[REACT_TAG_MAP[key] || key] = attributes[key];\n return obj;\n }, initProps);\n\nconst generateTitleAsReactComponent = (type, title, attributes) => {\n // assigning into an array to define toString function on it\n const initProps = {\n key: title,\n [HELMET_ATTRIBUTE]: true,\n };\n const props = convertElementAttributesToReactProps(attributes, initProps);\n\n return [React.createElement(TAG_NAMES.TITLE, props, title)];\n};\n\nconst generateTagsAsReactComponent = (type, tags) =>\n tags.map((tag, i) => {\n const mappedTag = {\n key: i,\n [HELMET_ATTRIBUTE]: true,\n };\n\n Object.keys(tag).forEach(attribute => {\n const mappedAttribute = REACT_TAG_MAP[attribute] || attribute;\n\n if (\n mappedAttribute === TAG_PROPERTIES.INNER_HTML ||\n mappedAttribute === TAG_PROPERTIES.CSS_TEXT\n ) {\n const content = tag.innerHTML || tag.cssText;\n mappedTag.dangerouslySetInnerHTML = { __html: content };\n } else {\n mappedTag[mappedAttribute] = tag[attribute];\n }\n });\n\n return React.createElement(type, mappedTag);\n });\n\nconst getMethodsForTag = (type, tags, encode) => {\n switch (type) {\n case TAG_NAMES.TITLE:\n return {\n toComponent: () =>\n generateTitleAsReactComponent(type, tags.title, tags.titleAttributes, encode),\n toString: () => generateTitleAsString(type, tags.title, tags.titleAttributes, encode),\n };\n case ATTRIBUTE_NAMES.BODY:\n case ATTRIBUTE_NAMES.HTML:\n return {\n toComponent: () => convertElementAttributesToReactProps(tags),\n toString: () => generateElementAttributesAsString(tags),\n };\n default:\n return {\n toComponent: () => generateTagsAsReactComponent(type, tags),\n toString: () => generateTagsAsString(type, tags, encode),\n };\n }\n};\n\nconst getPriorityMethods = ({ metaTags, linkTags, scriptTags, encode }) => {\n const meta = prioritizer(metaTags, SEO_PRIORITY_TAGS.meta);\n const link = prioritizer(linkTags, SEO_PRIORITY_TAGS.link);\n const script = prioritizer(scriptTags, SEO_PRIORITY_TAGS.script);\n\n // need to have toComponent() and toString()\n const priorityMethods = {\n toComponent: () => [\n ...generateTagsAsReactComponent(TAG_NAMES.META, meta.priority),\n ...generateTagsAsReactComponent(TAG_NAMES.LINK, link.priority),\n ...generateTagsAsReactComponent(TAG_NAMES.SCRIPT, script.priority),\n ],\n toString: () =>\n // generate all the tags as strings and concatenate them\n `${getMethodsForTag(TAG_NAMES.META, meta.priority, encode)} ${getMethodsForTag(\n TAG_NAMES.LINK,\n link.priority,\n encode\n )} ${getMethodsForTag(TAG_NAMES.SCRIPT, script.priority, encode)}`,\n };\n\n return {\n priorityMethods,\n metaTags: meta.default,\n linkTags: link.default,\n scriptTags: script.default,\n };\n};\n\nconst mapStateOnServer = props => {\n const {\n baseTag,\n bodyAttributes,\n encode,\n htmlAttributes,\n noscriptTags,\n styleTags,\n title = '',\n titleAttributes,\n prioritizeSeoTags,\n } = props;\n let { linkTags, metaTags, scriptTags } = props;\n let priorityMethods = {\n toComponent: () => {},\n toString: () => '',\n };\n if (prioritizeSeoTags) {\n ({ priorityMethods, linkTags, metaTags, scriptTags } = getPriorityMethods(props));\n }\n return {\n priority: priorityMethods,\n base: getMethodsForTag(TAG_NAMES.BASE, baseTag, encode),\n bodyAttributes: getMethodsForTag(ATTRIBUTE_NAMES.BODY, bodyAttributes, encode),\n htmlAttributes: getMethodsForTag(ATTRIBUTE_NAMES.HTML, htmlAttributes, encode),\n link: getMethodsForTag(TAG_NAMES.LINK, linkTags, encode),\n meta: getMethodsForTag(TAG_NAMES.META, metaTags, encode),\n noscript: getMethodsForTag(TAG_NAMES.NOSCRIPT, noscriptTags, encode),\n script: getMethodsForTag(TAG_NAMES.SCRIPT, scriptTags, encode),\n style: getMethodsForTag(TAG_NAMES.STYLE, styleTags, encode),\n title: getMethodsForTag(TAG_NAMES.TITLE, { title, titleAttributes }, encode),\n };\n};\n\nexport default mapStateOnServer;\n","import mapStateOnServer from './server';\n\nconst instances = [];\n\nexport function clearInstances() {\n instances.length = 0;\n}\n\nexport default class HelmetData {\n instances = [];\n\n value = {\n setHelmet: serverState => {\n this.context.helmet = serverState;\n },\n helmetInstances: {\n get: () => (this.canUseDOM ? instances : this.instances),\n add: instance => {\n (this.canUseDOM ? instances : this.instances).push(instance);\n },\n remove: instance => {\n const index = (this.canUseDOM ? instances : this.instances).indexOf(instance);\n (this.canUseDOM ? instances : this.instances).splice(index, 1);\n },\n },\n };\n\n constructor(context, canUseDOM = typeof document !== 'undefined') {\n this.context = context;\n this.canUseDOM = canUseDOM;\n\n if (!canUseDOM) {\n context.helmet = mapStateOnServer({\n baseTag: [],\n bodyAttributes: {},\n encodeSpecialCharacters: true,\n htmlAttributes: {},\n linkTags: [],\n metaTags: [],\n noscriptTags: [],\n scriptTags: [],\n styleTags: [],\n title: '',\n titleAttributes: {},\n });\n }\n }\n}\n","import React, { Component } from 'react';\nimport PropTypes from 'prop-types';\nimport HelmetData from './HelmetData';\n\nconst defaultValue = {};\n\nexport const Context = React.createContext(defaultValue);\n\nexport const providerShape = PropTypes.shape({\n setHelmet: PropTypes.func,\n helmetInstances: PropTypes.shape({\n get: PropTypes.func,\n add: PropTypes.func,\n remove: PropTypes.func,\n }),\n});\n\nconst canUseDOM = typeof document !== 'undefined';\n\nexport default class Provider extends Component {\n static canUseDOM = canUseDOM;\n\n static propTypes = {\n context: PropTypes.shape({\n helmet: PropTypes.shape(),\n }),\n children: PropTypes.node.isRequired,\n };\n\n static defaultProps = {\n context: {},\n };\n\n static displayName = 'HelmetProvider';\n\n constructor(props) {\n super(props);\n\n this.helmetData = new HelmetData(this.props.context, Provider.canUseDOM);\n }\n\n render() {\n return {this.props.children};\n }\n}\n","import { HELMET_ATTRIBUTE, TAG_NAMES, TAG_PROPERTIES } from './constants';\nimport { flattenArray } from './utils';\n\nconst updateTags = (type, tags) => {\n const headElement = document.head || document.querySelector(TAG_NAMES.HEAD);\n const tagNodes = headElement.querySelectorAll(`${type}[${HELMET_ATTRIBUTE}]`);\n const oldTags = [].slice.call(tagNodes);\n const newTags = [];\n let indexToDelete;\n\n if (tags && tags.length) {\n tags.forEach(tag => {\n const newElement = document.createElement(type);\n\n // eslint-disable-next-line\n for (const attribute in tag) {\n if (Object.prototype.hasOwnProperty.call(tag, attribute)) {\n if (attribute === TAG_PROPERTIES.INNER_HTML) {\n newElement.innerHTML = tag.innerHTML;\n } else if (attribute === TAG_PROPERTIES.CSS_TEXT) {\n if (newElement.styleSheet) {\n newElement.styleSheet.cssText = tag.cssText;\n } else {\n newElement.appendChild(document.createTextNode(tag.cssText));\n }\n } else {\n const value = typeof tag[attribute] === 'undefined' ? '' : tag[attribute];\n newElement.setAttribute(attribute, value);\n }\n }\n }\n\n newElement.setAttribute(HELMET_ATTRIBUTE, 'true');\n\n // Remove a duplicate tag from domTagstoRemove, so it isn't cleared.\n if (\n oldTags.some((existingTag, index) => {\n indexToDelete = index;\n return newElement.isEqualNode(existingTag);\n })\n ) {\n oldTags.splice(indexToDelete, 1);\n } else {\n newTags.push(newElement);\n }\n });\n }\n\n oldTags.forEach(tag => tag.parentNode.removeChild(tag));\n newTags.forEach(tag => headElement.appendChild(tag));\n\n return {\n oldTags,\n newTags,\n };\n};\n\nconst updateAttributes = (tagName, attributes) => {\n const elementTag = document.getElementsByTagName(tagName)[0];\n\n if (!elementTag) {\n return;\n }\n\n const helmetAttributeString = elementTag.getAttribute(HELMET_ATTRIBUTE);\n const helmetAttributes = helmetAttributeString ? helmetAttributeString.split(',') : [];\n const attributesToRemove = [].concat(helmetAttributes);\n const attributeKeys = Object.keys(attributes);\n\n for (let i = 0; i < attributeKeys.length; i += 1) {\n const attribute = attributeKeys[i];\n const value = attributes[attribute] || '';\n\n if (elementTag.getAttribute(attribute) !== value) {\n elementTag.setAttribute(attribute, value);\n }\n\n if (helmetAttributes.indexOf(attribute) === -1) {\n helmetAttributes.push(attribute);\n }\n\n const indexToSave = attributesToRemove.indexOf(attribute);\n if (indexToSave !== -1) {\n attributesToRemove.splice(indexToSave, 1);\n }\n }\n\n for (let i = attributesToRemove.length - 1; i >= 0; i -= 1) {\n elementTag.removeAttribute(attributesToRemove[i]);\n }\n\n if (helmetAttributes.length === attributesToRemove.length) {\n elementTag.removeAttribute(HELMET_ATTRIBUTE);\n } else if (elementTag.getAttribute(HELMET_ATTRIBUTE) !== attributeKeys.join(',')) {\n elementTag.setAttribute(HELMET_ATTRIBUTE, attributeKeys.join(','));\n }\n};\n\nconst updateTitle = (title, attributes) => {\n if (typeof title !== 'undefined' && document.title !== title) {\n document.title = flattenArray(title);\n }\n\n updateAttributes(TAG_NAMES.TITLE, attributes);\n};\n\nconst commitTagChanges = (newState, cb) => {\n const {\n baseTag,\n bodyAttributes,\n htmlAttributes,\n linkTags,\n metaTags,\n noscriptTags,\n onChangeClientState,\n scriptTags,\n styleTags,\n title,\n titleAttributes,\n } = newState;\n updateAttributes(TAG_NAMES.BODY, bodyAttributes);\n updateAttributes(TAG_NAMES.HTML, htmlAttributes);\n\n updateTitle(title, titleAttributes);\n\n const tagUpdates = {\n baseTag: updateTags(TAG_NAMES.BASE, baseTag),\n linkTags: updateTags(TAG_NAMES.LINK, linkTags),\n metaTags: updateTags(TAG_NAMES.META, metaTags),\n noscriptTags: updateTags(TAG_NAMES.NOSCRIPT, noscriptTags),\n scriptTags: updateTags(TAG_NAMES.SCRIPT, scriptTags),\n styleTags: updateTags(TAG_NAMES.STYLE, styleTags),\n };\n\n const addedTags = {};\n const removedTags = {};\n\n Object.keys(tagUpdates).forEach(tagType => {\n const { newTags, oldTags } = tagUpdates[tagType];\n\n if (newTags.length) {\n addedTags[tagType] = newTags;\n }\n if (oldTags.length) {\n removedTags[tagType] = tagUpdates[tagType].oldTags;\n }\n });\n\n if (cb) {\n cb();\n }\n\n onChangeClientState(newState, addedTags, removedTags);\n};\n\n// eslint-disable-next-line\nlet _helmetCallback = null;\n\nconst handleStateChangeOnClient = newState => {\n if (_helmetCallback) {\n cancelAnimationFrame(_helmetCallback);\n }\n\n if (newState.defer) {\n _helmetCallback = requestAnimationFrame(() => {\n commitTagChanges(newState, () => {\n _helmetCallback = null;\n });\n });\n } else {\n commitTagChanges(newState);\n _helmetCallback = null;\n }\n};\n\nexport default handleStateChangeOnClient;\n","import { Component } from 'react';\nimport shallowEqual from 'shallowequal';\nimport handleStateChangeOnClient from './client';\nimport mapStateOnServer from './server';\nimport { reducePropsToState } from './utils';\nimport Provider, { providerShape } from './Provider';\n\nexport default class Dispatcher extends Component {\n static propTypes = {\n context: providerShape.isRequired,\n };\n\n static displayName = 'HelmetDispatcher';\n\n rendered = false;\n\n shouldComponentUpdate(nextProps) {\n return !shallowEqual(nextProps, this.props);\n }\n\n componentDidUpdate() {\n this.emitChange();\n }\n\n componentWillUnmount() {\n const { helmetInstances } = this.props.context;\n helmetInstances.remove(this);\n this.emitChange();\n }\n\n emitChange() {\n const { helmetInstances, setHelmet } = this.props.context;\n let serverState = null;\n const state = reducePropsToState(\n helmetInstances.get().map(instance => {\n const props = { ...instance.props };\n delete props.context;\n return props;\n })\n );\n if (Provider.canUseDOM) {\n handleStateChangeOnClient(state);\n } else if (mapStateOnServer) {\n serverState = mapStateOnServer(state);\n }\n setHelmet(serverState);\n }\n\n // componentWillMount will be deprecated\n // for SSR, initialize on first render\n // constructor is also unsafe in StrictMode\n init() {\n if (this.rendered) {\n return;\n }\n\n this.rendered = true;\n\n const { helmetInstances } = this.props.context;\n helmetInstances.add(this);\n this.emitChange();\n }\n\n render() {\n this.init();\n\n return null;\n }\n}\n","import React, { Component } from 'react';\nimport PropTypes from 'prop-types';\nimport fastCompare from 'react-fast-compare';\nimport invariant from 'invariant';\nimport { Context } from './Provider';\nimport HelmetData from './HelmetData';\nimport Dispatcher from './Dispatcher';\nimport { without } from './utils';\nimport { TAG_NAMES, VALID_TAG_NAMES, HTML_TAG_MAP } from './constants';\n\nexport { default as HelmetData } from './HelmetData';\nexport { default as HelmetProvider } from './Provider';\n\n/* eslint-disable class-methods-use-this */\nexport class Helmet extends Component {\n /**\n * @param {Object} base: {\"target\": \"_blank\", \"href\": \"http://mysite.com/\"}\n * @param {Object} bodyAttributes: {\"className\": \"root\"}\n * @param {String} defaultTitle: \"Default Title\"\n * @param {Boolean} defer: true\n * @param {Boolean} encodeSpecialCharacters: true\n * @param {Object} htmlAttributes: {\"lang\": \"en\", \"amp\": undefined}\n * @param {Array} link: [{\"rel\": \"canonical\", \"href\": \"http://mysite.com/example\"}]\n * @param {Array} meta: [{\"name\": \"description\", \"content\": \"Test description\"}]\n * @param {Array} noscript: [{\"innerHTML\": \" console.log(newState)\"\n * @param {Array} script: [{\"type\": \"text/javascript\", \"src\": \"http://mysite.com/js/test.js\"}]\n * @param {Array} style: [{\"type\": \"text/css\", \"cssText\": \"div { display: block; color: blue; }\"}]\n * @param {String} title: \"Title\"\n * @param {Object} titleAttributes: {\"itemprop\": \"name\"}\n * @param {String} titleTemplate: \"MySite.com - %s\"\n * @param {Boolean} prioritizeSeoTags: false\n */\n /* eslint-disable react/forbid-prop-types, react/require-default-props */\n static propTypes = {\n base: PropTypes.object,\n bodyAttributes: PropTypes.object,\n children: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.node), PropTypes.node]),\n defaultTitle: PropTypes.string,\n defer: PropTypes.bool,\n encodeSpecialCharacters: PropTypes.bool,\n htmlAttributes: PropTypes.object,\n link: PropTypes.arrayOf(PropTypes.object),\n meta: PropTypes.arrayOf(PropTypes.object),\n noscript: PropTypes.arrayOf(PropTypes.object),\n onChangeClientState: PropTypes.func,\n script: PropTypes.arrayOf(PropTypes.object),\n style: PropTypes.arrayOf(PropTypes.object),\n title: PropTypes.string,\n titleAttributes: PropTypes.object,\n titleTemplate: PropTypes.string,\n prioritizeSeoTags: PropTypes.bool,\n helmetData: PropTypes.object,\n };\n /* eslint-enable react/prop-types, react/forbid-prop-types, react/require-default-props */\n\n static defaultProps = {\n defer: true,\n encodeSpecialCharacters: true,\n prioritizeSeoTags: false,\n };\n\n static displayName = 'Helmet';\n\n shouldComponentUpdate(nextProps) {\n return !fastCompare(without(this.props, 'helmetData'), without(nextProps, 'helmetData'));\n }\n\n mapNestedChildrenToProps(child, nestedChildren) {\n if (!nestedChildren) {\n return null;\n }\n\n switch (child.type) {\n case TAG_NAMES.SCRIPT:\n case TAG_NAMES.NOSCRIPT:\n return {\n innerHTML: nestedChildren,\n };\n\n case TAG_NAMES.STYLE:\n return {\n cssText: nestedChildren,\n };\n default:\n throw new Error(\n `<${child.type} /> elements are self-closing and can not contain children. Refer to our API for more information.`\n );\n }\n }\n\n flattenArrayTypeChildren({ child, arrayTypeChildren, newChildProps, nestedChildren }) {\n return {\n ...arrayTypeChildren,\n [child.type]: [\n ...(arrayTypeChildren[child.type] || []),\n {\n ...newChildProps,\n ...this.mapNestedChildrenToProps(child, nestedChildren),\n },\n ],\n };\n }\n\n mapObjectTypeChildren({ child, newProps, newChildProps, nestedChildren }) {\n switch (child.type) {\n case TAG_NAMES.TITLE:\n return {\n ...newProps,\n [child.type]: nestedChildren,\n titleAttributes: { ...newChildProps },\n };\n\n case TAG_NAMES.BODY:\n return {\n ...newProps,\n bodyAttributes: { ...newChildProps },\n };\n\n case TAG_NAMES.HTML:\n return {\n ...newProps,\n htmlAttributes: { ...newChildProps },\n };\n default:\n return {\n ...newProps,\n [child.type]: { ...newChildProps },\n };\n }\n }\n\n mapArrayTypeChildrenToProps(arrayTypeChildren, newProps) {\n let newFlattenedProps = { ...newProps };\n\n Object.keys(arrayTypeChildren).forEach(arrayChildName => {\n newFlattenedProps = {\n ...newFlattenedProps,\n [arrayChildName]: arrayTypeChildren[arrayChildName],\n };\n });\n\n return newFlattenedProps;\n }\n\n warnOnInvalidChildren(child, nestedChildren) {\n invariant(\n VALID_TAG_NAMES.some(name => child.type === name),\n typeof child.type === 'function'\n ? `You may be attempting to nest components within each other, which is not allowed. Refer to our API for more information.`\n : `Only elements types ${VALID_TAG_NAMES.join(\n ', '\n )} are allowed. Helmet does not support rendering <${\n child.type\n }> elements. Refer to our API for more information.`\n );\n\n invariant(\n !nestedChildren ||\n typeof nestedChildren === 'string' ||\n (Array.isArray(nestedChildren) &&\n !nestedChildren.some(nestedChild => typeof nestedChild !== 'string')),\n `Helmet expects a string as a child of <${child.type}>. Did you forget to wrap your children in braces? ( <${child.type}>{\\`\\`}${child.type}> ) Refer to our API for more information.`\n );\n\n return true;\n }\n\n mapChildrenToProps(children, newProps) {\n let arrayTypeChildren = {};\n\n React.Children.forEach(children, child => {\n if (!child || !child.props) {\n return;\n }\n\n const { children: nestedChildren, ...childProps } = child.props;\n // convert React props to HTML attributes\n const newChildProps = Object.keys(childProps).reduce((obj, key) => {\n obj[HTML_TAG_MAP[key] || key] = childProps[key];\n return obj;\n }, {});\n\n let { type } = child;\n if (typeof type === 'symbol') {\n type = type.toString();\n } else {\n this.warnOnInvalidChildren(child, nestedChildren);\n }\n\n switch (type) {\n case TAG_NAMES.FRAGMENT:\n newProps = this.mapChildrenToProps(nestedChildren, newProps);\n break;\n\n case TAG_NAMES.LINK:\n case TAG_NAMES.META:\n case TAG_NAMES.NOSCRIPT:\n case TAG_NAMES.SCRIPT:\n case TAG_NAMES.STYLE:\n arrayTypeChildren = this.flattenArrayTypeChildren({\n child,\n arrayTypeChildren,\n newChildProps,\n nestedChildren,\n });\n break;\n\n default:\n newProps = this.mapObjectTypeChildren({\n child,\n newProps,\n newChildProps,\n nestedChildren,\n });\n break;\n }\n });\n\n return this.mapArrayTypeChildrenToProps(arrayTypeChildren, newProps);\n }\n\n render() {\n const { children, ...props } = this.props;\n let newProps = { ...props };\n let { helmetData } = props;\n\n if (children) {\n newProps = this.mapChildrenToProps(children, newProps);\n }\n\n if (helmetData && !(helmetData instanceof HelmetData)) {\n helmetData = new HelmetData(helmetData.context, helmetData.instances);\n }\n\n return helmetData ? (\n // eslint-disable-next-line react/jsx-props-no-spreading\n \n ) : (\n \n {(\n context // eslint-disable-next-line react/jsx-props-no-spreading\n ) => }\n \n );\n }\n}\n","declare const __DEBUG_BUILD__: boolean;\n\n/**\n * This serves as a build time flag that will be true by default, but false in non-debug builds or if users replace `__SENTRY_DEBUG__` in their generated code.\n *\n * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking.\n */\nexport const DEBUG_BUILD = __DEBUG_BUILD__;\n","/**\n * NOTE: In order to avoid circular dependencies, if you add a function to this module and it needs to print something,\n * you must either a) use `console.log` rather than the logger, or b) put your function elsewhere.\n *\n * Note: This file was originally called `global.ts`, but was changed to unblock users which might be doing\n * string replaces with bundlers like Vite for `global` (would break imports that rely on importing from utils/src/global).\n *\n * Why worldwide?\n *\n * Why not?\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport type { Integration } from '@sentry/types';\n\nimport type { SdkSource } from './env';\n\n/** Internal global with common properties and Sentry extensions */\nexport interface InternalGlobal {\n navigator?: { userAgent?: string };\n console: Console;\n Sentry?: {\n Integrations?: Integration[];\n };\n onerror?: {\n (event: object | string, source?: string, lineno?: number, colno?: number, error?: Error): any;\n __SENTRY_INSTRUMENTED__?: true;\n __SENTRY_LOADER__?: true;\n };\n onunhandledrejection?: {\n (event: unknown): boolean;\n __SENTRY_INSTRUMENTED__?: true;\n __SENTRY_LOADER__?: true;\n };\n SENTRY_ENVIRONMENT?: string;\n SENTRY_DSN?: string;\n SENTRY_RELEASE?: {\n id?: string;\n };\n SENTRY_SDK_SOURCE?: SdkSource;\n /**\n * Debug IDs are indirectly injected by Sentry CLI or bundler plugins to directly reference a particular source map\n * for resolving of a source file. The injected code will place an entry into the record for each loaded bundle/JS\n * file.\n */\n _sentryDebugIds?: Record;\n __SENTRY__: {\n globalEventProcessors: any;\n hub: any;\n logger: any;\n extensions?: {\n /** Extension methods for the hub, which are bound to the current Hub instance */\n // eslint-disable-next-line @typescript-eslint/ban-types\n [key: string]: Function;\n };\n };\n /**\n * Raw module metadata that is injected by bundler plugins.\n *\n * Keys are `error.stack` strings, values are the metadata.\n */\n _sentryModuleMetadata?: Record;\n}\n\n// The code below for 'isGlobalObj' and 'GLOBAL_OBJ' was copied from core-js before modification\n// https://github.com/zloirock/core-js/blob/1b944df55282cdc99c90db5f49eb0b6eda2cc0a3/packages/core-js/internals/global.js\n// core-js has the following licence:\n//\n// Copyright (c) 2014-2022 Denis Pushkarev\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n/** Returns 'obj' if it's the global object, otherwise returns undefined */\nfunction isGlobalObj(obj: { Math?: Math }): any | undefined {\n return obj && obj.Math == Math ? obj : undefined;\n}\n\n/** Get's the global object for the current JavaScript runtime */\nexport const GLOBAL_OBJ: InternalGlobal =\n (typeof globalThis == 'object' && isGlobalObj(globalThis)) ||\n // eslint-disable-next-line no-restricted-globals\n (typeof window == 'object' && isGlobalObj(window)) ||\n (typeof self == 'object' && isGlobalObj(self)) ||\n (typeof global == 'object' && isGlobalObj(global)) ||\n (function (this: any) {\n return this;\n })() ||\n {};\n\n/**\n * @deprecated Use GLOBAL_OBJ instead or WINDOW from @sentry/browser. This will be removed in v8\n */\nexport function getGlobalObject(): T & InternalGlobal {\n return GLOBAL_OBJ as T & InternalGlobal;\n}\n\n/**\n * Returns a global singleton contained in the global `__SENTRY__` object.\n *\n * If the singleton doesn't already exist in `__SENTRY__`, it will be created using the given factory\n * function and added to the `__SENTRY__` object.\n *\n * @param name name of the global singleton on __SENTRY__\n * @param creator creator Factory function to create the singleton if it doesn't already exist on `__SENTRY__`\n * @param obj (Optional) The global object on which to look for `__SENTRY__`, if not `GLOBAL_OBJ`'s return value\n * @returns the singleton\n */\nexport function getGlobalSingleton(name: keyof InternalGlobal['__SENTRY__'], creator: () => T, obj?: unknown): T {\n const gbl = (obj || GLOBAL_OBJ) as InternalGlobal;\n const __SENTRY__ = (gbl.__SENTRY__ = gbl.__SENTRY__ || {});\n const singleton = __SENTRY__[name] || (__SENTRY__[name] = creator());\n return singleton;\n}\n","import type { ConsoleLevel } from '@sentry/types';\n\nimport { DEBUG_BUILD } from './debug-build';\nimport { GLOBAL_OBJ } from './worldwide';\n\n/** Prefix for logging strings */\nconst PREFIX = 'Sentry Logger ';\n\nexport const CONSOLE_LEVELS: readonly ConsoleLevel[] = [\n 'debug',\n 'info',\n 'warn',\n 'error',\n 'log',\n 'assert',\n 'trace',\n] as const;\n\ntype LoggerMethod = (...args: unknown[]) => void;\ntype LoggerConsoleMethods = Record;\n\n/** This may be mutated by the console instrumentation. */\nexport const originalConsoleMethods: {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key in ConsoleLevel]?: (...args: any[]) => void;\n} = {};\n\n/** JSDoc */\ninterface Logger extends LoggerConsoleMethods {\n disable(): void;\n enable(): void;\n isEnabled(): boolean;\n}\n\n/**\n * Temporarily disable sentry console instrumentations.\n *\n * @param callback The function to run against the original `console` messages\n * @returns The results of the callback\n */\nexport function consoleSandbox(callback: () => T): T {\n if (!('console' in GLOBAL_OBJ)) {\n return callback();\n }\n\n const console = GLOBAL_OBJ.console as Console;\n const wrappedFuncs: Partial = {};\n\n const wrappedLevels = Object.keys(originalConsoleMethods) as ConsoleLevel[];\n\n // Restore all wrapped console methods\n wrappedLevels.forEach(level => {\n const originalConsoleMethod = originalConsoleMethods[level] as LoggerMethod;\n wrappedFuncs[level] = console[level] as LoggerMethod | undefined;\n console[level] = originalConsoleMethod;\n });\n\n try {\n return callback();\n } finally {\n // Revert restoration to wrapped state\n wrappedLevels.forEach(level => {\n console[level] = wrappedFuncs[level] as LoggerMethod;\n });\n }\n}\n\nfunction makeLogger(): Logger {\n let enabled = false;\n const logger: Partial = {\n enable: () => {\n enabled = true;\n },\n disable: () => {\n enabled = false;\n },\n isEnabled: () => enabled,\n };\n\n if (DEBUG_BUILD) {\n CONSOLE_LEVELS.forEach(name => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n logger[name] = (...args: any[]) => {\n if (enabled) {\n consoleSandbox(() => {\n GLOBAL_OBJ.console[name](`${PREFIX}[${name}]:`, ...args);\n });\n }\n };\n });\n } else {\n CONSOLE_LEVELS.forEach(name => {\n logger[name] = () => undefined;\n });\n }\n\n return logger as Logger;\n}\n\nexport const logger = makeLogger();\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/explicit-module-boundary-types */\n\nimport type { ParameterizedString, PolymorphicEvent, Primitive } from '@sentry/types';\n\n// eslint-disable-next-line @typescript-eslint/unbound-method\nconst objectToString = Object.prototype.toString;\n\n/**\n * Checks whether given value's type is one of a few Error or Error-like\n * {@link isError}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isError(wat: unknown): wat is Error {\n switch (objectToString.call(wat)) {\n case '[object Error]':\n case '[object Exception]':\n case '[object DOMException]':\n return true;\n default:\n return isInstanceOf(wat, Error);\n }\n}\n/**\n * Checks whether given value is an instance of the given built-in class.\n *\n * @param wat The value to be checked\n * @param className\n * @returns A boolean representing the result.\n */\nfunction isBuiltin(wat: unknown, className: string): boolean {\n return objectToString.call(wat) === `[object ${className}]`;\n}\n\n/**\n * Checks whether given value's type is ErrorEvent\n * {@link isErrorEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isErrorEvent(wat: unknown): boolean {\n return isBuiltin(wat, 'ErrorEvent');\n}\n\n/**\n * Checks whether given value's type is DOMError\n * {@link isDOMError}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isDOMError(wat: unknown): boolean {\n return isBuiltin(wat, 'DOMError');\n}\n\n/**\n * Checks whether given value's type is DOMException\n * {@link isDOMException}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isDOMException(wat: unknown): boolean {\n return isBuiltin(wat, 'DOMException');\n}\n\n/**\n * Checks whether given value's type is a string\n * {@link isString}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isString(wat: unknown): wat is string {\n return isBuiltin(wat, 'String');\n}\n\n/**\n * Checks whether given string is parameterized\n * {@link isParameterizedString}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isParameterizedString(wat: unknown): wat is ParameterizedString {\n return (\n typeof wat === 'object' &&\n wat !== null &&\n '__sentry_template_string__' in wat &&\n '__sentry_template_values__' in wat\n );\n}\n\n/**\n * Checks whether given value is a primitive (undefined, null, number, boolean, string, bigint, symbol)\n * {@link isPrimitive}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isPrimitive(wat: unknown): wat is Primitive {\n return wat === null || isParameterizedString(wat) || (typeof wat !== 'object' && typeof wat !== 'function');\n}\n\n/**\n * Checks whether given value's type is an object literal, or a class instance.\n * {@link isPlainObject}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isPlainObject(wat: unknown): wat is Record {\n return isBuiltin(wat, 'Object');\n}\n\n/**\n * Checks whether given value's type is an Event instance\n * {@link isEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isEvent(wat: unknown): wat is PolymorphicEvent {\n return typeof Event !== 'undefined' && isInstanceOf(wat, Event);\n}\n\n/**\n * Checks whether given value's type is an Element instance\n * {@link isElement}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isElement(wat: unknown): boolean {\n return typeof Element !== 'undefined' && isInstanceOf(wat, Element);\n}\n\n/**\n * Checks whether given value's type is an regexp\n * {@link isRegExp}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isRegExp(wat: unknown): wat is RegExp {\n return isBuiltin(wat, 'RegExp');\n}\n\n/**\n * Checks whether given value has a then function.\n * @param wat A value to be checked.\n */\nexport function isThenable(wat: any): wat is PromiseLike {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return Boolean(wat && wat.then && typeof wat.then === 'function');\n}\n\n/**\n * Checks whether given value's type is a SyntheticEvent\n * {@link isSyntheticEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isSyntheticEvent(wat: unknown): boolean {\n return isPlainObject(wat) && 'nativeEvent' in wat && 'preventDefault' in wat && 'stopPropagation' in wat;\n}\n\n/**\n * Checks whether given value is NaN\n * {@link isNaN}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isNaN(wat: unknown): boolean {\n return typeof wat === 'number' && wat !== wat;\n}\n\n/**\n * Checks whether given value's type is an instance of provided constructor.\n * {@link isInstanceOf}.\n *\n * @param wat A value to be checked.\n * @param base A constructor to be used in a check.\n * @returns A boolean representing the result.\n */\nexport function isInstanceOf(wat: any, base: any): boolean {\n try {\n return wat instanceof base;\n } catch (_e) {\n return false;\n }\n}\n\ninterface VueViewModel {\n // Vue3\n __isVue?: boolean;\n // Vue2\n _isVue?: boolean;\n}\n/**\n * Checks whether given value's type is a Vue ViewModel.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isVueViewModel(wat: unknown): boolean {\n // Not using Object.prototype.toString because in Vue 3 it would read the instance's Symbol(Symbol.toStringTag) property.\n return !!(typeof wat === 'object' && wat !== null && ((wat as VueViewModel).__isVue || (wat as VueViewModel)._isVue));\n}\n","import { isString } from './is';\nimport { getGlobalObject } from './worldwide';\n\n// eslint-disable-next-line deprecation/deprecation\nconst WINDOW = getGlobalObject();\n\nconst DEFAULT_MAX_STRING_LENGTH = 80;\n\ntype SimpleNode = {\n parentNode: SimpleNode;\n} | null;\n\n/**\n * Given a child DOM element, returns a query-selector statement describing that\n * and its ancestors\n * e.g. [HTMLElement] => body > div > input#foo.btn[name=baz]\n * @returns generated DOM path\n */\nexport function htmlTreeAsString(\n elem: unknown,\n options: string[] | { keyAttrs?: string[]; maxStringLength?: number } = {},\n): string {\n if (!elem) {\n return '';\n }\n\n // try/catch both:\n // - accessing event.target (see getsentry/raven-js#838, #768)\n // - `htmlTreeAsString` because it's complex, and just accessing the DOM incorrectly\n // - can throw an exception in some circumstances.\n try {\n let currentElem = elem as SimpleNode;\n const MAX_TRAVERSE_HEIGHT = 5;\n const out = [];\n let height = 0;\n let len = 0;\n const separator = ' > ';\n const sepLength = separator.length;\n let nextStr;\n const keyAttrs = Array.isArray(options) ? options : options.keyAttrs;\n const maxStringLength = (!Array.isArray(options) && options.maxStringLength) || DEFAULT_MAX_STRING_LENGTH;\n\n while (currentElem && height++ < MAX_TRAVERSE_HEIGHT) {\n nextStr = _htmlElementAsString(currentElem, keyAttrs);\n // bail out if\n // - nextStr is the 'html' element\n // - the length of the string that would be created exceeds maxStringLength\n // (ignore this limit if we are on the first iteration)\n if (nextStr === 'html' || (height > 1 && len + out.length * sepLength + nextStr.length >= maxStringLength)) {\n break;\n }\n\n out.push(nextStr);\n\n len += nextStr.length;\n currentElem = currentElem.parentNode;\n }\n\n return out.reverse().join(separator);\n } catch (_oO) {\n return '';\n }\n}\n\n/**\n * Returns a simple, query-selector representation of a DOM element\n * e.g. [HTMLElement] => input#foo.btn[name=baz]\n * @returns generated DOM path\n */\nfunction _htmlElementAsString(el: unknown, keyAttrs?: string[]): string {\n const elem = el as {\n tagName?: string;\n id?: string;\n className?: string;\n getAttribute(key: string): string;\n };\n\n const out = [];\n let className;\n let classes;\n let key;\n let attr;\n let i;\n\n if (!elem || !elem.tagName) {\n return '';\n }\n\n // @ts-expect-error WINDOW has HTMLElement\n if (WINDOW.HTMLElement) {\n // If using the component name annotation plugin, this value may be available on the DOM node\n if (elem instanceof HTMLElement && elem.dataset && elem.dataset['sentryComponent']) {\n return elem.dataset['sentryComponent'];\n }\n }\n\n out.push(elem.tagName.toLowerCase());\n\n // Pairs of attribute keys defined in `serializeAttribute` and their values on element.\n const keyAttrPairs =\n keyAttrs && keyAttrs.length\n ? keyAttrs.filter(keyAttr => elem.getAttribute(keyAttr)).map(keyAttr => [keyAttr, elem.getAttribute(keyAttr)])\n : null;\n\n if (keyAttrPairs && keyAttrPairs.length) {\n keyAttrPairs.forEach(keyAttrPair => {\n out.push(`[${keyAttrPair[0]}=\"${keyAttrPair[1]}\"]`);\n });\n } else {\n if (elem.id) {\n out.push(`#${elem.id}`);\n }\n\n // eslint-disable-next-line prefer-const\n className = elem.className;\n if (className && isString(className)) {\n classes = className.split(/\\s+/);\n for (i = 0; i < classes.length; i++) {\n out.push(`.${classes[i]}`);\n }\n }\n }\n const allowedAttrs = ['aria-label', 'type', 'name', 'title', 'alt'];\n for (i = 0; i < allowedAttrs.length; i++) {\n key = allowedAttrs[i];\n attr = elem.getAttribute(key);\n if (attr) {\n out.push(`[${key}=\"${attr}\"]`);\n }\n }\n return out.join('');\n}\n\n/**\n * A safe form of location.href\n */\nexport function getLocationHref(): string {\n try {\n return WINDOW.document.location.href;\n } catch (oO) {\n return '';\n }\n}\n\n/**\n * Gets a DOM element by using document.querySelector.\n *\n * This wrapper will first check for the existance of the function before\n * actually calling it so that we don't have to take care of this check,\n * every time we want to access the DOM.\n *\n * Reason: DOM/querySelector is not available in all environments.\n *\n * We have to cast to any because utils can be consumed by a variety of environments,\n * and we don't want to break TS users. If you know what element will be selected by\n * `document.querySelector`, specify it as part of the generic call. For example,\n * `const element = getDomElement('selector');`\n *\n * @param selector the selector string passed on to document.querySelector\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function getDomElement(selector: string): E | null {\n if (WINDOW.document && WINDOW.document.querySelector) {\n return WINDOW.document.querySelector(selector) as unknown as E;\n }\n return null;\n}\n\n/**\n * Given a DOM element, traverses up the tree until it finds the first ancestor node\n * that has the `data-sentry-component` attribute. This attribute is added at build-time\n * by projects that have the component name annotation plugin installed.\n *\n * @returns a string representation of the component for the provided DOM element, or `null` if not found\n */\nexport function getComponentName(elem: unknown): string | null {\n // @ts-expect-error WINDOW has HTMLElement\n if (!WINDOW.HTMLElement) {\n return null;\n }\n\n let currentElem = elem as SimpleNode;\n const MAX_TRAVERSE_HEIGHT = 5;\n for (let i = 0; i < MAX_TRAVERSE_HEIGHT; i++) {\n if (!currentElem) {\n return null;\n }\n\n if (currentElem instanceof HTMLElement && currentElem.dataset['sentryComponent']) {\n return currentElem.dataset['sentryComponent'];\n }\n\n currentElem = currentElem.parentNode;\n }\n\n return null;\n}\n","import { isRegExp, isString, isVueViewModel } from './is';\n\nexport { escapeStringForRegex } from './vendor/escapeStringForRegex';\n\n/**\n * Truncates given string to the maximum characters count\n *\n * @param str An object that contains serializable values\n * @param max Maximum number of characters in truncated string (0 = unlimited)\n * @returns string Encoded\n */\nexport function truncate(str: string, max: number = 0): string {\n if (typeof str !== 'string' || max === 0) {\n return str;\n }\n return str.length <= max ? str : `${str.slice(0, max)}...`;\n}\n\n/**\n * This is basically just `trim_line` from\n * https://github.com/getsentry/sentry/blob/master/src/sentry/lang/javascript/processor.py#L67\n *\n * @param str An object that contains serializable values\n * @param max Maximum number of characters in truncated string\n * @returns string Encoded\n */\nexport function snipLine(line: string, colno: number): string {\n let newLine = line;\n const lineLength = newLine.length;\n if (lineLength <= 150) {\n return newLine;\n }\n if (colno > lineLength) {\n // eslint-disable-next-line no-param-reassign\n colno = lineLength;\n }\n\n let start = Math.max(colno - 60, 0);\n if (start < 5) {\n start = 0;\n }\n\n let end = Math.min(start + 140, lineLength);\n if (end > lineLength - 5) {\n end = lineLength;\n }\n if (end === lineLength) {\n start = Math.max(end - 140, 0);\n }\n\n newLine = newLine.slice(start, end);\n if (start > 0) {\n newLine = `'{snip} ${newLine}`;\n }\n if (end < lineLength) {\n newLine += ' {snip}';\n }\n\n return newLine;\n}\n\n/**\n * Join values in array\n * @param input array of values to be joined together\n * @param delimiter string to be placed in-between values\n * @returns Joined values\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function safeJoin(input: any[], delimiter?: string): string {\n if (!Array.isArray(input)) {\n return '';\n }\n\n const output = [];\n // eslint-disable-next-line @typescript-eslint/prefer-for-of\n for (let i = 0; i < input.length; i++) {\n const value = input[i];\n try {\n // This is a hack to fix a Vue3-specific bug that causes an infinite loop of\n // console warnings. This happens when a Vue template is rendered with\n // an undeclared variable, which we try to stringify, ultimately causing\n // Vue to issue another warning which repeats indefinitely.\n // see: https://github.com/getsentry/sentry-javascript/pull/8981\n if (isVueViewModel(value)) {\n output.push('[VueViewModel]');\n } else {\n output.push(String(value));\n }\n } catch (e) {\n output.push('[value cannot be serialized]');\n }\n }\n\n return output.join(delimiter);\n}\n\n/**\n * Checks if the given value matches a regex or string\n *\n * @param value The string to test\n * @param pattern Either a regex or a string against which `value` will be matched\n * @param requireExactStringMatch If true, `value` must match `pattern` exactly. If false, `value` will match\n * `pattern` if it contains `pattern`. Only applies to string-type patterns.\n */\nexport function isMatchingPattern(\n value: string,\n pattern: RegExp | string,\n requireExactStringMatch: boolean = false,\n): boolean {\n if (!isString(value)) {\n return false;\n }\n\n if (isRegExp(pattern)) {\n return pattern.test(value);\n }\n if (isString(pattern)) {\n return requireExactStringMatch ? value === pattern : value.includes(pattern);\n }\n\n return false;\n}\n\n/**\n * Test the given string against an array of strings and regexes. By default, string matching is done on a\n * substring-inclusion basis rather than a strict equality basis\n *\n * @param testString The string to test\n * @param patterns The patterns against which to test the string\n * @param requireExactStringMatch If true, `testString` must match one of the given string patterns exactly in order to\n * count. If false, `testString` will match a string pattern if it contains that pattern.\n * @returns\n */\nexport function stringMatchesSomePattern(\n testString: string,\n patterns: Array = [],\n requireExactStringMatch: boolean = false,\n): boolean {\n return patterns.some(pattern => isMatchingPattern(testString, pattern, requireExactStringMatch));\n}\n","/* eslint-disable max-lines */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { WrappedFunction } from '@sentry/types';\n\nimport { htmlTreeAsString } from './browser';\nimport { DEBUG_BUILD } from './debug-build';\nimport { isElement, isError, isEvent, isInstanceOf, isPlainObject, isPrimitive } from './is';\nimport { logger } from './logger';\nimport { truncate } from './string';\n\n/**\n * Replace a method in an object with a wrapped version of itself.\n *\n * @param source An object that contains a method to be wrapped.\n * @param name The name of the method to be wrapped.\n * @param replacementFactory A higher-order function that takes the original version of the given method and returns a\n * wrapped version. Note: The function returned by `replacementFactory` needs to be a non-arrow function, in order to\n * preserve the correct value of `this`, and the original method must be called using `origMethod.call(this, )` or `origMethod.apply(this, [])` (rather than being called directly), again to preserve `this`.\n * @returns void\n */\nexport function fill(source: { [key: string]: any }, name: string, replacementFactory: (...args: any[]) => any): void {\n if (!(name in source)) {\n return;\n }\n\n const original = source[name] as () => any;\n const wrapped = replacementFactory(original) as WrappedFunction;\n\n // Make sure it's a function first, as we need to attach an empty prototype for `defineProperties` to work\n // otherwise it'll throw \"TypeError: Object.defineProperties called on non-object\"\n if (typeof wrapped === 'function') {\n markFunctionWrapped(wrapped, original);\n }\n\n source[name] = wrapped;\n}\n\n/**\n * Defines a non-enumerable property on the given object.\n *\n * @param obj The object on which to set the property\n * @param name The name of the property to be set\n * @param value The value to which to set the property\n */\nexport function addNonEnumerableProperty(obj: object, name: string, value: unknown): void {\n try {\n Object.defineProperty(obj, name, {\n // enumerable: false, // the default, so we can save on bundle size by not explicitly setting it\n value: value,\n writable: true,\n configurable: true,\n });\n } catch (o_O) {\n DEBUG_BUILD && logger.log(`Failed to add non-enumerable property \"${name}\" to object`, obj);\n }\n}\n\n/**\n * Remembers the original function on the wrapped function and\n * patches up the prototype.\n *\n * @param wrapped the wrapper function\n * @param original the original function that gets wrapped\n */\nexport function markFunctionWrapped(wrapped: WrappedFunction, original: WrappedFunction): void {\n try {\n const proto = original.prototype || {};\n wrapped.prototype = original.prototype = proto;\n addNonEnumerableProperty(wrapped, '__sentry_original__', original);\n } catch (o_O) {} // eslint-disable-line no-empty\n}\n\n/**\n * This extracts the original function if available. See\n * `markFunctionWrapped` for more information.\n *\n * @param func the function to unwrap\n * @returns the unwrapped version of the function if available.\n */\nexport function getOriginalFunction(func: WrappedFunction): WrappedFunction | undefined {\n return func.__sentry_original__;\n}\n\n/**\n * Encodes given object into url-friendly format\n *\n * @param object An object that contains serializable values\n * @returns string Encoded\n */\nexport function urlEncode(object: { [key: string]: any }): string {\n return Object.keys(object)\n .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(object[key])}`)\n .join('&');\n}\n\n/**\n * Transforms any `Error` or `Event` into a plain object with all of their enumerable properties, and some of their\n * non-enumerable properties attached.\n *\n * @param value Initial source that we have to transform in order for it to be usable by the serializer\n * @returns An Event or Error turned into an object - or the value argurment itself, when value is neither an Event nor\n * an Error.\n */\nexport function convertToPlainObject(\n value: V,\n):\n | {\n [ownProps: string]: unknown;\n type: string;\n target: string;\n currentTarget: string;\n detail?: unknown;\n }\n | {\n [ownProps: string]: unknown;\n message: string;\n name: string;\n stack?: string;\n }\n | V {\n if (isError(value)) {\n return {\n message: value.message,\n name: value.name,\n stack: value.stack,\n ...getOwnProperties(value),\n };\n } else if (isEvent(value)) {\n const newObj: {\n [ownProps: string]: unknown;\n type: string;\n target: string;\n currentTarget: string;\n detail?: unknown;\n } = {\n type: value.type,\n target: serializeEventTarget(value.target),\n currentTarget: serializeEventTarget(value.currentTarget),\n ...getOwnProperties(value),\n };\n\n if (typeof CustomEvent !== 'undefined' && isInstanceOf(value, CustomEvent)) {\n newObj.detail = value.detail;\n }\n\n return newObj;\n } else {\n return value;\n }\n}\n\n/** Creates a string representation of the target of an `Event` object */\nfunction serializeEventTarget(target: unknown): string {\n try {\n return isElement(target) ? htmlTreeAsString(target) : Object.prototype.toString.call(target);\n } catch (_oO) {\n return '';\n }\n}\n\n/** Filters out all but an object's own properties */\nfunction getOwnProperties(obj: unknown): { [key: string]: unknown } {\n if (typeof obj === 'object' && obj !== null) {\n const extractedProps: { [key: string]: unknown } = {};\n for (const property in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, property)) {\n extractedProps[property] = (obj as Record)[property];\n }\n }\n return extractedProps;\n } else {\n return {};\n }\n}\n\n/**\n * Given any captured exception, extract its keys and create a sorted\n * and truncated list that will be used inside the event message.\n * eg. `Non-error exception captured with keys: foo, bar, baz`\n */\nexport function extractExceptionKeysForMessage(exception: Record, maxLength: number = 40): string {\n const keys = Object.keys(convertToPlainObject(exception));\n keys.sort();\n\n if (!keys.length) {\n return '[object has no keys]';\n }\n\n if (keys[0].length >= maxLength) {\n return truncate(keys[0], maxLength);\n }\n\n for (let includedKeys = keys.length; includedKeys > 0; includedKeys--) {\n const serialized = keys.slice(0, includedKeys).join(', ');\n if (serialized.length > maxLength) {\n continue;\n }\n if (includedKeys === keys.length) {\n return serialized;\n }\n return truncate(serialized, maxLength);\n }\n\n return '';\n}\n\n/**\n * Given any object, return a new object having removed all fields whose value was `undefined`.\n * Works recursively on objects and arrays.\n *\n * Attention: This function keeps circular references in the returned object.\n */\nexport function dropUndefinedKeys(inputValue: T): T {\n // This map keeps track of what already visited nodes map to.\n // Our Set - based memoBuilder doesn't work here because we want to the output object to have the same circular\n // references as the input object.\n const memoizationMap = new Map();\n\n // This function just proxies `_dropUndefinedKeys` to keep the `memoBuilder` out of this function's API\n return _dropUndefinedKeys(inputValue, memoizationMap);\n}\n\nfunction _dropUndefinedKeys(inputValue: T, memoizationMap: Map): T {\n if (isPojo(inputValue)) {\n // If this node has already been visited due to a circular reference, return the object it was mapped to in the new object\n const memoVal = memoizationMap.get(inputValue);\n if (memoVal !== undefined) {\n return memoVal as T;\n }\n\n const returnValue: { [key: string]: any } = {};\n // Store the mapping of this value in case we visit it again, in case of circular data\n memoizationMap.set(inputValue, returnValue);\n\n for (const key of Object.keys(inputValue)) {\n if (typeof inputValue[key] !== 'undefined') {\n returnValue[key] = _dropUndefinedKeys(inputValue[key], memoizationMap);\n }\n }\n\n return returnValue as T;\n }\n\n if (Array.isArray(inputValue)) {\n // If this node has already been visited due to a circular reference, return the array it was mapped to in the new object\n const memoVal = memoizationMap.get(inputValue);\n if (memoVal !== undefined) {\n return memoVal as T;\n }\n\n const returnValue: unknown[] = [];\n // Store the mapping of this value in case we visit it again, in case of circular data\n memoizationMap.set(inputValue, returnValue);\n\n inputValue.forEach((item: unknown) => {\n returnValue.push(_dropUndefinedKeys(item, memoizationMap));\n });\n\n return returnValue as unknown as T;\n }\n\n return inputValue;\n}\n\nfunction isPojo(input: unknown): input is Record {\n if (!isPlainObject(input)) {\n return false;\n }\n\n try {\n const name = (Object.getPrototypeOf(input) as { constructor: { name: string } }).constructor.name;\n return !name || name === 'Object';\n } catch {\n return true;\n }\n}\n\n/**\n * Ensure that something is an object.\n *\n * Turns `undefined` and `null` into `String`s and all other primitives into instances of their respective wrapper\n * classes (String, Boolean, Number, etc.). Acts as the identity function on non-primitives.\n *\n * @param wat The subject of the objectification\n * @returns A version of `wat` which can safely be used with `Object` class methods\n */\nexport function objectify(wat: unknown): typeof Object {\n let objectified;\n switch (true) {\n case wat === undefined || wat === null:\n objectified = new String(wat);\n break;\n\n // Though symbols and bigints do have wrapper classes (`Symbol` and `BigInt`, respectively), for whatever reason\n // those classes don't have constructors which can be used with the `new` keyword. We therefore need to cast each as\n // an object in order to wrap it.\n case typeof wat === 'symbol' || typeof wat === 'bigint':\n objectified = Object(wat);\n break;\n\n // this will catch the remaining primitives: `String`, `Number`, and `Boolean`\n case isPrimitive(wat):\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n objectified = new (wat as any).constructor(wat);\n break;\n\n // by process of elimination, at this point we know that `wat` must already be an object\n default:\n objectified = wat;\n break;\n }\n return objectified;\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { Event, Exception, Mechanism, StackFrame } from '@sentry/types';\n\nimport { addNonEnumerableProperty } from './object';\nimport { snipLine } from './string';\nimport { GLOBAL_OBJ } from './worldwide';\n\ninterface CryptoInternal {\n getRandomValues(array: Uint8Array): Uint8Array;\n randomUUID?(): string;\n}\n\n/** An interface for common properties on global */\ninterface CryptoGlobal {\n msCrypto?: CryptoInternal;\n crypto?: CryptoInternal;\n}\n\n/**\n * UUID4 generator\n *\n * @returns string Generated UUID4.\n */\nexport function uuid4(): string {\n const gbl = GLOBAL_OBJ as typeof GLOBAL_OBJ & CryptoGlobal;\n const crypto = gbl.crypto || gbl.msCrypto;\n\n let getRandomByte = (): number => Math.random() * 16;\n try {\n if (crypto && crypto.randomUUID) {\n return crypto.randomUUID().replace(/-/g, '');\n }\n if (crypto && crypto.getRandomValues) {\n getRandomByte = () => {\n // crypto.getRandomValues might return undefined instead of the typed array\n // in old Chromium versions (e.g. 23.0.1235.0 (151422))\n // However, `typedArray` is still filled in-place.\n // @see https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues#typedarray\n const typedArray = new Uint8Array(1);\n crypto.getRandomValues(typedArray);\n return typedArray[0];\n };\n }\n } catch (_) {\n // some runtimes can crash invoking crypto\n // https://github.com/getsentry/sentry-javascript/issues/8935\n }\n\n // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523\n // Concatenating the following numbers as strings results in '10000000100040008000100000000000'\n return (([1e7] as unknown as string) + 1e3 + 4e3 + 8e3 + 1e11).replace(/[018]/g, c =>\n // eslint-disable-next-line no-bitwise\n ((c as unknown as number) ^ ((getRandomByte() & 15) >> ((c as unknown as number) / 4))).toString(16),\n );\n}\n\nfunction getFirstException(event: Event): Exception | undefined {\n return event.exception && event.exception.values ? event.exception.values[0] : undefined;\n}\n\n/**\n * Extracts either message or type+value from an event that can be used for user-facing logs\n * @returns event's description\n */\nexport function getEventDescription(event: Event): string {\n const { message, event_id: eventId } = event;\n if (message) {\n return message;\n }\n\n const firstException = getFirstException(event);\n if (firstException) {\n if (firstException.type && firstException.value) {\n return `${firstException.type}: ${firstException.value}`;\n }\n return firstException.type || firstException.value || eventId || '';\n }\n return eventId || '';\n}\n\n/**\n * Adds exception values, type and value to an synthetic Exception.\n * @param event The event to modify.\n * @param value Value of the exception.\n * @param type Type of the exception.\n * @hidden\n */\nexport function addExceptionTypeValue(event: Event, value?: string, type?: string): void {\n const exception = (event.exception = event.exception || {});\n const values = (exception.values = exception.values || []);\n const firstException = (values[0] = values[0] || {});\n if (!firstException.value) {\n firstException.value = value || '';\n }\n if (!firstException.type) {\n firstException.type = type || 'Error';\n }\n}\n\n/**\n * Adds exception mechanism data to a given event. Uses defaults if the second parameter is not passed.\n *\n * @param event The event to modify.\n * @param newMechanism Mechanism data to add to the event.\n * @hidden\n */\nexport function addExceptionMechanism(event: Event, newMechanism?: Partial): void {\n const firstException = getFirstException(event);\n if (!firstException) {\n return;\n }\n\n const defaultMechanism = { type: 'generic', handled: true };\n const currentMechanism = firstException.mechanism;\n firstException.mechanism = { ...defaultMechanism, ...currentMechanism, ...newMechanism };\n\n if (newMechanism && 'data' in newMechanism) {\n const mergedData = { ...(currentMechanism && currentMechanism.data), ...newMechanism.data };\n firstException.mechanism.data = mergedData;\n }\n}\n\n// https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string\nconst SEMVER_REGEXP =\n /^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-((?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+([0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$/;\n\n/**\n * Represents Semantic Versioning object\n */\ninterface SemVer {\n major?: number;\n minor?: number;\n patch?: number;\n prerelease?: string;\n buildmetadata?: string;\n}\n\n/**\n * Parses input into a SemVer interface\n * @param input string representation of a semver version\n */\nexport function parseSemver(input: string): SemVer {\n const match = input.match(SEMVER_REGEXP) || [];\n const major = parseInt(match[1], 10);\n const minor = parseInt(match[2], 10);\n const patch = parseInt(match[3], 10);\n return {\n buildmetadata: match[5],\n major: isNaN(major) ? undefined : major,\n minor: isNaN(minor) ? undefined : minor,\n patch: isNaN(patch) ? undefined : patch,\n prerelease: match[4],\n };\n}\n\n/**\n * This function adds context (pre/post/line) lines to the provided frame\n *\n * @param lines string[] containing all lines\n * @param frame StackFrame that will be mutated\n * @param linesOfContext number of context lines we want to add pre/post\n */\nexport function addContextToFrame(lines: string[], frame: StackFrame, linesOfContext: number = 5): void {\n // When there is no line number in the frame, attaching context is nonsensical and will even break grouping\n if (frame.lineno === undefined) {\n return;\n }\n\n const maxLines = lines.length;\n const sourceLine = Math.max(Math.min(maxLines - 1, frame.lineno - 1), 0);\n\n frame.pre_context = lines\n .slice(Math.max(0, sourceLine - linesOfContext), sourceLine)\n .map((line: string) => snipLine(line, 0));\n\n frame.context_line = snipLine(lines[Math.min(maxLines - 1, sourceLine)], frame.colno || 0);\n\n frame.post_context = lines\n .slice(Math.min(sourceLine + 1, maxLines), sourceLine + 1 + linesOfContext)\n .map((line: string) => snipLine(line, 0));\n}\n\n/**\n * Checks whether or not we've already captured the given exception (note: not an identical exception - the very object\n * in question), and marks it captured if not.\n *\n * This is useful because it's possible for an error to get captured by more than one mechanism. After we intercept and\n * record an error, we rethrow it (assuming we've intercepted it before it's reached the top-level global handlers), so\n * that we don't interfere with whatever effects the error might have had were the SDK not there. At that point, because\n * the error has been rethrown, it's possible for it to bubble up to some other code we've instrumented. If it's not\n * caught after that, it will bubble all the way up to the global handlers (which of course we also instrument). This\n * function helps us ensure that even if we encounter the same error more than once, we only record it the first time we\n * see it.\n *\n * Note: It will ignore primitives (always return `false` and not mark them as seen), as properties can't be set on\n * them. {@link: Object.objectify} can be used on exceptions to convert any that are primitives into their equivalent\n * object wrapper forms so that this check will always work. However, because we need to flag the exact object which\n * will get rethrown, and because that rethrowing happens outside of the event processing pipeline, the objectification\n * must be done before the exception captured.\n *\n * @param A thrown exception to check or flag as having been seen\n * @returns `true` if the exception has already been captured, `false` if not (with the side effect of marking it seen)\n */\nexport function checkOrSetAlreadyCaught(exception: unknown): boolean {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if (exception && (exception as any).__sentry_captured__) {\n return true;\n }\n\n try {\n // set it this way rather than by assignment so that it's not ennumerable and therefore isn't recorded by the\n // `ExtraErrorData` integration\n addNonEnumerableProperty(exception as { [key: string]: unknown }, '__sentry_captured__', true);\n } catch (err) {\n // `exception` is a primitive, so we can't mark it seen\n }\n\n return false;\n}\n\n/**\n * Checks whether the given input is already an array, and if it isn't, wraps it in one.\n *\n * @param maybeArray Input to turn into an array, if necessary\n * @returns The input, if already an array, or an array with the input as the only element, if not\n */\nexport function arrayify(maybeArray: T | T[]): T[] {\n return Array.isArray(maybeArray) ? maybeArray : [maybeArray];\n}\n","/* eslint-disable @typescript-eslint/explicit-function-return-type */\n/* eslint-disable @typescript-eslint/typedef */\n/* eslint-disable @typescript-eslint/explicit-module-boundary-types */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { isThenable } from './is';\n\n/** SyncPromise internal states */\nconst enum States {\n /** Pending */\n PENDING = 0,\n /** Resolved / OK */\n RESOLVED = 1,\n /** Rejected / Error */\n REJECTED = 2,\n}\n\n// Overloads so we can call resolvedSyncPromise without arguments and generic argument\nexport function resolvedSyncPromise(): PromiseLike;\nexport function resolvedSyncPromise(value: T | PromiseLike): PromiseLike;\n\n/**\n * Creates a resolved sync promise.\n *\n * @param value the value to resolve the promise with\n * @returns the resolved sync promise\n */\nexport function resolvedSyncPromise(value?: T | PromiseLike): PromiseLike {\n return new SyncPromise(resolve => {\n resolve(value);\n });\n}\n\n/**\n * Creates a rejected sync promise.\n *\n * @param value the value to reject the promise with\n * @returns the rejected sync promise\n */\nexport function rejectedSyncPromise(reason?: any): PromiseLike {\n return new SyncPromise((_, reject) => {\n reject(reason);\n });\n}\n\n/**\n * Thenable class that behaves like a Promise and follows it's interface\n * but is not async internally\n */\nclass SyncPromise implements PromiseLike {\n private _state: States;\n private _handlers: Array<[boolean, (value: T) => void, (reason: any) => any]>;\n private _value: any;\n\n public constructor(\n executor: (resolve: (value?: T | PromiseLike | null) => void, reject: (reason?: any) => void) => void,\n ) {\n this._state = States.PENDING;\n this._handlers = [];\n\n try {\n executor(this._resolve, this._reject);\n } catch (e) {\n this._reject(e);\n }\n }\n\n /** JSDoc */\n public then(\n onfulfilled?: ((value: T) => TResult1 | PromiseLike) | null,\n onrejected?: ((reason: any) => TResult2 | PromiseLike) | null,\n ): PromiseLike {\n return new SyncPromise((resolve, reject) => {\n this._handlers.push([\n false,\n result => {\n if (!onfulfilled) {\n // TODO: ¯\\_(ツ)_/¯\n // TODO: FIXME\n resolve(result as any);\n } else {\n try {\n resolve(onfulfilled(result));\n } catch (e) {\n reject(e);\n }\n }\n },\n reason => {\n if (!onrejected) {\n reject(reason);\n } else {\n try {\n resolve(onrejected(reason));\n } catch (e) {\n reject(e);\n }\n }\n },\n ]);\n this._executeHandlers();\n });\n }\n\n /** JSDoc */\n public catch(\n onrejected?: ((reason: any) => TResult | PromiseLike) | null,\n ): PromiseLike {\n return this.then(val => val, onrejected);\n }\n\n /** JSDoc */\n public finally(onfinally?: (() => void) | null): PromiseLike {\n return new SyncPromise((resolve, reject) => {\n let val: TResult | any;\n let isRejected: boolean;\n\n return this.then(\n value => {\n isRejected = false;\n val = value;\n if (onfinally) {\n onfinally();\n }\n },\n reason => {\n isRejected = true;\n val = reason;\n if (onfinally) {\n onfinally();\n }\n },\n ).then(() => {\n if (isRejected) {\n reject(val);\n return;\n }\n\n resolve(val as unknown as any);\n });\n });\n }\n\n /** JSDoc */\n private readonly _resolve = (value?: T | PromiseLike | null) => {\n this._setResult(States.RESOLVED, value);\n };\n\n /** JSDoc */\n private readonly _reject = (reason?: any) => {\n this._setResult(States.REJECTED, reason);\n };\n\n /** JSDoc */\n private readonly _setResult = (state: States, value?: T | PromiseLike | any) => {\n if (this._state !== States.PENDING) {\n return;\n }\n\n if (isThenable(value)) {\n void (value as PromiseLike).then(this._resolve, this._reject);\n return;\n }\n\n this._state = state;\n this._value = value;\n\n this._executeHandlers();\n };\n\n /** JSDoc */\n private readonly _executeHandlers = () => {\n if (this._state === States.PENDING) {\n return;\n }\n\n const cachedHandlers = this._handlers.slice();\n this._handlers = [];\n\n cachedHandlers.forEach(handler => {\n if (handler[0]) {\n return;\n }\n\n if (this._state === States.RESOLVED) {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n handler[1](this._value as unknown as any);\n }\n\n if (this._state === States.REJECTED) {\n handler[2](this._value);\n }\n\n handler[0] = true;\n });\n };\n}\n\nexport { SyncPromise };\n","import type { Event, EventHint, EventProcessor } from '@sentry/types';\nimport { SyncPromise, getGlobalSingleton, isThenable, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from './debug-build';\n\n/**\n * Returns the global event processors.\n * @deprecated Global event processors will be removed in v8.\n */\nexport function getGlobalEventProcessors(): EventProcessor[] {\n return getGlobalSingleton('globalEventProcessors', () => []);\n}\n\n/**\n * Add a EventProcessor to be kept globally.\n * @deprecated Use `addEventProcessor` instead. Global event processors will be removed in v8.\n */\nexport function addGlobalEventProcessor(callback: EventProcessor): void {\n // eslint-disable-next-line deprecation/deprecation\n getGlobalEventProcessors().push(callback);\n}\n\n/**\n * Process an array of event processors, returning the processed event (or `null` if the event was dropped).\n */\nexport function notifyEventProcessors(\n processors: EventProcessor[],\n event: Event | null,\n hint: EventHint,\n index: number = 0,\n): PromiseLike {\n return new SyncPromise((resolve, reject) => {\n const processor = processors[index];\n if (event === null || typeof processor !== 'function') {\n resolve(event);\n } else {\n const result = processor({ ...event }, hint) as Event | null;\n\n DEBUG_BUILD && processor.id && result === null && logger.log(`Event processor \"${processor.id}\" dropped event`);\n\n if (isThenable(result)) {\n void result\n .then(final => notifyEventProcessors(processors, final, hint, index + 1).then(resolve))\n .then(null, reject);\n } else {\n void notifyEventProcessors(processors, result, hint, index + 1)\n .then(resolve)\n .then(null, reject);\n }\n }\n });\n}\n","import { GLOBAL_OBJ } from './worldwide';\n\nconst ONE_SECOND_IN_MS = 1000;\n\n/**\n * A partial definition of the [Performance Web API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Performance}\n * for accessing a high-resolution monotonic clock.\n */\ninterface Performance {\n /**\n * The millisecond timestamp at which measurement began, measured in Unix time.\n */\n timeOrigin: number;\n /**\n * Returns the current millisecond timestamp, where 0 represents the start of measurement.\n */\n now(): number;\n}\n\n/**\n * Returns a timestamp in seconds since the UNIX epoch using the Date API.\n *\n * TODO(v8): Return type should be rounded.\n */\nexport function dateTimestampInSeconds(): number {\n return Date.now() / ONE_SECOND_IN_MS;\n}\n\n/**\n * Returns a wrapper around the native Performance API browser implementation, or undefined for browsers that do not\n * support the API.\n *\n * Wrapping the native API works around differences in behavior from different browsers.\n */\nfunction createUnixTimestampInSecondsFunc(): () => number {\n const { performance } = GLOBAL_OBJ as typeof GLOBAL_OBJ & { performance?: Performance };\n if (!performance || !performance.now) {\n return dateTimestampInSeconds;\n }\n\n // Some browser and environments don't have a timeOrigin, so we fallback to\n // using Date.now() to compute the starting time.\n const approxStartingTimeOrigin = Date.now() - performance.now();\n const timeOrigin = performance.timeOrigin == undefined ? approxStartingTimeOrigin : performance.timeOrigin;\n\n // performance.now() is a monotonic clock, which means it starts at 0 when the process begins. To get the current\n // wall clock time (actual UNIX timestamp), we need to add the starting time origin and the current time elapsed.\n //\n // TODO: This does not account for the case where the monotonic clock that powers performance.now() drifts from the\n // wall clock time, which causes the returned timestamp to be inaccurate. We should investigate how to detect and\n // correct for this.\n // See: https://github.com/getsentry/sentry-javascript/issues/2590\n // See: https://github.com/mdn/content/issues/4713\n // See: https://dev.to/noamr/when-a-millisecond-is-not-a-millisecond-3h6\n return () => {\n return (timeOrigin + performance.now()) / ONE_SECOND_IN_MS;\n };\n}\n\n/**\n * Returns a timestamp in seconds since the UNIX epoch using either the Performance or Date APIs, depending on the\n * availability of the Performance API.\n *\n * BUG: Note that because of how browsers implement the Performance API, the clock might stop when the computer is\n * asleep. This creates a skew between `dateTimestampInSeconds` and `timestampInSeconds`. The\n * skew can grow to arbitrary amounts like days, weeks or months.\n * See https://github.com/getsentry/sentry-javascript/issues/2590.\n */\nexport const timestampInSeconds = createUnixTimestampInSecondsFunc();\n\n/**\n * Re-exported with an old name for backwards-compatibility.\n * TODO (v8): Remove this\n *\n * @deprecated Use `timestampInSeconds` instead.\n */\nexport const timestampWithMs = timestampInSeconds;\n\n/**\n * Internal helper to store what is the source of browserPerformanceTimeOrigin below. For debugging only.\n */\nexport let _browserPerformanceTimeOriginMode: string;\n\n/**\n * The number of milliseconds since the UNIX epoch. This value is only usable in a browser, and only when the\n * performance API is available.\n */\nexport const browserPerformanceTimeOrigin = ((): number | undefined => {\n // Unfortunately browsers may report an inaccurate time origin data, through either performance.timeOrigin or\n // performance.timing.navigationStart, which results in poor results in performance data. We only treat time origin\n // data as reliable if they are within a reasonable threshold of the current time.\n\n const { performance } = GLOBAL_OBJ as typeof GLOBAL_OBJ & Window;\n if (!performance || !performance.now) {\n _browserPerformanceTimeOriginMode = 'none';\n return undefined;\n }\n\n const threshold = 3600 * 1000;\n const performanceNow = performance.now();\n const dateNow = Date.now();\n\n // if timeOrigin isn't available set delta to threshold so it isn't used\n const timeOriginDelta = performance.timeOrigin\n ? Math.abs(performance.timeOrigin + performanceNow - dateNow)\n : threshold;\n const timeOriginIsReliable = timeOriginDelta < threshold;\n\n // While performance.timing.navigationStart is deprecated in favor of performance.timeOrigin, performance.timeOrigin\n // is not as widely supported. Namely, performance.timeOrigin is undefined in Safari as of writing.\n // Also as of writing, performance.timing is not available in Web Workers in mainstream browsers, so it is not always\n // a valid fallback. In the absence of an initial time provided by the browser, fallback to the current time from the\n // Date API.\n // eslint-disable-next-line deprecation/deprecation\n const navigationStart = performance.timing && performance.timing.navigationStart;\n const hasNavigationStart = typeof navigationStart === 'number';\n // if navigationStart isn't available set delta to threshold so it isn't used\n const navigationStartDelta = hasNavigationStart ? Math.abs(navigationStart + performanceNow - dateNow) : threshold;\n const navigationStartIsReliable = navigationStartDelta < threshold;\n\n if (timeOriginIsReliable || navigationStartIsReliable) {\n // Use the more reliable time origin\n if (timeOriginDelta <= navigationStartDelta) {\n _browserPerformanceTimeOriginMode = 'timeOrigin';\n return performance.timeOrigin;\n } else {\n _browserPerformanceTimeOriginMode = 'navigationStart';\n return navigationStart;\n }\n }\n\n // Either both timeOrigin and navigationStart are skewed or neither is available, fallback to Date.\n _browserPerformanceTimeOriginMode = 'dateNow';\n return dateNow;\n})();\n","export const DEFAULT_ENVIRONMENT = 'production';\n","import type { SerializedSession, Session, SessionContext, SessionStatus } from '@sentry/types';\nimport { dropUndefinedKeys, timestampInSeconds, uuid4 } from '@sentry/utils';\n/**\n * Creates a new `Session` object by setting certain default parameters. If optional @param context\n * is passed, the passed properties are applied to the session object.\n *\n * @param context (optional) additional properties to be applied to the returned session object\n *\n * @returns a new `Session` object\n */\nexport function makeSession(context?: Omit): Session {\n // Both timestamp and started are in seconds since the UNIX epoch.\n const startingTime = timestampInSeconds();\n\n const session: Session = {\n sid: uuid4(),\n init: true,\n timestamp: startingTime,\n started: startingTime,\n duration: 0,\n status: 'ok',\n errors: 0,\n ignoreDuration: false,\n toJSON: () => sessionToJSON(session),\n };\n\n if (context) {\n updateSession(session, context);\n }\n\n return session;\n}\n\n/**\n * Updates a session object with the properties passed in the context.\n *\n * Note that this function mutates the passed object and returns void.\n * (Had to do this instead of returning a new and updated session because closing and sending a session\n * makes an update to the session after it was passed to the sending logic.\n * @see BaseClient.captureSession )\n *\n * @param session the `Session` to update\n * @param context the `SessionContext` holding the properties that should be updated in @param session\n */\n// eslint-disable-next-line complexity\nexport function updateSession(session: Session, context: SessionContext = {}): void {\n if (context.user) {\n if (!session.ipAddress && context.user.ip_address) {\n session.ipAddress = context.user.ip_address;\n }\n\n if (!session.did && !context.did) {\n session.did = context.user.id || context.user.email || context.user.username;\n }\n }\n\n session.timestamp = context.timestamp || timestampInSeconds();\n\n if (context.abnormal_mechanism) {\n session.abnormal_mechanism = context.abnormal_mechanism;\n }\n\n if (context.ignoreDuration) {\n session.ignoreDuration = context.ignoreDuration;\n }\n if (context.sid) {\n // Good enough uuid validation. — Kamil\n session.sid = context.sid.length === 32 ? context.sid : uuid4();\n }\n if (context.init !== undefined) {\n session.init = context.init;\n }\n if (!session.did && context.did) {\n session.did = `${context.did}`;\n }\n if (typeof context.started === 'number') {\n session.started = context.started;\n }\n if (session.ignoreDuration) {\n session.duration = undefined;\n } else if (typeof context.duration === 'number') {\n session.duration = context.duration;\n } else {\n const duration = session.timestamp - session.started;\n session.duration = duration >= 0 ? duration : 0;\n }\n if (context.release) {\n session.release = context.release;\n }\n if (context.environment) {\n session.environment = context.environment;\n }\n if (!session.ipAddress && context.ipAddress) {\n session.ipAddress = context.ipAddress;\n }\n if (!session.userAgent && context.userAgent) {\n session.userAgent = context.userAgent;\n }\n if (typeof context.errors === 'number') {\n session.errors = context.errors;\n }\n if (context.status) {\n session.status = context.status;\n }\n}\n\n/**\n * Closes a session by setting its status and updating the session object with it.\n * Internally calls `updateSession` to update the passed session object.\n *\n * Note that this function mutates the passed session (@see updateSession for explanation).\n *\n * @param session the `Session` object to be closed\n * @param status the `SessionStatus` with which the session was closed. If you don't pass a status,\n * this function will keep the previously set status, unless it was `'ok'` in which case\n * it is changed to `'exited'`.\n */\nexport function closeSession(session: Session, status?: Exclude): void {\n let context = {};\n if (status) {\n context = { status };\n } else if (session.status === 'ok') {\n context = { status: 'exited' };\n }\n\n updateSession(session, context);\n}\n\n/**\n * Serializes a passed session object to a JSON object with a slightly different structure.\n * This is necessary because the Sentry backend requires a slightly different schema of a session\n * than the one the JS SDKs use internally.\n *\n * @param session the session to be converted\n *\n * @returns a JSON object of the passed session\n */\nfunction sessionToJSON(session: Session): SerializedSession {\n return dropUndefinedKeys({\n sid: `${session.sid}`,\n init: session.init,\n // Make sure that sec is converted to ms for date constructor\n started: new Date(session.started * 1000).toISOString(),\n timestamp: new Date(session.timestamp * 1000).toISOString(),\n status: session.status,\n errors: session.errors,\n did: typeof session.did === 'number' || typeof session.did === 'string' ? `${session.did}` : undefined,\n duration: session.duration,\n abnormal_mechanism: session.abnormal_mechanism,\n attrs: {\n release: session.release,\n environment: session.environment,\n ip_address: session.ipAddress,\n user_agent: session.userAgent,\n },\n });\n}\n","import type { StackFrame, StackLineParser, StackParser } from '@sentry/types';\n\nimport type { GetModuleFn } from './node-stack-trace';\nimport { filenameIsInApp, node } from './node-stack-trace';\n\nexport { filenameIsInApp };\n\nconst STACKTRACE_FRAME_LIMIT = 50;\n// Used to sanitize webpack (error: *) wrapped stack errors\nconst WEBPACK_ERROR_REGEXP = /\\(error: (.*)\\)/;\nconst STRIP_FRAME_REGEXP = /captureMessage|captureException/;\n\n/**\n * Creates a stack parser with the supplied line parsers\n *\n * StackFrames are returned in the correct order for Sentry Exception\n * frames and with Sentry SDK internal frames removed from the top and bottom\n *\n */\nexport function createStackParser(...parsers: StackLineParser[]): StackParser {\n const sortedParsers = parsers.sort((a, b) => a[0] - b[0]).map(p => p[1]);\n\n return (stack: string, skipFirst: number = 0): StackFrame[] => {\n const frames: StackFrame[] = [];\n const lines = stack.split('\\n');\n\n for (let i = skipFirst; i < lines.length; i++) {\n const line = lines[i];\n // Ignore lines over 1kb as they are unlikely to be stack frames.\n // Many of the regular expressions use backtracking which results in run time that increases exponentially with\n // input size. Huge strings can result in hangs/Denial of Service:\n // https://github.com/getsentry/sentry-javascript/issues/2286\n if (line.length > 1024) {\n continue;\n }\n\n // https://github.com/getsentry/sentry-javascript/issues/5459\n // Remove webpack (error: *) wrappers\n const cleanedLine = WEBPACK_ERROR_REGEXP.test(line) ? line.replace(WEBPACK_ERROR_REGEXP, '$1') : line;\n\n // https://github.com/getsentry/sentry-javascript/issues/7813\n // Skip Error: lines\n if (cleanedLine.match(/\\S*Error: /)) {\n continue;\n }\n\n for (const parser of sortedParsers) {\n const frame = parser(cleanedLine);\n\n if (frame) {\n frames.push(frame);\n break;\n }\n }\n\n if (frames.length >= STACKTRACE_FRAME_LIMIT) {\n break;\n }\n }\n\n return stripSentryFramesAndReverse(frames);\n };\n}\n\n/**\n * Gets a stack parser implementation from Options.stackParser\n * @see Options\n *\n * If options contains an array of line parsers, it is converted into a parser\n */\nexport function stackParserFromStackParserOptions(stackParser: StackParser | StackLineParser[]): StackParser {\n if (Array.isArray(stackParser)) {\n return createStackParser(...stackParser);\n }\n return stackParser;\n}\n\n/**\n * Removes Sentry frames from the top and bottom of the stack if present and enforces a limit of max number of frames.\n * Assumes stack input is ordered from top to bottom and returns the reverse representation so call site of the\n * function that caused the crash is the last frame in the array.\n * @hidden\n */\nexport function stripSentryFramesAndReverse(stack: ReadonlyArray): StackFrame[] {\n if (!stack.length) {\n return [];\n }\n\n const localStack = Array.from(stack);\n\n // If stack starts with one of our API calls, remove it (starts, meaning it's the top of the stack - aka last call)\n if (/sentryWrapped/.test(localStack[localStack.length - 1].function || '')) {\n localStack.pop();\n }\n\n // Reversing in the middle of the procedure allows us to just pop the values off the stack\n localStack.reverse();\n\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 if (STRIP_FRAME_REGEXP.test(localStack[localStack.length - 1].function || '')) {\n localStack.pop();\n\n // When using synthetic events, we will have a 2 levels deep stack, as `new Error('Sentry syntheticException')`\n // is produced within the hub itself, making it:\n //\n // Sentry.captureException()\n // getCurrentHub().captureException()\n //\n // instead of just the top `Sentry` call itself.\n // This forces us to possibly strip an additional frame in the exact same was as above.\n if (STRIP_FRAME_REGEXP.test(localStack[localStack.length - 1].function || '')) {\n localStack.pop();\n }\n }\n\n return localStack.slice(0, STACKTRACE_FRAME_LIMIT).map(frame => ({\n ...frame,\n filename: frame.filename || localStack[localStack.length - 1].filename,\n function: frame.function || '?',\n }));\n}\n\nconst defaultFunctionName = '';\n\n/**\n * Safely extract function name from itself\n */\nexport function getFunctionName(fn: unknown): string {\n try {\n if (!fn || typeof fn !== 'function') {\n return defaultFunctionName;\n }\n return fn.name || defaultFunctionName;\n } catch (e) {\n // Just accessing custom props in some Selenium environments\n // can cause a \"Permission denied\" exception (see raven-js#495).\n return defaultFunctionName;\n }\n}\n\n/**\n * Node.js stack line parser\n *\n * This is in @sentry/utils so it can be used from the Electron SDK in the browser for when `nodeIntegration == true`.\n * This allows it to be used without referencing or importing any node specific code which causes bundlers to complain\n */\nexport function nodeStackLineParser(getModule?: GetModuleFn): StackLineParser {\n return [90, node(getModule)];\n}\n","import type { Primitive } from '@sentry/types';\n\nimport { isNaN, isSyntheticEvent, isVueViewModel } from './is';\nimport type { MemoFunc } from './memo';\nimport { memoBuilder } from './memo';\nimport { convertToPlainObject } from './object';\nimport { getFunctionName } from './stacktrace';\n\ntype Prototype = { constructor: (...args: unknown[]) => unknown };\n// This is a hack to placate TS, relying on the fact that technically, arrays are objects with integer keys. Normally we\n// think of those keys as actual numbers, but `arr['0']` turns out to work just as well as `arr[0]`, and doing it this\n// way lets us use a single type in the places where behave as if we are only dealing with objects, even if some of them\n// might be arrays.\ntype ObjOrArray = { [key: string]: T };\n\n/**\n * Recursively normalizes the given object.\n *\n * - Creates a copy to prevent original input mutation\n * - Skips non-enumerable properties\n * - When stringifying, calls `toJSON` if implemented\n * - Removes circular references\n * - Translates non-serializable values (`undefined`/`NaN`/functions) to serializable format\n * - Translates known global objects/classes to a string representations\n * - Takes care of `Error` object serialization\n * - Optionally limits depth of final output\n * - Optionally limits number of properties/elements included in any single object/array\n *\n * @param input The object to be normalized.\n * @param depth The max depth to which to normalize the object. (Anything deeper stringified whole.)\n * @param maxProperties The max number of elements or properties to be included in any single array or\n * object in the normallized output.\n * @returns A normalized version of the object, or `\"**non-serializable**\"` if any errors are thrown during normalization.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function normalize(input: unknown, depth: number = 100, maxProperties: number = +Infinity): any {\n try {\n // since we're at the outermost level, we don't provide a key\n return visit('', input, depth, maxProperties);\n } catch (err) {\n return { ERROR: `**non-serializable** (${err})` };\n }\n}\n\n/** JSDoc */\nexport function normalizeToSize(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n object: { [key: string]: any },\n // Default Node.js REPL depth\n depth: number = 3,\n // 100kB, as 200kB is max payload size, so half sounds reasonable\n maxSize: number = 100 * 1024,\n): T {\n const normalized = normalize(object, depth);\n\n if (jsonSize(normalized) > maxSize) {\n return normalizeToSize(object, depth - 1, maxSize);\n }\n\n return normalized as T;\n}\n\n/**\n * Visits a node to perform normalization on it\n *\n * @param key The key corresponding to the given node\n * @param value The node to be visited\n * @param depth Optional number indicating the maximum recursion depth\n * @param maxProperties Optional maximum number of properties/elements included in any single object/array\n * @param memo Optional Memo class handling decycling\n */\nfunction visit(\n key: string,\n value: unknown,\n depth: number = +Infinity,\n maxProperties: number = +Infinity,\n memo: MemoFunc = memoBuilder(),\n): Primitive | ObjOrArray {\n const [memoize, unmemoize] = memo;\n\n // Get the simple cases out of the way first\n if (\n value == null || // this matches null and undefined -> eqeq not eqeqeq\n (['number', 'boolean', 'string'].includes(typeof value) && !isNaN(value))\n ) {\n return value as Primitive;\n }\n\n const stringified = stringifyValue(key, value);\n\n // Anything we could potentially dig into more (objects or arrays) will have come back as `\"[object XXXX]\"`.\n // Everything else will have already been serialized, so if we don't see that pattern, we're done.\n if (!stringified.startsWith('[object ')) {\n return stringified;\n }\n\n // From here on, we can assert that `value` is either an object or an array.\n\n // Do not normalize objects that we know have already been normalized. As a general rule, the\n // \"__sentry_skip_normalization__\" property should only be used sparingly and only should only be set on objects that\n // have already been normalized.\n if ((value as ObjOrArray)['__sentry_skip_normalization__']) {\n return value as ObjOrArray;\n }\n\n // We can set `__sentry_override_normalization_depth__` on an object to ensure that from there\n // We keep a certain amount of depth.\n // This should be used sparingly, e.g. we use it for the redux integration to ensure we get a certain amount of state.\n const remainingDepth =\n typeof (value as ObjOrArray)['__sentry_override_normalization_depth__'] === 'number'\n ? ((value as ObjOrArray)['__sentry_override_normalization_depth__'] as number)\n : depth;\n\n // We're also done if we've reached the max depth\n if (remainingDepth === 0) {\n // At this point we know `serialized` is a string of the form `\"[object XXXX]\"`. Clean it up so it's just `\"[XXXX]\"`.\n return stringified.replace('object ', '');\n }\n\n // If we've already visited this branch, bail out, as it's circular reference. If not, note that we're seeing it now.\n if (memoize(value)) {\n return '[Circular ~]';\n }\n\n // If the value has a `toJSON` method, we call it to extract more information\n const valueWithToJSON = value as unknown & { toJSON?: () => unknown };\n if (valueWithToJSON && typeof valueWithToJSON.toJSON === 'function') {\n try {\n const jsonValue = valueWithToJSON.toJSON();\n // We need to normalize the return value of `.toJSON()` in case it has circular references\n return visit('', jsonValue, remainingDepth - 1, maxProperties, memo);\n } catch (err) {\n // pass (The built-in `toJSON` failed, but we can still try to do it ourselves)\n }\n }\n\n // At this point we know we either have an object or an array, we haven't seen it before, and we're going to recurse\n // because we haven't yet reached the max depth. Create an accumulator to hold the results of visiting each\n // property/entry, and keep track of the number of items we add to it.\n const normalized = (Array.isArray(value) ? [] : {}) as ObjOrArray;\n let numAdded = 0;\n\n // Before we begin, convert`Error` and`Event` instances into plain objects, since some of each of their relevant\n // properties are non-enumerable and otherwise would get missed.\n const visitable = convertToPlainObject(value as ObjOrArray);\n\n for (const visitKey in visitable) {\n // Avoid iterating over fields in the prototype if they've somehow been exposed to enumeration.\n if (!Object.prototype.hasOwnProperty.call(visitable, visitKey)) {\n continue;\n }\n\n if (numAdded >= maxProperties) {\n normalized[visitKey] = '[MaxProperties ~]';\n break;\n }\n\n // Recursively visit all the child nodes\n const visitValue = visitable[visitKey];\n normalized[visitKey] = visit(visitKey, visitValue, remainingDepth - 1, maxProperties, memo);\n\n numAdded++;\n }\n\n // Once we've visited all the branches, remove the parent from memo storage\n unmemoize(value);\n\n // Return accumulated values\n return normalized;\n}\n\n/**\n * @deprecated This export will be removed in v8.\n */\nexport { visit as walk };\n\n/* eslint-disable complexity */\n/**\n * Stringify the given value. Handles various known special values and types.\n *\n * Not meant to be used on simple primitives which already have a string representation, as it will, for example, turn\n * the number 1231 into \"[Object Number]\", nor on `null`, as it will throw.\n *\n * @param value The value to stringify\n * @returns A stringified representation of the given value\n */\nfunction stringifyValue(\n key: unknown,\n // this type is a tiny bit of a cheat, since this function does handle NaN (which is technically a number), but for\n // our internal use, it'll do\n value: Exclude,\n): string {\n try {\n if (key === 'domain' && value && typeof value === 'object' && (value as { _events: unknown })._events) {\n return '[Domain]';\n }\n\n if (key === 'domainEmitter') {\n return '[DomainEmitter]';\n }\n\n // It's safe to use `global`, `window`, and `document` here in this manner, as we are asserting using `typeof` first\n // which won't throw if they are not present.\n\n if (typeof global !== 'undefined' && value === global) {\n return '[Global]';\n }\n\n // eslint-disable-next-line no-restricted-globals\n if (typeof window !== 'undefined' && value === window) {\n return '[Window]';\n }\n\n // eslint-disable-next-line no-restricted-globals\n if (typeof document !== 'undefined' && value === document) {\n return '[Document]';\n }\n\n if (isVueViewModel(value)) {\n return '[VueViewModel]';\n }\n\n // React's SyntheticEvent thingy\n if (isSyntheticEvent(value)) {\n return '[SyntheticEvent]';\n }\n\n if (typeof value === 'number' && value !== value) {\n return '[NaN]';\n }\n\n if (typeof value === 'function') {\n return `[Function: ${getFunctionName(value)}]`;\n }\n\n if (typeof value === 'symbol') {\n return `[${String(value)}]`;\n }\n\n // stringified BigInts are indistinguishable from regular numbers, so we need to label them to avoid confusion\n if (typeof value === 'bigint') {\n return `[BigInt: ${String(value)}]`;\n }\n\n // Now that we've knocked out all the special cases and the primitives, all we have left are objects. Simply casting\n // them to strings means that instances of classes which haven't defined their `toStringTag` will just come out as\n // `\"[object Object]\"`. If we instead look at the constructor's name (which is the same as the name of the class),\n // we can make sure that only plain objects come out that way.\n const objName = getConstructorName(value);\n\n // Handle HTML Elements\n if (/^HTML(\\w*)Element$/.test(objName)) {\n return `[HTMLElement: ${objName}]`;\n }\n\n return `[object ${objName}]`;\n } catch (err) {\n return `**non-serializable** (${err})`;\n }\n}\n/* eslint-enable complexity */\n\nfunction getConstructorName(value: unknown): string {\n const prototype: Prototype | null = Object.getPrototypeOf(value);\n\n return prototype ? prototype.constructor.name : 'null prototype';\n}\n\n/** Calculates bytes size of input string */\nfunction utf8Length(value: string): number {\n // eslint-disable-next-line no-bitwise\n return ~-encodeURI(value).split(/%..|./).length;\n}\n\n/** Calculates bytes size of input object */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction jsonSize(value: any): number {\n return utf8Length(JSON.stringify(value));\n}\n\n/**\n * Normalizes URLs in exceptions and stacktraces to a base path so Sentry can fingerprint\n * across platforms and working directory.\n *\n * @param url The URL to be normalized.\n * @param basePath The application base path.\n * @returns The normalized URL.\n */\nexport function normalizeUrlToBase(url: string, basePath: string): string {\n const escapedBase = basePath\n // Backslash to forward\n .replace(/\\\\/g, '/')\n // Escape RegExp special characters\n .replace(/[|\\\\{}()[\\]^$+*?.]/g, '\\\\$&');\n\n let newUrl = url;\n try {\n newUrl = decodeURI(url);\n } catch (_Oo) {\n // Sometime this breaks\n }\n return (\n newUrl\n .replace(/\\\\/g, '/')\n .replace(/webpack:\\/?/g, '') // Remove intermediate base path\n // eslint-disable-next-line @sentry-internal/sdk/no-regexp-constructor\n .replace(new RegExp(`(file://)?/*${escapedBase}/*`, 'ig'), 'app:///')\n );\n}\n","/* eslint-disable @typescript-eslint/no-unsafe-member-access */\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nexport type MemoFunc = [\n // memoize\n (obj: any) => boolean,\n // unmemoize\n (obj: any) => void,\n];\n\n/**\n * Helper to decycle json objects\n */\nexport function memoBuilder(): MemoFunc {\n const hasWeakSet = typeof WeakSet === 'function';\n const inner: any = hasWeakSet ? new WeakSet() : [];\n function memoize(obj: any): boolean {\n if (hasWeakSet) {\n if (inner.has(obj)) {\n return true;\n }\n inner.add(obj);\n return false;\n }\n // eslint-disable-next-line @typescript-eslint/prefer-for-of\n for (let i = 0; i < inner.length; i++) {\n const value = inner[i];\n if (value === obj) {\n return true;\n }\n }\n inner.push(obj);\n return false;\n }\n\n function unmemoize(obj: any): void {\n if (hasWeakSet) {\n inner.delete(obj);\n } else {\n for (let i = 0; i < inner.length; i++) {\n if (inner[i] === obj) {\n inner.splice(i, 1);\n break;\n }\n }\n }\n }\n return [memoize, unmemoize];\n}\n","import type { Span, SpanJSON, SpanTimeInput, TraceContext } from '@sentry/types';\nimport { dropUndefinedKeys, generateSentryTraceHeader, timestampInSeconds } from '@sentry/utils';\nimport type { Span as SpanClass } from '../tracing/span';\n\n// These are aligned with OpenTelemetry trace flags\nexport const TRACE_FLAG_NONE = 0x0;\nexport const TRACE_FLAG_SAMPLED = 0x1;\n\n/**\n * Convert a span to a trace context, which can be sent as the `trace` context in an event.\n */\nexport function spanToTraceContext(span: Span): TraceContext {\n const { spanId: span_id, traceId: trace_id } = span.spanContext();\n const { data, op, parent_span_id, status, tags, origin } = spanToJSON(span);\n\n return dropUndefinedKeys({\n data,\n op,\n parent_span_id,\n span_id,\n status,\n tags,\n trace_id,\n origin,\n });\n}\n\n/**\n * Convert a Span to a Sentry trace header.\n */\nexport function spanToTraceHeader(span: Span): string {\n const { traceId, spanId } = span.spanContext();\n const sampled = spanIsSampled(span);\n return generateSentryTraceHeader(traceId, spanId, sampled);\n}\n\n/**\n * Convert a span time input intp a timestamp in seconds.\n */\nexport function spanTimeInputToSeconds(input: SpanTimeInput | undefined): number {\n if (typeof input === 'number') {\n return ensureTimestampInSeconds(input);\n }\n\n if (Array.isArray(input)) {\n // See {@link HrTime} for the array-based time format\n return input[0] + input[1] / 1e9;\n }\n\n if (input instanceof Date) {\n return ensureTimestampInSeconds(input.getTime());\n }\n\n return timestampInSeconds();\n}\n\n/**\n * Converts a timestamp to second, if it was in milliseconds, or keeps it as second.\n */\nfunction ensureTimestampInSeconds(timestamp: number): number {\n const isMs = timestamp > 9999999999;\n return isMs ? timestamp / 1000 : timestamp;\n}\n\n/**\n * Convert a span to a JSON representation.\n * Note that all fields returned here are optional and need to be guarded against.\n *\n * Note: Because of this, we currently have a circular type dependency (which we opted out of in package.json).\n * This is not avoidable as we need `spanToJSON` in `spanUtils.ts`, which in turn is needed by `span.ts` for backwards compatibility.\n * And `spanToJSON` needs the Span class from `span.ts` to check here.\n * TODO v8: When we remove the deprecated stuff from `span.ts`, we can remove the circular dependency again.\n */\nexport function spanToJSON(span: Span): Partial {\n if (spanIsSpanClass(span)) {\n return span.getSpanJSON();\n }\n\n // Fallback: We also check for `.toJSON()` here...\n // eslint-disable-next-line deprecation/deprecation\n if (typeof span.toJSON === 'function') {\n // eslint-disable-next-line deprecation/deprecation\n return span.toJSON();\n }\n\n return {};\n}\n\n/**\n * Sadly, due to circular dependency checks we cannot actually import the Span class here and check for instanceof.\n * :( So instead we approximate this by checking if it has the `getSpanJSON` method.\n */\nfunction spanIsSpanClass(span: Span): span is SpanClass {\n return typeof (span as SpanClass).getSpanJSON === 'function';\n}\n\n/**\n * Returns true if a span is sampled.\n * In most cases, you should just use `span.isRecording()` instead.\n * However, this has a slightly different semantic, as it also returns false if the span is finished.\n * So in the case where this distinction is important, use this method.\n */\nexport function spanIsSampled(span: Span): boolean {\n // We align our trace flags with the ones OpenTelemetry use\n // So we also check for sampled the same way they do.\n const { traceFlags } = span.spanContext();\n // eslint-disable-next-line no-bitwise\n return Boolean(traceFlags & TRACE_FLAG_SAMPLED);\n}\n","import type {\n CaptureContext,\n Client,\n ClientOptions,\n Event,\n EventHint,\n Scope as ScopeInterface,\n ScopeContext,\n StackFrame,\n StackParser,\n} from '@sentry/types';\nimport { GLOBAL_OBJ, addExceptionMechanism, dateTimestampInSeconds, normalize, truncate, uuid4 } from '@sentry/utils';\n\nimport { DEFAULT_ENVIRONMENT } from '../constants';\nimport { getGlobalEventProcessors, notifyEventProcessors } from '../eventProcessors';\nimport { Scope, getGlobalScope } from '../scope';\nimport { applyScopeDataToEvent, mergeScopeData } from './applyScopeDataToEvent';\nimport { spanToJSON } from './spanUtils';\n\n/**\n * This type makes sure that we get either a CaptureContext, OR an EventHint.\n * It does not allow mixing them, which could lead to unexpected outcomes, e.g. this is disallowed:\n * { user: { id: '123' }, mechanism: { handled: false } }\n */\nexport type ExclusiveEventHintOrCaptureContext =\n | (CaptureContext & Partial<{ [key in keyof EventHint]: never }>)\n | (EventHint & Partial<{ [key in keyof ScopeContext]: never }>);\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 * Note: This also triggers callbacks for `addGlobalEventProcessor`, but not `beforeSend`.\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 * @hidden\n */\nexport function prepareEvent(\n options: ClientOptions,\n event: Event,\n hint: EventHint,\n scope?: Scope,\n client?: Client,\n isolationScope?: Scope,\n): PromiseLike {\n const { normalizeDepth = 3, normalizeMaxBreadth = 1_000 } = options;\n const prepared: Event = {\n ...event,\n event_id: event.event_id || hint.event_id || uuid4(),\n timestamp: event.timestamp || dateTimestampInSeconds(),\n };\n const integrations = hint.integrations || options.integrations.map(i => i.name);\n\n applyClientOptions(prepared, options);\n applyIntegrationsMetadata(prepared, integrations);\n\n // Only put debug IDs onto frames for error events.\n if (event.type === undefined) {\n applyDebugIds(prepared, options.stackParser);\n }\n\n // 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 const finalScope = getFinalScope(scope, hint.captureContext);\n\n if (hint.mechanism) {\n addExceptionMechanism(prepared, hint.mechanism);\n }\n\n const clientEventProcessors = client && client.getEventProcessors ? client.getEventProcessors() : [];\n\n // This should be the last thing called, since we want that\n // {@link Hub.addEventProcessor} gets the finished prepared event.\n // Merge scope data together\n const data = getGlobalScope().getScopeData();\n\n if (isolationScope) {\n const isolationData = isolationScope.getScopeData();\n mergeScopeData(data, isolationData);\n }\n\n if (finalScope) {\n const finalScopeData = finalScope.getScopeData();\n mergeScopeData(data, finalScopeData);\n }\n\n const attachments = [...(hint.attachments || []), ...data.attachments];\n if (attachments.length) {\n hint.attachments = attachments;\n }\n\n applyScopeDataToEvent(prepared, data);\n\n // TODO (v8): Update this order to be: Global > Client > Scope\n const eventProcessors = [\n ...clientEventProcessors,\n // eslint-disable-next-line deprecation/deprecation\n ...getGlobalEventProcessors(),\n // Run scope event processors _after_ all other processors\n ...data.eventProcessors,\n ];\n\n const result = notifyEventProcessors(eventProcessors, prepared, hint);\n\n return result.then(evt => {\n if (evt) {\n // We apply the debug_meta field only after all event processors have ran, so that if any event processors modified\n // file names (e.g.the RewriteFrames integration) the filename -> debug ID relationship isn't destroyed.\n // This should not cause any PII issues, since we're only moving data that is already on the event and not adding\n // any new data\n applyDebugMeta(evt);\n }\n\n if (typeof normalizeDepth === 'number' && normalizeDepth > 0) {\n return normalizeEvent(evt, normalizeDepth, normalizeMaxBreadth);\n }\n return evt;\n });\n}\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 */\nfunction applyClientOptions(event: Event, options: ClientOptions): void {\n const { environment, release, dist, maxValueLength = 250 } = options;\n\n if (!('environment' in event)) {\n event.environment = 'environment' in options ? environment : DEFAULT_ENVIRONMENT;\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 const exception = event.exception && event.exception.values && event.exception.values[0];\n if (exception && exception.value) {\n exception.value = truncate(exception.value, maxValueLength);\n }\n\n const request = event.request;\n if (request && request.url) {\n request.url = truncate(request.url, maxValueLength);\n }\n}\n\nconst debugIdStackParserCache = new WeakMap>();\n\n/**\n * Puts debug IDs into the stack frames of an error event.\n */\nexport function applyDebugIds(event: Event, stackParser: StackParser): void {\n const debugIdMap = GLOBAL_OBJ._sentryDebugIds;\n\n if (!debugIdMap) {\n return;\n }\n\n let debugIdStackFramesCache: Map;\n const cachedDebugIdStackFrameCache = debugIdStackParserCache.get(stackParser);\n if (cachedDebugIdStackFrameCache) {\n debugIdStackFramesCache = cachedDebugIdStackFrameCache;\n } else {\n debugIdStackFramesCache = new Map();\n debugIdStackParserCache.set(stackParser, debugIdStackFramesCache);\n }\n\n // Build a map of filename -> debug_id\n const filenameDebugIdMap = Object.keys(debugIdMap).reduce>((acc, debugIdStackTrace) => {\n let parsedStack: StackFrame[];\n const cachedParsedStack = debugIdStackFramesCache.get(debugIdStackTrace);\n if (cachedParsedStack) {\n parsedStack = cachedParsedStack;\n } else {\n parsedStack = stackParser(debugIdStackTrace);\n debugIdStackFramesCache.set(debugIdStackTrace, parsedStack);\n }\n\n for (let i = parsedStack.length - 1; i >= 0; i--) {\n const stackFrame = parsedStack[i];\n if (stackFrame.filename) {\n acc[stackFrame.filename] = debugIdMap[debugIdStackTrace];\n break;\n }\n }\n return acc;\n }, {});\n\n try {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n event!.exception!.values!.forEach(exception => {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n exception.stacktrace!.frames!.forEach(frame => {\n if (frame.filename) {\n frame.debug_id = filenameDebugIdMap[frame.filename];\n }\n });\n });\n } catch (e) {\n // To save bundle size we're just try catching here instead of checking for the existence of all the different objects.\n }\n}\n\n/**\n * Moves debug IDs from the stack frames of an error event into the debug_meta field.\n */\nexport function applyDebugMeta(event: Event): void {\n // Extract debug IDs and filenames from the stack frames on the event.\n const filenameDebugIdMap: Record = {};\n try {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n event.exception!.values!.forEach(exception => {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n exception.stacktrace!.frames!.forEach(frame => {\n if (frame.debug_id) {\n if (frame.abs_path) {\n filenameDebugIdMap[frame.abs_path] = frame.debug_id;\n } else if (frame.filename) {\n filenameDebugIdMap[frame.filename] = frame.debug_id;\n }\n delete frame.debug_id;\n }\n });\n });\n } catch (e) {\n // To save bundle size we're just try catching here instead of checking for the existence of all the different objects.\n }\n\n if (Object.keys(filenameDebugIdMap).length === 0) {\n return;\n }\n\n // Fill debug_meta information\n event.debug_meta = event.debug_meta || {};\n event.debug_meta.images = event.debug_meta.images || [];\n const images = event.debug_meta.images;\n Object.keys(filenameDebugIdMap).forEach(filename => {\n images.push({\n type: 'sourcemap',\n code_file: filename,\n debug_id: filenameDebugIdMap[filename],\n });\n });\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 */\nfunction applyIntegrationsMetadata(event: Event, integrationNames: string[]): void {\n if (integrationNames.length > 0) {\n event.sdk = event.sdk || {};\n event.sdk.integrations = [...(event.sdk.integrations || []), ...integrationNames];\n }\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 */\nfunction normalizeEvent(event: Event | null, depth: number, maxBreadth: number): Event | null {\n if (!event) {\n return null;\n }\n\n const normalized: Event = {\n ...event,\n ...(event.breadcrumbs && {\n breadcrumbs: event.breadcrumbs.map(b => ({\n ...b,\n ...(b.data && {\n data: normalize(b.data, depth, maxBreadth),\n }),\n })),\n }),\n ...(event.user && {\n user: normalize(event.user, depth, maxBreadth),\n }),\n ...(event.contexts && {\n contexts: normalize(event.contexts, depth, maxBreadth),\n }),\n ...(event.extra && {\n extra: normalize(event.extra, depth, maxBreadth),\n }),\n };\n\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 if (event.contexts && event.contexts.trace && normalized.contexts) {\n normalized.contexts.trace = event.contexts.trace;\n\n // event.contexts.trace.data may contain circular/dangerous data so we need to normalize it\n if (event.contexts.trace.data) {\n normalized.contexts.trace.data = normalize(event.contexts.trace.data, depth, maxBreadth);\n }\n }\n\n // event.spans[].data may contain circular/dangerous data so we need to normalize it\n if (event.spans) {\n normalized.spans = event.spans.map(span => {\n const data = spanToJSON(span).data;\n\n if (data) {\n // This is a bit weird, as we generally have `Span` instances here, but to be safe we do not assume so\n // eslint-disable-next-line deprecation/deprecation\n span.data = normalize(data, depth, maxBreadth);\n }\n\n return span;\n });\n }\n\n return normalized;\n}\n\nfunction getFinalScope(scope: Scope | undefined, captureContext: CaptureContext | undefined): Scope | undefined {\n if (!captureContext) {\n return scope;\n }\n\n const finalScope = scope ? scope.clone() : new Scope();\n finalScope.update(captureContext);\n return finalScope;\n}\n\n/**\n * Parse either an `EventHint` directly, or convert a `CaptureContext` to an `EventHint`.\n * This is used to allow to update method signatures that used to accept a `CaptureContext` but should now accept an `EventHint`.\n */\nexport function parseEventHintOrCaptureContext(\n hint: ExclusiveEventHintOrCaptureContext | undefined,\n): EventHint | undefined {\n if (!hint) {\n return undefined;\n }\n\n // If you pass a Scope or `() => Scope` as CaptureContext, we just return this as captureContext\n if (hintIsScopeOrFunction(hint)) {\n return { captureContext: hint };\n }\n\n if (hintIsScopeContext(hint)) {\n return {\n captureContext: hint,\n };\n }\n\n return hint;\n}\n\nfunction hintIsScopeOrFunction(\n hint: CaptureContext | EventHint,\n): hint is ScopeInterface | ((scope: ScopeInterface) => ScopeInterface) {\n return hint instanceof Scope || typeof hint === 'function';\n}\n\ntype ScopeContextProperty = keyof ScopeContext;\nconst captureContextKeys: readonly ScopeContextProperty[] = [\n 'user',\n 'level',\n 'extra',\n 'contexts',\n 'tags',\n 'fingerprint',\n 'requestSession',\n 'propagationContext',\n] as const;\n\nfunction hintIsScopeContext(hint: Partial | EventHint): hint is Partial {\n return Object.keys(hint).some(key => captureContextKeys.includes(key as ScopeContextProperty));\n}\n","/* eslint-disable max-lines */\nimport type {\n Attachment,\n Breadcrumb,\n CaptureContext,\n Client,\n Context,\n Contexts,\n Event,\n EventHint,\n EventProcessor,\n Extra,\n Extras,\n Primitive,\n PropagationContext,\n RequestSession,\n Scope as ScopeInterface,\n ScopeContext,\n ScopeData,\n Session,\n Severity,\n SeverityLevel,\n Span,\n Transaction,\n User,\n} from '@sentry/types';\nimport { dateTimestampInSeconds, isPlainObject, logger, uuid4 } from '@sentry/utils';\n\nimport { getGlobalEventProcessors, notifyEventProcessors } from './eventProcessors';\nimport { updateSession } from './session';\nimport { applyScopeDataToEvent } from './utils/applyScopeDataToEvent';\n\n/**\n * Default value for maximum number of breadcrumbs added to an event.\n */\nconst DEFAULT_MAX_BREADCRUMBS = 100;\n\n/**\n * The global scope is kept in this module.\n * When accessing this via `getGlobalScope()` we'll make sure to set one if none is currently present.\n */\nlet globalScope: ScopeInterface | undefined;\n\n/**\n * Holds additional event information. {@link Scope.applyToEvent} will be\n * called by the client before an event will be sent.\n */\nexport class Scope implements ScopeInterface {\n /** Flag if notifying is happening. */\n protected _notifyingListeners: boolean;\n\n /** Callback for client to receive scope changes. */\n protected _scopeListeners: Array<(scope: Scope) => void>;\n\n /** Callback list that will be called after {@link applyToEvent}. */\n protected _eventProcessors: EventProcessor[];\n\n /** Array of breadcrumbs. */\n protected _breadcrumbs: Breadcrumb[];\n\n /** User */\n protected _user: User;\n\n /** Tags */\n protected _tags: { [key: string]: Primitive };\n\n /** Extra */\n protected _extra: Extras;\n\n /** Contexts */\n protected _contexts: Contexts;\n\n /** Attachments */\n protected _attachments: Attachment[];\n\n /** Propagation Context for distributed tracing */\n protected _propagationContext: PropagationContext;\n\n /**\n * A place to stash data which is needed at some point in the SDK's event processing pipeline but which shouldn't get\n * sent to Sentry\n */\n protected _sdkProcessingMetadata: { [key: string]: unknown };\n\n /** Fingerprint */\n protected _fingerprint?: string[];\n\n /** Severity */\n // eslint-disable-next-line deprecation/deprecation\n protected _level?: Severity | SeverityLevel;\n\n /**\n * Transaction Name\n */\n protected _transactionName?: string;\n\n /** Span */\n protected _span?: Span;\n\n /** Session */\n protected _session?: Session;\n\n /** Request Mode Session Status */\n protected _requestSession?: RequestSession;\n\n /** The client on this scope */\n protected _client?: Client;\n\n // NOTE: Any field which gets added here should get added not only to the constructor but also to the `clone` method.\n\n public constructor() {\n this._notifyingListeners = false;\n this._scopeListeners = [];\n this._eventProcessors = [];\n this._breadcrumbs = [];\n this._attachments = [];\n this._user = {};\n this._tags = {};\n this._extra = {};\n this._contexts = {};\n this._sdkProcessingMetadata = {};\n this._propagationContext = generatePropagationContext();\n }\n\n /**\n * Inherit values from the parent scope.\n * @deprecated Use `scope.clone()` and `new Scope()` instead.\n */\n public static clone(scope?: Scope): Scope {\n return scope ? scope.clone() : new Scope();\n }\n\n /**\n * Clone this scope instance.\n */\n public clone(): Scope {\n const newScope = new Scope();\n newScope._breadcrumbs = [...this._breadcrumbs];\n newScope._tags = { ...this._tags };\n newScope._extra = { ...this._extra };\n newScope._contexts = { ...this._contexts };\n newScope._user = this._user;\n newScope._level = this._level;\n newScope._span = this._span;\n newScope._session = this._session;\n newScope._transactionName = this._transactionName;\n newScope._fingerprint = this._fingerprint;\n newScope._eventProcessors = [...this._eventProcessors];\n newScope._requestSession = this._requestSession;\n newScope._attachments = [...this._attachments];\n newScope._sdkProcessingMetadata = { ...this._sdkProcessingMetadata };\n newScope._propagationContext = { ...this._propagationContext };\n newScope._client = this._client;\n\n return newScope;\n }\n\n /** Update the client on the scope. */\n public setClient(client: Client | undefined): void {\n this._client = client;\n }\n\n /**\n * Get the client assigned to this scope.\n *\n * It is generally recommended to use the global function `Sentry.getClient()` instead, unless you know what you are doing.\n */\n public getClient(): Client | undefined {\n return this._client;\n }\n\n /**\n * Add internal on change listener. Used for sub SDKs that need to store the scope.\n * @hidden\n */\n public addScopeListener(callback: (scope: Scope) => void): void {\n this._scopeListeners.push(callback);\n }\n\n /**\n * @inheritDoc\n */\n public addEventProcessor(callback: EventProcessor): this {\n this._eventProcessors.push(callback);\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setUser(user: User | null): this {\n // If null is passed we want to unset everything, but still define keys,\n // so that later down in the pipeline any existing values are cleared.\n this._user = user || {\n email: undefined,\n id: undefined,\n ip_address: undefined,\n segment: undefined,\n username: undefined,\n };\n\n if (this._session) {\n updateSession(this._session, { user });\n }\n\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getUser(): User | undefined {\n return this._user;\n }\n\n /**\n * @inheritDoc\n */\n public getRequestSession(): RequestSession | undefined {\n return this._requestSession;\n }\n\n /**\n * @inheritDoc\n */\n public setRequestSession(requestSession?: RequestSession): this {\n this._requestSession = requestSession;\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setTags(tags: { [key: string]: Primitive }): this {\n this._tags = {\n ...this._tags,\n ...tags,\n };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setTag(key: string, value: Primitive): this {\n this._tags = { ...this._tags, [key]: value };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setExtras(extras: Extras): this {\n this._extra = {\n ...this._extra,\n ...extras,\n };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setExtra(key: string, extra: Extra): this {\n this._extra = { ...this._extra, [key]: extra };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setFingerprint(fingerprint: string[]): this {\n this._fingerprint = fingerprint;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setLevel(\n // eslint-disable-next-line deprecation/deprecation\n level: Severity | SeverityLevel,\n ): this {\n this._level = level;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * Sets the transaction name on the scope for future events.\n * @deprecated Use extra or tags instead.\n */\n public setTransactionName(name?: string): this {\n this._transactionName = name;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setContext(key: string, context: Context | null): this {\n if (context === null) {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete this._contexts[key];\n } else {\n this._contexts[key] = context;\n }\n\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * Sets the Span on the scope.\n * @param span Span\n * @deprecated Instead of setting a span on a scope, use `startSpan()`/`startSpanManual()` instead.\n */\n public setSpan(span?: Span): this {\n this._span = span;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * Returns the `Span` if there is one.\n * @deprecated Use `getActiveSpan()` instead.\n */\n public getSpan(): Span | undefined {\n return this._span;\n }\n\n /**\n * Returns the `Transaction` attached to the scope (if there is one).\n * @deprecated You should not rely on the transaction, but just use `startSpan()` APIs instead.\n */\n public getTransaction(): Transaction | undefined {\n // Often, this span (if it exists at all) will be a transaction, but it's not guaranteed to be. Regardless, it will\n // have a pointer to the currently-active transaction.\n const span = this._span;\n // Cannot replace with getRootSpan because getRootSpan returns a span, not a transaction\n // Also, this method will be removed anyway.\n // eslint-disable-next-line deprecation/deprecation\n return span && span.transaction;\n }\n\n /**\n * @inheritDoc\n */\n public setSession(session?: Session): this {\n if (!session) {\n delete this._session;\n } else {\n this._session = session;\n }\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getSession(): Session | undefined {\n return this._session;\n }\n\n /**\n * @inheritDoc\n */\n public update(captureContext?: CaptureContext): this {\n if (!captureContext) {\n return this;\n }\n\n const scopeToMerge = typeof captureContext === 'function' ? captureContext(this) : captureContext;\n\n if (scopeToMerge instanceof Scope) {\n const scopeData = scopeToMerge.getScopeData();\n\n this._tags = { ...this._tags, ...scopeData.tags };\n this._extra = { ...this._extra, ...scopeData.extra };\n this._contexts = { ...this._contexts, ...scopeData.contexts };\n if (scopeData.user && Object.keys(scopeData.user).length) {\n this._user = scopeData.user;\n }\n if (scopeData.level) {\n this._level = scopeData.level;\n }\n if (scopeData.fingerprint.length) {\n this._fingerprint = scopeData.fingerprint;\n }\n if (scopeToMerge.getRequestSession()) {\n this._requestSession = scopeToMerge.getRequestSession();\n }\n if (scopeData.propagationContext) {\n this._propagationContext = scopeData.propagationContext;\n }\n } else if (isPlainObject(scopeToMerge)) {\n const scopeContext = captureContext as ScopeContext;\n this._tags = { ...this._tags, ...scopeContext.tags };\n this._extra = { ...this._extra, ...scopeContext.extra };\n this._contexts = { ...this._contexts, ...scopeContext.contexts };\n if (scopeContext.user) {\n this._user = scopeContext.user;\n }\n if (scopeContext.level) {\n this._level = scopeContext.level;\n }\n if (scopeContext.fingerprint) {\n this._fingerprint = scopeContext.fingerprint;\n }\n if (scopeContext.requestSession) {\n this._requestSession = scopeContext.requestSession;\n }\n if (scopeContext.propagationContext) {\n this._propagationContext = scopeContext.propagationContext;\n }\n }\n\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public clear(): this {\n this._breadcrumbs = [];\n this._tags = {};\n this._extra = {};\n this._user = {};\n this._contexts = {};\n this._level = undefined;\n this._transactionName = undefined;\n this._fingerprint = undefined;\n this._requestSession = undefined;\n this._span = undefined;\n this._session = undefined;\n this._notifyScopeListeners();\n this._attachments = [];\n this._propagationContext = generatePropagationContext();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public addBreadcrumb(breadcrumb: Breadcrumb, maxBreadcrumbs?: number): this {\n const maxCrumbs = typeof maxBreadcrumbs === 'number' ? maxBreadcrumbs : DEFAULT_MAX_BREADCRUMBS;\n\n // No data has been changed, so don't notify scope listeners\n if (maxCrumbs <= 0) {\n return this;\n }\n\n const mergedBreadcrumb = {\n timestamp: dateTimestampInSeconds(),\n ...breadcrumb,\n };\n\n const breadcrumbs = this._breadcrumbs;\n breadcrumbs.push(mergedBreadcrumb);\n this._breadcrumbs = breadcrumbs.length > maxCrumbs ? breadcrumbs.slice(-maxCrumbs) : breadcrumbs;\n\n this._notifyScopeListeners();\n\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getLastBreadcrumb(): Breadcrumb | undefined {\n return this._breadcrumbs[this._breadcrumbs.length - 1];\n }\n\n /**\n * @inheritDoc\n */\n public clearBreadcrumbs(): this {\n this._breadcrumbs = [];\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public addAttachment(attachment: Attachment): this {\n this._attachments.push(attachment);\n return this;\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `getScopeData()` instead.\n */\n public getAttachments(): Attachment[] {\n const data = this.getScopeData();\n\n return data.attachments;\n }\n\n /**\n * @inheritDoc\n */\n public clearAttachments(): this {\n this._attachments = [];\n return this;\n }\n\n /** @inheritDoc */\n public getScopeData(): ScopeData {\n const {\n _breadcrumbs,\n _attachments,\n _contexts,\n _tags,\n _extra,\n _user,\n _level,\n _fingerprint,\n _eventProcessors,\n _propagationContext,\n _sdkProcessingMetadata,\n _transactionName,\n _span,\n } = this;\n\n return {\n breadcrumbs: _breadcrumbs,\n attachments: _attachments,\n contexts: _contexts,\n tags: _tags,\n extra: _extra,\n user: _user,\n level: _level,\n fingerprint: _fingerprint || [],\n eventProcessors: _eventProcessors,\n propagationContext: _propagationContext,\n sdkProcessingMetadata: _sdkProcessingMetadata,\n transactionName: _transactionName,\n span: _span,\n };\n }\n\n /**\n * Applies data from the scope to the event and runs all event processors on it.\n *\n * @param event Event\n * @param hint Object containing additional information about the original exception, for use by the event processors.\n * @hidden\n * @deprecated Use `applyScopeDataToEvent()` directly\n */\n public applyToEvent(\n event: Event,\n hint: EventHint = {},\n additionalEventProcessors: EventProcessor[] = [],\n ): PromiseLike {\n applyScopeDataToEvent(event, this.getScopeData());\n\n // TODO (v8): Update this order to be: Global > Client > Scope\n const eventProcessors: EventProcessor[] = [\n ...additionalEventProcessors,\n // eslint-disable-next-line deprecation/deprecation\n ...getGlobalEventProcessors(),\n ...this._eventProcessors,\n ];\n\n return notifyEventProcessors(eventProcessors, event, hint);\n }\n\n /**\n * Add data which will be accessible during event processing but won't get sent to Sentry\n */\n public setSDKProcessingMetadata(newData: { [key: string]: unknown }): this {\n this._sdkProcessingMetadata = { ...this._sdkProcessingMetadata, ...newData };\n\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setPropagationContext(context: PropagationContext): this {\n this._propagationContext = context;\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getPropagationContext(): PropagationContext {\n return this._propagationContext;\n }\n\n /**\n * Capture an exception for this scope.\n *\n * @param exception The exception to capture.\n * @param hint Optinal additional data to attach to the Sentry event.\n * @returns the id of the captured Sentry event.\n */\n public captureException(exception: unknown, hint?: EventHint): string {\n const eventId = hint && hint.event_id ? hint.event_id : uuid4();\n\n if (!this._client) {\n logger.warn('No client configured on scope - will not capture exception!');\n return eventId;\n }\n\n const syntheticException = new Error('Sentry syntheticException');\n\n this._client.captureException(\n exception,\n {\n originalException: exception,\n syntheticException,\n ...hint,\n event_id: eventId,\n },\n this,\n );\n\n return eventId;\n }\n\n /**\n * Capture a message for this scope.\n *\n * @param message The message to capture.\n * @param level An optional severity level to report the message with.\n * @param hint Optional additional data to attach to the Sentry event.\n * @returns the id of the captured message.\n */\n public captureMessage(message: string, level?: SeverityLevel, hint?: EventHint): string {\n const eventId = hint && hint.event_id ? hint.event_id : uuid4();\n\n if (!this._client) {\n logger.warn('No client configured on scope - will not capture message!');\n return eventId;\n }\n\n const syntheticException = new Error(message);\n\n this._client.captureMessage(\n message,\n level,\n {\n originalException: message,\n syntheticException,\n ...hint,\n event_id: eventId,\n },\n this,\n );\n\n return eventId;\n }\n\n /**\n * Captures a manually created event for this scope and sends it to Sentry.\n *\n * @param exception The event to capture.\n * @param hint Optional additional data to attach to the Sentry event.\n * @returns the id of the captured event.\n */\n public captureEvent(event: Event, hint?: EventHint): string {\n const eventId = hint && hint.event_id ? hint.event_id : uuid4();\n\n if (!this._client) {\n logger.warn('No client configured on scope - will not capture event!');\n return eventId;\n }\n\n this._client.captureEvent(event, { ...hint, event_id: eventId }, this);\n\n return eventId;\n }\n\n /**\n * This will be called on every set call.\n */\n protected _notifyScopeListeners(): void {\n // We need this check for this._notifyingListeners to be able to work on scope during updates\n // If this check is not here we'll produce endless recursion when something is done with the scope\n // during the callback.\n if (!this._notifyingListeners) {\n this._notifyingListeners = true;\n this._scopeListeners.forEach(callback => {\n callback(this);\n });\n this._notifyingListeners = false;\n }\n }\n}\n\n/**\n * Get the global scope.\n * This scope is applied to _all_ events.\n */\nexport function getGlobalScope(): ScopeInterface {\n if (!globalScope) {\n globalScope = new Scope();\n }\n\n return globalScope;\n}\n\n/**\n * This is mainly needed for tests.\n * DO NOT USE this, as this is an internal API and subject to change.\n * @hidden\n */\nexport function setGlobalScope(scope: ScopeInterface | undefined): void {\n globalScope = scope;\n}\n\nfunction generatePropagationContext(): PropagationContext {\n return {\n traceId: uuid4(),\n spanId: uuid4().substring(16),\n };\n}\n","import type {\n Breadcrumb,\n BreadcrumbHint,\n CaptureContext,\n CheckIn,\n Client,\n CustomSamplingContext,\n Event,\n EventHint,\n Extra,\n Extras,\n FinishedCheckIn,\n MonitorConfig,\n Primitive,\n Scope as ScopeInterface,\n Session,\n SessionContext,\n Severity,\n SeverityLevel,\n Span,\n TransactionContext,\n User,\n} from '@sentry/types';\nimport { GLOBAL_OBJ, isThenable, logger, timestampInSeconds, uuid4 } from '@sentry/utils';\n\nimport { DEFAULT_ENVIRONMENT } from './constants';\nimport { DEBUG_BUILD } from './debug-build';\nimport type { Hub } from './hub';\nimport { runWithAsyncContext } from './hub';\nimport { getCurrentHub, getIsolationScope } from './hub';\nimport type { Scope } from './scope';\nimport { closeSession, makeSession, updateSession } from './session';\nimport type { ExclusiveEventHintOrCaptureContext } from './utils/prepareEvent';\nimport { parseEventHintOrCaptureContext } from './utils/prepareEvent';\n\n/**\n * Captures an exception event and sends it to Sentry.\n *\n * @param exception The exception to capture.\n * @param hint Optional additional data to attach to the Sentry event.\n * @returns the id of the captured Sentry event.\n */\nexport function captureException(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n exception: any,\n hint?: ExclusiveEventHintOrCaptureContext,\n): string {\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().captureException(exception, parseEventHintOrCaptureContext(hint));\n}\n\n/**\n * Captures a message event and sends it to Sentry.\n *\n * @param exception The exception to capture.\n * @param captureContext Define the level of the message or pass in additional data to attach to the message.\n * @returns the id of the captured message.\n */\nexport function captureMessage(\n message: string,\n // eslint-disable-next-line deprecation/deprecation\n captureContext?: CaptureContext | Severity | SeverityLevel,\n): string {\n // This is necessary to provide explicit scopes upgrade, without changing the original\n // arity of the `captureMessage(message, level)` method.\n const level = typeof captureContext === 'string' ? captureContext : undefined;\n const context = typeof captureContext !== 'string' ? { captureContext } : undefined;\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().captureMessage(message, level, context);\n}\n\n/**\n * Captures a manually created event and sends it to Sentry.\n *\n * @param exception The event to send to Sentry.\n * @param hint Optional additional data to attach to the Sentry event.\n * @returns the id of the captured event.\n */\nexport function captureEvent(event: Event, hint?: EventHint): string {\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().captureEvent(event, hint);\n}\n\n/**\n * Callback to set context information onto the scope.\n * @param callback Callback function that receives Scope.\n *\n * @deprecated Use getCurrentScope() directly.\n */\nexport function configureScope(callback: (scope: Scope) => void): ReturnType {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().configureScope(callback);\n}\n\n/**\n * Records a new breadcrumb which will be attached to future events.\n *\n * Breadcrumbs will be added to subsequent events to provide more context on\n * user's actions prior to an error or crash.\n *\n * @param breadcrumb The breadcrumb to record.\n */\nexport function addBreadcrumb(breadcrumb: Breadcrumb, hint?: BreadcrumbHint): ReturnType {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().addBreadcrumb(breadcrumb, hint);\n}\n\n/**\n * Sets context data with the given name.\n * @param name of the context\n * @param context Any kind of data. This data will be normalized.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function setContext(name: string, context: { [key: string]: any } | null): ReturnType {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().setContext(name, context);\n}\n\n/**\n * Set an object that will be merged sent as extra data with the event.\n * @param extras Extras object to merge into current context.\n */\nexport function setExtras(extras: Extras): ReturnType {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().setExtras(extras);\n}\n\n/**\n * Set key:value that will be sent as extra data with the event.\n * @param key String of extra\n * @param extra Any kind of data. This data will be normalized.\n */\nexport function setExtra(key: string, extra: Extra): ReturnType {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().setExtra(key, extra);\n}\n\n/**\n * Set an object that will be merged sent as tags data with the event.\n * @param tags Tags context object to merge into current context.\n */\nexport function setTags(tags: { [key: string]: Primitive }): ReturnType {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().setTags(tags);\n}\n\n/**\n * Set key:value that will be sent as tags data with the event.\n *\n * Can also be used to unset a tag, by passing `undefined`.\n *\n * @param key String key of tag\n * @param value Value of tag\n */\nexport function setTag(key: string, value: Primitive): ReturnType {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().setTag(key, value);\n}\n\n/**\n * Updates user context information for future events.\n *\n * @param user User context object to be set in the current context. Pass `null` to unset the user.\n */\nexport function setUser(user: User | null): ReturnType {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().setUser(user);\n}\n\n/**\n * Creates a new scope with and executes the given operation within.\n * The scope is automatically removed once the operation\n * finishes or throws.\n *\n * This is essentially a convenience function for:\n *\n * pushScope();\n * callback();\n * popScope();\n */\nexport function withScope(callback: (scope: Scope) => T): T;\n/**\n * Set the given scope as the active scope in the callback.\n */\nexport function withScope(scope: ScopeInterface | undefined, callback: (scope: Scope) => T): T;\n/**\n * Either creates a new active scope, or sets the given scope as active scope in the given callback.\n */\nexport function withScope(\n ...rest: [callback: (scope: Scope) => T] | [scope: ScopeInterface | undefined, callback: (scope: Scope) => T]\n): T {\n // eslint-disable-next-line deprecation/deprecation\n const hub = getCurrentHub();\n\n // If a scope is defined, we want to make this the active scope instead of the default one\n if (rest.length === 2) {\n const [scope, callback] = rest;\n if (!scope) {\n // eslint-disable-next-line deprecation/deprecation\n return hub.withScope(callback);\n }\n\n // eslint-disable-next-line deprecation/deprecation\n return hub.withScope(() => {\n // eslint-disable-next-line deprecation/deprecation\n hub.getStackTop().scope = scope as Scope;\n return callback(scope as Scope);\n });\n }\n\n // eslint-disable-next-line deprecation/deprecation\n return hub.withScope(rest[0]);\n}\n\n/**\n * Attempts to fork the current isolation scope and the current scope based on the current async context strategy. If no\n * async context strategy is set, the isolation scope and the current scope will not be forked (this is currently the\n * case, for example, in the browser).\n *\n * Usage of this function in environments without async context strategy is discouraged and may lead to unexpected behaviour.\n *\n * This function is intended for Sentry SDK and SDK integration development. It is not recommended to be used in \"normal\"\n * applications directly because it comes with pitfalls. Use at your own risk!\n *\n * @param callback The callback in which the passed isolation scope is active. (Note: In environments without async\n * context strategy, the currently active isolation scope may change within execution of the callback.)\n * @returns The same value that `callback` returns.\n */\nexport function withIsolationScope(callback: (isolationScope: Scope) => T): T {\n return runWithAsyncContext(() => {\n return callback(getIsolationScope());\n });\n}\n\n/**\n * Forks the current scope and sets the provided span as active span in the context of the provided callback.\n *\n * @param span Spans started in the context of the provided callback will be children of this span.\n * @param callback Execution context in which the provided span will be active. Is passed the newly forked scope.\n * @returns the value returned from the provided callback function.\n */\nexport function withActiveSpan(span: Span, callback: (scope: Scope) => T): T {\n return withScope(scope => {\n // eslint-disable-next-line deprecation/deprecation\n scope.setSpan(span);\n return callback(scope);\n });\n}\n\n/**\n * Starts a new `Transaction` and returns it. This is the entry point to manual tracing instrumentation.\n *\n * A tree structure can be built by adding child spans to the transaction, and child spans to other spans. To start a\n * new child span within the transaction or any span, call the respective `.startChild()` method.\n *\n * Every child span must be finished before the transaction is finished, otherwise the unfinished spans are discarded.\n *\n * The transaction must be finished with a call to its `.end()` method, at which point the transaction with all its\n * finished child spans will be sent to Sentry.\n *\n * NOTE: This function should only be used for *manual* instrumentation. Auto-instrumentation should call\n * `startTransaction` directly on the hub.\n *\n * @param context Properties of the new `Transaction`.\n * @param customSamplingContext Information given to the transaction sampling function (along with context-dependent\n * default values). See {@link Options.tracesSampler}.\n *\n * @returns The transaction which was just started\n *\n * @deprecated Use `startSpan()`, `startSpanManual()` or `startInactiveSpan()` instead.\n */\nexport function startTransaction(\n context: TransactionContext,\n customSamplingContext?: CustomSamplingContext,\n): ReturnType {\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().startTransaction({ ...context }, customSamplingContext);\n}\n\n/**\n * Create a cron monitor check in and send it to Sentry.\n *\n * @param checkIn An object that describes a check in.\n * @param upsertMonitorConfig An optional object that describes a monitor config. Use this if you want\n * to create a monitor automatically when sending a check in.\n */\nexport function captureCheckIn(checkIn: CheckIn, upsertMonitorConfig?: MonitorConfig): string {\n const scope = getCurrentScope();\n const client = getClient();\n if (!client) {\n DEBUG_BUILD && logger.warn('Cannot capture check-in. No client defined.');\n } else if (!client.captureCheckIn) {\n DEBUG_BUILD && logger.warn('Cannot capture check-in. Client does not support sending check-ins.');\n } else {\n return client.captureCheckIn(checkIn, upsertMonitorConfig, scope);\n }\n\n return uuid4();\n}\n\n/**\n * Wraps a callback with a cron monitor check in. The check in will be sent to Sentry when the callback finishes.\n *\n * @param monitorSlug The distinct slug of the monitor.\n * @param upsertMonitorConfig An optional object that describes a monitor config. Use this if you want\n * to create a monitor automatically when sending a check in.\n */\nexport function withMonitor(\n monitorSlug: CheckIn['monitorSlug'],\n callback: () => T,\n upsertMonitorConfig?: MonitorConfig,\n): T {\n const checkInId = captureCheckIn({ monitorSlug, status: 'in_progress' }, upsertMonitorConfig);\n const now = timestampInSeconds();\n\n function finishCheckIn(status: FinishedCheckIn['status']): void {\n captureCheckIn({ monitorSlug, status, checkInId, duration: timestampInSeconds() - now });\n }\n\n let maybePromiseResult: T;\n try {\n maybePromiseResult = callback();\n } catch (e) {\n finishCheckIn('error');\n throw e;\n }\n\n if (isThenable(maybePromiseResult)) {\n Promise.resolve(maybePromiseResult).then(\n () => {\n finishCheckIn('ok');\n },\n () => {\n finishCheckIn('error');\n },\n );\n } else {\n finishCheckIn('ok');\n }\n\n return maybePromiseResult;\n}\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 */\nexport async function flush(timeout?: number): Promise {\n const client = getClient();\n if (client) {\n return client.flush(timeout);\n }\n DEBUG_BUILD && logger.warn('Cannot flush events. No client defined.');\n return Promise.resolve(false);\n}\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 */\nexport async function close(timeout?: number): Promise {\n const client = getClient();\n if (client) {\n return client.close(timeout);\n }\n DEBUG_BUILD && logger.warn('Cannot flush events and disable SDK. No client defined.');\n return Promise.resolve(false);\n}\n\n/**\n * This is the getter for lastEventId.\n *\n * @returns The last event id of a captured event.\n * @deprecated This function will be removed in the next major version of the Sentry SDK.\n */\nexport function lastEventId(): string | undefined {\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().lastEventId();\n}\n\n/**\n * Get the currently active client.\n */\nexport function getClient(): C | undefined {\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().getClient();\n}\n\n/**\n * Returns true if Sentry has been properly initialized.\n */\nexport function isInitialized(): boolean {\n return !!getClient();\n}\n\n/**\n * Get the currently active scope.\n */\nexport function getCurrentScope(): Scope {\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().getScope();\n}\n\n/**\n * Start a session on the current isolation scope.\n *\n * @param context (optional) additional properties to be applied to the returned session object\n *\n * @returns the new active session\n */\nexport function startSession(context?: SessionContext): Session {\n const client = getClient();\n const isolationScope = getIsolationScope();\n const currentScope = getCurrentScope();\n\n const { release, environment = DEFAULT_ENVIRONMENT } = (client && client.getOptions()) || {};\n\n // Will fetch userAgent if called from browser sdk\n const { userAgent } = GLOBAL_OBJ.navigator || {};\n\n const session = makeSession({\n release,\n environment,\n user: currentScope.getUser() || isolationScope.getUser(),\n ...(userAgent && { userAgent }),\n ...context,\n });\n\n // End existing session if there's one\n const currentSession = isolationScope.getSession();\n if (currentSession && currentSession.status === 'ok') {\n updateSession(currentSession, { status: 'exited' });\n }\n\n endSession();\n\n // Afterwards we set the new session on the scope\n isolationScope.setSession(session);\n\n // TODO (v8): Remove this and only use the isolation scope(?).\n // For v7 though, we can't \"soft-break\" people using getCurrentHub().getScope().setSession()\n currentScope.setSession(session);\n\n return session;\n}\n\n/**\n * End the session on the current isolation scope.\n */\nexport function endSession(): void {\n const isolationScope = getIsolationScope();\n const currentScope = getCurrentScope();\n\n const session = currentScope.getSession() || isolationScope.getSession();\n if (session) {\n closeSession(session);\n }\n _sendSessionUpdate();\n\n // the session is over; take it off of the scope\n isolationScope.setSession();\n\n // TODO (v8): Remove this and only use the isolation scope(?).\n // For v7 though, we can't \"soft-break\" people using getCurrentHub().getScope().setSession()\n currentScope.setSession();\n}\n\n/**\n * Sends the current Session on the scope\n */\nfunction _sendSessionUpdate(): void {\n const isolationScope = getIsolationScope();\n const currentScope = getCurrentScope();\n const client = getClient();\n // TODO (v8): Remove currentScope and only use the isolation scope(?).\n // For v7 though, we can't \"soft-break\" people using getCurrentHub().getScope().setSession()\n const session = currentScope.getSession() || isolationScope.getSession();\n if (session && client && client.captureSession) {\n client.captureSession(session);\n }\n}\n\n/**\n * Sends the current session on the scope to Sentry\n *\n * @param end If set the session will be marked as exited and removed from the scope.\n * Defaults to `false`.\n */\nexport function captureSession(end: boolean = false): void {\n // both send the update and pull the session from the scope\n if (end) {\n endSession();\n return;\n }\n\n // only send the update\n _sendSessionUpdate();\n}\n","import type { Span } from '@sentry/types';\n\n/**\n * Returns the root span of a given span.\n *\n * As long as we use `Transaction`s internally, the returned root span\n * will be a `Transaction` but be aware that this might change in the future.\n *\n * If the given span has no root span or transaction, `undefined` is returned.\n */\nexport function getRootSpan(span: Span): Span | undefined {\n // TODO (v8): Remove this check and just return span\n // eslint-disable-next-line deprecation/deprecation\n return span.transaction;\n}\n","import type { Client, DynamicSamplingContext, Scope, Span, Transaction } from '@sentry/types';\nimport { dropUndefinedKeys } from '@sentry/utils';\n\nimport { DEFAULT_ENVIRONMENT } from '../constants';\nimport { getClient, getCurrentScope } from '../exports';\nimport { getRootSpan } from '../utils/getRootSpan';\nimport { spanIsSampled, spanToJSON } from '../utils/spanUtils';\n\n/**\n * Creates a dynamic sampling context from a client.\n *\n * Dispatches the `createDsc` lifecycle hook as a side effect.\n */\nexport function getDynamicSamplingContextFromClient(\n trace_id: string,\n client: Client,\n scope?: Scope,\n): DynamicSamplingContext {\n const options = client.getOptions();\n\n const { publicKey: public_key } = client.getDsn() || {};\n // TODO(v8): Remove segment from User\n // eslint-disable-next-line deprecation/deprecation\n const { segment: user_segment } = (scope && scope.getUser()) || {};\n\n const dsc = dropUndefinedKeys({\n environment: options.environment || DEFAULT_ENVIRONMENT,\n release: options.release,\n user_segment,\n public_key,\n trace_id,\n }) as DynamicSamplingContext;\n\n client.emit && client.emit('createDsc', dsc);\n\n return dsc;\n}\n\n/**\n * A Span with a frozen dynamic sampling context.\n */\ntype TransactionWithV7FrozenDsc = Transaction & { _frozenDynamicSamplingContext?: DynamicSamplingContext };\n\n/**\n * Creates a dynamic sampling context from a span (and client and scope)\n *\n * @param span the span from which a few values like the root span name and sample rate are extracted.\n *\n * @returns a dynamic sampling context\n */\nexport function getDynamicSamplingContextFromSpan(span: Span): Readonly> {\n const client = getClient();\n if (!client) {\n return {};\n }\n\n // passing emit=false here to only emit later once the DSC is actually populated\n const dsc = getDynamicSamplingContextFromClient(spanToJSON(span).trace_id || '', client, getCurrentScope());\n\n // TODO (v8): Remove v7FrozenDsc as a Transaction will no longer have _frozenDynamicSamplingContext\n const txn = getRootSpan(span) as TransactionWithV7FrozenDsc | undefined;\n if (!txn) {\n return dsc;\n }\n\n // TODO (v8): Remove v7FrozenDsc as a Transaction will no longer have _frozenDynamicSamplingContext\n // For now we need to avoid breaking users who directly created a txn with a DSC, where this field is still set.\n // @see Transaction class constructor\n const v7FrozenDsc = txn && txn._frozenDynamicSamplingContext;\n if (v7FrozenDsc) {\n return v7FrozenDsc;\n }\n\n // TODO (v8): Replace txn.metadata with txn.attributes[]\n // We can't do this yet because attributes aren't always set yet.\n // eslint-disable-next-line deprecation/deprecation\n const { sampleRate: maybeSampleRate, source } = txn.metadata;\n if (maybeSampleRate != null) {\n dsc.sample_rate = `${maybeSampleRate}`;\n }\n\n // We don't want to have a transaction name in the DSC if the source is \"url\" because URLs might contain PII\n const jsonSpan = spanToJSON(txn);\n\n // after JSON conversion, txn.name becomes jsonSpan.description\n if (source && source !== 'url') {\n dsc.transaction = jsonSpan.description;\n }\n\n dsc.sampled = String(spanIsSampled(txn));\n\n client.emit && client.emit('createDsc', dsc);\n\n return dsc;\n}\n","import type { Breadcrumb, Event, ScopeData, Span } from '@sentry/types';\nimport { arrayify, dropUndefinedKeys } from '@sentry/utils';\nimport { getDynamicSamplingContextFromSpan } from '../tracing/dynamicSamplingContext';\nimport { getRootSpan } from './getRootSpan';\nimport { spanToJSON, spanToTraceContext } from './spanUtils';\n\n/**\n * Applies data from the scope to the event and runs all event processors on it.\n */\nexport function applyScopeDataToEvent(event: Event, data: ScopeData): void {\n const { fingerprint, span, breadcrumbs, sdkProcessingMetadata } = data;\n\n // Apply general data\n applyDataToEvent(event, data);\n\n // We want to set the trace context for normal events only if there isn't already\n // a trace context on the event. There is a product feature in place where we link\n // errors with transaction and it relies on that.\n if (span) {\n applySpanToEvent(event, span);\n }\n\n applyFingerprintToEvent(event, fingerprint);\n applyBreadcrumbsToEvent(event, breadcrumbs);\n applySdkMetadataToEvent(event, sdkProcessingMetadata);\n}\n\n/** Merge data of two scopes together. */\nexport function mergeScopeData(data: ScopeData, mergeData: ScopeData): void {\n const {\n extra,\n tags,\n user,\n contexts,\n level,\n sdkProcessingMetadata,\n breadcrumbs,\n fingerprint,\n eventProcessors,\n attachments,\n propagationContext,\n // eslint-disable-next-line deprecation/deprecation\n transactionName,\n span,\n } = mergeData;\n\n mergeAndOverwriteScopeData(data, 'extra', extra);\n mergeAndOverwriteScopeData(data, 'tags', tags);\n mergeAndOverwriteScopeData(data, 'user', user);\n mergeAndOverwriteScopeData(data, 'contexts', contexts);\n mergeAndOverwriteScopeData(data, 'sdkProcessingMetadata', sdkProcessingMetadata);\n\n if (level) {\n data.level = level;\n }\n\n if (transactionName) {\n // eslint-disable-next-line deprecation/deprecation\n data.transactionName = transactionName;\n }\n\n if (span) {\n data.span = span;\n }\n\n if (breadcrumbs.length) {\n data.breadcrumbs = [...data.breadcrumbs, ...breadcrumbs];\n }\n\n if (fingerprint.length) {\n data.fingerprint = [...data.fingerprint, ...fingerprint];\n }\n\n if (eventProcessors.length) {\n data.eventProcessors = [...data.eventProcessors, ...eventProcessors];\n }\n\n if (attachments.length) {\n data.attachments = [...data.attachments, ...attachments];\n }\n\n data.propagationContext = { ...data.propagationContext, ...propagationContext };\n}\n\n/**\n * Merges certain scope data. Undefined values will overwrite any existing values.\n * Exported only for tests.\n */\nexport function mergeAndOverwriteScopeData<\n Prop extends 'extra' | 'tags' | 'user' | 'contexts' | 'sdkProcessingMetadata',\n Data extends ScopeData,\n>(data: Data, prop: Prop, mergeVal: Data[Prop]): void {\n if (mergeVal && Object.keys(mergeVal).length) {\n // Clone object\n data[prop] = { ...data[prop] };\n for (const key in mergeVal) {\n if (Object.prototype.hasOwnProperty.call(mergeVal, key)) {\n data[prop][key] = mergeVal[key];\n }\n }\n }\n}\n\n/** Exported only for tests */\nexport function mergeArray(\n event: Event,\n prop: Prop,\n mergeVal: ScopeData[Prop],\n): void {\n const prevVal = event[prop];\n // If we are not merging any new values,\n // we only need to proceed if there was an empty array before (as we want to replace it with undefined)\n if (!mergeVal.length && (!prevVal || prevVal.length)) {\n return;\n }\n\n const merged = [...(prevVal || []), ...mergeVal] as ScopeData[Prop];\n event[prop] = merged.length ? merged : undefined;\n}\n\nfunction applyDataToEvent(event: Event, data: ScopeData): void {\n const {\n extra,\n tags,\n user,\n contexts,\n level,\n // eslint-disable-next-line deprecation/deprecation\n transactionName,\n } = data;\n\n const cleanedExtra = dropUndefinedKeys(extra);\n if (cleanedExtra && Object.keys(cleanedExtra).length) {\n event.extra = { ...cleanedExtra, ...event.extra };\n }\n\n const cleanedTags = dropUndefinedKeys(tags);\n if (cleanedTags && Object.keys(cleanedTags).length) {\n event.tags = { ...cleanedTags, ...event.tags };\n }\n\n const cleanedUser = dropUndefinedKeys(user);\n if (cleanedUser && Object.keys(cleanedUser).length) {\n event.user = { ...cleanedUser, ...event.user };\n }\n\n const cleanedContexts = dropUndefinedKeys(contexts);\n if (cleanedContexts && Object.keys(cleanedContexts).length) {\n event.contexts = { ...cleanedContexts, ...event.contexts };\n }\n\n if (level) {\n event.level = level;\n }\n\n if (transactionName) {\n event.transaction = transactionName;\n }\n}\n\nfunction applyBreadcrumbsToEvent(event: Event, breadcrumbs: Breadcrumb[]): void {\n const mergedBreadcrumbs = [...(event.breadcrumbs || []), ...breadcrumbs];\n event.breadcrumbs = mergedBreadcrumbs.length ? mergedBreadcrumbs : undefined;\n}\n\nfunction applySdkMetadataToEvent(event: Event, sdkProcessingMetadata: ScopeData['sdkProcessingMetadata']): void {\n event.sdkProcessingMetadata = {\n ...event.sdkProcessingMetadata,\n ...sdkProcessingMetadata,\n };\n}\n\nfunction applySpanToEvent(event: Event, span: Span): void {\n event.contexts = { trace: spanToTraceContext(span), ...event.contexts };\n const rootSpan = getRootSpan(span);\n if (rootSpan) {\n event.sdkProcessingMetadata = {\n dynamicSamplingContext: getDynamicSamplingContextFromSpan(span),\n ...event.sdkProcessingMetadata,\n };\n const transactionName = spanToJSON(rootSpan).description;\n if (transactionName) {\n event.tags = { transaction: transactionName, ...event.tags };\n }\n }\n}\n\n/**\n * Applies fingerprint from the scope to the event if there's one,\n * uses message if there's one instead or get rid of empty fingerprint\n */\nfunction applyFingerprintToEvent(event: Event, fingerprint: ScopeData['fingerprint'] | undefined): void {\n // Make sure it's an array first and we actually have something in place\n event.fingerprint = event.fingerprint ? arrayify(event.fingerprint) : [];\n\n // If we have something on the scope, then merge it with event\n if (fingerprint) {\n event.fingerprint = event.fingerprint.concat(fingerprint);\n }\n\n // If we have no data at all, remove empty array default\n if (event.fingerprint && !event.fingerprint.length) {\n delete event.fingerprint;\n }\n}\n","export const SDK_VERSION = '7.102.1';\n","/* eslint-disable max-lines */\nimport type {\n Breadcrumb,\n BreadcrumbHint,\n Client,\n CustomSamplingContext,\n Event,\n EventHint,\n Extra,\n Extras,\n Hub as HubInterface,\n Integration,\n IntegrationClass,\n Primitive,\n Session,\n SessionContext,\n Severity,\n SeverityLevel,\n Transaction,\n TransactionContext,\n User,\n} from '@sentry/types';\nimport {\n GLOBAL_OBJ,\n consoleSandbox,\n dateTimestampInSeconds,\n getGlobalSingleton,\n isThenable,\n logger,\n uuid4,\n} from '@sentry/utils';\n\nimport { DEFAULT_ENVIRONMENT } from './constants';\nimport { DEBUG_BUILD } from './debug-build';\nimport { Scope } from './scope';\nimport { closeSession, makeSession, updateSession } from './session';\nimport { SDK_VERSION } from './version';\n\n/**\n * API compatibility version of this hub.\n *\n * WARNING: This number should only be increased when the global interface\n * changes and new methods are introduced.\n *\n * @hidden\n */\nexport const API_VERSION = parseFloat(SDK_VERSION);\n\n/**\n * Default maximum number of breadcrumbs added to an event. Can be overwritten\n * with {@link Options.maxBreadcrumbs}.\n */\nconst DEFAULT_BREADCRUMBS = 100;\n\nexport interface RunWithAsyncContextOptions {\n /** Whether to reuse an existing async context if one exists. Defaults to false. */\n reuseExisting?: boolean;\n}\n\n/**\n * @private Private API with no semver guarantees!\n *\n * Strategy used to track async context.\n */\nexport interface AsyncContextStrategy {\n /**\n * Gets the current async context. Returns undefined if there is no current async context.\n */\n getCurrentHub: () => Hub | undefined;\n /**\n * Runs the supplied callback in its own async context.\n */\n runWithAsyncContext(callback: () => T, options: RunWithAsyncContextOptions): T;\n}\n\n/**\n * A layer in the process stack.\n * @hidden\n */\nexport interface Layer {\n client?: Client;\n scope: Scope;\n}\n\n/**\n * An object that contains a hub and maintains a scope stack.\n * @hidden\n */\nexport interface Carrier {\n __SENTRY__?: {\n hub?: Hub;\n acs?: AsyncContextStrategy;\n /**\n * Extra Hub properties injected by various SDKs\n */\n integrations?: Integration[];\n extensions?: {\n /** Extension methods for the hub, which are bound to the current Hub instance */\n // eslint-disable-next-line @typescript-eslint/ban-types\n [key: string]: Function;\n };\n };\n}\n\n/**\n * @inheritDoc\n */\nexport class Hub implements HubInterface {\n /** Is a {@link Layer}[] containing the client and scope */\n private readonly _stack: Layer[];\n\n /** Contains the last event id of a captured event. */\n private _lastEventId?: string;\n\n private _isolationScope: Scope;\n\n /**\n * Creates a new instance of the hub, will push one {@link Layer} into the\n * internal stack on creation.\n *\n * @param client bound to the hub.\n * @param scope bound to the hub.\n * @param version number, higher number means higher priority.\n *\n * @deprecated Instantiation of Hub objects is deprecated and the constructor will be removed in version 8 of the SDK.\n *\n * If you are currently using the Hub for multi-client use like so:\n *\n * ```\n * // OLD\n * const hub = new Hub();\n * hub.bindClient(client);\n * makeMain(hub)\n * ```\n *\n * instead initialize the client as follows:\n *\n * ```\n * // NEW\n * Sentry.withIsolationScope(() => {\n * Sentry.setCurrentClient(client);\n * client.init();\n * });\n * ```\n *\n * If you are using the Hub to capture events like so:\n *\n * ```\n * // OLD\n * const client = new Client();\n * const hub = new Hub(client);\n * hub.captureException()\n * ```\n *\n * instead capture isolated events as follows:\n *\n * ```\n * // NEW\n * const client = new Client();\n * const scope = new Scope();\n * scope.setClient(client);\n * scope.captureException();\n * ```\n */\n public constructor(\n client?: Client,\n scope?: Scope,\n isolationScope?: Scope,\n private readonly _version: number = API_VERSION,\n ) {\n let assignedScope;\n if (!scope) {\n assignedScope = new Scope();\n assignedScope.setClient(client);\n } else {\n assignedScope = scope;\n }\n\n let assignedIsolationScope;\n if (!isolationScope) {\n assignedIsolationScope = new Scope();\n assignedIsolationScope.setClient(client);\n } else {\n assignedIsolationScope = isolationScope;\n }\n\n this._stack = [{ scope: assignedScope }];\n\n if (client) {\n // eslint-disable-next-line deprecation/deprecation\n this.bindClient(client);\n }\n\n this._isolationScope = assignedIsolationScope;\n }\n\n /**\n * Checks if this hub's version is older than the given version.\n *\n * @param version A version number to compare to.\n * @return True if the given version is newer; otherwise false.\n *\n * @deprecated This will be removed in v8.\n */\n public isOlderThan(version: number): boolean {\n return this._version < version;\n }\n\n /**\n * This binds the given client to the current scope.\n * @param client An SDK client (client) instance.\n *\n * @deprecated Use `initAndBind()` directly, or `setCurrentClient()` and/or `client.init()` instead.\n */\n public bindClient(client?: Client): void {\n // eslint-disable-next-line deprecation/deprecation\n const top = this.getStackTop();\n top.client = client;\n top.scope.setClient(client);\n // eslint-disable-next-line deprecation/deprecation\n if (client && client.setupIntegrations) {\n // eslint-disable-next-line deprecation/deprecation\n client.setupIntegrations();\n }\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `withScope` instead.\n */\n public pushScope(): Scope {\n // We want to clone the content of prev scope\n // eslint-disable-next-line deprecation/deprecation\n const scope = this.getScope().clone();\n // eslint-disable-next-line deprecation/deprecation\n this.getStack().push({\n // eslint-disable-next-line deprecation/deprecation\n client: this.getClient(),\n scope,\n });\n return scope;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `withScope` instead.\n */\n public popScope(): boolean {\n // eslint-disable-next-line deprecation/deprecation\n if (this.getStack().length <= 1) return false;\n // eslint-disable-next-line deprecation/deprecation\n return !!this.getStack().pop();\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `Sentry.withScope()` instead.\n */\n public withScope(callback: (scope: Scope) => T): T {\n // eslint-disable-next-line deprecation/deprecation\n const scope = this.pushScope();\n\n let maybePromiseResult: T;\n try {\n maybePromiseResult = callback(scope);\n } catch (e) {\n // eslint-disable-next-line deprecation/deprecation\n this.popScope();\n throw e;\n }\n\n if (isThenable(maybePromiseResult)) {\n // @ts-expect-error - isThenable returns the wrong type\n return maybePromiseResult.then(\n res => {\n // eslint-disable-next-line deprecation/deprecation\n this.popScope();\n return res;\n },\n e => {\n // eslint-disable-next-line deprecation/deprecation\n this.popScope();\n throw e;\n },\n );\n }\n\n // eslint-disable-next-line deprecation/deprecation\n this.popScope();\n return maybePromiseResult;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `Sentry.getClient()` instead.\n */\n public getClient(): C | undefined {\n // eslint-disable-next-line deprecation/deprecation\n return this.getStackTop().client as C;\n }\n\n /**\n * Returns the scope of the top stack.\n *\n * @deprecated Use `Sentry.getCurrentScope()` instead.\n */\n public getScope(): Scope {\n // eslint-disable-next-line deprecation/deprecation\n return this.getStackTop().scope;\n }\n\n /**\n * @deprecated Use `Sentry.getIsolationScope()` instead.\n */\n public getIsolationScope(): Scope {\n return this._isolationScope;\n }\n\n /**\n * Returns the scope stack for domains or the process.\n * @deprecated This will be removed in v8.\n */\n public getStack(): Layer[] {\n return this._stack;\n }\n\n /**\n * Returns the topmost scope layer in the order domain > local > process.\n * @deprecated This will be removed in v8.\n */\n public getStackTop(): Layer {\n return this._stack[this._stack.length - 1];\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `Sentry.captureException()` instead.\n */\n public captureException(exception: unknown, hint?: EventHint): string {\n const eventId = (this._lastEventId = hint && hint.event_id ? hint.event_id : uuid4());\n const syntheticException = new Error('Sentry syntheticException');\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().captureException(exception, {\n originalException: exception,\n syntheticException,\n ...hint,\n event_id: eventId,\n });\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `Sentry.captureMessage()` instead.\n */\n public captureMessage(\n message: string,\n // eslint-disable-next-line deprecation/deprecation\n level?: Severity | SeverityLevel,\n hint?: EventHint,\n ): string {\n const eventId = (this._lastEventId = hint && hint.event_id ? hint.event_id : uuid4());\n const syntheticException = new Error(message);\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().captureMessage(message, level, {\n originalException: message,\n syntheticException,\n ...hint,\n event_id: eventId,\n });\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `Sentry.captureEvent()` instead.\n */\n public captureEvent(event: Event, hint?: EventHint): string {\n const eventId = hint && hint.event_id ? hint.event_id : uuid4();\n if (!event.type) {\n this._lastEventId = eventId;\n }\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().captureEvent(event, { ...hint, event_id: eventId });\n return eventId;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated This will be removed in v8.\n */\n public lastEventId(): string | undefined {\n return this._lastEventId;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `Sentry.addBreadcrumb()` instead.\n */\n public addBreadcrumb(breadcrumb: Breadcrumb, hint?: BreadcrumbHint): void {\n // eslint-disable-next-line deprecation/deprecation\n const { scope, client } = this.getStackTop();\n\n if (!client) return;\n\n const { beforeBreadcrumb = null, maxBreadcrumbs = DEFAULT_BREADCRUMBS } =\n (client.getOptions && client.getOptions()) || {};\n\n if (maxBreadcrumbs <= 0) return;\n\n const timestamp = dateTimestampInSeconds();\n const mergedBreadcrumb = { timestamp, ...breadcrumb };\n const finalBreadcrumb = beforeBreadcrumb\n ? (consoleSandbox(() => beforeBreadcrumb(mergedBreadcrumb, hint)) as Breadcrumb | null)\n : mergedBreadcrumb;\n\n if (finalBreadcrumb === null) return;\n\n if (client.emit) {\n client.emit('beforeAddBreadcrumb', finalBreadcrumb, hint);\n }\n\n // TODO(v8): I know this comment doesn't make much sense because the hub will be deprecated but I still wanted to\n // write it down. In theory, we would have to add the breadcrumbs to the isolation scope here, however, that would\n // duplicate all of the breadcrumbs. There was the possibility of adding breadcrumbs to both, the isolation scope\n // and the normal scope, and deduplicating it down the line in the event processing pipeline. However, that would\n // have been very fragile, because the breadcrumb objects would have needed to keep their identity all throughout\n // the event processing pipeline.\n // In the new implementation, the top level `Sentry.addBreadcrumb()` should ONLY write to the isolation scope.\n\n scope.addBreadcrumb(finalBreadcrumb, maxBreadcrumbs);\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `Sentry.setUser()` instead.\n */\n public setUser(user: User | null): void {\n // TODO(v8): The top level `Sentry.setUser()` function should write ONLY to the isolation scope.\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().setUser(user);\n // eslint-disable-next-line deprecation/deprecation\n this.getIsolationScope().setUser(user);\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `Sentry.setTags()` instead.\n */\n public setTags(tags: { [key: string]: Primitive }): void {\n // TODO(v8): The top level `Sentry.setTags()` function should write ONLY to the isolation scope.\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().setTags(tags);\n // eslint-disable-next-line deprecation/deprecation\n this.getIsolationScope().setTags(tags);\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `Sentry.setExtras()` instead.\n */\n public setExtras(extras: Extras): void {\n // TODO(v8): The top level `Sentry.setExtras()` function should write ONLY to the isolation scope.\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().setExtras(extras);\n // eslint-disable-next-line deprecation/deprecation\n this.getIsolationScope().setExtras(extras);\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `Sentry.setTag()` instead.\n */\n public setTag(key: string, value: Primitive): void {\n // TODO(v8): The top level `Sentry.setTag()` function should write ONLY to the isolation scope.\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().setTag(key, value);\n // eslint-disable-next-line deprecation/deprecation\n this.getIsolationScope().setTag(key, value);\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `Sentry.setExtra()` instead.\n */\n public setExtra(key: string, extra: Extra): void {\n // TODO(v8): The top level `Sentry.setExtra()` function should write ONLY to the isolation scope.\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().setExtra(key, extra);\n // eslint-disable-next-line deprecation/deprecation\n this.getIsolationScope().setExtra(key, extra);\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `Sentry.setContext()` instead.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n public setContext(name: string, context: { [key: string]: any } | null): void {\n // TODO(v8): The top level `Sentry.setContext()` function should write ONLY to the isolation scope.\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().setContext(name, context);\n // eslint-disable-next-line deprecation/deprecation\n this.getIsolationScope().setContext(name, context);\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `getScope()` directly.\n */\n public configureScope(callback: (scope: Scope) => void): void {\n // eslint-disable-next-line deprecation/deprecation\n const { scope, client } = this.getStackTop();\n if (client) {\n callback(scope);\n }\n }\n\n /**\n * @inheritDoc\n */\n public run(callback: (hub: Hub) => void): void {\n // eslint-disable-next-line deprecation/deprecation\n const oldHub = makeMain(this);\n try {\n callback(this);\n } finally {\n // eslint-disable-next-line deprecation/deprecation\n makeMain(oldHub);\n }\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `Sentry.getClient().getIntegrationByName()` instead.\n */\n public getIntegration(integration: IntegrationClass): T | null {\n // eslint-disable-next-line deprecation/deprecation\n const client = this.getClient();\n if (!client) return null;\n try {\n // eslint-disable-next-line deprecation/deprecation\n return client.getIntegration(integration);\n } catch (_oO) {\n DEBUG_BUILD && logger.warn(`Cannot retrieve integration ${integration.id} from the current Hub`);\n return null;\n }\n }\n\n /**\n * Starts a new `Transaction` and returns it. This is the entry point to manual tracing instrumentation.\n *\n * A tree structure can be built by adding child spans to the transaction, and child spans to other spans. To start a\n * new child span within the transaction or any span, call the respective `.startChild()` method.\n *\n * Every child span must be finished before the transaction is finished, otherwise the unfinished spans are discarded.\n *\n * The transaction must be finished with a call to its `.end()` method, at which point the transaction with all its\n * finished child spans will be sent to Sentry.\n *\n * @param context Properties of the new `Transaction`.\n * @param customSamplingContext Information given to the transaction sampling function (along with context-dependent\n * default values). See {@link Options.tracesSampler}.\n *\n * @returns The transaction which was just started\n *\n * @deprecated Use `startSpan()`, `startSpanManual()` or `startInactiveSpan()` instead.\n */\n public startTransaction(context: TransactionContext, customSamplingContext?: CustomSamplingContext): Transaction {\n const result = this._callExtensionMethod