@sentry/browser 11.0.0-beta.2 → 11.0.0-rc.0
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.
- package/build/npm/cjs/dev/index.js +1 -0
- package/build/npm/cjs/dev/index.js.map +1 -1
- package/build/npm/cjs/dev/integrations/breadcrumbs.js +0 -32
- package/build/npm/cjs/dev/integrations/breadcrumbs.js.map +1 -1
- package/build/npm/cjs/dev/integrations/contextlines.js +1 -1
- package/build/npm/cjs/dev/integrations/contextlines.js.map +1 -1
- package/build/npm/cjs/dev/integrations/httpcontext.js +2 -1
- package/build/npm/cjs/dev/integrations/httpcontext.js.map +1 -1
- package/build/npm/cjs/dev/integrations/webVitals.js +15 -4
- package/build/npm/cjs/dev/integrations/webVitals.js.map +1 -1
- package/build/npm/cjs/dev/sdk.js +1 -0
- package/build/npm/cjs/dev/sdk.js.map +1 -1
- package/build/npm/cjs/dev/tracing/browserTracingIntegration.js +51 -7
- package/build/npm/cjs/dev/tracing/browserTracingIntegration.js.map +1 -1
- package/build/npm/cjs/dev/tracing/linkedTraces.js.map +1 -1
- package/build/npm/cjs/prod/index.js +1 -0
- package/build/npm/cjs/prod/index.js.map +1 -1
- package/build/npm/cjs/prod/integrations/breadcrumbs.js +0 -32
- package/build/npm/cjs/prod/integrations/breadcrumbs.js.map +1 -1
- package/build/npm/cjs/prod/integrations/contextlines.js +1 -1
- package/build/npm/cjs/prod/integrations/contextlines.js.map +1 -1
- package/build/npm/cjs/prod/integrations/httpcontext.js +2 -1
- package/build/npm/cjs/prod/integrations/httpcontext.js.map +1 -1
- package/build/npm/cjs/prod/integrations/webVitals.js +15 -4
- package/build/npm/cjs/prod/integrations/webVitals.js.map +1 -1
- package/build/npm/cjs/prod/sdk.js +1 -0
- package/build/npm/cjs/prod/sdk.js.map +1 -1
- package/build/npm/cjs/prod/tracing/browserTracingIntegration.js +51 -7
- package/build/npm/cjs/prod/tracing/browserTracingIntegration.js.map +1 -1
- package/build/npm/cjs/prod/tracing/linkedTraces.js.map +1 -1
- package/build/npm/esm/dev/index.js +1 -1
- package/build/npm/esm/dev/integrations/breadcrumbs.js +1 -33
- package/build/npm/esm/dev/integrations/breadcrumbs.js.map +1 -1
- package/build/npm/esm/dev/integrations/contextlines.js +1 -1
- package/build/npm/esm/dev/integrations/contextlines.js.map +1 -1
- package/build/npm/esm/dev/integrations/httpcontext.js +2 -1
- package/build/npm/esm/dev/integrations/httpcontext.js.map +1 -1
- package/build/npm/esm/dev/integrations/webVitals.js +16 -5
- package/build/npm/esm/dev/integrations/webVitals.js.map +1 -1
- package/build/npm/esm/dev/package.json +1 -1
- package/build/npm/esm/dev/sdk.js +2 -1
- package/build/npm/esm/dev/sdk.js.map +1 -1
- package/build/npm/esm/dev/tracing/browserTracingIntegration.js +53 -9
- package/build/npm/esm/dev/tracing/browserTracingIntegration.js.map +1 -1
- package/build/npm/esm/dev/tracing/linkedTraces.js.map +1 -1
- package/build/npm/esm/prod/index.js +1 -1
- package/build/npm/esm/prod/integrations/breadcrumbs.js +1 -33
- package/build/npm/esm/prod/integrations/breadcrumbs.js.map +1 -1
- package/build/npm/esm/prod/integrations/contextlines.js +1 -1
- package/build/npm/esm/prod/integrations/contextlines.js.map +1 -1
- package/build/npm/esm/prod/integrations/httpcontext.js +2 -1
- package/build/npm/esm/prod/integrations/httpcontext.js.map +1 -1
- package/build/npm/esm/prod/integrations/webVitals.js +16 -5
- package/build/npm/esm/prod/integrations/webVitals.js.map +1 -1
- package/build/npm/esm/prod/package.json +1 -1
- package/build/npm/esm/prod/sdk.js +2 -1
- package/build/npm/esm/prod/sdk.js.map +1 -1
- package/build/npm/esm/prod/tracing/browserTracingIntegration.js +53 -9
- package/build/npm/esm/prod/tracing/browserTracingIntegration.js.map +1 -1
- package/build/npm/esm/prod/tracing/linkedTraces.js.map +1 -1
- package/build/npm/types/exports.d.ts +1 -1
- package/build/npm/types/exports.d.ts.map +1 -1
- package/build/npm/types/integrations/breadcrumbs.d.ts +0 -1
- package/build/npm/types/integrations/breadcrumbs.d.ts.map +1 -1
- package/build/npm/types/integrations/contextlines.d.ts +1 -1
- package/build/npm/types/integrations/contextlines.d.ts.map +1 -1
- package/build/npm/types/integrations/httpcontext.d.ts.map +1 -1
- package/build/npm/types/integrations/webVitals.d.ts +35 -0
- package/build/npm/types/integrations/webVitals.d.ts.map +1 -1
- package/build/npm/types/sdk.d.ts.map +1 -1
- package/build/npm/types/tracing/browserTracingIntegration.d.ts +20 -0
- package/build/npm/types/tracing/browserTracingIntegration.d.ts.map +1 -1
- package/build/npm/types/tracing/linkedTraces.d.ts.map +1 -1
- package/package.json +8 -8
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"browserTracingIntegration.js","sources":["../../../../../src/tracing/browserTracingIntegration.ts"],"sourcesContent":["/* eslint-disable max-lines */\nimport type { Client, IntegrationFn, RequestHookInfo, ResponseHookInfo, Span, StartSpanOptions } from '@sentry/core';\nimport {\n addNonEnumerableProperty,\n consoleSandbox,\n dateTimestampInSeconds,\n debug,\n generateSpanId,\n generateTraceId,\n getClient,\n getCurrentScope,\n getDynamicSamplingContextFromSpan,\n GLOBAL_OBJ,\n hasSpansEnabled,\n hasSpanStreamingEnabled,\n NAVIGATION_SPAN_NAME_FALLBACK,\n PAGELOAD_SPAN_NAME_FALLBACK,\n isURLObjectRelative,\n parseStringToURLObject,\n propagationContextFromHeaders,\n registerSpanErrorInstrumentation,\n SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n spanIsSampled,\n spanToJSON,\n timestampInSeconds,\n TRACING_DEFAULTS,\n browserPerformanceTimeOrigin,\n} from '@sentry/core';\nimport { _INTERNAL_ensureBrowserSpanStreaming, startIdleSpan, startInactiveSpan } from '@sentry/core/browser';\nimport {\n addHistoryInstrumentationHandler,\n addPerformanceEntries,\n getLocationHref,\n isBotUserAgent,\n startTrackingLongAnimationFrames,\n startTrackingLongTasks,\n} from '@sentry/browser-utils';\nimport { DEBUG_BUILD } from '../debug-build';\nimport { filterCollectedUrl } from '@sentry/core';\nimport { getHttpRequestData, WINDOW } from '../helpers';\nimport { WEB_VITALS_INTEGRATION_NAME, webVitalsIntegration } from '../integrations/webVitals';\nimport { registerBackgroundTabDetection } from './backgroundtab';\nimport { linkTraces } from './linkedTraces';\nimport { defaultRequestInstrumentationOptions, instrumentOutgoingRequests } from './request';\nimport { SENTRY_SEGMENT_NAME_SOURCE, SENTRY_OP, URL_FULL, URL_PATH } from '@sentry/conventions/attributes';\nimport { NAVIGATION, NAVIGATION_REDIRECT, PAGELOAD } from '@sentry/conventions/op';\n\nexport const BROWSER_TRACING_INTEGRATION_ID = 'BrowserTracing';\n\n/** Options for Browser Tracing integration */\nexport interface BrowserTracingOptions {\n /**\n * The time that has to pass without any span being created.\n * If this time is exceeded, the idle span will finish.\n *\n * Default: 1000 (ms)\n */\n idleTimeout: number;\n\n /**\n * The max. time an idle span may run.\n * If this time is exceeded, the idle span will finish no matter what.\n *\n * Default: 30000 (ms)\n */\n finalTimeout: number;\n\n /**\n The max. time an idle span may run.\n * If this time is exceeded, the idle span will finish no matter what.\n *\n * Default: 15000 (ms)\n */\n childSpanTimeout: 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 long animation frames and add them to the corresponding transaction.\n *\n * Default: false\n */\n enableLongAnimationFrame: boolean;\n\n /**\n * If true, Sentry will capture first input delay and add it to the corresponding transaction.\n *\n * Default: true\n */\n enableInp: boolean;\n\n /**\n * @deprecated This option is no longer used. Element timing is now tracked via the standalone\n * `elementTimingIntegration`. Add it to your `integrations` array to collect element timing metrics.\n */\n enableElementTiming?: boolean;\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 * Resource spans with `op`s matching strings in the array will not be emitted.\n *\n * Default: []\n */\n ignoreResourceSpans: Array<'resource.script' | 'resource.css' | 'resource.img' | 'resource.other' | string>;\n\n /**\n * By default, the SDK will try to detect redirects and avoid creating separate spans for them.\n * If you want to opt-out of this behavior, you can set this option to `false`.\n *\n * Default: true\n */\n detectRedirects: boolean;\n\n /**\n * Link the currently started trace to a previous trace (e.g. a prior pageload, navigation or\n * manually started span). When enabled, this option will allow you to navigate between traces\n * in the Sentry UI.\n *\n * You can set this option to the following values:\n *\n * - `'in-memory'`: The previous trace data will be stored in memory.\n * This is useful for single-page applications and enabled by default.\n *\n * - `'session-storage'`: The previous trace data will be stored in the `sessionStorage`.\n * This is useful for multi-page applications or static sites but it means that the\n * Sentry SDK writes to the browser's `sessionStorage`.\n *\n * - `'off'`: The previous trace data will not be stored or linked.\n *\n * You can also use {@link BrowserTracingOptions.consistentTraceSampling} to get\n * consistent trace sampling of subsequent traces. Otherwise, by default, your\n * `tracesSampleRate` or `tracesSampler` config significantly influences how often\n * traces will be linked.\n *\n * @default 'in-memory' - see explanation above\n */\n linkPreviousTrace: 'in-memory' | 'session-storage' | 'off';\n\n /**\n * If true, Sentry will consistently sample subsequent traces based on the\n * sampling decision of the initial trace. For example, if the initial page\n * load trace was sampled positively, all subsequent traces (e.g. navigations)\n * are also sampled positively. In case the initial trace was sampled negatively,\n * all subsequent traces are also sampled negatively.\n *\n * This option allows you to get consistent, linked traces within a user journey\n * while maintaining an overall quota based on your trace sampling settings.\n *\n * This option is only effective if {@link BrowserTracingOptions.linkPreviousTrace}\n * is enabled (i.e. not set to `'off'`).\n *\n * @default `false` - this is an opt-in feature.\n */\n consistentTraceSampling: boolean;\n\n /**\n * If set to `true`, the pageload span will not end itself automatically, unless it\n * runs until the {@link BrowserTracingOptions.finalTimeout} (30 seconds by default) is reached.\n *\n * Set this option to `true`, if you want full control over the pageload span duration.\n * You can use `Sentry.reportPageLoaded()` to manually end the pageload span whenever convenient.\n * Be aware that you have to ensure that this is always called, regardless of the chosen route\n * or path in the application.\n *\n * @default `false`. By default, the pageload span will end itself automatically, based on\n * the {@link BrowserTracingOptions.finalTimeout}, {@link BrowserTracingOptions.idleTimeout}\n * and {@link BrowserTracingOptions.childSpanTimeout}. This is more convenient to use but means\n * that the pageload duration can be arbitrary and might not be fully representative of a perceived\n * page load time.\n */\n enableReportPageLoaded: boolean;\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 /**\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 /**\n * This callback is invoked directly after a span is started for an outgoing fetch or XHR request.\n * You can use it to annotate the span with additional data or attributes, for example by setting\n * attributes based on the passed request headers.\n */\n onRequestSpanStart?(span: Span, requestInformation: RequestHookInfo): void;\n\n /**\n * Is called when spans end for outgoing requests, providing access to response headers.\n */\n onRequestSpanEnd?(span: Span, responseInformation: ResponseHookInfo): void;\n}\n\nconst DEFAULT_BROWSER_TRACING_OPTIONS: BrowserTracingOptions = {\n ...TRACING_DEFAULTS,\n instrumentNavigation: true,\n instrumentPageLoad: true,\n markBackgroundSpan: true,\n enableLongTask: true,\n enableLongAnimationFrame: true,\n enableInp: true,\n ignoreResourceSpans: [],\n detectRedirects: true,\n linkPreviousTrace: 'in-memory',\n consistentTraceSampling: false,\n enableReportPageLoaded: false,\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.\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 if ('enableElementTiming' in options) {\n consoleSandbox(() => {\n // oxlint-disable-next-line no-console\n console.warn(\n '[Sentry] `enableElementTiming` is deprecated and no longer has any effect. Use the standalone `elementTimingIntegration` instead.',\n );\n });\n }\n\n /**\n * This is just a small wrapper that makes `document` optional.\n * We want to be extra-safe and always check that this exists, to ensure weird environments do not blow up.\n */\n const optionalWindowDocument = WINDOW.document as (typeof WINDOW)['document'] | undefined;\n\n const {\n enableInp,\n enableLongTask,\n enableLongAnimationFrame,\n beforeStartSpan,\n idleTimeout,\n finalTimeout,\n childSpanTimeout,\n markBackgroundSpan,\n traceFetch,\n traceXHR,\n shouldCreateSpanForRequest,\n enableHTTPTimings,\n ignoreResourceSpans,\n instrumentPageLoad,\n instrumentNavigation,\n detectRedirects,\n linkPreviousTrace,\n consistentTraceSampling,\n enableReportPageLoaded,\n onRequestSpanStart,\n onRequestSpanEnd,\n } = {\n ...DEFAULT_BROWSER_TRACING_OPTIONS,\n ...options,\n };\n\n const _isBot = isBotUserAgent();\n\n let lastInteractionTimestamp: number | undefined;\n\n let _pageloadSpan: Span | undefined;\n\n /** Create routing idle transaction. */\n function _createRouteSpan(client: Client, startSpanOptions: StartSpanOptions, makeActive = true, url?: string): void {\n const isPageloadSpan = startSpanOptions.op === 'pageload';\n\n const initialSpanName = startSpanOptions.name;\n const finalStartSpanOptions: StartSpanOptions = beforeStartSpan\n ? beforeStartSpan(startSpanOptions)\n : startSpanOptions;\n\n // For navigations, `url` is the destination URL, so we use it to reflect the post-navigation location.\n // For pageloads (and manual navigation spans without a URL) we fall back to the current location.\n const urlObject = parseStringToURLObject(url || getLocationHref());\n\n const attributes = {\n ...(urlObject?.pathname && { [URL_PATH]: urlObject.pathname }),\n ...(urlObject && !isURLObjectRelative(urlObject) && { [URL_FULL]: filterCollectedUrl(urlObject.href) }),\n ...finalStartSpanOptions.attributes,\n };\n\n // If `finalStartSpanOptions.name` is different than `startSpanOptions.name`\n // it is because `beforeStartSpan` set a custom name. Therefore we set the source to 'custom'.\n if (initialSpanName !== finalStartSpanOptions.name) {\n attributes[SENTRY_SEGMENT_NAME_SOURCE] = 'custom';\n }\n\n finalStartSpanOptions.attributes = attributes;\n\n if (!makeActive) {\n // We want to ensure this has 0s duration\n const now = dateTimestampInSeconds();\n startInactiveSpan({\n ...finalStartSpanOptions,\n startTime: now,\n }).end(now);\n return;\n }\n\n const idleSpan = startIdleSpan(finalStartSpanOptions, {\n idleTimeout,\n finalTimeout,\n childSpanTimeout,\n // should wait for finish signal if it's a pageload transaction\n disableAutoFinish: isPageloadSpan,\n trimIdleSpanEndTimestamp: !enableReportPageLoaded,\n });\n\n if (isPageloadSpan && enableReportPageLoaded) {\n _pageloadSpan = idleSpan;\n }\n\n setActiveIdleSpan(client, idleSpan);\n\n function emitFinish(): void {\n if (optionalWindowDocument && ['interactive', 'complete'].includes(optionalWindowDocument.readyState)) {\n client.emit('idleSpanEnableAutoFinish', idleSpan);\n // Once the finish signal has been emitted, the listener is no longer needed. Removing it here (rather than\n // relying on `{ once: true }`) also covers the common case where the document is already loaded when the span\n // starts, so the listener never fires and would otherwise leak together with the `idleSpan` it closes over.\n optionalWindowDocument.removeEventListener('readystatechange', emitFinish);\n }\n }\n\n // Enable auto finish of the pageload span if users are not explicitly ending it\n if (isPageloadSpan && !enableReportPageLoaded && optionalWindowDocument) {\n optionalWindowDocument.addEventListener('readystatechange', emitFinish);\n\n emitFinish();\n }\n }\n\n return {\n name: BROWSER_TRACING_INTEGRATION_ID,\n setup(client) {\n if (_isBot) {\n DEBUG_BUILD && debug.log('[Tracing] Skipping browserTracingIntegration setup for bot user agent.');\n return;\n }\n\n registerSpanErrorInstrumentation();\n\n if (\n enableLongAnimationFrame &&\n GLOBAL_OBJ.PerformanceObserver &&\n PerformanceObserver.supportedEntryTypes?.includes('long-animation-frame')\n ) {\n startTrackingLongAnimationFrames();\n } else if (enableLongTask) {\n startTrackingLongTasks();\n }\n\n if (detectRedirects && optionalWindowDocument) {\n const interactionHandler = (): void => {\n lastInteractionTimestamp = timestampInSeconds();\n };\n addEventListener('click', interactionHandler, { capture: true });\n addEventListener('keydown', interactionHandler, { capture: true, passive: true });\n }\n\n function maybeEndActiveSpan(): void {\n const activeSpan = getActiveIdleSpan(client);\n\n if (activeSpan && !spanToJSON(activeSpan).end_timestamp) {\n DEBUG_BUILD &&\n debug.log(\n `[Tracing] Finishing current active span with op: ${spanToJSON(activeSpan).attributes[SENTRY_OP]}`,\n );\n // If there's an open active span, we need to finish it before creating an new one.\n activeSpan.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON, 'cancelled');\n activeSpan.end();\n }\n }\n\n client.on('beforeIdleSpanEnd', span => {\n // Interaction idle spans also flow through this hook, but the route bookkeeping below only\n // applies to the pageload/navigation span. We identify it by reference rather than by op:\n // only the route span is registered as the active idle span.\n if (getActiveIdleSpan(client) !== span) {\n return;\n }\n\n addPerformanceEntries(span, {\n ignoreResourceSpans,\n spanStreamingEnabled: hasSpanStreamingEnabled(client),\n });\n setActiveIdleSpan(client, undefined);\n\n // A trace should stay consistent over the entire timespan of one route - even after the pageload/navigation ended.\n // Only when another navigation happens, we want to create a new trace.\n // This way, e.g. errors that occur after the pageload span ended are still associated to the pageload trace.\n const scope = getCurrentScope();\n const oldPropagationContext = scope.getPropagationContext();\n\n scope.setPropagationContext({\n ...oldPropagationContext,\n traceId: span.spanContext().traceId,\n sampled: spanIsSampled(span),\n dsc: getDynamicSamplingContextFromSpan(span),\n });\n\n if (_pageloadSpan === span) {\n // clean up the stored pageload span on the integration.\n _pageloadSpan = undefined;\n }\n });\n\n client.on('startNavigationSpan', (startSpanOptions, navigationOptions) => {\n if (getClient() !== client) {\n return;\n }\n\n if (navigationOptions?.isRedirect) {\n DEBUG_BUILD &&\n debug.warn('[Tracing] Detected redirect, navigation span will not be the root span, but a child span.');\n _createRouteSpan(\n client,\n {\n op: NAVIGATION_REDIRECT,\n ...startSpanOptions,\n },\n false,\n navigationOptions.url,\n );\n return;\n }\n\n // Reset the last interaction timestamp since we now start a new navigation.\n // Any subsequent navigation span starts could again be a redirect, so we\n // should reset our heuristic detectors.\n lastInteractionTimestamp = undefined;\n\n maybeEndActiveSpan();\n\n const scope = getCurrentScope();\n scope.setPropagationContext({\n traceId: generateTraceId(),\n sampleRand: Math.random(),\n propagationSpanId: hasSpansEnabled() ? undefined : generateSpanId(),\n });\n\n // We reset this to ensure we do not have lingering incorrect data here\n // places that call this hook may set this where appropriate - else, the URL at span sending time is used\n scope.setSDKProcessingMetadata({\n normalizedRequest: undefined,\n });\n\n _createRouteSpan(\n client,\n {\n op: NAVIGATION,\n ...startSpanOptions,\n // Navigation starts a new trace and is NOT parented under any active interaction (e.g. ui.action.click)\n parentSpan: null,\n },\n true,\n navigationOptions?.url,\n );\n });\n\n client.on('startPageLoadSpan', (startSpanOptions, traceOptions = {}) => {\n if (getClient() !== client) {\n return;\n }\n maybeEndActiveSpan();\n\n const sentryTrace =\n traceOptions.sentryTrace || getMetaContent('sentry-trace') || getServerTiming('sentry-trace');\n const baggage = traceOptions.baggage || getMetaContent('baggage') || getServerTiming('baggage');\n\n const propagationContext = propagationContextFromHeaders(sentryTrace, baggage);\n\n const scope = getCurrentScope();\n scope.setPropagationContext(propagationContext);\n if (!hasSpansEnabled()) {\n // for browser, we wanna keep the spanIds consistent during the entire lifetime of the trace\n // this works by setting the propagationSpanId to a random spanId so that we have a consistent\n // span id to propagate in TwP mode (!hasSpansEnabled())\n scope.getPropagationContext().propagationSpanId = generateSpanId();\n }\n\n // We store the normalized request data on the scope, so we get the request data at time of span creation\n // otherwise, the URL etc. may already be of the following navigation, and we'd report the wrong URL\n scope.setSDKProcessingMetadata({\n normalizedRequest: getHttpRequestData(),\n });\n\n _createRouteSpan(client, {\n op: PAGELOAD,\n ...startSpanOptions,\n });\n });\n\n client.on('endPageloadSpan', () => {\n if (enableReportPageLoaded && _pageloadSpan) {\n _pageloadSpan.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON, 'reportPageLoaded');\n _pageloadSpan.end();\n }\n });\n },\n\n afterAllSetup(client) {\n if (_isBot) {\n return;\n }\n\n // Technically, every startSpan call already ensures that `spanStreamingIntegration` is installed,\n // but we do it here anyway for the edge case that users disabled pageload and navigation spans and\n // purely rely on manual startSpan calls.\n _INTERNAL_ensureBrowserSpanStreaming(client);\n\n // Auto-register webVitalsIntegration if the user hasn't added one. We do this in\n // afterAllSetup so that a user-provided webVitalsIntegration - which may be ordered after\n // browserTracingIntegration in the integrations array - has already been installed.\n if (client.addIntegration && !client.getIntegrationByName?.(WEB_VITALS_INTEGRATION_NAME)) {\n client.addIntegration(\n webVitalsIntegration({\n ignore: enableInp ? [] : ['inp'],\n }),\n );\n }\n\n let startingUrl: string | undefined = getLocationHref();\n\n if (linkPreviousTrace !== 'off') {\n linkTraces(client, { linkPreviousTrace, consistentTraceSampling });\n }\n\n if (WINDOW.location) {\n if (instrumentPageLoad) {\n startBrowserTracingPageLoadSpan(client, {\n // With span streaming, span names have to be low cardinality, and there is no route\n // information available here.\n name: hasSpanStreamingEnabled(client) ? PAGELOAD_SPAN_NAME_FALLBACK : WINDOW.location.pathname,\n attributes: {\n [SENTRY_SEGMENT_NAME_SOURCE]: 'url',\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.pageload.browser',\n },\n });\n }\n\n if (instrumentNavigation) {\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?.indexOf(to) !== -1) {\n startingUrl = undefined;\n return;\n }\n\n startingUrl = undefined;\n const parsed = parseStringToURLObject(to);\n const activeSpan = getActiveIdleSpan(client);\n const navigationIsRedirect =\n activeSpan && detectRedirects && isRedirect(activeSpan, lastInteractionTimestamp);\n\n startBrowserTracingNavigationSpan(\n client,\n {\n // With span streaming, span names have to be low cardinality, and there is no route\n // information available here.\n name: hasSpanStreamingEnabled(client)\n ? NAVIGATION_SPAN_NAME_FALLBACK\n : parsed?.pathname || WINDOW.location.pathname,\n attributes: {\n [SENTRY_SEGMENT_NAME_SOURCE]: 'url',\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.navigation.browser',\n },\n },\n { url: to, isRedirect: navigationIsRedirect },\n );\n });\n }\n }\n\n if (markBackgroundSpan) {\n registerBackgroundTabDetection();\n }\n\n instrumentOutgoingRequests(client, {\n traceFetch,\n traceXHR,\n tracePropagationTargets: client.getOptions().tracePropagationTargets,\n shouldCreateSpanForRequest,\n enableHTTPTimings,\n onRequestSpanStart,\n onRequestSpanEnd,\n });\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Manually start a page load span.\n * This will only do something if a browser tracing integration integration has been setup.\n *\n * If you provide a custom `traceOptions` object, it will be used to continue the trace\n * instead of the default behavior, which is to look it up on the <meta> tags.\n */\nexport function startBrowserTracingPageLoadSpan(\n client: Client,\n spanOptions: StartSpanOptions,\n traceOptions?: { sentryTrace?: string | undefined; baggage?: string | undefined },\n): Span | undefined {\n // `Pageload` is a low-cardinality span name, not a description of the page. The scope's\n // transaction name is what error events are grouped by, so it keeps the URL instead.\n const isFallbackSpanName = spanOptions.name === PAGELOAD_SPAN_NAME_FALLBACK;\n getCurrentScope().setTransactionName(isFallbackSpanName ? WINDOW.location?.pathname : spanOptions.name);\n // A pageload span always covers the entire page load, no matter how late the SDK or a routing\n // instrumentation gets around to starting it. Everything that happened before (DNS, TLS, TTFB,\n // HTML parsing, chunk loading) is part of the page load and the performance child spans we attach\n // later are anchored at the time origin anyway.\n const timeOrigin = browserPerformanceTimeOrigin();\n const pageloadSpanOptions: StartSpanOptions = {\n ...spanOptions,\n // startTime needs to be in seconds, not ms\n startTime: spanOptions.startTime ?? (timeOrigin ? timeOrigin / 1000 : undefined),\n };\n\n client.emit('startPageLoadSpan', pageloadSpanOptions, traceOptions);\n\n const pageloadSpan = getActiveIdleSpan(client);\n\n if (pageloadSpan) {\n client.emit('afterStartPageLoadSpan', pageloadSpan);\n }\n\n return pageloadSpan;\n}\n\n/**\n * Manually start a navigation span.\n * This will only do something if a browser tracing integration has been setup.\n */\nexport function startBrowserTracingNavigationSpan(\n client: Client,\n spanOptions: StartSpanOptions,\n options?: { url?: string; isRedirect?: boolean },\n): Span | undefined {\n const { url, isRedirect } = options || {};\n client.emit('beforeStartNavigationSpan', spanOptions, { isRedirect, url });\n client.emit('startNavigationSpan', spanOptions, { isRedirect, url });\n\n const scope = getCurrentScope();\n // `Navigation` is a low-cardinality span name, not a description of the page. The scope's\n // transaction name is what error events are grouped by, so it keeps the URL instead. `url` is the\n // destination, while `location` still points at the previous page during a `pushState`.\n const isFallbackSpanName = spanOptions.name === NAVIGATION_SPAN_NAME_FALLBACK;\n scope.setTransactionName(\n isFallbackSpanName ? (url && parseStringToURLObject(url)?.pathname) || WINDOW.location?.pathname : spanOptions.name,\n );\n\n // We store the normalized request data on the scope, so we get the request data at time of span creation\n // otherwise, the URL etc. may already be of the following navigation, and we'd report the wrong URL\n if (url && !isRedirect) {\n scope.setSDKProcessingMetadata({\n normalizedRequest: {\n ...getHttpRequestData(),\n url,\n },\n });\n }\n\n return getActiveIdleSpan(client);\n}\n\n/** Returns the value of a meta tag */\nexport function getMetaContent(metaName: string): string | undefined {\n /**\n * This is just a small wrapper that makes `document` optional.\n * We want to be extra-safe and always check that this exists, to ensure weird environments do not blow up.\n */\n const optionalWindowDocument = WINDOW.document as (typeof WINDOW)['document'] | undefined;\n\n const metaTag = optionalWindowDocument?.querySelector(`meta[name=${metaName}]`);\n return metaTag?.getAttribute('content') || undefined;\n}\n\n/** Returns the description of a server timing entry */\nexport function getServerTiming(name: string): string | undefined {\n // The cast is required for the declaration build (`build:types`), which resolves\n // `getEntriesByType('navigation')` to `PerformanceEntry[]` (no `serverTiming`). It only reads as\n // \"unnecessary\" to the type-aware linter, which runs with web-vitals' global augmentation applied.\n // oxlint-disable-next-line typescript/no-unnecessary-type-assertion\n const navigation = WINDOW.performance?.getEntriesByType?.('navigation')[0] as PerformanceNavigationTiming | undefined;\n const entry = navigation?.serverTiming?.find(entry => entry.name === name);\n return entry?.description;\n}\n\n// We store the active idle span on the client object, so we can access it from exported functions\nconst ACTIVE_IDLE_SPAN_PROPERTY = '_sentry_idleSpan';\nfunction getActiveIdleSpan(client: Client): Span | undefined {\n return (client as { [ACTIVE_IDLE_SPAN_PROPERTY]?: Span })[ACTIVE_IDLE_SPAN_PROPERTY];\n}\n\nfunction setActiveIdleSpan(client: Client, span: Span | undefined): void {\n addNonEnumerableProperty(client, ACTIVE_IDLE_SPAN_PROPERTY, span);\n}\n\n// The max. time in seconds between two pageload/navigation spans that makes us consider the second one a redirect\nconst REDIRECT_THRESHOLD = 1.5;\n\nfunction isRedirect(activeSpan: Span, lastInteractionTimestamp: number | undefined): boolean {\n const spanData = spanToJSON(activeSpan);\n\n const now = dateTimestampInSeconds();\n\n // More than REDIRECT_THRESHOLD seconds since last navigation/pageload span?\n // --> never consider this a redirect\n const startTimestamp = spanData.start_timestamp;\n if (now - startTimestamp > REDIRECT_THRESHOLD) {\n return false;\n }\n\n // A click happened in the last REDIRECT_THRESHOLD seconds?\n // --> never consider this a redirect\n if (lastInteractionTimestamp && now - lastInteractionTimestamp <= REDIRECT_THRESHOLD) {\n return false;\n }\n\n return true;\n}\n"],"names":["TRACING_DEFAULTS","defaultRequestInstrumentationOptions","consoleSandbox","WINDOW","isBotUserAgent","parseStringToURLObject","getLocationHref","attributes","URL_PATH","isURLObjectRelative","URL_FULL","filterCollectedUrl","SENTRY_SEGMENT_NAME_SOURCE","dateTimestampInSeconds","startInactiveSpan","startIdleSpan","DEBUG_BUILD","debug","registerSpanErrorInstrumentation","GLOBAL_OBJ","startTrackingLongAnimationFrames","startTrackingLongTasks","timestampInSeconds","spanToJSON","SENTRY_OP","SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON","addPerformanceEntries","hasSpanStreamingEnabled","getCurrentScope","spanIsSampled","getDynamicSamplingContextFromSpan","getClient","NAVIGATION_REDIRECT","generateTraceId","hasSpansEnabled","generateSpanId","NAVIGATION","propagationContextFromHeaders","getHttpRequestData","PAGELOAD","_INTERNAL_ensureBrowserSpanStreaming","WEB_VITALS_INTEGRATION_NAME","webVitalsIntegration","linkTraces","PAGELOAD_SPAN_NAME_FALLBACK","SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN","addHistoryInstrumentationHandler","NAVIGATION_SPAN_NAME_FALLBACK","registerBackgroundTabDetection","instrumentOutgoingRequests","browserPerformanceTimeOrigin","isRedirect","entry","addNonEnumerableProperty"],"mappings":";;;;;;;;;;;;;;AAgDO,MAAM,8BAAA,GAAiC;AAwM9C,MAAM,+BAAA,GAAyD;AAAA,EAC7D,GAAGA,qBAAA;AAAA,EACH,oBAAA,EAAsB,IAAA;AAAA,EACtB,kBAAA,EAAoB,IAAA;AAAA,EACpB,kBAAA,EAAoB,IAAA;AAAA,EACpB,cAAA,EAAgB,IAAA;AAAA,EAChB,wBAAA,EAA0B,IAAA;AAAA,EAC1B,SAAA,EAAW,IAAA;AAAA,EACX,qBAAqB,EAAC;AAAA,EACtB,eAAA,EAAiB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AAyB,CAAA;AACrF;AAEA,SAAS,iBAAA,CAAkB,QAAgB,IAAA,EAA8B;AACvE,EAAAC,6BAAA,CAAyB,MAAA,EAAQ,2BAA2B,IAAI,CAAA;AAClE;AAGA,MAAM,kBAAA,GAAqB,GAAA;AAE3B,SAAS,UAAA,CAAW,YAAkB,wBAAA,EAAuD;AAC3F,EAAA,MAAM,QAAA,GAAW9B,gBAAW,UAAU,CAAA;AAEtC,EAAA,MAAM,MAAMV,2BAAA,EAAuB;AAInC,EAAA,MAAM,iBAAiB,QAAA,CAAS,eAAA;AAChC,EAAA,IAAI,GAAA,GAAM,iBAAiB,kBAAA,EAAoB;AAC7C,IAAA,OAAO,KAAA;AAAA,EACT;AAIA,EAAA,IAAI,wBAAA,IAA4B,GAAA,GAAM,wBAAA,IAA4B,kBAAA,EAAoB;AACpF,IAAA,OAAO,KAAA;AAAA,EACT;AAEA,EAAA,OAAO,IAAA;AACT;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"browserTracingIntegration.js","sources":["../../../../../src/tracing/browserTracingIntegration.ts"],"sourcesContent":["/* eslint-disable max-lines */\nimport type { Client, IntegrationFn, RequestHookInfo, ResponseHookInfo, Span, StartSpanOptions } from '@sentry/core';\nimport {\n addNonEnumerableProperty,\n consoleSandbox,\n dateTimestampInSeconds,\n debug,\n generateSpanId,\n generateTraceId,\n getClient,\n getCurrentScope,\n getDynamicSamplingContextFromSpan,\n GLOBAL_OBJ,\n hasSpansEnabled,\n hasSpanStreamingEnabled,\n NAVIGATION_SPAN_NAME_FALLBACK,\n PAGELOAD_SPAN_NAME_FALLBACK,\n isURLObjectRelative,\n parseStringToURLObject,\n propagationContextFromHeaders,\n registerSpanErrorInstrumentation,\n spanIsSampled,\n spanToJSON,\n timestampInSeconds,\n TRACING_DEFAULTS,\n browserPerformanceTimeOrigin,\n} from '@sentry/core';\nimport { _INTERNAL_ensureBrowserSpanStreaming, startIdleSpan, startInactiveSpan } from '@sentry/core/browser';\nimport {\n addHistoryInstrumentationHandler,\n addPerformanceEntries,\n getLocationHref,\n isBotUserAgent,\n startTrackingLongAnimationFrames,\n startTrackingLongTasks,\n} from '@sentry/browser-utils';\nimport { BROWSER_NAVIGATION_TYPE } from '@sentry/conventions/attributes';\nimport { DEBUG_BUILD } from '../debug-build';\nimport { filterCollectedUrl } from '@sentry/core';\nimport { getHttpRequestData, WINDOW } from '../helpers';\nimport type { WebVitalsOptions } from '../integrations/webVitals';\nimport { WEB_VITALS_INTEGRATION_NAME, webVitalsIntegration } from '../integrations/webVitals';\nimport { registerBackgroundTabDetection } from './backgroundtab';\nimport { linkTraces } from './linkedTraces';\nimport { defaultRequestInstrumentationOptions, instrumentOutgoingRequests } from './request';\nimport {\n SENTRY_SEGMENT_NAME_SOURCE,\n SENTRY_OP,\n URL_FULL,\n URL_PATH,\n SENTRY_ORIGIN,\n SENTRY_IDLE_SPAN_FINISH_REASON,\n} from '@sentry/conventions/attributes';\nimport { NAVIGATION, NAVIGATION_REDIRECT, PAGELOAD } from '@sentry/conventions/op';\n\nexport const BROWSER_TRACING_INTEGRATION_ID = 'BrowserTracing';\n\n/** Options for Browser Tracing integration */\nexport interface BrowserTracingOptions {\n /**\n * The time that has to pass without any span being created.\n * If this time is exceeded, the idle span will finish.\n *\n * Default: 1000 (ms)\n */\n idleTimeout: number;\n\n /**\n * The max. time an idle span may run.\n * If this time is exceeded, the idle span will finish no matter what.\n *\n * Default: 30000 (ms)\n */\n finalTimeout: number;\n\n /**\n The max. time an idle span may run.\n * If this time is exceeded, the idle span will finish no matter what.\n *\n * Default: 15000 (ms)\n */\n childSpanTimeout: 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 * If a navigation span should be created when the page is restored from the back/forward cache.\n *\n * This is deliberately independent of {@link BrowserTracingOptions.instrumentNavigation}: a restore\n * is not a history change, and the framework integrations that own their own navigation spans turn\n * that option off without ever handling a restore. The point of this span is trace hygiene, keeping\n * everything after the restore off the trace the page had before it was frozen, so it is worth\n * having even where history instrumentation is not.\n *\n * Default: true\n */\n instrumentBfcacheRestore: 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 long animation frames and add them to the corresponding transaction.\n *\n * Default: false\n */\n enableLongAnimationFrame: boolean;\n\n /**\n * If true, Sentry will capture first input delay and add it to the corresponding transaction.\n *\n * Default: true\n *\n * @deprecated Use {@link BrowserTracingOptions.webVitals} instead: `webVitals: { ignore: ['inp'] }`.\n */\n enableInp: boolean;\n\n /**\n * Options for the `webVitalsIntegration` that is auto-registered when none is present.\n * Ignored if you register `webVitalsIntegration` yourself.\n */\n webVitals?: WebVitalsOptions;\n\n /**\n * @deprecated This option is no longer used. Element timing is now tracked via the standalone\n * `elementTimingIntegration`. Add it to your `integrations` array to collect element timing metrics.\n */\n enableElementTiming?: boolean;\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 * Resource spans with `op`s matching strings in the array will not be emitted.\n *\n * Default: []\n */\n ignoreResourceSpans: Array<'resource.script' | 'resource.css' | 'resource.img' | 'resource.other' | string>;\n\n /**\n * By default, the SDK will try to detect redirects and avoid creating separate spans for them.\n * If you want to opt-out of this behavior, you can set this option to `false`.\n *\n * Default: true\n */\n detectRedirects: boolean;\n\n /**\n * Link the currently started trace to a previous trace (e.g. a prior pageload, navigation or\n * manually started span). When enabled, this option will allow you to navigate between traces\n * in the Sentry UI.\n *\n * You can set this option to the following values:\n *\n * - `'in-memory'`: The previous trace data will be stored in memory.\n * This is useful for single-page applications and enabled by default.\n *\n * - `'session-storage'`: The previous trace data will be stored in the `sessionStorage`.\n * This is useful for multi-page applications or static sites but it means that the\n * Sentry SDK writes to the browser's `sessionStorage`.\n *\n * - `'off'`: The previous trace data will not be stored or linked.\n *\n * You can also use {@link BrowserTracingOptions.consistentTraceSampling} to get\n * consistent trace sampling of subsequent traces. Otherwise, by default, your\n * `tracesSampleRate` or `tracesSampler` config significantly influences how often\n * traces will be linked.\n *\n * @default 'in-memory' - see explanation above\n */\n linkPreviousTrace: 'in-memory' | 'session-storage' | 'off';\n\n /**\n * If true, Sentry will consistently sample subsequent traces based on the\n * sampling decision of the initial trace. For example, if the initial page\n * load trace was sampled positively, all subsequent traces (e.g. navigations)\n * are also sampled positively. In case the initial trace was sampled negatively,\n * all subsequent traces are also sampled negatively.\n *\n * This option allows you to get consistent, linked traces within a user journey\n * while maintaining an overall quota based on your trace sampling settings.\n *\n * This option is only effective if {@link BrowserTracingOptions.linkPreviousTrace}\n * is enabled (i.e. not set to `'off'`).\n *\n * @default `false` - this is an opt-in feature.\n */\n consistentTraceSampling: boolean;\n\n /**\n * If set to `true`, the pageload span will not end itself automatically, unless it\n * runs until the {@link BrowserTracingOptions.finalTimeout} (30 seconds by default) is reached.\n *\n * Set this option to `true`, if you want full control over the pageload span duration.\n * You can use `Sentry.reportPageLoaded()` to manually end the pageload span whenever convenient.\n * Be aware that you have to ensure that this is always called, regardless of the chosen route\n * or path in the application.\n *\n * @default `false`. By default, the pageload span will end itself automatically, based on\n * the {@link BrowserTracingOptions.finalTimeout}, {@link BrowserTracingOptions.idleTimeout}\n * and {@link BrowserTracingOptions.childSpanTimeout}. This is more convenient to use but means\n * that the pageload duration can be arbitrary and might not be fully representative of a perceived\n * page load time.\n */\n enableReportPageLoaded: boolean;\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 /**\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 /**\n * This callback is invoked directly after a span is started for an outgoing fetch or XHR request.\n * You can use it to annotate the span with additional data or attributes, for example by setting\n * attributes based on the passed request headers.\n */\n onRequestSpanStart?(span: Span, requestInformation: RequestHookInfo): void;\n\n /**\n * Is called when spans end for outgoing requests, providing access to response headers.\n */\n onRequestSpanEnd?(span: Span, responseInformation: ResponseHookInfo): void;\n}\n\nconst DEFAULT_BROWSER_TRACING_OPTIONS: BrowserTracingOptions = {\n ...TRACING_DEFAULTS,\n instrumentNavigation: true,\n instrumentBfcacheRestore: true,\n instrumentPageLoad: true,\n markBackgroundSpan: true,\n enableLongTask: true,\n enableLongAnimationFrame: true,\n // oxlint-disable-next-line typescript/no-deprecated -- still honoured until it is removed\n enableInp: true,\n ignoreResourceSpans: [],\n detectRedirects: true,\n linkPreviousTrace: 'in-memory',\n consistentTraceSampling: false,\n enableReportPageLoaded: false,\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.\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 if ('enableElementTiming' in options) {\n consoleSandbox(() => {\n // oxlint-disable-next-line no-console\n console.warn(\n '[Sentry] `enableElementTiming` is deprecated and no longer has any effect. Use the standalone `elementTimingIntegration` instead.',\n );\n });\n }\n\n /**\n * This is just a small wrapper that makes `document` optional.\n * We want to be extra-safe and always check that this exists, to ensure weird environments do not blow up.\n */\n const optionalWindowDocument = WINDOW.document as (typeof WINDOW)['document'] | undefined;\n\n const {\n // oxlint-disable-next-line typescript/no-deprecated -- still honoured until it is removed\n enableInp,\n enableLongTask,\n enableLongAnimationFrame,\n webVitals,\n beforeStartSpan,\n idleTimeout,\n finalTimeout,\n childSpanTimeout,\n markBackgroundSpan,\n traceFetch,\n traceXHR,\n shouldCreateSpanForRequest,\n enableHTTPTimings,\n ignoreResourceSpans,\n instrumentPageLoad,\n instrumentNavigation,\n instrumentBfcacheRestore,\n detectRedirects,\n linkPreviousTrace,\n consistentTraceSampling,\n enableReportPageLoaded,\n onRequestSpanStart,\n onRequestSpanEnd,\n } = {\n ...DEFAULT_BROWSER_TRACING_OPTIONS,\n ...options,\n };\n\n const _isBot = isBotUserAgent();\n\n let lastInteractionTimestamp: number | undefined;\n\n let _pageloadSpan: Span | undefined;\n\n /** Create routing idle transaction. */\n function _createRouteSpan(client: Client, startSpanOptions: StartSpanOptions, makeActive = true, url?: string): void {\n const isPageloadSpan = startSpanOptions.op === 'pageload';\n\n const initialSpanName = startSpanOptions.name;\n const finalStartSpanOptions: StartSpanOptions = beforeStartSpan\n ? beforeStartSpan(startSpanOptions)\n : startSpanOptions;\n\n // For navigations, `url` is the destination URL, so we use it to reflect the post-navigation location.\n // For pageloads (and manual navigation spans without a URL) we fall back to the current location.\n const urlObject = parseStringToURLObject(url || getLocationHref());\n\n const attributes = {\n ...(urlObject?.pathname && { [URL_PATH]: urlObject.pathname }),\n ...(urlObject && !isURLObjectRelative(urlObject) && { [URL_FULL]: filterCollectedUrl(urlObject.href) }),\n ...finalStartSpanOptions.attributes,\n };\n\n // If `finalStartSpanOptions.name` is different than `startSpanOptions.name`\n // it is because `beforeStartSpan` set a custom name. Therefore we set the source to 'custom'.\n if (initialSpanName !== finalStartSpanOptions.name) {\n attributes[SENTRY_SEGMENT_NAME_SOURCE] = 'custom';\n }\n\n finalStartSpanOptions.attributes = attributes;\n\n if (!makeActive) {\n // We want to ensure this has 0s duration\n const now = dateTimestampInSeconds();\n startInactiveSpan({\n ...finalStartSpanOptions,\n startTime: now,\n }).end(now);\n return;\n }\n\n const idleSpan = startIdleSpan(finalStartSpanOptions, {\n idleTimeout,\n finalTimeout,\n childSpanTimeout,\n // should wait for finish signal if it's a pageload transaction\n disableAutoFinish: isPageloadSpan,\n trimIdleSpanEndTimestamp: !enableReportPageLoaded,\n });\n\n if (isPageloadSpan && enableReportPageLoaded) {\n _pageloadSpan = idleSpan;\n }\n\n setActiveIdleSpan(client, idleSpan);\n\n function emitFinish(): void {\n if (optionalWindowDocument && ['interactive', 'complete'].includes(optionalWindowDocument.readyState)) {\n client.emit('idleSpanEnableAutoFinish', idleSpan);\n // Once the finish signal has been emitted, the listener is no longer needed. Removing it here (rather than\n // relying on `{ once: true }`) also covers the common case where the document is already loaded when the span\n // starts, so the listener never fires and would otherwise leak together with the `idleSpan` it closes over.\n optionalWindowDocument.removeEventListener('readystatechange', emitFinish);\n }\n }\n\n // Enable auto finish of the pageload span if users are not explicitly ending it\n if (isPageloadSpan && !enableReportPageLoaded && optionalWindowDocument) {\n optionalWindowDocument.addEventListener('readystatechange', emitFinish);\n\n emitFinish();\n }\n }\n\n return {\n name: BROWSER_TRACING_INTEGRATION_ID,\n setup(client) {\n if (_isBot) {\n DEBUG_BUILD && debug.log('[Tracing] Skipping browserTracingIntegration setup for bot user agent.');\n return;\n }\n\n registerSpanErrorInstrumentation();\n\n if (\n enableLongAnimationFrame &&\n GLOBAL_OBJ.PerformanceObserver &&\n PerformanceObserver.supportedEntryTypes?.includes('long-animation-frame')\n ) {\n startTrackingLongAnimationFrames();\n } else if (enableLongTask) {\n startTrackingLongTasks();\n }\n\n if (detectRedirects && optionalWindowDocument) {\n const interactionHandler = (): void => {\n lastInteractionTimestamp = timestampInSeconds();\n };\n addEventListener('click', interactionHandler, { capture: true });\n addEventListener('keydown', interactionHandler, { capture: true, passive: true });\n }\n\n function maybeEndActiveSpan(): void {\n const activeSpan = getActiveIdleSpan(client);\n\n if (activeSpan && !spanToJSON(activeSpan).end_timestamp) {\n DEBUG_BUILD &&\n debug.log(\n `[Tracing] Finishing current active span with op: ${spanToJSON(activeSpan).attributes[SENTRY_OP]}`,\n );\n // If there's an open active span, we need to finish it before creating an new one.\n activeSpan.setAttribute(SENTRY_IDLE_SPAN_FINISH_REASON, 'cancelled');\n activeSpan.end();\n }\n }\n\n client.on('beforeIdleSpanEnd', span => {\n // Interaction idle spans also flow through this hook, but the route bookkeeping below only\n // applies to the pageload/navigation span. We identify it by reference rather than by op:\n // only the route span is registered as the active idle span.\n if (getActiveIdleSpan(client) !== span) {\n return;\n }\n\n addPerformanceEntries(span, {\n ignoreResourceSpans,\n spanStreamingEnabled: hasSpanStreamingEnabled(client),\n });\n setActiveIdleSpan(client, undefined);\n\n // A trace should stay consistent over the entire timespan of one route - even after the pageload/navigation ended.\n // Only when another navigation happens, we want to create a new trace.\n // This way, e.g. errors that occur after the pageload span ended are still associated to the pageload trace.\n const scope = getCurrentScope();\n const oldPropagationContext = scope.getPropagationContext();\n\n scope.setPropagationContext({\n ...oldPropagationContext,\n traceId: span.spanContext().traceId,\n sampled: spanIsSampled(span),\n dsc: getDynamicSamplingContextFromSpan(span),\n });\n\n if (_pageloadSpan === span) {\n // clean up the stored pageload span on the integration.\n _pageloadSpan = undefined;\n }\n });\n\n client.on('startNavigationSpan', (startSpanOptions, navigationOptions) => {\n if (getClient() !== client) {\n return;\n }\n\n if (navigationOptions?.isRedirect) {\n DEBUG_BUILD &&\n debug.warn('[Tracing] Detected redirect, navigation span will not be the root span, but a child span.');\n _createRouteSpan(\n client,\n {\n op: NAVIGATION_REDIRECT,\n ...startSpanOptions,\n },\n false,\n navigationOptions.url,\n );\n return;\n }\n\n // Reset the last interaction timestamp since we now start a new navigation.\n // Any subsequent navigation span starts could again be a redirect, so we\n // should reset our heuristic detectors.\n lastInteractionTimestamp = undefined;\n\n maybeEndActiveSpan();\n\n const scope = getCurrentScope();\n scope.setPropagationContext({\n traceId: generateTraceId(),\n sampleRand: Math.random(),\n propagationSpanId: hasSpansEnabled() ? undefined : generateSpanId(),\n });\n\n // We reset this to ensure we do not have lingering incorrect data here\n // places that call this hook may set this where appropriate - else, the URL at span sending time is used\n scope.setSDKProcessingMetadata({\n normalizedRequest: undefined,\n });\n\n _createRouteSpan(\n client,\n {\n op: NAVIGATION,\n ...startSpanOptions,\n // Navigation starts a new trace and is NOT parented under any active interaction (e.g. ui.action.click)\n parentSpan: null,\n },\n true,\n navigationOptions?.url,\n );\n });\n\n client.on('startPageLoadSpan', (startSpanOptions, traceOptions = {}) => {\n if (getClient() !== client) {\n return;\n }\n maybeEndActiveSpan();\n\n const sentryTrace =\n traceOptions.sentryTrace || getMetaContent('sentry-trace') || getServerTiming('sentry-trace');\n const baggage = traceOptions.baggage || getMetaContent('baggage') || getServerTiming('baggage');\n\n const propagationContext = propagationContextFromHeaders(sentryTrace, baggage);\n\n const scope = getCurrentScope();\n scope.setPropagationContext(propagationContext);\n if (!hasSpansEnabled()) {\n // for browser, we wanna keep the spanIds consistent during the entire lifetime of the trace\n // this works by setting the propagationSpanId to a random spanId so that we have a consistent\n // span id to propagate in TwP mode (!hasSpansEnabled())\n scope.getPropagationContext().propagationSpanId = generateSpanId();\n }\n\n // We store the normalized request data on the scope, so we get the request data at time of span creation\n // otherwise, the URL etc. may already be of the following navigation, and we'd report the wrong URL\n scope.setSDKProcessingMetadata({\n normalizedRequest: getHttpRequestData(),\n });\n\n _createRouteSpan(client, {\n op: PAGELOAD,\n ...startSpanOptions,\n });\n });\n\n client.on('endPageloadSpan', () => {\n if (enableReportPageLoaded && _pageloadSpan) {\n _pageloadSpan.setAttribute(SENTRY_IDLE_SPAN_FINISH_REASON, 'reportPageLoaded');\n _pageloadSpan.end();\n }\n });\n\n // `pagehide` is the last moment a document leaving the page can still send. We cannot rely on\n // `registerBackgroundTabDetection`, which ends the span on `visibilitychange`: the client's own\n // `visibilitychange` flush is registered first and its deferring microtask runs after that\n // listener but before background tab detection's, so the buffer is still empty when it drains.\n // The segment span is buffered right after with nothing left to flush it, and the children have\n // been streamed all along, which leaves a rootless trace. Ending and flushing together here\n // keeps this self-contained instead of depending on that ordering.\n WINDOW.addEventListener?.('pagehide', () => {\n const activeSpan = getActiveIdleSpan(client);\n if (activeSpan && !spanToJSON(activeSpan).end_timestamp) {\n activeSpan.setAttribute(SENTRY_IDLE_SPAN_FINISH_REASON, 'documentHidden');\n activeSpan.end();\n }\n void client.flush();\n });\n },\n\n afterAllSetup(client) {\n if (_isBot) {\n return;\n }\n\n // Technically, every startSpan call already ensures that `spanStreamingIntegration` is installed,\n // but we do it here anyway for the edge case that users disabled pageload and navigation spans and\n // purely rely on manual startSpan calls.\n _INTERNAL_ensureBrowserSpanStreaming(client);\n\n // Auto-register webVitalsIntegration if the user hasn't added one. We do this in\n // afterAllSetup so that a user-provided webVitalsIntegration - which may be ordered after\n // browserTracingIntegration in the integrations array - has already been installed.\n if (client.addIntegration && !client.getIntegrationByName?.(WEB_VITALS_INTEGRATION_NAME)) {\n const ignore = webVitals?.ignore ?? [];\n client.addIntegration(\n webVitalsIntegration({\n ...webVitals,\n ignore: enableInp || ignore.includes('inp') ? ignore : [...ignore, 'inp'],\n }),\n );\n }\n\n let startingUrl: string | undefined = getLocationHref();\n\n if (linkPreviousTrace !== 'off') {\n linkTraces(client, { linkPreviousTrace, consistentTraceSampling });\n }\n\n if (WINDOW.location) {\n if (instrumentPageLoad) {\n startBrowserTracingPageLoadSpan(client, {\n // With span streaming, span names have to be low cardinality, and there is no route\n // information available here.\n name: hasSpanStreamingEnabled(client) ? PAGELOAD_SPAN_NAME_FALLBACK : WINDOW.location.pathname,\n attributes: {\n [SENTRY_SEGMENT_NAME_SOURCE]: 'url',\n [SENTRY_ORIGIN]: 'auto.pageload.browser',\n },\n });\n }\n\n if (instrumentNavigation) {\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 !== undefined && startingUrl.indexOf(to) !== -1) {\n startingUrl = undefined;\n return;\n }\n\n startingUrl = undefined;\n const parsed = parseStringToURLObject(to);\n const activeSpan = getActiveIdleSpan(client);\n const navigationIsRedirect =\n activeSpan && detectRedirects && isRedirect(activeSpan, lastInteractionTimestamp);\n\n startBrowserTracingNavigationSpan(\n client,\n {\n // With span streaming, span names have to be low cardinality, and there is no route\n // information available here.\n name: hasSpanStreamingEnabled(client)\n ? NAVIGATION_SPAN_NAME_FALLBACK\n : parsed?.pathname || WINDOW.location.pathname,\n attributes: {\n [SENTRY_SEGMENT_NAME_SOURCE]: 'url',\n [SENTRY_ORIGIN]: 'auto.navigation.browser',\n },\n },\n { url: to, isRedirect: navigationIsRedirect },\n );\n });\n }\n\n // A bfcache restore resurrects the frozen document, so there is no document load and no\n // usable history event: `popstate` either doesn't fire or is swallowed because the URL is\n // unchanged from when the page was frozen. Without a span of its own, everything after the\n // restore joins the trace the page had before it was frozen, separated by however long it\n // sat in the cache.\n if (instrumentBfcacheRestore) {\n WINDOW.addEventListener?.('pageshow', (event: PageTransitionEvent) => {\n if (!event.persisted) {\n return;\n }\n\n // A navigation has happened, so the pageload guard in the history handler above must not\n // suppress the next one.\n startingUrl = undefined;\n\n startBrowserTracingNavigationSpan(\n client,\n {\n // Deliberately no `startTime`: the span starts now, at the restore. The\n // `PerformanceNavigationTiming` entry still describes the original document load and\n // would date the span to before the page was frozen.\n //\n // TODO(routing): resolve the parameterized route via the route provider (#23551) and set\n // the source from it. No router event fires on a restore, so in a framework app this is\n // the only navigation span still named from a raw pathname.\n name: hasSpanStreamingEnabled(client)\n ? NAVIGATION_SPAN_NAME_FALLBACK\n : WINDOW.location?.pathname || '/',\n attributes: {\n [SENTRY_SEGMENT_NAME_SOURCE]: 'url',\n [SENTRY_ORIGIN]: 'auto.navigation.browser.bfcache',\n // A bfcache restore is near-instant, so these spans would otherwise drag\n // navigation duration percentiles down with no way to tell them apart.\n [BROWSER_NAVIGATION_TYPE]: 'bfcache',\n },\n },\n { url: WINDOW.location?.href },\n );\n });\n }\n }\n\n if (markBackgroundSpan) {\n registerBackgroundTabDetection();\n }\n\n instrumentOutgoingRequests(client, {\n traceFetch,\n traceXHR,\n tracePropagationTargets: client.getOptions().tracePropagationTargets,\n shouldCreateSpanForRequest,\n enableHTTPTimings,\n onRequestSpanStart,\n onRequestSpanEnd,\n });\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Manually start a page load span.\n * This will only do something if a browser tracing integration integration has been setup.\n *\n * If you provide a custom `traceOptions` object, it will be used to continue the trace\n * instead of the default behavior, which is to look it up on the <meta> tags.\n */\nexport function startBrowserTracingPageLoadSpan(\n client: Client,\n spanOptions: StartSpanOptions,\n traceOptions?: { sentryTrace?: string | undefined; baggage?: string | undefined },\n): Span | undefined {\n // `Pageload` is a low-cardinality span name, not a description of the page. The scope's\n // transaction name is what error events are grouped by, so it keeps the URL instead.\n const isFallbackSpanName = spanOptions.name === PAGELOAD_SPAN_NAME_FALLBACK;\n getCurrentScope().setTransactionName(isFallbackSpanName ? WINDOW.location?.pathname : spanOptions.name);\n // A pageload span always covers the entire page load, no matter how late the SDK or a routing\n // instrumentation gets around to starting it. Everything that happened before (DNS, TLS, TTFB,\n // HTML parsing, chunk loading) is part of the page load and the performance child spans we attach\n // later are anchored at the time origin anyway.\n const timeOrigin = browserPerformanceTimeOrigin();\n const pageloadSpanOptions: StartSpanOptions = {\n ...spanOptions,\n // startTime needs to be in seconds, not ms\n startTime: spanOptions.startTime ?? (timeOrigin ? timeOrigin / 1000 : undefined),\n };\n\n client.emit('startPageLoadSpan', pageloadSpanOptions, traceOptions);\n\n const pageloadSpan = getActiveIdleSpan(client);\n\n if (pageloadSpan) {\n client.emit('afterStartPageLoadSpan', pageloadSpan);\n }\n\n return pageloadSpan;\n}\n\n/**\n * Manually start a navigation span.\n * This will only do something if a browser tracing integration has been setup.\n */\nexport function startBrowserTracingNavigationSpan(\n client: Client,\n spanOptions: StartSpanOptions,\n options?: { url?: string; isRedirect?: boolean },\n): Span | undefined {\n const { url, isRedirect } = options || {};\n client.emit('beforeStartNavigationSpan', spanOptions, { isRedirect, url });\n client.emit('startNavigationSpan', spanOptions, { isRedirect, url });\n\n const scope = getCurrentScope();\n // `Navigation` is a low-cardinality span name, not a description of the page. The scope's\n // transaction name is what error events are grouped by, so it keeps the URL instead. `url` is the\n // destination, while `location` still points at the previous page during a `pushState`.\n const isFallbackSpanName = spanOptions.name === NAVIGATION_SPAN_NAME_FALLBACK;\n scope.setTransactionName(\n isFallbackSpanName ? (url && parseStringToURLObject(url)?.pathname) || WINDOW.location?.pathname : spanOptions.name,\n );\n\n // We store the normalized request data on the scope, so we get the request data at time of span creation\n // otherwise, the URL etc. may already be of the following navigation, and we'd report the wrong URL\n if (url && !isRedirect) {\n scope.setSDKProcessingMetadata({\n normalizedRequest: {\n ...getHttpRequestData(),\n url,\n },\n });\n }\n\n return getActiveIdleSpan(client);\n}\n\n/** Returns the value of a meta tag */\nexport function getMetaContent(metaName: string): string | undefined {\n /**\n * This is just a small wrapper that makes `document` optional.\n * We want to be extra-safe and always check that this exists, to ensure weird environments do not blow up.\n */\n const optionalWindowDocument = WINDOW.document as (typeof WINDOW)['document'] | undefined;\n\n const metaTag = optionalWindowDocument?.querySelector(`meta[name=${metaName}]`);\n return metaTag?.getAttribute('content') || undefined;\n}\n\n/** Returns the description of a server timing entry */\nexport function getServerTiming(name: string): string | undefined {\n // The cast is required for the declaration build (`build:types`), which resolves\n // `getEntriesByType('navigation')` to `PerformanceEntry[]` (no `serverTiming`). It only reads as\n // \"unnecessary\" to the type-aware linter, which runs with web-vitals' global augmentation applied.\n const navigation = WINDOW.performance?.getEntriesByType?.('navigation')[0] as PerformanceNavigationTiming | undefined;\n const entry = navigation?.serverTiming?.find(entry => entry.name === name);\n return entry?.description;\n}\n\n// We store the active idle span on the client object, so we can access it from exported functions\nconst ACTIVE_IDLE_SPAN_PROPERTY = '_sentry_idleSpan';\nfunction getActiveIdleSpan(client: Client): Span | undefined {\n return (client as { [ACTIVE_IDLE_SPAN_PROPERTY]?: Span })[ACTIVE_IDLE_SPAN_PROPERTY];\n}\n\nfunction setActiveIdleSpan(client: Client, span: Span | undefined): void {\n addNonEnumerableProperty(client, ACTIVE_IDLE_SPAN_PROPERTY, span);\n}\n\n// The max. time in seconds between two pageload/navigation spans that makes us consider the second one a redirect\nconst REDIRECT_THRESHOLD = 1.5;\n\nfunction isRedirect(activeSpan: Span, lastInteractionTimestamp: number | undefined): boolean {\n const spanData = spanToJSON(activeSpan);\n\n const now = dateTimestampInSeconds();\n\n // More than REDIRECT_THRESHOLD seconds since last navigation/pageload span?\n // --> never consider this a redirect\n const startTimestamp = spanData.start_timestamp;\n if (now - startTimestamp > REDIRECT_THRESHOLD) {\n return false;\n }\n\n // A click happened in the last REDIRECT_THRESHOLD seconds?\n // --> never consider this a redirect\n if (lastInteractionTimestamp && now - lastInteractionTimestamp <= REDIRECT_THRESHOLD) {\n return false;\n }\n\n return true;\n}\n"],"names":["TRACING_DEFAULTS","defaultRequestInstrumentationOptions","consoleSandbox","WINDOW","webVitals","isBotUserAgent","parseStringToURLObject","getLocationHref","attributes","URL_PATH","isURLObjectRelative","URL_FULL","filterCollectedUrl","SENTRY_SEGMENT_NAME_SOURCE","dateTimestampInSeconds","startInactiveSpan","startIdleSpan","DEBUG_BUILD","debug","registerSpanErrorInstrumentation","GLOBAL_OBJ","startTrackingLongAnimationFrames","startTrackingLongTasks","timestampInSeconds","spanToJSON","SENTRY_OP","SENTRY_IDLE_SPAN_FINISH_REASON","addPerformanceEntries","hasSpanStreamingEnabled","getCurrentScope","spanIsSampled","getDynamicSamplingContextFromSpan","getClient","NAVIGATION_REDIRECT","generateTraceId","hasSpansEnabled","generateSpanId","NAVIGATION","propagationContextFromHeaders","getHttpRequestData","PAGELOAD","_INTERNAL_ensureBrowserSpanStreaming","WEB_VITALS_INTEGRATION_NAME","webVitalsIntegration","linkTraces","PAGELOAD_SPAN_NAME_FALLBACK","SENTRY_ORIGIN","addHistoryInstrumentationHandler","NAVIGATION_SPAN_NAME_FALLBACK","BROWSER_NAVIGATION_TYPE","registerBackgroundTabDetection","instrumentOutgoingRequests","browserPerformanceTimeOrigin","isRedirect","entry","addNonEnumerableProperty"],"mappings":";;;;;;;;;;;;;;AAuDO,MAAM,8BAAA,GAAiC;AA6N9C,MAAM,+BAAA,GAAyD;AAAA,EAC7D,GAAGA,qBAAA;AAAA,EACH,oBAAA,EAAsB,IAAA;AAAA,EACtB,wBAAA,EAA0B,IAAA;AAAA,EAC1B,kBAAA,EAAoB,IAAA;AAAA,EACpB,kBAAA,EAAoB,IAAA;AAAA,EACpB,cAAA,EAAgB,IAAA;AAAA,EAChB,wBAAA,EAA0B,IAAA;AAAA;AAAA,EAE1B,SAAA,EAAW,IAAA;AAAA,EACX,qBAAqB,EAAC;AAAA,EACtB,eAAA,EAAiB,IAAA;AAAA,EACjB,iBAAA,EAAmB,WAAA;AAAA,EACnB,uBAAA,EAAyB,KAAA;AAAA,EACzB,sBAAA,EAAwB,KAAA;AAAA,EACxB,GAAGC;AACL,CAAA;AAWO,MAAM,yBAAA,IAA6B,CAAC,OAAA,GAA0C,EAAC,KAAM;AAC1F,EAAA,IAAI,yBAAyB,OAAA,EAAS;AACpC,IAAAC,mBAAA,CAAe,MAAM;AAEnB,MAAA,OAAA,CAAQ,IAAA;AAAA,QACN;AAAA,OACF;AAAA,IACF,CAAC,CAAA;AAAA,EACH;AAMA,EAAA,MAAM,yBAAyBC,cAAA,CAAO,QAAA;AAEtC,EAAA,MAAM;AAAA;AAAA,IAEJ,SAAA;AAAA,IACA,cAAA;AAAA,IACA,wBAAA;AAAA,eACAC,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AA,EAAoB;AACpF,IAAA,OAAO,KAAA;AAAA,EACT;AAEA,EAAA,OAAO,IAAA;AACT;;;;;;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"linkedTraces.js","sources":["../../../../../src/tracing/linkedTraces.ts"],"sourcesContent":["import type { Client, PropagationContext, Span, SpanContextData } from '@sentry/core';\nimport {\n debug,\n getCurrentScope,\n getRootSpan,\n SEMANTIC_ATTRIBUTE_SENTRY_PREVIOUS_TRACE_SAMPLE_RATE,\n SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE,\n SEMANTIC_LINK_ATTRIBUTE_LINK_TYPE,\n spanToJSON,\n} from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build';\nimport { WINDOW } from '../exports';\nimport { SENTRY_OP } from '@sentry/conventions/attributes';\n\nexport interface PreviousTraceInfo {\n /**\n * Span context of the previous trace's local root span\n */\n spanContext: SpanContextData;\n\n /**\n * Timestamp in seconds when the previous trace was started\n */\n startTimestamp: number;\n\n /**\n * sample rate of the previous trace\n */\n sampleRate: number;\n\n /**\n * The sample rand of the previous trace\n */\n sampleRand: number;\n}\n\n// 1h in seconds\nexport const PREVIOUS_TRACE_MAX_DURATION = 3600;\n\n// session storage key\nexport const PREVIOUS_TRACE_KEY = 'sentry_previous_trace';\n\nexport const PREVIOUS_TRACE_TMP_SPAN_ATTRIBUTE = 'sentry.previous_trace';\n\n/**\n * Takes care of linking traces and applying the (consistent) sampling behavoiour based on the passed options\n * @param options - options for linking traces and consistent trace sampling (@see BrowserTracingOptions)\n * @param client - Sentry client\n */\nexport function linkTraces(\n client: Client,\n {\n linkPreviousTrace,\n consistentTraceSampling,\n }: {\n linkPreviousTrace: 'session-storage' | 'in-memory';\n consistentTraceSampling: boolean;\n },\n): void {\n const useSessionStorage = linkPreviousTrace === 'session-storage';\n\n let inMemoryPreviousTraceInfo = useSessionStorage ? getPreviousTraceFromSessionStorage() : undefined;\n\n client.on('spanStart', span => {\n if (getRootSpan(span) !== span) {\n return;\n }\n\n const oldPropagationContext = getCurrentScope().getPropagationContext();\n inMemoryPreviousTraceInfo = addPreviousTraceSpanLink(inMemoryPreviousTraceInfo, span, oldPropagationContext);\n\n if (useSessionStorage) {\n storePreviousTraceInSessionStorage(inMemoryPreviousTraceInfo);\n }\n });\n\n let isFirstTraceOnPageload = true;\n if (consistentTraceSampling) {\n /*\n When users opt into `consistentTraceSampling`, we need to ensure that we propagate\n the previous trace's sample rate and rand to the current trace. This is necessary because otherwise, span\n metric extrapolation is inaccurate, as we'd propagate too high of a sample rate for the subsequent traces.\n\n So therefore, we pretend that the previous trace was the parent trace of the newly started trace. To do that,\n we mutate the propagation context of the current trace and set the sample rate and sample rand of the previous trace.\n Timing-wise, it is fine because it happens before we even sample the root span.\n\n @see https://github.com/getsentry/sentry-javascript/issues/15754\n */\n client.on('beforeSampling', mutableSamplingContextData => {\n if (!inMemoryPreviousTraceInfo) {\n return;\n }\n\n const scope = getCurrentScope();\n const currentPropagationContext = scope.getPropagationContext();\n\n // We do not want to force-continue the sampling decision if we continue a trace\n // that was started on the backend. Most prominently, this will happen in MPAs where\n // users hard-navigate between pages. In this case, the sampling decision of a potentially\n // started trace on the server takes precedence.\n // Why? We want to prioritize inter-trace consistency over intra-trace consistency.\n if (isFirstTraceOnPageload && currentPropagationContext.parentSpanId) {\n isFirstTraceOnPageload = false;\n return;\n }\n\n scope.setPropagationContext({\n ...currentPropagationContext,\n dsc: {\n ...currentPropagationContext.dsc,\n sample_rate: String(inMemoryPreviousTraceInfo.sampleRate),\n sampled: String(spanContextSampled(inMemoryPreviousTraceInfo.spanContext)),\n },\n sampleRand: inMemoryPreviousTraceInfo.sampleRand,\n });\n\n mutableSamplingContextData.parentSampled = spanContextSampled(inMemoryPreviousTraceInfo.spanContext);\n mutableSamplingContextData.parentSampleRate = inMemoryPreviousTraceInfo.sampleRate;\n\n mutableSamplingContextData.spanAttributes = {\n ...mutableSamplingContextData.spanAttributes,\n [SEMANTIC_ATTRIBUTE_SENTRY_PREVIOUS_TRACE_SAMPLE_RATE]: inMemoryPreviousTraceInfo.sampleRate,\n };\n });\n }\n}\n\n/**\n * Adds a previous_trace span link to the passed span if the passed\n * previousTraceInfo is still valid.\n *\n * @returns the updated previous trace info (based on the current span/trace) to\n * be used on the next call\n */\nexport function addPreviousTraceSpanLink(\n previousTraceInfo: PreviousTraceInfo | undefined,\n span: Span,\n oldPropagationContext: PropagationContext,\n): PreviousTraceInfo {\n const spanJson = spanToJSON(span);\n\n function getSampleRate(): number {\n try {\n const oldSampleRate = Number(\n spanJson.attributes[SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE] ?? oldPropagationContext.dsc?.sample_rate,\n );\n return Number.isNaN(oldSampleRate) ? 0 : oldSampleRate;\n } catch {\n return 0;\n }\n }\n\n const updatedPreviousTraceInfo = {\n spanContext: span.spanContext(),\n startTimestamp: spanJson.start_timestamp,\n sampleRate: getSampleRate(),\n sampleRand: oldPropagationContext.sampleRand,\n };\n\n if (!previousTraceInfo) {\n return updatedPreviousTraceInfo;\n }\n\n const previousTraceSpanCtx = previousTraceInfo.spanContext;\n if (previousTraceSpanCtx.traceId === spanJson.trace_id) {\n // This means, we're still in the same trace so let's not update the previous trace info\n // or add a link to the current span.\n // Once we move away from the long-lived, route-based trace model, we can remove this cases\n return previousTraceInfo;\n }\n\n // Only add the link if the startTimeStamp of the previous trace's root span is within\n // PREVIOUS_TRACE_MAX_DURATION (1h) of the current root span's startTimestamp\n // This is done to\n // - avoid adding links to \"stale\" traces\n // - enable more efficient querying for previous/next traces in Sentry\n if (Date.now() / 1000 - previousTraceInfo.startTimestamp <= PREVIOUS_TRACE_MAX_DURATION) {\n if (DEBUG_BUILD) {\n debug.log(\n `Adding previous_trace \\`${JSON.stringify(previousTraceSpanCtx)}\\` link to span \\`${JSON.stringify({\n op: spanJson.attributes[SENTRY_OP],\n ...span.spanContext(),\n })}\\``,\n );\n }\n\n span.addLink({\n context: previousTraceSpanCtx,\n attributes: {\n [SEMANTIC_LINK_ATTRIBUTE_LINK_TYPE]: 'previous_trace',\n },\n });\n\n // TODO: Remove this once EAP can store span links. We currently only set this attribute so that we\n // can obtain the previous trace information from the EAP store. Long-term, EAP will handle\n // span links and then we should remove this again. Also throwing in a TODO(v11), to remind us\n // to check this at v11 time :)\n span.setAttribute(\n PREVIOUS_TRACE_TMP_SPAN_ATTRIBUTE,\n `${previousTraceSpanCtx.traceId}-${previousTraceSpanCtx.spanId}-${\n spanContextSampled(previousTraceSpanCtx) ? 1 : 0\n }`,\n );\n }\n\n return updatedPreviousTraceInfo;\n}\n\n/**\n * Stores @param previousTraceInfo in sessionStorage.\n */\nexport function storePreviousTraceInSessionStorage(previousTraceInfo: PreviousTraceInfo): void {\n try {\n WINDOW.sessionStorage.setItem(PREVIOUS_TRACE_KEY, JSON.stringify(previousTraceInfo));\n } catch (e) {\n // Ignore potential errors (e.g. if sessionStorage is not available)\n DEBUG_BUILD && debug.warn('Could not store previous trace in sessionStorage', e);\n }\n}\n\n/**\n * Retrieves the previous trace from sessionStorage if available.\n */\nexport function getPreviousTraceFromSessionStorage(): PreviousTraceInfo | undefined {\n try {\n const previousTraceInfo = WINDOW.sessionStorage?.getItem(PREVIOUS_TRACE_KEY);\n // @ts-expect-error - intentionally risking JSON.parse throwing when previousTraceInfo is null to save bundle size\n return JSON.parse(previousTraceInfo);\n } catch {\n return undefined;\n }\n}\n\n/**\n * see {@link import('@sentry/core').spanIsSampled}\n */\nexport function spanContextSampled(ctx: SpanContextData): boolean {\n return ctx.traceFlags === 0x1;\n}\n"],"names":["getRootSpan","getCurrentScope","SEMANTIC_ATTRIBUTE_SENTRY_PREVIOUS_TRACE_SAMPLE_RATE","spanToJSON","SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE","DEBUG_BUILD","debug","SENTRY_OP","SEMANTIC_LINK_ATTRIBUTE_LINK_TYPE","WINDOW"],"mappings":";;;;;;;;;;;;;;;;AAqCO,MAAM,2BAAA,GAA8B;A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AACF,IAAA,MAAM,iBAAA,GAAoBG,cAAA,CAAO,cAAA,EAAgB,OAAA,CAAQ,kBAAkB,CAAA;AAE3E,IAAA,OAAO,IAAA,CAAK,MAAM,iBAAiB,CAAA;AAAA,EACrC,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,MAAA;AAAA,EACT;AACF;AAKO,SAAS,mBAAmB,GAAA,EAA+B;AAChE,EAAA,OAAO,IAAI,UAAA,KAAe,CAAA;AAC5B;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"linkedTraces.js","sources":["../../../../../src/tracing/linkedTraces.ts"],"sourcesContent":["import type { Client, PropagationContext, Span, SpanContextData } from '@sentry/core';\nimport {\n debug,\n getCurrentScope,\n getRootSpan,\n SEMANTIC_ATTRIBUTE_SENTRY_PREVIOUS_TRACE_SAMPLE_RATE,\n SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE,\n SEMANTIC_LINK_ATTRIBUTE_LINK_TYPE,\n spanToJSON,\n} from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build';\nimport { WINDOW } from '../exports';\nimport { SENTRY_OP } from '@sentry/conventions/attributes';\n\nexport interface PreviousTraceInfo {\n /**\n * Span context of the previous trace's local root span\n */\n spanContext: SpanContextData;\n\n /**\n * Timestamp in seconds when the previous trace was started\n */\n startTimestamp: number;\n\n /**\n * sample rate of the previous trace\n */\n sampleRate: number;\n\n /**\n * The sample rand of the previous trace\n */\n sampleRand: number;\n}\n\n// 1h in seconds\nexport const PREVIOUS_TRACE_MAX_DURATION = 3600;\n\n// session storage key\nexport const PREVIOUS_TRACE_KEY = 'sentry_previous_trace';\n\nexport const PREVIOUS_TRACE_TMP_SPAN_ATTRIBUTE = 'sentry.previous_trace';\n\n/**\n * Takes care of linking traces and applying the (consistent) sampling behavoiour based on the passed options\n * @param options - options for linking traces and consistent trace sampling (@see BrowserTracingOptions)\n * @param client - Sentry client\n */\nexport function linkTraces(\n client: Client,\n {\n linkPreviousTrace,\n consistentTraceSampling,\n }: {\n linkPreviousTrace: 'session-storage' | 'in-memory';\n consistentTraceSampling: boolean;\n },\n): void {\n const useSessionStorage = linkPreviousTrace === 'session-storage';\n\n let inMemoryPreviousTraceInfo = useSessionStorage ? getPreviousTraceFromSessionStorage() : undefined;\n\n client.on('spanStart', span => {\n if (getRootSpan(span) !== span) {\n return;\n }\n\n const oldPropagationContext = getCurrentScope().getPropagationContext();\n inMemoryPreviousTraceInfo = addPreviousTraceSpanLink(inMemoryPreviousTraceInfo, span, oldPropagationContext);\n\n if (useSessionStorage) {\n storePreviousTraceInSessionStorage(inMemoryPreviousTraceInfo);\n }\n });\n\n let isFirstTraceOnPageload = true;\n if (consistentTraceSampling) {\n /*\n When users opt into `consistentTraceSampling`, we need to ensure that we propagate\n the previous trace's sample rate and rand to the current trace. This is necessary because otherwise, span\n metric extrapolation is inaccurate, as we'd propagate too high of a sample rate for the subsequent traces.\n\n So therefore, we pretend that the previous trace was the parent trace of the newly started trace. To do that,\n we mutate the propagation context of the current trace and set the sample rate and sample rand of the previous trace.\n Timing-wise, it is fine because it happens before we even sample the root span.\n\n @see https://github.com/getsentry/sentry-javascript/issues/15754\n */\n client.on('beforeSampling', mutableSamplingContextData => {\n if (!inMemoryPreviousTraceInfo) {\n return;\n }\n\n const scope = getCurrentScope();\n const currentPropagationContext = scope.getPropagationContext();\n\n // We do not want to force-continue the sampling decision if we continue a trace\n // that was started on the backend. Most prominently, this will happen in MPAs where\n // users hard-navigate between pages. In this case, the sampling decision of a potentially\n // started trace on the server takes precedence.\n // Why? We want to prioritize inter-trace consistency over intra-trace consistency.\n if (isFirstTraceOnPageload && currentPropagationContext.parentSpanId) {\n isFirstTraceOnPageload = false;\n return;\n }\n\n scope.setPropagationContext({\n ...currentPropagationContext,\n dsc: {\n ...currentPropagationContext.dsc,\n sample_rate: String(inMemoryPreviousTraceInfo.sampleRate),\n sampled: String(spanContextSampled(inMemoryPreviousTraceInfo.spanContext)),\n },\n sampleRand: inMemoryPreviousTraceInfo.sampleRand,\n });\n\n mutableSamplingContextData.parentSampled = spanContextSampled(inMemoryPreviousTraceInfo.spanContext);\n mutableSamplingContextData.parentSampleRate = inMemoryPreviousTraceInfo.sampleRate;\n\n mutableSamplingContextData.spanAttributes = {\n ...mutableSamplingContextData.spanAttributes,\n [SEMANTIC_ATTRIBUTE_SENTRY_PREVIOUS_TRACE_SAMPLE_RATE]: inMemoryPreviousTraceInfo.sampleRate,\n };\n });\n }\n}\n\n/**\n * Adds a previous_trace span link to the passed span if the passed\n * previousTraceInfo is still valid.\n *\n * @returns the updated previous trace info (based on the current span/trace) to\n * be used on the next call\n */\nexport function addPreviousTraceSpanLink(\n previousTraceInfo: PreviousTraceInfo | undefined,\n span: Span,\n oldPropagationContext: PropagationContext,\n): PreviousTraceInfo {\n const spanJson = spanToJSON(span);\n\n function getSampleRate(): number {\n try {\n const oldSampleRate = Number(\n spanJson.attributes[SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE] ?? oldPropagationContext.dsc?.sample_rate,\n );\n return Number.isNaN(oldSampleRate) ? 0 : oldSampleRate;\n } catch {\n return 0;\n }\n }\n\n const updatedPreviousTraceInfo = {\n spanContext: span.spanContext(),\n startTimestamp: spanJson.start_timestamp,\n sampleRate: getSampleRate(),\n sampleRand: oldPropagationContext.sampleRand,\n };\n\n if (!previousTraceInfo) {\n return updatedPreviousTraceInfo;\n }\n\n const previousTraceSpanCtx = previousTraceInfo.spanContext;\n if (previousTraceSpanCtx.traceId === spanJson.trace_id) {\n // This means, we're still in the same trace so let's not update the previous trace info\n // or add a link to the current span.\n // Once we move away from the long-lived, route-based trace model, we can remove this cases\n return previousTraceInfo;\n }\n\n // Only add the link if the startTimeStamp of the previous trace's root span is within\n // PREVIOUS_TRACE_MAX_DURATION (1h) of the current root span's startTimestamp\n // This is done to\n // - avoid adding links to \"stale\" traces\n // - enable more efficient querying for previous/next traces in Sentry\n if (Date.now() / 1000 - previousTraceInfo.startTimestamp <= PREVIOUS_TRACE_MAX_DURATION) {\n if (DEBUG_BUILD) {\n debug.log(\n `Adding previous_trace \\`${JSON.stringify(previousTraceSpanCtx)}\\` link to span \\`${JSON.stringify({\n op: spanJson.attributes[SENTRY_OP],\n ...span.spanContext(),\n })}\\``,\n );\n }\n\n span.addLink({\n context: previousTraceSpanCtx,\n attributes: {\n [SEMANTIC_LINK_ATTRIBUTE_LINK_TYPE]: 'previous_trace',\n },\n });\n\n // TODO(v12): Remove this once the Sentry trace view finds linked traces via span links. EAP stores\n // span links, but the trace view still reads this attribute to navigate to the previous/next trace.\n span.setAttribute(\n PREVIOUS_TRACE_TMP_SPAN_ATTRIBUTE,\n `${previousTraceSpanCtx.traceId}-${previousTraceSpanCtx.spanId}-${\n spanContextSampled(previousTraceSpanCtx) ? 1 : 0\n }`,\n );\n }\n\n return updatedPreviousTraceInfo;\n}\n\n/**\n * Stores @param previousTraceInfo in sessionStorage.\n */\nexport function storePreviousTraceInSessionStorage(previousTraceInfo: PreviousTraceInfo): void {\n try {\n WINDOW.sessionStorage.setItem(PREVIOUS_TRACE_KEY, JSON.stringify(previousTraceInfo));\n } catch (e) {\n // Ignore potential errors (e.g. if sessionStorage is not available)\n DEBUG_BUILD && debug.warn('Could not store previous trace in sessionStorage', e);\n }\n}\n\n/**\n * Retrieves the previous trace from sessionStorage if available.\n */\nexport function getPreviousTraceFromSessionStorage(): PreviousTraceInfo | undefined {\n try {\n const previousTraceInfo = WINDOW.sessionStorage?.getItem(PREVIOUS_TRACE_KEY);\n // @ts-expect-error - intentionally risking JSON.parse throwing when previousTraceInfo is null to save bundle size\n return JSON.parse(previousTraceInfo);\n } catch {\n return undefined;\n }\n}\n\n/**\n * see {@link import('@sentry/core').spanIsSampled}\n */\nexport function spanContextSampled(ctx: SpanContextData): boolean {\n return ctx.traceFlags === 0x1;\n}\n"],"names":["getRootSpan","getCurrentScope","SEMANTIC_ATTRIBUTE_SENTRY_PREVIOUS_TRACE_SAMPLE_RATE","spanToJSON","SEMANTIC_ATTRIBUTE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,EAAG;AAEV,IAAAJ,sBAAA,IAAeC,UAAA,CAAM,IAAA,CAAK,kDAAA,EAAoD,CAAC,CAAA;AAAA,EACjF;AACF;AAKO,SAAS,kCAAA,GAAoE;AAClF,EAAA,IAAI;AACF,IAAA,MAAM,iBAAA,GAAoBG,cAAA,CAAO,cAAA,EAAgB,OAAA,CAAQ,kBAAkB,CAAA;AAE3E,IAAA,OAAO,IAAA,CAAK,MAAM,iBAAiB,CAAA;AAAA,EACrC,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,MAAA;AAAA,EACT;AACF;AAKO,SAAS,mBAAmB,GAAA,EAA+B;AAChE,EAAA,OAAO,IAAI,UAAA,KAAe,CAAA;AAC5B;;;;;;;;;;;"}
|
|
@@ -72,6 +72,7 @@ exports.captureFeedback = core.captureFeedback;
|
|
|
72
72
|
exports.captureMessage = core.captureMessage;
|
|
73
73
|
exports.captureSession = core.captureSession;
|
|
74
74
|
exports.close = core.close;
|
|
75
|
+
exports.consoleIntegration = core.consoleIntegration;
|
|
75
76
|
exports.consoleLoggingIntegration = core.consoleLoggingIntegration;
|
|
76
77
|
exports.continueTrace = core.continueTrace;
|
|
77
78
|
exports.createConsolaReporter = core.createConsolaReporter;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
|
@@ -9,7 +9,6 @@ const MAX_ALLOWED_STRING_LENGTH = 1024;
|
|
|
9
9
|
const INTEGRATION_NAME = "Breadcrumbs";
|
|
10
10
|
const _breadcrumbsIntegration = ((options = {}) => {
|
|
11
11
|
const _options = {
|
|
12
|
-
console: true,
|
|
13
12
|
dom: true,
|
|
14
13
|
fetch: true,
|
|
15
14
|
history: true,
|
|
@@ -20,9 +19,6 @@ const _breadcrumbsIntegration = ((options = {}) => {
|
|
|
20
19
|
return {
|
|
21
20
|
name: INTEGRATION_NAME,
|
|
22
21
|
setup(client) {
|
|
23
|
-
if (_options.console) {
|
|
24
|
-
core.addConsoleInstrumentationHandler(_getConsoleBreadcrumbHandler(client));
|
|
25
|
-
}
|
|
26
22
|
if (_options.dom) {
|
|
27
23
|
browserUtils.addClickKeypressInstrumentationHandler(_getDomBreadcrumbHandler(client, _options.dom));
|
|
28
24
|
}
|
|
@@ -103,34 +99,6 @@ function _getDomBreadcrumbHandler(client, dom) {
|
|
|
103
99
|
});
|
|
104
100
|
};
|
|
105
101
|
}
|
|
106
|
-
function _getConsoleBreadcrumbHandler(client) {
|
|
107
|
-
return function _consoleBreadcrumb(handlerData) {
|
|
108
|
-
if (core.getClient() !== client) {
|
|
109
|
-
return;
|
|
110
|
-
}
|
|
111
|
-
const breadcrumb = {
|
|
112
|
-
category: "console",
|
|
113
|
-
data: {
|
|
114
|
-
arguments: handlerData.args,
|
|
115
|
-
logger: "console"
|
|
116
|
-
},
|
|
117
|
-
level: core.severityLevelFromString(handlerData.level),
|
|
118
|
-
message: core.safeJoin(handlerData.args, " ")
|
|
119
|
-
};
|
|
120
|
-
if (handlerData.level === "assert") {
|
|
121
|
-
if (handlerData.args[0] === false) {
|
|
122
|
-
breadcrumb.message = `Assertion failed: ${core.safeJoin(handlerData.args.slice(1), " ") || "console.assert"}`;
|
|
123
|
-
breadcrumb.data.arguments = handlerData.args.slice(1);
|
|
124
|
-
} else {
|
|
125
|
-
return;
|
|
126
|
-
}
|
|
127
|
-
}
|
|
128
|
-
core.addBreadcrumb(breadcrumb, {
|
|
129
|
-
input: handlerData.args,
|
|
130
|
-
level: handlerData.level
|
|
131
|
-
});
|
|
132
|
-
};
|
|
133
|
-
}
|
|
134
102
|
function _getXhrBreadcrumbHandler(client) {
|
|
135
103
|
return function _xhrBreadcrumb(handlerData) {
|
|
136
104
|
if (core.getClient() !== client) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"breadcrumbs.js","sources":["../../../../../src/integrations/breadcrumbs.ts"],"sourcesContent":["/* eslint-disable max-lines */\n\nimport type {\n Breadcrumb,\n Client,\n Event as SentryEvent,\n FetchBreadcrumbData,\n FetchBreadcrumbHint,\n HandlerDataConsole,\n HandlerDataFetch,\n IntegrationFn,\n} from '@sentry/core';\nimport {\n addBreadcrumb,\n addConsoleInstrumentationHandler,\n addFetchInstrumentationHandler,\n debug,\n defineIntegration,\n getBreadcrumbLogLevelFromHttpStatusCode,\n getClient,\n getEventDescription,\n parseUrl,\n safeJoin,\n severityLevelFromString,\n} from '@sentry/core';\nimport type { FetchHint, HandlerDataDom, HandlerDataHistory, HandlerDataXhr } from '@sentry/browser-utils';\nimport {\n addClickKeypressInstrumentationHandler,\n addHistoryInstrumentationHandler,\n addXhrInstrumentationHandler,\n htmlTreeAsString,\n getComponentName,\n SENTRY_XHR_DATA_KEY,\n} from '@sentry/browser-utils';\nimport type { XhrBreadcrumbData, XhrBreadcrumbHint } from '@sentry/core/browser';\nimport { DEBUG_BUILD } from '../debug-build';\nimport { WINDOW } from '../helpers';\n\ninterface BreadcrumbsOptions {\n console: boolean;\n dom:\n | boolean\n | {\n serializeAttribute?: string | string[];\n maxStringLength?: number;\n };\n fetch: boolean;\n history: boolean;\n sentry: boolean;\n xhr: boolean;\n}\n\n/** maxStringLength gets capped to prevent 100 breadcrumbs exceeding 1MB event payload size */\nconst MAX_ALLOWED_STRING_LENGTH = 1024;\n\nconst INTEGRATION_NAME = 'Breadcrumbs' as const;\n\nconst _breadcrumbsIntegration = ((options: Partial<BreadcrumbsOptions> = {}) => {\n const _options = {\n console: true,\n dom: true,\n fetch: true,\n history: true,\n sentry: true,\n xhr: true,\n ...options,\n };\n\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n // TODO(v11): Remove this functionality and use `consoleIntegration` from @sentry/core instead.\n if (_options.console) {\n addConsoleInstrumentationHandler(_getConsoleBreadcrumbHandler(client));\n }\n if (_options.dom) {\n addClickKeypressInstrumentationHandler(_getDomBreadcrumbHandler(client, _options.dom));\n }\n if (_options.xhr) {\n addXhrInstrumentationHandler(_getXhrBreadcrumbHandler(client));\n }\n if (_options.fetch) {\n addFetchInstrumentationHandler(_getFetchBreadcrumbHandler(client));\n }\n if (_options.history) {\n addHistoryInstrumentationHandler(_getHistoryBreadcrumbHandler(client));\n }\n if (_options.sentry) {\n client.on('beforeSendEvent', _getSentryBreadcrumbHandler(client));\n }\n },\n };\n}) satisfies IntegrationFn;\n\nexport const breadcrumbsIntegration = defineIntegration(_breadcrumbsIntegration);\n\n/**\n * Adds a breadcrumb for Sentry events or transactions if this option is enabled.\n */\nfunction _getSentryBreadcrumbHandler(client: Client): (event: SentryEvent) => void {\n return function addSentryBreadcrumb(event: SentryEvent): void {\n if (getClient() !== client) {\n return;\n }\n\n addBreadcrumb(\n {\n category: `sentry.${event.type === 'transaction' ? 'transaction' : 'event'}`,\n event_id: event.event_id,\n level: event.level,\n message: getEventDescription(event),\n },\n {\n event,\n },\n );\n };\n}\n\n/**\n * A HOC that creates a function that creates breadcrumbs from DOM API calls.\n * This is a HOC so that we get access to dom options in the closure.\n */\nfunction _getDomBreadcrumbHandler(\n client: Client,\n dom: BreadcrumbsOptions['dom'],\n): (handlerData: HandlerDataDom) => void {\n return function _innerDomBreadcrumb(handlerData: HandlerDataDom): void {\n if (getClient() !== client) {\n return;\n }\n\n let target;\n let componentName;\n let keyAttrs = typeof dom === 'object' ? dom.serializeAttribute : undefined;\n\n let maxStringLength =\n typeof dom === 'object' && typeof dom.maxStringLength === 'number' ? dom.maxStringLength : undefined;\n if (maxStringLength && maxStringLength > MAX_ALLOWED_STRING_LENGTH) {\n DEBUG_BUILD &&\n debug.warn(\n `\\`dom.maxStringLength\\` cannot exceed ${MAX_ALLOWED_STRING_LENGTH}, but a value of ${maxStringLength} was configured. Sentry will use ${MAX_ALLOWED_STRING_LENGTH} instead.`,\n );\n maxStringLength = MAX_ALLOWED_STRING_LENGTH;\n }\n\n if (typeof keyAttrs === 'string') {\n keyAttrs = [keyAttrs];\n }\n\n // Accessing event.target can throw (see getsentry/raven-js#838, #768)\n try {\n const event = handlerData.event as Event | Node;\n const element = _isEvent(event) ? event.target : event;\n\n target = htmlTreeAsString(element, { keyAttrs, maxStringLength });\n componentName = getComponentName(element);\n } catch {\n target = '<unknown>';\n }\n\n if (target.length === 0) {\n return;\n }\n\n const breadcrumb: Breadcrumb = {\n category: `ui.${handlerData.name}`,\n message: target,\n };\n\n if (componentName) {\n breadcrumb.data = { 'ui.component_name': componentName };\n }\n\n addBreadcrumb(breadcrumb, {\n event: handlerData.event,\n name: handlerData.name,\n global: handlerData.global,\n });\n };\n}\n\n/**\n * Creates breadcrumbs from console API calls\n */\nfunction _getConsoleBreadcrumbHandler(client: Client): (handlerData: HandlerDataConsole) => void {\n return function _consoleBreadcrumb(handlerData: HandlerDataConsole): void {\n if (getClient() !== client) {\n return;\n }\n\n const breadcrumb = {\n category: 'console',\n data: {\n arguments: handlerData.args,\n logger: 'console',\n },\n level: severityLevelFromString(handlerData.level),\n message: safeJoin(handlerData.args, ' '),\n };\n\n if (handlerData.level === 'assert') {\n if (handlerData.args[0] === false) {\n breadcrumb.message = `Assertion failed: ${safeJoin(handlerData.args.slice(1), ' ') || 'console.assert'}`;\n breadcrumb.data.arguments = handlerData.args.slice(1);\n } else {\n // Don't capture a breadcrumb for passed assertions\n return;\n }\n }\n\n addBreadcrumb(breadcrumb, {\n input: handlerData.args,\n level: handlerData.level,\n });\n };\n}\n\n/**\n * Creates breadcrumbs from XHR API calls\n */\nfunction _getXhrBreadcrumbHandler(client: Client): (handlerData: HandlerDataXhr) => void {\n return function _xhrBreadcrumb(handlerData: HandlerDataXhr): void {\n if (getClient() !== client) {\n return;\n }\n\n const { startTimestamp, endTimestamp } = handlerData;\n\n const sentryXhrData = handlerData.xhr[SENTRY_XHR_DATA_KEY];\n\n // We only capture complete, non-sentry requests\n if (!startTimestamp || !endTimestamp || !sentryXhrData) {\n return;\n }\n\n const { method, url, status_code, body } = sentryXhrData;\n\n const data: XhrBreadcrumbData = {\n method,\n url,\n status_code,\n };\n\n const hint: XhrBreadcrumbHint = {\n xhr: handlerData.xhr,\n input: body,\n startTimestamp,\n endTimestamp,\n };\n\n const breadcrumb = {\n category: 'xhr',\n data,\n type: 'http',\n level: getBreadcrumbLogLevelFromHttpStatusCode(status_code),\n };\n\n client.emit('beforeOutgoingRequestBreadcrumb', breadcrumb, hint);\n\n addBreadcrumb(breadcrumb, hint);\n };\n}\n\n/**\n * Creates breadcrumbs from fetch API calls\n */\nfunction _getFetchBreadcrumbHandler(client: Client): (handlerData: HandlerDataFetch) => void {\n return function _fetchBreadcrumb(handlerData: HandlerDataFetch): void {\n if (getClient() !== client) {\n return;\n }\n\n const { startTimestamp, endTimestamp } = handlerData;\n\n // We only capture complete fetch requests\n if (!endTimestamp) {\n return;\n }\n\n if (handlerData.fetchData.url.match(/sentry_key/) && handlerData.fetchData.method === 'POST') {\n // We will not create breadcrumbs for fetch requests that contain `sentry_key` (internal sentry requests)\n return;\n }\n\n if (handlerData.error) {\n const hint: FetchBreadcrumbHint = {\n data: handlerData.error,\n input: handlerData.args,\n startTimestamp,\n endTimestamp,\n };\n\n const breadcrumb = {\n category: 'fetch',\n data: handlerData.fetchData,\n level: 'error',\n type: 'http',\n } satisfies Breadcrumb;\n\n client.emit('beforeOutgoingRequestBreadcrumb', breadcrumb, hint as FetchHint);\n\n addBreadcrumb(breadcrumb, hint);\n } else {\n const response = handlerData.response as Response | undefined;\n const data: FetchBreadcrumbData = {\n ...handlerData.fetchData,\n status_code: response?.status,\n };\n\n const hint: FetchBreadcrumbHint = {\n input: handlerData.args,\n response,\n startTimestamp,\n endTimestamp,\n };\n\n const breadcrumb = {\n category: 'fetch',\n data,\n type: 'http',\n level: getBreadcrumbLogLevelFromHttpStatusCode(data.status_code),\n };\n\n client.emit('beforeOutgoingRequestBreadcrumb', breadcrumb, hint as FetchHint);\n\n addBreadcrumb(breadcrumb, hint);\n }\n };\n}\n\n/**\n * Creates breadcrumbs from history API calls\n */\nfunction _getHistoryBreadcrumbHandler(client: Client): (handlerData: HandlerDataHistory) => void {\n return function _historyBreadcrumb(handlerData: HandlerDataHistory): void {\n if (getClient() !== client) {\n return;\n }\n\n let from: string | undefined = handlerData.from;\n let to: string | undefined = handlerData.to;\n const parsedLoc = parseUrl(WINDOW.location.href);\n let parsedFrom = from ? parseUrl(from) : undefined;\n const parsedTo = parseUrl(to);\n\n // Initial pushState doesn't provide `from` information\n if (!parsedFrom?.path) {\n parsedFrom = parsedLoc;\n }\n\n // Use only the path component of the URL if the URL matches the current\n // document (almost all the time when using pushState)\n if (parsedLoc.protocol === parsedTo.protocol && parsedLoc.host === parsedTo.host) {\n to = parsedTo.relative;\n }\n if (parsedLoc.protocol === parsedFrom.protocol && parsedLoc.host === parsedFrom.host) {\n from = parsedFrom.relative;\n }\n\n addBreadcrumb({\n category: 'navigation',\n data: {\n from,\n to,\n },\n });\n };\n}\n\nfunction _isEvent(event: unknown): event is Event {\n return !!event && !!(event as Record<string, unknown>).target;\n}\n"],"names":["addConsoleInstrumentationHandler","addClickKeypressInstrumentationHandler","addXhrInstrumentationHandler","addFetchInstrumentationHandler","addHistoryInstrumentationHandler","defineIntegration","getClient","addBreadcrumb","getEventDescription","DEBUG_BUILD","debug","htmlTreeAsString","getComponentName","severityLevelFromString","safeJoin","SENTRY_XHR_DATA_KEY","getBreadcrumbLogLevelFromHttpStatusCode","parseUrl","WINDOW"],"mappings":";;;;;;;AAqDA,MAAM,yBAAA,GAA4B,IAAA;AAElC,MAAM,gBAAA,GAAmB,aAAA;AAEzB,MAAM,uBAAA,IAA2B,CAAC,OA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B;AACA,IAAA,IAAI,UAAU,QAAA,KAAa,UAAA,CAAW,YAAY,SAAA,CAAU,IAAA,KAAS,WAAW,IAAA,EAAM;AACpF,MAAA,IAAA,GAAO,UAAA,CAAW,QAAA;AAAA,IACpB;AAEA,IAAAV,kBAAA,CAAc;AAAA,MACZ,QAAA,EAAU,YAAA;AAAA,MACV,IAAA,EAAM;AAAA,QACJ,IAAA;AAAA,QACA;AAAA;AACF,KACD,CAAA;AAAA,EACH,CAAA;AACF;AAEA,SAAS,SAAS,KAAA,EAAgC;AAChD,EAAA,OAAO,CAAC,CAAC,KAAA,IAAS,CAAC,CAAE,KAAA,CAAkC,MAAA;AACzD;;;;"}
|
|
1
|
+
{"version":3,"file":"breadcrumbs.js","sources":["../../../../../src/integrations/breadcrumbs.ts"],"sourcesContent":["/* eslint-disable max-lines */\n\nimport type {\n Breadcrumb,\n Client,\n Event as SentryEvent,\n FetchBreadcrumbData,\n FetchBreadcrumbHint,\n HandlerDataFetch,\n IntegrationFn,\n} from '@sentry/core';\nimport {\n addBreadcrumb,\n addFetchInstrumentationHandler,\n debug,\n defineIntegration,\n getBreadcrumbLogLevelFromHttpStatusCode,\n getClient,\n getEventDescription,\n parseUrl,\n} from '@sentry/core';\nimport type { FetchHint, HandlerDataDom, HandlerDataHistory, HandlerDataXhr } from '@sentry/browser-utils';\nimport {\n addClickKeypressInstrumentationHandler,\n addHistoryInstrumentationHandler,\n addXhrInstrumentationHandler,\n htmlTreeAsString,\n getComponentName,\n SENTRY_XHR_DATA_KEY,\n} from '@sentry/browser-utils';\nimport type { XhrBreadcrumbData, XhrBreadcrumbHint } from '@sentry/core/browser';\nimport { DEBUG_BUILD } from '../debug-build';\nimport { WINDOW } from '../helpers';\n\ninterface BreadcrumbsOptions {\n dom:\n | boolean\n | {\n serializeAttribute?: string | string[];\n maxStringLength?: number;\n };\n fetch: boolean;\n history: boolean;\n sentry: boolean;\n xhr: boolean;\n}\n\n/** maxStringLength gets capped to prevent 100 breadcrumbs exceeding 1MB event payload size */\nconst MAX_ALLOWED_STRING_LENGTH = 1024;\n\nconst INTEGRATION_NAME = 'Breadcrumbs' as const;\n\nconst _breadcrumbsIntegration = ((options: Partial<BreadcrumbsOptions> = {}) => {\n const _options = {\n dom: true,\n fetch: true,\n history: true,\n sentry: true,\n xhr: true,\n ...options,\n };\n\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n if (_options.dom) {\n addClickKeypressInstrumentationHandler(_getDomBreadcrumbHandler(client, _options.dom));\n }\n if (_options.xhr) {\n addXhrInstrumentationHandler(_getXhrBreadcrumbHandler(client));\n }\n if (_options.fetch) {\n addFetchInstrumentationHandler(_getFetchBreadcrumbHandler(client));\n }\n if (_options.history) {\n addHistoryInstrumentationHandler(_getHistoryBreadcrumbHandler(client));\n }\n if (_options.sentry) {\n client.on('beforeSendEvent', _getSentryBreadcrumbHandler(client));\n }\n },\n };\n}) satisfies IntegrationFn;\n\nexport const breadcrumbsIntegration = defineIntegration(_breadcrumbsIntegration);\n\n/**\n * Adds a breadcrumb for Sentry events or transactions if this option is enabled.\n */\nfunction _getSentryBreadcrumbHandler(client: Client): (event: SentryEvent) => void {\n return function addSentryBreadcrumb(event: SentryEvent): void {\n if (getClient() !== client) {\n return;\n }\n\n addBreadcrumb(\n {\n category: `sentry.${event.type === 'transaction' ? 'transaction' : 'event'}`,\n event_id: event.event_id,\n level: event.level,\n message: getEventDescription(event),\n },\n {\n event,\n },\n );\n };\n}\n\n/**\n * A HOC that creates a function that creates breadcrumbs from DOM API calls.\n * This is a HOC so that we get access to dom options in the closure.\n */\nfunction _getDomBreadcrumbHandler(\n client: Client,\n dom: BreadcrumbsOptions['dom'],\n): (handlerData: HandlerDataDom) => void {\n return function _innerDomBreadcrumb(handlerData: HandlerDataDom): void {\n if (getClient() !== client) {\n return;\n }\n\n let target;\n let componentName;\n let keyAttrs = typeof dom === 'object' ? dom.serializeAttribute : undefined;\n\n let maxStringLength =\n typeof dom === 'object' && typeof dom.maxStringLength === 'number' ? dom.maxStringLength : undefined;\n if (maxStringLength && maxStringLength > MAX_ALLOWED_STRING_LENGTH) {\n DEBUG_BUILD &&\n debug.warn(\n `\\`dom.maxStringLength\\` cannot exceed ${MAX_ALLOWED_STRING_LENGTH}, but a value of ${maxStringLength} was configured. Sentry will use ${MAX_ALLOWED_STRING_LENGTH} instead.`,\n );\n maxStringLength = MAX_ALLOWED_STRING_LENGTH;\n }\n\n if (typeof keyAttrs === 'string') {\n keyAttrs = [keyAttrs];\n }\n\n // Accessing event.target can throw (see getsentry/raven-js#838, #768)\n try {\n const event = handlerData.event as Event | Node;\n const element = _isEvent(event) ? event.target : event;\n\n target = htmlTreeAsString(element, { keyAttrs, maxStringLength });\n componentName = getComponentName(element);\n } catch {\n target = '<unknown>';\n }\n\n if (target.length === 0) {\n return;\n }\n\n const breadcrumb: Breadcrumb = {\n category: `ui.${handlerData.name}`,\n message: target,\n };\n\n if (componentName) {\n breadcrumb.data = { 'ui.component_name': componentName };\n }\n\n addBreadcrumb(breadcrumb, {\n event: handlerData.event,\n name: handlerData.name,\n global: handlerData.global,\n });\n };\n}\n\n/**\n * Creates breadcrumbs from XHR API calls\n */\nfunction _getXhrBreadcrumbHandler(client: Client): (handlerData: HandlerDataXhr) => void {\n return function _xhrBreadcrumb(handlerData: HandlerDataXhr): void {\n if (getClient() !== client) {\n return;\n }\n\n const { startTimestamp, endTimestamp } = handlerData;\n\n const sentryXhrData = handlerData.xhr[SENTRY_XHR_DATA_KEY];\n\n // We only capture complete, non-sentry requests\n if (!startTimestamp || !endTimestamp || !sentryXhrData) {\n return;\n }\n\n const { method, url, status_code, body } = sentryXhrData;\n\n const data: XhrBreadcrumbData = {\n method,\n url,\n status_code,\n };\n\n const hint: XhrBreadcrumbHint = {\n xhr: handlerData.xhr,\n input: body,\n startTimestamp,\n endTimestamp,\n };\n\n const breadcrumb = {\n category: 'xhr',\n data,\n type: 'http',\n level: getBreadcrumbLogLevelFromHttpStatusCode(status_code),\n };\n\n client.emit('beforeOutgoingRequestBreadcrumb', breadcrumb, hint);\n\n addBreadcrumb(breadcrumb, hint);\n };\n}\n\n/**\n * Creates breadcrumbs from fetch API calls\n */\nfunction _getFetchBreadcrumbHandler(client: Client): (handlerData: HandlerDataFetch) => void {\n return function _fetchBreadcrumb(handlerData: HandlerDataFetch): void {\n if (getClient() !== client) {\n return;\n }\n\n const { startTimestamp, endTimestamp } = handlerData;\n\n // We only capture complete fetch requests\n if (!endTimestamp) {\n return;\n }\n\n if (handlerData.fetchData.url.match(/sentry_key/) && handlerData.fetchData.method === 'POST') {\n // We will not create breadcrumbs for fetch requests that contain `sentry_key` (internal sentry requests)\n return;\n }\n\n if (handlerData.error) {\n const hint: FetchBreadcrumbHint = {\n data: handlerData.error,\n input: handlerData.args,\n startTimestamp,\n endTimestamp,\n };\n\n const breadcrumb = {\n category: 'fetch',\n data: handlerData.fetchData,\n level: 'error',\n type: 'http',\n } satisfies Breadcrumb;\n\n client.emit('beforeOutgoingRequestBreadcrumb', breadcrumb, hint as FetchHint);\n\n addBreadcrumb(breadcrumb, hint);\n } else {\n const response = handlerData.response as Response | undefined;\n const data: FetchBreadcrumbData = {\n ...handlerData.fetchData,\n status_code: response?.status,\n };\n\n const hint: FetchBreadcrumbHint = {\n input: handlerData.args,\n response,\n startTimestamp,\n endTimestamp,\n };\n\n const breadcrumb = {\n category: 'fetch',\n data,\n type: 'http',\n level: getBreadcrumbLogLevelFromHttpStatusCode(data.status_code),\n };\n\n client.emit('beforeOutgoingRequestBreadcrumb', breadcrumb, hint as FetchHint);\n\n addBreadcrumb(breadcrumb, hint);\n }\n };\n}\n\n/**\n * Creates breadcrumbs from history API calls\n */\nfunction _getHistoryBreadcrumbHandler(client: Client): (handlerData: HandlerDataHistory) => void {\n return function _historyBreadcrumb(handlerData: HandlerDataHistory): void {\n if (getClient() !== client) {\n return;\n }\n\n let from: string | undefined = handlerData.from;\n let to: string | undefined = handlerData.to;\n const parsedLoc = parseUrl(WINDOW.location.href);\n let parsedFrom = from ? parseUrl(from) : undefined;\n const parsedTo = parseUrl(to);\n\n // Initial pushState doesn't provide `from` information\n if (!parsedFrom?.path) {\n parsedFrom = parsedLoc;\n }\n\n // Use only the path component of the URL if the URL matches the current\n // document (almost all the time when using pushState)\n if (parsedLoc.protocol === parsedTo.protocol && parsedLoc.host === parsedTo.host) {\n to = parsedTo.relative;\n }\n if (parsedLoc.protocol === parsedFrom.protocol && parsedLoc.host === parsedFrom.host) {\n from = parsedFrom.relative;\n }\n\n addBreadcrumb({\n category: 'navigation',\n data: {\n from,\n to,\n },\n });\n };\n}\n\nfunction _isEvent(event: unknown): event is Event {\n return !!event && !!(event as Record<string, unknown>).target;\n}\n"],"names":["addClickKeypressInstrumentationHandler","addXhrInstrumentationHandler","addFetchInstrumentationHandler","addHistoryInstrumentationHandler","defineIntegration","getClient","addBreadcrumb","getEventDescription","DEBUG_BUILD","debug","htmlTreeAsString","getComponentName","SENTRY_XHR_DATA_KEY","getBreadcrumbLogLevelFromHttpStatusCode","parseUrl","WINDOW"],"mappings":";;;;;;;AAgDA,MAAM,yBAAA,GAA4B,IAAA;AAElC,MAAM,gBAAA,GAAmB,aAAA;AAEzB,MAAM,uBAAA,IAA2B,CAAC,OAAA,GAAuC,EAAC,KAAM;AAC9E,EAAA,MAAM,QAAA,GAAW;AAAA,IACf,GAAA,EAAK,IAAA;AAAA,IACL,KAAA,EAAO,IAAA;AAAA,IACP,OAAA,EAAS,IAAA;AAAA,IACT,MAAA,EAAQ,IAAA;AAAA,IACR,GAAA,EAAK,IAAA;AAAA,IACL,GAAG;AAAA,GACL;AAEA,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,gBAAA;AAAA,IACN,MAAM,MAAA,EAAQ;AACZ,MAAA,IAAI,SAAS,GAAA,EAAK;AAChB,QAAAA,mDAAA,CAAuC,wBAAA,CAAyB,MAAA,EAAQ,QAAA,CAAS,GAAG,CAAC,CAAA;AAAA,MACvF;AACA,MAAA,IAAI,SAAS,GAAA,EAAK;AAChB,QA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MAAA;AACzD;;;;"}
|
|
@@ -3,7 +3,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
|
3
3
|
const core = require('@sentry/core');
|
|
4
4
|
|
|
5
5
|
const WINDOW = core.GLOBAL_OBJ;
|
|
6
|
-
const DEFAULT_LINES_OF_CONTEXT =
|
|
6
|
+
const DEFAULT_LINES_OF_CONTEXT = 5;
|
|
7
7
|
const INTEGRATION_NAME = "ContextLines";
|
|
8
8
|
const _contextLinesIntegration = ((options = {}) => {
|
|
9
9
|
return {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"contextlines.js","sources":["../../../../../src/integrations/contextlines.ts"],"sourcesContent":["import type { Event, IntegrationFn, StackFrame } from '@sentry/core';\nimport { addContextToFrame, defineIntegration, GLOBAL_OBJ, stripUrlQueryAndFragment } from '@sentry/core';\n\nconst WINDOW = GLOBAL_OBJ as typeof GLOBAL_OBJ & Window;\n\nconst DEFAULT_LINES_OF_CONTEXT =
|
|
1
|
+
{"version":3,"file":"contextlines.js","sources":["../../../../../src/integrations/contextlines.ts"],"sourcesContent":["import type { Event, IntegrationFn, StackFrame } from '@sentry/core';\nimport { addContextToFrame, defineIntegration, GLOBAL_OBJ, stripUrlQueryAndFragment } from '@sentry/core';\n\nconst WINDOW = GLOBAL_OBJ as typeof GLOBAL_OBJ & Window;\n\nconst DEFAULT_LINES_OF_CONTEXT = 5;\n\nconst INTEGRATION_NAME = 'ContextLines' as const;\n\ninterface ContextLinesOptions {\n /**\n * Sets the number of context lines for each frame when loading a file.\n * Defaults to `dataCollection.frameContextLines` (5).\n *\n * Set to 0 to disable loading and inclusion of source files.\n *\n * When set, this option takes precedence over `dataCollection.frameContextLines`.\n **/\n frameContextLines?: number;\n}\n\nconst _contextLinesIntegration = ((options: ContextLinesOptions = {}) => {\n return {\n name: INTEGRATION_NAME,\n processEvent(event, _hint, client) {\n const contextLines =\n options.frameContextLines ?? client?.getDataCollectionOptions().frameContextLines ?? DEFAULT_LINES_OF_CONTEXT;\n return addSourceContext(event, contextLines);\n },\n };\n}) satisfies IntegrationFn;\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 */\nexport const contextLinesIntegration = defineIntegration(_contextLinesIntegration);\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?.values;\n if (!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?.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"],"names":["GLOBAL_OBJ","defineIntegration","stripUrlQueryAndFragment","addContextToFrame"],"mappings":";;;;AAGA,MAAM,MAAA,GAASA,eAAA;AAEf,MAAM,wBAAA,GAA2B,CAAA;AAEjC,MAAM,gBAAA,GAAmB,cAAA;AAczB,MAAM,wBAAA,IAA4B,CAAC,OAAA,GAA+B,EAAC,KAAM;AACv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AAA,EAAO,SAAA,EAAW,cAAc,YAAY;AAAA,OACxE;AAAA,IACF;AAAA,EACF,CAAC,CAAA;AAED,EAAA,OAAO,KAAA;AACT;AAKO,SAAS,yBAAA,CACd,KAAA,EACA,SAAA,EACA,YAAA,EACA,cAAA,EACY;AACZ,EAAA,IAAI,KAAA,CAAM,aAAa,YAAA,IAAgB,CAAC,MAAM,MAAA,IAAU,CAAC,UAAU,MAAA,EAAQ;AACzE,IAAA,OAAO,KAAA;AAAA,EACT;AAEA,EAAAC,sBAAA,CAAkB,SAAA,EAAW,OAAO,cAAc,CAAA;AAElD,EAAA,OAAO,KAAA;AACT;;;;;"}
|
|
@@ -34,6 +34,7 @@ const httpContextIntegration = core.defineIntegration(() => {
|
|
|
34
34
|
reqData.headers,
|
|
35
35
|
client.getDataCollectionOptions().httpHeaders.request
|
|
36
36
|
);
|
|
37
|
+
const referer = headers["Referer"];
|
|
37
38
|
core.safeSetSpanJSONAttributes(span, {
|
|
38
39
|
// This attribute is used by the "Filter out events from legacy browsers and crawlers" features on the Sentry backend.
|
|
39
40
|
// Therefore, it's set on every span.
|
|
@@ -43,7 +44,7 @@ const httpContextIntegration = core.defineIntegration(() => {
|
|
|
43
44
|
// Coerce empty string to undefined so the helper's nullish check drops it,
|
|
44
45
|
// rather than writing an empty `url.full` attribute onto the span.
|
|
45
46
|
[attributes.URL_FULL]: span.attributes?.[attributes.SENTRY_OP] !== "http.client" ? core.filterCollectedUrl(reqData.url) : void 0,
|
|
46
|
-
[`${attributes.HTTP_REQUEST_HEADER_KEY_BASE}.referer`]:
|
|
47
|
+
[`${attributes.HTTP_REQUEST_HEADER_KEY_BASE}.referer`]: referer ? [referer] : void 0
|
|
47
48
|
}
|
|
48
49
|
});
|
|
49
50
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"httpcontext.js","sources":["../../../../../src/integrations/httpcontext.ts"],"sourcesContent":["import { _INTERNAL_filterKeyValueData, defineIntegration, safeSetSpanJSONAttributes } from '@sentry/core';\nimport { getHttpRequestData, WINDOW } from '../helpers';\nimport { filterCollectedUrl } from '@sentry/core';\nimport { HTTP_REQUEST_HEADER_KEY_BASE, SENTRY_OP, URL_FULL, USER_AGENT_ORIGINAL } from '@sentry/conventions/attributes';\n\n/**\n * Collects information about HTTP request headers and\n * attaches them to the event.\n */\nexport const httpContextIntegration = defineIntegration(() => {\n return {\n name: 'HttpContext' as const,\n preprocessEvent(event, _hint, client) {\n // if none of the information we want exists, don't bother\n if (!WINDOW.navigator && !WINDOW.location && !WINDOW.document) {\n return;\n }\n\n const { url, headers: collectedHeaders } = getHttpRequestData();\n\n // We only filter the headers we collected ourselves, so headers the user set are left alone. Going by key\n // means we also catch these headers when `browserTracingIntegration` already put them on the event.\n const behavior = client.getDataCollectionOptions().httpHeaders.request;\n const userHeaders = Object.entries(event.request?.headers ?? {}).filter(([key]) => !(key in collectedHeaders));\n\n const headers = {\n ..._INTERNAL_filterKeyValueData(collectedHeaders, behavior),\n ...Object.fromEntries(userHeaders),\n };\n\n event.request = {\n // The URL isn't gated by `dataCollection`, same as on the server.\n url,\n ...event.request,\n ...(Object.keys(headers).length > 0 ? { headers } : { headers: undefined }),\n };\n },\n\n processSpan(span, client) {\n // if none of the information we want exists, don't bother\n if (!WINDOW.navigator && !WINDOW.location && !WINDOW.document) {\n return;\n }\n\n const reqData = getHttpRequestData();\n\n // `httpHeadersToSpanAttributes` would also work here, but its cookie and array handling never runs for these\n // two headers and costs every browser bundle ~400B gzip.\n const headers = _INTERNAL_filterKeyValueData(\n reqData.headers,\n client.getDataCollectionOptions().httpHeaders.request,\n );\n\n safeSetSpanJSONAttributes(span, {\n // This attribute is used by the \"Filter out events from legacy browsers and crawlers\" features on the Sentry backend.\n // Therefore, it's set on every span.\n [USER_AGENT_ORIGINAL]: headers['User-Agent'],\n\n // These attributes, we only need on the segment span (analogous to the `request` context for events)\n ...(span.is_segment && {\n // Coerce empty string to undefined so the helper's nullish check drops it,\n // rather than writing an empty `url.full` attribute onto the span.\n [URL_FULL]: span.attributes?.[SENTRY_OP] !== 'http.client' ? filterCollectedUrl(reqData.url) : undefined,\n [`${HTTP_REQUEST_HEADER_KEY_BASE}.referer`]:
|
|
1
|
+
{"version":3,"file":"httpcontext.js","sources":["../../../../../src/integrations/httpcontext.ts"],"sourcesContent":["import { _INTERNAL_filterKeyValueData, defineIntegration, safeSetSpanJSONAttributes } from '@sentry/core';\nimport { getHttpRequestData, WINDOW } from '../helpers';\nimport { filterCollectedUrl } from '@sentry/core';\nimport { HTTP_REQUEST_HEADER_KEY_BASE, SENTRY_OP, URL_FULL, USER_AGENT_ORIGINAL } from '@sentry/conventions/attributes';\n\n/**\n * Collects information about HTTP request headers and\n * attaches them to the event.\n */\nexport const httpContextIntegration = defineIntegration(() => {\n return {\n name: 'HttpContext' as const,\n preprocessEvent(event, _hint, client) {\n // if none of the information we want exists, don't bother\n if (!WINDOW.navigator && !WINDOW.location && !WINDOW.document) {\n return;\n }\n\n const { url, headers: collectedHeaders } = getHttpRequestData();\n\n // We only filter the headers we collected ourselves, so headers the user set are left alone. Going by key\n // means we also catch these headers when `browserTracingIntegration` already put them on the event.\n const behavior = client.getDataCollectionOptions().httpHeaders.request;\n const userHeaders = Object.entries(event.request?.headers ?? {}).filter(([key]) => !(key in collectedHeaders));\n\n const headers = {\n ..._INTERNAL_filterKeyValueData(collectedHeaders, behavior),\n ...Object.fromEntries(userHeaders),\n };\n\n event.request = {\n // The URL isn't gated by `dataCollection`, same as on the server.\n url,\n ...event.request,\n ...(Object.keys(headers).length > 0 ? { headers } : { headers: undefined }),\n };\n },\n\n processSpan(span, client) {\n // if none of the information we want exists, don't bother\n if (!WINDOW.navigator && !WINDOW.location && !WINDOW.document) {\n return;\n }\n\n const reqData = getHttpRequestData();\n\n // `httpHeadersToSpanAttributes` would also work here, but its cookie and array handling never runs for these\n // two headers and costs every browser bundle ~400B gzip.\n const headers = _INTERNAL_filterKeyValueData(\n reqData.headers,\n client.getDataCollectionOptions().httpHeaders.request,\n );\n const referer = headers['Referer'];\n\n safeSetSpanJSONAttributes(span, {\n // This attribute is used by the \"Filter out events from legacy browsers and crawlers\" features on the Sentry backend.\n // Therefore, it's set on every span.\n [USER_AGENT_ORIGINAL]: headers['User-Agent'],\n\n // These attributes, we only need on the segment span (analogous to the `request` context for events)\n ...(span.is_segment && {\n // Coerce empty string to undefined so the helper's nullish check drops it,\n // rather than writing an empty `url.full` attribute onto the span.\n [URL_FULL]: span.attributes?.[SENTRY_OP] !== 'http.client' ? filterCollectedUrl(reqData.url) : undefined,\n [`${HTTP_REQUEST_HEADER_KEY_BASE}.referer`]: referer ? [referer] : undefined,\n }),\n });\n },\n };\n});\n"],"names":["defineIntegration","WINDOW","getHttpRequestData","_INTERNAL_filterKeyValueData","safeSetSpanJSONAttributes","USER_AGENT_ORIGINAL","URL_FULL","SENTRY_OP","filterCollectedUrl","HTTP_REQUEST_HEADER_KEY_BASE"],"mappings":";;;;;;AASO,MAAM,sBAAA,GAAyBA,uBAAkB,MAAM;AAC5D,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,aAAA;AAAA,IACN,eAAA,CAAgB,KAAA,EAAO,KAAA,EAAO,MAAA,EAAQ;AAEpC,MAAA,IAAI,CAACC,eAAO,SAAA,IAAa,CAACA,eAAO,QAAA,IAAY,CAACA,eAAO,QAAA,EAAU;AAC7D,QAAA;AAAA,MACF;AAEA,MAAA,MAAM,EAAE,GAAA,EAAK,OAAA,EAAS,gBAAA,KAAqBC,0BAAA,EAAmB;AAI9D,MAAA,MAAM,QAAA,GAAW,MAAA,CAAO,wBAAA,EAAyB,CAAE,WAAA,CAAY,OAAA;AAC/D,MAAA,MAAM,cAAc,MAAA,CAAO,OAAA,CAAQ,KAAA,CAAM,OAAA,EAAS,WAAW,EAAE,CAAA,CAAE,MAAA,CAAO,CAAC,CAAC,GAAG,CAAA,KAAM,EAAE,OAAO,gBAAA,CAAiB,CAAA;AAE7G,MAAA,MAAM,OAAA,GAAU;AAAA,QACd,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 +5,22 @@ const browserUtils = require('@sentry/browser-utils');
|
|
|
5
5
|
|
|
6
6
|
const WEB_VITALS_INTEGRATION_NAME = "WebVitals";
|
|
7
7
|
const webVitalsIntegration = core.defineIntegration((options = {}) => {
|
|
8
|
-
const
|
|
8
|
+
const { ignore = [], softNavigations = true, bfcacheNavigations = true } = options;
|
|
9
|
+
const ignored = new Set(ignore);
|
|
9
10
|
return {
|
|
10
11
|
name: WEB_VITALS_INTEGRATION_NAME,
|
|
11
12
|
setup(client) {
|
|
12
13
|
const spanStreamingEnabled = core.hasSpanStreamingEnabled(client);
|
|
14
|
+
const reportSoftNavs = softNavigations && spanStreamingEnabled && browserUtils.supportsSoftNavigations();
|
|
15
|
+
const reportBfcache = bfcacheNavigations && spanStreamingEnabled;
|
|
16
|
+
const perNavigation = reportSoftNavs || reportBfcache;
|
|
17
|
+
if (reportSoftNavs) {
|
|
18
|
+
browserUtils.enableSoftNavigationReporting();
|
|
19
|
+
browserUtils.startSoftNavigationCorrelation(client);
|
|
20
|
+
}
|
|
21
|
+
if (reportBfcache) {
|
|
22
|
+
browserUtils.enableBfcacheReporting();
|
|
23
|
+
}
|
|
13
24
|
const trackClsOnPageloadSpan = !spanStreamingEnabled && !ignored.has("cls");
|
|
14
25
|
const trackLcpOnPageloadSpan = !spanStreamingEnabled && !ignored.has("lcp");
|
|
15
26
|
const finalizeWebVitals = browserUtils.startTrackingWebVitals({
|
|
@@ -34,14 +45,14 @@ const webVitalsIntegration = core.defineIntegration((options = {}) => {
|
|
|
34
45
|
});
|
|
35
46
|
if (spanStreamingEnabled) {
|
|
36
47
|
if (!ignored.has("lcp")) {
|
|
37
|
-
browserUtils.trackLcpAsSpan(client);
|
|
48
|
+
browserUtils.trackLcpAsSpan(client, perNavigation);
|
|
38
49
|
}
|
|
39
50
|
if (!ignored.has("cls")) {
|
|
40
|
-
browserUtils.trackClsAsSpan(client);
|
|
51
|
+
browserUtils.trackClsAsSpan(client, perNavigation);
|
|
41
52
|
}
|
|
42
53
|
}
|
|
43
54
|
if (!ignored.has("inp")) {
|
|
44
|
-
browserUtils.trackInpAsSpan(client);
|
|
55
|
+
browserUtils.trackInpAsSpan(client, perNavigation);
|
|
45
56
|
}
|
|
46
57
|
},
|
|
47
58
|
afterAllSetup() {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"webVitals.js","sources":["../../../../../src/integrations/webVitals.ts"],"sourcesContent":["import type { IntegrationFn, Span } from '@sentry/core';\nimport { defineIntegration, hasSpanStreamingEnabled } from '@sentry/core';\nimport {\n addWebVitalsToSpan,\n registerInpInteractionListener,\n startTrackingWebVitals,\n trackClsAsSpan,\n trackInpAsSpan,\n trackLcpAsSpan,\n} from '@sentry/browser-utils';\n\nexport const WEB_VITALS_INTEGRATION_NAME = 'WebVitals' as const;\n\nexport type WebVitalName = 'cls' | 'inp' | 'lcp';\n\nexport interface WebVitalsOptions {\n /**\n * Web vitals to skip.\n */\n ignore?: WebVitalName[];\n}\n\n/**\n * Captures Core Web Vitals (LCP, CLS, INP) and related pageload vitals.\n *\n * `browserTracingIntegration` auto-registers this integration if no\n * `webVitalsIntegration` is already present, so explicit registration is only\n * needed to customize options or to use it without `browserTracingIntegration`.\n */\nexport const webVitalsIntegration = defineIntegration((options: WebVitalsOptions = {}) => {\n const ignored = new Set(
|
|
1
|
+
{"version":3,"file":"webVitals.js","sources":["../../../../../src/integrations/webVitals.ts"],"sourcesContent":["import type { IntegrationFn, Span } from '@sentry/core';\nimport { defineIntegration, hasSpanStreamingEnabled } from '@sentry/core';\nimport {\n addWebVitalsToSpan,\n enableBfcacheReporting,\n enableSoftNavigationReporting,\n registerInpInteractionListener,\n startSoftNavigationCorrelation,\n startTrackingWebVitals,\n supportsSoftNavigations,\n trackClsAsSpan,\n trackInpAsSpan,\n trackLcpAsSpan,\n} from '@sentry/browser-utils';\n\nexport const WEB_VITALS_INTEGRATION_NAME = 'WebVitals' as const;\n\nexport type WebVitalName = 'cls' | 'inp' | 'lcp';\n\nexport interface WebVitalsOptions {\n /**\n * Web vitals to skip.\n */\n ignore?: WebVitalName[];\n\n /**\n * Give each soft navigation its own set of LCP, CLS and INP, detected through the browser's\n * [Soft Navigations API](https://developer.chrome.com/docs/web-platform/soft-navigations-experiment)\n * (Chromium 151+).\n *\n * Each soft navigation's vitals are reported against the navigation span they belong to. This\n * also changes how the initial page load is measured: its vitals are finalized at the first soft\n * navigation rather than accumulating over the page's lifetime.\n *\n * Soft navigations the browser doesn't detect (programmatic navigations, navigations that never\n * paint) report no vitals at all, so coverage is lower than for page loads. Set this to `false`\n * to report a single set of vitals for the whole page lifetime instead.\n *\n * Requires span streaming (`traceLifecycle: 'stream'`, the default), since soft navigation vitals\n * are finalized long after the navigation span they belong to has ended. Ignored in browsers\n * without support for the Soft Navigations API.\n *\n * Default: `true`\n */\n softNavigations?: boolean;\n\n /**\n * Give each back/forward-cache restore its own set of LCP, CLS and INP.\n *\n * A restore is a new page view measured against a document that was never reloaded, so its vitals\n * are reported against the navigation span `browserTracingIntegration` starts for the restore,\n * and tagged `browser.navigation.type: bfcache`. A restore is near-instant by construction, so\n * these are a distinct population from page load vitals and are meant to be read through that\n * attribute rather than pooled with them. Set this to `false` to leave restores unmeasured.\n *\n * Requires span streaming (`traceLifecycle: 'stream'`, the default) and\n * `browserTracingIntegration`, which supplies the navigation span these attach to.\n *\n * Default: `true`\n */\n bfcacheNavigations?: boolean;\n}\n\n/**\n * Captures Core Web Vitals (LCP, CLS, INP) and related pageload vitals.\n *\n * `browserTracingIntegration` auto-registers this integration if no\n * `webVitalsIntegration` is already present, so explicit registration is only\n * needed to customize options or to use it without `browserTracingIntegration`.\n */\nexport const webVitalsIntegration = defineIntegration((options: WebVitalsOptions = {}) => {\n const { ignore = [], softNavigations = true, bfcacheNavigations = true } = options;\n const ignored = new Set(ignore);\n\n return {\n name: WEB_VITALS_INTEGRATION_NAME,\n setup(client) {\n const spanStreamingEnabled = hasSpanStreamingEnabled(client);\n\n // Soft navigation vitals are finalized at the next soft navigation or on pagehide, long after\n // the navigation span they belong to has ended. Only span streaming can still send them.\n const reportSoftNavs = softNavigations && spanStreamingEnabled && supportsSoftNavigations();\n const reportBfcache = bfcacheNavigations && spanStreamingEnabled;\n\n // Both attribute a vital to the page view it was measured on rather than to the page load, so\n // either one puts the trackers on the per-navigation path.\n const perNavigation = reportSoftNavs || reportBfcache;\n\n // These have to run before any web vital observer is instrumented, since web-vitals only\n // reads its options when the observer is set up.\n if (reportSoftNavs) {\n enableSoftNavigationReporting();\n startSoftNavigationCorrelation(client);\n }\n\n if (reportBfcache) {\n enableBfcacheReporting();\n }\n\n // With span streaming enabled, CLS and LCP are tracked as standalone v2 spans (like INP).\n // Otherwise, they're recorded as measurements on the pageload span.\n const trackClsOnPageloadSpan = !spanStreamingEnabled && !ignored.has('cls');\n const trackLcpOnPageloadSpan = !spanStreamingEnabled && !ignored.has('lcp');\n\n const finalizeWebVitals = startTrackingWebVitals({\n trackCls: trackClsOnPageloadSpan,\n trackLcp: trackLcpOnPageloadSpan,\n client,\n });\n\n const pageloadSpans = new WeakSet<Span>();\n\n client.on('afterStartPageLoadSpan', span => {\n pageloadSpans.add(span);\n });\n\n client.on('spanEnd', span => {\n if (!pageloadSpans.delete(span)) {\n return;\n }\n\n finalizeWebVitals();\n addWebVitalsToSpan(span, {\n recordClsOnPageloadSpan: trackClsOnPageloadSpan,\n recordLcpOnPageloadSpan: trackLcpOnPageloadSpan,\n spanStreamingEnabled,\n });\n });\n\n if (spanStreamingEnabled) {\n if (!ignored.has('lcp')) {\n trackLcpAsSpan(client, perNavigation);\n }\n if (!ignored.has('cls')) {\n trackClsAsSpan(client, perNavigation);\n }\n }\n\n // INP is always sent as a streamed web vital span. When span streaming is disabled, INP still\n // streams (it overrides the static trace lifecycle for INP only), see `trackInpAsSpan`.\n if (!ignored.has('inp')) {\n trackInpAsSpan(client, perNavigation);\n }\n },\n afterAllSetup() {\n if (!ignored.has('inp')) {\n registerInpInteractionListener();\n }\n },\n };\n}) satisfies IntegrationFn;\n"],"names":["defineIntegration","hasSpanStreamingEnabled","supportsSoftNavigations","enableSoftNavigationReporting","startSoftNavigationCorrelation","enableBfcacheReporting","startTrackingWebVitals","addWebVitalsToSpan","trackLcpAsSpan","trackClsAsSpan","trackInpAsSpan","registerInpInteractionListener"],"mappings":";;;;;AAeO,MAAM,2BAAA,GAA8B;AAuDpC,MAAM,oBAAA,GAAuBA,sBAAA,CAAkB,CAAC,OAAA,GAA4B,EAAC,KAAM;AACxF,EAAA,MAAM,EAAE,SAAS,EAAC,EAAG,kBAAkB,IAAA,EAAM,kBAAA,GAAqB,MAAK,GAAI,OAAA;AAC3E,EAAA,MAAM,OAAA,GAAU,IAAI,GAAA,CAAI,MAAM,CAAA;AAE9B,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,2BAAA;AAAA,IACN,MAAM,MAAA,EAAQ;AACZ,MAAA,MAAM,oBAAA,GAAuBC,6BAAwB,MAAM,CAAA;AAI3D,MAAA,MAAM,cAAA,GAAiB,eAAA,IAAmB,oBAAA,IAAwBC,oCAAA,EAAwB;AAC1F,MAAA,MAAM,gBAAgB,kBAAA,IAAsB,oBAAA;AAI5C,MAAA,MAAM,gBAAgB,cAAA,IAAkB,aAAA;AAIxC,MAAA,IAAI,cAAA,EAAgB;AAClB,QAAAC,0CAAA,EAA8B;AAC9B,QAAAC,2CAAA,CAA+B,MAAM,CAAA;AAAA,MACvC;AAEA,MAAA,IAAI,aAAA,EAAe;AACjB,QAAAC,mCAAA,EAAuB;AAAA,MACzB;AAIA,MAAA,MAAM,yBAAyB,CAAC,oBAAA,IAAwB,CAAC,OAAA,CAAQ,IAAI,KAAK,CAAA;AAC1E,MAAA,MAAM,yBAAyB,CAAC,oBAAA,IAAwB,CAAC,OAAA,CAAQ,IAAI,KAAK,CAAA;AAE1E,MAAA,MAAM,oBAAoBC,mCAAA,CAAuB;AAAA,QAC/C,QAAA,EAAU,sBAAA;AAAA,QACV,QAAA,EAAU,sBAAA;AAAA,QACV;AAA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