UNPKG

390 kBSource Map (JSON)View Raw
1{"version":3,"file":"bundle.es6.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/flags.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/flags.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/transports/base.ts","../../../core/src/version.ts","../../../core/src/integrations/functiontostring.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","../../../core/src/basebackend.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","/*\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 { 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","/*\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","/* 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 { 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","export const SDK_VERSION = '6.19.7';\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","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 { 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 { 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","MAX_TRAVERSE_HEIGHT","MAX_OUTPUT_LEN","out","height","len","separator","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","SentryError","constructor","message","super","this","DSN_REGEX","dsnToString","dsn","withPassword","host","path","pass","port","projectId","protocol","publicKey","dsnFromComponents","components","user","makeDsn","from","str","match","exec","lastPath","slice","pop","projectMatch","dsnFromString","component","isValidProtocol","isNaN","parseInt","validateDsn","SeverityLevels","CONSOLE_LEVELS","consoleSandbox","callback","originalConsole","console","wrappedLevels","level","originalWrappedFunc","__sentry_original__","keys","makeLogger","enabled","logger","enable","disable","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","type","target","serializeEventTarget","currentTarget","CustomEvent","detail","Element","extractedProps","property","extractExceptionKeysForMessage","exception","maxLength","sort","includedKeys","serialized","dropUndefinedKeys","val","rv","createStackParser","parsers","sortedParsers","a","b","p","skipFirst","frames","line","parser","frame","localStack","firstFrameFunction","function","lastFrameFunction","filename","stripSentryFramesAndReverse","defaultFunctionName","getFunctionName","fn","supportsFetch","Headers","Request","Response","isNativeFetch","supportsReferrerPolicy","referrerPolicy","handlers","instrumented","instrument","originalConsoleMethod","triggerHandlers","apply","instrumentConsole","triggerDOMHandler","bind","globalDOMEventHandler","makeDOMEventHandler","document","addEventListener","originalAddEventListener","listener","options","__sentry_instrumentation_handlers__","handlerForType","refCount","handler","originalRemoveEventListener","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","lastHref","to","location","href","instrumentHistory","_oldOnErrorHandler","onerror","msg","column","arguments","_oldOnUnhandledRejectionHandler","onunhandledrejection","addInstrumentationHandler","data","fetchArgs","debounceTimerID","lastCapturedEvent","globalListener","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","event_id","eventId","firstException","addExceptionTypeValue","addExceptionMechanism","newMechanism","currentMechanism","mechanism","handled","mergedData","checkOrSetAlreadyCaught","__sentry_captured__","normalize","depth","Infinity","maxProperties","visit","ERROR","normalizeToSize","object","maxSize","normalized","encodeURI","utf8Length","JSON","stringify","memo","hasWeakSet","WeakSet","inner","has","add","delete","splice","memoBuilder","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","catch","finally","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","static","scope","newScope","_breadcrumbs","_tags","_extra","_contexts","_user","_level","_span","_session","_transactionName","_fingerprint","_eventProcessors","_requestSession","addScopeListener","_scopeListeners","addEventProcessor","setUser","update","_notifyScopeListeners","getUser","getRequestSession","setRequestSession","requestSession","setTags","tags","setTag","setExtras","extras","setExtra","extra","setFingerprint","fingerprint","setLevel","setTransactionName","setTransaction","setContext","context","setSpan","span","getSpan","getTransaction","transaction","setSession","session","getSession","captureContext","updatedScope","contexts","clear","addBreadcrumb","breadcrumb","maxBreadcrumbs","maxCrumbs","min","mergedBreadcrumb","timestamp","clearBreadcrumbs","applyToEvent","hint","trace","getTraceContext","transactionName","_applyFingerprint","breadcrumbs","sdkProcessingMetadata","_sdkProcessingMetadata","_notifyEventProcessors","getGlobalEventProcessors","setSDKProcessingMetadata","newData","processors","index","processor","final","_notifyingListeners","concat","addGlobalEventProcessor","Session","startingTime","started","ipAddress","ip_address","did","email","username","ignoreDuration","sid","init","duration","release","environment","userAgent","errors","close","toISOString","attrs","user_agent","DEFAULT_BREADCRUMBS","Hub","client","_version","getStackTop","bindClient","isOlderThan","version","setupIntegrations","pushScope","clone","getScope","getStack","getClient","popScope","withScope","_stack","captureException","_lastEventId","finalHint","syntheticException","originalException","_invokeClient","captureMessage","captureEvent","lastEventId","beforeBreadcrumb","getOptions","finalBreadcrumb","configureScope","run","oldHub","makeMain","getIntegration","integration","startSpan","_callExtensionMethod","startTransaction","customSamplingContext","traceHeaders","captureSession","endSession","_sendSessionUpdate","layer","startSession","navigator","currentSession","sentry","getMainCarrier","extensions","carrier","hub","registry","getHubFromCarrier","setHubOnCarrier","getCurrentHub","callOnHub","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","getSdkMetadataForEnvelopeHeader","api","sdk","enhanceEventWithSdkInfo","sdkInfo","packages","createSessionEnvelope","sent_at","NoopTransport","sendEvent","createTransport","makeRequest","bufferSize","rateLimits","send","envCategory","firstItemHeader","getEnvelopeType","request","getRateLimitReason","statusCode","flush","SDK_VERSION","originalFunctionToString","FunctionToString","Function","DEFAULT_IGNORE_ERRORS","InboundFilters","_options","clientOptions","internalOptions","allowUrls","whitelistUrls","denyUrls","blacklistUrls","ignoreErrors","ignoreInternal","_mergeOptions","_isSentryError","oO","_getPossibleEventMessages","some","_isIgnoredError","_getEventFilterUrl","_isDeniedUrl","_isAllowedUrl","_shouldDropEvent","_getLastValidUrl","stacktrace","UNKNOWN_FUNCTION","createFrame","lineno","colno","in_app","chromeRegex","chromeEvalRegex","chromeStackParser","parts","subMatch","extractSafariExtensionDetails","geckoREgex","geckoEvalRegex","geckoStackParser","winjsRegex","winjsStackParser","opera10Regex","opera10StackParser","opera11Regex","opera11StackParser","isSafariExtension","isSafariWebExtension","exceptionFromError","ex","parseStackFrames","extractMessage","eventFromError","popSize","framesToPop","reactMinifiedRegexp","getPopSize","eventFromException","attachStacktrace","eventFromUnknownInput","eventFromMessage","Info","eventFromString","isUnhandledRejection","domException","__serialized__","eventFromPlainObject","synthetic","cachedFetchImpl","getNativeFetchImplementation","fetchImpl","sendReport","sendBeacon","credentials","keepalive","requestTypeToCategory","BaseTransport","_api","_metadata","sendClientReports","visibilityState","_flushOutcomes","_sendRequest","eventType","useEnvelope","transactionSampling","samplingMethod","rate","sampleRate","baseClientNormalized","skippedNormalization","normalizeDepth","JSONStringifyError","newErr","innerErr","req","sample_rates","eventToSentryRequest","sendSession","sessionToSentryRequest","_buffer","recordLostEvent","_outcomes","outcomes","discardedEvents","quantity","discarded_events","_handleResponse","requestType","_rateLimits","_isRateLimited","_disabledUntil","FetchTransport","_fetch","sentryRequest","originalPayload","Promise","fetchParameters","assign","get","XHRTransport","getResponseHeader","open","setRequestHeader","makeNewFetchTransport","nativeFetch","requestOptions","text","statusText","makeNewXHRTransport","BrowserBackend","_transport","_setupTransport","_exception","_hint","_message","_newTransport","_experiments","newTransport","env","createEventEnvelope","getTransport","transportOptions","transport","ignoreOnError","shouldIgnoreOnError","ignoreNextOnError","wrap","before","wrapper","__sentry_wrapped__","sentryWrapped","wrappedArguments","arg","getOwnPropertyDescriptor","injectReportDialog","script","async","src","dsnLike","dialogOptions","endpoint","encodedOptions","getReportDialogEndpoint","onLoad","onload","injectionPoint","GlobalHandlers","_installGlobalOnErrorHandler","_installGlobalOnUnhandledRejectionHandler","stackTraceLimit","installFunc","_installFunc","getHubAndAttachStacktrace","ERROR_TYPES_RE","groups","_enhanceEventWithInitialFrame","_eventFromIncompleteOnError","addMechanismAndCapture","ev","ev0","ev0s","ev0sf","getLocationHref","DEFAULT_EVENT_TARGET","TryCatch","eventTarget","requestAnimationFrame","setInterval","_wrapTimeFunction","_wrapRAF","_wrapXHR","eventTargetOption","_wrapEventTarget","originalCallback","wrapOptions","originalFunction","eventName","handleEvent","wrappedEventHandler","originalEventHandler","Breadcrumbs","dom","addSentryBreadcrumb","_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","backendClass","_backend","_dsn","_process","_getBackend","_captureEvent","promisedEvent","_isEnabled","_sendSession","getDsn","_isClientDoneProcessing","clientFinished","transportFlushed","_integrations","initialized","_updateSessionFromEvent","crashed","errored","exceptions","sessionNonTerminal","Number","ticked","interval","_numProcessing","clearInterval","_prepareEvent","normalizeMaxBreadth","prepared","_applyClientOptions","_applyIntegrationsMetadata","finalScope","evt","_normalizeEvent","maxBreadth","dist","maxValueLength","integrationsArray","_sendEvent","_processEvent","finalEvent","beforeSend","outcome","isTransaction","__sentry__","nullErr","_ensureBeforeSendRv","processedEvent","promise","showReportDialog","platform","CoreIntegrations.InboundFilters","CoreIntegrations.FunctionToString","startSessionOnHub","windowIntegrations","_window","Sentry","Integrations","INTEGRATIONS","CoreIntegrations","BrowserIntegrations","SENTRY_RELEASE","autoSessionTracking","clientClass","debug","initialScope","initAndBind","startSessionTracking","internalWrap"],"mappings":";uBAGA,IAAYA,qBAAAA,EAAAA,aAAAA,8BAIVA,gBAEAA,oBAEAA,YAEAA,cAEAA,gBAEAA,sBCWF,MAAMC,EAAuB,YAObC,IACd,MAGwB,oBAAXC,OACPA,OACgB,oBAATC,KACPA,KACAH,WAeQI,EAAsBC,EAAwCC,EAAkBC,GAC9F,MAAMC,EAAUD,GAAON,IACjBQ,EAAcD,EAAOC,WAAaD,EAAOC,YAAc,GAE7D,OADkBA,EAAWJ,KAAUI,EAAWJ,GAAQC,KCvD5D,MAAMI,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,cAUjCC,EAAaN,GAC3B,OAAOI,EAAUJ,EAAK,uBAURO,EAAWP,GACzB,OAAOI,EAAUJ,EAAK,qBAqBRQ,EAASR,GACvB,OAAOI,EAAUJ,EAAK,mBAURS,EAAYT,GAC1B,OAAe,OAARA,GAAgC,iBAARA,GAAmC,mBAARA,WAU5CU,EAAcV,GAC5B,OAAOI,EAAUJ,EAAK,mBAURW,EAAQX,GACtB,MAAwB,oBAAVY,OAAyBV,EAAaF,EAAKY,gBA6B3CC,EAAWb,GAEzB,OAAOc,QAAQd,GAAOA,EAAIe,MAA4B,mBAAbf,EAAIe,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