UNPKG

388 kBSource Map (JSON)View Raw
1{"version":3,"file":"bundle.debug.min.js","sources":["../../../types/src/severity.ts","../../../utils/src/global.ts","../../../utils/src/is.ts","../../../utils/src/browser.ts","../../../utils/src/polyfill.ts","../../../utils/src/error.ts","../../../utils/src/dsn.ts","../../../utils/src/enums.ts","../../../utils/src/logger.ts","../../../utils/src/string.ts","../../../utils/src/object.ts","../../../utils/src/stacktrace.ts","../../../utils/src/supports.ts","../../../utils/src/instrument.ts","../../../utils/src/misc.ts","../../../utils/src/normalize.ts","../../../utils/src/memo.ts","../../../utils/src/syncpromise.ts","../../../utils/src/promisebuffer.ts","../../../utils/src/severity.ts","../../../utils/src/status.ts","../../../utils/src/time.ts","../../../utils/src/envelope.ts","../../../utils/src/ratelimit.ts","../../../hub/src/scope.ts","../../../hub/src/session.ts","../../../hub/src/hub.ts","../../../minimal/src/index.ts","../../../core/src/api.ts","../../../core/src/flags.ts","../../../core/src/integration.ts","../../../core/src/baseclient.ts","../../../core/src/request.ts","../../../core/src/transports/noop.ts","../../../core/src/basebackend.ts","../../../core/src/transports/base.ts","../../../core/src/integrations/functiontostring.ts","../../../core/src/version.ts","../../../core/src/integrations/inboundfilters.ts","../../src/stack-parsers.ts","../../src/eventbuilder.ts","../../src/flags.ts","../../src/transports/utils.ts","../../../utils/src/async.ts","../../src/transports/base.ts","../../../utils/src/clientreport.ts","../../src/transports/fetch.ts","../../src/transports/xhr.ts","../../src/transports/new-fetch.ts","../../src/transports/new-xhr.ts","../../src/backend.ts","../../src/helpers.ts","../../src/integrations/globalhandlers.ts","../../src/integrations/trycatch.ts","../../src/integrations/breadcrumbs.ts","../../src/integrations/linkederrors.ts","../../src/integrations/useragent.ts","../../src/integrations/dedupe.ts","../../src/client.ts","../../src/sdk.ts","../../src/index.ts","../../src/version.ts","../../../core/src/sdk.ts"],"sourcesContent":["/**\n * TODO(v7): Remove this enum and replace with SeverityLevel\n */\nexport enum Severity {\n /** JSDoc */\n Fatal = 'fatal',\n /** JSDoc */\n Error = 'error',\n /** JSDoc */\n Warning = 'warning',\n /** JSDoc */\n Log = 'log',\n /** JSDoc */\n Info = 'info',\n /** JSDoc */\n Debug = 'debug',\n /** JSDoc */\n Critical = 'critical',\n}\n\n// TODO: in v7, these can disappear, because they now also exist in `@sentry/utils`. (Having them there rather than here\n// is nice because then it enforces the idea that only types are exported from `@sentry/types`.)\nexport const SeverityLevels = ['fatal', 'error', 'warning', 'log', 'info', 'debug', 'critical'] as const;\nexport type SeverityLevel = typeof SeverityLevels[number];\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\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport { Integration } from '@sentry/types';\n\nimport { isNodeEnv } from './node';\n\n/** Internal */\ninterface SentryGlobal {\n Sentry?: {\n Integrations?: Integration[];\n };\n SENTRY_ENVIRONMENT?: string;\n SENTRY_DSN?: string;\n SENTRY_RELEASE?: {\n id?: string;\n };\n __SENTRY__: {\n globalEventProcessors: any;\n hub: any;\n logger: any;\n };\n}\n\nconst fallbackGlobalObject = {};\n\n/**\n * Safely get global scope object\n *\n * @returns Global scope object\n */\nexport function getGlobalObject<T>(): T & SentryGlobal {\n return (\n isNodeEnv()\n ? global\n : typeof window !== 'undefined' // eslint-disable-line no-restricted-globals\n ? window // eslint-disable-line no-restricted-globals\n : typeof self !== 'undefined'\n ? self\n : fallbackGlobalObject\n ) as T & SentryGlobal;\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 `getGlobalObject`'s return value\n * @returns the singleton\n */\nexport function getGlobalSingleton<T>(name: keyof SentryGlobal['__SENTRY__'], creator: () => T, obj?: unknown): T {\n const global = (obj || getGlobalObject()) as SentryGlobal;\n const __SENTRY__ = (global.__SENTRY__ = global.__SENTRY__ || {});\n const singleton = __SENTRY__[name] || (__SENTRY__[name] = creator());\n return singleton;\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/explicit-module-boundary-types */\n\nimport { 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\nfunction isBuiltin(wat: unknown, ty: string): boolean {\n return objectToString.call(wat) === `[object ${ty}]`;\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 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 || (typeof wat !== 'object' && typeof wat !== 'function');\n}\n\n/**\n * Checks whether given value's type is an object literal\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<string, unknown> {\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): boolean {\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<any> {\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","import { getGlobalObject } from './global';\nimport { isString } from './is';\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(elem: unknown, keyAttrs?: string[]): string {\n type SimpleNode = {\n parentNode: SimpleNode;\n } | null;\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 MAX_OUTPUT_LEN = 80;\n const out = [];\n let height = 0;\n let len = 0;\n const separator = ' > ';\n const sepLength = separator.length;\n let nextStr;\n\n // eslint-disable-next-line no-plusplus\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 MAX_OUTPUT_LEN\n // (ignore this limit if we are on the first iteration)\n if (nextStr === 'html' || (height > 1 && len + out.length * sepLength + nextStr.length >= MAX_OUTPUT_LEN)) {\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 '<unknown>';\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 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 = ['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 const global = getGlobalObject<Window>();\n try {\n return global.document.location.href;\n } catch (oO) {\n return '';\n }\n}\n","export const setPrototypeOf =\n Object.setPrototypeOf || ({ __proto__: [] } instanceof Array ? setProtoOf : mixinProperties);\n\n/**\n * setPrototypeOf polyfill using __proto__\n */\n// eslint-disable-next-line @typescript-eslint/ban-types\nfunction setProtoOf<TTarget extends object, TProto>(obj: TTarget, proto: TProto): TTarget & TProto {\n // @ts-ignore __proto__ does not exist on obj\n obj.__proto__ = proto;\n return obj as TTarget & TProto;\n}\n\n/**\n * setPrototypeOf polyfill using mixin\n */\n// eslint-disable-next-line @typescript-eslint/ban-types\nfunction mixinProperties<TTarget extends object, TProto>(obj: TTarget, proto: TProto): TTarget & TProto {\n for (const prop in proto) {\n if (!Object.prototype.hasOwnProperty.call(obj, prop)) {\n // @ts-ignore typescript complains about indexing so we remove\n obj[prop] = proto[prop];\n }\n }\n\n return obj as TTarget & TProto;\n}\n","import { setPrototypeOf } from './polyfill';\n\n/** An error emitted by Sentry SDKs and related utilities. */\nexport class SentryError extends Error {\n /** Display name of this error instance. */\n public name: string;\n\n public constructor(public message: string) {\n super(message);\n\n this.name = new.target.prototype.constructor.name;\n setPrototypeOf(this, new.target.prototype);\n }\n}\n","import { DsnComponents, DsnLike, DsnProtocol } from '@sentry/types';\n\nimport { SentryError } from './error';\nimport { IS_DEBUG_BUILD } from './flags';\n\n/** Regular expression used to parse a Dsn. */\nconst DSN_REGEX = /^(?:(\\w+):)\\/\\/(?:(\\w+)(?::(\\w+))?@)([\\w.-]+)(?::(\\d+))?\\/(.+)/;\n\nfunction isValidProtocol(protocol?: string): protocol is DsnProtocol {\n return protocol === 'http' || protocol === 'https';\n}\n\n/**\n * Renders the string representation of this Dsn.\n *\n * By default, this will render the public representation without the password\n * component. To get the deprecated private representation, set `withPassword`\n * to true.\n *\n * @param withPassword When set to true, the password will be included.\n */\nexport function dsnToString(dsn: DsnComponents, withPassword: boolean = false): string {\n const { host, path, pass, port, projectId, protocol, publicKey } = dsn;\n return (\n `${protocol}://${publicKey}${withPassword && pass ? `:${pass}` : ''}` +\n `@${host}${port ? `:${port}` : ''}/${path ? `${path}/` : path}${projectId}`\n );\n}\n\nfunction dsnFromString(str: string): DsnComponents {\n const match = DSN_REGEX.exec(str);\n\n if (!match) {\n throw new SentryError(`Invalid Sentry Dsn: ${str}`);\n }\n\n const [protocol, publicKey, pass = '', host, port = '', lastPath] = match.slice(1);\n let path = '';\n let projectId = lastPath;\n\n const split = projectId.split('/');\n if (split.length > 1) {\n path = split.slice(0, -1).join('/');\n projectId = split.pop() as string;\n }\n\n if (projectId) {\n const projectMatch = projectId.match(/^\\d+/);\n if (projectMatch) {\n projectId = projectMatch[0];\n }\n }\n\n return dsnFromComponents({ host, pass, path, projectId, port, protocol: protocol as DsnProtocol, publicKey });\n}\n\nfunction dsnFromComponents(components: DsnComponents): DsnComponents {\n // TODO this is for backwards compatibility, and can be removed in a future version\n if ('user' in components && !('publicKey' in components)) {\n components.publicKey = components.user;\n }\n\n return {\n user: components.publicKey || '',\n protocol: components.protocol,\n publicKey: components.publicKey || '',\n pass: components.pass || '',\n host: components.host,\n port: components.port || '',\n path: components.path || '',\n projectId: components.projectId,\n };\n}\n\nfunction validateDsn(dsn: DsnComponents): boolean | void {\n if (!IS_DEBUG_BUILD) {\n return;\n }\n\n const { port, projectId, protocol } = dsn;\n\n const requiredComponents: ReadonlyArray<keyof DsnComponents> = ['protocol', 'publicKey', 'host', 'projectId'];\n requiredComponents.forEach(component => {\n if (!dsn[component]) {\n throw new SentryError(`Invalid Sentry Dsn: ${component} missing`);\n }\n });\n\n if (!projectId.match(/^\\d+$/)) {\n throw new SentryError(`Invalid Sentry Dsn: Invalid projectId ${projectId}`);\n }\n\n if (!isValidProtocol(protocol)) {\n throw new SentryError(`Invalid Sentry Dsn: Invalid protocol ${protocol}`);\n }\n\n if (port && isNaN(parseInt(port, 10))) {\n throw new SentryError(`Invalid Sentry Dsn: Invalid port ${port}`);\n }\n\n return true;\n}\n\n/** The Sentry Dsn, identifying a Sentry instance and project. */\nexport function makeDsn(from: DsnLike): DsnComponents {\n const components = typeof from === 'string' ? dsnFromString(from) : dsnFromComponents(from);\n\n validateDsn(components);\n\n return components;\n}\n","export const SeverityLevels = ['fatal', 'error', 'warning', 'log', 'info', 'debug', 'critical'] as const;\nexport type SeverityLevel = typeof SeverityLevels[number];\n","import { WrappedFunction } from '@sentry/types';\n\nimport { IS_DEBUG_BUILD } from './flags';\nimport { getGlobalObject, getGlobalSingleton } from './global';\n\n// TODO: Implement different loggers for different environments\nconst global = getGlobalObject<Window | NodeJS.Global>();\n\n/** Prefix for logging strings */\nconst PREFIX = 'Sentry Logger ';\n\nexport const CONSOLE_LEVELS = ['debug', 'info', 'warn', 'error', 'log', 'assert'] as const;\n\ntype LoggerMethod = (...args: unknown[]) => void;\ntype LoggerConsoleMethods = Record<typeof CONSOLE_LEVELS[number], LoggerMethod>;\n\n/** JSDoc */\ninterface Logger extends LoggerConsoleMethods {\n disable(): void;\n enable(): void;\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<T>(callback: () => T): T {\n const global = getGlobalObject<Window>();\n\n if (!('console' in global)) {\n return callback();\n }\n\n const originalConsole = global.console as Console & Record<string, unknown>;\n const wrappedLevels: Partial<LoggerConsoleMethods> = {};\n\n // Restore all wrapped console methods\n CONSOLE_LEVELS.forEach(level => {\n // TODO(v7): Remove this check as it's only needed for Node 6\n const originalWrappedFunc =\n originalConsole[level] && (originalConsole[level] as WrappedFunction).__sentry_original__;\n if (level in global.console && originalWrappedFunc) {\n wrappedLevels[level] = originalConsole[level] as LoggerConsoleMethods[typeof level];\n originalConsole[level] = originalWrappedFunc as Console[typeof level];\n }\n });\n\n try {\n return callback();\n } finally {\n // Revert restoration to wrapped state\n Object.keys(wrappedLevels).forEach(level => {\n originalConsole[level] = wrappedLevels[level as typeof CONSOLE_LEVELS[number]];\n });\n }\n}\n\nfunction makeLogger(): Logger {\n let enabled = false;\n const logger: Partial<Logger> = {\n enable: () => {\n enabled = true;\n },\n disable: () => {\n enabled = false;\n },\n };\n\n if (IS_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.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\n// Ensure we only have a single logger instance, even if multiple versions of @sentry/utils are being used\nlet logger: Logger;\nif (IS_DEBUG_BUILD) {\n logger = getGlobalSingleton('logger', makeLogger);\n} else {\n logger = makeLogger();\n}\n\nexport { logger };\n","import { isRegExp, isString } from './is';\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.substr(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 output.push(String(value));\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 value matches a regex or includes the string\n * @param value The string value to be checked against\n * @param pattern Either a regex or a string that must be contained in value\n */\nexport function isMatchingPattern(value: string, pattern: RegExp | string): boolean {\n if (!isString(value)) {\n return false;\n }\n\n if (isRegExp(pattern)) {\n return pattern.test(value);\n }\n if (typeof pattern === 'string') {\n return value.indexOf(pattern) !== -1;\n }\n return false;\n}\n\n/**\n * Given a string, escape characters which have meaning in the regex grammar, such that the result is safe to feed to\n * `new RegExp()`.\n *\n * Based on https://github.com/sindresorhus/escape-string-regexp. Vendored to a) reduce the size by skipping the runtime\n * type-checking, and b) ensure it gets down-compiled for old versions of Node (the published package only supports Node\n * 12+).\n *\n * @param regexString The string to escape\n * @returns An version of the string with all special regex characters escaped\n */\nexport function escapeStringForRegex(regexString: string): string {\n // escape the hyphen separately so we can also replace it with a unicode literal hyphen, to avoid the problems\n // discussed in https://github.com/sindresorhus/escape-string-regexp/issues/20.\n return regexString.replace(/[|\\\\{}()[\\]^$+*?.]/g, '\\\\$&').replace(/-/g, '\\\\x2d');\n}\n","/* eslint-disable max-lines */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { ExtendedError, WrappedFunction } from '@sentry/types';\n\nimport { htmlTreeAsString } from './browser';\nimport { isElement, isError, isEvent, isInstanceOf, isPlainObject, isPrimitive } from './is';\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, <other\n * args>)` or `origMethod.apply(this, [<other args>])` (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 try {\n markFunctionWrapped(wrapped, original);\n } catch (_Oo) {\n // This can throw if multiple fill happens on a global object like XMLHttpRequest\n // Fixes https://github.com/getsentry/sentry-javascript/issues/2043\n }\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: { [key: string]: unknown }, name: string, value: unknown): void {\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}\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 const proto = original.prototype || {};\n wrapped.prototype = original.prototype = proto;\n addNonEnumerableProperty(wrapped, '__sentry_original__', original);\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 object into an object literal with all its attributes\n * attached to it.\n *\n * @param value Initial source that we have to transform in order for it to be usable by the serializer\n */\nexport function convertToPlainObject(value: unknown): {\n [key: string]: unknown;\n} {\n let newObj = value as {\n [key: string]: unknown;\n };\n\n if (isError(value)) {\n newObj = {\n message: value.message,\n name: value.name,\n stack: value.stack,\n ...getOwnProperties(value as ExtendedError),\n };\n } else if (isEvent(value)) {\n /**\n * Event-like interface that's usable in browser and node\n */\n interface SimpleEvent {\n [key: string]: unknown;\n type: string;\n target?: unknown;\n currentTarget?: unknown;\n }\n\n const event = value as SimpleEvent;\n\n newObj = {\n type: event.type,\n target: serializeEventTarget(event.target),\n currentTarget: serializeEventTarget(event.currentTarget),\n ...getOwnProperties(event),\n };\n\n if (typeof CustomEvent !== 'undefined' && isInstanceOf(value, CustomEvent)) {\n newObj.detail = event.detail;\n }\n }\n return newObj;\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 '<unknown>';\n }\n}\n\n/** Filters out all but an object's own properties */\nfunction getOwnProperties(obj: { [key: string]: unknown }): { [key: string]: unknown } {\n const extractedProps: { [key: string]: unknown } = {};\n for (const property in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, property)) {\n extractedProps[property] = obj[property];\n }\n }\n return extractedProps;\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 */\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\nexport function extractExceptionKeysForMessage(exception: any, 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 the new object with removed keys that value was `undefined`.\n * Works recursively on objects and arrays.\n */\nexport function dropUndefinedKeys<T>(val: T): T {\n if (isPlainObject(val)) {\n const rv: { [key: string]: any } = {};\n for (const key of Object.keys(val)) {\n if (typeof val[key] !== 'undefined') {\n rv[key] = dropUndefinedKeys(val[key]);\n }\n }\n return rv as T;\n }\n\n if (Array.isArray(val)) {\n return (val as any[]).map(dropUndefinedKeys) as any;\n }\n\n return val;\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","import { StackFrame } from '@sentry/types';\n\nconst STACKTRACE_LIMIT = 50;\n\nexport type StackParser = (stack: string, skipFirst?: number) => StackFrame[];\nexport type StackLineParserFn = (line: string) => StackFrame | undefined;\nexport type StackLineParser = [number, StackLineParserFn];\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\n for (const line of stack.split('\\n').slice(skipFirst)) {\n for (const parser of sortedParsers) {\n const frame = parser(line);\n\n if (frame) {\n frames.push(frame);\n break;\n }\n }\n }\n\n return stripSentryFramesAndReverse(frames);\n };\n}\n\n/**\n * @hidden\n */\nexport function stripSentryFramesAndReverse(stack: StackFrame[]): StackFrame[] {\n if (!stack.length) {\n return [];\n }\n\n let localStack = stack;\n\n const firstFrameFunction = localStack[0].function || '';\n const lastFrameFunction = localStack[localStack.length - 1].function || '';\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 (firstFrameFunction.indexOf('captureMessage') !== -1 || firstFrameFunction.indexOf('captureException') !== -1) {\n localStack = localStack.slice(1);\n }\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 (lastFrameFunction.indexOf('sentryWrapped') !== -1) {\n localStack = localStack.slice(0, -1);\n }\n\n // The frame where the crash happened, should be the last entry in the array\n return localStack\n .slice(0, STACKTRACE_LIMIT)\n .map(frame => ({\n ...frame,\n filename: frame.filename || localStack[0].filename,\n function: frame.function || '?',\n }))\n .reverse();\n}\n\nconst defaultFunctionName = '<anonymous>';\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","import { IS_DEBUG_BUILD } from './flags';\nimport { getGlobalObject } from './global';\nimport { logger } from './logger';\n\n/**\n * Tells whether current environment supports ErrorEvent objects\n * {@link supportsErrorEvent}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsErrorEvent(): boolean {\n try {\n new ErrorEvent('');\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports DOMError objects\n * {@link supportsDOMError}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsDOMError(): boolean {\n try {\n // Chrome: VM89:1 Uncaught TypeError: Failed to construct 'DOMError':\n // 1 argument required, but only 0 present.\n // @ts-ignore It really needs 1 argument, not 0.\n new DOMError('');\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports DOMException objects\n * {@link supportsDOMException}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsDOMException(): boolean {\n try {\n new DOMException('');\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports Fetch API\n * {@link supportsFetch}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsFetch(): boolean {\n if (!('fetch' in getGlobalObject<Window>())) {\n return false;\n }\n\n try {\n new Headers();\n new Request('');\n new Response();\n return true;\n } catch (e) {\n return false;\n }\n}\n/**\n * isNativeFetch checks if the given function is a native implementation of fetch()\n */\n// eslint-disable-next-line @typescript-eslint/ban-types\nexport function isNativeFetch(func: Function): boolean {\n return func && /^function fetch\\(\\)\\s+\\{\\s+\\[native code\\]\\s+\\}$/.test(func.toString());\n}\n\n/**\n * Tells whether current environment supports Fetch API natively\n * {@link supportsNativeFetch}.\n *\n * @returns true if `window.fetch` is natively implemented, false otherwise\n */\nexport function supportsNativeFetch(): boolean {\n if (!supportsFetch()) {\n return false;\n }\n\n const global = getGlobalObject<Window>();\n\n // Fast path to avoid DOM I/O\n // eslint-disable-next-line @typescript-eslint/unbound-method\n if (isNativeFetch(global.fetch)) {\n return true;\n }\n\n // window.fetch is implemented, but is polyfilled or already wrapped (e.g: by a chrome extension)\n // so create a \"pure\" iframe to see if that has native fetch\n let result = false;\n const doc = global.document;\n // eslint-disable-next-line deprecation/deprecation\n if (doc && typeof (doc.createElement as unknown) === 'function') {\n try {\n const sandbox = doc.createElement('iframe');\n sandbox.hidden = true;\n doc.head.appendChild(sandbox);\n if (sandbox.contentWindow && sandbox.contentWindow.fetch) {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n result = isNativeFetch(sandbox.contentWindow.fetch);\n }\n doc.head.removeChild(sandbox);\n } catch (err) {\n IS_DEBUG_BUILD &&\n logger.warn('Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ', err);\n }\n }\n\n return result;\n}\n\n/**\n * Tells whether current environment supports ReportingObserver API\n * {@link supportsReportingObserver}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsReportingObserver(): boolean {\n return 'ReportingObserver' in getGlobalObject();\n}\n\n/**\n * Tells whether current environment supports Referrer Policy API\n * {@link supportsReferrerPolicy}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsReferrerPolicy(): boolean {\n // Despite all stars in the sky saying that Edge supports old draft syntax, aka 'never', 'always', 'origin' and 'default'\n // (see https://caniuse.com/#feat=referrer-policy),\n // it doesn't. And it throws an exception instead of ignoring this parameter...\n // REF: https://github.com/getsentry/raven-js/issues/1233\n\n if (!supportsFetch()) {\n return false;\n }\n\n try {\n new Request('_', {\n referrerPolicy: 'origin' as ReferrerPolicy,\n });\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports History API\n * {@link supportsHistory}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsHistory(): boolean {\n // NOTE: in Chrome App environment, touching history.pushState, *even inside\n // a try/catch block*, will cause Chrome to output an error to console.error\n // borrowed from: https://github.com/angular/angular.js/pull/13945/files\n const global = getGlobalObject<Window>();\n /* eslint-disable @typescript-eslint/no-unsafe-member-access */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const chrome = (global as any).chrome;\n const isChromePackagedApp = chrome && chrome.app && chrome.app.runtime;\n /* eslint-enable @typescript-eslint/no-unsafe-member-access */\n const hasHistoryApi = 'history' in global && !!global.history.pushState && !!global.history.replaceState;\n\n return !isChromePackagedApp && hasHistoryApi;\n}\n","/* eslint-disable max-lines */\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/ban-types */\nimport { WrappedFunction } from '@sentry/types';\n\nimport { IS_DEBUG_BUILD } from './flags';\nimport { getGlobalObject } from './global';\nimport { isInstanceOf, isString } from './is';\nimport { CONSOLE_LEVELS, logger } from './logger';\nimport { fill } from './object';\nimport { getFunctionName } from './stacktrace';\nimport { supportsHistory, supportsNativeFetch } from './supports';\n\nconst global = getGlobalObject<Window>();\n\ntype InstrumentHandlerType =\n | 'console'\n | 'dom'\n | 'fetch'\n | 'history'\n | 'sentry'\n | 'xhr'\n | 'error'\n | 'unhandledrejection';\ntype InstrumentHandlerCallback = (data: any) => void;\n\n/**\n * Instrument native APIs to call handlers that can be used to create breadcrumbs, APM spans etc.\n * - Console API\n * - Fetch API\n * - XHR API\n * - History API\n * - DOM API (click/typing)\n * - Error API\n * - UnhandledRejection API\n */\n\nconst handlers: { [key in InstrumentHandlerType]?: InstrumentHandlerCallback[] } = {};\nconst instrumented: { [key in InstrumentHandlerType]?: boolean } = {};\n\n/** Instruments given API */\nfunction instrument(type: InstrumentHandlerType): void {\n if (instrumented[type]) {\n return;\n }\n\n instrumented[type] = true;\n\n switch (type) {\n case 'console':\n instrumentConsole();\n break;\n case 'dom':\n instrumentDOM();\n break;\n case 'xhr':\n instrumentXHR();\n break;\n case 'fetch':\n instrumentFetch();\n break;\n case 'history':\n instrumentHistory();\n break;\n case 'error':\n instrumentError();\n break;\n case 'unhandledrejection':\n instrumentUnhandledRejection();\n break;\n default:\n IS_DEBUG_BUILD && logger.warn('unknown instrumentation type:', type);\n return;\n }\n}\n\n/**\n * Add handler that will be called when given type of instrumentation triggers.\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nexport function addInstrumentationHandler(type: InstrumentHandlerType, callback: InstrumentHandlerCallback): void {\n handlers[type] = handlers[type] || [];\n (handlers[type] as InstrumentHandlerCallback[]).push(callback);\n instrument(type);\n}\n\n/** JSDoc */\nfunction triggerHandlers(type: InstrumentHandlerType, data: any): void {\n if (!type || !handlers[type]) {\n return;\n }\n\n for (const handler of handlers[type] || []) {\n try {\n handler(data);\n } catch (e) {\n IS_DEBUG_BUILD &&\n logger.error(\n `Error while triggering instrumentation handler.\\nType: ${type}\\nName: ${getFunctionName(handler)}\\nError:`,\n e,\n );\n }\n }\n}\n\n/** JSDoc */\nfunction instrumentConsole(): void {\n if (!('console' in global)) {\n return;\n }\n\n CONSOLE_LEVELS.forEach(function (level: string): void {\n if (!(level in global.console)) {\n return;\n }\n\n fill(global.console, level, function (originalConsoleMethod: () => any): Function {\n return function (...args: any[]): void {\n triggerHandlers('console', { args, level });\n\n // this fails for some browsers. :(\n if (originalConsoleMethod) {\n originalConsoleMethod.apply(global.console, args);\n }\n };\n });\n });\n}\n\n/** JSDoc */\nfunction instrumentFetch(): void {\n if (!supportsNativeFetch()) {\n return;\n }\n\n fill(global, 'fetch', function (originalFetch: () => void): () => void {\n return function (...args: any[]): void {\n const handlerData = {\n args,\n fetchData: {\n method: getFetchMethod(args),\n url: getFetchUrl(args),\n },\n startTimestamp: Date.now(),\n };\n\n triggerHandlers('fetch', {\n ...handlerData,\n });\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return originalFetch.apply(global, args).then(\n (response: Response) => {\n triggerHandlers('fetch', {\n ...handlerData,\n endTimestamp: Date.now(),\n response,\n });\n return response;\n },\n (error: Error) => {\n triggerHandlers('fetch', {\n ...handlerData,\n endTimestamp: Date.now(),\n error,\n });\n // NOTE: If you are a Sentry user, and you are seeing this stack frame,\n // it means the sentry.javascript SDK caught an error invoking your application code.\n // This is expected behavior and NOT indicative of a bug with sentry.javascript.\n throw error;\n },\n );\n };\n });\n}\n\ntype XHRSendInput = null | Blob | BufferSource | FormData | URLSearchParams | string;\n\n/** JSDoc */\ninterface SentryWrappedXMLHttpRequest extends XMLHttpRequest {\n [key: string]: any;\n __sentry_xhr__?: {\n method?: string;\n url?: string;\n status_code?: number;\n body?: XHRSendInput;\n };\n}\n\n/* eslint-disable @typescript-eslint/no-unsafe-member-access */\n/** Extract `method` from fetch call arguments */\nfunction getFetchMethod(fetchArgs: any[] = []): string {\n if ('Request' in global && isInstanceOf(fetchArgs[0], Request) && fetchArgs[0].method) {\n return String(fetchArgs[0].method).toUpperCase();\n }\n if (fetchArgs[1] && fetchArgs[1].method) {\n return String(fetchArgs[1].method).toUpperCase();\n }\n return 'GET';\n}\n\n/** Extract `url` from fetch call arguments */\nfunction getFetchUrl(fetchArgs: any[] = []): string {\n if (typeof fetchArgs[0] === 'string') {\n return fetchArgs[0];\n }\n if ('Request' in global && isInstanceOf(fetchArgs[0], Request)) {\n return fetchArgs[0].url;\n }\n return String(fetchArgs[0]);\n}\n/* eslint-enable @typescript-eslint/no-unsafe-member-access */\n\n/** JSDoc */\nfunction instrumentXHR(): void {\n if (!('XMLHttpRequest' in global)) {\n return;\n }\n\n const xhrproto = XMLHttpRequest.prototype;\n\n fill(xhrproto, 'open', function (originalOpen: () => void): () => void {\n return function (this: SentryWrappedXMLHttpRequest, ...args: any[]): void {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const xhr = this;\n const url = args[1];\n const xhrInfo: SentryWrappedXMLHttpRequest['__sentry_xhr__'] = (xhr.__sentry_xhr__ = {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n method: isString(args[0]) ? args[0].toUpperCase() : args[0],\n url: args[1],\n });\n\n // if Sentry key appears in URL, don't capture it as a request\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if (isString(url) && xhrInfo.method === 'POST' && url.match(/sentry_key/)) {\n xhr.__sentry_own_request__ = true;\n }\n\n const onreadystatechangeHandler = function (): void {\n if (xhr.readyState === 4) {\n try {\n // touching statusCode in some platforms throws\n // an exception\n xhrInfo.status_code = xhr.status;\n } catch (e) {\n /* do nothing */\n }\n\n triggerHandlers('xhr', {\n args,\n endTimestamp: Date.now(),\n startTimestamp: Date.now(),\n xhr,\n });\n }\n };\n\n if ('onreadystatechange' in xhr && typeof xhr.onreadystatechange === 'function') {\n fill(xhr, 'onreadystatechange', function (original: WrappedFunction): Function {\n return function (...readyStateArgs: any[]): void {\n onreadystatechangeHandler();\n return original.apply(xhr, readyStateArgs);\n };\n });\n } else {\n xhr.addEventListener('readystatechange', onreadystatechangeHandler);\n }\n\n return originalOpen.apply(xhr, args);\n };\n });\n\n fill(xhrproto, 'send', function (originalSend: () => void): () => void {\n return function (this: SentryWrappedXMLHttpRequest, ...args: any[]): void {\n if (this.__sentry_xhr__ && args[0] !== undefined) {\n this.__sentry_xhr__.body = args[0];\n }\n\n triggerHandlers('xhr', {\n args,\n startTimestamp: Date.now(),\n xhr: this,\n });\n\n return originalSend.apply(this, args);\n };\n });\n}\n\nlet lastHref: string;\n\n/** JSDoc */\nfunction instrumentHistory(): void {\n if (!supportsHistory()) {\n return;\n }\n\n const oldOnPopState = global.onpopstate;\n global.onpopstate = function (this: WindowEventHandlers, ...args: any[]): any {\n const to = global.location.href;\n // keep track of the current URL state, as we always receive only the updated state\n const from = lastHref;\n lastHref = to;\n triggerHandlers('history', {\n from,\n to,\n });\n if (oldOnPopState) {\n // Apparently this can throw in Firefox when incorrectly implemented plugin is installed.\n // https://github.com/getsentry/sentry-javascript/issues/3344\n // https://github.com/bugsnag/bugsnag-js/issues/469\n try {\n return oldOnPopState.apply(this, args);\n } catch (_oO) {\n // no-empty\n }\n }\n };\n\n /** @hidden */\n function historyReplacementFunction(originalHistoryFunction: () => void): () => void {\n return function (this: History, ...args: any[]): void {\n const url = args.length > 2 ? args[2] : undefined;\n if (url) {\n // coerce to string (this is what pushState does)\n const from = lastHref;\n const to = String(url);\n // keep track of the current URL state, as we always receive only the updated state\n lastHref = to;\n triggerHandlers('history', {\n from,\n to,\n });\n }\n return originalHistoryFunction.apply(this, args);\n };\n }\n\n fill(global.history, 'pushState', historyReplacementFunction);\n fill(global.history, 'replaceState', historyReplacementFunction);\n}\n\nconst debounceDuration = 1000;\nlet debounceTimerID: number | undefined;\nlet lastCapturedEvent: Event | undefined;\n\n/**\n * Decide whether the current event should finish the debounce of previously captured one.\n * @param previous previously captured event\n * @param current event to be captured\n */\nfunction shouldShortcircuitPreviousDebounce(previous: Event | undefined, current: Event): boolean {\n // If there was no previous event, it should always be swapped for the new one.\n if (!previous) {\n return true;\n }\n\n // If both events have different type, then user definitely performed two separate actions. e.g. click + keypress.\n if (previous.type !== current.type) {\n return true;\n }\n\n try {\n // If both events have the same type, it's still possible that actions were performed on different targets.\n // e.g. 2 clicks on different buttons.\n if (previous.target !== current.target) {\n return true;\n }\n } catch (e) {\n // just accessing `target` property can throw an exception in some rare circumstances\n // see: https://github.com/getsentry/sentry-javascript/issues/838\n }\n\n // If both events have the same type _and_ same `target` (an element which triggered an event, _not necessarily_\n // to which an event listener was attached), we treat them as the same action, as we want to capture\n // only one breadcrumb. e.g. multiple clicks on the same button, or typing inside a user input box.\n return false;\n}\n\n/**\n * Decide whether an event should be captured.\n * @param event event to be captured\n */\nfunction shouldSkipDOMEvent(event: Event): boolean {\n // We are only interested in filtering `keypress` events for now.\n if (event.type !== 'keypress') {\n return false;\n }\n\n try {\n const target = event.target as HTMLElement;\n\n if (!target || !target.tagName) {\n return true;\n }\n\n // Only consider keypress events on actual input elements. This will disregard keypresses targeting body\n // e.g.tabbing through elements, hotkeys, etc.\n if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable) {\n return false;\n }\n } catch (e) {\n // just accessing `target` property can throw an exception in some rare circumstances\n // see: https://github.com/getsentry/sentry-javascript/issues/838\n }\n\n return true;\n}\n\n/**\n * Wraps addEventListener to capture UI breadcrumbs\n * @param handler function that will be triggered\n * @param globalListener indicates whether event was captured by the global event listener\n * @returns wrapped breadcrumb events handler\n * @hidden\n */\nfunction makeDOMEventHandler(handler: Function, globalListener: boolean = false): (event: Event) => void {\n return (event: Event): void => {\n // It's possible this handler might trigger multiple times for the same\n // event (e.g. event propagation through node ancestors).\n // Ignore if we've already captured that event.\n if (!event || lastCapturedEvent === event) {\n return;\n }\n\n // We always want to skip _some_ events.\n if (shouldSkipDOMEvent(event)) {\n return;\n }\n\n const name = event.type === 'keypress' ? 'input' : event.type;\n\n // If there is no debounce timer, it means that we can safely capture the new event and store it for future comparisons.\n if (debounceTimerID === undefined) {\n handler({\n event: event,\n name,\n global: globalListener,\n });\n lastCapturedEvent = event;\n }\n // If there is a debounce awaiting, see if the new event is different enough to treat it as a unique one.\n // If that's the case, emit the previous event and store locally the newly-captured DOM event.\n else if (shouldShortcircuitPreviousDebounce(lastCapturedEvent, event)) {\n handler({\n event: event,\n name,\n global: globalListener,\n });\n lastCapturedEvent = event;\n }\n\n // Start a new debounce timer that will prevent us from capturing multiple events that should be grouped together.\n clearTimeout(debounceTimerID);\n debounceTimerID = global.setTimeout(() => {\n debounceTimerID = undefined;\n }, debounceDuration);\n };\n}\n\ntype AddEventListener = (\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | AddEventListenerOptions,\n) => void;\ntype RemoveEventListener = (\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | EventListenerOptions,\n) => void;\n\ntype InstrumentedElement = Element & {\n __sentry_instrumentation_handlers__?: {\n [key in 'click' | 'keypress']?: {\n handler?: Function;\n /** The number of custom listeners attached to this element */\n refCount: number;\n };\n };\n};\n\n/** JSDoc */\nfunction instrumentDOM(): void {\n if (!('document' in global)) {\n return;\n }\n\n // Make it so that any click or keypress that is unhandled / bubbled up all the way to the document triggers our dom\n // handlers. (Normally we have only one, which captures a breadcrumb for each click or keypress.) Do this before\n // we instrument `addEventListener` so that we don't end up attaching this handler twice.\n const triggerDOMHandler = triggerHandlers.bind(null, 'dom');\n const globalDOMEventHandler = makeDOMEventHandler(triggerDOMHandler, true);\n global.document.addEventListener('click', globalDOMEventHandler, false);\n global.document.addEventListener('keypress', globalDOMEventHandler, false);\n\n // After hooking into click and keypress events bubbled up to `document`, we also hook into user-handled\n // clicks & keypresses, by adding an event listener of our own to any element to which they add a listener. That\n // way, whenever one of their handlers is triggered, ours will be, too. (This is needed because their handler\n // could potentially prevent the event from bubbling up to our global listeners. This way, our handler are still\n // guaranteed to fire at least once.)\n ['EventTarget', 'Node'].forEach((target: string) => {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n const proto = (global as any)[target] && (global as any)[target].prototype;\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, no-prototype-builtins\n if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty('addEventListener')) {\n return;\n }\n\n fill(proto, 'addEventListener', function (originalAddEventListener: AddEventListener): AddEventListener {\n return function (\n this: Element,\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | AddEventListenerOptions,\n ): AddEventListener {\n if (type === 'click' || type == 'keypress') {\n try {\n const el = this as InstrumentedElement;\n const handlers = (el.__sentry_instrumentation_handlers__ = el.__sentry_instrumentation_handlers__ || {});\n const handlerForType = (handlers[type] = handlers[type] || { refCount: 0 });\n\n if (!handlerForType.handler) {\n const handler = makeDOMEventHandler(triggerDOMHandler);\n handlerForType.handler = handler;\n originalAddEventListener.call(this, type, handler, options);\n }\n\n handlerForType.refCount += 1;\n } catch (e) {\n // Accessing dom properties is always fragile.\n // Also allows us to skip `addEventListenrs` calls with no proper `this` context.\n }\n }\n\n return originalAddEventListener.call(this, type, listener, options);\n };\n });\n\n fill(\n proto,\n 'removeEventListener',\n function (originalRemoveEventListener: RemoveEventListener): RemoveEventListener {\n return function (\n this: Element,\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | EventListenerOptions,\n ): () => void {\n if (type === 'click' || type == 'keypress') {\n try {\n const el = this as InstrumentedElement;\n const handlers = el.__sentry_instrumentation_handlers__ || {};\n const handlerForType = handlers[type];\n\n if (handlerForType) {\n handlerForType.refCount -= 1;\n // If there are no longer any custom handlers of the current type on this element, we can remove ours, too.\n if (handlerForType.refCount <= 0) {\n originalRemoveEventListener.call(this, type, handlerForType.handler, options);\n handlerForType.handler = undefined;\n delete handlers[type]; // eslint-disable-line @typescript-eslint/no-dynamic-delete\n }\n\n // If there are no longer any custom handlers of any type on this element, cleanup everything.\n if (Object.keys(handlers).length === 0) {\n delete el.__sentry_instrumentation_handlers__;\n }\n }\n } catch (e) {\n // Accessing dom properties is always fragile.\n // Also allows us to skip `addEventListenrs` calls with no proper `this` context.\n }\n }\n\n return originalRemoveEventListener.call(this, type, listener, options);\n };\n },\n );\n });\n}\n\nlet _oldOnErrorHandler: OnErrorEventHandler = null;\n/** JSDoc */\nfunction instrumentError(): void {\n _oldOnErrorHandler = global.onerror;\n\n global.onerror = function (msg: any, url: any, line: any, column: any, error: any): boolean {\n triggerHandlers('error', {\n column,\n error,\n line,\n msg,\n url,\n });\n\n if (_oldOnErrorHandler) {\n // eslint-disable-next-line prefer-rest-params\n return _oldOnErrorHandler.apply(this, arguments);\n }\n\n return false;\n };\n}\n\nlet _oldOnUnhandledRejectionHandler: ((e: any) => void) | null = null;\n/** JSDoc */\nfunction instrumentUnhandledRejection(): void {\n _oldOnUnhandledRejectionHandler = global.onunhandledrejection;\n\n global.onunhandledrejection = function (e: any): boolean {\n triggerHandlers('unhandledrejection', e);\n\n if (_oldOnUnhandledRejectionHandler) {\n // eslint-disable-next-line prefer-rest-params\n return _oldOnUnhandledRejectionHandler.apply(this, arguments);\n }\n\n return true;\n };\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { Event, Exception, Mechanism, StackFrame } from '@sentry/types';\n\nimport { getGlobalObject } from './global';\nimport { addNonEnumerableProperty } from './object';\nimport { snipLine } from './string';\n\n/**\n * Extended Window interface that allows for Crypto API usage in IE browsers\n */\ninterface MsCryptoWindow extends Window {\n msCrypto?: Crypto;\n}\n\n/**\n * UUID4 generator\n *\n * @returns string Generated UUID4.\n */\nexport function uuid4(): string {\n const global = getGlobalObject() as MsCryptoWindow;\n const crypto = global.crypto || global.msCrypto;\n\n if (!(crypto === void 0) && crypto.getRandomValues) {\n // Use window.crypto API if available\n const arr = new Uint16Array(8);\n crypto.getRandomValues(arr);\n\n // set 4 in byte 7\n // eslint-disable-next-line no-bitwise\n arr[3] = (arr[3] & 0xfff) | 0x4000;\n // set 2 most significant bits of byte 9 to '10'\n // eslint-disable-next-line no-bitwise\n arr[4] = (arr[4] & 0x3fff) | 0x8000;\n\n const pad = (num: number): string => {\n let v = num.toString(16);\n while (v.length < 4) {\n v = `0${v}`;\n }\n return v;\n };\n\n return (\n pad(arr[0]) + pad(arr[1]) + pad(arr[2]) + pad(arr[3]) + pad(arr[4]) + pad(arr[5]) + pad(arr[6]) + pad(arr[7])\n );\n }\n // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523\n return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, c => {\n // eslint-disable-next-line no-bitwise\n const r = (Math.random() * 16) | 0;\n // eslint-disable-next-line no-bitwise\n const v = c === 'x' ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n}\n\n/**\n * Parses string form of URL into an object\n * // borrowed from https://tools.ietf.org/html/rfc3986#appendix-B\n * // intentionally using regex and not <a/> href parsing trick because React Native and other\n * // environments where DOM might not be available\n * @returns parsed URL object\n */\nexport function parseUrl(url: string): {\n host?: string;\n path?: string;\n protocol?: string;\n relative?: string;\n} {\n if (!url) {\n return {};\n }\n\n const match = url.match(/^(([^:/?#]+):)?(\\/\\/([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?$/);\n\n if (!match) {\n return {};\n }\n\n // coerce to undefined values to empty string so we don't get 'undefined'\n const query = match[6] || '';\n const fragment = match[8] || '';\n return {\n host: match[4],\n path: match[5],\n protocol: match[2],\n relative: match[5] + query + fragment, // everything minus origin\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 || '<unknown>';\n }\n return eventId || '<unknown>';\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<Mechanism>): 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 const lineno = frame.lineno || 0;\n const maxLines = lines.length;\n const sourceLine = Math.max(Math.min(maxLines, 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 * Strip the query string and fragment off of a given URL or path (if present)\n *\n * @param urlPath Full URL or path, including possible query string and/or fragment\n * @returns URL or path without query string or fragment\n */\nexport function stripUrlQueryAndFragment(urlPath: string): string {\n // eslint-disable-next-line no-useless-escape\n return urlPath.split(/[\\?#]/, 1)[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","import { Primitive } from '@sentry/types';\n\nimport { isError, isEvent, isNaN, isSyntheticEvent } from './is';\nimport { memoBuilder, MemoFunc } 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<T> = { [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 */\nexport function normalize(input: unknown, depth: number = +Infinity, maxProperties: number = +Infinity): any {\n try {\n // since we're at the outermost level, there is no key\n return visit('', input, depth, maxProperties);\n } catch (err) {\n return { ERROR: `**non-serializable** (${err})` };\n }\n}\n\n/** JSDoc */\nexport function normalizeToSize<T>(\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<unknown> {\n const [memoize, unmemoize] = memo;\n\n // If the value has a `toJSON` method, see if we can bail and let it do the work\n const valueWithToJSON = value as unknown & { toJSON?: () => Primitive | ObjOrArray<unknown> };\n if (valueWithToJSON && typeof valueWithToJSON.toJSON === 'function') {\n try {\n return valueWithToJSON.toJSON();\n } catch (err) {\n // pass (The built-in `toJSON` failed, but we can still try to do it ourselves)\n }\n }\n\n // Get the simple cases out of the way first\n if (value === null || (['number', 'boolean', 'string'].includes(typeof value) && !isNaN(value))) {\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 // We're also done if we've reached the max depth\n if (depth === 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 // 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<unknown>;\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 = (isError(value) || isEvent(value) ? convertToPlainObject(value) : value) as ObjOrArray<unknown>;\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, depth - 1, maxProperties, memo);\n\n numAdded += 1;\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// TODO remove this in v7 (this means the method will no longer be exported, under any name)\nexport { visit as walk };\n\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<unknown, string | number | boolean | null>,\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 // 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 // this catches `undefined` (but not `null`, which is a primitive and can be serialized on its own)\n if (value === void 0) {\n return '[undefined]';\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 return `[object ${(Object.getPrototypeOf(value) as Prototype).constructor.name}]`;\n } catch (err) {\n return `**non-serializable** (${err})`;\n }\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 */\nfunction jsonSize(value: any): number {\n return utf8Length(JSON.stringify(value));\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","/* 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/**\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<T>(value: T | PromiseLike<T>): PromiseLike<T> {\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<T = never>(reason?: any): PromiseLike<T> {\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<T> implements PromiseLike<T> {\n private _state: States = States.PENDING;\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<T> | null) => void, reject: (reason?: any) => void) => void,\n ) {\n try {\n executor(this._resolve, this._reject);\n } catch (e) {\n this._reject(e);\n }\n }\n\n /** JSDoc */\n public then<TResult1 = T, TResult2 = never>(\n onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | null,\n onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null,\n ): PromiseLike<TResult1 | TResult2> {\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<TResult = never>(\n onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | null,\n ): PromiseLike<T | TResult> {\n return this.then(val => val, onrejected);\n }\n\n /** JSDoc */\n public finally<TResult>(onfinally?: (() => void) | null): PromiseLike<TResult> {\n return new SyncPromise<TResult>((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<T> | 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<T> | any) => {\n if (this._state !== States.PENDING) {\n return;\n }\n\n if (isThenable(value)) {\n void (value as PromiseLike<T>).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 { SentryError } from './error';\nimport { rejectedSyncPromise, resolvedSyncPromise, SyncPromise } from './syncpromise';\n\nexport interface PromiseBuffer<T> {\n // exposes the internal array so tests can assert on the state of it.\n // XXX: this really should not be public api.\n $: Array<PromiseLike<T>>;\n add(taskProducer: () => PromiseLike<T>): PromiseLike<T>;\n drain(timeout?: number): PromiseLike<boolean>;\n}\n\n/**\n * Creates an new PromiseBuffer object with the specified limit\n * @param limit max number of promises that can be stored in the buffer\n */\nexport function makePromiseBuffer<T>(limit?: number): PromiseBuffer<T> {\n const buffer: Array<PromiseLike<T>> = [];\n\n function isReady(): boolean {\n return limit === undefined || buffer.length < limit;\n }\n\n /**\n * Remove a promise from the queue.\n *\n * @param task Can be any PromiseLike<T>\n * @returns Removed promise.\n */\n function remove(task: PromiseLike<T>): PromiseLike<T> {\n return buffer.splice(buffer.indexOf(task), 1)[0];\n }\n\n /**\n * Add a promise (representing an in-flight action) to the queue, and set it to remove itself on fulfillment.\n *\n * @param taskProducer A function producing any PromiseLike<T>; In previous versions this used to be `task:\n * PromiseLike<T>`, but under that model, Promises were instantly created on the call-site and their executor\n * functions therefore ran immediately. Thus, even if the buffer was full, the action still happened. By\n * requiring the promise to be wrapped in a function, we can defer promise creation until after the buffer\n * limit check.\n * @returns The original promise.\n */\n function add(taskProducer: () => PromiseLike<T>): PromiseLike<T> {\n if (!isReady()) {\n return rejectedSyncPromise(new SentryError('Not adding Promise due to buffer limit reached.'));\n }\n\n // start the task and add its promise to the queue\n const task = taskProducer();\n if (buffer.indexOf(task) === -1) {\n buffer.push(task);\n }\n void task\n .then(() => remove(task))\n // Use `then(null, rejectionHandler)` rather than `catch(rejectionHandler)` so that we can use `PromiseLike`\n // rather than `Promise`. `PromiseLike` doesn't have a `.catch` method, making its polyfill smaller. (ES5 didn't\n // have promises, so TS has to polyfill when down-compiling.)\n .then(null, () =>\n remove(task).then(null, () => {\n // We have to add another catch here because `remove()` starts a new promise chain.\n }),\n );\n return task;\n }\n\n /**\n * Wait for all promises in the queue to resolve or for timeout to expire, whichever comes first.\n *\n * @param timeout The time, in ms, after which to resolve to `false` if the queue is still non-empty. Passing `0` (or\n * not passing anything) will make the promise wait as long as it takes for the queue to drain before resolving to\n * `true`.\n * @returns A promise which will resolve to `true` if the queue is already empty or drains before the timeout, and\n * `false` otherwise\n */\n function drain(timeout?: number): PromiseLike<boolean> {\n return new SyncPromise<boolean>((resolve, reject) => {\n let counter = buffer.length;\n\n if (!counter) {\n return resolve(true);\n }\n\n // wait for `timeout` ms and then resolve to `false` (if not cancelled first)\n const capturedSetTimeout = setTimeout(() => {\n if (timeout && timeout > 0) {\n resolve(false);\n }\n }, timeout);\n\n // if all promises resolve in time, cancel the timer and resolve to `true`\n buffer.forEach(item => {\n void resolvedSyncPromise(item).then(() => {\n // eslint-disable-next-line no-plusplus\n if (!--counter) {\n clearTimeout(capturedSetTimeout);\n resolve(true);\n }\n }, reject);\n });\n });\n }\n\n return {\n $: buffer,\n add,\n drain,\n };\n}\n","import { Severity } from '@sentry/types';\n\nimport { SeverityLevel, SeverityLevels } from './enums';\n\nfunction isSupportedSeverity(level: string): level is Severity {\n return SeverityLevels.indexOf(level as SeverityLevel) !== -1;\n}\n/**\n * Converts a string-based level into a {@link Severity}.\n *\n * @param level string representation of Severity\n * @returns Severity\n */\nexport function severityFromString(level: SeverityLevel | string): Severity {\n if (level === 'warn') return Severity.Warning;\n if (isSupportedSeverity(level)) {\n return level;\n }\n return Severity.Log;\n}\n","import { EventStatus } from '@sentry/types';\n/**\n * Converts an HTTP status code to sentry status {@link EventStatus}.\n *\n * @param code number HTTP status code\n * @returns EventStatus\n */\nexport function eventStatusFromHttpCode(code: number): EventStatus {\n if (code >= 200 && code < 300) {\n return 'success';\n }\n\n if (code === 429) {\n return 'rate_limit';\n }\n\n if (code >= 400 && code < 500) {\n return 'invalid';\n }\n\n if (code >= 500) {\n return 'failed';\n }\n\n return 'unknown';\n}\n","import { getGlobalObject } from './global';\nimport { dynamicRequire, isNodeEnv } from './node';\n\n/**\n * An object that can return the current timestamp in seconds since the UNIX epoch.\n */\ninterface TimestampSource {\n nowSeconds(): number;\n}\n\n/**\n * A TimestampSource implementation for environments that do not support the Performance Web API natively.\n *\n * Note that this TimestampSource does not use a monotonic clock. A call to `nowSeconds` may return a timestamp earlier\n * than a previously returned value. We do not try to emulate a monotonic behavior in order to facilitate debugging. It\n * is more obvious to explain \"why does my span have negative duration\" than \"why my spans have zero duration\".\n */\nconst dateTimestampSource: TimestampSource = {\n nowSeconds: () => Date.now() / 1000,\n};\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 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 getBrowserPerformance(): Performance | undefined {\n const { performance } = getGlobalObject<Window>();\n if (!performance || !performance.now) {\n return undefined;\n }\n\n // Replace performance.timeOrigin with our own timeOrigin based on Date.now().\n //\n // This is a partial workaround for browsers reporting performance.timeOrigin such that performance.timeOrigin +\n // performance.now() gives a date arbitrarily in the past.\n //\n // Additionally, computing timeOrigin in this way fills the gap for browsers where performance.timeOrigin is\n // undefined.\n //\n // The assumption that performance.timeOrigin + performance.now() ~= Date.now() is flawed, but we depend on it to\n // interact with data coming out of performance entries.\n //\n // Note that despite recommendations against it in the spec, browsers implement the Performance API with a clock that\n // might stop when the computer is asleep (and perhaps under other circumstances). Such behavior causes\n // performance.timeOrigin + performance.now() to have an arbitrary skew over Date.now(). In laptop computers, we have\n // observed skews that can be as long as days, weeks or months.\n //\n // See https://github.com/getsentry/sentry-javascript/issues/2590.\n //\n // BUG: despite our best intentions, this workaround has its limitations. It mostly addresses timings of pageload\n // transactions, but ignores the skew built up over time that can aversely affect timestamps of navigation\n // transactions of long-lived web pages.\n const timeOrigin = Date.now() - performance.now();\n\n return {\n now: () => performance.now(),\n timeOrigin,\n };\n}\n\n/**\n * Returns the native Performance API implementation from Node.js. Returns undefined in old Node.js versions that don't\n * implement the API.\n */\nfunction getNodePerformance(): Performance | undefined {\n try {\n const perfHooks = dynamicRequire(module, 'perf_hooks') as { performance: Performance };\n return perfHooks.performance;\n } catch (_) {\n return undefined;\n }\n}\n\n/**\n * The Performance API implementation for the current platform, if available.\n */\nconst platformPerformance: Performance | undefined = isNodeEnv() ? getNodePerformance() : getBrowserPerformance();\n\nconst timestampSource: TimestampSource =\n platformPerformance === undefined\n ? dateTimestampSource\n : {\n nowSeconds: () => (platformPerformance.timeOrigin + platformPerformance.now()) / 1000,\n };\n\n/**\n * Returns a timestamp in seconds since the UNIX epoch using the Date API.\n */\nexport const dateTimestampInSeconds: () => number = dateTimestampSource.nowSeconds.bind(dateTimestampSource);\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 * See `usingPerformanceAPI` to test whether the Performance API is used.\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: () => number = timestampSource.nowSeconds.bind(timestampSource);\n\n// Re-exported with an old name for backwards-compatibility.\nexport const timestampWithMs = timestampInSeconds;\n\n/**\n * A boolean that is true when timestampInSeconds uses the Performance API to produce monotonic timestamps.\n */\nexport const usingPerformanceAPI = platformPerformance !== undefined;\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 } = getGlobalObject<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","import { Envelope } from '@sentry/types';\n\nimport { isPrimitive } from './is';\n\n/**\n * Creates an envelope.\n * Make sure to always explicitly provide the generic to this function\n * so that the envelope types resolve correctly.\n */\nexport function createEnvelope<E extends Envelope>(headers: E[0], items: E[1] = []): E {\n return [headers, items] as E;\n}\n\n/**\n * Add an item to an envelope.\n * Make sure to always explicitly provide the generic to this function\n * so that the envelope types resolve correctly.\n */\nexport function addItemToEnvelope<E extends Envelope>(envelope: E, newItem: E[1][number]): E {\n const [headers, items] = envelope;\n return [headers, [...items, newItem]] as E;\n}\n\n/**\n * Get the type of the envelope. Grabs the type from the first envelope item.\n */\nexport function getEnvelopeType<E extends Envelope>(envelope: E): string {\n const [, [[firstItemHeader]]] = envelope;\n return firstItemHeader.type;\n}\n\n/**\n * Serializes an envelope into a string.\n */\nexport function serializeEnvelope(envelope: Envelope): string {\n const [headers, items] = envelope;\n const serializedHeaders = JSON.stringify(headers);\n\n // Have to cast items to any here since Envelope is a union type\n // Fixed in Typescript 4.2\n // TODO: Remove any[] cast when we upgrade to TS 4.2\n // https://github.com/microsoft/TypeScript/issues/36390\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (items as any[]).reduce((acc, item: typeof items[number]) => {\n const [itemHeaders, payload] = item;\n // We do not serialize payloads that are primitives\n const serializedPayload = isPrimitive(payload) ? String(payload) : JSON.stringify(payload);\n return `${acc}\\n${JSON.stringify(itemHeaders)}\\n${serializedPayload}`;\n }, serializedHeaders);\n}\n","// Keeping the key broad until we add the new transports\nexport type RateLimits = Record<string, number>;\n\nexport const DEFAULT_RETRY_AFTER = 60 * 1000; // 60 seconds\n\n/**\n * Extracts Retry-After value from the request header or returns default value\n * @param header string representation of 'Retry-After' header\n * @param now current unix timestamp\n *\n */\nexport function parseRetryAfterHeader(header: string, now: number = Date.now()): number {\n const headerDelay = parseInt(`${header}`, 10);\n if (!isNaN(headerDelay)) {\n return headerDelay * 1000;\n }\n\n const headerDate = Date.parse(`${header}`);\n if (!isNaN(headerDate)) {\n return headerDate - now;\n }\n\n return DEFAULT_RETRY_AFTER;\n}\n\n/**\n * Gets the time that given category is disabled until for rate limiting\n */\nexport function disabledUntil(limits: RateLimits, category: string): number {\n return limits[category] || limits.all || 0;\n}\n\n/**\n * Checks if a category is rate limited\n */\nexport function isRateLimited(limits: RateLimits, category: string, now: number = Date.now()): boolean {\n return disabledUntil(limits, category) > now;\n}\n\n/**\n * Update ratelimits from incoming headers.\n * Returns true if headers contains a non-empty rate limiting header.\n */\nexport function updateRateLimits(\n limits: RateLimits,\n headers: Record<string, string | null | undefined>,\n now: number = Date.now(),\n): RateLimits {\n const updatedRateLimits: RateLimits = {\n ...limits,\n };\n\n // \"The name is case-insensitive.\"\n // https://developer.mozilla.org/en-US/docs/Web/API/Headers/get\n const rateLimitHeader = headers['x-sentry-rate-limits'];\n const retryAfterHeader = headers['retry-after'];\n\n if (rateLimitHeader) {\n /**\n * rate limit headers are of the form\n * <header>,<header>,..\n * where each <header> is of the form\n * <retry_after>: <categories>: <scope>: <reason_code>\n * where\n * <retry_after> is a delay in seconds\n * <categories> is the event type(s) (error, transaction, etc) being rate limited and is of the form\n * <category>;<category>;...\n * <scope> is what's being limited (org, project, or key) - ignored by SDK\n * <reason_code> is an arbitrary string like \"org_quota\" - ignored by SDK\n */\n for (const limit of rateLimitHeader.trim().split(',')) {\n const parameters = limit.split(':', 2);\n const headerDelay = parseInt(parameters[0], 10);\n const delay = (!isNaN(headerDelay) ? headerDelay : 60) * 1000; // 60sec default\n if (!parameters[1]) {\n updatedRateLimits.all = now + delay;\n } else {\n for (const category of parameters[1].split(';')) {\n updatedRateLimits[category] = now + delay;\n }\n }\n }\n } else if (retryAfterHeader) {\n updatedRateLimits.all = now + parseRetryAfterHeader(retryAfterHeader, now);\n }\n\n return updatedRateLimits;\n}\n","/* eslint-disable max-lines */\nimport {\n Breadcrumb,\n CaptureContext,\n Context,\n Contexts,\n Event,\n EventHint,\n EventProcessor,\n Extra,\n Extras,\n Primitive,\n RequestSession,\n Scope as ScopeInterface,\n ScopeContext,\n Severity,\n Span,\n Transaction,\n User,\n} from '@sentry/types';\nimport { dateTimestampInSeconds, getGlobalSingleton, isPlainObject, isThenable, SyncPromise } from '@sentry/utils';\n\nimport { Session } from './session';\n\n/**\n * Absolute maximum number of breadcrumbs added to an event.\n * The `maxBreadcrumbs` option cannot be higher than this value.\n */\nconst MAX_BREADCRUMBS = 100;\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 = false;\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 /** Fingerprint */\n protected _fingerprint?: string[];\n\n /** Severity */\n protected _level?: Severity;\n\n /** Transaction Name */\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 /**\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 /**\n * Inherit values from the parent scope.\n * @param scope to clone.\n */\n public static clone(scope?: Scope): Scope {\n const newScope = new Scope();\n if (scope) {\n newScope._breadcrumbs = [...scope._breadcrumbs];\n newScope._tags = { ...scope._tags };\n newScope._extra = { ...scope._extra };\n newScope._contexts = { ...scope._contexts };\n newScope._user = scope._user;\n newScope._level = scope._level;\n newScope._span = scope._span;\n newScope._session = scope._session;\n newScope._transactionName = scope._transactionName;\n newScope._fingerprint = scope._fingerprint;\n newScope._eventProcessors = [...scope._eventProcessors];\n newScope._requestSession = scope._requestSession;\n }\n return newScope;\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 this._user = user || {};\n if (this._session) {\n this._session.update({ user });\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(level: Severity): this {\n this._level = level;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setTransactionName(name?: string): this {\n this._transactionName = name;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * Can be removed in major version.\n * @deprecated in favor of {@link this.setTransactionName}\n */\n public setTransaction(name?: string): this {\n return this.setTransactionName(name);\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 = { ...this._contexts, [key]: context };\n }\n\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setSpan(span?: Span): this {\n this._span = span;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getSpan(): Span | undefined {\n return this._span;\n }\n\n /**\n * @inheritDoc\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.getSpan();\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 if (typeof captureContext === 'function') {\n const updatedScope = (captureContext as <T>(scope: T) => T)(this);\n return updatedScope instanceof Scope ? updatedScope : this;\n }\n\n if (captureContext instanceof Scope) {\n this._tags = { ...this._tags, ...captureContext._tags };\n this._extra = { ...this._extra, ...captureContext._extra };\n this._contexts = { ...this._contexts, ...captureContext._contexts };\n if (captureContext._user && Object.keys(captureContext._user).length) {\n this._user = captureContext._user;\n }\n if (captureContext._level) {\n this._level = captureContext._level;\n }\n if (captureContext._fingerprint) {\n this._fingerprint = captureContext._fingerprint;\n }\n if (captureContext._requestSession) {\n this._requestSession = captureContext._requestSession;\n }\n } else if (isPlainObject(captureContext)) {\n // eslint-disable-next-line no-param-reassign\n captureContext = captureContext as ScopeContext;\n this._tags = { ...this._tags, ...captureContext.tags };\n this._extra = { ...this._extra, ...captureContext.extra };\n this._contexts = { ...this._contexts, ...captureContext.contexts };\n if (captureContext.user) {\n this._user = captureContext.user;\n }\n if (captureContext.level) {\n this._level = captureContext.level;\n }\n if (captureContext.fingerprint) {\n this._fingerprint = captureContext.fingerprint;\n }\n if (captureContext.requestSession) {\n this._requestSession = captureContext.requestSession;\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 return this;\n }\n\n /**\n * @inheritDoc\n */\n public addBreadcrumb(breadcrumb: Breadcrumb, maxBreadcrumbs?: number): this {\n const maxCrumbs = typeof maxBreadcrumbs === 'number' ? Math.min(maxBreadcrumbs, MAX_BREADCRUMBS) : 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 this._breadcrumbs = [...this._breadcrumbs, mergedBreadcrumb].slice(-maxCrumbs);\n this._notifyScopeListeners();\n\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public clearBreadcrumbs(): this {\n this._breadcrumbs = [];\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * Applies the current context and fingerprint to the event.\n * Note that breadcrumbs will be added by the client.\n * Also if the event has already breadcrumbs on it, we do not merge them.\n * @param event Event\n * @param hint May contain additional information about the original exception.\n * @hidden\n */\n public applyToEvent(event: Event, hint?: EventHint): PromiseLike<Event | null> {\n if (this._extra && Object.keys(this._extra).length) {\n event.extra = { ...this._extra, ...event.extra };\n }\n if (this._tags && Object.keys(this._tags).length) {\n event.tags = { ...this._tags, ...event.tags };\n }\n if (this._user && Object.keys(this._user).length) {\n event.user = { ...this._user, ...event.user };\n }\n if (this._contexts && Object.keys(this._contexts).length) {\n event.contexts = { ...this._contexts, ...event.contexts };\n }\n if (this._level) {\n event.level = this._level;\n }\n if (this._transactionName) {\n event.transaction = this._transactionName;\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 (this._span) {\n event.contexts = { trace: this._span.getTraceContext(), ...event.contexts };\n const transactionName = this._span.transaction && this._span.transaction.name;\n if (transactionName) {\n event.tags = { transaction: transactionName, ...event.tags };\n }\n }\n\n this._applyFingerprint(event);\n\n event.breadcrumbs = [...(event.breadcrumbs || []), ...this._breadcrumbs];\n event.breadcrumbs = event.breadcrumbs.length > 0 ? event.breadcrumbs : undefined;\n\n event.sdkProcessingMetadata = this._sdkProcessingMetadata;\n\n return this._notifyEventProcessors([...getGlobalEventProcessors(), ...this._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 * This will be called after {@link applyToEvent} is finished.\n */\n protected _notifyEventProcessors(\n processors: EventProcessor[],\n event: Event | null,\n hint?: EventHint,\n index: number = 0,\n ): PromiseLike<Event | null> {\n return new SyncPromise<Event | null>((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 if (isThenable(result)) {\n void result\n .then(final => this._notifyEventProcessors(processors, final, hint, index + 1).then(resolve))\n .then(null, reject);\n } else {\n void this._notifyEventProcessors(processors, result, hint, index + 1)\n .then(resolve)\n .then(null, reject);\n }\n }\n });\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 * 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 */\n private _applyFingerprint(event: Event): void {\n // Make sure it's an array first and we actually have something in place\n event.fingerprint = event.fingerprint\n ? Array.isArray(event.fingerprint)\n ? event.fingerprint\n : [event.fingerprint]\n : [];\n\n // If we have something on the scope, then merge it with event\n if (this._fingerprint) {\n event.fingerprint = event.fingerprint.concat(this._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}\n\n/**\n * Returns the global event processors.\n */\nfunction getGlobalEventProcessors(): EventProcessor[] {\n return getGlobalSingleton<EventProcessor[]>('globalEventProcessors', () => []);\n}\n\n/**\n * Add a EventProcessor to be kept globally.\n * @param callback EventProcessor to add\n */\nexport function addGlobalEventProcessor(callback: EventProcessor): void {\n getGlobalEventProcessors().push(callback);\n}\n","import { Session as SessionInterface, SessionContext, SessionStatus } from '@sentry/types';\nimport { dropUndefinedKeys, timestampInSeconds, uuid4 } from '@sentry/utils';\n\n/**\n * @inheritdoc\n */\nexport class Session implements SessionInterface {\n public userAgent?: string;\n public errors: number = 0;\n public release?: string;\n public sid: string = uuid4();\n public did?: string;\n public timestamp: number;\n public started: number;\n public duration?: number = 0;\n public status: SessionStatus = 'ok';\n public environment?: string;\n public ipAddress?: string;\n public init: boolean = true;\n public ignoreDuration: boolean = false;\n\n public constructor(context?: Omit<SessionContext, 'started' | 'status'>) {\n // Both timestamp and started are in seconds since the UNIX epoch.\n const startingTime = timestampInSeconds();\n this.timestamp = startingTime;\n this.started = startingTime;\n if (context) {\n this.update(context);\n }\n }\n\n /** JSDoc */\n // eslint-disable-next-line complexity\n public update(context: SessionContext = {}): void {\n if (context.user) {\n if (!this.ipAddress && context.user.ip_address) {\n this.ipAddress = context.user.ip_address;\n }\n\n if (!this.did && !context.did) {\n this.did = context.user.id || context.user.email || context.user.username;\n }\n }\n\n this.timestamp = context.timestamp || timestampInSeconds();\n if (context.ignoreDuration) {\n this.ignoreDuration = context.ignoreDuration;\n }\n if (context.sid) {\n // Good enough uuid validation. — Kamil\n this.sid = context.sid.length === 32 ? context.sid : uuid4();\n }\n if (context.init !== undefined) {\n this.init = context.init;\n }\n if (!this.did && context.did) {\n this.did = `${context.did}`;\n }\n if (typeof context.started === 'number') {\n this.started = context.started;\n }\n if (this.ignoreDuration) {\n this.duration = undefined;\n } else if (typeof context.duration === 'number') {\n this.duration = context.duration;\n } else {\n const duration = this.timestamp - this.started;\n this.duration = duration >= 0 ? duration : 0;\n }\n if (context.release) {\n this.release = context.release;\n }\n if (context.environment) {\n this.environment = context.environment;\n }\n if (!this.ipAddress && context.ipAddress) {\n this.ipAddress = context.ipAddress;\n }\n if (!this.userAgent && context.userAgent) {\n this.userAgent = context.userAgent;\n }\n if (typeof context.errors === 'number') {\n this.errors = context.errors;\n }\n if (context.status) {\n this.status = context.status;\n }\n }\n\n /** JSDoc */\n public close(status?: Exclude<SessionStatus, 'ok'>): void {\n if (status) {\n this.update({ status });\n } else if (this.status === 'ok') {\n this.update({ status: 'exited' });\n } else {\n this.update();\n }\n }\n\n /** JSDoc */\n public toJSON(): {\n init: boolean;\n sid: string;\n did?: string;\n timestamp: string;\n started: string;\n duration?: number;\n status: SessionStatus;\n errors: number;\n attrs?: {\n release?: string;\n environment?: string;\n user_agent?: string;\n ip_address?: string;\n };\n } {\n return dropUndefinedKeys({\n sid: `${this.sid}`,\n init: this.init,\n // Make sure that sec is converted to ms for date constructor\n started: new Date(this.started * 1000).toISOString(),\n timestamp: new Date(this.timestamp * 1000).toISOString(),\n status: this.status,\n errors: this.errors,\n did: typeof this.did === 'number' || typeof this.did === 'string' ? `${this.did}` : undefined,\n duration: this.duration,\n attrs: {\n release: this.release,\n environment: this.environment,\n ip_address: this.ipAddress,\n user_agent: this.userAgent,\n },\n });\n }\n}\n","/* eslint-disable max-lines */\nimport {\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 SessionContext,\n Severity,\n Span,\n SpanContext,\n Transaction,\n TransactionContext,\n User,\n} from '@sentry/types';\nimport {\n consoleSandbox,\n dateTimestampInSeconds,\n getGlobalObject,\n getGlobalSingleton,\n isNodeEnv,\n logger,\n uuid4,\n} from '@sentry/utils';\n\nimport { IS_DEBUG_BUILD } from './flags';\nimport { Scope } from './scope';\nimport { Session } from './session';\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 = 4;\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\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 /**\n * Extra Hub properties injected by various SDKs\n */\n integrations?: Integration[];\n extensions?: {\n /** Hack to prevent bundlers from breaking our usage of the domain package in the cross-platform Hub package */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n domain?: { [key: string]: any };\n } & {\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 * @hidden\n * @deprecated Can be removed once `Hub.getActiveDomain` is removed.\n */\nexport interface DomainAsCarrier extends Carrier {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n members: { [key: string]: any }[];\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 /**\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 public constructor(client?: Client, scope: Scope = new Scope(), private readonly _version: number = API_VERSION) {\n this.getStackTop().scope = scope;\n if (client) {\n this.bindClient(client);\n }\n }\n\n /**\n * @inheritDoc\n */\n public isOlderThan(version: number): boolean {\n return this._version < version;\n }\n\n /**\n * @inheritDoc\n */\n public bindClient(client?: Client): void {\n const top = this.getStackTop();\n top.client = client;\n if (client && client.setupIntegrations) {\n client.setupIntegrations();\n }\n }\n\n /**\n * @inheritDoc\n */\n public pushScope(): Scope {\n // We want to clone the content of prev scope\n const scope = Scope.clone(this.getScope());\n this.getStack().push({\n client: this.getClient(),\n scope,\n });\n return scope;\n }\n\n /**\n * @inheritDoc\n */\n public popScope(): boolean {\n if (this.getStack().length <= 1) return false;\n return !!this.getStack().pop();\n }\n\n /**\n * @inheritDoc\n */\n public withScope(callback: (scope: Scope) => void): void {\n const scope = this.pushScope();\n try {\n callback(scope);\n } finally {\n this.popScope();\n }\n }\n\n /**\n * @inheritDoc\n */\n public getClient<C extends Client>(): C | undefined {\n return this.getStackTop().client as C;\n }\n\n /** Returns the scope of the top stack. */\n public getScope(): Scope | undefined {\n return this.getStackTop().scope;\n }\n\n /** Returns the scope stack for domains or the process. */\n public getStack(): Layer[] {\n return this._stack;\n }\n\n /** Returns the topmost scope layer in the order domain > local > process. */\n public getStackTop(): Layer {\n return this._stack[this._stack.length - 1];\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\n public captureException(exception: any, hint?: EventHint): string {\n const eventId = (this._lastEventId = hint && hint.event_id ? hint.event_id : uuid4());\n let finalHint = hint;\n\n // If there's no explicit hint provided, mimic the same thing that would happen\n // in the minimal itself to create a consistent behavior.\n // We don't do this in the client, as it's the lowest level API, and doing this,\n // would prevent user from having full control over direct calls.\n if (!hint) {\n let syntheticException: Error;\n try {\n throw new Error('Sentry syntheticException');\n } catch (exception) {\n syntheticException = exception as Error;\n }\n finalHint = {\n originalException: exception,\n syntheticException,\n };\n }\n\n this._invokeClient('captureException', exception, {\n ...finalHint,\n event_id: eventId,\n });\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public captureMessage(message: string, level?: Severity, hint?: EventHint): string {\n const eventId = (this._lastEventId = hint && hint.event_id ? hint.event_id : uuid4());\n let finalHint = hint;\n\n // If there's no explicit hint provided, mimic the same thing that would happen\n // in the minimal itself to create a consistent behavior.\n // We don't do this in the client, as it's the lowest level API, and doing this,\n // would prevent user from having full control over direct calls.\n if (!hint) {\n let syntheticException: Error;\n try {\n throw new Error(message);\n } catch (exception) {\n syntheticException = exception as Error;\n }\n finalHint = {\n originalException: message,\n syntheticException,\n };\n }\n\n this._invokeClient('captureMessage', message, level, {\n ...finalHint,\n event_id: eventId,\n });\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public captureEvent(event: Event, hint?: EventHint): string {\n const eventId = hint && hint.event_id ? hint.event_id : uuid4();\n if (event.type !== 'transaction') {\n this._lastEventId = eventId;\n }\n\n this._invokeClient('captureEvent', event, {\n ...hint,\n event_id: eventId,\n });\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public lastEventId(): string | undefined {\n return this._lastEventId;\n }\n\n /**\n * @inheritDoc\n */\n public addBreadcrumb(breadcrumb: Breadcrumb, hint?: BreadcrumbHint): void {\n const { scope, client } = this.getStackTop();\n\n if (!scope || !client) return;\n\n // eslint-disable-next-line @typescript-eslint/unbound-method\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 scope.addBreadcrumb(finalBreadcrumb, maxBreadcrumbs);\n }\n\n /**\n * @inheritDoc\n */\n public setUser(user: User | null): void {\n const scope = this.getScope();\n if (scope) scope.setUser(user);\n }\n\n /**\n * @inheritDoc\n */\n public setTags(tags: { [key: string]: Primitive }): void {\n const scope = this.getScope();\n if (scope) scope.setTags(tags);\n }\n\n /**\n * @inheritDoc\n */\n public setExtras(extras: Extras): void {\n const scope = this.getScope();\n if (scope) scope.setExtras(extras);\n }\n\n /**\n * @inheritDoc\n */\n public setTag(key: string, value: Primitive): void {\n const scope = this.getScope();\n if (scope) scope.setTag(key, value);\n }\n\n /**\n * @inheritDoc\n */\n public setExtra(key: string, extra: Extra): void {\n const scope = this.getScope();\n if (scope) scope.setExtra(key, extra);\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n public setContext(name: string, context: { [key: string]: any } | null): void {\n const scope = this.getScope();\n if (scope) scope.setContext(name, context);\n }\n\n /**\n * @inheritDoc\n */\n public configureScope(callback: (scope: Scope) => void): void {\n const { scope, client } = this.getStackTop();\n if (scope && client) {\n callback(scope);\n }\n }\n\n /**\n * @inheritDoc\n */\n public run(callback: (hub: Hub) => void): void {\n const oldHub = makeMain(this);\n try {\n callback(this);\n } finally {\n makeMain(oldHub);\n }\n }\n\n /**\n * @inheritDoc\n */\n public getIntegration<T extends Integration>(integration: IntegrationClass<T>): T | null {\n const client = this.getClient();\n if (!client) return null;\n try {\n return client.getIntegration(integration);\n } catch (_oO) {\n IS_DEBUG_BUILD && logger.warn(`Cannot retrieve integration ${integration.id} from the current Hub`);\n return null;\n }\n }\n\n /**\n * @inheritDoc\n */\n public startSpan(context: SpanContext): Span {\n return this._callExtensionMethod('startSpan', context);\n }\n\n /**\n * @inheritDoc\n */\n public startTransaction(context: TransactionContext, customSamplingContext?: CustomSamplingContext): Transaction {\n return this._callExtensionMethod('startTransaction', context, customSamplingContext);\n }\n\n /**\n * @inheritDoc\n */\n public traceHeaders(): { [key: string]: string } {\n return this._callExtensionMethod<{ [key: string]: string }>('traceHeaders');\n }\n\n /**\n * @inheritDoc\n */\n public captureSession(endSession: boolean = false): void {\n // both send the update and pull the session from the scope\n if (endSession) {\n return this.endSession();\n }\n\n // only send the update\n this._sendSessionUpdate();\n }\n\n /**\n * @inheritDoc\n */\n public endSession(): void {\n const layer = this.getStackTop();\n const scope = layer && layer.scope;\n const session = scope && scope.getSession();\n if (session) {\n session.close();\n }\n this._sendSessionUpdate();\n\n // the session is over; take it off of the scope\n if (scope) {\n scope.setSession();\n }\n }\n\n /**\n * @inheritDoc\n */\n public startSession(context?: SessionContext): Session {\n const { scope, client } = this.getStackTop();\n const { release, environment } = (client && client.getOptions()) || {};\n\n // Will fetch userAgent if called from browser sdk\n const global = getGlobalObject<{ navigator?: { userAgent?: string } }>();\n const { userAgent } = global.navigator || {};\n\n const session = new Session({\n release,\n environment,\n ...(scope && { user: scope.getUser() }),\n ...(userAgent && { userAgent }),\n ...context,\n });\n\n if (scope) {\n // End existing session if there's one\n const currentSession = scope.getSession && scope.getSession();\n if (currentSession && currentSession.status === 'ok') {\n currentSession.update({ status: 'exited' });\n }\n this.endSession();\n\n // Afterwards we set the new session on the scope\n scope.setSession(session);\n }\n\n return session;\n }\n\n /**\n * Sends the current Session on the scope\n */\n private _sendSessionUpdate(): void {\n const { scope, client } = this.getStackTop();\n if (!scope) return;\n\n const session = scope.getSession && scope.getSession();\n if (session) {\n if (client && client.captureSession) {\n client.captureSession(session);\n }\n }\n }\n\n /**\n * Internal helper function to call a method on the top client if it exists.\n *\n * @param method The method to call on the client.\n * @param args Arguments to pass to the client function.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private _invokeClient<M extends keyof Client>(method: M, ...args: any[]): void {\n const { scope, client } = this.getStackTop();\n if (client && client[method]) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any\n (client as any)[method](...args, scope);\n }\n }\n\n /**\n * Calls global extension method and binding current instance to the function call\n */\n // @ts-ignore Function lacks ending return statement and return type does not include 'undefined'. ts(2366)\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private _callExtensionMethod<T>(method: string, ...args: any[]): T {\n const carrier = getMainCarrier();\n const sentry = carrier.__SENTRY__;\n if (sentry && sentry.extensions && typeof sentry.extensions[method] === 'function') {\n return sentry.extensions[method].apply(this, args);\n }\n IS_DEBUG_BUILD && logger.warn(`Extension method ${method} couldn't be found, doing nothing.`);\n }\n}\n\n/**\n * Returns the global shim registry.\n *\n * FIXME: This function is problematic, because despite always returning a valid Carrier,\n * it has an optional `__SENTRY__` property, which then in turn requires us to always perform an unnecessary check\n * at the call-site. We always access the carrier through this function, so we can guarantee that `__SENTRY__` is there.\n **/\nexport function getMainCarrier(): Carrier {\n const carrier = getGlobalObject();\n carrier.__SENTRY__ = carrier.__SENTRY__ || {\n extensions: {},\n hub: undefined,\n };\n return carrier;\n}\n\n/**\n * Replaces the current main hub with the passed one on the global object\n *\n * @returns The old replaced hub\n */\nexport function makeMain(hub: Hub): Hub {\n const registry = getMainCarrier();\n const oldHub = getHubFromCarrier(registry);\n setHubOnCarrier(registry, hub);\n return oldHub;\n}\n\n/**\n * Returns the default hub instance.\n *\n * If a hub is already registered in the global carrier but this module\n * contains a more recent version, it replaces the registered version.\n * Otherwise, the currently registered hub will be returned.\n */\nexport function getCurrentHub(): Hub {\n // Get main carrier (global for every environment)\n const registry = getMainCarrier();\n\n // If there's no hub, or its an old API, assign a new one\n if (!hasHubOnCarrier(registry) || getHubFromCarrier(registry).isOlderThan(API_VERSION)) {\n setHubOnCarrier(registry, new Hub());\n }\n\n // Prefer domains over global if they are there (applicable only to Node environment)\n if (isNodeEnv()) {\n return getHubFromActiveDomain(registry);\n }\n // Return hub that lives on a global object\n return getHubFromCarrier(registry);\n}\n\n/**\n * Returns the active domain, if one exists\n * @deprecated No longer used; remove in v7\n * @returns The domain, or undefined if there is no active domain\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function getActiveDomain(): DomainAsCarrier | undefined {\n IS_DEBUG_BUILD && logger.warn('Function `getActiveDomain` is deprecated and will be removed in a future version.');\n\n const sentry = getMainCarrier().__SENTRY__;\n\n return sentry && sentry.extensions && sentry.extensions.domain && sentry.extensions.domain.active;\n}\n\n/**\n * Try to read the hub from an active domain, and fallback to the registry if one doesn't exist\n * @returns discovered hub\n */\nfunction getHubFromActiveDomain(registry: Carrier): Hub {\n try {\n const sentry = getMainCarrier().__SENTRY__;\n const activeDomain = sentry && sentry.extensions && sentry.extensions.domain && sentry.extensions.domain.active;\n\n // If there's no active domain, just return global hub\n if (!activeDomain) {\n return getHubFromCarrier(registry);\n }\n\n // If there's no hub on current domain, or it's an old API, assign a new one\n if (!hasHubOnCarrier(activeDomain) || getHubFromCarrier(activeDomain).isOlderThan(API_VERSION)) {\n const registryHubTopStack = getHubFromCarrier(registry).getStackTop();\n setHubOnCarrier(activeDomain, new Hub(registryHubTopStack.client, Scope.clone(registryHubTopStack.scope)));\n }\n\n // Return hub that lives on a domain\n return getHubFromCarrier(activeDomain);\n } catch (_Oo) {\n // Return hub that lives on a global object\n return getHubFromCarrier(registry);\n }\n}\n\n/**\n * This will tell whether a carrier has a hub on it or not\n * @param carrier object\n */\nfunction hasHubOnCarrier(carrier: Carrier): boolean {\n return !!(carrier && carrier.__SENTRY__ && carrier.__SENTRY__.hub);\n}\n\n/**\n * This will create a new {@link Hub} and add to the passed object on\n * __SENTRY__.hub.\n * @param carrier object\n * @hidden\n */\nexport function getHubFromCarrier(carrier: Carrier): Hub {\n return getGlobalSingleton<Hub>('hub', () => new Hub(), carrier);\n}\n\n/**\n * This will set passed {@link Hub} on the passed object's __SENTRY__.hub attribute\n * @param carrier object\n * @param hub Hub\n * @returns A boolean indicating success or failure\n */\nexport function setHubOnCarrier(carrier: Carrier, hub: Hub): boolean {\n if (!carrier) return false;\n const __SENTRY__ = (carrier.__SENTRY__ = carrier.__SENTRY__ || {});\n __SENTRY__.hub = hub;\n return true;\n}\n","import { getCurrentHub, Hub, Scope } from '@sentry/hub';\nimport {\n Breadcrumb,\n CaptureContext,\n CustomSamplingContext,\n Event,\n Extra,\n Extras,\n Primitive,\n Severity,\n Transaction,\n TransactionContext,\n User,\n} from '@sentry/types';\n\n/**\n * This calls a function on the current hub.\n * @param method function to call on hub.\n * @param args to pass to function.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction callOnHub<T>(method: string, ...args: any[]): T {\n const hub = getCurrentHub();\n if (hub && hub[method as keyof Hub]) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (hub[method as keyof Hub] as any)(...args);\n }\n throw new Error(`No hub defined or ${method} was not found on the hub, please open a bug report.`);\n}\n\n/**\n * Captures an exception event and sends it to Sentry.\n *\n * @param exception An exception-like object.\n * @returns The generated eventId.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\nexport function captureException(exception: any, captureContext?: CaptureContext): string {\n const syntheticException = new Error('Sentry syntheticException');\n\n return callOnHub('captureException', exception, {\n captureContext,\n originalException: exception,\n syntheticException,\n });\n}\n\n/**\n * Captures a message event and sends it to Sentry.\n *\n * @param message The message to send to Sentry.\n * @param Severity Define the level of the message.\n * @returns The generated eventId.\n */\nexport function captureMessage(message: string, captureContext?: CaptureContext | Severity): string {\n const syntheticException = new Error(message);\n\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\n return callOnHub('captureMessage', message, level, {\n originalException: message,\n syntheticException,\n ...context,\n });\n}\n\n/**\n * Captures a manually created event and sends it to Sentry.\n *\n * @param event The event to send to Sentry.\n * @returns The generated eventId.\n */\nexport function captureEvent(event: Event): string {\n return callOnHub('captureEvent', event);\n}\n\n/**\n * Callback to set context information onto the scope.\n * @param callback Callback function that receives Scope.\n */\nexport function configureScope(callback: (scope: Scope) => void): void {\n callOnHub<void>('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): void {\n callOnHub<void>('addBreadcrumb', breadcrumb);\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): void {\n callOnHub<void>('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): void {\n callOnHub<void>('setExtras', extras);\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 }): void {\n callOnHub<void>('setTags', tags);\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): void {\n callOnHub<void>('setExtra', key, extra);\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): void {\n callOnHub<void>('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): void {\n callOnHub<void>('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 *\n * @param callback that will be enclosed into push/popScope.\n */\nexport function withScope(callback: (scope: Scope) => void): void {\n callOnHub<void>('withScope', callback);\n}\n\n/**\n * Calls a function on the latest client. Use this with caution, it's meant as\n * in \"internal\" helper so we don't need to expose every possible function in\n * the shim. It is not guaranteed that the client actually implements the\n * function.\n *\n * @param method The method to call on the client/client.\n * @param args Arguments to pass to the client/fontend.\n * @hidden\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function _callOnClient(method: string, ...args: any[]): void {\n callOnHub<void>('_invokeClient', method, ...args);\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 `.finish()` 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 */\nexport function startTransaction(\n context: TransactionContext,\n customSamplingContext?: CustomSamplingContext,\n): Transaction {\n return callOnHub('startTransaction', { ...context }, customSamplingContext);\n}\n","import { DsnComponents, DsnLike, SdkMetadata } from '@sentry/types';\nimport { dsnToString, makeDsn, urlEncode } from '@sentry/utils';\n\nconst SENTRY_API_VERSION = '7';\n\n/**\n * Stores details about a Sentry SDK\n */\nexport interface APIDetails {\n /** The DSN as passed to Sentry.init() */\n initDsn: DsnLike;\n /** Metadata about the SDK (name, version, etc) for inclusion in envelope headers */\n metadata: SdkMetadata;\n /** The internally used Dsn object. */\n readonly dsn: DsnComponents;\n /** The envelope tunnel to use. */\n readonly tunnel?: string;\n}\n\n/**\n * Helper class to provide urls, headers and metadata that can be used to form\n * different types of requests to Sentry endpoints.\n * Supports both envelopes and regular event requests.\n *\n * @deprecated Please use APIDetails\n **/\nexport class API {\n /** The DSN as passed to Sentry.init() */\n public dsn: DsnLike;\n\n /** Metadata about the SDK (name, version, etc) for inclusion in envelope headers */\n public metadata: SdkMetadata;\n\n /** The internally used Dsn object. */\n private readonly _dsnObject: DsnComponents;\n\n /** The envelope tunnel to use. */\n private readonly _tunnel?: string;\n\n /** Create a new instance of API */\n public constructor(dsn: DsnLike, metadata: SdkMetadata = {}, tunnel?: string) {\n this.dsn = dsn;\n this._dsnObject = makeDsn(dsn);\n this.metadata = metadata;\n this._tunnel = tunnel;\n }\n\n /** Returns the Dsn object. */\n public getDsn(): DsnComponents {\n return this._dsnObject;\n }\n\n /** Does this transport force envelopes? */\n public forceEnvelope(): boolean {\n return !!this._tunnel;\n }\n\n /** Returns the prefix to construct Sentry ingestion API endpoints. */\n public getBaseApiEndpoint(): string {\n return getBaseApiEndpoint(this._dsnObject);\n }\n\n /** Returns the store endpoint URL. */\n public getStoreEndpoint(): string {\n return getStoreEndpoint(this._dsnObject);\n }\n\n /**\n * Returns the store endpoint URL with auth in the query string.\n *\n * Sending auth as part of the query string and not as custom HTTP headers avoids CORS preflight requests.\n */\n public getStoreEndpointWithUrlEncodedAuth(): string {\n return getStoreEndpointWithUrlEncodedAuth(this._dsnObject);\n }\n\n /**\n * Returns the envelope endpoint URL with auth in the query string.\n *\n * Sending auth as part of the query string and not as custom HTTP headers avoids CORS preflight requests.\n */\n public getEnvelopeEndpointWithUrlEncodedAuth(): string {\n return getEnvelopeEndpointWithUrlEncodedAuth(this._dsnObject, this._tunnel);\n }\n}\n\n/** Initializes API Details */\nexport function initAPIDetails(dsn: DsnLike, metadata?: SdkMetadata, tunnel?: string): APIDetails {\n return {\n initDsn: dsn,\n metadata: metadata || {},\n dsn: makeDsn(dsn),\n tunnel,\n } as APIDetails;\n}\n\n/** Returns the prefix to construct Sentry ingestion API endpoints. */\nfunction getBaseApiEndpoint(dsn: DsnComponents): string {\n const protocol = dsn.protocol ? `${dsn.protocol}:` : '';\n const port = dsn.port ? `:${dsn.port}` : '';\n return `${protocol}//${dsn.host}${port}${dsn.path ? `/${dsn.path}` : ''}/api/`;\n}\n\n/** Returns the ingest API endpoint for target. */\nfunction _getIngestEndpoint(dsn: DsnComponents, target: 'store' | 'envelope'): string {\n return `${getBaseApiEndpoint(dsn)}${dsn.projectId}/${target}/`;\n}\n\n/** Returns a URL-encoded string with auth config suitable for a query string. */\nfunction _encodedAuth(dsn: DsnComponents): string {\n return urlEncode({\n // We send only the minimum set of required information. See\n // https://github.com/getsentry/sentry-javascript/issues/2572.\n sentry_key: dsn.publicKey,\n sentry_version: SENTRY_API_VERSION,\n });\n}\n\n/** Returns the store endpoint URL. */\nfunction getStoreEndpoint(dsn: DsnComponents): string {\n return _getIngestEndpoint(dsn, 'store');\n}\n\n/**\n * Returns the store endpoint URL with auth in the query string.\n *\n * Sending auth as part of the query string and not as custom HTTP headers avoids CORS preflight requests.\n */\nexport function getStoreEndpointWithUrlEncodedAuth(dsn: DsnComponents): string {\n return `${getStoreEndpoint(dsn)}?${_encodedAuth(dsn)}`;\n}\n\n/** Returns the envelope endpoint URL. */\nfunction _getEnvelopeEndpoint(dsn: DsnComponents): string {\n return _getIngestEndpoint(dsn, 'envelope');\n}\n\n/**\n * Returns the envelope endpoint URL with auth in the query string.\n *\n * Sending auth as part of the query string and not as custom HTTP headers avoids CORS preflight requests.\n */\nexport function getEnvelopeEndpointWithUrlEncodedAuth(dsn: DsnComponents, tunnel?: string): string {\n return tunnel ? tunnel : `${_getEnvelopeEndpoint(dsn)}?${_encodedAuth(dsn)}`;\n}\n\n/**\n * Returns an object that can be used in request headers.\n * This is needed for node and the old /store endpoint in sentry\n */\nexport function getRequestHeaders(\n dsn: DsnComponents,\n clientName: string,\n clientVersion: string,\n): { [key: string]: string } {\n // CHANGE THIS to use metadata but keep clientName and clientVersion compatible\n const header = [`Sentry sentry_version=${SENTRY_API_VERSION}`];\n header.push(`sentry_client=${clientName}/${clientVersion}`);\n header.push(`sentry_key=${dsn.publicKey}`);\n if (dsn.pass) {\n header.push(`sentry_secret=${dsn.pass}`);\n }\n return {\n 'Content-Type': 'application/json',\n 'X-Sentry-Auth': header.join(', '),\n };\n}\n\n/** Returns the url to the report dialog endpoint. */\nexport function getReportDialogEndpoint(\n dsnLike: DsnLike,\n dialogOptions: {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key: string]: any;\n user?: { name?: string; email?: string };\n },\n): string {\n const dsn = makeDsn(dsnLike);\n const endpoint = `${getBaseApiEndpoint(dsn)}embed/error-page/`;\n\n let encodedOptions = `dsn=${dsnToString(dsn)}`;\n for (const key in dialogOptions) {\n if (key === 'dsn') {\n continue;\n }\n\n if (key === 'user') {\n if (!dialogOptions.user) {\n continue;\n }\n if (dialogOptions.user.name) {\n encodedOptions += `&name=${encodeURIComponent(dialogOptions.user.name)}`;\n }\n if (dialogOptions.user.email) {\n encodedOptions += `&email=${encodeURIComponent(dialogOptions.user.email)}`;\n }\n } else {\n encodedOptions += `&${encodeURIComponent(key)}=${encodeURIComponent(dialogOptions[key] as string)}`;\n }\n }\n\n return `${endpoint}?${encodedOptions}`;\n}\n","/*\n * This file defines flags and constants that can be modified during compile time in order to facilitate tree shaking\n * for users.\n *\n * Debug flags need to be declared in each package individually and must not be imported across package boundaries,\n * because some build tools have trouble tree-shaking imported guards.\n *\n * As a convention, we define debug flags in a `flags.ts` file in the root of a package's `src` folder.\n *\n * Debug flag files will contain \"magic strings\" like `__SENTRY_DEBUG__` that may get replaced with actual values during\n * our, or the user's build process. Take care when introducing new flags - they must not throw if they are not\n * replaced.\n */\n\ndeclare const __SENTRY_DEBUG__: boolean;\n\n/** Flag that is true for debug builds, false otherwise. */\nexport const IS_DEBUG_BUILD = typeof __SENTRY_DEBUG__ === 'undefined' ? true : __SENTRY_DEBUG__;\n","import { addGlobalEventProcessor, getCurrentHub } from '@sentry/hub';\nimport { Integration, Options } from '@sentry/types';\nimport { addNonEnumerableProperty, logger } from '@sentry/utils';\n\nimport { IS_DEBUG_BUILD } from './flags';\n\nexport const installedIntegrations: string[] = [];\n\n/** Map of integrations assigned to a client */\nexport type IntegrationIndex = {\n [key: string]: Integration;\n} & { initialized?: boolean };\n\n/**\n * @private\n */\nfunction filterDuplicates(integrations: Integration[]): Integration[] {\n return integrations.reduce((acc, integrations) => {\n if (acc.every(accIntegration => integrations.name !== accIntegration.name)) {\n acc.push(integrations);\n }\n return acc;\n }, [] as Integration[]);\n}\n\n/** Gets integration to install */\nexport function getIntegrationsToSetup(options: Options): Integration[] {\n const defaultIntegrations = (options.defaultIntegrations && [...options.defaultIntegrations]) || [];\n const userIntegrations = options.integrations;\n\n let integrations: Integration[] = [...filterDuplicates(defaultIntegrations)];\n\n if (Array.isArray(userIntegrations)) {\n // Filter out integrations that are also included in user options\n integrations = [\n ...integrations.filter(integrations =>\n userIntegrations.every(userIntegration => userIntegration.name !== integrations.name),\n ),\n // And filter out duplicated user options integrations\n ...filterDuplicates(userIntegrations),\n ];\n } else if (typeof userIntegrations === 'function') {\n integrations = userIntegrations(integrations);\n integrations = Array.isArray(integrations) ? integrations : [integrations];\n }\n\n // Make sure that if present, `Debug` integration will always run last\n const integrationsNames = integrations.map(i => i.name);\n const alwaysLastToRun = 'Debug';\n if (integrationsNames.indexOf(alwaysLastToRun) !== -1) {\n integrations.push(...integrations.splice(integrationsNames.indexOf(alwaysLastToRun), 1));\n }\n\n return integrations;\n}\n\n/** Setup given integration */\nexport function setupIntegration(integration: Integration): void {\n if (installedIntegrations.indexOf(integration.name) !== -1) {\n return;\n }\n integration.setupOnce(addGlobalEventProcessor, getCurrentHub);\n installedIntegrations.push(integration.name);\n IS_DEBUG_BUILD && logger.log(`Integration installed: ${integration.name}`);\n}\n\n/**\n * Given a list of integration instances this installs them all. When `withDefaults` is set to `true` then all default\n * integrations are added unless they were already provided before.\n * @param integrations array of integration instances\n * @param withDefault should enable default integrations\n */\nexport function setupIntegrations<O extends Options>(options: O): IntegrationIndex {\n const integrations: IntegrationIndex = {};\n getIntegrationsToSetup(options).forEach(integration => {\n integrations[integration.name] = integration;\n setupIntegration(integration);\n });\n // set the `initialized` flag so we don't run through the process again unecessarily; use `Object.defineProperty`\n // because by default it creates a property which is nonenumerable, which we want since `initialized` shouldn't be\n // considered a member of the index the way the actual integrations are\n addNonEnumerableProperty(integrations, 'initialized', true);\n return integrations;\n}\n","/* eslint-disable max-lines */\nimport { Scope, Session } from '@sentry/hub';\nimport {\n Client,\n DsnComponents,\n Event,\n EventHint,\n Integration,\n IntegrationClass,\n Options,\n Severity,\n Transport,\n} from '@sentry/types';\nimport {\n checkOrSetAlreadyCaught,\n dateTimestampInSeconds,\n isPlainObject,\n isPrimitive,\n isThenable,\n logger,\n makeDsn,\n normalize,\n rejectedSyncPromise,\n resolvedSyncPromise,\n SentryError,\n SyncPromise,\n truncate,\n uuid4,\n} from '@sentry/utils';\n\nimport { Backend, BackendClass } from './basebackend';\nimport { IS_DEBUG_BUILD } from './flags';\nimport { IntegrationIndex, setupIntegrations } from './integration';\n\nconst ALREADY_SEEN_ERROR = \"Not capturing exception because it's already been captured.\";\n\n/**\n * Base implementation for all JavaScript SDK clients.\n *\n * Call the constructor with the corresponding backend constructor and options\n * specific to the client subclass. To access these options later, use\n * {@link Client.getOptions}. Also, the Backend instance is available via\n * {@link Client.getBackend}.\n *\n * If a Dsn is specified in the options, it will be parsed and stored. Use\n * {@link Client.getDsn} to retrieve the Dsn at any moment. In case the Dsn is\n * invalid, the constructor will throw a {@link SentryException}. Note that\n * without a valid Dsn, the SDK will not send any events to Sentry.\n *\n * Before sending an event via the backend, it is passed through\n * {@link BaseClient._prepareEvent} to add SDK information and scope data\n * (breadcrumbs and context). To add more custom information, override this\n * method and extend the resulting prepared event.\n *\n * To issue automatically created events (e.g. via instrumentation), use\n * {@link Client.captureEvent}. It will prepare the event and pass it through\n * the callback lifecycle. To issue auto-breadcrumbs, use\n * {@link Client.addBreadcrumb}.\n *\n * @example\n * class NodeClient extends BaseClient<NodeBackend, NodeOptions> {\n * public constructor(options: NodeOptions) {\n * super(NodeBackend, options);\n * }\n *\n * // ...\n * }\n */\nexport abstract class BaseClient<B extends Backend, O extends Options> implements Client<O> {\n /**\n * The backend used to physically interact in the environment. Usually, this\n * will correspond to the client. When composing SDKs, however, the Backend\n * from the root SDK will be used.\n */\n protected readonly _backend: B;\n\n /** Options passed to the SDK. */\n protected readonly _options: O;\n\n /** The client Dsn, if specified in options. Without this Dsn, the SDK will be disabled. */\n protected readonly _dsn?: DsnComponents;\n\n /** Array of used integrations. */\n protected _integrations: IntegrationIndex = {};\n\n /** Number of calls being processed */\n protected _numProcessing: number = 0;\n\n /**\n * Initializes this client instance.\n *\n * @param backendClass A constructor function to create the backend.\n * @param options Options for the client.\n */\n protected constructor(backendClass: BackendClass<B, O>, options: O) {\n this._backend = new backendClass(options);\n this._options = options;\n\n if (options.dsn) {\n this._dsn = makeDsn(options.dsn);\n }\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\n public captureException(exception: any, hint?: EventHint, scope?: Scope): string | undefined {\n // ensure we haven't captured this very object before\n if (checkOrSetAlreadyCaught(exception)) {\n IS_DEBUG_BUILD && logger.log(ALREADY_SEEN_ERROR);\n return;\n }\n\n let eventId: string | undefined = hint && hint.event_id;\n\n this._process(\n this._getBackend()\n .eventFromException(exception, hint)\n .then(event => this._captureEvent(event, hint, scope))\n .then(result => {\n eventId = result;\n }),\n );\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public captureMessage(message: string, level?: Severity, hint?: EventHint, scope?: Scope): string | undefined {\n let eventId: string | undefined = hint && hint.event_id;\n\n const promisedEvent = isPrimitive(message)\n ? this._getBackend().eventFromMessage(String(message), level, hint)\n : this._getBackend().eventFromException(message, hint);\n\n this._process(\n promisedEvent\n .then(event => this._captureEvent(event, hint, scope))\n .then(result => {\n eventId = result;\n }),\n );\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public captureEvent(event: Event, hint?: EventHint, scope?: Scope): string | undefined {\n // ensure we haven't captured this very object before\n if (hint && hint.originalException && checkOrSetAlreadyCaught(hint.originalException)) {\n IS_DEBUG_BUILD && logger.log(ALREADY_SEEN_ERROR);\n return;\n }\n\n let eventId: string | undefined = hint && hint.event_id;\n\n this._process(\n this._captureEvent(event, hint, scope).then(result => {\n eventId = result;\n }),\n );\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public captureSession(session: Session): void {\n if (!this._isEnabled()) {\n IS_DEBUG_BUILD && logger.warn('SDK not enabled, will not capture session.');\n return;\n }\n\n if (!(typeof session.release === 'string')) {\n IS_DEBUG_BUILD && logger.warn('Discarded session because of missing or non-string release');\n } else {\n this._sendSession(session);\n // After sending, we set init false to indicate it's not the first occurrence\n session.update({ init: false });\n }\n }\n\n /**\n * @inheritDoc\n */\n public getDsn(): DsnComponents | undefined {\n return this._dsn;\n }\n\n /**\n * @inheritDoc\n */\n public getOptions(): O {\n return this._options;\n }\n\n /**\n * @inheritDoc\n */\n public getTransport(): Transport {\n return this._getBackend().getTransport();\n }\n\n /**\n * @inheritDoc\n */\n public flush(timeout?: number): PromiseLike<boolean> {\n return this._isClientDoneProcessing(timeout).then(clientFinished => {\n return this.getTransport()\n .close(timeout)\n .then(transportFlushed => clientFinished && transportFlushed);\n });\n }\n\n /**\n * @inheritDoc\n */\n public close(timeout?: number): PromiseLike<boolean> {\n return this.flush(timeout).then(result => {\n this.getOptions().enabled = false;\n return result;\n });\n }\n\n /**\n * Sets up the integrations\n */\n public setupIntegrations(): void {\n if (this._isEnabled() && !this._integrations.initialized) {\n this._integrations = setupIntegrations(this._options);\n }\n }\n\n /**\n * @inheritDoc\n */\n public getIntegration<T extends Integration>(integration: IntegrationClass<T>): T | null {\n try {\n return (this._integrations[integration.id] as T) || null;\n } catch (_oO) {\n IS_DEBUG_BUILD && logger.warn(`Cannot retrieve integration ${integration.id} from the current Client`);\n return null;\n }\n }\n\n /** Updates existing session based on the provided event */\n protected _updateSessionFromEvent(session: Session, event: Event): void {\n let crashed = false;\n let errored = false;\n const exceptions = event.exception && event.exception.values;\n\n if (exceptions) {\n errored = true;\n\n for (const ex of exceptions) {\n const mechanism = ex.mechanism;\n if (mechanism && mechanism.handled === false) {\n crashed = true;\n break;\n }\n }\n }\n\n // A session is updated and that session update is sent in only one of the two following scenarios:\n // 1. Session with non terminal status and 0 errors + an error occurred -> Will set error count to 1 and send update\n // 2. Session with non terminal status and 1 error + a crash occurred -> Will set status crashed and send update\n const sessionNonTerminal = session.status === 'ok';\n const shouldUpdateAndSend = (sessionNonTerminal && session.errors === 0) || (sessionNonTerminal && crashed);\n\n if (shouldUpdateAndSend) {\n session.update({\n ...(crashed && { status: 'crashed' }),\n errors: session.errors || Number(errored || crashed),\n });\n this.captureSession(session);\n }\n }\n\n /** Deliver captured session to Sentry */\n protected _sendSession(session: Session): void {\n this._getBackend().sendSession(session);\n }\n\n /**\n * Determine if the client is finished processing. Returns a promise because it will wait `timeout` ms before saying\n * \"no\" (resolving to `false`) in order to give the client a chance to potentially finish first.\n *\n * @param timeout The time, in ms, after which to resolve to `false` if the client is still busy. Passing `0` (or not\n * passing anything) will make the promise wait as long as it takes for processing to finish before resolving to\n * `true`.\n * @returns A promise which will resolve to `true` if processing is already done or finishes before the timeout, and\n * `false` otherwise\n */\n protected _isClientDoneProcessing(timeout?: number): PromiseLike<boolean> {\n return new SyncPromise(resolve => {\n let ticked: number = 0;\n const tick: number = 1;\n\n const interval = setInterval(() => {\n if (this._numProcessing == 0) {\n clearInterval(interval);\n resolve(true);\n } else {\n ticked += tick;\n if (timeout && ticked >= timeout) {\n clearInterval(interval);\n resolve(false);\n }\n }\n }, tick);\n });\n }\n\n /** Returns the current backend. */\n protected _getBackend(): B {\n return this._backend;\n }\n\n /** Determines whether this SDK is enabled and a valid Dsn is present. */\n protected _isEnabled(): boolean {\n return this.getOptions().enabled !== false && this._dsn !== undefined;\n }\n\n /**\n * Adds common information to events.\n *\n * The information includes release and environment from `options`,\n * breadcrumbs and context (extra, tags and user) from the scope.\n *\n * Information that is already present in the event is never overwritten. For\n * nested objects, such as the context, keys are merged.\n *\n * @param event The original event.\n * @param hint May contain additional information about the original exception.\n * @param scope A scope containing event metadata.\n * @returns A new event with more information.\n */\n protected _prepareEvent(event: Event, scope?: Scope, hint?: EventHint): PromiseLike<Event | null> {\n const { normalizeDepth = 3, normalizeMaxBreadth = 1_000 } = this.getOptions();\n const prepared: Event = {\n ...event,\n event_id: event.event_id || (hint && hint.event_id ? hint.event_id : uuid4()),\n timestamp: event.timestamp || dateTimestampInSeconds(),\n };\n\n this._applyClientOptions(prepared);\n this._applyIntegrationsMetadata(prepared);\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 let finalScope = scope;\n if (hint && hint.captureContext) {\n finalScope = Scope.clone(finalScope).update(hint.captureContext);\n }\n\n // We prepare the result here with a resolved Event.\n let result = resolvedSyncPromise<Event | null>(prepared);\n\n // This should be the last thing called, since we want that\n // {@link Hub.addEventProcessor} gets the finished prepared event.\n if (finalScope) {\n // In case we have a hub we reassign it.\n result = finalScope.applyToEvent(prepared, hint);\n }\n\n return result.then(evt => {\n if (evt) {\n // TODO this is more of the hack trying to solve https://github.com/getsentry/sentry-javascript/issues/2809\n // it is only attached as extra data to the event if the event somehow skips being normalized\n evt.sdkProcessingMetadata = {\n ...evt.sdkProcessingMetadata,\n normalizeDepth: `${normalize(normalizeDepth)} (${typeof normalizeDepth})`,\n };\n }\n if (typeof normalizeDepth === 'number' && normalizeDepth > 0) {\n return this._normalizeEvent(evt, normalizeDepth, normalizeMaxBreadth);\n }\n return evt;\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 */\n protected _normalizeEvent(event: Event | null, depth: number, maxBreadth: number): Event | null {\n if (!event) {\n return null;\n }\n\n const normalized = {\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 // 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) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n normalized.contexts.trace = event.contexts.trace;\n }\n\n normalized.sdkProcessingMetadata = { ...normalized.sdkProcessingMetadata, baseClientNormalized: true };\n\n return normalized;\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 */\n protected _applyClientOptions(event: Event): void {\n const options = this.getOptions();\n const { environment, release, dist, maxValueLength = 250 } = options;\n\n if (!('environment' in event)) {\n event.environment = 'environment' in options ? environment : 'production';\n }\n\n if (event.release === undefined && release !== undefined) {\n event.release = release;\n }\n\n if (event.dist === undefined && dist !== undefined) {\n event.dist = dist;\n }\n\n if (event.message) {\n event.message = truncate(event.message, maxValueLength);\n }\n\n 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\n /**\n * This function adds all used integrations to the SDK info in the event.\n * @param event The event that will be filled with all integrations.\n */\n protected _applyIntegrationsMetadata(event: Event): void {\n const integrationsArray = Object.keys(this._integrations);\n if (integrationsArray.length > 0) {\n event.sdk = event.sdk || {};\n event.sdk.integrations = [...(event.sdk.integrations || []), ...integrationsArray];\n }\n }\n\n /**\n * Tells the backend to send this event\n * @param event The Sentry event to send\n */\n protected _sendEvent(event: Event): void {\n this._getBackend().sendEvent(event);\n }\n\n /**\n * Processes the event and logs an error in case of rejection\n * @param event\n * @param hint\n * @param scope\n */\n protected _captureEvent(event: Event, hint?: EventHint, scope?: Scope): PromiseLike<string | undefined> {\n return this._processEvent(event, hint, scope).then(\n finalEvent => {\n return finalEvent.event_id;\n },\n reason => {\n IS_DEBUG_BUILD && logger.error(reason);\n return undefined;\n },\n );\n }\n\n /**\n * Processes an event (either error or message) and sends it to Sentry.\n *\n * This also adds breadcrumbs and context information to the event. However,\n * platform specific meta data (such as the User's IP address) must be added\n * by the SDK implementor.\n *\n *\n * @param event The event to send to Sentry.\n * @param hint May contain additional information about the original exception.\n * @param scope A scope containing event metadata.\n * @returns A SyncPromise that resolves with the event or rejects in case event was/will not be send.\n */\n protected _processEvent(event: Event, hint?: EventHint, scope?: Scope): PromiseLike<Event> {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const { beforeSend, sampleRate } = this.getOptions();\n const transport = this.getTransport();\n\n type RecordLostEvent = NonNullable<Transport['recordLostEvent']>;\n type RecordLostEventParams = Parameters<RecordLostEvent>;\n\n function recordLostEvent(outcome: RecordLostEventParams[0], category: RecordLostEventParams[1]): void {\n if (transport.recordLostEvent) {\n transport.recordLostEvent(outcome, category);\n }\n }\n\n if (!this._isEnabled()) {\n return rejectedSyncPromise(new SentryError('SDK not enabled, will not capture event.'));\n }\n\n const isTransaction = event.type === 'transaction';\n // 1.0 === 100% events are sent\n // 0.0 === 0% events are sent\n // Sampling for transaction happens somewhere else\n if (!isTransaction && typeof sampleRate === 'number' && Math.random() > sampleRate) {\n recordLostEvent('sample_rate', 'event');\n return rejectedSyncPromise(\n new SentryError(\n `Discarding event because it's not included in the random sample (sampling rate = ${sampleRate})`,\n ),\n );\n }\n\n return this._prepareEvent(event, scope, hint)\n .then(prepared => {\n if (prepared === null) {\n recordLostEvent('event_processor', event.type || 'event');\n throw new SentryError('An event processor returned null, will not send event.');\n }\n\n const isInternalException = hint && hint.data && (hint.data as { __sentry__: boolean }).__sentry__ === true;\n if (isInternalException || isTransaction || !beforeSend) {\n return prepared;\n }\n\n const beforeSendResult = beforeSend(prepared, hint);\n return _ensureBeforeSendRv(beforeSendResult);\n })\n .then(processedEvent => {\n if (processedEvent === null) {\n recordLostEvent('before_send', event.type || 'event');\n throw new SentryError('`beforeSend` returned `null`, will not send event.');\n }\n\n const session = scope && scope.getSession && scope.getSession();\n if (!isTransaction && session) {\n this._updateSessionFromEvent(session, processedEvent);\n }\n\n this._sendEvent(processedEvent);\n return processedEvent;\n })\n .then(null, reason => {\n if (reason instanceof SentryError) {\n throw reason;\n }\n\n this.captureException(reason, {\n data: {\n __sentry__: true,\n },\n originalException: reason as Error,\n });\n throw new SentryError(\n `Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.\\nReason: ${reason}`,\n );\n });\n }\n\n /**\n * Occupies the client with processing and event\n */\n protected _process<T>(promise: PromiseLike<T>): void {\n this._numProcessing += 1;\n void promise.then(\n value => {\n this._numProcessing -= 1;\n return value;\n },\n reason => {\n this._numProcessing -= 1;\n return reason;\n },\n );\n }\n}\n\n/**\n * Verifies that return value of configured `beforeSend` is of expected type.\n */\nfunction _ensureBeforeSendRv(rv: PromiseLike<Event | null> | Event | null): PromiseLike<Event | null> | Event | null {\n const nullErr = '`beforeSend` method has to return `null` or a valid event.';\n if (isThenable(rv)) {\n return rv.then(\n event => {\n if (!(isPlainObject(event) || event === null)) {\n throw new SentryError(nullErr);\n }\n return event;\n },\n e => {\n throw new SentryError(`beforeSend rejected with ${e}`);\n },\n );\n } else if (!(isPlainObject(rv) || rv === null)) {\n throw new SentryError(nullErr);\n }\n return rv;\n}\n","import {\n Event,\n EventEnvelope,\n EventItem,\n SdkInfo,\n SentryRequest,\n SentryRequestType,\n Session,\n SessionAggregates,\n SessionEnvelope,\n SessionItem,\n} from '@sentry/types';\nimport { createEnvelope, dsnToString, normalize, serializeEnvelope } from '@sentry/utils';\n\nimport { APIDetails, getEnvelopeEndpointWithUrlEncodedAuth, getStoreEndpointWithUrlEncodedAuth } from './api';\n\n/** Extract sdk info from from the API metadata */\nfunction getSdkMetadataForEnvelopeHeader(api: APIDetails): SdkInfo | undefined {\n if (!api.metadata || !api.metadata.sdk) {\n return;\n }\n const { name, version } = api.metadata.sdk;\n return { name, version };\n}\n\n/**\n * Apply SdkInfo (name, version, packages, integrations) to the corresponding event key.\n * Merge with existing data if any.\n **/\nfunction enhanceEventWithSdkInfo(event: Event, sdkInfo?: SdkInfo): Event {\n if (!sdkInfo) {\n return event;\n }\n event.sdk = event.sdk || {};\n event.sdk.name = event.sdk.name || sdkInfo.name;\n event.sdk.version = event.sdk.version || sdkInfo.version;\n event.sdk.integrations = [...(event.sdk.integrations || []), ...(sdkInfo.integrations || [])];\n event.sdk.packages = [...(event.sdk.packages || []), ...(sdkInfo.packages || [])];\n return event;\n}\n\n/** Creates an envelope from a Session */\nexport function createSessionEnvelope(\n session: Session | SessionAggregates,\n api: APIDetails,\n): [SessionEnvelope, SentryRequestType] {\n const sdkInfo = getSdkMetadataForEnvelopeHeader(api);\n const envelopeHeaders = {\n sent_at: new Date().toISOString(),\n ...(sdkInfo && { sdk: sdkInfo }),\n ...(!!api.tunnel && { dsn: dsnToString(api.dsn) }),\n };\n\n // I know this is hacky but we don't want to add `sessions` to request type since it's never rate limited\n const type = 'aggregates' in session ? ('sessions' as SentryRequestType) : 'session';\n\n // TODO (v7) Have to cast type because envelope items do not accept a `SentryRequestType`\n const envelopeItem = [{ type } as { type: 'session' | 'sessions' }, session] as SessionItem;\n const envelope = createEnvelope<SessionEnvelope>(envelopeHeaders, [envelopeItem]);\n\n return [envelope, type];\n}\n\n/** Creates a SentryRequest from a Session. */\nexport function sessionToSentryRequest(session: Session | SessionAggregates, api: APIDetails): SentryRequest {\n const [envelope, type] = createSessionEnvelope(session, api);\n return {\n body: serializeEnvelope(envelope),\n type,\n url: getEnvelopeEndpointWithUrlEncodedAuth(api.dsn, api.tunnel),\n };\n}\n\n/**\n * Create an Envelope from an event. Note that this is duplicated from below,\n * but on purpose as this will be refactored in v7.\n */\nexport function createEventEnvelope(event: Event, api: APIDetails): EventEnvelope {\n const sdkInfo = getSdkMetadataForEnvelopeHeader(api);\n const eventType = event.type || 'event';\n\n const { transactionSampling } = event.sdkProcessingMetadata || {};\n const { method: samplingMethod, rate: sampleRate } = transactionSampling || {};\n\n // TODO: Below is a temporary hack in order to debug a serialization error - see\n // https://github.com/getsentry/sentry-javascript/issues/2809,\n // https://github.com/getsentry/sentry-javascript/pull/4425, and\n // https://github.com/getsentry/sentry-javascript/pull/4574.\n //\n // TL; DR: even though we normalize all events (which should prevent this), something is causing `JSON.stringify` to\n // throw a circular reference error.\n //\n // When it's time to remove it:\n // 1. Delete everything between here and where the request object `req` is created, EXCEPT the line deleting\n // `sdkProcessingMetadata`\n // 2. Restore the original version of the request body, which is commented out\n // 3. Search for either of the PR URLs above and pull out the companion hacks in the browser playwright tests and the\n // baseClient tests in this package\n enhanceEventWithSdkInfo(event, api.metadata.sdk);\n event.tags = event.tags || {};\n event.extra = event.extra || {};\n\n // In theory, all events should be marked as having gone through normalization and so\n // we should never set this tag/extra data\n if (!(event.sdkProcessingMetadata && event.sdkProcessingMetadata.baseClientNormalized)) {\n event.tags.skippedNormalization = true;\n event.extra.normalizeDepth = event.sdkProcessingMetadata ? event.sdkProcessingMetadata.normalizeDepth : 'unset';\n }\n\n // prevent this data from being sent to sentry\n // TODO: This is NOT part of the hack - DO NOT DELETE\n delete event.sdkProcessingMetadata;\n\n const envelopeHeaders = {\n event_id: event.event_id as string,\n sent_at: new Date().toISOString(),\n ...(sdkInfo && { sdk: sdkInfo }),\n ...(!!api.tunnel && { dsn: dsnToString(api.dsn) }),\n };\n const eventItem: EventItem = [\n {\n type: eventType,\n sample_rates: [{ id: samplingMethod, rate: sampleRate }],\n },\n event,\n ];\n return createEnvelope<EventEnvelope>(envelopeHeaders, [eventItem]);\n}\n\n/** Creates a SentryRequest from an event. */\nexport function eventToSentryRequest(event: Event, api: APIDetails): SentryRequest {\n const sdkInfo = getSdkMetadataForEnvelopeHeader(api);\n const eventType = event.type || 'event';\n const useEnvelope = eventType === 'transaction' || !!api.tunnel;\n\n const { transactionSampling } = event.sdkProcessingMetadata || {};\n const { method: samplingMethod, rate: sampleRate } = transactionSampling || {};\n\n // TODO: Below is a temporary hack in order to debug a serialization error - see\n // https://github.com/getsentry/sentry-javascript/issues/2809,\n // https://github.com/getsentry/sentry-javascript/pull/4425, and\n // https://github.com/getsentry/sentry-javascript/pull/4574.\n //\n // TL; DR: even though we normalize all events (which should prevent this), something is causing `JSON.stringify` to\n // throw a circular reference error.\n //\n // When it's time to remove it:\n // 1. Delete everything between here and where the request object `req` is created, EXCEPT the line deleting\n // `sdkProcessingMetadata`\n // 2. Restore the original version of the request body, which is commented out\n // 3. Search for either of the PR URLs above and pull out the companion hacks in the browser playwright tests and the\n // baseClient tests in this package\n enhanceEventWithSdkInfo(event, api.metadata.sdk);\n event.tags = event.tags || {};\n event.extra = event.extra || {};\n\n // In theory, all events should be marked as having gone through normalization and so\n // we should never set this tag/extra data\n if (!(event.sdkProcessingMetadata && event.sdkProcessingMetadata.baseClientNormalized)) {\n event.tags.skippedNormalization = true;\n event.extra.normalizeDepth = event.sdkProcessingMetadata ? event.sdkProcessingMetadata.normalizeDepth : 'unset';\n }\n\n // prevent this data from being sent to sentry\n // TODO: This is NOT part of the hack - DO NOT DELETE\n delete event.sdkProcessingMetadata;\n\n let body;\n try {\n // 99.9% of events should get through just fine - no change in behavior for them\n body = JSON.stringify(event);\n } catch (err) {\n // Record data about the error without replacing original event data, then force renormalization\n event.tags.JSONStringifyError = true;\n event.extra.JSONStringifyError = err;\n try {\n body = JSON.stringify(normalize(event));\n } catch (newErr) {\n // At this point even renormalization hasn't worked, meaning something about the event data has gone very wrong.\n // Time to cut our losses and record only the new error. With luck, even in the problematic cases we're trying to\n // debug with this hack, we won't ever land here.\n const innerErr = newErr as Error;\n body = JSON.stringify({\n message: 'JSON.stringify error after renormalization',\n // setting `extra: { innerErr }` here for some reason results in an empty object, so unpack manually\n extra: { message: innerErr.message, stack: innerErr.stack },\n });\n }\n }\n\n const req: SentryRequest = {\n // this is the relevant line of code before the hack was added, to make it easy to undo said hack once we've solved\n // the mystery\n // body: JSON.stringify(sdkInfo ? enhanceEventWithSdkInfo(event, api.metadata.sdk) : event),\n body,\n type: eventType,\n url: useEnvelope\n ? getEnvelopeEndpointWithUrlEncodedAuth(api.dsn, api.tunnel)\n : getStoreEndpointWithUrlEncodedAuth(api.dsn),\n };\n\n // https://develop.sentry.dev/sdk/envelopes/\n\n // Since we don't need to manipulate envelopes nor store them, there is no\n // exported concept of an Envelope with operations including serialization and\n // deserialization. Instead, we only implement a minimal subset of the spec to\n // serialize events inline here.\n if (useEnvelope) {\n const envelopeHeaders = {\n event_id: event.event_id as string,\n sent_at: new Date().toISOString(),\n ...(sdkInfo && { sdk: sdkInfo }),\n ...(!!api.tunnel && { dsn: dsnToString(api.dsn) }),\n };\n const eventItem: EventItem = [\n {\n type: eventType,\n sample_rates: [{ id: samplingMethod, rate: sampleRate }],\n },\n req.body,\n ];\n const envelope = createEnvelope<EventEnvelope>(envelopeHeaders, [eventItem]);\n req.body = serializeEnvelope(envelope);\n }\n\n return req;\n}\n","import { Event, Response, Transport } from '@sentry/types';\nimport { resolvedSyncPromise } from '@sentry/utils';\n\n/** Noop transport */\nexport class NoopTransport implements Transport {\n /**\n * @inheritDoc\n */\n public sendEvent(_: Event): PromiseLike<Response> {\n return resolvedSyncPromise({\n reason: 'NoopTransport: Event has been skipped because no Dsn is configured.',\n status: 'skipped',\n });\n }\n\n /**\n * @inheritDoc\n */\n public close(_?: number): PromiseLike<boolean> {\n return resolvedSyncPromise(true);\n }\n}\n","import { Event, EventHint, Options, Session, Severity, Transport } from '@sentry/types';\nimport { logger, SentryError } from '@sentry/utils';\n\nimport { initAPIDetails } from './api';\nimport { IS_DEBUG_BUILD } from './flags';\nimport { createEventEnvelope, createSessionEnvelope } from './request';\nimport { NewTransport } from './transports/base';\nimport { NoopTransport } from './transports/noop';\n\n/**\n * Internal platform-dependent Sentry SDK Backend.\n *\n * While {@link Client} contains business logic specific to an SDK, the\n * Backend offers platform specific implementations for low-level operations.\n * These are persisting and loading information, sending events, and hooking\n * into the environment.\n *\n * Backends receive a handle to the Client in their constructor. When a\n * Backend automatically generates events, it must pass them to\n * the Client for validation and processing first.\n *\n * Usually, the Client will be of corresponding type, e.g. NodeBackend\n * receives NodeClient. However, higher-level SDKs can choose to instantiate\n * multiple Backends and delegate tasks between them. In this case, an event\n * generated by one backend might very well be sent by another one.\n *\n * The client also provides access to options via {@link Client.getOptions}.\n * @hidden\n */\nexport interface Backend {\n /** Creates an {@link Event} from all inputs to `captureException` and non-primitive inputs to `captureMessage`. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n eventFromException(exception: any, hint?: EventHint): PromiseLike<Event>;\n\n /** Creates an {@link Event} from primitive inputs to `captureMessage`. */\n eventFromMessage(message: string, level?: Severity, hint?: EventHint): PromiseLike<Event>;\n\n /** Submits the event to Sentry */\n sendEvent(event: Event): void;\n\n /** Submits the session to Sentry */\n sendSession(session: Session): void;\n\n /**\n * Returns the transport that is used by the backend.\n * Please note that the transport gets lazy initialized so it will only be there once the first event has been sent.\n *\n * @returns The transport.\n */\n getTransport(): Transport;\n}\n\n/**\n * A class object that can instantiate Backend objects.\n * @hidden\n */\nexport type BackendClass<B extends Backend, O extends Options> = new (options: O) => B;\n\n/**\n * This is the base implemention of a Backend.\n * @hidden\n */\nexport abstract class BaseBackend<O extends Options> implements Backend {\n /** Options passed to the SDK. */\n protected readonly _options: O;\n\n /** Cached transport used internally. */\n protected _transport: Transport;\n\n /** New v7 Transport that is initialized alongside the old one */\n protected _newTransport?: NewTransport;\n\n /** Creates a new backend instance. */\n public constructor(options: O) {\n this._options = options;\n if (!this._options.dsn) {\n IS_DEBUG_BUILD && logger.warn('No DSN provided, backend will not do anything.');\n }\n this._transport = this._setupTransport();\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\n public eventFromException(_exception: any, _hint?: EventHint): PromiseLike<Event> {\n throw new SentryError('Backend has to implement `eventFromException` method');\n }\n\n /**\n * @inheritDoc\n */\n public eventFromMessage(_message: string, _level?: Severity, _hint?: EventHint): PromiseLike<Event> {\n throw new SentryError('Backend has to implement `eventFromMessage` method');\n }\n\n /**\n * @inheritDoc\n */\n public sendEvent(event: Event): void {\n // TODO(v7): Remove the if-else\n if (\n this._newTransport &&\n this._options.dsn &&\n this._options._experiments &&\n this._options._experiments.newTransport\n ) {\n const api = initAPIDetails(this._options.dsn, this._options._metadata, this._options.tunnel);\n const env = createEventEnvelope(event, api);\n void this._newTransport.send(env).then(null, reason => {\n IS_DEBUG_BUILD && logger.error('Error while sending event:', reason);\n });\n } else {\n void this._transport.sendEvent(event).then(null, reason => {\n IS_DEBUG_BUILD && logger.error('Error while sending event:', reason);\n });\n }\n }\n\n /**\n * @inheritDoc\n */\n public sendSession(session: Session): void {\n if (!this._transport.sendSession) {\n IS_DEBUG_BUILD && logger.warn(\"Dropping session because custom transport doesn't implement sendSession\");\n return;\n }\n\n // TODO(v7): Remove the if-else\n if (\n this._newTransport &&\n this._options.dsn &&\n this._options._experiments &&\n this._options._experiments.newTransport\n ) {\n const api = initAPIDetails(this._options.dsn, this._options._metadata, this._options.tunnel);\n const [env] = createSessionEnvelope(session, api);\n void this._newTransport.send(env).then(null, reason => {\n IS_DEBUG_BUILD && logger.error('Error while sending session:', reason);\n });\n } else {\n void this._transport.sendSession(session).then(null, reason => {\n IS_DEBUG_BUILD && logger.error('Error while sending session:', reason);\n });\n }\n }\n\n /**\n * @inheritDoc\n */\n public getTransport(): Transport {\n return this._transport;\n }\n\n /**\n * Sets up the transport so it can be used later to send requests.\n */\n protected _setupTransport(): Transport {\n return new NoopTransport();\n }\n}\n","import { Envelope, EventStatus } from '@sentry/types';\nimport {\n disabledUntil,\n eventStatusFromHttpCode,\n getEnvelopeType,\n isRateLimited,\n makePromiseBuffer,\n PromiseBuffer,\n RateLimits,\n rejectedSyncPromise,\n resolvedSyncPromise,\n serializeEnvelope,\n updateRateLimits,\n} from '@sentry/utils';\n\nexport const ERROR_TRANSPORT_CATEGORY = 'error';\n\nexport const TRANSACTION_TRANSPORT_CATEGORY = 'transaction';\n\nexport const ATTACHMENT_TRANSPORT_CATEGORY = 'attachment';\n\nexport const SESSION_TRANSPORT_CATEGORY = 'session';\n\ntype TransportCategory =\n | typeof ERROR_TRANSPORT_CATEGORY\n | typeof TRANSACTION_TRANSPORT_CATEGORY\n | typeof ATTACHMENT_TRANSPORT_CATEGORY\n | typeof SESSION_TRANSPORT_CATEGORY;\n\nexport type TransportRequest = {\n body: string;\n category: TransportCategory;\n};\n\nexport type TransportMakeRequestResponse = {\n body?: string;\n headers?: {\n [key: string]: string | null;\n 'x-sentry-rate-limits': string | null;\n 'retry-after': string | null;\n };\n reason?: string;\n statusCode: number;\n};\n\nexport type TransportResponse = {\n status: EventStatus;\n reason?: string;\n};\n\ninterface InternalBaseTransportOptions {\n bufferSize?: number;\n}\n\nexport interface BaseTransportOptions extends InternalBaseTransportOptions {\n // url to send the event\n // transport does not care about dsn specific - client should take care of\n // parsing and figuring that out\n url: string;\n}\n\n// TODO: Move into Browser Transport\nexport interface BrowserTransportOptions extends BaseTransportOptions {\n // options to pass into fetch request\n fetchParams: Record<string, string>;\n headers?: Record<string, string>;\n sendClientReports?: boolean;\n}\n\nexport interface NewTransport {\n send(request: Envelope): PromiseLike<TransportResponse>;\n flush(timeout?: number): PromiseLike<boolean>;\n}\n\nexport type TransportRequestExecutor = (request: TransportRequest) => PromiseLike<TransportMakeRequestResponse>;\n\nexport const DEFAULT_TRANSPORT_BUFFER_SIZE = 30;\n\n/**\n * Creates a `NewTransport`\n *\n * @param options\n * @param makeRequest\n */\nexport function createTransport(\n options: InternalBaseTransportOptions,\n makeRequest: TransportRequestExecutor,\n buffer: PromiseBuffer<TransportResponse> = makePromiseBuffer(options.bufferSize || DEFAULT_TRANSPORT_BUFFER_SIZE),\n): NewTransport {\n let rateLimits: RateLimits = {};\n\n const flush = (timeout?: number): PromiseLike<boolean> => buffer.drain(timeout);\n\n function send(envelope: Envelope): PromiseLike<TransportResponse> {\n const envCategory = getEnvelopeType(envelope);\n const category = envCategory === 'event' ? 'error' : (envCategory as TransportCategory);\n const request: TransportRequest = {\n category,\n body: serializeEnvelope(envelope),\n };\n\n // Don't add to buffer if transport is already rate-limited\n if (isRateLimited(rateLimits, category)) {\n return rejectedSyncPromise({\n status: 'rate_limit',\n reason: getRateLimitReason(rateLimits, category),\n });\n }\n\n const requestTask = (): PromiseLike<TransportResponse> =>\n makeRequest(request).then(({ body, headers, reason, statusCode }): PromiseLike<TransportResponse> => {\n const status = eventStatusFromHttpCode(statusCode);\n if (headers) {\n rateLimits = updateRateLimits(rateLimits, headers);\n }\n if (status === 'success') {\n return resolvedSyncPromise({ status, reason });\n }\n return rejectedSyncPromise({\n status,\n reason:\n reason ||\n body ||\n (status === 'rate_limit' ? getRateLimitReason(rateLimits, category) : 'Unknown transport error'),\n });\n });\n\n return buffer.add(requestTask);\n }\n\n return {\n send,\n flush,\n };\n}\n\nfunction getRateLimitReason(rateLimits: RateLimits, category: TransportCategory): string {\n return `Too many ${category} requests, backing off until: ${new Date(\n disabledUntil(rateLimits, category),\n ).toISOString()}`;\n}\n","import { Integration, WrappedFunction } from '@sentry/types';\nimport { getOriginalFunction } from '@sentry/utils';\n\nlet originalFunctionToString: () => void;\n\n/** Patch toString calls to return proper name for wrapped functions */\nexport class FunctionToString implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'FunctionToString';\n\n /**\n * @inheritDoc\n */\n public name: string = FunctionToString.id;\n\n /**\n * @inheritDoc\n */\n public setupOnce(): void {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n originalFunctionToString = Function.prototype.toString;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n Function.prototype.toString = function (this: WrappedFunction, ...args: any[]): string {\n const context = getOriginalFunction(this) || this;\n return originalFunctionToString.apply(context, args);\n };\n }\n}\n","export const SDK_VERSION = '6.19.7';\n","import { Event, EventProcessor, Hub, Integration, StackFrame } from '@sentry/types';\nimport { getEventDescription, isMatchingPattern, logger } from '@sentry/utils';\n\nimport { IS_DEBUG_BUILD } from '../flags';\n\n// \"Script error.\" is hard coded into browsers for errors that it can't read.\n// this is the result of a script being pulled in from an external domain and CORS.\nconst DEFAULT_IGNORE_ERRORS = [/^Script error\\.?$/, /^Javascript error: Script error\\.? on line 0$/];\n\n/** Options for the InboundFilters integration */\nexport interface InboundFiltersOptions {\n allowUrls: Array<string | RegExp>;\n denyUrls: Array<string | RegExp>;\n ignoreErrors: Array<string | RegExp>;\n ignoreInternal: boolean;\n\n /** @deprecated use {@link InboundFiltersOptions.allowUrls} instead. */\n whitelistUrls: Array<string | RegExp>;\n /** @deprecated use {@link InboundFiltersOptions.denyUrls} instead. */\n blacklistUrls: Array<string | RegExp>;\n}\n\n/** Inbound filters configurable by the user */\nexport class InboundFilters implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'InboundFilters';\n\n /**\n * @inheritDoc\n */\n public name: string = InboundFilters.id;\n\n public constructor(private readonly _options: Partial<InboundFiltersOptions> = {}) {}\n\n /**\n * @inheritDoc\n */\n public setupOnce(addGlobalEventProcessor: (processor: EventProcessor) => void, getCurrentHub: () => Hub): void {\n addGlobalEventProcessor((event: Event) => {\n const hub = getCurrentHub();\n if (hub) {\n const self = hub.getIntegration(InboundFilters);\n if (self) {\n const client = hub.getClient();\n const clientOptions = client ? client.getOptions() : {};\n const options = _mergeOptions(self._options, clientOptions);\n return _shouldDropEvent(event, options) ? null : event;\n }\n }\n return event;\n });\n }\n}\n\n/** JSDoc */\nexport function _mergeOptions(\n internalOptions: Partial<InboundFiltersOptions> = {},\n clientOptions: Partial<InboundFiltersOptions> = {},\n): Partial<InboundFiltersOptions> {\n return {\n allowUrls: [\n // eslint-disable-next-line deprecation/deprecation\n ...(internalOptions.whitelistUrls || []),\n ...(internalOptions.allowUrls || []),\n // eslint-disable-next-line deprecation/deprecation\n ...(clientOptions.whitelistUrls || []),\n ...(clientOptions.allowUrls || []),\n ],\n denyUrls: [\n // eslint-disable-next-line deprecation/deprecation\n ...(internalOptions.blacklistUrls || []),\n ...(internalOptions.denyUrls || []),\n // eslint-disable-next-line deprecation/deprecation\n ...(clientOptions.blacklistUrls || []),\n ...(clientOptions.denyUrls || []),\n ],\n ignoreErrors: [\n ...(internalOptions.ignoreErrors || []),\n ...(clientOptions.ignoreErrors || []),\n ...DEFAULT_IGNORE_ERRORS,\n ],\n ignoreInternal: internalOptions.ignoreInternal !== undefined ? internalOptions.ignoreInternal : true,\n };\n}\n\n/** JSDoc */\nexport function _shouldDropEvent(event: Event, options: Partial<InboundFiltersOptions>): boolean {\n if (options.ignoreInternal && _isSentryError(event)) {\n IS_DEBUG_BUILD &&\n logger.warn(`Event dropped due to being internal Sentry Error.\\nEvent: ${getEventDescription(event)}`);\n return true;\n }\n if (_isIgnoredError(event, options.ignoreErrors)) {\n IS_DEBUG_BUILD &&\n logger.warn(\n `Event dropped due to being matched by \\`ignoreErrors\\` option.\\nEvent: ${getEventDescription(event)}`,\n );\n return true;\n }\n if (_isDeniedUrl(event, options.denyUrls)) {\n IS_DEBUG_BUILD &&\n logger.warn(\n `Event dropped due to being matched by \\`denyUrls\\` option.\\nEvent: ${getEventDescription(\n event,\n )}.\\nUrl: ${_getEventFilterUrl(event)}`,\n );\n return true;\n }\n if (!_isAllowedUrl(event, options.allowUrls)) {\n IS_DEBUG_BUILD &&\n logger.warn(\n `Event dropped due to not being matched by \\`allowUrls\\` option.\\nEvent: ${getEventDescription(\n event,\n )}.\\nUrl: ${_getEventFilterUrl(event)}`,\n );\n return true;\n }\n return false;\n}\n\nfunction _isIgnoredError(event: Event, ignoreErrors?: Array<string | RegExp>): boolean {\n if (!ignoreErrors || !ignoreErrors.length) {\n return false;\n }\n\n return _getPossibleEventMessages(event).some(message =>\n ignoreErrors.some(pattern => isMatchingPattern(message, pattern)),\n );\n}\n\nfunction _isDeniedUrl(event: Event, denyUrls?: Array<string | RegExp>): boolean {\n // TODO: Use Glob instead?\n if (!denyUrls || !denyUrls.length) {\n return false;\n }\n const url = _getEventFilterUrl(event);\n return !url ? false : denyUrls.some(pattern => isMatchingPattern(url, pattern));\n}\n\nfunction _isAllowedUrl(event: Event, allowUrls?: Array<string | RegExp>): boolean {\n // TODO: Use Glob instead?\n if (!allowUrls || !allowUrls.length) {\n return true;\n }\n const url = _getEventFilterUrl(event);\n return !url ? true : allowUrls.some(pattern => isMatchingPattern(url, pattern));\n}\n\nfunction _getPossibleEventMessages(event: Event): string[] {\n if (event.message) {\n return [event.message];\n }\n if (event.exception) {\n try {\n const { type = '', value = '' } = (event.exception.values && event.exception.values[0]) || {};\n return [`${value}`, `${type}: ${value}`];\n } catch (oO) {\n IS_DEBUG_BUILD && logger.error(`Cannot extract message for event ${getEventDescription(event)}`);\n return [];\n }\n }\n return [];\n}\n\nfunction _isSentryError(event: Event): boolean {\n try {\n // @ts-ignore can't be a sentry error if undefined\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return event.exception.values[0].type === 'SentryError';\n } catch (e) {\n // ignore\n }\n return false;\n}\n\nfunction _getLastValidUrl(frames: StackFrame[] = []): string | null {\n for (let i = frames.length - 1; i >= 0; i--) {\n const frame = frames[i];\n\n if (frame && frame.filename !== '<anonymous>' && frame.filename !== '[native code]') {\n return frame.filename || null;\n }\n }\n\n return null;\n}\n\nfunction _getEventFilterUrl(event: Event): string | null {\n try {\n if (event.stacktrace) {\n return _getLastValidUrl(event.stacktrace.frames);\n }\n let frames;\n try {\n // @ts-ignore we only care about frames if the whole thing here is defined\n frames = event.exception.values[0].stacktrace.frames;\n } catch (e) {\n // ignore\n }\n return frames ? _getLastValidUrl(frames) : null;\n } catch (oO) {\n IS_DEBUG_BUILD && logger.error(`Cannot extract url for event ${getEventDescription(event)}`);\n return null;\n }\n}\n","import { StackFrame } from '@sentry/types';\nimport { StackLineParser, StackLineParserFn } from '@sentry/utils';\n\n// global reference to slice\nconst UNKNOWN_FUNCTION = '?';\n\nconst OPERA10_PRIORITY = 10;\nconst OPERA11_PRIORITY = 20;\nconst CHROME_PRIORITY = 30;\nconst WINJS_PRIORITY = 40;\nconst GECKO_PRIORITY = 50;\n\nfunction createFrame(filename: string, func: string, lineno?: number, colno?: number): StackFrame {\n const frame: StackFrame = {\n filename,\n function: func,\n // All browser frames are considered in_app\n in_app: true,\n };\n\n if (lineno !== undefined) {\n frame.lineno = lineno;\n }\n\n if (colno !== undefined) {\n frame.colno = colno;\n }\n\n return frame;\n}\n\n// Chromium based browsers: Chrome, Brave, new Opera, new Edge\nconst chromeRegex =\n /^\\s*at (?:(.*?) ?\\((?:address at )?)?((?:file|https?|blob|chrome-extension|address|native|eval|webpack|<anonymous>|[-a-z]+:|.*bundle|\\/).*?)(?::(\\d+))?(?::(\\d+))?\\)?\\s*$/i;\nconst chromeEvalRegex = /\\((\\S*)(?::(\\d+))(?::(\\d+))\\)/;\n\nconst chrome: StackLineParserFn = line => {\n const parts = chromeRegex.exec(line);\n\n if (parts) {\n const isEval = parts[2] && parts[2].indexOf('eval') === 0; // start of line\n\n if (isEval) {\n const subMatch = chromeEvalRegex.exec(parts[2]);\n\n if (subMatch) {\n // throw out eval line/column and use top-most line/column number\n parts[2] = subMatch[1]; // url\n parts[3] = subMatch[2]; // line\n parts[4] = subMatch[3]; // column\n }\n }\n\n // Kamil: One more hack won't hurt us right? Understanding and adding more rules on top of these regexps right now\n // would be way too time consuming. (TODO: Rewrite whole RegExp to be more readable)\n const [func, filename] = extractSafariExtensionDetails(parts[1] || UNKNOWN_FUNCTION, parts[2]);\n\n return createFrame(filename, func, parts[3] ? +parts[3] : undefined, parts[4] ? +parts[4] : undefined);\n }\n\n return;\n};\n\nexport const chromeStackParser: StackLineParser = [CHROME_PRIORITY, chrome];\n\n// gecko regex: `(?:bundle|\\d+\\.js)`: `bundle` is for react native, `\\d+\\.js` also but specifically for ram bundles because it\n// generates filenames without a prefix like `file://` the filenames in the stacktrace are just 42.js\n// We need this specific case for now because we want no other regex to match.\nconst geckoREgex =\n /^\\s*(.*?)(?:\\((.*?)\\))?(?:^|@)?((?:file|https?|blob|chrome|webpack|resource|moz-extension|capacitor).*?:\\/.*?|\\[native code\\]|[^@]*(?:bundle|\\d+\\.js)|\\/[\\w\\-. /=]+)(?::(\\d+))?(?::(\\d+))?\\s*$/i;\nconst geckoEvalRegex = /(\\S+) line (\\d+)(?: > eval line \\d+)* > eval/i;\n\nconst gecko: StackLineParserFn = line => {\n const parts = geckoREgex.exec(line);\n\n if (parts) {\n const isEval = parts[3] && parts[3].indexOf(' > eval') > -1;\n if (isEval) {\n const subMatch = geckoEvalRegex.exec(parts[3]);\n\n if (subMatch) {\n // throw out eval line/column and use top-most line number\n parts[1] = parts[1] || 'eval';\n parts[3] = subMatch[1];\n parts[4] = subMatch[2];\n parts[5] = ''; // no column when eval\n }\n }\n\n let filename = parts[3];\n let func = parts[1] || UNKNOWN_FUNCTION;\n [func, filename] = extractSafariExtensionDetails(func, filename);\n\n return createFrame(filename, func, parts[4] ? +parts[4] : undefined, parts[5] ? +parts[5] : undefined);\n }\n\n return;\n};\n\nexport const geckoStackParser: StackLineParser = [GECKO_PRIORITY, gecko];\n\nconst winjsRegex =\n /^\\s*at (?:((?:\\[object object\\])?.+) )?\\(?((?:file|ms-appx|https?|webpack|blob):.*?):(\\d+)(?::(\\d+))?\\)?\\s*$/i;\n\nconst winjs: StackLineParserFn = line => {\n const parts = winjsRegex.exec(line);\n\n return parts\n ? createFrame(parts[2], parts[1] || UNKNOWN_FUNCTION, +parts[3], parts[4] ? +parts[4] : undefined)\n : undefined;\n};\n\nexport const winjsStackParser: StackLineParser = [WINJS_PRIORITY, winjs];\n\nconst opera10Regex = / line (\\d+).*script (?:in )?(\\S+)(?:: in function (\\S+))?$/i;\n\nconst opera10: StackLineParserFn = line => {\n const parts = opera10Regex.exec(line);\n return parts ? createFrame(parts[2], parts[3] || UNKNOWN_FUNCTION, +parts[1]) : undefined;\n};\n\nexport const opera10StackParser: StackLineParser = [OPERA10_PRIORITY, opera10];\n\nconst opera11Regex =\n / line (\\d+), column (\\d+)\\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\\(.*\\))? in (.*):\\s*$/i;\n\nconst opera11: StackLineParserFn = line => {\n const parts = opera11Regex.exec(line);\n return parts ? createFrame(parts[5], parts[3] || parts[4] || UNKNOWN_FUNCTION, +parts[1], +parts[2]) : undefined;\n};\n\nexport const opera11StackParser: StackLineParser = [OPERA11_PRIORITY, opera11];\n\n/**\n * Safari web extensions, starting version unknown, can produce \"frames-only\" stacktraces.\n * What it means, is that instead of format like:\n *\n * Error: wat\n * at function@url:row:col\n * at function@url:row:col\n * at function@url:row:col\n *\n * it produces something like:\n *\n * function@url:row:col\n * function@url:row:col\n * function@url:row:col\n *\n * Because of that, it won't be captured by `chrome` RegExp and will fall into `Gecko` branch.\n * This function is extracted so that we can use it in both places without duplicating the logic.\n * Unfortunately \"just\" changing RegExp is too complicated now and making it pass all tests\n * and fix this case seems like an impossible, or at least way too time-consuming task.\n */\nconst extractSafariExtensionDetails = (func: string, filename: string): [string, string] => {\n const isSafariExtension = func.indexOf('safari-extension') !== -1;\n const isSafariWebExtension = func.indexOf('safari-web-extension') !== -1;\n\n return isSafariExtension || isSafariWebExtension\n ? [\n func.indexOf('@') !== -1 ? func.split('@')[0] : UNKNOWN_FUNCTION,\n isSafariExtension ? `safari-extension:${filename}` : `safari-web-extension:${filename}`,\n ]\n : [func, filename];\n};\n","import { Event, EventHint, Exception, Severity, StackFrame } from '@sentry/types';\nimport {\n addExceptionMechanism,\n addExceptionTypeValue,\n createStackParser,\n extractExceptionKeysForMessage,\n isDOMError,\n isDOMException,\n isError,\n isErrorEvent,\n isEvent,\n isPlainObject,\n normalizeToSize,\n resolvedSyncPromise,\n} from '@sentry/utils';\n\nimport {\n chromeStackParser,\n geckoStackParser,\n opera10StackParser,\n opera11StackParser,\n winjsStackParser,\n} from './stack-parsers';\n\n/**\n * This function creates an exception from an TraceKitStackTrace\n * @param stacktrace TraceKitStackTrace that will be converted to an exception\n * @hidden\n */\nexport function exceptionFromError(ex: Error): Exception {\n // Get the frames first since Opera can lose the stack if we touch anything else first\n const frames = parseStackFrames(ex);\n\n const exception: Exception = {\n type: ex && ex.name,\n value: extractMessage(ex),\n };\n\n if (frames.length) {\n exception.stacktrace = { frames };\n }\n\n if (exception.type === undefined && exception.value === '') {\n exception.value = 'Unrecoverable error caught';\n }\n\n return exception;\n}\n\n/**\n * @hidden\n */\nexport function eventFromPlainObject(\n exception: Record<string, unknown>,\n syntheticException?: Error,\n isUnhandledRejection?: boolean,\n): Event {\n const event: Event = {\n exception: {\n values: [\n {\n type: isEvent(exception) ? exception.constructor.name : isUnhandledRejection ? 'UnhandledRejection' : 'Error',\n value: `Non-Error ${\n isUnhandledRejection ? 'promise rejection' : 'exception'\n } captured with keys: ${extractExceptionKeysForMessage(exception)}`,\n },\n ],\n },\n extra: {\n __serialized__: normalizeToSize(exception),\n },\n };\n\n if (syntheticException) {\n const frames = parseStackFrames(syntheticException);\n if (frames.length) {\n event.stacktrace = { frames };\n }\n }\n\n return event;\n}\n\n/**\n * @hidden\n */\nexport function eventFromError(ex: Error): Event {\n return {\n exception: {\n values: [exceptionFromError(ex)],\n },\n };\n}\n\n/** Parses stack frames from an error */\nexport function parseStackFrames(ex: Error & { framesToPop?: number; stacktrace?: string }): StackFrame[] {\n // Access and store the stacktrace property before doing ANYTHING\n // else to it because Opera is not very good at providing it\n // reliably in other circumstances.\n const stacktrace = ex.stacktrace || ex.stack || '';\n\n const popSize = getPopSize(ex);\n\n try {\n return createStackParser(\n opera10StackParser,\n opera11StackParser,\n chromeStackParser,\n winjsStackParser,\n geckoStackParser,\n )(stacktrace, popSize);\n } catch (e) {\n // no-empty\n }\n\n return [];\n}\n\n// Based on our own mapping pattern - https://github.com/getsentry/sentry/blob/9f08305e09866c8bd6d0c24f5b0aabdd7dd6c59c/src/sentry/lang/javascript/errormapping.py#L83-L108\nconst reactMinifiedRegexp = /Minified React error #\\d+;/i;\n\nfunction getPopSize(ex: Error & { framesToPop?: number }): number {\n if (ex) {\n if (typeof ex.framesToPop === 'number') {\n return ex.framesToPop;\n }\n\n if (reactMinifiedRegexp.test(ex.message)) {\n return 1;\n }\n }\n\n return 0;\n}\n\n/**\n * There are cases where stacktrace.message is an Event object\n * https://github.com/getsentry/sentry-javascript/issues/1949\n * In this specific case we try to extract stacktrace.message.error.message\n */\nfunction extractMessage(ex: Error & { message: { error?: Error } }): string {\n const message = ex && ex.message;\n if (!message) {\n return 'No error message';\n }\n if (message.error && typeof message.error.message === 'string') {\n return message.error.message;\n }\n return message;\n}\n\n/**\n * Creates an {@link Event} from all inputs to `captureException` and non-primitive inputs to `captureMessage`.\n * @hidden\n */\nexport function eventFromException(\n exception: unknown,\n hint?: EventHint,\n attachStacktrace?: boolean,\n): PromiseLike<Event> {\n const syntheticException = (hint && hint.syntheticException) || undefined;\n const event = eventFromUnknownInput(exception, syntheticException, attachStacktrace);\n addExceptionMechanism(event); // defaults to { type: 'generic', handled: true }\n event.level = Severity.Error;\n if (hint && hint.event_id) {\n event.event_id = hint.event_id;\n }\n return resolvedSyncPromise(event);\n}\n\n/**\n * Builds and Event from a Message\n * @hidden\n */\nexport function eventFromMessage(\n message: string,\n level: Severity = Severity.Info,\n hint?: EventHint,\n attachStacktrace?: boolean,\n): PromiseLike<Event> {\n const syntheticException = (hint && hint.syntheticException) || undefined;\n const event = eventFromString(message, syntheticException, attachStacktrace);\n event.level = level;\n if (hint && hint.event_id) {\n event.event_id = hint.event_id;\n }\n return resolvedSyncPromise(event);\n}\n\n/**\n * @hidden\n */\nexport function eventFromUnknownInput(\n exception: unknown,\n syntheticException?: Error,\n attachStacktrace?: boolean,\n isUnhandledRejection?: boolean,\n): Event {\n let event: Event;\n\n if (isErrorEvent(exception as ErrorEvent) && (exception as ErrorEvent).error) {\n // If it is an ErrorEvent with `error` property, extract it to get actual Error\n const errorEvent = exception as ErrorEvent;\n return eventFromError(errorEvent.error as Error);\n }\n\n // If it is a `DOMError` (which is a legacy API, but still supported in some browsers) then we just extract the name\n // and message, as it doesn't provide anything else. According to the spec, all `DOMExceptions` should also be\n // `Error`s, but that's not the case in IE11, so in that case we treat it the same as we do a `DOMError`.\n //\n // https://developer.mozilla.org/en-US/docs/Web/API/DOMError\n // https://developer.mozilla.org/en-US/docs/Web/API/DOMException\n // https://webidl.spec.whatwg.org/#es-DOMException-specialness\n if (isDOMError(exception as DOMError) || isDOMException(exception as DOMException)) {\n const domException = exception as DOMException;\n\n if ('stack' in (exception as Error)) {\n event = eventFromError(exception as Error);\n } else {\n const name = domException.name || (isDOMError(domException) ? 'DOMError' : 'DOMException');\n const message = domException.message ? `${name}: ${domException.message}` : name;\n event = eventFromString(message, syntheticException, attachStacktrace);\n addExceptionTypeValue(event, message);\n }\n if ('code' in domException) {\n event.tags = { ...event.tags, 'DOMException.code': `${domException.code}` };\n }\n\n return event;\n }\n if (isError(exception)) {\n // we have a real Error object, do nothing\n return eventFromError(exception);\n }\n if (isPlainObject(exception) || isEvent(exception)) {\n // If it's a plain object or an instance of `Event` (the built-in JS kind, not this SDK's `Event` type), serialize\n // it manually. This will allow us to group events based on top-level keys which is much better than creating a new\n // group on any key/value change.\n const objectException = exception as Record<string, unknown>;\n event = eventFromPlainObject(objectException, syntheticException, isUnhandledRejection);\n addExceptionMechanism(event, {\n synthetic: true,\n });\n return event;\n }\n\n // If none of previous checks were valid, then it means that it's not:\n // - an instance of DOMError\n // - an instance of DOMException\n // - an instance of Event\n // - an instance of Error\n // - a valid ErrorEvent (one with an error property)\n // - a plain Object\n //\n // So bail out and capture it as a simple message:\n event = eventFromString(exception as string, syntheticException, attachStacktrace);\n addExceptionTypeValue(event, `${exception}`, undefined);\n addExceptionMechanism(event, {\n synthetic: true,\n });\n\n return event;\n}\n\n/**\n * @hidden\n */\nexport function eventFromString(input: string, syntheticException?: Error, attachStacktrace?: boolean): Event {\n const event: Event = {\n message: input,\n };\n\n if (attachStacktrace && syntheticException) {\n const frames = parseStackFrames(syntheticException);\n if (frames.length) {\n event.stacktrace = { frames };\n }\n }\n\n return event;\n}\n","/*\n * This file defines flags and constants that can be modified during compile time in order to facilitate tree shaking\n * for users.\n *\n * Debug flags need to be declared in each package individually and must not be imported across package boundaries,\n * because some build tools have trouble tree-shaking imported guards.\n *\n * As a convention, we define debug flags in a `flags.ts` file in the root of a package's `src` folder.\n *\n * Debug flag files will contain \"magic strings\" like `__SENTRY_DEBUG__` that may get replaced with actual values during\n * our, or the user's build process. Take care when introducing new flags - they must not throw if they are not\n * replaced.\n */\n\ndeclare const __SENTRY_DEBUG__: boolean;\n\n/** Flag that is true for debug builds, false otherwise. */\nexport const IS_DEBUG_BUILD = typeof __SENTRY_DEBUG__ === 'undefined' ? true : __SENTRY_DEBUG__;\n","import { forget, getGlobalObject, isNativeFetch, logger, supportsFetch } from '@sentry/utils';\n\nimport { IS_DEBUG_BUILD } from '../flags';\n\nconst global = getGlobalObject<Window>();\nlet cachedFetchImpl: FetchImpl;\n\nexport type FetchImpl = typeof fetch;\n\n/**\n * A special usecase for incorrectly wrapped Fetch APIs in conjunction with ad-blockers.\n * Whenever someone wraps the Fetch API and returns the wrong promise chain,\n * this chain becomes orphaned and there is no possible way to capture it's rejections\n * other than allowing it bubble up to this very handler. eg.\n *\n * const f = window.fetch;\n * window.fetch = function () {\n * const p = f.apply(this, arguments);\n *\n * p.then(function() {\n * console.log('hi.');\n * });\n *\n * return p;\n * }\n *\n * `p.then(function () { ... })` is producing a completely separate promise chain,\n * however, what's returned is `p` - the result of original `fetch` call.\n *\n * This mean, that whenever we use the Fetch API to send our own requests, _and_\n * some ad-blocker blocks it, this orphaned chain will _always_ reject,\n * effectively causing another event to be captured.\n * This makes a whole process become an infinite loop, which we need to somehow\n * deal with, and break it in one way or another.\n *\n * To deal with this issue, we are making sure that we _always_ use the real\n * browser Fetch API, instead of relying on what `window.fetch` exposes.\n * The only downside to this would be missing our own requests as breadcrumbs,\n * but because we are already not doing this, it should be just fine.\n *\n * Possible failed fetch error messages per-browser:\n *\n * Chrome: Failed to fetch\n * Edge: Failed to Fetch\n * Firefox: NetworkError when attempting to fetch resource\n * Safari: resource blocked by content blocker\n */\nexport function getNativeFetchImplementation(): FetchImpl {\n if (cachedFetchImpl) {\n return cachedFetchImpl;\n }\n\n /* eslint-disable @typescript-eslint/unbound-method */\n\n // Fast path to avoid DOM I/O\n if (isNativeFetch(global.fetch)) {\n return (cachedFetchImpl = global.fetch.bind(global));\n }\n\n const document = global.document;\n let fetchImpl = global.fetch;\n // eslint-disable-next-line deprecation/deprecation\n if (document && typeof document.createElement === 'function') {\n try {\n const sandbox = document.createElement('iframe');\n sandbox.hidden = true;\n document.head.appendChild(sandbox);\n const contentWindow = sandbox.contentWindow;\n if (contentWindow && contentWindow.fetch) {\n fetchImpl = contentWindow.fetch;\n }\n document.head.removeChild(sandbox);\n } catch (e) {\n IS_DEBUG_BUILD &&\n logger.warn('Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ', e);\n }\n }\n\n return (cachedFetchImpl = fetchImpl.bind(global));\n /* eslint-enable @typescript-eslint/unbound-method */\n}\n\n/**\n * Sends sdk client report using sendBeacon or fetch as a fallback if available\n *\n * @param url report endpoint\n * @param body report payload\n */\nexport function sendReport(url: string, body: string): void {\n const isRealNavigator = Object.prototype.toString.call(global && global.navigator) === '[object Navigator]';\n const hasSendBeacon = isRealNavigator && typeof global.navigator.sendBeacon === 'function';\n\n if (hasSendBeacon) {\n // Prevent illegal invocations - https://xgwang.me/posts/you-may-not-know-beacon/#it-may-throw-error%2C-be-sure-to-catch\n const sendBeacon = global.navigator.sendBeacon.bind(global.navigator);\n return sendBeacon(url, body);\n }\n\n if (supportsFetch()) {\n const fetch = getNativeFetchImplementation();\n return forget(\n fetch(url, {\n body,\n method: 'POST',\n credentials: 'omit',\n keepalive: true,\n }),\n );\n }\n}\n","/**\n * Consumes the promise and logs the error when it rejects.\n * @param promise A promise to forget.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function forget(promise: PromiseLike<any>): void {\n void promise.then(null, e => {\n // TODO: Use a better logging mechanism\n // eslint-disable-next-line no-console\n console.error(e);\n });\n}\n","import {\n APIDetails,\n eventToSentryRequest,\n getEnvelopeEndpointWithUrlEncodedAuth,\n getStoreEndpointWithUrlEncodedAuth,\n initAPIDetails,\n sessionToSentryRequest,\n} from '@sentry/core';\nimport {\n ClientReport,\n Event,\n Outcome,\n Response as SentryResponse,\n SentryRequest,\n SentryRequestType,\n Session,\n Transport,\n TransportOptions,\n} from '@sentry/types';\nimport {\n createClientReportEnvelope,\n disabledUntil,\n dsnToString,\n eventStatusFromHttpCode,\n getGlobalObject,\n isRateLimited,\n logger,\n makePromiseBuffer,\n PromiseBuffer,\n RateLimits,\n serializeEnvelope,\n updateRateLimits,\n} from '@sentry/utils';\n\nimport { IS_DEBUG_BUILD } from '../flags';\nimport { sendReport } from './utils';\n\nfunction requestTypeToCategory(ty: SentryRequestType): string {\n const tyStr = ty as string;\n return tyStr === 'event' ? 'error' : tyStr;\n}\n\nconst global = getGlobalObject<Window>();\n\n/** Base Transport class implementation */\nexport abstract class BaseTransport implements Transport {\n /**\n * @deprecated\n */\n public url: string;\n\n /** Helper to get Sentry API endpoints. */\n protected readonly _api: APIDetails;\n\n /** A simple buffer holding all requests. */\n protected readonly _buffer: PromiseBuffer<SentryResponse> = makePromiseBuffer(30);\n\n /** Locks transport after receiving rate limits in a response */\n protected _rateLimits: RateLimits = {};\n\n protected _outcomes: { [key: string]: number } = {};\n\n public constructor(public options: TransportOptions) {\n this._api = initAPIDetails(options.dsn, options._metadata, options.tunnel);\n // eslint-disable-next-line deprecation/deprecation\n this.url = getStoreEndpointWithUrlEncodedAuth(this._api.dsn);\n\n if (this.options.sendClientReports && global.document) {\n global.document.addEventListener('visibilitychange', () => {\n if (global.document.visibilityState === 'hidden') {\n this._flushOutcomes();\n }\n });\n }\n }\n\n /**\n * @inheritDoc\n */\n public sendEvent(event: Event): PromiseLike<SentryResponse> {\n return this._sendRequest(eventToSentryRequest(event, this._api), event);\n }\n\n /**\n * @inheritDoc\n */\n public sendSession(session: Session): PromiseLike<SentryResponse> {\n return this._sendRequest(sessionToSentryRequest(session, this._api), session);\n }\n\n /**\n * @inheritDoc\n */\n public close(timeout?: number): PromiseLike<boolean> {\n return this._buffer.drain(timeout);\n }\n\n /**\n * @inheritDoc\n */\n public recordLostEvent(reason: Outcome, category: SentryRequestType): void {\n if (!this.options.sendClientReports) {\n return;\n }\n // We want to track each category (event, transaction, session) separately\n // but still keep the distinction between different type of outcomes.\n // We could use nested maps, but it's much easier to read and type this way.\n // A correct type for map-based implementation if we want to go that route\n // would be `Partial<Record<SentryRequestType, Partial<Record<Outcome, number>>>>`\n const key = `${requestTypeToCategory(category)}:${reason}`;\n IS_DEBUG_BUILD && logger.log(`Adding outcome: ${key}`);\n this._outcomes[key] = (this._outcomes[key] ?? 0) + 1;\n }\n\n /**\n * Send outcomes as an envelope\n */\n protected _flushOutcomes(): void {\n if (!this.options.sendClientReports) {\n return;\n }\n\n const outcomes = this._outcomes;\n this._outcomes = {};\n\n // Nothing to send\n if (!Object.keys(outcomes).length) {\n IS_DEBUG_BUILD && logger.log('No outcomes to flush');\n return;\n }\n\n IS_DEBUG_BUILD && logger.log(`Flushing outcomes:\\n${JSON.stringify(outcomes, null, 2)}`);\n\n const url = getEnvelopeEndpointWithUrlEncodedAuth(this._api.dsn, this._api.tunnel);\n\n const discardedEvents = Object.keys(outcomes).map(key => {\n const [category, reason] = key.split(':');\n return {\n reason,\n category,\n quantity: outcomes[key],\n };\n // TODO: Improve types on discarded_events to get rid of cast\n }) as ClientReport['discarded_events'];\n const envelope = createClientReportEnvelope(discardedEvents, this._api.tunnel && dsnToString(this._api.dsn));\n\n try {\n sendReport(url, serializeEnvelope(envelope));\n } catch (e) {\n IS_DEBUG_BUILD && logger.error(e);\n }\n }\n\n /**\n * Handle Sentry repsonse for promise-based transports.\n */\n protected _handleResponse({\n requestType,\n response,\n headers,\n resolve,\n reject,\n }: {\n requestType: SentryRequestType;\n response: Response | XMLHttpRequest;\n headers: Record<string, string | null>;\n resolve: (value?: SentryResponse | PromiseLike<SentryResponse> | null | undefined) => void;\n reject: (reason?: unknown) => void;\n }): void {\n const status = eventStatusFromHttpCode(response.status);\n\n this._rateLimits = updateRateLimits(this._rateLimits, headers);\n // eslint-disable-next-line deprecation/deprecation\n if (this._isRateLimited(requestType)) {\n IS_DEBUG_BUILD &&\n // eslint-disable-next-line deprecation/deprecation\n logger.warn(`Too many ${requestType} requests, backing off until: ${this._disabledUntil(requestType)}`);\n }\n\n if (status === 'success') {\n resolve({ status });\n return;\n }\n\n reject(response);\n }\n\n /**\n * Gets the time that given category is disabled until for rate limiting\n *\n * @deprecated Please use `disabledUntil` from @sentry/utils\n */\n protected _disabledUntil(requestType: SentryRequestType): Date {\n const category = requestTypeToCategory(requestType);\n return new Date(disabledUntil(this._rateLimits, category));\n }\n\n /**\n * Checks if a category is rate limited\n *\n * @deprecated Please use `isRateLimited` from @sentry/utils\n */\n protected _isRateLimited(requestType: SentryRequestType): boolean {\n const category = requestTypeToCategory(requestType);\n return isRateLimited(this._rateLimits, category);\n }\n\n protected abstract _sendRequest(\n sentryRequest: SentryRequest,\n originalPayload: Event | Session,\n ): PromiseLike<SentryResponse>;\n}\n","import { ClientReport, ClientReportEnvelope, ClientReportItem } from '@sentry/types';\n\nimport { createEnvelope } from './envelope';\nimport { dateTimestampInSeconds } from './time';\n\n/**\n * Creates client report envelope\n * @param discarded_events An array of discard events\n * @param dsn A DSN that can be set on the header. Optional.\n */\nexport function createClientReportEnvelope(\n discarded_events: ClientReport['discarded_events'],\n dsn?: string,\n timestamp?: number,\n): ClientReportEnvelope {\n const clientReportItem: ClientReportItem = [\n { type: 'client_report' },\n {\n timestamp: timestamp || dateTimestampInSeconds(),\n discarded_events,\n },\n ];\n return createEnvelope<ClientReportEnvelope>(dsn ? { dsn } : {}, [clientReportItem]);\n}\n","import { Event, Response, SentryRequest, Session, TransportOptions } from '@sentry/types';\nimport { SentryError, supportsReferrerPolicy, SyncPromise } from '@sentry/utils';\n\nimport { BaseTransport } from './base';\nimport { FetchImpl, getNativeFetchImplementation } from './utils';\n\n/** `fetch` based transport */\nexport class FetchTransport extends BaseTransport {\n /**\n * Fetch API reference which always points to native browser implementation.\n */\n private _fetch: typeof fetch;\n\n public constructor(options: TransportOptions, fetchImpl: FetchImpl = getNativeFetchImplementation()) {\n super(options);\n this._fetch = fetchImpl;\n }\n\n /**\n * @param sentryRequest Prepared SentryRequest to be delivered\n * @param originalPayload Original payload used to create SentryRequest\n */\n protected _sendRequest(sentryRequest: SentryRequest, originalPayload: Event | Session): PromiseLike<Response> {\n // eslint-disable-next-line deprecation/deprecation\n if (this._isRateLimited(sentryRequest.type)) {\n this.recordLostEvent('ratelimit_backoff', sentryRequest.type);\n\n return Promise.reject({\n event: originalPayload,\n type: sentryRequest.type,\n // eslint-disable-next-line deprecation/deprecation\n reason: `Transport for ${sentryRequest.type} requests locked till ${this._disabledUntil(\n sentryRequest.type,\n )} due to too many requests.`,\n status: 429,\n });\n }\n\n const options: RequestInit = {\n body: sentryRequest.body,\n method: 'POST',\n // Despite all stars in the sky saying that Edge supports old draft syntax, aka 'never', 'always', 'origin' and 'default'\n // (see https://caniuse.com/#feat=referrer-policy),\n // it doesn't. And it throws an exception instead of ignoring this parameter...\n // REF: https://github.com/getsentry/raven-js/issues/1233\n referrerPolicy: (supportsReferrerPolicy() ? 'origin' : '') as ReferrerPolicy,\n };\n if (this.options.fetchParameters !== undefined) {\n Object.assign(options, this.options.fetchParameters);\n }\n if (this.options.headers !== undefined) {\n options.headers = this.options.headers;\n }\n\n return this._buffer\n .add(\n () =>\n new SyncPromise<Response>((resolve, reject) => {\n void this._fetch(sentryRequest.url, options)\n .then(response => {\n const headers = {\n 'x-sentry-rate-limits': response.headers.get('X-Sentry-Rate-Limits'),\n 'retry-after': response.headers.get('Retry-After'),\n };\n this._handleResponse({\n requestType: sentryRequest.type,\n response,\n headers,\n resolve,\n reject,\n });\n })\n .catch(reject);\n }),\n )\n .then(undefined, reason => {\n // It's either buffer rejection or any other xhr/fetch error, which are treated as NetworkError.\n if (reason instanceof SentryError) {\n this.recordLostEvent('queue_overflow', sentryRequest.type);\n } else {\n this.recordLostEvent('network_error', sentryRequest.type);\n }\n throw reason;\n });\n }\n}\n","import { Event, Response, SentryRequest, Session } from '@sentry/types';\nimport { SentryError, SyncPromise } from '@sentry/utils';\n\nimport { BaseTransport } from './base';\n\n/** `XHR` based transport */\nexport class XHRTransport extends BaseTransport {\n /**\n * @param sentryRequest Prepared SentryRequest to be delivered\n * @param originalPayload Original payload used to create SentryRequest\n */\n protected _sendRequest(sentryRequest: SentryRequest, originalPayload: Event | Session): PromiseLike<Response> {\n // eslint-disable-next-line deprecation/deprecation\n if (this._isRateLimited(sentryRequest.type)) {\n this.recordLostEvent('ratelimit_backoff', sentryRequest.type);\n\n return Promise.reject({\n event: originalPayload,\n type: sentryRequest.type,\n // eslint-disable-next-line deprecation/deprecation\n reason: `Transport for ${sentryRequest.type} requests locked till ${this._disabledUntil(\n sentryRequest.type,\n )} due to too many requests.`,\n status: 429,\n });\n }\n\n return this._buffer\n .add(\n () =>\n new SyncPromise<Response>((resolve, reject) => {\n const request = new XMLHttpRequest();\n\n request.onreadystatechange = (): void => {\n if (request.readyState === 4) {\n const headers = {\n 'x-sentry-rate-limits': request.getResponseHeader('X-Sentry-Rate-Limits'),\n 'retry-after': request.getResponseHeader('Retry-After'),\n };\n this._handleResponse({ requestType: sentryRequest.type, response: request, headers, resolve, reject });\n }\n };\n\n request.open('POST', sentryRequest.url);\n for (const header in this.options.headers) {\n if (Object.prototype.hasOwnProperty.call(this.options.headers, header)) {\n request.setRequestHeader(header, this.options.headers[header]);\n }\n }\n request.send(sentryRequest.body);\n }),\n )\n .then(undefined, reason => {\n // It's either buffer rejection or any other xhr/fetch error, which are treated as NetworkError.\n if (reason instanceof SentryError) {\n this.recordLostEvent('queue_overflow', sentryRequest.type);\n } else {\n this.recordLostEvent('network_error', sentryRequest.type);\n }\n throw reason;\n });\n }\n}\n","import {\n BaseTransportOptions,\n createTransport,\n NewTransport,\n TransportMakeRequestResponse,\n TransportRequest,\n} from '@sentry/core';\n\nimport { FetchImpl, getNativeFetchImplementation } from './utils';\n\nexport interface FetchTransportOptions extends BaseTransportOptions {\n requestOptions?: RequestInit;\n}\n\n/**\n * Creates a Transport that uses the Fetch API to send events to Sentry.\n */\nexport function makeNewFetchTransport(\n options: FetchTransportOptions,\n nativeFetch: FetchImpl = getNativeFetchImplementation(),\n): NewTransport {\n function makeRequest(request: TransportRequest): PromiseLike<TransportMakeRequestResponse> {\n const requestOptions: RequestInit = {\n body: request.body,\n method: 'POST',\n referrerPolicy: 'origin',\n ...options.requestOptions,\n };\n\n return nativeFetch(options.url, requestOptions).then(response => {\n return response.text().then(body => ({\n body,\n headers: {\n 'x-sentry-rate-limits': response.headers.get('X-Sentry-Rate-Limits'),\n 'retry-after': response.headers.get('Retry-After'),\n },\n reason: response.statusText,\n statusCode: response.status,\n }));\n });\n }\n\n return createTransport({ bufferSize: options.bufferSize }, makeRequest);\n}\n","import {\n BaseTransportOptions,\n createTransport,\n NewTransport,\n TransportMakeRequestResponse,\n TransportRequest,\n} from '@sentry/core';\nimport { SyncPromise } from '@sentry/utils';\n\n/**\n * The DONE ready state for XmlHttpRequest\n *\n * Defining it here as a constant b/c XMLHttpRequest.DONE is not always defined\n * (e.g. during testing, it is `undefined`)\n *\n * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyState}\n */\nconst XHR_READYSTATE_DONE = 4;\n\nexport interface XHRTransportOptions extends BaseTransportOptions {\n headers?: { [key: string]: string };\n}\n\n/**\n * Creates a Transport that uses the XMLHttpRequest API to send events to Sentry.\n */\nexport function makeNewXHRTransport(options: XHRTransportOptions): NewTransport {\n function makeRequest(request: TransportRequest): PromiseLike<TransportMakeRequestResponse> {\n return new SyncPromise<TransportMakeRequestResponse>((resolve, _reject) => {\n const xhr = new XMLHttpRequest();\n\n xhr.onreadystatechange = (): void => {\n if (xhr.readyState === XHR_READYSTATE_DONE) {\n const response = {\n body: xhr.response,\n headers: {\n 'x-sentry-rate-limits': xhr.getResponseHeader('X-Sentry-Rate-Limits'),\n 'retry-after': xhr.getResponseHeader('Retry-After'),\n },\n reason: xhr.statusText,\n statusCode: xhr.status,\n };\n resolve(response);\n }\n };\n\n xhr.open('POST', options.url);\n\n for (const header in options.headers) {\n if (Object.prototype.hasOwnProperty.call(options.headers, header)) {\n xhr.setRequestHeader(header, options.headers[header]);\n }\n }\n\n xhr.send(request.body);\n });\n }\n\n return createTransport({ bufferSize: options.bufferSize }, makeRequest);\n}\n","import { BaseBackend, getEnvelopeEndpointWithUrlEncodedAuth, initAPIDetails } from '@sentry/core';\nimport { Event, EventHint, Options, Severity, Transport, TransportOptions } from '@sentry/types';\nimport { supportsFetch } from '@sentry/utils';\n\nimport { eventFromException, eventFromMessage } from './eventbuilder';\nimport { FetchTransport, makeNewFetchTransport, makeNewXHRTransport, XHRTransport } from './transports';\n\n/**\n * Configuration options for the Sentry Browser SDK.\n * @see BrowserClient for more information.\n */\nexport interface BrowserOptions extends Options {\n /**\n * A pattern for error URLs which should exclusively be sent to Sentry.\n * This is the opposite of {@link Options.denyUrls}.\n * By default, all errors will be sent.\n */\n allowUrls?: Array<string | RegExp>;\n\n /**\n * A pattern for error URLs which should not be sent to Sentry.\n * To allow certain errors instead, use {@link Options.allowUrls}.\n * By default, all errors will be sent.\n */\n denyUrls?: Array<string | RegExp>;\n\n /** @deprecated use {@link Options.allowUrls} instead. */\n whitelistUrls?: Array<string | RegExp>;\n\n /** @deprecated use {@link Options.denyUrls} instead. */\n blacklistUrls?: Array<string | RegExp>;\n}\n\n/**\n * The Sentry Browser SDK Backend.\n * @hidden\n */\nexport class BrowserBackend extends BaseBackend<BrowserOptions> {\n /**\n * @inheritDoc\n */\n public eventFromException(exception: unknown, hint?: EventHint): PromiseLike<Event> {\n return eventFromException(exception, hint, this._options.attachStacktrace);\n }\n /**\n * @inheritDoc\n */\n public eventFromMessage(message: string, level: Severity = Severity.Info, hint?: EventHint): PromiseLike<Event> {\n return eventFromMessage(message, level, hint, this._options.attachStacktrace);\n }\n\n /**\n * @inheritDoc\n */\n protected _setupTransport(): Transport {\n if (!this._options.dsn) {\n // We return the noop transport here in case there is no Dsn.\n return super._setupTransport();\n }\n\n const transportOptions: TransportOptions = {\n ...this._options.transportOptions,\n dsn: this._options.dsn,\n tunnel: this._options.tunnel,\n sendClientReports: this._options.sendClientReports,\n _metadata: this._options._metadata,\n };\n\n const api = initAPIDetails(transportOptions.dsn, transportOptions._metadata, transportOptions.tunnel);\n const url = getEnvelopeEndpointWithUrlEncodedAuth(api.dsn, api.tunnel);\n\n if (this._options.transport) {\n return new this._options.transport(transportOptions);\n }\n if (supportsFetch()) {\n const requestOptions: RequestInit = { ...transportOptions.fetchParameters };\n this._newTransport = makeNewFetchTransport({ requestOptions, url });\n return new FetchTransport(transportOptions);\n }\n\n this._newTransport = makeNewXHRTransport({\n url,\n headers: transportOptions.headers,\n });\n return new XHRTransport(transportOptions);\n }\n}\n","import { captureException, getReportDialogEndpoint, withScope } from '@sentry/core';\nimport { DsnLike, Event as SentryEvent, Mechanism, Scope, WrappedFunction } from '@sentry/types';\nimport {\n addExceptionMechanism,\n addExceptionTypeValue,\n addNonEnumerableProperty,\n getGlobalObject,\n getOriginalFunction,\n logger,\n markFunctionWrapped,\n} from '@sentry/utils';\n\nimport { IS_DEBUG_BUILD } from './flags';\n\nconst global = getGlobalObject<Window>();\nlet ignoreOnError: number = 0;\n\n/**\n * @hidden\n */\nexport function shouldIgnoreOnError(): boolean {\n return ignoreOnError > 0;\n}\n\n/**\n * @hidden\n */\nexport function ignoreNextOnError(): void {\n // onerror should trigger before setTimeout\n ignoreOnError += 1;\n setTimeout(() => {\n ignoreOnError -= 1;\n });\n}\n\n/**\n * Instruments the given function and sends an event to Sentry every time the\n * function throws an exception.\n *\n * @param fn A function to wrap.\n * @returns The wrapped function.\n * @hidden\n */\nexport function wrap(\n fn: WrappedFunction,\n options: {\n mechanism?: Mechanism;\n } = {},\n before?: WrappedFunction,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n): any {\n // for future readers what this does is wrap a function and then create\n // a bi-directional wrapping between them.\n //\n // example: wrapped = wrap(original);\n // original.__sentry_wrapped__ -> wrapped\n // wrapped.__sentry_original__ -> original\n\n if (typeof fn !== 'function') {\n return fn;\n }\n\n try {\n // if we're dealing with a function that was previously wrapped, return\n // the original wrapper.\n const wrapper = fn.__sentry_wrapped__;\n if (wrapper) {\n return wrapper;\n }\n\n // We don't wanna wrap it twice\n if (getOriginalFunction(fn)) {\n return fn;\n }\n } catch (e) {\n // Just accessing custom props in some Selenium environments\n // can cause a \"Permission denied\" exception (see raven-js#495).\n // Bail on wrapping and return the function as-is (defers to window.onerror).\n return fn;\n }\n\n /* eslint-disable prefer-rest-params */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const sentryWrapped: WrappedFunction = function (this: any): void {\n const args = Array.prototype.slice.call(arguments);\n\n try {\n if (before && typeof before === 'function') {\n before.apply(this, arguments);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access\n const wrappedArguments = args.map((arg: any) => wrap(arg, options));\n\n // Attempt to invoke user-land function\n // NOTE: If you are a Sentry user, and you are seeing this stack frame, it\n // means the sentry.javascript SDK caught an error invoking your application code. This\n // is expected behavior and NOT indicative of a bug with sentry.javascript.\n return fn.apply(this, wrappedArguments);\n } catch (ex) {\n ignoreNextOnError();\n\n withScope((scope: Scope) => {\n scope.addEventProcessor((event: SentryEvent) => {\n if (options.mechanism) {\n addExceptionTypeValue(event, undefined, undefined);\n addExceptionMechanism(event, options.mechanism);\n }\n\n event.extra = {\n ...event.extra,\n arguments: args,\n };\n\n return event;\n });\n\n captureException(ex);\n });\n\n throw ex;\n }\n };\n /* eslint-enable prefer-rest-params */\n\n // Accessing some objects may throw\n // ref: https://github.com/getsentry/sentry-javascript/issues/1168\n try {\n for (const property in fn) {\n if (Object.prototype.hasOwnProperty.call(fn, property)) {\n sentryWrapped[property] = fn[property];\n }\n }\n } catch (_oO) {} // eslint-disable-line no-empty\n\n // Signal that this function has been wrapped/filled already\n // for both debugging and to prevent it to being wrapped/filled twice\n markFunctionWrapped(sentryWrapped, fn);\n\n addNonEnumerableProperty(fn, '__sentry_wrapped__', sentryWrapped);\n\n // Restore original function name (not all browsers allow that)\n try {\n const descriptor = Object.getOwnPropertyDescriptor(sentryWrapped, 'name') as PropertyDescriptor;\n if (descriptor.configurable) {\n Object.defineProperty(sentryWrapped, 'name', {\n get(): string {\n return fn.name;\n },\n });\n }\n // eslint-disable-next-line no-empty\n } catch (_oO) {}\n\n return sentryWrapped;\n}\n\n/**\n * All properties the report dialog supports\n */\nexport interface ReportDialogOptions {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key: string]: any;\n eventId?: string;\n dsn?: DsnLike;\n user?: {\n email?: string;\n name?: string;\n };\n lang?: string;\n title?: string;\n subtitle?: string;\n subtitle2?: string;\n labelName?: string;\n labelEmail?: string;\n labelComments?: string;\n labelClose?: string;\n labelSubmit?: string;\n errorGeneric?: string;\n errorFormEntry?: string;\n successMessage?: string;\n /** Callback after reportDialog showed up */\n onLoad?(): void;\n}\n\n/**\n * Injects the Report Dialog script\n * @hidden\n */\nexport function injectReportDialog(options: ReportDialogOptions = {}): void {\n if (!global.document) {\n return;\n }\n\n if (!options.eventId) {\n IS_DEBUG_BUILD && logger.error('Missing eventId option in showReportDialog call');\n return;\n }\n\n if (!options.dsn) {\n IS_DEBUG_BUILD && logger.error('Missing dsn option in showReportDialog call');\n return;\n }\n\n const script = global.document.createElement('script');\n script.async = true;\n script.src = getReportDialogEndpoint(options.dsn, options);\n\n if (options.onLoad) {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n script.onload = options.onLoad;\n }\n\n const injectionPoint = global.document.head || global.document.body;\n\n if (injectionPoint) {\n injectionPoint.appendChild(script);\n }\n}\n","/* eslint-disable @typescript-eslint/no-unsafe-member-access */\nimport { getCurrentHub } from '@sentry/core';\nimport { Event, EventHint, Hub, Integration, Primitive, Severity } from '@sentry/types';\nimport {\n addExceptionMechanism,\n addInstrumentationHandler,\n getLocationHref,\n isErrorEvent,\n isPrimitive,\n isString,\n logger,\n} from '@sentry/utils';\n\nimport { eventFromUnknownInput } from '../eventbuilder';\nimport { IS_DEBUG_BUILD } from '../flags';\nimport { shouldIgnoreOnError } from '../helpers';\n\ntype GlobalHandlersIntegrationsOptionKeys = 'onerror' | 'onunhandledrejection';\n\n/** JSDoc */\ntype GlobalHandlersIntegrations = Record<GlobalHandlersIntegrationsOptionKeys, boolean>;\n\n/** Global handlers */\nexport class GlobalHandlers implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'GlobalHandlers';\n\n /**\n * @inheritDoc\n */\n public name: string = GlobalHandlers.id;\n\n /** JSDoc */\n private readonly _options: GlobalHandlersIntegrations;\n\n /**\n * Stores references functions to installing handlers. Will set to undefined\n * after they have been run so that they are not used twice.\n */\n private _installFunc: Record<GlobalHandlersIntegrationsOptionKeys, (() => void) | undefined> = {\n onerror: _installGlobalOnErrorHandler,\n onunhandledrejection: _installGlobalOnUnhandledRejectionHandler,\n };\n\n /** JSDoc */\n public constructor(options?: GlobalHandlersIntegrations) {\n this._options = {\n onerror: true,\n onunhandledrejection: true,\n ...options,\n };\n }\n /**\n * @inheritDoc\n */\n public setupOnce(): void {\n Error.stackTraceLimit = 50;\n const options = this._options;\n\n // We can disable guard-for-in as we construct the options object above + do checks against\n // `this._installFunc` for the property.\n // eslint-disable-next-line guard-for-in\n for (const key in options) {\n const installFunc = this._installFunc[key as GlobalHandlersIntegrationsOptionKeys];\n if (installFunc && options[key as GlobalHandlersIntegrationsOptionKeys]) {\n globalHandlerLog(key);\n installFunc();\n this._installFunc[key as GlobalHandlersIntegrationsOptionKeys] = undefined;\n }\n }\n }\n}\n\n/** JSDoc */\nfunction _installGlobalOnErrorHandler(): void {\n addInstrumentationHandler(\n 'error',\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (data: { msg: any; url: any; line: any; column: any; error: any }) => {\n const [hub, attachStacktrace] = getHubAndAttachStacktrace();\n if (!hub.getIntegration(GlobalHandlers)) {\n return;\n }\n const { msg, url, line, column, error } = data;\n if (shouldIgnoreOnError() || (error && error.__sentry_own_request__)) {\n return;\n }\n\n const event =\n error === undefined && isString(msg)\n ? _eventFromIncompleteOnError(msg, url, line, column)\n : _enhanceEventWithInitialFrame(\n eventFromUnknownInput(error || msg, undefined, attachStacktrace, false),\n url,\n line,\n column,\n );\n\n event.level = Severity.Error;\n\n addMechanismAndCapture(hub, error, event, 'onerror');\n },\n );\n}\n\n/** JSDoc */\nfunction _installGlobalOnUnhandledRejectionHandler(): void {\n addInstrumentationHandler(\n 'unhandledrejection',\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (e: any) => {\n const [hub, attachStacktrace] = getHubAndAttachStacktrace();\n if (!hub.getIntegration(GlobalHandlers)) {\n return;\n }\n let error = e;\n\n // dig the object of the rejection out of known event types\n try {\n // PromiseRejectionEvents store the object of the rejection under 'reason'\n // see https://developer.mozilla.org/en-US/docs/Web/API/PromiseRejectionEvent\n if ('reason' in e) {\n error = e.reason;\n }\n // something, somewhere, (likely a browser extension) effectively casts PromiseRejectionEvents\n // to CustomEvents, moving the `promise` and `reason` attributes of the PRE into\n // the CustomEvent's `detail` attribute, since they're not part of CustomEvent's spec\n // see https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent and\n // https://github.com/getsentry/sentry-javascript/issues/2380\n else if ('detail' in e && 'reason' in e.detail) {\n error = e.detail.reason;\n }\n } catch (_oO) {\n // no-empty\n }\n\n if (shouldIgnoreOnError() || (error && error.__sentry_own_request__)) {\n return true;\n }\n\n const event = isPrimitive(error)\n ? _eventFromRejectionWithPrimitive(error)\n : eventFromUnknownInput(error, undefined, attachStacktrace, true);\n\n event.level = Severity.Error;\n\n addMechanismAndCapture(hub, error, event, 'onunhandledrejection');\n return;\n },\n );\n}\n\n/**\n * Create an event from a promise rejection where the `reason` is a primitive.\n *\n * @param reason: The `reason` property of the promise rejection\n * @returns An Event object with an appropriate `exception` value\n */\nfunction _eventFromRejectionWithPrimitive(reason: Primitive): Event {\n return {\n exception: {\n values: [\n {\n type: 'UnhandledRejection',\n // String() is needed because the Primitive type includes symbols (which can't be automatically stringified)\n value: `Non-Error promise rejection captured with value: ${String(reason)}`,\n },\n ],\n },\n };\n}\n\n/**\n * This function creates a stack from an old, error-less onerror handler.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _eventFromIncompleteOnError(msg: any, url: any, line: any, column: any): Event {\n const ERROR_TYPES_RE =\n /^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;\n\n // If 'message' is ErrorEvent, get real message from inside\n let message = isErrorEvent(msg) ? msg.message : msg;\n let name = 'Error';\n\n const groups = message.match(ERROR_TYPES_RE);\n if (groups) {\n name = groups[1];\n message = groups[2];\n }\n\n const event = {\n exception: {\n values: [\n {\n type: name,\n value: message,\n },\n ],\n },\n };\n\n return _enhanceEventWithInitialFrame(event, url, line, column);\n}\n\n/** JSDoc */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _enhanceEventWithInitialFrame(event: Event, url: any, line: any, column: any): Event {\n // event.exception\n const e = (event.exception = event.exception || {});\n // event.exception.values\n const ev = (e.values = e.values || []);\n // event.exception.values[0]\n const ev0 = (ev[0] = ev[0] || {});\n // event.exception.values[0].stacktrace\n const ev0s = (ev0.stacktrace = ev0.stacktrace || {});\n // event.exception.values[0].stacktrace.frames\n const ev0sf = (ev0s.frames = ev0s.frames || []);\n\n const colno = isNaN(parseInt(column, 10)) ? undefined : column;\n const lineno = isNaN(parseInt(line, 10)) ? undefined : line;\n const filename = isString(url) && url.length > 0 ? url : getLocationHref();\n\n // event.exception.values[0].stacktrace.frames\n if (ev0sf.length === 0) {\n ev0sf.push({\n colno,\n filename,\n function: '?',\n in_app: true,\n lineno,\n });\n }\n\n return event;\n}\n\nfunction globalHandlerLog(type: string): void {\n IS_DEBUG_BUILD && logger.log(`Global Handler attached: ${type}`);\n}\n\nfunction addMechanismAndCapture(hub: Hub, error: EventHint['originalException'], event: Event, type: string): void {\n addExceptionMechanism(event, {\n handled: false,\n type,\n });\n hub.captureEvent(event, {\n originalException: error,\n });\n}\n\nfunction getHubAndAttachStacktrace(): [Hub, boolean | undefined] {\n const hub = getCurrentHub();\n const client = hub.getClient();\n const attachStacktrace = client && client.getOptions().attachStacktrace;\n return [hub, attachStacktrace];\n}\n","import { Integration, WrappedFunction } from '@sentry/types';\nimport { fill, getFunctionName, getGlobalObject, getOriginalFunction } from '@sentry/utils';\n\nimport { wrap } from '../helpers';\n\nconst DEFAULT_EVENT_TARGET = [\n 'EventTarget',\n 'Window',\n 'Node',\n 'ApplicationCache',\n 'AudioTrackList',\n 'ChannelMergerNode',\n 'CryptoOperation',\n 'EventSource',\n 'FileReader',\n 'HTMLUnknownElement',\n 'IDBDatabase',\n 'IDBRequest',\n 'IDBTransaction',\n 'KeyOperation',\n 'MediaController',\n 'MessagePort',\n 'ModalWindow',\n 'Notification',\n 'SVGElementInstance',\n 'Screen',\n 'TextTrack',\n 'TextTrackCue',\n 'TextTrackList',\n 'WebSocket',\n 'WebSocketWorker',\n 'Worker',\n 'XMLHttpRequest',\n 'XMLHttpRequestEventTarget',\n 'XMLHttpRequestUpload',\n];\n\ntype XMLHttpRequestProp = 'onload' | 'onerror' | 'onprogress' | 'onreadystatechange';\n\n/** JSDoc */\ninterface TryCatchOptions {\n setTimeout: boolean;\n setInterval: boolean;\n requestAnimationFrame: boolean;\n XMLHttpRequest: boolean;\n eventTarget: boolean | string[];\n}\n\n/** Wrap timer functions and event targets to catch errors and provide better meta data */\nexport class TryCatch implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'TryCatch';\n\n /**\n * @inheritDoc\n */\n public name: string = TryCatch.id;\n\n /** JSDoc */\n private readonly _options: TryCatchOptions;\n\n /**\n * @inheritDoc\n */\n public constructor(options?: Partial<TryCatchOptions>) {\n this._options = {\n XMLHttpRequest: true,\n eventTarget: true,\n requestAnimationFrame: true,\n setInterval: true,\n setTimeout: true,\n ...options,\n };\n }\n\n /**\n * Wrap timer functions and event targets to catch errors\n * and provide better metadata.\n */\n public setupOnce(): void {\n const global = getGlobalObject();\n\n if (this._options.setTimeout) {\n fill(global, 'setTimeout', _wrapTimeFunction);\n }\n\n if (this._options.setInterval) {\n fill(global, 'setInterval', _wrapTimeFunction);\n }\n\n if (this._options.requestAnimationFrame) {\n fill(global, 'requestAnimationFrame', _wrapRAF);\n }\n\n if (this._options.XMLHttpRequest && 'XMLHttpRequest' in global) {\n fill(XMLHttpRequest.prototype, 'send', _wrapXHR);\n }\n\n const eventTargetOption = this._options.eventTarget;\n if (eventTargetOption) {\n const eventTarget = Array.isArray(eventTargetOption) ? eventTargetOption : DEFAULT_EVENT_TARGET;\n eventTarget.forEach(_wrapEventTarget);\n }\n }\n}\n\n/** JSDoc */\nfunction _wrapTimeFunction(original: () => void): () => number {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return function (this: any, ...args: any[]): number {\n const originalCallback = args[0];\n args[0] = wrap(originalCallback, {\n mechanism: {\n data: { function: getFunctionName(original) },\n handled: true,\n type: 'instrument',\n },\n });\n return original.apply(this, args);\n };\n}\n\n/** JSDoc */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _wrapRAF(original: any): (callback: () => void) => any {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return function (this: any, callback: () => void): () => void {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return original.apply(this, [\n wrap(callback, {\n mechanism: {\n data: {\n function: 'requestAnimationFrame',\n handler: getFunctionName(original),\n },\n handled: true,\n type: 'instrument',\n },\n }),\n ]);\n };\n}\n\n/** JSDoc */\nfunction _wrapXHR(originalSend: () => void): () => void {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return function (this: XMLHttpRequest, ...args: any[]): void {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const xhr = this;\n const xmlHttpRequestProps: XMLHttpRequestProp[] = ['onload', 'onerror', 'onprogress', 'onreadystatechange'];\n\n xmlHttpRequestProps.forEach(prop => {\n if (prop in xhr && typeof xhr[prop] === 'function') {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n fill(xhr, prop, function (original: WrappedFunction): () => any {\n const wrapOptions = {\n mechanism: {\n data: {\n function: prop,\n handler: getFunctionName(original),\n },\n handled: true,\n type: 'instrument',\n },\n };\n\n // If Instrument integration has been called before TryCatch, get the name of original function\n const originalFunction = getOriginalFunction(original);\n if (originalFunction) {\n wrapOptions.mechanism.data.handler = getFunctionName(originalFunction);\n }\n\n // Otherwise wrap directly\n return wrap(original, wrapOptions);\n });\n }\n });\n\n return originalSend.apply(this, args);\n };\n}\n\n/** JSDoc */\nfunction _wrapEventTarget(target: string): void {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const global = getGlobalObject() as { [key: string]: any };\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n const proto = global[target] && global[target].prototype;\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, no-prototype-builtins\n if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty('addEventListener')) {\n return;\n }\n\n fill(proto, 'addEventListener', function (original: () => void): (\n eventName: string,\n fn: EventListenerObject,\n options?: boolean | AddEventListenerOptions,\n ) => void {\n return function (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this: any,\n eventName: string,\n fn: EventListenerObject,\n options?: boolean | AddEventListenerOptions,\n ): (eventName: string, fn: EventListenerObject, capture?: boolean, secure?: boolean) => void {\n try {\n if (typeof fn.handleEvent === 'function') {\n fn.handleEvent = wrap(fn.handleEvent.bind(fn), {\n mechanism: {\n data: {\n function: 'handleEvent',\n handler: getFunctionName(fn),\n target,\n },\n handled: true,\n type: 'instrument',\n },\n });\n }\n } catch (err) {\n // can sometimes get 'Permission denied to access property \"handle Event'\n }\n\n return original.apply(this, [\n eventName,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n wrap(fn as any as WrappedFunction, {\n mechanism: {\n data: {\n function: 'addEventListener',\n handler: getFunctionName(fn),\n target,\n },\n handled: true,\n type: 'instrument',\n },\n }),\n options,\n ]);\n };\n });\n\n fill(\n proto,\n 'removeEventListener',\n function (\n originalRemoveEventListener: () => void,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ): (this: any, eventName: string, fn: EventListenerObject, options?: boolean | EventListenerOptions) => () => void {\n return function (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this: any,\n eventName: string,\n fn: EventListenerObject,\n options?: boolean | EventListenerOptions,\n ): () => void {\n /**\n * There are 2 possible scenarios here:\n *\n * 1. Someone passes a callback, which was attached prior to Sentry initialization, or by using unmodified\n * method, eg. `document.addEventListener.call(el, name, handler). In this case, we treat this function\n * as a pass-through, and call original `removeEventListener` with it.\n *\n * 2. Someone passes a callback, which was attached after Sentry was initialized, which means that it was using\n * our wrapped version of `addEventListener`, which internally calls `wrap` helper.\n * This helper \"wraps\" whole callback inside a try/catch statement, and attached appropriate metadata to it,\n * in order for us to make a distinction between wrapped/non-wrapped functions possible.\n * If a function was wrapped, it has additional property of `__sentry_wrapped__`, holding the handler.\n *\n * When someone adds a handler prior to initialization, and then do it again, but after,\n * then we have to detach both of them. Otherwise, if we'd detach only wrapped one, it'd be impossible\n * to get rid of the initial handler and it'd stick there forever.\n */\n const wrappedEventHandler = fn as unknown as WrappedFunction;\n try {\n const originalEventHandler = wrappedEventHandler && wrappedEventHandler.__sentry_wrapped__;\n if (originalEventHandler) {\n originalRemoveEventListener.call(this, eventName, originalEventHandler, options);\n }\n } catch (e) {\n // ignore, accessing __sentry_wrapped__ will throw in some Selenium environments\n }\n return originalRemoveEventListener.call(this, eventName, wrappedEventHandler, options);\n };\n },\n );\n}\n","/* eslint-disable @typescript-eslint/no-unsafe-member-access */\n/* eslint-disable max-lines */\nimport { getCurrentHub } from '@sentry/core';\nimport { Event, Integration, Severity } from '@sentry/types';\nimport {\n addInstrumentationHandler,\n getEventDescription,\n getGlobalObject,\n htmlTreeAsString,\n parseUrl,\n safeJoin,\n severityFromString,\n} from '@sentry/utils';\n\n/** JSDoc */\ninterface BreadcrumbsOptions {\n console: boolean;\n dom: boolean | { serializeAttribute: string | string[] };\n fetch: boolean;\n history: boolean;\n sentry: boolean;\n xhr: boolean;\n}\n\n/**\n * Default Breadcrumbs instrumentations\n * TODO: Deprecated - with v6, this will be renamed to `Instrument`\n */\nexport class Breadcrumbs implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'Breadcrumbs';\n\n /**\n * @inheritDoc\n */\n public name: string = Breadcrumbs.id;\n\n /** JSDoc */\n private readonly _options: BreadcrumbsOptions;\n\n /**\n * @inheritDoc\n */\n public constructor(options?: Partial<BreadcrumbsOptions>) {\n this._options = {\n console: true,\n dom: true,\n fetch: true,\n history: true,\n sentry: true,\n xhr: true,\n ...options,\n };\n }\n\n /**\n * Create a breadcrumb of `sentry` from the events themselves\n */\n public addSentryBreadcrumb(event: Event): void {\n if (!this._options.sentry) {\n return;\n }\n getCurrentHub().addBreadcrumb(\n {\n category: `sentry.${event.type === 'transaction' ? 'transaction' : 'event'}`,\n event_id: event.event_id,\n level: event.level,\n message: getEventDescription(event),\n },\n {\n event,\n },\n );\n }\n\n /**\n * Instrument browser built-ins w/ breadcrumb capturing\n * - Console API\n * - DOM API (click/typing)\n * - XMLHttpRequest API\n * - Fetch API\n * - History API\n */\n public setupOnce(): void {\n if (this._options.console) {\n addInstrumentationHandler('console', _consoleBreadcrumb);\n }\n if (this._options.dom) {\n addInstrumentationHandler('dom', _domBreadcrumb(this._options.dom));\n }\n if (this._options.xhr) {\n addInstrumentationHandler('xhr', _xhrBreadcrumb);\n }\n if (this._options.fetch) {\n addInstrumentationHandler('fetch', _fetchBreadcrumb);\n }\n if (this._options.history) {\n addInstrumentationHandler('history', _historyBreadcrumb);\n }\n }\n}\n\n/**\n * A HOC that creaes a function that creates breadcrumbs from DOM API calls.\n * This is a HOC so that we get access to dom options in the closure.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _domBreadcrumb(dom: BreadcrumbsOptions['dom']): (handlerData: { [key: string]: any }) => void {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n function _innerDomBreadcrumb(handlerData: { [key: string]: any }): void {\n let target;\n let keyAttrs = typeof dom === 'object' ? dom.serializeAttribute : undefined;\n\n if (typeof keyAttrs === 'string') {\n keyAttrs = [keyAttrs];\n }\n\n // Accessing event.target can throw (see getsentry/raven-js#838, #768)\n try {\n target = handlerData.event.target\n ? htmlTreeAsString(handlerData.event.target as Node, keyAttrs)\n : htmlTreeAsString(handlerData.event as unknown as Node, keyAttrs);\n } catch (e) {\n target = '<unknown>';\n }\n\n if (target.length === 0) {\n return;\n }\n\n getCurrentHub().addBreadcrumb(\n {\n category: `ui.${handlerData.name}`,\n message: target,\n },\n {\n event: handlerData.event,\n name: handlerData.name,\n global: handlerData.global,\n },\n );\n }\n\n return _innerDomBreadcrumb;\n}\n\n/**\n * Creates breadcrumbs from console API calls\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _consoleBreadcrumb(handlerData: { [key: string]: any }): void {\n const breadcrumb = {\n category: 'console',\n data: {\n arguments: handlerData.args,\n logger: 'console',\n },\n level: severityFromString(handlerData.level),\n message: safeJoin(handlerData.args, ' '),\n };\n\n if (handlerData.level === 'assert') {\n if (handlerData.args[0] === false) {\n breadcrumb.message = `Assertion failed: ${safeJoin(handlerData.args.slice(1), ' ') || 'console.assert'}`;\n breadcrumb.data.arguments = handlerData.args.slice(1);\n } else {\n // Don't capture a breadcrumb for passed assertions\n return;\n }\n }\n\n getCurrentHub().addBreadcrumb(breadcrumb, {\n input: handlerData.args,\n level: handlerData.level,\n });\n}\n\n/**\n * Creates breadcrumbs from XHR API calls\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _xhrBreadcrumb(handlerData: { [key: string]: any }): void {\n if (handlerData.endTimestamp) {\n // We only capture complete, non-sentry requests\n if (handlerData.xhr.__sentry_own_request__) {\n return;\n }\n\n const { method, url, status_code, body } = handlerData.xhr.__sentry_xhr__ || {};\n\n getCurrentHub().addBreadcrumb(\n {\n category: 'xhr',\n data: {\n method,\n url,\n status_code,\n },\n type: 'http',\n },\n {\n xhr: handlerData.xhr,\n input: body,\n },\n );\n\n return;\n }\n}\n\n/**\n * Creates breadcrumbs from fetch API calls\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _fetchBreadcrumb(handlerData: { [key: string]: any }): void {\n // We only capture complete fetch requests\n if (!handlerData.endTimestamp) {\n return;\n }\n\n if (handlerData.fetchData.url.match(/sentry_key/) && handlerData.fetchData.method === 'POST') {\n // We will not create breadcrumbs for fetch requests that contain `sentry_key` (internal sentry requests)\n return;\n }\n\n if (handlerData.error) {\n getCurrentHub().addBreadcrumb(\n {\n category: 'fetch',\n data: handlerData.fetchData,\n level: Severity.Error,\n type: 'http',\n },\n {\n data: handlerData.error,\n input: handlerData.args,\n },\n );\n } else {\n getCurrentHub().addBreadcrumb(\n {\n category: 'fetch',\n data: {\n ...handlerData.fetchData,\n status_code: handlerData.response.status,\n },\n type: 'http',\n },\n {\n input: handlerData.args,\n response: handlerData.response,\n },\n );\n }\n}\n\n/**\n * Creates breadcrumbs from history API calls\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _historyBreadcrumb(handlerData: { [key: string]: any }): void {\n const global = getGlobalObject<Window>();\n let from = handlerData.from;\n let to = handlerData.to;\n const parsedLoc = parseUrl(global.location.href);\n let parsedFrom = parseUrl(from);\n const parsedTo = parseUrl(to);\n\n // Initial pushState doesn't provide `from` information\n if (!parsedFrom.path) {\n parsedFrom = parsedLoc;\n }\n\n // Use only the path component of the URL if the URL matches the current\n // document (almost all the time when using pushState)\n if (parsedLoc.protocol === parsedTo.protocol && parsedLoc.host === parsedTo.host) {\n to = parsedTo.relative;\n }\n if (parsedLoc.protocol === parsedFrom.protocol && parsedLoc.host === parsedFrom.host) {\n from = parsedFrom.relative;\n }\n\n getCurrentHub().addBreadcrumb({\n category: 'navigation',\n data: {\n from,\n to,\n },\n });\n}\n","import { addGlobalEventProcessor, getCurrentHub } from '@sentry/core';\nimport { Event, EventHint, Exception, ExtendedError, Integration } from '@sentry/types';\nimport { isInstanceOf } from '@sentry/utils';\n\nimport { exceptionFromError } from '../eventbuilder';\n\nconst DEFAULT_KEY = 'cause';\nconst DEFAULT_LIMIT = 5;\n\ninterface LinkedErrorsOptions {\n key: string;\n limit: number;\n}\n\n/** Adds SDK info to an event. */\nexport class LinkedErrors implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'LinkedErrors';\n\n /**\n * @inheritDoc\n */\n public readonly name: string = LinkedErrors.id;\n\n /**\n * @inheritDoc\n */\n private readonly _key: LinkedErrorsOptions['key'];\n\n /**\n * @inheritDoc\n */\n private readonly _limit: LinkedErrorsOptions['limit'];\n\n /**\n * @inheritDoc\n */\n public constructor(options: Partial<LinkedErrorsOptions> = {}) {\n this._key = options.key || DEFAULT_KEY;\n this._limit = options.limit || DEFAULT_LIMIT;\n }\n\n /**\n * @inheritDoc\n */\n public setupOnce(): void {\n addGlobalEventProcessor((event: Event, hint?: EventHint) => {\n const self = getCurrentHub().getIntegration(LinkedErrors);\n return self ? _handler(self._key, self._limit, event, hint) : event;\n });\n }\n}\n\n/**\n * @inheritDoc\n */\nexport function _handler(key: string, limit: number, event: Event, hint?: EventHint): Event | null {\n if (!event.exception || !event.exception.values || !hint || !isInstanceOf(hint.originalException, Error)) {\n return event;\n }\n const linkedErrors = _walkErrorTree(limit, hint.originalException as ExtendedError, key);\n event.exception.values = [...linkedErrors, ...event.exception.values];\n return event;\n}\n\n/**\n * JSDOC\n */\nexport function _walkErrorTree(limit: number, error: ExtendedError, key: string, stack: Exception[] = []): Exception[] {\n if (!isInstanceOf(error[key], Error) || stack.length + 1 >= limit) {\n return stack;\n }\n const exception = exceptionFromError(error[key]);\n return _walkErrorTree(limit, error[key], key, [exception, ...stack]);\n}\n","import { addGlobalEventProcessor, getCurrentHub } from '@sentry/core';\nimport { Event, Integration } from '@sentry/types';\nimport { getGlobalObject } from '@sentry/utils';\n\nconst global = getGlobalObject<Window>();\n\n/** UserAgent */\nexport class UserAgent implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'UserAgent';\n\n /**\n * @inheritDoc\n */\n public name: string = UserAgent.id;\n\n /**\n * @inheritDoc\n */\n public setupOnce(): void {\n addGlobalEventProcessor((event: Event) => {\n if (getCurrentHub().getIntegration(UserAgent)) {\n // if none of the information we want exists, don't bother\n if (!global.navigator && !global.location && !global.document) {\n return event;\n }\n\n // grab as much info as exists and add it to the event\n const url = (event.request && event.request.url) || (global.location && global.location.href);\n const { referrer } = global.document || {};\n const { userAgent } = global.navigator || {};\n\n const headers = {\n ...(event.request && event.request.headers),\n ...(referrer && { Referer: referrer }),\n ...(userAgent && { 'User-Agent': userAgent }),\n };\n const request = { ...(url && { url }), headers };\n\n return { ...event, request };\n }\n return event;\n });\n }\n}\n","import { Event, EventProcessor, Exception, Hub, Integration, StackFrame } from '@sentry/types';\nimport { logger } from '@sentry/utils';\n\nimport { IS_DEBUG_BUILD } from '../flags';\n\n/** Deduplication filter */\nexport class Dedupe implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'Dedupe';\n\n /**\n * @inheritDoc\n */\n public name: string = Dedupe.id;\n\n /**\n * @inheritDoc\n */\n private _previousEvent?: Event;\n\n /**\n * @inheritDoc\n */\n public setupOnce(addGlobalEventProcessor: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {\n addGlobalEventProcessor((currentEvent: Event) => {\n const self = getCurrentHub().getIntegration(Dedupe);\n if (self) {\n // Juuust in case something goes wrong\n try {\n if (_shouldDropEvent(currentEvent, self._previousEvent)) {\n IS_DEBUG_BUILD && logger.warn('Event dropped due to being a duplicate of previously captured event.');\n return null;\n }\n } catch (_oO) {\n return (self._previousEvent = currentEvent);\n }\n\n return (self._previousEvent = currentEvent);\n }\n return currentEvent;\n });\n }\n}\n\n/** JSDoc */\nfunction _shouldDropEvent(currentEvent: Event, previousEvent?: Event): boolean {\n if (!previousEvent) {\n return false;\n }\n\n if (_isSameMessageEvent(currentEvent, previousEvent)) {\n return true;\n }\n\n if (_isSameExceptionEvent(currentEvent, previousEvent)) {\n return true;\n }\n\n return false;\n}\n\n/** JSDoc */\nfunction _isSameMessageEvent(currentEvent: Event, previousEvent: Event): boolean {\n const currentMessage = currentEvent.message;\n const previousMessage = previousEvent.message;\n\n // If neither event has a message property, they were both exceptions, so bail out\n if (!currentMessage && !previousMessage) {\n return false;\n }\n\n // If only one event has a stacktrace, but not the other one, they are not the same\n if ((currentMessage && !previousMessage) || (!currentMessage && previousMessage)) {\n return false;\n }\n\n if (currentMessage !== previousMessage) {\n return false;\n }\n\n if (!_isSameFingerprint(currentEvent, previousEvent)) {\n return false;\n }\n\n if (!_isSameStacktrace(currentEvent, previousEvent)) {\n return false;\n }\n\n return true;\n}\n\n/** JSDoc */\nfunction _isSameExceptionEvent(currentEvent: Event, previousEvent: Event): boolean {\n const previousException = _getExceptionFromEvent(previousEvent);\n const currentException = _getExceptionFromEvent(currentEvent);\n\n if (!previousException || !currentException) {\n return false;\n }\n\n if (previousException.type !== currentException.type || previousException.value !== currentException.value) {\n return false;\n }\n\n if (!_isSameFingerprint(currentEvent, previousEvent)) {\n return false;\n }\n\n if (!_isSameStacktrace(currentEvent, previousEvent)) {\n return false;\n }\n\n return true;\n}\n\n/** JSDoc */\nfunction _isSameStacktrace(currentEvent: Event, previousEvent: Event): boolean {\n let currentFrames = _getFramesFromEvent(currentEvent);\n let previousFrames = _getFramesFromEvent(previousEvent);\n\n // If neither event has a stacktrace, they are assumed to be the same\n if (!currentFrames && !previousFrames) {\n return true;\n }\n\n // If only one event has a stacktrace, but not the other one, they are not the same\n if ((currentFrames && !previousFrames) || (!currentFrames && previousFrames)) {\n return false;\n }\n\n currentFrames = currentFrames as StackFrame[];\n previousFrames = previousFrames as StackFrame[];\n\n // If number of frames differ, they are not the same\n if (previousFrames.length !== currentFrames.length) {\n return false;\n }\n\n // Otherwise, compare the two\n for (let i = 0; i < previousFrames.length; i++) {\n const frameA = previousFrames[i];\n const frameB = currentFrames[i];\n\n if (\n frameA.filename !== frameB.filename ||\n frameA.lineno !== frameB.lineno ||\n frameA.colno !== frameB.colno ||\n frameA.function !== frameB.function\n ) {\n return false;\n }\n }\n\n return true;\n}\n\n/** JSDoc */\nfunction _isSameFingerprint(currentEvent: Event, previousEvent: Event): boolean {\n let currentFingerprint = currentEvent.fingerprint;\n let previousFingerprint = previousEvent.fingerprint;\n\n // If neither event has a fingerprint, they are assumed to be the same\n if (!currentFingerprint && !previousFingerprint) {\n return true;\n }\n\n // If only one event has a fingerprint, but not the other one, they are not the same\n if ((currentFingerprint && !previousFingerprint) || (!currentFingerprint && previousFingerprint)) {\n return false;\n }\n\n currentFingerprint = currentFingerprint as string[];\n previousFingerprint = previousFingerprint as string[];\n\n // Otherwise, compare the two\n try {\n return !!(currentFingerprint.join('') === previousFingerprint.join(''));\n } catch (_oO) {\n return false;\n }\n}\n\n/** JSDoc */\nfunction _getExceptionFromEvent(event: Event): Exception | undefined {\n return event.exception && event.exception.values && event.exception.values[0];\n}\n\n/** JSDoc */\nfunction _getFramesFromEvent(event: Event): StackFrame[] | undefined {\n const exception = event.exception;\n\n if (exception) {\n try {\n // @ts-ignore Object could be undefined\n return exception.values[0].stacktrace.frames;\n } catch (_oO) {\n return undefined;\n }\n } else if (event.stacktrace) {\n return event.stacktrace.frames;\n }\n return undefined;\n}\n","import { BaseClient, Scope, SDK_VERSION } from '@sentry/core';\nimport { Event, EventHint } from '@sentry/types';\nimport { getGlobalObject, logger } from '@sentry/utils';\n\nimport { BrowserBackend, BrowserOptions } from './backend';\nimport { IS_DEBUG_BUILD } from './flags';\nimport { injectReportDialog, ReportDialogOptions } from './helpers';\nimport { Breadcrumbs } from './integrations';\n\n/**\n * The Sentry Browser SDK Client.\n *\n * @see BrowserOptions for documentation on configuration options.\n * @see SentryClient for usage documentation.\n */\nexport class BrowserClient extends BaseClient<BrowserBackend, BrowserOptions> {\n /**\n * Creates a new Browser SDK instance.\n *\n * @param options Configuration options for this SDK.\n */\n public constructor(options: BrowserOptions = {}) {\n options._metadata = options._metadata || {};\n options._metadata.sdk = options._metadata.sdk || {\n name: 'sentry.javascript.browser',\n packages: [\n {\n name: 'npm:@sentry/browser',\n version: SDK_VERSION,\n },\n ],\n version: SDK_VERSION,\n };\n\n super(BrowserBackend, options);\n }\n\n /**\n * Show a report dialog to the user to send feedback to a specific event.\n *\n * @param options Set individual options for the dialog\n */\n public showReportDialog(options: ReportDialogOptions = {}): void {\n // doesn't work without a document (React Native)\n const document = getGlobalObject<Window>().document;\n if (!document) {\n return;\n }\n\n if (!this._isEnabled()) {\n IS_DEBUG_BUILD && logger.error('Trying to call showReportDialog with Sentry Client disabled');\n return;\n }\n\n injectReportDialog({\n ...options,\n dsn: options.dsn || this.getDsn(),\n });\n }\n\n /**\n * @inheritDoc\n */\n protected _prepareEvent(event: Event, scope?: Scope, hint?: EventHint): PromiseLike<Event | null> {\n event.platform = event.platform || 'javascript';\n return super._prepareEvent(event, scope, hint);\n }\n\n /**\n * @inheritDoc\n */\n protected _sendEvent(event: Event): void {\n const integration = this.getIntegration(Breadcrumbs);\n if (integration) {\n integration.addSentryBreadcrumb(event);\n }\n super._sendEvent(event);\n }\n}\n","import { getCurrentHub, initAndBind, Integrations as CoreIntegrations } from '@sentry/core';\nimport { Hub } from '@sentry/types';\nimport { addInstrumentationHandler, getGlobalObject, logger, resolvedSyncPromise } from '@sentry/utils';\n\nimport { BrowserOptions } from './backend';\nimport { BrowserClient } from './client';\nimport { IS_DEBUG_BUILD } from './flags';\nimport { ReportDialogOptions, wrap as internalWrap } from './helpers';\nimport { Breadcrumbs, Dedupe, GlobalHandlers, LinkedErrors, TryCatch, UserAgent } from './integrations';\n\nexport const defaultIntegrations = [\n new CoreIntegrations.InboundFilters(),\n new CoreIntegrations.FunctionToString(),\n new TryCatch(),\n new Breadcrumbs(),\n new GlobalHandlers(),\n new LinkedErrors(),\n new Dedupe(),\n new UserAgent(),\n];\n\n/**\n * The Sentry Browser SDK Client.\n *\n * To use this SDK, call the {@link init} function as early as possible when\n * loading the web page. To set context information or send manual events, use\n * the provided methods.\n *\n * @example\n *\n * ```\n *\n * import { init } from '@sentry/browser';\n *\n * init({\n * dsn: '__DSN__',\n * // ...\n * });\n * ```\n *\n * @example\n * ```\n *\n * import { configureScope } from '@sentry/browser';\n * configureScope((scope: Scope) => {\n * scope.setExtra({ battery: 0.7 });\n * scope.setTag({ user_mode: 'admin' });\n * scope.setUser({ id: '4711' });\n * });\n * ```\n *\n * @example\n * ```\n *\n * import { addBreadcrumb } from '@sentry/browser';\n * addBreadcrumb({\n * message: 'My Breadcrumb',\n * // ...\n * });\n * ```\n *\n * @example\n *\n * ```\n *\n * import * as Sentry from '@sentry/browser';\n * Sentry.captureMessage('Hello, world!');\n * Sentry.captureException(new Error('Good bye'));\n * Sentry.captureEvent({\n * message: 'Manual',\n * stacktrace: [\n * // ...\n * ],\n * });\n * ```\n *\n * @see {@link BrowserOptions} for documentation on configuration options.\n */\nexport function init(options: BrowserOptions = {}): void {\n if (options.defaultIntegrations === undefined) {\n options.defaultIntegrations = defaultIntegrations;\n }\n if (options.release === undefined) {\n const window = getGlobalObject<Window>();\n // This supports the variable that sentry-webpack-plugin injects\n if (window.SENTRY_RELEASE && window.SENTRY_RELEASE.id) {\n options.release = window.SENTRY_RELEASE.id;\n }\n }\n if (options.autoSessionTracking === undefined) {\n options.autoSessionTracking = true;\n }\n if (options.sendClientReports === undefined) {\n options.sendClientReports = true;\n }\n\n initAndBind(BrowserClient, options);\n\n if (options.autoSessionTracking) {\n startSessionTracking();\n }\n}\n\n/**\n * Present the user with a report dialog.\n *\n * @param options Everything is optional, we try to fetch all info need from the global scope.\n */\nexport function showReportDialog(options: ReportDialogOptions = {}): void {\n const hub = getCurrentHub();\n const scope = hub.getScope();\n if (scope) {\n options.user = {\n ...scope.getUser(),\n ...options.user,\n };\n }\n\n if (!options.eventId) {\n options.eventId = hub.lastEventId();\n }\n const client = hub.getClient<BrowserClient>();\n if (client) {\n client.showReportDialog(options);\n }\n}\n\n/**\n * This is the getter for lastEventId.\n *\n * @returns The last event id of a captured event.\n */\nexport function lastEventId(): string | undefined {\n return getCurrentHub().lastEventId();\n}\n\n/**\n * This function is here to be API compatible with the loader.\n * @hidden\n */\nexport function forceLoad(): void {\n // Noop\n}\n\n/**\n * This function is here to be API compatible with the loader.\n * @hidden\n */\nexport function onLoad(callback: () => void): void {\n callback();\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 function flush(timeout?: number): PromiseLike<boolean> {\n const client = getCurrentHub().getClient<BrowserClient>();\n if (client) {\n return client.flush(timeout);\n }\n IS_DEBUG_BUILD && logger.warn('Cannot flush events. No client defined.');\n return resolvedSyncPromise(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 function close(timeout?: number): PromiseLike<boolean> {\n const client = getCurrentHub().getClient<BrowserClient>();\n if (client) {\n return client.close(timeout);\n }\n IS_DEBUG_BUILD && logger.warn('Cannot flush events and disable SDK. No client defined.');\n return resolvedSyncPromise(false);\n}\n\n/**\n * Wrap code within a try/catch block so the SDK is able to capture errors.\n *\n * @param fn A function to wrap.\n *\n * @returns The result of wrapped function call.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function wrap(fn: (...args: any) => any): any {\n return internalWrap(fn)();\n}\n\nfunction startSessionOnHub(hub: Hub): void {\n hub.startSession({ ignoreDuration: true });\n hub.captureSession();\n}\n\n/**\n * Enable automatic Session Tracking for the initial page load.\n */\nfunction startSessionTracking(): void {\n const window = getGlobalObject<Window>();\n const document = window.document;\n\n if (typeof document === 'undefined') {\n IS_DEBUG_BUILD && logger.warn('Session tracking in non-browser environment with @sentry/browser is not supported.');\n return;\n }\n\n const hub = getCurrentHub();\n\n // The only way for this to be false is for there to be a version mismatch between @sentry/browser (>= 6.0.0) and\n // @sentry/hub (< 5.27.0). In the simple case, there won't ever be such a mismatch, because the two packages are\n // pinned at the same version in package.json, but there are edge cases where it's possible. See\n // https://github.com/getsentry/sentry-javascript/issues/3207 and\n // https://github.com/getsentry/sentry-javascript/issues/3234 and\n // https://github.com/getsentry/sentry-javascript/issues/3278.\n if (!hub.captureSession) {\n return;\n }\n\n // The session duration for browser sessions does not track a meaningful\n // concept that can be used as a metric.\n // Automatically captured sessions are akin to page views, and thus we\n // discard their duration.\n startSessionOnHub(hub);\n\n // We want to create a session for every navigation as well\n addInstrumentationHandler('history', ({ from, to }) => {\n // Don't create an additional session for the initial route or if the location did not change\n if (!(from === undefined || from === to)) {\n startSessionOnHub(getCurrentHub());\n }\n });\n}\n","export * from './exports';\n\nimport { Integrations as CoreIntegrations } from '@sentry/core';\nimport { getGlobalObject } from '@sentry/utils';\n\nimport * as BrowserIntegrations from './integrations';\nimport * as Transports from './transports';\n\nlet windowIntegrations = {};\n\n// This block is needed to add compatibility with the integrations packages when used with a CDN\nconst _window = getGlobalObject<Window>();\nif (_window.Sentry && _window.Sentry.Integrations) {\n windowIntegrations = _window.Sentry.Integrations;\n}\n\nconst INTEGRATIONS = {\n ...windowIntegrations,\n ...CoreIntegrations,\n ...BrowserIntegrations,\n};\n\nexport { INTEGRATIONS as Integrations, Transports };\n","// TODO: Remove in the next major release and rely only on @sentry/core SDK_VERSION and SdkInfo metadata\nexport const SDK_NAME = 'sentry.javascript.browser';\n","import { getCurrentHub } from '@sentry/hub';\nimport { Client, Options } from '@sentry/types';\nimport { logger } from '@sentry/utils';\n\nimport { IS_DEBUG_BUILD } from './flags';\n\n/** A class object that can instantiate Client objects. */\nexport type ClientClass<F extends Client, O extends Options> = new (options: O) => F;\n\n/**\n * Internal function to create a new SDK client instance. The client is\n * installed and then bound to the current scope.\n *\n * @param clientClass The client class to instantiate.\n * @param options Options to pass to the client.\n */\nexport function initAndBind<F extends Client, O extends Options>(clientClass: ClientClass<F, O>, options: O): void {\n if (options.debug === true) {\n if (IS_DEBUG_BUILD) {\n logger.enable();\n } else {\n // use `console.warn` rather than `logger.warn` since by non-debug bundles have all `logger.x` statements stripped\n // eslint-disable-next-line no-console\n console.warn('[Sentry] Cannot initialize SDK with `debug` option using a non-debug bundle.');\n }\n }\n const hub = getCurrentHub();\n const scope = hub.getScope();\n if (scope) {\n scope.update(options.initialScope);\n }\n const client = new clientClass(options);\n hub.bindClient(client);\n}\n"],"names":["Severity","fallbackGlobalObject","getGlobalObject","window","self","getGlobalSingleton","name","creator","obj","global","__SENTRY__","objectToString","Object","prototype","toString","isError","wat","call","isInstanceOf","Error","isBuiltin","ty","isErrorEvent","isDOMError","isString","isPrimitive","isPlainObject","isEvent","Event","isThenable","Boolean","then","base","_e","htmlTreeAsString","elem","keyAttrs","currentElem","out","height","len","sepLength","length","nextStr","_htmlElementAsString","push","parentNode","reverse","join","_oO","el","className","classes","key","attr","i","tagName","toLowerCase","keyAttrPairs","filter","keyAttr","getAttribute","map","forEach","keyAttrPair","id","split","allowedAttrs","setPrototypeOf","__proto__","Array","proto","prop","hasOwnProperty","message","_super","_this","_newTarget","constructor","__extends","DSN_REGEX","dsnToString","dsn","withPassword","host","path","pass","port","projectId","dsnFromComponents","components","publicKey","user","protocol","makeDsn","from","str","match","exec","SentryError","_a","_b","_c","slice","pop","projectMatch","dsnFromString","component","isValidProtocol","isNaN","parseInt","validateDsn","logger","SeverityLevels","PREFIX","CONSOLE_LEVELS","consoleSandbox","callback","originalConsole","console","wrappedLevels","level","originalWrappedFunc","__sentry_original__","keys","makeLogger","enabled","enable","disable","_i","args","truncate","max","substr","safeJoin","input","delimiter","isArray","output","value","String","e","isMatchingPattern","pattern","test","indexOf","fill","source","replacementFactory","original","wrapped","markFunctionWrapped","_Oo","addNonEnumerableProperty","defineProperty","writable","configurable","getOriginalFunction","func","convertToPlainObject","newObj","stack","getOwnProperties","event_1","type","target","serializeEventTarget","currentTarget","CustomEvent","detail","Element","extractedProps","property","extractExceptionKeysForMessage","exception","maxLength","sort","includedKeys","serialized","dropUndefinedKeys","val","rv","__values","stripSentryFramesAndReverse","localStack","firstFrameFunction","function","lastFrameFunction","frame","filename","defaultFunctionName","getFunctionName","fn","supportsFetch","Headers","Request","Response","isNativeFetch","supportsReferrerPolicy","referrerPolicy","lastHref","handlers","instrumented","instrument","originalConsoleMethod","triggerHandlers","apply","instrumentConsole","triggerDOMHandler","bind","globalDOMEventHandler","makeDOMEventHandler","document","addEventListener","originalAddEventListener","listener","options","this","handlers_1","__sentry_instrumentation_handlers__","handlerForType","refCount","handler","originalRemoveEventListener","handlers_2","undefined","instrumentDOM","xhrproto","XMLHttpRequest","originalOpen","xhr","url","xhrInfo","__sentry_xhr__","method","toUpperCase","__sentry_own_request__","onreadystatechangeHandler","readyState","status_code","status","endTimestamp","Date","now","startTimestamp","onreadystatechange","readyStateArgs","originalSend","body","instrumentXHR","fetch","result","doc","createElement","sandbox","hidden","head","appendChild","contentWindow","removeChild","err","warn","supportsNativeFetch","originalFetch","handlerData","fetchData","getFetchMethod","getFetchUrl","response","error","instrumentFetch","chrome","isChromePackagedApp","app","runtime","hasHistoryApi","history","pushState","replaceState","supportsHistory","oldOnPopState","onpopstate","historyReplacementFunction","originalHistoryFunction","to","location","href","instrumentHistory","_oldOnErrorHandler","onerror","msg","line","column","arguments","_oldOnUnhandledRejectionHandler","onunhandledrejection","addInstrumentationHandler","data","fetchArgs","debounceTimerID","lastCapturedEvent","globalListener","event","isContentEditable","shouldSkipDOMEvent","previous","current","shouldShortcircuitPreviousDebounce","clearTimeout","setTimeout","uuid4","crypto","msCrypto","getRandomValues","arr","Uint16Array","pad","num","v","replace","c","r","Math","random","parseUrl","query","fragment","relative","getFirstException","values","getEventDescription","eventId","firstException","addExceptionTypeValue","addExceptionMechanism","newMechanism","currentMechanism","mechanism","handled","mergedData","checkOrSetAlreadyCaught","__sentry_captured__","normalize","depth","maxProperties","Infinity","visit","ERROR","normalizeToSize","object","maxSize","normalized","encodeURI","utf8Length","JSON","stringify","memo","hasWeakSet","inner","WeakSet","has","add","delete","splice","memoize","unmemoize","valueWithToJSON","toJSON","includes","stringified","_events","isSyntheticEvent","getPrototypeOf","stringifyValue","startsWith","numAdded","visitable","visitKey","visitValue","resolvedSyncPromise","SyncPromise","resolve","rejectedSyncPromise","reason","_","reject","executor","_setResult","state","_state","_resolve","_reject","_value","_executeHandlers","cachedHandlers","_handlers","onfulfilled","onrejected","onfinally","isRejected","makePromiseBuffer","limit","buffer","remove","task","$","taskProducer","drain","timeout","counter","capturedSetTimeout","item","severityFromString","Warning","isSupportedSeverity","Log","eventStatusFromHttpCode","code","dateTimestampSource","nowSeconds","platformPerformance","performance","timeOrigin","getBrowserPerformance","timestampSource","dateTimestampInSeconds","timestampInSeconds","createEnvelope","headers","items","serializeEnvelope","envelope","serializedHeaders","reduce","acc","itemHeaders","payload","serializedPayload","threshold","performanceNow","dateNow","timeOriginDelta","abs","timeOriginIsReliable","navigationStart","timing","navigationStartDelta","disabledUntil","limits","category","all","isRateLimited","updateRateLimits","updatedRateLimits","rateLimitHeader","retryAfterHeader","trim","parameters","headerDelay","delay","header","headerDate","parse","parseRetryAfterHeader","Scope","scope","newScope","_breadcrumbs","_tags","_extra","_contexts","_user","_level","_span","_session","_transactionName","_fingerprint","_eventProcessors","_requestSession","_scopeListeners","update","_notifyScopeListeners","requestSession","tags","extras","extra","fingerprint","setTransactionName","context","span","getSpan","transaction","session","captureContext","updatedScope","contexts","breadcrumb","maxBreadcrumbs","maxCrumbs","min","mergedBreadcrumb","timestamp","__spread","hint","trace","getTraceContext","transactionName","_applyFingerprint","breadcrumbs","sdkProcessingMetadata","_sdkProcessingMetadata","_notifyEventProcessors","getGlobalEventProcessors","newData","processors","index","processor","final","_notifyingListeners","concat","addGlobalEventProcessor","startingTime","started","Session","ipAddress","ip_address","did","email","username","ignoreDuration","sid","init","duration","release","environment","userAgent","errors","toISOString","attrs","user_agent","client","_version","getStackTop","bindClient","Hub","version","setupIntegrations","clone","getScope","getStack","getClient","pushScope","popScope","_stack","_lastEventId","event_id","finalHint","syntheticException","originalException","_invokeClient","beforeBreadcrumb","_d","finalBreadcrumb","addBreadcrumb","setUser","setTags","setExtras","setTag","setExtra","setContext","oldHub","makeMain","integration","getIntegration","_callExtensionMethod","customSamplingContext","endSession","_sendSessionUpdate","layer","getSession","close","setSession","getUser","currentSession","captureSession","carrier","getMainCarrier","sentry","extensions","hub","registry","getHubFromCarrier","setHubOnCarrier","getCurrentHub","isOlderThan","callOnHub","captureException","withScope","initAPIDetails","metadata","tunnel","initDsn","getBaseApiEndpoint","_getIngestEndpoint","_encodedAuth","sentry_key","sentry_version","encodeURIComponent","getStoreEndpointWithUrlEncodedAuth","getStoreEndpoint","getEnvelopeEndpointWithUrlEncodedAuth","_getEnvelopeEndpoint","installedIntegrations","filterDuplicates","integrations","every","accIntegration","defaultIntegrations","userIntegrations","userIntegration","integrationsNames","alwaysLastToRun","getIntegrationsToSetup","setupOnce","log","setupIntegration","ALREADY_SEEN_ERROR","backendClass","_backend","_options","_dsn","BaseClient","_process","_getBackend","eventFromException","_captureEvent","promisedEvent","eventFromMessage","_isEnabled","_sendSession","getTransport","_isClientDoneProcessing","clientFinished","transportFlushed","flush","getOptions","_integrations","initialized","crashed","errored","exceptions","exceptions_1","sessionNonTerminal","Number","sendSession","ticked","interval","setInterval","_numProcessing","clearInterval","normalizeDepth","normalizeMaxBreadth","prepared","_applyClientOptions","_applyIntegrationsMetadata","finalScope","applyToEvent","evt","_normalizeEvent","maxBreadth","b","baseClientNormalized","dist","maxValueLength","request","integrationsArray","sdk","sendEvent","_processEvent","finalEvent","beforeSend","sampleRate","transport","recordLostEvent","outcome","isTransaction","_prepareEvent","__sentry__","nullErr","_ensureBeforeSendRv","processedEvent","_updateSessionFromEvent","_sendEvent","promise","getSdkMetadataForEnvelopeHeader","api","enhanceEventWithSdkInfo","sdkInfo","packages","createSessionEnvelope","sent_at","NoopTransport","_transport","_setupTransport","BaseBackend","_exception","_hint","_message","_newTransport","_experiments","newTransport","env","eventType","samplingMethod","skippedNormalization","sample_rates","rate","createEventEnvelope","_metadata","send","createTransport","makeRequest","bufferSize","rateLimits","envCategory","getEnvelopeType","getRateLimitReason","originalFunctionToString","SDK_VERSION","FunctionToString","Function","DEFAULT_IGNORE_ERRORS","InboundFilters","self_1","clientOptions","internalOptions","allowUrls","whitelistUrls","denyUrls","blacklistUrls","ignoreErrors","ignoreInternal","_mergeOptions","_isSentryError","oO","_getPossibleEventMessages","some","_isIgnoredError","_getEventFilterUrl","_isDeniedUrl","_isAllowedUrl","_shouldDropEvent","_getLastValidUrl","frames","stacktrace","frames_1","UNKNOWN_FUNCTION","createFrame","lineno","colno","in_app","chromeRegex","chromeEvalRegex","chromeStackParser","parts","subMatch","geckoREgex","geckoEvalRegex","geckoStackParser","winjsRegex","winjsStackParser","opera10Regex","opera10StackParser","opera11Regex","opera11StackParser","extractSafariExtensionDetails","isSafariExtension","isSafariWebExtension","exceptionFromError","ex","parseStackFrames","extractMessage","eventFromError","popSize","framesToPop","reactMinifiedRegexp","getPopSize","parsers","sortedParsers","a","p","skipFirst","sortedParsers_1","parser","createStackParser","attachStacktrace","eventFromUnknownInput","Info","eventFromString","isUnhandledRejection","domException","name_1","__serialized__","eventFromPlainObject","synthetic","frames_2","cachedFetchImpl","getNativeFetchImplementation","fetchImpl","sendReport","navigator","sendBeacon","fetch_1","credentials","keepalive","requestTypeToCategory","_api","sendClientReports","visibilityState","_flushOutcomes","BaseTransport","_sendRequest","useEnvelope","JSONStringifyError","newErr","innerErr","req","eventToSentryRequest","sessionToSentryRequest","_buffer","_outcomes","outcomes","discarded_events","discardedEvents","quantity","requestType","_rateLimits","_isRateLimited","_disabledUntil","_fetch","FetchTransport","sentryRequest","originalPayload","Promise","fetchParameters","assign","get","_handleResponse","catch","XHRTransport","getResponseHeader","open","setRequestHeader","makeNewFetchTransport","nativeFetch","requestOptions","text","statusText","statusCode","makeNewXHRTransport","BrowserBackend","transportOptions","ignoreOnError","shouldIgnoreOnError","ignoreNextOnError","wrap","before","wrapper","__sentry_wrapped__","sentryWrapped","wrappedArguments","arg","addEventProcessor","getOwnPropertyDescriptor","injectReportDialog","script","async","src","dsnLike","dialogOptions","endpoint","encodedOptions","getReportDialogEndpoint","onLoad","onload","injectionPoint","GlobalHandlers","_installGlobalOnErrorHandler","_installGlobalOnUnhandledRejectionHandler","stackTraceLimit","installFunc","_installFunc","ERROR_TYPES_RE","groups","_enhanceEventWithInitialFrame","_eventFromIncompleteOnError","addMechanismAndCapture","ev","ev0","ev0s","ev0sf","getLocationHref","captureEvent","getHubAndAttachStacktrace","DEFAULT_EVENT_TARGET","TryCatch","eventTarget","requestAnimationFrame","_wrapTimeFunction","_wrapRAF","_wrapXHR","eventTargetOption","_wrapEventTarget","originalCallback","xmlHttpRequestProps","wrapOptions","originalFunction","eventName","handleEvent","wrappedEventHandler","originalEventHandler","Breadcrumbs","dom","_consoleBreadcrumb","_innerDomBreadcrumb","serializeAttribute","_domBreadcrumb","_xhrBreadcrumb","_fetchBreadcrumb","_historyBreadcrumb","parsedLoc","parsedFrom","parsedTo","LinkedErrors","_key","_limit","linkedErrors","_walkErrorTree","_handler","UserAgent","referrer","Referer","Dedupe","currentEvent","previousEvent","currentMessage","previousMessage","_isSameFingerprint","_isSameStacktrace","_isSameMessageEvent","previousException","_getExceptionFromEvent","currentException","_isSameExceptionEvent","_previousEvent","currentFrames","_getFramesFromEvent","previousFrames","frameA","frameB","currentFingerprint","previousFingerprint","BrowserClient","getDsn","platform","addSentryBreadcrumb","CoreIntegrations.InboundFilters","CoreIntegrations.FunctionToString","startSessionOnHub","startSession","windowIntegrations","_window","Sentry","Integrations","INTEGRATIONS","CoreIntegrations","BrowserIntegrations","window_1","SENTRY_RELEASE","autoSessionTracking","clientClass","debug","initialScope","initAndBind","startSessionTracking","lastEventId","showReportDialog","internalWrap"],"mappings":";+dAGYA,m4BAAAA,EAAAA,aAAAA,8BAIVA,gBAEAA,oBAEAA,YAEAA,cAEAA,gBAEAA,sBCWF,IAAMC,EAAuB,YAObC,IACd,MAGwB,oBAAXC,OACPA,OACgB,oBAATC,KACPA,KACAH,WAeQI,EAAsBC,EAAwCC,EAAkBC,GAC9F,IAAMC,EAAUD,GAAON,IACjBQ,EAAcD,EAAOC,WAAaD,EAAOC,YAAc,GAE7D,OADkBA,EAAWJ,KAAUI,EAAWJ,GAAQC,KCvD5D,IAAMI,EAAiBC,OAAOC,UAAUC,kBASxBC,EAAQC,GACtB,OAAQL,EAAeM,KAAKD,IAC1B,IAAK,iBACL,IAAK,qBACL,IAAK,wBACH,OAAO,EACT,QACE,OAAOE,EAAaF,EAAKG,QAI/B,SAASC,EAAUJ,EAAcK,GAC/B,OAAOV,EAAeM,KAAKD,KAAS,WAAWK,eAUjCC,EAAaN,GAC3B,OAAOI,EAAUJ,EAAK,uBAURO,EAAWP,GACzB,OAAOI,EAAUJ,EAAK,qBAqBRQ,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