@wix/create-app 0.0.61 → 0.0.62

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../../node_modules/@sentry/utils/esm/index.js","../../../node_modules/@sentry/src/is.ts","../../../node_modules/@sentry/src/string.ts","../../../node_modules/@sentry/src/aggregate-errors.ts","../../../node_modules/@sentry/src/worldwide.ts","../../../node_modules/@sentry/src/browser.ts","../../../node_modules/@sentry/src/debug-build.ts","../../../node_modules/@sentry/src/logger.ts","../../../node_modules/@sentry/src/dsn.ts","../../../node_modules/@sentry/src/error.ts","../../../node_modules/@sentry/src/object.ts","../../../node_modules/@sentry/src/node-stack-trace.ts","../../../node_modules/@sentry/src/stacktrace.ts","../../../node_modules/@sentry/src/instrument/_handlers.ts","../../../node_modules/@sentry/src/instrument/console.ts","../../../node_modules/@sentry/src/misc.ts","../../../node_modules/@sentry/src/instrument/dom.ts","../../../node_modules/@sentry/src/supports.ts","../../../node_modules/@sentry/src/instrument/fetch.ts","../../../node_modules/@sentry/src/instrument/globalError.ts","../../../node_modules/@sentry/src/instrument/globalUnhandledRejection.ts","../../../node_modules/@sentry/src/vendor/supportsHistory.ts","../../../node_modules/@sentry/src/instrument/history.ts","../../../node_modules/@sentry/src/instrument/xhr.ts","../../../node_modules/@sentry/src/env.ts","../../../node_modules/@sentry/src/node.ts","../../../node_modules/@sentry/src/isBrowser.ts","../../../node_modules/@sentry/src/memo.ts","../../../node_modules/@sentry/src/normalize.ts","../../../node_modules/@sentry/src/path.ts","../../../node_modules/@sentry/src/syncpromise.ts","../../../node_modules/@sentry/src/promisebuffer.ts","../../../node_modules/@sentry/src/cookie.ts","../../../node_modules/@sentry/src/url.ts","../../../node_modules/@sentry/src/requestdata.ts","../../../node_modules/@sentry/src/severity.ts","../../../node_modules/@sentry/src/time.ts","../../../node_modules/@sentry/src/baggage.ts","../../../node_modules/@sentry/src/tracing.ts","../../../node_modules/@sentry/src/envelope.ts","../../../node_modules/@sentry/src/clientreport.ts","../../../node_modules/@sentry/src/ratelimit.ts","../../../node_modules/@sentry/src/eventbuilder.ts","../../../node_modules/@sentry/src/lru.ts","../../../node_modules/@sentry/src/buildPolyfills/_nullishCoalesce.ts","../../../node_modules/@sentry/src/buildPolyfills/_optionalChain.ts","../../../node_modules/@sentry/src/buildPolyfills/_optionalChainDelete.ts","../../../node_modules/@sentry/src/debug-build.ts","../../../node_modules/@sentry/src/eventProcessors.ts","../../../node_modules/@sentry/src/constants.ts","../../../node_modules/@sentry/src/session.ts","../../../node_modules/@sentry/src/utils/getRootSpan.ts","../../../node_modules/@sentry/src/utils/spanUtils.ts","../../../node_modules/@sentry/src/tracing/dynamicSamplingContext.ts","../../../node_modules/@sentry/src/utils/applyScopeDataToEvent.ts","../../../node_modules/@sentry/src/scope.ts","../../../node_modules/@sentry/src/version.ts","../../../node_modules/@sentry/src/hub.ts","../../../node_modules/@sentry/src/utils/prepareEvent.ts","../../../node_modules/@sentry/src/exports.ts","../../../node_modules/@sentry/src/tracing/utils.ts","../../../node_modules/@sentry/src/tracing/spanstatus.ts","../../../node_modules/@sentry/src/tracing/errors.ts","../../../node_modules/@sentry/src/utils/handleCallbackErrors.ts","../../../node_modules/@sentry/src/utils/hasTracingEnabled.ts","../../../node_modules/@sentry/src/tracing/trace.ts","../../../node_modules/@sentry/src/semanticAttributes.ts","../../../node_modules/@sentry/src/metrics/metric-summary.ts","../../../node_modules/@sentry/src/tracing/span.ts","../../../node_modules/@sentry/src/tracing/transaction.ts","../../../node_modules/@sentry/src/tracing/idletransaction.ts","../../../node_modules/@sentry/src/tracing/sampling.ts","../../../node_modules/@sentry/src/tracing/hubextensions.ts","../../../node_modules/@sentry/src/tracing/measurement.ts","../../../node_modules/@sentry/src/integration.ts","../../../node_modules/@sentry/src/api.ts","../../../node_modules/@sentry/src/envelope.ts","../../../node_modules/@sentry/src/metrics/utils.ts","../../../node_modules/@sentry/src/metrics/envelope.ts","../../../node_modules/@sentry/src/baseclient.ts","../../../node_modules/@sentry/src/sdk.ts","../../../node_modules/@sentry/src/transports/base.ts","../../../node_modules/@sentry/src/transports/multiplexed.ts","../../../node_modules/@sentry/src/utils/parameterize.ts","../../../node_modules/@sentry/src/metadata.ts","../../../node_modules/@sentry/src/integrations/metadata.ts","../../../node_modules/@sentry/src/integrations/inboundfilters.ts","../../../node_modules/@sentry/src/integrations/functiontostring.ts","../../../node_modules/@sentry/src/metrics/constants.ts","../../../node_modules/@sentry/src/metrics/instance.ts","../../../node_modules/@sentry/src/metrics/browser-aggregator.ts","../../../node_modules/@sentry/src/metrics/integration.ts","../../../node_modules/@sentry/src/metrics/exports.ts","../../../node_modules/@sentry/src/sessionflusher.ts","../../../node_modules/@sentry/src/checkin.ts","../../../node_modules/@sentry/src/metrics/aggregator.ts","../../../node_modules/@sentry/src/server-runtime-client.ts","../../../node_modules/@sentry/src/transports/offline.ts","../../../node_modules/@sentry/src/span.ts","../../../node_modules/@sentry/src/utils/isSentryRequestUrl.ts","../../../node_modules/@sentry/src/utils/sdkMetadata.ts","../../../node_modules/@sentry/src/integrations/requestdata.ts","../../../node_modules/@sentry/src/integrations/linkederrors.ts","../../../node_modules/@sentry/src/index.ts","../../../node_modules/@sentry-internal/src/common/fetch.ts","../../../node_modules/@sentry-internal/src/common/debug-build.ts","../../../node_modules/@sentry-internal/src/browser/web-vitals/lib/bindReporter.ts","../../../node_modules/@sentry-internal/src/browser/types.ts","../../../node_modules/@sentry-internal/src/browser/web-vitals/lib/generateUniqueID.ts","../../../node_modules/@sentry-internal/src/browser/web-vitals/lib/getNavigationEntry.ts","../../../node_modules/@sentry-internal/src/browser/web-vitals/lib/getActivationStart.ts","../../../node_modules/@sentry-internal/src/browser/web-vitals/lib/initMetric.ts","../../../node_modules/@sentry-internal/src/browser/web-vitals/lib/observe.ts","../../../node_modules/@sentry-internal/src/browser/web-vitals/lib/onHidden.ts","../../../node_modules/@sentry-internal/src/browser/web-vitals/getCLS.ts","../../../node_modules/@sentry-internal/src/browser/web-vitals/lib/getVisibilityWatcher.ts","../../../node_modules/@sentry-internal/src/browser/web-vitals/getFID.ts","../../../node_modules/@sentry-internal/src/browser/web-vitals/lib/polyfills/interactionCountPolyfill.ts","../../../node_modules/@sentry-internal/src/browser/web-vitals/getINP.ts","../../../node_modules/@sentry-internal/src/browser/web-vitals/getLCP.ts","../../../node_modules/@sentry-internal/src/browser/web-vitals/onTTFB.ts","../../../node_modules/@sentry-internal/src/browser/instrument.ts","../../../node_modules/@sentry-internal/src/browser/request.ts","../../../node_modules/@sentry-internal/src/browser/backgroundtab.ts","../../../node_modules/@sentry-internal/src/browser/metrics/utils.ts","../../../node_modules/@sentry-internal/src/browser/metrics/index.ts","../../../node_modules/@sentry-internal/src/browser/router.ts","../../../node_modules/@sentry-internal/src/browser/browsertracing.ts","../../../node_modules/@sentry-internal/src/browser/browserTracingIntegration.ts","../../../node_modules/@sentry-internal/tracing/esm/index.js","../../../node_modules/@sentry-internal/src/node/integrations/utils/node-utils.ts","../../../node_modules/@sentry-internal/src/node/integrations/express.ts","../../../node_modules/@sentry-internal/src/node/integrations/postgres.ts","../../../node_modules/@sentry-internal/src/node/integrations/mysql.ts","../../../node_modules/@sentry-internal/src/node/integrations/mongo.ts","../../../node_modules/@sentry-internal/src/node/integrations/prisma.ts","../../../node_modules/@sentry-internal/src/node/integrations/graphql.ts","../../../node_modules/@sentry-internal/src/node/integrations/apollo.ts","../../../node_modules/src/captureconsole.ts","../../../node_modules/src/debug.ts","../../../node_modules/src/debug-build.ts","../../../node_modules/src/dedupe.ts","../../../node_modules/src/extraerrordata.ts","../../../node_modules/src/reportingobserver.ts","../../../node_modules/src/rewriteframes.ts","../../../node_modules/src/sessiontiming.ts","../../../node_modules/src/httpclient.ts","../../../node_modules/src/contextlines.ts","../../../node_modules/@sentry/integrations/esm/index.js"],"sourcesContent":["export { applyAggregateErrorsToEvent } from './aggregate-errors.js';\nexport { getComponentName, getDomElement, getLocationHref, htmlTreeAsString } from './browser.js';\nexport { dsnFromString, dsnToString, makeDsn } from './dsn.js';\nexport { SentryError } from './error.js';\nexport { GLOBAL_OBJ, getGlobalObject, getGlobalSingleton } from './worldwide.js';\nexport { addInstrumentationHandler } from './instrument/index.js';\nexport { isDOMError, isDOMException, isElement, isError, isErrorEvent, isEvent, isInstanceOf, isNaN, isParameterizedString, isPlainObject, isPrimitive, isRegExp, isString, isSyntheticEvent, isThenable, isVueViewModel } from './is.js';\nexport { isBrowser } from './isBrowser.js';\nexport { CONSOLE_LEVELS, consoleSandbox, logger, originalConsoleMethods } from './logger.js';\nexport { memoBuilder } from './memo.js';\nexport { addContextToFrame, addExceptionMechanism, addExceptionTypeValue, arrayify, checkOrSetAlreadyCaught, getEventDescription, parseSemver, uuid4 } from './misc.js';\nexport { dynamicRequire, isNodeEnv, loadModule } from './node.js';\nexport { normalize, normalizeToSize, normalizeUrlToBase, walk } from './normalize.js';\nexport { addNonEnumerableProperty, convertToPlainObject, dropUndefinedKeys, extractExceptionKeysForMessage, fill, getOriginalFunction, markFunctionWrapped, objectify, urlEncode } from './object.js';\nexport { basename, dirname, isAbsolute, join, normalizePath, relative, resolve } from './path.js';\nexport { makePromiseBuffer } from './promisebuffer.js';\nexport { DEFAULT_USER_INCLUDES, addRequestDataToEvent, addRequestDataToTransaction, extractPathForTransaction, extractRequestData, winterCGHeadersToDict, winterCGRequestToRequestData } from './requestdata.js';\nexport { severityFromString, severityLevelFromString, validSeverityLevels } from './severity.js';\nexport { createStackParser, getFunctionName, nodeStackLineParser, stackParserFromStackParserOptions, stripSentryFramesAndReverse } from './stacktrace.js';\nexport { isMatchingPattern, safeJoin, snipLine, stringMatchesSomePattern, truncate } from './string.js';\nexport { isNativeFetch, supportsDOMError, supportsDOMException, supportsErrorEvent, supportsFetch, supportsNativeFetch, supportsReferrerPolicy, supportsReportingObserver } from './supports.js';\nexport { SyncPromise, rejectedSyncPromise, resolvedSyncPromise } from './syncpromise.js';\nexport { _browserPerformanceTimeOriginMode, browserPerformanceTimeOrigin, dateTimestampInSeconds, timestampInSeconds, timestampWithMs } from './time.js';\nexport { TRACEPARENT_REGEXP, extractTraceparentData, generateSentryTraceHeader, propagationContextFromHeaders, tracingContextFromHeaders } from './tracing.js';\nexport { getSDKSource, isBrowserBundle } from './env.js';\nexport { addItemToEnvelope, createAttachmentEnvelopeItem, createEnvelope, createEventEnvelopeHeaders, envelopeContainsItemType, envelopeItemTypeToDataCategory, forEachEnvelopeItem, getSdkMetadataForEnvelopeHeader, parseEnvelope, serializeEnvelope } from './envelope.js';\nexport { createClientReportEnvelope } from './clientreport.js';\nexport { DEFAULT_RETRY_AFTER, disabledUntil, isRateLimited, parseRetryAfterHeader, updateRateLimits } from './ratelimit.js';\nexport { BAGGAGE_HEADER_NAME, MAX_BAGGAGE_STRING_LENGTH, SENTRY_BAGGAGE_KEY_PREFIX, SENTRY_BAGGAGE_KEY_PREFIX_REGEX, baggageHeaderToDynamicSamplingContext, dynamicSamplingContextToSentryBaggageHeader } from './baggage.js';\nexport { getNumberOfUrlSegments, getSanitizedUrlString, parseUrl, stripUrlQueryAndFragment } from './url.js';\nexport { addOrUpdateIntegration } from './userIntegrations.js';\nexport { makeFifoCache } from './cache.js';\nexport { eventFromMessage, eventFromUnknownInput, exceptionFromError, parseStackFrames } from './eventbuilder.js';\nexport { callFrameToStackFrame, watchdogTimer } from './anr.js';\nexport { LRUMap } from './lru.js';\nexport { _asyncNullishCoalesce } from './buildPolyfills/_asyncNullishCoalesce.js';\nexport { _asyncOptionalChain } from './buildPolyfills/_asyncOptionalChain.js';\nexport { _asyncOptionalChainDelete } from './buildPolyfills/_asyncOptionalChainDelete.js';\nexport { _nullishCoalesce } from './buildPolyfills/_nullishCoalesce.js';\nexport { _optionalChain } from './buildPolyfills/_optionalChain.js';\nexport { _optionalChainDelete } from './buildPolyfills/_optionalChainDelete.js';\nexport { addConsoleInstrumentationHandler } from './instrument/console.js';\nexport { addClickKeypressInstrumentationHandler } from './instrument/dom.js';\nexport { SENTRY_XHR_DATA_KEY, addXhrInstrumentationHandler } from './instrument/xhr.js';\nexport { addFetchInstrumentationHandler } from './instrument/fetch.js';\nexport { addHistoryInstrumentationHandler } from './instrument/history.js';\nexport { addGlobalErrorInstrumentationHandler } from './instrument/globalError.js';\nexport { addGlobalUnhandledRejectionInstrumentationHandler } from './instrument/globalUnhandledRejection.js';\nexport { resetInstrumentationHandlers } from './instrument/_handlers.js';\nexport { filenameIsInApp } from './node-stack-trace.js';\nexport { escapeStringForRegex } from './vendor/escapeStringForRegex.js';\nexport { supportsHistory } from './vendor/supportsHistory.js';\n//# sourceMappingURL=index.js.map\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/explicit-module-boundary-types */\n\nimport type { ParameterizedString, PolymorphicEvent, Primitive } from '@sentry/types';\n\n// eslint-disable-next-line @typescript-eslint/unbound-method\nconst objectToString = Object.prototype.toString;\n\n/**\n * Checks whether given value's type is one of a few Error or Error-like\n * {@link isError}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isError(wat: unknown): wat is Error {\n switch (objectToString.call(wat)) {\n case '[object Error]':\n case '[object Exception]':\n case '[object DOMException]':\n return true;\n default:\n return isInstanceOf(wat, Error);\n }\n}\n/**\n * Checks whether given value is an instance of the given built-in class.\n *\n * @param wat The value to be checked\n * @param className\n * @returns A boolean representing the result.\n */\nfunction isBuiltin(wat: unknown, className: string): boolean {\n return objectToString.call(wat) === `[object ${className}]`;\n}\n\n/**\n * Checks whether given value's type is ErrorEvent\n * {@link isErrorEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isErrorEvent(wat: unknown): boolean {\n return isBuiltin(wat, 'ErrorEvent');\n}\n\n/**\n * Checks whether given value's type is DOMError\n * {@link isDOMError}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isDOMError(wat: unknown): boolean {\n return isBuiltin(wat, 'DOMError');\n}\n\n/**\n * Checks whether given value's type is DOMException\n * {@link isDOMException}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isDOMException(wat: unknown): boolean {\n return isBuiltin(wat, 'DOMException');\n}\n\n/**\n * Checks whether given value's type is a string\n * {@link isString}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isString(wat: unknown): wat is string {\n return isBuiltin(wat, 'String');\n}\n\n/**\n * Checks whether given string is parameterized\n * {@link isParameterizedString}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isParameterizedString(wat: unknown): wat is ParameterizedString {\n return (\n typeof wat === 'object' &&\n wat !== null &&\n '__sentry_template_string__' in wat &&\n '__sentry_template_values__' in wat\n );\n}\n\n/**\n * Checks whether given value is a primitive (undefined, null, number, boolean, string, bigint, symbol)\n * {@link isPrimitive}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isPrimitive(wat: unknown): wat is Primitive {\n return wat === null || isParameterizedString(wat) || (typeof wat !== 'object' && typeof wat !== 'function');\n}\n\n/**\n * Checks whether given value's type is an object literal, or a class instance.\n * {@link isPlainObject}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isPlainObject(wat: unknown): wat is Record<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): wat is PolymorphicEvent {\n return typeof Event !== 'undefined' && isInstanceOf(wat, Event);\n}\n\n/**\n * Checks whether given value's type is an Element instance\n * {@link isElement}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isElement(wat: unknown): boolean {\n return typeof Element !== 'undefined' && isInstanceOf(wat, Element);\n}\n\n/**\n * Checks whether given value's type is an regexp\n * {@link isRegExp}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isRegExp(wat: unknown): wat is RegExp {\n return isBuiltin(wat, 'RegExp');\n}\n\n/**\n * Checks whether given value has a then function.\n * @param wat A value to be checked.\n */\nexport function isThenable(wat: any): wat is PromiseLike<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\ninterface VueViewModel {\n // Vue3\n __isVue?: boolean;\n // Vue2\n _isVue?: boolean;\n}\n/**\n * Checks whether given value's type is a Vue ViewModel.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isVueViewModel(wat: unknown): boolean {\n // Not using Object.prototype.toString because in Vue 3 it would read the instance's Symbol(Symbol.toStringTag) property.\n return !!(typeof wat === 'object' && wat !== null && ((wat as VueViewModel).__isVue || (wat as VueViewModel)._isVue));\n}\n","import { isRegExp, isString, isVueViewModel } from './is';\n\nexport { escapeStringForRegex } from './vendor/escapeStringForRegex';\n\n/**\n * Truncates given string to the maximum characters count\n *\n * @param str An object that contains serializable values\n * @param max Maximum number of characters in truncated string (0 = unlimited)\n * @returns string Encoded\n */\nexport function truncate(str: string, max: number = 0): string {\n if (typeof str !== 'string' || max === 0) {\n return str;\n }\n return str.length <= max ? str : `${str.slice(0, max)}...`;\n}\n\n/**\n * This is basically just `trim_line` from\n * https://github.com/getsentry/sentry/blob/master/src/sentry/lang/javascript/processor.py#L67\n *\n * @param str An object that contains serializable values\n * @param max Maximum number of characters in truncated string\n * @returns string Encoded\n */\nexport function snipLine(line: string, colno: number): string {\n let newLine = line;\n const lineLength = newLine.length;\n if (lineLength <= 150) {\n return newLine;\n }\n if (colno > lineLength) {\n // eslint-disable-next-line no-param-reassign\n colno = lineLength;\n }\n\n let start = Math.max(colno - 60, 0);\n if (start < 5) {\n start = 0;\n }\n\n let end = Math.min(start + 140, lineLength);\n if (end > lineLength - 5) {\n end = lineLength;\n }\n if (end === lineLength) {\n start = Math.max(end - 140, 0);\n }\n\n newLine = newLine.slice(start, end);\n if (start > 0) {\n newLine = `'{snip} ${newLine}`;\n }\n if (end < lineLength) {\n newLine += ' {snip}';\n }\n\n return newLine;\n}\n\n/**\n * Join values in array\n * @param input array of values to be joined together\n * @param delimiter string to be placed in-between values\n * @returns Joined values\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function safeJoin(input: any[], delimiter?: string): string {\n if (!Array.isArray(input)) {\n return '';\n }\n\n const output = [];\n // eslint-disable-next-line @typescript-eslint/prefer-for-of\n for (let i = 0; i < input.length; i++) {\n const value = input[i];\n try {\n // This is a hack to fix a Vue3-specific bug that causes an infinite loop of\n // console warnings. This happens when a Vue template is rendered with\n // an undeclared variable, which we try to stringify, ultimately causing\n // Vue to issue another warning which repeats indefinitely.\n // see: https://github.com/getsentry/sentry-javascript/pull/8981\n if (isVueViewModel(value)) {\n output.push('[VueViewModel]');\n } else {\n output.push(String(value));\n }\n } catch (e) {\n output.push('[value cannot be serialized]');\n }\n }\n\n return output.join(delimiter);\n}\n\n/**\n * Checks if the given value matches a regex or string\n *\n * @param value The string to test\n * @param pattern Either a regex or a string against which `value` will be matched\n * @param requireExactStringMatch If true, `value` must match `pattern` exactly. If false, `value` will match\n * `pattern` if it contains `pattern`. Only applies to string-type patterns.\n */\nexport function isMatchingPattern(\n value: string,\n pattern: RegExp | string,\n requireExactStringMatch: boolean = false,\n): boolean {\n if (!isString(value)) {\n return false;\n }\n\n if (isRegExp(pattern)) {\n return pattern.test(value);\n }\n if (isString(pattern)) {\n return requireExactStringMatch ? value === pattern : value.includes(pattern);\n }\n\n return false;\n}\n\n/**\n * Test the given string against an array of strings and regexes. By default, string matching is done on a\n * substring-inclusion basis rather than a strict equality basis\n *\n * @param testString The string to test\n * @param patterns The patterns against which to test the string\n * @param requireExactStringMatch If true, `testString` must match one of the given string patterns exactly in order to\n * count. If false, `testString` will match a string pattern if it contains that pattern.\n * @returns\n */\nexport function stringMatchesSomePattern(\n testString: string,\n patterns: Array<string | RegExp> = [],\n requireExactStringMatch: boolean = false,\n): boolean {\n return patterns.some(pattern => isMatchingPattern(testString, pattern, requireExactStringMatch));\n}\n","import type { Event, EventHint, Exception, ExtendedError, StackParser } from '@sentry/types';\n\nimport { isInstanceOf } from './is';\nimport { truncate } from './string';\n\n/**\n * Creates exceptions inside `event.exception.values` for errors that are nested on properties based on the `key` parameter.\n */\nexport function applyAggregateErrorsToEvent(\n exceptionFromErrorImplementation: (stackParser: StackParser, ex: Error) => Exception,\n parser: StackParser,\n maxValueLimit: number = 250,\n key: string,\n limit: number,\n event: Event,\n hint?: EventHint,\n): void {\n if (!event.exception || !event.exception.values || !hint || !isInstanceOf(hint.originalException, Error)) {\n return;\n }\n\n // Generally speaking the last item in `event.exception.values` is the exception originating from the original Error\n const originalException: Exception | undefined =\n event.exception.values.length > 0 ? event.exception.values[event.exception.values.length - 1] : undefined;\n\n // We only create exception grouping if there is an exception in the event.\n if (originalException) {\n event.exception.values = truncateAggregateExceptions(\n aggregateExceptionsFromError(\n exceptionFromErrorImplementation,\n parser,\n limit,\n hint.originalException as ExtendedError,\n key,\n event.exception.values,\n originalException,\n 0,\n ),\n maxValueLimit,\n );\n }\n}\n\nfunction aggregateExceptionsFromError(\n exceptionFromErrorImplementation: (stackParser: StackParser, ex: Error) => Exception,\n parser: StackParser,\n limit: number,\n error: ExtendedError,\n key: string,\n prevExceptions: Exception[],\n exception: Exception,\n exceptionId: number,\n): Exception[] {\n if (prevExceptions.length >= limit + 1) {\n return prevExceptions;\n }\n\n let newExceptions = [...prevExceptions];\n\n // Recursively call this function in order to walk down a chain of errors\n if (isInstanceOf(error[key], Error)) {\n applyExceptionGroupFieldsForParentException(exception, exceptionId);\n const newException = exceptionFromErrorImplementation(parser, error[key]);\n const newExceptionId = newExceptions.length;\n applyExceptionGroupFieldsForChildException(newException, key, newExceptionId, exceptionId);\n newExceptions = aggregateExceptionsFromError(\n exceptionFromErrorImplementation,\n parser,\n limit,\n error[key],\n key,\n [newException, ...newExceptions],\n newException,\n newExceptionId,\n );\n }\n\n // This will create exception grouping for AggregateErrors\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AggregateError\n if (Array.isArray(error.errors)) {\n error.errors.forEach((childError, i) => {\n if (isInstanceOf(childError, Error)) {\n applyExceptionGroupFieldsForParentException(exception, exceptionId);\n const newException = exceptionFromErrorImplementation(parser, childError);\n const newExceptionId = newExceptions.length;\n applyExceptionGroupFieldsForChildException(newException, `errors[${i}]`, newExceptionId, exceptionId);\n newExceptions = aggregateExceptionsFromError(\n exceptionFromErrorImplementation,\n parser,\n limit,\n childError,\n key,\n [newException, ...newExceptions],\n newException,\n newExceptionId,\n );\n }\n });\n }\n\n return newExceptions;\n}\n\nfunction applyExceptionGroupFieldsForParentException(exception: Exception, exceptionId: number): void {\n // Don't know if this default makes sense. The protocol requires us to set these values so we pick *some* default.\n exception.mechanism = exception.mechanism || { type: 'generic', handled: true };\n\n exception.mechanism = {\n ...exception.mechanism,\n ...(exception.type === 'AggregateError' && { is_exception_group: true }),\n exception_id: exceptionId,\n };\n}\n\nfunction applyExceptionGroupFieldsForChildException(\n exception: Exception,\n source: string,\n exceptionId: number,\n parentId: number | undefined,\n): void {\n // Don't know if this default makes sense. The protocol requires us to set these values so we pick *some* default.\n exception.mechanism = exception.mechanism || { type: 'generic', handled: true };\n\n exception.mechanism = {\n ...exception.mechanism,\n type: 'chained',\n source,\n exception_id: exceptionId,\n parent_id: parentId,\n };\n}\n\n/**\n * Truncate the message (exception.value) of all exceptions in the event.\n * Because this event processor is ran after `applyClientOptions`,\n * we need to truncate the message of the added exceptions here.\n */\nfunction truncateAggregateExceptions(exceptions: Exception[], maxValueLength: number): Exception[] {\n return exceptions.map(exception => {\n if (exception.value) {\n exception.value = truncate(exception.value, maxValueLength);\n }\n return exception;\n });\n}\n","/**\n * NOTE: In order to avoid circular dependencies, if you add a function to this module and it needs to print something,\n * you must either a) use `console.log` rather than the logger, or b) put your function elsewhere.\n *\n * Note: This file was originally called `global.ts`, but was changed to unblock users which might be doing\n * string replaces with bundlers like Vite for `global` (would break imports that rely on importing from utils/src/global).\n *\n * Why worldwide?\n *\n * Why not?\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport type { Integration } from '@sentry/types';\n\nimport type { SdkSource } from './env';\n\n/** Internal global with common properties and Sentry extensions */\nexport interface InternalGlobal {\n navigator?: { userAgent?: string };\n console: Console;\n Sentry?: {\n Integrations?: Integration[];\n };\n onerror?: {\n (event: object | string, source?: string, lineno?: number, colno?: number, error?: Error): any;\n __SENTRY_INSTRUMENTED__?: true;\n __SENTRY_LOADER__?: true;\n };\n onunhandledrejection?: {\n (event: unknown): boolean;\n __SENTRY_INSTRUMENTED__?: true;\n __SENTRY_LOADER__?: true;\n };\n SENTRY_ENVIRONMENT?: string;\n SENTRY_DSN?: string;\n SENTRY_RELEASE?: {\n id?: string;\n };\n SENTRY_SDK_SOURCE?: SdkSource;\n /**\n * Debug IDs are indirectly injected by Sentry CLI or bundler plugins to directly reference a particular source map\n * for resolving of a source file. The injected code will place an entry into the record for each loaded bundle/JS\n * file.\n */\n _sentryDebugIds?: Record<string, string>;\n __SENTRY__: {\n globalEventProcessors: any;\n hub: any;\n logger: any;\n extensions?: {\n /** Extension methods for the hub, which are bound to the current Hub instance */\n // eslint-disable-next-line @typescript-eslint/ban-types\n [key: string]: Function;\n };\n };\n /**\n * Raw module metadata that is injected by bundler plugins.\n *\n * Keys are `error.stack` strings, values are the metadata.\n */\n _sentryModuleMetadata?: Record<string, any>;\n}\n\n// The code below for 'isGlobalObj' and 'GLOBAL_OBJ' was copied from core-js before modification\n// https://github.com/zloirock/core-js/blob/1b944df55282cdc99c90db5f49eb0b6eda2cc0a3/packages/core-js/internals/global.js\n// core-js has the following licence:\n//\n// Copyright (c) 2014-2022 Denis Pushkarev\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n/** Returns 'obj' if it's the global object, otherwise returns undefined */\nfunction isGlobalObj(obj: { Math?: Math }): any | undefined {\n return obj && obj.Math == Math ? obj : undefined;\n}\n\n/** Get's the global object for the current JavaScript runtime */\nexport const GLOBAL_OBJ: InternalGlobal =\n (typeof globalThis == 'object' && isGlobalObj(globalThis)) ||\n // eslint-disable-next-line no-restricted-globals\n (typeof window == 'object' && isGlobalObj(window)) ||\n (typeof self == 'object' && isGlobalObj(self)) ||\n (typeof global == 'object' && isGlobalObj(global)) ||\n (function (this: any) {\n return this;\n })() ||\n {};\n\n/**\n * @deprecated Use GLOBAL_OBJ instead or WINDOW from @sentry/browser. This will be removed in v8\n */\nexport function getGlobalObject<T>(): T & InternalGlobal {\n return GLOBAL_OBJ as T & InternalGlobal;\n}\n\n/**\n * Returns a global singleton contained in the global `__SENTRY__` object.\n *\n * If the singleton doesn't already exist in `__SENTRY__`, it will be created using the given factory\n * function and added to the `__SENTRY__` object.\n *\n * @param name name of the global singleton on __SENTRY__\n * @param creator creator Factory function to create the singleton if it doesn't already exist on `__SENTRY__`\n * @param obj (Optional) The global object on which to look for `__SENTRY__`, if not `GLOBAL_OBJ`'s return value\n * @returns the singleton\n */\nexport function getGlobalSingleton<T>(name: keyof InternalGlobal['__SENTRY__'], creator: () => T, obj?: unknown): T {\n const gbl = (obj || GLOBAL_OBJ) as InternalGlobal;\n const __SENTRY__ = (gbl.__SENTRY__ = gbl.__SENTRY__ || {});\n const singleton = __SENTRY__[name] || (__SENTRY__[name] = creator());\n return singleton;\n}\n","import { isString } from './is';\nimport { getGlobalObject } from './worldwide';\n\n// eslint-disable-next-line deprecation/deprecation\nconst WINDOW = getGlobalObject<Window>();\n\nconst DEFAULT_MAX_STRING_LENGTH = 80;\n\ntype SimpleNode = {\n parentNode: SimpleNode;\n} | null;\n\n/**\n * Given a child DOM element, returns a query-selector statement describing that\n * and its ancestors\n * e.g. [HTMLElement] => body > div > input#foo.btn[name=baz]\n * @returns generated DOM path\n */\nexport function htmlTreeAsString(\n elem: unknown,\n options: string[] | { keyAttrs?: string[]; maxStringLength?: number } = {},\n): string {\n if (!elem) {\n return '<unknown>';\n }\n\n // try/catch both:\n // - accessing event.target (see getsentry/raven-js#838, #768)\n // - `htmlTreeAsString` because it's complex, and just accessing the DOM incorrectly\n // - can throw an exception in some circumstances.\n try {\n let currentElem = elem as SimpleNode;\n const MAX_TRAVERSE_HEIGHT = 5;\n const out = [];\n let height = 0;\n let len = 0;\n const separator = ' > ';\n const sepLength = separator.length;\n let nextStr;\n const keyAttrs = Array.isArray(options) ? options : options.keyAttrs;\n const maxStringLength = (!Array.isArray(options) && options.maxStringLength) || DEFAULT_MAX_STRING_LENGTH;\n\n while (currentElem && height++ < MAX_TRAVERSE_HEIGHT) {\n nextStr = _htmlElementAsString(currentElem, keyAttrs);\n // bail out if\n // - nextStr is the 'html' element\n // - the length of the string that would be created exceeds maxStringLength\n // (ignore this limit if we are on the first iteration)\n if (nextStr === 'html' || (height > 1 && len + out.length * sepLength + nextStr.length >= maxStringLength)) {\n break;\n }\n\n out.push(nextStr);\n\n len += nextStr.length;\n currentElem = currentElem.parentNode;\n }\n\n return out.reverse().join(separator);\n } catch (_oO) {\n return '<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 // @ts-expect-error WINDOW has HTMLElement\n if (WINDOW.HTMLElement) {\n // If using the component name annotation plugin, this value may be available on the DOM node\n if (elem instanceof HTMLElement && elem.dataset && elem.dataset['sentryComponent']) {\n return elem.dataset['sentryComponent'];\n }\n }\n\n out.push(elem.tagName.toLowerCase());\n\n // Pairs of attribute keys defined in `serializeAttribute` and their values on element.\n const keyAttrPairs =\n keyAttrs && keyAttrs.length\n ? keyAttrs.filter(keyAttr => elem.getAttribute(keyAttr)).map(keyAttr => [keyAttr, elem.getAttribute(keyAttr)])\n : null;\n\n if (keyAttrPairs && keyAttrPairs.length) {\n keyAttrPairs.forEach(keyAttrPair => {\n out.push(`[${keyAttrPair[0]}=\"${keyAttrPair[1]}\"]`);\n });\n } else {\n if (elem.id) {\n out.push(`#${elem.id}`);\n }\n\n // eslint-disable-next-line prefer-const\n className = elem.className;\n if (className && isString(className)) {\n classes = className.split(/\\s+/);\n for (i = 0; i < classes.length; i++) {\n out.push(`.${classes[i]}`);\n }\n }\n }\n const allowedAttrs = ['aria-label', 'type', 'name', 'title', 'alt'];\n for (i = 0; i < allowedAttrs.length; i++) {\n key = allowedAttrs[i];\n attr = elem.getAttribute(key);\n if (attr) {\n out.push(`[${key}=\"${attr}\"]`);\n }\n }\n return out.join('');\n}\n\n/**\n * A safe form of location.href\n */\nexport function getLocationHref(): string {\n try {\n return WINDOW.document.location.href;\n } catch (oO) {\n return '';\n }\n}\n\n/**\n * Gets a DOM element by using document.querySelector.\n *\n * This wrapper will first check for the existance of the function before\n * actually calling it so that we don't have to take care of this check,\n * every time we want to access the DOM.\n *\n * Reason: DOM/querySelector is not available in all environments.\n *\n * We have to cast to any because utils can be consumed by a variety of environments,\n * and we don't want to break TS users. If you know what element will be selected by\n * `document.querySelector`, specify it as part of the generic call. For example,\n * `const element = getDomElement<Element>('selector');`\n *\n * @param selector the selector string passed on to document.querySelector\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function getDomElement<E = any>(selector: string): E | null {\n if (WINDOW.document && WINDOW.document.querySelector) {\n return WINDOW.document.querySelector(selector) as unknown as E;\n }\n return null;\n}\n\n/**\n * Given a DOM element, traverses up the tree until it finds the first ancestor node\n * that has the `data-sentry-component` attribute. This attribute is added at build-time\n * by projects that have the component name annotation plugin installed.\n *\n * @returns a string representation of the component for the provided DOM element, or `null` if not found\n */\nexport function getComponentName(elem: unknown): string | null {\n // @ts-expect-error WINDOW has HTMLElement\n if (!WINDOW.HTMLElement) {\n return null;\n }\n\n let currentElem = elem as SimpleNode;\n const MAX_TRAVERSE_HEIGHT = 5;\n for (let i = 0; i < MAX_TRAVERSE_HEIGHT; i++) {\n if (!currentElem) {\n return null;\n }\n\n if (currentElem instanceof HTMLElement && currentElem.dataset['sentryComponent']) {\n return currentElem.dataset['sentryComponent'];\n }\n\n currentElem = currentElem.parentNode;\n }\n\n return null;\n}\n","declare const __DEBUG_BUILD__: boolean;\n\n/**\n * This serves as a build time flag that will be true by default, but false in non-debug builds or if users replace `__SENTRY_DEBUG__` in their generated code.\n *\n * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking.\n */\nexport const DEBUG_BUILD = __DEBUG_BUILD__;\n","import type { ConsoleLevel } from '@sentry/types';\n\nimport { DEBUG_BUILD } from './debug-build';\nimport { GLOBAL_OBJ } from './worldwide';\n\n/** Prefix for logging strings */\nconst PREFIX = 'Sentry Logger ';\n\nexport const CONSOLE_LEVELS: readonly ConsoleLevel[] = [\n 'debug',\n 'info',\n 'warn',\n 'error',\n 'log',\n 'assert',\n 'trace',\n] as const;\n\ntype LoggerMethod = (...args: unknown[]) => void;\ntype LoggerConsoleMethods = Record<ConsoleLevel, LoggerMethod>;\n\n/** This may be mutated by the console instrumentation. */\nexport const originalConsoleMethods: {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key in ConsoleLevel]?: (...args: any[]) => void;\n} = {};\n\n/** JSDoc */\ninterface Logger extends LoggerConsoleMethods {\n disable(): void;\n enable(): void;\n isEnabled(): boolean;\n}\n\n/**\n * Temporarily disable sentry console instrumentations.\n *\n * @param callback The function to run against the original `console` messages\n * @returns The results of the callback\n */\nexport function consoleSandbox<T>(callback: () => T): T {\n if (!('console' in GLOBAL_OBJ)) {\n return callback();\n }\n\n const console = GLOBAL_OBJ.console as Console;\n const wrappedFuncs: Partial<LoggerConsoleMethods> = {};\n\n const wrappedLevels = Object.keys(originalConsoleMethods) as ConsoleLevel[];\n\n // Restore all wrapped console methods\n wrappedLevels.forEach(level => {\n const originalConsoleMethod = originalConsoleMethods[level] as LoggerMethod;\n wrappedFuncs[level] = console[level] as LoggerMethod | undefined;\n console[level] = originalConsoleMethod;\n });\n\n try {\n return callback();\n } finally {\n // Revert restoration to wrapped state\n wrappedLevels.forEach(level => {\n console[level] = wrappedFuncs[level] as LoggerMethod;\n });\n }\n}\n\nfunction makeLogger(): Logger {\n let enabled = false;\n const logger: Partial<Logger> = {\n enable: () => {\n enabled = true;\n },\n disable: () => {\n enabled = false;\n },\n isEnabled: () => enabled,\n };\n\n if (DEBUG_BUILD) {\n CONSOLE_LEVELS.forEach(name => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n logger[name] = (...args: any[]) => {\n if (enabled) {\n consoleSandbox(() => {\n GLOBAL_OBJ.console[name](`${PREFIX}[${name}]:`, ...args);\n });\n }\n };\n });\n } else {\n CONSOLE_LEVELS.forEach(name => {\n logger[name] = () => undefined;\n });\n }\n\n return logger as Logger;\n}\n\nexport const logger = makeLogger();\n","import type { DsnComponents, DsnLike, DsnProtocol } from '@sentry/types';\n\nimport { DEBUG_BUILD } from './debug-build';\nimport { consoleSandbox, logger } from './logger';\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\n/**\n * Parses a Dsn from a given string.\n *\n * @param str A Dsn as string\n * @returns Dsn as DsnComponents or undefined if @param str is not a valid DSN string\n */\nexport function dsnFromString(str: string): DsnComponents | undefined {\n const match = DSN_REGEX.exec(str);\n\n if (!match) {\n // This should be logged to the console\n consoleSandbox(() => {\n // eslint-disable-next-line no-console\n console.error(`Invalid Sentry Dsn: ${str}`);\n });\n return undefined;\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 return {\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 {\n if (!DEBUG_BUILD) {\n return true;\n }\n\n const { port, projectId, protocol } = dsn;\n\n const requiredComponents: ReadonlyArray<keyof DsnComponents> = ['protocol', 'publicKey', 'host', 'projectId'];\n const hasMissingRequiredComponent = requiredComponents.find(component => {\n if (!dsn[component]) {\n logger.error(`Invalid Sentry Dsn: ${component} missing`);\n return true;\n }\n return false;\n });\n\n if (hasMissingRequiredComponent) {\n return false;\n }\n\n if (!projectId.match(/^\\d+$/)) {\n logger.error(`Invalid Sentry Dsn: Invalid projectId ${projectId}`);\n return false;\n }\n\n if (!isValidProtocol(protocol)) {\n logger.error(`Invalid Sentry Dsn: Invalid protocol ${protocol}`);\n return false;\n }\n\n if (port && isNaN(parseInt(port, 10))) {\n logger.error(`Invalid Sentry Dsn: Invalid port ${port}`);\n return false;\n }\n\n return true;\n}\n\n/**\n * Creates a valid Sentry Dsn object, identifying a Sentry instance and project.\n * @returns a valid DsnComponents object or `undefined` if @param from is an invalid DSN source\n */\nexport function makeDsn(from: DsnLike): DsnComponents | undefined {\n const components = typeof from === 'string' ? dsnFromString(from) : dsnFromComponents(from);\n if (!components || !validateDsn(components)) {\n return undefined;\n }\n return components;\n}\n","import type { ConsoleLevel } from '@sentry/types';\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 logLevel: ConsoleLevel;\n\n public constructor(public message: string, logLevel: ConsoleLevel = 'warn') {\n super(message);\n\n this.name = new.target.prototype.constructor.name;\n // This sets the prototype to be `Error`, not `SentryError`. It's unclear why we do this, but commenting this line\n // out causes various (seemingly totally unrelated) playwright tests consistently time out. FYI, this makes\n // instances of `SentryError` fail `obj instanceof SentryError` checks.\n Object.setPrototypeOf(this, new.target.prototype);\n this.logLevel = logLevel;\n }\n}\n","/* eslint-disable max-lines */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { WrappedFunction } from '@sentry/types';\n\nimport { htmlTreeAsString } from './browser';\nimport { DEBUG_BUILD } from './debug-build';\nimport { isElement, isError, isEvent, isInstanceOf, isPlainObject, isPrimitive } from './is';\nimport { logger } from './logger';\nimport { truncate } from './string';\n\n/**\n * Replace a method in an object with a wrapped version of itself.\n *\n * @param source An object that contains a method to be wrapped.\n * @param name The name of the method to be wrapped.\n * @param replacementFactory A higher-order function that takes the original version of the given method and returns a\n * wrapped version. Note: The function returned by `replacementFactory` needs to be a non-arrow function, in order to\n * preserve the correct value of `this`, and the original method must be called using `origMethod.call(this, <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 markFunctionWrapped(wrapped, original);\n }\n\n source[name] = wrapped;\n}\n\n/**\n * Defines a non-enumerable property on the given object.\n *\n * @param obj The object on which to set the property\n * @param name The name of the property to be set\n * @param value The value to which to set the property\n */\nexport function addNonEnumerableProperty(obj: object, name: string, value: unknown): void {\n try {\n Object.defineProperty(obj, name, {\n // enumerable: false, // the default, so we can save on bundle size by not explicitly setting it\n value: value,\n writable: true,\n configurable: true,\n });\n } catch (o_O) {\n DEBUG_BUILD && logger.log(`Failed to add non-enumerable property \"${name}\" to object`, obj);\n }\n}\n\n/**\n * Remembers the original function on the wrapped function and\n * patches up the prototype.\n *\n * @param wrapped the wrapper function\n * @param original the original function that gets wrapped\n */\nexport function markFunctionWrapped(wrapped: WrappedFunction, original: WrappedFunction): void {\n try {\n const proto = original.prototype || {};\n wrapped.prototype = original.prototype = proto;\n addNonEnumerableProperty(wrapped, '__sentry_original__', original);\n } catch (o_O) {} // eslint-disable-line no-empty\n}\n\n/**\n * This extracts the original function if available. See\n * `markFunctionWrapped` for more information.\n *\n * @param func the function to unwrap\n * @returns the unwrapped version of the function if available.\n */\nexport function getOriginalFunction(func: WrappedFunction): WrappedFunction | undefined {\n return func.__sentry_original__;\n}\n\n/**\n * Encodes given object into url-friendly format\n *\n * @param object An object that contains serializable values\n * @returns string Encoded\n */\nexport function urlEncode(object: { [key: string]: any }): string {\n return Object.keys(object)\n .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(object[key])}`)\n .join('&');\n}\n\n/**\n * Transforms any `Error` or `Event` into a plain object with all of their enumerable properties, and some of their\n * non-enumerable properties attached.\n *\n * @param value Initial source that we have to transform in order for it to be usable by the serializer\n * @returns An Event or Error turned into an object - or the value argurment itself, when value is neither an Event nor\n * an Error.\n */\nexport function convertToPlainObject<V>(\n value: V,\n):\n | {\n [ownProps: string]: unknown;\n type: string;\n target: string;\n currentTarget: string;\n detail?: unknown;\n }\n | {\n [ownProps: string]: unknown;\n message: string;\n name: string;\n stack?: string;\n }\n | V {\n if (isError(value)) {\n return {\n message: value.message,\n name: value.name,\n stack: value.stack,\n ...getOwnProperties(value),\n };\n } else if (isEvent(value)) {\n const newObj: {\n [ownProps: string]: unknown;\n type: string;\n target: string;\n currentTarget: string;\n detail?: unknown;\n } = {\n type: value.type,\n target: serializeEventTarget(value.target),\n currentTarget: serializeEventTarget(value.currentTarget),\n ...getOwnProperties(value),\n };\n\n if (typeof CustomEvent !== 'undefined' && isInstanceOf(value, CustomEvent)) {\n newObj.detail = value.detail;\n }\n\n return newObj;\n } else {\n return value;\n }\n}\n\n/** Creates a string representation of the target of an `Event` object */\nfunction serializeEventTarget(target: unknown): string {\n try {\n return isElement(target) ? htmlTreeAsString(target) : Object.prototype.toString.call(target);\n } catch (_oO) {\n return '<unknown>';\n }\n}\n\n/** Filters out all but an object's own properties */\nfunction getOwnProperties(obj: unknown): { [key: string]: unknown } {\n if (typeof obj === 'object' && obj !== null) {\n const extractedProps: { [key: string]: unknown } = {};\n for (const property in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, property)) {\n extractedProps[property] = (obj as Record<string, unknown>)[property];\n }\n }\n return extractedProps;\n } else {\n return {};\n }\n}\n\n/**\n * Given any captured exception, extract its keys and create a sorted\n * and truncated list that will be used inside the event message.\n * eg. `Non-error exception captured with keys: foo, bar, baz`\n */\nexport function extractExceptionKeysForMessage(exception: Record<string, unknown>, maxLength: number = 40): string {\n const keys = Object.keys(convertToPlainObject(exception));\n keys.sort();\n\n if (!keys.length) {\n return '[object has no keys]';\n }\n\n if (keys[0].length >= maxLength) {\n return truncate(keys[0], maxLength);\n }\n\n for (let includedKeys = keys.length; includedKeys > 0; includedKeys--) {\n const serialized = keys.slice(0, includedKeys).join(', ');\n if (serialized.length > maxLength) {\n continue;\n }\n if (includedKeys === keys.length) {\n return serialized;\n }\n return truncate(serialized, maxLength);\n }\n\n return '';\n}\n\n/**\n * Given any object, return a new object having removed all fields whose value was `undefined`.\n * Works recursively on objects and arrays.\n *\n * Attention: This function keeps circular references in the returned object.\n */\nexport function dropUndefinedKeys<T>(inputValue: T): T {\n // This map keeps track of what already visited nodes map to.\n // Our Set - based memoBuilder doesn't work here because we want to the output object to have the same circular\n // references as the input object.\n const memoizationMap = new Map<unknown, unknown>();\n\n // This function just proxies `_dropUndefinedKeys` to keep the `memoBuilder` out of this function's API\n return _dropUndefinedKeys(inputValue, memoizationMap);\n}\n\nfunction _dropUndefinedKeys<T>(inputValue: T, memoizationMap: Map<unknown, unknown>): T {\n if (isPojo(inputValue)) {\n // If this node has already been visited due to a circular reference, return the object it was mapped to in the new object\n const memoVal = memoizationMap.get(inputValue);\n if (memoVal !== undefined) {\n return memoVal as T;\n }\n\n const returnValue: { [key: string]: any } = {};\n // Store the mapping of this value in case we visit it again, in case of circular data\n memoizationMap.set(inputValue, returnValue);\n\n for (const key of Object.keys(inputValue)) {\n if (typeof inputValue[key] !== 'undefined') {\n returnValue[key] = _dropUndefinedKeys(inputValue[key], memoizationMap);\n }\n }\n\n return returnValue as T;\n }\n\n if (Array.isArray(inputValue)) {\n // If this node has already been visited due to a circular reference, return the array it was mapped to in the new object\n const memoVal = memoizationMap.get(inputValue);\n if (memoVal !== undefined) {\n return memoVal as T;\n }\n\n const returnValue: unknown[] = [];\n // Store the mapping of this value in case we visit it again, in case of circular data\n memoizationMap.set(inputValue, returnValue);\n\n inputValue.forEach((item: unknown) => {\n returnValue.push(_dropUndefinedKeys(item, memoizationMap));\n });\n\n return returnValue as unknown as T;\n }\n\n return inputValue;\n}\n\nfunction isPojo(input: unknown): input is Record<string, unknown> {\n if (!isPlainObject(input)) {\n return false;\n }\n\n try {\n const name = (Object.getPrototypeOf(input) as { constructor: { name: string } }).constructor.name;\n return !name || name === 'Object';\n } catch {\n return true;\n }\n}\n\n/**\n * Ensure that something is an object.\n *\n * Turns `undefined` and `null` into `String`s and all other primitives into instances of their respective wrapper\n * classes (String, Boolean, Number, etc.). Acts as the identity function on non-primitives.\n *\n * @param wat The subject of the objectification\n * @returns A version of `wat` which can safely be used with `Object` class methods\n */\nexport function objectify(wat: unknown): typeof Object {\n let objectified;\n switch (true) {\n case wat === undefined || wat === null:\n objectified = new String(wat);\n break;\n\n // Though symbols and bigints do have wrapper classes (`Symbol` and `BigInt`, respectively), for whatever reason\n // those classes don't have constructors which can be used with the `new` keyword. We therefore need to cast each as\n // an object in order to wrap it.\n case typeof wat === 'symbol' || typeof wat === 'bigint':\n objectified = Object(wat);\n break;\n\n // this will catch the remaining primitives: `String`, `Number`, and `Boolean`\n case isPrimitive(wat):\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n objectified = new (wat as any).constructor(wat);\n break;\n\n // by process of elimination, at this point we know that `wat` must already be an object\n default:\n objectified = wat;\n break;\n }\n return objectified;\n}\n","// This code was originally forked from https://github.com/felixge/node-stack-trace\n// Since then it has been highly modified to fit our needs.\n\n// Copyright (c) 2011 Felix Geisendörfer (felix@debuggable.com)//\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions://\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.//\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nimport type { StackLineParserFn } from '@sentry/types';\n\nexport type GetModuleFn = (filename: string | undefined) => string | undefined;\n\n/**\n * Does this filename look like it's part of the app code?\n */\nexport function filenameIsInApp(filename: string, isNative: boolean = false): boolean {\n const isInternal =\n isNative ||\n (filename &&\n // It's not internal if it's an absolute linux path\n !filename.startsWith('/') &&\n // It's not internal if it's an absolute windows path\n !filename.match(/^[A-Z]:/) &&\n // It's not internal if the path is starting with a dot\n !filename.startsWith('.') &&\n // It's not internal if the frame has a protocol. In node, this is usually the case if the file got pre-processed with a bundler like webpack\n !filename.match(/^[a-zA-Z]([a-zA-Z0-9.\\-+])*:\\/\\//)); // Schema from: https://stackoverflow.com/a/3641782\n\n // in_app is all that's not an internal Node function or a module within node_modules\n // note that isNative appears to return true even for node core libraries\n // see https://github.com/getsentry/raven-node/issues/176\n\n return !isInternal && filename !== undefined && !filename.includes('node_modules/');\n}\n\n/** Node Stack line parser */\n// eslint-disable-next-line complexity\nexport function node(getModule?: GetModuleFn): StackLineParserFn {\n const FILENAME_MATCH = /^\\s*[-]{4,}$/;\n const FULL_MATCH = /at (?:async )?(?:(.+?)\\s+\\()?(?:(.+):(\\d+):(\\d+)?|([^)]+))\\)?/;\n\n // eslint-disable-next-line complexity\n return (line: string) => {\n const lineMatch = line.match(FULL_MATCH);\n\n if (lineMatch) {\n let object: string | undefined;\n let method: string | undefined;\n let functionName: string | undefined;\n let typeName: string | undefined;\n let methodName: string | undefined;\n\n if (lineMatch[1]) {\n functionName = lineMatch[1];\n\n let methodStart = functionName.lastIndexOf('.');\n if (functionName[methodStart - 1] === '.') {\n methodStart--;\n }\n\n if (methodStart > 0) {\n object = functionName.slice(0, methodStart);\n method = functionName.slice(methodStart + 1);\n const objectEnd = object.indexOf('.Module');\n if (objectEnd > 0) {\n functionName = functionName.slice(objectEnd + 1);\n object = object.slice(0, objectEnd);\n }\n }\n typeName = undefined;\n }\n\n if (method) {\n typeName = object;\n methodName = method;\n }\n\n if (method === '<anonymous>') {\n methodName = undefined;\n functionName = undefined;\n }\n\n if (functionName === undefined) {\n methodName = methodName || '<anonymous>';\n functionName = typeName ? `${typeName}.${methodName}` : methodName;\n }\n\n let filename = lineMatch[2] && lineMatch[2].startsWith('file://') ? lineMatch[2].slice(7) : lineMatch[2];\n const isNative = lineMatch[5] === 'native';\n\n // If it's a Windows path, trim the leading slash so that `/C:/foo` becomes `C:/foo`\n if (filename && filename.match(/\\/[A-Z]:/)) {\n filename = filename.slice(1);\n }\n\n if (!filename && lineMatch[5] && !isNative) {\n filename = lineMatch[5];\n }\n\n return {\n filename,\n module: getModule ? getModule(filename) : undefined,\n function: functionName,\n lineno: parseInt(lineMatch[3], 10) || undefined,\n colno: parseInt(lineMatch[4], 10) || undefined,\n in_app: filenameIsInApp(filename, isNative),\n };\n }\n\n if (line.match(FILENAME_MATCH)) {\n return {\n filename: line,\n };\n }\n\n return undefined;\n };\n}\n","import type { StackFrame, StackLineParser, StackParser } from '@sentry/types';\n\nimport type { GetModuleFn } from './node-stack-trace';\nimport { filenameIsInApp, node } from './node-stack-trace';\n\nexport { filenameIsInApp };\n\nconst STACKTRACE_FRAME_LIMIT = 50;\n// Used to sanitize webpack (error: *) wrapped stack errors\nconst WEBPACK_ERROR_REGEXP = /\\(error: (.*)\\)/;\nconst STRIP_FRAME_REGEXP = /captureMessage|captureException/;\n\n/**\n * Creates a stack parser with the supplied line parsers\n *\n * StackFrames are returned in the correct order for Sentry Exception\n * frames and with Sentry SDK internal frames removed from the top and bottom\n *\n */\nexport function createStackParser(...parsers: StackLineParser[]): StackParser {\n const sortedParsers = parsers.sort((a, b) => a[0] - b[0]).map(p => p[1]);\n\n return (stack: string, skipFirst: number = 0): StackFrame[] => {\n const frames: StackFrame[] = [];\n const lines = stack.split('\\n');\n\n for (let i = skipFirst; i < lines.length; i++) {\n const line = lines[i];\n // Ignore lines over 1kb as they are unlikely to be stack frames.\n // Many of the regular expressions use backtracking which results in run time that increases exponentially with\n // input size. Huge strings can result in hangs/Denial of Service:\n // https://github.com/getsentry/sentry-javascript/issues/2286\n if (line.length > 1024) {\n continue;\n }\n\n // https://github.com/getsentry/sentry-javascript/issues/5459\n // Remove webpack (error: *) wrappers\n const cleanedLine = WEBPACK_ERROR_REGEXP.test(line) ? line.replace(WEBPACK_ERROR_REGEXP, '$1') : line;\n\n // https://github.com/getsentry/sentry-javascript/issues/7813\n // Skip Error: lines\n if (cleanedLine.match(/\\S*Error: /)) {\n continue;\n }\n\n for (const parser of sortedParsers) {\n const frame = parser(cleanedLine);\n\n if (frame) {\n frames.push(frame);\n break;\n }\n }\n\n if (frames.length >= STACKTRACE_FRAME_LIMIT) {\n break;\n }\n }\n\n return stripSentryFramesAndReverse(frames);\n };\n}\n\n/**\n * Gets a stack parser implementation from Options.stackParser\n * @see Options\n *\n * If options contains an array of line parsers, it is converted into a parser\n */\nexport function stackParserFromStackParserOptions(stackParser: StackParser | StackLineParser[]): StackParser {\n if (Array.isArray(stackParser)) {\n return createStackParser(...stackParser);\n }\n return stackParser;\n}\n\n/**\n * Removes Sentry frames from the top and bottom of the stack if present and enforces a limit of max number of frames.\n * Assumes stack input is ordered from top to bottom and returns the reverse representation so call site of the\n * function that caused the crash is the last frame in the array.\n * @hidden\n */\nexport function stripSentryFramesAndReverse(stack: ReadonlyArray<StackFrame>): StackFrame[] {\n if (!stack.length) {\n return [];\n }\n\n const localStack = Array.from(stack);\n\n // If stack starts with one of our API calls, remove it (starts, meaning it's the top of the stack - aka last call)\n if (/sentryWrapped/.test(localStack[localStack.length - 1].function || '')) {\n localStack.pop();\n }\n\n // Reversing in the middle of the procedure allows us to just pop the values off the stack\n localStack.reverse();\n\n // If stack ends with one of our internal API calls, remove it (ends, meaning it's the bottom of the stack - aka top-most call)\n if (STRIP_FRAME_REGEXP.test(localStack[localStack.length - 1].function || '')) {\n localStack.pop();\n\n // When using synthetic events, we will have a 2 levels deep stack, as `new Error('Sentry syntheticException')`\n // is produced within the hub itself, making it:\n //\n // Sentry.captureException()\n // getCurrentHub().captureException()\n //\n // instead of just the top `Sentry` call itself.\n // This forces us to possibly strip an additional frame in the exact same was as above.\n if (STRIP_FRAME_REGEXP.test(localStack[localStack.length - 1].function || '')) {\n localStack.pop();\n }\n }\n\n return localStack.slice(0, STACKTRACE_FRAME_LIMIT).map(frame => ({\n ...frame,\n filename: frame.filename || localStack[localStack.length - 1].filename,\n function: frame.function || '?',\n }));\n}\n\nconst defaultFunctionName = '<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\n/**\n * Node.js stack line parser\n *\n * This is in @sentry/utils so it can be used from the Electron SDK in the browser for when `nodeIntegration == true`.\n * This allows it to be used without referencing or importing any node specific code which causes bundlers to complain\n */\nexport function nodeStackLineParser(getModule?: GetModuleFn): StackLineParser {\n return [90, node(getModule)];\n}\n","import { DEBUG_BUILD } from '../debug-build';\nimport { logger } from '../logger';\nimport { getFunctionName } from '../stacktrace';\n\nexport type InstrumentHandlerType = 'console' | 'dom' | 'fetch' | 'history' | 'xhr' | 'error' | 'unhandledrejection';\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type InstrumentHandlerCallback = (data: any) => void;\n\n// We keep the handlers globally\nconst handlers: { [key in InstrumentHandlerType]?: InstrumentHandlerCallback[] } = {};\nconst instrumented: { [key in InstrumentHandlerType]?: boolean } = {};\n\n/** Add a handler function. */\nexport function addHandler(type: InstrumentHandlerType, handler: InstrumentHandlerCallback): void {\n handlers[type] = handlers[type] || [];\n (handlers[type] as InstrumentHandlerCallback[]).push(handler);\n}\n\n/**\n * Reset all instrumentation handlers.\n * This can be used by tests to ensure we have a clean slate of instrumentation handlers.\n */\nexport function resetInstrumentationHandlers(): void {\n Object.keys(handlers).forEach(key => {\n handlers[key as InstrumentHandlerType] = undefined;\n });\n}\n\n/** Maybe run an instrumentation function, unless it was already called. */\nexport function maybeInstrument(type: InstrumentHandlerType, instrumentFn: () => void): void {\n if (!instrumented[type]) {\n instrumentFn();\n instrumented[type] = true;\n }\n}\n\n/** Trigger handlers for a given instrumentation type. */\nexport function triggerHandlers(type: InstrumentHandlerType, data: unknown): void {\n const typeHandlers = type && handlers[type];\n if (!typeHandlers) {\n return;\n }\n\n for (const handler of typeHandlers) {\n try {\n handler(data);\n } catch (e) {\n DEBUG_BUILD &&\n logger.error(\n `Error while triggering instrumentation handler.\\nType: ${type}\\nName: ${getFunctionName(handler)}\\nError:`,\n e,\n );\n }\n }\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/ban-types */\nimport type { ConsoleLevel, HandlerDataConsole } from '@sentry/types';\n\nimport { CONSOLE_LEVELS, originalConsoleMethods } from '../logger';\nimport { fill } from '../object';\nimport { GLOBAL_OBJ } from '../worldwide';\nimport { addHandler, maybeInstrument, triggerHandlers } from './_handlers';\n\n/**\n * Add an instrumentation handler for when a console.xxx method is called.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nexport function addConsoleInstrumentationHandler(handler: (data: HandlerDataConsole) => void): void {\n const type = 'console';\n addHandler(type, handler);\n maybeInstrument(type, instrumentConsole);\n}\n\nfunction instrumentConsole(): void {\n if (!('console' in GLOBAL_OBJ)) {\n return;\n }\n\n CONSOLE_LEVELS.forEach(function (level: ConsoleLevel): void {\n if (!(level in GLOBAL_OBJ.console)) {\n return;\n }\n\n fill(GLOBAL_OBJ.console, level, function (originalConsoleMethod: () => any): Function {\n originalConsoleMethods[level] = originalConsoleMethod;\n\n return function (...args: any[]): void {\n const handlerData: HandlerDataConsole = { args, level };\n triggerHandlers('console', handlerData);\n\n const log = originalConsoleMethods[level];\n log && log.apply(GLOBAL_OBJ.console, args);\n };\n });\n });\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { Event, Exception, Mechanism, StackFrame } from '@sentry/types';\n\nimport { addNonEnumerableProperty } from './object';\nimport { snipLine } from './string';\nimport { GLOBAL_OBJ } from './worldwide';\n\ninterface CryptoInternal {\n getRandomValues(array: Uint8Array): Uint8Array;\n randomUUID?(): string;\n}\n\n/** An interface for common properties on global */\ninterface CryptoGlobal {\n msCrypto?: CryptoInternal;\n crypto?: CryptoInternal;\n}\n\n/**\n * UUID4 generator\n *\n * @returns string Generated UUID4.\n */\nexport function uuid4(): string {\n const gbl = GLOBAL_OBJ as typeof GLOBAL_OBJ & CryptoGlobal;\n const crypto = gbl.crypto || gbl.msCrypto;\n\n let getRandomByte = (): number => Math.random() * 16;\n try {\n if (crypto && crypto.randomUUID) {\n return crypto.randomUUID().replace(/-/g, '');\n }\n if (crypto && crypto.getRandomValues) {\n getRandomByte = () => {\n // crypto.getRandomValues might return undefined instead of the typed array\n // in old Chromium versions (e.g. 23.0.1235.0 (151422))\n // However, `typedArray` is still filled in-place.\n // @see https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues#typedarray\n const typedArray = new Uint8Array(1);\n crypto.getRandomValues(typedArray);\n return typedArray[0];\n };\n }\n } catch (_) {\n // some runtimes can crash invoking crypto\n // https://github.com/getsentry/sentry-javascript/issues/8935\n }\n\n // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523\n // Concatenating the following numbers as strings results in '10000000100040008000100000000000'\n return (([1e7] as unknown as string) + 1e3 + 4e3 + 8e3 + 1e11).replace(/[018]/g, c =>\n // eslint-disable-next-line no-bitwise\n ((c as unknown as number) ^ ((getRandomByte() & 15) >> ((c as unknown as number) / 4))).toString(16),\n );\n}\n\nfunction getFirstException(event: Event): Exception | undefined {\n return event.exception && event.exception.values ? event.exception.values[0] : undefined;\n}\n\n/**\n * Extracts either message or type+value from an event that can be used for user-facing logs\n * @returns event's description\n */\nexport function getEventDescription(event: Event): string {\n const { message, event_id: eventId } = event;\n if (message) {\n return message;\n }\n\n const firstException = getFirstException(event);\n if (firstException) {\n if (firstException.type && firstException.value) {\n return `${firstException.type}: ${firstException.value}`;\n }\n return firstException.type || firstException.value || eventId || '<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 // When there is no line number in the frame, attaching context is nonsensical and will even break grouping\n if (frame.lineno === undefined) {\n return;\n }\n\n const maxLines = lines.length;\n const sourceLine = Math.max(Math.min(maxLines - 1, frame.lineno - 1), 0);\n\n frame.pre_context = lines\n .slice(Math.max(0, sourceLine - linesOfContext), sourceLine)\n .map((line: string) => snipLine(line, 0));\n\n frame.context_line = snipLine(lines[Math.min(maxLines - 1, sourceLine)], frame.colno || 0);\n\n frame.post_context = lines\n .slice(Math.min(sourceLine + 1, maxLines), sourceLine + 1 + linesOfContext)\n .map((line: string) => snipLine(line, 0));\n}\n\n/**\n * Checks whether or not we've already captured the given exception (note: not an identical exception - the very object\n * in question), and marks it captured if not.\n *\n * This is useful because it's possible for an error to get captured by more than one mechanism. After we intercept and\n * record an error, we rethrow it (assuming we've intercepted it before it's reached the top-level global handlers), so\n * that we don't interfere with whatever effects the error might have had were the SDK not there. At that point, because\n * the error has been rethrown, it's possible for it to bubble up to some other code we've instrumented. If it's not\n * caught after that, it will bubble all the way up to the global handlers (which of course we also instrument). This\n * function helps us ensure that even if we encounter the same error more than once, we only record it the first time we\n * see it.\n *\n * Note: It will ignore primitives (always return `false` and not mark them as seen), as properties can't be set on\n * them. {@link: Object.objectify} can be used on exceptions to convert any that are primitives into their equivalent\n * object wrapper forms so that this check will always work. However, because we need to flag the exact object which\n * will get rethrown, and because that rethrowing happens outside of the event processing pipeline, the objectification\n * must be done before the exception captured.\n *\n * @param A thrown exception to check or flag as having been seen\n * @returns `true` if the exception has already been captured, `false` if not (with the side effect of marking it seen)\n */\nexport function checkOrSetAlreadyCaught(exception: unknown): boolean {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if (exception && (exception as any).__sentry_captured__) {\n return true;\n }\n\n try {\n // set it this way rather than by assignment so that it's not ennumerable and therefore isn't recorded by the\n // `ExtraErrorData` integration\n addNonEnumerableProperty(exception as { [key: string]: unknown }, '__sentry_captured__', true);\n } catch (err) {\n // `exception` is a primitive, so we can't mark it seen\n }\n\n return false;\n}\n\n/**\n * Checks whether the given input is already an array, and if it isn't, wraps it in one.\n *\n * @param maybeArray Input to turn into an array, if necessary\n * @returns The input, if already an array, or an array with the input as the only element, if not\n */\nexport function arrayify<T = unknown>(maybeArray: T | T[]): T[] {\n return Array.isArray(maybeArray) ? maybeArray : [maybeArray];\n}\n","// TODO(v8): Move everything in this file into the browser package. Nothing here is generic and we run risk of leaking browser types into non-browser packages.\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/ban-types */\nimport type { HandlerDataDom } from '@sentry/types';\n\nimport { uuid4 } from '../misc';\nimport { addNonEnumerableProperty, fill } from '../object';\nimport { GLOBAL_OBJ } from '../worldwide';\nimport { addHandler, maybeInstrument, triggerHandlers } from './_handlers';\n\ntype SentryWrappedTarget = HTMLElement & { _sentryId?: string };\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\nconst WINDOW = GLOBAL_OBJ as unknown as Window;\nconst DEBOUNCE_DURATION = 1000;\n\nlet debounceTimerID: number | undefined;\nlet lastCapturedEventType: string | undefined;\nlet lastCapturedEventTargetId: string | undefined;\n\n/**\n * Add an instrumentation handler for when a click or a keypress happens.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nexport function addClickKeypressInstrumentationHandler(handler: (data: HandlerDataDom) => void): void {\n const type = 'dom';\n addHandler(type, handler);\n maybeInstrument(type, instrumentDOM);\n}\n\n/** Exported for tests only. */\nexport function instrumentDOM(): void {\n if (!WINDOW.document) {\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 WINDOW.document.addEventListener('click', globalDOMEventHandler, false);\n WINDOW.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 = (WINDOW as any)[target] && (WINDOW 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++;\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--;\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\n/**\n * Check whether the event is similar to the last captured one. For example, two click events on the same button.\n */\nfunction isSimilarToLastCapturedEvent(event: Event): boolean {\n // If both events have different type, then user definitely performed two separate actions. e.g. click + keypress.\n if (event.type !== lastCapturedEventType) {\n return false;\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 (!event.target || (event.target as SentryWrappedTarget)._sentryId !== lastCapturedEventTargetId) {\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 // 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 true;\n}\n\n/**\n * Decide whether an event should be captured.\n * @param event event to be captured\n */\nfunction shouldSkipDOMEvent(eventType: string, target: SentryWrappedTarget | null): boolean {\n // We are only interested in filtering `keypress` events for now.\n if (eventType !== 'keypress') {\n return false;\n }\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\n return true;\n}\n\n/**\n * Wraps addEventListener to capture UI breadcrumbs\n */\nfunction makeDOMEventHandler(\n handler: (data: HandlerDataDom) => void,\n globalListener: boolean = false,\n): (event: Event) => void {\n return (event: Event & { _sentryCaptured?: true }): 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 || event['_sentryCaptured']) {\n return;\n }\n\n const target = getEventTarget(event);\n\n // We always want to skip _some_ events.\n if (shouldSkipDOMEvent(event.type, target)) {\n return;\n }\n\n // Mark event as \"seen\"\n addNonEnumerableProperty(event, '_sentryCaptured', true);\n\n if (target && !target._sentryId) {\n // Add UUID to event target so we can identify if\n addNonEnumerableProperty(target, '_sentryId', uuid4());\n }\n\n const name = event.type === 'keypress' ? 'input' : event.type;\n\n // If there is no last captured event, it means that we can safely capture the new event and store it for future comparisons.\n // If there is a last captured event, 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 if (!isSimilarToLastCapturedEvent(event)) {\n const handlerData: HandlerDataDom = { event, name, global: globalListener };\n handler(handlerData);\n lastCapturedEventType = event.type;\n lastCapturedEventTargetId = target ? target._sentryId : undefined;\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 = WINDOW.setTimeout(() => {\n lastCapturedEventTargetId = undefined;\n lastCapturedEventType = undefined;\n }, DEBOUNCE_DURATION);\n };\n}\n\nfunction getEventTarget(event: Event): SentryWrappedTarget | null {\n try {\n return event.target as SentryWrappedTarget | null;\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 return null;\n }\n}\n","import { DEBUG_BUILD } from './debug-build';\nimport { logger } from './logger';\nimport { getGlobalObject } from './worldwide';\n\n// eslint-disable-next-line deprecation/deprecation\nconst WINDOW = getGlobalObject<Window>();\n\ndeclare const EdgeRuntime: string | undefined;\n\nexport { supportsHistory } from './vendor/supportsHistory';\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-expect-error 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 WINDOW)) {\n return false;\n }\n\n try {\n new Headers();\n new Request('http://www.example.com');\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 (typeof EdgeRuntime === 'string') {\n return true;\n }\n\n if (!supportsFetch()) {\n return false;\n }\n\n // Fast path to avoid DOM I/O\n // eslint-disable-next-line @typescript-eslint/unbound-method\n if (isNativeFetch(WINDOW.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 = WINDOW.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 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 WINDOW;\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","/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/ban-types */\nimport type { HandlerDataFetch } from '@sentry/types';\n\nimport { fill } from '../object';\nimport { supportsNativeFetch } from '../supports';\nimport { GLOBAL_OBJ } from '../worldwide';\nimport { addHandler, maybeInstrument, triggerHandlers } from './_handlers';\n\ntype FetchResource = string | { toString(): string } | { url: string };\n\n/**\n * Add an instrumentation handler for when a fetch request happens.\n * The handler function is called once when the request starts and once when it ends,\n * which can be identified by checking if it has an `endTimestamp`.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nexport function addFetchInstrumentationHandler(handler: (data: HandlerDataFetch) => void): void {\n const type = 'fetch';\n addHandler(type, handler);\n maybeInstrument(type, instrumentFetch);\n}\n\nfunction instrumentFetch(): void {\n if (!supportsNativeFetch()) {\n return;\n }\n\n fill(GLOBAL_OBJ, 'fetch', function (originalFetch: () => void): () => void {\n return function (...args: any[]): void {\n const { method, url } = parseFetchArgs(args);\n\n const handlerData: HandlerDataFetch = {\n args,\n fetchData: {\n method,\n url,\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_OBJ, args).then(\n (response: Response) => {\n const finishedHandlerData: HandlerDataFetch = {\n ...handlerData,\n endTimestamp: Date.now(),\n response,\n };\n\n triggerHandlers('fetch', finishedHandlerData);\n return response;\n },\n (error: Error) => {\n const erroredHandlerData: HandlerDataFetch = {\n ...handlerData,\n endTimestamp: Date.now(),\n error,\n };\n\n triggerHandlers('fetch', erroredHandlerData);\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\nfunction hasProp<T extends string>(obj: unknown, prop: T): obj is Record<string, string> {\n return !!obj && typeof obj === 'object' && !!(obj as Record<string, string>)[prop];\n}\n\nfunction getUrlFromResource(resource: FetchResource): string {\n if (typeof resource === 'string') {\n return resource;\n }\n\n if (!resource) {\n return '';\n }\n\n if (hasProp(resource, 'url')) {\n return resource.url;\n }\n\n if (resource.toString) {\n return resource.toString();\n }\n\n return '';\n}\n\n/**\n * Parses the fetch arguments to find the used Http method and the url of the request.\n * Exported for tests only.\n */\nexport function parseFetchArgs(fetchArgs: unknown[]): { method: string; url: string } {\n if (fetchArgs.length === 0) {\n return { method: 'GET', url: '' };\n }\n\n if (fetchArgs.length === 2) {\n const [url, options] = fetchArgs as [FetchResource, object];\n\n return {\n url: getUrlFromResource(url),\n method: hasProp(options, 'method') ? String(options.method).toUpperCase() : 'GET',\n };\n }\n\n const arg = fetchArgs[0];\n return {\n url: getUrlFromResource(arg as FetchResource),\n method: hasProp(arg, 'method') ? String(arg.method).toUpperCase() : 'GET',\n };\n}\n","import type { HandlerDataError } from '@sentry/types';\n\nimport { GLOBAL_OBJ } from '../worldwide';\nimport { addHandler, maybeInstrument, triggerHandlers } from './_handlers';\n\nlet _oldOnErrorHandler: (typeof GLOBAL_OBJ)['onerror'] | null = null;\n\n/**\n * Add an instrumentation handler for when an error is captured by the global error handler.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nexport function addGlobalErrorInstrumentationHandler(handler: (data: HandlerDataError) => void): void {\n const type = 'error';\n addHandler(type, handler);\n maybeInstrument(type, instrumentError);\n}\n\nfunction instrumentError(): void {\n _oldOnErrorHandler = GLOBAL_OBJ.onerror;\n\n GLOBAL_OBJ.onerror = function (\n msg: string | object,\n url?: string,\n line?: number,\n column?: number,\n error?: Error,\n ): boolean {\n const handlerData: HandlerDataError = {\n column,\n error,\n line,\n msg,\n url,\n };\n triggerHandlers('error', handlerData);\n\n if (_oldOnErrorHandler && !_oldOnErrorHandler.__SENTRY_LOADER__) {\n // eslint-disable-next-line prefer-rest-params\n return _oldOnErrorHandler.apply(this, arguments);\n }\n\n return false;\n };\n\n GLOBAL_OBJ.onerror.__SENTRY_INSTRUMENTED__ = true;\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport type { HandlerDataUnhandledRejection } from '@sentry/types';\n\nimport { GLOBAL_OBJ } from '../worldwide';\nimport { addHandler, maybeInstrument, triggerHandlers } from './_handlers';\n\nlet _oldOnUnhandledRejectionHandler: (typeof GLOBAL_OBJ)['onunhandledrejection'] | null = null;\n\n/**\n * Add an instrumentation handler for when an unhandled promise rejection is captured.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nexport function addGlobalUnhandledRejectionInstrumentationHandler(\n handler: (data: HandlerDataUnhandledRejection) => void,\n): void {\n const type = 'unhandledrejection';\n addHandler(type, handler);\n maybeInstrument(type, instrumentUnhandledRejection);\n}\n\nfunction instrumentUnhandledRejection(): void {\n _oldOnUnhandledRejectionHandler = GLOBAL_OBJ.onunhandledrejection;\n\n GLOBAL_OBJ.onunhandledrejection = function (e: any): boolean {\n const handlerData: HandlerDataUnhandledRejection = e;\n triggerHandlers('unhandledrejection', handlerData);\n\n if (_oldOnUnhandledRejectionHandler && !_oldOnUnhandledRejectionHandler.__SENTRY_LOADER__) {\n // eslint-disable-next-line prefer-rest-params\n return _oldOnUnhandledRejectionHandler.apply(this, arguments);\n }\n\n return true;\n };\n\n GLOBAL_OBJ.onunhandledrejection.__SENTRY_INSTRUMENTED__ = true;\n}\n","// Based on https://github.com/angular/angular.js/pull/13945/files\n// The MIT License\n\n// Copyright (c) 2010-2016 Google, Inc. http://angularjs.org\n\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nimport { getGlobalObject } from '../worldwide';\n\n// eslint-disable-next-line deprecation/deprecation\nconst WINDOW = getGlobalObject<Window>();\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 /* eslint-disable @typescript-eslint/no-unsafe-member-access */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const chromeVar = (WINDOW as any).chrome;\n const isChromePackagedApp = chromeVar && chromeVar.app && chromeVar.app.runtime;\n /* eslint-enable @typescript-eslint/no-unsafe-member-access */\n const hasHistoryApi = 'history' in WINDOW && !!WINDOW.history.pushState && !!WINDOW.history.replaceState;\n\n return !isChromePackagedApp && hasHistoryApi;\n}\n","// TODO(v8): Move everything in this file into the browser package. Nothing here is generic and we run risk of leaking browser types into non-browser packages.\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/ban-types */\nimport type { HandlerDataHistory } from '@sentry/types';\n\nimport { fill } from '../object';\nimport { supportsHistory } from '../supports';\nimport { GLOBAL_OBJ } from '../worldwide';\nimport { addHandler, maybeInstrument, triggerHandlers } from './_handlers';\n\nconst WINDOW = GLOBAL_OBJ as unknown as Window;\n\nlet lastHref: string | undefined;\n\n/**\n * Add an instrumentation handler for when a fetch request happens.\n * The handler function is called once when the request starts and once when it ends,\n * which can be identified by checking if it has an `endTimestamp`.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nexport function addHistoryInstrumentationHandler(handler: (data: HandlerDataHistory) => void): void {\n const type = 'history';\n addHandler(type, handler);\n maybeInstrument(type, instrumentHistory);\n}\n\nfunction instrumentHistory(): void {\n if (!supportsHistory()) {\n return;\n }\n\n const oldOnPopState = WINDOW.onpopstate;\n WINDOW.onpopstate = function (this: WindowEventHandlers, ...args: any[]): any {\n const to = WINDOW.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 const handlerData: HandlerDataHistory = { from, to };\n triggerHandlers('history', handlerData);\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 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 const handlerData: HandlerDataHistory = { from, to };\n triggerHandlers('history', handlerData);\n }\n return originalHistoryFunction.apply(this, args);\n };\n }\n\n fill(WINDOW.history, 'pushState', historyReplacementFunction);\n fill(WINDOW.history, 'replaceState', historyReplacementFunction);\n}\n","// TODO(v8): Move everything in this file into the browser package. Nothing here is generic and we run risk of leaking browser types into non-browser packages.\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/ban-types */\nimport type { HandlerDataXhr, SentryWrappedXMLHttpRequest, WrappedFunction } from '@sentry/types';\n\nimport { isString } from '../is';\nimport { fill } from '../object';\nimport { GLOBAL_OBJ } from '../worldwide';\nimport { addHandler, maybeInstrument, triggerHandlers } from './_handlers';\n\nconst WINDOW = GLOBAL_OBJ as unknown as Window;\n\nexport const SENTRY_XHR_DATA_KEY = '__sentry_xhr_v3__';\n\n/**\n * Add an instrumentation handler for when an XHR request happens.\n * The handler function is called once when the request starts and once when it ends,\n * which can be identified by checking if it has an `endTimestamp`.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nexport function addXhrInstrumentationHandler(handler: (data: HandlerDataXhr) => void): void {\n const type = 'xhr';\n addHandler(type, handler);\n maybeInstrument(type, instrumentXHR);\n}\n\n/** Exported only for tests. */\nexport function instrumentXHR(): void {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if (!(WINDOW as any).XMLHttpRequest) {\n return;\n }\n\n const xhrproto = XMLHttpRequest.prototype;\n\n fill(xhrproto, 'open', function (originalOpen: () => void): () => void {\n return function (this: XMLHttpRequest & SentryWrappedXMLHttpRequest, ...args: any[]): void {\n const startTimestamp = Date.now();\n\n // open() should always be called with two or more arguments\n // But to be on the safe side, we actually validate this and bail out if we don't have a method & url\n const method = isString(args[0]) ? args[0].toUpperCase() : undefined;\n const url = parseUrl(args[1]);\n\n if (!method || !url) {\n return originalOpen.apply(this, args);\n }\n\n this[SENTRY_XHR_DATA_KEY] = {\n method,\n url,\n request_headers: {},\n };\n\n // if Sentry key appears in URL, don't capture it as a request\n if (method === 'POST' && url.match(/sentry_key/)) {\n this.__sentry_own_request__ = true;\n }\n\n const onreadystatechangeHandler: () => void = () => {\n // For whatever reason, this is not the same instance here as from the outer method\n const xhrInfo = this[SENTRY_XHR_DATA_KEY];\n\n if (!xhrInfo) {\n return;\n }\n\n if (this.readyState === 4) {\n try {\n // touching statusCode in some platforms throws\n // an exception\n xhrInfo.status_code = this.status;\n } catch (e) {\n /* do nothing */\n }\n\n const handlerData: HandlerDataXhr = {\n args: [method, url],\n endTimestamp: Date.now(),\n startTimestamp,\n xhr: this,\n };\n triggerHandlers('xhr', handlerData);\n }\n };\n\n if ('onreadystatechange' in this && typeof this.onreadystatechange === 'function') {\n fill(this, 'onreadystatechange', function (original: WrappedFunction): Function {\n return function (this: SentryWrappedXMLHttpRequest, ...readyStateArgs: any[]): void {\n onreadystatechangeHandler();\n return original.apply(this, readyStateArgs);\n };\n });\n } else {\n this.addEventListener('readystatechange', onreadystatechangeHandler);\n }\n\n // Intercepting `setRequestHeader` to access the request headers of XHR instance.\n // This will only work for user/library defined headers, not for the default/browser-assigned headers.\n // Request cookies are also unavailable for XHR, as `Cookie` header can't be defined by `setRequestHeader`.\n fill(this, 'setRequestHeader', function (original: WrappedFunction): Function {\n return function (this: SentryWrappedXMLHttpRequest, ...setRequestHeaderArgs: unknown[]): void {\n const [header, value] = setRequestHeaderArgs;\n\n const xhrInfo = this[SENTRY_XHR_DATA_KEY];\n\n if (xhrInfo && isString(header) && isString(value)) {\n xhrInfo.request_headers[header.toLowerCase()] = value;\n }\n\n return original.apply(this, setRequestHeaderArgs);\n };\n });\n\n return originalOpen.apply(this, args);\n };\n });\n\n fill(xhrproto, 'send', function (originalSend: () => void): () => void {\n return function (this: XMLHttpRequest & SentryWrappedXMLHttpRequest, ...args: any[]): void {\n const sentryXhrData = this[SENTRY_XHR_DATA_KEY];\n\n if (!sentryXhrData) {\n return originalSend.apply(this, args);\n }\n\n if (args[0] !== undefined) {\n sentryXhrData.body = args[0];\n }\n\n const handlerData: HandlerDataXhr = {\n args: [sentryXhrData.method, sentryXhrData.url],\n startTimestamp: Date.now(),\n xhr: this,\n };\n triggerHandlers('xhr', handlerData);\n\n return originalSend.apply(this, args);\n };\n });\n}\n\nfunction parseUrl(url: string | unknown): string | undefined {\n if (isString(url)) {\n return url;\n }\n\n try {\n // url can be a string or URL\n // but since URL is not available in IE11, we do not check for it,\n // but simply assume it is an URL and return `toString()` from it (which returns the full URL)\n // If that fails, we just return undefined\n return (url as URL).toString();\n } catch {} // eslint-disable-line no-empty\n\n return undefined;\n}\n","/*\n * This module exists for optimizations in the build process through rollup and terser. We define some global\n * constants, which can be overridden during build. By guarding certain pieces of code with functions that return these\n * constants, we can control whether or not they appear in the final bundle. (Any code guarded by a false condition will\n * never run, and will hence be dropped during treeshaking.) The two primary uses for this are stripping out calls to\n * `logger` and preventing node-related code from appearing in browser bundles.\n *\n * Attention:\n * This file should not be used to define constants/flags that are intended to be used for tree-shaking conducted by\n * users. These flags should live in their respective packages, as we identified user tooling (specifically webpack)\n * having issues tree-shaking these constants across package boundaries.\n * An example for this is the __SENTRY_DEBUG__ constant. It is declared in each package individually because we want\n * users to be able to shake away expressions that it guards.\n */\n\ndeclare const __SENTRY_BROWSER_BUNDLE__: boolean | undefined;\n\nexport type SdkSource = 'npm' | 'cdn' | 'loader';\n\n/**\n * Figures out if we're building a browser bundle.\n *\n * @returns true if this is a browser bundle build.\n */\nexport function isBrowserBundle(): boolean {\n return typeof __SENTRY_BROWSER_BUNDLE__ !== 'undefined' && !!__SENTRY_BROWSER_BUNDLE__;\n}\n\n/**\n * Get source of SDK.\n */\nexport function getSDKSource(): SdkSource {\n // @ts-expect-error __SENTRY_SDK_SOURCE__ is injected by rollup during build process\n return __SENTRY_SDK_SOURCE__;\n}\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\nimport { isBrowserBundle } from './env';\n\n/**\n * Checks whether we're in the Node.js or Browser environment\n *\n * @returns Answer to given question\n */\nexport function isNodeEnv(): boolean {\n // explicitly check for browser bundles as those can be optimized statically\n // by terser/rollup.\n return (\n !isBrowserBundle() &&\n Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]'\n );\n}\n\n/**\n * Requires a module which is protected against bundler minification.\n *\n * @param request The module path to resolve\n */\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any\nexport function dynamicRequire(mod: any, request: string): any {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return mod.require(request);\n}\n\n/**\n * Helper for dynamically loading module that should work with linked dependencies.\n * The problem is that we _should_ be using `require(require.resolve(moduleName, { paths: [cwd()] }))`\n * However it's _not possible_ to do that with Webpack, as it has to know all the dependencies during\n * build time. `require.resolve` is also not available in any other way, so we cannot create,\n * a fake helper like we do with `dynamicRequire`.\n *\n * We always prefer to use local package, thus the value is not returned early from each `try/catch` block.\n * That is to mimic the behavior of `require.resolve` exactly.\n *\n * @param moduleName module name to require\n * @returns possibly required module\n */\nexport function loadModule<T>(moduleName: string): T | undefined {\n let mod: T | undefined;\n\n try {\n mod = dynamicRequire(module, moduleName);\n } catch (e) {\n // no-empty\n }\n\n try {\n const { cwd } = dynamicRequire(module, 'process');\n mod = dynamicRequire(module, `${cwd()}/node_modules/${moduleName}`) as T;\n } catch (e) {\n // no-empty\n }\n\n return mod;\n}\n","import { isNodeEnv } from './node';\nimport { GLOBAL_OBJ } from './worldwide';\n\n/**\n * Returns true if we are in the browser.\n */\nexport function isBrowser(): boolean {\n // eslint-disable-next-line no-restricted-globals\n return typeof window !== 'undefined' && (!isNodeEnv() || isElectronNodeRenderer());\n}\n\ntype ElectronProcess = { type?: string };\n\n// Electron renderers with nodeIntegration enabled are detected as Node.js so we specifically test for them\nfunction isElectronNodeRenderer(): boolean {\n return (\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any\n (GLOBAL_OBJ as any).process !== undefined && ((GLOBAL_OBJ as any).process as ElectronProcess).type === 'renderer'\n );\n}\n","/* eslint-disable @typescript-eslint/no-unsafe-member-access */\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nexport type MemoFunc = [\n // memoize\n (obj: any) => boolean,\n // unmemoize\n (obj: any) => void,\n];\n\n/**\n * Helper to decycle json objects\n */\nexport function memoBuilder(): MemoFunc {\n const hasWeakSet = typeof WeakSet === 'function';\n const inner: any = hasWeakSet ? new WeakSet() : [];\n function memoize(obj: any): boolean {\n if (hasWeakSet) {\n if (inner.has(obj)) {\n return true;\n }\n inner.add(obj);\n return false;\n }\n // eslint-disable-next-line @typescript-eslint/prefer-for-of\n for (let i = 0; i < inner.length; i++) {\n const value = inner[i];\n if (value === obj) {\n return true;\n }\n }\n inner.push(obj);\n return false;\n }\n\n function unmemoize(obj: any): void {\n if (hasWeakSet) {\n inner.delete(obj);\n } else {\n for (let i = 0; i < inner.length; i++) {\n if (inner[i] === obj) {\n inner.splice(i, 1);\n break;\n }\n }\n }\n }\n return [memoize, unmemoize];\n}\n","import type { Primitive } from '@sentry/types';\n\nimport { isNaN, isSyntheticEvent, isVueViewModel } from './is';\nimport type { MemoFunc } from './memo';\nimport { memoBuilder } from './memo';\nimport { convertToPlainObject } from './object';\nimport { getFunctionName } from './stacktrace';\n\ntype Prototype = { constructor: (...args: unknown[]) => unknown };\n// This is a hack to placate TS, relying on the fact that technically, arrays are objects with integer keys. Normally we\n// think of those keys as actual numbers, but `arr['0']` turns out to work just as well as `arr[0]`, and doing it this\n// way lets us use a single type in the places where behave as if we are only dealing with objects, even if some of them\n// might be arrays.\ntype ObjOrArray<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 */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function normalize(input: unknown, depth: number = 100, maxProperties: number = +Infinity): any {\n try {\n // since we're at the outermost level, we don't provide a key\n return visit('', input, depth, maxProperties);\n } catch (err) {\n return { ERROR: `**non-serializable** (${err})` };\n }\n}\n\n/** JSDoc */\nexport function normalizeToSize<T>(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n object: { [key: string]: any },\n // Default Node.js REPL depth\n depth: number = 3,\n // 100kB, as 200kB is max payload size, so half sounds reasonable\n maxSize: number = 100 * 1024,\n): T {\n const normalized = normalize(object, depth);\n\n if (jsonSize(normalized) > maxSize) {\n return normalizeToSize(object, depth - 1, maxSize);\n }\n\n return normalized as T;\n}\n\n/**\n * Visits a node to perform normalization on it\n *\n * @param key The key corresponding to the given node\n * @param value The node to be visited\n * @param depth Optional number indicating the maximum recursion depth\n * @param maxProperties Optional maximum number of properties/elements included in any single object/array\n * @param memo Optional Memo class handling decycling\n */\nfunction visit(\n key: string,\n value: unknown,\n depth: number = +Infinity,\n maxProperties: number = +Infinity,\n memo: MemoFunc = memoBuilder(),\n): Primitive | ObjOrArray<unknown> {\n const [memoize, unmemoize] = memo;\n\n // Get the simple cases out of the way first\n if (\n value == null || // this matches null and undefined -> eqeq not eqeqeq\n (['number', 'boolean', 'string'].includes(typeof value) && !isNaN(value))\n ) {\n return value as Primitive;\n }\n\n const stringified = stringifyValue(key, value);\n\n // Anything we could potentially dig into more (objects or arrays) will have come back as `\"[object XXXX]\"`.\n // Everything else will have already been serialized, so if we don't see that pattern, we're done.\n if (!stringified.startsWith('[object ')) {\n return stringified;\n }\n\n // From here on, we can assert that `value` is either an object or an array.\n\n // Do not normalize objects that we know have already been normalized. As a general rule, the\n // \"__sentry_skip_normalization__\" property should only be used sparingly and only should only be set on objects that\n // have already been normalized.\n if ((value as ObjOrArray<unknown>)['__sentry_skip_normalization__']) {\n return value as ObjOrArray<unknown>;\n }\n\n // We can set `__sentry_override_normalization_depth__` on an object to ensure that from there\n // We keep a certain amount of depth.\n // This should be used sparingly, e.g. we use it for the redux integration to ensure we get a certain amount of state.\n const remainingDepth =\n typeof (value as ObjOrArray<unknown>)['__sentry_override_normalization_depth__'] === 'number'\n ? ((value as ObjOrArray<unknown>)['__sentry_override_normalization_depth__'] as number)\n : depth;\n\n // We're also done if we've reached the max depth\n if (remainingDepth === 0) {\n // At this point we know `serialized` is a string of the form `\"[object XXXX]\"`. Clean it up so it's just `\"[XXXX]\"`.\n return stringified.replace('object ', '');\n }\n\n // If we've already visited this branch, bail out, as it's circular reference. If not, note that we're seeing it now.\n if (memoize(value)) {\n return '[Circular ~]';\n }\n\n // If the value has a `toJSON` method, we call it to extract more information\n const valueWithToJSON = value as unknown & { toJSON?: () => unknown };\n if (valueWithToJSON && typeof valueWithToJSON.toJSON === 'function') {\n try {\n const jsonValue = valueWithToJSON.toJSON();\n // We need to normalize the return value of `.toJSON()` in case it has circular references\n return visit('', jsonValue, remainingDepth - 1, maxProperties, memo);\n } catch (err) {\n // pass (The built-in `toJSON` failed, but we can still try to do it ourselves)\n }\n }\n\n // At this point we know we either have an object or an array, we haven't seen it before, and we're going to recurse\n // because we haven't yet reached the max depth. Create an accumulator to hold the results of visiting each\n // property/entry, and keep track of the number of items we add to it.\n const normalized = (Array.isArray(value) ? [] : {}) as ObjOrArray<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 = convertToPlainObject(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, remainingDepth - 1, maxProperties, memo);\n\n numAdded++;\n }\n\n // Once we've visited all the branches, remove the parent from memo storage\n unmemoize(value);\n\n // Return accumulated values\n return normalized;\n}\n\n/**\n * @deprecated This export will be removed in v8.\n */\nexport { visit as walk };\n\n/* eslint-disable complexity */\n/**\n * Stringify the given value. Handles various known special values and types.\n *\n * Not meant to be used on simple primitives which already have a string representation, as it will, for example, turn\n * the number 1231 into \"[Object Number]\", nor on `null`, as it will throw.\n *\n * @param value The value to stringify\n * @returns A stringified representation of the given value\n */\nfunction stringifyValue(\n key: unknown,\n // this type is a tiny bit of a cheat, since this function does handle NaN (which is technically a number), but for\n // our internal use, it'll do\n value: Exclude<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 if (isVueViewModel(value)) {\n return '[VueViewModel]';\n }\n\n // React's SyntheticEvent thingy\n if (isSyntheticEvent(value)) {\n return '[SyntheticEvent]';\n }\n\n if (typeof value === 'number' && value !== value) {\n return '[NaN]';\n }\n\n if (typeof value === 'function') {\n return `[Function: ${getFunctionName(value)}]`;\n }\n\n if (typeof value === 'symbol') {\n return `[${String(value)}]`;\n }\n\n // stringified BigInts are indistinguishable from regular numbers, so we need to label them to avoid confusion\n if (typeof value === 'bigint') {\n return `[BigInt: ${String(value)}]`;\n }\n\n // Now that we've knocked out all the special cases and the primitives, all we have left are objects. Simply casting\n // them to strings means that instances of classes which haven't defined their `toStringTag` will just come out as\n // `\"[object Object]\"`. If we instead look at the constructor's name (which is the same as the name of the class),\n // we can make sure that only plain objects come out that way.\n const objName = getConstructorName(value);\n\n // Handle HTML Elements\n if (/^HTML(\\w*)Element$/.test(objName)) {\n return `[HTMLElement: ${objName}]`;\n }\n\n return `[object ${objName}]`;\n } catch (err) {\n return `**non-serializable** (${err})`;\n }\n}\n/* eslint-enable complexity */\n\nfunction getConstructorName(value: unknown): string {\n const prototype: Prototype | null = Object.getPrototypeOf(value);\n\n return prototype ? prototype.constructor.name : 'null prototype';\n}\n\n/** Calculates bytes size of input string */\nfunction utf8Length(value: string): number {\n // eslint-disable-next-line no-bitwise\n return ~-encodeURI(value).split(/%..|./).length;\n}\n\n/** Calculates bytes size of input object */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction jsonSize(value: any): number {\n return utf8Length(JSON.stringify(value));\n}\n\n/**\n * Normalizes URLs in exceptions and stacktraces to a base path so Sentry can fingerprint\n * across platforms and working directory.\n *\n * @param url The URL to be normalized.\n * @param basePath The application base path.\n * @returns The normalized URL.\n */\nexport function normalizeUrlToBase(url: string, basePath: string): string {\n const escapedBase = basePath\n // Backslash to forward\n .replace(/\\\\/g, '/')\n // Escape RegExp special characters\n .replace(/[|\\\\{}()[\\]^$+*?.]/g, '\\\\$&');\n\n let newUrl = url;\n try {\n newUrl = decodeURI(url);\n } catch (_Oo) {\n // Sometime this breaks\n }\n return (\n newUrl\n .replace(/\\\\/g, '/')\n .replace(/webpack:\\/?/g, '') // Remove intermediate base path\n // eslint-disable-next-line @sentry-internal/sdk/no-regexp-constructor\n .replace(new RegExp(`(file://)?/*${escapedBase}/*`, 'ig'), 'app:///')\n );\n}\n","// Slightly modified (no IE8 support, ES6) and transcribed to TypeScript\n// https://github.com/calvinmetcalf/rollup-plugin-node-builtins/blob/63ab8aacd013767445ca299e468d9a60a95328d7/src/es6/path.js\n//\n// Copyright Joyent, Inc.and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n/** JSDoc */\nfunction normalizeArray(parts: string[], allowAboveRoot?: boolean): string[] {\n // if the path tries to go above the root, `up` ends up > 0\n let up = 0;\n for (let i = parts.length - 1; i >= 0; i--) {\n const last = parts[i];\n if (last === '.') {\n parts.splice(i, 1);\n } else if (last === '..') {\n parts.splice(i, 1);\n up++;\n } else if (up) {\n parts.splice(i, 1);\n up--;\n }\n }\n\n // if the path is allowed to go above the root, restore leading ..s\n if (allowAboveRoot) {\n for (; up--; up) {\n parts.unshift('..');\n }\n }\n\n return parts;\n}\n\n// Split a filename into [root, dir, basename, ext], unix version\n// 'root' is just a slash, or nothing.\nconst splitPathRe = /^(\\S+:\\\\|\\/?)([\\s\\S]*?)((?:\\.{1,2}|[^/\\\\]+?|)(\\.[^./\\\\]*|))(?:[/\\\\]*)$/;\n/** JSDoc */\nfunction splitPath(filename: string): string[] {\n // Truncate files names greater than 1024 characters to avoid regex dos\n // https://github.com/getsentry/sentry-javascript/pull/8737#discussion_r1285719172\n const truncated = filename.length > 1024 ? `<truncated>${filename.slice(-1024)}` : filename;\n const parts = splitPathRe.exec(truncated);\n return parts ? parts.slice(1) : [];\n}\n\n// path.resolve([from ...], to)\n// posix version\n/** JSDoc */\nexport function resolve(...args: string[]): string {\n let resolvedPath = '';\n let resolvedAbsolute = false;\n\n for (let i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) {\n const path = i >= 0 ? args[i] : '/';\n\n // Skip empty entries\n if (!path) {\n continue;\n }\n\n resolvedPath = `${path}/${resolvedPath}`;\n resolvedAbsolute = path.charAt(0) === '/';\n }\n\n // At this point the path should be resolved to a full absolute path, but\n // handle relative paths to be safe (might happen when process.cwd() fails)\n\n // Normalize the path\n resolvedPath = normalizeArray(\n resolvedPath.split('/').filter(p => !!p),\n !resolvedAbsolute,\n ).join('/');\n\n return (resolvedAbsolute ? '/' : '') + resolvedPath || '.';\n}\n\n/** JSDoc */\nfunction trim(arr: string[]): string[] {\n let start = 0;\n for (; start < arr.length; start++) {\n if (arr[start] !== '') {\n break;\n }\n }\n\n let end = arr.length - 1;\n for (; end >= 0; end--) {\n if (arr[end] !== '') {\n break;\n }\n }\n\n if (start > end) {\n return [];\n }\n return arr.slice(start, end - start + 1);\n}\n\n// path.relative(from, to)\n// posix version\n/** JSDoc */\nexport function relative(from: string, to: string): string {\n /* eslint-disable no-param-reassign */\n from = resolve(from).slice(1);\n to = resolve(to).slice(1);\n /* eslint-enable no-param-reassign */\n\n const fromParts = trim(from.split('/'));\n const toParts = trim(to.split('/'));\n\n const length = Math.min(fromParts.length, toParts.length);\n let samePartsLength = length;\n for (let i = 0; i < length; i++) {\n if (fromParts[i] !== toParts[i]) {\n samePartsLength = i;\n break;\n }\n }\n\n let outputParts = [];\n for (let i = samePartsLength; i < fromParts.length; i++) {\n outputParts.push('..');\n }\n\n outputParts = outputParts.concat(toParts.slice(samePartsLength));\n\n return outputParts.join('/');\n}\n\n// path.normalize(path)\n// posix version\n/** JSDoc */\nexport function normalizePath(path: string): string {\n const isPathAbsolute = isAbsolute(path);\n const trailingSlash = path.slice(-1) === '/';\n\n // Normalize the path\n let normalizedPath = normalizeArray(\n path.split('/').filter(p => !!p),\n !isPathAbsolute,\n ).join('/');\n\n if (!normalizedPath && !isPathAbsolute) {\n normalizedPath = '.';\n }\n if (normalizedPath && trailingSlash) {\n normalizedPath += '/';\n }\n\n return (isPathAbsolute ? '/' : '') + normalizedPath;\n}\n\n// posix version\n/** JSDoc */\nexport function isAbsolute(path: string): boolean {\n return path.charAt(0) === '/';\n}\n\n// posix version\n/** JSDoc */\nexport function join(...args: string[]): string {\n return normalizePath(args.join('/'));\n}\n\n/** JSDoc */\nexport function dirname(path: string): string {\n const result = splitPath(path);\n const root = result[0];\n let dir = result[1];\n\n if (!root && !dir) {\n // No dirname whatsoever\n return '.';\n }\n\n if (dir) {\n // It has a dirname, strip trailing slash\n dir = dir.slice(0, dir.length - 1);\n }\n\n return root + dir;\n}\n\n/** JSDoc */\nexport function basename(path: string, ext?: string): string {\n let f = splitPath(path)[2];\n if (ext && f.slice(ext.length * -1) === ext) {\n f = f.slice(0, f.length - ext.length);\n }\n return f;\n}\n","/* eslint-disable @typescript-eslint/explicit-function-return-type */\n/* eslint-disable @typescript-eslint/typedef */\n/* eslint-disable @typescript-eslint/explicit-module-boundary-types */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { isThenable } from './is';\n\n/** SyncPromise internal states */\nconst enum States {\n /** Pending */\n PENDING = 0,\n /** Resolved / OK */\n RESOLVED = 1,\n /** Rejected / Error */\n REJECTED = 2,\n}\n\n// Overloads so we can call resolvedSyncPromise without arguments and generic argument\nexport function resolvedSyncPromise(): PromiseLike<void>;\nexport function resolvedSyncPromise<T>(value: T | PromiseLike<T>): PromiseLike<T>;\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;\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 this._state = States.PENDING;\n this._handlers = [];\n\n try {\n executor(this._resolve, this._reject);\n } catch (e) {\n this._reject(e);\n }\n }\n\n /** JSDoc */\n public then<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 { SyncPromise, rejectedSyncPromise, resolvedSyncPromise } 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 because buffer limit was 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 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","/**\n * This code was originally copied from the 'cookie` module at v0.5.0 and was simplified for our use case.\n * https://github.com/jshttp/cookie/blob/a0c84147aab6266bdb3996cf4062e93907c0b0fc/index.js\n * It had the following license:\n *\n * (The MIT License)\n *\n * Copyright (c) 2012-2014 Roman Shtylman <shtylman@gmail.com>\n * Copyright (c) 2015 Douglas Christopher Wilson <doug@somethingdoug.com>\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * 'Software'), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n\n/**\n * Parses a cookie string\n */\nexport function parseCookie(str: string): Record<string, string> {\n const obj: Record<string, string> = {};\n let index = 0;\n\n while (index < str.length) {\n const eqIdx = str.indexOf('=', index);\n\n // no more cookie pairs\n if (eqIdx === -1) {\n break;\n }\n\n let endIdx = str.indexOf(';', index);\n\n if (endIdx === -1) {\n endIdx = str.length;\n } else if (endIdx < eqIdx) {\n // backtrack on prior semicolon\n index = str.lastIndexOf(';', eqIdx - 1) + 1;\n continue;\n }\n\n const key = str.slice(index, eqIdx).trim();\n\n // only assign once\n if (undefined === obj[key]) {\n let val = str.slice(eqIdx + 1, endIdx).trim();\n\n // quoted values\n if (val.charCodeAt(0) === 0x22) {\n val = val.slice(1, -1);\n }\n\n try {\n obj[key] = val.indexOf('%') !== -1 ? decodeURIComponent(val) : val;\n } catch (e) {\n obj[key] = val;\n }\n }\n\n index = endIdx + 1;\n }\n\n return obj;\n}\n","type PartialURL = {\n host?: string;\n path?: string;\n protocol?: string;\n relative?: string;\n search?: string;\n hash?: string;\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): PartialURL {\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 search: query,\n hash: fragment,\n relative: match[5] + query + fragment, // everything minus origin\n };\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 * Returns number of URL segments of a passed string URL.\n */\nexport function getNumberOfUrlSegments(url: string): number {\n // split at '/' or at '\\/' to split regex urls correctly\n return url.split(/\\\\?\\//).filter(s => s.length > 0 && s !== ',').length;\n}\n\n/**\n * Takes a URL object and returns a sanitized string which is safe to use as span description\n * see: https://develop.sentry.dev/sdk/data-handling/#structuring-data\n */\nexport function getSanitizedUrlString(url: PartialURL): string {\n const { protocol, host, path } = url;\n\n const filteredHost =\n (host &&\n host\n // Always filter out authority\n .replace(/^.*@/, '[filtered]:[filtered]@')\n // Don't show standard :80 (http) and :443 (https) ports to reduce the noise\n // TODO: Use new URL global if it exists\n .replace(/(:80)$/, '')\n .replace(/(:443)$/, '')) ||\n '';\n\n return `${protocol ? `${protocol}://` : ''}${filteredHost}${path}`;\n}\n","import type {\n Event,\n ExtractedNodeRequestData,\n PolymorphicRequest,\n Transaction,\n TransactionSource,\n WebFetchHeaders,\n WebFetchRequest,\n} from '@sentry/types';\n\nimport { parseCookie } from './cookie';\nimport { DEBUG_BUILD } from './debug-build';\nimport { isPlainObject, isString } from './is';\nimport { logger } from './logger';\nimport { normalize } from './normalize';\nimport { stripUrlQueryAndFragment } from './url';\n\nconst DEFAULT_INCLUDES = {\n ip: false,\n request: true,\n transaction: true,\n user: true,\n};\nconst DEFAULT_REQUEST_INCLUDES = ['cookies', 'data', 'headers', 'method', 'query_string', 'url'];\nexport const DEFAULT_USER_INCLUDES = ['id', 'username', 'email'];\n\ntype InjectedNodeDeps = {\n cookie: {\n parse: (cookieStr: string) => Record<string, string>;\n };\n url: {\n parse: (urlStr: string) => {\n query: string | null;\n };\n };\n};\n\n/**\n * Options deciding what parts of the request to use when enhancing an event\n */\nexport type AddRequestDataToEventOptions = {\n /** Flags controlling whether each type of data should be added to the event */\n include?: {\n ip?: boolean;\n request?: boolean | Array<(typeof DEFAULT_REQUEST_INCLUDES)[number]>;\n transaction?: boolean | TransactionNamingScheme;\n user?: boolean | Array<(typeof DEFAULT_USER_INCLUDES)[number]>;\n };\n\n /** Injected platform-specific dependencies */\n deps?: {\n cookie: {\n parse: (cookieStr: string) => Record<string, string>;\n };\n url: {\n parse: (urlStr: string) => {\n query: string | null;\n };\n };\n };\n};\n\nexport type TransactionNamingScheme = 'path' | 'methodPath' | 'handler';\n\n/**\n * Sets parameterized route as transaction name e.g.: `GET /users/:id`\n * Also adds more context data on the transaction from the request.\n *\n * @deprecated This utility will be removed in v8.\n */\nexport function addRequestDataToTransaction(\n transaction: Transaction | undefined,\n req: PolymorphicRequest,\n deps?: InjectedNodeDeps,\n): void {\n if (!transaction) return;\n // eslint-disable-next-line deprecation/deprecation\n if (!transaction.metadata.source || transaction.metadata.source === 'url') {\n // Attempt to grab a parameterized route off of the request\n const [name, source] = extractPathForTransaction(req, { path: true, method: true });\n transaction.updateName(name);\n // TODO: SEMANTIC_ATTRIBUTE_SENTRY_SOURCE is in core, align this once we merge utils & core\n // eslint-disable-next-line deprecation/deprecation\n transaction.setMetadata({ source });\n }\n transaction.setAttribute('url', req.originalUrl || req.url);\n if (req.baseUrl) {\n transaction.setAttribute('baseUrl', req.baseUrl);\n }\n // TODO: We need to rewrite this to a flat format?\n // eslint-disable-next-line deprecation/deprecation\n transaction.setData('query', extractQueryParams(req, deps));\n}\n\n/**\n * Extracts a complete and parameterized path from the request object and uses it to construct transaction name.\n * If the parameterized transaction name cannot be extracted, we fall back to the raw URL.\n *\n * Additionally, this function determines and returns the transaction name source\n *\n * eg. GET /mountpoint/user/:id\n *\n * @param req A request object\n * @param options What to include in the transaction name (method, path, or a custom route name to be\n * used instead of the request's route)\n *\n * @returns A tuple of the fully constructed transaction name [0] and its source [1] (can be either 'route' or 'url')\n */\nexport function extractPathForTransaction(\n req: PolymorphicRequest,\n options: { path?: boolean; method?: boolean; customRoute?: string } = {},\n): [string, TransactionSource] {\n const method = req.method && req.method.toUpperCase();\n\n let path = '';\n let source: TransactionSource = 'url';\n\n // Check to see if there's a parameterized route we can use (as there is in Express)\n if (options.customRoute || req.route) {\n path = options.customRoute || `${req.baseUrl || ''}${req.route && req.route.path}`;\n source = 'route';\n }\n\n // Otherwise, just take the original URL\n else if (req.originalUrl || req.url) {\n path = stripUrlQueryAndFragment(req.originalUrl || req.url || '');\n }\n\n let name = '';\n if (options.method && method) {\n name += method;\n }\n if (options.method && options.path) {\n name += ' ';\n }\n if (options.path && path) {\n name += path;\n }\n\n return [name, source];\n}\n\n/** JSDoc */\nfunction extractTransaction(req: PolymorphicRequest, type: boolean | TransactionNamingScheme): string {\n switch (type) {\n case 'path': {\n return extractPathForTransaction(req, { path: true })[0];\n }\n case 'handler': {\n return (req.route && req.route.stack && req.route.stack[0] && req.route.stack[0].name) || '<anonymous>';\n }\n case 'methodPath':\n default: {\n // if exist _reconstructedRoute return that path instead of route.path\n const customRoute = req._reconstructedRoute ? req._reconstructedRoute : undefined;\n return extractPathForTransaction(req, { path: true, method: true, customRoute })[0];\n }\n }\n}\n\n/** JSDoc */\nfunction extractUserData(\n user: {\n [key: string]: unknown;\n },\n keys: boolean | string[],\n): { [key: string]: unknown } {\n const extractedUser: { [key: string]: unknown } = {};\n const attributes = Array.isArray(keys) ? keys : DEFAULT_USER_INCLUDES;\n\n attributes.forEach(key => {\n if (user && key in user) {\n extractedUser[key] = user[key];\n }\n });\n\n return extractedUser;\n}\n\n/**\n * Normalize data from the request object, accounting for framework differences.\n *\n * @param req The request object from which to extract data\n * @param options.include An optional array of keys to include in the normalized data. Defaults to\n * DEFAULT_REQUEST_INCLUDES if not provided.\n * @param options.deps Injected, platform-specific dependencies\n * @returns An object containing normalized request data\n */\nexport function extractRequestData(\n req: PolymorphicRequest,\n options?: {\n include?: string[];\n deps?: InjectedNodeDeps;\n },\n): ExtractedNodeRequestData {\n const { include = DEFAULT_REQUEST_INCLUDES, deps } = options || {};\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const requestData: { [key: string]: any } = {};\n\n // headers:\n // node, express, koa, nextjs: req.headers\n const headers = (req.headers || {}) as {\n host?: string;\n cookie?: string;\n };\n // method:\n // node, express, koa, nextjs: req.method\n const method = req.method;\n // host:\n // express: req.hostname in > 4 and req.host in < 4\n // koa: req.host\n // node, nextjs: req.headers.host\n // Express 4 mistakenly strips off port number from req.host / req.hostname so we can't rely on them\n // See: https://github.com/expressjs/express/issues/3047#issuecomment-236653223\n // Also: https://github.com/getsentry/sentry-javascript/issues/1917\n const host = headers.host || req.hostname || req.host || '<no host>';\n // protocol:\n // node, nextjs: <n/a>\n // express, koa: req.protocol\n const protocol = req.protocol === 'https' || (req.socket && req.socket.encrypted) ? 'https' : 'http';\n // url (including path and query string):\n // node, express: req.originalUrl\n // koa, nextjs: req.url\n const originalUrl = req.originalUrl || req.url || '';\n // absolute url\n const absoluteUrl = originalUrl.startsWith(protocol) ? originalUrl : `${protocol}://${host}${originalUrl}`;\n include.forEach(key => {\n switch (key) {\n case 'headers': {\n requestData.headers = headers;\n\n // Remove the Cookie header in case cookie data should not be included in the event\n if (!include.includes('cookies')) {\n delete (requestData.headers as { cookie?: string }).cookie;\n }\n\n break;\n }\n case 'method': {\n requestData.method = method;\n break;\n }\n case 'url': {\n requestData.url = absoluteUrl;\n break;\n }\n case 'cookies': {\n // cookies:\n // node, express, koa: req.headers.cookie\n // vercel, sails.js, express (w/ cookie middleware), nextjs: req.cookies\n requestData.cookies =\n // TODO (v8 / #5257): We're only sending the empty object for backwards compatibility, so the last bit can\n // come off in v8\n req.cookies || (headers.cookie && parseCookie(headers.cookie)) || {};\n break;\n }\n case 'query_string': {\n // query string:\n // node: req.url (raw)\n // express, koa, nextjs: req.query\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n requestData.query_string = extractQueryParams(req, deps);\n break;\n }\n case 'data': {\n if (method === 'GET' || method === 'HEAD') {\n break;\n }\n // body data:\n // express, koa, nextjs: req.body\n //\n // when using node by itself, you have to read the incoming stream(see\n // https://nodejs.dev/learn/get-http-request-body-data-using-nodejs); if a user is doing that, we can't know\n // where they're going to store the final result, so they'll have to capture this data themselves\n if (req.body !== undefined) {\n requestData.data = isString(req.body) ? req.body : JSON.stringify(normalize(req.body));\n }\n break;\n }\n default: {\n if ({}.hasOwnProperty.call(req, key)) {\n requestData[key] = (req as { [key: string]: unknown })[key];\n }\n }\n }\n });\n\n return requestData;\n}\n\n/**\n * Add data from the given request to the given event\n *\n * @param event The event to which the request data will be added\n * @param req Request object\n * @param options.include Flags to control what data is included\n * @param options.deps Injected platform-specific dependencies\n * @returns The mutated `Event` object\n */\nexport function addRequestDataToEvent(\n event: Event,\n req: PolymorphicRequest,\n options?: AddRequestDataToEventOptions,\n): Event {\n const include = {\n ...DEFAULT_INCLUDES,\n ...(options && options.include),\n };\n\n if (include.request) {\n const extractedRequestData = Array.isArray(include.request)\n ? extractRequestData(req, { include: include.request, deps: options && options.deps })\n : extractRequestData(req, { deps: options && options.deps });\n\n event.request = {\n ...event.request,\n ...extractedRequestData,\n };\n }\n\n if (include.user) {\n const extractedUser = req.user && isPlainObject(req.user) ? extractUserData(req.user, include.user) : {};\n\n if (Object.keys(extractedUser).length) {\n event.user = {\n ...event.user,\n ...extractedUser,\n };\n }\n }\n\n // client ip:\n // node, nextjs: req.socket.remoteAddress\n // express, koa: req.ip\n if (include.ip) {\n const ip = req.ip || (req.socket && req.socket.remoteAddress);\n if (ip) {\n event.user = {\n ...event.user,\n ip_address: ip,\n };\n }\n }\n\n if (include.transaction && !event.transaction) {\n // TODO do we even need this anymore?\n // TODO make this work for nextjs\n event.transaction = extractTransaction(req, include.transaction);\n }\n\n return event;\n}\n\nfunction extractQueryParams(\n req: PolymorphicRequest,\n deps?: InjectedNodeDeps,\n): string | Record<string, unknown> | undefined {\n // url (including path and query string):\n // node, express: req.originalUrl\n // koa, nextjs: req.url\n let originalUrl = req.originalUrl || req.url || '';\n\n if (!originalUrl) {\n return;\n }\n\n // The `URL` constructor can't handle internal URLs of the form `/some/path/here`, so stick a dummy protocol and\n // hostname on the beginning. Since the point here is just to grab the query string, it doesn't matter what we use.\n if (originalUrl.startsWith('/')) {\n originalUrl = `http://dogs.are.great${originalUrl}`;\n }\n\n try {\n return (\n req.query ||\n (typeof URL !== 'undefined' && new URL(originalUrl).search.slice(1)) ||\n // In Node 8, `URL` isn't in the global scope, so we have to use the built-in module from Node\n (deps && deps.url && deps.url.parse(originalUrl).query) ||\n undefined\n );\n } catch {\n return undefined;\n }\n}\n\n/**\n * Transforms a `Headers` object that implements the `Web Fetch API` (https://developer.mozilla.org/en-US/docs/Web/API/Headers) into a simple key-value dict.\n * The header keys will be lower case: e.g. A \"Content-Type\" header will be stored as \"content-type\".\n */\n// TODO(v8): Make this function return undefined when the extraction fails.\nexport function winterCGHeadersToDict(winterCGHeaders: WebFetchHeaders): Record<string, string> {\n const headers: Record<string, string> = {};\n try {\n winterCGHeaders.forEach((value, key) => {\n if (typeof value === 'string') {\n // We check that value is a string even though it might be redundant to make sure prototype pollution is not possible.\n headers[key] = value;\n }\n });\n } catch (e) {\n DEBUG_BUILD &&\n logger.warn('Sentry failed extracting headers from a request object. If you see this, please file an issue.');\n }\n\n return headers;\n}\n\n/**\n * Converts a `Request` object that implements the `Web Fetch API` (https://developer.mozilla.org/en-US/docs/Web/API/Headers) into the format that the `RequestData` integration understands.\n */\nexport function winterCGRequestToRequestData(req: WebFetchRequest): PolymorphicRequest {\n const headers = winterCGHeadersToDict(req.headers);\n return {\n method: req.method,\n url: req.url,\n headers,\n };\n}\n","/* eslint-disable deprecation/deprecation */\nimport type { Severity, SeverityLevel } from '@sentry/types';\n\n// Note: Ideally the `SeverityLevel` type would be derived from `validSeverityLevels`, but that would mean either\n//\n// a) moving `validSeverityLevels` to `@sentry/types`,\n// b) moving the`SeverityLevel` type here, or\n// c) importing `validSeverityLevels` from here into `@sentry/types`.\n//\n// Option A would make `@sentry/types` a runtime dependency of `@sentry/utils` (not good), and options B and C would\n// create a circular dependency between `@sentry/types` and `@sentry/utils` (also not good). So a TODO accompanying the\n// type, reminding anyone who changes it to change this list also, will have to do.\n\nexport const validSeverityLevels = ['fatal', 'error', 'warning', 'log', 'info', 'debug'];\n\n/**\n * Converts a string-based level into a member of the deprecated {@link Severity} enum.\n *\n * @deprecated `severityFromString` is deprecated. Please use `severityLevelFromString` instead.\n *\n * @param level String representation of Severity\n * @returns Severity\n */\nexport function severityFromString(level: Severity | SeverityLevel | string): Severity {\n return severityLevelFromString(level) as Severity;\n}\n\n/**\n * Converts a string-based level into a `SeverityLevel`, normalizing it along the way.\n *\n * @param level String representation of desired `SeverityLevel`.\n * @returns The `SeverityLevel` corresponding to the given string, or 'log' if the string isn't a valid level.\n */\nexport function severityLevelFromString(level: SeverityLevel | string): SeverityLevel {\n return (level === 'warn' ? 'warning' : validSeverityLevels.includes(level) ? level : 'log') as SeverityLevel;\n}\n","import { GLOBAL_OBJ } from './worldwide';\n\nconst ONE_SECOND_IN_MS = 1000;\n\n/**\n * A partial definition of the [Performance Web API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Performance}\n * for accessing a high-resolution monotonic clock.\n */\ninterface Performance {\n /**\n * The millisecond timestamp at which measurement began, measured in Unix time.\n */\n timeOrigin: number;\n /**\n * Returns the current millisecond timestamp, where 0 represents the start of measurement.\n */\n now(): number;\n}\n\n/**\n * Returns a timestamp in seconds since the UNIX epoch using the Date API.\n *\n * TODO(v8): Return type should be rounded.\n */\nexport function dateTimestampInSeconds(): number {\n return Date.now() / ONE_SECOND_IN_MS;\n}\n\n/**\n * Returns a wrapper around the native Performance API browser implementation, or undefined for browsers that do not\n * support the API.\n *\n * Wrapping the native API works around differences in behavior from different browsers.\n */\nfunction createUnixTimestampInSecondsFunc(): () => number {\n const { performance } = GLOBAL_OBJ as typeof GLOBAL_OBJ & { performance?: Performance };\n if (!performance || !performance.now) {\n return dateTimestampInSeconds;\n }\n\n // Some browser and environments don't have a timeOrigin, so we fallback to\n // using Date.now() to compute the starting time.\n const approxStartingTimeOrigin = Date.now() - performance.now();\n const timeOrigin = performance.timeOrigin == undefined ? approxStartingTimeOrigin : performance.timeOrigin;\n\n // performance.now() is a monotonic clock, which means it starts at 0 when the process begins. To get the current\n // wall clock time (actual UNIX timestamp), we need to add the starting time origin and the current time elapsed.\n //\n // TODO: This does not account for the case where the monotonic clock that powers performance.now() drifts from the\n // wall clock time, which causes the returned timestamp to be inaccurate. We should investigate how to detect and\n // correct for this.\n // See: https://github.com/getsentry/sentry-javascript/issues/2590\n // See: https://github.com/mdn/content/issues/4713\n // See: https://dev.to/noamr/when-a-millisecond-is-not-a-millisecond-3h6\n return () => {\n return (timeOrigin + performance.now()) / ONE_SECOND_IN_MS;\n };\n}\n\n/**\n * Returns a timestamp in seconds since the UNIX epoch using either the Performance or Date APIs, depending on the\n * availability of the Performance API.\n *\n * BUG: Note that because of how browsers implement the Performance API, the clock might stop when the computer is\n * asleep. This creates a skew between `dateTimestampInSeconds` and `timestampInSeconds`. The\n * skew can grow to arbitrary amounts like days, weeks or months.\n * See https://github.com/getsentry/sentry-javascript/issues/2590.\n */\nexport const timestampInSeconds = createUnixTimestampInSecondsFunc();\n\n/**\n * Re-exported with an old name for backwards-compatibility.\n * TODO (v8): Remove this\n *\n * @deprecated Use `timestampInSeconds` instead.\n */\nexport const timestampWithMs = timestampInSeconds;\n\n/**\n * Internal helper to store what is the source of browserPerformanceTimeOrigin below. For debugging only.\n */\nexport let _browserPerformanceTimeOriginMode: string;\n\n/**\n * The number of milliseconds since the UNIX epoch. This value is only usable in a browser, and only when the\n * performance API is available.\n */\nexport const browserPerformanceTimeOrigin = ((): number | undefined => {\n // Unfortunately browsers may report an inaccurate time origin data, through either performance.timeOrigin or\n // performance.timing.navigationStart, which results in poor results in performance data. We only treat time origin\n // data as reliable if they are within a reasonable threshold of the current time.\n\n const { performance } = GLOBAL_OBJ as typeof GLOBAL_OBJ & Window;\n if (!performance || !performance.now) {\n _browserPerformanceTimeOriginMode = 'none';\n return undefined;\n }\n\n const threshold = 3600 * 1000;\n const performanceNow = performance.now();\n const dateNow = Date.now();\n\n // if timeOrigin isn't available set delta to threshold so it isn't used\n const timeOriginDelta = performance.timeOrigin\n ? Math.abs(performance.timeOrigin + performanceNow - dateNow)\n : threshold;\n const timeOriginIsReliable = timeOriginDelta < threshold;\n\n // While performance.timing.navigationStart is deprecated in favor of performance.timeOrigin, performance.timeOrigin\n // is not as widely supported. Namely, performance.timeOrigin is undefined in Safari as of writing.\n // Also as of writing, performance.timing is not available in Web Workers in mainstream browsers, so it is not always\n // a valid fallback. In the absence of an initial time provided by the browser, fallback to the current time from the\n // Date API.\n // eslint-disable-next-line deprecation/deprecation\n const navigationStart = performance.timing && performance.timing.navigationStart;\n const hasNavigationStart = typeof navigationStart === 'number';\n // if navigationStart isn't available set delta to threshold so it isn't used\n const navigationStartDelta = hasNavigationStart ? Math.abs(navigationStart + performanceNow - dateNow) : threshold;\n const navigationStartIsReliable = navigationStartDelta < threshold;\n\n if (timeOriginIsReliable || navigationStartIsReliable) {\n // Use the more reliable time origin\n if (timeOriginDelta <= navigationStartDelta) {\n _browserPerformanceTimeOriginMode = 'timeOrigin';\n return performance.timeOrigin;\n } else {\n _browserPerformanceTimeOriginMode = 'navigationStart';\n return navigationStart;\n }\n }\n\n // Either both timeOrigin and navigationStart are skewed or neither is available, fallback to Date.\n _browserPerformanceTimeOriginMode = 'dateNow';\n return dateNow;\n})();\n","import type { DynamicSamplingContext } from '@sentry/types';\n\nimport { DEBUG_BUILD } from './debug-build';\nimport { isString } from './is';\nimport { logger } from './logger';\n\nexport const BAGGAGE_HEADER_NAME = 'baggage';\n\nexport const SENTRY_BAGGAGE_KEY_PREFIX = 'sentry-';\n\nexport const SENTRY_BAGGAGE_KEY_PREFIX_REGEX = /^sentry-/;\n\n/**\n * Max length of a serialized baggage string\n *\n * https://www.w3.org/TR/baggage/#limits\n */\nexport const MAX_BAGGAGE_STRING_LENGTH = 8192;\n\n/**\n * Takes a baggage header and turns it into Dynamic Sampling Context, by extracting all the \"sentry-\" prefixed values\n * from it.\n *\n * @param baggageHeader A very bread definition of a baggage header as it might appear in various frameworks.\n * @returns The Dynamic Sampling Context that was found on `baggageHeader`, if there was any, `undefined` otherwise.\n */\nexport function baggageHeaderToDynamicSamplingContext(\n // Very liberal definition of what any incoming header might look like\n baggageHeader: string | string[] | number | null | undefined | boolean,\n): Partial<DynamicSamplingContext> | undefined {\n if (!isString(baggageHeader) && !Array.isArray(baggageHeader)) {\n return undefined;\n }\n\n // Intermediary object to store baggage key value pairs of incoming baggage headers on.\n // It is later used to read Sentry-DSC-values from.\n let baggageObject: Readonly<Record<string, string>> = {};\n\n if (Array.isArray(baggageHeader)) {\n // Combine all baggage headers into one object containing the baggage values so we can later read the Sentry-DSC-values from it\n baggageObject = baggageHeader.reduce<Record<string, string>>((acc, curr) => {\n const currBaggageObject = baggageHeaderToObject(curr);\n for (const key of Object.keys(currBaggageObject)) {\n acc[key] = currBaggageObject[key];\n }\n return acc;\n }, {});\n } else {\n // Return undefined if baggage header is an empty string (technically an empty baggage header is not spec conform but\n // this is how we choose to handle it)\n if (!baggageHeader) {\n return undefined;\n }\n\n baggageObject = baggageHeaderToObject(baggageHeader);\n }\n\n // Read all \"sentry-\" prefixed values out of the baggage object and put it onto a dynamic sampling context object.\n const dynamicSamplingContext = Object.entries(baggageObject).reduce<Record<string, string>>((acc, [key, value]) => {\n if (key.match(SENTRY_BAGGAGE_KEY_PREFIX_REGEX)) {\n const nonPrefixedKey = key.slice(SENTRY_BAGGAGE_KEY_PREFIX.length);\n acc[nonPrefixedKey] = value;\n }\n return acc;\n }, {});\n\n // Only return a dynamic sampling context object if there are keys in it.\n // A keyless object means there were no sentry values on the header, which means that there is no DSC.\n if (Object.keys(dynamicSamplingContext).length > 0) {\n return dynamicSamplingContext as Partial<DynamicSamplingContext>;\n } else {\n return undefined;\n }\n}\n\n/**\n * Turns a Dynamic Sampling Object into a baggage header by prefixing all the keys on the object with \"sentry-\".\n *\n * @param dynamicSamplingContext The Dynamic Sampling Context to turn into a header. For convenience and compatibility\n * with the `getDynamicSamplingContext` method on the Transaction class ,this argument can also be `undefined`. If it is\n * `undefined` the function will return `undefined`.\n * @returns a baggage header, created from `dynamicSamplingContext`, or `undefined` either if `dynamicSamplingContext`\n * was `undefined`, or if `dynamicSamplingContext` didn't contain any values.\n */\nexport function dynamicSamplingContextToSentryBaggageHeader(\n // this also takes undefined for convenience and bundle size in other places\n dynamicSamplingContext?: Partial<DynamicSamplingContext>,\n): string | undefined {\n if (!dynamicSamplingContext) {\n return undefined;\n }\n\n // Prefix all DSC keys with \"sentry-\" and put them into a new object\n const sentryPrefixedDSC = Object.entries(dynamicSamplingContext).reduce<Record<string, string>>(\n (acc, [dscKey, dscValue]) => {\n if (dscValue) {\n acc[`${SENTRY_BAGGAGE_KEY_PREFIX}${dscKey}`] = dscValue;\n }\n return acc;\n },\n {},\n );\n\n return objectToBaggageHeader(sentryPrefixedDSC);\n}\n\n/**\n * Will parse a baggage header, which is a simple key-value map, into a flat object.\n *\n * @param baggageHeader The baggage header to parse.\n * @returns a flat object containing all the key-value pairs from `baggageHeader`.\n */\nfunction baggageHeaderToObject(baggageHeader: string): Record<string, string> {\n return baggageHeader\n .split(',')\n .map(baggageEntry => baggageEntry.split('=').map(keyOrValue => decodeURIComponent(keyOrValue.trim())))\n .reduce<Record<string, string>>((acc, [key, value]) => {\n acc[key] = value;\n return acc;\n }, {});\n}\n\n/**\n * Turns a flat object (key-value pairs) into a baggage header, which is also just key-value pairs.\n *\n * @param object The object to turn into a baggage header.\n * @returns a baggage header string, or `undefined` if the object didn't have any values, since an empty baggage header\n * is not spec compliant.\n */\nfunction objectToBaggageHeader(object: Record<string, string>): string | undefined {\n if (Object.keys(object).length === 0) {\n // An empty baggage header is not spec compliant: We return undefined.\n return undefined;\n }\n\n return Object.entries(object).reduce((baggageHeader, [objectKey, objectValue], currentIndex) => {\n const baggageEntry = `${encodeURIComponent(objectKey)}=${encodeURIComponent(objectValue)}`;\n const newBaggageHeader = currentIndex === 0 ? baggageEntry : `${baggageHeader},${baggageEntry}`;\n if (newBaggageHeader.length > MAX_BAGGAGE_STRING_LENGTH) {\n DEBUG_BUILD &&\n logger.warn(\n `Not adding key: ${objectKey} with val: ${objectValue} to baggage header due to exceeding baggage size limits.`,\n );\n return baggageHeader;\n } else {\n return newBaggageHeader;\n }\n }, '');\n}\n","import type { PropagationContext, TraceparentData } from '@sentry/types';\n\nimport { baggageHeaderToDynamicSamplingContext } from './baggage';\nimport { uuid4 } from './misc';\n\n// eslint-disable-next-line @sentry-internal/sdk/no-regexp-constructor -- RegExp is used for readability here\nexport const TRACEPARENT_REGEXP = new RegExp(\n '^[ \\\\t]*' + // whitespace\n '([0-9a-f]{32})?' + // trace_id\n '-?([0-9a-f]{16})?' + // span_id\n '-?([01])?' + // sampled\n '[ \\\\t]*$', // whitespace\n);\n\n/**\n * Extract transaction context data from a `sentry-trace` header.\n *\n * @param traceparent Traceparent string\n *\n * @returns Object containing data from the header, or undefined if traceparent string is malformed\n */\nexport function extractTraceparentData(traceparent?: string): TraceparentData | undefined {\n if (!traceparent) {\n return undefined;\n }\n\n const matches = traceparent.match(TRACEPARENT_REGEXP);\n if (!matches) {\n return undefined;\n }\n\n let parentSampled: boolean | undefined;\n if (matches[3] === '1') {\n parentSampled = true;\n } else if (matches[3] === '0') {\n parentSampled = false;\n }\n\n return {\n traceId: matches[1],\n parentSampled,\n parentSpanId: matches[2],\n };\n}\n\n/**\n * Create tracing context from incoming headers.\n *\n * @deprecated Use `propagationContextFromHeaders` instead.\n */\n// TODO(v8): Remove this function\nexport function tracingContextFromHeaders(\n sentryTrace: Parameters<typeof extractTraceparentData>[0],\n baggage: Parameters<typeof baggageHeaderToDynamicSamplingContext>[0],\n): {\n traceparentData: ReturnType<typeof extractTraceparentData>;\n dynamicSamplingContext: ReturnType<typeof baggageHeaderToDynamicSamplingContext>;\n propagationContext: PropagationContext;\n} {\n const traceparentData = extractTraceparentData(sentryTrace);\n const dynamicSamplingContext = baggageHeaderToDynamicSamplingContext(baggage);\n\n const { traceId, parentSpanId, parentSampled } = traceparentData || {};\n\n if (!traceparentData) {\n return {\n traceparentData,\n dynamicSamplingContext: undefined,\n propagationContext: {\n traceId: traceId || uuid4(),\n spanId: uuid4().substring(16),\n },\n };\n } else {\n return {\n traceparentData,\n dynamicSamplingContext: dynamicSamplingContext || {}, // If we have traceparent data but no DSC it means we are not head of trace and we must freeze it\n propagationContext: {\n traceId: traceId || uuid4(),\n parentSpanId: parentSpanId || uuid4().substring(16),\n spanId: uuid4().substring(16),\n sampled: parentSampled,\n dsc: dynamicSamplingContext || {}, // If we have traceparent data but no DSC it means we are not head of trace and we must freeze it\n },\n };\n }\n}\n\n/**\n * Create a propagation context from incoming headers.\n */\nexport function propagationContextFromHeaders(\n sentryTrace: string | undefined,\n baggage: string | number | boolean | string[] | null | undefined,\n): PropagationContext {\n const traceparentData = extractTraceparentData(sentryTrace);\n const dynamicSamplingContext = baggageHeaderToDynamicSamplingContext(baggage);\n\n const { traceId, parentSpanId, parentSampled } = traceparentData || {};\n\n if (!traceparentData) {\n return {\n traceId: traceId || uuid4(),\n spanId: uuid4().substring(16),\n };\n } else {\n return {\n traceId: traceId || uuid4(),\n parentSpanId: parentSpanId || uuid4().substring(16),\n spanId: uuid4().substring(16),\n sampled: parentSampled,\n dsc: dynamicSamplingContext || {}, // If we have traceparent data but no DSC it means we are not head of trace and we must freeze it\n };\n }\n}\n\n/**\n * Create sentry-trace header from span context values.\n */\nexport function generateSentryTraceHeader(\n traceId: string = uuid4(),\n spanId: string = uuid4().substring(16),\n sampled?: boolean,\n): string {\n let sampledString = '';\n if (sampled !== undefined) {\n sampledString = sampled ? '-1' : '-0';\n }\n return `${traceId}-${spanId}${sampledString}`;\n}\n","import type {\n Attachment,\n AttachmentItem,\n BaseEnvelopeHeaders,\n BaseEnvelopeItemHeaders,\n DataCategory,\n DsnComponents,\n Envelope,\n EnvelopeItemType,\n Event,\n EventEnvelopeHeaders,\n SdkInfo,\n SdkMetadata,\n TextEncoderInternal,\n} from '@sentry/types';\n\nimport { dsnToString } from './dsn';\nimport { normalize } from './normalize';\nimport { dropUndefinedKeys } from './object';\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 unknown as E;\n}\n\n/**\n * Convenience function to loop through the items and item types of an envelope.\n * (This function was mostly created because working with envelope types is painful at the moment)\n *\n * If the callback returns true, the rest of the items will be skipped.\n */\nexport function forEachEnvelopeItem<E extends Envelope>(\n envelope: Envelope,\n callback: (envelopeItem: E[1][number], envelopeItemType: E[1][number][0]['type']) => boolean | void,\n): boolean {\n const envelopeItems = envelope[1];\n\n for (const envelopeItem of envelopeItems) {\n const envelopeItemType = envelopeItem[0].type;\n const result = callback(envelopeItem, envelopeItemType);\n\n if (result) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Returns true if the envelope contains any of the given envelope item types\n */\nexport function envelopeContainsItemType(envelope: Envelope, types: EnvelopeItemType[]): boolean {\n return forEachEnvelopeItem(envelope, (_, type) => types.includes(type));\n}\n\n/**\n * Encode a string to UTF8.\n */\nfunction encodeUTF8(input: string, textEncoder?: TextEncoderInternal): Uint8Array {\n const utf8 = textEncoder || new TextEncoder();\n return utf8.encode(input);\n}\n\n/**\n * Serializes an envelope.\n */\nexport function serializeEnvelope(envelope: Envelope, textEncoder?: TextEncoderInternal): string | Uint8Array {\n const [envHeaders, items] = envelope;\n\n // Initially we construct our envelope as a string and only convert to binary chunks if we encounter binary data\n let parts: string | Uint8Array[] = JSON.stringify(envHeaders);\n\n function append(next: string | Uint8Array): void {\n if (typeof parts === 'string') {\n parts = typeof next === 'string' ? parts + next : [encodeUTF8(parts, textEncoder), next];\n } else {\n parts.push(typeof next === 'string' ? encodeUTF8(next, textEncoder) : next);\n }\n }\n\n for (const item of items) {\n const [itemHeaders, payload] = item;\n\n append(`\\n${JSON.stringify(itemHeaders)}\\n`);\n\n if (typeof payload === 'string' || payload instanceof Uint8Array) {\n append(payload);\n } else {\n let stringifiedPayload: string;\n try {\n stringifiedPayload = JSON.stringify(payload);\n } catch (e) {\n // In case, despite all our efforts to keep `payload` circular-dependency-free, `JSON.strinify()` still\n // fails, we try again after normalizing it again with infinite normalization depth. This of course has a\n // performance impact but in this case a performance hit is better than throwing.\n stringifiedPayload = JSON.stringify(normalize(payload));\n }\n append(stringifiedPayload);\n }\n }\n\n return typeof parts === 'string' ? parts : concatBuffers(parts);\n}\n\nfunction concatBuffers(buffers: Uint8Array[]): Uint8Array {\n const totalLength = buffers.reduce((acc, buf) => acc + buf.length, 0);\n\n const merged = new Uint8Array(totalLength);\n let offset = 0;\n for (const buffer of buffers) {\n merged.set(buffer, offset);\n offset += buffer.length;\n }\n\n return merged;\n}\n\nexport interface TextDecoderInternal {\n decode(input?: Uint8Array): string;\n}\n\n/**\n * Parses an envelope\n */\nexport function parseEnvelope(\n env: string | Uint8Array,\n textEncoder: TextEncoderInternal,\n textDecoder: TextDecoderInternal,\n): Envelope {\n let buffer = typeof env === 'string' ? textEncoder.encode(env) : env;\n\n function readBinary(length: number): Uint8Array {\n const bin = buffer.subarray(0, length);\n // Replace the buffer with the remaining data excluding trailing newline\n buffer = buffer.subarray(length + 1);\n return bin;\n }\n\n function readJson<T>(): T {\n let i = buffer.indexOf(0xa);\n // If we couldn't find a newline, we must have found the end of the buffer\n if (i < 0) {\n i = buffer.length;\n }\n\n return JSON.parse(textDecoder.decode(readBinary(i))) as T;\n }\n\n const envelopeHeader = readJson<BaseEnvelopeHeaders>();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const items: [any, any][] = [];\n\n while (buffer.length) {\n const itemHeader = readJson<BaseEnvelopeItemHeaders>();\n const binaryLength = typeof itemHeader.length === 'number' ? itemHeader.length : undefined;\n\n items.push([itemHeader, binaryLength ? readBinary(binaryLength) : readJson()]);\n }\n\n return [envelopeHeader, items];\n}\n\n/**\n * Creates attachment envelope items\n */\nexport function createAttachmentEnvelopeItem(\n attachment: Attachment,\n textEncoder?: TextEncoderInternal,\n): AttachmentItem {\n const buffer = typeof attachment.data === 'string' ? encodeUTF8(attachment.data, textEncoder) : attachment.data;\n\n return [\n dropUndefinedKeys({\n type: 'attachment',\n length: buffer.length,\n filename: attachment.filename,\n content_type: attachment.contentType,\n attachment_type: attachment.attachmentType,\n }),\n buffer,\n ];\n}\n\nconst ITEM_TYPE_TO_DATA_CATEGORY_MAP: Record<EnvelopeItemType, DataCategory> = {\n session: 'session',\n sessions: 'session',\n attachment: 'attachment',\n transaction: 'transaction',\n event: 'error',\n client_report: 'internal',\n user_report: 'default',\n profile: 'profile',\n replay_event: 'replay',\n replay_recording: 'replay',\n check_in: 'monitor',\n feedback: 'feedback',\n span: 'span',\n statsd: 'metric_bucket',\n};\n\n/**\n * Maps the type of an envelope item to a data category.\n */\nexport function envelopeItemTypeToDataCategory(type: EnvelopeItemType): DataCategory {\n return ITEM_TYPE_TO_DATA_CATEGORY_MAP[type];\n}\n\n/** Extracts the minimal SDK info from the metadata or an events */\nexport function getSdkMetadataForEnvelopeHeader(metadataOrEvent?: SdkMetadata | Event): SdkInfo | undefined {\n if (!metadataOrEvent || !metadataOrEvent.sdk) {\n return;\n }\n const { name, version } = metadataOrEvent.sdk;\n return { name, version };\n}\n\n/**\n * Creates event envelope headers, based on event, sdk info and tunnel\n * Note: This function was extracted from the core package to make it available in Replay\n */\nexport function createEventEnvelopeHeaders(\n event: Event,\n sdkInfo: SdkInfo | undefined,\n tunnel: string | undefined,\n dsn?: DsnComponents,\n): EventEnvelopeHeaders {\n const dynamicSamplingContext = event.sdkProcessingMetadata && event.sdkProcessingMetadata.dynamicSamplingContext;\n return {\n event_id: event.event_id as string,\n sent_at: new Date().toISOString(),\n ...(sdkInfo && { sdk: sdkInfo }),\n ...(!!tunnel && dsn && { dsn: dsnToString(dsn) }),\n ...(dynamicSamplingContext && {\n trace: dropUndefinedKeys({ ...dynamicSamplingContext }),\n }),\n };\n}\n","import type { 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 type { DataCategory, TransportMakeRequestResponse } from '@sentry/types';\n\n// Intentionally keeping the key broad, as we don't know for sure what rate limit headers get returned from backend\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 the given category is disabled until for rate limiting.\n * In case no category-specific limit is set but a general rate limit across all categories is active,\n * that time is returned.\n *\n * @return the time in ms that the category is disabled until or 0 if there's no active rate limit.\n */\nexport function disabledUntil(limits: RateLimits, dataCategory: DataCategory): number {\n return limits[dataCategory] || limits.all || 0;\n}\n\n/**\n * Checks if a category is rate limited\n */\nexport function isRateLimited(limits: RateLimits, dataCategory: DataCategory, now: number = Date.now()): boolean {\n return disabledUntil(limits, dataCategory) > now;\n}\n\n/**\n * Update ratelimits from incoming headers.\n *\n * @return the updated RateLimits object.\n */\nexport function updateRateLimits(\n limits: RateLimits,\n { statusCode, headers }: TransportMakeRequestResponse,\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 && headers['x-sentry-rate-limits'];\n const retryAfterHeader = headers && 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>: <namespaces>\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 * <namespaces> Semicolon-separated list of metric namespace identifiers. Defines which namespace(s) will be affected.\n * Only present if rate limit applies to the metric_bucket data category.\n */\n for (const limit of rateLimitHeader.trim().split(',')) {\n const [retryAfter, categories, , , namespaces] = limit.split(':', 5);\n const headerDelay = parseInt(retryAfter, 10);\n const delay = (!isNaN(headerDelay) ? headerDelay : 60) * 1000; // 60sec default\n if (!categories) {\n updatedRateLimits.all = now + delay;\n } else {\n for (const category of categories.split(';')) {\n if (category === 'metric_bucket') {\n // namespaces will be present when category === 'metric_bucket'\n if (!namespaces || namespaces.split(';').includes('custom')) {\n updatedRateLimits[category] = now + delay;\n }\n } else {\n updatedRateLimits[category] = now + delay;\n }\n }\n }\n }\n } else if (retryAfterHeader) {\n updatedRateLimits.all = now + parseRetryAfterHeader(retryAfterHeader, now);\n } else if (statusCode === 429) {\n updatedRateLimits.all = now + 60 * 1000;\n }\n\n return updatedRateLimits;\n}\n","import type {\n Client,\n Event,\n EventHint,\n Exception,\n Extras,\n Hub,\n Mechanism,\n ParameterizedString,\n Severity,\n SeverityLevel,\n StackFrame,\n StackParser,\n} from '@sentry/types';\n\nimport { isError, isParameterizedString, isPlainObject } from './is';\nimport { addExceptionMechanism, addExceptionTypeValue } from './misc';\nimport { normalizeToSize } from './normalize';\nimport { extractExceptionKeysForMessage } from './object';\n\n/**\n * Extracts stack frames from the error.stack string\n */\nexport function parseStackFrames(stackParser: StackParser, error: Error): StackFrame[] {\n return stackParser(error.stack || '', 1);\n}\n\n/**\n * Extracts stack frames from the error and builds a Sentry Exception\n */\nexport function exceptionFromError(stackParser: StackParser, error: Error): Exception {\n const exception: Exception = {\n type: error.name || error.constructor.name,\n value: error.message,\n };\n\n const frames = parseStackFrames(stackParser, error);\n if (frames.length) {\n exception.stacktrace = { frames };\n }\n\n return exception;\n}\n\nfunction getMessageForObject(exception: object): string {\n if ('name' in exception && typeof exception.name === 'string') {\n let message = `'${exception.name}' captured as exception`;\n\n if ('message' in exception && typeof exception.message === 'string') {\n message += ` with message '${exception.message}'`;\n }\n\n return message;\n } else if ('message' in exception && typeof exception.message === 'string') {\n return exception.message;\n } else {\n // This will allow us to group events based on top-level keys\n // which is much better than creating new group when any key/value change\n return `Object captured as exception with keys: ${extractExceptionKeysForMessage(\n exception as Record<string, unknown>,\n )}`;\n }\n}\n\n/**\n * Builds and Event from a Exception\n *\n * TODO(v8): Remove getHub fallback\n * @hidden\n */\nexport function eventFromUnknownInput(\n // eslint-disable-next-line deprecation/deprecation\n getHubOrClient: (() => Hub) | Client | undefined,\n stackParser: StackParser,\n exception: unknown,\n hint?: EventHint,\n): Event {\n const client =\n typeof getHubOrClient === 'function'\n ? // eslint-disable-next-line deprecation/deprecation\n getHubOrClient().getClient()\n : getHubOrClient;\n\n let ex: unknown = exception;\n const providedMechanism: Mechanism | undefined =\n hint && hint.data && (hint.data as { mechanism: Mechanism }).mechanism;\n const mechanism: Mechanism = providedMechanism || {\n handled: true,\n type: 'generic',\n };\n\n let extras: Extras | undefined;\n\n if (!isError(exception)) {\n if (isPlainObject(exception)) {\n const normalizeDepth = client && client.getOptions().normalizeDepth;\n extras = { ['__serialized__']: normalizeToSize(exception as Record<string, unknown>, normalizeDepth) };\n\n const message = getMessageForObject(exception);\n ex = (hint && hint.syntheticException) || new Error(message);\n (ex as Error).message = message;\n } else {\n // This handles when someone does: `throw \"something awesome\";`\n // We use synthesized Error here so we can extract a (rough) stack trace.\n ex = (hint && hint.syntheticException) || new Error(exception as string);\n (ex as Error).message = exception as string;\n }\n mechanism.synthetic = true;\n }\n\n const event: Event = {\n exception: {\n values: [exceptionFromError(stackParser, ex as Error)],\n },\n };\n\n if (extras) {\n event.extra = extras;\n }\n\n addExceptionTypeValue(event, undefined, undefined);\n addExceptionMechanism(event, mechanism);\n\n return {\n ...event,\n event_id: hint && hint.event_id,\n };\n}\n\n/**\n * Builds and Event from a Message\n * @hidden\n */\nexport function eventFromMessage(\n stackParser: StackParser,\n message: ParameterizedString,\n // eslint-disable-next-line deprecation/deprecation\n level: Severity | SeverityLevel = 'info',\n hint?: EventHint,\n attachStacktrace?: boolean,\n): Event {\n const event: Event = {\n event_id: hint && hint.event_id,\n level,\n };\n\n if (attachStacktrace && hint && hint.syntheticException) {\n const frames = parseStackFrames(stackParser, hint.syntheticException);\n if (frames.length) {\n event.exception = {\n values: [\n {\n value: message,\n stacktrace: { frames },\n },\n ],\n };\n }\n }\n\n if (isParameterizedString(message)) {\n const { __sentry_template_string__, __sentry_template_values__ } = message;\n\n event.logentry = {\n message: __sentry_template_string__,\n params: __sentry_template_values__,\n };\n return event;\n }\n\n event.message = message;\n return event;\n}\n","/** A simple Least Recently Used map */\nexport class LRUMap<K, V> {\n private readonly _cache: Map<K, V>;\n\n public constructor(private readonly _maxSize: number) {\n this._cache = new Map<K, V>();\n }\n\n /** Get the current size of the cache */\n public get size(): number {\n return this._cache.size;\n }\n\n /** Get an entry or undefined if it was not in the cache. Re-inserts to update the recently used order */\n public get(key: K): V | undefined {\n const value = this._cache.get(key);\n if (value === undefined) {\n return undefined;\n }\n // Remove and re-insert to update the order\n this._cache.delete(key);\n this._cache.set(key, value);\n return value;\n }\n\n /** Insert an entry and evict an older entry if we've reached maxSize */\n public set(key: K, value: V): void {\n if (this._cache.size >= this._maxSize) {\n // keys() returns an iterator in insertion order so keys().next() gives us the oldest key\n this._cache.delete(this._cache.keys().next().value);\n }\n this._cache.set(key, value);\n }\n\n /** Remove an entry and return the entry if it was in the cache */\n public remove(key: K): V | undefined {\n const value = this._cache.get(key);\n if (value) {\n this._cache.delete(key);\n }\n return value;\n }\n\n /** Clear all entries */\n public clear(): void {\n this._cache.clear();\n }\n\n /** Get all the keys */\n public keys(): Array<K> {\n return Array.from(this._cache.keys());\n }\n\n /** Get all the values */\n public values(): Array<V> {\n const values: V[] = [];\n this._cache.forEach(value => values.push(value));\n return values;\n }\n}\n","// https://github.com/alangpierce/sucrase/tree/265887868966917f3b924ce38dfad01fbab1329f\n//\n// The MIT License (MIT)\n//\n// Copyright (c) 2012-2018 various contributors (see AUTHORS)\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n/**\n * Polyfill for the nullish coalescing operator (`??`).\n *\n * Note that the RHS is wrapped in a function so that if it's a computed value, that evaluation won't happen unless the\n * LHS evaluates to a nullish value, to mimic the operator's short-circuiting behavior.\n *\n * Adapted from Sucrase (https://github.com/alangpierce/sucrase)\n *\n * @param lhs The value of the expression to the left of the `??`\n * @param rhsFn A function returning the value of the expression to the right of the `??`\n * @returns The LHS value, unless it's `null` or `undefined`, in which case, the RHS value\n */\nexport function _nullishCoalesce(lhs: unknown, rhsFn: () => unknown): unknown {\n // by checking for loose equality to `null`, we catch both `null` and `undefined`\n return lhs != null ? lhs : rhsFn();\n}\n\n// Sucrase version:\n// function _nullishCoalesce(lhs, rhsFn) {\n// if (lhs != null) {\n// return lhs;\n// } else {\n// return rhsFn();\n// }\n// }\n","// https://github.com/alangpierce/sucrase/tree/265887868966917f3b924ce38dfad01fbab1329f\n//\n// The MIT License (MIT)\n//\n// Copyright (c) 2012-2018 various contributors (see AUTHORS)\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\nimport type { GenericFunction } from './types';\n\n/**\n * Polyfill for the optional chain operator, `?.`, given previous conversion of the expression into an array of values,\n * descriptors, and functions.\n *\n * Adapted from Sucrase (https://github.com/alangpierce/sucrase)\n * See https://github.com/alangpierce/sucrase/blob/265887868966917f3b924ce38dfad01fbab1329f/src/transformers/OptionalChainingNullishTransformer.ts#L15\n *\n * @param ops Array result of expression conversion\n * @returns The value of the expression\n */\nexport function _optionalChain(ops: unknown[]): unknown {\n let lastAccessLHS: unknown = undefined;\n let value = ops[0];\n let i = 1;\n while (i < ops.length) {\n const op = ops[i] as string;\n const fn = ops[i + 1] as (intermediateValue: unknown) => unknown;\n i += 2;\n // by checking for loose equality to `null`, we catch both `null` and `undefined`\n if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) {\n // really we're meaning to return `undefined` as an actual value here, but it saves bytes not to write it\n return;\n }\n if (op === 'access' || op === 'optionalAccess') {\n lastAccessLHS = value;\n value = fn(value);\n } else if (op === 'call' || op === 'optionalCall') {\n value = fn((...args: unknown[]) => (value as GenericFunction).call(lastAccessLHS, ...args));\n lastAccessLHS = undefined;\n }\n }\n return value;\n}\n\n// Sucrase version\n// function _optionalChain(ops) {\n// let lastAccessLHS = undefined;\n// let value = ops[0];\n// let i = 1;\n// while (i < ops.length) {\n// const op = ops[i];\n// const fn = ops[i + 1];\n// i += 2;\n// if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) {\n// return undefined;\n// }\n// if (op === 'access' || op === 'optionalAccess') {\n// lastAccessLHS = value;\n// value = fn(value);\n// } else if (op === 'call' || op === 'optionalCall') {\n// value = fn((...args) => value.call(lastAccessLHS, ...args));\n// lastAccessLHS = undefined;\n// }\n// }\n// return value;\n// }\n","// https://github.com/alangpierce/sucrase/tree/265887868966917f3b924ce38dfad01fbab1329f\n//\n// The MIT License (MIT)\n//\n// Copyright (c) 2012-2018 various contributors (see AUTHORS)\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\nimport { _optionalChain } from './_optionalChain';\n\n/**\n * Polyfill for the optional chain operator, `?.`, given previous conversion of the expression into an array of values,\n * descriptors, and functions, in cases where the value of the expression is to be deleted.\n *\n * Adapted from Sucrase (https://github.com/alangpierce/sucrase) See\n * https://github.com/alangpierce/sucrase/blob/265887868966917f3b924ce38dfad01fbab1329f/src/transformers/OptionalChainingNullishTransformer.ts#L15\n *\n * @param ops Array result of expression conversion\n * @returns The return value of the `delete` operator: `true`, unless the deletion target is an own, non-configurable\n * property (one which can't be deleted or turned into an accessor, and whose enumerability can't be changed), in which\n * case `false`.\n */\nexport function _optionalChainDelete(ops: unknown[]): boolean {\n const result = _optionalChain(ops) as boolean | null;\n // If `result` is `null`, it means we didn't get to the end of the chain and so nothing was deleted (in which case,\n // return `true` since that's what `delete` does when it no-ops). If it's non-null, we know the delete happened, in\n // which case we return whatever the `delete` returned, which will be a boolean.\n return result == null ? true : result;\n}\n\n// Sucrase version:\n// function _optionalChainDelete(ops) {\n// const result = _optionalChain(ops);\n// // by checking for loose equality to `null`, we catch both `null` and `undefined`\n// return result == null ? true : result;\n// }\n","declare const __DEBUG_BUILD__: boolean;\n\n/**\n * This serves as a build time flag that will be true by default, but false in non-debug builds or if users replace `__SENTRY_DEBUG__` in their generated code.\n *\n * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking.\n */\nexport const DEBUG_BUILD = __DEBUG_BUILD__;\n","import type { Event, EventHint, EventProcessor } from '@sentry/types';\nimport { SyncPromise, getGlobalSingleton, isThenable, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from './debug-build';\n\n/**\n * Returns the global event processors.\n * @deprecated Global event processors will be removed in v8.\n */\nexport function getGlobalEventProcessors(): EventProcessor[] {\n return getGlobalSingleton<EventProcessor[]>('globalEventProcessors', () => []);\n}\n\n/**\n * Add a EventProcessor to be kept globally.\n * @deprecated Use `addEventProcessor` instead. Global event processors will be removed in v8.\n */\nexport function addGlobalEventProcessor(callback: EventProcessor): void {\n // eslint-disable-next-line deprecation/deprecation\n getGlobalEventProcessors().push(callback);\n}\n\n/**\n * Process an array of event processors, returning the processed event (or `null` if the event was dropped).\n */\nexport function notifyEventProcessors(\n processors: EventProcessor[],\n event: Event | null,\n hint: EventHint,\n index: number = 0,\n): PromiseLike<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\n DEBUG_BUILD && processor.id && result === null && logger.log(`Event processor \"${processor.id}\" dropped event`);\n\n if (isThenable(result)) {\n void result\n .then(final => notifyEventProcessors(processors, final, hint, index + 1).then(resolve))\n .then(null, reject);\n } else {\n void notifyEventProcessors(processors, result, hint, index + 1)\n .then(resolve)\n .then(null, reject);\n }\n }\n });\n}\n","export const DEFAULT_ENVIRONMENT = 'production';\n","import type { SerializedSession, Session, SessionContext, SessionStatus } from '@sentry/types';\nimport { dropUndefinedKeys, timestampInSeconds, uuid4 } from '@sentry/utils';\n/**\n * Creates a new `Session` object by setting certain default parameters. If optional @param context\n * is passed, the passed properties are applied to the session object.\n *\n * @param context (optional) additional properties to be applied to the returned session object\n *\n * @returns a new `Session` object\n */\nexport function makeSession(context?: Omit<SessionContext, 'started' | 'status'>): Session {\n // Both timestamp and started are in seconds since the UNIX epoch.\n const startingTime = timestampInSeconds();\n\n const session: Session = {\n sid: uuid4(),\n init: true,\n timestamp: startingTime,\n started: startingTime,\n duration: 0,\n status: 'ok',\n errors: 0,\n ignoreDuration: false,\n toJSON: () => sessionToJSON(session),\n };\n\n if (context) {\n updateSession(session, context);\n }\n\n return session;\n}\n\n/**\n * Updates a session object with the properties passed in the context.\n *\n * Note that this function mutates the passed object and returns void.\n * (Had to do this instead of returning a new and updated session because closing and sending a session\n * makes an update to the session after it was passed to the sending logic.\n * @see BaseClient.captureSession )\n *\n * @param session the `Session` to update\n * @param context the `SessionContext` holding the properties that should be updated in @param session\n */\n// eslint-disable-next-line complexity\nexport function updateSession(session: Session, context: SessionContext = {}): void {\n if (context.user) {\n if (!session.ipAddress && context.user.ip_address) {\n session.ipAddress = context.user.ip_address;\n }\n\n if (!session.did && !context.did) {\n session.did = context.user.id || context.user.email || context.user.username;\n }\n }\n\n session.timestamp = context.timestamp || timestampInSeconds();\n\n if (context.abnormal_mechanism) {\n session.abnormal_mechanism = context.abnormal_mechanism;\n }\n\n if (context.ignoreDuration) {\n session.ignoreDuration = context.ignoreDuration;\n }\n if (context.sid) {\n // Good enough uuid validation. — Kamil\n session.sid = context.sid.length === 32 ? context.sid : uuid4();\n }\n if (context.init !== undefined) {\n session.init = context.init;\n }\n if (!session.did && context.did) {\n session.did = `${context.did}`;\n }\n if (typeof context.started === 'number') {\n session.started = context.started;\n }\n if (session.ignoreDuration) {\n session.duration = undefined;\n } else if (typeof context.duration === 'number') {\n session.duration = context.duration;\n } else {\n const duration = session.timestamp - session.started;\n session.duration = duration >= 0 ? duration : 0;\n }\n if (context.release) {\n session.release = context.release;\n }\n if (context.environment) {\n session.environment = context.environment;\n }\n if (!session.ipAddress && context.ipAddress) {\n session.ipAddress = context.ipAddress;\n }\n if (!session.userAgent && context.userAgent) {\n session.userAgent = context.userAgent;\n }\n if (typeof context.errors === 'number') {\n session.errors = context.errors;\n }\n if (context.status) {\n session.status = context.status;\n }\n}\n\n/**\n * Closes a session by setting its status and updating the session object with it.\n * Internally calls `updateSession` to update the passed session object.\n *\n * Note that this function mutates the passed session (@see updateSession for explanation).\n *\n * @param session the `Session` object to be closed\n * @param status the `SessionStatus` with which the session was closed. If you don't pass a status,\n * this function will keep the previously set status, unless it was `'ok'` in which case\n * it is changed to `'exited'`.\n */\nexport function closeSession(session: Session, status?: Exclude<SessionStatus, 'ok'>): void {\n let context = {};\n if (status) {\n context = { status };\n } else if (session.status === 'ok') {\n context = { status: 'exited' };\n }\n\n updateSession(session, context);\n}\n\n/**\n * Serializes a passed session object to a JSON object with a slightly different structure.\n * This is necessary because the Sentry backend requires a slightly different schema of a session\n * than the one the JS SDKs use internally.\n *\n * @param session the session to be converted\n *\n * @returns a JSON object of the passed session\n */\nfunction sessionToJSON(session: Session): SerializedSession {\n return dropUndefinedKeys({\n sid: `${session.sid}`,\n init: session.init,\n // Make sure that sec is converted to ms for date constructor\n started: new Date(session.started * 1000).toISOString(),\n timestamp: new Date(session.timestamp * 1000).toISOString(),\n status: session.status,\n errors: session.errors,\n did: typeof session.did === 'number' || typeof session.did === 'string' ? `${session.did}` : undefined,\n duration: session.duration,\n abnormal_mechanism: session.abnormal_mechanism,\n attrs: {\n release: session.release,\n environment: session.environment,\n ip_address: session.ipAddress,\n user_agent: session.userAgent,\n },\n });\n}\n","import type { Span } from '@sentry/types';\n\n/**\n * Returns the root span of a given span.\n *\n * As long as we use `Transaction`s internally, the returned root span\n * will be a `Transaction` but be aware that this might change in the future.\n *\n * If the given span has no root span or transaction, `undefined` is returned.\n */\nexport function getRootSpan(span: Span): Span | undefined {\n // TODO (v8): Remove this check and just return span\n // eslint-disable-next-line deprecation/deprecation\n return span.transaction;\n}\n","import type { Span, SpanJSON, SpanTimeInput, TraceContext } from '@sentry/types';\nimport { dropUndefinedKeys, generateSentryTraceHeader, timestampInSeconds } from '@sentry/utils';\nimport type { Span as SpanClass } from '../tracing/span';\n\n// These are aligned with OpenTelemetry trace flags\nexport const TRACE_FLAG_NONE = 0x0;\nexport const TRACE_FLAG_SAMPLED = 0x1;\n\n/**\n * Convert a span to a trace context, which can be sent as the `trace` context in an event.\n */\nexport function spanToTraceContext(span: Span): TraceContext {\n const { spanId: span_id, traceId: trace_id } = span.spanContext();\n const { data, op, parent_span_id, status, tags, origin } = spanToJSON(span);\n\n return dropUndefinedKeys({\n data,\n op,\n parent_span_id,\n span_id,\n status,\n tags,\n trace_id,\n origin,\n });\n}\n\n/**\n * Convert a Span to a Sentry trace header.\n */\nexport function spanToTraceHeader(span: Span): string {\n const { traceId, spanId } = span.spanContext();\n const sampled = spanIsSampled(span);\n return generateSentryTraceHeader(traceId, spanId, sampled);\n}\n\n/**\n * Convert a span time input intp a timestamp in seconds.\n */\nexport function spanTimeInputToSeconds(input: SpanTimeInput | undefined): number {\n if (typeof input === 'number') {\n return ensureTimestampInSeconds(input);\n }\n\n if (Array.isArray(input)) {\n // See {@link HrTime} for the array-based time format\n return input[0] + input[1] / 1e9;\n }\n\n if (input instanceof Date) {\n return ensureTimestampInSeconds(input.getTime());\n }\n\n return timestampInSeconds();\n}\n\n/**\n * Converts a timestamp to second, if it was in milliseconds, or keeps it as second.\n */\nfunction ensureTimestampInSeconds(timestamp: number): number {\n const isMs = timestamp > 9999999999;\n return isMs ? timestamp / 1000 : timestamp;\n}\n\n/**\n * Convert a span to a JSON representation.\n * Note that all fields returned here are optional and need to be guarded against.\n *\n * Note: Because of this, we currently have a circular type dependency (which we opted out of in package.json).\n * This is not avoidable as we need `spanToJSON` in `spanUtils.ts`, which in turn is needed by `span.ts` for backwards compatibility.\n * And `spanToJSON` needs the Span class from `span.ts` to check here.\n * TODO v8: When we remove the deprecated stuff from `span.ts`, we can remove the circular dependency again.\n */\nexport function spanToJSON(span: Span): Partial<SpanJSON> {\n if (spanIsSpanClass(span)) {\n return span.getSpanJSON();\n }\n\n // Fallback: We also check for `.toJSON()` here...\n // eslint-disable-next-line deprecation/deprecation\n if (typeof span.toJSON === 'function') {\n // eslint-disable-next-line deprecation/deprecation\n return span.toJSON();\n }\n\n return {};\n}\n\n/**\n * Sadly, due to circular dependency checks we cannot actually import the Span class here and check for instanceof.\n * :( So instead we approximate this by checking if it has the `getSpanJSON` method.\n */\nfunction spanIsSpanClass(span: Span): span is SpanClass {\n return typeof (span as SpanClass).getSpanJSON === 'function';\n}\n\n/**\n * Returns true if a span is sampled.\n * In most cases, you should just use `span.isRecording()` instead.\n * However, this has a slightly different semantic, as it also returns false if the span is finished.\n * So in the case where this distinction is important, use this method.\n */\nexport function spanIsSampled(span: Span): boolean {\n // We align our trace flags with the ones OpenTelemetry use\n // So we also check for sampled the same way they do.\n const { traceFlags } = span.spanContext();\n // eslint-disable-next-line no-bitwise\n return Boolean(traceFlags & TRACE_FLAG_SAMPLED);\n}\n","import type { Client, DynamicSamplingContext, Scope, Span, Transaction } from '@sentry/types';\nimport { dropUndefinedKeys } from '@sentry/utils';\n\nimport { DEFAULT_ENVIRONMENT } from '../constants';\nimport { getClient, getCurrentScope } from '../exports';\nimport { getRootSpan } from '../utils/getRootSpan';\nimport { spanIsSampled, spanToJSON } from '../utils/spanUtils';\n\n/**\n * Creates a dynamic sampling context from a client.\n *\n * Dispatches the `createDsc` lifecycle hook as a side effect.\n */\nexport function getDynamicSamplingContextFromClient(\n trace_id: string,\n client: Client,\n scope?: Scope,\n): DynamicSamplingContext {\n const options = client.getOptions();\n\n const { publicKey: public_key } = client.getDsn() || {};\n // TODO(v8): Remove segment from User\n // eslint-disable-next-line deprecation/deprecation\n const { segment: user_segment } = (scope && scope.getUser()) || {};\n\n const dsc = dropUndefinedKeys({\n environment: options.environment || DEFAULT_ENVIRONMENT,\n release: options.release,\n user_segment,\n public_key,\n trace_id,\n }) as DynamicSamplingContext;\n\n client.emit && client.emit('createDsc', dsc);\n\n return dsc;\n}\n\n/**\n * A Span with a frozen dynamic sampling context.\n */\ntype TransactionWithV7FrozenDsc = Transaction & { _frozenDynamicSamplingContext?: DynamicSamplingContext };\n\n/**\n * Creates a dynamic sampling context from a span (and client and scope)\n *\n * @param span the span from which a few values like the root span name and sample rate are extracted.\n *\n * @returns a dynamic sampling context\n */\nexport function getDynamicSamplingContextFromSpan(span: Span): Readonly<Partial<DynamicSamplingContext>> {\n const client = getClient();\n if (!client) {\n return {};\n }\n\n // passing emit=false here to only emit later once the DSC is actually populated\n const dsc = getDynamicSamplingContextFromClient(spanToJSON(span).trace_id || '', client, getCurrentScope());\n\n // TODO (v8): Remove v7FrozenDsc as a Transaction will no longer have _frozenDynamicSamplingContext\n const txn = getRootSpan(span) as TransactionWithV7FrozenDsc | undefined;\n if (!txn) {\n return dsc;\n }\n\n // TODO (v8): Remove v7FrozenDsc as a Transaction will no longer have _frozenDynamicSamplingContext\n // For now we need to avoid breaking users who directly created a txn with a DSC, where this field is still set.\n // @see Transaction class constructor\n const v7FrozenDsc = txn && txn._frozenDynamicSamplingContext;\n if (v7FrozenDsc) {\n return v7FrozenDsc;\n }\n\n // TODO (v8): Replace txn.metadata with txn.attributes[]\n // We can't do this yet because attributes aren't always set yet.\n // eslint-disable-next-line deprecation/deprecation\n const { sampleRate: maybeSampleRate, source } = txn.metadata;\n if (maybeSampleRate != null) {\n dsc.sample_rate = `${maybeSampleRate}`;\n }\n\n // We don't want to have a transaction name in the DSC if the source is \"url\" because URLs might contain PII\n const jsonSpan = spanToJSON(txn);\n\n // after JSON conversion, txn.name becomes jsonSpan.description\n if (source && source !== 'url') {\n dsc.transaction = jsonSpan.description;\n }\n\n dsc.sampled = String(spanIsSampled(txn));\n\n client.emit && client.emit('createDsc', dsc);\n\n return dsc;\n}\n","import type { Breadcrumb, Event, ScopeData, Span } from '@sentry/types';\nimport { arrayify, dropUndefinedKeys } from '@sentry/utils';\nimport { getDynamicSamplingContextFromSpan } from '../tracing/dynamicSamplingContext';\nimport { getRootSpan } from './getRootSpan';\nimport { spanToJSON, spanToTraceContext } from './spanUtils';\n\n/**\n * Applies data from the scope to the event and runs all event processors on it.\n */\nexport function applyScopeDataToEvent(event: Event, data: ScopeData): void {\n const { fingerprint, span, breadcrumbs, sdkProcessingMetadata } = data;\n\n // Apply general data\n applyDataToEvent(event, data);\n\n // We want to set the trace context for normal events only if there isn't already\n // a trace context on the event. There is a product feature in place where we link\n // errors with transaction and it relies on that.\n if (span) {\n applySpanToEvent(event, span);\n }\n\n applyFingerprintToEvent(event, fingerprint);\n applyBreadcrumbsToEvent(event, breadcrumbs);\n applySdkMetadataToEvent(event, sdkProcessingMetadata);\n}\n\n/** Merge data of two scopes together. */\nexport function mergeScopeData(data: ScopeData, mergeData: ScopeData): void {\n const {\n extra,\n tags,\n user,\n contexts,\n level,\n sdkProcessingMetadata,\n breadcrumbs,\n fingerprint,\n eventProcessors,\n attachments,\n propagationContext,\n // eslint-disable-next-line deprecation/deprecation\n transactionName,\n span,\n } = mergeData;\n\n mergeAndOverwriteScopeData(data, 'extra', extra);\n mergeAndOverwriteScopeData(data, 'tags', tags);\n mergeAndOverwriteScopeData(data, 'user', user);\n mergeAndOverwriteScopeData(data, 'contexts', contexts);\n mergeAndOverwriteScopeData(data, 'sdkProcessingMetadata', sdkProcessingMetadata);\n\n if (level) {\n data.level = level;\n }\n\n if (transactionName) {\n // eslint-disable-next-line deprecation/deprecation\n data.transactionName = transactionName;\n }\n\n if (span) {\n data.span = span;\n }\n\n if (breadcrumbs.length) {\n data.breadcrumbs = [...data.breadcrumbs, ...breadcrumbs];\n }\n\n if (fingerprint.length) {\n data.fingerprint = [...data.fingerprint, ...fingerprint];\n }\n\n if (eventProcessors.length) {\n data.eventProcessors = [...data.eventProcessors, ...eventProcessors];\n }\n\n if (attachments.length) {\n data.attachments = [...data.attachments, ...attachments];\n }\n\n data.propagationContext = { ...data.propagationContext, ...propagationContext };\n}\n\n/**\n * Merges certain scope data. Undefined values will overwrite any existing values.\n * Exported only for tests.\n */\nexport function mergeAndOverwriteScopeData<\n Prop extends 'extra' | 'tags' | 'user' | 'contexts' | 'sdkProcessingMetadata',\n Data extends ScopeData,\n>(data: Data, prop: Prop, mergeVal: Data[Prop]): void {\n if (mergeVal && Object.keys(mergeVal).length) {\n // Clone object\n data[prop] = { ...data[prop] };\n for (const key in mergeVal) {\n if (Object.prototype.hasOwnProperty.call(mergeVal, key)) {\n data[prop][key] = mergeVal[key];\n }\n }\n }\n}\n\n/** Exported only for tests */\nexport function mergeArray<Prop extends 'breadcrumbs' | 'fingerprint'>(\n event: Event,\n prop: Prop,\n mergeVal: ScopeData[Prop],\n): void {\n const prevVal = event[prop];\n // If we are not merging any new values,\n // we only need to proceed if there was an empty array before (as we want to replace it with undefined)\n if (!mergeVal.length && (!prevVal || prevVal.length)) {\n return;\n }\n\n const merged = [...(prevVal || []), ...mergeVal] as ScopeData[Prop];\n event[prop] = merged.length ? merged : undefined;\n}\n\nfunction applyDataToEvent(event: Event, data: ScopeData): void {\n const {\n extra,\n tags,\n user,\n contexts,\n level,\n // eslint-disable-next-line deprecation/deprecation\n transactionName,\n } = data;\n\n const cleanedExtra = dropUndefinedKeys(extra);\n if (cleanedExtra && Object.keys(cleanedExtra).length) {\n event.extra = { ...cleanedExtra, ...event.extra };\n }\n\n const cleanedTags = dropUndefinedKeys(tags);\n if (cleanedTags && Object.keys(cleanedTags).length) {\n event.tags = { ...cleanedTags, ...event.tags };\n }\n\n const cleanedUser = dropUndefinedKeys(user);\n if (cleanedUser && Object.keys(cleanedUser).length) {\n event.user = { ...cleanedUser, ...event.user };\n }\n\n const cleanedContexts = dropUndefinedKeys(contexts);\n if (cleanedContexts && Object.keys(cleanedContexts).length) {\n event.contexts = { ...cleanedContexts, ...event.contexts };\n }\n\n if (level) {\n event.level = level;\n }\n\n if (transactionName) {\n event.transaction = transactionName;\n }\n}\n\nfunction applyBreadcrumbsToEvent(event: Event, breadcrumbs: Breadcrumb[]): void {\n const mergedBreadcrumbs = [...(event.breadcrumbs || []), ...breadcrumbs];\n event.breadcrumbs = mergedBreadcrumbs.length ? mergedBreadcrumbs : undefined;\n}\n\nfunction applySdkMetadataToEvent(event: Event, sdkProcessingMetadata: ScopeData['sdkProcessingMetadata']): void {\n event.sdkProcessingMetadata = {\n ...event.sdkProcessingMetadata,\n ...sdkProcessingMetadata,\n };\n}\n\nfunction applySpanToEvent(event: Event, span: Span): void {\n event.contexts = { trace: spanToTraceContext(span), ...event.contexts };\n const rootSpan = getRootSpan(span);\n if (rootSpan) {\n event.sdkProcessingMetadata = {\n dynamicSamplingContext: getDynamicSamplingContextFromSpan(span),\n ...event.sdkProcessingMetadata,\n };\n const transactionName = spanToJSON(rootSpan).description;\n if (transactionName) {\n event.tags = { transaction: transactionName, ...event.tags };\n }\n }\n}\n\n/**\n * Applies fingerprint from the scope to the event if there's one,\n * uses message if there's one instead or get rid of empty fingerprint\n */\nfunction applyFingerprintToEvent(event: Event, fingerprint: ScopeData['fingerprint'] | undefined): void {\n // Make sure it's an array first and we actually have something in place\n event.fingerprint = event.fingerprint ? arrayify(event.fingerprint) : [];\n\n // If we have something on the scope, then merge it with event\n if (fingerprint) {\n event.fingerprint = event.fingerprint.concat(fingerprint);\n }\n\n // If we have no data at all, remove empty array default\n if (event.fingerprint && !event.fingerprint.length) {\n delete event.fingerprint;\n }\n}\n","/* eslint-disable max-lines */\nimport type {\n Attachment,\n Breadcrumb,\n CaptureContext,\n Client,\n Context,\n Contexts,\n Event,\n EventHint,\n EventProcessor,\n Extra,\n Extras,\n Primitive,\n PropagationContext,\n RequestSession,\n Scope as ScopeInterface,\n ScopeContext,\n ScopeData,\n Session,\n Severity,\n SeverityLevel,\n Span,\n Transaction,\n User,\n} from '@sentry/types';\nimport { dateTimestampInSeconds, isPlainObject, logger, uuid4 } from '@sentry/utils';\n\nimport { getGlobalEventProcessors, notifyEventProcessors } from './eventProcessors';\nimport { updateSession } from './session';\nimport { applyScopeDataToEvent } from './utils/applyScopeDataToEvent';\n\n/**\n * Default value for maximum number of breadcrumbs added to an event.\n */\nconst DEFAULT_MAX_BREADCRUMBS = 100;\n\n/**\n * The global scope is kept in this module.\n * When accessing this via `getGlobalScope()` we'll make sure to set one if none is currently present.\n */\nlet globalScope: ScopeInterface | undefined;\n\n/**\n * Holds additional event information. {@link Scope.applyToEvent} will be\n * called by the client before an event will be sent.\n */\nexport class Scope implements ScopeInterface {\n /** Flag if notifying is happening. */\n protected _notifyingListeners: boolean;\n\n /** Callback for client to receive scope changes. */\n protected _scopeListeners: Array<(scope: Scope) => void>;\n\n /** Callback list that will be called after {@link applyToEvent}. */\n protected _eventProcessors: EventProcessor[];\n\n /** Array of breadcrumbs. */\n protected _breadcrumbs: Breadcrumb[];\n\n /** User */\n protected _user: User;\n\n /** Tags */\n protected _tags: { [key: string]: Primitive };\n\n /** Extra */\n protected _extra: Extras;\n\n /** Contexts */\n protected _contexts: Contexts;\n\n /** Attachments */\n protected _attachments: Attachment[];\n\n /** Propagation Context for distributed tracing */\n protected _propagationContext: PropagationContext;\n\n /**\n * A place to stash data which is needed at some point in the SDK's event processing pipeline but which shouldn't get\n * sent to Sentry\n */\n protected _sdkProcessingMetadata: { [key: string]: unknown };\n\n /** Fingerprint */\n protected _fingerprint?: string[];\n\n /** Severity */\n // eslint-disable-next-line deprecation/deprecation\n protected _level?: Severity | SeverityLevel;\n\n /**\n * Transaction Name\n */\n protected _transactionName?: string;\n\n /** Span */\n protected _span?: Span;\n\n /** Session */\n protected _session?: Session;\n\n /** Request Mode Session Status */\n protected _requestSession?: RequestSession;\n\n /** The client on this scope */\n protected _client?: Client;\n\n // NOTE: Any field which gets added here should get added not only to the constructor but also to the `clone` method.\n\n public constructor() {\n this._notifyingListeners = false;\n this._scopeListeners = [];\n this._eventProcessors = [];\n this._breadcrumbs = [];\n this._attachments = [];\n this._user = {};\n this._tags = {};\n this._extra = {};\n this._contexts = {};\n this._sdkProcessingMetadata = {};\n this._propagationContext = generatePropagationContext();\n }\n\n /**\n * Inherit values from the parent scope.\n * @deprecated Use `scope.clone()` and `new Scope()` instead.\n */\n public static clone(scope?: Scope): Scope {\n return scope ? scope.clone() : new Scope();\n }\n\n /**\n * Clone this scope instance.\n */\n public clone(): Scope {\n const newScope = new Scope();\n newScope._breadcrumbs = [...this._breadcrumbs];\n newScope._tags = { ...this._tags };\n newScope._extra = { ...this._extra };\n newScope._contexts = { ...this._contexts };\n newScope._user = this._user;\n newScope._level = this._level;\n newScope._span = this._span;\n newScope._session = this._session;\n newScope._transactionName = this._transactionName;\n newScope._fingerprint = this._fingerprint;\n newScope._eventProcessors = [...this._eventProcessors];\n newScope._requestSession = this._requestSession;\n newScope._attachments = [...this._attachments];\n newScope._sdkProcessingMetadata = { ...this._sdkProcessingMetadata };\n newScope._propagationContext = { ...this._propagationContext };\n newScope._client = this._client;\n\n return newScope;\n }\n\n /** Update the client on the scope. */\n public setClient(client: Client | undefined): void {\n this._client = client;\n }\n\n /**\n * Get the client assigned to this scope.\n *\n * It is generally recommended to use the global function `Sentry.getClient()` instead, unless you know what you are doing.\n */\n public getClient(): Client | undefined {\n return this._client;\n }\n\n /**\n * Add internal on change listener. Used for sub SDKs that need to store the scope.\n * @hidden\n */\n public addScopeListener(callback: (scope: Scope) => void): void {\n this._scopeListeners.push(callback);\n }\n\n /**\n * @inheritDoc\n */\n public addEventProcessor(callback: EventProcessor): this {\n this._eventProcessors.push(callback);\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setUser(user: User | null): this {\n // If null is passed we want to unset everything, but still define keys,\n // so that later down in the pipeline any existing values are cleared.\n this._user = user || {\n email: undefined,\n id: undefined,\n ip_address: undefined,\n segment: undefined,\n username: undefined,\n };\n\n if (this._session) {\n updateSession(this._session, { user });\n }\n\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getUser(): User | undefined {\n return this._user;\n }\n\n /**\n * @inheritDoc\n */\n public getRequestSession(): RequestSession | undefined {\n return this._requestSession;\n }\n\n /**\n * @inheritDoc\n */\n public setRequestSession(requestSession?: RequestSession): this {\n this._requestSession = requestSession;\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setTags(tags: { [key: string]: Primitive }): this {\n this._tags = {\n ...this._tags,\n ...tags,\n };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setTag(key: string, value: Primitive): this {\n this._tags = { ...this._tags, [key]: value };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setExtras(extras: Extras): this {\n this._extra = {\n ...this._extra,\n ...extras,\n };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setExtra(key: string, extra: Extra): this {\n this._extra = { ...this._extra, [key]: extra };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setFingerprint(fingerprint: string[]): this {\n this._fingerprint = fingerprint;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setLevel(\n // eslint-disable-next-line deprecation/deprecation\n level: Severity | SeverityLevel,\n ): this {\n this._level = level;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * Sets the transaction name on the scope for future events.\n */\n public setTransactionName(name?: string): this {\n this._transactionName = name;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setContext(key: string, context: Context | null): this {\n if (context === null) {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete this._contexts[key];\n } else {\n this._contexts[key] = context;\n }\n\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * Sets the Span on the scope.\n * @param span Span\n * @deprecated Instead of setting a span on a scope, use `startSpan()`/`startSpanManual()` instead.\n */\n public setSpan(span?: Span): this {\n this._span = span;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * Returns the `Span` if there is one.\n * @deprecated Use `getActiveSpan()` instead.\n */\n public getSpan(): Span | undefined {\n return this._span;\n }\n\n /**\n * Returns the `Transaction` attached to the scope (if there is one).\n * @deprecated You should not rely on the transaction, but just use `startSpan()` APIs instead.\n */\n public getTransaction(): Transaction | undefined {\n // Often, this span (if it exists at all) will be a transaction, but it's not guaranteed to be. Regardless, it will\n // have a pointer to the currently-active transaction.\n const span = this._span;\n // Cannot replace with getRootSpan because getRootSpan returns a span, not a transaction\n // Also, this method will be removed anyway.\n // eslint-disable-next-line deprecation/deprecation\n return span && span.transaction;\n }\n\n /**\n * @inheritDoc\n */\n public setSession(session?: Session): this {\n if (!session) {\n delete this._session;\n } else {\n this._session = session;\n }\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getSession(): Session | undefined {\n return this._session;\n }\n\n /**\n * @inheritDoc\n */\n public update(captureContext?: CaptureContext): this {\n if (!captureContext) {\n return this;\n }\n\n const scopeToMerge = typeof captureContext === 'function' ? captureContext(this) : captureContext;\n\n if (scopeToMerge instanceof Scope) {\n const scopeData = scopeToMerge.getScopeData();\n\n this._tags = { ...this._tags, ...scopeData.tags };\n this._extra = { ...this._extra, ...scopeData.extra };\n this._contexts = { ...this._contexts, ...scopeData.contexts };\n if (scopeData.user && Object.keys(scopeData.user).length) {\n this._user = scopeData.user;\n }\n if (scopeData.level) {\n this._level = scopeData.level;\n }\n if (scopeData.fingerprint.length) {\n this._fingerprint = scopeData.fingerprint;\n }\n if (scopeToMerge.getRequestSession()) {\n this._requestSession = scopeToMerge.getRequestSession();\n }\n if (scopeData.propagationContext) {\n this._propagationContext = scopeData.propagationContext;\n }\n } else if (isPlainObject(scopeToMerge)) {\n const scopeContext = captureContext as ScopeContext;\n this._tags = { ...this._tags, ...scopeContext.tags };\n this._extra = { ...this._extra, ...scopeContext.extra };\n this._contexts = { ...this._contexts, ...scopeContext.contexts };\n if (scopeContext.user) {\n this._user = scopeContext.user;\n }\n if (scopeContext.level) {\n this._level = scopeContext.level;\n }\n if (scopeContext.fingerprint) {\n this._fingerprint = scopeContext.fingerprint;\n }\n if (scopeContext.requestSession) {\n this._requestSession = scopeContext.requestSession;\n }\n if (scopeContext.propagationContext) {\n this._propagationContext = scopeContext.propagationContext;\n }\n }\n\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public clear(): this {\n this._breadcrumbs = [];\n this._tags = {};\n this._extra = {};\n this._user = {};\n this._contexts = {};\n this._level = undefined;\n this._transactionName = undefined;\n this._fingerprint = undefined;\n this._requestSession = undefined;\n this._span = undefined;\n this._session = undefined;\n this._notifyScopeListeners();\n this._attachments = [];\n this._propagationContext = generatePropagationContext();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public addBreadcrumb(breadcrumb: Breadcrumb, maxBreadcrumbs?: number): this {\n const maxCrumbs = typeof maxBreadcrumbs === 'number' ? maxBreadcrumbs : DEFAULT_MAX_BREADCRUMBS;\n\n // No data has been changed, so don't notify scope listeners\n if (maxCrumbs <= 0) {\n return this;\n }\n\n const mergedBreadcrumb = {\n timestamp: dateTimestampInSeconds(),\n ...breadcrumb,\n };\n\n const breadcrumbs = this._breadcrumbs;\n breadcrumbs.push(mergedBreadcrumb);\n this._breadcrumbs = breadcrumbs.length > maxCrumbs ? breadcrumbs.slice(-maxCrumbs) : breadcrumbs;\n\n this._notifyScopeListeners();\n\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getLastBreadcrumb(): Breadcrumb | undefined {\n return this._breadcrumbs[this._breadcrumbs.length - 1];\n }\n\n /**\n * @inheritDoc\n */\n public clearBreadcrumbs(): this {\n this._breadcrumbs = [];\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public addAttachment(attachment: Attachment): this {\n this._attachments.push(attachment);\n return this;\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `getScopeData()` instead.\n */\n public getAttachments(): Attachment[] {\n const data = this.getScopeData();\n\n return data.attachments;\n }\n\n /**\n * @inheritDoc\n */\n public clearAttachments(): this {\n this._attachments = [];\n return this;\n }\n\n /** @inheritDoc */\n public getScopeData(): ScopeData {\n const {\n _breadcrumbs,\n _attachments,\n _contexts,\n _tags,\n _extra,\n _user,\n _level,\n _fingerprint,\n _eventProcessors,\n _propagationContext,\n _sdkProcessingMetadata,\n _transactionName,\n _span,\n } = this;\n\n return {\n breadcrumbs: _breadcrumbs,\n attachments: _attachments,\n contexts: _contexts,\n tags: _tags,\n extra: _extra,\n user: _user,\n level: _level,\n fingerprint: _fingerprint || [],\n eventProcessors: _eventProcessors,\n propagationContext: _propagationContext,\n sdkProcessingMetadata: _sdkProcessingMetadata,\n transactionName: _transactionName,\n span: _span,\n };\n }\n\n /**\n * Applies data from the scope to the event and runs all event processors on it.\n *\n * @param event Event\n * @param hint Object containing additional information about the original exception, for use by the event processors.\n * @hidden\n * @deprecated Use `applyScopeDataToEvent()` directly\n */\n public applyToEvent(\n event: Event,\n hint: EventHint = {},\n additionalEventProcessors: EventProcessor[] = [],\n ): PromiseLike<Event | null> {\n applyScopeDataToEvent(event, this.getScopeData());\n\n // TODO (v8): Update this order to be: Global > Client > Scope\n const eventProcessors: EventProcessor[] = [\n ...additionalEventProcessors,\n // eslint-disable-next-line deprecation/deprecation\n ...getGlobalEventProcessors(),\n ...this._eventProcessors,\n ];\n\n return notifyEventProcessors(eventProcessors, event, hint);\n }\n\n /**\n * Add data which will be accessible during event processing but won't get sent to Sentry\n */\n public setSDKProcessingMetadata(newData: { [key: string]: unknown }): this {\n this._sdkProcessingMetadata = { ...this._sdkProcessingMetadata, ...newData };\n\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setPropagationContext(context: PropagationContext): this {\n this._propagationContext = context;\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getPropagationContext(): PropagationContext {\n return this._propagationContext;\n }\n\n /**\n * Capture an exception for this scope.\n *\n * @param exception The exception to capture.\n * @param hint Optinal additional data to attach to the Sentry event.\n * @returns the id of the captured Sentry event.\n */\n public captureException(exception: unknown, hint?: EventHint): string {\n const eventId = hint && hint.event_id ? hint.event_id : uuid4();\n\n if (!this._client) {\n logger.warn('No client configured on scope - will not capture exception!');\n return eventId;\n }\n\n const syntheticException = new Error('Sentry syntheticException');\n\n this._client.captureException(\n exception,\n {\n originalException: exception,\n syntheticException,\n ...hint,\n event_id: eventId,\n },\n this,\n );\n\n return eventId;\n }\n\n /**\n * Capture a message for this scope.\n *\n * @param message The message to capture.\n * @param level An optional severity level to report the message with.\n * @param hint Optional additional data to attach to the Sentry event.\n * @returns the id of the captured message.\n */\n public captureMessage(message: string, level?: SeverityLevel, hint?: EventHint): string {\n const eventId = hint && hint.event_id ? hint.event_id : uuid4();\n\n if (!this._client) {\n logger.warn('No client configured on scope - will not capture message!');\n return eventId;\n }\n\n const syntheticException = new Error(message);\n\n this._client.captureMessage(\n message,\n level,\n {\n originalException: message,\n syntheticException,\n ...hint,\n event_id: eventId,\n },\n this,\n );\n\n return eventId;\n }\n\n /**\n * Captures a manually created event for this scope and sends it to Sentry.\n *\n * @param exception The event to capture.\n * @param hint Optional additional data to attach to the Sentry event.\n * @returns the id of the captured event.\n */\n public captureEvent(event: Event, hint?: EventHint): string {\n const eventId = hint && hint.event_id ? hint.event_id : uuid4();\n\n if (!this._client) {\n logger.warn('No client configured on scope - will not capture event!');\n return eventId;\n }\n\n this._client.captureEvent(event, { ...hint, event_id: eventId }, this);\n\n return eventId;\n }\n\n /**\n * This will be called on every set call.\n */\n protected _notifyScopeListeners(): void {\n // We need this check for this._notifyingListeners to be able to work on scope during updates\n // If this check is not here we'll produce endless recursion when something is done with the scope\n // during the callback.\n if (!this._notifyingListeners) {\n this._notifyingListeners = true;\n this._scopeListeners.forEach(callback => {\n callback(this);\n });\n this._notifyingListeners = false;\n }\n }\n}\n\n/**\n * Get the global scope.\n * This scope is applied to _all_ events.\n */\nexport function getGlobalScope(): ScopeInterface {\n if (!globalScope) {\n globalScope = new Scope();\n }\n\n return globalScope;\n}\n\n/**\n * This is mainly needed for tests.\n * DO NOT USE this, as this is an internal API and subject to change.\n * @hidden\n */\nexport function setGlobalScope(scope: ScopeInterface | undefined): void {\n globalScope = scope;\n}\n\nfunction generatePropagationContext(): PropagationContext {\n return {\n traceId: uuid4(),\n spanId: uuid4().substring(16),\n };\n}\n","export const SDK_VERSION = '7.118.0';\n","/* eslint-disable max-lines */\nimport type {\n Breadcrumb,\n BreadcrumbHint,\n Client,\n CustomSamplingContext,\n Event,\n EventHint,\n Extra,\n Extras,\n Hub as HubInterface,\n Integration,\n IntegrationClass,\n Primitive,\n Session,\n SessionContext,\n Severity,\n SeverityLevel,\n Transaction,\n TransactionContext,\n User,\n} from '@sentry/types';\nimport {\n GLOBAL_OBJ,\n consoleSandbox,\n dateTimestampInSeconds,\n getGlobalSingleton,\n isThenable,\n logger,\n uuid4,\n} from '@sentry/utils';\n\nimport { DEFAULT_ENVIRONMENT } from './constants';\nimport { DEBUG_BUILD } from './debug-build';\nimport { Scope } from './scope';\nimport { closeSession, makeSession, updateSession } from './session';\nimport { SDK_VERSION } from './version';\n\n/**\n * API compatibility version of this hub.\n *\n * WARNING: This number should only be increased when the global interface\n * changes and new methods are introduced.\n *\n * @hidden\n */\nexport const API_VERSION = parseFloat(SDK_VERSION);\n\n/**\n * Default maximum number of breadcrumbs added to an event. Can be overwritten\n * with {@link Options.maxBreadcrumbs}.\n */\nconst DEFAULT_BREADCRUMBS = 100;\n\nexport interface RunWithAsyncContextOptions {\n /** Whether to reuse an existing async context if one exists. Defaults to false. */\n reuseExisting?: boolean;\n}\n\n/**\n * @private Private API with no semver guarantees!\n *\n * Strategy used to track async context.\n */\nexport interface AsyncContextStrategy {\n /**\n * Gets the current async context. Returns undefined if there is no current async context.\n */\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub: () => Hub | undefined;\n /**\n * Runs the supplied callback in its own async context.\n */\n runWithAsyncContext<T>(callback: () => T, options: RunWithAsyncContextOptions): T;\n}\n\n/**\n * A layer in the process stack.\n * @hidden\n */\nexport interface Layer {\n client?: Client;\n scope: Scope;\n}\n\n/**\n * An object that contains a hub and maintains a scope stack.\n * @hidden\n */\nexport interface Carrier {\n __SENTRY__?: {\n // eslint-disable-next-line deprecation/deprecation\n hub?: Hub;\n acs?: AsyncContextStrategy;\n /**\n * Extra Hub properties injected by various SDKs\n */\n integrations?: Integration[];\n extensions?: {\n /** Extension methods for the hub, which are bound to the current Hub instance */\n // eslint-disable-next-line @typescript-eslint/ban-types\n [key: string]: Function;\n };\n };\n}\n\n/**\n * @deprecated The `Hub` class will be removed in version 8 of the SDK in favour of `Scope` and `Client` objects.\n *\n * If you previously used the `Hub` class directly, replace it with `Scope` and `Client` objects. More information:\n * - [Multiple Sentry Instances](https://docs.sentry.io/platforms/javascript/best-practices/multiple-sentry-instances/)\n * - [Browser Extensions](https://docs.sentry.io/platforms/javascript/best-practices/browser-extensions/)\n *\n * Some of our APIs are typed with the Hub class instead of the interface (e.g. `getCurrentHub`). Most of them are deprecated\n * themselves and will also be removed in version 8. More information:\n * - [Migration Guide](https://github.com/getsentry/sentry-javascript/blob/develop/MIGRATION.md#deprecate-hub)\n */\n// eslint-disable-next-line deprecation/deprecation\nexport class Hub implements HubInterface {\n /** Is a {@link Layer}[] containing the client and scope */\n private readonly _stack: Layer[];\n\n /** Contains the last event id of a captured event. */\n private _lastEventId?: string;\n\n private _isolationScope: Scope;\n\n /**\n * Creates a new instance of the hub, will push one {@link Layer} into the\n * internal stack on creation.\n *\n * @param client bound to the hub.\n * @param scope bound to the hub.\n * @param version number, higher number means higher priority.\n *\n * @deprecated Instantiation of Hub objects is deprecated and the constructor will be removed in version 8 of the SDK.\n *\n * If you are currently using the Hub for multi-client use like so:\n *\n * ```\n * // OLD\n * const hub = new Hub();\n * hub.bindClient(client);\n * makeMain(hub)\n * ```\n *\n * instead initialize the client as follows:\n *\n * ```\n * // NEW\n * Sentry.withIsolationScope(() => {\n * Sentry.setCurrentClient(client);\n * client.init();\n * });\n * ```\n *\n * If you are using the Hub to capture events like so:\n *\n * ```\n * // OLD\n * const client = new Client();\n * const hub = new Hub(client);\n * hub.captureException()\n * ```\n *\n * instead capture isolated events as follows:\n *\n * ```\n * // NEW\n * const client = new Client();\n * const scope = new Scope();\n * scope.setClient(client);\n * scope.captureException();\n * ```\n */\n public constructor(\n client?: Client,\n scope?: Scope,\n isolationScope?: Scope,\n private readonly _version: number = API_VERSION,\n ) {\n let assignedScope;\n if (!scope) {\n assignedScope = new Scope();\n assignedScope.setClient(client);\n } else {\n assignedScope = scope;\n }\n\n let assignedIsolationScope;\n if (!isolationScope) {\n assignedIsolationScope = new Scope();\n assignedIsolationScope.setClient(client);\n } else {\n assignedIsolationScope = isolationScope;\n }\n\n this._stack = [{ scope: assignedScope }];\n\n if (client) {\n // eslint-disable-next-line deprecation/deprecation\n this.bindClient(client);\n }\n\n this._isolationScope = assignedIsolationScope;\n }\n\n /**\n * Checks if this hub's version is older than the given version.\n *\n * @param version A version number to compare to.\n * @return True if the given version is newer; otherwise false.\n *\n * @deprecated This will be removed in v8.\n */\n public isOlderThan(version: number): boolean {\n return this._version < version;\n }\n\n /**\n * This binds the given client to the current scope.\n * @param client An SDK client (client) instance.\n *\n * @deprecated Use `initAndBind()` directly, or `setCurrentClient()` and/or `client.init()` instead.\n */\n public bindClient(client?: Client): void {\n // eslint-disable-next-line deprecation/deprecation\n const top = this.getStackTop();\n top.client = client;\n top.scope.setClient(client);\n // eslint-disable-next-line deprecation/deprecation\n if (client && client.setupIntegrations) {\n // eslint-disable-next-line deprecation/deprecation\n client.setupIntegrations();\n }\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `withScope` instead.\n */\n public pushScope(): Scope {\n // We want to clone the content of prev scope\n // eslint-disable-next-line deprecation/deprecation\n const scope = this.getScope().clone();\n // eslint-disable-next-line deprecation/deprecation\n this.getStack().push({\n // eslint-disable-next-line deprecation/deprecation\n client: this.getClient(),\n scope,\n });\n return scope;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `withScope` instead.\n */\n public popScope(): boolean {\n // eslint-disable-next-line deprecation/deprecation\n if (this.getStack().length <= 1) return false;\n // eslint-disable-next-line deprecation/deprecation\n return !!this.getStack().pop();\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `Sentry.withScope()` instead.\n */\n public withScope<T>(callback: (scope: Scope) => T): T {\n // eslint-disable-next-line deprecation/deprecation\n const scope = this.pushScope();\n\n let maybePromiseResult: T;\n try {\n maybePromiseResult = callback(scope);\n } catch (e) {\n // eslint-disable-next-line deprecation/deprecation\n this.popScope();\n throw e;\n }\n\n if (isThenable(maybePromiseResult)) {\n // @ts-expect-error - isThenable returns the wrong type\n return maybePromiseResult.then(\n res => {\n // eslint-disable-next-line deprecation/deprecation\n this.popScope();\n return res;\n },\n e => {\n // eslint-disable-next-line deprecation/deprecation\n this.popScope();\n throw e;\n },\n );\n }\n\n // eslint-disable-next-line deprecation/deprecation\n this.popScope();\n return maybePromiseResult;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `Sentry.getClient()` instead.\n */\n public getClient<C extends Client>(): C | undefined {\n // eslint-disable-next-line deprecation/deprecation\n return this.getStackTop().client as C;\n }\n\n /**\n * Returns the scope of the top stack.\n *\n * @deprecated Use `Sentry.getCurrentScope()` instead.\n */\n public getScope(): Scope {\n // eslint-disable-next-line deprecation/deprecation\n return this.getStackTop().scope;\n }\n\n /**\n * @deprecated Use `Sentry.getIsolationScope()` instead.\n */\n public getIsolationScope(): Scope {\n return this._isolationScope;\n }\n\n /**\n * Returns the scope stack for domains or the process.\n * @deprecated This will be removed in v8.\n */\n public getStack(): Layer[] {\n return this._stack;\n }\n\n /**\n * Returns the topmost scope layer in the order domain > local > process.\n * @deprecated This will be removed in v8.\n */\n public getStackTop(): Layer {\n return this._stack[this._stack.length - 1];\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `Sentry.captureException()` instead.\n */\n public captureException(exception: unknown, hint?: EventHint): string {\n const eventId = (this._lastEventId = hint && hint.event_id ? hint.event_id : uuid4());\n const syntheticException = new Error('Sentry syntheticException');\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().captureException(exception, {\n originalException: exception,\n syntheticException,\n ...hint,\n event_id: eventId,\n });\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `Sentry.captureMessage()` instead.\n */\n public captureMessage(\n message: string,\n // eslint-disable-next-line deprecation/deprecation\n level?: Severity | SeverityLevel,\n hint?: EventHint,\n ): string {\n const eventId = (this._lastEventId = hint && hint.event_id ? hint.event_id : uuid4());\n const syntheticException = new Error(message);\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().captureMessage(message, level, {\n originalException: message,\n syntheticException,\n ...hint,\n event_id: eventId,\n });\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `Sentry.captureEvent()` instead.\n */\n public captureEvent(event: Event, hint?: EventHint): string {\n const eventId = hint && hint.event_id ? hint.event_id : uuid4();\n if (!event.type) {\n this._lastEventId = eventId;\n }\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().captureEvent(event, { ...hint, event_id: eventId });\n return eventId;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated This will be removed in v8.\n */\n public lastEventId(): string | undefined {\n return this._lastEventId;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `Sentry.addBreadcrumb()` instead.\n */\n public addBreadcrumb(breadcrumb: Breadcrumb, hint?: BreadcrumbHint): void {\n // eslint-disable-next-line deprecation/deprecation\n const { scope, client } = this.getStackTop();\n\n if (!client) return;\n\n const { beforeBreadcrumb = null, maxBreadcrumbs = DEFAULT_BREADCRUMBS } =\n (client.getOptions && client.getOptions()) || {};\n\n if (maxBreadcrumbs <= 0) return;\n\n const timestamp = dateTimestampInSeconds();\n const mergedBreadcrumb = { timestamp, ...breadcrumb };\n const finalBreadcrumb = beforeBreadcrumb\n ? (consoleSandbox(() => beforeBreadcrumb(mergedBreadcrumb, hint)) as Breadcrumb | null)\n : mergedBreadcrumb;\n\n if (finalBreadcrumb === null) return;\n\n if (client.emit) {\n client.emit('beforeAddBreadcrumb', finalBreadcrumb, hint);\n }\n\n // TODO(v8): I know this comment doesn't make much sense because the hub will be deprecated but I still wanted to\n // write it down. In theory, we would have to add the breadcrumbs to the isolation scope here, however, that would\n // duplicate all of the breadcrumbs. There was the possibility of adding breadcrumbs to both, the isolation scope\n // and the normal scope, and deduplicating it down the line in the event processing pipeline. However, that would\n // have been very fragile, because the breadcrumb objects would have needed to keep their identity all throughout\n // the event processing pipeline.\n // In the new implementation, the top level `Sentry.addBreadcrumb()` should ONLY write to the isolation scope.\n\n scope.addBreadcrumb(finalBreadcrumb, maxBreadcrumbs);\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `Sentry.setUser()` instead.\n */\n public setUser(user: User | null): void {\n // TODO(v8): The top level `Sentry.setUser()` function should write ONLY to the isolation scope.\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().setUser(user);\n // eslint-disable-next-line deprecation/deprecation\n this.getIsolationScope().setUser(user);\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `Sentry.setTags()` instead.\n */\n public setTags(tags: { [key: string]: Primitive }): void {\n // TODO(v8): The top level `Sentry.setTags()` function should write ONLY to the isolation scope.\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().setTags(tags);\n // eslint-disable-next-line deprecation/deprecation\n this.getIsolationScope().setTags(tags);\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `Sentry.setExtras()` instead.\n */\n public setExtras(extras: Extras): void {\n // TODO(v8): The top level `Sentry.setExtras()` function should write ONLY to the isolation scope.\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().setExtras(extras);\n // eslint-disable-next-line deprecation/deprecation\n this.getIsolationScope().setExtras(extras);\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `Sentry.setTag()` instead.\n */\n public setTag(key: string, value: Primitive): void {\n // TODO(v8): The top level `Sentry.setTag()` function should write ONLY to the isolation scope.\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().setTag(key, value);\n // eslint-disable-next-line deprecation/deprecation\n this.getIsolationScope().setTag(key, value);\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `Sentry.setExtra()` instead.\n */\n public setExtra(key: string, extra: Extra): void {\n // TODO(v8): The top level `Sentry.setExtra()` function should write ONLY to the isolation scope.\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().setExtra(key, extra);\n // eslint-disable-next-line deprecation/deprecation\n this.getIsolationScope().setExtra(key, extra);\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `Sentry.setContext()` instead.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n public setContext(name: string, context: { [key: string]: any } | null): void {\n // TODO(v8): The top level `Sentry.setContext()` function should write ONLY to the isolation scope.\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().setContext(name, context);\n // eslint-disable-next-line deprecation/deprecation\n this.getIsolationScope().setContext(name, context);\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `getScope()` directly.\n */\n public configureScope(callback: (scope: Scope) => void): void {\n // eslint-disable-next-line deprecation/deprecation\n const { scope, client } = this.getStackTop();\n if (client) {\n callback(scope);\n }\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line deprecation/deprecation\n public run(callback: (hub: Hub) => void): void {\n // eslint-disable-next-line deprecation/deprecation\n const oldHub = makeMain(this);\n try {\n callback(this);\n } finally {\n // eslint-disable-next-line deprecation/deprecation\n makeMain(oldHub);\n }\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `Sentry.getClient().getIntegrationByName()` instead.\n */\n public getIntegration<T extends Integration>(integration: IntegrationClass<T>): T | null {\n // eslint-disable-next-line deprecation/deprecation\n const client = this.getClient();\n if (!client) return null;\n try {\n // eslint-disable-next-line deprecation/deprecation\n return client.getIntegration(integration);\n } catch (_oO) {\n DEBUG_BUILD && logger.warn(`Cannot retrieve integration ${integration.id} from the current Hub`);\n return null;\n }\n }\n\n /**\n * Starts a new `Transaction` and returns it. This is the entry point to manual tracing instrumentation.\n *\n * A tree structure can be built by adding child spans to the transaction, and child spans to other spans. To start a\n * new child span within the transaction or any span, call the respective `.startChild()` method.\n *\n * Every child span must be finished before the transaction is finished, otherwise the unfinished spans are discarded.\n *\n * The transaction must be finished with a call to its `.end()` method, at which point the transaction with all its\n * finished child spans will be sent to Sentry.\n *\n * @param context Properties of the new `Transaction`.\n * @param customSamplingContext Information given to the transaction sampling function (along with context-dependent\n * default values). See {@link Options.tracesSampler}.\n *\n * @returns The transaction which was just started\n *\n * @deprecated Use `startSpan()`, `startSpanManual()` or `startInactiveSpan()` instead.\n */\n public startTransaction(context: TransactionContext, customSamplingContext?: CustomSamplingContext): Transaction {\n const result = this._callExtensionMethod<Transaction>('startTransaction', context, customSamplingContext);\n\n if (DEBUG_BUILD && !result) {\n // eslint-disable-next-line deprecation/deprecation\n const client = this.getClient();\n if (!client) {\n logger.warn(\n \"Tracing extension 'startTransaction' is missing. You should 'init' the SDK before calling 'startTransaction'\",\n );\n } else {\n logger.warn(`Tracing extension 'startTransaction' has not been added. Call 'addTracingExtensions' before calling 'init':\nSentry.addTracingExtensions();\nSentry.init({...});\n`);\n }\n }\n\n return result;\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `spanToTraceHeader()` instead.\n */\n public traceHeaders(): { [key: string]: string } {\n return this._callExtensionMethod<{ [key: string]: string }>('traceHeaders');\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use top level `captureSession` instead.\n */\n public captureSession(endSession: boolean = false): void {\n // both send the update and pull the session from the scope\n if (endSession) {\n // eslint-disable-next-line deprecation/deprecation\n return this.endSession();\n }\n\n // only send the update\n this._sendSessionUpdate();\n }\n\n /**\n * @inheritDoc\n * @deprecated Use top level `endSession` instead.\n */\n public endSession(): void {\n // eslint-disable-next-line deprecation/deprecation\n const layer = this.getStackTop();\n const scope = layer.scope;\n const session = scope.getSession();\n if (session) {\n closeSession(session);\n }\n this._sendSessionUpdate();\n\n // the session is over; take it off of the scope\n scope.setSession();\n }\n\n /**\n * @inheritDoc\n * @deprecated Use top level `startSession` instead.\n */\n public startSession(context?: SessionContext): Session {\n // eslint-disable-next-line deprecation/deprecation\n const { scope, client } = this.getStackTop();\n const { release, environment = DEFAULT_ENVIRONMENT } = (client && client.getOptions()) || {};\n\n // Will fetch userAgent if called from browser sdk\n const { userAgent } = GLOBAL_OBJ.navigator || {};\n\n const session = makeSession({\n release,\n environment,\n user: scope.getUser(),\n ...(userAgent && { userAgent }),\n ...context,\n });\n\n // End existing session if there's one\n const currentSession = scope.getSession && scope.getSession();\n if (currentSession && currentSession.status === 'ok') {\n updateSession(currentSession, { status: 'exited' });\n }\n // eslint-disable-next-line deprecation/deprecation\n this.endSession();\n\n // Afterwards we set the new session on the scope\n scope.setSession(session);\n\n return session;\n }\n\n /**\n * Returns if default PII should be sent to Sentry and propagated in ourgoing requests\n * when Tracing is used.\n *\n * @deprecated Use top-level `getClient().getOptions().sendDefaultPii` instead. This function\n * only unnecessarily increased API surface but only wrapped accessing the option.\n */\n public shouldSendDefaultPii(): boolean {\n // eslint-disable-next-line deprecation/deprecation\n const client = this.getClient();\n const options = client && client.getOptions();\n return Boolean(options && options.sendDefaultPii);\n }\n\n /**\n * Sends the current Session on the scope\n */\n private _sendSessionUpdate(): void {\n // eslint-disable-next-line deprecation/deprecation\n const { scope, client } = this.getStackTop();\n\n const session = scope.getSession();\n if (session && client && client.captureSession) {\n client.captureSession(session);\n }\n }\n\n /**\n * Calls global extension method and binding current instance to the function call\n */\n // @ts-expect-error 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 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 GLOBAL_OBJ.__SENTRY__ = GLOBAL_OBJ.__SENTRY__ || {\n extensions: {},\n hub: undefined,\n };\n return GLOBAL_OBJ;\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 *\n * @deprecated Use `setCurrentClient()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\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 *\n * @deprecated Use the respective replacement method directly instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function getCurrentHub(): Hub {\n // Get main carrier (global for every environment)\n const registry = getMainCarrier();\n\n if (registry.__SENTRY__ && registry.__SENTRY__.acs) {\n const hub = registry.__SENTRY__.acs.getCurrentHub();\n\n if (hub) {\n return hub;\n }\n }\n\n // Return hub that lives on a global object\n return getGlobalHub(registry);\n}\n\n/**\n * Get the currently active isolation scope.\n * The isolation scope is active for the current exection context,\n * meaning that it will remain stable for the same Hub.\n */\nexport function getIsolationScope(): Scope {\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().getIsolationScope();\n}\n\n// eslint-disable-next-line deprecation/deprecation\nfunction getGlobalHub(registry: Carrier = getMainCarrier()): Hub {\n // If there's no hub, or its an old API, assign a new one\n\n if (\n !hasHubOnCarrier(registry) ||\n // eslint-disable-next-line deprecation/deprecation\n getHubFromCarrier(registry).isOlderThan(API_VERSION)\n ) {\n // eslint-disable-next-line deprecation/deprecation\n setHubOnCarrier(registry, new Hub());\n }\n\n // Return hub that lives on a global object\n return getHubFromCarrier(registry);\n}\n\n/**\n * @private Private API with no semver guarantees!\n *\n * If the carrier does not contain a hub, a new hub is created with the global hub client and scope.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function ensureHubOnCarrier(carrier: Carrier, parent: Hub = getGlobalHub()): void {\n // If there's no hub on current domain, or it's an old API, assign a new one\n if (\n !hasHubOnCarrier(carrier) ||\n // eslint-disable-next-line deprecation/deprecation\n getHubFromCarrier(carrier).isOlderThan(API_VERSION)\n ) {\n // eslint-disable-next-line deprecation/deprecation\n const client = parent.getClient();\n // eslint-disable-next-line deprecation/deprecation\n const scope = parent.getScope();\n // eslint-disable-next-line deprecation/deprecation\n const isolationScope = parent.getIsolationScope();\n // eslint-disable-next-line deprecation/deprecation\n setHubOnCarrier(carrier, new Hub(client, scope.clone(), isolationScope.clone()));\n }\n}\n\n/**\n * @private Private API with no semver guarantees!\n *\n * Sets the global async context strategy\n */\nexport function setAsyncContextStrategy(strategy: AsyncContextStrategy | undefined): void {\n // Get main carrier (global for every environment)\n const registry = getMainCarrier();\n registry.__SENTRY__ = registry.__SENTRY__ || {};\n registry.__SENTRY__.acs = strategy;\n}\n\n/**\n * Runs the supplied callback in its own async context. Async Context strategies are defined per SDK.\n *\n * @param callback The callback to run in its own async context\n * @param options Options to pass to the async context strategy\n * @returns The result of the callback\n */\nexport function runWithAsyncContext<T>(callback: () => T, options: RunWithAsyncContextOptions = {}): T {\n const registry = getMainCarrier();\n\n if (registry.__SENTRY__ && registry.__SENTRY__.acs) {\n return registry.__SENTRY__.acs.runWithAsyncContext(callback, options);\n }\n\n // if there was no strategy, fallback to just calling the callback\n return callback();\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 */\n// eslint-disable-next-line deprecation/deprecation\nexport function getHubFromCarrier(carrier: Carrier): Hub {\n // eslint-disable-next-line deprecation/deprecation\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 */\n// eslint-disable-next-line deprecation/deprecation\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 type {\n CaptureContext,\n Client,\n ClientOptions,\n Event,\n EventHint,\n Scope as ScopeInterface,\n ScopeContext,\n StackFrame,\n StackParser,\n} from '@sentry/types';\nimport { GLOBAL_OBJ, addExceptionMechanism, dateTimestampInSeconds, normalize, truncate, uuid4 } from '@sentry/utils';\n\nimport { DEFAULT_ENVIRONMENT } from '../constants';\nimport { getGlobalEventProcessors, notifyEventProcessors } from '../eventProcessors';\nimport { Scope, getGlobalScope } from '../scope';\nimport { applyScopeDataToEvent, mergeScopeData } from './applyScopeDataToEvent';\nimport { spanToJSON } from './spanUtils';\n\n/**\n * This type makes sure that we get either a CaptureContext, OR an EventHint.\n * It does not allow mixing them, which could lead to unexpected outcomes, e.g. this is disallowed:\n * { user: { id: '123' }, mechanism: { handled: false } }\n */\nexport type ExclusiveEventHintOrCaptureContext =\n | (CaptureContext & Partial<{ [key in keyof EventHint]: never }>)\n | (EventHint & Partial<{ [key in keyof ScopeContext]: never }>);\n\n/**\n * Adds common information to events.\n *\n * The information includes release and environment from `options`,\n * breadcrumbs and context (extra, tags and user) from the scope.\n *\n * Information that is already present in the event is never overwritten. For\n * nested objects, such as the context, keys are merged.\n *\n * Note: This also triggers callbacks for `addGlobalEventProcessor`, but not `beforeSend`.\n *\n * @param event The original event.\n * @param hint May contain additional information about the original exception.\n * @param scope A scope containing event metadata.\n * @returns A new event with more information.\n * @hidden\n */\nexport function prepareEvent(\n options: ClientOptions,\n event: Event,\n hint: EventHint,\n scope?: Scope,\n client?: Client,\n isolationScope?: Scope,\n): PromiseLike<Event | null> {\n const { normalizeDepth = 3, normalizeMaxBreadth = 1_000 } = options;\n const prepared: Event = {\n ...event,\n event_id: event.event_id || hint.event_id || uuid4(),\n timestamp: event.timestamp || dateTimestampInSeconds(),\n };\n const integrations = hint.integrations || options.integrations.map(i => i.name);\n\n applyClientOptions(prepared, options);\n applyIntegrationsMetadata(prepared, integrations);\n\n // Only put debug IDs onto frames for error events.\n if (event.type === undefined) {\n applyDebugIds(prepared, options.stackParser);\n }\n\n // If we have scope given to us, use it as the base for further modifications.\n // This allows us to prevent unnecessary copying of data if `captureContext` is not provided.\n const finalScope = getFinalScope(scope, hint.captureContext);\n\n if (hint.mechanism) {\n addExceptionMechanism(prepared, hint.mechanism);\n }\n\n const clientEventProcessors = client && client.getEventProcessors ? client.getEventProcessors() : [];\n\n // This should be the last thing called, since we want that\n // {@link Hub.addEventProcessor} gets the finished prepared event.\n // Merge scope data together\n const data = getGlobalScope().getScopeData();\n\n if (isolationScope) {\n const isolationData = isolationScope.getScopeData();\n mergeScopeData(data, isolationData);\n }\n\n if (finalScope) {\n const finalScopeData = finalScope.getScopeData();\n mergeScopeData(data, finalScopeData);\n }\n\n const attachments = [...(hint.attachments || []), ...data.attachments];\n if (attachments.length) {\n hint.attachments = attachments;\n }\n\n applyScopeDataToEvent(prepared, data);\n\n // TODO (v8): Update this order to be: Global > Client > Scope\n const eventProcessors = [\n ...clientEventProcessors,\n // eslint-disable-next-line deprecation/deprecation\n ...getGlobalEventProcessors(),\n // Run scope event processors _after_ all other processors\n ...data.eventProcessors,\n ];\n\n const result = notifyEventProcessors(eventProcessors, prepared, hint);\n\n return result.then(evt => {\n if (evt) {\n // We apply the debug_meta field only after all event processors have ran, so that if any event processors modified\n // file names (e.g.the RewriteFrames integration) the filename -> debug ID relationship isn't destroyed.\n // This should not cause any PII issues, since we're only moving data that is already on the event and not adding\n // any new data\n applyDebugMeta(evt);\n }\n\n if (typeof normalizeDepth === 'number' && normalizeDepth > 0) {\n return normalizeEvent(evt, normalizeDepth, normalizeMaxBreadth);\n }\n return evt;\n });\n}\n\n/**\n * Enhances event using the client configuration.\n * It takes care of all \"static\" values like environment, release and `dist`,\n * as well as truncating overly long values.\n * @param event event instance to be enhanced\n */\nfunction applyClientOptions(event: Event, options: ClientOptions): void {\n const { environment, release, dist, maxValueLength = 250 } = options;\n\n if (!('environment' in event)) {\n event.environment = 'environment' in options ? environment : DEFAULT_ENVIRONMENT;\n }\n\n if (event.release === undefined && release !== undefined) {\n event.release = release;\n }\n\n if (event.dist === undefined && dist !== undefined) {\n event.dist = dist;\n }\n\n if (event.message) {\n event.message = truncate(event.message, maxValueLength);\n }\n\n const exception = event.exception && event.exception.values && event.exception.values[0];\n if (exception && exception.value) {\n exception.value = truncate(exception.value, maxValueLength);\n }\n\n const request = event.request;\n if (request && request.url) {\n request.url = truncate(request.url, maxValueLength);\n }\n}\n\nconst debugIdStackParserCache = new WeakMap<StackParser, Map<string, StackFrame[]>>();\n\n/**\n * Puts debug IDs into the stack frames of an error event.\n */\nexport function applyDebugIds(event: Event, stackParser: StackParser): void {\n const debugIdMap = GLOBAL_OBJ._sentryDebugIds;\n\n if (!debugIdMap) {\n return;\n }\n\n let debugIdStackFramesCache: Map<string, StackFrame[]>;\n const cachedDebugIdStackFrameCache = debugIdStackParserCache.get(stackParser);\n if (cachedDebugIdStackFrameCache) {\n debugIdStackFramesCache = cachedDebugIdStackFrameCache;\n } else {\n debugIdStackFramesCache = new Map<string, StackFrame[]>();\n debugIdStackParserCache.set(stackParser, debugIdStackFramesCache);\n }\n\n // Build a map of filename -> debug_id\n const filenameDebugIdMap = Object.keys(debugIdMap).reduce<Record<string, string>>((acc, debugIdStackTrace) => {\n let parsedStack: StackFrame[];\n const cachedParsedStack = debugIdStackFramesCache.get(debugIdStackTrace);\n if (cachedParsedStack) {\n parsedStack = cachedParsedStack;\n } else {\n parsedStack = stackParser(debugIdStackTrace);\n debugIdStackFramesCache.set(debugIdStackTrace, parsedStack);\n }\n\n for (let i = parsedStack.length - 1; i >= 0; i--) {\n const stackFrame = parsedStack[i];\n if (stackFrame.filename) {\n acc[stackFrame.filename] = debugIdMap[debugIdStackTrace];\n break;\n }\n }\n return acc;\n }, {});\n\n try {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n event!.exception!.values!.forEach(exception => {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n exception.stacktrace!.frames!.forEach(frame => {\n if (frame.filename) {\n frame.debug_id = filenameDebugIdMap[frame.filename];\n }\n });\n });\n } catch (e) {\n // To save bundle size we're just try catching here instead of checking for the existence of all the different objects.\n }\n}\n\n/**\n * Moves debug IDs from the stack frames of an error event into the debug_meta field.\n */\nexport function applyDebugMeta(event: Event): void {\n // Extract debug IDs and filenames from the stack frames on the event.\n const filenameDebugIdMap: Record<string, string> = {};\n try {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n event.exception!.values!.forEach(exception => {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n exception.stacktrace!.frames!.forEach(frame => {\n if (frame.debug_id) {\n if (frame.abs_path) {\n filenameDebugIdMap[frame.abs_path] = frame.debug_id;\n } else if (frame.filename) {\n filenameDebugIdMap[frame.filename] = frame.debug_id;\n }\n delete frame.debug_id;\n }\n });\n });\n } catch (e) {\n // To save bundle size we're just try catching here instead of checking for the existence of all the different objects.\n }\n\n if (Object.keys(filenameDebugIdMap).length === 0) {\n return;\n }\n\n // Fill debug_meta information\n event.debug_meta = event.debug_meta || {};\n event.debug_meta.images = event.debug_meta.images || [];\n const images = event.debug_meta.images;\n Object.keys(filenameDebugIdMap).forEach(filename => {\n images.push({\n type: 'sourcemap',\n code_file: filename,\n debug_id: filenameDebugIdMap[filename],\n });\n });\n}\n\n/**\n * This function adds all used integrations to the SDK info in the event.\n * @param event The event that will be filled with all integrations.\n */\nfunction applyIntegrationsMetadata(event: Event, integrationNames: string[]): void {\n if (integrationNames.length > 0) {\n event.sdk = event.sdk || {};\n event.sdk.integrations = [...(event.sdk.integrations || []), ...integrationNames];\n }\n}\n\n/**\n * Applies `normalize` function on necessary `Event` attributes to make them safe for serialization.\n * Normalized keys:\n * - `breadcrumbs.data`\n * - `user`\n * - `contexts`\n * - `extra`\n * @param event Event\n * @returns Normalized event\n */\nfunction normalizeEvent(event: Event | null, depth: number, maxBreadth: number): Event | null {\n if (!event) {\n return null;\n }\n\n const normalized: Event = {\n ...event,\n ...(event.breadcrumbs && {\n breadcrumbs: event.breadcrumbs.map(b => ({\n ...b,\n ...(b.data && {\n data: normalize(b.data, depth, maxBreadth),\n }),\n })),\n }),\n ...(event.user && {\n user: normalize(event.user, depth, maxBreadth),\n }),\n ...(event.contexts && {\n contexts: normalize(event.contexts, depth, maxBreadth),\n }),\n ...(event.extra && {\n extra: normalize(event.extra, depth, maxBreadth),\n }),\n };\n\n // event.contexts.trace stores information about a Transaction. Similarly,\n // event.spans[] stores information about child Spans. Given that a\n // Transaction is conceptually a Span, normalization should apply to both\n // Transactions and Spans consistently.\n // For now the decision is to skip normalization of Transactions and Spans,\n // so this block overwrites the normalized event to add back the original\n // Transaction information prior to normalization.\n if (event.contexts && event.contexts.trace && normalized.contexts) {\n normalized.contexts.trace = event.contexts.trace;\n\n // event.contexts.trace.data may contain circular/dangerous data so we need to normalize it\n if (event.contexts.trace.data) {\n normalized.contexts.trace.data = normalize(event.contexts.trace.data, depth, maxBreadth);\n }\n }\n\n // event.spans[].data may contain circular/dangerous data so we need to normalize it\n if (event.spans) {\n normalized.spans = event.spans.map(span => {\n const data = spanToJSON(span).data;\n\n if (data) {\n // This is a bit weird, as we generally have `Span` instances here, but to be safe we do not assume so\n // eslint-disable-next-line deprecation/deprecation\n span.data = normalize(data, depth, maxBreadth);\n }\n\n return span;\n });\n }\n\n return normalized;\n}\n\nfunction getFinalScope(scope: Scope | undefined, captureContext: CaptureContext | undefined): Scope | undefined {\n if (!captureContext) {\n return scope;\n }\n\n const finalScope = scope ? scope.clone() : new Scope();\n finalScope.update(captureContext);\n return finalScope;\n}\n\n/**\n * Parse either an `EventHint` directly, or convert a `CaptureContext` to an `EventHint`.\n * This is used to allow to update method signatures that used to accept a `CaptureContext` but should now accept an `EventHint`.\n */\nexport function parseEventHintOrCaptureContext(\n hint: ExclusiveEventHintOrCaptureContext | undefined,\n): EventHint | undefined {\n if (!hint) {\n return undefined;\n }\n\n // If you pass a Scope or `() => Scope` as CaptureContext, we just return this as captureContext\n if (hintIsScopeOrFunction(hint)) {\n return { captureContext: hint };\n }\n\n if (hintIsScopeContext(hint)) {\n return {\n captureContext: hint,\n };\n }\n\n return hint;\n}\n\nfunction hintIsScopeOrFunction(\n hint: CaptureContext | EventHint,\n): hint is ScopeInterface | ((scope: ScopeInterface) => ScopeInterface) {\n return hint instanceof Scope || typeof hint === 'function';\n}\n\ntype ScopeContextProperty = keyof ScopeContext;\nconst captureContextKeys: readonly ScopeContextProperty[] = [\n 'user',\n 'level',\n 'extra',\n 'contexts',\n 'tags',\n 'fingerprint',\n 'requestSession',\n 'propagationContext',\n] as const;\n\nfunction hintIsScopeContext(hint: Partial<ScopeContext> | EventHint): hint is Partial<ScopeContext> {\n return Object.keys(hint).some(key => captureContextKeys.includes(key as ScopeContextProperty));\n}\n","import type {\n Breadcrumb,\n BreadcrumbHint,\n CaptureContext,\n CheckIn,\n Client,\n CustomSamplingContext,\n Event,\n EventHint,\n Extra,\n Extras,\n FinishedCheckIn,\n MonitorConfig,\n Primitive,\n Scope as ScopeInterface,\n Session,\n SessionContext,\n Severity,\n SeverityLevel,\n Span,\n TransactionContext,\n User,\n} from '@sentry/types';\nimport { GLOBAL_OBJ, isThenable, logger, timestampInSeconds, uuid4 } from '@sentry/utils';\n\nimport { DEFAULT_ENVIRONMENT } from './constants';\nimport { DEBUG_BUILD } from './debug-build';\nimport type { Hub } from './hub';\nimport { runWithAsyncContext } from './hub';\nimport { getCurrentHub, getIsolationScope } from './hub';\nimport type { Scope } from './scope';\nimport { closeSession, makeSession, updateSession } from './session';\nimport type { ExclusiveEventHintOrCaptureContext } from './utils/prepareEvent';\nimport { parseEventHintOrCaptureContext } from './utils/prepareEvent';\n\n/**\n * Captures an exception event and sends it to Sentry.\n *\n * @param exception The exception to capture.\n * @param hint Optional additional data to attach to the Sentry event.\n * @returns the id of the captured Sentry event.\n */\nexport function captureException(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n exception: any,\n hint?: ExclusiveEventHintOrCaptureContext,\n): string {\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().captureException(exception, parseEventHintOrCaptureContext(hint));\n}\n\n/**\n * Captures a message event and sends it to Sentry.\n *\n * @param exception The exception to capture.\n * @param captureContext Define the level of the message or pass in additional data to attach to the message.\n * @returns the id of the captured message.\n */\nexport function captureMessage(\n message: string,\n // eslint-disable-next-line deprecation/deprecation\n captureContext?: CaptureContext | Severity | SeverityLevel,\n): string {\n // This is necessary to provide explicit scopes upgrade, without changing the original\n // arity of the `captureMessage(message, level)` method.\n const level = typeof captureContext === 'string' ? captureContext : undefined;\n const context = typeof captureContext !== 'string' ? { captureContext } : undefined;\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().captureMessage(message, level, context);\n}\n\n/**\n * Captures a manually created event and sends it to Sentry.\n *\n * @param exception The event to send to Sentry.\n * @param hint Optional additional data to attach to the Sentry event.\n * @returns the id of the captured event.\n */\nexport function captureEvent(event: Event, hint?: EventHint): string {\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().captureEvent(event, hint);\n}\n\n/**\n * Callback to set context information onto the scope.\n * @param callback Callback function that receives Scope.\n *\n * @deprecated Use getCurrentScope() directly.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function configureScope(callback: (scope: Scope) => void): ReturnType<Hub['configureScope']> {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().configureScope(callback);\n}\n\n/**\n * Records a new breadcrumb which will be attached to future events.\n *\n * Breadcrumbs will be added to subsequent events to provide more context on\n * user's actions prior to an error or crash.\n *\n * @param breadcrumb The breadcrumb to record.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function addBreadcrumb(breadcrumb: Breadcrumb, hint?: BreadcrumbHint): ReturnType<Hub['addBreadcrumb']> {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().addBreadcrumb(breadcrumb, hint);\n}\n\n/**\n * Sets context data with the given name.\n * @param name of the context\n * @param context Any kind of data. This data will be normalized.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any, deprecation/deprecation\nexport function setContext(name: string, context: { [key: string]: any } | null): ReturnType<Hub['setContext']> {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().setContext(name, context);\n}\n\n/**\n * Set an object that will be merged sent as extra data with the event.\n * @param extras Extras object to merge into current context.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function setExtras(extras: Extras): ReturnType<Hub['setExtras']> {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().setExtras(extras);\n}\n\n/**\n * Set key:value that will be sent as extra data with the event.\n * @param key String of extra\n * @param extra Any kind of data. This data will be normalized.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function setExtra(key: string, extra: Extra): ReturnType<Hub['setExtra']> {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().setExtra(key, extra);\n}\n\n/**\n * Set an object that will be merged sent as tags data with the event.\n * @param tags Tags context object to merge into current context.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function setTags(tags: { [key: string]: Primitive }): ReturnType<Hub['setTags']> {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().setTags(tags);\n}\n\n/**\n * Set key:value that will be sent as tags data with the event.\n *\n * Can also be used to unset a tag, by passing `undefined`.\n *\n * @param key String key of tag\n * @param value Value of tag\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function setTag(key: string, value: Primitive): ReturnType<Hub['setTag']> {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().setTag(key, value);\n}\n\n/**\n * Updates user context information for future events.\n *\n * @param user User context object to be set in the current context. Pass `null` to unset the user.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function setUser(user: User | null): ReturnType<Hub['setUser']> {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().setUser(user);\n}\n\n/**\n * Creates a new scope with and executes the given operation within.\n * The scope is automatically removed once the operation\n * finishes or throws.\n *\n * This is essentially a convenience function for:\n *\n * pushScope();\n * callback();\n * popScope();\n */\nexport function withScope<T>(callback: (scope: Scope) => T): T;\n/**\n * Set the given scope as the active scope in the callback.\n */\nexport function withScope<T>(scope: ScopeInterface | undefined, callback: (scope: Scope) => T): T;\n/**\n * Either creates a new active scope, or sets the given scope as active scope in the given callback.\n */\nexport function withScope<T>(\n ...rest: [callback: (scope: Scope) => T] | [scope: ScopeInterface | undefined, callback: (scope: Scope) => T]\n): T {\n // eslint-disable-next-line deprecation/deprecation\n const hub = getCurrentHub();\n\n // If a scope is defined, we want to make this the active scope instead of the default one\n if (rest.length === 2) {\n const [scope, callback] = rest;\n if (!scope) {\n // eslint-disable-next-line deprecation/deprecation\n return hub.withScope(callback);\n }\n\n // eslint-disable-next-line deprecation/deprecation\n return hub.withScope(() => {\n // eslint-disable-next-line deprecation/deprecation\n hub.getStackTop().scope = scope as Scope;\n return callback(scope as Scope);\n });\n }\n\n // eslint-disable-next-line deprecation/deprecation\n return hub.withScope(rest[0]);\n}\n\n/**\n * Attempts to fork the current isolation scope and the current scope based on the current async context strategy. If no\n * async context strategy is set, the isolation scope and the current scope will not be forked (this is currently the\n * case, for example, in the browser).\n *\n * Usage of this function in environments without async context strategy is discouraged and may lead to unexpected behaviour.\n *\n * This function is intended for Sentry SDK and SDK integration development. It is not recommended to be used in \"normal\"\n * applications directly because it comes with pitfalls. Use at your own risk!\n *\n * @param callback The callback in which the passed isolation scope is active. (Note: In environments without async\n * context strategy, the currently active isolation scope may change within execution of the callback.)\n * @returns The same value that `callback` returns.\n */\nexport function withIsolationScope<T>(callback: (isolationScope: Scope) => T): T {\n return runWithAsyncContext(() => {\n return callback(getIsolationScope());\n });\n}\n\n/**\n * Forks the current scope and sets the provided span as active span in the context of the provided callback.\n *\n * @param span Spans started in the context of the provided callback will be children of this span.\n * @param callback Execution context in which the provided span will be active. Is passed the newly forked scope.\n * @returns the value returned from the provided callback function.\n */\nexport function withActiveSpan<T>(span: Span, callback: (scope: Scope) => T): T {\n return withScope(scope => {\n // eslint-disable-next-line deprecation/deprecation\n scope.setSpan(span);\n return callback(scope);\n });\n}\n\n/**\n * Starts a new `Transaction` and returns it. This is the entry point to manual tracing instrumentation.\n *\n * A tree structure can be built by adding child spans to the transaction, and child spans to other spans. To start a\n * new child span within the transaction or any span, call the respective `.startChild()` method.\n *\n * Every child span must be finished before the transaction is finished, otherwise the unfinished spans are discarded.\n *\n * The transaction must be finished with a call to its `.end()` method, at which point the transaction with all its\n * finished child spans will be sent to Sentry.\n *\n * NOTE: This function should only be used for *manual* instrumentation. Auto-instrumentation should call\n * `startTransaction` directly on the hub.\n *\n * @param context Properties of the new `Transaction`.\n * @param customSamplingContext Information given to the transaction sampling function (along with context-dependent\n * default values). See {@link Options.tracesSampler}.\n *\n * @returns The transaction which was just started\n *\n * @deprecated Use `startSpan()`, `startSpanManual()` or `startInactiveSpan()` instead.\n */\nexport function startTransaction(\n context: TransactionContext,\n customSamplingContext?: CustomSamplingContext,\n // eslint-disable-next-line deprecation/deprecation\n): ReturnType<Hub['startTransaction']> {\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().startTransaction({ ...context }, customSamplingContext);\n}\n\n/**\n * Create a cron monitor check in and send it to Sentry.\n *\n * @param checkIn An object that describes a check in.\n * @param upsertMonitorConfig An optional object that describes a monitor config. Use this if you want\n * to create a monitor automatically when sending a check in.\n */\nexport function captureCheckIn(checkIn: CheckIn, upsertMonitorConfig?: MonitorConfig): string {\n const scope = getCurrentScope();\n const client = getClient();\n if (!client) {\n DEBUG_BUILD && logger.warn('Cannot capture check-in. No client defined.');\n } else if (!client.captureCheckIn) {\n DEBUG_BUILD && logger.warn('Cannot capture check-in. Client does not support sending check-ins.');\n } else {\n return client.captureCheckIn(checkIn, upsertMonitorConfig, scope);\n }\n\n return uuid4();\n}\n\n/**\n * Wraps a callback with a cron monitor check in. The check in will be sent to Sentry when the callback finishes.\n *\n * @param monitorSlug The distinct slug of the monitor.\n * @param upsertMonitorConfig An optional object that describes a monitor config. Use this if you want\n * to create a monitor automatically when sending a check in.\n */\nexport function withMonitor<T>(\n monitorSlug: CheckIn['monitorSlug'],\n callback: () => T,\n upsertMonitorConfig?: MonitorConfig,\n): T {\n const checkInId = captureCheckIn({ monitorSlug, status: 'in_progress' }, upsertMonitorConfig);\n const now = timestampInSeconds();\n\n function finishCheckIn(status: FinishedCheckIn['status']): void {\n captureCheckIn({ monitorSlug, status, checkInId, duration: timestampInSeconds() - now });\n }\n\n let maybePromiseResult: T;\n try {\n maybePromiseResult = callback();\n } catch (e) {\n finishCheckIn('error');\n throw e;\n }\n\n if (isThenable(maybePromiseResult)) {\n Promise.resolve(maybePromiseResult).then(\n () => {\n finishCheckIn('ok');\n },\n () => {\n finishCheckIn('error');\n },\n );\n } else {\n finishCheckIn('ok');\n }\n\n return maybePromiseResult;\n}\n\n/**\n * Call `flush()` on the current client, if there is one. See {@link Client.flush}.\n *\n * @param timeout Maximum time in ms the client should wait to flush its event queue. Omitting this parameter will cause\n * the client to wait until all events are sent before resolving the promise.\n * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it\n * doesn't (or if there's no client defined).\n */\nexport async function flush(timeout?: number): Promise<boolean> {\n const client = getClient();\n if (client) {\n return client.flush(timeout);\n }\n DEBUG_BUILD && logger.warn('Cannot flush events. No client defined.');\n return Promise.resolve(false);\n}\n\n/**\n * Call `close()` on the current client, if there is one. See {@link Client.close}.\n *\n * @param timeout Maximum time in ms the client should wait to flush its event queue before shutting down. Omitting this\n * parameter will cause the client to wait until all events are sent before disabling itself.\n * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it\n * doesn't (or if there's no client defined).\n */\nexport async function close(timeout?: number): Promise<boolean> {\n const client = getClient();\n if (client) {\n return client.close(timeout);\n }\n DEBUG_BUILD && logger.warn('Cannot flush events and disable SDK. No client defined.');\n return Promise.resolve(false);\n}\n\n/**\n * This is the getter for lastEventId.\n *\n * @returns The last event id of a captured event.\n */\nexport function lastEventId(): string | undefined {\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().lastEventId();\n}\n\n/**\n * Get the currently active client.\n */\nexport function getClient<C extends Client>(): C | undefined {\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().getClient<C>();\n}\n\n/**\n * Returns true if Sentry has been properly initialized.\n */\nexport function isInitialized(): boolean {\n return !!getClient();\n}\n\n/**\n * Get the currently active scope.\n */\nexport function getCurrentScope(): Scope {\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().getScope();\n}\n\n/**\n * Start a session on the current isolation scope.\n *\n * @param context (optional) additional properties to be applied to the returned session object\n *\n * @returns the new active session\n */\nexport function startSession(context?: SessionContext): Session {\n const client = getClient();\n const isolationScope = getIsolationScope();\n const currentScope = getCurrentScope();\n\n const { release, environment = DEFAULT_ENVIRONMENT } = (client && client.getOptions()) || {};\n\n // Will fetch userAgent if called from browser sdk\n const { userAgent } = GLOBAL_OBJ.navigator || {};\n\n const session = makeSession({\n release,\n environment,\n user: currentScope.getUser() || isolationScope.getUser(),\n ...(userAgent && { userAgent }),\n ...context,\n });\n\n // End existing session if there's one\n const currentSession = isolationScope.getSession();\n if (currentSession && currentSession.status === 'ok') {\n updateSession(currentSession, { status: 'exited' });\n }\n\n endSession();\n\n // Afterwards we set the new session on the scope\n isolationScope.setSession(session);\n\n // TODO (v8): Remove this and only use the isolation scope(?).\n // For v7 though, we can't \"soft-break\" people using getCurrentHub().getScope().setSession()\n currentScope.setSession(session);\n\n return session;\n}\n\n/**\n * End the session on the current isolation scope.\n */\nexport function endSession(): void {\n const isolationScope = getIsolationScope();\n const currentScope = getCurrentScope();\n\n const session = currentScope.getSession() || isolationScope.getSession();\n if (session) {\n closeSession(session);\n }\n _sendSessionUpdate();\n\n // the session is over; take it off of the scope\n isolationScope.setSession();\n\n // TODO (v8): Remove this and only use the isolation scope(?).\n // For v7 though, we can't \"soft-break\" people using getCurrentHub().getScope().setSession()\n currentScope.setSession();\n}\n\n/**\n * Sends the current Session on the scope\n */\nfunction _sendSessionUpdate(): void {\n const isolationScope = getIsolationScope();\n const currentScope = getCurrentScope();\n const client = getClient();\n // TODO (v8): Remove currentScope and only use the isolation scope(?).\n // For v7 though, we can't \"soft-break\" people using getCurrentHub().getScope().setSession()\n const session = currentScope.getSession() || isolationScope.getSession();\n if (session && client && client.captureSession) {\n client.captureSession(session);\n }\n}\n\n/**\n * Sends the current session on the scope to Sentry\n *\n * @param end If set the session will be marked as exited and removed from the scope.\n * Defaults to `false`.\n */\nexport function captureSession(end: boolean = false): void {\n // both send the update and pull the session from the scope\n if (end) {\n endSession();\n return;\n }\n\n // only send the update\n _sendSessionUpdate();\n}\n","import type { Transaction } from '@sentry/types';\nimport { extractTraceparentData as _extractTraceparentData } from '@sentry/utils';\n\nimport type { Hub } from '../hub';\nimport { getCurrentHub } from '../hub';\n\n/**\n * Grabs active transaction off scope.\n *\n * @deprecated You should not rely on the transaction, but just use `startSpan()` APIs instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function getActiveTransaction<T extends Transaction>(maybeHub?: Hub): T | undefined {\n // eslint-disable-next-line deprecation/deprecation\n const hub = maybeHub || getCurrentHub();\n // eslint-disable-next-line deprecation/deprecation\n const scope = hub.getScope();\n // eslint-disable-next-line deprecation/deprecation\n return scope.getTransaction() as T | undefined;\n}\n\n// so it can be used in manual instrumentation without necessitating a hard dependency on @sentry/utils\nexport { stripUrlQueryAndFragment } from '@sentry/utils';\n\n/**\n * The `extractTraceparentData` function and `TRACEPARENT_REGEXP` constant used\n * to be declared in this file. It was later moved into `@sentry/utils` as part of a\n * move to remove `@sentry/tracing` dependencies from `@sentry/node` (`extractTraceparentData`\n * is the only tracing function used by `@sentry/node`).\n *\n * These exports are kept here for backwards compatability's sake.\n *\n * See https://github.com/getsentry/sentry-javascript/issues/4642 for more details.\n *\n * @deprecated Import this function from `@sentry/utils` instead\n */\nexport const extractTraceparentData = _extractTraceparentData;\n","import type { Span } from '@sentry/types';\n\n/** The status of an Span.\n *\n * @deprecated Use string literals - if you require type casting, cast to SpanStatusType type\n */\nexport enum SpanStatus {\n /** The operation completed successfully. */\n Ok = 'ok',\n /** Deadline expired before operation could complete. */\n DeadlineExceeded = 'deadline_exceeded',\n /** 401 Unauthorized (actually does mean unauthenticated according to RFC 7235) */\n Unauthenticated = 'unauthenticated',\n /** 403 Forbidden */\n PermissionDenied = 'permission_denied',\n /** 404 Not Found. Some requested entity (file or directory) was not found. */\n NotFound = 'not_found',\n /** 429 Too Many Requests */\n ResourceExhausted = 'resource_exhausted',\n /** Client specified an invalid argument. 4xx. */\n InvalidArgument = 'invalid_argument',\n /** 501 Not Implemented */\n Unimplemented = 'unimplemented',\n /** 503 Service Unavailable */\n Unavailable = 'unavailable',\n /** Other/generic 5xx. */\n InternalError = 'internal_error',\n /** Unknown. Any non-standard HTTP status code. */\n UnknownError = 'unknown_error',\n /** The operation was cancelled (typically by the user). */\n Cancelled = 'cancelled',\n /** Already exists (409) */\n AlreadyExists = 'already_exists',\n /** Operation was rejected because the system is not in a state required for the operation's */\n FailedPrecondition = 'failed_precondition',\n /** The operation was aborted, typically due to a concurrency issue. */\n Aborted = 'aborted',\n /** Operation was attempted past the valid range. */\n OutOfRange = 'out_of_range',\n /** Unrecoverable data loss or corruption */\n DataLoss = 'data_loss',\n}\n\nexport type SpanStatusType =\n /** The operation completed successfully. */\n | 'ok'\n /** Deadline expired before operation could complete. */\n | 'deadline_exceeded'\n /** 401 Unauthorized (actually does mean unauthenticated according to RFC 7235) */\n | 'unauthenticated'\n /** 403 Forbidden */\n | 'permission_denied'\n /** 404 Not Found. Some requested entity (file or directory) was not found. */\n | 'not_found'\n /** 429 Too Many Requests */\n | 'resource_exhausted'\n /** Client specified an invalid argument. 4xx. */\n | 'invalid_argument'\n /** 501 Not Implemented */\n | 'unimplemented'\n /** 503 Service Unavailable */\n | 'unavailable'\n /** Other/generic 5xx. */\n | 'internal_error'\n /** Unknown. Any non-standard HTTP status code. */\n | 'unknown_error'\n /** The operation was cancelled (typically by the user). */\n | 'cancelled'\n /** Already exists (409) */\n | 'already_exists'\n /** Operation was rejected because the system is not in a state required for the operation's */\n | 'failed_precondition'\n /** The operation was aborted, typically due to a concurrency issue. */\n | 'aborted'\n /** Operation was attempted past the valid range. */\n | 'out_of_range'\n /** Unrecoverable data loss or corruption */\n | 'data_loss';\n\n/**\n * Converts a HTTP status code into a {@link SpanStatusType}.\n *\n * @param httpStatus The HTTP response status code.\n * @returns The span status or unknown_error.\n */\nexport function getSpanStatusFromHttpCode(httpStatus: number): SpanStatusType {\n if (httpStatus < 400 && httpStatus >= 100) {\n return 'ok';\n }\n\n if (httpStatus >= 400 && httpStatus < 500) {\n switch (httpStatus) {\n case 401:\n return 'unauthenticated';\n case 403:\n return 'permission_denied';\n case 404:\n return 'not_found';\n case 409:\n return 'already_exists';\n case 413:\n return 'failed_precondition';\n case 429:\n return 'resource_exhausted';\n default:\n return 'invalid_argument';\n }\n }\n\n if (httpStatus >= 500 && httpStatus < 600) {\n switch (httpStatus) {\n case 501:\n return 'unimplemented';\n case 503:\n return 'unavailable';\n case 504:\n return 'deadline_exceeded';\n default:\n return 'internal_error';\n }\n }\n\n return 'unknown_error';\n}\n\n/**\n * Converts a HTTP status code into a {@link SpanStatusType}.\n *\n * @deprecated Use {@link spanStatusFromHttpCode} instead.\n * This export will be removed in v8 as the signature contains a typo.\n *\n * @param httpStatus The HTTP response status code.\n * @returns The span status or unknown_error.\n */\nexport const spanStatusfromHttpCode = getSpanStatusFromHttpCode;\n\n/**\n * Sets the Http status attributes on the current span based on the http code.\n * Additionally, the span's status is updated, depending on the http code.\n */\nexport function setHttpStatus(span: Span, httpStatus: number): void {\n // TODO (v8): Remove these calls\n // Relay does not require us to send the status code as a tag\n // For now, just because users might expect it to land as a tag we keep sending it.\n // Same with data.\n // In v8, we replace both, simply with\n // span.setAttribute('http.response.status_code', httpStatus);\n\n // eslint-disable-next-line deprecation/deprecation\n span.setTag('http.status_code', String(httpStatus));\n // eslint-disable-next-line deprecation/deprecation\n span.setData('http.response.status_code', httpStatus);\n\n const spanStatus = getSpanStatusFromHttpCode(httpStatus);\n if (spanStatus !== 'unknown_error') {\n span.setStatus(spanStatus);\n }\n}\n","import {\n addGlobalErrorInstrumentationHandler,\n addGlobalUnhandledRejectionInstrumentationHandler,\n logger,\n} from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { SpanStatusType } from './spanstatus';\nimport { getActiveTransaction } from './utils';\n\nlet errorsInstrumented = false;\n\n/**\n * Configures global error listeners\n */\nexport function registerErrorInstrumentation(): void {\n if (errorsInstrumented) {\n return;\n }\n\n errorsInstrumented = true;\n addGlobalErrorInstrumentationHandler(errorCallback);\n addGlobalUnhandledRejectionInstrumentationHandler(errorCallback);\n}\n\n/**\n * If an error or unhandled promise occurs, we mark the active transaction as failed\n */\nfunction errorCallback(): void {\n // eslint-disable-next-line deprecation/deprecation\n const activeTransaction = getActiveTransaction();\n if (activeTransaction) {\n const status: SpanStatusType = 'internal_error';\n DEBUG_BUILD && logger.log(`[Tracing] Transaction: ${status} -> Global error occured`);\n activeTransaction.setStatus(status);\n }\n}\n\n// The function name will be lost when bundling but we need to be able to identify this listener later to maintain the\n// node.js default exit behaviour\nerrorCallback.tag = 'sentry_tracingErrorCallback';\n","import { isThenable } from '@sentry/utils';\n\n/**\n * Wrap a callback function with error handling.\n * If an error is thrown, it will be passed to the `onError` callback and re-thrown.\n *\n * If the return value of the function is a promise, it will be handled with `maybeHandlePromiseRejection`.\n *\n * If an `onFinally` callback is provided, this will be called when the callback has finished\n * - so if it returns a promise, once the promise resolved/rejected,\n * else once the callback has finished executing.\n * The `onFinally` callback will _always_ be called, no matter if an error was thrown or not.\n */\nexport function handleCallbackErrors<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n Fn extends () => any,\n>(\n fn: Fn,\n onError: (error: unknown) => void,\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n onFinally: () => void = () => {},\n): ReturnType<Fn> {\n let maybePromiseResult: ReturnType<Fn>;\n try {\n maybePromiseResult = fn();\n } catch (e) {\n onError(e);\n onFinally();\n throw e;\n }\n\n return maybeHandlePromiseRejection(maybePromiseResult, onError, onFinally);\n}\n\n/**\n * Maybe handle a promise rejection.\n * This expects to be given a value that _may_ be a promise, or any other value.\n * If it is a promise, and it rejects, it will call the `onError` callback.\n * Other than this, it will generally return the given value as-is.\n */\nfunction maybeHandlePromiseRejection<MaybePromise>(\n value: MaybePromise,\n onError: (error: unknown) => void,\n onFinally: () => void,\n): MaybePromise {\n if (isThenable(value)) {\n // @ts-expect-error - the isThenable check returns the \"wrong\" type here\n return value.then(\n res => {\n onFinally();\n return res;\n },\n e => {\n onError(e);\n onFinally();\n throw e;\n },\n );\n }\n\n onFinally();\n return value;\n}\n","import type { Options } from '@sentry/types';\n\nimport { getClient } from '../exports';\n\n// Treeshakable guard to remove all code related to tracing\ndeclare const __SENTRY_TRACING__: boolean | undefined;\n\n/**\n * Determines if tracing is currently enabled.\n *\n * Tracing is enabled when at least one of `tracesSampleRate` and `tracesSampler` is defined in the SDK config.\n */\nexport function hasTracingEnabled(\n maybeOptions?: Pick<Options, 'tracesSampleRate' | 'tracesSampler' | 'enableTracing'> | undefined,\n): boolean {\n if (typeof __SENTRY_TRACING__ === 'boolean' && !__SENTRY_TRACING__) {\n return false;\n }\n\n const client = getClient();\n const options = maybeOptions || (client && client.getOptions());\n return !!options && (options.enableTracing || 'tracesSampleRate' in options || 'tracesSampler' in options);\n}\n","import type { Scope, Span, SpanTimeInput, StartSpanOptions, TransactionContext } from '@sentry/types';\n\nimport { addNonEnumerableProperty, dropUndefinedKeys, logger, tracingContextFromHeaders } from '@sentry/utils';\nimport { getDynamicSamplingContextFromSpan } from '.';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport { getCurrentScope, withScope } from '../exports';\nimport type { Hub } from '../hub';\nimport { runWithAsyncContext } from '../hub';\nimport { getIsolationScope } from '../hub';\nimport { getCurrentHub } from '../hub';\nimport type { Scope as ScopeClass } from '../scope';\nimport { handleCallbackErrors } from '../utils/handleCallbackErrors';\nimport { hasTracingEnabled } from '../utils/hasTracingEnabled';\nimport { spanIsSampled, spanTimeInputToSeconds, spanToJSON } from '../utils/spanUtils';\n\n/**\n * Wraps a function with a transaction/span and finishes the span after the function is done.\n *\n * Note that if you have not enabled tracing extensions via `addTracingExtensions`\n * or you didn't set `tracesSampleRate`, this function will not generate spans\n * and the `span` returned from the callback will be undefined.\n *\n * This function is meant to be used internally and may break at any time. Use at your own risk.\n *\n * @internal\n * @private\n *\n * @deprecated Use `startSpan` instead.\n */\nexport function trace<T>(\n context: TransactionContext,\n callback: (span?: Span) => T,\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n onError: (error: unknown, span?: Span) => void = () => {},\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n afterFinish: () => void = () => {},\n): T {\n // eslint-disable-next-line deprecation/deprecation\n const hub = getCurrentHub();\n const scope = getCurrentScope();\n // eslint-disable-next-line deprecation/deprecation\n const parentSpan = scope.getSpan();\n\n const spanContext = normalizeContext(context);\n const activeSpan = createChildSpanOrTransaction(hub, {\n parentSpan,\n spanContext,\n forceTransaction: false,\n scope,\n });\n\n // eslint-disable-next-line deprecation/deprecation\n scope.setSpan(activeSpan);\n\n return handleCallbackErrors(\n () => callback(activeSpan),\n error => {\n activeSpan && activeSpan.setStatus('internal_error');\n onError(error, activeSpan);\n },\n () => {\n activeSpan && activeSpan.end();\n // eslint-disable-next-line deprecation/deprecation\n scope.setSpan(parentSpan);\n afterFinish();\n },\n );\n}\n\n/**\n * Wraps a function with a transaction/span and finishes the span after the function is done.\n * The created span is the active span and will be used as parent by other spans created inside the function\n * and can be accessed via `Sentry.getSpan()`, as long as the function is executed while the scope is active.\n *\n * If you want to create a span that is not set as active, use {@link startInactiveSpan}.\n *\n * Note that if you have not enabled tracing extensions via `addTracingExtensions`\n * or you didn't set `tracesSampleRate`, this function will not generate spans\n * and the `span` returned from the callback will be undefined.\n */\nexport function startSpan<T>(context: StartSpanOptions, callback: (span: Span | undefined) => T): T {\n const spanContext = normalizeContext(context);\n\n return runWithAsyncContext(() => {\n return withScope(context.scope, scope => {\n // eslint-disable-next-line deprecation/deprecation\n const hub = getCurrentHub();\n // eslint-disable-next-line deprecation/deprecation\n const parentSpan = scope.getSpan();\n\n const shouldSkipSpan = context.onlyIfParent && !parentSpan;\n const activeSpan = shouldSkipSpan\n ? undefined\n : createChildSpanOrTransaction(hub, {\n parentSpan,\n spanContext,\n forceTransaction: context.forceTransaction,\n scope,\n });\n\n return handleCallbackErrors(\n () => callback(activeSpan),\n () => {\n // Only update the span status if it hasn't been changed yet\n if (activeSpan) {\n const { status } = spanToJSON(activeSpan);\n if (!status || status === 'ok') {\n activeSpan.setStatus('internal_error');\n }\n }\n },\n () => activeSpan && activeSpan.end(),\n );\n });\n });\n}\n\n/**\n * @deprecated Use {@link startSpan} instead.\n */\nexport const startActiveSpan = startSpan;\n\n/**\n * Similar to `Sentry.startSpan`. Wraps a function with a transaction/span, but does not finish the span\n * after the function is done automatically. You'll have to call `span.end()` manually.\n *\n * The created span is the active span and will be used as parent by other spans created inside the function\n * and can be accessed via `Sentry.getActiveSpan()`, as long as the function is executed while the scope is active.\n *\n * Note that if you have not enabled tracing extensions via `addTracingExtensions`\n * or you didn't set `tracesSampleRate`, this function will not generate spans\n * and the `span` returned from the callback will be undefined.\n */\nexport function startSpanManual<T>(\n context: StartSpanOptions,\n callback: (span: Span | undefined, finish: () => void) => T,\n): T {\n const spanContext = normalizeContext(context);\n\n return runWithAsyncContext(() => {\n return withScope(context.scope, scope => {\n // eslint-disable-next-line deprecation/deprecation\n const hub = getCurrentHub();\n // eslint-disable-next-line deprecation/deprecation\n const parentSpan = scope.getSpan();\n\n const shouldSkipSpan = context.onlyIfParent && !parentSpan;\n const activeSpan = shouldSkipSpan\n ? undefined\n : createChildSpanOrTransaction(hub, {\n parentSpan,\n spanContext,\n forceTransaction: context.forceTransaction,\n scope,\n });\n\n function finishAndSetSpan(): void {\n activeSpan && activeSpan.end();\n }\n\n return handleCallbackErrors(\n () => callback(activeSpan, finishAndSetSpan),\n () => {\n // Only update the span status if it hasn't been changed yet, and the span is not yet finished\n if (activeSpan && activeSpan.isRecording()) {\n const { status } = spanToJSON(activeSpan);\n if (!status || status === 'ok') {\n activeSpan.setStatus('internal_error');\n }\n }\n },\n );\n });\n });\n}\n\n/**\n * Creates a span. This span is not set as active, so will not get automatic instrumentation spans\n * as children or be able to be accessed via `Sentry.getSpan()`.\n *\n * If you want to create a span that is set as active, use {@link startSpan}.\n *\n * Note that if you have not enabled tracing extensions via `addTracingExtensions`\n * or you didn't set `tracesSampleRate` or `tracesSampler`, this function will not generate spans\n * and the `span` returned from the callback will be undefined.\n */\nexport function startInactiveSpan(context: StartSpanOptions): Span | undefined {\n if (!hasTracingEnabled()) {\n return undefined;\n }\n\n const spanContext = normalizeContext(context);\n // eslint-disable-next-line deprecation/deprecation\n const hub = getCurrentHub();\n const parentSpan = context.scope\n ? // eslint-disable-next-line deprecation/deprecation\n context.scope.getSpan()\n : getActiveSpan();\n\n const shouldSkipSpan = context.onlyIfParent && !parentSpan;\n\n if (shouldSkipSpan) {\n return undefined;\n }\n\n const scope = context.scope || getCurrentScope();\n\n // Even though we don't actually want to make this span active on the current scope,\n // we need to make it active on a temporary scope that we use for event processing\n // as otherwise, it won't pick the correct span for the event when processing it\n const temporaryScope = (scope as ScopeClass).clone();\n\n return createChildSpanOrTransaction(hub, {\n parentSpan,\n spanContext,\n forceTransaction: context.forceTransaction,\n scope: temporaryScope,\n });\n}\n\n/**\n * Returns the currently active span.\n */\nexport function getActiveSpan(): Span | undefined {\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentScope().getSpan();\n}\n\ninterface ContinueTrace {\n /**\n * Continue a trace from `sentry-trace` and `baggage` values.\n * These values can be obtained from incoming request headers,\n * or in the browser from `<meta name=\"sentry-trace\">` and `<meta name=\"baggage\">` HTML tags.\n *\n * @deprecated Use the version of this function taking a callback as second parameter instead:\n *\n * ```\n * Sentry.continueTrace(sentryTrace: '...', baggage: '...' }, () => {\n * // ...\n * })\n * ```\n *\n */\n ({\n sentryTrace,\n baggage,\n }: {\n // eslint-disable-next-line deprecation/deprecation\n sentryTrace: Parameters<typeof tracingContextFromHeaders>[0];\n // eslint-disable-next-line deprecation/deprecation\n baggage: Parameters<typeof tracingContextFromHeaders>[1];\n }): Partial<TransactionContext>;\n\n /**\n * Continue a trace from `sentry-trace` and `baggage` values.\n * These values can be obtained from incoming request headers, or in the browser from `<meta name=\"sentry-trace\">`\n * and `<meta name=\"baggage\">` HTML tags.\n *\n * Spans started with `startSpan`, `startSpanManual` and `startInactiveSpan`, within the callback will automatically\n * be attached to the incoming trace.\n *\n * Deprecation notice: In the next major version of the SDK the provided callback will not receive a transaction\n * context argument.\n */\n <V>(\n {\n sentryTrace,\n baggage,\n }: {\n // eslint-disable-next-line deprecation/deprecation\n sentryTrace: Parameters<typeof tracingContextFromHeaders>[0];\n // eslint-disable-next-line deprecation/deprecation\n baggage: Parameters<typeof tracingContextFromHeaders>[1];\n },\n // TODO(v8): Remove parameter from this callback.\n callback: (transactionContext: Partial<TransactionContext>) => V,\n ): V;\n}\n\nexport const continueTrace: ContinueTrace = <V>(\n {\n sentryTrace,\n baggage,\n }: {\n // eslint-disable-next-line deprecation/deprecation\n sentryTrace: Parameters<typeof tracingContextFromHeaders>[0];\n // eslint-disable-next-line deprecation/deprecation\n baggage: Parameters<typeof tracingContextFromHeaders>[1];\n },\n callback?: (transactionContext: Partial<TransactionContext>) => V,\n): V | Partial<TransactionContext> => {\n // TODO(v8): Change this function so it doesn't do anything besides setting the propagation context on the current scope:\n /*\n return withScope((scope) => {\n const propagationContext = propagationContextFromHeaders(sentryTrace, baggage);\n scope.setPropagationContext(propagationContext);\n return callback();\n })\n */\n\n const currentScope = getCurrentScope();\n\n // eslint-disable-next-line deprecation/deprecation\n const { traceparentData, dynamicSamplingContext, propagationContext } = tracingContextFromHeaders(\n sentryTrace,\n baggage,\n );\n\n currentScope.setPropagationContext(propagationContext);\n\n if (DEBUG_BUILD && traceparentData) {\n logger.log(`[Tracing] Continuing trace ${traceparentData.traceId}.`);\n }\n\n const transactionContext: Partial<TransactionContext> = {\n ...traceparentData,\n metadata: dropUndefinedKeys({\n dynamicSamplingContext,\n }),\n };\n\n if (!callback) {\n return transactionContext;\n }\n\n return runWithAsyncContext(() => {\n return callback(transactionContext);\n });\n};\n\nfunction createChildSpanOrTransaction(\n // eslint-disable-next-line deprecation/deprecation\n hub: Hub,\n {\n parentSpan,\n spanContext,\n forceTransaction,\n scope,\n }: {\n parentSpan: Span | undefined;\n spanContext: TransactionContext;\n forceTransaction?: boolean;\n scope: Scope;\n },\n): Span | undefined {\n if (!hasTracingEnabled()) {\n return undefined;\n }\n\n const isolationScope = getIsolationScope();\n\n let span: Span | undefined;\n if (parentSpan && !forceTransaction) {\n // eslint-disable-next-line deprecation/deprecation\n span = parentSpan.startChild(spanContext);\n } else if (parentSpan) {\n // If we forced a transaction but have a parent span, make sure to continue from the parent span, not the scope\n const dsc = getDynamicSamplingContextFromSpan(parentSpan);\n const { traceId, spanId: parentSpanId } = parentSpan.spanContext();\n const sampled = spanIsSampled(parentSpan);\n\n // eslint-disable-next-line deprecation/deprecation\n span = hub.startTransaction({\n traceId,\n parentSpanId,\n parentSampled: sampled,\n ...spanContext,\n metadata: {\n dynamicSamplingContext: dsc,\n // eslint-disable-next-line deprecation/deprecation\n ...spanContext.metadata,\n },\n });\n } else {\n const { traceId, dsc, parentSpanId, sampled } = {\n ...isolationScope.getPropagationContext(),\n ...scope.getPropagationContext(),\n };\n\n // eslint-disable-next-line deprecation/deprecation\n span = hub.startTransaction({\n traceId,\n parentSpanId,\n parentSampled: sampled,\n ...spanContext,\n metadata: {\n dynamicSamplingContext: dsc,\n // eslint-disable-next-line deprecation/deprecation\n ...spanContext.metadata,\n },\n });\n }\n\n // We always set this as active span on the scope\n // In the case of this being an inactive span, we ensure to pass a detached scope in here in the first place\n // But by having this here, we can ensure that the lookup through `getCapturedScopesOnSpan` results in the correct scope & span combo\n // eslint-disable-next-line deprecation/deprecation\n scope.setSpan(span);\n\n setCapturedScopesOnSpan(span, scope, isolationScope);\n\n return span;\n}\n\n/**\n * This converts StartSpanOptions to TransactionContext.\n * For the most part (for now) we accept the same options,\n * but some of them need to be transformed.\n *\n * Eventually the StartSpanOptions will be more aligned with OpenTelemetry.\n */\nfunction normalizeContext(context: StartSpanOptions): TransactionContext {\n if (context.startTime) {\n const ctx: TransactionContext & { startTime?: SpanTimeInput } = { ...context };\n ctx.startTimestamp = spanTimeInputToSeconds(context.startTime);\n delete ctx.startTime;\n return ctx;\n }\n\n return context;\n}\n\nconst SCOPE_ON_START_SPAN_FIELD = '_sentryScope';\nconst ISOLATION_SCOPE_ON_START_SPAN_FIELD = '_sentryIsolationScope';\n\ntype SpanWithScopes = Span & {\n [SCOPE_ON_START_SPAN_FIELD]?: Scope;\n [ISOLATION_SCOPE_ON_START_SPAN_FIELD]?: Scope;\n};\n\nfunction setCapturedScopesOnSpan(span: Span | undefined, scope: Scope, isolationScope: Scope): void {\n if (span) {\n addNonEnumerableProperty(span, ISOLATION_SCOPE_ON_START_SPAN_FIELD, isolationScope);\n addNonEnumerableProperty(span, SCOPE_ON_START_SPAN_FIELD, scope);\n }\n}\n\n/**\n * Grabs the scope and isolation scope off a span that were active when the span was started.\n */\nexport function getCapturedScopesOnSpan(span: Span): { scope?: Scope; isolationScope?: Scope } {\n return {\n scope: (span as SpanWithScopes)[SCOPE_ON_START_SPAN_FIELD],\n isolationScope: (span as SpanWithScopes)[ISOLATION_SCOPE_ON_START_SPAN_FIELD],\n };\n}\n","/**\n * Use this attribute to represent the source of a span.\n * Should be one of: custom, url, route, view, component, task, unknown\n *\n */\nexport const SEMANTIC_ATTRIBUTE_SENTRY_SOURCE = 'sentry.source';\n\n/**\n * Use this attribute to represent the sample rate used for a span.\n */\nexport const SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE = 'sentry.sample_rate';\n\n/**\n * Use this attribute to represent the operation of a span.\n */\nexport const SEMANTIC_ATTRIBUTE_SENTRY_OP = 'sentry.op';\n\n/**\n * Use this attribute to represent the origin of a span.\n */\nexport const SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN = 'sentry.origin';\n\n/**\n * The id of the profile that this span occured in.\n */\nexport const SEMANTIC_ATTRIBUTE_PROFILE_ID = 'profile_id';\n","import type { MeasurementUnit, Span } from '@sentry/types';\nimport type { MetricSummary } from '@sentry/types';\nimport type { Primitive } from '@sentry/types';\nimport { dropUndefinedKeys } from '@sentry/utils';\nimport { getActiveSpan } from '../tracing';\nimport type { MetricType } from './types';\n\n/**\n * key: bucketKey\n * value: [exportKey, MetricSummary]\n */\ntype MetricSummaryStorage = Map<string, [string, MetricSummary]>;\n\nlet SPAN_METRIC_SUMMARY: WeakMap<Span, MetricSummaryStorage> | undefined;\n\nfunction getMetricStorageForSpan(span: Span): MetricSummaryStorage | undefined {\n return SPAN_METRIC_SUMMARY ? SPAN_METRIC_SUMMARY.get(span) : undefined;\n}\n\n/**\n * Fetches the metric summary if it exists for the passed span\n */\nexport function getMetricSummaryJsonForSpan(span: Span): Record<string, Array<MetricSummary>> | undefined {\n const storage = getMetricStorageForSpan(span);\n\n if (!storage) {\n return undefined;\n }\n const output: Record<string, Array<MetricSummary>> = {};\n\n for (const [, [exportKey, summary]] of storage) {\n if (!output[exportKey]) {\n output[exportKey] = [];\n }\n\n output[exportKey].push(dropUndefinedKeys(summary));\n }\n\n return output;\n}\n\n/**\n * Updates the metric summary on the currently active span\n */\nexport function updateMetricSummaryOnActiveSpan(\n metricType: MetricType,\n sanitizedName: string,\n value: number,\n unit: MeasurementUnit,\n tags: Record<string, Primitive>,\n bucketKey: string,\n): void {\n const span = getActiveSpan();\n if (span) {\n const storage = getMetricStorageForSpan(span) || new Map<string, [string, MetricSummary]>();\n\n const exportKey = `${metricType}:${sanitizedName}@${unit}`;\n const bucketItem = storage.get(bucketKey);\n\n if (bucketItem) {\n const [, summary] = bucketItem;\n storage.set(bucketKey, [\n exportKey,\n {\n min: Math.min(summary.min, value),\n max: Math.max(summary.max, value),\n count: (summary.count += 1),\n sum: (summary.sum += value),\n tags: summary.tags,\n },\n ]);\n } else {\n storage.set(bucketKey, [\n exportKey,\n {\n min: value,\n max: value,\n count: 1,\n sum: value,\n tags,\n },\n ]);\n }\n\n if (!SPAN_METRIC_SUMMARY) {\n SPAN_METRIC_SUMMARY = new WeakMap();\n }\n\n SPAN_METRIC_SUMMARY.set(span, storage);\n }\n}\n","/* eslint-disable max-lines */\nimport type {\n Instrumenter,\n Measurements,\n Primitive,\n Span as SpanInterface,\n SpanAttributeValue,\n SpanAttributes,\n SpanContext,\n SpanContextData,\n SpanJSON,\n SpanOrigin,\n SpanTimeInput,\n TraceContext,\n Transaction,\n} from '@sentry/types';\nimport { dropUndefinedKeys, logger, timestampInSeconds, uuid4 } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport { getMetricSummaryJsonForSpan } from '../metrics/metric-summary';\nimport {\n SEMANTIC_ATTRIBUTE_PROFILE_ID,\n SEMANTIC_ATTRIBUTE_SENTRY_OP,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n} from '../semanticAttributes';\nimport { getRootSpan } from '../utils/getRootSpan';\nimport {\n TRACE_FLAG_NONE,\n TRACE_FLAG_SAMPLED,\n spanTimeInputToSeconds,\n spanToJSON,\n spanToTraceContext,\n spanToTraceHeader,\n} from '../utils/spanUtils';\nimport type { SpanStatusType } from './spanstatus';\nimport { setHttpStatus } from './spanstatus';\n\n/**\n * Keeps track of finished spans for a given transaction\n * @internal\n * @hideconstructor\n * @hidden\n */\nexport class SpanRecorder {\n public spans: Span[];\n\n private readonly _maxlen: number;\n\n public constructor(maxlen: number = 1000) {\n this._maxlen = maxlen;\n this.spans = [];\n }\n\n /**\n * This is just so that we don't run out of memory while recording a lot\n * of spans. At some point we just stop and flush out the start of the\n * trace tree (i.e.the first n spans with the smallest\n * start_timestamp).\n */\n public add(span: Span): void {\n if (this.spans.length > this._maxlen) {\n // eslint-disable-next-line deprecation/deprecation\n span.spanRecorder = undefined;\n } else {\n this.spans.push(span);\n }\n }\n}\n\n/**\n * Span contains all data about a span\n */\nexport class Span implements SpanInterface {\n /**\n * Tags for the span.\n * @deprecated Use `spanToJSON(span).atttributes` instead.\n */\n public tags: { [key: string]: Primitive };\n\n /**\n * Data for the span.\n * @deprecated Use `spanToJSON(span).atttributes` instead.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n public data: { [key: string]: any };\n\n /**\n * List of spans that were finalized\n *\n * @deprecated This property will no longer be public. Span recording will be handled internally.\n */\n public spanRecorder?: SpanRecorder;\n\n /**\n * @inheritDoc\n * @deprecated Use top level `Sentry.getRootSpan()` instead\n */\n public transaction?: Transaction;\n\n /**\n * The instrumenter that created this span.\n *\n * TODO (v8): This can probably be replaced by an `instanceOf` check of the span class.\n * the instrumenter can only be sentry or otel so we can check the span instance\n * to verify which one it is and remove this field entirely.\n *\n * @deprecated This field will be removed.\n */\n public instrumenter: Instrumenter;\n\n protected _traceId: string;\n protected _spanId: string;\n protected _parentSpanId?: string | undefined;\n protected _sampled: boolean | undefined;\n protected _name?: string | undefined;\n protected _attributes: SpanAttributes;\n /** Epoch timestamp in seconds when the span started. */\n protected _startTime: number;\n /** Epoch timestamp in seconds when the span ended. */\n protected _endTime?: number | undefined;\n /** Internal keeper of the status */\n protected _status?: SpanStatusType | string | undefined;\n protected _exclusiveTime?: number;\n\n protected _measurements: Measurements;\n\n private _logMessage?: string;\n\n /**\n * You should never call the constructor manually, always use `Sentry.startTransaction()`\n * or call `startChild()` on an existing span.\n * @internal\n * @hideconstructor\n * @hidden\n */\n public constructor(spanContext: SpanContext = {}) {\n this._traceId = spanContext.traceId || uuid4();\n this._spanId = spanContext.spanId || uuid4().substring(16);\n this._startTime = spanContext.startTimestamp || timestampInSeconds();\n // eslint-disable-next-line deprecation/deprecation\n this.tags = spanContext.tags ? { ...spanContext.tags } : {};\n // eslint-disable-next-line deprecation/deprecation\n this.data = spanContext.data ? { ...spanContext.data } : {};\n // eslint-disable-next-line deprecation/deprecation\n this.instrumenter = spanContext.instrumenter || 'sentry';\n\n this._attributes = {};\n this.setAttributes({\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: spanContext.origin || 'manual',\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: spanContext.op,\n ...spanContext.attributes,\n });\n\n // eslint-disable-next-line deprecation/deprecation\n this._name = spanContext.name || spanContext.description;\n\n if (spanContext.parentSpanId) {\n this._parentSpanId = spanContext.parentSpanId;\n }\n // We want to include booleans as well here\n if ('sampled' in spanContext) {\n this._sampled = spanContext.sampled;\n }\n if (spanContext.status) {\n this._status = spanContext.status;\n }\n if (spanContext.endTimestamp) {\n this._endTime = spanContext.endTimestamp;\n }\n if (spanContext.exclusiveTime !== undefined) {\n this._exclusiveTime = spanContext.exclusiveTime;\n }\n this._measurements = spanContext.measurements ? { ...spanContext.measurements } : {};\n }\n\n // This rule conflicts with another eslint rule :(\n /* eslint-disable @typescript-eslint/member-ordering */\n\n /**\n * An alias for `description` of the Span.\n * @deprecated Use `spanToJSON(span).description` instead.\n */\n public get name(): string {\n return this._name || '';\n }\n\n /**\n * Update the name of the span.\n * @deprecated Use `spanToJSON(span).description` instead.\n */\n public set name(name: string) {\n this.updateName(name);\n }\n\n /**\n * Get the description of the Span.\n * @deprecated Use `spanToJSON(span).description` instead.\n */\n public get description(): string | undefined {\n return this._name;\n }\n\n /**\n * Get the description of the Span.\n * @deprecated Use `spanToJSON(span).description` instead.\n */\n public set description(description: string | undefined) {\n this._name = description;\n }\n\n /**\n * The ID of the trace.\n * @deprecated Use `spanContext().traceId` instead.\n */\n public get traceId(): string {\n return this._traceId;\n }\n\n /**\n * The ID of the trace.\n * @deprecated You cannot update the traceId of a span after span creation.\n */\n public set traceId(traceId: string) {\n this._traceId = traceId;\n }\n\n /**\n * The ID of the span.\n * @deprecated Use `spanContext().spanId` instead.\n */\n public get spanId(): string {\n return this._spanId;\n }\n\n /**\n * The ID of the span.\n * @deprecated You cannot update the spanId of a span after span creation.\n */\n public set spanId(spanId: string) {\n this._spanId = spanId;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `startSpan` functions instead.\n */\n public set parentSpanId(string) {\n this._parentSpanId = string;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `spanToJSON(span).parent_span_id` instead.\n */\n public get parentSpanId(): string | undefined {\n return this._parentSpanId;\n }\n\n /**\n * Was this span chosen to be sent as part of the sample?\n * @deprecated Use `isRecording()` instead.\n */\n public get sampled(): boolean | undefined {\n return this._sampled;\n }\n\n /**\n * Was this span chosen to be sent as part of the sample?\n * @deprecated You cannot update the sampling decision of a span after span creation.\n */\n public set sampled(sampled: boolean | undefined) {\n this._sampled = sampled;\n }\n\n /**\n * Attributes for the span.\n * @deprecated Use `spanToJSON(span).atttributes` instead.\n */\n public get attributes(): SpanAttributes {\n return this._attributes;\n }\n\n /**\n * Attributes for the span.\n * @deprecated Use `setAttributes()` instead.\n */\n public set attributes(attributes: SpanAttributes) {\n this._attributes = attributes;\n }\n\n /**\n * Timestamp in seconds (epoch time) indicating when the span started.\n * @deprecated Use `spanToJSON()` instead.\n */\n public get startTimestamp(): number {\n return this._startTime;\n }\n\n /**\n * Timestamp in seconds (epoch time) indicating when the span started.\n * @deprecated In v8, you will not be able to update the span start time after creation.\n */\n public set startTimestamp(startTime: number) {\n this._startTime = startTime;\n }\n\n /**\n * Timestamp in seconds when the span ended.\n * @deprecated Use `spanToJSON()` instead.\n */\n public get endTimestamp(): number | undefined {\n return this._endTime;\n }\n\n /**\n * Timestamp in seconds when the span ended.\n * @deprecated Set the end time via `span.end()` instead.\n */\n public set endTimestamp(endTime: number | undefined) {\n this._endTime = endTime;\n }\n\n /**\n * The status of the span.\n *\n * @deprecated Use `spanToJSON().status` instead to get the status.\n */\n public get status(): SpanStatusType | string | undefined {\n return this._status;\n }\n\n /**\n * The status of the span.\n *\n * @deprecated Use `.setStatus()` instead to set or update the status.\n */\n public set status(status: SpanStatusType | string | undefined) {\n this._status = status;\n }\n\n /**\n * Operation of the span\n *\n * @deprecated Use `spanToJSON().op` to read the op instead.\n */\n public get op(): string | undefined {\n return this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP] as string | undefined;\n }\n\n /**\n * Operation of the span\n *\n * @deprecated Use `startSpan()` functions to set or `span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_OP, 'op')\n * to update the span instead.\n */\n public set op(op: string | undefined) {\n this.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_OP, op);\n }\n\n /**\n * The origin of the span, giving context about what created the span.\n *\n * @deprecated Use `spanToJSON().origin` to read the origin instead.\n */\n public get origin(): SpanOrigin | undefined {\n return this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN] as SpanOrigin | undefined;\n }\n\n /**\n * The origin of the span, giving context about what created the span.\n *\n * @deprecated Use `startSpan()` functions to set the origin instead.\n */\n public set origin(origin: SpanOrigin | undefined) {\n this.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, origin);\n }\n\n /* eslint-enable @typescript-eslint/member-ordering */\n\n /** @inheritdoc */\n public spanContext(): SpanContextData {\n const { _spanId: spanId, _traceId: traceId, _sampled: sampled } = this;\n return {\n spanId,\n traceId,\n traceFlags: sampled ? TRACE_FLAG_SAMPLED : TRACE_FLAG_NONE,\n };\n }\n\n /**\n * Creates a new `Span` while setting the current `Span.id` as `parentSpanId`.\n * Also the `sampled` decision will be inherited.\n *\n * @deprecated Use `startSpan()`, `startSpanManual()` or `startInactiveSpan()` instead.\n */\n public startChild(\n spanContext?: Pick<SpanContext, Exclude<keyof SpanContext, 'sampled' | 'traceId' | 'parentSpanId'>>,\n ): SpanInterface {\n const childSpan = new Span({\n ...spanContext,\n parentSpanId: this._spanId,\n sampled: this._sampled,\n traceId: this._traceId,\n });\n\n // eslint-disable-next-line deprecation/deprecation\n childSpan.spanRecorder = this.spanRecorder;\n // eslint-disable-next-line deprecation/deprecation\n if (childSpan.spanRecorder) {\n // eslint-disable-next-line deprecation/deprecation\n childSpan.spanRecorder.add(childSpan);\n }\n\n const rootSpan = getRootSpan(this);\n // TODO: still set span.transaction here until we have a more permanent solution\n // Probably similarly to the weakmap we hold in node-experimental\n // eslint-disable-next-line deprecation/deprecation\n childSpan.transaction = rootSpan as Transaction;\n\n if (DEBUG_BUILD && rootSpan) {\n const opStr = (spanContext && spanContext.op) || '< unknown op >';\n const nameStr = spanToJSON(childSpan).description || '< unknown name >';\n const idStr = rootSpan.spanContext().spanId;\n\n const logMessage = `[Tracing] Starting '${opStr}' span on transaction '${nameStr}' (${idStr}).`;\n logger.log(logMessage);\n this._logMessage = logMessage;\n }\n\n return childSpan;\n }\n\n /**\n * Sets the tag attribute on the current span.\n *\n * Can also be used to unset a tag, by passing `undefined`.\n *\n * @param key Tag key\n * @param value Tag value\n * @deprecated Use `setAttribute()` instead.\n */\n public setTag(key: string, value: Primitive): this {\n // eslint-disable-next-line deprecation/deprecation\n this.tags = { ...this.tags, [key]: value };\n return this;\n }\n\n /**\n * Sets the data attribute on the current span\n * @param key Data key\n * @param value Data value\n * @deprecated Use `setAttribute()` instead.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n public setData(key: string, value: any): this {\n // eslint-disable-next-line deprecation/deprecation\n this.data = { ...this.data, [key]: value };\n return this;\n }\n\n /** @inheritdoc */\n public setAttribute(key: string, value: SpanAttributeValue | undefined): void {\n if (value === undefined) {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete this._attributes[key];\n } else {\n this._attributes[key] = value;\n }\n }\n\n /** @inheritdoc */\n public setAttributes(attributes: SpanAttributes): void {\n Object.keys(attributes).forEach(key => this.setAttribute(key, attributes[key]));\n }\n\n /**\n * @inheritDoc\n */\n public setStatus(value: SpanStatusType): this {\n this._status = value;\n return this;\n }\n\n /**\n * @inheritDoc\n * @deprecated Use top-level `setHttpStatus()` instead.\n */\n public setHttpStatus(httpStatus: number): this {\n setHttpStatus(this, httpStatus);\n return this;\n }\n\n /**\n * @inheritdoc\n *\n * @deprecated Use `.updateName()` instead.\n */\n public setName(name: string): void {\n this.updateName(name);\n }\n\n /**\n * @inheritDoc\n */\n public updateName(name: string): this {\n this._name = name;\n return this;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `spanToJSON(span).status === 'ok'` instead.\n */\n public isSuccess(): boolean {\n return this._status === 'ok';\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `.end()` instead.\n */\n public finish(endTimestamp?: number): void {\n return this.end(endTimestamp);\n }\n\n /** @inheritdoc */\n public end(endTimestamp?: SpanTimeInput): void {\n // If already ended, skip\n if (this._endTime) {\n return;\n }\n const rootSpan = getRootSpan(this);\n if (\n DEBUG_BUILD &&\n // Don't call this for transactions\n rootSpan &&\n rootSpan.spanContext().spanId !== this._spanId\n ) {\n const logMessage = this._logMessage;\n if (logMessage) {\n logger.log((logMessage as string).replace('Starting', 'Finishing'));\n }\n }\n\n this._endTime = spanTimeInputToSeconds(endTimestamp);\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `spanToTraceHeader()` instead.\n */\n public toTraceparent(): string {\n return spanToTraceHeader(this);\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `spanToJSON()` or access the fields directly instead.\n */\n public toContext(): SpanContext {\n return dropUndefinedKeys({\n data: this._getData(),\n description: this._name,\n endTimestamp: this._endTime,\n // eslint-disable-next-line deprecation/deprecation\n op: this.op,\n parentSpanId: this._parentSpanId,\n sampled: this._sampled,\n spanId: this._spanId,\n startTimestamp: this._startTime,\n status: this._status,\n // eslint-disable-next-line deprecation/deprecation\n tags: this.tags,\n traceId: this._traceId,\n });\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Update the fields directly instead.\n */\n public updateWithContext(spanContext: SpanContext): this {\n // eslint-disable-next-line deprecation/deprecation\n this.data = spanContext.data || {};\n // eslint-disable-next-line deprecation/deprecation\n this._name = spanContext.name || spanContext.description;\n this._endTime = spanContext.endTimestamp;\n // eslint-disable-next-line deprecation/deprecation\n this.op = spanContext.op;\n this._parentSpanId = spanContext.parentSpanId;\n this._sampled = spanContext.sampled;\n this._spanId = spanContext.spanId || this._spanId;\n this._startTime = spanContext.startTimestamp || this._startTime;\n this._status = spanContext.status;\n // eslint-disable-next-line deprecation/deprecation\n this.tags = spanContext.tags || {};\n this._traceId = spanContext.traceId || this._traceId;\n\n return this;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `spanToTraceContext()` util function instead.\n */\n public getTraceContext(): TraceContext {\n return spanToTraceContext(this);\n }\n\n /**\n * Get JSON representation of this span.\n *\n * @hidden\n * @internal This method is purely for internal purposes and should not be used outside\n * of SDK code. If you need to get a JSON representation of a span,\n * use `spanToJSON(span)` instead.\n */\n public getSpanJSON(): SpanJSON {\n return dropUndefinedKeys({\n data: this._getData(),\n description: this._name,\n op: this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP] as string | undefined,\n parent_span_id: this._parentSpanId,\n span_id: this._spanId,\n start_timestamp: this._startTime,\n status: this._status,\n // eslint-disable-next-line deprecation/deprecation\n tags: Object.keys(this.tags).length > 0 ? this.tags : undefined,\n timestamp: this._endTime,\n trace_id: this._traceId,\n origin: this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN] as SpanOrigin | undefined,\n _metrics_summary: getMetricSummaryJsonForSpan(this),\n profile_id: this._attributes[SEMANTIC_ATTRIBUTE_PROFILE_ID] as string | undefined,\n exclusive_time: this._exclusiveTime,\n measurements: Object.keys(this._measurements).length > 0 ? this._measurements : undefined,\n });\n }\n\n /** @inheritdoc */\n public isRecording(): boolean {\n return !this._endTime && !!this._sampled;\n }\n\n /**\n * Convert the object to JSON.\n * @deprecated Use `spanToJSON(span)` instead.\n */\n public toJSON(): SpanJSON {\n return this.getSpanJSON();\n }\n\n /**\n * Get the merged data for this span.\n * For now, this combines `data` and `attributes` together,\n * until eventually we can ingest `attributes` directly.\n */\n private _getData():\n | {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key: string]: any;\n }\n | undefined {\n // eslint-disable-next-line deprecation/deprecation\n const { data, _attributes: attributes } = this;\n\n const hasData = Object.keys(data).length > 0;\n const hasAttributes = Object.keys(attributes).length > 0;\n\n if (!hasData && !hasAttributes) {\n return undefined;\n }\n\n if (hasData && hasAttributes) {\n return {\n ...data,\n ...attributes,\n };\n }\n\n return hasData ? data : attributes;\n }\n}\n","import type {\n Context,\n Contexts,\n DynamicSamplingContext,\n MeasurementUnit,\n SpanTimeInput,\n Transaction as TransactionInterface,\n TransactionContext,\n TransactionEvent,\n TransactionMetadata,\n} from '@sentry/types';\nimport { dropUndefinedKeys, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { Hub } from '../hub';\nimport { getCurrentHub } from '../hub';\nimport { getMetricSummaryJsonForSpan } from '../metrics/metric-summary';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE } from '../semanticAttributes';\nimport { spanTimeInputToSeconds, spanToJSON, spanToTraceContext } from '../utils/spanUtils';\nimport { getDynamicSamplingContextFromSpan } from './dynamicSamplingContext';\nimport { Span as SpanClass, SpanRecorder } from './span';\nimport { getCapturedScopesOnSpan } from './trace';\n\n/** JSDoc */\nexport class Transaction extends SpanClass implements TransactionInterface {\n /**\n * The reference to the current hub.\n */\n // eslint-disable-next-line deprecation/deprecation\n public _hub: Hub;\n\n protected _name: string;\n\n private _contexts: Contexts;\n\n private _trimEnd?: boolean | undefined;\n\n // DO NOT yet remove this property, it is used in a hack for v7 backwards compatibility.\n private _frozenDynamicSamplingContext: Readonly<Partial<DynamicSamplingContext>> | undefined;\n\n private _metadata: Partial<TransactionMetadata>;\n\n /**\n * This constructor should never be called manually. Those instrumenting tracing should use\n * `Sentry.startTransaction()`, and internal methods should use `hub.startTransaction()`.\n * @internal\n * @hideconstructor\n * @hidden\n *\n * @deprecated Transactions will be removed in v8. Use spans instead.\n */\n // eslint-disable-next-line deprecation/deprecation\n public constructor(transactionContext: TransactionContext, hub?: Hub) {\n super(transactionContext);\n this._contexts = {};\n\n // eslint-disable-next-line deprecation/deprecation\n this._hub = hub || getCurrentHub();\n\n this._name = transactionContext.name || '';\n\n this._metadata = {\n // eslint-disable-next-line deprecation/deprecation\n ...transactionContext.metadata,\n };\n\n this._trimEnd = transactionContext.trimEnd;\n\n // this is because transactions are also spans, and spans have a transaction pointer\n // TODO (v8): Replace this with another way to set the root span\n // eslint-disable-next-line deprecation/deprecation\n this.transaction = this;\n\n // If Dynamic Sampling Context is provided during the creation of the transaction, we freeze it as it usually means\n // there is incoming Dynamic Sampling Context. (Either through an incoming request, a baggage meta-tag, or other means)\n const incomingDynamicSamplingContext = this._metadata.dynamicSamplingContext;\n if (incomingDynamicSamplingContext) {\n // We shallow copy this in case anything writes to the original reference of the passed in `dynamicSamplingContext`\n this._frozenDynamicSamplingContext = { ...incomingDynamicSamplingContext };\n }\n }\n\n // This sadly conflicts with the getter/setter ordering :(\n /* eslint-disable @typescript-eslint/member-ordering */\n\n /**\n * Getter for `name` property.\n * @deprecated Use `spanToJSON(span).description` instead.\n */\n public get name(): string {\n return this._name;\n }\n\n /**\n * Setter for `name` property, which also sets `source` as custom.\n * @deprecated Use `updateName()` and `setMetadata()` instead.\n */\n public set name(newName: string) {\n // eslint-disable-next-line deprecation/deprecation\n this.setName(newName);\n }\n\n /**\n * Get the metadata for this transaction.\n * @deprecated Use `spanGetMetadata(transaction)` instead.\n */\n public get metadata(): TransactionMetadata {\n // We merge attributes in for backwards compatibility\n return {\n // Defaults\n // eslint-disable-next-line deprecation/deprecation\n source: 'custom',\n spanMetadata: {},\n\n // Legacy metadata\n ...this._metadata,\n\n // From attributes\n ...(this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] && {\n source: this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] as TransactionMetadata['source'],\n }),\n ...(this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE] && {\n sampleRate: this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE] as TransactionMetadata['sampleRate'],\n }),\n };\n }\n\n /**\n * Update the metadata for this transaction.\n * @deprecated Use `spanGetMetadata(transaction)` instead.\n */\n public set metadata(metadata: TransactionMetadata) {\n this._metadata = metadata;\n }\n\n /* eslint-enable @typescript-eslint/member-ordering */\n\n /**\n * Setter for `name` property, which also sets `source` on the metadata.\n *\n * @deprecated Use `.updateName()` and `.setAttribute()` instead.\n */\n public setName(name: string, source: TransactionMetadata['source'] = 'custom'): void {\n this._name = name;\n this.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, source);\n }\n\n /** @inheritdoc */\n public updateName(name: string): this {\n this._name = name;\n return this;\n }\n\n /**\n * Attaches SpanRecorder to the span itself\n * @param maxlen maximum number of spans that can be recorded\n */\n public initSpanRecorder(maxlen: number = 1000): void {\n // eslint-disable-next-line deprecation/deprecation\n if (!this.spanRecorder) {\n // eslint-disable-next-line deprecation/deprecation\n this.spanRecorder = new SpanRecorder(maxlen);\n }\n // eslint-disable-next-line deprecation/deprecation\n this.spanRecorder.add(this);\n }\n\n /**\n * Set the context of a transaction event.\n * @deprecated Use either `.setAttribute()`, or set the context on the scope before creating the transaction.\n */\n public setContext(key: string, context: Context | null): void {\n if (context === null) {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete this._contexts[key];\n } else {\n this._contexts[key] = context;\n }\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use top-level `setMeasurement()` instead.\n */\n public setMeasurement(name: string, value: number, unit: MeasurementUnit = ''): void {\n this._measurements[name] = { value, unit };\n }\n\n /**\n * Store metadata on this transaction.\n * @deprecated Use attributes or store data on the scope instead.\n */\n public setMetadata(newMetadata: Partial<TransactionMetadata>): void {\n this._metadata = { ...this._metadata, ...newMetadata };\n }\n\n /**\n * @inheritDoc\n */\n public end(endTimestamp?: SpanTimeInput): string | undefined {\n const timestampInS = spanTimeInputToSeconds(endTimestamp);\n const transaction = this._finishTransaction(timestampInS);\n if (!transaction) {\n return undefined;\n }\n // eslint-disable-next-line deprecation/deprecation\n return this._hub.captureEvent(transaction);\n }\n\n /**\n * @inheritDoc\n */\n public toContext(): TransactionContext {\n // eslint-disable-next-line deprecation/deprecation\n const spanContext = super.toContext();\n\n return dropUndefinedKeys({\n ...spanContext,\n name: this._name,\n trimEnd: this._trimEnd,\n });\n }\n\n /**\n * @inheritDoc\n */\n public updateWithContext(transactionContext: TransactionContext): this {\n // eslint-disable-next-line deprecation/deprecation\n super.updateWithContext(transactionContext);\n\n this._name = transactionContext.name || '';\n this._trimEnd = transactionContext.trimEnd;\n\n return this;\n }\n\n /**\n * @inheritdoc\n *\n * @experimental\n *\n * @deprecated Use top-level `getDynamicSamplingContextFromSpan` instead.\n */\n public getDynamicSamplingContext(): Readonly<Partial<DynamicSamplingContext>> {\n return getDynamicSamplingContextFromSpan(this);\n }\n\n /**\n * Override the current hub with a new one.\n * Used if you want another hub to finish the transaction.\n *\n * @internal\n */\n // eslint-disable-next-line deprecation/deprecation\n public setHub(hub: Hub): void {\n this._hub = hub;\n }\n\n /**\n * Get the profile id of the transaction.\n */\n public getProfileId(): string | undefined {\n if (this._contexts !== undefined && this._contexts['profile'] !== undefined) {\n return this._contexts['profile'].profile_id as string;\n }\n return undefined;\n }\n\n /**\n * Finish the transaction & prepare the event to send to Sentry.\n */\n protected _finishTransaction(endTimestamp?: number): TransactionEvent | undefined {\n // This transaction is already finished, so we should not flush it again.\n if (this._endTime !== undefined) {\n return undefined;\n }\n\n if (!this._name) {\n DEBUG_BUILD && logger.warn('Transaction has no name, falling back to `<unlabeled transaction>`.');\n this._name = '<unlabeled transaction>';\n }\n\n // just sets the end timestamp\n super.end(endTimestamp);\n\n // eslint-disable-next-line deprecation/deprecation\n const client = this._hub.getClient();\n if (client && client.emit) {\n client.emit('finishTransaction', this);\n }\n\n if (this._sampled !== true) {\n // At this point if `sampled !== true` we want to discard the transaction.\n DEBUG_BUILD && logger.log('[Tracing] Discarding transaction because its trace was not chosen to be sampled.');\n\n if (client) {\n client.recordDroppedEvent('sample_rate', 'transaction');\n }\n\n return undefined;\n }\n\n // eslint-disable-next-line deprecation/deprecation\n const finishedSpans = this.spanRecorder\n ? // eslint-disable-next-line deprecation/deprecation\n this.spanRecorder.spans.filter(span => span !== this && spanToJSON(span).timestamp)\n : [];\n\n if (this._trimEnd && finishedSpans.length > 0) {\n const endTimes = finishedSpans.map(span => spanToJSON(span).timestamp).filter(Boolean) as number[];\n this._endTime = endTimes.reduce((prev, current) => {\n return prev > current ? prev : current;\n });\n }\n\n const { scope: capturedSpanScope, isolationScope: capturedSpanIsolationScope } = getCapturedScopesOnSpan(this);\n\n // eslint-disable-next-line deprecation/deprecation\n const { metadata } = this;\n // eslint-disable-next-line deprecation/deprecation\n const { source } = metadata;\n\n const transaction: TransactionEvent = {\n contexts: {\n ...this._contexts,\n // We don't want to override trace context\n trace: spanToTraceContext(this),\n },\n // TODO: Pass spans serialized via `spanToJSON()` here instead in v8.\n spans: finishedSpans,\n start_timestamp: this._startTime,\n // eslint-disable-next-line deprecation/deprecation\n tags: this.tags,\n timestamp: this._endTime,\n transaction: this._name,\n type: 'transaction',\n sdkProcessingMetadata: {\n ...metadata,\n capturedSpanScope,\n capturedSpanIsolationScope,\n ...dropUndefinedKeys({\n dynamicSamplingContext: getDynamicSamplingContextFromSpan(this),\n }),\n },\n _metrics_summary: getMetricSummaryJsonForSpan(this),\n ...(source && {\n transaction_info: {\n source,\n },\n }),\n };\n\n const hasMeasurements = Object.keys(this._measurements).length > 0;\n\n if (hasMeasurements) {\n DEBUG_BUILD &&\n logger.log(\n '[Measurements] Adding measurements to transaction',\n JSON.stringify(this._measurements, undefined, 2),\n );\n transaction.measurements = this._measurements;\n }\n\n // eslint-disable-next-line deprecation/deprecation\n DEBUG_BUILD && logger.log(`[Tracing] Finishing ${this.op} transaction: ${this._name}.`);\n\n return transaction;\n }\n}\n","/* eslint-disable max-lines */\nimport type { SpanTimeInput, TransactionContext } from '@sentry/types';\nimport { logger, timestampInSeconds } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { Hub } from '../hub';\nimport { spanTimeInputToSeconds, spanToJSON } from '../utils/spanUtils';\nimport type { Span } from './span';\nimport { SpanRecorder } from './span';\nimport { Transaction } from './transaction';\n\nexport const TRACING_DEFAULTS = {\n idleTimeout: 1000,\n finalTimeout: 30000,\n heartbeatInterval: 5000,\n};\n\nconst FINISH_REASON_TAG = 'finishReason';\n\nconst IDLE_TRANSACTION_FINISH_REASONS = [\n 'heartbeatFailed',\n 'idleTimeout',\n 'documentHidden',\n 'finalTimeout',\n 'externalFinish',\n 'cancelled',\n];\n\n/**\n * @inheritDoc\n */\nexport class IdleTransactionSpanRecorder extends SpanRecorder {\n public constructor(\n private readonly _pushActivity: (id: string) => void,\n private readonly _popActivity: (id: string) => void,\n public transactionSpanId: string,\n maxlen?: number,\n ) {\n super(maxlen);\n }\n\n /**\n * @inheritDoc\n */\n public add(span: Span): void {\n // We should make sure we do not push and pop activities for\n // the transaction that this span recorder belongs to.\n if (span.spanContext().spanId !== this.transactionSpanId) {\n // We patch span.end() to pop an activity after setting an endTimestamp.\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const originalEnd = span.end;\n span.end = (...rest: unknown[]) => {\n this._popActivity(span.spanContext().spanId);\n return originalEnd.apply(span, rest);\n };\n\n // We should only push new activities if the span does not have an end timestamp.\n if (spanToJSON(span).timestamp === undefined) {\n this._pushActivity(span.spanContext().spanId);\n }\n }\n\n super.add(span);\n }\n}\n\nexport type BeforeFinishCallback = (transactionSpan: IdleTransaction, endTimestamp: number) => void;\n\n/**\n * An IdleTransaction is a transaction that automatically finishes. It does this by tracking child spans as activities.\n * You can have multiple IdleTransactions active, but if the `onScope` option is specified, the idle transaction will\n * put itself on the scope on creation.\n */\nexport class IdleTransaction extends Transaction {\n // Activities store a list of active spans\n public activities: Record<string, boolean>;\n // Track state of activities in previous heartbeat\n private _prevHeartbeatString: string | undefined;\n\n // Amount of times heartbeat has counted. Will cause transaction to finish after 3 beats.\n private _heartbeatCounter: number;\n\n // We should not use heartbeat if we finished a transaction\n private _finished: boolean;\n\n // Idle timeout was canceled and we should finish the transaction with the last span end.\n private _idleTimeoutCanceledPermanently: boolean;\n\n private readonly _beforeFinishCallbacks: BeforeFinishCallback[];\n\n /**\n * Timer that tracks Transaction idleTimeout\n */\n private _idleTimeoutID: ReturnType<typeof setTimeout> | undefined;\n\n private _finishReason: (typeof IDLE_TRANSACTION_FINISH_REASONS)[number];\n\n private _autoFinishAllowed: boolean;\n\n /**\n * @deprecated Transactions will be removed in v8. Use spans instead.\n */\n public constructor(\n transactionContext: TransactionContext,\n // eslint-disable-next-line deprecation/deprecation\n private readonly _idleHub: Hub,\n /**\n * The time to wait in ms until the idle transaction will be finished. This timer is started each time\n * there are no active spans on this transaction.\n */\n private readonly _idleTimeout: number = TRACING_DEFAULTS.idleTimeout,\n /**\n * The final value in ms that a transaction cannot exceed\n */\n private readonly _finalTimeout: number = TRACING_DEFAULTS.finalTimeout,\n private readonly _heartbeatInterval: number = TRACING_DEFAULTS.heartbeatInterval,\n // Whether or not the transaction should put itself on the scope when it starts and pop itself off when it ends\n private readonly _onScope: boolean = false,\n /**\n * When set to `true`, will disable the idle timeout (`_idleTimeout` option) and heartbeat mechanisms (`_heartbeatInterval`\n * option) until the `sendAutoFinishSignal()` method is called. The final timeout mechanism (`_finalTimeout` option)\n * will not be affected by this option, meaning the transaction will definitely be finished when the final timeout is\n * reached, no matter what this option is configured to.\n *\n * Defaults to `false`.\n */\n delayAutoFinishUntilSignal: boolean = false,\n ) {\n super(transactionContext, _idleHub);\n\n this.activities = {};\n this._heartbeatCounter = 0;\n this._finished = false;\n this._idleTimeoutCanceledPermanently = false;\n this._beforeFinishCallbacks = [];\n this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[4];\n this._autoFinishAllowed = !delayAutoFinishUntilSignal;\n\n if (_onScope) {\n // We set the transaction here on the scope so error events pick up the trace\n // context and attach it to the error.\n DEBUG_BUILD && logger.log(`Setting idle transaction on scope. Span ID: ${this.spanContext().spanId}`);\n // eslint-disable-next-line deprecation/deprecation\n _idleHub.getScope().setSpan(this);\n }\n\n if (!delayAutoFinishUntilSignal) {\n this._restartIdleTimeout();\n }\n\n setTimeout(() => {\n if (!this._finished) {\n this.setStatus('deadline_exceeded');\n this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[3];\n this.end();\n }\n }, this._finalTimeout);\n }\n\n /** {@inheritDoc} */\n public end(endTimestamp?: SpanTimeInput): string | undefined {\n const endTimestampInS = spanTimeInputToSeconds(endTimestamp);\n\n this._finished = true;\n this.activities = {};\n\n // eslint-disable-next-line deprecation/deprecation\n if (this.op === 'ui.action.click') {\n this.setAttribute(FINISH_REASON_TAG, this._finishReason);\n }\n\n // eslint-disable-next-line deprecation/deprecation\n if (this.spanRecorder) {\n DEBUG_BUILD &&\n // eslint-disable-next-line deprecation/deprecation\n logger.log('[Tracing] finishing IdleTransaction', new Date(endTimestampInS * 1000).toISOString(), this.op);\n\n for (const callback of this._beforeFinishCallbacks) {\n callback(this, endTimestampInS);\n }\n\n // eslint-disable-next-line deprecation/deprecation\n this.spanRecorder.spans = this.spanRecorder.spans.filter((span: Span) => {\n // If we are dealing with the transaction itself, we just return it\n if (span.spanContext().spanId === this.spanContext().spanId) {\n return true;\n }\n\n // We cancel all pending spans with status \"cancelled\" to indicate the idle transaction was finished early\n if (!spanToJSON(span).timestamp) {\n span.setStatus('cancelled');\n span.end(endTimestampInS);\n DEBUG_BUILD &&\n logger.log('[Tracing] cancelling span since transaction ended early', JSON.stringify(span, undefined, 2));\n }\n\n const { start_timestamp: startTime, timestamp: endTime } = spanToJSON(span);\n const spanStartedBeforeTransactionFinish = startTime && startTime < endTimestampInS;\n\n // Add a delta with idle timeout so that we prevent false positives\n const timeoutWithMarginOfError = (this._finalTimeout + this._idleTimeout) / 1000;\n const spanEndedBeforeFinalTimeout = endTime && startTime && endTime - startTime < timeoutWithMarginOfError;\n\n if (DEBUG_BUILD) {\n const stringifiedSpan = JSON.stringify(span, undefined, 2);\n if (!spanStartedBeforeTransactionFinish) {\n logger.log('[Tracing] discarding Span since it happened after Transaction was finished', stringifiedSpan);\n } else if (!spanEndedBeforeFinalTimeout) {\n logger.log('[Tracing] discarding Span since it finished after Transaction final timeout', stringifiedSpan);\n }\n }\n\n return spanStartedBeforeTransactionFinish && spanEndedBeforeFinalTimeout;\n });\n\n DEBUG_BUILD && logger.log('[Tracing] flushing IdleTransaction');\n } else {\n DEBUG_BUILD && logger.log('[Tracing] No active IdleTransaction');\n }\n\n // if `this._onScope` is `true`, the transaction put itself on the scope when it started\n if (this._onScope) {\n // eslint-disable-next-line deprecation/deprecation\n const scope = this._idleHub.getScope();\n // eslint-disable-next-line deprecation/deprecation\n if (scope.getTransaction() === this) {\n // eslint-disable-next-line deprecation/deprecation\n scope.setSpan(undefined);\n }\n }\n\n return super.end(endTimestamp);\n }\n\n /**\n * Register a callback function that gets executed before the transaction finishes.\n * Useful for cleanup or if you want to add any additional spans based on current context.\n *\n * This is exposed because users have no other way of running something before an idle transaction\n * finishes.\n */\n public registerBeforeFinishCallback(callback: BeforeFinishCallback): void {\n this._beforeFinishCallbacks.push(callback);\n }\n\n /**\n * @inheritDoc\n */\n public initSpanRecorder(maxlen?: number): void {\n // eslint-disable-next-line deprecation/deprecation\n if (!this.spanRecorder) {\n const pushActivity = (id: string): void => {\n if (this._finished) {\n return;\n }\n this._pushActivity(id);\n };\n const popActivity = (id: string): void => {\n if (this._finished) {\n return;\n }\n this._popActivity(id);\n };\n\n // eslint-disable-next-line deprecation/deprecation\n this.spanRecorder = new IdleTransactionSpanRecorder(pushActivity, popActivity, this.spanContext().spanId, maxlen);\n\n // Start heartbeat so that transactions do not run forever.\n DEBUG_BUILD && logger.log('Starting heartbeat');\n this._pingHeartbeat();\n }\n // eslint-disable-next-line deprecation/deprecation\n this.spanRecorder.add(this);\n }\n\n /**\n * Cancels the existing idle timeout, if there is one.\n * @param restartOnChildSpanChange Default is `true`.\n * If set to false the transaction will end\n * with the last child span.\n */\n public cancelIdleTimeout(\n endTimestamp?: Parameters<IdleTransaction['end']>[0],\n {\n restartOnChildSpanChange,\n }: {\n restartOnChildSpanChange?: boolean;\n } = {\n restartOnChildSpanChange: true,\n },\n ): void {\n this._idleTimeoutCanceledPermanently = restartOnChildSpanChange === false;\n if (this._idleTimeoutID) {\n clearTimeout(this._idleTimeoutID);\n this._idleTimeoutID = undefined;\n\n if (Object.keys(this.activities).length === 0 && this._idleTimeoutCanceledPermanently) {\n this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[5];\n this.end(endTimestamp);\n }\n }\n }\n\n /**\n * Temporary method used to externally set the transaction's `finishReason`\n *\n * ** WARNING**\n * This is for the purpose of experimentation only and will be removed in the near future, do not use!\n *\n * @internal\n *\n */\n public setFinishReason(reason: string): void {\n this._finishReason = reason;\n }\n\n /**\n * Permits the IdleTransaction to automatically end itself via the idle timeout and heartbeat mechanisms when the `delayAutoFinishUntilSignal` option was set to `true`.\n */\n public sendAutoFinishSignal(): void {\n if (!this._autoFinishAllowed) {\n DEBUG_BUILD && logger.log('[Tracing] Received finish signal for idle transaction.');\n this._restartIdleTimeout();\n this._autoFinishAllowed = true;\n }\n }\n\n /**\n * Restarts idle timeout, if there is no running idle timeout it will start one.\n */\n private _restartIdleTimeout(endTimestamp?: Parameters<IdleTransaction['end']>[0]): void {\n this.cancelIdleTimeout();\n this._idleTimeoutID = setTimeout(() => {\n if (!this._finished && Object.keys(this.activities).length === 0) {\n this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[1];\n this.end(endTimestamp);\n }\n }, this._idleTimeout);\n }\n\n /**\n * Start tracking a specific activity.\n * @param spanId The span id that represents the activity\n */\n private _pushActivity(spanId: string): void {\n this.cancelIdleTimeout(undefined, { restartOnChildSpanChange: !this._idleTimeoutCanceledPermanently });\n DEBUG_BUILD && logger.log(`[Tracing] pushActivity: ${spanId}`);\n this.activities[spanId] = true;\n DEBUG_BUILD && logger.log('[Tracing] new activities count', Object.keys(this.activities).length);\n }\n\n /**\n * Remove an activity from usage\n * @param spanId The span id that represents the activity\n */\n private _popActivity(spanId: string): void {\n if (this.activities[spanId]) {\n DEBUG_BUILD && logger.log(`[Tracing] popActivity ${spanId}`);\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete this.activities[spanId];\n DEBUG_BUILD && logger.log('[Tracing] new activities count', Object.keys(this.activities).length);\n }\n\n if (Object.keys(this.activities).length === 0) {\n const endTimestamp = timestampInSeconds();\n if (this._idleTimeoutCanceledPermanently) {\n if (this._autoFinishAllowed) {\n this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[5];\n this.end(endTimestamp);\n }\n } else {\n // We need to add the timeout here to have the real endtimestamp of the transaction\n // Remember timestampInSeconds is in seconds, timeout is in ms\n this._restartIdleTimeout(endTimestamp + this._idleTimeout / 1000);\n }\n }\n }\n\n /**\n * Checks when entries of this.activities are not changing for 3 beats.\n * If this occurs we finish the transaction.\n */\n private _beat(): void {\n // We should not be running heartbeat if the idle transaction is finished.\n if (this._finished) {\n return;\n }\n\n const heartbeatString = Object.keys(this.activities).join('');\n\n if (heartbeatString === this._prevHeartbeatString) {\n this._heartbeatCounter++;\n } else {\n this._heartbeatCounter = 1;\n }\n\n this._prevHeartbeatString = heartbeatString;\n\n if (this._heartbeatCounter >= 3) {\n if (this._autoFinishAllowed) {\n DEBUG_BUILD && logger.log('[Tracing] Transaction finished because of no change for 3 heart beats');\n this.setStatus('deadline_exceeded');\n this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[0];\n this.end();\n }\n } else {\n this._pingHeartbeat();\n }\n }\n\n /**\n * Pings the heartbeat\n */\n private _pingHeartbeat(): void {\n DEBUG_BUILD && logger.log(`pinging Heartbeat -> current counter: ${this._heartbeatCounter}`);\n setTimeout(() => {\n this._beat();\n }, this._heartbeatInterval);\n }\n}\n","import type { Options, SamplingContext } from '@sentry/types';\nimport { isNaN, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE } from '../semanticAttributes';\nimport { hasTracingEnabled } from '../utils/hasTracingEnabled';\nimport { spanToJSON } from '../utils/spanUtils';\nimport type { Transaction } from './transaction';\n\n/**\n * Makes a sampling decision for the given transaction and stores it on the transaction.\n *\n * Called every time a transaction is created. Only transactions which emerge with a `sampled` value of `true` will be\n * sent to Sentry.\n *\n * This method muttes the given `transaction` and will set the `sampled` value on it.\n * It returns the same transaction, for convenience.\n */\nexport function sampleTransaction<T extends Transaction>(\n transaction: T,\n options: Pick<Options, 'tracesSampleRate' | 'tracesSampler' | 'enableTracing'>,\n samplingContext: SamplingContext,\n): T {\n // nothing to do if tracing is not enabled\n if (!hasTracingEnabled(options)) {\n // eslint-disable-next-line deprecation/deprecation\n transaction.sampled = false;\n return transaction;\n }\n\n // if the user has forced a sampling decision by passing a `sampled` value in their transaction context, go with that\n // eslint-disable-next-line deprecation/deprecation\n if (transaction.sampled !== undefined) {\n // eslint-disable-next-line deprecation/deprecation\n transaction.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, Number(transaction.sampled));\n return transaction;\n }\n\n // we would have bailed already if neither `tracesSampler` nor `tracesSampleRate` nor `enableTracing` were defined, so one of these should\n // work; prefer the hook if so\n let sampleRate;\n if (typeof options.tracesSampler === 'function') {\n sampleRate = options.tracesSampler(samplingContext);\n transaction.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, Number(sampleRate));\n } else if (samplingContext.parentSampled !== undefined) {\n sampleRate = samplingContext.parentSampled;\n } else if (typeof options.tracesSampleRate !== 'undefined') {\n sampleRate = options.tracesSampleRate;\n transaction.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, Number(sampleRate));\n } else {\n // When `enableTracing === true`, we use a sample rate of 100%\n sampleRate = 1;\n transaction.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, sampleRate);\n }\n\n // Since this is coming from the user (or from a function provided by the user), who knows what we might get. (The\n // only valid values are booleans or numbers between 0 and 1.)\n if (!isValidSampleRate(sampleRate)) {\n DEBUG_BUILD && logger.warn('[Tracing] Discarding transaction because of invalid sample rate.');\n // eslint-disable-next-line deprecation/deprecation\n transaction.sampled = false;\n return transaction;\n }\n\n // if the function returned 0 (or false), or if `tracesSampleRate` is 0, it's a sign the transaction should be dropped\n if (!sampleRate) {\n DEBUG_BUILD &&\n logger.log(\n `[Tracing] Discarding transaction because ${\n typeof options.tracesSampler === 'function'\n ? 'tracesSampler returned 0 or false'\n : 'a negative sampling decision was inherited or tracesSampleRate is set to 0'\n }`,\n );\n // eslint-disable-next-line deprecation/deprecation\n transaction.sampled = false;\n return transaction;\n }\n\n // Now we roll the dice. Math.random is inclusive of 0, but not of 1, so strict < is safe here. In case sampleRate is\n // a boolean, the < comparison will cause it to be automatically cast to 1 if it's true and 0 if it's false.\n // eslint-disable-next-line deprecation/deprecation\n transaction.sampled = Math.random() < (sampleRate as number | boolean);\n\n // if we're not going to keep it, we're done\n // eslint-disable-next-line deprecation/deprecation\n if (!transaction.sampled) {\n DEBUG_BUILD &&\n logger.log(\n `[Tracing] Discarding transaction because it's not included in the random sample (sampling rate = ${Number(\n sampleRate,\n )})`,\n );\n return transaction;\n }\n\n DEBUG_BUILD &&\n // eslint-disable-next-line deprecation/deprecation\n logger.log(`[Tracing] starting ${transaction.op} transaction - ${spanToJSON(transaction).description}`);\n return transaction;\n}\n\n/**\n * Checks the given sample rate to make sure it is valid type and value (a boolean, or a number between 0 and 1).\n */\nexport function isValidSampleRate(rate: unknown): boolean {\n // we need to check NaN explicitly because it's of type 'number' and therefore wouldn't get caught by this typecheck\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n if (isNaN(rate) || !(typeof rate === 'number' || typeof rate === 'boolean')) {\n DEBUG_BUILD &&\n logger.warn(\n `[Tracing] Given sample rate is invalid. Sample rate must be a boolean or a number between 0 and 1. Got ${JSON.stringify(\n rate,\n )} of type ${JSON.stringify(typeof rate)}.`,\n );\n return false;\n }\n\n // in case sampleRate is a boolean, it will get automatically cast to 1 if it's true and 0 if it's false\n if (rate < 0 || rate > 1) {\n DEBUG_BUILD &&\n logger.warn(`[Tracing] Given sample rate is invalid. Sample rate must be between 0 and 1. Got ${rate}.`);\n return false;\n }\n return true;\n}\n","import type { ClientOptions, CustomSamplingContext, TransactionContext } from '@sentry/types';\nimport { logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { Hub } from '../hub';\nimport { getMainCarrier } from '../hub';\nimport { spanToTraceHeader } from '../utils/spanUtils';\nimport { registerErrorInstrumentation } from './errors';\nimport { IdleTransaction } from './idletransaction';\nimport { sampleTransaction } from './sampling';\nimport { Transaction } from './transaction';\n\n/** Returns all trace headers that are currently on the top scope. */\n// eslint-disable-next-line deprecation/deprecation\nfunction traceHeaders(this: Hub): { [key: string]: string } {\n // eslint-disable-next-line deprecation/deprecation\n const scope = this.getScope();\n // eslint-disable-next-line deprecation/deprecation\n const span = scope.getSpan();\n\n return span\n ? {\n 'sentry-trace': spanToTraceHeader(span),\n }\n : {};\n}\n\n/**\n * Creates a new transaction and adds a sampling decision if it doesn't yet have one.\n *\n * The Hub.startTransaction method delegates to this method to do its work, passing the Hub instance in as `this`, as if\n * it had been called on the hub directly. Exists as a separate function so that it can be injected into the class as an\n * \"extension method.\"\n *\n * @param this: The Hub starting the transaction\n * @param transactionContext: Data used to configure the transaction\n * @param CustomSamplingContext: Optional data to be provided to the `tracesSampler` function (if any)\n *\n * @returns The new transaction\n *\n * @see {@link Hub.startTransaction}\n */\nfunction _startTransaction(\n // eslint-disable-next-line deprecation/deprecation\n this: Hub,\n transactionContext: TransactionContext,\n customSamplingContext?: CustomSamplingContext,\n): Transaction {\n // eslint-disable-next-line deprecation/deprecation\n const client = this.getClient();\n const options: Partial<ClientOptions> = (client && client.getOptions()) || {};\n\n const configInstrumenter = options.instrumenter || 'sentry';\n const transactionInstrumenter = transactionContext.instrumenter || 'sentry';\n\n if (configInstrumenter !== transactionInstrumenter) {\n DEBUG_BUILD &&\n logger.error(\n `A transaction was started with instrumenter=\\`${transactionInstrumenter}\\`, but the SDK is configured with the \\`${configInstrumenter}\\` instrumenter.\nThe transaction will not be sampled. Please use the ${configInstrumenter} instrumentation to start transactions.`,\n );\n\n // eslint-disable-next-line deprecation/deprecation\n transactionContext.sampled = false;\n }\n\n // eslint-disable-next-line deprecation/deprecation\n let transaction = new Transaction(transactionContext, this);\n transaction = sampleTransaction(transaction, options, {\n name: transactionContext.name,\n parentSampled: transactionContext.parentSampled,\n transactionContext,\n attributes: {\n // eslint-disable-next-line deprecation/deprecation\n ...transactionContext.data,\n ...transactionContext.attributes,\n },\n ...customSamplingContext,\n });\n if (transaction.isRecording()) {\n transaction.initSpanRecorder(options._experiments && (options._experiments.maxSpans as number));\n }\n if (client && client.emit) {\n client.emit('startTransaction', transaction);\n }\n return transaction;\n}\n\n/**\n * Create new idle transaction.\n */\nexport function startIdleTransaction(\n // eslint-disable-next-line deprecation/deprecation\n hub: Hub,\n transactionContext: TransactionContext,\n idleTimeout: number,\n finalTimeout: number,\n onScope?: boolean,\n customSamplingContext?: CustomSamplingContext,\n heartbeatInterval?: number,\n delayAutoFinishUntilSignal: boolean = false,\n): IdleTransaction {\n // eslint-disable-next-line deprecation/deprecation\n const client = hub.getClient();\n const options: Partial<ClientOptions> = (client && client.getOptions()) || {};\n\n // eslint-disable-next-line deprecation/deprecation\n let transaction = new IdleTransaction(\n transactionContext,\n hub,\n idleTimeout,\n finalTimeout,\n heartbeatInterval,\n onScope,\n delayAutoFinishUntilSignal,\n );\n transaction = sampleTransaction(transaction, options, {\n name: transactionContext.name,\n parentSampled: transactionContext.parentSampled,\n transactionContext,\n attributes: {\n // eslint-disable-next-line deprecation/deprecation\n ...transactionContext.data,\n ...transactionContext.attributes,\n },\n ...customSamplingContext,\n });\n if (transaction.isRecording()) {\n transaction.initSpanRecorder(options._experiments && (options._experiments.maxSpans as number));\n }\n if (client && client.emit) {\n client.emit('startTransaction', transaction);\n }\n return transaction;\n}\n\n/**\n * Adds tracing extensions to the global hub.\n */\nexport function addTracingExtensions(): void {\n const carrier = getMainCarrier();\n if (!carrier.__SENTRY__) {\n return;\n }\n carrier.__SENTRY__.extensions = carrier.__SENTRY__.extensions || {};\n if (!carrier.__SENTRY__.extensions.startTransaction) {\n carrier.__SENTRY__.extensions.startTransaction = _startTransaction;\n }\n if (!carrier.__SENTRY__.extensions.traceHeaders) {\n carrier.__SENTRY__.extensions.traceHeaders = traceHeaders;\n }\n\n registerErrorInstrumentation();\n}\n","import type { MeasurementUnit } from '@sentry/types';\n\nimport { getActiveTransaction } from './utils';\n\n/**\n * Adds a measurement to the current active transaction.\n */\nexport function setMeasurement(name: string, value: number, unit: MeasurementUnit): void {\n // eslint-disable-next-line deprecation/deprecation\n const transaction = getActiveTransaction();\n if (transaction) {\n // eslint-disable-next-line deprecation/deprecation\n transaction.setMeasurement(name, value, unit);\n }\n}\n","import type {\n Client,\n Event,\n EventHint,\n Integration,\n IntegrationClass,\n IntegrationFn,\n IntegrationFnResult,\n Options,\n} from '@sentry/types';\nimport { arrayify, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from './debug-build';\nimport { addGlobalEventProcessor } from './eventProcessors';\nimport { getClient } from './exports';\nimport { getCurrentHub } from './hub';\n\ndeclare module '@sentry/types' {\n interface Integration {\n isDefaultInstance?: boolean;\n }\n}\n\nexport const installedIntegrations: string[] = [];\n\n/** Map of integrations assigned to a client */\nexport type IntegrationIndex = {\n [key: string]: Integration;\n};\n\n/**\n * Remove duplicates from the given array, preferring the last instance of any duplicate. Not guaranteed to\n * preseve the order of integrations in the array.\n *\n * @private\n */\nfunction filterDuplicates(integrations: Integration[]): Integration[] {\n const integrationsByName: { [key: string]: Integration } = {};\n\n integrations.forEach(currentInstance => {\n const { name } = currentInstance;\n\n const existingInstance = integrationsByName[name];\n\n // We want integrations later in the array to overwrite earlier ones of the same type, except that we never want a\n // default instance to overwrite an existing user instance\n if (existingInstance && !existingInstance.isDefaultInstance && currentInstance.isDefaultInstance) {\n return;\n }\n\n integrationsByName[name] = currentInstance;\n });\n\n return Object.keys(integrationsByName).map(k => integrationsByName[k]);\n}\n\n/** Gets integrations to install */\nexport function getIntegrationsToSetup(options: Pick<Options, 'defaultIntegrations' | 'integrations'>): Integration[] {\n const defaultIntegrations = options.defaultIntegrations || [];\n const userIntegrations = options.integrations;\n\n // We flag default instances, so that later we can tell them apart from any user-created instances of the same class\n defaultIntegrations.forEach(integration => {\n integration.isDefaultInstance = true;\n });\n\n let integrations: Integration[];\n\n if (Array.isArray(userIntegrations)) {\n integrations = [...defaultIntegrations, ...userIntegrations];\n } else if (typeof userIntegrations === 'function') {\n integrations = arrayify(userIntegrations(defaultIntegrations));\n } else {\n integrations = defaultIntegrations;\n }\n\n const finalIntegrations = filterDuplicates(integrations);\n\n // The `Debug` integration prints copies of the `event` and `hint` which will be passed to `beforeSend` or\n // `beforeSendTransaction`. It therefore has to run after all other integrations, so that the changes of all event\n // processors will be reflected in the printed values. For lack of a more elegant way to guarantee that, we therefore\n // locate it and, assuming it exists, pop it out of its current spot and shove it onto the end of the array.\n const debugIndex = findIndex(finalIntegrations, integration => integration.name === 'Debug');\n if (debugIndex !== -1) {\n const [debugInstance] = finalIntegrations.splice(debugIndex, 1);\n finalIntegrations.push(debugInstance);\n }\n\n return finalIntegrations;\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(client: Client, integrations: Integration[]): IntegrationIndex {\n const integrationIndex: IntegrationIndex = {};\n\n integrations.forEach(integration => {\n // guard against empty provided integrations\n if (integration) {\n setupIntegration(client, integration, integrationIndex);\n }\n });\n\n return integrationIndex;\n}\n\n/**\n * Execute the `afterAllSetup` hooks of the given integrations.\n */\nexport function afterSetupIntegrations(client: Client, integrations: Integration[]): void {\n for (const integration of integrations) {\n // guard against empty provided integrations\n if (integration && integration.afterAllSetup) {\n integration.afterAllSetup(client);\n }\n }\n}\n\n/** Setup a single integration. */\nexport function setupIntegration(client: Client, integration: Integration, integrationIndex: IntegrationIndex): void {\n if (integrationIndex[integration.name]) {\n DEBUG_BUILD && logger.log(`Integration skipped because it was already installed: ${integration.name}`);\n return;\n }\n integrationIndex[integration.name] = integration;\n\n // `setupOnce` is only called the first time\n if (installedIntegrations.indexOf(integration.name) === -1) {\n // eslint-disable-next-line deprecation/deprecation\n integration.setupOnce(addGlobalEventProcessor, getCurrentHub);\n installedIntegrations.push(integration.name);\n }\n\n // `setup` is run for each client\n if (integration.setup && typeof integration.setup === 'function') {\n integration.setup(client);\n }\n\n if (client.on && typeof integration.preprocessEvent === 'function') {\n const callback = integration.preprocessEvent.bind(integration) as typeof integration.preprocessEvent;\n client.on('preprocessEvent', (event, hint) => callback(event, hint, client));\n }\n\n if (client.addEventProcessor && typeof integration.processEvent === 'function') {\n const callback = integration.processEvent.bind(integration) as typeof integration.processEvent;\n\n const processor = Object.assign((event: Event, hint: EventHint) => callback(event, hint, client), {\n id: integration.name,\n });\n\n client.addEventProcessor(processor);\n }\n\n DEBUG_BUILD && logger.log(`Integration installed: ${integration.name}`);\n}\n\n/** Add an integration to the current hub's client. */\nexport function addIntegration(integration: Integration): void {\n const client = getClient();\n\n if (!client || !client.addIntegration) {\n DEBUG_BUILD && logger.warn(`Cannot add integration \"${integration.name}\" because no SDK Client is available.`);\n return;\n }\n\n client.addIntegration(integration);\n}\n\n// Polyfill for Array.findIndex(), which is not supported in ES5\nfunction findIndex<T>(arr: T[], callback: (item: T) => boolean): number {\n for (let i = 0; i < arr.length; i++) {\n if (callback(arr[i]) === true) {\n return i;\n }\n }\n\n return -1;\n}\n\n/**\n * Convert a new integration function to the legacy class syntax.\n * In v8, we can remove this and instead export the integration functions directly.\n *\n * @deprecated This will be removed in v8!\n */\nexport function convertIntegrationFnToClass<Fn extends IntegrationFn>(\n name: string,\n fn: Fn,\n): IntegrationClass<Integration> {\n return Object.assign(\n function ConvertedIntegration(...args: Parameters<Fn>): Integration {\n return fn(...args);\n },\n { id: name },\n ) as unknown as IntegrationClass<Integration>;\n}\n\n/**\n * Define an integration function that can be used to create an integration instance.\n * Note that this by design hides the implementation details of the integration, as they are considered internal.\n */\nexport function defineIntegration<Fn extends IntegrationFn>(fn: Fn): (...args: Parameters<Fn>) => IntegrationFnResult {\n return fn;\n}\n","import type { ClientOptions, DsnComponents, DsnLike, SdkInfo } from '@sentry/types';\nimport { dsnToString, makeDsn, urlEncode } from '@sentry/utils';\n\nconst SENTRY_API_VERSION = '7';\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): string {\n return `${getBaseApiEndpoint(dsn)}${dsn.projectId}/envelope/`;\n}\n\n/** Returns a URL-encoded string with auth config suitable for a query string. */\nfunction _encodedAuth(dsn: DsnComponents, sdkInfo: SdkInfo | undefined): 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 ...(sdkInfo && { sentry_client: `${sdkInfo.name}/${sdkInfo.version}` }),\n });\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(\n dsn: DsnComponents,\n // TODO (v8): Remove `tunnelOrOptions` in favor of `options`, and use the substitute code below\n // options: ClientOptions = {} as ClientOptions,\n tunnelOrOptions: string | ClientOptions = {} as ClientOptions,\n): string {\n // TODO (v8): Use this code instead\n // const { tunnel, _metadata = {} } = options;\n // return tunnel ? tunnel : `${_getIngestEndpoint(dsn)}?${_encodedAuth(dsn, _metadata.sdk)}`;\n\n const tunnel = typeof tunnelOrOptions === 'string' ? tunnelOrOptions : tunnelOrOptions.tunnel;\n const sdkInfo =\n typeof tunnelOrOptions === 'string' || !tunnelOrOptions._metadata ? undefined : tunnelOrOptions._metadata.sdk;\n\n return tunnel ? tunnel : `${_getIngestEndpoint(dsn)}?${_encodedAuth(dsn, sdkInfo)}`;\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 if (!dsn) {\n return '';\n }\n\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 === 'onClose') {\n continue;\n }\n\n if (key === 'user') {\n const user = dialogOptions.user;\n if (!user) {\n continue;\n }\n if (user.name) {\n encodedOptions += `&name=${encodeURIComponent(user.name)}`;\n }\n if (user.email) {\n encodedOptions += `&email=${encodeURIComponent(user.email)}`;\n }\n } else {\n encodedOptions += `&${encodeURIComponent(key)}=${encodeURIComponent(dialogOptions[key] as string)}`;\n }\n }\n\n return `${endpoint}?${encodedOptions}`;\n}\n","import type {\n DsnComponents,\n Event,\n EventEnvelope,\n EventItem,\n SdkInfo,\n SdkMetadata,\n Session,\n SessionAggregates,\n SessionEnvelope,\n SessionItem,\n} from '@sentry/types';\nimport {\n createEnvelope,\n createEventEnvelopeHeaders,\n dsnToString,\n getSdkMetadataForEnvelopeHeader,\n} from '@sentry/utils';\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 dsn?: DsnComponents,\n metadata?: SdkMetadata,\n tunnel?: string,\n): SessionEnvelope {\n const sdkInfo = getSdkMetadataForEnvelopeHeader(metadata);\n const envelopeHeaders = {\n sent_at: new Date().toISOString(),\n ...(sdkInfo && { sdk: sdkInfo }),\n ...(!!tunnel && dsn && { dsn: dsnToString(dsn) }),\n };\n\n const envelopeItem: SessionItem =\n 'aggregates' in session ? [{ type: 'sessions' }, session] : [{ type: 'session' }, session.toJSON()];\n\n return createEnvelope<SessionEnvelope>(envelopeHeaders, [envelopeItem]);\n}\n\n/**\n * Create an Envelope from an event.\n */\nexport function createEventEnvelope(\n event: Event,\n dsn?: DsnComponents,\n metadata?: SdkMetadata,\n tunnel?: string,\n): EventEnvelope {\n const sdkInfo = getSdkMetadataForEnvelopeHeader(metadata);\n\n /*\n Note: Due to TS, event.type may be `replay_event`, theoretically.\n In practice, we never call `createEventEnvelope` with `replay_event` type,\n and we'd have to adjut a looot of types to make this work properly.\n We want to avoid casting this around, as that could lead to bugs (e.g. when we add another type)\n So the safe choice is to really guard against the replay_event type here.\n */\n const eventType = event.type && event.type !== 'replay_event' ? event.type : 'event';\n\n enhanceEventWithSdkInfo(event, metadata && metadata.sdk);\n\n const envelopeHeaders = createEventEnvelopeHeaders(event, sdkInfo, tunnel, dsn);\n\n // Prevent this data (which, if it exists, was used in earlier steps in the processing pipeline) from being sent to\n // sentry. (Note: Our use of this property comes and goes with whatever we might be debugging, whatever hacks we may\n // have temporarily added, etc. Even if we don't happen to be using it at some point in the future, let's not get rid\n // of this `delete`, lest we miss putting it back in the next time the property is in use.)\n delete event.sdkProcessingMetadata;\n\n const eventItem: EventItem = [{ type: eventType }, event];\n return createEnvelope<EventEnvelope>(envelopeHeaders, [eventItem]);\n}\n","import type { MeasurementUnit, MetricBucketItem, Primitive } from '@sentry/types';\nimport { dropUndefinedKeys } from '@sentry/utils';\nimport type { MetricType } from './types';\n\n/**\n * Generate bucket key from metric properties.\n */\nexport function getBucketKey(\n metricType: MetricType,\n name: string,\n unit: MeasurementUnit,\n tags: Record<string, string>,\n): string {\n const stringifiedTags = Object.entries(dropUndefinedKeys(tags)).sort((a, b) => a[0].localeCompare(b[0]));\n return `${metricType}${name}${unit}${stringifiedTags}`;\n}\n\n/* eslint-disable no-bitwise */\n/**\n * Simple hash function for strings.\n */\nexport function simpleHash(s: string): number {\n let rv = 0;\n for (let i = 0; i < s.length; i++) {\n const c = s.charCodeAt(i);\n rv = (rv << 5) - rv + c;\n rv &= rv;\n }\n return rv >>> 0;\n}\n/* eslint-enable no-bitwise */\n\n/**\n * Serialize metrics buckets into a string based on statsd format.\n *\n * Example of format:\n * metric.name@second:1:1.2|d|#a:value,b:anothervalue|T12345677\n * Segments:\n * name: metric.name\n * unit: second\n * value: [1, 1.2]\n * type of metric: d (distribution)\n * tags: { a: value, b: anothervalue }\n * timestamp: 12345677\n */\nexport function serializeMetricBuckets(metricBucketItems: MetricBucketItem[]): string {\n let out = '';\n for (const item of metricBucketItems) {\n const tagEntries = Object.entries(item.tags);\n const maybeTags = tagEntries.length > 0 ? `|#${tagEntries.map(([key, value]) => `${key}:${value}`).join(',')}` : '';\n out += `${item.name}@${item.unit}:${item.metric}|${item.metricType}${maybeTags}|T${item.timestamp}\\n`;\n }\n return out;\n}\n\n/** Sanitizes units */\nexport function sanitizeUnit(unit: string): string {\n return unit.replace(/[^\\w]+/gi, '_');\n}\n\n/** Sanitizes metric keys */\nexport function sanitizeMetricKey(key: string): string {\n return key.replace(/[^\\w\\-.]+/gi, '_');\n}\n\nfunction sanitizeTagKey(key: string): string {\n return key.replace(/[^\\w\\-./]+/gi, '');\n}\n\nconst tagValueReplacements: [string, string][] = [\n ['\\n', '\\\\n'],\n ['\\r', '\\\\r'],\n ['\\t', '\\\\t'],\n ['\\\\', '\\\\\\\\'],\n ['|', '\\\\u{7c}'],\n [',', '\\\\u{2c}'],\n];\n\nfunction getCharOrReplacement(input: string): string {\n for (const [search, replacement] of tagValueReplacements) {\n if (input === search) {\n return replacement;\n }\n }\n\n return input;\n}\n\nfunction sanitizeTagValue(value: string): string {\n return [...value].reduce((acc, char) => acc + getCharOrReplacement(char), '');\n}\n\n/**\n * Sanitizes tags.\n */\nexport function sanitizeTags(unsanitizedTags: Record<string, Primitive>): Record<string, string> {\n const tags: Record<string, string> = {};\n for (const key in unsanitizedTags) {\n if (Object.prototype.hasOwnProperty.call(unsanitizedTags, key)) {\n const sanitizedKey = sanitizeTagKey(key);\n tags[sanitizedKey] = sanitizeTagValue(String(unsanitizedTags[key]));\n }\n }\n return tags;\n}\n","import type { DsnComponents, MetricBucketItem, SdkMetadata, StatsdEnvelope, StatsdItem } from '@sentry/types';\nimport { createEnvelope, dsnToString } from '@sentry/utils';\nimport { serializeMetricBuckets } from './utils';\n\n/**\n * Create envelope from a metric aggregate.\n */\nexport function createMetricEnvelope(\n metricBucketItems: Array<MetricBucketItem>,\n dsn?: DsnComponents,\n metadata?: SdkMetadata,\n tunnel?: string,\n): StatsdEnvelope {\n const headers: StatsdEnvelope[0] = {\n sent_at: new Date().toISOString(),\n };\n\n if (metadata && metadata.sdk) {\n headers.sdk = {\n name: metadata.sdk.name,\n version: metadata.sdk.version,\n };\n }\n\n if (!!tunnel && dsn) {\n headers.dsn = dsnToString(dsn);\n }\n\n const item = createMetricEnvelopeItem(metricBucketItems);\n return createEnvelope<StatsdEnvelope>(headers, [item]);\n}\n\nfunction createMetricEnvelopeItem(metricBucketItems: MetricBucketItem[]): StatsdItem {\n const payload = serializeMetricBuckets(metricBucketItems);\n const metricHeaders: StatsdItem[0] = {\n type: 'statsd',\n length: payload.length,\n };\n return [metricHeaders, payload];\n}\n","/* eslint-disable max-lines */\nimport type {\n Breadcrumb,\n BreadcrumbHint,\n Client,\n ClientOptions,\n DataCategory,\n DsnComponents,\n DynamicSamplingContext,\n Envelope,\n ErrorEvent,\n Event,\n EventDropReason,\n EventHint,\n EventProcessor,\n FeedbackEvent,\n Integration,\n IntegrationClass,\n MetricBucketItem,\n MetricsAggregator,\n Outcome,\n ParameterizedString,\n SdkMetadata,\n Session,\n SessionAggregates,\n Severity,\n SeverityLevel,\n StartSpanOptions,\n Transaction,\n TransactionEvent,\n Transport,\n TransportMakeRequestResponse,\n} from '@sentry/types';\nimport {\n SentryError,\n SyncPromise,\n addItemToEnvelope,\n checkOrSetAlreadyCaught,\n createAttachmentEnvelopeItem,\n isParameterizedString,\n isPlainObject,\n isPrimitive,\n isThenable,\n logger,\n makeDsn,\n rejectedSyncPromise,\n resolvedSyncPromise,\n} from '@sentry/utils';\n\nimport { getEnvelopeEndpointWithUrlEncodedAuth } from './api';\nimport { DEBUG_BUILD } from './debug-build';\nimport { createEventEnvelope, createSessionEnvelope } from './envelope';\nimport { getClient } from './exports';\nimport { getIsolationScope } from './hub';\nimport type { IntegrationIndex } from './integration';\nimport { afterSetupIntegrations } from './integration';\nimport { setupIntegration, setupIntegrations } from './integration';\nimport { createMetricEnvelope } from './metrics/envelope';\nimport type { Scope } from './scope';\nimport { updateSession } from './session';\nimport { getDynamicSamplingContextFromClient } from './tracing/dynamicSamplingContext';\nimport { prepareEvent } from './utils/prepareEvent';\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 options\n * specific to the client subclass. To access these options later, use\n * {@link Client.getOptions}.\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, 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<NodeOptions> {\n * public constructor(options: NodeOptions) {\n * super(options);\n * }\n *\n * // ...\n * }\n */\nexport abstract class BaseClient<O extends ClientOptions> implements Client<O> {\n /**\n * A reference to a metrics aggregator\n *\n * @experimental Note this is alpha API. It may experience breaking changes in the future.\n */\n public metricsAggregator?: MetricsAggregator;\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 protected readonly _transport?: Transport;\n\n /** Array of set up integrations. */\n protected _integrations: IntegrationIndex;\n\n /** Indicates whether this client's integrations have been set up. */\n protected _integrationsInitialized: boolean;\n\n /** Number of calls being processed */\n protected _numProcessing: number;\n\n protected _eventProcessors: EventProcessor[];\n\n /** Holds flushable */\n private _outcomes: { [key: string]: number };\n\n // eslint-disable-next-line @typescript-eslint/ban-types\n private _hooks: Record<string, Function[]>;\n\n /**\n * Initializes this client instance.\n *\n * @param options Options for the client.\n */\n protected constructor(options: O) {\n this._options = options;\n this._integrations = {};\n this._integrationsInitialized = false;\n this._numProcessing = 0;\n this._outcomes = {};\n this._hooks = {};\n this._eventProcessors = [];\n\n if (options.dsn) {\n this._dsn = makeDsn(options.dsn);\n } else {\n DEBUG_BUILD && logger.warn('No DSN provided, client will not send events.');\n }\n\n if (this._dsn) {\n const url = getEnvelopeEndpointWithUrlEncodedAuth(this._dsn, options);\n this._transport = options.transport({\n tunnel: this._options.tunnel,\n recordDroppedEvent: this.recordDroppedEvent.bind(this),\n ...options.transportOptions,\n url,\n });\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 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.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(\n message: ParameterizedString,\n // eslint-disable-next-line deprecation/deprecation\n level?: Severity | SeverityLevel,\n hint?: EventHint,\n scope?: Scope,\n ): string | undefined {\n let eventId: string | undefined = hint && hint.event_id;\n\n const eventMessage = isParameterizedString(message) ? message : String(message);\n\n const promisedEvent = isPrimitive(message)\n ? this.eventFromMessage(eventMessage, level, hint)\n : this.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 DEBUG_BUILD && logger.log(ALREADY_SEEN_ERROR);\n return;\n }\n\n let eventId: string | undefined = hint && hint.event_id;\n\n const sdkProcessingMetadata = event.sdkProcessingMetadata || {};\n const capturedSpanScope: Scope | undefined = sdkProcessingMetadata.capturedSpanScope;\n\n this._process(\n this._captureEvent(event, hint, capturedSpanScope || 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 (!(typeof session.release === 'string')) {\n 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 updateSession(session, { 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 * @see SdkMetadata in @sentry/types\n *\n * @return The metadata of the SDK\n */\n public getSdkMetadata(): SdkMetadata | undefined {\n return this._options._metadata;\n }\n\n /**\n * @inheritDoc\n */\n public getTransport(): Transport | undefined {\n return this._transport;\n }\n\n /**\n * @inheritDoc\n */\n public flush(timeout?: number): PromiseLike<boolean> {\n const transport = this._transport;\n if (transport) {\n if (this.metricsAggregator) {\n this.metricsAggregator.flush();\n }\n return this._isClientDoneProcessing(timeout).then(clientFinished => {\n return transport.flush(timeout).then(transportFlushed => clientFinished && transportFlushed);\n });\n } else {\n return resolvedSyncPromise(true);\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 if (this.metricsAggregator) {\n this.metricsAggregator.close();\n }\n return result;\n });\n }\n\n /** Get all installed event processors. */\n public getEventProcessors(): EventProcessor[] {\n return this._eventProcessors;\n }\n\n /** @inheritDoc */\n public addEventProcessor(eventProcessor: EventProcessor): void {\n this._eventProcessors.push(eventProcessor);\n }\n\n /**\n * This is an internal function to setup all integrations that should run on the client.\n * @deprecated Use `client.init()` instead.\n */\n public setupIntegrations(forceInitialize?: boolean): void {\n if ((forceInitialize && !this._integrationsInitialized) || (this._isEnabled() && !this._integrationsInitialized)) {\n this._setupIntegrations();\n }\n }\n\n /** @inheritdoc */\n public init(): void {\n if (this._isEnabled()) {\n this._setupIntegrations();\n }\n }\n\n /**\n * Gets an installed integration by its `id`.\n *\n * @returns The installed integration or `undefined` if no integration with that `id` was installed.\n * @deprecated Use `getIntegrationByName()` instead.\n */\n public getIntegrationById(integrationId: string): Integration | undefined {\n return this.getIntegrationByName(integrationId);\n }\n\n /**\n * Gets an installed integration by its name.\n *\n * @returns The installed integration or `undefined` if no integration with that `name` was installed.\n */\n public getIntegrationByName<T extends Integration = Integration>(integrationName: string): T | undefined {\n return this._integrations[integrationName] as T | undefined;\n }\n\n /**\n * Returns the client's instance of the given integration class, it any.\n * @deprecated Use `getIntegrationByName()` instead.\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 DEBUG_BUILD && logger.warn(`Cannot retrieve integration ${integration.id} from the current Client`);\n return null;\n }\n }\n\n /**\n * @inheritDoc\n */\n public addIntegration(integration: Integration): void {\n const isAlreadyInstalled = this._integrations[integration.name];\n\n // This hook takes care of only installing if not already installed\n setupIntegration(this, integration, this._integrations);\n // Here we need to check manually to make sure to not run this multiple times\n if (!isAlreadyInstalled) {\n afterSetupIntegrations(this, [integration]);\n }\n }\n\n /**\n * @inheritDoc\n */\n public sendEvent(event: Event, hint: EventHint = {}): void {\n this.emit('beforeSendEvent', event, hint);\n\n let env = createEventEnvelope(event, this._dsn, this._options._metadata, this._options.tunnel);\n\n for (const attachment of hint.attachments || []) {\n env = addItemToEnvelope(\n env,\n createAttachmentEnvelopeItem(\n attachment,\n this._options.transportOptions && this._options.transportOptions.textEncoder,\n ),\n );\n }\n\n const promise = this._sendEnvelope(env);\n if (promise) {\n promise.then(sendResponse => this.emit('afterSendEvent', event, sendResponse), null);\n }\n }\n\n /**\n * @inheritDoc\n */\n public sendSession(session: Session | SessionAggregates): void {\n const env = createSessionEnvelope(session, this._dsn, this._options._metadata, this._options.tunnel);\n\n // _sendEnvelope should not throw\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this._sendEnvelope(env);\n }\n\n /**\n * @inheritDoc\n */\n public recordDroppedEvent(reason: EventDropReason, category: DataCategory, _event?: Event): void {\n // Note: we use `event` in replay, where we overwrite this hook.\n\n if (this._options.sendClientReports) {\n // We want to track each category (error, transaction, session, replay_event) 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 // With typescript 4.1 we could even use template literal types\n const key = `${reason}:${category}`;\n DEBUG_BUILD && logger.log(`Adding outcome: \"${key}\"`);\n\n // The following works because undefined + 1 === NaN and NaN is falsy\n this._outcomes[key] = this._outcomes[key] + 1 || 1;\n }\n }\n\n /**\n * @inheritDoc\n */\n public captureAggregateMetrics(metricBucketItems: Array<MetricBucketItem>): void {\n DEBUG_BUILD && logger.log(`Flushing aggregated metrics, number of metrics: ${metricBucketItems.length}`);\n const metricsEnvelope = createMetricEnvelope(\n metricBucketItems,\n this._dsn,\n this._options._metadata,\n this._options.tunnel,\n );\n\n // _sendEnvelope should not throw\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this._sendEnvelope(metricsEnvelope);\n }\n\n // Keep on() & emit() signatures in sync with types' client.ts interface\n /* eslint-disable @typescript-eslint/unified-signatures */\n\n /** @inheritdoc */\n public on(hook: 'startTransaction', callback: (transaction: Transaction) => void): void;\n\n /** @inheritdoc */\n public on(hook: 'finishTransaction', callback: (transaction: Transaction) => void): void;\n\n /** @inheritdoc */\n public on(hook: 'beforeEnvelope', callback: (envelope: Envelope) => void): void;\n\n /** @inheritdoc */\n public on(hook: 'beforeSendEvent', callback: (event: Event, hint?: EventHint) => void): void;\n\n /** @inheritdoc */\n public on(hook: 'preprocessEvent', callback: (event: Event, hint?: EventHint) => void): void;\n\n /** @inheritdoc */\n public on(\n hook: 'afterSendEvent',\n callback: (event: Event, sendResponse: TransportMakeRequestResponse | void) => void,\n ): void;\n\n /** @inheritdoc */\n public on(hook: 'beforeAddBreadcrumb', callback: (breadcrumb: Breadcrumb, hint?: BreadcrumbHint) => void): void;\n\n /** @inheritdoc */\n public on(hook: 'createDsc', callback: (dsc: DynamicSamplingContext) => void): void;\n\n /** @inheritdoc */\n public on(hook: 'otelSpanEnd', callback: (otelSpan: unknown, mutableOptions: { drop: boolean }) => void): void;\n\n /** @inheritdoc */\n public on(\n hook: 'beforeSendFeedback',\n callback: (feedback: FeedbackEvent, options?: { includeReplay: boolean }) => void,\n ): void;\n\n /** @inheritdoc */\n public on(hook: 'startPageLoadSpan', callback: (options: StartSpanOptions) => void): void;\n\n /** @inheritdoc */\n public on(hook: 'startNavigationSpan', callback: (options: StartSpanOptions) => void): void;\n\n /** @inheritdoc */\n public on(hook: string, callback: unknown): void {\n if (!this._hooks[hook]) {\n this._hooks[hook] = [];\n }\n\n // @ts-expect-error We assue the types are correct\n this._hooks[hook].push(callback);\n }\n\n /** @inheritdoc */\n public emit(hook: 'startTransaction', transaction: Transaction): void;\n\n /** @inheritdoc */\n public emit(hook: 'finishTransaction', transaction: Transaction): void;\n\n /** @inheritdoc */\n public emit(hook: 'beforeEnvelope', envelope: Envelope): void;\n\n /** @inheritdoc */\n public emit(hook: 'beforeSendEvent', event: Event, hint?: EventHint): void;\n\n /** @inheritdoc */\n public emit(hook: 'preprocessEvent', event: Event, hint?: EventHint): void;\n\n /** @inheritdoc */\n public emit(hook: 'afterSendEvent', event: Event, sendResponse: TransportMakeRequestResponse | void): void;\n\n /** @inheritdoc */\n public emit(hook: 'beforeAddBreadcrumb', breadcrumb: Breadcrumb, hint?: BreadcrumbHint): void;\n\n /** @inheritdoc */\n public emit(hook: 'createDsc', dsc: DynamicSamplingContext): void;\n\n /** @inheritdoc */\n public emit(hook: 'otelSpanEnd', otelSpan: unknown, mutableOptions: { drop: boolean }): void;\n\n /** @inheritdoc */\n public emit(hook: 'beforeSendFeedback', feedback: FeedbackEvent, options?: { includeReplay: boolean }): void;\n\n /** @inheritdoc */\n public emit(hook: 'startPageLoadSpan', options: StartSpanOptions): void;\n\n /** @inheritdoc */\n public emit(hook: 'startNavigationSpan', options: StartSpanOptions): void;\n\n /** @inheritdoc */\n public emit(hook: string, ...rest: unknown[]): void {\n if (this._hooks[hook]) {\n this._hooks[hook].forEach(callback => callback(...rest));\n }\n }\n\n /* eslint-enable @typescript-eslint/unified-signatures */\n\n /** Setup integrations for this client. */\n protected _setupIntegrations(): void {\n const { integrations } = this._options;\n this._integrations = setupIntegrations(this, integrations);\n afterSetupIntegrations(this, integrations);\n\n // TODO v8: We don't need this flag anymore\n this._integrationsInitialized = true;\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 updateSession(session, {\n ...(crashed && { status: 'crashed' }),\n errors: session.errors || Number(errored || crashed),\n });\n this.captureSession(session);\n }\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 /** Determines whether this SDK is enabled and a transport is present. */\n protected _isEnabled(): boolean {\n return this.getOptions().enabled !== false && this._transport !== 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(\n event: Event,\n hint: EventHint,\n scope?: Scope,\n isolationScope = getIsolationScope(),\n ): PromiseLike<Event | null> {\n const options = this.getOptions();\n const integrations = Object.keys(this._integrations);\n if (!hint.integrations && integrations.length > 0) {\n hint.integrations = integrations;\n }\n\n this.emit('preprocessEvent', event, hint);\n\n return prepareEvent(options, event, hint, scope, this, isolationScope).then(evt => {\n if (evt === null) {\n return evt;\n }\n\n const propagationContext = {\n ...isolationScope.getPropagationContext(),\n ...(scope ? scope.getPropagationContext() : undefined),\n };\n\n const trace = evt.contexts && evt.contexts.trace;\n if (!trace && propagationContext) {\n const { traceId: trace_id, spanId, parentSpanId, dsc } = propagationContext;\n evt.contexts = {\n trace: {\n trace_id,\n span_id: spanId,\n parent_span_id: parentSpanId,\n },\n ...evt.contexts,\n };\n\n const dynamicSamplingContext = dsc ? dsc : getDynamicSamplingContextFromClient(trace_id, this, scope);\n\n evt.sdkProcessingMetadata = {\n dynamicSamplingContext,\n ...evt.sdkProcessingMetadata,\n };\n }\n return evt;\n });\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 if (DEBUG_BUILD) {\n // If something's gone wrong, log the error as a warning. If it's just us having used a `SentryError` for\n // control flow, log just the message (no stack) as a log-level log.\n const sentryError = reason as SentryError;\n if (sentryError.logLevel === 'log') {\n logger.log(sentryError.message);\n } else {\n logger.warn(sentryError);\n }\n }\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 const options = this.getOptions();\n const { sampleRate } = options;\n\n const isTransaction = isTransactionEvent(event);\n const isError = isErrorEvent(event);\n const eventType = event.type || 'error';\n const beforeSendLabel = `before send for type \\`${eventType}\\``;\n\n // 1.0 === 100% events are sent\n // 0.0 === 0% events are sent\n // Sampling for transaction happens somewhere else\n if (isError && typeof sampleRate === 'number' && Math.random() > sampleRate) {\n this.recordDroppedEvent('sample_rate', 'error', event);\n return rejectedSyncPromise(\n new SentryError(\n `Discarding event because it's not included in the random sample (sampling rate = ${sampleRate})`,\n 'log',\n ),\n );\n }\n\n const dataCategory: DataCategory = eventType === 'replay_event' ? 'replay' : eventType;\n\n const sdkProcessingMetadata = event.sdkProcessingMetadata || {};\n const capturedSpanIsolationScope: Scope | undefined = sdkProcessingMetadata.capturedSpanIsolationScope;\n\n return this._prepareEvent(event, hint, scope, capturedSpanIsolationScope)\n .then(prepared => {\n if (prepared === null) {\n this.recordDroppedEvent('event_processor', dataCategory, event);\n throw new SentryError('An event processor returned `null`, will not send event.', 'log');\n }\n\n const isInternalException = hint.data && (hint.data as { __sentry__: boolean }).__sentry__ === true;\n if (isInternalException) {\n return prepared;\n }\n\n const result = processBeforeSend(options, prepared, hint);\n return _validateBeforeSendResult(result, beforeSendLabel);\n })\n .then(processedEvent => {\n if (processedEvent === null) {\n this.recordDroppedEvent('before_send', dataCategory, event);\n throw new SentryError(`${beforeSendLabel} returned \\`null\\`, will not send event.`, 'log');\n }\n\n const session = scope && scope.getSession();\n if (!isTransaction && session) {\n this._updateSessionFromEvent(session, processedEvent);\n }\n\n // None of the Sentry built event processor will update transaction name,\n // so if the transaction name has been changed by an event processor, we know\n // it has to come from custom event processor added by a user\n const transactionInfo = processedEvent.transaction_info;\n if (isTransaction && transactionInfo && processedEvent.transaction !== event.transaction) {\n const source = 'custom';\n processedEvent.transaction_info = {\n ...transactionInfo,\n source,\n };\n }\n\n this.sendEvent(processedEvent, hint);\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,\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++;\n void promise.then(\n value => {\n this._numProcessing--;\n return value;\n },\n reason => {\n this._numProcessing--;\n return reason;\n },\n );\n }\n\n /**\n * @inheritdoc\n */\n protected _sendEnvelope(envelope: Envelope): PromiseLike<void | TransportMakeRequestResponse> | void {\n this.emit('beforeEnvelope', envelope);\n\n if (this._isEnabled() && this._transport) {\n return this._transport.send(envelope).then(null, reason => {\n DEBUG_BUILD && logger.error('Error while sending event:', reason);\n });\n } else {\n DEBUG_BUILD && logger.error('Transport disabled');\n }\n }\n\n /**\n * Clears outcomes on this client and returns them.\n */\n protected _clearOutcomes(): Outcome[] {\n const outcomes = this._outcomes;\n this._outcomes = {};\n return Object.keys(outcomes).map(key => {\n const [reason, category] = key.split(':') as [EventDropReason, DataCategory];\n return {\n reason,\n category,\n quantity: outcomes[key],\n };\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 abstract eventFromException(_exception: any, _hint?: EventHint): PromiseLike<Event>;\n\n /**\n * @inheritDoc\n */\n public abstract eventFromMessage(\n _message: ParameterizedString,\n // eslint-disable-next-line deprecation/deprecation\n _level?: Severity | SeverityLevel,\n _hint?: EventHint,\n ): PromiseLike<Event>;\n}\n\n/**\n * Verifies that return value of configured `beforeSend` or `beforeSendTransaction` is of expected type, and returns the value if so.\n */\nfunction _validateBeforeSendResult(\n beforeSendResult: PromiseLike<Event | null> | Event | null,\n beforeSendLabel: string,\n): PromiseLike<Event | null> | Event | null {\n const invalidValueError = `${beforeSendLabel} must return \\`null\\` or a valid event.`;\n if (isThenable(beforeSendResult)) {\n return beforeSendResult.then(\n event => {\n if (!isPlainObject(event) && event !== null) {\n throw new SentryError(invalidValueError);\n }\n return event;\n },\n e => {\n throw new SentryError(`${beforeSendLabel} rejected with ${e}`);\n },\n );\n } else if (!isPlainObject(beforeSendResult) && beforeSendResult !== null) {\n throw new SentryError(invalidValueError);\n }\n return beforeSendResult;\n}\n\n/**\n * Process the matching `beforeSendXXX` callback.\n */\nfunction processBeforeSend(\n options: ClientOptions,\n event: Event,\n hint: EventHint,\n): PromiseLike<Event | null> | Event | null {\n const { beforeSend, beforeSendTransaction } = options;\n\n if (isErrorEvent(event) && beforeSend) {\n return beforeSend(event, hint);\n }\n\n if (isTransactionEvent(event) && beforeSendTransaction) {\n return beforeSendTransaction(event, hint);\n }\n\n return event;\n}\n\nfunction isErrorEvent(event: Event): event is ErrorEvent {\n return event.type === undefined;\n}\n\nfunction isTransactionEvent(event: Event): event is TransactionEvent {\n return event.type === 'transaction';\n}\n\n/**\n * Add an event processor to the current client.\n * This event processor will run for all events processed by this client.\n */\nexport function addEventProcessor(callback: EventProcessor): void {\n const client = getClient();\n\n if (!client || !client.addEventProcessor) {\n return;\n }\n\n client.addEventProcessor(callback);\n}\n","import type { Client, ClientOptions } from '@sentry/types';\nimport { consoleSandbox, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from './debug-build';\nimport { getCurrentScope } from './exports';\nimport { getCurrentHub } from './hub';\n\n/** A class object that can instantiate Client objects. */\nexport type ClientClass<F extends Client, O extends ClientOptions> = 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 ClientOptions>(\n clientClass: ClientClass<F, O>,\n options: O,\n): void {\n if (options.debug === true) {\n if (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 consoleSandbox(() => {\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 }\n const scope = getCurrentScope();\n scope.update(options.initialScope);\n\n const client = new clientClass(options);\n setCurrentClient(client);\n initializeClient(client);\n}\n\n/**\n * Make the given client the current client.\n */\nexport function setCurrentClient(client: Client): void {\n // eslint-disable-next-line deprecation/deprecation\n const hub = getCurrentHub();\n // eslint-disable-next-line deprecation/deprecation\n const top = hub.getStackTop();\n top.client = client;\n top.scope.setClient(client);\n}\n\n/**\n * Initialize the client for the current scope.\n * Make sure to call this after `setCurrentClient()`.\n */\nfunction initializeClient(client: Client): void {\n if (client.init) {\n client.init();\n // TODO v8: Remove this fallback\n // eslint-disable-next-line deprecation/deprecation\n } else if (client.setupIntegrations) {\n // eslint-disable-next-line deprecation/deprecation\n client.setupIntegrations();\n }\n}\n","import type {\n Envelope,\n EnvelopeItem,\n EnvelopeItemType,\n Event,\n EventDropReason,\n EventItem,\n InternalBaseTransportOptions,\n Transport,\n TransportMakeRequestResponse,\n TransportRequestExecutor,\n} from '@sentry/types';\nimport type { PromiseBuffer, RateLimits } from '@sentry/utils';\nimport {\n SentryError,\n createEnvelope,\n envelopeItemTypeToDataCategory,\n forEachEnvelopeItem,\n isRateLimited,\n logger,\n makePromiseBuffer,\n resolvedSyncPromise,\n serializeEnvelope,\n updateRateLimits,\n} from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\n\nexport const DEFAULT_TRANSPORT_BUFFER_SIZE = 30;\n\n/**\n * Creates an instance of a Sentry `Transport`\n *\n * @param options\n * @param makeRequest\n */\nexport function createTransport(\n options: InternalBaseTransportOptions,\n makeRequest: TransportRequestExecutor,\n buffer: PromiseBuffer<void | TransportMakeRequestResponse> = makePromiseBuffer(\n options.bufferSize || DEFAULT_TRANSPORT_BUFFER_SIZE,\n ),\n): Transport {\n let rateLimits: RateLimits = {};\n const flush = (timeout?: number): PromiseLike<boolean> => buffer.drain(timeout);\n\n function send(envelope: Envelope): PromiseLike<void | TransportMakeRequestResponse> {\n const filteredEnvelopeItems: EnvelopeItem[] = [];\n\n // Drop rate limited items from envelope\n forEachEnvelopeItem(envelope, (item, type) => {\n const dataCategory = envelopeItemTypeToDataCategory(type);\n if (isRateLimited(rateLimits, dataCategory)) {\n const event: Event | undefined = getEventForEnvelopeItem(item, type);\n options.recordDroppedEvent('ratelimit_backoff', dataCategory, event);\n } else {\n filteredEnvelopeItems.push(item);\n }\n });\n\n // Skip sending if envelope is empty after filtering out rate limited events\n if (filteredEnvelopeItems.length === 0) {\n return resolvedSyncPromise();\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const filteredEnvelope: Envelope = createEnvelope(envelope[0], filteredEnvelopeItems as any);\n\n // Creates client report for each item in an envelope\n const recordEnvelopeLoss = (reason: EventDropReason): void => {\n forEachEnvelopeItem(filteredEnvelope, (item, type) => {\n const event: Event | undefined = getEventForEnvelopeItem(item, type);\n options.recordDroppedEvent(reason, envelopeItemTypeToDataCategory(type), event);\n });\n };\n\n const requestTask = (): PromiseLike<void | TransportMakeRequestResponse> =>\n makeRequest({ body: serializeEnvelope(filteredEnvelope, options.textEncoder) }).then(\n response => {\n // We don't want to throw on NOK responses, but we want to at least log them\n if (response.statusCode !== undefined && (response.statusCode < 200 || response.statusCode >= 300)) {\n DEBUG_BUILD && logger.warn(`Sentry responded with status code ${response.statusCode} to sent event.`);\n }\n\n rateLimits = updateRateLimits(rateLimits, response);\n return response;\n },\n error => {\n recordEnvelopeLoss('network_error');\n throw error;\n },\n );\n\n return buffer.add(requestTask).then(\n result => result,\n error => {\n if (error instanceof SentryError) {\n DEBUG_BUILD && logger.error('Skipped sending event because buffer is full.');\n recordEnvelopeLoss('queue_overflow');\n return resolvedSyncPromise();\n } else {\n throw error;\n }\n },\n );\n }\n\n // We use this to identifify if the transport is the base transport\n // TODO (v8): Remove this again as we'll no longer need it\n send.__sentry__baseTransport__ = true;\n\n return {\n send,\n flush,\n };\n}\n\nfunction getEventForEnvelopeItem(item: Envelope[1][number], type: EnvelopeItemType): Event | undefined {\n if (type !== 'event' && type !== 'transaction') {\n return undefined;\n }\n\n return Array.isArray(item) ? (item as EventItem)[1] : undefined;\n}\n","import type {\n BaseTransportOptions,\n Envelope,\n EnvelopeItemType,\n Event,\n EventItem,\n Transport,\n TransportMakeRequestResponse,\n} from '@sentry/types';\nimport { createEnvelope, dsnFromString, forEachEnvelopeItem } from '@sentry/utils';\n\nimport { getEnvelopeEndpointWithUrlEncodedAuth } from '../api';\n\ninterface MatchParam {\n /** The envelope to be sent */\n envelope: Envelope;\n /**\n * A function that returns an event from the envelope if one exists. You can optionally pass an array of envelope item\n * types to filter by - only envelopes matching the given types will be multiplexed.\n * Allowed values are: 'event', 'transaction', 'profile', 'replay_event'\n *\n * @param types Defaults to ['event']\n */\n getEvent(types?: EnvelopeItemType[]): Event | undefined;\n}\n\ntype RouteTo = { dsn: string; release: string };\ntype Matcher = (param: MatchParam) => (string | RouteTo)[];\n\n/**\n * Gets an event from an envelope.\n *\n * This is only exported for use in the tests\n */\nexport function eventFromEnvelope(env: Envelope, types: EnvelopeItemType[]): Event | undefined {\n let event: Event | undefined;\n\n forEachEnvelopeItem(env, (item, type) => {\n if (types.includes(type)) {\n event = Array.isArray(item) ? (item as EventItem)[1] : undefined;\n }\n // bail out if we found an event\n return !!event;\n });\n\n return event;\n}\n\n/**\n * Creates a transport that overrides the release on all events.\n */\nfunction makeOverrideReleaseTransport<TO extends BaseTransportOptions>(\n createTransport: (options: TO) => Transport,\n release: string,\n): (options: TO) => Transport {\n return options => {\n const transport = createTransport(options);\n\n return {\n ...transport,\n send: async (envelope: Envelope): Promise<void | TransportMakeRequestResponse> => {\n const event = eventFromEnvelope(envelope, ['event', 'transaction', 'profile', 'replay_event']);\n\n if (event) {\n event.release = release;\n }\n return transport.send(envelope);\n },\n };\n };\n}\n\n/** Overrides the DSN in the envelope header */\nfunction overrideDsn(envelope: Envelope, dsn: string): Envelope {\n return createEnvelope(\n dsn\n ? {\n ...envelope[0],\n dsn,\n }\n : envelope[0],\n envelope[1],\n );\n}\n\n/**\n * Creates a transport that can send events to different DSNs depending on the envelope contents.\n */\nexport function makeMultiplexedTransport<TO extends BaseTransportOptions>(\n createTransport: (options: TO) => Transport,\n matcher: Matcher,\n): (options: TO) => Transport {\n return options => {\n const fallbackTransport = createTransport(options);\n const otherTransports = new Map<string, Transport>();\n\n function getTransport(dsn: string, release: string | undefined): [string, Transport] | undefined {\n // We create a transport for every unique dsn/release combination as there may be code from multiple releases in\n // use at the same time\n const key = release ? `${dsn}:${release}` : dsn;\n\n let transport = otherTransports.get(key);\n\n if (!transport) {\n const validatedDsn = dsnFromString(dsn);\n if (!validatedDsn) {\n return undefined;\n }\n\n const url = getEnvelopeEndpointWithUrlEncodedAuth(validatedDsn, options.tunnel);\n\n transport = release\n ? makeOverrideReleaseTransport(createTransport, release)({ ...options, url })\n : createTransport({ ...options, url });\n\n otherTransports.set(key, transport);\n }\n\n return [dsn, transport];\n }\n\n async function send(envelope: Envelope): Promise<void | TransportMakeRequestResponse> {\n function getEvent(types?: EnvelopeItemType[]): Event | undefined {\n const eventTypes: EnvelopeItemType[] = types && types.length ? types : ['event'];\n return eventFromEnvelope(envelope, eventTypes);\n }\n\n const transports = matcher({ envelope, getEvent })\n .map(result => {\n if (typeof result === 'string') {\n return getTransport(result, undefined);\n } else {\n return getTransport(result.dsn, result.release);\n }\n })\n .filter((t): t is [string, Transport] => !!t);\n\n // If we have no transports to send to, use the fallback transport\n if (transports.length === 0) {\n // Don't override the DSN in the header for the fallback transport. '' is falsy\n transports.push(['', fallbackTransport]);\n }\n\n const results = await Promise.all(\n transports.map(([dsn, transport]) => transport.send(overrideDsn(envelope, dsn))),\n );\n\n return results[0];\n }\n\n async function flush(timeout: number | undefined): Promise<boolean> {\n const promises = [await fallbackTransport.flush(timeout)];\n for (const [, transport] of otherTransports) {\n promises.push(await transport.flush(timeout));\n }\n\n return promises.every(r => r);\n }\n\n return {\n send,\n flush,\n };\n };\n}\n","import type { ParameterizedString } from '@sentry/types';\n\n/**\n * Tagged template function which returns paramaterized representation of the message\n * For example: parameterize`This is a log statement with ${x} and ${y} params`, would return:\n * \"__sentry_template_string__\": 'This is a log statement with %s and %s params',\n * \"__sentry_template_values__\": ['first', 'second']\n * @param strings An array of string values splitted between expressions\n * @param values Expressions extracted from template string\n * @returns String with template information in __sentry_template_string__ and __sentry_template_values__ properties\n */\nexport function parameterize(strings: TemplateStringsArray, ...values: string[]): ParameterizedString {\n const formatted = new String(String.raw(strings, ...values)) as ParameterizedString;\n formatted.__sentry_template_string__ = strings.join('\\x00').replace(/%/g, '%%').replace(/\\0/g, '%s');\n formatted.__sentry_template_values__ = values;\n return formatted;\n}\n","import type { Event, StackParser } from '@sentry/types';\nimport { GLOBAL_OBJ } from '@sentry/utils';\n\n/** Keys are source filename/url, values are metadata objects. */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst filenameMetadataMap = new Map<string, any>();\n/** Set of stack strings that have already been parsed. */\nconst parsedStacks = new Set<string>();\n\nfunction ensureMetadataStacksAreParsed(parser: StackParser): void {\n if (!GLOBAL_OBJ._sentryModuleMetadata) {\n return;\n }\n\n for (const stack of Object.keys(GLOBAL_OBJ._sentryModuleMetadata)) {\n const metadata = GLOBAL_OBJ._sentryModuleMetadata[stack];\n\n if (parsedStacks.has(stack)) {\n continue;\n }\n\n // Ensure this stack doesn't get parsed again\n parsedStacks.add(stack);\n\n const frames = parser(stack);\n\n // Go through the frames starting from the top of the stack and find the first one with a filename\n for (const frame of frames.reverse()) {\n if (frame.filename) {\n // Save the metadata for this filename\n filenameMetadataMap.set(frame.filename, metadata);\n break;\n }\n }\n }\n}\n\n/**\n * Retrieve metadata for a specific JavaScript file URL.\n *\n * Metadata is injected by the Sentry bundler plugins using the `_experiments.moduleMetadata` config option.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function getMetadataForUrl(parser: StackParser, filename: string): any | undefined {\n ensureMetadataStacksAreParsed(parser);\n return filenameMetadataMap.get(filename);\n}\n\n/**\n * Adds metadata to stack frames.\n *\n * Metadata is injected by the Sentry bundler plugins using the `_experiments.moduleMetadata` config option.\n */\nexport function addMetadataToStackFrames(parser: StackParser, event: Event): void {\n try {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n event.exception!.values!.forEach(exception => {\n if (!exception.stacktrace) {\n return;\n }\n\n for (const frame of exception.stacktrace.frames || []) {\n if (!frame.filename) {\n continue;\n }\n\n const metadata = getMetadataForUrl(parser, frame.filename);\n\n if (metadata) {\n frame.module_metadata = metadata;\n }\n }\n });\n } catch (_) {\n // To save bundle size we're just try catching here instead of checking for the existence of all the different objects.\n }\n}\n\n/**\n * Strips metadata from stack frames.\n */\nexport function stripMetadataFromStackFrames(event: Event): void {\n try {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n event.exception!.values!.forEach(exception => {\n if (!exception.stacktrace) {\n return;\n }\n\n for (const frame of exception.stacktrace.frames || []) {\n delete frame.module_metadata;\n }\n });\n } catch (_) {\n // To save bundle size we're just try catching here instead of checking for the existence of all the different objects.\n }\n}\n","import type { Client, Event, EventHint, EventItem, Integration, IntegrationClass, IntegrationFn } from '@sentry/types';\nimport { forEachEnvelopeItem } from '@sentry/utils';\nimport { convertIntegrationFnToClass, defineIntegration } from '../integration';\n\nimport { addMetadataToStackFrames, stripMetadataFromStackFrames } from '../metadata';\n\nconst INTEGRATION_NAME = 'ModuleMetadata';\n\nconst _moduleMetadataIntegration = (() => {\n return {\n name: INTEGRATION_NAME,\n // TODO v8: Remove this\n setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function\n setup(client) {\n if (typeof client.on !== 'function') {\n return;\n }\n\n // We need to strip metadata from stack frames before sending them to Sentry since these are client side only.\n client.on('beforeEnvelope', envelope => {\n forEachEnvelopeItem(envelope, (item, type) => {\n if (type === 'event') {\n const event = Array.isArray(item) ? (item as EventItem)[1] : undefined;\n\n if (event) {\n stripMetadataFromStackFrames(event);\n item[1] = event;\n }\n }\n });\n });\n },\n\n processEvent(event, _hint, client) {\n const stackParser = client.getOptions().stackParser;\n addMetadataToStackFrames(stackParser, event);\n return event;\n },\n };\n}) satisfies IntegrationFn;\n\nexport const moduleMetadataIntegration = defineIntegration(_moduleMetadataIntegration);\n\n/**\n * Adds module metadata to stack frames.\n *\n * Metadata can be injected by the Sentry bundler plugins using the `_experiments.moduleMetadata` config option.\n *\n * When this integration is added, the metadata passed to the bundler plugin is added to the stack frames of all events\n * under the `module_metadata` property. This can be used to help in tagging or routing of events from different teams\n * our sources\n *\n * @deprecated Use `moduleMetadataIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const ModuleMetadata = convertIntegrationFnToClass(\n INTEGRATION_NAME,\n moduleMetadataIntegration,\n) as IntegrationClass<\n Integration & {\n setup: (client: Client) => void;\n processEvent: (event: Event, hint: EventHint, client: Client) => Event;\n }\n>;\n","import type { Client, Event, EventHint, Integration, IntegrationClass, IntegrationFn, StackFrame } from '@sentry/types';\nimport { getEventDescription, logger, stringMatchesSomePattern } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport { convertIntegrationFnToClass, defineIntegration } from '../integration';\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 = [\n /^Script error\\.?$/,\n /^Javascript error: Script error\\.? on line 0$/,\n /^ResizeObserver loop completed with undelivered notifications.$/,\n /^Cannot redefine property: googletag$/,\n];\n\nconst DEFAULT_IGNORE_TRANSACTIONS = [\n /^.*\\/healthcheck$/,\n /^.*\\/healthy$/,\n /^.*\\/live$/,\n /^.*\\/ready$/,\n /^.*\\/heartbeat$/,\n /^.*\\/health$/,\n /^.*\\/healthz$/,\n];\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 ignoreTransactions: Array<string | RegExp>;\n ignoreInternal: boolean;\n disableErrorDefaults: boolean;\n disableTransactionDefaults: boolean;\n}\n\nconst INTEGRATION_NAME = 'InboundFilters';\nconst _inboundFiltersIntegration = ((options: Partial<InboundFiltersOptions> = {}) => {\n return {\n name: INTEGRATION_NAME,\n // TODO v8: Remove this\n setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function\n processEvent(event, _hint, client) {\n const clientOptions = client.getOptions();\n const mergedOptions = _mergeOptions(options, clientOptions);\n return _shouldDropEvent(event, mergedOptions) ? null : event;\n },\n };\n}) satisfies IntegrationFn;\n\nexport const inboundFiltersIntegration = defineIntegration(_inboundFiltersIntegration);\n\n/**\n * Inbound filters configurable by the user.\n * @deprecated Use `inboundFiltersIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const InboundFilters = convertIntegrationFnToClass(\n INTEGRATION_NAME,\n inboundFiltersIntegration,\n) as IntegrationClass<Integration & { preprocessEvent: (event: Event, hint: EventHint, client: Client) => void }> & {\n new (\n options?: Partial<{\n allowUrls: Array<string | RegExp>;\n denyUrls: Array<string | RegExp>;\n ignoreErrors: Array<string | RegExp>;\n ignoreTransactions: Array<string | RegExp>;\n ignoreInternal: boolean;\n disableErrorDefaults: boolean;\n disableTransactionDefaults: boolean;\n }>,\n ): Integration;\n};\n\nfunction _mergeOptions(\n internalOptions: Partial<InboundFiltersOptions> = {},\n clientOptions: Partial<InboundFiltersOptions> = {},\n): Partial<InboundFiltersOptions> {\n return {\n allowUrls: [...(internalOptions.allowUrls || []), ...(clientOptions.allowUrls || [])],\n denyUrls: [...(internalOptions.denyUrls || []), ...(clientOptions.denyUrls || [])],\n ignoreErrors: [\n ...(internalOptions.ignoreErrors || []),\n ...(clientOptions.ignoreErrors || []),\n ...(internalOptions.disableErrorDefaults ? [] : DEFAULT_IGNORE_ERRORS),\n ],\n ignoreTransactions: [\n ...(internalOptions.ignoreTransactions || []),\n ...(clientOptions.ignoreTransactions || []),\n ...(internalOptions.disableTransactionDefaults ? [] : DEFAULT_IGNORE_TRANSACTIONS),\n ],\n ignoreInternal: internalOptions.ignoreInternal !== undefined ? internalOptions.ignoreInternal : true,\n };\n}\n\nfunction _shouldDropEvent(event: Event, options: Partial<InboundFiltersOptions>): boolean {\n if (options.ignoreInternal && _isSentryError(event)) {\n 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 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 (_isIgnoredTransaction(event, options.ignoreTransactions)) {\n DEBUG_BUILD &&\n logger.warn(\n `Event dropped due to being matched by \\`ignoreTransactions\\` option.\\nEvent: ${getEventDescription(event)}`,\n );\n return true;\n }\n if (_isDeniedUrl(event, options.denyUrls)) {\n 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 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 event.type, this is not an error\n if (event.type || !ignoreErrors || !ignoreErrors.length) {\n return false;\n }\n\n return _getPossibleEventMessages(event).some(message => stringMatchesSomePattern(message, ignoreErrors));\n}\n\nfunction _isIgnoredTransaction(event: Event, ignoreTransactions?: Array<string | RegExp>): boolean {\n if (event.type !== 'transaction' || !ignoreTransactions || !ignoreTransactions.length) {\n return false;\n }\n\n const name = event.transaction;\n return name ? stringMatchesSomePattern(name, ignoreTransactions) : false;\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 : stringMatchesSomePattern(url, denyUrls);\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 : stringMatchesSomePattern(url, allowUrls);\n}\n\nfunction _getPossibleEventMessages(event: Event): string[] {\n const possibleMessages: string[] = [];\n\n if (event.message) {\n possibleMessages.push(event.message);\n }\n\n let lastException;\n try {\n // @ts-expect-error Try catching to save bundle size\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n lastException = event.exception.values[event.exception.values.length - 1];\n } catch (e) {\n // try catching to save bundle size checking existence of variables\n }\n\n if (lastException) {\n if (lastException.value) {\n possibleMessages.push(lastException.value);\n if (lastException.type) {\n possibleMessages.push(`${lastException.type}: ${lastException.value}`);\n }\n }\n }\n\n if (DEBUG_BUILD && possibleMessages.length === 0) {\n logger.error(`Could not extract message for event ${getEventDescription(event)}`);\n }\n\n return possibleMessages;\n}\n\nfunction _isSentryError(event: Event): boolean {\n try {\n // @ts-expect-error 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 let frames;\n try {\n // @ts-expect-error 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 DEBUG_BUILD && logger.error(`Cannot extract url for event ${getEventDescription(event)}`);\n return null;\n }\n}\n","import type { Client, Integration, IntegrationClass, IntegrationFn, WrappedFunction } from '@sentry/types';\nimport { getOriginalFunction } from '@sentry/utils';\nimport { getClient } from '../exports';\nimport { convertIntegrationFnToClass, defineIntegration } from '../integration';\n\nlet originalFunctionToString: () => void;\n\nconst INTEGRATION_NAME = 'FunctionToString';\n\nconst SETUP_CLIENTS = new WeakMap<Client, boolean>();\n\nconst _functionToStringIntegration = (() => {\n return {\n name: INTEGRATION_NAME,\n setupOnce() {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n originalFunctionToString = Function.prototype.toString;\n\n // intrinsics (like Function.prototype) might be immutable in some environments\n // e.g. Node with --frozen-intrinsics, XS (an embedded JavaScript engine) or SES (a JavaScript proposal)\n try {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n Function.prototype.toString = function (this: WrappedFunction, ...args: any[]): string {\n const originalFunction = getOriginalFunction(this);\n const context =\n SETUP_CLIENTS.has(getClient() as Client) && originalFunction !== undefined ? originalFunction : this;\n return originalFunctionToString.apply(context, args);\n };\n } catch {\n // ignore errors here, just don't patch this\n }\n },\n setup(client) {\n SETUP_CLIENTS.set(client, true);\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Patch toString calls to return proper name for wrapped functions.\n *\n * ```js\n * Sentry.init({\n * integrations: [\n * functionToStringIntegration(),\n * ],\n * });\n * ```\n */\nexport const functionToStringIntegration = defineIntegration(_functionToStringIntegration);\n\n/**\n * Patch toString calls to return proper name for wrapped functions.\n *\n * @deprecated Use `functionToStringIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const FunctionToString = convertIntegrationFnToClass(\n INTEGRATION_NAME,\n functionToStringIntegration,\n) as IntegrationClass<Integration & { setupOnce: () => void }>;\n\n// eslint-disable-next-line deprecation/deprecation\nexport type FunctionToString = typeof FunctionToString;\n","export const COUNTER_METRIC_TYPE = 'c' as const;\nexport const GAUGE_METRIC_TYPE = 'g' as const;\nexport const SET_METRIC_TYPE = 's' as const;\nexport const DISTRIBUTION_METRIC_TYPE = 'd' as const;\n\n/**\n * This does not match spec in https://develop.sentry.dev/sdk/metrics\n * but was chosen to optimize for the most common case in browser environments.\n */\nexport const DEFAULT_BROWSER_FLUSH_INTERVAL = 5000;\n\n/**\n * SDKs are required to bucket into 10 second intervals (rollup in seconds)\n * which is the current lower bound of metric accuracy.\n */\nexport const DEFAULT_FLUSH_INTERVAL = 10000;\n\n/**\n * The maximum number of metrics that should be stored in memory.\n */\nexport const MAX_WEIGHT = 10000;\n","import type { MetricInstance } from '@sentry/types';\nimport { COUNTER_METRIC_TYPE, DISTRIBUTION_METRIC_TYPE, GAUGE_METRIC_TYPE, SET_METRIC_TYPE } from './constants';\nimport { simpleHash } from './utils';\n\n/**\n * A metric instance representing a counter.\n */\nexport class CounterMetric implements MetricInstance {\n public constructor(private _value: number) {}\n\n /** @inheritDoc */\n public get weight(): number {\n return 1;\n }\n\n /** @inheritdoc */\n public add(value: number): void {\n this._value += value;\n }\n\n /** @inheritdoc */\n public toString(): string {\n return `${this._value}`;\n }\n}\n\n/**\n * A metric instance representing a gauge.\n */\nexport class GaugeMetric implements MetricInstance {\n private _last: number;\n private _min: number;\n private _max: number;\n private _sum: number;\n private _count: number;\n\n public constructor(value: number) {\n this._last = value;\n this._min = value;\n this._max = value;\n this._sum = value;\n this._count = 1;\n }\n\n /** @inheritDoc */\n public get weight(): number {\n return 5;\n }\n\n /** @inheritdoc */\n public add(value: number): void {\n this._last = value;\n if (value < this._min) {\n this._min = value;\n }\n if (value > this._max) {\n this._max = value;\n }\n this._sum += value;\n this._count++;\n }\n\n /** @inheritdoc */\n public toString(): string {\n return `${this._last}:${this._min}:${this._max}:${this._sum}:${this._count}`;\n }\n}\n\n/**\n * A metric instance representing a distribution.\n */\nexport class DistributionMetric implements MetricInstance {\n private _value: number[];\n\n public constructor(first: number) {\n this._value = [first];\n }\n\n /** @inheritDoc */\n public get weight(): number {\n return this._value.length;\n }\n\n /** @inheritdoc */\n public add(value: number): void {\n this._value.push(value);\n }\n\n /** @inheritdoc */\n public toString(): string {\n return this._value.join(':');\n }\n}\n\n/**\n * A metric instance representing a set.\n */\nexport class SetMetric implements MetricInstance {\n private _value: Set<number | string>;\n\n public constructor(public first: number | string) {\n this._value = new Set([first]);\n }\n\n /** @inheritDoc */\n public get weight(): number {\n return this._value.size;\n }\n\n /** @inheritdoc */\n public add(value: number | string): void {\n this._value.add(value);\n }\n\n /** @inheritdoc */\n public toString(): string {\n return Array.from(this._value)\n .map(val => (typeof val === 'string' ? simpleHash(val) : val))\n .join(':');\n }\n}\n\nexport const METRIC_MAP = {\n [COUNTER_METRIC_TYPE]: CounterMetric,\n [GAUGE_METRIC_TYPE]: GaugeMetric,\n [DISTRIBUTION_METRIC_TYPE]: DistributionMetric,\n [SET_METRIC_TYPE]: SetMetric,\n};\n","import type { Client, ClientOptions, MeasurementUnit, MetricsAggregator, Primitive } from '@sentry/types';\nimport { timestampInSeconds } from '@sentry/utils';\nimport { DEFAULT_BROWSER_FLUSH_INTERVAL, SET_METRIC_TYPE } from './constants';\nimport { METRIC_MAP } from './instance';\nimport { updateMetricSummaryOnActiveSpan } from './metric-summary';\nimport type { MetricBucket, MetricType } from './types';\nimport { getBucketKey, sanitizeMetricKey, sanitizeTags, sanitizeUnit } from './utils';\n\n/**\n * A simple metrics aggregator that aggregates metrics in memory and flushes them periodically.\n * Default flush interval is 5 seconds.\n *\n * @experimental This API is experimental and might change in the future.\n */\nexport class BrowserMetricsAggregator implements MetricsAggregator {\n // TODO(@anonrig): Use FinalizationRegistry to have a proper way of flushing the buckets\n // when the aggregator is garbage collected.\n // Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry\n private _buckets: MetricBucket;\n private readonly _interval: ReturnType<typeof setInterval>;\n\n public constructor(private readonly _client: Client<ClientOptions>) {\n this._buckets = new Map();\n this._interval = setInterval(() => this.flush(), DEFAULT_BROWSER_FLUSH_INTERVAL);\n }\n\n /**\n * @inheritDoc\n */\n public add(\n metricType: MetricType,\n unsanitizedName: string,\n value: number | string,\n unsanitizedUnit: MeasurementUnit | undefined = 'none',\n unsanitizedTags: Record<string, Primitive> | undefined = {},\n maybeFloatTimestamp: number | undefined = timestampInSeconds(),\n ): void {\n const timestamp = Math.floor(maybeFloatTimestamp);\n const name = sanitizeMetricKey(unsanitizedName);\n const tags = sanitizeTags(unsanitizedTags);\n const unit = sanitizeUnit(unsanitizedUnit as string);\n\n const bucketKey = getBucketKey(metricType, name, unit, tags);\n\n let bucketItem = this._buckets.get(bucketKey);\n // If this is a set metric, we need to calculate the delta from the previous weight.\n const previousWeight = bucketItem && metricType === SET_METRIC_TYPE ? bucketItem.metric.weight : 0;\n\n if (bucketItem) {\n bucketItem.metric.add(value);\n // TODO(abhi): Do we need this check?\n if (bucketItem.timestamp < timestamp) {\n bucketItem.timestamp = timestamp;\n }\n } else {\n bucketItem = {\n // @ts-expect-error we don't need to narrow down the type of value here, saves bundle size.\n metric: new METRIC_MAP[metricType](value),\n timestamp,\n metricType,\n name,\n unit,\n tags,\n };\n this._buckets.set(bucketKey, bucketItem);\n }\n\n // If value is a string, it's a set metric so calculate the delta from the previous weight.\n const val = typeof value === 'string' ? bucketItem.metric.weight - previousWeight : value;\n updateMetricSummaryOnActiveSpan(metricType, name, val, unit, unsanitizedTags, bucketKey);\n }\n\n /**\n * @inheritDoc\n */\n public flush(): void {\n // short circuit if buckets are empty.\n if (this._buckets.size === 0) {\n return;\n }\n\n if (this._client.captureAggregateMetrics) {\n // TODO(@anonrig): Use Object.values() when we support ES6+\n const metricBuckets = Array.from(this._buckets).map(([, bucketItem]) => bucketItem);\n this._client.captureAggregateMetrics(metricBuckets);\n }\n\n this._buckets.clear();\n }\n\n /**\n * @inheritDoc\n */\n public close(): void {\n clearInterval(this._interval);\n this.flush();\n }\n}\n","import type { Client, ClientOptions, Integration, IntegrationClass, IntegrationFn } from '@sentry/types';\nimport type { BaseClient } from '../baseclient';\nimport { convertIntegrationFnToClass, defineIntegration } from '../integration';\nimport { BrowserMetricsAggregator } from './browser-aggregator';\n\nconst INTEGRATION_NAME = 'MetricsAggregator';\n\nconst _metricsAggregatorIntegration = (() => {\n return {\n name: INTEGRATION_NAME,\n // TODO v8: Remove this\n setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function\n setup(client: BaseClient<ClientOptions>) {\n client.metricsAggregator = new BrowserMetricsAggregator(client);\n },\n };\n}) satisfies IntegrationFn;\n\nexport const metricsAggregatorIntegration = defineIntegration(_metricsAggregatorIntegration);\n\n/**\n * Enables Sentry metrics monitoring.\n *\n * @experimental This API is experimental and might having breaking changes in the future.\n * @deprecated Use `metricsAggegratorIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const MetricsAggregator = convertIntegrationFnToClass(\n INTEGRATION_NAME,\n metricsAggregatorIntegration,\n) as IntegrationClass<Integration & { setup: (client: Client) => void }>;\n","import type { ClientOptions, MeasurementUnit, Primitive } from '@sentry/types';\nimport { logger } from '@sentry/utils';\nimport type { BaseClient } from '../baseclient';\nimport { DEBUG_BUILD } from '../debug-build';\nimport { getClient, getCurrentScope } from '../exports';\nimport { spanToJSON } from '../utils/spanUtils';\nimport { COUNTER_METRIC_TYPE, DISTRIBUTION_METRIC_TYPE, GAUGE_METRIC_TYPE, SET_METRIC_TYPE } from './constants';\nimport { MetricsAggregator, metricsAggregatorIntegration } from './integration';\nimport type { MetricType } from './types';\n\ninterface MetricData {\n unit?: MeasurementUnit;\n tags?: Record<string, Primitive>;\n timestamp?: number;\n}\n\nfunction addToMetricsAggregator(\n metricType: MetricType,\n name: string,\n value: number | string,\n data: MetricData | undefined = {},\n): void {\n const client = getClient<BaseClient<ClientOptions>>();\n const scope = getCurrentScope();\n if (client) {\n if (!client.metricsAggregator) {\n DEBUG_BUILD &&\n logger.warn('No metrics aggregator enabled. Please add the MetricsAggregator integration to use metrics APIs');\n return;\n }\n const { unit, tags, timestamp } = data;\n const { release, environment } = client.getOptions();\n // eslint-disable-next-line deprecation/deprecation\n const transaction = scope.getTransaction();\n const metricTags: Record<string, string> = {};\n if (release) {\n metricTags.release = release;\n }\n if (environment) {\n metricTags.environment = environment;\n }\n if (transaction) {\n metricTags.transaction = spanToJSON(transaction).description || '';\n }\n\n DEBUG_BUILD && logger.log(`Adding value of ${value} to ${metricType} metric ${name}`);\n client.metricsAggregator.add(metricType, name, value, unit, { ...metricTags, ...tags }, timestamp);\n }\n}\n\n/**\n * Adds a value to a counter metric\n *\n * @experimental This API is experimental and might have breaking changes in the future.\n */\nexport function increment(name: string, value: number = 1, data?: MetricData): void {\n addToMetricsAggregator(COUNTER_METRIC_TYPE, name, value, data);\n}\n\n/**\n * Adds a value to a distribution metric\n *\n * @experimental This API is experimental and might have breaking changes in the future.\n */\nexport function distribution(name: string, value: number, data?: MetricData): void {\n addToMetricsAggregator(DISTRIBUTION_METRIC_TYPE, name, value, data);\n}\n\n/**\n * Adds a value to a set metric. Value must be a string or integer.\n *\n * @experimental This API is experimental and might have breaking changes in the future.\n */\nexport function set(name: string, value: number | string, data?: MetricData): void {\n addToMetricsAggregator(SET_METRIC_TYPE, name, value, data);\n}\n\n/**\n * Adds a value to a gauge metric\n *\n * @experimental This API is experimental and might have breaking changes in the future.\n */\nexport function gauge(name: string, value: number, data?: MetricData): void {\n addToMetricsAggregator(GAUGE_METRIC_TYPE, name, value, data);\n}\n\nexport const metrics = {\n increment,\n distribution,\n set,\n gauge,\n /** @deprecated Use `metrics.metricsAggregratorIntegration()` instead. */\n // eslint-disable-next-line deprecation/deprecation\n MetricsAggregator,\n metricsAggregatorIntegration,\n};\n","import type {\n AggregationCounts,\n Client,\n RequestSessionStatus,\n SessionAggregates,\n SessionFlusherLike,\n} from '@sentry/types';\nimport { dropUndefinedKeys } from '@sentry/utils';\nimport { getCurrentScope } from './exports';\n\ntype ReleaseHealthAttributes = {\n environment?: string;\n release: string;\n};\n\n/**\n * @inheritdoc\n */\nexport class SessionFlusher implements SessionFlusherLike {\n public readonly flushTimeout: number;\n private _pendingAggregates: Record<number, AggregationCounts>;\n private _sessionAttrs: ReleaseHealthAttributes;\n // Cast to any so that it can use Node.js timeout\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private _intervalId: any;\n private _isEnabled: boolean;\n private _client: Client;\n\n public constructor(client: Client, attrs: ReleaseHealthAttributes) {\n this._client = client;\n this.flushTimeout = 60;\n this._pendingAggregates = {};\n this._isEnabled = true;\n\n // Call to setInterval, so that flush is called every 60 seconds.\n this._intervalId = setInterval(() => this.flush(), this.flushTimeout * 1000);\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if (this._intervalId.unref) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n this._intervalId.unref();\n }\n this._sessionAttrs = attrs;\n }\n\n /** Checks if `pendingAggregates` has entries, and if it does flushes them by calling `sendSession` */\n public flush(): void {\n const sessionAggregates = this.getSessionAggregates();\n if (sessionAggregates.aggregates.length === 0) {\n return;\n }\n this._pendingAggregates = {};\n this._client.sendSession(sessionAggregates);\n }\n\n /** Massages the entries in `pendingAggregates` and returns aggregated sessions */\n public getSessionAggregates(): SessionAggregates {\n const aggregates: AggregationCounts[] = Object.keys(this._pendingAggregates).map((key: string) => {\n return this._pendingAggregates[parseInt(key)];\n });\n\n const sessionAggregates: SessionAggregates = {\n attrs: this._sessionAttrs,\n aggregates,\n };\n return dropUndefinedKeys(sessionAggregates);\n }\n\n /** JSDoc */\n public close(): void {\n clearInterval(this._intervalId);\n this._isEnabled = false;\n this.flush();\n }\n\n /**\n * Wrapper function for _incrementSessionStatusCount that checks if the instance of SessionFlusher is enabled then\n * fetches the session status of the request from `Scope.getRequestSession().status` on the scope and passes them to\n * `_incrementSessionStatusCount` along with the start date\n */\n public incrementSessionStatusCount(): void {\n if (!this._isEnabled) {\n return;\n }\n const scope = getCurrentScope();\n const requestSession = scope.getRequestSession();\n\n if (requestSession && requestSession.status) {\n this._incrementSessionStatusCount(requestSession.status, new Date());\n // This is not entirely necessarily but is added as a safe guard to indicate the bounds of a request and so in\n // case captureRequestSession is called more than once to prevent double count\n scope.setRequestSession(undefined);\n /* eslint-enable @typescript-eslint/no-unsafe-member-access */\n }\n }\n\n /**\n * Increments status bucket in pendingAggregates buffer (internal state) corresponding to status of\n * the session received\n */\n private _incrementSessionStatusCount(status: RequestSessionStatus, date: Date): number {\n // Truncate minutes and seconds on Session Started attribute to have one minute bucket keys\n const sessionStartedTrunc = new Date(date).setSeconds(0, 0);\n this._pendingAggregates[sessionStartedTrunc] = this._pendingAggregates[sessionStartedTrunc] || {};\n\n // corresponds to aggregated sessions in one specific minute bucket\n // for example, {\"started\":\"2021-03-16T08:00:00.000Z\",\"exited\":4, \"errored\": 1}\n const aggregationCounts: AggregationCounts = this._pendingAggregates[sessionStartedTrunc];\n if (!aggregationCounts.started) {\n aggregationCounts.started = new Date(sessionStartedTrunc).toISOString();\n }\n\n switch (status) {\n case 'errored':\n aggregationCounts.errored = (aggregationCounts.errored || 0) + 1;\n return aggregationCounts.errored;\n case 'ok':\n aggregationCounts.exited = (aggregationCounts.exited || 0) + 1;\n return aggregationCounts.exited;\n default:\n aggregationCounts.crashed = (aggregationCounts.crashed || 0) + 1;\n return aggregationCounts.crashed;\n }\n }\n}\n","import type {\n CheckInEnvelope,\n CheckInItem,\n DsnComponents,\n DynamicSamplingContext,\n SdkMetadata,\n SerializedCheckIn,\n} from '@sentry/types';\nimport { createEnvelope, dropUndefinedKeys, dsnToString } from '@sentry/utils';\n\n/**\n * Create envelope from check in item.\n */\nexport function createCheckInEnvelope(\n checkIn: SerializedCheckIn,\n dynamicSamplingContext?: Partial<DynamicSamplingContext>,\n metadata?: SdkMetadata,\n tunnel?: string,\n dsn?: DsnComponents,\n): CheckInEnvelope {\n const headers: CheckInEnvelope[0] = {\n sent_at: new Date().toISOString(),\n };\n\n if (metadata && metadata.sdk) {\n headers.sdk = {\n name: metadata.sdk.name,\n version: metadata.sdk.version,\n };\n }\n\n if (!!tunnel && !!dsn) {\n headers.dsn = dsnToString(dsn);\n }\n\n if (dynamicSamplingContext) {\n headers.trace = dropUndefinedKeys(dynamicSamplingContext) as DynamicSamplingContext;\n }\n\n const item = createCheckInEnvelopeItem(checkIn);\n return createEnvelope<CheckInEnvelope>(headers, [item]);\n}\n\nfunction createCheckInEnvelopeItem(checkIn: SerializedCheckIn): CheckInItem {\n const checkInHeaders: CheckInItem[0] = {\n type: 'check_in',\n };\n return [checkInHeaders, checkIn];\n}\n","import type {\n Client,\n ClientOptions,\n MeasurementUnit,\n MetricsAggregator as MetricsAggregatorBase,\n Primitive,\n} from '@sentry/types';\nimport { timestampInSeconds } from '@sentry/utils';\nimport { DEFAULT_FLUSH_INTERVAL, MAX_WEIGHT, SET_METRIC_TYPE } from './constants';\nimport { METRIC_MAP } from './instance';\nimport { updateMetricSummaryOnActiveSpan } from './metric-summary';\nimport type { MetricBucket, MetricType } from './types';\nimport { getBucketKey, sanitizeMetricKey, sanitizeTags, sanitizeUnit } from './utils';\n\n/**\n * A metrics aggregator that aggregates metrics in memory and flushes them periodically.\n */\nexport class MetricsAggregator implements MetricsAggregatorBase {\n // TODO(@anonrig): Use FinalizationRegistry to have a proper way of flushing the buckets\n // when the aggregator is garbage collected.\n // Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry\n private _buckets: MetricBucket;\n\n // Different metrics have different weights. We use this to limit the number of metrics\n // that we store in memory.\n private _bucketsTotalWeight;\n\n // Cast to any so that it can use Node.js timeout\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private readonly _interval: any;\n\n // SDKs are required to shift the flush interval by random() * rollup_in_seconds.\n // That shift is determined once per startup to create jittering.\n private readonly _flushShift: number;\n\n // An SDK is required to perform force flushing ahead of scheduled time if the memory\n // pressure is too high. There is no rule for this other than that SDKs should be tracking\n // abstract aggregation complexity (eg: a counter only carries a single float, whereas a\n // distribution is a float per emission).\n //\n // Force flush is used on either shutdown, flush() or when we exceed the max weight.\n private _forceFlush: boolean;\n\n public constructor(private readonly _client: Client<ClientOptions>) {\n this._buckets = new Map();\n this._bucketsTotalWeight = 0;\n\n this._interval = setInterval(() => this._flush(), DEFAULT_FLUSH_INTERVAL) as any;\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if (this._interval.unref) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n this._interval.unref();\n }\n\n this._flushShift = Math.floor((Math.random() * DEFAULT_FLUSH_INTERVAL) / 1000);\n this._forceFlush = false;\n }\n\n /**\n * @inheritDoc\n */\n public add(\n metricType: MetricType,\n unsanitizedName: string,\n value: number | string,\n unsanitizedUnit: MeasurementUnit = 'none',\n unsanitizedTags: Record<string, Primitive> = {},\n maybeFloatTimestamp = timestampInSeconds(),\n ): void {\n const timestamp = Math.floor(maybeFloatTimestamp);\n const name = sanitizeMetricKey(unsanitizedName);\n const tags = sanitizeTags(unsanitizedTags);\n const unit = sanitizeUnit(unsanitizedUnit as string);\n\n const bucketKey = getBucketKey(metricType, name, unit, tags);\n\n let bucketItem = this._buckets.get(bucketKey);\n // If this is a set metric, we need to calculate the delta from the previous weight.\n const previousWeight = bucketItem && metricType === SET_METRIC_TYPE ? bucketItem.metric.weight : 0;\n\n if (bucketItem) {\n bucketItem.metric.add(value);\n // TODO(abhi): Do we need this check?\n if (bucketItem.timestamp < timestamp) {\n bucketItem.timestamp = timestamp;\n }\n } else {\n bucketItem = {\n // @ts-expect-error we don't need to narrow down the type of value here, saves bundle size.\n metric: new METRIC_MAP[metricType](value),\n timestamp,\n metricType,\n name,\n unit,\n tags,\n };\n this._buckets.set(bucketKey, bucketItem);\n }\n\n // If value is a string, it's a set metric so calculate the delta from the previous weight.\n const val = typeof value === 'string' ? bucketItem.metric.weight - previousWeight : value;\n updateMetricSummaryOnActiveSpan(metricType, name, val, unit, unsanitizedTags, bucketKey);\n\n // We need to keep track of the total weight of the buckets so that we can\n // flush them when we exceed the max weight.\n this._bucketsTotalWeight += bucketItem.metric.weight;\n\n if (this._bucketsTotalWeight >= MAX_WEIGHT) {\n this.flush();\n }\n }\n\n /**\n * Flushes the current metrics to the transport via the transport.\n */\n public flush(): void {\n this._forceFlush = true;\n this._flush();\n }\n\n /**\n * Shuts down metrics aggregator and clears all metrics.\n */\n public close(): void {\n this._forceFlush = true;\n clearInterval(this._interval);\n this._flush();\n }\n\n /**\n * Flushes the buckets according to the internal state of the aggregator.\n * If it is a force flush, which happens on shutdown, it will flush all buckets.\n * Otherwise, it will only flush buckets that are older than the flush interval,\n * and according to the flush shift.\n *\n * This function mutates `_forceFlush` and `_bucketsTotalWeight` properties.\n */\n private _flush(): void {\n // TODO(@anonrig): Add Atomics for locking to avoid having force flush and regular flush\n // running at the same time.\n // Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Atomics\n\n // This path eliminates the need for checking for timestamps since we're forcing a flush.\n // Remember to reset the flag, or it will always flush all metrics.\n if (this._forceFlush) {\n this._forceFlush = false;\n this._bucketsTotalWeight = 0;\n this._captureMetrics(this._buckets);\n this._buckets.clear();\n return;\n }\n const cutoffSeconds = Math.floor(timestampInSeconds()) - DEFAULT_FLUSH_INTERVAL / 1000 - this._flushShift;\n // TODO(@anonrig): Optimization opportunity.\n // Convert this map to an array and store key in the bucketItem.\n const flushedBuckets: MetricBucket = new Map();\n for (const [key, bucket] of this._buckets) {\n if (bucket.timestamp <= cutoffSeconds) {\n flushedBuckets.set(key, bucket);\n this._bucketsTotalWeight -= bucket.metric.weight;\n }\n }\n\n for (const [key] of flushedBuckets) {\n this._buckets.delete(key);\n }\n\n this._captureMetrics(flushedBuckets);\n }\n\n /**\n * Only captures a subset of the buckets passed to this function.\n * @param flushedBuckets\n */\n private _captureMetrics(flushedBuckets: MetricBucket): void {\n if (flushedBuckets.size > 0 && this._client.captureAggregateMetrics) {\n // TODO(@anonrig): Optimization opportunity.\n // This copy operation can be avoided if we store the key in the bucketItem.\n const buckets = Array.from(flushedBuckets).map(([, bucketItem]) => bucketItem);\n this._client.captureAggregateMetrics(buckets);\n }\n }\n}\n","import type {\n BaseTransportOptions,\n CheckIn,\n ClientOptions,\n DynamicSamplingContext,\n Event,\n EventHint,\n MonitorConfig,\n ParameterizedString,\n SerializedCheckIn,\n Severity,\n SeverityLevel,\n TraceContext,\n} from '@sentry/types';\nimport { eventFromMessage, eventFromUnknownInput, logger, resolvedSyncPromise, uuid4 } from '@sentry/utils';\n\nimport { BaseClient } from './baseclient';\nimport { createCheckInEnvelope } from './checkin';\nimport { DEBUG_BUILD } from './debug-build';\nimport { getClient } from './exports';\nimport { MetricsAggregator } from './metrics/aggregator';\nimport type { Scope } from './scope';\nimport { SessionFlusher } from './sessionflusher';\nimport {\n addTracingExtensions,\n getDynamicSamplingContextFromClient,\n getDynamicSamplingContextFromSpan,\n} from './tracing';\nimport { getRootSpan } from './utils/getRootSpan';\nimport { spanToTraceContext } from './utils/spanUtils';\n\nexport interface ServerRuntimeClientOptions extends ClientOptions<BaseTransportOptions> {\n platform?: string;\n runtime?: { name: string; version?: string };\n serverName?: string;\n}\n\n/**\n * The Sentry Server Runtime Client SDK.\n */\nexport class ServerRuntimeClient<\n O extends ClientOptions & ServerRuntimeClientOptions = ServerRuntimeClientOptions,\n> extends BaseClient<O> {\n protected _sessionFlusher: SessionFlusher | undefined;\n\n /**\n * Creates a new Edge SDK instance.\n * @param options Configuration options for this SDK.\n */\n public constructor(options: O) {\n // Server clients always support tracing\n addTracingExtensions();\n\n super(options);\n\n if (options._experiments && options._experiments['metricsAggregator']) {\n this.metricsAggregator = new MetricsAggregator(this);\n }\n }\n\n /**\n * @inheritDoc\n */\n public eventFromException(exception: unknown, hint?: EventHint): PromiseLike<Event> {\n return resolvedSyncPromise(eventFromUnknownInput(getClient(), this._options.stackParser, exception, hint));\n }\n\n /**\n * @inheritDoc\n */\n public eventFromMessage(\n message: ParameterizedString,\n // eslint-disable-next-line deprecation/deprecation\n level: Severity | SeverityLevel = 'info',\n hint?: EventHint,\n ): PromiseLike<Event> {\n return resolvedSyncPromise(\n eventFromMessage(this._options.stackParser, message, level, hint, this._options.attachStacktrace),\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 // Check if the flag `autoSessionTracking` is enabled, and if `_sessionFlusher` exists because it is initialised only\n // when the `requestHandler` middleware is used, and hence the expectation is to have SessionAggregates payload\n // sent to the Server only when the `requestHandler` middleware is used\n if (this._options.autoSessionTracking && this._sessionFlusher && scope) {\n const requestSession = scope.getRequestSession();\n\n // Necessary checks to ensure this is code block is executed only within a request\n // Should override the status only if `requestSession.status` is `Ok`, which is its initial stage\n if (requestSession && requestSession.status === 'ok') {\n requestSession.status = 'errored';\n }\n }\n\n return super.captureException(exception, hint, scope);\n }\n\n /**\n * @inheritDoc\n */\n public captureEvent(event: Event, hint?: EventHint, scope?: Scope): string | undefined {\n // Check if the flag `autoSessionTracking` is enabled, and if `_sessionFlusher` exists because it is initialised only\n // when the `requestHandler` middleware is used, and hence the expectation is to have SessionAggregates payload\n // sent to the Server only when the `requestHandler` middleware is used\n if (this._options.autoSessionTracking && this._sessionFlusher && scope) {\n const eventType = event.type || 'exception';\n const isException =\n eventType === 'exception' && event.exception && event.exception.values && event.exception.values.length > 0;\n\n // If the event is of type Exception, then a request session should be captured\n if (isException) {\n const requestSession = scope.getRequestSession();\n\n // Ensure that this is happening within the bounds of a request, and make sure not to override\n // Session Status if Errored / Crashed\n if (requestSession && requestSession.status === 'ok') {\n requestSession.status = 'errored';\n }\n }\n }\n\n return super.captureEvent(event, hint, scope);\n }\n\n /**\n *\n * @inheritdoc\n */\n public close(timeout?: number): PromiseLike<boolean> {\n if (this._sessionFlusher) {\n this._sessionFlusher.close();\n }\n return super.close(timeout);\n }\n\n /** Method that initialises an instance of SessionFlusher on Client */\n public initSessionFlusher(): void {\n const { release, environment } = this._options;\n if (!release) {\n DEBUG_BUILD && logger.warn('Cannot initialise an instance of SessionFlusher if no release is provided!');\n } else {\n this._sessionFlusher = new SessionFlusher(this, {\n release,\n environment,\n });\n }\n }\n\n /**\n * Create a cron monitor check in and send it to Sentry.\n *\n * @param checkIn An object that describes a check in.\n * @param upsertMonitorConfig An optional object that describes a monitor config. Use this if you want\n * to create a monitor automatically when sending a check in.\n */\n public captureCheckIn(checkIn: CheckIn, monitorConfig?: MonitorConfig, scope?: Scope): string {\n const id = 'checkInId' in checkIn && checkIn.checkInId ? checkIn.checkInId : uuid4();\n if (!this._isEnabled()) {\n DEBUG_BUILD && logger.warn('SDK not enabled, will not capture checkin.');\n return id;\n }\n\n const options = this.getOptions();\n const { release, environment, tunnel } = options;\n\n const serializedCheckIn: SerializedCheckIn = {\n check_in_id: id,\n monitor_slug: checkIn.monitorSlug,\n status: checkIn.status,\n release,\n environment,\n };\n\n if ('duration' in checkIn) {\n serializedCheckIn.duration = checkIn.duration;\n }\n\n if (monitorConfig) {\n serializedCheckIn.monitor_config = {\n schedule: monitorConfig.schedule,\n checkin_margin: monitorConfig.checkinMargin,\n max_runtime: monitorConfig.maxRuntime,\n timezone: monitorConfig.timezone,\n };\n }\n\n const [dynamicSamplingContext, traceContext] = this._getTraceInfoFromScope(scope);\n if (traceContext) {\n serializedCheckIn.contexts = {\n trace: traceContext,\n };\n }\n\n const envelope = createCheckInEnvelope(\n serializedCheckIn,\n dynamicSamplingContext,\n this.getSdkMetadata(),\n tunnel,\n this.getDsn(),\n );\n\n DEBUG_BUILD && logger.info('Sending checkin:', checkIn.monitorSlug, checkIn.status);\n\n // _sendEnvelope should not throw\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this._sendEnvelope(envelope);\n\n return id;\n }\n\n /**\n * Method responsible for capturing/ending a request session by calling `incrementSessionStatusCount` to increment\n * appropriate session aggregates bucket\n */\n protected _captureRequestSession(): void {\n if (!this._sessionFlusher) {\n DEBUG_BUILD && logger.warn('Discarded request mode session because autoSessionTracking option was disabled');\n } else {\n this._sessionFlusher.incrementSessionStatusCount();\n }\n }\n\n /**\n * @inheritDoc\n */\n protected _prepareEvent(\n event: Event,\n hint: EventHint,\n scope?: Scope,\n isolationScope?: Scope,\n ): PromiseLike<Event | null> {\n if (this._options.platform) {\n event.platform = event.platform || this._options.platform;\n }\n\n if (this._options.runtime) {\n event.contexts = {\n ...event.contexts,\n runtime: (event.contexts || {}).runtime || this._options.runtime,\n };\n }\n\n if (this._options.serverName) {\n event.server_name = event.server_name || this._options.serverName;\n }\n\n return super._prepareEvent(event, hint, scope, isolationScope);\n }\n\n /** Extract trace information from scope */\n private _getTraceInfoFromScope(\n scope: Scope | undefined,\n ): [dynamicSamplingContext: Partial<DynamicSamplingContext> | undefined, traceContext: TraceContext | undefined] {\n if (!scope) {\n return [undefined, undefined];\n }\n\n // eslint-disable-next-line deprecation/deprecation\n const span = scope.getSpan();\n if (span) {\n const samplingContext = getRootSpan(span) ? getDynamicSamplingContextFromSpan(span) : undefined;\n return [samplingContext, spanToTraceContext(span)];\n }\n\n const { traceId, spanId, parentSpanId, dsc } = scope.getPropagationContext();\n const traceContext: TraceContext = {\n trace_id: traceId,\n span_id: spanId,\n parent_span_id: parentSpanId,\n };\n if (dsc) {\n return [dsc, traceContext];\n }\n\n return [getDynamicSamplingContextFromClient(traceId, this, scope), traceContext];\n }\n}\n","import type { Envelope, InternalBaseTransportOptions, Transport, TransportMakeRequestResponse } from '@sentry/types';\nimport { envelopeContainsItemType, logger, parseRetryAfterHeader } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\n\nexport const MIN_DELAY = 100; // 100 ms\nexport const START_DELAY = 5_000; // 5 seconds\nconst MAX_DELAY = 3.6e6; // 1 hour\n\nfunction log(msg: string, error?: Error): void {\n DEBUG_BUILD && logger.info(`[Offline]: ${msg}`, error);\n}\n\nexport interface OfflineStore {\n insert(env: Envelope): Promise<void>;\n pop(): Promise<Envelope | undefined>;\n}\n\nexport type CreateOfflineStore = (options: OfflineTransportOptions) => OfflineStore;\n\nexport interface OfflineTransportOptions extends InternalBaseTransportOptions {\n /**\n * A function that creates the offline store instance.\n */\n createStore?: CreateOfflineStore;\n\n /**\n * Flush the offline store shortly after startup.\n *\n * Defaults: false\n */\n flushAtStartup?: boolean;\n\n /**\n * Called before an event is stored.\n *\n * Return false to drop the envelope rather than store it.\n *\n * @param envelope The envelope that failed to send.\n * @param error The error that occurred.\n * @param retryDelay The current retry delay in milliseconds.\n */\n shouldStore?: (envelope: Envelope, error: Error, retryDelay: number) => boolean | Promise<boolean>;\n}\n\ntype Timer = number | { unref?: () => void };\n\n/**\n * Wraps a transport and stores and retries events when they fail to send.\n *\n * @param createTransport The transport to wrap.\n */\nexport function makeOfflineTransport<TO>(\n createTransport: (options: TO) => Transport,\n): (options: TO & OfflineTransportOptions) => Transport {\n return options => {\n const transport = createTransport(options);\n const store = options.createStore ? options.createStore(options) : undefined;\n\n let retryDelay = START_DELAY;\n let flushTimer: Timer | undefined;\n\n function shouldQueue(env: Envelope, error: Error, retryDelay: number): boolean | Promise<boolean> {\n // We don't queue Session Replay envelopes because they are:\n // - Ordered and Replay relies on the response status to know when they're successfully sent.\n // - Likely to fill the queue quickly and block other events from being sent.\n // We also want to drop client reports because they can be generated when we retry sending events while offline.\n if (envelopeContainsItemType(env, ['replay_event', 'replay_recording', 'client_report'])) {\n return false;\n }\n\n if (options.shouldStore) {\n return options.shouldStore(env, error, retryDelay);\n }\n\n return true;\n }\n\n function flushIn(delay: number): void {\n if (!store) {\n return;\n }\n\n if (flushTimer) {\n clearTimeout(flushTimer as ReturnType<typeof setTimeout>);\n }\n\n flushTimer = setTimeout(async () => {\n flushTimer = undefined;\n\n const found = await store.pop();\n if (found) {\n log('Attempting to send previously queued event');\n void send(found).catch(e => {\n log('Failed to retry sending', e);\n });\n }\n }, delay) as Timer;\n\n // We need to unref the timer in node.js, otherwise the node process never exit.\n if (typeof flushTimer !== 'number' && flushTimer.unref) {\n flushTimer.unref();\n }\n }\n\n function flushWithBackOff(): void {\n if (flushTimer) {\n return;\n }\n\n flushIn(retryDelay);\n\n retryDelay = Math.min(retryDelay * 2, MAX_DELAY);\n }\n\n async function send(envelope: Envelope): Promise<void | TransportMakeRequestResponse> {\n try {\n const result = await transport.send(envelope);\n\n let delay = MIN_DELAY;\n\n if (result) {\n // If there's a retry-after header, use that as the next delay.\n if (result.headers && result.headers['retry-after']) {\n delay = parseRetryAfterHeader(result.headers['retry-after']);\n } // If we have a server error, return now so we don't flush the queue.\n else if ((result.statusCode || 0) >= 400) {\n return result;\n }\n }\n\n flushIn(delay);\n retryDelay = START_DELAY;\n return result;\n } catch (e) {\n if (store && (await shouldQueue(envelope, e as Error, retryDelay))) {\n await store.insert(envelope);\n flushWithBackOff();\n log('Error sending. Event queued', e as Error);\n return {};\n } else {\n throw e;\n }\n }\n }\n\n if (options.flushAtStartup) {\n flushWithBackOff();\n }\n\n return {\n send,\n flush: t => transport.flush(t),\n };\n };\n}\n","import type { DsnComponents, SpanEnvelope, SpanItem } from '@sentry/types';\nimport type { Span } from '@sentry/types';\nimport { createEnvelope, dsnToString } from '@sentry/utils';\n\n/**\n * Create envelope from Span item.\n */\nexport function createSpanEnvelope(spans: Span[], dsn?: DsnComponents): SpanEnvelope {\n const headers: SpanEnvelope[0] = {\n sent_at: new Date().toISOString(),\n };\n\n if (dsn) {\n headers.dsn = dsnToString(dsn);\n }\n\n const items = spans.map(createSpanItem);\n return createEnvelope<SpanEnvelope>(headers, items);\n}\n\nfunction createSpanItem(span: Span): SpanItem {\n const spanHeaders: SpanItem[0] = {\n type: 'span',\n };\n return [spanHeaders, span];\n}\n","import type { Client, DsnComponents, Hub } from '@sentry/types';\n\n/**\n * Checks whether given url points to Sentry server\n * @param url url to verify\n *\n * TODO(v8): Remove Hub fallback type\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function isSentryRequestUrl(url: string, hubOrClient: Hub | Client | undefined): boolean {\n const client =\n hubOrClient && isHub(hubOrClient)\n ? // eslint-disable-next-line deprecation/deprecation\n hubOrClient.getClient()\n : hubOrClient;\n const dsn = client && client.getDsn();\n const tunnel = client && client.getOptions().tunnel;\n\n return checkDsn(url, dsn) || checkTunnel(url, tunnel);\n}\n\nfunction checkTunnel(url: string, tunnel: string | undefined): boolean {\n if (!tunnel) {\n return false;\n }\n\n return removeTrailingSlash(url) === removeTrailingSlash(tunnel);\n}\n\nfunction checkDsn(url: string, dsn: DsnComponents | undefined): boolean {\n return dsn ? url.includes(dsn.host) : false;\n}\n\nfunction removeTrailingSlash(str: string): string {\n return str[str.length - 1] === '/' ? str.slice(0, -1) : str;\n}\n\n// eslint-disable-next-line deprecation/deprecation\nfunction isHub(hubOrClient: Hub | Client | undefined): hubOrClient is Hub {\n // eslint-disable-next-line deprecation/deprecation\n return (hubOrClient as Hub).getClient !== undefined;\n}\n","import type { Options } from '@sentry/types';\nimport { SDK_VERSION } from '../version';\n\n/**\n * A builder for the SDK metadata in the options for the SDK initialization.\n *\n * Note: This function is identical to `buildMetadata` in Remix and NextJS and SvelteKit.\n * We don't extract it for bundle size reasons.\n * @see https://github.com/getsentry/sentry-javascript/pull/7404\n * @see https://github.com/getsentry/sentry-javascript/pull/4196\n *\n * If you make changes to this function consider updating the others as well.\n *\n * @param options SDK options object that gets mutated\n * @param names list of package names\n */\nexport function applySdkMetadata(options: Options, name: string, names = [name], source = 'npm'): void {\n const metadata = options._metadata || {};\n\n if (!metadata.sdk) {\n metadata.sdk = {\n name: `sentry.javascript.${name}`,\n packages: names.map(name => ({\n name: `${source}:@sentry/${name}`,\n version: SDK_VERSION,\n })),\n version: SDK_VERSION,\n };\n }\n\n options._metadata = metadata;\n}\n","import type {\n Client,\n Event,\n EventHint,\n Integration,\n IntegrationClass,\n IntegrationFn,\n Transaction,\n} from '@sentry/types';\nimport type { AddRequestDataToEventOptions, TransactionNamingScheme } from '@sentry/utils';\nimport { addRequestDataToEvent, extractPathForTransaction } from '@sentry/utils';\nimport { convertIntegrationFnToClass, defineIntegration } from '../integration';\nimport { spanToJSON } from '../utils/spanUtils';\n\nexport type RequestDataIntegrationOptions = {\n /**\n * Controls what data is pulled from the request and added to the event\n */\n include?: {\n cookies?: boolean;\n data?: boolean;\n headers?: boolean;\n ip?: boolean;\n query_string?: boolean;\n url?: boolean;\n user?:\n | boolean\n | {\n id?: boolean;\n username?: boolean;\n email?: boolean;\n };\n };\n\n /** Whether to identify transactions by parameterized path, parameterized path with method, or handler name */\n transactionNamingScheme?: TransactionNamingScheme;\n};\n\nconst DEFAULT_OPTIONS = {\n include: {\n cookies: true,\n data: true,\n headers: true,\n ip: false,\n query_string: true,\n url: true,\n user: {\n id: true,\n username: true,\n email: true,\n },\n },\n transactionNamingScheme: 'methodPath',\n};\n\nconst INTEGRATION_NAME = 'RequestData';\n\nconst _requestDataIntegration = ((options: RequestDataIntegrationOptions = {}) => {\n const _addRequestData = addRequestDataToEvent;\n const _options: Required<RequestDataIntegrationOptions> = {\n ...DEFAULT_OPTIONS,\n ...options,\n include: {\n // @ts-expect-error It's mad because `method` isn't a known `include` key. (It's only here and not set by default in\n // `addRequestDataToEvent` for legacy reasons. TODO (v8): Change that.)\n method: true,\n ...DEFAULT_OPTIONS.include,\n ...options.include,\n user:\n options.include && typeof options.include.user === 'boolean'\n ? options.include.user\n : {\n ...DEFAULT_OPTIONS.include.user,\n // Unclear why TS still thinks `options.include.user` could be a boolean at this point\n ...((options.include || {}).user as Record<string, boolean>),\n },\n },\n };\n\n return {\n name: INTEGRATION_NAME,\n // TODO v8: Remove this\n setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function\n processEvent(event, _hint, client) {\n // Note: In the long run, most of the logic here should probably move into the request data utility functions. For\n // the moment it lives here, though, until https://github.com/getsentry/sentry-javascript/issues/5718 is addressed.\n // (TL;DR: Those functions touch many parts of the repo in many different ways, and need to be clened up. Once\n // that's happened, it will be easier to add this logic in without worrying about unexpected side effects.)\n const { transactionNamingScheme } = _options;\n\n const { sdkProcessingMetadata = {} } = event;\n const req = sdkProcessingMetadata.request;\n\n if (!req) {\n return event;\n }\n\n // The Express request handler takes a similar `include` option to that which can be passed to this integration.\n // If passed there, we store it in `sdkProcessingMetadata`. TODO(v8): Force express and GCP people to use this\n // integration, so that all of this passing and conversion isn't necessary\n const addRequestDataOptions =\n sdkProcessingMetadata.requestDataOptionsFromExpressHandler ||\n sdkProcessingMetadata.requestDataOptionsFromGCPWrapper ||\n convertReqDataIntegrationOptsToAddReqDataOpts(_options);\n\n const processedEvent = _addRequestData(event, req, addRequestDataOptions);\n\n // Transaction events already have the right `transaction` value\n if (event.type === 'transaction' || transactionNamingScheme === 'handler') {\n return processedEvent;\n }\n\n // In all other cases, use the request's associated transaction (if any) to overwrite the event's `transaction`\n // value with a high-quality one\n const reqWithTransaction = req as { _sentryTransaction?: Transaction };\n const transaction = reqWithTransaction._sentryTransaction;\n if (transaction) {\n const name = spanToJSON(transaction).description || '';\n\n // TODO (v8): Remove the nextjs check and just base it on `transactionNamingScheme` for all SDKs. (We have to\n // keep it the way it is for the moment, because changing the names of transactions in Sentry has the potential\n // to break things like alert rules.)\n const shouldIncludeMethodInTransactionName =\n getSDKName(client) === 'sentry.javascript.nextjs'\n ? name.startsWith('/api')\n : transactionNamingScheme !== 'path';\n\n const [transactionValue] = extractPathForTransaction(req, {\n path: true,\n method: shouldIncludeMethodInTransactionName,\n customRoute: name,\n });\n\n processedEvent.transaction = transactionValue;\n }\n\n return processedEvent;\n },\n };\n}) satisfies IntegrationFn;\n\nexport const requestDataIntegration = defineIntegration(_requestDataIntegration);\n\n/**\n * Add data about a request to an event. Primarily for use in Node-based SDKs, but included in `@sentry/integrations`\n * so it can be used in cross-platform SDKs like `@sentry/nextjs`.\n * @deprecated Use `requestDataIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const RequestData = convertIntegrationFnToClass(INTEGRATION_NAME, requestDataIntegration) as IntegrationClass<\n Integration & { processEvent: (event: Event, hint: EventHint, client: Client) => Event }\n> & {\n new (options?: {\n /**\n * Controls what data is pulled from the request and added to the event\n */\n include?: {\n cookies?: boolean;\n data?: boolean;\n headers?: boolean;\n ip?: boolean;\n query_string?: boolean;\n url?: boolean;\n user?:\n | boolean\n | {\n id?: boolean;\n username?: boolean;\n email?: boolean;\n };\n };\n\n /** Whether to identify transactions by parameterized path, parameterized path with method, or handler name */\n transactionNamingScheme?: TransactionNamingScheme;\n }): Integration;\n};\n\n/** Convert this integration's options to match what `addRequestDataToEvent` expects */\n/** TODO: Can possibly be deleted once https://github.com/getsentry/sentry-javascript/issues/5718 is fixed */\nfunction convertReqDataIntegrationOptsToAddReqDataOpts(\n integrationOptions: Required<RequestDataIntegrationOptions>,\n): AddRequestDataToEventOptions {\n const {\n transactionNamingScheme,\n include: { ip, user, ...requestOptions },\n } = integrationOptions;\n\n const requestIncludeKeys: string[] = [];\n for (const [key, value] of Object.entries(requestOptions)) {\n if (value) {\n requestIncludeKeys.push(key);\n }\n }\n\n let addReqDataUserOpt;\n if (user === undefined) {\n addReqDataUserOpt = true;\n } else if (typeof user === 'boolean') {\n addReqDataUserOpt = user;\n } else {\n const userIncludeKeys: string[] = [];\n for (const [key, value] of Object.entries(user)) {\n if (value) {\n userIncludeKeys.push(key);\n }\n }\n addReqDataUserOpt = userIncludeKeys;\n }\n\n return {\n include: {\n ip,\n user: addReqDataUserOpt,\n request: requestIncludeKeys.length !== 0 ? requestIncludeKeys : undefined,\n transaction: transactionNamingScheme,\n },\n };\n}\n\nfunction getSDKName(client: Client): string | undefined {\n try {\n // For a long chain like this, it's fewer bytes to combine a try-catch with assuming everything is there than to\n // write out a long chain of `a && a.b && a.b.c && ...`\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return client.getOptions()._metadata!.sdk!.name;\n } catch (err) {\n // In theory we should never get here\n return undefined;\n }\n}\n","import type { Client, Event, EventHint, Integration, IntegrationClass, IntegrationFn } from '@sentry/types';\nimport { applyAggregateErrorsToEvent, exceptionFromError } from '@sentry/utils';\nimport { convertIntegrationFnToClass, defineIntegration } from '../integration';\n\ninterface LinkedErrorsOptions {\n key?: string;\n limit?: number;\n}\n\nconst DEFAULT_KEY = 'cause';\nconst DEFAULT_LIMIT = 5;\n\nconst INTEGRATION_NAME = 'LinkedErrors';\n\nconst _linkedErrorsIntegration = ((options: LinkedErrorsOptions = {}) => {\n const limit = options.limit || DEFAULT_LIMIT;\n const key = options.key || DEFAULT_KEY;\n\n return {\n name: INTEGRATION_NAME,\n // TODO v8: Remove this\n setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function\n preprocessEvent(event, hint, client) {\n const options = client.getOptions();\n\n applyAggregateErrorsToEvent(\n exceptionFromError,\n options.stackParser,\n options.maxValueLength,\n key,\n limit,\n event,\n hint,\n );\n },\n };\n}) satisfies IntegrationFn;\n\nexport const linkedErrorsIntegration = defineIntegration(_linkedErrorsIntegration);\n\n/**\n * Adds SDK info to an event.\n * @deprecated Use `linkedErrorsIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const LinkedErrors = convertIntegrationFnToClass(INTEGRATION_NAME, linkedErrorsIntegration) as IntegrationClass<\n Integration & { preprocessEvent: (event: Event, hint: EventHint, client: Client) => void }\n> & { new (options?: { key?: string; limit?: number }): Integration };\n","export type { ClientClass } from './sdk';\nexport type { AsyncContextStrategy, Carrier, Layer, RunWithAsyncContextOptions } from './hub';\nexport type { OfflineStore, OfflineTransportOptions } from './transports/offline';\nexport type { ServerRuntimeClientOptions } from './server-runtime-client';\nexport type { RequestDataIntegrationOptions } from './integrations/requestdata';\nexport type { IntegrationIndex } from './integration';\n\nexport * from './tracing';\nexport * from './semanticAttributes';\nexport { createEventEnvelope, createSessionEnvelope } from './envelope';\nexport {\n addBreadcrumb,\n captureCheckIn,\n withMonitor,\n captureException,\n captureEvent,\n captureMessage,\n close,\n // eslint-disable-next-line deprecation/deprecation\n configureScope,\n flush,\n lastEventId,\n // eslint-disable-next-line deprecation/deprecation\n startTransaction,\n setContext,\n setExtra,\n setExtras,\n setTag,\n setTags,\n setUser,\n withScope,\n withIsolationScope,\n getClient,\n isInitialized,\n getCurrentScope,\n startSession,\n endSession,\n captureSession,\n withActiveSpan,\n} from './exports';\nexport {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub,\n getIsolationScope,\n getHubFromCarrier,\n // eslint-disable-next-line deprecation/deprecation\n Hub,\n // eslint-disable-next-line deprecation/deprecation\n makeMain,\n getMainCarrier,\n runWithAsyncContext,\n setHubOnCarrier,\n ensureHubOnCarrier,\n setAsyncContextStrategy,\n} from './hub';\nexport { makeSession, closeSession, updateSession } from './session';\nexport { SessionFlusher } from './sessionflusher';\nexport { Scope, getGlobalScope, setGlobalScope } from './scope';\nexport {\n notifyEventProcessors,\n // eslint-disable-next-line deprecation/deprecation\n addGlobalEventProcessor,\n} from './eventProcessors';\nexport { getEnvelopeEndpointWithUrlEncodedAuth, getReportDialogEndpoint } from './api';\nexport { BaseClient, addEventProcessor } from './baseclient';\nexport { ServerRuntimeClient } from './server-runtime-client';\nexport { initAndBind, setCurrentClient } from './sdk';\nexport { createTransport } from './transports/base';\nexport { makeOfflineTransport } from './transports/offline';\nexport { makeMultiplexedTransport } from './transports/multiplexed';\nexport { SDK_VERSION } from './version';\nexport {\n getIntegrationsToSetup,\n addIntegration,\n defineIntegration,\n // eslint-disable-next-line deprecation/deprecation\n convertIntegrationFnToClass,\n} from './integration';\nexport { applyScopeDataToEvent, mergeScopeData } from './utils/applyScopeDataToEvent';\nexport { prepareEvent } from './utils/prepareEvent';\nexport { createCheckInEnvelope } from './checkin';\nexport { createSpanEnvelope } from './span';\nexport { hasTracingEnabled } from './utils/hasTracingEnabled';\nexport { isSentryRequestUrl } from './utils/isSentryRequestUrl';\nexport { handleCallbackErrors } from './utils/handleCallbackErrors';\nexport { parameterize } from './utils/parameterize';\nexport { spanToTraceHeader, spanToJSON, spanIsSampled, spanToTraceContext } from './utils/spanUtils';\nexport { getRootSpan } from './utils/getRootSpan';\nexport { applySdkMetadata } from './utils/sdkMetadata';\nexport { DEFAULT_ENVIRONMENT } from './constants';\n/* eslint-disable deprecation/deprecation */\nexport { ModuleMetadata } from './integrations/metadata';\nexport { RequestData } from './integrations/requestdata';\nexport { InboundFilters } from './integrations/inboundfilters';\nexport { FunctionToString } from './integrations/functiontostring';\nexport { LinkedErrors } from './integrations/linkederrors';\n/* eslint-enable deprecation/deprecation */\nimport * as INTEGRATIONS from './integrations';\nexport { functionToStringIntegration } from './integrations/functiontostring';\nexport { inboundFiltersIntegration } from './integrations/inboundfilters';\nexport { linkedErrorsIntegration } from './integrations/linkederrors';\nexport { moduleMetadataIntegration } from './integrations/metadata';\nexport { requestDataIntegration } from './integrations/requestdata';\nexport { metrics } from './metrics/exports';\n\n/** @deprecated Import the integration function directly, e.g. `inboundFiltersIntegration()` instead of `new Integrations.InboundFilter(). */\nconst Integrations = INTEGRATIONS;\n\n// eslint-disable-next-line deprecation/deprecation\nexport { Integrations };\n","import {\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n getClient,\n getCurrentScope,\n getDynamicSamplingContextFromClient,\n getDynamicSamplingContextFromSpan,\n getIsolationScope,\n hasTracingEnabled,\n setHttpStatus,\n spanToTraceHeader,\n startInactiveSpan,\n} from '@sentry/core';\nimport type { Client, HandlerDataFetch, Scope, Span, SpanOrigin } from '@sentry/types';\nimport {\n BAGGAGE_HEADER_NAME,\n dynamicSamplingContextToSentryBaggageHeader,\n generateSentryTraceHeader,\n isInstanceOf,\n parseUrl,\n} from '@sentry/utils';\n\ntype PolymorphicRequestHeaders =\n | Record<string, string | undefined>\n | Array<[string, string]>\n // the below is not preicsely the Header type used in Request, but it'll pass duck-typing\n | {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key: string]: any;\n append: (key: string, value: string) => void;\n get: (key: string) => string | null | undefined;\n };\n\n/**\n * Create and track fetch request spans for usage in combination with `addInstrumentationHandler`.\n *\n * @returns Span if a span was created, otherwise void.\n */\nexport function instrumentFetchRequest(\n handlerData: HandlerDataFetch,\n shouldCreateSpan: (url: string) => boolean,\n shouldAttachHeaders: (url: string) => boolean,\n spans: Record<string, Span>,\n spanOrigin: SpanOrigin = 'auto.http.browser',\n): Span | undefined {\n if (!hasTracingEnabled() || !handlerData.fetchData) {\n return undefined;\n }\n\n const shouldCreateSpanResult = shouldCreateSpan(handlerData.fetchData.url);\n\n if (handlerData.endTimestamp && shouldCreateSpanResult) {\n const spanId = handlerData.fetchData.__span;\n if (!spanId) return;\n\n const span = spans[spanId];\n if (span) {\n endSpan(span, handlerData);\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete spans[spanId];\n }\n return undefined;\n }\n\n const scope = getCurrentScope();\n const client = getClient();\n\n const { method, url } = handlerData.fetchData;\n\n const fullUrl = getFullURL(url);\n const host = fullUrl ? parseUrl(fullUrl).host : undefined;\n\n const span = shouldCreateSpanResult\n ? startInactiveSpan({\n name: `${method} ${url}`,\n onlyIfParent: true,\n attributes: {\n url,\n type: 'fetch',\n 'http.method': method,\n 'http.url': fullUrl,\n 'server.address': host,\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: spanOrigin,\n },\n op: 'http.client',\n })\n : undefined;\n\n if (span) {\n handlerData.fetchData.__span = span.spanContext().spanId;\n spans[span.spanContext().spanId] = span;\n }\n\n if (shouldAttachHeaders(handlerData.fetchData.url) && client) {\n const request: string | Request = handlerData.args[0];\n\n // In case the user hasn't set the second argument of a fetch call we default it to `{}`.\n handlerData.args[1] = handlerData.args[1] || {};\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const options: { [key: string]: any } = handlerData.args[1];\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access\n options.headers = addTracingHeadersToFetchRequest(request, client, scope, options, span);\n }\n\n return span;\n}\n\n/**\n * Adds sentry-trace and baggage headers to the various forms of fetch headers\n */\nexport function addTracingHeadersToFetchRequest(\n request: string | unknown, // unknown is actually type Request but we can't export DOM types from this package,\n client: Client,\n scope: Scope,\n options: {\n headers?:\n | {\n [key: string]: string[] | string | undefined;\n }\n | PolymorphicRequestHeaders;\n },\n requestSpan?: Span,\n): PolymorphicRequestHeaders | undefined {\n // eslint-disable-next-line deprecation/deprecation\n const span = requestSpan || scope.getSpan();\n\n const isolationScope = getIsolationScope();\n\n const { traceId, spanId, sampled, dsc } = {\n ...isolationScope.getPropagationContext(),\n ...scope.getPropagationContext(),\n };\n\n const sentryTraceHeader = span ? spanToTraceHeader(span) : generateSentryTraceHeader(traceId, spanId, sampled);\n\n const sentryBaggageHeader = dynamicSamplingContextToSentryBaggageHeader(\n dsc ||\n (span ? getDynamicSamplingContextFromSpan(span) : getDynamicSamplingContextFromClient(traceId, client, scope)),\n );\n\n const headers =\n options.headers ||\n (typeof Request !== 'undefined' && isInstanceOf(request, Request) ? (request as Request).headers : undefined);\n\n if (!headers) {\n return { 'sentry-trace': sentryTraceHeader, baggage: sentryBaggageHeader };\n } else if (typeof Headers !== 'undefined' && isInstanceOf(headers, Headers)) {\n const newHeaders = new Headers(headers as Headers);\n\n newHeaders.append('sentry-trace', sentryTraceHeader);\n\n if (sentryBaggageHeader) {\n // If the same header is appended multiple times the browser will merge the values into a single request header.\n // Its therefore safe to simply push a \"baggage\" entry, even though there might already be another baggage header.\n newHeaders.append(BAGGAGE_HEADER_NAME, sentryBaggageHeader);\n }\n\n return newHeaders as PolymorphicRequestHeaders;\n } else if (Array.isArray(headers)) {\n const newHeaders = [...headers, ['sentry-trace', sentryTraceHeader]];\n\n if (sentryBaggageHeader) {\n // If there are multiple entries with the same key, the browser will merge the values into a single request header.\n // Its therefore safe to simply push a \"baggage\" entry, even though there might already be another baggage header.\n newHeaders.push([BAGGAGE_HEADER_NAME, sentryBaggageHeader]);\n }\n\n return newHeaders as PolymorphicRequestHeaders;\n } else {\n const existingBaggageHeader = 'baggage' in headers ? headers.baggage : undefined;\n const newBaggageHeaders: string[] = [];\n\n if (Array.isArray(existingBaggageHeader)) {\n newBaggageHeaders.push(...existingBaggageHeader);\n } else if (existingBaggageHeader) {\n newBaggageHeaders.push(existingBaggageHeader);\n }\n\n if (sentryBaggageHeader) {\n newBaggageHeaders.push(sentryBaggageHeader);\n }\n\n return {\n ...(headers as Exclude<typeof headers, Headers>),\n 'sentry-trace': sentryTraceHeader,\n baggage: newBaggageHeaders.length > 0 ? newBaggageHeaders.join(',') : undefined,\n };\n }\n}\n\nfunction getFullURL(url: string): string | undefined {\n try {\n const parsed = new URL(url);\n return parsed.href;\n } catch {\n return undefined;\n }\n}\n\nfunction endSpan(span: Span, handlerData: HandlerDataFetch): void {\n if (handlerData.response) {\n setHttpStatus(span, handlerData.response.status);\n\n const contentLength =\n handlerData.response && handlerData.response.headers && handlerData.response.headers.get('content-length');\n\n if (contentLength) {\n const contentLengthNum = parseInt(contentLength);\n if (contentLengthNum > 0) {\n span.setAttribute('http.response_content_length', contentLengthNum);\n }\n }\n } else if (handlerData.error) {\n span.setStatus('internal_error');\n }\n span.end();\n}\n","declare const __DEBUG_BUILD__: boolean;\n\n/**\n * This serves as a build time flag that will be true by default, but false in non-debug builds or if users replace `__SENTRY_DEBUG__` in their generated code.\n *\n * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking.\n */\nexport const DEBUG_BUILD = __DEBUG_BUILD__;\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { Metric, ReportCallback } from '../types';\n\nexport const bindReporter = (\n callback: ReportCallback,\n metric: Metric,\n reportAllChanges?: boolean,\n): ((forceReport?: boolean) => void) => {\n let prevValue: number;\n let delta: number;\n return (forceReport?: boolean) => {\n if (metric.value >= 0) {\n if (forceReport || reportAllChanges) {\n delta = metric.value - (prevValue || 0);\n\n // Report the metric if there's a non-zero delta or if no previous\n // value exists (which can happen in the case of the document becoming\n // hidden when the metric value is 0).\n // See: https://github.com/GoogleChrome/web-vitals/issues/14\n if (delta || prevValue === undefined) {\n prevValue = metric.value;\n metric.delta = delta;\n callback(metric);\n }\n }\n }\n };\n};\n","import { GLOBAL_OBJ } from '@sentry/utils';\n\nexport const WINDOW = GLOBAL_OBJ as typeof GLOBAL_OBJ &\n // document is not available in all browser environments (webworkers). We make it optional so you have to explicitly check for it\n Omit<Window, 'document'> &\n Partial<Pick<Window, 'document'>>;\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Performantly generate a unique, 30-char string by combining a version\n * number, the current timestamp with a 13-digit number integer.\n * @return {string}\n */\nexport const generateUniqueID = (): string => {\n return `v3-${Date.now()}-${Math.floor(Math.random() * (9e12 - 1)) + 1e12}`;\n};\n","/*\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { WINDOW } from '../../types';\nimport type { NavigationTimingPolyfillEntry } from '../types';\n\nconst getNavigationEntryFromPerformanceTiming = (): NavigationTimingPolyfillEntry => {\n // eslint-disable-next-line deprecation/deprecation\n const timing = WINDOW.performance.timing;\n // eslint-disable-next-line deprecation/deprecation\n const type = WINDOW.performance.navigation.type;\n\n const navigationEntry: { [key: string]: number | string } = {\n entryType: 'navigation',\n startTime: 0,\n type: type == 2 ? 'back_forward' : type === 1 ? 'reload' : 'navigate',\n };\n\n for (const key in timing) {\n if (key !== 'navigationStart' && key !== 'toJSON') {\n // eslint-disable-next-line deprecation/deprecation\n navigationEntry[key] = Math.max((timing[key as keyof PerformanceTiming] as number) - timing.navigationStart, 0);\n }\n }\n return navigationEntry as unknown as NavigationTimingPolyfillEntry;\n};\n\nexport const getNavigationEntry = (): PerformanceNavigationTiming | NavigationTimingPolyfillEntry | undefined => {\n if (WINDOW.__WEB_VITALS_POLYFILL__) {\n return (\n WINDOW.performance &&\n ((performance.getEntriesByType && performance.getEntriesByType('navigation')[0]) ||\n getNavigationEntryFromPerformanceTiming())\n );\n } else {\n return WINDOW.performance && performance.getEntriesByType && performance.getEntriesByType('navigation')[0];\n }\n};\n","/*\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getNavigationEntry } from './getNavigationEntry';\n\nexport const getActivationStart = (): number => {\n const navEntry = getNavigationEntry();\n return (navEntry && navEntry.activationStart) || 0;\n};\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { WINDOW } from '../../types';\nimport type { Metric } from '../types';\nimport { generateUniqueID } from './generateUniqueID';\nimport { getActivationStart } from './getActivationStart';\nimport { getNavigationEntry } from './getNavigationEntry';\n\nexport const initMetric = (name: Metric['name'], value?: number): Metric => {\n const navEntry = getNavigationEntry();\n let navigationType: Metric['navigationType'] = 'navigate';\n\n if (navEntry) {\n if ((WINDOW.document && WINDOW.document.prerendering) || getActivationStart() > 0) {\n navigationType = 'prerender';\n } else {\n navigationType = navEntry.type.replace(/_/g, '-') as Metric['navigationType'];\n }\n }\n\n return {\n name,\n value: typeof value === 'undefined' ? -1 : value,\n rating: 'good', // Will be updated if the value changes.\n delta: 0,\n entries: [],\n id: generateUniqueID(),\n navigationType,\n };\n};\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { FirstInputPolyfillEntry, NavigationTimingPolyfillEntry, PerformancePaintTiming } from '../types';\n\nexport interface PerformanceEntryHandler {\n (entry: PerformanceEntry): void;\n}\n\ninterface PerformanceEntryMap {\n event: PerformanceEventTiming[];\n paint: PerformancePaintTiming[];\n 'layout-shift': LayoutShift[];\n 'largest-contentful-paint': LargestContentfulPaint[];\n 'first-input': PerformanceEventTiming[] | FirstInputPolyfillEntry[];\n navigation: PerformanceNavigationTiming[] | NavigationTimingPolyfillEntry[];\n resource: PerformanceResourceTiming[];\n longtask: PerformanceEntry[];\n}\n\n/**\n * Takes a performance entry type and a callback function, and creates a\n * `PerformanceObserver` instance that will observe the specified entry type\n * with buffering enabled and call the callback _for each entry_.\n *\n * This function also feature-detects entry support and wraps the logic in a\n * try/catch to avoid errors in unsupporting browsers.\n */\nexport const observe = <K extends keyof PerformanceEntryMap>(\n type: K,\n callback: (entries: PerformanceEntryMap[K]) => void,\n opts?: PerformanceObserverInit,\n): PerformanceObserver | undefined => {\n try {\n if (PerformanceObserver.supportedEntryTypes.includes(type)) {\n const po = new PerformanceObserver(list => {\n callback(list.getEntries() as PerformanceEntryMap[K]);\n });\n po.observe(\n Object.assign(\n {\n type,\n buffered: true,\n },\n opts || {},\n ) as PerformanceObserverInit,\n );\n return po;\n }\n } catch (e) {\n // Do nothing.\n }\n return;\n};\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { WINDOW } from '../../types';\n\nexport interface OnHiddenCallback {\n (event: Event): void;\n}\n\nexport const onHidden = (cb: OnHiddenCallback, once?: boolean): void => {\n const onHiddenOrPageHide = (event: Event): void => {\n if (event.type === 'pagehide' || WINDOW.document!.visibilityState === 'hidden') {\n cb(event);\n if (once) {\n removeEventListener('visibilitychange', onHiddenOrPageHide, true);\n removeEventListener('pagehide', onHiddenOrPageHide, true);\n }\n }\n };\n\n if (WINDOW.document) {\n addEventListener('visibilitychange', onHiddenOrPageHide, true);\n // Some browsers have buggy implementations of visibilitychange,\n // so we use pagehide in addition, just to be safe.\n addEventListener('pagehide', onHiddenOrPageHide, true);\n }\n};\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { bindReporter } from './lib/bindReporter';\nimport { initMetric } from './lib/initMetric';\nimport { observe } from './lib/observe';\nimport { onHidden } from './lib/onHidden';\nimport type { CLSMetric, ReportCallback, StopListening } from './types';\n\n/**\n * Calculates the [CLS](https://web.dev/cls/) value for the current page and\n * calls the `callback` function once the value is ready to be reported, along\n * with all `layout-shift` performance entries that were used in the metric\n * value calculation. The reported value is a `double` (corresponding to a\n * [layout shift score](https://web.dev/cls/#layout-shift-score)).\n *\n * If the `reportAllChanges` configuration option is set to `true`, the\n * `callback` function will be called as soon as the value is initially\n * determined as well as any time the value changes throughout the page\n * lifespan.\n *\n * _**Important:** CLS should be continually monitored for changes throughout\n * the entire lifespan of a page—including if the user returns to the page after\n * it's been hidden/backgrounded. However, since browsers often [will not fire\n * additional callbacks once the user has backgrounded a\n * page](https://developer.chrome.com/blog/page-lifecycle-api/#advice-hidden),\n * `callback` is always called when the page's visibility state changes to\n * hidden. As a result, the `callback` function might be called multiple times\n * during the same page load._\n */\nexport const onCLS = (\n onReport: ReportCallback,\n options: { reportAllChanges?: boolean } = {},\n): StopListening | undefined => {\n const metric = initMetric('CLS', 0);\n let report: ReturnType<typeof bindReporter>;\n\n let sessionValue = 0;\n let sessionEntries: PerformanceEntry[] = [];\n\n // const handleEntries = (entries: Metric['entries']) => {\n const handleEntries = (entries: LayoutShift[]): void => {\n entries.forEach(entry => {\n // Only count layout shifts without recent user input.\n if (!entry.hadRecentInput) {\n const firstSessionEntry = sessionEntries[0];\n const lastSessionEntry = sessionEntries[sessionEntries.length - 1];\n\n // If the entry occurred less than 1 second after the previous entry and\n // less than 5 seconds after the first entry in the session, include the\n // entry in the current session. Otherwise, start a new session.\n if (\n sessionValue &&\n sessionEntries.length !== 0 &&\n entry.startTime - lastSessionEntry.startTime < 1000 &&\n entry.startTime - firstSessionEntry.startTime < 5000\n ) {\n sessionValue += entry.value;\n sessionEntries.push(entry);\n } else {\n sessionValue = entry.value;\n sessionEntries = [entry];\n }\n\n // If the current session value is larger than the current CLS value,\n // update CLS and the entries contributing to it.\n if (sessionValue > metric.value) {\n metric.value = sessionValue;\n metric.entries = sessionEntries;\n if (report) {\n report();\n }\n }\n }\n });\n };\n\n const po = observe('layout-shift', handleEntries);\n if (po) {\n report = bindReporter(onReport, metric, options.reportAllChanges);\n\n const stopListening = (): void => {\n handleEntries(po.takeRecords() as CLSMetric['entries']);\n report(true);\n };\n\n onHidden(stopListening);\n\n return stopListening;\n }\n\n return;\n};\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { WINDOW } from '../../types';\nimport { onHidden } from './onHidden';\n\nlet firstHiddenTime = -1;\n\nconst initHiddenTime = (): void => {\n // If the document is hidden and not prerendering, assume it was always\n // hidden and the page was loaded in the background.\n if (WINDOW.document && WINDOW.document.visibilityState) {\n firstHiddenTime = WINDOW.document.visibilityState === 'hidden' && !WINDOW.document.prerendering ? 0 : Infinity;\n }\n};\n\nconst trackChanges = (): void => {\n // Update the time if/when the document becomes hidden.\n onHidden(({ timeStamp }) => {\n firstHiddenTime = timeStamp;\n }, true);\n};\n\nexport const getVisibilityWatcher = (): {\n readonly firstHiddenTime: number;\n} => {\n if (firstHiddenTime < 0) {\n // If the document is hidden when this code runs, assume it was hidden\n // since navigation start. This isn't a perfect heuristic, but it's the\n // best we can do until an API is available to support querying past\n // visibilityState.\n initHiddenTime();\n trackChanges();\n }\n return {\n get firstHiddenTime() {\n return firstHiddenTime;\n },\n };\n};\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { bindReporter } from './lib/bindReporter';\nimport { getVisibilityWatcher } from './lib/getVisibilityWatcher';\nimport { initMetric } from './lib/initMetric';\nimport { observe } from './lib/observe';\nimport { onHidden } from './lib/onHidden';\nimport type { FIDMetric, PerformanceEventTiming, ReportCallback } from './types';\n\n/**\n * Calculates the [FID](https://web.dev/fid/) value for the current page and\n * calls the `callback` function once the value is ready, along with the\n * relevant `first-input` performance entry used to determine the value. The\n * reported value is a `DOMHighResTimeStamp`.\n *\n * _**Important:** since FID is only reported after the user interacts with the\n * page, it's possible that it will not be reported for some page loads._\n */\nexport const onFID = (onReport: ReportCallback): void => {\n const visibilityWatcher = getVisibilityWatcher();\n const metric = initMetric('FID');\n // eslint-disable-next-line prefer-const\n let report: ReturnType<typeof bindReporter>;\n\n const handleEntry = (entry: PerformanceEventTiming): void => {\n // Only report if the page wasn't hidden prior to the first input.\n if (entry.startTime < visibilityWatcher.firstHiddenTime) {\n metric.value = entry.processingStart - entry.startTime;\n metric.entries.push(entry);\n report(true);\n }\n };\n\n const handleEntries = (entries: FIDMetric['entries']): void => {\n (entries as PerformanceEventTiming[]).forEach(handleEntry);\n };\n\n const po = observe('first-input', handleEntries);\n report = bindReporter(onReport, metric);\n\n if (po) {\n onHidden(() => {\n handleEntries(po.takeRecords() as FIDMetric['entries']);\n po.disconnect();\n }, true);\n }\n};\n","/*\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { Metric } from '../../types';\nimport { observe } from '../observe';\n\ndeclare global {\n interface Performance {\n interactionCount: number;\n }\n}\n\nlet interactionCountEstimate = 0;\nlet minKnownInteractionId = Infinity;\nlet maxKnownInteractionId = 0;\n\nconst updateEstimate = (entries: Metric['entries']): void => {\n (entries as PerformanceEventTiming[]).forEach(e => {\n if (e.interactionId) {\n minKnownInteractionId = Math.min(minKnownInteractionId, e.interactionId);\n maxKnownInteractionId = Math.max(maxKnownInteractionId, e.interactionId);\n\n interactionCountEstimate = maxKnownInteractionId ? (maxKnownInteractionId - minKnownInteractionId) / 7 + 1 : 0;\n }\n });\n};\n\nlet po: PerformanceObserver | undefined;\n\n/**\n * Returns the `interactionCount` value using the native API (if available)\n * or the polyfill estimate in this module.\n */\nexport const getInteractionCount = (): number => {\n return po ? interactionCountEstimate : performance.interactionCount || 0;\n};\n\n/**\n * Feature detects native support or initializes the polyfill if needed.\n */\nexport const initInteractionCountPolyfill = (): void => {\n if ('interactionCount' in performance || po) return;\n\n po = observe('event', updateEstimate, {\n type: 'event',\n buffered: true,\n durationThreshold: 0,\n } as PerformanceObserverInit);\n};\n","/*\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { bindReporter } from './lib/bindReporter';\nimport { initMetric } from './lib/initMetric';\nimport { observe } from './lib/observe';\nimport { onHidden } from './lib/onHidden';\nimport { getInteractionCount, initInteractionCountPolyfill } from './lib/polyfills/interactionCountPolyfill';\nimport type { ReportCallback, ReportOpts } from './types';\nimport type { INPMetric } from './types/inp';\n\ninterface Interaction {\n id: number;\n latency: number;\n entries: PerformanceEventTiming[];\n}\n\n/**\n * Returns the interaction count since the last bfcache restore (or for the\n * full page lifecycle if there were no bfcache restores).\n */\nconst getInteractionCountForNavigation = (): number => {\n return getInteractionCount();\n};\n\n// To prevent unnecessary memory usage on pages with lots of interactions,\n// store at most 10 of the longest interactions to consider as INP candidates.\nconst MAX_INTERACTIONS_TO_CONSIDER = 10;\n\n// A list of longest interactions on the page (by latency) sorted so the\n// longest one is first. The list is as most MAX_INTERACTIONS_TO_CONSIDER long.\nconst longestInteractionList: Interaction[] = [];\n\n// A mapping of longest interactions by their interaction ID.\n// This is used for faster lookup.\nconst longestInteractionMap: { [interactionId: string]: Interaction } = {};\n\n/**\n * Takes a performance entry and adds it to the list of worst interactions\n * if its duration is long enough to make it among the worst. If the\n * entry is part of an existing interaction, it is merged and the latency\n * and entries list is updated as needed.\n */\nconst processEntry = (entry: PerformanceEventTiming): void => {\n // The least-long of the 10 longest interactions.\n const minLongestInteraction = longestInteractionList[longestInteractionList.length - 1];\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const existingInteraction = longestInteractionMap[entry.interactionId!];\n\n // Only process the entry if it's possibly one of the ten longest,\n // or if it's part of an existing interaction.\n if (\n existingInteraction ||\n longestInteractionList.length < MAX_INTERACTIONS_TO_CONSIDER ||\n entry.duration > minLongestInteraction.latency\n ) {\n // If the interaction already exists, update it. Otherwise create one.\n if (existingInteraction) {\n existingInteraction.entries.push(entry);\n existingInteraction.latency = Math.max(existingInteraction.latency, entry.duration);\n } else {\n const interaction = {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n id: entry.interactionId!,\n latency: entry.duration,\n entries: [entry],\n };\n longestInteractionMap[interaction.id] = interaction;\n longestInteractionList.push(interaction);\n }\n\n // Sort the entries by latency (descending) and keep only the top ten.\n longestInteractionList.sort((a, b) => b.latency - a.latency);\n longestInteractionList.splice(MAX_INTERACTIONS_TO_CONSIDER).forEach(i => {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete longestInteractionMap[i.id];\n });\n }\n};\n\n/**\n * Returns the estimated p98 longest interaction based on the stored\n * interaction candidates and the interaction count for the current page.\n */\nconst estimateP98LongestInteraction = (): Interaction => {\n const candidateInteractionIndex = Math.min(\n longestInteractionList.length - 1,\n Math.floor(getInteractionCountForNavigation() / 50),\n );\n\n return longestInteractionList[candidateInteractionIndex];\n};\n\n/**\n * Calculates the [INP](https://web.dev/responsiveness/) value for the current\n * page and calls the `callback` function once the value is ready, along with\n * the `event` performance entries reported for that interaction. The reported\n * value is a `DOMHighResTimeStamp`.\n *\n * A custom `durationThreshold` configuration option can optionally be passed to\n * control what `event-timing` entries are considered for INP reporting. The\n * default threshold is `40`, which means INP scores of less than 40 are\n * reported as 0. Note that this will not affect your 75th percentile INP value\n * unless that value is also less than 40 (well below the recommended\n * [good](https://web.dev/inp/#what-is-a-good-inp-score) threshold).\n *\n * If the `reportAllChanges` configuration option is set to `true`, the\n * `callback` function will be called as soon as the value is initially\n * determined as well as any time the value changes throughout the page\n * lifespan.\n *\n * _**Important:** INP should be continually monitored for changes throughout\n * the entire lifespan of a page—including if the user returns to the page after\n * it's been hidden/backgrounded. However, since browsers often [will not fire\n * additional callbacks once the user has backgrounded a\n * page](https://developer.chrome.com/blog/page-lifecycle-api/#advice-hidden),\n * `callback` is always called when the page's visibility state changes to\n * hidden. As a result, the `callback` function might be called multiple times\n * during the same page load._\n */\nexport const onINP = (onReport: ReportCallback, opts?: ReportOpts): void => {\n // Set defaults\n // eslint-disable-next-line no-param-reassign\n opts = opts || {};\n\n // https://web.dev/inp/#what's-a-%22good%22-inp-value\n // const thresholds = [200, 500];\n\n // TODO(philipwalton): remove once the polyfill is no longer needed.\n initInteractionCountPolyfill();\n\n const metric = initMetric('INP');\n // eslint-disable-next-line prefer-const\n let report: ReturnType<typeof bindReporter>;\n\n const handleEntries = (entries: INPMetric['entries']): void => {\n entries.forEach(entry => {\n if (entry.interactionId) {\n processEntry(entry);\n }\n\n // Entries of type `first-input` don't currently have an `interactionId`,\n // so to consider them in INP we have to first check that an existing\n // entry doesn't match the `duration` and `startTime`.\n // Note that this logic assumes that `event` entries are dispatched\n // before `first-input` entries. This is true in Chrome but it is not\n // true in Firefox; however, Firefox doesn't support interactionId, so\n // it's not an issue at the moment.\n // TODO(philipwalton): remove once crbug.com/1325826 is fixed.\n if (entry.entryType === 'first-input') {\n const noMatchingEntry = !longestInteractionList.some(interaction => {\n return interaction.entries.some(prevEntry => {\n return entry.duration === prevEntry.duration && entry.startTime === prevEntry.startTime;\n });\n });\n if (noMatchingEntry) {\n processEntry(entry);\n }\n }\n });\n\n const inp = estimateP98LongestInteraction();\n\n if (inp && inp.latency !== metric.value) {\n metric.value = inp.latency;\n metric.entries = inp.entries;\n report();\n }\n };\n\n const po = observe('event', handleEntries, {\n // Event Timing entries have their durations rounded to the nearest 8ms,\n // so a duration of 40ms would be any event that spans 2.5 or more frames\n // at 60Hz. This threshold is chosen to strike a balance between usefulness\n // and performance. Running this callback for any interaction that spans\n // just one or two frames is likely not worth the insight that could be\n // gained.\n durationThreshold: opts.durationThreshold || 40,\n } as PerformanceObserverInit);\n\n report = bindReporter(onReport, metric, opts.reportAllChanges);\n\n if (po) {\n // Also observe entries of type `first-input`. This is useful in cases\n // where the first interaction is less than the `durationThreshold`.\n po.observe({ type: 'first-input', buffered: true });\n\n onHidden(() => {\n handleEntries(po.takeRecords() as INPMetric['entries']);\n\n // If the interaction count shows that there were interactions but\n // none were captured by the PerformanceObserver, report a latency of 0.\n if (metric.value < 0 && getInteractionCountForNavigation() > 0) {\n metric.value = 0;\n metric.entries = [];\n }\n\n report(true);\n });\n }\n};\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { WINDOW } from '../types';\nimport { bindReporter } from './lib/bindReporter';\nimport { getActivationStart } from './lib/getActivationStart';\nimport { getVisibilityWatcher } from './lib/getVisibilityWatcher';\nimport { initMetric } from './lib/initMetric';\nimport { observe } from './lib/observe';\nimport { onHidden } from './lib/onHidden';\nimport type { LCPMetric, ReportCallback, StopListening } from './types';\n\nconst reportedMetricIDs: Record<string, boolean> = {};\n\n/**\n * Calculates the [LCP](https://web.dev/lcp/) value for the current page and\n * calls the `callback` function once the value is ready (along with the\n * relevant `largest-contentful-paint` performance entry used to determine the\n * value). The reported value is a `DOMHighResTimeStamp`.\n */\nexport const onLCP = (onReport: ReportCallback): StopListening | undefined => {\n const visibilityWatcher = getVisibilityWatcher();\n const metric = initMetric('LCP');\n let report: ReturnType<typeof bindReporter>;\n\n const handleEntries = (entries: LCPMetric['entries']): void => {\n const lastEntry = entries[entries.length - 1] as LargestContentfulPaint;\n if (lastEntry) {\n // The startTime attribute returns the value of the renderTime if it is\n // not 0, and the value of the loadTime otherwise. The activationStart\n // reference is used because LCP should be relative to page activation\n // rather than navigation start if the page was prerendered.\n const value = Math.max(lastEntry.startTime - getActivationStart(), 0);\n\n // Only report if the page wasn't hidden prior to LCP.\n if (value < visibilityWatcher.firstHiddenTime) {\n metric.value = value;\n metric.entries = [lastEntry];\n report();\n }\n }\n };\n\n const po = observe('largest-contentful-paint', handleEntries);\n\n if (po) {\n report = bindReporter(onReport, metric);\n\n const stopListening = (): void => {\n if (!reportedMetricIDs[metric.id]) {\n handleEntries(po.takeRecords() as LCPMetric['entries']);\n po.disconnect();\n reportedMetricIDs[metric.id] = true;\n report(true);\n }\n };\n\n // Stop listening after input. Note: while scrolling is an input that\n // stop LCP observation, it's unreliable since it can be programmatically\n // generated. See: https://github.com/GoogleChrome/web-vitals/issues/75\n ['keydown', 'click'].forEach(type => {\n if (WINDOW.document) {\n addEventListener(type, stopListening, { once: true, capture: true });\n }\n });\n\n onHidden(stopListening, true);\n\n return stopListening;\n }\n\n return;\n};\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { WINDOW } from '../types';\nimport { bindReporter } from './lib/bindReporter';\nimport { getActivationStart } from './lib/getActivationStart';\nimport { getNavigationEntry } from './lib/getNavigationEntry';\nimport { initMetric } from './lib/initMetric';\nimport type { ReportCallback, ReportOpts } from './types';\nimport type { TTFBMetric } from './types/ttfb';\n\n/**\n * Runs in the next task after the page is done loading and/or prerendering.\n * @param callback\n */\nconst whenReady = (callback: () => void): void => {\n if (!WINDOW.document) {\n return;\n }\n\n if (WINDOW.document.prerendering) {\n addEventListener('prerenderingchange', () => whenReady(callback), true);\n } else if (WINDOW.document.readyState !== 'complete') {\n addEventListener('load', () => whenReady(callback), true);\n } else {\n // Queue a task so the callback runs after `loadEventEnd`.\n setTimeout(callback, 0);\n }\n};\n\n/**\n * Calculates the [TTFB](https://web.dev/time-to-first-byte/) value for the\n * current page and calls the `callback` function once the page has loaded,\n * along with the relevant `navigation` performance entry used to determine the\n * value. The reported value is a `DOMHighResTimeStamp`.\n *\n * Note, this function waits until after the page is loaded to call `callback`\n * in order to ensure all properties of the `navigation` entry are populated.\n * This is useful if you want to report on other metrics exposed by the\n * [Navigation Timing API](https://w3c.github.io/navigation-timing/). For\n * example, the TTFB metric starts from the page's [time\n * origin](https://www.w3.org/TR/hr-time-2/#sec-time-origin), which means it\n * includes time spent on DNS lookup, connection negotiation, network latency,\n * and server processing time.\n */\nexport const onTTFB = (onReport: ReportCallback, opts?: ReportOpts): void => {\n // Set defaults\n // eslint-disable-next-line no-param-reassign\n opts = opts || {};\n\n // https://web.dev/ttfb/#what-is-a-good-ttfb-score\n // const thresholds = [800, 1800];\n\n const metric = initMetric('TTFB');\n const report = bindReporter(onReport, metric, opts.reportAllChanges);\n\n whenReady(() => {\n const navEntry = getNavigationEntry() as TTFBMetric['entries'][number];\n\n if (navEntry) {\n // The activationStart reference is used because TTFB should be\n // relative to page activation rather than navigation start if the\n // page was prerendered. But in cases where `activationStart` occurs\n // after the first byte is received, this time should be clamped at 0.\n metric.value = Math.max(navEntry.responseStart - getActivationStart(), 0);\n\n // In some cases the value reported is negative or is larger\n // than the current page time. Ignore these cases:\n // https://github.com/GoogleChrome/web-vitals/issues/137\n // https://github.com/GoogleChrome/web-vitals/issues/162\n if (metric.value < 0 || metric.value > performance.now()) return;\n\n metric.entries = [navEntry];\n\n report(true);\n }\n });\n};\n","import { getFunctionName, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../common/debug-build';\nimport { onCLS } from './web-vitals/getCLS';\nimport { onFID } from './web-vitals/getFID';\nimport { onINP } from './web-vitals/getINP';\nimport { onLCP } from './web-vitals/getLCP';\nimport { observe } from './web-vitals/lib/observe';\nimport { onTTFB } from './web-vitals/onTTFB';\n\ntype InstrumentHandlerTypePerformanceObserver =\n | 'longtask'\n | 'event'\n | 'navigation'\n | 'paint'\n | 'resource'\n | 'first-input';\n\ntype InstrumentHandlerTypeMetric = 'cls' | 'lcp' | 'fid' | 'ttfb' | 'inp';\n\n// We provide this here manually instead of relying on a global, as this is not available in non-browser environements\n// And we do not want to expose such types\ninterface PerformanceEntry {\n readonly duration: number;\n readonly entryType: string;\n readonly name: string;\n readonly startTime: number;\n toJSON(): Record<string, unknown>;\n}\ninterface PerformanceEventTiming extends PerformanceEntry {\n processingStart: number;\n processingEnd: number;\n duration: number;\n cancelable?: boolean;\n target?: unknown | null;\n interactionId?: number;\n}\n\ninterface Metric {\n /**\n * The name of the metric (in acronym form).\n */\n name: 'CLS' | 'FCP' | 'FID' | 'INP' | 'LCP' | 'TTFB';\n\n /**\n * The current value of the metric.\n */\n value: number;\n\n /**\n * The rating as to whether the metric value is within the \"good\",\n * \"needs improvement\", or \"poor\" thresholds of the metric.\n */\n rating: 'good' | 'needs-improvement' | 'poor';\n\n /**\n * The delta between the current value and the last-reported value.\n * On the first report, `delta` and `value` will always be the same.\n */\n delta: number;\n\n /**\n * A unique ID representing this particular metric instance. This ID can\n * be used by an analytics tool to dedupe multiple values sent for the same\n * metric instance, or to group multiple deltas together and calculate a\n * total. It can also be used to differentiate multiple different metric\n * instances sent from the same page, which can happen if the page is\n * restored from the back/forward cache (in that case new metrics object\n * get created).\n */\n id: string;\n\n /**\n * Any performance entries relevant to the metric value calculation.\n * The array may also be empty if the metric value was not based on any\n * entries (e.g. a CLS value of 0 given no layout shifts).\n */\n entries: PerformanceEntry[];\n\n /**\n * The type of navigation\n *\n * Navigation Timing API (or `undefined` if the browser doesn't\n * support that API). For pages that are restored from the bfcache, this\n * value will be 'back-forward-cache'.\n */\n navigationType: 'navigate' | 'reload' | 'back-forward' | 'back-forward-cache' | 'prerender';\n}\n\ntype InstrumentHandlerType = InstrumentHandlerTypeMetric | InstrumentHandlerTypePerformanceObserver;\n\ntype StopListening = undefined | void | (() => void);\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype InstrumentHandlerCallback = (data: any) => void;\n\ntype CleanupHandlerCallback = () => void;\n\nconst handlers: { [key in InstrumentHandlerType]?: InstrumentHandlerCallback[] } = {};\nconst instrumented: { [key in InstrumentHandlerType]?: boolean } = {};\n\nlet _previousCls: Metric | undefined;\nlet _previousFid: Metric | undefined;\nlet _previousLcp: Metric | undefined;\nlet _previousTtfb: Metric | undefined;\nlet _previousInp: Metric | undefined;\n\n/**\n * Add a callback that will be triggered when a CLS metric is available.\n * Returns a cleanup callback which can be called to remove the instrumentation handler.\n *\n * Pass `stopOnCallback = true` to stop listening for CLS when the cleanup callback is called.\n * This will lead to the CLS being finalized and frozen.\n */\nexport function addClsInstrumentationHandler(\n callback: (data: { metric: Metric }) => void,\n stopOnCallback = false,\n): CleanupHandlerCallback {\n return addMetricObserver('cls', callback, instrumentCls, _previousCls, stopOnCallback);\n}\n\n/**\n * Add a callback that will be triggered when a LCP metric is available.\n * Returns a cleanup callback which can be called to remove the instrumentation handler.\n *\n * Pass `stopOnCallback = true` to stop listening for LCP when the cleanup callback is called.\n * This will lead to the LCP being finalized and frozen.\n */\nexport function addLcpInstrumentationHandler(\n callback: (data: { metric: Metric }) => void,\n stopOnCallback = false,\n): CleanupHandlerCallback {\n return addMetricObserver('lcp', callback, instrumentLcp, _previousLcp, stopOnCallback);\n}\n\n/**\n * Add a callback that will be triggered when a FID metric is available.\n */\nexport function addTtfbInstrumentationHandler(callback: (data: { metric: Metric }) => void): CleanupHandlerCallback {\n return addMetricObserver('ttfb', callback, instrumentTtfb, _previousTtfb);\n}\n\n/**\n * Add a callback that will be triggered when a FID metric is available.\n * Returns a cleanup callback which can be called to remove the instrumentation handler.\n */\nexport function addFidInstrumentationHandler(callback: (data: { metric: Metric }) => void): CleanupHandlerCallback {\n return addMetricObserver('fid', callback, instrumentFid, _previousFid);\n}\n\n/**\n * Add a callback that will be triggered when a INP metric is available.\n * Returns a cleanup callback which can be called to remove the instrumentation handler.\n */\nexport function addInpInstrumentationHandler(\n callback: (data: { metric: Omit<Metric, 'entries'> & { entries: PerformanceEventTiming[] } }) => void,\n): CleanupHandlerCallback {\n return addMetricObserver('inp', callback, instrumentInp, _previousInp);\n}\n\nexport function addPerformanceInstrumentationHandler(\n type: 'event' | 'first-input',\n callback: (data: { entries: ((PerformanceEntry & { target?: unknown | null }) | PerformanceEventTiming)[] }) => void,\n): CleanupHandlerCallback;\nexport function addPerformanceInstrumentationHandler(\n type: InstrumentHandlerTypePerformanceObserver,\n callback: (data: { entries: PerformanceEntry[] }) => void,\n): CleanupHandlerCallback;\n\n/**\n * Add a callback that will be triggered when a performance observer is triggered,\n * and receives the entries of the observer.\n * Returns a cleanup callback which can be called to remove the instrumentation handler.\n */\nexport function addPerformanceInstrumentationHandler(\n type: InstrumentHandlerTypePerformanceObserver,\n callback: (data: { entries: PerformanceEntry[] }) => void,\n): CleanupHandlerCallback {\n addHandler(type, callback);\n\n if (!instrumented[type]) {\n instrumentPerformanceObserver(type);\n instrumented[type] = true;\n }\n\n return getCleanupCallback(type, callback);\n}\n\n/** Trigger all handlers of a given type. */\nfunction triggerHandlers(type: InstrumentHandlerType, data: unknown): void {\n const typeHandlers = handlers[type];\n\n if (!typeHandlers || !typeHandlers.length) {\n return;\n }\n\n for (const handler of typeHandlers) {\n try {\n handler(data);\n } catch (e) {\n DEBUG_BUILD &&\n logger.error(\n `Error while triggering instrumentation handler.\\nType: ${type}\\nName: ${getFunctionName(handler)}\\nError:`,\n e,\n );\n }\n }\n}\n\nfunction instrumentCls(): StopListening {\n return onCLS(\n metric => {\n triggerHandlers('cls', {\n metric,\n });\n _previousCls = metric;\n },\n { reportAllChanges: true },\n );\n}\n\nfunction instrumentFid(): void {\n return onFID(metric => {\n triggerHandlers('fid', {\n metric,\n });\n _previousFid = metric;\n });\n}\n\nfunction instrumentLcp(): StopListening {\n return onLCP(metric => {\n triggerHandlers('lcp', {\n metric,\n });\n _previousLcp = metric;\n });\n}\n\nfunction instrumentTtfb(): StopListening {\n return onTTFB(metric => {\n triggerHandlers('ttfb', {\n metric,\n });\n _previousTtfb = metric;\n });\n}\n\nfunction instrumentInp(): void {\n return onINP(metric => {\n triggerHandlers('inp', {\n metric,\n });\n _previousInp = metric;\n });\n}\n\nfunction addMetricObserver(\n type: InstrumentHandlerTypeMetric,\n callback: InstrumentHandlerCallback,\n instrumentFn: () => StopListening,\n previousValue: Metric | undefined,\n stopOnCallback = false,\n): CleanupHandlerCallback {\n addHandler(type, callback);\n\n let stopListening: StopListening | undefined;\n\n if (!instrumented[type]) {\n stopListening = instrumentFn();\n instrumented[type] = true;\n }\n\n if (previousValue) {\n callback({ metric: previousValue });\n }\n\n return getCleanupCallback(type, callback, stopOnCallback ? stopListening : undefined);\n}\n\nfunction instrumentPerformanceObserver(type: InstrumentHandlerTypePerformanceObserver): void {\n const options: PerformanceObserverInit = {};\n\n // Special per-type options we want to use\n if (type === 'event') {\n options.durationThreshold = 0;\n }\n\n observe(\n type,\n entries => {\n triggerHandlers(type, { entries });\n },\n options,\n );\n}\n\nfunction addHandler(type: InstrumentHandlerType, handler: InstrumentHandlerCallback): void {\n handlers[type] = handlers[type] || [];\n (handlers[type] as InstrumentHandlerCallback[]).push(handler);\n}\n\n// Get a callback which can be called to remove the instrumentation handler\nfunction getCleanupCallback(\n type: InstrumentHandlerType,\n callback: InstrumentHandlerCallback,\n stopListening: StopListening,\n): CleanupHandlerCallback {\n return () => {\n if (stopListening) {\n stopListening();\n }\n\n const typeHandlers = handlers[type];\n\n if (!typeHandlers) {\n return;\n }\n\n const index = typeHandlers.indexOf(callback);\n if (index !== -1) {\n typeHandlers.splice(index, 1);\n }\n };\n}\n","/* eslint-disable max-lines */\nimport {\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n getClient,\n getCurrentScope,\n getDynamicSamplingContextFromClient,\n getDynamicSamplingContextFromSpan,\n getIsolationScope,\n hasTracingEnabled,\n setHttpStatus,\n spanToJSON,\n spanToTraceHeader,\n startInactiveSpan,\n} from '@sentry/core';\nimport type { HandlerDataXhr, SentryWrappedXMLHttpRequest, Span } from '@sentry/types';\nimport {\n BAGGAGE_HEADER_NAME,\n SENTRY_XHR_DATA_KEY,\n addFetchInstrumentationHandler,\n addXhrInstrumentationHandler,\n browserPerformanceTimeOrigin,\n dynamicSamplingContextToSentryBaggageHeader,\n generateSentryTraceHeader,\n parseUrl,\n stringMatchesSomePattern,\n} from '@sentry/utils';\n\nimport { instrumentFetchRequest } from '../common/fetch';\nimport { addPerformanceInstrumentationHandler } from './instrument';\nimport { WINDOW } from './types';\n\nexport const DEFAULT_TRACE_PROPAGATION_TARGETS = ['localhost', /^\\/(?!\\/)/];\n\n/** Options for Request Instrumentation */\nexport interface RequestInstrumentationOptions {\n /**\n * @deprecated Will be removed in v8.\n * Use `shouldCreateSpanForRequest` to control span creation and `tracePropagationTargets` to control\n * trace header attachment.\n */\n tracingOrigins: Array<string | RegExp>;\n\n /**\n * List of strings and/or regexes used to determine which outgoing requests will have `sentry-trace` and `baggage`\n * headers attached.\n *\n * @deprecated Use the top-level `tracePropagationTargets` option in `Sentry.init` instead.\n * This option will be removed in v8.\n *\n * Default: ['localhost', /^\\//] @see {DEFAULT_TRACE_PROPAGATION_TARGETS}\n */\n tracePropagationTargets: Array<string | RegExp>;\n\n /**\n * Flag to disable patching all together for fetch requests.\n *\n * Default: true\n */\n traceFetch: boolean;\n\n /**\n * Flag to disable patching all together for xhr requests.\n *\n * Default: true\n */\n traceXHR: boolean;\n\n /**\n * If true, Sentry will capture http timings and add them to the corresponding http spans.\n *\n * Default: true\n */\n enableHTTPTimings: boolean;\n\n /**\n * This function will be called before creating a span for a request with the given url.\n * Return false if you don't want a span for the given url.\n *\n * Default: (url: string) => true\n */\n shouldCreateSpanForRequest?(this: void, url: string): boolean;\n}\n\nexport const defaultRequestInstrumentationOptions: RequestInstrumentationOptions = {\n traceFetch: true,\n traceXHR: true,\n enableHTTPTimings: true,\n // TODO (v8): Remove this property\n tracingOrigins: DEFAULT_TRACE_PROPAGATION_TARGETS,\n tracePropagationTargets: DEFAULT_TRACE_PROPAGATION_TARGETS,\n};\n\n/** Registers span creators for xhr and fetch requests */\nexport function instrumentOutgoingRequests(_options?: Partial<RequestInstrumentationOptions>): void {\n const {\n traceFetch,\n traceXHR,\n // eslint-disable-next-line deprecation/deprecation\n tracePropagationTargets,\n // eslint-disable-next-line deprecation/deprecation\n tracingOrigins,\n shouldCreateSpanForRequest,\n enableHTTPTimings,\n } = {\n traceFetch: defaultRequestInstrumentationOptions.traceFetch,\n traceXHR: defaultRequestInstrumentationOptions.traceXHR,\n ..._options,\n };\n\n const shouldCreateSpan =\n typeof shouldCreateSpanForRequest === 'function' ? shouldCreateSpanForRequest : (_: string) => true;\n\n // TODO(v8) Remove tracingOrigins here\n // The only reason we're passing it in here is because this instrumentOutgoingRequests function is publicly exported\n // and we don't want to break the API. We can remove it in v8.\n const shouldAttachHeadersWithTargets = (url: string): boolean =>\n shouldAttachHeaders(url, tracePropagationTargets || tracingOrigins);\n\n const spans: Record<string, Span> = {};\n\n if (traceFetch) {\n addFetchInstrumentationHandler(handlerData => {\n const createdSpan = instrumentFetchRequest(handlerData, shouldCreateSpan, shouldAttachHeadersWithTargets, spans);\n // We cannot use `window.location` in the generic fetch instrumentation,\n // but we need it for reliable `server.address` attribute.\n // so we extend this in here\n if (createdSpan) {\n const fullUrl = getFullURL(handlerData.fetchData.url);\n const host = fullUrl ? parseUrl(fullUrl).host : undefined;\n createdSpan.setAttributes({\n 'http.url': fullUrl,\n 'server.address': host,\n });\n }\n\n if (enableHTTPTimings && createdSpan) {\n addHTTPTimings(createdSpan);\n }\n });\n }\n\n if (traceXHR) {\n addXhrInstrumentationHandler(handlerData => {\n const createdSpan = xhrCallback(handlerData, shouldCreateSpan, shouldAttachHeadersWithTargets, spans);\n if (enableHTTPTimings && createdSpan) {\n addHTTPTimings(createdSpan);\n }\n });\n }\n}\n\nfunction isPerformanceResourceTiming(entry: PerformanceEntry): entry is PerformanceResourceTiming {\n return (\n entry.entryType === 'resource' &&\n 'initiatorType' in entry &&\n typeof (entry as PerformanceResourceTiming).nextHopProtocol === 'string' &&\n (entry.initiatorType === 'fetch' || entry.initiatorType === 'xmlhttprequest')\n );\n}\n\n/**\n * Creates a temporary observer to listen to the next fetch/xhr resourcing timings,\n * so that when timings hit their per-browser limit they don't need to be removed.\n *\n * @param span A span that has yet to be finished, must contain `url` on data.\n */\nfunction addHTTPTimings(span: Span): void {\n const { url } = spanToJSON(span).data || {};\n\n if (!url || typeof url !== 'string') {\n return;\n }\n\n const cleanup = addPerformanceInstrumentationHandler('resource', ({ entries }) => {\n entries.forEach(entry => {\n if (isPerformanceResourceTiming(entry) && entry.name.endsWith(url)) {\n const spanData = resourceTimingEntryToSpanData(entry);\n spanData.forEach(data => span.setAttribute(...data));\n // In the next tick, clean this handler up\n // We have to wait here because otherwise this cleans itself up before it is fully done\n setTimeout(cleanup);\n }\n });\n });\n}\n\n/**\n * Converts ALPN protocol ids to name and version.\n *\n * (https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#alpn-protocol-ids)\n * @param nextHopProtocol PerformanceResourceTiming.nextHopProtocol\n */\nexport function extractNetworkProtocol(nextHopProtocol: string): { name: string; version: string } {\n let name = 'unknown';\n let version = 'unknown';\n let _name = '';\n for (const char of nextHopProtocol) {\n // http/1.1 etc.\n if (char === '/') {\n [name, version] = nextHopProtocol.split('/');\n break;\n }\n // h2, h3 etc.\n if (!isNaN(Number(char))) {\n name = _name === 'h' ? 'http' : _name;\n version = nextHopProtocol.split(_name)[1];\n break;\n }\n _name += char;\n }\n if (_name === nextHopProtocol) {\n // webrtc, ftp, etc.\n name = _name;\n }\n return { name, version };\n}\n\nfunction getAbsoluteTime(time: number = 0): number {\n return ((browserPerformanceTimeOrigin || performance.timeOrigin) + time) / 1000;\n}\n\nfunction resourceTimingEntryToSpanData(resourceTiming: PerformanceResourceTiming): [string, string | number][] {\n const { name, version } = extractNetworkProtocol(resourceTiming.nextHopProtocol);\n\n const timingSpanData: [string, string | number][] = [];\n\n timingSpanData.push(['network.protocol.version', version], ['network.protocol.name', name]);\n\n if (!browserPerformanceTimeOrigin) {\n return timingSpanData;\n }\n return [\n ...timingSpanData,\n ['http.request.redirect_start', getAbsoluteTime(resourceTiming.redirectStart)],\n ['http.request.fetch_start', getAbsoluteTime(resourceTiming.fetchStart)],\n ['http.request.domain_lookup_start', getAbsoluteTime(resourceTiming.domainLookupStart)],\n ['http.request.domain_lookup_end', getAbsoluteTime(resourceTiming.domainLookupEnd)],\n ['http.request.connect_start', getAbsoluteTime(resourceTiming.connectStart)],\n ['http.request.secure_connection_start', getAbsoluteTime(resourceTiming.secureConnectionStart)],\n ['http.request.connection_end', getAbsoluteTime(resourceTiming.connectEnd)],\n ['http.request.request_start', getAbsoluteTime(resourceTiming.requestStart)],\n ['http.request.response_start', getAbsoluteTime(resourceTiming.responseStart)],\n ['http.request.response_end', getAbsoluteTime(resourceTiming.responseEnd)],\n ];\n}\n\n/**\n * A function that determines whether to attach tracing headers to a request.\n * This was extracted from `instrumentOutgoingRequests` to make it easier to test shouldAttachHeaders.\n * We only export this fuction for testing purposes.\n */\nexport function shouldAttachHeaders(url: string, tracePropagationTargets: (string | RegExp)[] | undefined): boolean {\n return stringMatchesSomePattern(url, tracePropagationTargets || DEFAULT_TRACE_PROPAGATION_TARGETS);\n}\n\n/**\n * Create and track xhr request spans\n *\n * @returns Span if a span was created, otherwise void.\n */\n// eslint-disable-next-line complexity\nexport function xhrCallback(\n handlerData: HandlerDataXhr,\n shouldCreateSpan: (url: string) => boolean,\n shouldAttachHeaders: (url: string) => boolean,\n spans: Record<string, Span>,\n): Span | undefined {\n const xhr = handlerData.xhr;\n const sentryXhrData = xhr && xhr[SENTRY_XHR_DATA_KEY];\n\n if (!hasTracingEnabled() || !xhr || xhr.__sentry_own_request__ || !sentryXhrData) {\n return undefined;\n }\n\n const shouldCreateSpanResult = shouldCreateSpan(sentryXhrData.url);\n\n // check first if the request has finished and is tracked by an existing span which should now end\n if (handlerData.endTimestamp && shouldCreateSpanResult) {\n const spanId = xhr.__sentry_xhr_span_id__;\n if (!spanId) return;\n\n const span = spans[spanId];\n if (span && sentryXhrData.status_code !== undefined) {\n setHttpStatus(span, sentryXhrData.status_code);\n span.end();\n\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete spans[spanId];\n }\n return undefined;\n }\n\n const scope = getCurrentScope();\n const isolationScope = getIsolationScope();\n\n const fullUrl = getFullURL(sentryXhrData.url);\n const host = fullUrl ? parseUrl(fullUrl).host : undefined;\n\n const span = shouldCreateSpanResult\n ? startInactiveSpan({\n name: `${sentryXhrData.method} ${sentryXhrData.url}`,\n onlyIfParent: true,\n attributes: {\n type: 'xhr',\n 'http.method': sentryXhrData.method,\n 'http.url': fullUrl,\n url: sentryXhrData.url,\n 'server.address': host,\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.browser',\n },\n op: 'http.client',\n })\n : undefined;\n\n if (span) {\n xhr.__sentry_xhr_span_id__ = span.spanContext().spanId;\n spans[xhr.__sentry_xhr_span_id__] = span;\n }\n\n const client = getClient();\n\n if (xhr.setRequestHeader && shouldAttachHeaders(sentryXhrData.url) && client) {\n const { traceId, spanId, sampled, dsc } = {\n ...isolationScope.getPropagationContext(),\n ...scope.getPropagationContext(),\n };\n\n const sentryTraceHeader = span ? spanToTraceHeader(span) : generateSentryTraceHeader(traceId, spanId, sampled);\n\n const sentryBaggageHeader = dynamicSamplingContextToSentryBaggageHeader(\n dsc ||\n (span ? getDynamicSamplingContextFromSpan(span) : getDynamicSamplingContextFromClient(traceId, client, scope)),\n );\n\n setHeaderOnXhr(xhr, sentryTraceHeader, sentryBaggageHeader);\n }\n\n return span;\n}\n\nfunction setHeaderOnXhr(\n xhr: SentryWrappedXMLHttpRequest,\n sentryTraceHeader: string,\n sentryBaggageHeader: string | undefined,\n): void {\n try {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n xhr.setRequestHeader!('sentry-trace', sentryTraceHeader);\n if (sentryBaggageHeader) {\n // From MDN: \"If this method is called several times with the same header, the values are merged into one single request header.\"\n // We can therefore simply set a baggage header without checking what was there before\n // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n xhr.setRequestHeader!(BAGGAGE_HEADER_NAME, sentryBaggageHeader);\n }\n } catch (_) {\n // Error: InvalidStateError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': The object's state must be OPENED.\n }\n}\n\nfunction getFullURL(url: string): string | undefined {\n try {\n // By adding a base URL to new URL(), this will also work for relative urls\n // If `url` is a full URL, the base URL is ignored anyhow\n const parsed = new URL(url, WINDOW.location.origin);\n return parsed.href;\n } catch {\n return undefined;\n }\n}\n","import type { IdleTransaction, SpanStatusType } from '@sentry/core';\nimport { getActiveTransaction, spanToJSON } from '@sentry/core';\nimport { logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../common/debug-build';\nimport { WINDOW } from './types';\n\n/**\n * Add a listener that cancels and finishes a transaction when the global\n * document is hidden.\n */\nexport function registerBackgroundTabDetection(): void {\n if (WINDOW.document) {\n WINDOW.document.addEventListener('visibilitychange', () => {\n // eslint-disable-next-line deprecation/deprecation\n const activeTransaction = getActiveTransaction() as IdleTransaction;\n if (WINDOW.document!.hidden && activeTransaction) {\n const statusType: SpanStatusType = 'cancelled';\n\n const { op, status } = spanToJSON(activeTransaction);\n\n DEBUG_BUILD &&\n logger.log(`[Tracing] Transaction: ${statusType} -> since tab moved to the background, op: ${op}`);\n // We should not set status if it is already set, this prevent important statuses like\n // error or data loss from being overwritten on transaction.\n if (!status) {\n activeTransaction.setStatus(statusType);\n }\n // TODO: Can we rewrite this to an attribute?\n // eslint-disable-next-line deprecation/deprecation\n activeTransaction.setTag('visibilitychange', 'document.hidden');\n activeTransaction.end();\n }\n });\n } else {\n DEBUG_BUILD && logger.warn('[Tracing] Could not set up background tab detection due to lack of global document');\n }\n}\n","import type { Transaction } from '@sentry/core';\nimport type { Span, SpanContext } from '@sentry/types';\n\n/**\n * Checks if a given value is a valid measurement value.\n */\nexport function isMeasurementValue(value: unknown): value is number {\n return typeof value === 'number' && isFinite(value);\n}\n\n/**\n * Helper function to start child on transactions. This function will make sure that the transaction will\n * use the start timestamp of the created child span if it is earlier than the transactions actual\n * start timestamp.\n *\n * Note: this will not be possible anymore in v8,\n * unless we do some special handling for browser here...\n */\nexport function _startChild(transaction: Transaction, { startTimestamp, ...ctx }: SpanContext): Span {\n // eslint-disable-next-line deprecation/deprecation\n if (startTimestamp && transaction.startTimestamp > startTimestamp) {\n // eslint-disable-next-line deprecation/deprecation\n transaction.startTimestamp = startTimestamp;\n }\n\n // eslint-disable-next-line deprecation/deprecation\n return transaction.startChild({\n startTimestamp,\n ...ctx,\n });\n}\n","/* eslint-disable max-lines */\nimport type { IdleTransaction, Transaction } from '@sentry/core';\nimport {\n Span,\n getActiveTransaction,\n getClient,\n hasTracingEnabled,\n isValidSampleRate,\n setMeasurement,\n} from '@sentry/core';\nimport type { ClientOptions, Measurements, SpanContext, TransactionContext } from '@sentry/types';\nimport { browserPerformanceTimeOrigin, getComponentName, htmlTreeAsString, logger, parseUrl } from '@sentry/utils';\n\nimport { spanToJSON } from '@sentry/core';\nimport { DEBUG_BUILD } from '../../common/debug-build';\nimport {\n addClsInstrumentationHandler,\n addFidInstrumentationHandler,\n addInpInstrumentationHandler,\n addLcpInstrumentationHandler,\n addPerformanceInstrumentationHandler,\n addTtfbInstrumentationHandler,\n} from '../instrument';\nimport { WINDOW } from '../types';\nimport { getVisibilityWatcher } from '../web-vitals/lib/getVisibilityWatcher';\nimport type {\n InteractionRouteNameMapping,\n NavigatorDeviceMemory,\n NavigatorNetworkInformation,\n} from '../web-vitals/types';\nimport { _startChild, isMeasurementValue } from './utils';\n\nimport { createSpanEnvelope } from '@sentry/core';\nimport { getNavigationEntry } from '../web-vitals/lib/getNavigationEntry';\n\nconst MAX_INT_AS_BYTES = 2147483647;\n\n/**\n * Converts from milliseconds to seconds\n * @param time time in ms\n */\nfunction msToSec(time: number): number {\n return time / 1000;\n}\n\nfunction getBrowserPerformanceAPI(): Performance | undefined {\n // @ts-expect-error we want to make sure all of these are available, even if TS is sure they are\n return WINDOW && WINDOW.addEventListener && WINDOW.performance;\n}\n\nlet _performanceCursor: number = 0;\n\nlet _measurements: Measurements = {};\nlet _lcpEntry: LargestContentfulPaint | undefined;\nlet _clsEntry: LayoutShift | undefined;\n\n/**\n * Start tracking web vitals.\n * The callback returned by this function can be used to stop tracking & ensure all measurements are final & captured.\n *\n * @returns A function that forces web vitals collection\n */\nexport function startTrackingWebVitals(): () => void {\n const performance = getBrowserPerformanceAPI();\n if (performance && browserPerformanceTimeOrigin) {\n // @ts-expect-error we want to make sure all of these are available, even if TS is sure they are\n if (performance.mark) {\n WINDOW.performance.mark('sentry-tracing-init');\n }\n const fidCallback = _trackFID();\n const clsCallback = _trackCLS();\n const lcpCallback = _trackLCP();\n const ttfbCallback = _trackTtfb();\n\n return (): void => {\n fidCallback();\n clsCallback();\n lcpCallback();\n ttfbCallback();\n };\n }\n\n return () => undefined;\n}\n\n/**\n * Start tracking long tasks.\n */\nexport function startTrackingLongTasks(): void {\n addPerformanceInstrumentationHandler('longtask', ({ entries }) => {\n for (const entry of entries) {\n // eslint-disable-next-line deprecation/deprecation\n const transaction = getActiveTransaction() as IdleTransaction | undefined;\n if (!transaction) {\n return;\n }\n const startTime = msToSec((browserPerformanceTimeOrigin as number) + entry.startTime);\n const duration = msToSec(entry.duration);\n\n // eslint-disable-next-line deprecation/deprecation\n transaction.startChild({\n description: 'Main UI thread blocked',\n op: 'ui.long-task',\n origin: 'auto.ui.browser.metrics',\n startTimestamp: startTime,\n endTimestamp: startTime + duration,\n });\n }\n });\n}\n\n/**\n * Start tracking interaction events.\n */\nexport function startTrackingInteractions(): void {\n addPerformanceInstrumentationHandler('event', ({ entries }) => {\n for (const entry of entries) {\n // eslint-disable-next-line deprecation/deprecation\n const transaction = getActiveTransaction() as IdleTransaction | undefined;\n if (!transaction) {\n return;\n }\n\n if (entry.name === 'click') {\n const startTime = msToSec((browserPerformanceTimeOrigin as number) + entry.startTime);\n const duration = msToSec(entry.duration);\n\n const span: SpanContext = {\n description: htmlTreeAsString(entry.target),\n op: `ui.interaction.${entry.name}`,\n origin: 'auto.ui.browser.metrics',\n startTimestamp: startTime,\n endTimestamp: startTime + duration,\n };\n\n const componentName = getComponentName(entry.target);\n if (componentName) {\n span.attributes = { 'ui.component_name': componentName };\n }\n\n // eslint-disable-next-line deprecation/deprecation\n transaction.startChild(span);\n }\n }\n });\n}\n\n/**\n * Start tracking INP webvital events.\n */\nexport function startTrackingINP(\n interactionIdtoRouteNameMapping: InteractionRouteNameMapping,\n interactionsSampleRate: number,\n): () => void {\n const performance = getBrowserPerformanceAPI();\n if (performance && browserPerformanceTimeOrigin) {\n const inpCallback = _trackINP(interactionIdtoRouteNameMapping, interactionsSampleRate);\n\n return (): void => {\n inpCallback();\n };\n }\n\n return () => undefined;\n}\n\n/** Starts tracking the Cumulative Layout Shift on the current page. */\nfunction _trackCLS(): () => void {\n return addClsInstrumentationHandler(({ metric }) => {\n const entry = metric.entries[metric.entries.length - 1];\n if (!entry) {\n return;\n }\n\n DEBUG_BUILD && logger.log('[Measurements] Adding CLS');\n _measurements['cls'] = { value: metric.value, unit: '' };\n _clsEntry = entry as LayoutShift;\n }, true);\n}\n\n/** Starts tracking the Largest Contentful Paint on the current page. */\nfunction _trackLCP(): () => void {\n return addLcpInstrumentationHandler(({ metric }) => {\n const entry = metric.entries[metric.entries.length - 1];\n if (!entry) {\n return;\n }\n\n DEBUG_BUILD && logger.log('[Measurements] Adding LCP');\n _measurements['lcp'] = { value: metric.value, unit: 'millisecond' };\n _lcpEntry = entry as LargestContentfulPaint;\n }, true);\n}\n\n/** Starts tracking the First Input Delay on the current page. */\nfunction _trackFID(): () => void {\n return addFidInstrumentationHandler(({ metric }) => {\n const entry = metric.entries[metric.entries.length - 1];\n if (!entry) {\n return;\n }\n\n const timeOrigin = msToSec(browserPerformanceTimeOrigin as number);\n const startTime = msToSec(entry.startTime);\n DEBUG_BUILD && logger.log('[Measurements] Adding FID');\n _measurements['fid'] = { value: metric.value, unit: 'millisecond' };\n _measurements['mark.fid'] = { value: timeOrigin + startTime, unit: 'second' };\n });\n}\n\nfunction _trackTtfb(): () => void {\n return addTtfbInstrumentationHandler(({ metric }) => {\n const entry = metric.entries[metric.entries.length - 1];\n if (!entry) {\n return;\n }\n\n DEBUG_BUILD && logger.log('[Measurements] Adding TTFB');\n _measurements['ttfb'] = { value: metric.value, unit: 'millisecond' };\n });\n}\n\nconst INP_ENTRY_MAP: Record<string, 'click' | 'hover' | 'drag' | 'press'> = {\n click: 'click',\n pointerdown: 'click',\n pointerup: 'click',\n mousedown: 'click',\n mouseup: 'click',\n touchstart: 'click',\n touchend: 'click',\n mouseover: 'hover',\n mouseout: 'hover',\n mouseenter: 'hover',\n mouseleave: 'hover',\n pointerover: 'hover',\n pointerout: 'hover',\n pointerenter: 'hover',\n pointerleave: 'hover',\n dragstart: 'drag',\n dragend: 'drag',\n drag: 'drag',\n dragenter: 'drag',\n dragleave: 'drag',\n dragover: 'drag',\n drop: 'drag',\n keydown: 'press',\n keyup: 'press',\n keypress: 'press',\n input: 'press',\n};\n\n/** Starts tracking the Interaction to Next Paint on the current page. */\nfunction _trackINP(\n interactionIdToRouteNameMapping: InteractionRouteNameMapping,\n interactionsSampleRate: number,\n): () => void {\n return addInpInstrumentationHandler(({ metric }) => {\n if (metric.value === undefined) {\n return;\n }\n const entry = metric.entries.find(\n entry => entry.duration === metric.value && INP_ENTRY_MAP[entry.name] !== undefined,\n );\n const client = getClient();\n if (!entry || !client) {\n return;\n }\n const interactionType = INP_ENTRY_MAP[entry.name];\n const options = client.getOptions();\n /** Build the INP span, create an envelope from the span, and then send the envelope */\n const startTime = msToSec((browserPerformanceTimeOrigin as number) + entry.startTime);\n const duration = msToSec(metric.value);\n const interaction =\n entry.interactionId !== undefined ? interactionIdToRouteNameMapping[entry.interactionId] : undefined;\n if (interaction === undefined) {\n return;\n }\n const { routeName, parentContext, activeTransaction, user, replayId } = interaction;\n const userDisplay = user !== undefined ? user.email || user.id || user.ip_address : undefined;\n // eslint-disable-next-line deprecation/deprecation\n const profileId = activeTransaction !== undefined ? activeTransaction.getProfileId() : undefined;\n const span = new Span({\n startTimestamp: startTime,\n endTimestamp: startTime + duration,\n op: `ui.interaction.${interactionType}`,\n name: htmlTreeAsString(entry.target),\n attributes: {\n release: options.release,\n environment: options.environment,\n transaction: routeName,\n ...(userDisplay !== undefined && userDisplay !== '' ? { user: userDisplay } : {}),\n ...(profileId !== undefined ? { profile_id: profileId } : {}),\n ...(replayId !== undefined ? { replay_id: replayId } : {}),\n },\n exclusiveTime: metric.value,\n measurements: {\n inp: { value: metric.value, unit: 'millisecond' },\n },\n });\n\n /** Check to see if the span should be sampled */\n const sampleRate = getSampleRate(parentContext, options, interactionsSampleRate);\n\n if (!sampleRate) {\n return;\n }\n\n if (Math.random() < (sampleRate as number | boolean)) {\n const envelope = span ? createSpanEnvelope([span], client.getDsn()) : undefined;\n const transport = client && client.getTransport();\n if (transport && envelope) {\n transport.send(envelope).then(null, reason => {\n DEBUG_BUILD && logger.error('Error while sending interaction:', reason);\n });\n }\n return;\n }\n });\n}\n\n/** Add performance related spans to a transaction */\nexport function addPerformanceEntries(transaction: Transaction): void {\n const performance = getBrowserPerformanceAPI();\n if (!performance || !WINDOW.performance.getEntries || !browserPerformanceTimeOrigin) {\n // Gatekeeper if performance API not available\n return;\n }\n\n DEBUG_BUILD && logger.log('[Tracing] Adding & adjusting spans using Performance API');\n const timeOrigin = msToSec(browserPerformanceTimeOrigin);\n\n const performanceEntries = performance.getEntries();\n\n const { op, start_timestamp: transactionStartTime } = spanToJSON(transaction);\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n performanceEntries.slice(_performanceCursor).forEach((entry: Record<string, any>) => {\n const startTime = msToSec(entry.startTime);\n const duration = msToSec(entry.duration);\n\n // eslint-disable-next-line deprecation/deprecation\n if (transaction.op === 'navigation' && transactionStartTime && timeOrigin + startTime < transactionStartTime) {\n return;\n }\n\n switch (entry.entryType) {\n case 'navigation': {\n _addNavigationSpans(transaction, entry, timeOrigin);\n break;\n }\n case 'mark':\n case 'paint':\n case 'measure': {\n _addMeasureSpans(transaction, entry, startTime, duration, timeOrigin);\n\n // capture web vitals\n const firstHidden = getVisibilityWatcher();\n // Only report if the page wasn't hidden prior to the web vital.\n const shouldRecord = entry.startTime < firstHidden.firstHiddenTime;\n\n if (entry.name === 'first-paint' && shouldRecord) {\n DEBUG_BUILD && logger.log('[Measurements] Adding FP');\n _measurements['fp'] = { value: entry.startTime, unit: 'millisecond' };\n }\n if (entry.name === 'first-contentful-paint' && shouldRecord) {\n DEBUG_BUILD && logger.log('[Measurements] Adding FCP');\n _measurements['fcp'] = { value: entry.startTime, unit: 'millisecond' };\n }\n break;\n }\n case 'resource': {\n _addResourceSpans(transaction, entry, entry.name as string, startTime, duration, timeOrigin);\n break;\n }\n default:\n // Ignore other entry types.\n }\n });\n\n _performanceCursor = Math.max(performanceEntries.length - 1, 0);\n\n _trackNavigator(transaction);\n\n // Measurements are only available for pageload transactions\n if (op === 'pageload') {\n _addTtfbRequestTimeToMeasurements(_measurements);\n\n ['fcp', 'fp', 'lcp'].forEach(name => {\n if (!_measurements[name] || !transactionStartTime || timeOrigin >= transactionStartTime) {\n return;\n }\n // The web vitals, fcp, fp, lcp, and ttfb, all measure relative to timeOrigin.\n // Unfortunately, timeOrigin is not captured within the transaction span data, so these web vitals will need\n // to be adjusted to be relative to transaction.startTimestamp.\n const oldValue = _measurements[name].value;\n const measurementTimestamp = timeOrigin + msToSec(oldValue);\n\n // normalizedValue should be in milliseconds\n const normalizedValue = Math.abs((measurementTimestamp - transactionStartTime) * 1000);\n const delta = normalizedValue - oldValue;\n\n DEBUG_BUILD && logger.log(`[Measurements] Normalized ${name} from ${oldValue} to ${normalizedValue} (${delta})`);\n _measurements[name].value = normalizedValue;\n });\n\n const fidMark = _measurements['mark.fid'];\n if (fidMark && _measurements['fid']) {\n // create span for FID\n _startChild(transaction, {\n description: 'first input delay',\n endTimestamp: fidMark.value + msToSec(_measurements['fid'].value),\n op: 'ui.action',\n origin: 'auto.ui.browser.metrics',\n startTimestamp: fidMark.value,\n });\n\n // Delete mark.fid as we don't want it to be part of final payload\n delete _measurements['mark.fid'];\n }\n\n // If FCP is not recorded we should not record the cls value\n // according to the new definition of CLS.\n if (!('fcp' in _measurements)) {\n delete _measurements.cls;\n }\n\n Object.keys(_measurements).forEach(measurementName => {\n setMeasurement(measurementName, _measurements[measurementName].value, _measurements[measurementName].unit);\n });\n\n _tagMetricInfo(transaction);\n }\n\n _lcpEntry = undefined;\n _clsEntry = undefined;\n _measurements = {};\n}\n\n/** Create measure related spans */\nexport function _addMeasureSpans(\n transaction: Transaction,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n entry: Record<string, any>,\n startTime: number,\n duration: number,\n timeOrigin: number,\n): number {\n const measureStartTimestamp = timeOrigin + startTime;\n const measureEndTimestamp = measureStartTimestamp + duration;\n\n _startChild(transaction, {\n description: entry.name as string,\n endTimestamp: measureEndTimestamp,\n op: entry.entryType as string,\n origin: 'auto.resource.browser.metrics',\n startTimestamp: measureStartTimestamp,\n });\n\n return measureStartTimestamp;\n}\n\n/** Instrument navigation entries */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _addNavigationSpans(transaction: Transaction, entry: Record<string, any>, timeOrigin: number): void {\n ['unloadEvent', 'redirect', 'domContentLoadedEvent', 'loadEvent', 'connect'].forEach(event => {\n _addPerformanceNavigationTiming(transaction, entry, event, timeOrigin);\n });\n _addPerformanceNavigationTiming(transaction, entry, 'secureConnection', timeOrigin, 'TLS/SSL', 'connectEnd');\n _addPerformanceNavigationTiming(transaction, entry, 'fetch', timeOrigin, 'cache', 'domainLookupStart');\n _addPerformanceNavigationTiming(transaction, entry, 'domainLookup', timeOrigin, 'DNS');\n _addRequest(transaction, entry, timeOrigin);\n}\n\n/** Create performance navigation related spans */\nfunction _addPerformanceNavigationTiming(\n transaction: Transaction,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n entry: Record<string, any>,\n event: string,\n timeOrigin: number,\n description?: string,\n eventEnd?: string,\n): void {\n const end = eventEnd ? (entry[eventEnd] as number | undefined) : (entry[`${event}End`] as number | undefined);\n const start = entry[`${event}Start`] as number | undefined;\n if (!start || !end) {\n return;\n }\n _startChild(transaction, {\n op: 'browser',\n origin: 'auto.browser.browser.metrics',\n description: description || event,\n startTimestamp: timeOrigin + msToSec(start),\n endTimestamp: timeOrigin + msToSec(end),\n });\n}\n\n/** Create request and response related spans */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _addRequest(transaction: Transaction, entry: Record<string, any>, timeOrigin: number): void {\n if (entry.responseEnd) {\n // It is possible that we are collecting these metrics when the page hasn't finished loading yet, for example when the HTML slowly streams in.\n // In this case, ie. when the document request hasn't finished yet, `entry.responseEnd` will be 0.\n // In order not to produce faulty spans, where the end timestamp is before the start timestamp, we will only collect\n // these spans when the responseEnd value is available. The backend (Relay) would drop the entire transaction if it contained faulty spans.\n _startChild(transaction, {\n op: 'browser',\n origin: 'auto.browser.browser.metrics',\n description: 'request',\n startTimestamp: timeOrigin + msToSec(entry.requestStart as number),\n endTimestamp: timeOrigin + msToSec(entry.responseEnd as number),\n });\n\n _startChild(transaction, {\n op: 'browser',\n origin: 'auto.browser.browser.metrics',\n description: 'response',\n startTimestamp: timeOrigin + msToSec(entry.responseStart as number),\n endTimestamp: timeOrigin + msToSec(entry.responseEnd as number),\n });\n }\n}\n\nexport interface ResourceEntry extends Record<string, unknown> {\n initiatorType?: string;\n transferSize?: number;\n encodedBodySize?: number;\n decodedBodySize?: number;\n renderBlockingStatus?: string;\n}\n\n/** Create resource-related spans */\nexport function _addResourceSpans(\n transaction: Transaction,\n entry: ResourceEntry,\n resourceUrl: string,\n startTime: number,\n duration: number,\n timeOrigin: number,\n): void {\n // we already instrument based on fetch and xhr, so we don't need to\n // duplicate spans here.\n if (entry.initiatorType === 'xmlhttprequest' || entry.initiatorType === 'fetch') {\n return;\n }\n\n const parsedUrl = parseUrl(resourceUrl);\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const data: Record<string, any> = {};\n setResourceEntrySizeData(data, entry, 'transferSize', 'http.response_transfer_size');\n setResourceEntrySizeData(data, entry, 'encodedBodySize', 'http.response_content_length');\n setResourceEntrySizeData(data, entry, 'decodedBodySize', 'http.decoded_response_content_length');\n\n if ('renderBlockingStatus' in entry) {\n data['resource.render_blocking_status'] = entry.renderBlockingStatus;\n }\n if (parsedUrl.protocol) {\n data['url.scheme'] = parsedUrl.protocol.split(':').pop(); // the protocol returned by parseUrl includes a :, but OTEL spec does not, so we remove it.\n }\n\n if (parsedUrl.host) {\n data['server.address'] = parsedUrl.host;\n }\n\n data['url.same_origin'] = resourceUrl.includes(WINDOW.location.origin);\n\n const startTimestamp = timeOrigin + startTime;\n const endTimestamp = startTimestamp + duration;\n\n _startChild(transaction, {\n description: resourceUrl.replace(WINDOW.location.origin, ''),\n endTimestamp,\n op: entry.initiatorType ? `resource.${entry.initiatorType}` : 'resource.other',\n origin: 'auto.resource.browser.metrics',\n startTimestamp,\n data,\n });\n}\n\n/**\n * Capture the information of the user agent.\n */\nfunction _trackNavigator(transaction: Transaction): void {\n const navigator = WINDOW.navigator as null | (Navigator & NavigatorNetworkInformation & NavigatorDeviceMemory);\n if (!navigator) {\n return;\n }\n\n // track network connectivity\n const connection = navigator.connection;\n if (connection) {\n if (connection.effectiveType) {\n // TODO: Can we rewrite this to an attribute?\n // eslint-disable-next-line deprecation/deprecation\n transaction.setTag('effectiveConnectionType', connection.effectiveType);\n }\n\n if (connection.type) {\n // TODO: Can we rewrite this to an attribute?\n // eslint-disable-next-line deprecation/deprecation\n transaction.setTag('connectionType', connection.type);\n }\n\n if (isMeasurementValue(connection.rtt)) {\n _measurements['connection.rtt'] = { value: connection.rtt, unit: 'millisecond' };\n }\n }\n\n if (isMeasurementValue(navigator.deviceMemory)) {\n // TODO: Can we rewrite this to an attribute?\n // eslint-disable-next-line deprecation/deprecation\n transaction.setTag('deviceMemory', `${navigator.deviceMemory} GB`);\n }\n\n if (isMeasurementValue(navigator.hardwareConcurrency)) {\n // TODO: Can we rewrite this to an attribute?\n // eslint-disable-next-line deprecation/deprecation\n transaction.setTag('hardwareConcurrency', String(navigator.hardwareConcurrency));\n }\n}\n\n/** Add LCP / CLS data to transaction to allow debugging */\nfunction _tagMetricInfo(transaction: Transaction): void {\n if (_lcpEntry) {\n DEBUG_BUILD && logger.log('[Measurements] Adding LCP Data');\n\n // Capture Properties of the LCP element that contributes to the LCP.\n\n if (_lcpEntry.element) {\n // TODO: Can we rewrite this to an attribute?\n // eslint-disable-next-line deprecation/deprecation\n transaction.setTag('lcp.element', htmlTreeAsString(_lcpEntry.element));\n }\n\n if (_lcpEntry.id) {\n // TODO: Can we rewrite this to an attribute?\n // eslint-disable-next-line deprecation/deprecation\n transaction.setTag('lcp.id', _lcpEntry.id);\n }\n\n if (_lcpEntry.url) {\n // Trim URL to the first 200 characters.\n // TODO: Can we rewrite this to an attribute?\n // eslint-disable-next-line deprecation/deprecation\n transaction.setTag('lcp.url', _lcpEntry.url.trim().slice(0, 200));\n }\n\n // TODO: Can we rewrite this to an attribute?\n // eslint-disable-next-line deprecation/deprecation\n transaction.setTag('lcp.size', _lcpEntry.size);\n }\n\n // See: https://developer.mozilla.org/en-US/docs/Web/API/LayoutShift\n if (_clsEntry && _clsEntry.sources) {\n DEBUG_BUILD && logger.log('[Measurements] Adding CLS Data');\n _clsEntry.sources.forEach((source, index) =>\n // TODO: Can we rewrite this to an attribute?\n // eslint-disable-next-line deprecation/deprecation\n transaction.setTag(`cls.source.${index + 1}`, htmlTreeAsString(source.node)),\n );\n }\n}\n\nfunction setResourceEntrySizeData(\n data: Record<string, unknown>,\n entry: ResourceEntry,\n key: keyof Pick<ResourceEntry, 'transferSize' | 'encodedBodySize' | 'decodedBodySize'>,\n dataKey: 'http.response_transfer_size' | 'http.response_content_length' | 'http.decoded_response_content_length',\n): void {\n const entryVal = entry[key];\n if (entryVal != null && entryVal < MAX_INT_AS_BYTES) {\n data[dataKey] = entryVal;\n }\n}\n\n/**\n * Add ttfb request time information to measurements.\n *\n * ttfb information is added via vendored web vitals library.\n */\nfunction _addTtfbRequestTimeToMeasurements(_measurements: Measurements): void {\n const navEntry = getNavigationEntry();\n if (!navEntry) {\n return;\n }\n\n const { responseStart, requestStart } = navEntry;\n\n if (requestStart <= responseStart) {\n DEBUG_BUILD && logger.log('[Measurements] Adding TTFB Request Time');\n _measurements['ttfb.requestTime'] = {\n value: responseStart - requestStart,\n unit: 'millisecond',\n };\n }\n}\n\n/** Taken from @sentry/core sampling.ts */\nfunction getSampleRate(\n transactionContext: TransactionContext | undefined,\n options: ClientOptions,\n interactionsSampleRate: number,\n): number | boolean {\n if (!hasTracingEnabled(options)) {\n return false;\n }\n let sampleRate;\n if (transactionContext !== undefined && typeof options.tracesSampler === 'function') {\n sampleRate = options.tracesSampler({\n transactionContext,\n name: transactionContext.name,\n parentSampled: transactionContext.parentSampled,\n attributes: {\n // eslint-disable-next-line deprecation/deprecation\n ...transactionContext.data,\n ...transactionContext.attributes,\n },\n location: WINDOW.location,\n });\n } else if (transactionContext !== undefined && transactionContext.sampled !== undefined) {\n sampleRate = transactionContext.sampled;\n } else if (typeof options.tracesSampleRate !== 'undefined') {\n sampleRate = options.tracesSampleRate;\n } else {\n sampleRate = 1;\n }\n if (!isValidSampleRate(sampleRate)) {\n DEBUG_BUILD && logger.warn('[Tracing] Discarding interaction span because of invalid sample rate.');\n return false;\n }\n if (sampleRate === true) {\n return interactionsSampleRate;\n } else if (sampleRate === false) {\n return 0;\n }\n return sampleRate * interactionsSampleRate;\n}\n","import type { Transaction, TransactionContext } from '@sentry/types';\nimport { addHistoryInstrumentationHandler, browserPerformanceTimeOrigin, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../common/debug-build';\nimport { WINDOW } from './types';\n\n/**\n * Default function implementing pageload and navigation transactions\n */\nexport function instrumentRoutingWithDefaults<T extends Transaction>(\n customStartTransaction: (context: TransactionContext) => T | undefined,\n startTransactionOnPageLoad: boolean = true,\n startTransactionOnLocationChange: boolean = true,\n): void {\n if (!WINDOW || !WINDOW.location) {\n DEBUG_BUILD && logger.warn('Could not initialize routing instrumentation due to invalid location');\n return;\n }\n\n let startingUrl: string | undefined = WINDOW.location.href;\n\n let activeTransaction: T | undefined;\n if (startTransactionOnPageLoad) {\n activeTransaction = customStartTransaction({\n name: WINDOW.location.pathname,\n // pageload should always start at timeOrigin (and needs to be in s, not ms)\n startTimestamp: browserPerformanceTimeOrigin ? browserPerformanceTimeOrigin / 1000 : undefined,\n op: 'pageload',\n origin: 'auto.pageload.browser',\n metadata: { source: 'url' },\n });\n }\n\n if (startTransactionOnLocationChange) {\n addHistoryInstrumentationHandler(({ to, from }) => {\n /**\n * This early return is there to account for some cases where a navigation transaction starts right after\n * long-running pageload. We make sure that if `from` is undefined and a valid `startingURL` exists, we don't\n * create an uneccessary navigation transaction.\n *\n * This was hard to duplicate, but this behavior stopped as soon as this fix was applied. This issue might also\n * only be caused in certain development environments where the usage of a hot module reloader is causing\n * errors.\n */\n if (from === undefined && startingUrl && startingUrl.indexOf(to) !== -1) {\n startingUrl = undefined;\n return;\n }\n\n if (from !== to) {\n startingUrl = undefined;\n if (activeTransaction) {\n DEBUG_BUILD && logger.log(`[Tracing] Finishing current transaction with op: ${activeTransaction.op}`);\n // If there's an open transaction on the scope, we need to finish it before creating an new one.\n activeTransaction.end();\n }\n activeTransaction = customStartTransaction({\n name: WINDOW.location.pathname,\n op: 'navigation',\n origin: 'auto.navigation.browser',\n metadata: { source: 'url' },\n });\n }\n });\n }\n}\n","/* eslint-disable max-lines */\nimport type { Hub, IdleTransaction } from '@sentry/core';\nimport { getClient, getCurrentScope } from '@sentry/core';\nimport {\n SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,\n TRACING_DEFAULTS,\n addTracingExtensions,\n getActiveTransaction,\n startIdleTransaction,\n} from '@sentry/core';\nimport type { EventProcessor, Integration, Transaction, TransactionContext, TransactionSource } from '@sentry/types';\nimport { getDomElement, logger, propagationContextFromHeaders } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../common/debug-build';\nimport { registerBackgroundTabDetection } from './backgroundtab';\nimport { addPerformanceInstrumentationHandler } from './instrument';\nimport {\n addPerformanceEntries,\n startTrackingINP,\n startTrackingInteractions,\n startTrackingLongTasks,\n startTrackingWebVitals,\n} from './metrics';\nimport type { RequestInstrumentationOptions } from './request';\nimport { defaultRequestInstrumentationOptions, instrumentOutgoingRequests } from './request';\nimport { instrumentRoutingWithDefaults } from './router';\nimport { WINDOW } from './types';\nimport type { InteractionRouteNameMapping } from './web-vitals/types';\n\nexport const BROWSER_TRACING_INTEGRATION_ID = 'BrowserTracing';\n\n/** Options for Browser Tracing integration */\nexport interface BrowserTracingOptions extends RequestInstrumentationOptions {\n /**\n * The time to wait in ms until the transaction will be finished during an idle state. An idle state is defined\n * by a moment where there are no in-progress spans.\n *\n * The transaction will use the end timestamp of the last finished span as the endtime for the transaction.\n * If there are still active spans when this the `idleTimeout` is set, the `idleTimeout` will get reset.\n * Time is in ms.\n *\n * Default: 1000\n */\n idleTimeout: number;\n\n /**\n * The max duration for a transaction. If a transaction duration hits the `finalTimeout` value, it\n * will be finished.\n * Time is in ms.\n *\n * Default: 30000\n */\n finalTimeout: number;\n\n /**\n * The heartbeat interval. If no new spans are started or open spans are finished within 3 heartbeats,\n * the transaction will be finished.\n * Time is in ms.\n *\n * Default: 5000\n */\n heartbeatInterval: number;\n\n /**\n * Flag to enable/disable creation of `navigation` transaction on history changes.\n *\n * Default: true\n */\n startTransactionOnLocationChange: boolean;\n\n /**\n * Flag to enable/disable creation of `pageload` transaction on first pageload.\n *\n * Default: true\n */\n startTransactionOnPageLoad: boolean;\n\n /**\n * Flag Transactions where tabs moved to background with \"cancelled\". Browser background tab timing is\n * not suited towards doing precise measurements of operations. By default, we recommend that this option\n * be enabled as background transactions can mess up your statistics in nondeterministic ways.\n *\n * Default: true\n */\n markBackgroundTransactions: boolean;\n\n /**\n * If true, Sentry will capture long tasks and add them to the corresponding transaction.\n *\n * Default: true\n */\n enableLongTask: boolean;\n\n /**\n * If true, Sentry will capture INP web vitals as standalone spans .\n *\n * Default: false\n */\n enableInp: boolean;\n\n /**\n * Sample rate to determine interaction span sampling.\n * interactionsSampleRate is applied on top of the global tracesSampleRate.\n * ie a tracesSampleRate of 0.1 and interactionsSampleRate of 0.5 will result in a 0.05 sample rate for interactions.\n *\n * Default: 1\n */\n interactionsSampleRate: number;\n\n /**\n * _metricOptions allows the user to send options to change how metrics are collected.\n *\n * _metricOptions is currently experimental.\n *\n * Default: undefined\n */\n _metricOptions?: Partial<{\n /**\n * @deprecated This property no longer has any effect and will be removed in v8.\n */\n _reportAllChanges: boolean;\n }>;\n\n /**\n * _experiments allows the user to send options to define how this integration works.\n * Note that the `enableLongTask` options is deprecated in favor of the option at the top level, and will be removed in v8.\n *\n * TODO (v8): Remove enableLongTask\n *\n * Default: undefined\n */\n _experiments: Partial<{\n enableLongTask: boolean;\n enableInteractions: boolean;\n // eslint-disable-next-line deprecation/deprecation\n onStartRouteTransaction: (t: Transaction | undefined, ctx: TransactionContext, getCurrentHub: () => Hub) => void;\n }>;\n\n /**\n * beforeNavigate is called before a pageload/navigation transaction is created and allows users to modify transaction\n * context data, or drop the transaction entirely (by setting `sampled = false` in the context).\n *\n * Note: For legacy reasons, transactions can also be dropped by returning `undefined`.\n *\n * @param context: The context data which will be passed to `startTransaction` by default\n *\n * @returns A (potentially) modified context object, with `sampled = false` if the transaction should be dropped.\n */\n beforeNavigate?(this: void, context: TransactionContext): TransactionContext | undefined;\n\n /**\n * Instrumentation that creates routing change transactions. By default creates\n * pageload and navigation transactions.\n */\n routingInstrumentation<T extends Transaction>(\n this: void,\n customStartTransaction: (context: TransactionContext) => T | undefined,\n startTransactionOnPageLoad?: boolean,\n startTransactionOnLocationChange?: boolean,\n ): void;\n}\n\nconst DEFAULT_BROWSER_TRACING_OPTIONS: BrowserTracingOptions = {\n ...TRACING_DEFAULTS,\n markBackgroundTransactions: true,\n routingInstrumentation: instrumentRoutingWithDefaults,\n startTransactionOnLocationChange: true,\n startTransactionOnPageLoad: true,\n enableLongTask: true,\n enableInp: false,\n interactionsSampleRate: 1,\n _experiments: {},\n ...defaultRequestInstrumentationOptions,\n};\n\n/** We store up to 10 interaction candidates max to cap memory usage. This is the same cap as getINP from web-vitals */\nconst MAX_INTERACTIONS = 10;\n\n/**\n * The Browser Tracing integration automatically instruments browser pageload/navigation\n * actions as transactions, and captures requests, metrics and errors as spans.\n *\n * The integration can be configured with a variety of options, and can be extended to use\n * any routing library. This integration uses {@see IdleTransaction} to create transactions.\n *\n * @deprecated Use `browserTracingIntegration()` instead.\n */\nexport class BrowserTracing implements Integration {\n // This class currently doesn't have a static `id` field like the other integration classes, because it prevented\n // @sentry/tracing from being treeshaken. Tree shakers do not like static fields, because they behave like side effects.\n // TODO: Come up with a better plan, than using static fields on integration classes, and use that plan on all\n // integrations.\n\n /** Browser Tracing integration options */\n public options: BrowserTracingOptions;\n\n /**\n * @inheritDoc\n */\n public name: string;\n\n // eslint-disable-next-line deprecation/deprecation\n private _getCurrentHub?: () => Hub;\n\n private _collectWebVitals: () => void;\n\n private _hasSetTracePropagationTargets: boolean;\n private _interactionIdToRouteNameMapping: InteractionRouteNameMapping;\n private _latestRoute: {\n name: string | undefined;\n context: TransactionContext | undefined;\n };\n\n public constructor(_options?: Partial<BrowserTracingOptions>) {\n this.name = BROWSER_TRACING_INTEGRATION_ID;\n this._hasSetTracePropagationTargets = false;\n\n addTracingExtensions();\n\n if (DEBUG_BUILD) {\n this._hasSetTracePropagationTargets = !!(\n _options &&\n // eslint-disable-next-line deprecation/deprecation\n (_options.tracePropagationTargets || _options.tracingOrigins)\n );\n }\n\n this.options = {\n ...DEFAULT_BROWSER_TRACING_OPTIONS,\n ..._options,\n };\n\n // Special case: enableLongTask can be set in _experiments\n // TODO (v8): Remove this in v8\n if (this.options._experiments.enableLongTask !== undefined) {\n this.options.enableLongTask = this.options._experiments.enableLongTask;\n }\n\n // TODO (v8): remove this block after tracingOrigins is removed\n // Set tracePropagationTargets to tracingOrigins if specified by the user\n // In case both are specified, tracePropagationTargets takes precedence\n // eslint-disable-next-line deprecation/deprecation\n if (_options && !_options.tracePropagationTargets && _options.tracingOrigins) {\n // eslint-disable-next-line deprecation/deprecation\n this.options.tracePropagationTargets = _options.tracingOrigins;\n }\n\n this._collectWebVitals = startTrackingWebVitals();\n /** Stores a mapping of interactionIds from PerformanceEventTimings to the origin interaction path */\n this._interactionIdToRouteNameMapping = {};\n\n if (this.options.enableInp) {\n startTrackingINP(this._interactionIdToRouteNameMapping, this.options.interactionsSampleRate);\n }\n if (this.options.enableLongTask) {\n startTrackingLongTasks();\n }\n if (this.options._experiments.enableInteractions) {\n startTrackingInteractions();\n }\n\n this._latestRoute = {\n name: undefined,\n context: undefined,\n };\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line deprecation/deprecation\n public setupOnce(_: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {\n this._getCurrentHub = getCurrentHub;\n const hub = getCurrentHub();\n // eslint-disable-next-line deprecation/deprecation\n const client = hub.getClient();\n const clientOptions = client && client.getOptions();\n\n const {\n routingInstrumentation: instrumentRouting,\n startTransactionOnLocationChange,\n startTransactionOnPageLoad,\n markBackgroundTransactions,\n traceFetch,\n traceXHR,\n shouldCreateSpanForRequest,\n enableHTTPTimings,\n _experiments,\n } = this.options;\n\n const clientOptionsTracePropagationTargets = clientOptions && clientOptions.tracePropagationTargets;\n // There are three ways to configure tracePropagationTargets:\n // 1. via top level client option `tracePropagationTargets`\n // 2. via BrowserTracing option `tracePropagationTargets`\n // 3. via BrowserTracing option `tracingOrigins` (deprecated)\n //\n // To avoid confusion, favour top level client option `tracePropagationTargets`, and fallback to\n // BrowserTracing option `tracePropagationTargets` and then `tracingOrigins` (deprecated).\n // This is done as it minimizes bundle size (we don't have to have undefined checks).\n //\n // If both 1 and either one of 2 or 3 are set (from above), we log out a warning.\n // eslint-disable-next-line deprecation/deprecation\n const tracePropagationTargets = clientOptionsTracePropagationTargets || this.options.tracePropagationTargets;\n if (DEBUG_BUILD && this._hasSetTracePropagationTargets && clientOptionsTracePropagationTargets) {\n logger.warn(\n '[Tracing] The `tracePropagationTargets` option was set in the BrowserTracing integration and top level `Sentry.init`. The top level `Sentry.init` value is being used.',\n );\n }\n\n instrumentRouting(\n (context: TransactionContext) => {\n const transaction = this._createRouteTransaction(context);\n\n this.options._experiments.onStartRouteTransaction &&\n this.options._experiments.onStartRouteTransaction(transaction, context, getCurrentHub);\n\n return transaction;\n },\n startTransactionOnPageLoad,\n startTransactionOnLocationChange,\n );\n\n if (markBackgroundTransactions) {\n registerBackgroundTabDetection();\n }\n\n if (_experiments.enableInteractions) {\n this._registerInteractionListener();\n }\n\n if (this.options.enableInp) {\n this._registerInpInteractionListener();\n }\n\n instrumentOutgoingRequests({\n traceFetch,\n traceXHR,\n tracePropagationTargets,\n shouldCreateSpanForRequest,\n enableHTTPTimings,\n });\n }\n\n /** Create routing idle transaction. */\n private _createRouteTransaction(context: TransactionContext): Transaction | undefined {\n if (!this._getCurrentHub) {\n DEBUG_BUILD &&\n logger.warn(`[Tracing] Did not create ${context.op} transaction because _getCurrentHub is invalid.`);\n return undefined;\n }\n\n const hub = this._getCurrentHub();\n\n const { beforeNavigate, idleTimeout, finalTimeout, heartbeatInterval } = this.options;\n\n const isPageloadTransaction = context.op === 'pageload';\n\n let expandedContext: TransactionContext;\n if (isPageloadTransaction) {\n const sentryTrace = isPageloadTransaction ? getMetaContent('sentry-trace') : '';\n const baggage = isPageloadTransaction ? getMetaContent('baggage') : undefined;\n const { traceId, dsc, parentSpanId, sampled } = propagationContextFromHeaders(sentryTrace, baggage);\n expandedContext = {\n traceId,\n parentSpanId,\n parentSampled: sampled,\n ...context,\n metadata: {\n // eslint-disable-next-line deprecation/deprecation\n ...context.metadata,\n dynamicSamplingContext: dsc,\n },\n trimEnd: true,\n };\n } else {\n expandedContext = {\n trimEnd: true,\n ...context,\n };\n }\n\n const modifiedContext = typeof beforeNavigate === 'function' ? beforeNavigate(expandedContext) : expandedContext;\n\n // For backwards compatibility reasons, beforeNavigate can return undefined to \"drop\" the transaction (prevent it\n // from being sent to Sentry).\n const finalContext = modifiedContext === undefined ? { ...expandedContext, sampled: false } : modifiedContext;\n\n // If `beforeNavigate` set a custom name, record that fact\n // eslint-disable-next-line deprecation/deprecation\n finalContext.metadata =\n finalContext.name !== expandedContext.name\n ? // eslint-disable-next-line deprecation/deprecation\n { ...finalContext.metadata, source: 'custom' }\n : // eslint-disable-next-line deprecation/deprecation\n finalContext.metadata;\n\n this._latestRoute.name = finalContext.name;\n this._latestRoute.context = finalContext;\n\n // eslint-disable-next-line deprecation/deprecation\n if (finalContext.sampled === false) {\n DEBUG_BUILD && logger.log(`[Tracing] Will not send ${finalContext.op} transaction because of beforeNavigate.`);\n }\n\n DEBUG_BUILD && logger.log(`[Tracing] Starting ${finalContext.op} transaction on scope`);\n\n const { location } = WINDOW;\n\n const idleTransaction = startIdleTransaction(\n hub,\n finalContext,\n idleTimeout,\n finalTimeout,\n true,\n { location }, // for use in the tracesSampler\n heartbeatInterval,\n isPageloadTransaction, // should wait for finish signal if it's a pageload transaction\n );\n\n if (isPageloadTransaction) {\n if (WINDOW.document) {\n WINDOW.document.addEventListener('readystatechange', () => {\n if (['interactive', 'complete'].includes(WINDOW.document!.readyState)) {\n idleTransaction.sendAutoFinishSignal();\n }\n });\n\n if (['interactive', 'complete'].includes(WINDOW.document.readyState)) {\n idleTransaction.sendAutoFinishSignal();\n }\n }\n }\n\n idleTransaction.registerBeforeFinishCallback(transaction => {\n this._collectWebVitals();\n addPerformanceEntries(transaction);\n });\n\n return idleTransaction as Transaction;\n }\n\n /** Start listener for interaction transactions */\n private _registerInteractionListener(): void {\n let inflightInteractionTransaction: IdleTransaction | undefined;\n const registerInteractionTransaction = (): void => {\n const { idleTimeout, finalTimeout, heartbeatInterval } = this.options;\n const op = 'ui.action.click';\n\n // eslint-disable-next-line deprecation/deprecation\n const currentTransaction = getActiveTransaction();\n if (currentTransaction && currentTransaction.op && ['navigation', 'pageload'].includes(currentTransaction.op)) {\n DEBUG_BUILD &&\n logger.warn(\n `[Tracing] Did not create ${op} transaction because a pageload or navigation transaction is in progress.`,\n );\n return undefined;\n }\n\n if (inflightInteractionTransaction) {\n inflightInteractionTransaction.setFinishReason('interactionInterrupted');\n inflightInteractionTransaction.end();\n inflightInteractionTransaction = undefined;\n }\n\n if (!this._getCurrentHub) {\n DEBUG_BUILD && logger.warn(`[Tracing] Did not create ${op} transaction because _getCurrentHub is invalid.`);\n return undefined;\n }\n\n if (!this._latestRoute.name) {\n DEBUG_BUILD && logger.warn(`[Tracing] Did not create ${op} transaction because _latestRouteName is missing.`);\n return undefined;\n }\n\n const hub = this._getCurrentHub();\n const { location } = WINDOW;\n\n const context: TransactionContext = {\n name: this._latestRoute.name,\n op,\n trimEnd: true,\n data: {\n [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: this._latestRoute.context\n ? getSource(this._latestRoute.context)\n : undefined || 'url',\n },\n };\n\n inflightInteractionTransaction = startIdleTransaction(\n hub,\n context,\n idleTimeout,\n finalTimeout,\n true,\n { location }, // for use in the tracesSampler\n heartbeatInterval,\n );\n };\n\n ['click'].forEach(type => {\n if (WINDOW.document) {\n addEventListener(type, registerInteractionTransaction, { once: false, capture: true });\n }\n });\n }\n\n /** Creates a listener on interaction entries, and maps interactionIds to the origin path of the interaction */\n private _registerInpInteractionListener(): void {\n const handleEntries = ({ entries }: { entries: PerformanceEntry[] }): void => {\n const client = getClient();\n // We need to get the replay, user, and activeTransaction from the current scope\n // so that we can associate replay id, profile id, and a user display to the span\n const replay =\n client !== undefined && client.getIntegrationByName !== undefined\n ? (client.getIntegrationByName('Replay') as Integration & { getReplayId: () => string })\n : undefined;\n const replayId = replay !== undefined ? replay.getReplayId() : undefined;\n // eslint-disable-next-line deprecation/deprecation\n const activeTransaction = getActiveTransaction();\n const currentScope = getCurrentScope();\n const user = currentScope !== undefined ? currentScope.getUser() : undefined;\n entries.forEach(entry => {\n if (isPerformanceEventTiming(entry)) {\n const interactionId = entry.interactionId;\n if (interactionId === undefined) {\n return;\n }\n const existingInteraction = this._interactionIdToRouteNameMapping[interactionId];\n const duration = entry.duration;\n const startTime = entry.startTime;\n const keys = Object.keys(this._interactionIdToRouteNameMapping);\n const minInteractionId =\n keys.length > 0\n ? keys.reduce((a, b) => {\n return this._interactionIdToRouteNameMapping[a].duration <\n this._interactionIdToRouteNameMapping[b].duration\n ? a\n : b;\n })\n : undefined;\n // For a first input event to be considered, we must check that an interaction event does not already exist with the same duration and start time.\n // This is also checked in the web-vitals library.\n if (entry.entryType === 'first-input') {\n const matchingEntry = keys\n .map(key => this._interactionIdToRouteNameMapping[key])\n .some(interaction => {\n return interaction.duration === duration && interaction.startTime === startTime;\n });\n if (matchingEntry) {\n return;\n }\n }\n // Interactions with an id of 0 and are not first-input are not valid.\n if (!interactionId) {\n return;\n }\n // If the interaction already exists, we want to use the duration of the longest entry, since that is what the INP metric uses.\n if (existingInteraction) {\n existingInteraction.duration = Math.max(existingInteraction.duration, duration);\n } else if (\n keys.length < MAX_INTERACTIONS ||\n minInteractionId === undefined ||\n duration > this._interactionIdToRouteNameMapping[minInteractionId].duration\n ) {\n // If the interaction does not exist, we want to add it to the mapping if there is space, or if the duration is longer than the shortest entry.\n const routeName = this._latestRoute.name;\n const parentContext = this._latestRoute.context;\n if (routeName && parentContext) {\n if (minInteractionId && Object.keys(this._interactionIdToRouteNameMapping).length >= MAX_INTERACTIONS) {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete this._interactionIdToRouteNameMapping[minInteractionId];\n }\n this._interactionIdToRouteNameMapping[interactionId] = {\n routeName,\n duration,\n parentContext,\n user,\n activeTransaction,\n replayId,\n startTime,\n };\n }\n }\n }\n });\n };\n addPerformanceInstrumentationHandler('event', handleEntries);\n addPerformanceInstrumentationHandler('first-input', handleEntries);\n }\n}\n\n/** Returns the value of a meta tag */\nexport function getMetaContent(metaName: string): string | undefined {\n // Can't specify generic to `getDomElement` because tracing can be used\n // in a variety of environments, have to disable `no-unsafe-member-access`\n // as a result.\n const metaTag = getDomElement(`meta[name=${metaName}]`);\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return metaTag ? metaTag.getAttribute('content') : undefined;\n}\n\nfunction getSource(context: TransactionContext): TransactionSource | undefined {\n const sourceFromAttributes = context.attributes && context.attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];\n // eslint-disable-next-line deprecation/deprecation\n const sourceFromData = context.data && context.data[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];\n // eslint-disable-next-line deprecation/deprecation\n const sourceFromMetadata = context.metadata && context.metadata.source;\n\n return sourceFromAttributes || sourceFromData || sourceFromMetadata;\n}\n\nfunction isPerformanceEventTiming(entry: PerformanceEntry): entry is PerformanceEventTiming {\n return 'duration' in entry;\n}\n","/* eslint-disable max-lines */\nimport type { IdleTransaction } from '@sentry/core';\nimport { getActiveSpan, getClient, getCurrentScope } from '@sentry/core';\nimport { getCurrentHub } from '@sentry/core';\nimport {\n SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,\n TRACING_DEFAULTS,\n addTracingExtensions,\n getActiveTransaction,\n spanToJSON,\n startIdleTransaction,\n} from '@sentry/core';\nimport type {\n Client,\n Integration,\n IntegrationFn,\n StartSpanOptions,\n Transaction,\n TransactionContext,\n TransactionSource,\n} from '@sentry/types';\nimport type { Span } from '@sentry/types';\nimport {\n addHistoryInstrumentationHandler,\n browserPerformanceTimeOrigin,\n getDomElement,\n logger,\n propagationContextFromHeaders,\n} from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../common/debug-build';\nimport { registerBackgroundTabDetection } from './backgroundtab';\nimport { addPerformanceInstrumentationHandler } from './instrument';\nimport {\n addPerformanceEntries,\n startTrackingINP,\n startTrackingInteractions,\n startTrackingLongTasks,\n startTrackingWebVitals,\n} from './metrics';\nimport type { RequestInstrumentationOptions } from './request';\nimport { defaultRequestInstrumentationOptions, instrumentOutgoingRequests } from './request';\nimport { WINDOW } from './types';\nimport type { InteractionRouteNameMapping } from './web-vitals/types';\n\nexport const BROWSER_TRACING_INTEGRATION_ID = 'BrowserTracing';\n\n/** Options for Browser Tracing integration */\nexport interface BrowserTracingOptions extends RequestInstrumentationOptions {\n /**\n * The time to wait in ms until the transaction will be finished during an idle state. An idle state is defined\n * by a moment where there are no in-progress spans.\n *\n * The transaction will use the end timestamp of the last finished span as the endtime for the transaction.\n * If there are still active spans when this the `idleTimeout` is set, the `idleTimeout` will get reset.\n * Time is in ms.\n *\n * Default: 1000\n */\n idleTimeout: number;\n\n /**\n * The max duration for a transaction. If a transaction duration hits the `finalTimeout` value, it\n * will be finished.\n * Time is in ms.\n *\n * Default: 30000\n */\n finalTimeout: number;\n\n /**\n * The heartbeat interval. If no new spans are started or open spans are finished within 3 heartbeats,\n * the transaction will be finished.\n * Time is in ms.\n *\n * Default: 5000\n */\n heartbeatInterval: number;\n\n /**\n * If a span should be created on page load.\n * If this is set to `false`, this integration will not start the default page load span.\n * Default: true\n */\n instrumentPageLoad: boolean;\n\n /**\n * If a span should be created on navigation (history change).\n * If this is set to `false`, this integration will not start the default navigation spans.\n * Default: true\n */\n instrumentNavigation: boolean;\n\n /**\n * Flag spans where tabs moved to background with \"cancelled\". Browser background tab timing is\n * not suited towards doing precise measurements of operations. By default, we recommend that this option\n * be enabled as background transactions can mess up your statistics in nondeterministic ways.\n *\n * Default: true\n */\n markBackgroundSpan: boolean;\n\n /**\n * If true, Sentry will capture long tasks and add them to the corresponding transaction.\n *\n * Default: true\n */\n enableLongTask: boolean;\n\n /**\n * If true, Sentry will capture INP web vitals as standalone spans .\n *\n * Default: false\n */\n enableInp: boolean;\n\n /**\n * Sample rate to determine interaction span sampling.\n * interactionsSampleRate is applied on top of the global tracesSampleRate.\n * ie a tracesSampleRate of 0.1 and interactionsSampleRate of 0.5 will result in a 0.05 sample rate for interactions.\n *\n * Default: 1\n */\n interactionsSampleRate: number;\n\n /**\n * _metricOptions allows the user to send options to change how metrics are collected.\n *\n * _metricOptions is currently experimental.\n *\n * Default: undefined\n */\n _metricOptions?: Partial<{\n /**\n * @deprecated This property no longer has any effect and will be removed in v8.\n */\n _reportAllChanges: boolean;\n }>;\n\n /**\n * _experiments allows the user to send options to define how this integration works.\n * Note that the `enableLongTask` options is deprecated in favor of the option at the top level, and will be removed in v8.\n *\n * TODO (v8): Remove enableLongTask\n *\n * Default: undefined\n */\n _experiments: Partial<{\n enableInteractions: boolean;\n }>;\n\n /**\n * A callback which is called before a span for a pageload or navigation is started.\n * It receives the options passed to `startSpan`, and expects to return an updated options object.\n */\n beforeStartSpan?: (options: StartSpanOptions) => StartSpanOptions;\n}\n\nconst DEFAULT_BROWSER_TRACING_OPTIONS: BrowserTracingOptions = {\n ...TRACING_DEFAULTS,\n instrumentNavigation: true,\n instrumentPageLoad: true,\n markBackgroundSpan: true,\n enableLongTask: true,\n enableInp: false,\n interactionsSampleRate: 1,\n _experiments: {},\n ...defaultRequestInstrumentationOptions,\n};\n\n/**\n * The Browser Tracing integration automatically instruments browser pageload/navigation\n * actions as transactions, and captures requests, metrics and errors as spans.\n *\n * The integration can be configured with a variety of options, and can be extended to use\n * any routing library. This integration uses {@see IdleTransaction} to create transactions.\n *\n * We explicitly export the proper type here, as this has to be extended in some cases.\n */\nexport const browserTracingIntegration = ((_options: Partial<BrowserTracingOptions> = {}) => {\n const _hasSetTracePropagationTargets = DEBUG_BUILD\n ? !!(\n // eslint-disable-next-line deprecation/deprecation\n (_options.tracePropagationTargets || _options.tracingOrigins)\n )\n : false;\n\n addTracingExtensions();\n\n // TODO (v8): remove this block after tracingOrigins is removed\n // Set tracePropagationTargets to tracingOrigins if specified by the user\n // In case both are specified, tracePropagationTargets takes precedence\n // eslint-disable-next-line deprecation/deprecation\n if (!_options.tracePropagationTargets && _options.tracingOrigins) {\n // eslint-disable-next-line deprecation/deprecation\n _options.tracePropagationTargets = _options.tracingOrigins;\n }\n\n const options = {\n ...DEFAULT_BROWSER_TRACING_OPTIONS,\n ..._options,\n };\n\n const _collectWebVitals = startTrackingWebVitals();\n\n /** Stores a mapping of interactionIds from PerformanceEventTimings to the origin interaction path */\n const interactionIdToRouteNameMapping: InteractionRouteNameMapping = {};\n if (options.enableInp) {\n startTrackingINP(interactionIdToRouteNameMapping, options.interactionsSampleRate);\n }\n\n if (options.enableLongTask) {\n startTrackingLongTasks();\n }\n if (options._experiments.enableInteractions) {\n startTrackingInteractions();\n }\n\n const latestRoute: {\n name: string | undefined;\n context: TransactionContext | undefined;\n } = {\n name: undefined,\n context: undefined,\n };\n\n /** Create routing idle transaction. */\n function _createRouteTransaction(context: TransactionContext): Transaction | undefined {\n // eslint-disable-next-line deprecation/deprecation\n const hub = getCurrentHub();\n\n const { beforeStartSpan, idleTimeout, finalTimeout, heartbeatInterval } = options;\n\n const isPageloadTransaction = context.op === 'pageload';\n\n let expandedContext: TransactionContext;\n if (isPageloadTransaction) {\n const sentryTrace = isPageloadTransaction ? getMetaContent('sentry-trace') : '';\n const baggage = isPageloadTransaction ? getMetaContent('baggage') : undefined;\n const { traceId, dsc, parentSpanId, sampled } = propagationContextFromHeaders(sentryTrace, baggage);\n expandedContext = {\n traceId,\n parentSpanId,\n parentSampled: sampled,\n ...context,\n metadata: {\n // eslint-disable-next-line deprecation/deprecation\n ...context.metadata,\n dynamicSamplingContext: dsc,\n },\n trimEnd: true,\n };\n } else {\n expandedContext = {\n trimEnd: true,\n ...context,\n };\n }\n\n const finalContext = beforeStartSpan ? beforeStartSpan(expandedContext) : expandedContext;\n\n // If `beforeStartSpan` set a custom name, record that fact\n // eslint-disable-next-line deprecation/deprecation\n finalContext.metadata =\n finalContext.name !== expandedContext.name\n ? // eslint-disable-next-line deprecation/deprecation\n { ...finalContext.metadata, source: 'custom' }\n : // eslint-disable-next-line deprecation/deprecation\n finalContext.metadata;\n\n latestRoute.name = finalContext.name;\n latestRoute.context = finalContext;\n\n if (finalContext.sampled === false) {\n DEBUG_BUILD && logger.log(`[Tracing] Will not send ${finalContext.op} transaction because of beforeNavigate.`);\n }\n\n DEBUG_BUILD && logger.log(`[Tracing] Starting ${finalContext.op} transaction on scope`);\n\n const { location } = WINDOW;\n\n const idleTransaction = startIdleTransaction(\n hub,\n finalContext,\n idleTimeout,\n finalTimeout,\n true,\n { location }, // for use in the tracesSampler\n heartbeatInterval,\n isPageloadTransaction, // should wait for finish signal if it's a pageload transaction\n );\n\n if (isPageloadTransaction && WINDOW.document) {\n WINDOW.document.addEventListener('readystatechange', () => {\n if (['interactive', 'complete'].includes(WINDOW.document!.readyState)) {\n idleTransaction.sendAutoFinishSignal();\n }\n });\n\n if (['interactive', 'complete'].includes(WINDOW.document.readyState)) {\n idleTransaction.sendAutoFinishSignal();\n }\n }\n\n idleTransaction.registerBeforeFinishCallback(transaction => {\n _collectWebVitals();\n addPerformanceEntries(transaction);\n });\n\n return idleTransaction as Transaction;\n }\n\n return {\n name: BROWSER_TRACING_INTEGRATION_ID,\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n setupOnce: () => {},\n afterAllSetup(client) {\n const clientOptions = client.getOptions();\n\n const { markBackgroundSpan, traceFetch, traceXHR, shouldCreateSpanForRequest, enableHTTPTimings, _experiments } =\n options;\n\n const clientOptionsTracePropagationTargets = clientOptions && clientOptions.tracePropagationTargets;\n // There are three ways to configure tracePropagationTargets:\n // 1. via top level client option `tracePropagationTargets`\n // 2. via BrowserTracing option `tracePropagationTargets`\n // 3. via BrowserTracing option `tracingOrigins` (deprecated)\n //\n // To avoid confusion, favour top level client option `tracePropagationTargets`, and fallback to\n // BrowserTracing option `tracePropagationTargets` and then `tracingOrigins` (deprecated).\n // This is done as it minimizes bundle size (we don't have to have undefined checks).\n //\n // If both 1 and either one of 2 or 3 are set (from above), we log out a warning.\n // eslint-disable-next-line deprecation/deprecation\n const tracePropagationTargets = clientOptionsTracePropagationTargets || options.tracePropagationTargets;\n if (DEBUG_BUILD && _hasSetTracePropagationTargets && clientOptionsTracePropagationTargets) {\n logger.warn(\n '[Tracing] The `tracePropagationTargets` option was set in the BrowserTracing integration and top level `Sentry.init`. The top level `Sentry.init` value is being used.',\n );\n }\n\n let activeSpan: Span | undefined;\n let startingUrl: string | undefined = WINDOW.location && WINDOW.location.href;\n\n if (client.on) {\n client.on('startNavigationSpan', (context: StartSpanOptions) => {\n if (activeSpan) {\n DEBUG_BUILD && logger.log(`[Tracing] Finishing current transaction with op: ${spanToJSON(activeSpan).op}`);\n // If there's an open transaction on the scope, we need to finish it before creating an new one.\n activeSpan.end();\n }\n activeSpan = _createRouteTransaction({\n op: 'navigation',\n ...context,\n });\n });\n\n client.on('startPageLoadSpan', (context: StartSpanOptions) => {\n if (activeSpan) {\n DEBUG_BUILD && logger.log(`[Tracing] Finishing current transaction with op: ${spanToJSON(activeSpan).op}`);\n // If there's an open transaction on the scope, we need to finish it before creating an new one.\n activeSpan.end();\n }\n activeSpan = _createRouteTransaction({\n op: 'pageload',\n ...context,\n });\n });\n }\n\n if (options.instrumentPageLoad && client.emit && WINDOW.location) {\n const context: StartSpanOptions = {\n name: WINDOW.location.pathname,\n // pageload should always start at timeOrigin (and needs to be in s, not ms)\n startTimestamp: browserPerformanceTimeOrigin ? browserPerformanceTimeOrigin / 1000 : undefined,\n origin: 'auto.pageload.browser',\n attributes: {\n [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'url',\n },\n };\n startBrowserTracingPageLoadSpan(client, context);\n }\n\n if (options.instrumentNavigation && client.emit && WINDOW.location) {\n addHistoryInstrumentationHandler(({ to, from }) => {\n /**\n * This early return is there to account for some cases where a navigation transaction starts right after\n * long-running pageload. We make sure that if `from` is undefined and a valid `startingURL` exists, we don't\n * create an uneccessary navigation transaction.\n *\n * This was hard to duplicate, but this behavior stopped as soon as this fix was applied. This issue might also\n * only be caused in certain development environments where the usage of a hot module reloader is causing\n * errors.\n */\n if (from === undefined && startingUrl && startingUrl.indexOf(to) !== -1) {\n startingUrl = undefined;\n return;\n }\n\n if (from !== to) {\n startingUrl = undefined;\n const context: StartSpanOptions = {\n name: WINDOW.location.pathname,\n origin: 'auto.navigation.browser',\n attributes: {\n [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'url',\n },\n };\n\n startBrowserTracingNavigationSpan(client, context);\n }\n });\n }\n\n if (markBackgroundSpan) {\n registerBackgroundTabDetection();\n }\n\n if (_experiments.enableInteractions) {\n registerInteractionListener(options, latestRoute);\n }\n\n if (options.enableInp) {\n registerInpInteractionListener(interactionIdToRouteNameMapping, latestRoute);\n }\n\n instrumentOutgoingRequests({\n traceFetch,\n traceXHR,\n tracePropagationTargets,\n shouldCreateSpanForRequest,\n enableHTTPTimings,\n });\n },\n // TODO v8: Remove this again\n // This is private API that we use to fix converted BrowserTracing integrations in Next.js & SvelteKit\n options,\n };\n}) satisfies IntegrationFn;\n\n/**\n * Manually start a page load span.\n * This will only do something if the BrowserTracing integration has been setup.\n */\nexport function startBrowserTracingPageLoadSpan(client: Client, spanOptions: StartSpanOptions): Span | undefined {\n if (!client.emit) {\n return;\n }\n\n client.emit('startPageLoadSpan', spanOptions);\n\n const span = getActiveSpan();\n const op = span && spanToJSON(span).op;\n return op === 'pageload' ? span : undefined;\n}\n\n/**\n * Manually start a navigation span.\n * This will only do something if the BrowserTracing integration has been setup.\n */\nexport function startBrowserTracingNavigationSpan(client: Client, spanOptions: StartSpanOptions): Span | undefined {\n if (!client.emit) {\n return;\n }\n\n client.emit('startNavigationSpan', spanOptions);\n\n const span = getActiveSpan();\n const op = span && spanToJSON(span).op;\n return op === 'navigation' ? span : undefined;\n}\n\n/** Returns the value of a meta tag */\nexport function getMetaContent(metaName: string): string | undefined {\n // Can't specify generic to `getDomElement` because tracing can be used\n // in a variety of environments, have to disable `no-unsafe-member-access`\n // as a result.\n const metaTag = getDomElement(`meta[name=${metaName}]`);\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return metaTag ? metaTag.getAttribute('content') : undefined;\n}\n\n/** Start listener for interaction transactions */\nfunction registerInteractionListener(\n options: BrowserTracingOptions,\n latestRoute: {\n name: string | undefined;\n context: TransactionContext | undefined;\n },\n): void {\n let inflightInteractionTransaction: IdleTransaction | undefined;\n const registerInteractionTransaction = (): void => {\n const { idleTimeout, finalTimeout, heartbeatInterval } = options;\n const op = 'ui.action.click';\n\n // eslint-disable-next-line deprecation/deprecation\n const currentTransaction = getActiveTransaction();\n if (currentTransaction && currentTransaction.op && ['navigation', 'pageload'].includes(currentTransaction.op)) {\n DEBUG_BUILD &&\n logger.warn(\n `[Tracing] Did not create ${op} transaction because a pageload or navigation transaction is in progress.`,\n );\n return undefined;\n }\n\n if (inflightInteractionTransaction) {\n inflightInteractionTransaction.setFinishReason('interactionInterrupted');\n inflightInteractionTransaction.end();\n inflightInteractionTransaction = undefined;\n }\n\n if (!latestRoute.name) {\n DEBUG_BUILD && logger.warn(`[Tracing] Did not create ${op} transaction because _latestRouteName is missing.`);\n return undefined;\n }\n\n const { location } = WINDOW;\n\n const context: TransactionContext = {\n name: latestRoute.name,\n op,\n trimEnd: true,\n data: {\n [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: latestRoute.context ? getSource(latestRoute.context) : undefined || 'url',\n },\n };\n\n inflightInteractionTransaction = startIdleTransaction(\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub(),\n context,\n idleTimeout,\n finalTimeout,\n true,\n { location }, // for use in the tracesSampler\n heartbeatInterval,\n );\n };\n\n ['click'].forEach(type => {\n if (WINDOW.document) {\n addEventListener(type, registerInteractionTransaction, { once: false, capture: true });\n }\n });\n}\n\nfunction isPerformanceEventTiming(entry: PerformanceEntry): entry is PerformanceEventTiming {\n return 'duration' in entry;\n}\n\n/** We store up to 10 interaction candidates max to cap memory usage. This is the same cap as getINP from web-vitals */\nconst MAX_INTERACTIONS = 10;\n\n/** Creates a listener on interaction entries, and maps interactionIds to the origin path of the interaction */\nfunction registerInpInteractionListener(\n interactionIdToRouteNameMapping: InteractionRouteNameMapping,\n latestRoute: {\n name: string | undefined;\n context: TransactionContext | undefined;\n },\n): void {\n const handleEntries = ({ entries }: { entries: PerformanceEntry[] }): void => {\n const client = getClient();\n // We need to get the replay, user, and activeTransaction from the current scope\n // so that we can associate replay id, profile id, and a user display to the span\n const replay =\n client !== undefined && client.getIntegrationByName !== undefined\n ? (client.getIntegrationByName('Replay') as Integration & { getReplayId: () => string })\n : undefined;\n const replayId = replay !== undefined ? replay.getReplayId() : undefined;\n // eslint-disable-next-line deprecation/deprecation\n const activeTransaction = getActiveTransaction();\n const currentScope = getCurrentScope();\n const user = currentScope !== undefined ? currentScope.getUser() : undefined;\n entries.forEach(entry => {\n if (isPerformanceEventTiming(entry)) {\n const interactionId = entry.interactionId;\n if (interactionId === undefined) {\n return;\n }\n const existingInteraction = interactionIdToRouteNameMapping[interactionId];\n const duration = entry.duration;\n const startTime = entry.startTime;\n const keys = Object.keys(interactionIdToRouteNameMapping);\n const minInteractionId =\n keys.length > 0\n ? keys.reduce((a, b) => {\n return interactionIdToRouteNameMapping[a].duration < interactionIdToRouteNameMapping[b].duration\n ? a\n : b;\n })\n : undefined;\n // For a first input event to be considered, we must check that an interaction event does not already exist with the same duration and start time.\n // This is also checked in the web-vitals library.\n if (entry.entryType === 'first-input') {\n const matchingEntry = keys\n .map(key => interactionIdToRouteNameMapping[key])\n .some(interaction => {\n return interaction.duration === duration && interaction.startTime === startTime;\n });\n if (matchingEntry) {\n return;\n }\n }\n // Interactions with an id of 0 and are not first-input are not valid.\n if (!interactionId) {\n return;\n }\n // If the interaction already exists, we want to use the duration of the longest entry, since that is what the INP metric uses.\n if (existingInteraction) {\n existingInteraction.duration = Math.max(existingInteraction.duration, duration);\n } else if (\n keys.length < MAX_INTERACTIONS ||\n minInteractionId === undefined ||\n duration > interactionIdToRouteNameMapping[minInteractionId].duration\n ) {\n // If the interaction does not exist, we want to add it to the mapping if there is space, or if the duration is longer than the shortest entry.\n const routeName = latestRoute.name;\n const parentContext = latestRoute.context;\n if (routeName && parentContext) {\n if (minInteractionId && Object.keys(interactionIdToRouteNameMapping).length >= MAX_INTERACTIONS) {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete interactionIdToRouteNameMapping[minInteractionId];\n }\n interactionIdToRouteNameMapping[interactionId] = {\n routeName,\n duration,\n parentContext,\n user,\n activeTransaction,\n replayId,\n startTime,\n };\n }\n }\n }\n });\n };\n addPerformanceInstrumentationHandler('event', handleEntries);\n addPerformanceInstrumentationHandler('first-input', handleEntries);\n}\n\nfunction getSource(context: TransactionContext): TransactionSource | undefined {\n const sourceFromAttributes = context.attributes && context.attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];\n // eslint-disable-next-line deprecation/deprecation\n const sourceFromData = context.data && context.data[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];\n // eslint-disable-next-line deprecation/deprecation\n const sourceFromMetadata = context.metadata && context.metadata.source;\n\n return sourceFromAttributes || sourceFromData || sourceFromMetadata;\n}\n","export { IdleTransaction, Span, SpanStatus, Transaction, extractTraceparentData, getActiveTransaction, hasTracingEnabled, spanStatusfromHttpCode, startIdleTransaction } from '@sentry/core';\nexport { TRACEPARENT_REGEXP, stripUrlQueryAndFragment } from '@sentry/utils';\nexport { Express } from './node/integrations/express.js';\nexport { Postgres } from './node/integrations/postgres.js';\nexport { Mysql } from './node/integrations/mysql.js';\nexport { Mongo } from './node/integrations/mongo.js';\nexport { Prisma } from './node/integrations/prisma.js';\nexport { GraphQL } from './node/integrations/graphql.js';\nexport { Apollo } from './node/integrations/apollo.js';\nexport { lazyLoadedNodePerformanceMonitoringIntegrations } from './node/integrations/lazy.js';\nexport { BROWSER_TRACING_INTEGRATION_ID, BrowserTracing } from './browser/browsertracing.js';\nexport { browserTracingIntegration, startBrowserTracingNavigationSpan, startBrowserTracingPageLoadSpan } from './browser/browserTracingIntegration.js';\nexport { defaultRequestInstrumentationOptions, instrumentOutgoingRequests } from './browser/request.js';\nexport { addClsInstrumentationHandler, addFidInstrumentationHandler, addLcpInstrumentationHandler, addPerformanceInstrumentationHandler } from './browser/instrument.js';\nexport { addTracingHeadersToFetchRequest, instrumentFetchRequest } from './common/fetch.js';\nexport { addExtensionMethods } from './extensions.js';\n//# sourceMappingURL=index.js.map\n","import type { Hub } from '@sentry/types';\n\n/**\n * Check if Sentry auto-instrumentation should be disabled.\n *\n * @param getCurrentHub A method to fetch the current hub\n * @returns boolean\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function shouldDisableAutoInstrumentation(getCurrentHub: () => Hub): boolean {\n // eslint-disable-next-line deprecation/deprecation\n const clientOptions = getCurrentHub().getClient()?.getOptions();\n const instrumenter = clientOptions?.instrumenter || 'sentry';\n\n return instrumenter !== 'sentry';\n}\n","/* eslint-disable max-lines */\nimport { SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, spanToJSON } from '@sentry/core';\nimport type { Hub, Integration, PolymorphicRequest, Transaction } from '@sentry/types';\nimport {\n GLOBAL_OBJ,\n extractPathForTransaction,\n getNumberOfUrlSegments,\n isRegExp,\n logger,\n stripUrlQueryAndFragment,\n} from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../../common/debug-build';\nimport { shouldDisableAutoInstrumentation } from './utils/node-utils';\n\ntype Method =\n | 'all'\n | 'get'\n | 'post'\n | 'put'\n | 'delete'\n | 'patch'\n | 'options'\n | 'head'\n | 'checkout'\n | 'copy'\n | 'lock'\n | 'merge'\n | 'mkactivity'\n | 'mkcol'\n | 'move'\n | 'm-search'\n | 'notify'\n | 'purge'\n | 'report'\n | 'search'\n | 'subscribe'\n | 'trace'\n | 'unlock'\n | 'unsubscribe'\n | 'use';\n\ntype Router = {\n [method in Method]: (...args: any) => any; // eslint-disable-line @typescript-eslint/no-explicit-any\n};\n\n/* Extend the PolymorphicRequest type with a patched parameter to build a reconstructed route */\ntype PatchedRequest = PolymorphicRequest & { _reconstructedRoute?: string; _hasParameters?: boolean };\n\n/* Types used for patching the express router prototype */\ntype ExpressRouter = Router & {\n _router?: ExpressRouter;\n stack?: Layer[];\n lazyrouter?: () => void;\n settings?: unknown;\n process_params: (\n layer: Layer,\n called: unknown,\n req: PatchedRequest,\n res: ExpressResponse,\n done: () => void,\n ) => unknown;\n};\n\ntype Layer = {\n match: (path: string) => boolean;\n handle_request: (req: PatchedRequest, res: ExpressResponse, next: () => void) => void;\n route?: { path: RouteType | RouteType[] };\n path?: string;\n regexp?: RegExp;\n keys?: { name: string | number; offset: number; optional: boolean }[];\n};\n\ntype RouteType = string | RegExp;\n\ninterface ExpressResponse {\n once(name: string, callback: () => void): void;\n}\n\n/**\n * Internal helper for `__sentry_transaction`\n * @hidden\n */\ninterface SentryTracingResponse {\n __sentry_transaction?: Transaction;\n}\n\n/**\n * Express integration\n *\n * Provides an request and error handler for Express framework as well as tracing capabilities\n */\nexport class Express implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'Express';\n\n /**\n * @inheritDoc\n */\n public name: string;\n\n /**\n * Express App instance\n */\n private readonly _router?: Router;\n private readonly _methods?: Method[];\n\n /**\n * @inheritDoc\n */\n public constructor(options: { app?: Router; router?: Router; methods?: Method[] } = {}) {\n this.name = Express.id;\n this._router = options.router || options.app;\n this._methods = (Array.isArray(options.methods) ? options.methods : []).concat('use');\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line deprecation/deprecation\n public setupOnce(_: unknown, getCurrentHub: () => Hub): void {\n if (!this._router) {\n DEBUG_BUILD && logger.error('ExpressIntegration is missing an Express instance');\n return;\n }\n\n if (shouldDisableAutoInstrumentation(getCurrentHub)) {\n DEBUG_BUILD && logger.log('Express Integration is skipped because of instrumenter configuration.');\n return;\n }\n\n instrumentMiddlewares(this._router, this._methods);\n instrumentRouter(this._router as ExpressRouter);\n }\n}\n\n/**\n * Wraps original middleware function in a tracing call, which stores the info about the call as a span,\n * and finishes it once the middleware is done invoking.\n *\n * Express middlewares have 3 various forms, thus we have to take care of all of them:\n * // sync\n * app.use(function (req, res) { ... })\n * // async\n * app.use(function (req, res, next) { ... })\n * // error handler\n * app.use(function (err, req, res, next) { ... })\n *\n * They all internally delegate to the `router[method]` of the given application instance.\n */\n// eslint-disable-next-line @typescript-eslint/ban-types, @typescript-eslint/no-explicit-any\nfunction wrap(fn: Function, method: Method): (...args: any[]) => void {\n const arity = fn.length;\n\n switch (arity) {\n case 2: {\n return function (this: NodeJS.Global, req: unknown, res: ExpressResponse & SentryTracingResponse): void {\n const transaction = res.__sentry_transaction;\n if (transaction) {\n // eslint-disable-next-line deprecation/deprecation\n const span = transaction.startChild({\n description: fn.name,\n op: `middleware.express.${method}`,\n origin: 'auto.middleware.express',\n });\n res.once('finish', () => {\n span.end();\n });\n }\n return fn.call(this, req, res);\n };\n }\n case 3: {\n return function (\n this: NodeJS.Global,\n req: unknown,\n res: ExpressResponse & SentryTracingResponse,\n next: () => void,\n ): void {\n const transaction = res.__sentry_transaction;\n // eslint-disable-next-line deprecation/deprecation\n const span = transaction?.startChild({\n description: fn.name,\n op: `middleware.express.${method}`,\n origin: 'auto.middleware.express',\n });\n fn.call(this, req, res, function (this: NodeJS.Global, ...args: unknown[]): void {\n span?.end();\n next.call(this, ...args);\n });\n };\n }\n case 4: {\n return function (\n this: NodeJS.Global,\n err: Error,\n req: Request,\n res: Response & SentryTracingResponse,\n next: () => void,\n ): void {\n const transaction = res.__sentry_transaction;\n // eslint-disable-next-line deprecation/deprecation\n const span = transaction?.startChild({\n description: fn.name,\n op: `middleware.express.${method}`,\n origin: 'auto.middleware.express',\n });\n fn.call(this, err, req, res, function (this: NodeJS.Global, ...args: unknown[]): void {\n span?.end();\n next.call(this, ...args);\n });\n };\n }\n default: {\n throw new Error(`Express middleware takes 2-4 arguments. Got: ${arity}`);\n }\n }\n}\n\n/**\n * Takes all the function arguments passed to the original `app` or `router` method, eg. `app.use` or `router.use`\n * and wraps every function, as well as array of functions with a call to our `wrap` method.\n * We have to take care of the arrays as well as iterate over all of the arguments,\n * as `app.use` can accept middlewares in few various forms.\n *\n * app.use([<path>], <fn>)\n * app.use([<path>], <fn>, ...<fn>)\n * app.use([<path>], ...<fn>[])\n */\nfunction wrapMiddlewareArgs(args: unknown[], method: Method): unknown[] {\n return args.map((arg: unknown) => {\n if (typeof arg === 'function') {\n return wrap(arg, method);\n }\n\n if (Array.isArray(arg)) {\n return arg.map((a: unknown) => {\n if (typeof a === 'function') {\n return wrap(a, method);\n }\n return a;\n });\n }\n\n return arg;\n });\n}\n\n/**\n * Patches original router to utilize our tracing functionality\n */\nfunction patchMiddleware(router: Router, method: Method): Router {\n const originalCallback = router[method];\n\n router[method] = function (...args: unknown[]): void {\n return originalCallback.call(this, ...wrapMiddlewareArgs(args, method));\n };\n\n return router;\n}\n\n/**\n * Patches original router methods\n */\nfunction instrumentMiddlewares(router: Router, methods: Method[] = []): void {\n methods.forEach((method: Method) => patchMiddleware(router, method));\n}\n\n/**\n * Patches the prototype of Express.Router to accumulate the resolved route\n * if a layer instance's `match` function was called and it returned a successful match.\n *\n * @see https://github.com/expressjs/express/blob/master/lib/router/index.js\n *\n * @param appOrRouter the router instance which can either be an app (i.e. top-level) or a (nested) router.\n */\nfunction instrumentRouter(appOrRouter: ExpressRouter): void {\n // This is how we can distinguish between app and routers\n const isApp = 'settings' in appOrRouter;\n\n // In case the app's top-level router hasn't been initialized yet, we have to do it now\n if (isApp && appOrRouter._router === undefined && appOrRouter.lazyrouter) {\n appOrRouter.lazyrouter();\n }\n\n const router = isApp ? appOrRouter._router : appOrRouter;\n\n if (!router) {\n /*\n If we end up here, this means likely that this integration is used with Express 3 or Express 5.\n For now, we don't support these versions (3 is very old and 5 is still in beta). To support Express 5,\n we'd need to make more changes to the routing instrumentation because the router is no longer part of\n the Express core package but maintained in its own package. The new router has different function\n signatures and works slightly differently, demanding more changes than just taking the router from\n `app.router` instead of `app._router`.\n @see https://github.com/pillarjs/router\n\n TODO: Proper Express 5 support\n */\n DEBUG_BUILD && logger.debug('Cannot instrument router for URL Parameterization (did not find a valid router).');\n DEBUG_BUILD && logger.debug('Routing instrumentation is currently only supported in Express 4.');\n return;\n }\n\n const routerProto = Object.getPrototypeOf(router) as ExpressRouter;\n\n const originalProcessParams = routerProto.process_params;\n routerProto.process_params = function process_params(\n layer: Layer,\n called: unknown,\n req: PatchedRequest,\n res: ExpressResponse & SentryTracingResponse,\n done: () => unknown,\n ) {\n // Base case: We're in the first part of the URL (thus we start with the root '/')\n if (!req._reconstructedRoute) {\n req._reconstructedRoute = '';\n }\n\n // If the layer's partial route has params, is a regex or an array, the route is stored in layer.route.\n const { layerRoutePath, isRegex, isArray, numExtraSegments }: LayerRoutePathInfo = getLayerRoutePathInfo(layer);\n\n if (layerRoutePath || isRegex || isArray) {\n req._hasParameters = true;\n }\n\n // Otherwise, the hardcoded path (i.e. a partial route without params) is stored in layer.path\n let partialRoute;\n\n if (layerRoutePath) {\n partialRoute = layerRoutePath;\n } else {\n /**\n * prevent duplicate segment in _reconstructedRoute param if router match multiple routes before final path\n * example:\n * original url: /api/v1/1234\n * prevent: /api/api/v1/:userId\n * router structure\n * /api -> middleware\n * /api/v1 -> middleware\n * /1234 -> endpoint with param :userId\n * final _reconstructedRoute is /api/v1/:userId\n */\n partialRoute = preventDuplicateSegments(req.originalUrl, req._reconstructedRoute, layer.path) || '';\n }\n\n // Normalize the partial route so that it doesn't contain leading or trailing slashes\n // and exclude empty or '*' wildcard routes.\n // The exclusion of '*' routes is our best effort to not \"pollute\" the transaction name\n // with interim handlers (e.g. ones that check authentication or do other middleware stuff).\n // We want to end up with the parameterized URL of the incoming request without any extraneous path segments.\n const finalPartialRoute = partialRoute\n .split('/')\n .filter(segment => segment.length > 0 && (isRegex || isArray || !segment.includes('*')))\n .join('/');\n\n // If we found a valid partial URL, we append it to the reconstructed route\n if (finalPartialRoute && finalPartialRoute.length > 0) {\n // If the partial route is from a regex route, we append a '/' to close the regex\n req._reconstructedRoute += `/${finalPartialRoute}${isRegex ? '/' : ''}`;\n }\n\n // Now we check if we are in the \"last\" part of the route. We determine this by comparing the\n // number of URL segments from the original URL to that of our reconstructed parameterized URL.\n // If we've reached our final destination, we update the transaction name.\n const urlLength = getNumberOfUrlSegments(stripUrlQueryAndFragment(req.originalUrl || '')) + numExtraSegments;\n const routeLength = getNumberOfUrlSegments(req._reconstructedRoute);\n\n if (urlLength === routeLength) {\n if (!req._hasParameters) {\n if (req._reconstructedRoute !== req.originalUrl) {\n req._reconstructedRoute = req.originalUrl ? stripUrlQueryAndFragment(req.originalUrl) : req.originalUrl;\n }\n }\n\n const transaction = res.__sentry_transaction;\n const attributes = (transaction && spanToJSON(transaction).data) || {};\n if (transaction && attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] !== 'custom') {\n // If the request URL is '/' or empty, the reconstructed route will be empty.\n // Therefore, we fall back to setting the final route to '/' in this case.\n const finalRoute = req._reconstructedRoute || '/';\n\n const [name, source] = extractPathForTransaction(req, { path: true, method: true, customRoute: finalRoute });\n transaction.updateName(name);\n transaction.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, source);\n }\n }\n\n return originalProcessParams.call(this, layer, called, req, res, done);\n };\n}\n\ntype LayerRoutePathInfo = {\n layerRoutePath?: string;\n isRegex: boolean;\n isArray: boolean;\n numExtraSegments: number;\n};\n\n/**\n * Recreate layer.route.path from layer.regexp and layer.keys.\n * Works until express.js used package path-to-regexp@0.1.7\n * or until layer.keys contain offset attribute\n *\n * @param layer the layer to extract the stringified route from\n *\n * @returns string in layer.route.path structure 'router/:pathParam' or undefined\n */\nexport const extractOriginalRoute = (\n path?: Layer['path'],\n regexp?: Layer['regexp'],\n keys?: Layer['keys'],\n): string | undefined => {\n if (!path || !regexp || !keys || Object.keys(keys).length === 0 || !keys[0]?.offset) {\n return undefined;\n }\n\n const orderedKeys = keys.sort((a, b) => a.offset - b.offset);\n\n // add d flag for getting indices from regexp result\n // eslint-disable-next-line @sentry-internal/sdk/no-regexp-constructor -- regexp comes from express.js\n const pathRegex = new RegExp(regexp, `${regexp.flags}d`);\n /**\n * use custom type cause of TS error with missing indices in RegExpExecArray\n */\n const execResult = pathRegex.exec(path) as (RegExpExecArray & { indices: [number, number][] }) | null;\n\n if (!execResult || !execResult.indices) {\n return undefined;\n }\n /**\n * remove first match from regex cause contain whole layer.path\n */\n const [, ...paramIndices] = execResult.indices;\n\n if (paramIndices.length !== orderedKeys.length) {\n return undefined;\n }\n let resultPath = path;\n let indexShift = 0;\n\n /**\n * iterate param matches from regexp.exec\n */\n paramIndices.forEach((item: [number, number] | undefined, index: number) => {\n /** check if offsets is define because in some cases regex d flag returns undefined */\n if (item) {\n const [startOffset, endOffset] = item;\n /**\n * isolate part before param\n */\n const substr1 = resultPath.substring(0, startOffset - indexShift);\n /**\n * define paramName as replacement in format :pathParam\n */\n const replacement = `:${orderedKeys[index].name}`;\n\n /**\n * isolate part after param\n */\n const substr2 = resultPath.substring(endOffset - indexShift);\n\n /**\n * recreate original path but with param replacement\n */\n resultPath = substr1 + replacement + substr2;\n\n /**\n * calculate new index shift after resultPath was modified\n */\n indexShift = indexShift + (endOffset - startOffset - replacement.length);\n }\n });\n\n return resultPath;\n};\n\n/**\n * Extracts and stringifies the layer's route which can either be a string with parameters (`users/:id`),\n * a RegEx (`/test/`) or an array of strings and regexes (`['/path1', /\\/path[2-5]/, /path/:id]`). Additionally\n * returns extra information about the route, such as if the route is defined as regex or as an array.\n *\n * @param layer the layer to extract the stringified route from\n *\n * @returns an object containing the stringified route, a flag determining if the route was a regex\n * and the number of extra segments to the matched path that are additionally in the route,\n * if the route was an array (defaults to 0).\n */\nfunction getLayerRoutePathInfo(layer: Layer): LayerRoutePathInfo {\n let lrp = layer.route?.path;\n\n const isRegex = isRegExp(lrp);\n const isArray = Array.isArray(lrp);\n\n if (!lrp) {\n // parse node.js major version\n // Next.js will complain if we directly use `proces.versions` here because of edge runtime.\n const [major] = (GLOBAL_OBJ as unknown as NodeJS.Global).process.versions.node.split('.').map(Number);\n\n // allow call extractOriginalRoute only if node version support Regex d flag, node 16+\n if (major >= 16) {\n /**\n * If lrp does not exist try to recreate original layer path from route regexp\n */\n lrp = extractOriginalRoute(layer.path, layer.regexp, layer.keys);\n }\n }\n\n if (!lrp) {\n return { isRegex, isArray, numExtraSegments: 0 };\n }\n\n const numExtraSegments = isArray\n ? Math.max(getNumberOfArrayUrlSegments(lrp as RouteType[]) - getNumberOfUrlSegments(layer.path || ''), 0)\n : 0;\n\n const layerRoutePath = getLayerRoutePathString(isArray, lrp);\n\n return { layerRoutePath, isRegex, isArray, numExtraSegments };\n}\n\n/**\n * Returns the number of URL segments in an array of routes\n *\n * Example: ['/api/test', /\\/api\\/post[0-9]/, '/users/:id/details`] -> 7\n */\nfunction getNumberOfArrayUrlSegments(routesArray: RouteType[]): number {\n return routesArray.reduce((accNumSegments: number, currentRoute: RouteType) => {\n // array members can be a RegEx -> convert them toString\n return accNumSegments + getNumberOfUrlSegments(currentRoute.toString());\n }, 0);\n}\n\n/**\n * Extracts and returns the stringified version of the layers route path\n * Handles route arrays (by joining the paths together) as well as RegExp and normal\n * string values (in the latter case the toString conversion is technically unnecessary but\n * it doesn't hurt us either).\n */\nfunction getLayerRoutePathString(isArray: boolean, lrp?: RouteType | RouteType[]): string | undefined {\n if (isArray) {\n return (lrp as RouteType[]).map(r => r.toString()).join(',');\n }\n return lrp && lrp.toString();\n}\n\n/**\n * remove duplicate segment contain in layerPath against reconstructedRoute,\n * and return only unique segment that can be added into reconstructedRoute\n */\nexport function preventDuplicateSegments(\n originalUrl?: string,\n reconstructedRoute?: string,\n layerPath?: string,\n): string | undefined {\n // filter query params\n const normalizeURL = stripUrlQueryAndFragment(originalUrl || '');\n const originalUrlSplit = normalizeURL?.split('/').filter(v => !!v);\n let tempCounter = 0;\n const currentOffset = reconstructedRoute?.split('/').filter(v => !!v).length || 0;\n const result = layerPath\n ?.split('/')\n .filter(segment => {\n if (originalUrlSplit?.[currentOffset + tempCounter] === segment) {\n tempCounter += 1;\n return true;\n }\n return false;\n })\n .join('/');\n return result;\n}\n","import type { Hub } from '@sentry/core';\nimport type { EventProcessor } from '@sentry/types';\nimport { fill, isThenable, loadModule, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../../common/debug-build';\nimport type { LazyLoadedIntegration } from './lazy';\nimport { shouldDisableAutoInstrumentation } from './utils/node-utils';\n\ntype PgClientQuery = (\n config: unknown,\n values?: unknown,\n callback?: (err: unknown, result: unknown) => void,\n) => void | Promise<unknown>;\n\ninterface PgClient {\n prototype: {\n query: PgClientQuery;\n };\n}\n\ninterface PgClientThis {\n database?: string;\n host?: string;\n port?: number;\n user?: string;\n}\n\ninterface PgOptions {\n usePgNative?: boolean;\n /**\n * Supply your postgres module directly, instead of having Sentry attempt automatic resolution.\n * Use this if you (a) use a module that's not `pg`, or (b) use a bundler that breaks resolution (e.g. esbuild).\n *\n * Usage:\n * ```\n * import pg from 'pg';\n *\n * Sentry.init({\n * integrations: [new Sentry.Integrations.Postgres({ module: pg })],\n * });\n * ```\n */\n module?: PGModule;\n}\n\ntype PGModule = { Client: PgClient; native: { Client: PgClient } | null };\n\n/** Tracing integration for node-postgres package */\nexport class Postgres implements LazyLoadedIntegration<PGModule> {\n /**\n * @inheritDoc\n */\n public static id: string = 'Postgres';\n\n /**\n * @inheritDoc\n */\n public name: string;\n\n private _usePgNative: boolean;\n\n private _module?: PGModule;\n\n public constructor(options: PgOptions = {}) {\n this.name = Postgres.id;\n this._usePgNative = !!options.usePgNative;\n this._module = options.module;\n }\n\n /** @inheritdoc */\n public loadDependency(): PGModule | undefined {\n return (this._module = this._module || loadModule('pg'));\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line deprecation/deprecation\n public setupOnce(_: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {\n if (shouldDisableAutoInstrumentation(getCurrentHub)) {\n DEBUG_BUILD && logger.log('Postgres Integration is skipped because of instrumenter configuration.');\n return;\n }\n\n const pkg = this.loadDependency();\n\n if (!pkg) {\n DEBUG_BUILD && logger.error('Postgres Integration was unable to require `pg` package.');\n return;\n }\n\n const Client = this._usePgNative ? pkg.native?.Client : pkg.Client;\n\n if (!Client) {\n DEBUG_BUILD && logger.error(\"Postgres Integration was unable to access 'pg-native' bindings.\");\n return;\n }\n\n /**\n * function (query, callback) => void\n * function (query, params, callback) => void\n * function (query) => Promise\n * function (query, params) => Promise\n * function (pg.Cursor) => pg.Cursor\n */\n fill(Client.prototype, 'query', function (orig: PgClientQuery) {\n return function (this: PgClientThis, config: unknown, values: unknown, callback: unknown) {\n // eslint-disable-next-line deprecation/deprecation\n const scope = getCurrentHub().getScope();\n // eslint-disable-next-line deprecation/deprecation\n const parentSpan = scope.getSpan();\n\n const data: Record<string, string | number> = {\n 'db.system': 'postgresql',\n };\n\n try {\n if (this.database) {\n data['db.name'] = this.database;\n }\n if (this.host) {\n data['server.address'] = this.host;\n }\n if (this.port) {\n data['server.port'] = this.port;\n }\n if (this.user) {\n data['db.user'] = this.user;\n }\n } catch (e) {\n // ignore\n }\n\n // eslint-disable-next-line deprecation/deprecation\n const span = parentSpan?.startChild({\n description: typeof config === 'string' ? config : (config as { text: string }).text,\n op: 'db',\n origin: 'auto.db.postgres',\n data,\n });\n\n if (typeof callback === 'function') {\n return orig.call(this, config, values, function (err: Error, result: unknown) {\n span?.end();\n callback(err, result);\n });\n }\n\n if (typeof values === 'function') {\n return orig.call(this, config, function (err: Error, result: unknown) {\n span?.end();\n values(err, result);\n });\n }\n\n const rv = typeof values !== 'undefined' ? orig.call(this, config, values) : orig.call(this, config);\n\n if (isThenable(rv)) {\n return rv.then((res: unknown) => {\n span?.end();\n return res;\n });\n }\n\n span?.end();\n return rv;\n };\n });\n }\n}\n","import type { Hub } from '@sentry/core';\nimport type { EventProcessor, Span } from '@sentry/types';\nimport { fill, loadModule, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../../common/debug-build';\nimport type { LazyLoadedIntegration } from './lazy';\nimport { shouldDisableAutoInstrumentation } from './utils/node-utils';\n\ninterface MysqlConnection {\n prototype: {\n connect: () => void;\n };\n createQuery: () => void;\n}\n\ninterface MysqlConnectionConfig {\n host: string;\n port: number;\n user: string;\n}\n\n/** Tracing integration for node-mysql package */\nexport class Mysql implements LazyLoadedIntegration<MysqlConnection> {\n /**\n * @inheritDoc\n */\n public static id: string = 'Mysql';\n\n /**\n * @inheritDoc\n */\n public name: string;\n\n private _module?: MysqlConnection;\n\n public constructor() {\n this.name = Mysql.id;\n }\n\n /** @inheritdoc */\n public loadDependency(): MysqlConnection | undefined {\n return (this._module = this._module || loadModule('mysql/lib/Connection.js'));\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line deprecation/deprecation\n public setupOnce(_: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {\n if (shouldDisableAutoInstrumentation(getCurrentHub)) {\n DEBUG_BUILD && logger.log('Mysql Integration is skipped because of instrumenter configuration.');\n return;\n }\n\n const pkg = this.loadDependency();\n\n if (!pkg) {\n DEBUG_BUILD && logger.error('Mysql Integration was unable to require `mysql` package.');\n return;\n }\n\n let mySqlConfig: MysqlConnectionConfig | undefined = undefined;\n\n try {\n pkg.prototype.connect = new Proxy(pkg.prototype.connect, {\n apply(wrappingTarget, thisArg: { config: MysqlConnectionConfig }, args) {\n if (!mySqlConfig) {\n mySqlConfig = thisArg.config;\n }\n return wrappingTarget.apply(thisArg, args);\n },\n });\n } catch (e) {\n DEBUG_BUILD && logger.error('Mysql Integration was unable to instrument `mysql` config.');\n }\n\n function spanDataFromConfig(): Record<string, string | number | undefined> {\n if (!mySqlConfig) {\n return {};\n }\n return {\n 'server.address': mySqlConfig.host,\n 'server.port': mySqlConfig.port,\n 'db.user': mySqlConfig.user,\n };\n }\n\n function finishSpan(span: Span | undefined): void {\n if (!span) {\n return;\n }\n\n const data = spanDataFromConfig();\n Object.keys(data).forEach(key => {\n span.setAttribute(key, data[key]);\n });\n\n span.end();\n }\n\n // The original function will have one of these signatures:\n // function (callback) => void\n // function (options, callback) => void\n // function (options, values, callback) => void\n fill(pkg, 'createQuery', function (orig: () => void) {\n return function (this: unknown, options: unknown, values: unknown, callback: unknown) {\n // eslint-disable-next-line deprecation/deprecation\n const scope = getCurrentHub().getScope();\n // eslint-disable-next-line deprecation/deprecation\n const parentSpan = scope.getSpan();\n\n // eslint-disable-next-line deprecation/deprecation\n const span = parentSpan?.startChild({\n description: typeof options === 'string' ? options : (options as { sql: string }).sql,\n op: 'db',\n origin: 'auto.db.mysql',\n data: {\n 'db.system': 'mysql',\n },\n });\n\n if (typeof callback === 'function') {\n return orig.call(this, options, values, function (err: Error, result: unknown, fields: unknown) {\n finishSpan(span);\n callback(err, result, fields);\n });\n }\n\n if (typeof values === 'function') {\n return orig.call(this, options, function (err: Error, result: unknown, fields: unknown) {\n finishSpan(span);\n values(err, result, fields);\n });\n }\n\n // streaming, no callback!\n const query = orig.call(this, options, values) as { on: (event: string, callback: () => void) => void };\n\n query.on('end', () => {\n finishSpan(span);\n });\n\n return query;\n };\n });\n }\n}\n","import type { Hub } from '@sentry/core';\nimport type { EventProcessor, SpanContext } from '@sentry/types';\nimport { fill, isThenable, loadModule, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../../common/debug-build';\nimport type { LazyLoadedIntegration } from './lazy';\nimport { shouldDisableAutoInstrumentation } from './utils/node-utils';\n\n// This allows us to use the same array for both defaults options and the type itself.\n// (note `as const` at the end to make it a union of string literal types (i.e. \"a\" | \"b\" | ... )\n// and not just a string[])\ntype Operation = (typeof OPERATIONS)[number];\nconst OPERATIONS = [\n 'aggregate', // aggregate(pipeline, options, callback)\n 'bulkWrite', // bulkWrite(operations, options, callback)\n 'countDocuments', // countDocuments(query, options, callback)\n 'createIndex', // createIndex(fieldOrSpec, options, callback)\n 'createIndexes', // createIndexes(indexSpecs, options, callback)\n 'deleteMany', // deleteMany(filter, options, callback)\n 'deleteOne', // deleteOne(filter, options, callback)\n 'distinct', // distinct(key, query, options, callback)\n 'drop', // drop(options, callback)\n 'dropIndex', // dropIndex(indexName, options, callback)\n 'dropIndexes', // dropIndexes(options, callback)\n 'estimatedDocumentCount', // estimatedDocumentCount(options, callback)\n 'find', // find(query, options, callback)\n 'findOne', // findOne(query, options, callback)\n 'findOneAndDelete', // findOneAndDelete(filter, options, callback)\n 'findOneAndReplace', // findOneAndReplace(filter, replacement, options, callback)\n 'findOneAndUpdate', // findOneAndUpdate(filter, update, options, callback)\n 'indexes', // indexes(options, callback)\n 'indexExists', // indexExists(indexes, options, callback)\n 'indexInformation', // indexInformation(options, callback)\n 'initializeOrderedBulkOp', // initializeOrderedBulkOp(options, callback)\n 'insertMany', // insertMany(docs, options, callback)\n 'insertOne', // insertOne(doc, options, callback)\n 'isCapped', // isCapped(options, callback)\n 'mapReduce', // mapReduce(map, reduce, options, callback)\n 'options', // options(options, callback)\n 'parallelCollectionScan', // parallelCollectionScan(options, callback)\n 'rename', // rename(newName, options, callback)\n 'replaceOne', // replaceOne(filter, doc, options, callback)\n 'stats', // stats(options, callback)\n 'updateMany', // updateMany(filter, update, options, callback)\n 'updateOne', // updateOne(filter, update, options, callback)\n] as const;\n\n// All of the operations above take `options` and `callback` as their final parameters, but some of them\n// take additional parameters as well. For those operations, this is a map of\n// { <operation name>: [<names of additional parameters>] }, as a way to know what to call the operation's\n// positional arguments when we add them to the span's `data` object later\nconst OPERATION_SIGNATURES: {\n [op in Operation]?: string[];\n} = {\n // aggregate intentionally not included because `pipeline` arguments are too complex to serialize well\n // see https://github.com/getsentry/sentry-javascript/pull/3102\n bulkWrite: ['operations'],\n countDocuments: ['query'],\n createIndex: ['fieldOrSpec'],\n createIndexes: ['indexSpecs'],\n deleteMany: ['filter'],\n deleteOne: ['filter'],\n distinct: ['key', 'query'],\n dropIndex: ['indexName'],\n find: ['query'],\n findOne: ['query'],\n findOneAndDelete: ['filter'],\n findOneAndReplace: ['filter', 'replacement'],\n findOneAndUpdate: ['filter', 'update'],\n indexExists: ['indexes'],\n insertMany: ['docs'],\n insertOne: ['doc'],\n mapReduce: ['map', 'reduce'],\n rename: ['newName'],\n replaceOne: ['filter', 'doc'],\n updateMany: ['filter', 'update'],\n updateOne: ['filter', 'update'],\n};\n\ninterface MongoCollection {\n collectionName: string;\n dbName: string;\n namespace: string;\n prototype: {\n [operation in Operation]: (...args: unknown[]) => unknown;\n };\n}\n\ninterface MongoOptions {\n operations?: Operation[];\n describeOperations?: boolean | Operation[];\n useMongoose?: boolean;\n}\n\ninterface MongoCursor {\n once(event: 'close', listener: () => void): void;\n}\n\nfunction isCursor(maybeCursor: MongoCursor): maybeCursor is MongoCursor {\n return maybeCursor && typeof maybeCursor === 'object' && maybeCursor.once && typeof maybeCursor.once === 'function';\n}\n\ntype MongoModule = { Collection: MongoCollection };\n\n/** Tracing integration for mongo package */\nexport class Mongo implements LazyLoadedIntegration<MongoModule> {\n /**\n * @inheritDoc\n */\n public static id: string = 'Mongo';\n\n /**\n * @inheritDoc\n */\n public name: string;\n\n private _operations: Operation[];\n private _describeOperations?: boolean | Operation[];\n private _useMongoose: boolean;\n\n private _module?: MongoModule;\n\n /**\n * @inheritDoc\n */\n public constructor(options: MongoOptions = {}) {\n this.name = Mongo.id;\n this._operations = Array.isArray(options.operations) ? options.operations : (OPERATIONS as unknown as Operation[]);\n this._describeOperations = 'describeOperations' in options ? options.describeOperations : true;\n this._useMongoose = !!options.useMongoose;\n }\n\n /** @inheritdoc */\n public loadDependency(): MongoModule | undefined {\n const moduleName = this._useMongoose ? 'mongoose' : 'mongodb';\n return (this._module = this._module || loadModule(moduleName));\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line deprecation/deprecation\n public setupOnce(_: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {\n if (shouldDisableAutoInstrumentation(getCurrentHub)) {\n DEBUG_BUILD && logger.log('Mongo Integration is skipped because of instrumenter configuration.');\n return;\n }\n\n const pkg = this.loadDependency();\n\n if (!pkg) {\n const moduleName = this._useMongoose ? 'mongoose' : 'mongodb';\n DEBUG_BUILD && logger.error(`Mongo Integration was unable to require \\`${moduleName}\\` package.`);\n return;\n }\n\n this._instrumentOperations(pkg.Collection, this._operations, getCurrentHub);\n }\n\n /**\n * Patches original collection methods\n */\n // eslint-disable-next-line deprecation/deprecation\n private _instrumentOperations(collection: MongoCollection, operations: Operation[], getCurrentHub: () => Hub): void {\n operations.forEach((operation: Operation) => this._patchOperation(collection, operation, getCurrentHub));\n }\n\n /**\n * Patches original collection to utilize our tracing functionality\n */\n // eslint-disable-next-line deprecation/deprecation\n private _patchOperation(collection: MongoCollection, operation: Operation, getCurrentHub: () => Hub): void {\n if (!(operation in collection.prototype)) return;\n\n const getSpanContext = this._getSpanContextFromOperationArguments.bind(this);\n\n fill(collection.prototype, operation, function (orig: () => void | Promise<unknown>) {\n return function (this: unknown, ...args: unknown[]) {\n const lastArg = args[args.length - 1];\n // eslint-disable-next-line deprecation/deprecation\n const hub = getCurrentHub();\n // eslint-disable-next-line deprecation/deprecation\n const scope = hub.getScope();\n // eslint-disable-next-line deprecation/deprecation\n const client = hub.getClient();\n // eslint-disable-next-line deprecation/deprecation\n const parentSpan = scope.getSpan();\n\n const sendDefaultPii = client?.getOptions().sendDefaultPii;\n\n // Check if the operation was passed a callback. (mapReduce requires a different check, as\n // its (non-callback) arguments can also be functions.)\n if (typeof lastArg !== 'function' || (operation === 'mapReduce' && args.length === 2)) {\n // eslint-disable-next-line deprecation/deprecation\n const span = parentSpan?.startChild(getSpanContext(this, operation, args, sendDefaultPii));\n const maybePromiseOrCursor = orig.call(this, ...args);\n\n if (isThenable(maybePromiseOrCursor)) {\n return maybePromiseOrCursor.then((res: unknown) => {\n span?.end();\n return res;\n });\n }\n // If the operation returns a Cursor\n // we need to attach a listener to it to finish the span when the cursor is closed.\n else if (isCursor(maybePromiseOrCursor)) {\n const cursor = maybePromiseOrCursor as MongoCursor;\n\n try {\n cursor.once('close', () => {\n span?.end();\n });\n } catch (e) {\n // If the cursor is already closed, `once` will throw an error. In that case, we can\n // finish the span immediately.\n span?.end();\n }\n\n return cursor;\n } else {\n span?.end();\n return maybePromiseOrCursor;\n }\n }\n\n // eslint-disable-next-line deprecation/deprecation\n const span = parentSpan?.startChild(getSpanContext(this, operation, args.slice(0, -1)));\n\n return orig.call(this, ...args.slice(0, -1), function (err: Error, result: unknown) {\n span?.end();\n lastArg(err, result);\n });\n };\n });\n }\n\n /**\n * Form a SpanContext based on the user input to a given operation.\n */\n private _getSpanContextFromOperationArguments(\n collection: MongoCollection,\n operation: Operation,\n args: unknown[],\n sendDefaultPii: boolean | undefined = false,\n ): SpanContext {\n const data: { [key: string]: string } = {\n 'db.system': 'mongodb',\n 'db.name': collection.dbName,\n 'db.operation': operation,\n 'db.mongodb.collection': collection.collectionName,\n };\n const spanContext: SpanContext = {\n op: 'db',\n // TODO v8: Use `${collection.collectionName}.${operation}`\n origin: 'auto.db.mongo',\n description: operation,\n data,\n };\n\n // If the operation takes no arguments besides `options` and `callback`, or if argument\n // collection is disabled for this operation, just return early.\n const signature = OPERATION_SIGNATURES[operation];\n const shouldDescribe = Array.isArray(this._describeOperations)\n ? this._describeOperations.includes(operation)\n : this._describeOperations;\n\n if (!signature || !shouldDescribe || !sendDefaultPii) {\n return spanContext;\n }\n\n try {\n // Special case for `mapReduce`, as the only one accepting functions as arguments.\n if (operation === 'mapReduce') {\n const [map, reduce] = args as { name?: string }[];\n data[signature[0]] = typeof map === 'string' ? map : map.name || '<anonymous>';\n data[signature[1]] = typeof reduce === 'string' ? reduce : reduce.name || '<anonymous>';\n } else {\n for (let i = 0; i < signature.length; i++) {\n data[`db.mongodb.${signature[i]}`] = JSON.stringify(args[i]);\n }\n }\n } catch (_oO) {\n // no-empty\n }\n\n return spanContext;\n }\n}\n","import { SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, getCurrentHub, startSpan } from '@sentry/core';\nimport type { Integration } from '@sentry/types';\nimport { addNonEnumerableProperty, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../../common/debug-build';\nimport { shouldDisableAutoInstrumentation } from './utils/node-utils';\n\ntype PrismaAction =\n | 'findUnique'\n | 'findMany'\n | 'findFirst'\n | 'create'\n | 'createMany'\n | 'update'\n | 'updateMany'\n | 'upsert'\n | 'delete'\n | 'deleteMany'\n | 'executeRaw'\n | 'queryRaw'\n | 'aggregate'\n | 'count'\n | 'runCommandRaw';\n\ninterface PrismaMiddlewareParams {\n model?: unknown;\n action: PrismaAction;\n args: unknown;\n dataPath: string[];\n runInTransaction: boolean;\n}\n\ntype PrismaMiddleware<T = unknown> = (\n params: PrismaMiddlewareParams,\n next: (params: PrismaMiddlewareParams) => Promise<T>,\n) => Promise<T>;\n\ninterface PrismaClient {\n _sentryInstrumented?: boolean;\n _engineConfig?: {\n activeProvider?: string;\n clientVersion?: string;\n };\n $use: (cb: PrismaMiddleware) => void;\n}\n\nfunction isValidPrismaClient(possibleClient: unknown): possibleClient is PrismaClient {\n return !!possibleClient && !!(possibleClient as PrismaClient)['$use'];\n}\n\n/** Tracing integration for @prisma/client package */\nexport class Prisma implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'Prisma';\n\n /**\n * @inheritDoc\n */\n public name: string;\n\n /**\n * @inheritDoc\n */\n public constructor(options: { client?: unknown } = {}) {\n this.name = Prisma.id;\n\n // We instrument the PrismaClient inside the constructor and not inside `setupOnce` because in some cases of server-side\n // bundling (Next.js) multiple Prisma clients can be instantiated, even though users don't intend to. When instrumenting\n // in setupOnce we can only ever instrument one client.\n // https://github.com/getsentry/sentry-javascript/issues/7216#issuecomment-1602375012\n // In the future we might explore providing a dedicated PrismaClient middleware instead of this hack.\n if (isValidPrismaClient(options.client) && !options.client._sentryInstrumented) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n addNonEnumerableProperty(options.client as any, '_sentryInstrumented', true);\n\n const clientData: Record<string, string | number> = {};\n try {\n const engineConfig = (options.client as PrismaClient)._engineConfig;\n if (engineConfig) {\n const { activeProvider, clientVersion } = engineConfig;\n if (activeProvider) {\n clientData['db.system'] = activeProvider;\n }\n if (clientVersion) {\n clientData['db.prisma.version'] = clientVersion;\n }\n }\n } catch (e) {\n // ignore\n }\n\n options.client.$use((params, next: (params: PrismaMiddlewareParams) => Promise<unknown>) => {\n // eslint-disable-next-line deprecation/deprecation\n if (shouldDisableAutoInstrumentation(getCurrentHub)) {\n return next(params);\n }\n\n const action = params.action;\n const model = params.model;\n\n return startSpan(\n {\n name: model ? `${model} ${action}` : action,\n onlyIfParent: true,\n op: 'db.prisma',\n attributes: {\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.db.prisma',\n },\n data: { ...clientData, 'db.operation': action },\n },\n () => next(params),\n );\n });\n } else {\n DEBUG_BUILD &&\n logger.warn('Unsupported Prisma client provided to PrismaIntegration. Provided client:', options.client);\n }\n }\n\n /**\n * @inheritDoc\n */\n public setupOnce(): void {\n // Noop - here for backwards compatibility\n }\n}\n","import type { Hub } from '@sentry/core';\nimport type { EventProcessor } from '@sentry/types';\nimport { fill, isThenable, loadModule, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../../common/debug-build';\nimport type { LazyLoadedIntegration } from './lazy';\nimport { shouldDisableAutoInstrumentation } from './utils/node-utils';\n\ntype GraphQLModule = {\n [method: string]: (...args: unknown[]) => unknown;\n};\n\n/** Tracing integration for graphql package */\nexport class GraphQL implements LazyLoadedIntegration<GraphQLModule> {\n /**\n * @inheritDoc\n */\n public static id: string = 'GraphQL';\n\n /**\n * @inheritDoc\n */\n public name: string;\n\n private _module?: GraphQLModule;\n\n public constructor() {\n this.name = GraphQL.id;\n }\n\n /** @inheritdoc */\n public loadDependency(): GraphQLModule | undefined {\n return (this._module = this._module || loadModule('graphql/execution/execute.js'));\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line deprecation/deprecation\n public setupOnce(_: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {\n if (shouldDisableAutoInstrumentation(getCurrentHub)) {\n DEBUG_BUILD && logger.log('GraphQL Integration is skipped because of instrumenter configuration.');\n return;\n }\n\n const pkg = this.loadDependency();\n\n if (!pkg) {\n DEBUG_BUILD && logger.error('GraphQL Integration was unable to require graphql/execution package.');\n return;\n }\n\n fill(pkg, 'execute', function (orig: () => void | Promise<unknown>) {\n return function (this: unknown, ...args: unknown[]) {\n // eslint-disable-next-line deprecation/deprecation\n const scope = getCurrentHub().getScope();\n // eslint-disable-next-line deprecation/deprecation\n const parentSpan = scope.getSpan();\n\n // eslint-disable-next-line deprecation/deprecation\n const span = parentSpan?.startChild({\n description: 'execute',\n op: 'graphql.execute',\n origin: 'auto.graphql.graphql',\n });\n\n // eslint-disable-next-line deprecation/deprecation\n scope?.setSpan(span);\n\n const rv = orig.call(this, ...args);\n\n if (isThenable(rv)) {\n return rv.then((res: unknown) => {\n span?.end();\n // eslint-disable-next-line deprecation/deprecation\n scope?.setSpan(parentSpan);\n\n return res;\n });\n }\n\n span?.end();\n // eslint-disable-next-line deprecation/deprecation\n scope?.setSpan(parentSpan);\n return rv;\n };\n });\n }\n}\n","import type { Hub } from '@sentry/core';\nimport type { EventProcessor } from '@sentry/types';\nimport { arrayify, fill, isThenable, loadModule, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../../common/debug-build';\nimport type { LazyLoadedIntegration } from './lazy';\nimport { shouldDisableAutoInstrumentation } from './utils/node-utils';\n\ninterface ApolloOptions {\n useNestjs?: boolean;\n}\n\ntype ApolloResolverGroup = {\n [key: string]: () => unknown;\n};\n\ntype ApolloModelResolvers = {\n [key: string]: ApolloResolverGroup;\n};\n\ntype GraphQLModule = {\n GraphQLFactory: {\n prototype: {\n create: (resolvers: ApolloModelResolvers[]) => unknown;\n };\n };\n};\n\ntype ApolloModule = {\n ApolloServerBase: {\n prototype: {\n constructSchema: (config: unknown) => unknown;\n };\n };\n};\n\n/** Tracing integration for Apollo */\nexport class Apollo implements LazyLoadedIntegration<GraphQLModule & ApolloModule> {\n /**\n * @inheritDoc\n */\n public static id: string = 'Apollo';\n\n /**\n * @inheritDoc\n */\n public name: string;\n\n private readonly _useNest: boolean;\n\n private _module?: GraphQLModule & ApolloModule;\n\n /**\n * @inheritDoc\n */\n public constructor(\n options: ApolloOptions = {\n useNestjs: false,\n },\n ) {\n this.name = Apollo.id;\n this._useNest = !!options.useNestjs;\n }\n\n /** @inheritdoc */\n public loadDependency(): (GraphQLModule & ApolloModule) | undefined {\n if (this._useNest) {\n this._module = this._module || loadModule('@nestjs/graphql');\n } else {\n this._module = this._module || loadModule('apollo-server-core');\n }\n\n return this._module;\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line deprecation/deprecation\n public setupOnce(_: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {\n if (shouldDisableAutoInstrumentation(getCurrentHub)) {\n DEBUG_BUILD && logger.log('Apollo Integration is skipped because of instrumenter configuration.');\n return;\n }\n\n if (this._useNest) {\n const pkg = this.loadDependency();\n\n if (!pkg) {\n DEBUG_BUILD && logger.error('Apollo-NestJS Integration was unable to require @nestjs/graphql package.');\n return;\n }\n\n /**\n * Iterate over resolvers of NestJS ResolversExplorerService before schemas are constructed.\n */\n fill(\n pkg.GraphQLFactory.prototype,\n 'mergeWithSchema',\n function (orig: (this: unknown, ...args: unknown[]) => unknown) {\n return function (\n this: { resolversExplorerService: { explore: () => ApolloModelResolvers[] } },\n ...args: unknown[]\n ) {\n fill(this.resolversExplorerService, 'explore', function (orig: () => ApolloModelResolvers[]) {\n return function (this: unknown) {\n const resolvers = arrayify(orig.call(this));\n\n const instrumentedResolvers = instrumentResolvers(resolvers, getCurrentHub);\n\n return instrumentedResolvers;\n };\n });\n\n return orig.call(this, ...args);\n };\n },\n );\n } else {\n const pkg = this.loadDependency();\n\n if (!pkg) {\n DEBUG_BUILD && logger.error('Apollo Integration was unable to require apollo-server-core package.');\n return;\n }\n\n /**\n * Iterate over resolvers of the ApolloServer instance before schemas are constructed.\n */\n fill(pkg.ApolloServerBase.prototype, 'constructSchema', function (orig: (config: unknown) => unknown) {\n return function (this: {\n config: { resolvers?: ApolloModelResolvers[]; schema?: unknown; modules?: unknown };\n }) {\n if (!this.config.resolvers) {\n if (DEBUG_BUILD) {\n if (this.config.schema) {\n logger.warn(\n 'Apollo integration is not able to trace `ApolloServer` instances constructed via `schema` property.' +\n 'If you are using NestJS with Apollo, please use `Sentry.Integrations.Apollo({ useNestjs: true })` instead.',\n );\n logger.warn();\n } else if (this.config.modules) {\n logger.warn(\n 'Apollo integration is not able to trace `ApolloServer` instances constructed via `modules` property.',\n );\n }\n\n logger.error('Skipping tracing as no resolvers found on the `ApolloServer` instance.');\n }\n\n return orig.call(this);\n }\n\n const resolvers = arrayify(this.config.resolvers);\n\n this.config.resolvers = instrumentResolvers(resolvers, getCurrentHub);\n\n return orig.call(this);\n };\n });\n }\n }\n}\n\n// eslint-disable-next-line deprecation/deprecation\nfunction instrumentResolvers(resolvers: ApolloModelResolvers[], getCurrentHub: () => Hub): ApolloModelResolvers[] {\n return resolvers.map(model => {\n Object.keys(model).forEach(resolverGroupName => {\n Object.keys(model[resolverGroupName]).forEach(resolverName => {\n if (typeof model[resolverGroupName][resolverName] !== 'function') {\n return;\n }\n\n wrapResolver(model, resolverGroupName, resolverName, getCurrentHub);\n });\n });\n\n return model;\n });\n}\n\n/**\n * Wrap a single resolver which can be a parent of other resolvers and/or db operations.\n */\nfunction wrapResolver(\n model: ApolloModelResolvers,\n resolverGroupName: string,\n resolverName: string,\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub: () => Hub,\n): void {\n fill(model[resolverGroupName], resolverName, function (orig: () => unknown | Promise<unknown>) {\n return function (this: unknown, ...args: unknown[]) {\n // eslint-disable-next-line deprecation/deprecation\n const scope = getCurrentHub().getScope();\n // eslint-disable-next-line deprecation/deprecation\n const parentSpan = scope.getSpan();\n // eslint-disable-next-line deprecation/deprecation\n const span = parentSpan?.startChild({\n description: `${resolverGroupName}.${resolverName}`,\n op: 'graphql.resolve',\n origin: 'auto.graphql.apollo',\n });\n\n const rv = orig.call(this, ...args);\n\n if (isThenable(rv)) {\n return rv.then((res: unknown) => {\n span?.end();\n return res;\n });\n }\n\n span?.end();\n\n return rv;\n };\n });\n}\n","import {\n captureException,\n captureMessage,\n convertIntegrationFnToClass,\n defineIntegration,\n getClient,\n withScope,\n} from '@sentry/core';\nimport type { CaptureContext, Client, Integration, IntegrationClass, IntegrationFn } from '@sentry/types';\nimport {\n CONSOLE_LEVELS,\n GLOBAL_OBJ,\n addConsoleInstrumentationHandler,\n addExceptionMechanism,\n safeJoin,\n severityLevelFromString,\n} from '@sentry/utils';\n\ninterface CaptureConsoleOptions {\n levels?: string[];\n}\n\nconst INTEGRATION_NAME = 'CaptureConsole';\n\nconst _captureConsoleIntegration = ((options: CaptureConsoleOptions = {}) => {\n const levels = options.levels || CONSOLE_LEVELS;\n\n return {\n name: INTEGRATION_NAME,\n // TODO v8: Remove this\n setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function\n setup(client) {\n if (!('console' in GLOBAL_OBJ)) {\n return;\n }\n\n addConsoleInstrumentationHandler(({ args, level }) => {\n if (getClient() !== client || !levels.includes(level)) {\n return;\n }\n\n consoleHandler(args, level);\n });\n },\n };\n}) satisfies IntegrationFn;\n\nexport const captureConsoleIntegration = defineIntegration(_captureConsoleIntegration);\n\n/**\n * Send Console API calls as Sentry Events.\n * @deprecated Use `captureConsoleIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const CaptureConsole = convertIntegrationFnToClass(\n INTEGRATION_NAME,\n captureConsoleIntegration,\n) as IntegrationClass<Integration & { setup: (client: Client) => void }> & {\n new (options?: { levels?: string[] }): Integration;\n};\n\nfunction consoleHandler(args: unknown[], level: string): void {\n const captureContext: CaptureContext = {\n level: severityLevelFromString(level),\n extra: {\n arguments: args,\n },\n };\n\n withScope(scope => {\n scope.addEventProcessor(event => {\n event.logger = 'console';\n\n addExceptionMechanism(event, {\n handled: false,\n type: 'console',\n });\n\n return event;\n });\n\n if (level === 'assert' && args[0] === false) {\n const message = `Assertion failed: ${safeJoin(args.slice(1), ' ') || 'console.assert'}`;\n scope.setExtra('arguments', args.slice(1));\n captureMessage(message, captureContext);\n return;\n }\n\n const error = args.find(arg => arg instanceof Error);\n if (level === 'error' && error) {\n captureException(error, captureContext);\n return;\n }\n\n const message = safeJoin(args, ' ');\n captureMessage(message, captureContext);\n });\n}\n","import { convertIntegrationFnToClass, defineIntegration } from '@sentry/core';\nimport type { Client, Event, EventHint, Integration, IntegrationClass, IntegrationFn } from '@sentry/types';\nimport { consoleSandbox } from '@sentry/utils';\n\nconst INTEGRATION_NAME = 'Debug';\n\ninterface DebugOptions {\n /** Controls whether console output created by this integration should be stringified. Default: `false` */\n stringify?: boolean;\n /** Controls whether a debugger should be launched before an event is sent. Default: `false` */\n debugger?: boolean;\n}\n\nconst _debugIntegration = ((options: DebugOptions = {}) => {\n const _options = {\n debugger: false,\n stringify: false,\n ...options,\n };\n\n return {\n name: INTEGRATION_NAME,\n // TODO v8: Remove this\n setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function\n setup(client) {\n if (!client.on) {\n return;\n }\n\n client.on('beforeSendEvent', (event: Event, hint?: EventHint) => {\n if (_options.debugger) {\n // eslint-disable-next-line no-debugger\n debugger;\n }\n\n /* eslint-disable no-console */\n consoleSandbox(() => {\n if (_options.stringify) {\n console.log(JSON.stringify(event, null, 2));\n if (hint && Object.keys(hint).length) {\n console.log(JSON.stringify(hint, null, 2));\n }\n } else {\n console.log(event);\n if (hint && Object.keys(hint).length) {\n console.log(hint);\n }\n }\n });\n /* eslint-enable no-console */\n });\n },\n };\n}) satisfies IntegrationFn;\n\nexport const debugIntegration = defineIntegration(_debugIntegration);\n\n/**\n * Integration to debug sent Sentry events.\n * This integration should not be used in production.\n *\n * @deprecated Use `debugIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const Debug = convertIntegrationFnToClass(INTEGRATION_NAME, debugIntegration) as IntegrationClass<\n Integration & { setup: (client: Client) => void }\n> & {\n new (options?: {\n stringify?: boolean;\n debugger?: boolean;\n }): Integration;\n};\n","declare const __DEBUG_BUILD__: boolean;\n\n/**\n * This serves as a build time flag that will be true by default, but false in non-debug builds or if users replace `__SENTRY_DEBUG__` in their generated code.\n *\n * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking.\n */\nexport const DEBUG_BUILD = __DEBUG_BUILD__;\n","import { convertIntegrationFnToClass, defineIntegration } from '@sentry/core';\nimport type { Event, Exception, Integration, IntegrationClass, IntegrationFn, StackFrame } from '@sentry/types';\nimport { logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from './debug-build';\n\nconst INTEGRATION_NAME = 'Dedupe';\n\nconst _dedupeIntegration = (() => {\n let previousEvent: Event | undefined;\n\n return {\n name: INTEGRATION_NAME,\n // TODO v8: Remove this\n setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function\n processEvent(currentEvent) {\n // We want to ignore any non-error type events, e.g. transactions or replays\n // These should never be deduped, and also not be compared against as _previousEvent.\n if (currentEvent.type) {\n return currentEvent;\n }\n\n // Juuust in case something goes wrong\n try {\n if (_shouldDropEvent(currentEvent, previousEvent)) {\n DEBUG_BUILD && logger.warn('Event dropped due to being a duplicate of previously captured event.');\n return null;\n }\n } catch (_oO) {} // eslint-disable-line no-empty\n\n return (previousEvent = currentEvent);\n },\n };\n}) satisfies IntegrationFn;\n\nexport const dedupeIntegration = defineIntegration(_dedupeIntegration);\n\n/**\n * Deduplication filter.\n * @deprecated Use `dedupeIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const Dedupe = convertIntegrationFnToClass(INTEGRATION_NAME, dedupeIntegration) as IntegrationClass<\n Integration & { processEvent: (event: Event) => Event }\n>;\n\n/** only exported for tests. */\nexport function _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\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\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\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\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\nfunction _getExceptionFromEvent(event: Event): Exception | undefined {\n return event.exception && event.exception.values && event.exception.values[0];\n}\n\nfunction _getFramesFromEvent(event: Event): StackFrame[] | undefined {\n const exception = event.exception;\n\n if (exception) {\n try {\n // @ts-expect-error Object could be undefined\n return exception.values[0].stacktrace.frames;\n } catch (_oO) {\n return undefined;\n }\n }\n return undefined;\n}\n","import { convertIntegrationFnToClass, defineIntegration } from '@sentry/core';\nimport type {\n Contexts,\n Event,\n EventHint,\n ExtendedError,\n Integration,\n IntegrationClass,\n IntegrationFn,\n} from '@sentry/types';\nimport { addNonEnumerableProperty, isError, isPlainObject, logger, normalize } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from './debug-build';\n\nconst INTEGRATION_NAME = 'ExtraErrorData';\n\ninterface ExtraErrorDataOptions {\n /**\n * The object depth up to which to capture data on error objects.\n */\n depth: number;\n\n /**\n * Whether to capture error causes.\n *\n * More information: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/cause\n */\n captureErrorCause: boolean;\n}\n\nconst _extraErrorDataIntegration = ((options: Partial<ExtraErrorDataOptions> = {}) => {\n const depth = options.depth || 3;\n\n // TODO(v8): Flip the default for this option to true\n const captureErrorCause = options.captureErrorCause || false;\n\n return {\n name: INTEGRATION_NAME,\n // TODO v8: Remove this\n setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function\n processEvent(event, hint) {\n return _enhanceEventWithErrorData(event, hint, depth, captureErrorCause);\n },\n };\n}) satisfies IntegrationFn;\n\nexport const extraErrorDataIntegration = defineIntegration(_extraErrorDataIntegration);\n\n/**\n * Extract additional data for from original exceptions.\n * @deprecated Use `extraErrorDataIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const ExtraErrorData = convertIntegrationFnToClass(\n INTEGRATION_NAME,\n extraErrorDataIntegration,\n) as IntegrationClass<Integration & { processEvent: (event: Event, hint: EventHint) => Event }> & {\n new (\n options?: Partial<{\n depth: number;\n captureErrorCause: boolean;\n }>,\n ): Integration;\n};\n\nfunction _enhanceEventWithErrorData(\n event: Event,\n hint: EventHint = {},\n depth: number,\n captureErrorCause: boolean,\n): Event {\n if (!hint.originalException || !isError(hint.originalException)) {\n return event;\n }\n const exceptionName = (hint.originalException as ExtendedError).name || hint.originalException.constructor.name;\n\n const errorData = _extractErrorData(hint.originalException as ExtendedError, captureErrorCause);\n\n if (errorData) {\n const contexts: Contexts = {\n ...event.contexts,\n };\n\n const normalizedErrorData = normalize(errorData, depth);\n\n if (isPlainObject(normalizedErrorData)) {\n // We mark the error data as \"already normalized\" here, because we don't want other normalization procedures to\n // potentially truncate the data we just already normalized, with a certain depth setting.\n addNonEnumerableProperty(normalizedErrorData, '__sentry_skip_normalization__', true);\n contexts[exceptionName] = normalizedErrorData;\n }\n\n return {\n ...event,\n contexts,\n };\n }\n\n return event;\n}\n\n/**\n * Extract extra information from the Error object\n */\nfunction _extractErrorData(error: ExtendedError, captureErrorCause: boolean): Record<string, unknown> | null {\n // We are trying to enhance already existing event, so no harm done if it won't succeed\n try {\n const nativeKeys = [\n 'name',\n 'message',\n 'stack',\n 'line',\n 'column',\n 'fileName',\n 'lineNumber',\n 'columnNumber',\n 'toJSON',\n ];\n\n const extraErrorInfo: Record<string, unknown> = {};\n\n // We want only enumerable properties, thus `getOwnPropertyNames` is redundant here, as we filter keys anyway.\n for (const key of Object.keys(error)) {\n if (nativeKeys.indexOf(key) !== -1) {\n continue;\n }\n const value = error[key];\n extraErrorInfo[key] = isError(value) ? value.toString() : value;\n }\n\n // Error.cause is a standard property that is non enumerable, we therefore need to access it separately.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/cause\n if (captureErrorCause && error.cause !== undefined) {\n extraErrorInfo.cause = isError(error.cause) ? error.cause.toString() : error.cause;\n }\n\n // Check if someone attached `toJSON` method to grab even more properties (eg. axios is doing that)\n if (typeof error.toJSON === 'function') {\n const serializedError = error.toJSON() as Record<string, unknown>;\n\n for (const key of Object.keys(serializedError)) {\n const value = serializedError[key];\n extraErrorInfo[key] = isError(value) ? value.toString() : value;\n }\n }\n\n return extraErrorInfo;\n } catch (oO) {\n DEBUG_BUILD && logger.error('Unable to extract extra data from the Error object:', oO);\n }\n\n return null;\n}\n","import { captureMessage, convertIntegrationFnToClass, defineIntegration, getClient, withScope } from '@sentry/core';\nimport type { Client, Integration, IntegrationClass, IntegrationFn } from '@sentry/types';\nimport { GLOBAL_OBJ, supportsReportingObserver } from '@sentry/utils';\n\nconst WINDOW = GLOBAL_OBJ as typeof GLOBAL_OBJ & Window;\n\nconst INTEGRATION_NAME = 'ReportingObserver';\n\ninterface Report {\n [key: string]: unknown;\n type: ReportTypes;\n url: string;\n body?: ReportBody;\n}\n\ntype ReportTypes = 'crash' | 'deprecation' | 'intervention';\n\ntype ReportBody = CrashReportBody | DeprecationReportBody | InterventionReportBody;\n\ninterface CrashReportBody {\n [key: string]: unknown;\n crashId: string;\n reason?: string;\n}\n\ninterface DeprecationReportBody {\n [key: string]: unknown;\n id: string;\n anticipatedRemoval?: Date;\n message: string;\n sourceFile?: string;\n lineNumber?: number;\n columnNumber?: number;\n}\n\ninterface InterventionReportBody {\n [key: string]: unknown;\n id: string;\n message: string;\n sourceFile?: string;\n lineNumber?: number;\n columnNumber?: number;\n}\n\ninterface ReportingObserverOptions {\n types?: ReportTypes[];\n}\n\nconst SETUP_CLIENTS = new WeakMap<Client, boolean>();\n\nconst _reportingObserverIntegration = ((options: ReportingObserverOptions = {}) => {\n const types = options.types || ['crash', 'deprecation', 'intervention'];\n\n /** Handler for the reporting observer. */\n function handler(reports: Report[]): void {\n if (!SETUP_CLIENTS.has(getClient() as Client)) {\n return;\n }\n\n for (const report of reports) {\n withScope(scope => {\n scope.setExtra('url', report.url);\n\n const label = `ReportingObserver [${report.type}]`;\n let details = 'No details available';\n\n if (report.body) {\n // Object.keys doesn't work on ReportBody, as all properties are inheirted\n const plainBody: {\n [key: string]: unknown;\n } = {};\n\n // eslint-disable-next-line guard-for-in\n for (const prop in report.body) {\n plainBody[prop] = report.body[prop];\n }\n\n scope.setExtra('body', plainBody);\n\n if (report.type === 'crash') {\n const body = report.body as CrashReportBody;\n // A fancy way to create a message out of crashId OR reason OR both OR fallback\n details = [body.crashId || '', body.reason || ''].join(' ').trim() || details;\n } else {\n const body = report.body as DeprecationReportBody | InterventionReportBody;\n details = body.message || details;\n }\n }\n\n captureMessage(`${label}: ${details}`);\n });\n }\n }\n\n return {\n name: INTEGRATION_NAME,\n setupOnce() {\n if (!supportsReportingObserver()) {\n return;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any\n const observer = new (WINDOW as any).ReportingObserver(handler, {\n buffered: true,\n types,\n });\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n observer.observe();\n },\n\n setup(client): void {\n SETUP_CLIENTS.set(client, true);\n },\n };\n}) satisfies IntegrationFn;\n\nexport const reportingObserverIntegration = defineIntegration(_reportingObserverIntegration);\n\n/**\n * Reporting API integration - https://w3c.github.io/reporting/\n * @deprecated Use `reportingObserverIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const ReportingObserver = convertIntegrationFnToClass(\n INTEGRATION_NAME,\n reportingObserverIntegration,\n) as IntegrationClass<Integration & { setup: (client: Client) => void }> & {\n new (options?: {\n types?: ReportTypes[];\n }): Integration;\n};\n","import { convertIntegrationFnToClass, defineIntegration } from '@sentry/core';\nimport type { Event, Integration, IntegrationClass, IntegrationFn, StackFrame, Stacktrace } from '@sentry/types';\nimport { basename, relative } from '@sentry/utils';\n\ntype StackFrameIteratee = (frame: StackFrame) => StackFrame;\n\nconst INTEGRATION_NAME = 'RewriteFrames';\n\ninterface RewriteFramesOptions {\n root?: string;\n prefix?: string;\n iteratee?: StackFrameIteratee;\n}\n\nconst _rewriteFramesIntegration = ((options: RewriteFramesOptions = {}) => {\n const root = options.root;\n const prefix = options.prefix || 'app:///';\n\n const iteratee: StackFrameIteratee =\n options.iteratee ||\n ((frame: StackFrame) => {\n if (!frame.filename) {\n return frame;\n }\n // Determine if this is a Windows frame by checking for a Windows-style prefix such as `C:\\`\n const isWindowsFrame =\n /^[a-zA-Z]:\\\\/.test(frame.filename) ||\n // or the presence of a backslash without a forward slash (which are not allowed on Windows)\n (frame.filename.includes('\\\\') && !frame.filename.includes('/'));\n // Check if the frame filename begins with `/`\n const startsWithSlash = /^\\//.test(frame.filename);\n if (isWindowsFrame || startsWithSlash) {\n const filename = isWindowsFrame\n ? frame.filename\n .replace(/^[a-zA-Z]:/, '') // remove Windows-style prefix\n .replace(/\\\\/g, '/') // replace all `\\\\` instances with `/`\n : frame.filename;\n const base = root ? relative(root, filename) : basename(filename);\n frame.filename = `${prefix}${base}`;\n }\n return frame;\n });\n\n /** Process an exception event. */\n function _processExceptionsEvent(event: Event): Event {\n try {\n return {\n ...event,\n exception: {\n ...event.exception,\n // The check for this is performed inside `process` call itself, safe to skip here\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n values: event.exception!.values!.map(value => ({\n ...value,\n ...(value.stacktrace && { stacktrace: _processStacktrace(value.stacktrace) }),\n })),\n },\n };\n } catch (_oO) {\n return event;\n }\n }\n\n /** Process a stack trace. */\n function _processStacktrace(stacktrace?: Stacktrace): Stacktrace {\n return {\n ...stacktrace,\n frames: stacktrace && stacktrace.frames && stacktrace.frames.map(f => iteratee(f)),\n };\n }\n\n return {\n name: INTEGRATION_NAME,\n // TODO v8: Remove this\n setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function\n processEvent(originalEvent) {\n let processedEvent = originalEvent;\n\n if (originalEvent.exception && Array.isArray(originalEvent.exception.values)) {\n processedEvent = _processExceptionsEvent(processedEvent);\n }\n\n return processedEvent;\n },\n };\n}) satisfies IntegrationFn;\n\nexport const rewriteFramesIntegration = defineIntegration(_rewriteFramesIntegration);\n\n/**\n * Rewrite event frames paths.\n * @deprecated Use `rewriteFramesIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const RewriteFrames = convertIntegrationFnToClass(\n INTEGRATION_NAME,\n rewriteFramesIntegration,\n) as IntegrationClass<Integration & { processEvent: (event: Event) => Event }> & {\n new (options?: { root?: string; prefix?: string; iteratee?: StackFrameIteratee }): Integration;\n};\n","import { convertIntegrationFnToClass, defineIntegration } from '@sentry/core';\nimport type { Event, Integration, IntegrationClass, IntegrationFn } from '@sentry/types';\n\nconst INTEGRATION_NAME = 'SessionTiming';\n\nconst _sessionTimingIntegration = (() => {\n const startTime = Date.now();\n\n return {\n name: INTEGRATION_NAME,\n // TODO v8: Remove this\n setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function\n processEvent(event) {\n const now = Date.now();\n\n return {\n ...event,\n extra: {\n ...event.extra,\n ['session:start']: startTime,\n ['session:duration']: now - startTime,\n ['session:end']: now,\n },\n };\n },\n };\n}) satisfies IntegrationFn;\n\nexport const sessionTimingIntegration = defineIntegration(_sessionTimingIntegration);\n\n/**\n * This function adds duration since Sentry was initialized till the time event was sent.\n * @deprecated Use `sessionTimingIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const SessionTiming = convertIntegrationFnToClass(\n INTEGRATION_NAME,\n sessionTimingIntegration,\n) as IntegrationClass<Integration & { processEvent: (event: Event) => Event }>;\n","import {\n captureEvent,\n convertIntegrationFnToClass,\n defineIntegration,\n getClient,\n isSentryRequestUrl,\n} from '@sentry/core';\nimport type {\n Client,\n Event as SentryEvent,\n Integration,\n IntegrationClass,\n IntegrationFn,\n SentryWrappedXMLHttpRequest,\n} from '@sentry/types';\nimport {\n GLOBAL_OBJ,\n SENTRY_XHR_DATA_KEY,\n addExceptionMechanism,\n addFetchInstrumentationHandler,\n addXhrInstrumentationHandler,\n logger,\n supportsNativeFetch,\n} from '@sentry/utils';\n\nimport { DEBUG_BUILD } from './debug-build';\n\nexport type HttpStatusCodeRange = [number, number] | number;\nexport type HttpRequestTarget = string | RegExp;\n\nconst INTEGRATION_NAME = 'HttpClient';\n\ninterface HttpClientOptions {\n /**\n * HTTP status codes that should be considered failed.\n * This array can contain tuples of `[begin, end]` (both inclusive),\n * single status codes, or a combinations of both\n *\n * Example: [[500, 505], 507]\n * Default: [[500, 599]]\n */\n failedRequestStatusCodes: HttpStatusCodeRange[];\n\n /**\n * Targets to track for failed requests.\n * This array can contain strings or regular expressions.\n *\n * Example: ['http://localhost', /api\\/.*\\/]\n * Default: [/.*\\/]\n */\n failedRequestTargets: HttpRequestTarget[];\n}\n\nconst _httpClientIntegration = ((options: Partial<HttpClientOptions> = {}) => {\n const _options: HttpClientOptions = {\n failedRequestStatusCodes: [[500, 599]],\n failedRequestTargets: [/.*/],\n ...options,\n };\n\n return {\n name: INTEGRATION_NAME,\n // TODO v8: Remove this\n setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function\n setup(client): void {\n _wrapFetch(client, _options);\n _wrapXHR(client, _options);\n },\n };\n}) satisfies IntegrationFn;\n\nexport const httpClientIntegration = defineIntegration(_httpClientIntegration);\n\n/**\n * Create events for failed client side HTTP requests.\n * @deprecated Use `httpClientIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const HttpClient = convertIntegrationFnToClass(INTEGRATION_NAME, httpClientIntegration) as IntegrationClass<\n Integration & { setup: (client: Client) => void }\n> & {\n new (options?: {\n failedRequestStatusCodes: HttpStatusCodeRange[];\n failedRequestTargets: HttpRequestTarget[];\n }): Integration;\n};\n\n/**\n * Interceptor function for fetch requests\n *\n * @param requestInfo The Fetch API request info\n * @param response The Fetch API response\n * @param requestInit The request init object\n */\nfunction _fetchResponseHandler(\n options: HttpClientOptions,\n requestInfo: RequestInfo,\n response: Response,\n requestInit?: RequestInit,\n): void {\n if (_shouldCaptureResponse(options, response.status, response.url)) {\n const request = _getRequest(requestInfo, requestInit);\n\n let requestHeaders, responseHeaders, requestCookies, responseCookies;\n\n if (_shouldSendDefaultPii()) {\n [{ headers: requestHeaders, cookies: requestCookies }, { headers: responseHeaders, cookies: responseCookies }] = [\n { cookieHeader: 'Cookie', obj: request },\n { cookieHeader: 'Set-Cookie', obj: response },\n ].map(({ cookieHeader, obj }) => {\n const headers = _extractFetchHeaders(obj.headers);\n let cookies;\n\n try {\n const cookieString = headers[cookieHeader] || headers[cookieHeader.toLowerCase()] || undefined;\n\n if (cookieString) {\n cookies = _parseCookieString(cookieString);\n }\n } catch (e) {\n DEBUG_BUILD && logger.log(`Could not extract cookies from header ${cookieHeader}`);\n }\n\n return {\n headers,\n cookies,\n };\n });\n }\n\n const event = _createEvent({\n url: request.url,\n method: request.method,\n status: response.status,\n requestHeaders,\n responseHeaders,\n requestCookies,\n responseCookies,\n });\n\n captureEvent(event);\n }\n}\n\n/**\n * Interceptor function for XHR requests\n *\n * @param xhr The XHR request\n * @param method The HTTP method\n * @param headers The HTTP headers\n */\nfunction _xhrResponseHandler(\n options: HttpClientOptions,\n xhr: XMLHttpRequest,\n method: string,\n headers: Record<string, string>,\n): void {\n if (_shouldCaptureResponse(options, xhr.status, xhr.responseURL)) {\n let requestHeaders, responseCookies, responseHeaders;\n\n if (_shouldSendDefaultPii()) {\n try {\n const cookieString = xhr.getResponseHeader('Set-Cookie') || xhr.getResponseHeader('set-cookie') || undefined;\n\n if (cookieString) {\n responseCookies = _parseCookieString(cookieString);\n }\n } catch (e) {\n DEBUG_BUILD && logger.log('Could not extract cookies from response headers');\n }\n\n try {\n responseHeaders = _getXHRResponseHeaders(xhr);\n } catch (e) {\n DEBUG_BUILD && logger.log('Could not extract headers from response');\n }\n\n requestHeaders = headers;\n }\n\n const event = _createEvent({\n url: xhr.responseURL,\n method,\n status: xhr.status,\n requestHeaders,\n // Can't access request cookies from XHR\n responseHeaders,\n responseCookies,\n });\n\n captureEvent(event);\n }\n}\n\n/**\n * Extracts response size from `Content-Length` header when possible\n *\n * @param headers\n * @returns The response size in bytes or undefined\n */\nfunction _getResponseSizeFromHeaders(headers?: Record<string, string>): number | undefined {\n if (headers) {\n const contentLength = headers['Content-Length'] || headers['content-length'];\n\n if (contentLength) {\n return parseInt(contentLength, 10);\n }\n }\n\n return undefined;\n}\n\n/**\n * Creates an object containing cookies from the given cookie string\n *\n * @param cookieString The cookie string to parse\n * @returns The parsed cookies\n */\nfunction _parseCookieString(cookieString: string): Record<string, string> {\n return cookieString.split('; ').reduce((acc: Record<string, string>, cookie: string) => {\n const [key, value] = cookie.split('=');\n acc[key] = value;\n return acc;\n }, {});\n}\n\n/**\n * Extracts the headers as an object from the given Fetch API request or response object\n *\n * @param headers The headers to extract\n * @returns The extracted headers as an object\n */\nfunction _extractFetchHeaders(headers: Headers): Record<string, string> {\n const result: Record<string, string> = {};\n\n headers.forEach((value, key) => {\n result[key] = value;\n });\n\n return result;\n}\n\n/**\n * Extracts the response headers as an object from the given XHR object\n *\n * @param xhr The XHR object to extract the response headers from\n * @returns The response headers as an object\n */\nfunction _getXHRResponseHeaders(xhr: XMLHttpRequest): Record<string, string> {\n const headers = xhr.getAllResponseHeaders();\n\n if (!headers) {\n return {};\n }\n\n return headers.split('\\r\\n').reduce((acc: Record<string, string>, line: string) => {\n const [key, value] = line.split(': ');\n acc[key] = value;\n return acc;\n }, {});\n}\n\n/**\n * Checks if the given target url is in the given list of targets\n *\n * @param target The target url to check\n * @returns true if the target url is in the given list of targets, false otherwise\n */\nfunction _isInGivenRequestTargets(\n failedRequestTargets: HttpClientOptions['failedRequestTargets'],\n target: string,\n): boolean {\n return failedRequestTargets.some((givenRequestTarget: HttpRequestTarget) => {\n if (typeof givenRequestTarget === 'string') {\n return target.includes(givenRequestTarget);\n }\n\n return givenRequestTarget.test(target);\n });\n}\n\n/**\n * Checks if the given status code is in the given range\n *\n * @param status The status code to check\n * @returns true if the status code is in the given range, false otherwise\n */\nfunction _isInGivenStatusRanges(\n failedRequestStatusCodes: HttpClientOptions['failedRequestStatusCodes'],\n status: number,\n): boolean {\n return failedRequestStatusCodes.some((range: HttpStatusCodeRange) => {\n if (typeof range === 'number') {\n return range === status;\n }\n\n return status >= range[0] && status <= range[1];\n });\n}\n\n/**\n * Wraps `fetch` function to capture request and response data\n */\nfunction _wrapFetch(client: Client, options: HttpClientOptions): void {\n if (!supportsNativeFetch()) {\n return;\n }\n\n addFetchInstrumentationHandler(handlerData => {\n if (getClient() !== client) {\n return;\n }\n\n const { response, args } = handlerData;\n const [requestInfo, requestInit] = args as [RequestInfo, RequestInit | undefined];\n\n if (!response) {\n return;\n }\n\n _fetchResponseHandler(options, requestInfo, response as Response, requestInit);\n });\n}\n\n/**\n * Wraps XMLHttpRequest to capture request and response data\n */\nfunction _wrapXHR(client: Client, options: HttpClientOptions): void {\n if (!('XMLHttpRequest' in GLOBAL_OBJ)) {\n return;\n }\n\n addXhrInstrumentationHandler(handlerData => {\n if (getClient() !== client) {\n return;\n }\n\n const xhr = handlerData.xhr as SentryWrappedXMLHttpRequest & XMLHttpRequest;\n\n const sentryXhrData = xhr[SENTRY_XHR_DATA_KEY];\n\n if (!sentryXhrData) {\n return;\n }\n\n const { method, request_headers: headers } = sentryXhrData;\n\n try {\n _xhrResponseHandler(options, xhr, method, headers);\n } catch (e) {\n DEBUG_BUILD && logger.warn('Error while extracting response event form XHR response', e);\n }\n });\n}\n\n/**\n * Checks whether to capture given response as an event\n *\n * @param status response status code\n * @param url response url\n */\nfunction _shouldCaptureResponse(options: HttpClientOptions, status: number, url: string): boolean {\n return (\n _isInGivenStatusRanges(options.failedRequestStatusCodes, status) &&\n _isInGivenRequestTargets(options.failedRequestTargets, url) &&\n !isSentryRequestUrl(url, getClient())\n );\n}\n\n/**\n * Creates a synthetic Sentry event from given response data\n *\n * @param data response data\n * @returns event\n */\nfunction _createEvent(data: {\n url: string;\n method: string;\n status: number;\n responseHeaders?: Record<string, string>;\n responseCookies?: Record<string, string>;\n requestHeaders?: Record<string, string>;\n requestCookies?: Record<string, string>;\n}): SentryEvent {\n const message = `HTTP Client Error with status code: ${data.status}`;\n\n const event: SentryEvent = {\n message,\n exception: {\n values: [\n {\n type: 'Error',\n value: message,\n },\n ],\n },\n request: {\n url: data.url,\n method: data.method,\n headers: data.requestHeaders,\n cookies: data.requestCookies,\n },\n contexts: {\n response: {\n status_code: data.status,\n headers: data.responseHeaders,\n cookies: data.responseCookies,\n body_size: _getResponseSizeFromHeaders(data.responseHeaders),\n },\n },\n };\n\n addExceptionMechanism(event, {\n type: 'http.client',\n handled: false,\n });\n\n return event;\n}\n\nfunction _getRequest(requestInfo: RequestInfo, requestInit?: RequestInit): Request {\n if (!requestInit && requestInfo instanceof Request) {\n return requestInfo;\n }\n\n // If both are set, we try to construct a new Request with the given arguments\n // However, if e.g. the original request has a `body`, this will throw an error because it was already accessed\n // In this case, as a fallback, we just use the original request - using both is rather an edge case\n if (requestInfo instanceof Request && requestInfo.bodyUsed) {\n return requestInfo;\n }\n\n return new Request(requestInfo, requestInit);\n}\n\nfunction _shouldSendDefaultPii(): boolean {\n const client = getClient();\n return client ? Boolean(client.getOptions().sendDefaultPii) : false;\n}\n","import { convertIntegrationFnToClass, defineIntegration } from '@sentry/core';\nimport type { Event, Integration, IntegrationClass, IntegrationFn, StackFrame } from '@sentry/types';\nimport { GLOBAL_OBJ, addContextToFrame, stripUrlQueryAndFragment } from '@sentry/utils';\n\nconst WINDOW = GLOBAL_OBJ as typeof GLOBAL_OBJ & Window;\n\nconst DEFAULT_LINES_OF_CONTEXT = 7;\n\nconst INTEGRATION_NAME = 'ContextLines';\n\ninterface ContextLinesOptions {\n /**\n * Sets the number of context lines for each frame when loading a file.\n * Defaults to 7.\n *\n * Set to 0 to disable loading and inclusion of source files.\n **/\n frameContextLines?: number;\n}\n\nconst _contextLinesIntegration = ((options: ContextLinesOptions = {}) => {\n const contextLines = options.frameContextLines != null ? options.frameContextLines : DEFAULT_LINES_OF_CONTEXT;\n\n return {\n name: INTEGRATION_NAME,\n // TODO v8: Remove this\n setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function\n processEvent(event) {\n return addSourceContext(event, contextLines);\n },\n };\n}) satisfies IntegrationFn;\n\nexport const contextLinesIntegration = defineIntegration(_contextLinesIntegration);\n\n/**\n * Collects source context lines around the lines of stackframes pointing to JS embedded in\n * the current page's HTML.\n *\n * This integration DOES NOT work for stack frames pointing to JS files that are loaded by the browser.\n * For frames pointing to files, context lines are added during ingestion and symbolication\n * by attempting to download the JS files to the Sentry backend.\n *\n * Use this integration if you have inline JS code in HTML pages that can't be accessed\n * by our backend (e.g. due to a login-protected page).\n *\n * @deprecated Use `contextLinesIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const ContextLines = convertIntegrationFnToClass(INTEGRATION_NAME, contextLinesIntegration) as IntegrationClass<\n Integration & { processEvent: (event: Event) => Event }\n> & { new (options?: { frameContextLines?: number }): Integration };\n\n/**\n * Processes an event and adds context lines.\n */\nfunction addSourceContext(event: Event, contextLines: number): Event {\n const doc = WINDOW.document;\n const htmlFilename = WINDOW.location && stripUrlQueryAndFragment(WINDOW.location.href);\n if (!doc || !htmlFilename) {\n return event;\n }\n\n const exceptions = event.exception && event.exception.values;\n if (!exceptions || !exceptions.length) {\n return event;\n }\n\n const html = doc.documentElement.innerHTML;\n if (!html) {\n return event;\n }\n\n const htmlLines = ['<!DOCTYPE html>', '<html>', ...html.split('\\n'), '</html>'];\n\n exceptions.forEach(exception => {\n const stacktrace = exception.stacktrace;\n if (stacktrace && stacktrace.frames) {\n stacktrace.frames = stacktrace.frames.map(frame =>\n applySourceContextToFrame(frame, htmlLines, htmlFilename, contextLines),\n );\n }\n });\n\n return event;\n}\n\n/**\n * Only exported for testing\n */\nexport function applySourceContextToFrame(\n frame: StackFrame,\n htmlLines: string[],\n htmlFilename: string,\n linesOfContext: number,\n): StackFrame {\n if (frame.filename !== htmlFilename || !frame.lineno || !htmlLines.length) {\n return frame;\n }\n\n addContextToFrame(htmlLines, frame, linesOfContext);\n\n return frame;\n}\n","export { CaptureConsole, captureConsoleIntegration } from './captureconsole.js';\nexport { Debug, debugIntegration } from './debug.js';\nexport { Dedupe, dedupeIntegration } from './dedupe.js';\nexport { ExtraErrorData, extraErrorDataIntegration } from './extraerrordata.js';\nexport { Offline } from './offline.js';\nexport { ReportingObserver, reportingObserverIntegration } from './reportingobserver.js';\nexport { RewriteFrames, rewriteFramesIntegration } from './rewriteframes.js';\nexport { SessionTiming, sessionTimingIntegration } from './sessiontiming.js';\nexport { Transaction } from './transaction.js';\nexport { HttpClient, httpClientIntegration } from './httpclient.js';\nexport { ContextLines, contextLinesIntegration } from './contextlines.js';\n//# sourceMappingURL=index.js.map\n"],"mappings":";;oDAAAA,QCKAC,IACA,IAAMC,GAAiB,OAAO,UAAU,SASjC,SAASC,GAAQC,EAA4B,CAClD,OAAQF,GAAe,KAAKE,CAAG,EAAC,CAC9B,IAAK,iBACL,IAAK,qBACL,IAAK,wBACH,MAAO,GACT,QACE,OAAOC,GAAaD,EAAK,KAAK,CACpC,CACA,CAQA,SAASE,GAAUF,EAAcG,EAA4B,CAC3D,OAAOL,GAAe,KAAKE,CAAG,IAAM,WAAWG,CAAS,GAC1D,CASO,SAASC,GAAaJ,EAAuB,CAClD,OAAOE,GAAUF,EAAK,YAAY,CACpC,CASO,SAASK,GAAWL,EAAuB,CAChD,OAAOE,GAAUF,EAAK,UAAU,CAClC,CASO,SAASM,GAAeN,EAAuB,CACpD,OAAOE,GAAUF,EAAK,cAAc,CACtC,CASO,SAASO,EAASP,EAA6B,CACpD,OAAOE,GAAUF,EAAK,QAAQ,CAChC,CASO,SAASQ,GAAsBR,EAA0C,CAC9E,OACE,OAAOA,GAAQ,UACfA,IAAQ,MACR,+BAAgCA,GAChC,+BAAgCA,CAEpC,CASO,SAASS,GAAYT,EAAgC,CAC1D,OAAOA,IAAQ,MAAQQ,GAAsBR,CAAG,GAAM,OAAOA,GAAQ,UAAY,OAAOA,GAAQ,UAClG,CASO,SAASU,EAAcV,EAA8C,CAC1E,OAAOE,GAAUF,EAAK,QAAQ,CAChC,CASO,SAASW,GAAQX,EAAuC,CAC7D,OAAO,OAAO,MAAU,KAAeC,GAAaD,EAAK,KAAK,CAChE,CASO,SAASY,GAAUZ,EAAuB,CAC/C,OAAO,OAAO,QAAY,KAAeC,GAAaD,EAAK,OAAO,CACpE,CASO,SAASa,GAASb,EAA6B,CACpD,OAAOE,GAAUF,EAAK,QAAQ,CAChC,CAMO,SAASc,EAAWd,EAAmC,CAE5D,MAAO,GAAQA,GAAOA,EAAI,MAAQ,OAAOA,EAAI,MAAS,WAC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,eAAA,EACA,KClb1F,IAAMiE,GAASC,EAETC,GAA2B,EAE3BC,GAAmB,eAYnBC,GAA4B,CAACC,EAA+B,CAAA,IAAO,CACvE,IAAMC,EAAeD,EAAQ,mBAAqB,KAAOA,EAAQ,kBAAoBH,GAErF,MAAO,CACL,KAAMC,GAEN,WAAY,CAAA,EACZ,aAAaI,EAAO,CAClB,OAAOC,GAAiBD,EAAOD,CAAY,CACjD,CACA,CACA,EAEaG,GAA4CL,GAgB5CM,GAAeC,EAA4BR,GAAkBM,EAAuB,EAOjG,SAASD,GAAiBD,EAAcD,EAA6B,CACnE,IAAMM,EAAMZ,GAAO,SACba,EAAeb,GAAO,UAAYc,GAAyBd,GAAO,SAAS,IAAI,EACrF,GAAI,CAACY,GAAO,CAACC,EACX,OAAON,EAGT,IAAMQ,EAAaR,EAAM,WAAaA,EAAM,UAAU,OACtD,GAAI,CAACQ,GAAc,CAACA,EAAW,OAC7B,OAAOR,EAGT,IAAMS,EAAOJ,EAAI,gBAAgB,UACjC,GAAI,CAACI,EACH,OAAOT,EAGT,IAAMU,EAAY,CAAC,kBAAmB,SAAU,GAAGD,EAAK,MAAM;CAAI,EAAG,SAAS,EAE9E,OAAAD,EAAW,QAAQG,GAAa,CAC9B,IAAMC,EAAaD,EAAU,WACzBC,GAAcA,EAAW,SAC3BA,EAAW,OAASA,EAAW,OAAO,IAAIC,GACxCC,GAA0BD,EAAOH,EAAWJ,EAAcP,CAAY,CAC9E,EAEA,CAAG,EAEMC,CACT,CAKO,SAASc,GACdD,EACAH,EACAJ,EACAS,EACY,CACZ,OAAIF,EAAM,WAAaP,GAAgB,CAACO,EAAM,QAAU,CAACH,EAAU,QAInEM,GAAkBN,EAAWG,EAAOE,CAAc,EAE3CF,CACT,CCvGAI","names":["init_esm_shims","init_esm_shims","objectToString","isError","wat","isInstanceOf","isBuiltin","className","isErrorEvent","isDOMError","isDOMException","isString","isParameterizedString","isPrimitive","isPlainObject","isEvent","isElement","isRegExp","isThenable","isSyntheticEvent","isNaN","base","isVueViewModel","truncate","str","max","snipLine","line","colno","newLine","lineLength","start","end","safeJoin","input","delimiter","output","i","value","isVueViewModel","isMatchingPattern","pattern","requireExactStringMatch","isString","isRegExp","stringMatchesSomePattern","testString","patterns","applyAggregateErrorsToEvent","exceptionFromErrorImplementation","parser","maxValueLimit","key","limit","event","hint","isInstanceOf","originalException","truncateAggregateExceptions","aggregateExceptionsFromError","error","prevExceptions","exception","exceptionId","newExceptions","applyExceptionGroupFieldsForParentException","newException","newExceptionId","applyExceptionGroupFieldsForChildException","childError","i","source","parentId","exceptions","maxValueLength","truncate","init_esm_shims","isGlobalObj","obj","GLOBAL_OBJ","getGlobalObject","getGlobalSingleton","name","creator","gbl","__SENTRY__","WINDOW","getGlobalObject","DEFAULT_MAX_STRING_LENGTH","htmlTreeAsString","elem","options","currentElem","MAX_TRAVERSE_HEIGHT","out","height","len","separator","sepLength","nextStr","keyAttrs","maxStringLength","_htmlElementAsString","el","className","classes","key","attr","i","keyAttrPairs","keyAttr","keyAttrPair","isString","allowedAttrs","getLocationHref","getDomElement","selector","getComponentName","init_esm_shims","DEBUG_BUILD","PREFIX","CONSOLE_LEVELS","originalConsoleMethods","consoleSandbox","callback","GLOBAL_OBJ","console","wrappedFuncs","wrappedLevels","level","originalConsoleMethod","makeLogger","enabled","logger","DEBUG_BUILD","name","args","DSN_REGEX","isValidProtocol","protocol","dsnToString","dsn","withPassword","host","path","pass","port","projectId","publicKey","dsnFromString","str","match","consoleSandbox","lastPath","split","projectMatch","dsnFromComponents","components","validateDsn","DEBUG_BUILD","component","logger","makeDsn","from","init_esm_shims","SentryError","message","logLevel","fill","source","name","replacementFactory","original","wrapped","markFunctionWrapped","addNonEnumerableProperty","obj","value","DEBUG_BUILD","logger","proto","getOriginalFunction","func","urlEncode","object","key","convertToPlainObject","isError","getOwnProperties","isEvent","newObj","serializeEventTarget","isInstanceOf","target","isElement","htmlTreeAsString","extractedProps","property","extractExceptionKeysForMessage","exception","maxLength","keys","truncate","includedKeys","serialized","dropUndefinedKeys","inputValue","_dropUndefinedKeys","memoizationMap","isPojo","memoVal","returnValue","item","input","isPlainObject","init_esm_shims","filenameIsInApp","filename","isNative","node","getModule","FILENAME_MATCH","FULL_MATCH","line","lineMatch","object","method","functionName","typeName","methodName","methodStart","objectEnd","STACKTRACE_FRAME_LIMIT","WEBPACK_ERROR_REGEXP","STRIP_FRAME_REGEXP","createStackParser","parsers","sortedParsers","a","b","p","stack","skipFirst","frames","lines","i","line","cleanedLine","parser","frame","stripSentryFramesAndReverse","stackParserFromStackParserOptions","stackParser","localStack","defaultFunctionName","getFunctionName","fn","nodeStackLineParser","getModule","node","handlers","instrumented","addHandler","type","handler","maybeInstrument","type","instrumentFn","instrumented","triggerHandlers","data","typeHandlers","handlers","handler","e","DEBUG_BUILD","logger","getFunctionName","addConsoleInstrumentationHandler","handler","type","addHandler","maybeInstrument","instrumentConsole","GLOBAL_OBJ","CONSOLE_LEVELS","level","fill","originalConsoleMethod","originalConsoleMethods","args","triggerHandlers","log","uuid4","gbl","GLOBAL_OBJ","crypto","getRandomByte","typedArray","c","getFirstException","event","getEventDescription","message","eventId","firstException","addExceptionTypeValue","value","type","exception","values","addExceptionMechanism","newMechanism","defaultMechanism","currentMechanism","mergedData","SEMVER_REGEXP","parseSemver","input","match","major","minor","patch","addContextToFrame","lines","frame","linesOfContext","maxLines","sourceLine","line","snipLine","checkOrSetAlreadyCaught","addNonEnumerableProperty","arrayify","maybeArray","WINDOW","GLOBAL_OBJ","DEBOUNCE_DURATION","debounceTimerID","lastCapturedEventType","lastCapturedEventTargetId","addClickKeypressInstrumentationHandler","handler","type","addHandler","maybeInstrument","instrumentDOM","triggerDOMHandler","triggerHandlers","globalDOMEventHandler","makeDOMEventHandler","target","proto","fill","originalAddEventListener","listener","options","el","handlers","handlerForType","originalRemoveEventListener","isSimilarToLastCapturedEvent","event","shouldSkipDOMEvent","eventType","globalListener","getEventTarget","addNonEnumerableProperty","uuid4","name","WINDOW","getGlobalObject","supportsFetch","WINDOW","isNativeFetch","func","supportsNativeFetch","result","doc","sandbox","err","DEBUG_BUILD","logger","supportsReportingObserver","addFetchInstrumentationHandler","handler","type","addHandler","maybeInstrument","instrumentFetch","supportsNativeFetch","fill","GLOBAL_OBJ","originalFetch","args","method","url","parseFetchArgs","handlerData","triggerHandlers","response","finishedHandlerData","error","erroredHandlerData","hasProp","obj","prop","getUrlFromResource","resource","fetchArgs","options","arg","_oldOnErrorHandler","addGlobalErrorInstrumentationHandler","handler","type","addHandler","maybeInstrument","instrumentError","GLOBAL_OBJ","msg","url","line","column","error","triggerHandlers","_oldOnUnhandledRejectionHandler","addGlobalUnhandledRejectionInstrumentationHandler","handler","type","addHandler","maybeInstrument","instrumentUnhandledRejection","GLOBAL_OBJ","triggerHandlers","WINDOW","getGlobalObject","supportsHistory","chromeVar","isChromePackagedApp","hasHistoryApi","WINDOW","GLOBAL_OBJ","lastHref","addHistoryInstrumentationHandler","handler","type","addHandler","maybeInstrument","instrumentHistory","supportsHistory","oldOnPopState","args","to","from","triggerHandlers","historyReplacementFunction","originalHistoryFunction","url","fill","WINDOW","GLOBAL_OBJ","SENTRY_XHR_DATA_KEY","addXhrInstrumentationHandler","handler","type","addHandler","maybeInstrument","instrumentXHR","xhrproto","fill","originalOpen","args","startTimestamp","method","isString","url","parseUrl","onreadystatechangeHandler","xhrInfo","handlerData","triggerHandlers","original","readyStateArgs","setRequestHeaderArgs","header","value","originalSend","sentryXhrData","init_esm_shims","isBrowserBundle","getSDKSource","isNodeEnv","isBrowserBundle","dynamicRequire","mod","request","loadModule","moduleName","cwd","isBrowser","isNodeEnv","isElectronNodeRenderer","GLOBAL_OBJ","init_esm_shims","memoBuilder","hasWeakSet","inner","memoize","obj","i","unmemoize","normalize","input","depth","maxProperties","visit","err","normalizeToSize","object","maxSize","normalized","jsonSize","key","value","memo","memoBuilder","memoize","unmemoize","isNaN","stringified","stringifyValue","remainingDepth","valueWithToJSON","jsonValue","numAdded","visitable","convertToPlainObject","visitKey","visitValue","isVueViewModel","isSyntheticEvent","getFunctionName","objName","getConstructorName","prototype","utf8Length","init_esm_shims","normalizeArray","parts","allowAboveRoot","up","i","last","splitPathRe","splitPath","filename","truncated","resolve","args","resolvedPath","resolvedAbsolute","path","p","trim","arr","start","end","relative","from","to","fromParts","toParts","length","samePartsLength","outputParts","dirname","path","result","splitPath","root","dir","basename","ext","f","States","RESOLVED","REJECTED","resolvedSyncPromise","value","SyncPromise","resolve","rejectedSyncPromise","reason","_","reject","_SyncPromise","executor","e","onfulfilled","onrejected","result","val","onfinally","isRejected","state","isThenable","cachedHandlers","handler","makePromiseBuffer","limit","buffer","isReady","remove","task","add","taskProducer","rejectedSyncPromise","SentryError","drain","timeout","SyncPromise","resolve","reject","counter","capturedSetTimeout","item","resolvedSyncPromise","init_esm_shims","parseCookie","str","obj","index","eqIdx","endIdx","key","val","init_esm_shims","parseUrl","url","match","query","fragment","stripUrlQueryAndFragment","urlPath","getNumberOfUrlSegments","s","getSanitizedUrlString","protocol","host","path","filteredHost","DEFAULT_INCLUDES","DEFAULT_REQUEST_INCLUDES","DEFAULT_USER_INCLUDES","extractPathForTransaction","req","options","method","path","source","stripUrlQueryAndFragment","name","extractTransaction","type","customRoute","extractUserData","user","keys","extractedUser","DEFAULT_USER_INCLUDES","key","extractRequestData","include","DEFAULT_REQUEST_INCLUDES","deps","requestData","headers","host","protocol","originalUrl","absoluteUrl","parseCookie","extractQueryParams","isString","normalize","addRequestDataToEvent","event","DEFAULT_INCLUDES","extractedRequestData","isPlainObject","ip","init_esm_shims","validSeverityLevels","severityLevelFromString","level","validSeverityLevels","ONE_SECOND_IN_MS","dateTimestampInSeconds","createUnixTimestampInSecondsFunc","performance","GLOBAL_OBJ","approxStartingTimeOrigin","timeOrigin","timestampInSeconds","_browserPerformanceTimeOriginMode","browserPerformanceTimeOrigin","performance","GLOBAL_OBJ","threshold","performanceNow","dateNow","timeOriginDelta","timeOriginIsReliable","navigationStart","navigationStartDelta","navigationStartIsReliable","BAGGAGE_HEADER_NAME","SENTRY_BAGGAGE_KEY_PREFIX","SENTRY_BAGGAGE_KEY_PREFIX_REGEX","MAX_BAGGAGE_STRING_LENGTH","baggageHeaderToDynamicSamplingContext","baggageHeader","isString","baggageObject","acc","curr","currBaggageObject","baggageHeaderToObject","key","dynamicSamplingContext","value","nonPrefixedKey","dynamicSamplingContextToSentryBaggageHeader","sentryPrefixedDSC","dscKey","dscValue","objectToBaggageHeader","baggageEntry","keyOrValue","object","objectKey","objectValue","currentIndex","newBaggageHeader","DEBUG_BUILD","logger","TRACEPARENT_REGEXP","extractTraceparentData","traceparent","matches","parentSampled","tracingContextFromHeaders","sentryTrace","baggage","traceparentData","dynamicSamplingContext","baggageHeaderToDynamicSamplingContext","traceId","parentSpanId","uuid4","propagationContextFromHeaders","generateSentryTraceHeader","spanId","sampled","sampledString","createEnvelope","headers","items","addItemToEnvelope","envelope","newItem","forEachEnvelopeItem","callback","envelopeItems","envelopeItem","envelopeItemType","envelopeContainsItemType","types","_","type","encodeUTF8","input","textEncoder","serializeEnvelope","envHeaders","parts","append","next","item","itemHeaders","payload","stringifiedPayload","normalize","concatBuffers","buffers","totalLength","acc","buf","merged","offset","buffer","parseEnvelope","env","textDecoder","readBinary","length","bin","readJson","i","envelopeHeader","itemHeader","binaryLength","createAttachmentEnvelopeItem","attachment","dropUndefinedKeys","ITEM_TYPE_TO_DATA_CATEGORY_MAP","envelopeItemTypeToDataCategory","getSdkMetadataForEnvelopeHeader","metadataOrEvent","name","version","createEventEnvelopeHeaders","event","sdkInfo","tunnel","dsn","dynamicSamplingContext","dsnToString","createClientReportEnvelope","discarded_events","dsn","timestamp","clientReportItem","dateTimestampInSeconds","createEnvelope","init_esm_shims","parseRetryAfterHeader","header","now","headerDelay","headerDate","disabledUntil","limits","dataCategory","isRateLimited","updateRateLimits","statusCode","headers","updatedRateLimits","rateLimitHeader","retryAfterHeader","limit","retryAfter","categories","namespaces","delay","category","parseStackFrames","stackParser","error","exceptionFromError","exception","frames","getMessageForObject","message","extractExceptionKeysForMessage","eventFromUnknownInput","getHubOrClient","hint","client","ex","mechanism","extras","isError","isPlainObject","normalizeDepth","normalizeToSize","event","addExceptionTypeValue","addExceptionMechanism","eventFromMessage","level","attachStacktrace","isParameterizedString","__sentry_template_string__","__sentry_template_values__","init_esm_shims","LRUMap","_maxSize","key","value","values","init_esm_shims","_nullishCoalesce","lhs","rhsFn","init_esm_shims","_optionalChain","ops","lastAccessLHS","value","i","op","fn","args","_optionalChainDelete","ops","result","_optionalChain","init_esm_shims","DEBUG_BUILD","getGlobalEventProcessors","getGlobalSingleton","addGlobalEventProcessor","callback","notifyEventProcessors","processors","event","hint","index","SyncPromise","resolve","reject","processor","result","DEBUG_BUILD","logger","isThenable","final","init_esm_shims","DEFAULT_ENVIRONMENT","makeSession","context","startingTime","timestampInSeconds","session","uuid4","sessionToJSON","updateSession","duration","closeSession","status","dropUndefinedKeys","init_esm_shims","getRootSpan","span","TRACE_FLAG_NONE","TRACE_FLAG_SAMPLED","spanToTraceContext","span","span_id","trace_id","data","op","parent_span_id","status","tags","origin","spanToJSON","dropUndefinedKeys","spanToTraceHeader","traceId","spanId","sampled","spanIsSampled","generateSentryTraceHeader","spanTimeInputToSeconds","input","ensureTimestampInSeconds","timestampInSeconds","timestamp","spanIsSpanClass","traceFlags","getDynamicSamplingContextFromClient","trace_id","client","scope","options","public_key","user_segment","dsc","dropUndefinedKeys","DEFAULT_ENVIRONMENT","getDynamicSamplingContextFromSpan","span","getClient","spanToJSON","getCurrentScope","txn","getRootSpan","v7FrozenDsc","maybeSampleRate","source","jsonSpan","spanIsSampled","applyScopeDataToEvent","event","data","fingerprint","span","breadcrumbs","sdkProcessingMetadata","applyDataToEvent","applySpanToEvent","applyFingerprintToEvent","applyBreadcrumbsToEvent","applySdkMetadataToEvent","mergeScopeData","mergeData","extra","tags","user","contexts","level","eventProcessors","attachments","propagationContext","transactionName","mergeAndOverwriteScopeData","prop","mergeVal","key","cleanedExtra","dropUndefinedKeys","cleanedTags","cleanedUser","cleanedContexts","mergedBreadcrumbs","spanToTraceContext","rootSpan","getRootSpan","getDynamicSamplingContextFromSpan","spanToJSON","arrayify","DEFAULT_MAX_BREADCRUMBS","globalScope","Scope","_Scope","generatePropagationContext","scope","newScope","client","callback","user","updateSession","requestSession","tags","key","value","extras","extra","fingerprint","level","name","context","span","session","captureContext","scopeToMerge","scopeData","isPlainObject","scopeContext","breadcrumb","maxBreadcrumbs","maxCrumbs","mergedBreadcrumb","dateTimestampInSeconds","breadcrumbs","attachment","_breadcrumbs","_attachments","_contexts","_tags","_extra","_user","_level","_fingerprint","_eventProcessors","_propagationContext","_sdkProcessingMetadata","_transactionName","_span","event","hint","additionalEventProcessors","applyScopeDataToEvent","eventProcessors","getGlobalEventProcessors","notifyEventProcessors","newData","exception","eventId","uuid4","logger","syntheticException","message","getGlobalScope","generatePropagationContext","uuid4","init_esm_shims","SDK_VERSION","API_VERSION","SDK_VERSION","DEFAULT_BREADCRUMBS","Hub","client","scope","isolationScope","_version","assignedScope","Scope","assignedIsolationScope","version","top","callback","maybePromiseResult","e","isThenable","res","exception","hint","eventId","uuid4","syntheticException","message","level","event","breadcrumb","beforeBreadcrumb","maxBreadcrumbs","mergedBreadcrumb","dateTimestampInSeconds","finalBreadcrumb","consoleSandbox","user","tags","extras","key","value","extra","name","context","oldHub","makeMain","integration","DEBUG_BUILD","logger","customSamplingContext","result","endSession","session","closeSession","release","environment","DEFAULT_ENVIRONMENT","userAgent","GLOBAL_OBJ","makeSession","currentSession","updateSession","options","method","args","sentry","getMainCarrier","hub","registry","getHubFromCarrier","setHubOnCarrier","getCurrentHub","getGlobalHub","getIsolationScope","hasHubOnCarrier","runWithAsyncContext","callback","options","registry","getMainCarrier","hasHubOnCarrier","carrier","getHubFromCarrier","getGlobalSingleton","Hub","setHubOnCarrier","hub","__SENTRY__","prepareEvent","options","event","hint","scope","client","isolationScope","normalizeDepth","normalizeMaxBreadth","prepared","uuid4","dateTimestampInSeconds","integrations","i","applyClientOptions","applyIntegrationsMetadata","applyDebugIds","finalScope","getFinalScope","addExceptionMechanism","clientEventProcessors","data","getGlobalScope","isolationData","mergeScopeData","finalScopeData","attachments","applyScopeDataToEvent","eventProcessors","getGlobalEventProcessors","notifyEventProcessors","evt","applyDebugMeta","normalizeEvent","environment","release","dist","maxValueLength","DEFAULT_ENVIRONMENT","truncate","exception","request","debugIdStackParserCache","stackParser","debugIdMap","GLOBAL_OBJ","debugIdStackFramesCache","cachedDebugIdStackFrameCache","filenameDebugIdMap","acc","debugIdStackTrace","parsedStack","cachedParsedStack","stackFrame","frame","images","filename","integrationNames","depth","maxBreadth","normalized","b","normalize","span","spanToJSON","captureContext","Scope","parseEventHintOrCaptureContext","hintIsScopeOrFunction","hintIsScopeContext","captureContextKeys","key","captureException","exception","hint","getCurrentHub","parseEventHintOrCaptureContext","captureMessage","message","captureContext","level","context","captureEvent","event","configureScope","callback","addBreadcrumb","breadcrumb","setContext","name","setExtras","extras","setExtra","key","extra","setTags","tags","setTag","value","setUser","user","withScope","rest","hub","scope","withIsolationScope","runWithAsyncContext","getIsolationScope","withActiveSpan","span","startTransaction","customSamplingContext","flush","timeout","client","getClient","DEBUG_BUILD","logger","close","lastEventId","getCurrentHub","isInitialized","getCurrentScope","startSession","context","isolationScope","getIsolationScope","currentScope","release","environment","DEFAULT_ENVIRONMENT","userAgent","GLOBAL_OBJ","session","makeSession","currentSession","updateSession","endSession","closeSession","_sendSessionUpdate","captureSession","end","getActiveTransaction","maybeHub","getCurrentHub","extractTraceparentData","_extractTraceparentData","init_esm_shims","SpanStatus","Ok","DeadlineExceeded","Unauthenticated","PermissionDenied","NotFound","ResourceExhausted","InvalidArgument","Unimplemented","Unavailable","InternalError","UnknownError","Cancelled","AlreadyExists","FailedPrecondition","Aborted","OutOfRange","DataLoss","getSpanStatusFromHttpCode","httpStatus","spanStatusfromHttpCode","setHttpStatus","span","spanStatus","errorsInstrumented","registerErrorInstrumentation","addGlobalErrorInstrumentationHandler","errorCallback","addGlobalUnhandledRejectionInstrumentationHandler","activeTransaction","getActiveTransaction","status","DEBUG_BUILD","logger","handleCallbackErrors","fn","onError","onFinally","maybePromiseResult","e","maybeHandlePromiseRejection","value","isThenable","res","hasTracingEnabled","maybeOptions","client","getClient","options","trace","context","callback","onError","afterFinish","hub","getCurrentHub","scope","getCurrentScope","parentSpan","spanContext","normalizeContext","activeSpan","createChildSpanOrTransaction","handleCallbackErrors","error","startSpan","runWithAsyncContext","withScope","status","spanToJSON","startSpanManual","context","callback","spanContext","normalizeContext","runWithAsyncContext","withScope","scope","hub","getCurrentHub","parentSpan","activeSpan","createChildSpanOrTransaction","finishAndSetSpan","handleCallbackErrors","status","spanToJSON","startInactiveSpan","hasTracingEnabled","getActiveSpan","temporaryScope","getCurrentScope","continueTrace","sentryTrace","baggage","currentScope","traceparentData","dynamicSamplingContext","propagationContext","tracingContextFromHeaders","DEBUG_BUILD","logger","transactionContext","dropUndefinedKeys","forceTransaction","isolationScope","getIsolationScope","span","dsc","getDynamicSamplingContextFromSpan","traceId","parentSpanId","sampled","spanIsSampled","setCapturedScopesOnSpan","ctx","spanTimeInputToSeconds","SCOPE_ON_START_SPAN_FIELD","ISOLATION_SCOPE_ON_START_SPAN_FIELD","addNonEnumerableProperty","getCapturedScopesOnSpan","init_esm_shims","SEMANTIC_ATTRIBUTE_SENTRY_SOURCE","SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE","SEMANTIC_ATTRIBUTE_SENTRY_OP","SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN","SEMANTIC_ATTRIBUTE_PROFILE_ID","SPAN_METRIC_SUMMARY","getMetricStorageForSpan","span","getMetricSummaryJsonForSpan","storage","output","exportKey","summary","dropUndefinedKeys","updateMetricSummaryOnActiveSpan","metricType","sanitizedName","value","unit","tags","bucketKey","getActiveSpan","bucketItem","SpanRecorder","maxlen","span","Span","_Span","spanContext","uuid4","timestampInSeconds","SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN","SEMANTIC_ATTRIBUTE_SENTRY_OP","name","description","traceId","spanId","string","sampled","attributes","startTime","endTime","status","op","origin","TRACE_FLAG_SAMPLED","TRACE_FLAG_NONE","childSpan","rootSpan","getRootSpan","DEBUG_BUILD","opStr","nameStr","spanToJSON","idStr","logMessage","logger","key","value","httpStatus","setHttpStatus","endTimestamp","spanTimeInputToSeconds","spanToTraceHeader","dropUndefinedKeys","spanToTraceContext","getMetricSummaryJsonForSpan","SEMANTIC_ATTRIBUTE_PROFILE_ID","data","hasData","hasAttributes","Transaction","SpanClass","transactionContext","hub","getCurrentHub","incomingDynamicSamplingContext","newName","SEMANTIC_ATTRIBUTE_SENTRY_SOURCE","SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE","metadata","name","source","maxlen","SpanRecorder","key","context","value","unit","newMetadata","endTimestamp","timestampInS","spanTimeInputToSeconds","transaction","spanContext","dropUndefinedKeys","getDynamicSamplingContextFromSpan","DEBUG_BUILD","logger","client","finishedSpans","span","spanToJSON","endTimes","prev","current","capturedSpanScope","capturedSpanIsolationScope","getCapturedScopesOnSpan","spanToTraceContext","getMetricSummaryJsonForSpan","TRACING_DEFAULTS","FINISH_REASON_TAG","IDLE_TRANSACTION_FINISH_REASONS","IdleTransactionSpanRecorder","SpanRecorder","_pushActivity","_popActivity","transactionSpanId","maxlen","span","originalEnd","rest","spanToJSON","IdleTransaction","Transaction","transactionContext","_idleHub","_idleTimeout","_finalTimeout","_heartbeatInterval","_onScope","delayAutoFinishUntilSignal","DEBUG_BUILD","logger","endTimestamp","endTimestampInS","spanTimeInputToSeconds","callback","startTime","endTime","spanStartedBeforeTransactionFinish","timeoutWithMarginOfError","spanEndedBeforeFinalTimeout","stringifiedSpan","scope","pushActivity","id","popActivity","restartOnChildSpanChange","reason","spanId","timestampInSeconds","heartbeatString","sampleTransaction","transaction","options","samplingContext","hasTracingEnabled","SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE","sampleRate","isValidSampleRate","DEBUG_BUILD","logger","spanToJSON","rate","isNaN","traceHeaders","span","spanToTraceHeader","_startTransaction","transactionContext","customSamplingContext","client","options","configInstrumenter","transactionInstrumenter","DEBUG_BUILD","logger","transaction","Transaction","sampleTransaction","startIdleTransaction","hub","idleTimeout","finalTimeout","onScope","heartbeatInterval","delayAutoFinishUntilSignal","IdleTransaction","addTracingExtensions","carrier","getMainCarrier","registerErrorInstrumentation","setMeasurement","name","value","unit","transaction","getActiveTransaction","installedIntegrations","filterDuplicates","integrations","integrationsByName","currentInstance","name","existingInstance","k","getIntegrationsToSetup","options","defaultIntegrations","userIntegrations","integration","arrayify","finalIntegrations","debugIndex","findIndex","debugInstance","setupIntegrations","client","integrationIndex","setupIntegration","afterSetupIntegrations","DEBUG_BUILD","logger","addGlobalEventProcessor","getCurrentHub","callback","event","hint","processor","addIntegration","getClient","arr","i","convertIntegrationFnToClass","fn","args","SENTRY_API_VERSION","getBaseApiEndpoint","dsn","protocol","port","_getIngestEndpoint","_encodedAuth","sdkInfo","urlEncode","getEnvelopeEndpointWithUrlEncodedAuth","tunnelOrOptions","tunnel","getReportDialogEndpoint","dsnLike","dialogOptions","makeDsn","endpoint","encodedOptions","dsnToString","key","user","enhanceEventWithSdkInfo","event","sdkInfo","createSessionEnvelope","session","dsn","metadata","tunnel","getSdkMetadataForEnvelopeHeader","envelopeHeaders","dsnToString","envelopeItem","createEnvelope","createEventEnvelope","eventType","createEventEnvelopeHeaders","getBucketKey","metricType","name","unit","tags","stringifiedTags","dropUndefinedKeys","a","b","simpleHash","s","rv","i","c","serializeMetricBuckets","metricBucketItems","out","item","tagEntries","maybeTags","key","value","sanitizeUnit","sanitizeMetricKey","sanitizeTagKey","tagValueReplacements","getCharOrReplacement","input","search","replacement","sanitizeTagValue","acc","char","sanitizeTags","unsanitizedTags","sanitizedKey","createMetricEnvelope","metricBucketItems","dsn","metadata","tunnel","headers","dsnToString","item","createMetricEnvelopeItem","createEnvelope","payload","serializeMetricBuckets","ALREADY_SEEN_ERROR","BaseClient","options","makeDsn","DEBUG_BUILD","logger","url","getEnvelopeEndpointWithUrlEncodedAuth","exception","hint","scope","checkOrSetAlreadyCaught","eventId","event","result","message","level","eventMessage","isParameterizedString","promisedEvent","isPrimitive","capturedSpanScope","session","updateSession","timeout","transport","clientFinished","transportFlushed","resolvedSyncPromise","eventProcessor","forceInitialize","integrationId","integrationName","integration","isAlreadyInstalled","setupIntegration","afterSetupIntegrations","env","createEventEnvelope","attachment","addItemToEnvelope","createAttachmentEnvelopeItem","promise","sendResponse","createSessionEnvelope","reason","category","_event","key","metricBucketItems","metricsEnvelope","createMetricEnvelope","hook","callback","rest","integrations","setupIntegrations","crashed","errored","exceptions","ex","mechanism","sessionNonTerminal","SyncPromise","resolve","ticked","tick","interval","isolationScope","getIsolationScope","prepareEvent","evt","propagationContext","trace_id","spanId","parentSpanId","dsc","dynamicSamplingContext","getDynamicSamplingContextFromClient","finalEvent","sentryError","sampleRate","isTransaction","isTransactionEvent","isError","isErrorEvent","eventType","beforeSendLabel","rejectedSyncPromise","SentryError","dataCategory","capturedSpanIsolationScope","prepared","processBeforeSend","_validateBeforeSendResult","processedEvent","transactionInfo","source","value","envelope","outcomes","beforeSendResult","invalidValueError","isThenable","isPlainObject","e","beforeSend","beforeSendTransaction","addEventProcessor","client","getClient","initAndBind","clientClass","options","DEBUG_BUILD","logger","consoleSandbox","getCurrentScope","client","setCurrentClient","initializeClient","top","getCurrentHub","DEFAULT_TRANSPORT_BUFFER_SIZE","createTransport","options","makeRequest","buffer","makePromiseBuffer","rateLimits","flush","timeout","send","envelope","filteredEnvelopeItems","forEachEnvelopeItem","item","type","dataCategory","envelopeItemTypeToDataCategory","isRateLimited","event","getEventForEnvelopeItem","resolvedSyncPromise","filteredEnvelope","createEnvelope","recordEnvelopeLoss","reason","requestTask","serializeEnvelope","response","DEBUG_BUILD","logger","updateRateLimits","error","result","SentryError","eventFromEnvelope","env","types","event","forEachEnvelopeItem","item","type","makeOverrideReleaseTransport","createTransport","release","options","transport","envelope","overrideDsn","dsn","createEnvelope","makeMultiplexedTransport","matcher","fallbackTransport","otherTransports","getTransport","key","validatedDsn","dsnFromString","url","getEnvelopeEndpointWithUrlEncodedAuth","send","getEvent","eventTypes","transports","result","t","flush","timeout","promises","r","init_esm_shims","parameterize","strings","values","formatted","filenameMetadataMap","parsedStacks","ensureMetadataStacksAreParsed","parser","GLOBAL_OBJ","stack","metadata","frames","frame","getMetadataForUrl","filename","addMetadataToStackFrames","event","exception","stripMetadataFromStackFrames","INTEGRATION_NAME","_moduleMetadataIntegration","client","envelope","forEachEnvelopeItem","item","type","event","stripMetadataFromStackFrames","_hint","stackParser","addMetadataToStackFrames","moduleMetadataIntegration","ModuleMetadata","convertIntegrationFnToClass","DEFAULT_IGNORE_ERRORS","DEFAULT_IGNORE_TRANSACTIONS","INTEGRATION_NAME","_inboundFiltersIntegration","options","event","_hint","client","clientOptions","mergedOptions","_mergeOptions","_shouldDropEvent","inboundFiltersIntegration","InboundFilters","convertIntegrationFnToClass","internalOptions","_isSentryError","DEBUG_BUILD","logger","getEventDescription","_isIgnoredError","_isIgnoredTransaction","_isDeniedUrl","_getEventFilterUrl","_isAllowedUrl","ignoreErrors","_getPossibleEventMessages","message","stringMatchesSomePattern","ignoreTransactions","name","denyUrls","url","allowUrls","possibleMessages","lastException","_getLastValidUrl","frames","i","frame","originalFunctionToString","INTEGRATION_NAME","SETUP_CLIENTS","_functionToStringIntegration","args","originalFunction","getOriginalFunction","context","getClient","client","functionToStringIntegration","FunctionToString","convertIntegrationFnToClass","init_esm_shims","COUNTER_METRIC_TYPE","GAUGE_METRIC_TYPE","SET_METRIC_TYPE","DISTRIBUTION_METRIC_TYPE","CounterMetric","_value","value","GaugeMetric","DistributionMetric","first","SetMetric","val","simpleHash","METRIC_MAP","COUNTER_METRIC_TYPE","GAUGE_METRIC_TYPE","DISTRIBUTION_METRIC_TYPE","SET_METRIC_TYPE","BrowserMetricsAggregator","_client","metricType","unsanitizedName","value","unsanitizedUnit","unsanitizedTags","maybeFloatTimestamp","timestampInSeconds","timestamp","name","sanitizeMetricKey","tags","sanitizeTags","unit","sanitizeUnit","bucketKey","getBucketKey","bucketItem","previousWeight","SET_METRIC_TYPE","METRIC_MAP","val","updateMetricSummaryOnActiveSpan","metricBuckets","INTEGRATION_NAME","_metricsAggregatorIntegration","client","BrowserMetricsAggregator","metricsAggregatorIntegration","MetricsAggregator","convertIntegrationFnToClass","addToMetricsAggregator","metricType","name","value","data","client","getClient","scope","getCurrentScope","DEBUG_BUILD","logger","unit","tags","timestamp","release","environment","transaction","metricTags","spanToJSON","increment","COUNTER_METRIC_TYPE","distribution","DISTRIBUTION_METRIC_TYPE","set","SET_METRIC_TYPE","gauge","GAUGE_METRIC_TYPE","metrics","MetricsAggregator","metricsAggregatorIntegration","SessionFlusher","client","attrs","sessionAggregates","aggregates","key","dropUndefinedKeys","scope","getCurrentScope","requestSession","status","date","sessionStartedTrunc","aggregationCounts","createCheckInEnvelope","checkIn","dynamicSamplingContext","metadata","tunnel","dsn","headers","dsnToString","dropUndefinedKeys","item","createCheckInEnvelopeItem","createEnvelope","MetricsAggregator","_client","metricType","unsanitizedName","value","unsanitizedUnit","unsanitizedTags","maybeFloatTimestamp","timestampInSeconds","timestamp","name","sanitizeMetricKey","tags","sanitizeTags","unit","sanitizeUnit","bucketKey","getBucketKey","bucketItem","previousWeight","SET_METRIC_TYPE","METRIC_MAP","val","updateMetricSummaryOnActiveSpan","cutoffSeconds","flushedBuckets","key","bucket","buckets","ServerRuntimeClient","BaseClient","options","addTracingExtensions","MetricsAggregator","exception","hint","resolvedSyncPromise","eventFromUnknownInput","getClient","message","level","eventFromMessage","scope","requestSession","event","timeout","release","environment","SessionFlusher","DEBUG_BUILD","logger","checkIn","monitorConfig","id","uuid4","tunnel","serializedCheckIn","dynamicSamplingContext","traceContext","envelope","createCheckInEnvelope","isolationScope","span","getRootSpan","getDynamicSamplingContextFromSpan","spanToTraceContext","traceId","spanId","parentSpanId","dsc","getDynamicSamplingContextFromClient","MIN_DELAY","START_DELAY","MAX_DELAY","log","msg","error","DEBUG_BUILD","logger","makeOfflineTransport","createTransport","options","transport","store","retryDelay","flushTimer","shouldQueue","env","envelopeContainsItemType","flushIn","delay","found","send","e","flushWithBackOff","envelope","result","parseRetryAfterHeader","t","createSpanEnvelope","spans","dsn","headers","dsnToString","items","createSpanItem","createEnvelope","span","init_esm_shims","isSentryRequestUrl","url","hubOrClient","client","isHub","dsn","tunnel","checkDsn","checkTunnel","removeTrailingSlash","str","applySdkMetadata","options","name","names","source","metadata","SDK_VERSION","DEFAULT_OPTIONS","INTEGRATION_NAME","_requestDataIntegration","options","_addRequestData","addRequestDataToEvent","_options","event","_hint","client","transactionNamingScheme","sdkProcessingMetadata","req","addRequestDataOptions","convertReqDataIntegrationOptsToAddReqDataOpts","processedEvent","transaction","name","spanToJSON","shouldIncludeMethodInTransactionName","getSDKName","transactionValue","extractPathForTransaction","requestDataIntegration","RequestData","convertIntegrationFnToClass","integrationOptions","ip","user","requestOptions","requestIncludeKeys","key","value","addReqDataUserOpt","userIncludeKeys","DEFAULT_KEY","DEFAULT_LIMIT","INTEGRATION_NAME","_linkedErrorsIntegration","options","limit","key","event","hint","client","applyAggregateErrorsToEvent","exceptionFromError","linkedErrorsIntegration","LinkedErrors","convertIntegrationFnToClass","Integrations","INTEGRATIONS","instrumentFetchRequest","handlerData","shouldCreateSpan","shouldAttachHeaders","spans","spanOrigin","hasTracingEnabled","shouldCreateSpanResult","spanId","span","endSpan","scope","getCurrentScope","client","getClient","method","url","fullUrl","getFullURL","host","parseUrl","startInactiveSpan","SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN","request","options","addTracingHeadersToFetchRequest","requestSpan","isolationScope","getIsolationScope","traceId","sampled","dsc","sentryTraceHeader","spanToTraceHeader","generateSentryTraceHeader","sentryBaggageHeader","dynamicSamplingContextToSentryBaggageHeader","getDynamicSamplingContextFromSpan","getDynamicSamplingContextFromClient","headers","isInstanceOf","newHeaders","BAGGAGE_HEADER_NAME","existingBaggageHeader","newBaggageHeaders","setHttpStatus","contentLength","contentLengthNum","init_esm_shims","DEBUG_BUILD","init_esm_shims","bindReporter","callback","metric","reportAllChanges","prevValue","delta","forceReport","WINDOW","GLOBAL_OBJ","init_esm_shims","generateUniqueID","getNavigationEntryFromPerformanceTiming","timing","WINDOW","type","navigationEntry","key","getNavigationEntry","getActivationStart","navEntry","getNavigationEntry","initMetric","name","value","navEntry","getNavigationEntry","navigationType","WINDOW","getActivationStart","generateUniqueID","init_esm_shims","observe","type","callback","opts","po","list","onHidden","cb","once","onHiddenOrPageHide","event","WINDOW","onCLS","onReport","options","metric","initMetric","report","sessionValue","sessionEntries","handleEntries","entries","entry","firstSessionEntry","lastSessionEntry","po","observe","bindReporter","stopListening","onHidden","firstHiddenTime","initHiddenTime","WINDOW","trackChanges","onHidden","timeStamp","getVisibilityWatcher","onFID","onReport","visibilityWatcher","getVisibilityWatcher","metric","initMetric","report","handleEntry","entry","handleEntries","entries","po","observe","bindReporter","onHidden","interactionCountEstimate","minKnownInteractionId","maxKnownInteractionId","updateEstimate","entries","e","po","getInteractionCount","initInteractionCountPolyfill","observe","getInteractionCountForNavigation","getInteractionCount","MAX_INTERACTIONS_TO_CONSIDER","longestInteractionList","longestInteractionMap","processEntry","entry","minLongestInteraction","existingInteraction","interaction","a","b","i","estimateP98LongestInteraction","candidateInteractionIndex","onINP","onReport","opts","initInteractionCountPolyfill","metric","initMetric","report","handleEntries","entries","prevEntry","inp","po","observe","bindReporter","onHidden","reportedMetricIDs","onLCP","onReport","visibilityWatcher","getVisibilityWatcher","metric","initMetric","report","handleEntries","entries","lastEntry","value","getActivationStart","po","observe","bindReporter","stopListening","type","WINDOW","onHidden","whenReady","callback","WINDOW","onTTFB","onReport","opts","metric","initMetric","report","bindReporter","navEntry","getNavigationEntry","getActivationStart","handlers","instrumented","_previousCls","_previousFid","_previousLcp","_previousTtfb","_previousInp","addClsInstrumentationHandler","callback","stopOnCallback","addMetricObserver","instrumentCls","addLcpInstrumentationHandler","instrumentLcp","addTtfbInstrumentationHandler","instrumentTtfb","addFidInstrumentationHandler","instrumentFid","addInpInstrumentationHandler","instrumentInp","addPerformanceInstrumentationHandler","type","addHandler","instrumentPerformanceObserver","getCleanupCallback","triggerHandlers","data","typeHandlers","handler","e","DEBUG_BUILD","logger","getFunctionName","onCLS","metric","onFID","onLCP","onTTFB","onINP","instrumentFn","previousValue","stopListening","options","observe","entries","index","DEFAULT_TRACE_PROPAGATION_TARGETS","defaultRequestInstrumentationOptions","instrumentOutgoingRequests","_options","traceFetch","traceXHR","tracePropagationTargets","tracingOrigins","shouldCreateSpanForRequest","enableHTTPTimings","shouldCreateSpan","_","shouldAttachHeadersWithTargets","url","shouldAttachHeaders","spans","addFetchInstrumentationHandler","handlerData","createdSpan","instrumentFetchRequest","fullUrl","getFullURL","host","parseUrl","addHTTPTimings","addXhrInstrumentationHandler","xhrCallback","isPerformanceResourceTiming","entry","span","spanToJSON","cleanup","addPerformanceInstrumentationHandler","entries","resourceTimingEntryToSpanData","data","extractNetworkProtocol","nextHopProtocol","name","version","_name","char","getAbsoluteTime","time","browserPerformanceTimeOrigin","resourceTiming","timingSpanData","stringMatchesSomePattern","xhr","sentryXhrData","SENTRY_XHR_DATA_KEY","hasTracingEnabled","shouldCreateSpanResult","spanId","setHttpStatus","scope","getCurrentScope","isolationScope","getIsolationScope","startInactiveSpan","SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN","client","getClient","traceId","sampled","dsc","sentryTraceHeader","spanToTraceHeader","generateSentryTraceHeader","sentryBaggageHeader","dynamicSamplingContextToSentryBaggageHeader","getDynamicSamplingContextFromSpan","getDynamicSamplingContextFromClient","setHeaderOnXhr","BAGGAGE_HEADER_NAME","WINDOW","registerBackgroundTabDetection","WINDOW","activeTransaction","getActiveTransaction","statusType","op","status","spanToJSON","DEBUG_BUILD","logger","init_esm_shims","isMeasurementValue","value","_startChild","transaction","startTimestamp","ctx","MAX_INT_AS_BYTES","msToSec","time","getBrowserPerformanceAPI","WINDOW","_performanceCursor","_measurements","_lcpEntry","_clsEntry","startTrackingWebVitals","performance","browserPerformanceTimeOrigin","fidCallback","_trackFID","clsCallback","_trackCLS","lcpCallback","_trackLCP","ttfbCallback","_trackTtfb","startTrackingLongTasks","addPerformanceInstrumentationHandler","entries","entry","transaction","getActiveTransaction","startTime","duration","startTrackingInteractions","span","htmlTreeAsString","componentName","getComponentName","startTrackingINP","interactionIdtoRouteNameMapping","interactionsSampleRate","inpCallback","_trackINP","addClsInstrumentationHandler","metric","DEBUG_BUILD","logger","addLcpInstrumentationHandler","addFidInstrumentationHandler","timeOrigin","addTtfbInstrumentationHandler","INP_ENTRY_MAP","interactionIdToRouteNameMapping","addInpInstrumentationHandler","client","getClient","interactionType","options","interaction","routeName","parentContext","activeTransaction","user","replayId","userDisplay","profileId","Span","sampleRate","getSampleRate","envelope","createSpanEnvelope","transport","reason","addPerformanceEntries","performanceEntries","op","transactionStartTime","spanToJSON","_addNavigationSpans","_addMeasureSpans","firstHidden","getVisibilityWatcher","shouldRecord","_addResourceSpans","_trackNavigator","_addTtfbRequestTimeToMeasurements","name","oldValue","measurementTimestamp","normalizedValue","delta","fidMark","_startChild","measurementName","setMeasurement","_tagMetricInfo","measureStartTimestamp","measureEndTimestamp","event","_addPerformanceNavigationTiming","_addRequest","description","eventEnd","end","start","resourceUrl","parsedUrl","parseUrl","data","setResourceEntrySizeData","startTimestamp","endTimestamp","navigator","connection","isMeasurementValue","source","index","key","dataKey","entryVal","navEntry","getNavigationEntry","responseStart","requestStart","transactionContext","hasTracingEnabled","isValidSampleRate","instrumentRoutingWithDefaults","customStartTransaction","startTransactionOnPageLoad","startTransactionOnLocationChange","WINDOW","DEBUG_BUILD","logger","startingUrl","activeTransaction","browserPerformanceTimeOrigin","addHistoryInstrumentationHandler","to","from","BROWSER_TRACING_INTEGRATION_ID","DEFAULT_BROWSER_TRACING_OPTIONS","TRACING_DEFAULTS","instrumentRoutingWithDefaults","defaultRequestInstrumentationOptions","MAX_INTERACTIONS","BrowserTracing","_options","addTracingExtensions","DEBUG_BUILD","startTrackingWebVitals","startTrackingINP","startTrackingLongTasks","startTrackingInteractions","_","getCurrentHub","client","clientOptions","instrumentRouting","startTransactionOnLocationChange","startTransactionOnPageLoad","markBackgroundTransactions","traceFetch","traceXHR","shouldCreateSpanForRequest","enableHTTPTimings","_experiments","clientOptionsTracePropagationTargets","tracePropagationTargets","logger","context","transaction","registerBackgroundTabDetection","instrumentOutgoingRequests","hub","beforeNavigate","idleTimeout","finalTimeout","heartbeatInterval","isPageloadTransaction","expandedContext","sentryTrace","getMetaContent","baggage","traceId","dsc","parentSpanId","sampled","propagationContextFromHeaders","modifiedContext","finalContext","location","WINDOW","idleTransaction","startIdleTransaction","addPerformanceEntries","inflightInteractionTransaction","registerInteractionTransaction","op","currentTransaction","getActiveTransaction","SEMANTIC_ATTRIBUTE_SENTRY_SOURCE","getSource","type","handleEntries","entries","getClient","replay","replayId","activeTransaction","currentScope","getCurrentScope","user","entry","isPerformanceEventTiming","interactionId","existingInteraction","duration","startTime","keys","minInteractionId","a","b","key","interaction","routeName","parentContext","addPerformanceInstrumentationHandler","metaName","metaTag","getDomElement","sourceFromAttributes","sourceFromData","sourceFromMetadata","BROWSER_TRACING_INTEGRATION_ID","DEFAULT_BROWSER_TRACING_OPTIONS","TRACING_DEFAULTS","defaultRequestInstrumentationOptions","browserTracingIntegration","_options","_hasSetTracePropagationTargets","DEBUG_BUILD","addTracingExtensions","options","_collectWebVitals","startTrackingWebVitals","interactionIdToRouteNameMapping","startTrackingINP","startTrackingLongTasks","startTrackingInteractions","latestRoute","_createRouteTransaction","context","hub","getCurrentHub","beforeStartSpan","idleTimeout","finalTimeout","heartbeatInterval","isPageloadTransaction","expandedContext","sentryTrace","getMetaContent","baggage","traceId","dsc","parentSpanId","sampled","propagationContextFromHeaders","finalContext","logger","location","WINDOW","idleTransaction","startIdleTransaction","transaction","addPerformanceEntries","client","clientOptions","markBackgroundSpan","traceFetch","traceXHR","shouldCreateSpanForRequest","enableHTTPTimings","_experiments","clientOptionsTracePropagationTargets","tracePropagationTargets","activeSpan","startingUrl","spanToJSON","browserPerformanceTimeOrigin","SEMANTIC_ATTRIBUTE_SENTRY_SOURCE","startBrowserTracingPageLoadSpan","addHistoryInstrumentationHandler","to","from","startBrowserTracingNavigationSpan","registerBackgroundTabDetection","registerInteractionListener","registerInpInteractionListener","instrumentOutgoingRequests","spanOptions","span","getActiveSpan","metaName","metaTag","getDomElement","inflightInteractionTransaction","registerInteractionTransaction","op","currentTransaction","getActiveTransaction","getSource","type","isPerformanceEventTiming","entry","MAX_INTERACTIONS","handleEntries","entries","getClient","replay","replayId","activeTransaction","currentScope","getCurrentScope","user","interactionId","existingInteraction","duration","startTime","keys","minInteractionId","a","b","key","interaction","routeName","parentContext","addPerformanceInstrumentationHandler","sourceFromAttributes","sourceFromData","sourceFromMetadata","init_esm_shims","shouldDisableAutoInstrumentation","getCurrentHub","clientOptions","_optionalChain","_","_2","_3","_4","_5","_6","Express","_Express","options","_","getCurrentHub","DEBUG_BUILD","logger","shouldDisableAutoInstrumentation","instrumentMiddlewares","instrumentRouter","wrap","fn","method","arity","req","res","transaction","span","next","_optionalChain","_2","_3","args","_4","_5","err","_6","_7","_8","_9","wrapMiddlewareArgs","arg","a","patchMiddleware","router","originalCallback","methods","appOrRouter","isApp","routerProto","originalProcessParams","layer","called","done","layerRoutePath","isRegex","isArray","numExtraSegments","getLayerRoutePathInfo","partialRoute","preventDuplicateSegments","finalPartialRoute","segment","urlLength","getNumberOfUrlSegments","stripUrlQueryAndFragment","routeLength","attributes","spanToJSON","SEMANTIC_ATTRIBUTE_SENTRY_SOURCE","finalRoute","name","source","extractPathForTransaction","extractOriginalRoute","path","regexp","keys","_10","_11","orderedKeys","b","execResult","paramIndices","resultPath","indexShift","item","index","startOffset","endOffset","substr1","replacement","substr2","lrp","_12","_13","isRegExp","major","GLOBAL_OBJ","getNumberOfArrayUrlSegments","getLayerRoutePathString","routesArray","accNumSegments","currentRoute","r","originalUrl","reconstructedRoute","layerPath","normalizeURL","originalUrlSplit","_14","_15","_16","_17","v","tempCounter","currentOffset","_18","_19","_20","_21","_22","_23","_24","_25","_26","_27","_28","_29","Postgres","_Postgres","options","loadModule","_","getCurrentHub","shouldDisableAutoInstrumentation","DEBUG_BUILD","logger","pkg","Client","_optionalChain","_2","_3","fill","orig","config","values","callback","parentSpan","data","span","_4","_5","err","result","_6","_7","_8","_9","rv","isThenable","res","_10","_11","_12","_13","Mysql","_Mysql","loadModule","_","getCurrentHub","shouldDisableAutoInstrumentation","DEBUG_BUILD","logger","pkg","mySqlConfig","wrappingTarget","thisArg","args","spanDataFromConfig","finishSpan","span","data","key","fill","orig","options","values","callback","parentSpan","_optionalChain","_2","_3","err","result","fields","query","OPERATIONS","OPERATION_SIGNATURES","isCursor","maybeCursor","Mongo","_Mongo","options","moduleName","loadModule","_","getCurrentHub","shouldDisableAutoInstrumentation","DEBUG_BUILD","logger","pkg","collection","operations","operation","getSpanContext","fill","orig","args","lastArg","hub","scope","client","parentSpan","sendDefaultPii","_optionalChain","_2","_3","_4","span","_5","_6","maybePromiseOrCursor","isThenable","res","_7","_8","cursor","_9","_10","_11","_12","_13","_14","_15","_16","err","result","_17","_18","data","spanContext","signature","shouldDescribe","map","reduce","i","isValidPrismaClient","possibleClient","Prisma","_Prisma","options","addNonEnumerableProperty","clientData","engineConfig","activeProvider","clientVersion","params","next","shouldDisableAutoInstrumentation","getCurrentHub","action","model","startSpan","SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN","DEBUG_BUILD","logger","GraphQL","_GraphQL","loadModule","_","getCurrentHub","shouldDisableAutoInstrumentation","DEBUG_BUILD","logger","pkg","fill","orig","args","scope","parentSpan","span","_optionalChain","_2","_3","_4","_5","rv","isThenable","res","_6","_7","_8","_9","_10","_11","_12","_13","Apollo","_Apollo","options","loadModule","_","getCurrentHub","shouldDisableAutoInstrumentation","DEBUG_BUILD","logger","pkg","fill","orig","args","resolvers","arrayify","instrumentResolvers","model","resolverGroupName","resolverName","wrapResolver","parentSpan","span","_optionalChain","_2","_3","rv","isThenable","res","_4","_5","_6","_7","INTEGRATION_NAME","_captureConsoleIntegration","options","levels","CONSOLE_LEVELS","client","GLOBAL_OBJ","addConsoleInstrumentationHandler","args","level","getClient","consoleHandler","captureConsoleIntegration","CaptureConsole","convertIntegrationFnToClass","captureContext","severityLevelFromString","withScope","scope","event","addExceptionMechanism","message","safeJoin","captureMessage","error","arg","captureException","INTEGRATION_NAME","_debugIntegration","options","_options","client","event","hint","consoleSandbox","debugIntegration","Debug","convertIntegrationFnToClass","init_esm_shims","DEBUG_BUILD","INTEGRATION_NAME","_dedupeIntegration","previousEvent","currentEvent","_shouldDropEvent","DEBUG_BUILD","logger","dedupeIntegration","Dedupe","convertIntegrationFnToClass","_isSameMessageEvent","_isSameExceptionEvent","currentMessage","previousMessage","_isSameFingerprint","_isSameStacktrace","previousException","_getExceptionFromEvent","currentException","currentFrames","_getFramesFromEvent","previousFrames","frameA","frameB","currentFingerprint","previousFingerprint","event","exception","INTEGRATION_NAME","_extraErrorDataIntegration","options","depth","captureErrorCause","event","hint","_enhanceEventWithErrorData","extraErrorDataIntegration","ExtraErrorData","convertIntegrationFnToClass","isError","exceptionName","errorData","_extractErrorData","contexts","normalizedErrorData","normalize","isPlainObject","addNonEnumerableProperty","error","nativeKeys","extraErrorInfo","key","value","serializedError","oO","DEBUG_BUILD","logger","WINDOW","GLOBAL_OBJ","INTEGRATION_NAME","SETUP_CLIENTS","_reportingObserverIntegration","options","types","handler","reports","getClient","report","withScope","scope","label","details","plainBody","prop","body","captureMessage","supportsReportingObserver","client","reportingObserverIntegration","ReportingObserver","convertIntegrationFnToClass","INTEGRATION_NAME","_rewriteFramesIntegration","options","root","prefix","iteratee","frame","isWindowsFrame","startsWithSlash","filename","base","relative","basename","_processExceptionsEvent","event","value","_processStacktrace","stacktrace","f","originalEvent","processedEvent","rewriteFramesIntegration","RewriteFrames","convertIntegrationFnToClass","INTEGRATION_NAME","_sessionTimingIntegration","startTime","event","now","sessionTimingIntegration","SessionTiming","convertIntegrationFnToClass","INTEGRATION_NAME","_httpClientIntegration","options","_options","client","_wrapFetch","_wrapXHR","httpClientIntegration","HttpClient","convertIntegrationFnToClass","_fetchResponseHandler","requestInfo","response","requestInit","_shouldCaptureResponse","request","_getRequest","requestHeaders","responseHeaders","requestCookies","responseCookies","_shouldSendDefaultPii","cookieHeader","obj","headers","_extractFetchHeaders","cookies","cookieString","_parseCookieString","DEBUG_BUILD","logger","event","_createEvent","captureEvent","_xhrResponseHandler","xhr","method","_getXHRResponseHeaders","_getResponseSizeFromHeaders","contentLength","acc","cookie","key","value","result","line","_isInGivenRequestTargets","failedRequestTargets","target","givenRequestTarget","_isInGivenStatusRanges","failedRequestStatusCodes","status","range","supportsNativeFetch","addFetchInstrumentationHandler","handlerData","getClient","args","GLOBAL_OBJ","addXhrInstrumentationHandler","sentryXhrData","SENTRY_XHR_DATA_KEY","e","url","isSentryRequestUrl","data","message","addExceptionMechanism","WINDOW","GLOBAL_OBJ","DEFAULT_LINES_OF_CONTEXT","INTEGRATION_NAME","_contextLinesIntegration","options","contextLines","event","addSourceContext","contextLinesIntegration","ContextLines","convertIntegrationFnToClass","doc","htmlFilename","stripUrlQueryAndFragment","exceptions","html","htmlLines","exception","stacktrace","frame","applySourceContextToFrame","linesOfContext","addContextToFrame","init_esm_shims"]}