@sentry/browser
Version:
Official Sentry SDK for browsers
372 lines (371 loc) • 17.8 kB
JavaScript
const require_debug_build = require("../debug-build.js");
const require_helpers = require("../helpers.js");
const require_webVitals = require("../integrations/webVitals.js");
const require_backgroundtab = require("./backgroundtab.js");
const require_linkedTraces = require("../integrations/linkedTraces.js");
const require_fetchTracing = require("../integrations/fetchTracing.js");
const require_xhrTracing = require("../integrations/xhrTracing.js");
let _sentry_core = require("@sentry/core");
let _sentry_browser_utils = require("@sentry/browser-utils");
let _sentry_conventions_attributes = require("@sentry/conventions/attributes");
let _sentry_conventions_op = require("@sentry/conventions/op");
let _sentry_core_browser = require("@sentry/core/browser");
// src/tracing/browserTracingIntegration.ts
const BROWSER_TRACING_INTEGRATION_ID = "BrowserTracing";
const DEFAULT_BROWSER_TRACING_OPTIONS = {
..._sentry_core.TRACING_DEFAULTS,
instrumentNavigation: true,
instrumentBfcacheRestore: true,
instrumentPageLoad: true,
markBackgroundSpan: true,
detectRedirects: true,
enableReportPageLoaded: false
};
/**
* Defaults for the options that `browserTracingIntegration` forwards to the integrations it registers.
* They are spread rather than destructured, so an explicit `undefined` still overrides them.
*/
const DEFAULT_FORWARDED_OPTIONS = {
enableInp: true,
enableLongTask: true,
enableLongAnimationFrame: true,
traceFetch: true,
traceXHR: true,
linkPreviousTrace: "in-memory"
};
/**
* The Browser Tracing integration automatically instruments browser pageload/navigation
* actions as transactions, and captures requests, metrics and errors as spans.
*
* The integration can be configured with a variety of options, and can be extended to use
* any routing library.
*
* We explicitly export the proper type here, as this has to be extended in some cases.
*/
const browserTracingIntegration = ((options = {}) => {
if ("enableElementTiming" in options) (0, _sentry_core.consoleSandbox)(() => {
console.warn("[Sentry] `enableElementTiming` is deprecated and no longer has any effect. Use the standalone `elementTimingIntegration` instead.");
});
const { enableInp, webVitals, enableLongTask, enableLongAnimationFrame, ignoreResourceSpans, traceFetch, traceXHR, shouldCreateSpanForRequest, enableHTTPTimings, onRequestSpanStart, onRequestSpanEnd, linkPreviousTrace, consistentTraceSampling } = {
...DEFAULT_FORWARDED_OPTIONS,
...options
};
return _browserTracingIntegration(options, (client) => {
if (!client.addIntegration) return;
const ignore = webVitals?.ignore ?? [];
client.addIntegration(require_webVitals.webVitalsIntegration({
...webVitals,
ignore: enableInp || ignore.includes("inp") ? ignore : [...ignore, "inp"]
}));
if (enableLongTask || enableLongAnimationFrame) client.addIntegration((0, _sentry_browser_utils.longTasksIntegration)({
enableLongTask,
enableLongAnimationFrame
}));
client.addIntegration((0, _sentry_browser_utils.resourcesIntegration)({ ignoreResourceSpans }));
const requestOptions = {
shouldCreateSpanForRequest,
enableHTTPTimings,
onRequestSpanStart,
onRequestSpanEnd
};
if (traceFetch) client.addIntegration(require_fetchTracing.fetchTracingIntegration(requestOptions));
if (traceXHR) client.addIntegration(require_xhrTracing.xhrTracingIntegration(requestOptions));
if (linkPreviousTrace !== "off") client.addIntegration(require_linkedTraces.linkedTracesIntegration({
storage: linkPreviousTrace,
consistentTraceSampling
}));
});
});
/**
* The pageload and navigation spans of `browserTracingIntegration`, without the features it registers as
* standalone integrations (such as `webVitalsIntegration`).
*
* Use it instead of `browserTracingIntegration` to only bundle the integrations you add yourself.
*/
const browserTracingCoreIntegration = ((options = {}) => _browserTracingIntegration(options));
function _browserTracingIntegration(options, addDefaultIntegrations) {
/**
* This is just a small wrapper that makes `document` optional.
* We want to be extra-safe and always check that this exists, to ensure weird environments do not blow up.
*/
const optionalWindowDocument = require_helpers.WINDOW.document;
const { beforeStartSpan, idleTimeout, finalTimeout, childSpanTimeout, markBackgroundSpan, instrumentPageLoad, instrumentNavigation, instrumentBfcacheRestore, detectRedirects, enableReportPageLoaded } = {
...DEFAULT_BROWSER_TRACING_OPTIONS,
...options
};
const _isBot = (0, _sentry_browser_utils.isBotUserAgent)();
let lastInteractionTimestamp;
let _pageloadSpan;
/** Create routing idle transaction. */
function _createRouteSpan(client, startSpanOptions, makeActive = true, url) {
const isPageloadSpan = startSpanOptions.op === "pageload";
const initialSpanName = startSpanOptions.name;
const finalStartSpanOptions = beforeStartSpan ? beforeStartSpan(startSpanOptions) : startSpanOptions;
const urlObject = (0, _sentry_core.parseStringToURLObject)(url || (0, _sentry_browser_utils.getLocationHref)());
const attributes = {
[_sentry_conventions_attributes.URL_PATH]: urlObject?.pathname,
...urlObject && !(0, _sentry_core.isURLObjectRelative)(urlObject) && { [_sentry_conventions_attributes.URL_FULL]: (0, _sentry_core.filterCollectedUrl)(urlObject.href) },
...finalStartSpanOptions.attributes
};
if (initialSpanName !== finalStartSpanOptions.name) attributes[_sentry_conventions_attributes.SENTRY_SEGMENT_NAME_SOURCE] = "custom";
finalStartSpanOptions.attributes = attributes;
if (!makeActive) {
const now = (0, _sentry_core.dateTimestampInSeconds)();
(0, _sentry_core_browser.startInactiveSpan)({
...finalStartSpanOptions,
startTime: now
}).end(now);
return;
}
const idleSpan = (0, _sentry_core_browser.startIdleSpan)(finalStartSpanOptions, {
idleTimeout,
finalTimeout,
childSpanTimeout,
disableAutoFinish: isPageloadSpan,
trimIdleSpanEndTimestamp: !enableReportPageLoaded
});
if (isPageloadSpan && enableReportPageLoaded) _pageloadSpan = idleSpan;
setActiveIdleSpan(client, idleSpan);
function emitFinish() {
if (optionalWindowDocument && ["interactive", "complete"].includes(optionalWindowDocument.readyState)) {
client.emit("idleSpanEnableAutoFinish", idleSpan);
optionalWindowDocument.removeEventListener("readystatechange", emitFinish);
}
}
if (isPageloadSpan && !enableReportPageLoaded && optionalWindowDocument) {
optionalWindowDocument.addEventListener("readystatechange", emitFinish);
emitFinish();
}
}
return {
name: BROWSER_TRACING_INTEGRATION_ID,
setup(client) {
if (_isBot) {
require_debug_build.DEBUG_BUILD && _sentry_core.debug.log("[Tracing] Skipping browserTracingIntegration setup for bot user agent.");
return;
}
(0, _sentry_core.registerSpanErrorInstrumentation)();
if (detectRedirects && optionalWindowDocument) {
const interactionHandler = () => {
lastInteractionTimestamp = (0, _sentry_core.timestampInSeconds)();
};
addEventListener("click", interactionHandler, { capture: true });
addEventListener("keydown", interactionHandler, {
capture: true,
passive: true
});
}
function maybeEndActiveSpan() {
const activeSpan = getActiveIdleSpan(client);
if (activeSpan && !(0, _sentry_core.spanToJSON)(activeSpan).end_timestamp) {
require_debug_build.DEBUG_BUILD && _sentry_core.debug.log(`[Tracing] Finishing current active span with op: ${(0, _sentry_core.spanToJSON)(activeSpan).attributes[_sentry_conventions_attributes.SENTRY_OP]}`);
activeSpan.setAttribute(_sentry_conventions_attributes.SENTRY_IDLE_SPAN_FINISH_REASON, "cancelled");
activeSpan.end();
}
}
client.on("beforeIdleSpanEnd", (span) => {
if (getActiveIdleSpan(client) !== span) return;
(0, _sentry_browser_utils.addPerformanceEntries)(span, { spanStreamingEnabled: (0, _sentry_core.hasSpanStreamingEnabled)(client) });
setActiveIdleSpan(client, void 0);
const scope = (0, _sentry_core.getCurrentScope)();
const oldPropagationContext = scope.getPropagationContext();
scope.setPropagationContext({
...oldPropagationContext,
traceId: span.spanContext().traceId,
sampled: (0, _sentry_core.spanIsSampled)(span),
dsc: (0, _sentry_core.getDynamicSamplingContextFromSpan)(span)
});
if (_pageloadSpan === span) _pageloadSpan = void 0;
});
client.on("startNavigationSpan", (startSpanOptions, navigationOptions) => {
if ((0, _sentry_core.getClient)() !== client) return;
if (navigationOptions?.isRedirect) {
require_debug_build.DEBUG_BUILD && _sentry_core.debug.warn("[Tracing] Detected redirect, navigation span will not be the root span, but a child span.");
_createRouteSpan(client, {
op: _sentry_conventions_op.NAVIGATION_REDIRECT,
...startSpanOptions
}, false, navigationOptions.url);
return;
}
lastInteractionTimestamp = void 0;
maybeEndActiveSpan();
const scope = (0, _sentry_core.getCurrentScope)();
scope.setPropagationContext({
traceId: (0, _sentry_core.generateTraceId)(),
sampleRand: Math.random(),
propagationSpanId: (0, _sentry_core.hasSpansEnabled)() ? void 0 : (0, _sentry_core.generateSpanId)()
});
scope.setSDKProcessingMetadata({ normalizedRequest: void 0 });
_createRouteSpan(client, {
op: _sentry_conventions_op.NAVIGATION,
...startSpanOptions,
parentSpan: null
}, true, navigationOptions?.url);
});
client.on("startPageLoadSpan", (startSpanOptions, traceOptions = {}) => {
if ((0, _sentry_core.getClient)() !== client) return;
maybeEndActiveSpan();
const sentryTrace = traceOptions.sentryTrace || getMetaContent("sentry-trace") || getServerTiming("sentry-trace");
const baggage = traceOptions.baggage || getMetaContent("baggage") || getServerTiming("baggage");
const propagationContext = (0, _sentry_core.propagationContextFromHeaders)(sentryTrace, baggage);
const scope = (0, _sentry_core.getCurrentScope)();
scope.setPropagationContext(propagationContext);
if (!(0, _sentry_core.hasSpansEnabled)()) scope.getPropagationContext().propagationSpanId = (0, _sentry_core.generateSpanId)();
const requestData = require_helpers.getHttpRequestData(client);
scope.setSDKProcessingMetadata({ normalizedRequest: {
...requestData,
url: (0, _sentry_core.filterCollectedUrl)(requestData.url, client)
} });
_createRouteSpan(client, {
op: _sentry_conventions_op.PAGELOAD,
...startSpanOptions
});
});
client.on("endPageloadSpan", () => {
if (enableReportPageLoaded && _pageloadSpan) {
_pageloadSpan.setAttribute(_sentry_conventions_attributes.SENTRY_IDLE_SPAN_FINISH_REASON, "reportPageLoaded");
_pageloadSpan.end();
}
});
require_helpers.WINDOW.addEventListener?.("pagehide", () => {
const activeSpan = getActiveIdleSpan(client);
if (activeSpan && !(0, _sentry_core.spanToJSON)(activeSpan).end_timestamp) {
activeSpan.setAttribute(_sentry_conventions_attributes.SENTRY_IDLE_SPAN_FINISH_REASON, "documentHidden");
activeSpan.end();
}
client.flush();
});
},
afterAllSetup(client) {
if (_isBot) return;
(0, _sentry_core_browser._INTERNAL_ensureBrowserSpanStreaming)(client);
addDefaultIntegrations?.(client);
let startingUrl = (0, _sentry_browser_utils.getLocationHref)();
if (require_helpers.WINDOW.location) {
if (instrumentPageLoad) startBrowserTracingPageLoadSpan(client, {
name: (0, _sentry_core.hasSpanStreamingEnabled)(client) ? _sentry_core.PAGELOAD_SPAN_NAME_FALLBACK : require_helpers.WINDOW.location.pathname,
attributes: {
[_sentry_conventions_attributes.SENTRY_SEGMENT_NAME_SOURCE]: "url",
[_sentry_conventions_attributes.SENTRY_ORIGIN]: "auto.pageload.browser"
}
});
if (instrumentNavigation) (0, _sentry_browser_utils.addHistoryInstrumentationHandler)(({ to, from }) => {
/**
* This early return is there to account for some cases where a navigation transaction starts right after
* long-running pageload. We make sure that if `from` is undefined and a valid `startingURL` exists, we don't
* create an uneccessary navigation transaction.
*
* This was hard to duplicate, but this behavior stopped as soon as this fix was applied. This issue might also
* only be caused in certain development environments where the usage of a hot module reloader is causing
* errors.
*/
if (from === void 0 && startingUrl !== void 0 && startingUrl.indexOf(to) !== -1) {
startingUrl = void 0;
return;
}
startingUrl = void 0;
const parsed = (0, _sentry_core.parseStringToURLObject)(to);
const activeSpan = getActiveIdleSpan(client);
const navigationIsRedirect = activeSpan && detectRedirects && isRedirect(activeSpan, lastInteractionTimestamp);
startBrowserTracingNavigationSpan(client, {
name: (0, _sentry_core.hasSpanStreamingEnabled)(client) ? _sentry_core.NAVIGATION_SPAN_NAME_FALLBACK : parsed?.pathname || require_helpers.WINDOW.location.pathname,
attributes: {
[_sentry_conventions_attributes.SENTRY_SEGMENT_NAME_SOURCE]: "url",
[_sentry_conventions_attributes.SENTRY_ORIGIN]: "auto.navigation.browser"
}
}, {
url: to,
isRedirect: navigationIsRedirect
});
});
if (instrumentBfcacheRestore) require_helpers.WINDOW.addEventListener?.("pageshow", (event) => {
if (!event.persisted) return;
startingUrl = void 0;
startBrowserTracingNavigationSpan(client, {
name: (0, _sentry_core.hasSpanStreamingEnabled)(client) ? _sentry_core.NAVIGATION_SPAN_NAME_FALLBACK : require_helpers.WINDOW.location?.pathname || "/",
attributes: {
[_sentry_conventions_attributes.SENTRY_SEGMENT_NAME_SOURCE]: "url",
[_sentry_conventions_attributes.SENTRY_ORIGIN]: "auto.navigation.browser.bfcache",
[_sentry_conventions_attributes.BROWSER_NAVIGATION_TYPE]: "back-forward-cache"
}
}, { url: require_helpers.WINDOW.location?.href });
});
}
if (markBackgroundSpan) require_backgroundtab.registerBackgroundTabDetection();
}
};
}
/**
* Manually start a page load span.
* This will only do something if a browser tracing integration integration has been setup.
*
* If you provide a custom `traceOptions` object, it will be used to continue the trace
* instead of the default behavior, which is to look it up on the <meta> tags.
*/
function startBrowserTracingPageLoadSpan(client, spanOptions, traceOptions) {
const isFallbackSpanName = spanOptions.name === _sentry_core.PAGELOAD_SPAN_NAME_FALLBACK;
(0, _sentry_core.getCurrentScope)().setTransactionName(isFallbackSpanName ? require_helpers.WINDOW.location?.pathname : spanOptions.name);
const timeOrigin = (0, _sentry_core.browserPerformanceTimeOrigin)();
const pageloadSpanOptions = {
...spanOptions,
startTime: spanOptions.startTime ?? (timeOrigin ? timeOrigin / 1e3 : void 0)
};
client.emit("startPageLoadSpan", pageloadSpanOptions, traceOptions);
const pageloadSpan = getActiveIdleSpan(client);
if (pageloadSpan) client.emit("afterStartPageLoadSpan", pageloadSpan);
return pageloadSpan;
}
/**
* Manually start a navigation span.
* This will only do something if a browser tracing integration has been setup.
*/
function startBrowserTracingNavigationSpan(client, spanOptions, options) {
const { url, isRedirect } = options || {};
client.emit("beforeStartNavigationSpan", spanOptions, {
isRedirect,
url
});
client.emit("startNavigationSpan", spanOptions, {
isRedirect,
url
});
const scope = (0, _sentry_core.getCurrentScope)();
const isFallbackSpanName = spanOptions.name === _sentry_core.NAVIGATION_SPAN_NAME_FALLBACK;
scope.setTransactionName(isFallbackSpanName ? url && (0, _sentry_core.parseStringToURLObject)(url)?.pathname || require_helpers.WINDOW.location?.pathname : spanOptions.name);
if (url && !isRedirect) scope.setSDKProcessingMetadata({ normalizedRequest: {
...require_helpers.getHttpRequestData(client),
url: (0, _sentry_core.filterCollectedUrl)(url, client)
} });
return getActiveIdleSpan(client);
}
/** Returns the value of a meta tag */
function getMetaContent(metaName) {
return (require_helpers.WINDOW.document?.querySelector(`meta[name=${metaName}]`))?.getAttribute("content") || void 0;
}
/** Returns the description of a server timing entry */
function getServerTiming(name) {
return ((require_helpers.WINDOW.performance?.getEntriesByType?.("navigation")[0])?.serverTiming?.find((entry) => entry.name === name))?.description;
}
const ACTIVE_IDLE_SPAN_PROPERTY = "_sentry_idleSpan";
function getActiveIdleSpan(client) {
return client[ACTIVE_IDLE_SPAN_PROPERTY];
}
function setActiveIdleSpan(client, span) {
(0, _sentry_core.addNonEnumerableProperty)(client, ACTIVE_IDLE_SPAN_PROPERTY, span);
}
const REDIRECT_THRESHOLD = 1.5;
function isRedirect(activeSpan, lastInteractionTimestamp) {
const spanData = (0, _sentry_core.spanToJSON)(activeSpan);
const now = (0, _sentry_core.dateTimestampInSeconds)();
if (now - spanData.start_timestamp > REDIRECT_THRESHOLD) return false;
if (lastInteractionTimestamp && now - lastInteractionTimestamp <= REDIRECT_THRESHOLD) return false;
return true;
}
exports.BROWSER_TRACING_INTEGRATION_ID = BROWSER_TRACING_INTEGRATION_ID;
exports.browserTracingCoreIntegration = browserTracingCoreIntegration;
exports.browserTracingIntegration = browserTracingIntegration;
exports.getMetaContent = getMetaContent;
exports.getServerTiming = getServerTiming;
exports.startBrowserTracingNavigationSpan = startBrowserTracingNavigationSpan;
exports.startBrowserTracingPageLoadSpan = startBrowserTracingPageLoadSpan;
//# sourceMappingURL=browserTracingIntegration.js.map