@sentry/core
Version:
Base implementation for all Sentry JavaScript SDKs
4,156 lines • 155 kB
JavaScript
const require_cacheOrigin = require("./cacheOrigin.js");
let _sentry_conventions_attributes = require("@sentry/conventions/attributes");
let _sentry_conventions_op = require("@sentry/conventions/op");
// src/tracing/spans/spanNames.ts
/**
* Fallback name for pageload spans when no better-suited span name is available.
* @see https://conventions.sentry.dev/names/#browser-pageload
*/
const PAGELOAD_SPAN_NAME_FALLBACK = "Pageload";
/**
* Fallback name for navigation spans when no better-suited span name is available.
* @see https://conventions.sentry.dev/names/#browser-navigation
*/
const NAVIGATION_SPAN_NAME_FALLBACK = "Navigation";
/**
* Fallback name for db spans when no better-suited span name is available.
* @see https://conventions.sentry.dev/names/#db-queries
*/
const DB_SPAN_NAME_FALLBACK = "Database operation";
/**
* Fallback name for gen_ai agent spans when no better-suited span name is available.
* @see https://conventions.sentry.dev/names/#gen_ai-agent
*/
const GEN_AI_AGENT_SPAN_NAME_FALLBACK = "Generative AI agent operation";
/**
* Fallback name for gen_ai model spans when no better-suited span name is available.
* @see https://conventions.sentry.dev/names/#gen_ai-inference
*/
const GEN_AI_INFERENCE_SPAN_NAME_FALLBACK = "Generative AI model operation";
/**
* Fallback name for graphql spans when no better-suited span name is available.
* @see https://conventions.sentry.dev/names/#graphql-graphql
*/
const GRAPHQL_SPAN_NAME_FALLBACK = "GraphQL Operation";
/**
* Fallback name for http.(client|server) spans when no better-suited span name is available.
* @see https://conventions.sentry.dev/names/#http
*/
const HTTP_SPAN_NAME_FALLBACK = "HTTP";
/**
* Fallback name for messaging spans when no better-suited span name is available.
* @see https://conventions.sentry.dev/names/#messaging
*/
const MESSAGING_SPAN_NAME_FALLBACK = "Messaging";
/**
* Fallback name for mcp server spans when no better-suited span name is available.
* @see https://conventions.sentry.dev/names/#mcp-server
*/
const MCP_SERVER_SPAN_NAME_FALLBACK = "MCP server operation";
/**
* Fallback name for mcp notification spans when no better-suited span name is available.
* @see https://conventions.sentry.dev/names/#mcp-notification
*/
const MCP_NOTIFICATION_SPAN_NAME_FALLBACK = "MCP notification";
/**
* Fallback name for resource spans when no better-suited span name is available.
* @see https://conventions.sentry.dev/names/#resource-resources
*/
const RESOURCE_SPAN_NAME_FALLBACK = "Resource";
/**
* Fallback name for router spans when no better-suited span name is available.
* @see https://conventions.sentry.dev/names/#routing-router
*/
const ROUTER_SPAN_NAME_FALLBACK = "Router";
/**
* Fallback name for request handler spans when no better-suited span name is available.
* @see https://conventions.sentry.dev/names/#web_server-request-handler
*/
const REQUEST_HANDLER_SPAN_NAME_FALLBACK = "Request handler";
/**
* Fallback name for serverless function execution spans when no better-suited span name is available.
* @see https://conventions.sentry.dev/names/#faas-serverless-function-execution
*/
const SERVERLESS_FUNCTION_SPAN_NAME_FALLBACK = "Serverless function execution";
/**
* Fallback name for function execution spans when no better-suited span name is available.
* @see https://conventions.sentry.dev/names/#function
*/
const FUNCTION_SPAN_NAME_FALLBACK = "Function execution";
/**
* Fallback name for ui.mount spans when no better-suited span name is available.
* @see https://conventions.sentry.dev/names/#ui-component-mount
*/
const UI_MOUNT_SPAN_NAME_FALLBACK = "Component mount";
/**
* Fallback name for ui.update spans when no better-suited span name is available.
* @see https://conventions.sentry.dev/names/#ui-component-update
*/
const UI_UPDATE_SPAN_NAME_FALLBACK = "Component update";
/**
* Fallback name for ui.render spans when no better-suited span name is available.
* @see https://conventions.sentry.dev/names/#ui-component-render
*/
const UI_RENDER_SPAN_NAME_FALLBACK = "Component render";
/**
* Fallback name for ui.unmount spans when no better-suited span name is available.
* @see https://conventions.sentry.dev/names/#ui-component-unmount
*/
const UI_UNMOUNT_SPAN_NAME_FALLBACK = "Component unmount";
/**
* Fallback name for ui.resolve spans when no better-suited span name is available.
* @see https://conventions.sentry.dev/names/#ui-component-resolve
*/
const UI_RESOLVE_SPAN_NAME_FALLBACK = "Component resolve";
/**
* Fallback name for ui.task spans when no better-suited span name is available.
* @see https://conventions.sentry.dev/names/#ui-ui-task
*/
const UI_TASK_SPAN_NAME_FALLBACK = "UI task";
/**
* Fallback name for ui.long_task and ui.long_animation_frame spans when no better-suited span name is available.
* @see https://conventions.sentry.dev/names/#ui-main-ui-thread-blocked
*/
const UI_LONG_TASK_SPAN_NAME_FALLBACK = "Main UI thread blocked";
/**
* Fallback name for ui.action spans when no better-suited span name is available.
* @see https://conventions.sentry.dev/names/#ui-ui-action
*/
const UI_ACTION_SPAN_NAME_FALLBACK = "UI action";
/**
* Fallback name for ui.action.click spans when no better-suited span name is available.
* @see https://conventions.sentry.dev/names/#ui-click-action
*/
const UI_ACTION_CLICK_SPAN_NAME_FALLBACK = "Click";
/**
* Fallback name for ui.interaction.click spans when no better-suited span name is available.
* @see https://conventions.sentry.dev/names/#ui-click-interaction
*/
const UI_INTERACTION_CLICK_SPAN_NAME_FALLBACK = "Click";
/**
* Fallback name for ui.interaction.hover spans when no better-suited span name is available.
* @see https://conventions.sentry.dev/names/#ui-hover-interaction
*/
const UI_INTERACTION_HOVER_SPAN_NAME_FALLBACK = "Hover";
/**
* Fallback name for ui.interaction.drag spans when no better-suited span name is available.
* @see https://conventions.sentry.dev/names/#ui-drag-interaction
*/
const UI_INTERACTION_DRAG_SPAN_NAME_FALLBACK = "Drag";
/**
* Fallback name for ui.interaction.press spans when no better-suited span name is available.
* @see https://conventions.sentry.dev/names/#ui-key-press-interaction
*/
const UI_INTERACTION_PRESS_SPAN_NAME_FALLBACK = "Key press";
/**
* Fallback name for ui.webvital.lcp spans when no better-suited span name is available.
* @see https://conventions.sentry.dev/names/#ui-largest-contentful-paint
*/
const UI_WEBVITAL_LCP_SPAN_NAME_FALLBACK = "Largest contentful paint";
/**
* Fallback name for ui.webvital.cls spans when no better-suited span name is available.
* @see https://conventions.sentry.dev/names/#ui-layout-shift
*/
const UI_WEBVITAL_CLS_SPAN_NAME_FALLBACK = "Layout shift";
/**
* Fallback name for generic ui spans when no better-suited span name is available.
* @see https://conventions.sentry.dev/names/#ui-ui
*/
const UI_SPAN_NAME_FALLBACK = "UI";
/**
* The `cache.operation` attribute value each cache op carries. Cache span names are
* `cache.{{cache.operation}}`, so the op constant itself doubles as the low-cardinality span name.
* @see https://conventions.sentry.dev/names/#cache
*/
const CACHE_OPERATION_NAMES = {
[_sentry_conventions_op.CACHE_GET]: "get",
[_sentry_conventions_op.CACHE_PUT]: "put",
[_sentry_conventions_op.CACHE_REMOVE]: "remove"
};
/**
* Span names for the browser navigation timing ops, keyed by op. None of these ops has an attribute
* template, so the static name is the only name they can get.
* @see https://conventions.sentry.dev/names/#browser-navigation-timing
*/
const BROWSER_NAVIGATION_TIMING_SPAN_NAMES = {
[_sentry_conventions_op.BROWSER_CACHE]: "Cache lookup",
[_sentry_conventions_op.BROWSER_DNS]: "DNS lookup",
[_sentry_conventions_op.BROWSER_CONNECT]: "Connect",
[_sentry_conventions_op.BROWSER_TLS_SSL]: "TLS handshake",
[_sentry_conventions_op.BROWSER_REDIRECT]: "Redirect",
[_sentry_conventions_op.BROWSER_REQUEST]: "Request",
[_sentry_conventions_op.BROWSER_RESPONSE]: "Response",
[_sentry_conventions_op.BROWSER_UNLOAD_EVENT]: "Unload event",
[_sentry_conventions_op.BROWSER_DOM_CONTENT_LOADED_EVENT]: "DOMContentLoaded event",
[_sentry_conventions_op.BROWSER_LOAD_EVENT]: "Load event"
};
// src/envelope.ts
/**
* Apply SdkInfo (name, version, packages, integrations) to the corresponding event key.
* Merge with existing data if any.
*
* @internal, exported only for testing
**/
function _enhanceEventWithSdkInfo(event, newSdkInfo) {
if (!newSdkInfo) return event;
const eventSdkInfo = event.sdk || {};
event.sdk = {
...eventSdkInfo,
name: eventSdkInfo.name || newSdkInfo.name,
version: eventSdkInfo.version || newSdkInfo.version,
integrations: [...event.sdk?.integrations || [], ...newSdkInfo.integrations || []],
packages: [...event.sdk?.packages || [], ...newSdkInfo.packages || []],
settings: event.sdk?.settings || newSdkInfo.settings ? {
...event.sdk?.settings,
...newSdkInfo.settings
} : void 0
};
return event;
}
/** Creates an envelope from a Session */
function createSessionEnvelope(session, dsn, metadata, tunnel) {
const sdkInfo = require_cacheOrigin.getSdkMetadataForEnvelopeHeader(metadata);
const envelopeHeaders = {
sent_at: new Date(require_cacheOrigin.safeDateNow()).toISOString(),
...sdkInfo && { sdk: sdkInfo },
...!!tunnel && dsn && { dsn: require_cacheOrigin.dsnToString(dsn) }
};
const envelopeItem = "aggregates" in session ? [{ type: "sessions" }, session] : [{ type: "session" }, session.toJSON()];
return require_cacheOrigin.createEnvelope(envelopeHeaders, [envelopeItem]);
}
/**
* Create an Envelope from an event.
*/
function createEventEnvelope(event, dsn, metadata, tunnel) {
const sdkInfo = require_cacheOrigin.getSdkMetadataForEnvelopeHeader(metadata);
const eventType = event.type && event.type !== "replay_event" ? event.type : "event";
_enhanceEventWithSdkInfo(event, metadata?.sdk);
const envelopeHeaders = require_cacheOrigin.createEventEnvelopeHeaders(event, sdkInfo, tunnel, dsn);
delete event.sdkProcessingMetadata;
return require_cacheOrigin.createEnvelope(envelopeHeaders, [[{ type: eventType }, event]]);
}
// src/api.ts
const SENTRY_API_VERSION = "7";
/** Returns the prefix to construct Sentry ingestion API endpoints. */
function getBaseApiEndpoint(dsn) {
const protocol = dsn.protocol ? `${dsn.protocol}:` : "";
const port = dsn.port ? `:${dsn.port}` : "";
return `${protocol}//${dsn.host}${port}${dsn.path ? `/${dsn.path}` : ""}/api/`;
}
/** Returns the ingest API endpoint for target. */
function _getIngestEndpoint(dsn) {
return `${getBaseApiEndpoint(dsn)}${dsn.projectId}/envelope/`;
}
/** Returns a URL-encoded string with auth config suitable for a query string. */
function _encodedAuth(dsn, sdkInfo) {
const params = { sentry_version: "7" };
if (dsn.publicKey) params.sentry_key = dsn.publicKey;
if (sdkInfo) params.sentry_client = `${sdkInfo.name}/${sdkInfo.version}`;
return new URLSearchParams(params).toString();
}
/**
* Returns the envelope endpoint URL with auth in the query string.
*
* Sending auth as part of the query string and not as custom HTTP headers avoids CORS preflight requests.
*/
function getEnvelopeEndpointWithUrlEncodedAuth(dsn, tunnel, sdkInfo) {
return tunnel ? tunnel : `${_getIngestEndpoint(dsn)}?${_encodedAuth(dsn, sdkInfo)}`;
}
/** Returns the url to the report dialog endpoint. */
function getReportDialogEndpoint(dsnLike, dialogOptions) {
const dsn = require_cacheOrigin.makeDsn(dsnLike);
if (!dsn) return "";
const endpoint = `${getBaseApiEndpoint(dsn)}embed/error-page/`;
let encodedOptions = `dsn=${require_cacheOrigin.dsnToString(dsn)}`;
for (const key in dialogOptions) {
if (key === "dsn") continue;
if (key === "onClose" || key === "onError") continue;
if (key === "user") {
const user = dialogOptions.user;
if (!user) continue;
if (user.name) encodedOptions += `&name=${encodeURIComponent(user.name)}`;
if (user.email) encodedOptions += `&email=${encodeURIComponent(user.email)}`;
} else encodedOptions += `&${encodeURIComponent(key)}=${encodeURIComponent(dialogOptions[key])}`;
}
return `${endpoint}?${encodedOptions}`;
}
// src/tracing/spans/extractGenAiSpans.ts
/**
* Extracts gen_ai spans from a transaction event, converts them to span v2 format,
* and returns them as a SpanContainerItem.
*
* Only applies to static mode (non-streaming) transactions.
*
* WARNING: This function mutates `event.spans` by removing the extracted gen_ai spans
* from the array. Call this before creating the event envelope so the transaction
* item does not include the extracted spans.
*/
function extractGenAiSpansFromEvent(event, client) {
if (event.type !== "transaction" || !event.spans?.length || !event.sdkProcessingMetadata?.hasGenAiSpans || require_cacheOrigin.hasSpanStreamingEnabled(client)) return;
const genAiSpans = [];
const remainingSpans = [];
for (const span of event.spans) if (span.op?.startsWith("gen_ai.")) genAiSpans.push(require_cacheOrigin.spanJsonToSerializedStreamedSpan(span));
else remainingSpans.push(span);
if (genAiSpans.length === 0) return;
event.spans = remainingSpans;
return require_cacheOrigin.createSpanContainerItem(genAiSpans, client);
}
// src/utils/promisebuffer.ts
const SENTRY_BUFFER_FULL_ERROR = Symbol.for("SentryBufferFullError");
/**
* Creates an new PromiseBuffer object with the specified limit
* @param limit max number of promises that can be stored in the buffer
*/
function makePromiseBuffer(limit = 100) {
const buffer = /* @__PURE__ */ new Set();
function isReady() {
return buffer.size < limit;
}
/**
* Remove a promise from the queue.
*
* @param task Can be any PromiseLike<T>
* @returns Removed promise.
*/
function remove(task) {
buffer.delete(task);
}
/**
* Add a promise (representing an in-flight action) to the queue, and set it to remove itself on fulfillment.
*
* @param taskProducer A function producing any PromiseLike<T>; In previous versions this used to be `task:
* PromiseLike<T>`, but under that model, Promises were instantly created on the call-site and their executor
* functions therefore ran immediately. Thus, even if the buffer was full, the action still happened. By
* requiring the promise to be wrapped in a function, we can defer promise creation until after the buffer
* limit check.
* @returns The original promise.
*/
function add(taskProducer) {
if (!isReady()) return require_cacheOrigin.rejectedSyncPromise(SENTRY_BUFFER_FULL_ERROR);
const task = taskProducer();
buffer.add(task);
task.then(() => remove(task), () => remove(task));
return task;
}
/**
* Wait for all promises in the queue to resolve or for timeout to expire, whichever comes first.
*
* @param timeout The time, in ms, after which to resolve to `false` if the queue is still non-empty. Passing `0` (or
* not passing anything) will make the promise wait as long as it takes for the queue to drain before resolving to
* `true`.
* @returns A promise which will resolve to `true` if the queue is already empty or drains before the timeout, and
* `false` otherwise
*/
function drain(timeout) {
if (!buffer.size) return require_cacheOrigin.resolvedSyncPromise(true);
const drainPromise = Promise.allSettled(Array.from(buffer)).then(() => true);
if (!timeout) return drainPromise;
const promises = [drainPromise, new Promise((resolve) => require_cacheOrigin.safeUnref(setTimeout(() => resolve(false), timeout)))];
return Promise.race(promises);
}
return {
get $() {
return Array.from(buffer);
},
add,
drain
};
}
// src/utils/ratelimit.ts
const DEFAULT_RETRY_AFTER = 6e4;
/**
* Extracts Retry-After value from the request header or returns default value
* @param header string representation of 'Retry-After' header
* @param now current unix timestamp
*
*/
function parseRetryAfterHeader(header, now = require_cacheOrigin.safeDateNow()) {
const headerDelay = parseInt(`${header}`, 10);
if (!isNaN(headerDelay)) return headerDelay * 1e3;
const headerDate = Date.parse(`${header}`);
if (!isNaN(headerDate)) return headerDate - now;
return DEFAULT_RETRY_AFTER;
}
/**
* Gets the time that the given category is disabled until for rate limiting.
* In case no category-specific limit is set but a general rate limit across all categories is active,
* that time is returned.
*
* @return the time in ms that the category is disabled until or 0 if there's no active rate limit.
*/
function disabledUntil(limits, dataCategory) {
return limits[dataCategory] || limits.all || 0;
}
/**
* Checks if a category is rate limited
*/
function isRateLimited(limits, dataCategory, now = require_cacheOrigin.safeDateNow()) {
return disabledUntil(limits, dataCategory) > now;
}
/**
* Update ratelimits from incoming headers.
*
* @return the updated RateLimits object.
*/
function updateRateLimits(limits, response, now = require_cacheOrigin.safeDateNow()) {
const updatedRateLimits = { ...limits };
forEachRateLimit(response, now, (category, until) => {
updatedRateLimits[category] = Math.max(updatedRateLimits[category] || 0, until);
});
return updatedRateLimits;
}
/**
* Calls `extendRateLimit` with the category and deadline of each rate limit in the response.
*/
function forEachRateLimit({ statusCode, headers }, now, extendRateLimit) {
const rateLimitHeader = headers?.["x-sentry-rate-limits"];
const retryAfterHeader = headers?.["retry-after"];
if (rateLimitHeader)
/**
* rate limit headers are of the form
* <header>,<header>,..
* where each <header> is of the form
* <retry_after>: <categories>: <scope>: <reason_code>: <namespaces>
* where
* <retry_after> is a delay in seconds
* <categories> is the event type(s) (error, transaction, etc) being rate limited and is of the form
* <category>;<category>;...
* <scope> is what's being limited (org, project, or key) - ignored by SDK
* <reason_code> is an arbitrary string like "org_quota" - ignored by SDK
* <namespaces> Semicolon-separated list of metric namespace identifiers. Defines which namespace(s) will be affected.
* Only present if rate limit applies to the metric_bucket data category.
*/
for (const limit of rateLimitHeader.trim().split(",")) {
const [retryAfter, categories, , , namespaces] = limit.split(":", 5);
const headerDelay = parseInt(retryAfter, 10);
const delay = (!isNaN(headerDelay) ? headerDelay : 60) * 1e3;
if (!categories) extendRateLimit("all", now + delay);
else for (const category of categories.split(";")) if (category === "metric_bucket") {
if (!namespaces || namespaces.split(";").includes("custom")) extendRateLimit(category, now + delay);
} else extendRateLimit(category, now + delay);
}
else if (retryAfterHeader) extendRateLimit("all", now + parseRetryAfterHeader(retryAfterHeader, now));
else if (statusCode === 429) extendRateLimit("all", now + 6e4);
}
/**
* Creates an instance of a Sentry `Transport`
*
* @param options
* @param makeRequest
*/
function createTransport(options, makeRequest, buffer = makePromiseBuffer(options.bufferSize || 64)) {
let rateLimits = {};
const flush = (timeout) => buffer.drain(timeout);
function recordItemLoss(reason, [headers, payload], type) {
const dataCategory = require_cacheOrigin.envelopeItemTypeToDataCategory(type);
if (type === "transaction") options.recordDroppedEvent(reason, "span", (payload.spans?.length ?? 0) + 1);
options.recordDroppedEvent(reason, dataCategory, typeof headers.item_count === "number" ? headers.item_count : 1);
}
function send(envelope) {
const filteredEnvelopeItems = [];
require_cacheOrigin.forEachEnvelopeItem(envelope, (item, type) => {
if (isRateLimited(rateLimits, require_cacheOrigin.envelopeItemTypeToDataCategory(type))) recordItemLoss("ratelimit_backoff", item, type);
else filteredEnvelopeItems.push(item);
});
if (filteredEnvelopeItems.length === 0) return Promise.resolve({});
const filteredEnvelope = require_cacheOrigin.createEnvelope(envelope[0], filteredEnvelopeItems);
const recordEnvelopeLoss = (reason) => {
if (require_cacheOrigin.envelopeContainsItemType(filteredEnvelope, ["client_report"])) {
require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.warn(`Dropping client report. Will not send outcomes (reason: ${reason}).`);
return;
}
require_cacheOrigin.forEachEnvelopeItem(filteredEnvelope, (item, type) => {
recordItemLoss(reason, item, type);
});
};
const requestTask = () => makeRequest({ body: require_cacheOrigin.serializeEnvelope(filteredEnvelope) }).then((response) => {
if (response.statusCode === 413) {
require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.error("Sentry responded with status code 413. Envelope was discarded due to exceeding size limits.");
recordEnvelopeLoss("send_error");
return response;
}
if (require_cacheOrigin.DEBUG_BUILD && response.statusCode !== void 0 && (response.statusCode < 200 || response.statusCode >= 300)) require_cacheOrigin.debug.warn(`Sentry responded with status code ${response.statusCode} to sent event.`);
rateLimits = updateRateLimits(rateLimits, response);
return response;
}, (error) => {
recordEnvelopeLoss("network_error");
require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.error("Encountered error running transport request:", error);
throw error;
});
return buffer.add(requestTask).then((result) => result, (error) => {
if (error === SENTRY_BUFFER_FULL_ERROR) {
require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.error("Skipped sending event because buffer is full.");
recordEnvelopeLoss("queue_overflow");
return Promise.resolve({});
} else throw error;
});
}
return {
send,
flush
};
}
// src/utils/clientreport.ts
/**
* Creates client report envelope
* @param discarded_events An array of discard events
* @param dsn A DSN that can be set on the header. Optional.
*/
function createClientReportEnvelope(discarded_events, dsn, timestamp) {
const clientReportItem = [{ type: "client_report" }, {
timestamp: timestamp || require_cacheOrigin.dateTimestampInSeconds(),
discarded_events
}];
return require_cacheOrigin.createEnvelope(dsn ? { dsn } : {}, [clientReportItem]);
}
// src/utils/transactionEvent.ts
/**
* Converts a transaction event to a span JSON object.
*/
function convertTransactionEventToSpanJson(event) {
const { trace_id, parent_span_id, span_id, status, origin, data, op, links } = event.contexts?.trace ?? {};
return {
data: data ?? {},
description: event.transaction,
op,
parent_span_id,
span_id: span_id ?? "",
start_timestamp: event.start_timestamp ?? 0,
status: status ?? "ok",
timestamp: event.timestamp,
trace_id: trace_id ?? "",
origin,
links,
profile_id: data?.[_sentry_conventions_attributes.SENTRY_PROFILE_ID],
exclusive_time: data?.[_sentry_conventions_attributes.SENTRY_EXCLUSIVE_TIME],
measurements: event.measurements,
is_segment: true
};
}
/**
* Converts a span JSON object to a transaction event.
*/
function convertSpanJsonToTransactionEvent(span) {
return {
type: "transaction",
timestamp: span.timestamp,
start_timestamp: span.start_timestamp,
transaction: span.description,
contexts: { trace: {
trace_id: span.trace_id,
span_id: span.span_id,
parent_span_id: span.parent_span_id,
op: span.op,
status: span.status,
origin: span.origin,
links: span.links,
data: {
...span.data,
...span.profile_id && { [_sentry_conventions_attributes.SENTRY_PROFILE_ID]: span.profile_id },
...span.exclusive_time && { [_sentry_conventions_attributes.SENTRY_EXCLUSIVE_TIME]: span.exclusive_time }
}
} },
measurements: span.measurements
};
}
// src/utils/warnAboutIgnoredTransactionOptions.ts
/**
* Warns about `beforeSendTransaction` and `ignoreTransactions` being ignored because span streaming is enabled.
*
* Both options are tied to the transaction event that span streaming no longer produces, so they silently
* stop taking effect when users upgrade. Since that's easy to miss, this warning bypasses the `debug` logger
* (which is opt-in and stripped from non-debug bundles) and writes to the console directly.
*/
function maybeWarnAboutIgnoredTransactionOptions(options) {
if (options.traceLifecycle !== "stream" || !(options.beforeSendTransaction || options.ignoreTransactions?.length)) return;
require_cacheOrigin.consoleSandbox(() => {
console.warn("[Sentry] `beforeSendTransaction` and `ignoreTransactions` are ignored with `traceLifecycle: 'stream'` (enabled by default). Use `beforeSendSpan` and `ignoreSpans` instead, or set `traceLifecycle: 'static'`.");
});
}
// src/utils/data-collection/resolveDataCollectionOptions.ts
const DEFAULTS = {
userInfo: true,
cookies: true,
httpHeaders: {
request: true,
response: true
},
httpBodies: [
"incomingRequest",
"outgoingRequest",
"incomingResponse",
"outgoingResponse"
],
urlQueryParams: true,
graphQL: {
document: true,
variables: true
},
genAI: {
inputs: true,
outputs: true
},
mcp: {
inputs: true,
outputs: true
},
databaseQueryData: true,
queues: true,
stackFrameVariables: true,
frameContextLines: 5
};
function isCollectBehavior(value) {
return typeof value === "boolean" || "allow" in value || "deny" in value;
}
function resolveHttpHeaders(httpHeaders) {
if (httpHeaders === void 0) return { ...DEFAULTS.httpHeaders };
if (isCollectBehavior(httpHeaders)) return {
request: httpHeaders,
response: httpHeaders
};
return {
request: httpHeaders.request ?? DEFAULTS.httpHeaders.request,
response: httpHeaders.response ?? DEFAULTS.httpHeaders.response
};
}
/**
* Resolves the effective `DataCollection` configuration from client options.
*
* Precedence:
* 1. Spec defaults
* 2. Fields explicitly set in `dataCollection`
*/
function resolveDataCollectionOptions(options) {
const dc = options.dataCollection ?? {};
return {
userInfo: dc.userInfo ?? DEFAULTS.userInfo,
cookies: dc.cookies ?? DEFAULTS.cookies,
httpHeaders: resolveHttpHeaders(dc.httpHeaders),
httpBodies: dc.httpBodies ?? DEFAULTS.httpBodies,
urlQueryParams: dc.urlQueryParams ?? DEFAULTS.urlQueryParams,
graphQL: {
document: dc.graphQL?.document ?? DEFAULTS.graphQL.document,
variables: dc.graphQL?.variables ?? DEFAULTS.graphQL.variables
},
genAI: {
inputs: dc.genAI?.inputs ?? DEFAULTS.genAI.inputs,
outputs: dc.genAI?.outputs ?? DEFAULTS.genAI.outputs
},
mcp: {
inputs: dc.mcp?.inputs ?? DEFAULTS.mcp.inputs,
outputs: dc.mcp?.outputs ?? DEFAULTS.mcp.outputs
},
databaseQueryData: dc.databaseQueryData ?? DEFAULTS.databaseQueryData,
queues: dc.queues ?? DEFAULTS.queues,
stackFrameVariables: dc.stackFrameVariables ?? DEFAULTS.stackFrameVariables,
frameContextLines: dc.frameContextLines ?? DEFAULTS.frameContextLines
};
}
// src/client.ts
const ALREADY_SEEN_ERROR = "Not capturing exception because it's already been captured.";
const MISSING_RELEASE_FOR_SESSION_ERROR = "Discarded session because of missing or non-string release";
const INTERNAL_ERROR_SYMBOL = Symbol.for("SentryInternalError");
const DO_NOT_SEND_EVENT_SYMBOL = Symbol.for("SentryDoNotSendEventError");
const CLOSED_CLIENT_SYMBOL = Symbol.for("SentryClosedClient");
/**
* Whether `close()` was called on the given client.
*
* @hidden
*/
function isClientClosed(client) {
return CLOSED_CLIENT_SYMBOL in client;
}
function _makeInternalError(message) {
return {
message,
[INTERNAL_ERROR_SYMBOL]: true
};
}
function _makeDoNotSendEventError(message) {
return {
message,
[DO_NOT_SEND_EVENT_SYMBOL]: true
};
}
function _makeSampledOutError(sampleRate) {
return _makeDoNotSendEventError(`Discarding event because it's not included in the random sample (sampling rate = ${sampleRate})`);
}
function _isInternalError(error) {
return require_cacheOrigin.isObjectLike(error) && INTERNAL_ERROR_SYMBOL in error;
}
function _isDoNotSendEventError(error) {
return require_cacheOrigin.isObjectLike(error) && DO_NOT_SEND_EVENT_SYMBOL in error;
}
/**
* Base implementation for all JavaScript SDK clients.
*
* Call the constructor with the corresponding options
* specific to the client subclass. To access these options later, use
* {@link Client.getOptions}.
*
* If a Dsn is specified in the options, it will be parsed and stored. Use
* {@link Client.getDsn} to retrieve the Dsn at any moment. In case the Dsn is
* invalid, the constructor will throw a {@link SentryException}. Note that
* without a valid Dsn, the SDK will not send any events to Sentry.
*
* Before sending an event, it is passed through
* {@link Client._prepareEvent} to add SDK information and scope data
* (breadcrumbs and context). To add more custom information, override this
* method and extend the resulting prepared event.
*
* To issue automatically created events (e.g. via instrumentation), use
* {@link Client.captureEvent}. It will prepare the event and pass it through
* the callback lifecycle. To issue auto-breadcrumbs, use
* {@link Client.addBreadcrumb}.
*
* @example
* class NodeClient extends Client<NodeOptions> {
* public constructor(options: NodeOptions) {
* super(options);
* }
*
* // ...
* }
*/
var Client = class {
/**
* Initializes this client instance.
*
* @param options Options for the client.
*/
constructor(options) {
this._options = {
attachStacktrace: true,
...options,
traceLifecycle: options.traceLifecycle === "static" ? "static" : "stream"
};
this._integrations = {};
this._numProcessing = 0;
this._outcomes = {};
this._hooks = {};
this._eventProcessors = [];
this._promiseBuffer = makePromiseBuffer(options.transportOptions?.bufferSize ?? 64);
this._dataCollection = resolveDataCollectionOptions(options);
this._unhandledSessionStatus = "crashed";
this._attachStacktraceIsDefault = options.attachStacktrace === void 0;
if (options.dsn) this._dsn = require_cacheOrigin.makeDsn(options.dsn);
else require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.warn("No DSN provided, client will not send events.");
const { beforeSendSpan, traceLifecycle } = this._options;
if (require_cacheOrigin.DEBUG_BUILD && beforeSendSpan && require_cacheOrigin.isStaticBeforeSendSpanCallback(beforeSendSpan) !== (traceLifecycle === "static")) require_cacheOrigin.consoleSandbox(() => {
console.warn(`Ignoring \`beforeSendSpan\`: ${traceLifecycle === "static" ? "wrap it with" : "remove"} \`Sentry.withStaticSpan\` to use it with \`traceLifecycle: "${traceLifecycle}"\`.`);
});
if (this._dsn) {
const url = getEnvelopeEndpointWithUrlEncodedAuth(this._dsn, options.tunnel, options._metadata ? options._metadata.sdk : void 0);
this._transport = options.transport({
tunnel: this._options.tunnel,
recordDroppedEvent: this.recordDroppedEvent.bind(this),
...options.transportOptions,
url
});
}
}
/**
* Captures an exception event and sends it to Sentry.
*
* Unlike `captureException` exported from every SDK, this method requires that you pass it the current scope.
*/
captureException(exception, hint, scope) {
const eventId = require_cacheOrigin.uuid4();
if (require_cacheOrigin.checkOrSetAlreadyCaught(exception)) {
require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.log(ALREADY_SEEN_ERROR);
return eventId;
}
const hintWithEventId = {
event_id: eventId,
...hint
};
this._process(() => this.eventFromException(exception, hintWithEventId).then((event) => this._captureEvent(event, hintWithEventId, scope)).then((res) => res), "error");
return hintWithEventId.event_id;
}
/**
* Captures a message event and sends it to Sentry.
*
* Unlike `captureMessage` exported from every SDK, this method requires that you pass it the current scope.
*/
captureMessage(message, level, hint, currentScope) {
const hintWithEventId = {
event_id: require_cacheOrigin.uuid4(),
...hint
};
const eventMessage = require_cacheOrigin.isParameterizedString(message) ? message : String(message);
const isMessage = require_cacheOrigin.isPrimitive(message);
const promisedEvent = isMessage ? this.eventFromMessage(eventMessage, level, hintWithEventId).then((event) => {
if (event.exception && this._attachStacktraceIsDefault) event.sdkProcessingMetadata = {
...event.sdkProcessingMetadata,
hasDefaultSyntheticStacktrace: true
};
return event;
}) : this.eventFromException(message, hintWithEventId);
this._process(() => promisedEvent.then((event) => this._captureEvent(event, hintWithEventId, currentScope)), isMessage ? "unknown" : "error");
return hintWithEventId.event_id;
}
/**
* Captures a manually created event and sends it to Sentry.
*
* Unlike `captureEvent` exported from every SDK, this method requires that you pass it the current scope.
*/
captureEvent(event, hint, currentScope) {
const eventId = require_cacheOrigin.uuid4();
if (hint?.originalException && require_cacheOrigin.checkOrSetAlreadyCaught(hint.originalException)) {
require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.log(ALREADY_SEEN_ERROR);
return eventId;
}
const hintWithEventId = {
event_id: eventId,
...hint
};
const sdkProcessingMetadata = event.sdkProcessingMetadata || {};
const capturedSpanScope = sdkProcessingMetadata.capturedSpanScope;
const capturedSpanIsolationScope = sdkProcessingMetadata.capturedSpanIsolationScope;
const dataCategory = require_cacheOrigin.getDataCategoryByType(event.type);
this._process(() => this._captureEvent(event, hintWithEventId, capturedSpanScope || currentScope, capturedSpanIsolationScope), dataCategory);
return hintWithEventId.event_id;
}
/**
* Captures a session.
*/
captureSession(session) {
this.sendSession(session);
require_cacheOrigin.updateSession(session, { init: false });
}
/**
* Get the current Dsn.
*/
getDsn() {
return this._dsn;
}
/**
* Get the current options.
*/
getOptions() {
return this._options;
}
/**
* Get the resolved data collection configuration.
*/
getDataCollectionOptions() {
return this._dataCollection;
}
/**
* Get the SDK metadata.
* @see SdkMetadata
*/
getSdkMetadata() {
return this._options._metadata;
}
/**
* Returns the transport that is used by the client.
* Please note that the transport gets lazy initialized so it will only be there once the first event has been sent.
*/
getTransport() {
return this._transport;
}
/**
* Wait for all events to be sent or the timeout to expire, whichever comes first.
*
* @param timeout Maximum time in ms the client should wait for events to be flushed. Omitting this parameter will
* cause the client to wait until all events are sent before resolving the promise.
* @returns A promise that will resolve with `true` if all events are sent before the timeout, or `false` if there are
* still events in the queue when the timeout is reached.
*/
async flush(timeout) {
const transport = this._transport;
this.emit("flush");
if (!transport) return true;
const clientFinished = await this._isClientDoneProcessing(timeout);
const transportFlushed = await transport.flush(timeout);
return clientFinished && transportFlushed;
}
/**
* Flush the event queue and set the client to `enabled = false`. See {@link Client.flush}.
*
* @param {number} timeout Maximum time in ms the client should wait before shutting down. Omitting this parameter will cause
* the client to wait until all events are sent before disabling itself.
* @returns {Promise<boolean>} A promise which resolves to `true` if the flush completes successfully before the timeout, or `false` if
* it doesn't.
*/
async close(timeout) {
Object.defineProperty(this, CLOSED_CLIENT_SYMBOL, { value: true });
const result = await this.flush(timeout);
this.getOptions().enabled = false;
this.emit("close");
return result;
}
/**
* Get all installed event processors.
*/
getEventProcessors() {
return this._eventProcessors;
}
/**
* Adds an event processor that applies to any event processed by this client.
*/
addEventProcessor(eventProcessor) {
this._eventProcessors.push(eventProcessor);
}
/**
* Initialize this client.
* Call this after the client was set on a scope.
*/
init() {
if (this._isEnabled() || this._options.integrations.some(({ name }) => name.startsWith("Spotlight"))) {
this._setupIntegrations();
maybeWarnAboutIgnoredTransactionOptions(this._options);
}
}
/**
* Gets an installed integration by its name.
*
* @returns {Integration|undefined} The installed integration or `undefined` if no integration with that `name` was installed.
*/
getIntegrationByName(integrationName) {
return this._integrations[integrationName];
}
/**
* Returns the names of all installed integrations.
*/
getIntegrationNames() {
return Object.keys(this._integrations);
}
/**
* Add an integration to the client.
* This can be used to e.g. lazy load integrations.
* In most cases, this should not be necessary,
* and you're better off just passing the integrations via `integrations: []` at initialization time.
* However, if you find the need to conditionally load & add an integration, you can use `addIntegration` to do so.
*/
addIntegration(integration) {
const isAlreadyInstalled = this._integrations[integration.name];
if (!isAlreadyInstalled && integration.beforeSetup) integration.beforeSetup(this);
require_cacheOrigin.setupIntegration(this, integration, this._integrations);
if (!isAlreadyInstalled) require_cacheOrigin.afterSetupIntegrations(this, [integration]);
}
/**
* Send a fully prepared event to Sentry.
*/
sendEvent(event, hint = {}) {
this.emit("beforeSendEvent", event, hint);
const genAiSpanItem = extractGenAiSpansFromEvent(event, this);
let env = createEventEnvelope(event, this._dsn, this._options._metadata, this._options.tunnel);
if (!require_cacheOrigin.isInternalException(hint)) for (const attachment of hint.attachments || []) env = require_cacheOrigin.addItemToEnvelope(env, require_cacheOrigin.createAttachmentEnvelopeItem(attachment));
if (genAiSpanItem) env = require_cacheOrigin.addItemToEnvelope(env, genAiSpanItem);
this.sendEnvelope(env).then((sendResponse) => this.emit("afterSendEvent", event, sendResponse));
}
/**
* Send a session or session aggregrates to Sentry.
*/
sendSession(session) {
const { release: clientReleaseOption, environment: clientEnvironmentOption = require_cacheOrigin.DEFAULT_ENVIRONMENT } = this._options;
if ("aggregates" in session) {
const sessionAttrs = session.attrs || {};
if (!sessionAttrs.release && !clientReleaseOption) {
require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.warn(MISSING_RELEASE_FOR_SESSION_ERROR);
return;
}
sessionAttrs.release = sessionAttrs.release || clientReleaseOption;
sessionAttrs.environment = sessionAttrs.environment || clientEnvironmentOption;
session.attrs = sessionAttrs;
} else {
if (!session.release && !clientReleaseOption) {
require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.warn(MISSING_RELEASE_FOR_SESSION_ERROR);
return;
}
session.release = session.release || clientReleaseOption;
session.environment = session.environment || clientEnvironmentOption;
}
this.emit("beforeSendSession", session);
const env = createSessionEnvelope(session, this._dsn, this._options._metadata, this._options.tunnel);
this.sendEnvelope(env);
}
/**
* Record on the client that an event got dropped (ie, an event that will not be sent to Sentry).
*/
recordDroppedEvent(reason, category, count = 1) {
if (this._options.sendClientReports) {
const key = `${reason}:${category}`;
require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.log(`Recording outcome: "${key}"${count > 1 ? ` (${count} times)` : ""}`);
this._outcomes[key] = (this._outcomes[key] || 0) + count;
}
}
/**
* Register a hook on this client.
*/
on(hook, callback) {
const hookCallbacks = this._hooks[hook] = this._hooks[hook] || /* @__PURE__ */ new Set();
const uniqueCallback = (...args) => callback(...args);
hookCallbacks.add(uniqueCallback);
return () => {
hookCallbacks.delete(uniqueCallback);
};
}
/**
* Emit a hook that was previously registered via `on()`.
*/
emit(hook, ...rest) {
const callbacks = this._hooks[hook];
if (callbacks) callbacks.forEach((callback) => callback(...rest));
}
/**
* Send an envelope to Sentry.
*/
async sendEnvelope(envelope) {
this.emit("beforeEnvelope", envelope);
if (this._isEnabled() && this._transport) try {
const result = await this._transport.send(envelope);
this.emit("afterEnvelope", envelope);
return result;
} catch (reason) {
require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.error("Error while sending envelope:", reason);
return {};
}
require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.error("Transport disabled");
return {};
}
/**
* Register a cleanup function to be called when the client is disposed.
* This is useful for integrations that need to clean up global state.
*
* NOTE: This is a no-op in the base `Client` class. Subclasses like `ServerRuntimeClient`
* override this method to actually register and execute cleanup callbacks.
*/
registerCleanup(callback) {}
/**
* Disposes of the client and releases all resources.
*
* Subclasses should override this method to clean up their own resources, including invoking
* any callbacks registered via {@link Client.registerCleanup}. The base implementation is a
* no-op and does NOT execute registered cleanup callbacks.
*
* After calling dispose(), the client should not be used anymore.
*/
dispose() {}
/** Setup integrations for this client. */
_setupIntegrations() {
const { integrations } = this._options;
this._integrations = require_cacheOrigin.setupIntegrations(this, integrations);
require_cacheOrigin.afterSetupIntegrations(this, integrations);
}
/** Updates existing session based on the provided event */
_updateSessionFromEvent(session, event) {
let unhandled = event.level === "fatal";
let errored = false;
const exceptions = event.exception?.values;
if (exceptions) {
errored = true;
unhandled = false;
for (const ex of exceptions) if (ex.mechanism?.handled === false) {
unhandled = true;
break;
}
}
const sessionNonTerminal = session.status === "ok";
if (sessionNonTerminal && session.errors === 0 || sessionNonTerminal && unhandled) {
require_cacheOrigin.updateSession(session, {
...unhandled && { status: this._unhandledSessionStatus },
errors: session.errors || Number(errored || unhandled)
});
this.captureSession(session);
}
}
/**
* Determine if the client is finished processing. Returns a promise because it will wait `timeout` ms before saying
* "no" (resolving to `false`) in order to give the client a chance to potentially finish first.
*
* @param timeout The time, in ms, after which to resolve to `false` if the client is still busy. Passing `0` (or not
* passing anything) will make the promise wait as long as it takes for processing to finish before resolving to
* `true`.
* @returns A promise which will resolve to `true` if processing is already done or finishes before the timeout, and
* `false` otherwise
*/
async _isClientDoneProcessing(timeout) {
let ticked = 0;
while (!timeout || ticked < timeout) {
await new Promise((resolve) => setTimeout(resolve, 1));
if (!this._numProcessing) return true;
ticked++;
}
return false;
}
/** Determines whether this SDK is enabled and a transport is present. */
_isEnabled() {
return this.getOptions().enabled !== false && this._transport !== void 0;
}
/**
* Adds common information to events.
*
* The information includes release and environment from `options`,
* breadcrumbs and context (extra, tags and user) from the scope.
*
* Information that is already present in the event is never overwritten. For
* nested objects, such as the context, keys are merged.
*
* @param event The original event.
* @param hint May contain additional information about the original exception.
* @param currentScope A scope containing event metadata.
* @returns A new event with more information.
*/
_prepareEvent(event, hint, currentScope, isolationScope) {
const options = this.getOptions();
const integrations = this.getIntegrationNames();
if (!hint.integrations && integrations.length) hint.integrations = integrations;
this.emit("preprocessEvent", event, hint);
if (!event.type) isolationScope.setLastEventId(event.event_id || hint.event_id);
return require_cacheOrigin.prepareEvent(options, event, hint, currentScope, this, isolationScope).then((evt) => {
if (evt === null) return evt;
this.emit("postprocessEvent", evt, hint);
evt.contexts = {
trace: {
...evt.contexts?.trace,
...require_cacheOrigin.getTraceContextFromScope(currentScope)
},
...evt.contexts
};
evt.sdkProcessingMetadata = {
dynamicSamplingContext: require_cacheOrigin.getDynamicSamplingContextFromScope(this, currentScope),
...evt.sdkProcessingMetadata
};
return evt;
});
}
/**
* Processes the event and logs an error in case of rejection
* @param event
* @param hint
* @param scope
*/
_captureEvent(event, hint = {}, currentScope = require_cacheOrigin.getCurrentScope(), isolationScope = require_cacheOrigin.getIsolationScope()) {
if (require_cacheOrigin.DEBUG_BUILD && isErrorEvent(event)) require_cacheOrigin.debug.log(`Captured error event \`${require_cacheOrigin.getPossibleEventMessages(event)[0] || "<unknown>"}\``);
return this._processEvent(event, hint, currentScope, isolationScope).then((finalEvent) => {
return finalEvent.event_id;
}, (reason) => {
if (require_cacheOrigin.DEBUG_BUILD) {
if (_isDoNotSendEventError(reason)) require_cacheOrigin.debug.log(reason.message);
else if (_isInternalError(reason)) require_cacheOrigin.debug.warn(reason.message);
else require_cacheOrigin.debug.warn(reason);
}
});
}
/**
* Processes an event (either error or message) and sends it to Sentry.
*
* This also adds breadcrumbs and context information to the event. However,
* platform specific meta data (such as the User's IP address) must be added
* by the SDK implementor.
*
*
* @param event The event to send to Sentry.
* @param hint May contain additional information about the original exception.
* @param currentScope A scope containing event metadata.
* @returns A SyncPromise that resolves with the event or rejects in case event was/will not be send.
*/
_processEvent(event, hint, currentScope, isolationScope) {
const options = this.getOptions();
const { sampleRate } = options;
const isTransaction = isTransactionEvent(event);
const isError = isErrorEvent(event);
const beforeSendLabel = `before send for type \`${event.type || "error"}\``;
let beforeSendDropReason = "before_send";
let ignoredSpanCount = 0;
const parsedSampleRate = typeof sampleRate === "undefined" ? void 0 : require_cacheOrigin.parseSampleRate(sampleRate);
const isSampledOut = isError && typeof parsedSampleRate === "number" && require_cacheOrigin.safeMathRandom() > parsedSampleRate;
const dataCategory = require_cacheOrigin.getDataCategoryByType(event.type);
let preparedSpanCount = 0;
const session = currentScope.getSession() || isolationScope.getSession();
if (isSampledOut && session?.status !== "ok") {
this.recordDroppedEvent("sample_rate", "error");
return require_cacheOrigin.rejectedSyncPromise(_makeSampledOutError(sampleRate));
}
return this._prepareEvent(event, hint, currentScope, isolationScope).then((prepared) => {
if (prepared === null) throw _makeDoNotSendEventError("An event processor returned `null`, will not send event.");
preparedSpanCount = prepared.spans?.length || 0;
if (require_cacheOrigin.isInternalException(hint)) return prepared;
return processBeforeSend(options, prepared, hint, (reason) => {
beforeSendDropReason = reason;
}, (count) => {
ignoredSpanCount = count;
});
}).then((processedEvent) => {
if (ignoredSpanCount) this.recordDroppedEvent("ignored", "span", ignoredSpanCount);
if (!require_cacheOrigin.isPlainObject(processedEvent) || processedEvent === null) {
this.recordDroppedEvent(beforeSendDropReason, dataCategory);
if (isTransaction) this.recordDroppedEvent(beforeSendDropReason, "span", 1 + preparedSpanCount - ignoredSpanCount);
if (processedEvent !== null) throw _makeInternalError(`${beforeSendLabel} must return \`null\` or a valid event.`);
throw _makeDoNotSendEventError(`${beforeSendDropReason === "ignored" ? "Transaction matched `ignoreSpans`" : `${beforeSendLabel} ${beforeSendDropReason === "callback_error" ? "threw an error" : "returned `null`"}`}, will not send event.`);
}
if (isError && session) this._updateSessionFromEvent(session, processedEvent);
if (isSampledOut) {
this.recordDroppedEvent("sample_rate", "error");
throw _makeSampledOutError(sampleRate);
}
if (isTransaction) {
const droppedSpanCount = preparedSpanCount - ignoredSpanCount - (processedEvent.spans?.length || 0);
if (droppedSpanCount > 0) this.recordDroppedEvent("before_send", "span", droppedSpanCount);
}
const transactionInfo = processedEvent.transaction_info;
if (isTransaction && transactionInfo && processedEvent.transaction !== event.transaction) {
const source = "custom";
processedEvent.transaction_info = {
...transactionInfo,
source
};
}
this.sendEvent(processedEvent, hint);
return processedEvent;
}).then(null, (reason) => {
if (_isDoNotSendEventError(reason) || _isInternalError(reason)) throw reason;
this.captureException(reason, {
mechanism: {
handled: false,
type: "internal"
},
data: { __sentry__: true },
originalException: reason
});
throw _makeInternalError(`Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.\nReason: ${reason}`);
});
}
/**
* Occupies the client with processing and event
*/
_process(taskProducer, dataCategory) {
this._numProcessing++;
this._promiseBuffer.add(taskProducer).then((value) => {
this._numProcessing--;
return value;
}, (reason) => {
this._numProcessing--;
if (reason === SENTRY_BUFFER_FULL_ERROR) this.recordDroppedEvent("queue_overflow", dataCategory);
return reason;
});
}
/**
* Clears outcomes on this client and returns them.
*/
_clearOutcomes() {
const outcomes = this._outcomes;
this._outcomes = {};
return Object.entries(outcomes).map(([key, quantity]) => {
const [reason, category] = key.split(":");
return {
reason,
category,
quantity
};
});
}
/**
* Sends client reports as an envelope.
*/
_flushOutcomes() {
require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.log("Flushing outcomes...");
const outcomes = this._clearOutcomes();
if (outcomes.length === 0) {
require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.log("No outcomes to send");
return;
}
if (!this._dsn) {
require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.log("No dsn provided, will not send outcomes");
return;
}
require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.log("Sending outcomes:", outcomes);
const envelope = createClientReportEnvelope(outcomes, this._options.tunnel && require_cacheOrigin.dsnToString(this._dsn));
this.sendEnvelope(envelope);
}
};
/**
* Process the matching `beforeSendXXX` callback.
*/
function processBeforeSend(options, event, hint, onDrop, onIgnoredSpans) {
const { beforeSend, ignoreSpans, beforeSendTransaction } = options;
const beforeSendSpan = require_cacheOrigin.isStaticBeforeSendSpanCallback(options.beforeSendSpan) && options.beforeSendSpan;
let processedEvent = event;
if (isErrorEvent(processedEvent) && beforeSend) {
const errorEvent = processedEvent;
return require_cacheOrigin.safeCallback(require_cacheOrigin.DEBUG_BUILD ? "The `beforeSend` callback threw an error, dropping the event:" : "", () => beforeSend(errorEvent, hint), () => {
onDrop("callback_error");
return null;
});
}
if (isTransactionEvent(processedEvent)) {
if (beforeSendSpan || ignoreSpans) {
const rootSpanJson = convertTransactionEventToSpanJson(processedEvent);
if (ignoreSpans?.length && require_cacheOrigin.shouldIgnoreSpan({
description: rootSpanJson.description,
op: rootSpanJson.op,
attributes: rootSpanJson.data
}, ignoreSpans)) {
onDrop("ignored");
return null;
}
if (beforeSendSpan) {
const processedRootSpanJson = require_cacheOrigin.applyBeforeSendSpanCallback(rootSpanJson, beforeSendSpan);
processedEvent = require_cacheOrigin.merge(event, convertSpanJsonToTransactionEvent(processedRootSpanJson));
}
if (processedEvent.spans) {
const processedSpans = [];
const initialSpans = processedEvent.spans;
for (const span of initialSpans) {
if (ignoreSpans?.length && require_cacheOrigin.shouldIgnoreSpan({
description: span.description,
op: span.op,
attributes: span.data
}, ignoreSpans)) {
require_cacheOrigin.reparentChildSpans(initialSpans, span);
continue;
}
if (beforeSendSpan) processedSpans.push(require_cacheOrigin.applyBeforeSendSpanCallback(span, beforeSendSpan));
else processedSpans.push(span);
}
onIgnoredSpans(initialSpans.length - processedSpans.length);
processedEvent.spans = processedSpans;
}
}
if (beforeSendTransaction) return require_cacheOrigin.safeCallback(require_cacheOrigin.DEBUG_BUILD ? "The `beforeSendTransaction` callback threw an error, dropping the event:" : "", () => beforeSendTransaction(processedEvent, hint), () => {
onDrop("callback_error");
return null;
});
}
return processedEvent;
}
function isErrorEvent(event) {
return event.type === void 0;
}
function isTransactionEvent(event) {
return event.type === "transaction";
}
// src/utils/cookie.ts
/**
* The value decoding in `cookiePairsToRecord` was originally copied from the 'cookie` module at v0.5.0.
* https://github.com/jshttp/cookie/blob/a0c84147aab6266bdb3996cf4062e93907c0b0fc/index.js
* It had the following license:
*
* (The MIT License)
*
* Copyright (c) 2012-2014 Roman Shtylman <shtylman@gmail.com>
* Copyright (c) 2015 Douglas Christopher Wilson <doug@somethingdoug.com>
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* 'Software'), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/**
* Splits a `Cookie` / `Set-Cookie` header into its ordered name-value pairs. Values are trimmed, but not
* decoded or unquoted.
*
* A segment without an `=` is a nameless cookie, so the bare token is its value (RFC 6265bis).
*/
function parseCookieHeader(value, headerName) {
return (Array.isArray(value) ? value : [value]).flatMap((headerValue) => {
if (typeof headerValue !== "string") return [];
return headerName === "set-cookie" ? splitJoinedSetCookieHeader(headerValue).map((cookie) => cookie.split(";")[0]) : headerValue.split(";");
}).map((segment) => segment.trim()).filter((segment) => segment !== "" && segment !== "=").map((segment) => {
const equalSignIndex = segment.indexOf("=");
return equalSignIndex === -1 ? ["", segment] : [segment.slice(0, equalSignIndex).trim(), segment.slice(equalSignIndex + 1).trim()];
});
}
/**
* No SDK path reads a joined header today, but `Headers.get('set-cookie')` and `xhr.getResponseHeader()`
* join repeated `Set-Cookie` headers with ", ". A "," only starts a new cookie when a "name=" follows
* before the next ";" or ",", so the "," in `Expires=Wed, 21 Oct 2026 07:28:00 GMT` does not split.
*/
function splitJoinedSetCookieHeader(headerValue) {
return headerValue.split(/,(?=[^;=,]*=)/);
}
/**
* Converts cookie pairs to a record with decoded values. The first cookie of a name wins.
*
* A nameless cookie's token is its value, and no name-based denylist can match it. So it is stored
* under the name `''` and its value is always filtered.
*/
function cookiePairsToRecord(pairs) {
const record = {};
for (const [name, value] of pairs) if (record[name] === void 0) record[name] = name === "" ? require_cacheOrigin.FILTERED_VALUE : decodeCookieValue(value);
return record;
}
function decodeCookieValue(value) {
const unquoted = value.length > 1 && value.startsWith("\"") && value.endsWith("\"") ? value.slice(1, -1) : value;
try {
return unquoted.indexOf("%") !== -1 ? decodeURIComponent(unquoted) : unquoted;
} catch {
return unquoted;
}
}
// src/utils/data-collection/filterQueryParams.ts
/**
* Filters a query parameter string according to a `CollectBehavior`.
*
* Parameter names are decoded for filtering, while the original encoding, order, and duplicate keys are preserved.
*/
function filterQueryParams(queryString, behavior) {
if (!queryString || behavior === false) return;
return queryString.split("&").map((pair) => {
const separatorIndex = pair.indexOf("=");
const encodedKey = separatorIndex === -1 ? pair : pair.slice(0, separatorIndex);
const key = new URLSearchParams(`${encodedKey}=`).keys().next().value;
return key !== void 0 && require_cacheOrigin.shouldFilterDataKey(key, behavior) ? `${encodedKey}=${require_cacheOrigin.FILTERED_VALUE}` : pair;
}).join("&");
}
// src/utils/data-collection/filterUrlQuery.ts
/**
* Applies a `CollectBehavior` to the query string of a full URL, leaving every other URL component
* (scheme, host, path, fragment) untouched.
*
* The query is located by string offsets rather than by parsing, so the URL is returned byte-for-byte
* apart from the query itself. This keeps relative URLs, non-HTTP schemes and unusual encodings intact,
* none of which survive a `URL` round-trip.
*
* Returns the URL with its query filtered, or with the query removed entirely when collection is off.
*/
function filterUrlQuery(url, behavior) {
const fragmentStart = url.indexOf("#");
const queryEnd = fragmentStart === -1 ? url.length : fragmentStart;
const queryStart = url.indexOf("?");
if (queryStart === -1 || queryStart > queryEnd) return url;
const prefix = url.slice(0, queryStart);
const query = url.slice(queryStart + 1, queryEnd);
const suffix = url.slice(queryEnd);
const filtered = filterQueryParams(query, behavior);
return filtered ? `${prefix}?${filtered}${suffix}` : `${prefix}${suffix}`;
}
// src/utils/data-collection/filterCollectedUrl.ts
function urlQueryParamsBehavior(client) {
return (client ?? require_cacheOrigin.getClient())?.getDataCollectionOptions().urlQueryParams ?? true;
}
function filterCollectedUrl(url, client) {
return url === void 0 ? void 0 : filterUrlQuery(url, urlQueryParamsBehavior(client));
}
/**
* Applies `dataCollection.urlQueryParams` to a query string the SDK collected itself, for use as
* `url.query`. Returns `undefined` when the query must not be collected at all.
*
* See {@link filterCollectedUrl} for why this is a helper and why passing `client` is preferred.
*/
function filterCollectedUrlQuery(query, client) {
return query ? filterQueryParams(query, urlQueryParamsBehavior(client)) : void 0;
}
// src/checkin.ts
/**
* Create envelope from check in item.
*/
function createCheckInEnvelope(checkIn, dynamicSamplingContext, metadata, tunnel, dsn) {
const headers = { sent_at: new Date(require_cacheOrigin.safeDateNow()).toISOString() };
if (metadata?.sdk) headers.sdk = {
name: metadata.sdk.name,
version: metadata.sdk.version
};
if (!!tunnel && !!dsn) headers.dsn = require_cacheOrigin.dsnToString(dsn);
if (dynamicSamplingContext) headers.trace = dynamicSamplingContext;
const item = createCheckInEnvelopeItem(checkIn);
return require_cacheOrigin.createEnvelope(headers, [item]);
}
function createCheckInEnvelopeItem(checkIn) {
return [{ type: "check_in" }, checkIn];
}
// src/utils/url.ts
const DEFAULT_BASE_URL = "thismessage:/";
/**
* Checks if the URL object is relative
*
* @param url - The URL object to check
* @returns True if the URL object is relative, false otherwise
*/
function isURLObjectRelative(url) {
return "isRelative" in url;
}
/**
* Parses string to a URL object
*
* @param url - The URL to parse
* @returns The parsed URL object or undefined if the URL is invalid
*/
function parseStringToURLObject(url, urlBase) {
const isRelative = url.indexOf("://") <= 0 && url.indexOf("//") !== 0;
const base = urlBase ?? (isRelative ? DEFAULT_BASE_URL : void 0);
try {
if ("canParse" in URL && !URL.canParse(url, base)) return;
const fullUrlObject = new URL(url, base);
if (isRelative) return {
isRelative,
pathname: fullUrlObject.pathname,
search: fullUrlObject.search,
hash: fullUrlObject.hash
};
return fullUrlObject;
} catch {}
}
/**
* Takes a URL object and returns a sanitized string which is safe to use as span name
* see: https://develop.sentry.dev/sdk/data-handling/#structuring-data
*/
function getSanitizedUrlStringFromUrlObject(url) {
if (isURLObjectRelative(url)) return url.pathname;
const newUrl = new URL(url);
newUrl.search = "";
newUrl.hash = "";
if (["80", "443"].includes(newUrl.port)) newUrl.port = "";
if (newUrl.password) newUrl.password = "%filtered%";
if (newUrl.username) newUrl.username = "%filtered%";
return newUrl.toString();
}
/**
* Normalizes a query string for the `url.query` attribute, which is specced without the leading `?`.
*
* Accepts either a raw query string (`URL.search`, which includes the `?`) or an already-stripped one.
* Empty results become `undefined` so callers can assign the return value to an attribute
* unconditionally — setting an attribute to `undefined` is a no-op.
*/
function getUrlQuery(query) {
return query?.replace(/^\?/, "") || void 0;
}
/**
* Normalizes a fragment for the `url.fragment` attribute, which is specced without the leading `#`.
*
* Accepts either a raw fragment (`URL.hash`, which includes the `#`) or an already-stripped one.
* Empty results become `undefined` so callers can assign the return value to an attribute
* unconditionally — setting an attribute to `undefined` is a no-op.
*/
function getUrlFragment(fragment) {
return fragment?.replace(/^#/, "") || void 0;
}
/**
* The domain a request goes to, for the `url.domain` attribute and low-cardinality span names.
*
* Relative URLs need a `base` to resolve against — browsers have the page origin, server runtimes do
* not. URLs with no domain at all, such as data URLs, return `undefined`.
*/
function getUrlDomain(url, base) {
try {
return new URL(url, base).hostname || void 0;
} catch {
return;
}
}
function getHttpSpanNameFromUrlObject(urlObject, kind, request, routeName) {
return `${request?.method?.toUpperCase() ?? "GET"} ${routeName ? routeName : urlObject ? kind === "client" ? getSanitizedUrlStringFromUrlObject(urlObject) : urlObject.pathname : "/"}`;
}
/**
* Takes a parsed URL object and returns a set of attributes for the span
* that represents the HTTP request for that url. This is used for both server
* and client http spans.
*
* Follows https://opentelemetry.io/docs/specs/semconv/http/.
*
* @param urlObject - see {@link parseStringToURLObject}
* @param kind - The type of HTTP operation (server or client)
* @param spanOrigin - The origin of the span
* @param request - The request object, see {@link PartialRequest}
* @param routeName - The name of the route, must be low cardinality
* @param client - The client the span belongs to, used to resolve `dataCollection.urlQueryParams`.
* Falls back to the current scope's client when omitted, which is the wrong one in a multi-client setup.
* @returns The span name and attributes for the HTTP operation
*/
function getHttpSpanDetailsFromUrlObject(urlObject, kind, spanOrigin, request, routeName, client) {
const attributes = { [_sentry_conventions_attributes.SENTRY_ORIGIN]: spanOrigin };
let nameSource = "url";
if (routeName) {
attributes[kind === "server" ? _sentry_conventions_attributes.HTTP_ROUTE : _sentry_conventions_attributes.URL_TEMPLATE] = routeName;
nameSource = "route";
}
if (request?.method) attributes[_sentry_conventions_attributes.HTTP_REQUEST_METHOD] = request.method.toUpperCase();
if (urlObject) {
attributes[_sentry_conventions_attributes.URL_FULL] = filterCollectedUrl(isURLObjectRelative(urlObject) ? getSanitizedUrlStringFromUrlObject(urlObject) : urlObject.href, client);
attributes[_sentry_conventions_attributes.URL_QUERY] = filterCollectedUrlQuery(getUrlQuery(urlObject.search), client);
attributes[_sentry_conventions_attributes.URL_FRAGMENT] = getUrlFragment(urlObject.hash);
if (urlObject.pathname) {
attributes[_sentry_conventions_attributes.URL_PATH] = urlObject.pathname;
if (urlObject.pathname === "/") nameSource = "route";
}
if (!isURLObjectRelative(urlObject)) {
if (urlObject.port) attributes[_sentry_conventions_attributes.URL_PORT] = Number(urlObject.port);
if (urlObject.protocol) attributes[_sentry_conventions_attributes.URL_SCHEME] = urlObject.protocol.replace(/:$/, "");
if (urlObject.hostname) attributes[kind === "server" ? _sentry_conventions_attributes.SERVER_ADDRESS : _sentry_conventions_attributes.URL_DOMAIN] = urlObject.hostname;
}
}
if (kind === "server") attributes[_sentry_conventions_attributes.SENTRY_SEGMENT_NAME_SOURCE] = nameSource;
return [getHttpSpanNameFromUrlObject(urlObject, kind, request, routeName), attributes];
}
/**
* Parses string form of URL into an object
* // borrowed from https://tools.ietf.org/html/rfc3986#appendix-B
* // intentionally using regex and not <a/> href parsing trick because React Native and other
* // environments where DOM might not be available
* @returns parsed URL object
*/
function parseUrl(url) {
if (!url) return {};
const match = url.match(/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);
if (!match) return {};
const query = match[6] || "";
const fragment = match[8] || "";
return {
host: match[4],
path: match[5],
protocol: match[2],
search: query,
hash: fragment,
relative: match[5] + query + fragment
};
}
/**
* Strip the query string and fragment off of a given URL or path (if present)
*
* @param urlPath Full URL or path, including possible query string and/or fragment
* @returns URL or path without query string or fragment
*/
function stripUrlQueryAndFragment(urlPath) {
return urlPath.split(/[?#]/, 1)[0];
}
/**
* Takes a URL object and returns a sanitized string which is safe to use as span name
* see: https://develop.sentry.dev/sdk/data-handling/#structuring-data
*/
function getSanitizedUrlString(url) {
const { protocol, host, path } = url;
const filteredHost = host?.replace(/^.*@/, "[filtered]:[filtered]@").replace(/(:80)$/, "").replace(/(:443)$/, "") || "";
return `${protocol ? `${protocol}://` : ""}${filteredHost}${path || ""}`;
}
/**
* Strips the content from a data URL, returning a placeholder with the MIME type.
*
* Data URLs can be very long (e.g. base64 encoded scripts for Web Workers),
* with little valuable information, often leading to envelopes getting dropped due
* to size limit violations. Therefore, we strip data URLs and replace them with a
* placeholder.
*
* @param url - The URL to process
* @param includeDataPrefix - If true, includes the first 10 characters of the data stream
* for debugging (e.g., to identify magic bytes like WASM's AGFzbQ).
* Defaults to true.
* @returns For data URLs, returns a short format like `data:text/javascript;base64,SGVsbG8gV2... [truncated]`.
* For non-data URLs, returns the original URL unchanged.
*/
function stripDataUrlContent(url, includeDataPrefix = true) {
if (url.startsWith("data:")) {
const match = url.match(/^data:([^;,]+)/);
const mimeType = match ? match[1] : "text/plain";
const isBase64 = url.includes(";base64,");
const dataStart = url.indexOf(",");
let dataPrefix = "";
if (includeDataPrefix && dataStart !== -1) {
const data = url.slice(dataStart + 1);
dataPrefix = data.length > 10 ? `${data.slice(0, 10)}... [truncated]` : data;
}
return `data:${mimeType}${isBase64 ? ",base64" : ""}${dataPrefix ? `,${dataPrefix}` : ""}`;
}
return url;
}
// src/utils/isSentryRequestUrl.ts
/**
* Checks whether given url points to Sentry server
*
* @param url url to verify
*/
function isSentryRequestUrl(url, client) {
const dsn = client?.getDsn();
const tunnel = client?.getOptions().tunnel;
return checkDsn(url, dsn) || checkTunnel(url, tunnel);
}
function checkTunnel(url, tunnel) {
if (!tunnel) return false;
return removeTrailingSlash(url) === removeTrailingSlash(tunnel);
}
function checkDsn(url, dsn) {
const urlParts = parseStringToURLObject(url);
if (!urlParts || isURLObjectRelative(urlParts)) return false;
if (!dsn) return false;
return hostnameMatchesDsnHost(urlParts.hostname, dsn.host) && /(^|&|\?)sentry_key=/.test(urlParts.search);
}
function hostnameMatchesDsnHost(hostname, dsnHost) {
return hostname === dsnHost || dsnHost.length > 0 && hostname.endsWith(`.${dsnHost}`);
}
function removeTrailingSlash(str) {
return str[str.length - 1] === "/" ? str.slice(0, -1) : str;
}
// src/utils/hash.ts
/**
* 32-bit FNV-1a. Keep this algorithm stable: tunnel paths must match across SDK versions.
*/
function fnv1a32(input) {
let hash = 2166136261;
for (let i = 0; i < input.length; i++) {
hash ^= input.charCodeAt(i);
hash = Math.imul(hash, 16777619);
}
return (hash >>> 0).toString(36);
}
// src/utils/tunnelStore.ts
/**
* Only this module touches the store, through the functions below.
*/
function getTunnelStore() {
return require_cacheOrigin.getGlobalSingleton("tunnelStore", () => ({ clients: /* @__PURE__ */ new WeakMap() }));
}
/**
* What the tunnel keeps for a client.
*/
function getClientTunnel(client) {
return getTunnelStore().clients.get(client);
}
/**
* Sets what the tunnel keeps for a client. Merges into what is already there, like `scope.setTags`.
*/
function setClientTunnel(client, state) {
const { clients } = getTunnelStore();
clients.set(client, {
...clients.get(client),
...state
});
}
/**
* The framework-known tunnel settings, see `setTunnelDefaults`.
*/
function getStoredTunnelDefaults() {
return getTunnelStore().defaults;
}
/**
* Replaces the framework-known tunnel settings.
*/
function setStoredTunnelDefaults(defaults) {
getTunnelStore().defaults = defaults;
}
/**
* Records that core's HTTP server instrumentation is set up. Its `emit` wrapper handles tunnel requests, so `node:http`
* servers need no second one for the tunnel.
*/
function setHttpServerHandlesTunnel() {
getTunnelStore().httpServerHandlesTunnel = true;
}
/**
* Whether core's HTTP server instrumentation handles tunnel requests, see {@link setHttpServerHandlesTunnel}.
*/
function httpServerHandlesTunnel() {
return !!getTunnelStore().httpServerHandlesTunnel;
}
/**
* Sets what answers tunnel requests on Node servers, like the forwarder `serveTunnelIntegration` brings in.
*/
function setNodeTunnelHandler(handler) {
getTunnelStore().nodeHandler = handler;
}
/**
* What answers tunnel requests on Node servers, see {@link setNodeTunnelHandler}.
*/
function getNodeTunnelHandler() {
return getTunnelStore().nodeHandler;
}
// src/utils/tunnel.ts
/**
* Computes a server client's served tunnel from its resolved options, and stores it.
*/
function setServedTunnel(client, tunnelOptions, forward) {
const allowedDsns = resolveAllowedDsns(tunnelOptions.allowedDsns, client.getDsn());
const servedTunnel = {
paths: resolveTunnelPaths(tunnelOptions, allowedDsns),
basePath: tunnelOptions.basePath,
allowedDsns,
forward,
intercept: tunnelOptions.intercept !== false
};
setClientTunnel(client, { served: servedTunnel });
return servedTunnel;
}
/**
* The active client's served tunnel. It lives in the tunnel store, so a copy of this module that didn't set it up,
* like the one a bundler gives Next.js's middleware next to its `instrumentation`, still finds it.
*/
function getServedTunnel(client = require_cacheOrigin.getClient()) {
return client && getClientTunnel(client)?.served;
}
/**
* Fills in framework defaults (like the base path) for a managed tunnel on the DSN-derived path. User options win.
* A path the user wrote, as a string or `path`, is used as written, so a tunnel served outside the app keeps working.
* The base path is normalized, and a root one is no default at all.
*/
function applyBrowserTunnelDefaults(tunnel, defaults) {
if (!tunnel || typeof tunnel === "string" || tunnel !== true && tunnel.path) return tunnel;
const { basePath, ...rest } = defaults ?? {};
const normalizedBasePath = normalizeTunnelBasePath(basePath);
const resolvedDefaults = normalizedBasePath ? {
...rest,
basePath: normalizedBasePath
} : rest;
if (!Object.keys(resolvedDefaults).length) return tunnel;
return {
...resolvedDefaults,
...tunnel === true ? {} : tunnel
};
}
/**
* Returns the same-origin tunnel path for a DSN, e.g. `/k3x9q2a`, by default the active client's. Browser and server
* derive it independently, and as a hash it gives ad-blocker filter lists nothing to match.
*/
function getTunnelPath(dsn) {
const components = dsn ? require_cacheOrigin.makeDsn(dsn) : require_cacheOrigin.getClient()?.getDsn();
return components ? `/${fnv1a32(require_cacheOrigin.dsnToString(components))}` : void 0;
}
/**
* Returns the active server client's tunnel paths, relative to its base path. For frameworks that can only register
* routes; everything else uses {@link handleTunnelRequestIfMatched}.
*/
function getTunnelPaths() {
return getServedTunnel()?.paths ?? [];
}
/**
* The paths a managed tunnel is served at: the fixed `path`, or else one per allowed DSN.
*/
function resolveTunnelPaths(tunnelOptions, allowedDsns) {
const fixedPath = tunnelOptions.path?.replace(/\/$/, "");
if (fixedPath) return [fixedPath];
const paths = allowedDsns.map((dsn) => getTunnelPath(dsn));
return [...new Set(paths.filter((path) => !!path))];
}
/**
* `ignoreSpans` filters for the server spans of tunnel requests. They match `url.path` and the legacy `http.url`,
* which some framework spans start with (SvelteKit's `sveltekit.handle.root`).
*/
function getTunnelIgnoreSpanFilters(tunnelOptions, paths) {
if (!paths.length) return [];
const pathPattern = `${require_cacheOrigin.escapeStringForRegex(normalizeTunnelBasePath(tunnelOptions.basePath))}(?:${paths.map(require_cacheOrigin.escapeStringForRegex).join("|")})/?`;
return [{ attributes: { [_sentry_conventions_attributes.URL_PATH]: new RegExp(`^${pathPattern}$`) } }, { attributes: { "http.url": new RegExp(`^[a-z][a-z\\d+.-]*://[^/]+${pathPattern}(?:[?#].*)?$`) } }];
}
/**
* Normalizes a base path to `/app`, or `''` for the root.
*/
function normalizeTunnelBasePath(basePath) {
const path = (basePath?.startsWith("./") ? basePath.slice(1) : basePath ?? "").replace(/\/$/, "");
return !path || path.startsWith("/") ? path : `/${path}`;
}
/**
* Resolves the tunnel the public helpers match: `options`, else the one `serveTunnelIntegration` serves, else the
* path of the active client's own DSN.
*/
function resolveTunnelMatch(options) {
const servedTunnel = !options && getServedTunnel();
if (servedTunnel) return servedTunnel;
const allowedDsns = resolveAllowedDsns(options?.allowedDsns, require_cacheOrigin.getClient()?.getDsn());
return {
paths: resolveTunnelPaths(options ?? {}, allowedDsns),
basePath: options?.basePath,
allowedDsns
};
}
/**
* Returns true if the request is a POST to one of the tunnel's paths.
*/
function matchesTunnel(request, tunnel) {
if (request.method !== "POST" || !request.url) return false;
const path = stripBasePath(parseUrl(request.url).path || "/", tunnel.basePath);
return path !== void 0 && tunnel.paths.includes(path.replace(/\/$/, ""));
}
/**
* Returns true if the request is a POST to the managed tunnel. The tunnel comes from `options`, else from
* `serveTunnelIntegration`, else it's the path of the active client's own DSN.
*/
function isTunnelRequest(request, options) {
return matchesTunnel(request, resolveTunnelMatch(options));
}
/**
* Returns true if the request targets the tunnel `serveTunnelIntegration` serves, whether the SDK answers it or the
* app does with `intercept: false`. The server SDKs record no session or span for these. Unlike
* {@link isTunnelRequest}, there's no fallback, so the framework SDKs serve nothing without the integration. `client`
* defaults to the active one.
*/
function isServedTunnelRequest(request, client) {
try {
return !!matchServedTunnel(request, client);
} catch (error) {
require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.error("Sentry tunnel: failed to match a request", error);
return false;
}
}
/**
* The served tunnel, if the SDK answers this request on it. `client` defaults to the active one.
*/
function getServedTunnelMatch(request, client) {
const servedTunnel = matchServedTunnel(request, client);
return servedTunnel?.intercept ? servedTunnel : void 0;
}
/**
* The served tunnel, if this request targets it.
*/
function matchServedTunnel(request, client) {
const servedTunnel = getServedTunnel(client);
return servedTunnel?.allowedDsns.length && matchesTunnel(request, servedTunnel) ? servedTunnel : void 0;
}
/**
* Forwards the request if it targets the tunnel `serveTunnelIntegration` serves, otherwise returns `undefined`. The
* runtime and framework SDKs answer tunnel requests with it, ahead of the app.
*
* It never throws, since a throw here would break the app's own requests. Until a request is claimed, a failure hands
* it to the app. Once claimed, its body may be read already, so a failure ends in a 502 instead. `client` defaults to
* the active one.
*/
function handleServedTunnelRequest(request, client) {
let servedTunnel;
try {
servedTunnel = request.body && getServedTunnelMatch(request, client);
if (!servedTunnel) return;
} catch (error) {
require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.error("Sentry tunnel: failed to match a request", error);
return;
}
const { forward, allowedDsns } = servedTunnel;
return Promise.resolve().then(() => forward(request, allowedDsns)).catch((error) => {
require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.error("Sentry tunnel: failed to forward a request", error);
return new Response(null, { status: 502 });
});
}
/**
* `allowedDsns` plus the server's own DSN, which is always allowed.
*/
function resolveAllowedDsns(allowedDsns, ownDsn) {
const dsns = /* @__PURE__ */ new Set();
for (const components of [...(allowedDsns ?? []).map((dsn) => require_cacheOrigin.makeDsn(dsn)), ownDsn]) if (components) dsns.add(require_cacheOrigin.dsnToString(components));
return [...dsns];
}
/**
* Returns the path below `basePath`, or `undefined` outside it.
*/
function stripBasePath(pathname, basePath) {
const base = normalizeTunnelBasePath(basePath);
if (!base) return pathname;
return pathname === base || pathname.startsWith(`${base}/`) ? pathname.slice(base.length) : void 0;
}
// src/utils/tunnelForward.ts
function handleTunnelRequest(requestOrOptions, responseOrOptions, nodeOptions) {
if (isNodeTunnelResponse(responseOrOptions)) {
const nodeResponse = responseOrOptions;
return forwardTunnelRequest(toFetchRequest(requestOrOptions), getAllowedDsns(nodeOptions)).then((fetchResponse) => writeNodeResponse(nodeResponse, fetchResponse));
}
const isLegacyCall = "request" in requestOrOptions && !("method" in requestOrOptions);
return forwardTunnelRequest(isLegacyCall ? requestOrOptions.request : requestOrOptions, getAllowedDsns(isLegacyCall ? requestOrOptions : responseOrOptions));
}
function handleTunnelRequestIfMatched(request, responseOrOptions, nodeOptions) {
const response = isNodeTunnelResponse(responseOrOptions) ? responseOrOptions : void 0;
const tunnel = resolveTunnelMatch(response ? nodeOptions : responseOrOptions);
if (!tunnel.allowedDsns.length || !matchesTunnel(request, tunnel)) return;
if (!response) return forwardTunnelRequest(request, tunnel.allowedDsns);
return forwardTunnelRequest(toFetchRequest(request), tunnel.allowedDsns).then((fetchResponse) => writeNodeResponse(response, fetchResponse));
}
/**
* Answers a request to the tunnel `serveTunnelIntegration` serves on a Node server, ahead of the app. Returns `true`
* when it claimed the request and answers it, `false` to hand the request to the app.
*
* It never throws, since it runs inside the server's `emit`, where a throw crashes the process. Until a request is
* claimed, a failure hands it to the app. Once claimed, its body may be read already, so a failure ends in a 502.
*/
function handleServedNodeTunnelRequest(request, response) {
let forward;
try {
const servedTunnel = getServedTunnelMatch(request);
if (!servedTunnel) return false;
const fetchRequest = toFetchRequest(request);
forward = () => servedTunnel.forward(fetchRequest, servedTunnel.allowedDsns);
} catch (error) {
require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.error("Sentry tunnel: failed to match a request", error);
return false;
}
Promise.resolve().then(forward).then((fetchResponse) => writeNodeResponse(response, fetchResponse)).catch((error) => {
require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.error("Sentry tunnel: failed to forward a request", error);
try {
if (!response.headersSent) response.writeHead(502);
response.end(/* @__PURE__ */ new Uint8Array());
} catch {}
});
return true;
}
/**
* `allowedDsns` plus the server's own DSN. Without `allowedDsns`, the DSNs `serveTunnelIntegration` allows, so its
* options apply here too.
*/
function getAllowedDsns(options) {
return options?.allowedDsns ? resolveAllowedDsns(options.allowedDsns, require_cacheOrigin.getClient()?.getDsn()) : resolveTunnelMatch().allowedDsns;
}
/**
* The headers of Sentry's answer the browser SDK reads. The rest describe the connection to Sentry, which HTTP/2
* rejects.
*/
const FORWARDED_RESPONSE_HEADERS = [
"content-type",
"retry-after",
"x-sentry-rate-limits"
];
/**
* The headers of Sentry's answer to pass on to the browser, see `FORWARDED_RESPONSE_HEADERS`.
*/
function pickForwardedHeaders(response) {
const headers = {};
for (const name of FORWARDED_RESPONSE_HEADERS) {
const value = response.headers.get(name);
if (value) headers[name] = value;
}
return headers;
}
function isNodeTunnelResponse(value) {
return typeof value?.writeHead === "function";
}
function toFetchRequest(request) {
const headers = new Headers();
for (const [name, value] of Object.entries(request.headers)) if (value !== void 0 && !name.startsWith(":")) headers.set(name, Array.isArray(value) ? value.join(", ") : value);
let iterator;
const getIterator = () => iterator ?? (iterator = request[Symbol.asyncIterator]());
const encoder = new TextEncoder();
const body = new ReadableStream({
async pull(controller) {
const { done, value } = await getIterator().next();
if (done) {
controller.close();
return;
}
controller.enqueue(typeof value === "string" ? encoder.encode(value) : value);
},
async cancel() {
while (!(await getIterator().next()).done);
}
});
return new Request("http://localhost/", {
method: "POST",
headers,
body,
duplex: "half"
});
}
async function writeNodeResponse(response, fetchResponse) {
const body = await fetchResponse.arrayBuffer().catch(() => void 0);
if (!body) {
response.writeHead(500);
response.end(/* @__PURE__ */ new Uint8Array());
return;
}
response.writeHead(fetchResponse.status, pickForwardedHeaders(fetchResponse));
response.end(new Uint8Array(body));
}
function withDecodedBodyHeaders(response) {
const headers = new Headers(response.headers);
headers.delete("content-encoding");
headers.delete("content-length");
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers
});
}
/**
* Forwards an envelope to Sentry if its DSN is one of `allowedDsns`, otherwise answers with the rejecting response.
*/
async function forwardTunnelRequest(request, allowedDsns) {
return withDecodedBodyHeaders(await forwardEnvelope(request, allowedDsns));
}
/**
* How long a forward waits on Sentry, so a hanging Sentry doesn't hold the browser's connection open.
*/
const FORWARD_TIMEOUT_MS = 3e4;
async function forwardEnvelope(request, allowedDsns) {
if (allowedDsns.length === 0) return new Response("Tunnel not configured", { status: 500 });
if (!Number(request.headers.get("content-length"))) return new Response("Length required", { status: 411 });
const reader = request.body?.getReader();
const head = reader && await readEnvelopeHeaderLine(reader).catch(() => void 0);
if (!reader || !head) return new Response("Invalid envelope", { status: 400 });
const sentryIngestUrl = resolveIngestUrl(head.line, allowedDsns);
if (typeof sentryIngestUrl !== "string") {
reader.cancel().catch(() => void 0);
return sentryIngestUrl;
}
try {
return await require_cacheOrigin.suppressTracing(() => fetch(sentryIngestUrl, {
method: "POST",
headers: forwardHeaders(request),
body: prependToStream(head.read, reader),
duplex: "half",
signal: AbortSignal.timeout(FORWARD_TIMEOUT_MS)
}));
} catch (error) {
require_cacheOrigin.debug.error("Sentry tunnel: failed to forward envelope", error);
return new Response("Failed to forward envelope to Sentry", { status: 500 });
}
}
/**
* Returns the ingest URL for an envelope header line, or the rejecting response.
*/
function resolveIngestUrl(headerLine, allowedDsns) {
let envelopeHeader;
try {
envelopeHeader = JSON.parse(new TextDecoder().decode(headerLine));
} catch {
return new Response("Invalid envelope", { status: 400 });
}
if (!envelopeHeader) return new Response("Invalid envelope: missing header", { status: 400 });
const dsn = envelopeHeader.dsn;
if (!dsn || typeof dsn !== "string") return new Response("Invalid envelope: missing DSN", { status: 400 });
if (!allowedDsns.some((allowed) => allowed === dsn)) {
require_cacheOrigin.debug.warn(`Sentry tunnel: rejected request with unauthorized DSN (${dsn})`);
return new Response("DSN not allowed", { status: 403 });
}
const dsnComponents = require_cacheOrigin.makeDsn(dsn);
if (!dsnComponents) {
require_cacheOrigin.debug.warn(`Could not extract DSN Components from: ${dsn}`);
return new Response("Invalid DSN", { status: 403 });
}
return getEnvelopeEndpointWithUrlEncodedAuth(dsnComponents);
}
/**
* A header line longer than this is not an envelope.
*/
const MAX_ENVELOPE_HEADER_BYTES = 65536;
/**
* Client headers Relay reads from a browser's own request: the user agent and its client hints to tell the browser,
* and `Origin` or `Referer` for the project's allowed domains check, which Relay skips without them.
*/
const FORWARDED_CLIENT_HEADERS = [
"user-agent",
"sec-ch-ua",
"sec-ch-ua-model",
"sec-ch-ua-platform",
"sec-ch-ua-platform-version",
"origin",
"referer"
];
/**
* Sentry SaaS replaces `X-Sentry-Forwarded-For` with the connecting IP, which is the tunnel server, but keeps these
* and prefers them. Passing them through keeps the client IP, as a rewrite proxy does.
*/
const FORWARDED_CLIENT_IP_HEADERS = [
"cf-connecting-ip",
"x-vercel-forwarded-for",
"x-forwarded-for"
];
/**
* Reads the body up to the envelope header line. Returns the line and every byte read, or `undefined`.
*/
async function readEnvelopeHeaderLine(reader) {
let read = /* @__PURE__ */ new Uint8Array(0);
while (read.length <= MAX_ENVELOPE_HEADER_BYTES) {
const { done, value } = await reader.read();
if (done) return read.length ? {
line: read,
read
} : void 0;
const searchFrom = read.length;
read = concatBytes(read, value);
const newline = read.indexOf(10, searchFrom);
if (newline !== -1) return {
line: read.subarray(0, newline),
read
};
}
await reader.cancel();
}
function concatBytes(a, b) {
const merged = new Uint8Array(a.length + b.length);
merged.set(a);
merged.set(b, a.length);
return merged;
}
function prependToStream(prefix, reader) {
return new ReadableStream({
start(controller) {
controller.enqueue(prefix);
},
async pull(controller) {
const { done, value } = await reader.read();
if (done) {
controller.close();
return;
}
controller.enqueue(value);
},
cancel(reason) {
return reader.cancel(reason);
}
});
}
function forwardHeaders(request) {
const headers = { "Content-Type": "application/x-sentry-envelope" };
const clientIp = FORWARDED_CLIENT_IP_HEADERS.map((name) => request.headers.get(name)).find(Boolean);
if (clientIp) headers["X-Sentry-Forwarded-For"] = clientIp;
for (const name of [...FORWARDED_CLIENT_IP_HEADERS, ...FORWARDED_CLIENT_HEADERS]) {
const value = request.headers.get(name);
if (value) headers[name] = value;
}
return headers;
}
// src/utils/tracePropagationTargets.ts
const NOT_PROPAGATED_MESSAGE = "[Tracing] Not injecting trace data for url because it does not match tracePropagationTargets:";
const NORMALIZED_REGEXP_CACHE = /* @__PURE__ */ new WeakMap();
/**
* Returns an equivalent RegExp that ignores case and is safe to `test()` repeatedly.
*
* The `g` and `y` flags are dropped because they make `test()` stateful via `lastIndex`, which would make a target
* match only every other request. Results are cached since targets are matched once per outgoing request.
*/
function normalizeRegExpTarget(pattern) {
const flags = `${pattern.flags.replace(/[gy]/g, "")}${pattern.ignoreCase ? "" : "i"}`;
if (flags === pattern.flags) return pattern;
const cached = NORMALIZED_REGEXP_CACHE.get(pattern);
if (cached) return cached;
const normalizedPattern = new RegExp(pattern.source, flags);
NORMALIZED_REGEXP_CACHE.set(pattern, normalizedPattern);
return normalizedPattern;
}
/**
* Check if a value matches any of the given `tracePropagationTargets`.
*
* The value is usually a URL, but it can be anything a propagation decision is made on, such as a
* Cloudflare binding name. String targets match as a substring unless `requireExactStringMatch` is set.
*
* Matching is case-insensitive: URL normalization (e.g. `new URL()`) lower-cases the origin, so a target
* written with the same casing as the request (`'myApi.com'`, `/^myApi\.com/`) would otherwise never match.
*/
function matchesTracePropagationTargets(value, tracePropagationTargets, requireExactStringMatch = false) {
const lowerCaseValue = value.toLowerCase();
for (const target of tracePropagationTargets) if (require_cacheOrigin.isString(target)) {
const lowerCaseTarget = target.toLowerCase();
if (requireExactStringMatch ? lowerCaseValue === lowerCaseTarget : lowerCaseValue.includes(lowerCaseTarget)) return true;
} else if (require_cacheOrigin.isRegExp(target) && normalizeRegExpTarget(target).test(value)) return true;
return false;
}
/**
* Check if a given URL should be propagated to or not.
* If no url is defined, or no trace propagation targets are defined, this will always return `true`.
* You can also optionally provide a decision map, to cache decisions and avoid repeated regex lookups.
*/
function shouldPropagateTraceForUrl(url, tracePropagationTargets, decisionMap) {
if (typeof url !== "string" || !tracePropagationTargets) return true;
const cachedDecision = decisionMap?.get(url);
if (cachedDecision !== void 0) {
require_cacheOrigin.DEBUG_BUILD && !cachedDecision && require_cacheOrigin.debug.log(NOT_PROPAGATED_MESSAGE, url);
return cachedDecision;
}
const decision = matchesTracePropagationTargets(url, tracePropagationTargets);
decisionMap?.set(url, decision);
require_cacheOrigin.DEBUG_BUILD && !decision && require_cacheOrigin.debug.log(NOT_PROPAGATED_MESSAGE, url);
return decision;
}
// src/utils/meta.ts
/**
* Returns a string of meta tags that represent the current trace data.
*
* You can use this to propagate a trace from your server-side rendered Html to the browser.
* This function returns up to two meta tags, `sentry-trace` and `baggage`, depending on the
* current trace data state.
*
* @example
* Usage example:
*
* ```js
* function renderHtml() {
* return `
* <head>
* ${getTraceMetaTags()}
* </head>
* `;
* }
* ```
*
*/
function getTraceMetaTags(traceData) {
return Object.entries(traceData || require_cacheOrigin.getTraceData()).map(([key, value]) => `<meta name="${key}" content="${value}"/>`).join("");
}
/**
* The name of the meta tag that gives the release to the browser SDK. Framework SDKs write it into each page
* instead of injecting the release into the client chunks, where it would change their content hashes on every
* release.
*/
const RELEASE_META_TAG_NAME = "sentry-release";
/**
* Returns the meta tag that gives `release` to the browser SDK.
*/
function getReleaseMetaTag(release) {
return `<meta name="${RELEASE_META_TAG_NAME}" content="${escapeHtmlAttribute(release)}"/>`;
}
function escapeHtmlAttribute(value) {
return value.replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<").replace(/>/g, ">");
}
// src/utils/request.ts
/** Hard cap on captured body size, even when `maxRequestBodySize` is `'always'`. */
const MAX_BODY_BYTE_LENGTH = 1048576;
/** Content types that are safe to capture as text. */
const TEXT_CONTENT_TYPES = [
"text/",
"application/json",
"application/x-www-form-urlencoded",
"application/xml",
"application/graphql"
];
/**
* Convert a `maxRequestBodySize` setting to a maximum byte length.
*/
function getMaxBodyByteLength(maxRequestBodySize) {
if (maxRequestBodySize === "small") return 1e3;
if (maxRequestBodySize === "medium") return 1e4;
return MAX_BODY_BYTE_LENGTH;
}
/**
* Transforms a `Headers` object that implements the `Web Fetch API` (https://developer.mozilla.org/en-US/docs/Web/API/Headers) into a simple key-value dict.
* The header keys will be lower case: e.g. A "Content-Type" header will be stored as "content-type".
*/
function winterCGHeadersToDict(winterCGHeaders) {
const headers = {};
try {
winterCGHeaders.forEach((value, key) => {
if (typeof value === "string") headers[key] = value;
});
} catch {}
return headers;
}
/**
* Convert common request headers to a simple dictionary.
*/
function headersToDict(reqHeaders) {
const headers = Object.create(null);
try {
Object.entries(reqHeaders).forEach(([key, value]) => {
if (key.startsWith(":")) return;
if (typeof value === "string") headers[key] = value;
else if (typeof value === "number") headers[key] = String(value);
});
} catch {}
return headers;
}
/**
* The `host` header, or the HTTP/2 `:authority` pseudo-header that replaces it.
*/
function getHostFromHeaders(headers) {
const host = headers.host ?? headers[":authority"];
return typeof host === "string" ? host : void 0;
}
/**
* Converts a `Request` object that implements the `Web Fetch API` (https://developer.mozilla.org/en-US/docs/Web/API/Headers) into the format that the `RequestData` integration understands.
*/
function winterCGRequestToRequestData(req) {
const headers = winterCGHeadersToDict(req.headers);
return {
method: req.method,
url: req.url,
query_string: extractQueryParamsFromUrl(req.url),
headers
};
}
/**
* Checks if the content type is textual and safe to capture.
*/
function isTextualContentType(contentType) {
if (!contentType) return false;
const lowerContentType = contentType.toLowerCase();
return TEXT_CONTENT_TYPES.some((type) => lowerContentType.includes(type));
}
/**
* Captures the body from a Web Fetch API Request and adds it to the isolation scope.
*
* This function clones the request to read the body without affecting the original.
* Only textual content types are captured - binary data is skipped.
*
* This is used by WinterCG-compatible runtimes (Cloudflare Workers, Deno, Bun, Vercel Edge, etc.)
* that use the Web Fetch API Request object.
*
* @param request - The incoming Web Fetch API Request
* @param isolationScope - The isolation scope to add the body to
* @param maxRequestBodySize - The maximum size of the request body to capture ('small' = 1KB, 'medium' = 10KB, 'always' = 1MB)
*/
async function captureBodyFromWinterCGRequest(request, isolationScope, maxRequestBodySize) {
try {
const contentType = request.headers.get("content-type");
if (!isTextualContentType(contentType)) {
require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.log("Skipping body capture for non-textual content type:", contentType);
return;
}
if (!request.body) return;
const contentLength = request.headers.get("content-length");
const maxBodySize = getMaxBodyByteLength(maxRequestBodySize);
if (contentLength) {
const length = parseInt(contentLength, 10);
if (!isNaN(length) && length > 1048576) {
require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.log("Skipping body capture: body too large", length);
return;
}
}
const bodyPromise = request.clone().text();
const timeoutPromise = new Promise((resolve) => {
require_cacheOrigin.safeUnref(setTimeout(() => resolve(null), 2e3));
});
const body = await Promise.race([bodyPromise, timeoutPromise]);
if (body === null) {
require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.log("Timeout reading request body");
return;
}
if (!body) return;
const bytes = new TextEncoder().encode(body);
const bodyByteLength = bytes.length;
let truncatedBody;
if (bodyByteLength > maxBodySize) truncatedBody = `${new TextDecoder().decode(bytes.slice(0, maxBodySize - 3))}...`;
else truncatedBody = body;
isolationScope.setSDKProcessingMetadata({ normalizedRequest: { data: truncatedBody } });
require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.log("Captured request body:", bodyByteLength, "bytes");
} catch (error) {
require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.error("Error capturing request body:", error);
}
}
/**
* Convert a HTTP request object to RequestEventData to be passed as normalizedRequest.
* Instead of allowing `PolymorphicRequest` to be passed,
* we want to be more specific and generally require a http.IncomingMessage-like object.
*/
function httpRequestToRequestData(request) {
const headers = request.headers || {};
const host = (typeof headers["x-forwarded-host"] === "string" ? headers["x-forwarded-host"] : void 0) || getHostFromHeaders(headers);
const protocol = (typeof headers["x-forwarded-proto"] === "string" ? headers["x-forwarded-proto"] : void 0) || request.protocol || (request.socket?.encrypted ? "https" : "http");
const url = request.url || "";
const absoluteUrl = getAbsoluteUrl({
url,
host,
protocol
});
const data = request.body || void 0;
const cookies = request.cookies;
return {
url: absoluteUrl,
method: request.method,
query_string: extractQueryParamsFromUrl(url),
headers: headersToDict(headers),
cookies,
data
};
}
function getAbsoluteUrl({ url, protocol, host }) {
if (url?.startsWith("http")) return url;
if (url && host) return `${protocol}://${host}${url}`;
}
/**
* Converts incoming HTTP request or response headers to OpenTelemetry span attributes following semantic conventions.
* Header names are converted to the format: http.<request|response>.header.<key>
* where <key> is the header name in lowercase. Header values are always emitted as a string array.
*
* @param lifecycle - The lifecycle of the headers, either 'request' or 'response'
*
* @see https://opentelemetry.io/docs/specs/semconv/registry/attributes/http/#http-request-header
* @see https://opentelemetry.io/docs/specs/semconv/registry/attributes/http/#http-response-header
*
* @see https://conventions.sentry.dev/attributes/http/#http-request-header-key
* @see https://conventions.sentry.dev/attributes/http/#http-response-header-key
*/
function httpHeadersToSpanAttributes(headers, dataCollection, lifecycle = "request") {
const headerBehavior = lifecycle === "request" ? dataCollection.httpHeaders.request : dataCollection.httpHeaders.response;
const cookieBehavior = dataCollection.cookies;
const prefix = `http.${lifecycle}.header.`;
const spanAttributes = {};
try {
const regularHeaders = {};
for (const [key, value] of Object.entries(headers)) {
if (value == null) continue;
const lowerKey = key.toLowerCase();
if (lowerKey === "cookie" || lowerKey === "set-cookie") {
if (cookieBehavior === false) continue;
const cookies = parseCookieHeader(value, lowerKey);
spanAttributes[`${prefix}${lowerKey}`] = cookies.length ? filterCookiePairs(cookies, cookieBehavior) : [require_cacheOrigin.FILTERED_VALUE];
} else {
if (headerBehavior === false) continue;
if (Array.isArray(value)) regularHeaders[lowerKey] = value.filter((v) => v != null).map((v) => String(v));
else if (typeof value === "string") regularHeaders[lowerKey] = [value];
}
}
if (headerBehavior !== false) for (const [headerKey, headerValues] of Object.entries(regularHeaders)) spanAttributes[`${prefix}${headerKey}`] = require_cacheOrigin.shouldFilterDataKey(headerKey, headerBehavior) ? [require_cacheOrigin.FILTERED_VALUE] : headerValues;
} catch {}
return spanAttributes;
}
/** Formats cookie pairs as `name=value` span attribute values, with sensitive values replaced. */
function filterCookiePairs(cookies, cookieBehavior) {
return cookies.map(([cookieKey, cookieValue]) => {
if (cookieKey === "") return require_cacheOrigin.FILTERED_VALUE;
return require_cacheOrigin.shouldFilterDataKey(cookieKey, cookieBehavior, require_cacheOrigin.SENSITIVE_COOKIE_NAME_SNIPPETS) ? `${cookieKey}=${require_cacheOrigin.FILTERED_VALUE}` : `${cookieKey}=${cookieValue}`;
});
}
/** Extract the query params from an URL. */
function extractQueryParamsFromUrl(url) {
if (!url) return;
try {
return getUrlQuery(new URL(url, "http://s.io").search);
} catch {
return;
}
}
/**
* Read the `content-length` header as a number, if it holds a valid one.
*
* `content-length` is the encoded (on-the-wire) body size whether or not a `content-encoding` is
* applied, so it maps to `http.request.body.size` / `http.response.body.size`. The decoded body size
* cannot be derived from it.
*/
function getContentLengthFromHeaders(headers) {
const contentLength = headers["content-length"];
if (typeof contentLength !== "string") return;
const length = parseInt(contentLength, 10);
return length >= 0 ? length : void 0;
}
// src/breadcrumbs.ts
/**
* Default maximum number of breadcrumbs added to an event. Can be overwritten
* with {@link Options.maxBreadcrumbs}.
*/
const DEFAULT_BREADCRUMBS = 100;
/**
* Records a new breadcrumb which will be attached to future events.
*
* Breadcrumbs will be added to subsequent events to provide more context on
* user's actions prior to an error or crash.
*/
function addBreadcrumb(breadcrumb, hint) {
const client = require_cacheOrigin.getClient();
const isolationScope = require_cacheOrigin.getIsolationScope();
if (!client) return;
const { beforeBreadcrumb = null, maxBreadcrumbs = DEFAULT_BREADCRUMBS } = client.getOptions();
if (maxBreadcrumbs <= 0) return;
const mergedBreadcrumb = {
timestamp: require_cacheOrigin.dateTimestampInSeconds(),
...breadcrumb
};
const finalBreadcrumb = beforeBreadcrumb ? require_cacheOrigin.safeCallback(require_cacheOrigin.DEBUG_BUILD ? "The `beforeBreadcrumb` callback threw an error, dropping the breadcrumb:" : "", () => require_cacheOrigin.consoleSandbox(() => beforeBreadcrumb(mergedBreadcrumb, hint)), () => null) : mergedBreadcrumb;
if (finalBreadcrumb === null) return;
if (client.emit) client.emit("beforeAddBreadcrumb", finalBreadcrumb, hint);
isolationScope.addBreadcrumb(finalBreadcrumb, maxBreadcrumbs);
}
// src/utils/eventbuilder.ts
/**
* Extracts stack frames from the error.stack string
*/
function parseStackFrames(stackParser, error) {
return stackParser(error.stack || "", 1);
}
function hasSentryFetchUrlHost(error) {
return require_cacheOrigin.isError(error) && "__sentry_fetch_url_host__" in error && typeof error.__sentry_fetch_url_host__ === "string";
}
/**
* Enhances the error message with the hostname for better Sentry error reporting.
* This allows third-party packages to still match on the original error message,
* while Sentry gets the enhanced version with context.
*
* Only used internally
* @hidden
*/
function _enhanceErrorWithSentryInfo(error) {
const message = errorMessageToString(error.message);
if (hasSentryFetchUrlHost(error)) return `${message} (${error.__sentry_fetch_url_host__})`;
return message;
}
function errorMessageToString(message) {
if (typeof message === "string") return message;
if (message == null) return "";
if (require_cacheOrigin.isPrimitive(message)) return String(message);
if (require_cacheOrigin.isPlainObject(message) || Array.isArray(message)) {
const json = require_cacheOrigin.stringify(message, "");
if (json) return json;
}
return require_cacheOrigin.stringifyValue(void 0, message);
}
/**
* Extracts stack frames from the error and builds a Sentry Exception
*/
function exceptionFromError(stackParser, error) {
const exception = {
type: error.name || error.constructor.name,
value: _enhanceErrorWithSentryInfo(error)
};
const frames = parseStackFrames(stackParser, error);
if (frames.length) exception.stacktrace = { frames };
return exception;
}
/** If a plain object has a property that is an `Error`, return this error. */
function getErrorPropertyFromObject(obj) {
for (const prop in obj) if (Object.prototype.hasOwnProperty.call(obj, prop)) {
const value = obj[prop];
if (require_cacheOrigin.isError(value)) return value;
}
}
function getMessageForObject(exception) {
if ("name" in exception && typeof exception.name === "string") {
let message = `'${exception.name}' captured as exception`;
if ("message" in exception && typeof exception.message === "string") message += ` with message '${exception.message}'`;
return message;
} else if ("message" in exception && typeof exception.message === "string") return exception.message;
const keys = require_cacheOrigin.extractExceptionKeysForMessage(exception);
if (require_cacheOrigin.isErrorEvent(exception)) return `Event \`ErrorEvent\` captured as exception with message \`${exception.message}\``;
const className = getObjectClassName(exception);
return `${className && className !== "Object" ? `'${className}'` : "Object"} captured as exception with keys: ${keys}`;
}
function getObjectClassName(obj) {
try {
const prototype = Object.getPrototypeOf(obj);
return prototype ? prototype.constructor.name : void 0;
} catch {}
}
function getException(client, mechanism, exception, hint) {
if (require_cacheOrigin.isError(exception)) return [exception, void 0];
mechanism.synthetic = true;
if (require_cacheOrigin.isPlainObject(exception)) {
const normalizeDepth = client?.getOptions().normalizeDepth;
const extras = { ["__serialized__"]: require_cacheOrigin.normalizeToSize(exception, normalizeDepth) };
const errorFromProp = getErrorPropertyFromObject(exception);
if (errorFromProp) return [errorFromProp, extras];
const message = getMessageForObject(exception);
const ex = hint?.syntheticException || new Error(message);
ex.message = message;
return [ex, extras];
}
const ex = hint?.syntheticException || new Error(exception);
ex.message = `${exception}`;
return [ex, void 0];
}
/**
* Builds and Event from a Exception
* @hidden
*/
function eventFromUnknownInput(client, stackParser, exception, hint) {
const mechanism = hint?.data && hint.data.mechanism || {
handled: true,
type: "generic"
};
const [ex, extras] = getException(client, mechanism, exception, hint);
const event = { exception: { values: [exceptionFromError(stackParser, ex)] } };
if (extras) event.extra = extras;
require_cacheOrigin.addExceptionTypeValue(event, void 0, void 0);
require_cacheOrigin.addExceptionMechanism(event, mechanism);
return {
...event,
event_id: hint?.event_id
};
}
/**
* Builds and Event from a Message
* @hidden
*/
function eventFromMessage(stackParser, message, level = "info", hint, attachStacktrace) {
const event = {
event_id: hint?.event_id,
level
};
if (attachStacktrace && hint?.syntheticException) {
const frames = parseStackFrames(stackParser, hint.syntheticException);
if (frames.length) {
event.exception = { values: [{
value: message,
stacktrace: { frames }
}] };
require_cacheOrigin.addExceptionMechanism(event, { synthetic: true });
}
}
if (require_cacheOrigin.isParameterizedString(message)) {
const { __sentry_template_string__, __sentry_template_values__ } = message;
event.logentry = {
message: __sentry_template_string__,
params: __sentry_template_values__
};
return event;
}
event.message = message;
return event;
}
// src/vendor/getIpAddress.ts
const ipHeaderNames = [
"X-Client-IP",
"X-Forwarded-For",
"Fly-Client-IP",
"CF-Connecting-IP",
"Fastly-Client-Ip",
"True-Client-Ip",
"X-Real-IP",
"X-Cluster-Client-IP",
"X-Forwarded",
"Forwarded-For",
"Forwarded",
"X-Vercel-Forwarded-For"
];
/**
* Get the IP address of the client sending a request.
*
* It receives a Request headers object and use it to get the
* IP address from one of the following headers in order.
*
* If the IP address is valid, it will be returned. Otherwise, null will be
* returned.
*
* If the header values contains more than one IP address, the first valid one
* will be returned.
*/
function getClientIPAddress$1(headers) {
const lowerCaseHeaders = {};
for (const key of Object.keys(headers)) lowerCaseHeaders[key.toLowerCase()] = headers[key];
return ipHeaderNames.map((headerName) => {
const rawValue = lowerCaseHeaders[headerName.toLowerCase()];
const value = Array.isArray(rawValue) ? rawValue.join(";") : rawValue;
if (headerName === "Forwarded") return parseForwardedHeader(value);
return value?.split(",").map((v) => v.trim());
}).reduce((acc, val) => {
if (!val) return acc;
return acc.concat(val);
}, []).find((ip) => ip !== null && isIP(ip)) || null;
}
function parseForwardedHeader(value) {
if (!value) return null;
for (const part of value.split(";")) if (part.startsWith("for=")) return part.slice(4);
return null;
}
/**
* Custom method instead of importing this from `net` package, as this only exists in node
* Accepts:
* 127.0.0.1
* 192.168.1.1
* 192.168.1.255
* 255.255.255.255
* 10.1.1.1
* 0.0.0.0
* 2b01:cb19:8350:ed00:d0dd:fa5b:de31:8be5
*
* Rejects:
* 1.1.1.01
* 30.168.1.255.1
* 127.1
* 192.168.1.256
* -1.2.3.4
* 1.1.1.1.
* 3...3
* 192.168.1.099
*/
function isIP(str) {
return /(?:^(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}$)|(?:^(?:(?:[a-fA-F\d]{1,4}:){7}(?:[a-fA-F\d]{1,4}|:)|(?:[a-fA-F\d]{1,4}:){6}(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|:[a-fA-F\d]{1,4}|:)|(?:[a-fA-F\d]{1,4}:){5}(?::(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-fA-F\d]{1,4}){1,2}|:)|(?:[a-fA-F\d]{1,4}:){4}(?:(?::[a-fA-F\d]{1,4}){0,1}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-fA-F\d]{1,4}){1,3}|:)|(?:[a-fA-F\d]{1,4}:){3}(?:(?::[a-fA-F\d]{1,4}){0,2}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-fA-F\d]{1,4}){1,4}|:)|(?:[a-fA-F\d]{1,4}:){2}(?:(?::[a-fA-F\d]{1,4}){0,3}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-fA-F\d]{1,4}){1,5}|:)|(?:[a-fA-F\d]{1,4}:){1}(?:(?::[a-fA-F\d]{1,4}){0,4}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-fA-F\d]{1,4}){1,6}|:)|(?::(?:(?::[a-fA-F\d]{1,4}){0,5}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-fA-F\d]{1,4}){1,7}|:)))(?:%[0-9a-zA-Z]{1,})?$)/.test(str);
}
// src/utils/clientIPAddress.ts
const IP_HEADER_NAMES = new Set(ipHeaderNames.map((name) => name.toLowerCase()));
/**
* Get the IP address of the client sending a request, from its forwarding headers.
*
* The vendored implementation accepts only bare addresses, so the header values are
* normalized first. Some proxies (for example Azure App Service) add the client port,
* and RFC 7239 allows a quoted `Forwarded` value and any case for `for=`.
*/
function getClientIPAddress(headers) {
const normalized = {};
for (const [key, value] of Object.entries(headers)) {
const name = key.toLowerCase();
if (value == null || !IP_HEADER_NAMES.has(name)) continue;
const joined = Array.isArray(value) ? value.join(",") : value;
normalized[key] = name === "forwarded" ? normalizeForwardedHeader(joined) : joined.split(",").map((ip) => stripPort(ip.trim())).join(",");
}
return getClientIPAddress$1(normalized);
}
function normalizeForwardedHeader(value) {
const forPair = value.split(/[,;]/).map((part) => part.trim()).find((part) => part.slice(0, 4).toLowerCase() === "for=");
return forPair ? `for=${stripPort(forPair.slice(4).replace(/^"(.*)"$/, "$1"))}` : "";
}
function stripPort(ip) {
return ip.match(/^\[([^\]]+)\](?::\d+)?$/)?.[1] ?? ip.match(/^(\d{1,3}(?:\.\d{1,3}){3}):\d+$/)?.[1] ?? ip;
}
// src/utils/trace-info.ts
/** Extract trace information from scope */
function _getTraceInfoFromScope(client, scope) {
if (!scope) return [void 0, void 0];
return require_cacheOrigin.withScope(scope, () => {
const span = require_cacheOrigin.getActiveSpan();
const traceContext = span ? require_cacheOrigin.spanToTraceContext(span) : require_cacheOrigin.getTraceContextFromScope(scope);
return [span ? require_cacheOrigin.getDynamicSamplingContextFromSpan(span) : require_cacheOrigin.getDynamicSamplingContextFromScope(client, scope), traceContext];
});
}
// src/fetch.ts
/**
* Create and track fetch request spans for usage in combination with `addFetchInstrumentationHandler`.
*
* @returns Span if a span was created, otherwise void.
*/
function instrumentFetchRequest(handlerData, shouldCreateSpan, shouldAttachHeaders, spans, instrumentFetchRequestOptions) {
if (!handlerData.fetchData) return;
const { method, url } = handlerData.fetchData;
const shouldCreateSpanResult = require_cacheOrigin.hasSpansEnabled() && shouldCreateSpan(url);
if (handlerData.endTimestamp) {
const spanId = handlerData.fetchData.__span;
if (!spanId) return;
const span = spans[spanId];
if (span) {
if (shouldCreateSpanResult) {
endSpan(span, handlerData);
_callOnRequestSpanEnd(span, handlerData, instrumentFetchRequestOptions);
}
delete spans[spanId];
}
return;
}
const { spanOrigin = "auto.http.browser", propagateTraceparent = false, urlBase } = instrumentFetchRequestOptions ?? {};
const client = require_cacheOrigin.getClient();
const hasParent = !!require_cacheOrigin.getActiveSpan();
const shouldEmitSpan = hasParent || !!client && require_cacheOrigin.hasSpanStreamingEnabled(client);
const span = shouldCreateSpanResult && shouldEmitSpan ? require_cacheOrigin.startInactiveSpan$1(getSpanStartOptions(url, method, spanOrigin, client, urlBase)) : new require_cacheOrigin.SentryNonRecordingSpan();
const spanForTraceHeaders = require_cacheOrigin.spanIsIgnored(span) && hasParent ? void 0 : span;
if (shouldCreateSpanResult && !shouldEmitSpan) client?.recordDroppedEvent("no_parent_span", "span");
handlerData.fetchData.__span = span.spanContext().spanId;
spans[span.spanContext().spanId] = span;
if (shouldAttachHeaders(handlerData.fetchData.url)) {
const request = handlerData.args[0];
const options = { ...handlerData.args[1] || {} };
const headers = _INTERNAL_getTracingHeadersForFetchRequest(request, options, require_cacheOrigin.hasSpansEnabled() && shouldEmitSpan ? spanForTraceHeaders : void 0, propagateTraceparent);
if (headers) {
handlerData.args[1] = options;
options.headers = headers;
}
}
if (client) {
const fetchHint = {
input: handlerData.args,
response: handlerData.response,
startTimestamp: handlerData.startTimestamp,
endTimestamp: handlerData.endTimestamp
};
client.emit("beforeOutgoingRequestSpan", span, fetchHint);
}
return span;
}
/**
* Calls the onRequestSpanEnd callback if it is defined.
*/
function _callOnRequestSpanEnd(span, handlerData, instrumentFetchRequestOptions) {
instrumentFetchRequestOptions?.onRequestSpanEnd?.(span, {
headers: handlerData.response?.headers,
error: handlerData.error
});
}
/**
* Builds merged fetch headers that include `sentry-trace` and `baggage` (and optionally `traceparent`)
* for the given request and init, without mutating the original request or options.
* Returns `undefined` when there is no `sentry-trace` value to attach.
*
* @internal Exported for cross-package instrumentation (for example Cloudflare Workers fetcher bindings)
* and unit tests
*
* Baggage handling:
* 1. No previous baggage header → include Sentry baggage
* 2. Previous baggage has no Sentry entries → merge Sentry baggage in
* 3. Previous baggage already has Sentry entries → leave as-is (may be user-defined)
*/
function _INTERNAL_getTracingHeadersForFetchRequest(request, fetchOptionsObj, span, propagateTraceparent) {
const traceHeaders = require_cacheOrigin.getTraceData({
span,
propagateTraceparent
});
const sentryTrace = traceHeaders["sentry-trace"];
const baggage = traceHeaders.baggage;
const traceparent = traceHeaders.traceparent;
if (!sentryTrace) return;
const originalHeaders = fetchOptionsObj.headers || (require_cacheOrigin.isRequest(request) ? request.headers : void 0);
if (!originalHeaders) return {
"sentry-trace": sentryTrace,
...baggage && { baggage },
...traceparent && { traceparent }
};
else if (isHeaders(originalHeaders)) {
const newHeaders = new Headers(originalHeaders);
if (!newHeaders.get("sentry-trace")) newHeaders.set("sentry-trace", sentryTrace);
if (propagateTraceparent && traceparent && !newHeaders.get("traceparent")) newHeaders.set("traceparent", traceparent);
if (baggage) {
const prevBaggageHeader = newHeaders.get("baggage");
if (!prevBaggageHeader) newHeaders.set("baggage", baggage);
else if (!baggageHeaderHasSentryBaggageValues(prevBaggageHeader)) newHeaders.set("baggage", `${prevBaggageHeader},${baggage}`);
}
return newHeaders;
} else if (isHeadersInitTupleArray(originalHeaders)) {
const newHeaders = [...originalHeaders];
if (!newHeaders.find((header) => header[0] === "sentry-trace")) newHeaders.push(["sentry-trace", sentryTrace]);
if (propagateTraceparent && traceparent && !newHeaders.find((header) => header[0] === "traceparent")) newHeaders.push(["traceparent", traceparent]);
const prevBaggageHeaderWithSentryValues = originalHeaders.find((header) => header[0] === "baggage" && typeof header[1] === "string" && baggageHeaderHasSentryBaggageValues(header[1]));
if (baggage && !prevBaggageHeaderWithSentryValues) newHeaders.push(["baggage", baggage]);
return newHeaders;
} else {
const existingSentryTraceHeader = "sentry-trace" in originalHeaders ? originalHeaders["sentry-trace"] : void 0;
const existingTraceparentHeader = "traceparent" in originalHeaders ? originalHeaders.traceparent : void 0;
const existingBaggageHeader = "baggage" in originalHeaders ? originalHeaders.baggage : void 0;
const newBaggageHeaders = existingBaggageHeader ? Array.isArray(existingBaggageHeader) ? [...existingBaggageHeader] : [existingBaggageHeader] : [];
const prevBaggageHeaderWithSentryValues = existingBaggageHeader && (Array.isArray(existingBaggageHeader) ? existingBaggageHeader.find((headerItem) => baggageHeaderHasSentryBaggageValues(headerItem)) : baggageHeaderHasSentryBaggageValues(existingBaggageHeader));
if (baggage && !prevBaggageHeaderWithSentryValues) newBaggageHeaders.push(baggage);
const newHeaders = Object.assign({}, originalHeaders, {
"sentry-trace": existingSentryTraceHeader ?? sentryTrace,
...newBaggageHeaders.length > 0 && { baggage: newBaggageHeaders.join(",") }
});
if (propagateTraceparent && traceparent && !existingTraceparentHeader) newHeaders.traceparent = traceparent;
return newHeaders;
}
}
function endSpan(span, handlerData) {
if (handlerData.response) {
require_cacheOrigin.setHttpStatus(span, handlerData.response.status);
const contentLength = handlerData.response?.headers?.get("content-length");
if (contentLength) {
const contentLengthNum = parseInt(contentLength);
if (contentLengthNum > 0) span.setAttribute(_sentry_conventions_attributes.HTTP_RESPONSE_BODY_SIZE, contentLengthNum);
}
} else if (handlerData.error) span.setStatus({
code: 2,
message: "internal_error"
});
span.end();
}
function baggageHeaderHasSentryBaggageValues(baggageHeader) {
if (typeof baggageHeader !== "string") return false;
return baggageHeader.split(",").some((baggageEntry) => baggageEntry.trim().startsWith(require_cacheOrigin.SENTRY_BAGGAGE_KEY_PREFIX));
}
function isHeaders(headers) {
return typeof Headers !== "undefined" && require_cacheOrigin.isInstanceOf(headers, Headers);
}
/** `HeadersInit` array form: each entry is a [name, value] pair of strings. */
function isHeadersInitTupleArray(headers) {
if (!Array.isArray(headers)) return false;
return headers.every((item) => Array.isArray(item) && item.length === 2 && typeof item[0] === "string");
}
function getSpanStartOptions(url, method, spanOrigin, client, urlBase) {
const isStreamed = !!client && require_cacheOrigin.hasSpanStreamingEnabled(client);
const domain = getUrlDomain(url, urlBase);
if (url.startsWith("data:")) {
const sanitizedUrl = stripDataUrlContent(url);
return {
name: isStreamed ? method : `${method} ${sanitizedUrl}`,
attributes: getFetchSpanAttributes(url, void 0, method, spanOrigin, client, domain)
};
}
const parsedUrl = parseStringToURLObject(url);
const sanitizedUrl = parsedUrl ? getSanitizedUrlStringFromUrlObject(parsedUrl) : url;
return {
name: isStreamed ? domain ? `${method} ${domain}` : method : `${method} ${sanitizedUrl}`,
attributes: getFetchSpanAttributes(url, parsedUrl, method, spanOrigin, client, domain)
};
}
function getFetchSpanAttributes(url, parsedUrl, method, spanOrigin, client, domain) {
const attributes = {
[_sentry_conventions_attributes.URL_FULL]: filterCollectedUrl(stripDataUrlContent(url), client),
type: "fetch",
[_sentry_conventions_attributes.HTTP_REQUEST_METHOD]: method,
[_sentry_conventions_attributes.SENTRY_ORIGIN]: spanOrigin,
[_sentry_conventions_attributes.SENTRY_OP]: _sentry_conventions_op.HTTP_CLIENT,
[_sentry_conventions_attributes.URL_DOMAIN]: domain
};
if (parsedUrl) {
if (!isURLObjectRelative(parsedUrl)) {
attributes[_sentry_conventions_attributes.URL_FULL] = filterCollectedUrl(stripDataUrlContent(parsedUrl.href), client);
attributes[_sentry_conventions_attributes.SERVER_ADDRESS] = parsedUrl.hostname;
attributes[_sentry_conventions_attributes.SERVER_PORT] = parsedUrl.port ? Number(parsedUrl.port) : void 0;
}
attributes[_sentry_conventions_attributes.URL_QUERY] = filterCollectedUrlQuery(getUrlQuery(parsedUrl.search), client);
attributes[_sentry_conventions_attributes.URL_FRAGMENT] = getUrlFragment(parsedUrl.hash);
}
return attributes;
}
// src/utils/supports.ts
const WINDOW = require_cacheOrigin.GLOBAL_OBJ;
/**
* Tells whether current environment supports ErrorEvent objects
* {@link supportsErrorEvent}.
*
* @returns Answer to the given question.
*/
function supportsErrorEvent() {
try {
new ErrorEvent("");
return true;
} catch {
return false;
}
}
/**
* Tells whether current environment supports DOMException objects
* {@link supportsDOMException}.
*
* @returns Answer to the given question.
*/
function supportsDOMException() {
try {
new DOMException("");
return true;
} catch {
return false;
}
}
/**
* Tells whether current environment supports Fetch API
* {@link supportsFetch}.
*
* @returns Answer to the given question.
* @deprecated This is no longer used and will be removed in a future major version.
*/
const supportsFetch = _isFetchSupported;
function _isFetchSupported() {
if (!("fetch" in WINDOW)) return false;
try {
new Headers();
new Request("data:,");
new Response();
return true;
} catch {
return false;
}
}
/**
* isNative checks if the given function is a native implementation
*/
function isNativeFunction(func) {
return func && /^function\s+\w+\(\)\s+\{\s+\[native code\]\s+\}$/.test(func.toString());
}
/**
* Tells whether current environment supports Fetch API natively
* {@link supportsNativeFetch}.
*
* @returns true if `window.fetch` is natively implemented, false otherwise
*/
function supportsNativeFetch() {
if (typeof EdgeRuntime === "string") return true;
if (!_isFetchSupported()) return false;
if (isNativeFunction(WINDOW.fetch)) return true;
let result = false;
const doc = WINDOW.document;
if (doc && typeof doc.createElement === "function") try {
const sandbox = doc.createElement("iframe");
sandbox.hidden = true;
doc.head.appendChild(sandbox);
if (sandbox.contentWindow?.fetch) result = isNativeFunction(sandbox.contentWindow.fetch);
doc.head.removeChild(sandbox);
} catch (err) {
require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.warn("Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ", err);
}
return result;
}
/**
* Tells whether current environment supports Referrer Policy API
* {@link supportsReferrerPolicy}.
*
* @returns Answer to the given question.
* @deprecated This is no longer used and will be removed in a future major version.
*/
function supportsReferrerPolicy() {
if (!_isFetchSupported()) return false;
try {
new Request("_", { referrerPolicy: "origin" });
return true;
} catch {
return false;
}
}
// src/instrument/fetch.ts
/**
* Add an instrumentation handler for when a fetch request happens.
* The handler function is called once when the request starts and once when it ends,
* which can be identified by checking if it has an `endTimestamp`.
* Returns a function to remove the handler.
*
* Use at your own risk, this might break without changelog notice, only used internally.
* @hidden
*/
function addFetchInstrumentationHandler(handler) {
const type = "fetch";
const removeHandler = require_cacheOrigin.addHandler(type, handler);
require_cacheOrigin.maybeInstrument(type, () => instrumentFetch());
return removeHandler;
}
/**
* Add an instrumentation handler for long-lived fetch requests, like consuming server-sent events (SSE) via fetch.
* The handler will resolve the request body and emit the actual `endTimestamp`, so that the
* span can be updated accordingly.
* Returns a function to remove the handler.
*
* Only used internally
* @hidden
*/
function addFetchEndInstrumentationHandler(handler) {
const type = "fetch-body-resolved";
const removeHandler = require_cacheOrigin.addHandler(type, handler);
require_cacheOrigin.maybeInstrument(type, () => instrumentFetch(streamHandler));
return removeHandler;
}
function instrumentFetch(onFetchResolved) {
if (require_cacheOrigin.isBrowser() && !supportsNativeFetch()) return;
require_cacheOrigin.fill(require_cacheOrigin.GLOBAL_OBJ, "fetch", function(originalFetch) {
return new Proxy(originalFetch, { apply(target, _thisArg, args) {
const virtualError = /* @__PURE__ */ new Error();
const { method, url } = parseFetchArgs(args);
const handlerData = {
args,
fetchData: {
method,
url
},
startTimestamp: require_cacheOrigin.timestampInSeconds() * 1e3,
virtualError,
headers: getHeadersFromFetchArgs(args)
};
if (!onFetchResolved) require_cacheOrigin.triggerHandlers("fetch", { ...handlerData });
return Reflect.apply(target, require_cacheOrigin.GLOBAL_OBJ, args).then(async (response) => {
if (onFetchResolved) onFetchResolved(response);
else require_cacheOrigin.triggerHandlers("fetch", {
...handlerData,
endTimestamp: require_cacheOrigin.timestampInSeconds() * 1e3,
response
});
return response;
}, (error) => {
require_cacheOrigin.triggerHandlers("fetch", {
...handlerData,
endTimestamp: require_cacheOrigin.timestampInSeconds() * 1e3,
error
});
if (require_cacheOrigin.isError(error) && error.stack === void 0) {
error.stack = virtualError.stack;
require_cacheOrigin.addNonEnumerableProperty(error, "framesToPop", 1);
}
const enhanceOption = require_cacheOrigin.getClient()?.getOptions().enhanceFetchErrorMessages ?? "always";
if (enhanceOption !== false && require_cacheOrigin.isError(error) && error.name === "TypeError" && (error.message === "Failed to fetch" || error.message === "Load failed" || error.message === "NetworkError when attempting to fetch resource.")) try {
const hostname = new URL(handlerData.fetchData.url, require_cacheOrigin.GLOBAL_OBJ.location?.href).host;
if (hostname) {
if (enhanceOption === "always") error.message = `${error.message} (${hostname})`;
else require_cacheOrigin.addNonEnumerableProperty(error, "__sentry_fetch_url_host__", hostname);
}
} catch {}
throw error;
});
} });
});
}
async function resolveResponse(res, onFinishedResolving) {
if (res?.body) {
const body = res.body;
const responseReader = body.getReader();
const maxFetchDurationTimeout = setTimeout(() => {
body.cancel().then(null, () => {});
}, 9e4);
let readingActive = true;
while (readingActive) {
let chunkTimeout;
try {
chunkTimeout = setTimeout(() => {
body.cancel().then(null, () => {});
}, 5e3);
const { done } = await responseReader.read();
clearTimeout(chunkTimeout);
if (done) {
onFinishedResolving();
readingActive = false;
}
} catch {
readingActive = false;
} finally {
clearTimeout(chunkTimeout);
}
}
clearTimeout(maxFetchDurationTimeout);
responseReader.releaseLock();
body.cancel().then(null, () => {});
}
}
function streamHandler(response) {
let clonedResponseForResolving;
try {
clonedResponseForResolving = response.clone();
} catch {
return;
}
resolveResponse(clonedResponseForResolving, () => {
require_cacheOrigin.triggerHandlers("fetch-body-resolved", {
endTimestamp: require_cacheOrigin.timestampInSeconds() * 1e3,
response
});
});
}
function hasProp(obj, prop) {
return require_cacheOrigin.isObjectLike(obj) && !!obj[prop];
}
function getUrlFromResource(resource) {
if (typeof resource === "string") return resource;
if (!resource) return "";
if (hasProp(resource, "url")) return resource.url;
if (resource.toString) return resource.toString();
return "";
}
/**
* Parses the fetch arguments to find the used Http method and the url of the request.
* Exported for tests only.
*/
function parseFetchArgs(fetchArgs) {
if (fetchArgs.length === 0) return {
method: "GET",
url: ""
};
if (fetchArgs.length === 2) {
const [resource, options] = fetchArgs;
return {
url: getUrlFromResource(resource),
method: hasProp(options, "method") ? String(options.method).toUpperCase() : require_cacheOrigin.isRequest(resource) && hasProp(resource, "method") ? String(resource.method).toUpperCase() : "GET"
};
}
const arg = fetchArgs[0];
return {
url: getUrlFromResource(arg),
method: hasProp(arg, "method") ? String(arg.method).toUpperCase() : "GET"
};
}
function getHeadersFromFetchArgs(fetchArgs) {
const [requestArgument, optionsArgument] = fetchArgs;
try {
if (typeof optionsArgument === "object" && optionsArgument !== null && "headers" in optionsArgument && optionsArgument.headers) return new Headers(optionsArgument.headers);
if (require_cacheOrigin.isRequest(requestArgument)) return new Headers(requestArgument.headers);
} catch {}
}
// src/utils/breadcrumb-log-level.ts
/**
* Determine a breadcrumb's log level (only `warning` or `error`) based on an HTTP status code.
*/
function getBreadcrumbLogLevelFromHttpStatusCode(statusCode) {
if (statusCode === void 0) return;
else if (statusCode >= 400 && statusCode < 500) return "warning";
else if (statusCode >= 500) return "error";
else return;
}
// src/utils/lru.ts
/** A simple Least Recently Used map */
var LRUMap = class {
constructor(_maxSize) {
this._maxSize = _maxSize;
this._cache = /* @__PURE__ */ new Map();
}
/** Get the current size of the cache */
get size() {
return this._cache.size;
}
/** Get an entry or undefined if it was not in the cache. Re-inserts to update the recently used order */
get(key) {
const value = this._cache.get(key);
if (value === void 0) return;
this._cache.delete(key);
this._cache.set(key, value);
return value;
}
/** Insert an entry and evict an older entry if we've reached maxSize */
set(key, value) {
this._cache.delete(key);
if (this._cache.size >= this._maxSize) {
const nextKey = this._cache.keys().next().value;
this._cache.delete(nextKey);
}
this._cache.set(key, value);
}
/** Remove an entry and return the entry if it was in the cache */
remove(key) {
const value = this._cache.get(key);
if (value) this._cache.delete(key);
return value;
}
/** Clear all entries */
clear() {
this._cache.clear();
}
/** Get all the keys */
keys() {
return Array.from(this._cache.keys());
}
/** Get all the values */
values() {
const values = [];
this._cache.forEach((value) => values.push(value));
return values;
}
};
// src/integrations/fetch.ts
/**
* Builds an integration that instruments the global `fetch` function: creates `http.client` spans,
* records breadcrumbs, and attaches trace propagation headers.
*
* Runtimes that patch the global `fetch` (Bun, Cloudflare Workers, Deno, Vercel Edge) differ only in
* the integration name and span origin, so they all share this implementation. Node is not one of
* them: it instruments undici through diagnostics channels instead. Neither is the browser, whose
* fetch tracing is driven by `browserTracingIntegration` and shares its span map with XHR.
*/
function createFetchIntegration({ name, spanOrigin }) {
const spans = {};
const configs = /* @__PURE__ */ new WeakMap();
const integration = ((options = {}) => {
return {
name,
setupOnce() {
addFetchInstrumentationHandler((handlerData) => {
const client = require_cacheOrigin.getClient();
const config = client && configs.get(client);
if (!client || !config) return;
if (require_cacheOrigin.isTracingSuppressed() || isSentryRequestUrl(handlerData.fetchData.url, client)) return;
const { propagateTraceparent } = client.getOptions();
instrumentFetchRequest(handlerData, config.shouldCreateSpan, config.shouldAttachTraceData, spans, {
spanOrigin,
propagateTraceparent
});
if (config.breadcrumbs) createBreadcrumb(handlerData, client);
});
},
setup(client) {
configs.set(client, resolveConfig(client, options));
}
};
});
return require_cacheOrigin.defineIntegration(integration);
}
function resolveConfig(client, options) {
const { breadcrumbs = true, shouldCreateSpanForRequest, tracePropagation = true } = options;
const createSpanUrlMap = new LRUMap(100);
const headersUrlMap = new LRUMap(100);
return {
breadcrumbs,
shouldCreateSpan(url) {
if (shouldCreateSpanForRequest === void 0) return true;
const cachedDecision = createSpanUrlMap.get(url);
if (cachedDecision !== void 0) return cachedDecision;
const decision = shouldCreateSpanForRequest(url);
createSpanUrlMap.set(url, decision);
return decision;
},
shouldAttachTraceData(url) {
if (!tracePropagation) return false;
return shouldPropagateTraceForUrl(url, client.getOptions().tracePropagationTargets, headersUrlMap);
}
};
}
function createBreadcrumb(handlerData, client) {
const { startTimestamp, endTimestamp } = handlerData;
if (!endTimestamp) return;
const parsedUrl = parseUrl(handlerData.fetchData.url);
const breadcrumbData = {
method: handlerData.fetchData.method,
url: getSanitizedUrlString(parsedUrl),
[_sentry_conventions_attributes.URL_QUERY]: filterCollectedUrlQuery(getUrlQuery(parsedUrl.search), client),
[_sentry_conventions_attributes.URL_FRAGMENT]: getUrlFragment(parsedUrl.hash)
};
if (handlerData.error) {
const hint = {
data: handlerData.error,
input: handlerData.args,
startTimestamp,
endTimestamp
};
addBreadcrumb({
category: "fetch",
data: breadcrumbData,
level: "error",
type: "http"
}, hint);
} else {
const response = handlerData.response;
breadcrumbData.request_body_size = handlerData.fetchData.request_body_size;
breadcrumbData.response_body_size = handlerData.fetchData.response_body_size;
breadcrumbData.status_code = response?.status;
const hint = {
input: handlerData.args,
response,
startTimestamp,
endTimestamp
};
addBreadcrumb({
category: "fetch",
data: breadcrumbData,
type: "http",
level: getBreadcrumbLogLevelFromHttpStatusCode(breadcrumbData.status_code)
}, hint);
}
}
Object.defineProperty(exports, "BROWSER_NAVIGATION_TIMING_SPAN_NAMES", {
enumerable: true,
get: function() {
return BROWSER_NAVIGATION_TIMING_SPAN_NAMES;
}
});
Object.defineProperty(exports, "CACHE_OPERATION_NAMES", {
enumerable: true,
get: function() {
return CACHE_OPERATION_NAMES;
}
});
Object.defineProperty(exports, "Client", {
enumerable: true,
get: function() {
return Client;
}
});
Object.defineProperty(exports, "DB_SPAN_NAME_FALLBACK", {
enumerable: true,
get: function() {
return DB_SPAN_NAME_FALLBACK;
}
});
Object.defineProperty(exports, "DEFAULT_RETRY_AFTER", {
enumerable: true,
get: function() {
return DEFAULT_RETRY_AFTER;
}
});
Object.defineProperty(exports, "FUNCTION_SPAN_NAME_FALLBACK", {
enumerable: true,
get: function() {
return FUNCTION_SPAN_NAME_FALLBACK;
}
});
Object.defineProperty(exports, "GEN_AI_AGENT_SPAN_NAME_FALLBACK", {
enumerable: true,
get: function() {
return GEN_AI_AGENT_SPAN_NAME_FALLBACK;
}
});
Object.defineProperty(exports, "GEN_AI_INFERENCE_SPAN_NAME_FALLBACK", {
enumerable: true,
get: function() {
return GEN_AI_INFERENCE_SPAN_NAME_FALLBACK;
}
});
Object.defineProperty(exports, "GRAPHQL_SPAN_NAME_FALLBACK", {
enumerable: true,
get: function() {
return GRAPHQL_SPAN_NAME_FALLBACK;
}
});
Object.defineProperty(exports, "HTTP_SPAN_NAME_FALLBACK", {
enumerable: true,
get: function() {
return HTTP_SPAN_NAME_FALLBACK;
}
});
Object.defineProperty(exports, "LRUMap", {
enumerable: true,
get: function() {
return LRUMap;
}
});
Object.defineProperty(exports, "MAX_BODY_BYTE_LENGTH", {
enumerable: true,
get: function() {
return MAX_BODY_BYTE_LENGTH;
}
});
Object.defineProperty(exports, "MCP_NOTIFICATION_SPAN_NAME_FALLBACK", {
enumerable: true,
get: function() {
return MCP_NOTIFICATION_SPAN_NAME_FALLBACK;
}
});
Object.defineProperty(exports, "MCP_SERVER_SPAN_NAME_FALLBACK", {
enumerable: true,
get: function() {
return MCP_SERVER_SPAN_NAME_FALLBACK;
}
});
Object.defineProperty(exports, "MESSAGING_SPAN_NAME_FALLBACK", {
enumerable: true,
get: function() {
return MESSAGING_SPAN_NAME_FALLBACK;
}
});
Object.defineProperty(exports, "NAVIGATION_SPAN_NAME_FALLBACK", {
enumerable: true,
get: function() {
return NAVIGATION_SPAN_NAME_FALLBACK;
}
});
Object.defineProperty(exports, "PAGELOAD_SPAN_NAME_FALLBACK", {
enumerable: true,
get: function() {
return PAGELOAD_SPAN_NAME_FALLBACK;
}
});
Object.defineProperty(exports, "RELEASE_META_TAG_NAME", {
enumerable: true,
get: function() {
return RELEASE_META_TAG_NAME;
}
});
Object.defineProperty(exports, "REQUEST_HANDLER_SPAN_NAME_FALLBACK", {
enumerable: true,
get: function() {
return REQUEST_HANDLER_SPAN_NAME_FALLBACK;
}
});
Object.defineProperty(exports, "RESOURCE_SPAN_NAME_FALLBACK", {
enumerable: true,
get: function() {
return RESOURCE_SPAN_NAME_FALLBACK;
}
});
Object.defineProperty(exports, "ROUTER_SPAN_NAME_FALLBACK", {
enumerable: true,
get: function() {
return ROUTER_SPAN_NAME_FALLBACK;
}
});
Object.defineProperty(exports, "SENTRY_API_VERSION", {
enumerable: true,
get: function() {
return SENTRY_API_VERSION;
}
});
Object.defineProperty(exports, "SENTRY_BUFFER_FULL_ERROR", {
enumerable: true,
get: function() {
return SENTRY_BUFFER_FULL_ERROR;
}
});
Object.defineProperty(exports, "SERVERLESS_FUNCTION_SPAN_NAME_FALLBACK", {
enumerable: true,
get: function() {
return SERVERLESS_FUNCTION_SPAN_NAME_FALLBACK;
}
});
Object.defineProperty(exports, "UI_ACTION_CLICK_SPAN_NAME_FALLBACK", {
enumerable: true,
get: function() {
return UI_ACTION_CLICK_SPAN_NAME_FALLBACK;
}
});
Object.defineProperty(exports, "UI_ACTION_SPAN_NAME_FALLBACK", {
enumerable: true,
get: function() {
return UI_ACTION_SPAN_NAME_FALLBACK;
}
});
Object.defineProperty(exports, "UI_INTERACTION_CLICK_SPAN_NAME_FALLBACK", {
enumerable: true,
get: function() {
return UI_INTERACTION_CLICK_SPAN_NAME_FALLBACK;
}
});
Object.defineProperty(exports, "UI_INTERACTION_DRAG_SPAN_NAME_FALLBACK", {
enumerable: true,
get: function() {
return UI_INTERACTION_DRAG_SPAN_NAME_FALLBACK;
}
});
Object.defineProperty(exports, "UI_INTERACTION_HOVER_SPAN_NAME_FALLBACK", {
enumerable: true,
get: function() {
return UI_INTERACTION_HOVER_SPAN_NAME_FALLBACK;
}
});
Object.defineProperty(exports, "UI_INTERACTION_PRESS_SPAN_NAME_FALLBACK", {
enumerable: true,
get: function() {
return UI_INTERACTION_PRESS_SPAN_NAME_FALLBACK;
}
});
Object.defineProperty(exports, "UI_LONG_TASK_SPAN_NAME_FALLBACK", {
enumerable: true,
get: function() {
return UI_LONG_TASK_SPAN_NAME_FALLBACK;
}
});
Object.defineProperty(exports, "UI_MOUNT_SPAN_NAME_FALLBACK", {
enumerable: true,
get: function() {
return UI_MOUNT_SPAN_NAME_FALLBACK;
}
});
Object.defineProperty(exports, "UI_RENDER_SPAN_NAME_FALLBACK", {
enumerable: true,
get: function() {
return UI_RENDER_SPAN_NAME_FALLBACK;
}
});
Object.defineProperty(exports, "UI_RESOLVE_SPAN_NAME_FALLBACK", {
enumerable: true,
get: function() {
return UI_RESOLVE_SPAN_NAME_FALLBACK;
}
});
Object.defineProperty(exports, "UI_SPAN_NAME_FALLBACK", {
enumerable: true,
get: function() {
return UI_SPAN_NAME_FALLBACK;
}
});
Object.defineProperty(exports, "UI_TASK_SPAN_NAME_FALLBACK", {
enumerable: true,
get: function() {
return UI_TASK_SPAN_NAME_FALLBACK;
}
});
Object.defineProperty(exports, "UI_UNMOUNT_SPAN_NAME_FALLBACK", {
enumerable: true,
get: function() {
return UI_UNMOUNT_SPAN_NAME_FALLBACK;
}
});
Object.defineProperty(exports, "UI_UPDATE_SPAN_NAME_FALLBACK", {
enumerable: true,
get: function() {
return UI_UPDATE_SPAN_NAME_FALLBACK;
}
});
Object.defineProperty(exports, "UI_WEBVITAL_CLS_SPAN_NAME_FALLBACK", {
enumerable: true,
get: function() {
return UI_WEBVITAL_CLS_SPAN_NAME_FALLBACK;
}
});
Object.defineProperty(exports, "UI_WEBVITAL_LCP_SPAN_NAME_FALLBACK", {
enumerable: true,
get: function() {
return UI_WEBVITAL_LCP_SPAN_NAME_FALLBACK;
}
});
Object.defineProperty(exports, "_INTERNAL_getTracingHeadersForFetchRequest", {
enumerable: true,
get: function() {
return _INTERNAL_getTracingHeadersForFetchRequest;
}
});
Object.defineProperty(exports, "_enhanceErrorWithSentryInfo", {
enumerable: true,
get: function() {
return _enhanceErrorWithSentryInfo;
}
});
Object.defineProperty(exports, "_getTraceInfoFromScope", {
enumerable: true,
get: function() {
return _getTraceInfoFromScope;
}
});
Object.defineProperty(exports, "addBreadcrumb", {
enumerable: true,
get: function() {
return addBreadcrumb;
}
});
Object.defineProperty(exports, "addFetchEndInstrumentationHandler", {
enumerable: true,
get: function() {
return addFetchEndInstrumentationHandler;
}
});
Object.defineProperty(exports, "addFetchInstrumentationHandler", {
enumerable: true,
get: function() {
return addFetchInstrumentationHandler;
}
});
Object.defineProperty(exports, "applyBrowserTunnelDefaults", {
enumerable: true,
get: function() {
return applyBrowserTunnelDefaults;
}
});
Object.defineProperty(exports, "captureBodyFromWinterCGRequest", {
enumerable: true,
get: function() {
return captureBodyFromWinterCGRequest;
}
});
Object.defineProperty(exports, "cookiePairsToRecord", {
enumerable: true,
get: function() {
return cookiePairsToRecord;
}
});
Object.defineProperty(exports, "createCheckInEnvelope", {
enumerable: true,
get: function() {
return createCheckInEnvelope;
}
});
Object.defineProperty(exports, "createClientReportEnvelope", {
enumerable: true,
get: function() {
return createClientReportEnvelope;
}
});
Object.defineProperty(exports, "createEventEnvelope", {
enumerable: true,
get: function() {
return createEventEnvelope;
}
});
Object.defineProperty(exports, "createFetchIntegration", {
enumerable: true,
get: function() {
return createFetchIntegration;
}
});
Object.defineProperty(exports, "createSessionEnvelope", {
enumerable: true,
get: function() {
return createSessionEnvelope;
}
});
Object.defineProperty(exports, "createTransport", {
enumerable: true,
get: function() {
return createTransport;
}
});
Object.defineProperty(exports, "disabledUntil", {
enumerable: true,
get: function() {
return disabledUntil;
}
});
Object.defineProperty(exports, "eventFromMessage", {
enumerable: true,
get: function() {
return eventFromMessage;
}
});
Object.defineProperty(exports, "eventFromUnknownInput", {
enumerable: true,
get: function() {
return eventFromUnknownInput;
}
});
Object.defineProperty(exports, "exceptionFromError", {
enumerable: true,
get: function() {
return exceptionFromError;
}
});
Object.defineProperty(exports, "extractQueryParamsFromUrl", {
enumerable: true,
get: function() {
return extractQueryParamsFromUrl;
}
});
Object.defineProperty(exports, "filterCollectedUrl", {
enumerable: true,
get: function() {
return filterCollectedUrl;
}
});
Object.defineProperty(exports, "filterCollectedUrlQuery", {
enumerable: true,
get: function() {
return filterCollectedUrlQuery;
}
});
Object.defineProperty(exports, "filterCookiePairs", {
enumerable: true,
get: function() {
return filterCookiePairs;
}
});
Object.defineProperty(exports, "filterQueryParams", {
enumerable: true,
get: function() {
return filterQueryParams;
}
});
Object.defineProperty(exports, "filterUrlQuery", {
enumerable: true,
get: function() {
return filterUrlQuery;
}
});
Object.defineProperty(exports, "fnv1a32", {
enumerable: true,
get: function() {
return fnv1a32;
}
});
Object.defineProperty(exports, "forwardTunnelRequest", {
enumerable: true,
get: function() {
return forwardTunnelRequest;
}
});
Object.defineProperty(exports, "getBreadcrumbLogLevelFromHttpStatusCode", {
enumerable: true,
get: function() {
return getBreadcrumbLogLevelFromHttpStatusCode;
}
});
Object.defineProperty(exports, "getClientIPAddress", {
enumerable: true,
get: function() {
return getClientIPAddress;
}
});
Object.defineProperty(exports, "getClientTunnel", {
enumerable: true,
get: function() {
return getClientTunnel;
}
});
Object.defineProperty(exports, "getContentLengthFromHeaders", {
enumerable: true,
get: function() {
return getContentLengthFromHeaders;
}
});
Object.defineProperty(exports, "getEnvelopeEndpointWithUrlEncodedAuth", {
enumerable: true,
get: function() {
return getEnvelopeEndpointWithUrlEncodedAuth;
}
});
Object.defineProperty(exports, "getHostFromHeaders", {
enumerable: true,
get: function() {
return getHostFromHeaders;
}
});
Object.defineProperty(exports, "getHttpSpanDetailsFromUrlObject", {
enumerable: true,
get: function() {
return getHttpSpanDetailsFromUrlObject;
}
});
Object.defineProperty(exports, "getMaxBodyByteLength", {
enumerable: true,
get: function() {
return getMaxBodyByteLength;
}
});
Object.defineProperty(exports, "getNodeTunnelHandler", {
enumerable: true,
get: function() {
return getNodeTunnelHandler;
}
});
Object.defineProperty(exports, "getReleaseMetaTag", {
enumerable: true,
get: function() {
return getReleaseMetaTag;
}
});
Object.defineProperty(exports, "getReportDialogEndpoint", {
enumerable: true,
get: function() {
return getReportDialogEndpoint;
}
});
Object.defineProperty(exports, "getSanitizedUrlString", {
enumerable: true,
get: function() {
return getSanitizedUrlString;
}
});
Object.defineProperty(exports, "getSanitizedUrlStringFromUrlObject", {
enumerable: true,
get: function() {
return getSanitizedUrlStringFromUrlObject;
}
});
Object.defineProperty(exports, "getServedTunnel", {
enumerable: true,
get: function() {
return getServedTunnel;
}
});
Object.defineProperty(exports, "getStoredTunnelDefaults", {
enumerable: true,
get: function() {
return getStoredTunnelDefaults;
}
});
Object.defineProperty(exports, "getTraceMetaTags", {
enumerable: true,
get: function() {
return getTraceMetaTags;
}
});
Object.defineProperty(exports, "getTunnelIgnoreSpanFilters", {
enumerable: true,
get: function() {
return getTunnelIgnoreSpanFilters;
}
});
Object.defineProperty(exports, "getTunnelPath", {
enumerable: true,
get: function() {
return getTunnelPath;
}
});
Object.defineProperty(exports, "getTunnelPaths", {
enumerable: true,
get: function() {
return getTunnelPaths;
}
});
Object.defineProperty(exports, "getUrlDomain", {
enumerable: true,
get: function() {
return getUrlDomain;
}
});
Object.defineProperty(exports, "getUrlFragment", {
enumerable: true,
get: function() {
return getUrlFragment;
}
});
Object.defineProperty(exports, "getUrlQuery", {
enumerable: true,
get: function() {
return getUrlQuery;
}
});
Object.defineProperty(exports, "handleServedNodeTunnelRequest", {
enumerable: true,
get: function() {
return handleServedNodeTunnelRequest;
}
});
Object.defineProperty(exports, "handleServedTunnelRequest", {
enumerable: true,
get: function() {
return handleServedTunnelRequest;
}
});
Object.defineProperty(exports, "handleTunnelRequest", {
enumerable: true,
get: function() {
return handleTunnelRequest;
}
});
Object.defineProperty(exports, "handleTunnelRequestIfMatched", {
enumerable: true,
get: function() {
return handleTunnelRequestIfMatched;
}
});
Object.defineProperty(exports, "headersToDict", {
enumerable: true,
get: function() {
return headersToDict;
}
});
Object.defineProperty(exports, "httpHeadersToSpanAttributes", {
enumerable: true,
get: function() {
return httpHeadersToSpanAttributes;
}
});
Object.defineProperty(exports, "httpRequestToRequestData", {
enumerable: true,
get: function() {
return httpRequestToRequestData;
}
});
Object.defineProperty(exports, "httpServerHandlesTunnel", {
enumerable: true,
get: function() {
return httpServerHandlesTunnel;
}
});
Object.defineProperty(exports, "instrumentFetchRequest", {
enumerable: true,
get: function() {
return instrumentFetchRequest;
}
});
Object.defineProperty(exports, "ipHeaderNames", {
enumerable: true,
get: function() {
return ipHeaderNames;
}
});
Object.defineProperty(exports, "isClientClosed", {
enumerable: true,
get: function() {
return isClientClosed;
}
});
Object.defineProperty(exports, "isNativeFunction", {
enumerable: true,
get: function() {
return isNativeFunction;
}
});
Object.defineProperty(exports, "isRateLimited", {
enumerable: true,
get: function() {
return isRateLimited;
}
});
Object.defineProperty(exports, "isSentryRequestUrl", {
enumerable: true,
get: function() {
return isSentryRequestUrl;
}
});
Object.defineProperty(exports, "isServedTunnelRequest", {
enumerable: true,
get: function() {
return isServedTunnelRequest;
}
});
Object.defineProperty(exports, "isTunnelRequest", {
enumerable: true,
get: function() {
return isTunnelRequest;
}
});
Object.defineProperty(exports, "isURLObjectRelative", {
enumerable: true,
get: function() {
return isURLObjectRelative;
}
});
Object.defineProperty(exports, "makePromiseBuffer", {
enumerable: true,
get: function() {
return makePromiseBuffer;
}
});
Object.defineProperty(exports, "matchesTracePropagationTargets", {
enumerable: true,
get: function() {
return matchesTracePropagationTargets;
}
});
Object.defineProperty(exports, "normalizeTunnelBasePath", {
enumerable: true,
get: function() {
return normalizeTunnelBasePath;
}
});
Object.defineProperty(exports, "parseCookieHeader", {
enumerable: true,
get: function() {
return parseCookieHeader;
}
});
Object.defineProperty(exports, "parseRetryAfterHeader", {
enumerable: true,
get: function() {
return parseRetryAfterHeader;
}
});
Object.defineProperty(exports, "parseStackFrames", {
enumerable: true,
get: function() {
return parseStackFrames;
}
});
Object.defineProperty(exports, "parseStringToURLObject", {
enumerable: true,
get: function() {
return parseStringToURLObject;
}
});
Object.defineProperty(exports, "parseUrl", {
enumerable: true,
get: function() {
return parseUrl;
}
});
Object.defineProperty(exports, "pickForwardedHeaders", {
enumerable: true,
get: function() {
return pickForwardedHeaders;
}
});
Object.defineProperty(exports, "setClientTunnel", {
enumerable: true,
get: function() {
return setClientTunnel;
}
});
Object.defineProperty(exports, "setHttpServerHandlesTunnel", {
enumerable: true,
get: function() {
return setHttpServerHandlesTunnel;
}
});
Object.defineProperty(exports, "setNodeTunnelHandler", {
enumerable: true,
get: function() {
return setNodeTunnelHandler;
}
});
Object.defineProperty(exports, "setServedTunnel", {
enumerable: true,
get: function() {
return setServedTunnel;
}
});
Object.defineProperty(exports, "setStoredTunnelDefaults", {
enumerable: true,
get: function() {
return setStoredTunnelDefaults;
}
});
Object.defineProperty(exports, "shouldPropagateTraceForUrl", {
enumerable: true,
get: function() {
return shouldPropagateTraceForUrl;
}
});
Object.defineProperty(exports, "stripDataUrlContent", {
enumerable: true,
get: function() {
return stripDataUrlContent;
}
});
Object.defineProperty(exports, "stripUrlQueryAndFragment", {
enumerable: true,
get: function() {
return stripUrlQueryAndFragment;
}
});
Object.defineProperty(exports, "supportsDOMException", {
enumerable: true,
get: function() {
return supportsDOMException;
}
});
Object.defineProperty(exports, "supportsErrorEvent", {
enumerable: true,
get: function() {
return supportsErrorEvent;
}
});
Object.defineProperty(exports, "supportsFetch", {
enumerable: true,
get: function() {
return supportsFetch;
}
});
Object.defineProperty(exports, "supportsReferrerPolicy", {
enumerable: true,
get: function() {
return supportsReferrerPolicy;
}
});
Object.defineProperty(exports, "updateRateLimits", {
enumerable: true,
get: function() {
return updateRateLimits;
}
});
Object.defineProperty(exports, "winterCGHeadersToDict", {
enumerable: true,
get: function() {
return winterCGHeadersToDict;
}
});
Object.defineProperty(exports, "winterCGRequestToRequestData", {
enumerable: true,
get: function() {
return winterCGRequestToRequestData;
}
});
//# sourceMappingURL=fetch.js.map