UNPKG

@sentry/core

Version:
4,188 lines • 176 kB
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const require_cacheOrigin = require("./chunks/cacheOrigin.js");
const require_fetch = require("./chunks/fetch.js");
let _sentry_conventions_attributes = require("@sentry/conventions/attributes");
let _sentry_conventions_op = require("@sentry/conventions/op");
// src/monitor.ts
/**
* Wraps a callback with a cron monitor check in. The check in will be sent to Sentry when the callback finishes.
*
* @param monitorSlug The distinct slug of the monitor.
* @param callback Callback to be monitored
* @param upsertMonitorConfig An optional object that describes a monitor config. Use this if you want
* to create a monitor automatically when sending a check in.
*/
function withMonitor(monitorSlug, callback, upsertMonitorConfig) {
	function runCallback() {
		const checkInId = captureCheckIn({
			monitorSlug,
			status: "in_progress"
		}, upsertMonitorConfig);
		const now = require_cacheOrigin.timestampInSeconds();
		function finishCheckIn(status) {
			captureCheckIn({
				monitorSlug,
				status,
				checkInId,
				duration: require_cacheOrigin.timestampInSeconds() - now
			});
		}
		let maybePromiseResult;
		try {
			maybePromiseResult = callback();
		} catch (e) {
			finishCheckIn("error");
			throw e;
		}
		if (require_cacheOrigin.isThenable(maybePromiseResult)) return maybePromiseResult.then((r) => {
			finishCheckIn("ok");
			return r;
		}, (e) => {
			finishCheckIn("error");
			throw e;
		});
		finishCheckIn("ok");
		return maybePromiseResult;
	}
	const oldPropagationContext = { ...require_cacheOrigin.getCurrentScope().getPropagationContext() };
	return require_cacheOrigin.withIsolationScope(() => {
		if (upsertMonitorConfig?.isolateTrace) return require_cacheOrigin.startNewTrace(runCallback);
		const scope = require_cacheOrigin.getCurrentScope();
		if (!require_cacheOrigin.isContinuingTrace(scope.getPropagationContext())) scope.setPropagationContext(oldPropagationContext);
		return runCallback();
	});
}
/**
* Create a cron monitor check in and send it to Sentry.
*
* @param checkIn An object that describes a check in.
* @param upsertMonitorConfig An optional object that describes a monitor config. Use this if you want
* to create a monitor automatically when sending a check in.
*/
function captureCheckIn(checkIn, upsertMonitorConfig) {
	const scope = require_cacheOrigin.getCurrentScope();
	const client = require_cacheOrigin.getClient();
	if (!client) require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.warn("Cannot capture check-in. No client defined.");
	else if (!client.captureCheckIn) require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.warn("Cannot capture check-in. Client does not support sending check-ins.");
	else return client.captureCheckIn(checkIn, upsertMonitorConfig, scope);
	return require_cacheOrigin.uuid4();
}
// src/asyncContext/tracing-channel-binding.ts
/**
* Execute a callback whenever the tracing channel binding is available.
* If it is not available after retry, the callback is not executed.
*/
function waitForTracingChannelBinding(callback, retries = 1) {
	if (require_cacheOrigin.getAsyncContextStrategy(require_cacheOrigin.getMainCarrier()).getTracingChannelBinding?.()) {
		callback();
		return;
	}
	if (!retries) return;
	require_cacheOrigin.safeUnref(setTimeout(() => {
		waitForTracingChannelBinding(callback, retries - 1);
	}, 1));
}
// src/sdk.ts
/**
* Internal function to create a new SDK client instance. The client is
* installed and then bound to the current scope.
*
* @param clientClass The client class to instantiate.
* @param options Options to pass to the client.
*/
function initAndBind(clientClass, options) {
	if (options.debug === true) {
		if (require_cacheOrigin.DEBUG_BUILD) require_cacheOrigin.debug.enable();
		else require_cacheOrigin.consoleSandbox(() => {
			console.warn("[Sentry] Cannot initialize SDK with `debug` option using a non-debug bundle.");
		});
	}
	warnIfClientIsActive();
	require_cacheOrigin.getCurrentScope().update(options.initialScope);
	const client = new clientClass(options);
	setCurrentClient(client);
	client.init();
	return client;
}
/**
* Returns the client bound to the current scope, unless it is closed.
*
* @hidden
*/
function getActiveClient() {
	const client = require_cacheOrigin.getClient();
	return client && !require_fetch.isClientClosed(client) ? client : void 0;
}
/**
* Warns when `init()` runs while a client is still bound. The new client
* replaces it, but the old client stays alive, so the two can mix state.
*
* @hidden
*/
function warnIfClientIsActive() {
	if (getActiveClient()) require_cacheOrigin.consoleSandbox(() => {
		console.warn("[Sentry] `Sentry.init()` was called more than once. The new client replaces the active client, but the active client is not closed, so state from both can mix. Call `Sentry.init()` only once, or call `await Sentry.close()` before you call it again.");
	});
}
/**
* Make the given client the current client.
*/
function setCurrentClient(client) {
	require_cacheOrigin.getCurrentScope().setClient(client);
}
const START_DELAY = 5e3;
const MAX_DELAY = 36e5;
/**
* Wraps a transport and stores and retries events when they fail to send.
*
* @param createTransport The transport to wrap.
*/
function makeOfflineTransport(createTransport) {
	function log(...args) {
		require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.log("[Offline]:", ...args);
	}
	return (options) => {
		const transport = createTransport(options);
		if (!options.createStore) throw new Error("No `createStore` function was provided");
		const store = options.createStore(options);
		let retryDelay = START_DELAY;
		let flushTimer;
		function shouldQueue(env, error, retryDelay) {
			if (require_cacheOrigin.envelopeContainsItemType(env, ["client_report"])) return false;
			if (options.shouldStore) return options.shouldStore(env, error, retryDelay);
			return true;
		}
		function flushIn(delay) {
			if (flushTimer) clearTimeout(flushTimer);
			flushTimer = require_cacheOrigin.safeUnref(setTimeout(async () => {
				flushTimer = void 0;
				const found = await store.shift();
				if (found) {
					log("Attempting to send previously queued event");
					found[0].sent_at = new Date(require_cacheOrigin.safeDateNow()).toISOString();
					send(found, true).catch((e) => {
						log("Failed to retry sending", e);
					});
				}
			}, delay));
		}
		function flushWithBackOff() {
			if (flushTimer) return;
			flushIn(retryDelay);
			retryDelay = Math.min(retryDelay * 2, MAX_DELAY);
		}
		async function send(envelope, isRetry = false) {
			if (!isRetry && require_cacheOrigin.envelopeContainsItemType(envelope, ["replay_event", "replay_recording"])) {
				await store.push(envelope);
				flushIn(100);
				return {};
			}
			try {
				if (options.shouldSend) {
					const decision = options.shouldSend(envelope);
					if ((require_cacheOrigin.isThenable(decision) ? await decision : decision) === false) throw new Error("Envelope not sent because `shouldSend` callback returned false");
				}
				const result = await transport.send(envelope);
				let delay = 100;
				if (result) {
					if (result.headers?.["retry-after"]) delay = require_fetch.parseRetryAfterHeader(result.headers["retry-after"]);
					else if (result.headers?.["x-sentry-rate-limits"]) delay = 6e4;
					else if ((result.statusCode || 0) >= 400) return result;
				}
				flushIn(delay);
				retryDelay = START_DELAY;
				return result;
			} catch (e) {
				const decision = shouldQueue(envelope, e, retryDelay);
				if (require_cacheOrigin.isThenable(decision) ? await decision : decision) {
					if (isRetry) await store.unshift(envelope);
					else await store.push(envelope);
					flushWithBackOff();
					log("Error sending. Event queued.", e);
					return {};
				} else throw e;
			}
		}
		if (options.flushAtStartup) flushWithBackOff();
		return {
			send,
			flush: (timeout) => {
				if (timeout === void 0) {
					retryDelay = START_DELAY;
					flushIn(100);
				}
				return transport.flush(timeout);
			}
		};
	};
}
// src/transports/multiplexed.ts
/**
* Key used in event.extra to provide routing information for the multiplexed transport.
* Should contain an array of `{ dsn: string, release?: string }` objects.
*/
const MULTIPLEXED_TRANSPORT_EXTRA_KEY = "MULTIPLEXED_TRANSPORT_EXTRA_KEY";
/**
* Gets an event from an envelope.
*
* This is only exported for use in the tests
*/
function eventFromEnvelope(env, types) {
	let event;
	require_cacheOrigin.forEachEnvelopeItem(env, (item, type) => {
		if (types.includes(type)) event = Array.isArray(item) ? item[1] : void 0;
		return !!event;
	});
	return event;
}
/**
* Creates a transport that overrides the release on all events.
*/
function makeOverrideReleaseTransport(createTransport, release) {
	return (options) => {
		const transport = createTransport(options);
		return {
			...transport,
			send: async (envelope) => {
				const event = eventFromEnvelope(envelope, [
					"event",
					"transaction",
					"profile",
					"replay_event"
				]);
				if (event) event.release = release;
				return transport.send(envelope);
			}
		};
	};
}
/** Overrides the DSN in the envelope header  */
function overrideDsn(envelope, dsn) {
	return require_cacheOrigin.createEnvelope(dsn ? {
		...envelope[0],
		dsn
	} : envelope[0], envelope[1]);
}
/**
* Creates a transport that can send events to different DSNs depending on the envelope contents.
*
* If no matcher is provided, the transport will look for routing information in
* `event.extra[MULTIPLEXED_TRANSPORT_EXTRA_KEY]`, which should contain
* an array of `{ dsn: string, release?: string }` objects.
*/
function makeMultiplexedTransport(createTransport, matcher) {
	return (options) => {
		const fallbackTransport = createTransport(options);
		const otherTransports = /* @__PURE__ */ new Map();
		const actualMatcher = matcher || ((args) => {
			const event = args.getEvent();
			if (event?.extra?.["MULTIPLEXED_TRANSPORT_EXTRA_KEY"] && Array.isArray(event.extra["MULTIPLEXED_TRANSPORT_EXTRA_KEY"])) return event.extra["MULTIPLEXED_TRANSPORT_EXTRA_KEY"];
			return [];
		});
		function getTransport(dsn, release) {
			const key = release ? `${dsn}:${release}` : dsn;
			let transport = otherTransports.get(key);
			if (!transport) {
				const validatedDsn = require_cacheOrigin.dsnFromString(dsn);
				if (!validatedDsn) return;
				const url = require_fetch.getEnvelopeEndpointWithUrlEncodedAuth(validatedDsn, options.tunnel);
				transport = release ? makeOverrideReleaseTransport(createTransport, release)({
					...options,
					url
				}) : createTransport({
					...options,
					url
				});
				otherTransports.set(key, transport);
			}
			return [dsn, transport];
		}
		async function send(envelope) {
			function getEvent(types) {
				return eventFromEnvelope(envelope, types?.length ? types : ["event"]);
			}
			const transports = actualMatcher({
				envelope,
				getEvent
			}).map((result) => {
				if (typeof result === "string") return getTransport(result, void 0);
				else return getTransport(result.dsn, result.release);
			}).filter((t) => !!t);
			const transportsWithFallback = transports.length ? transports : [["", fallbackTransport]];
			return (await Promise.all(transportsWithFallback.map(([dsn, transport]) => transport.send(overrideDsn(envelope, dsn)))))[0];
		}
		async function flush(timeout) {
			const allTransports = [...otherTransports.values(), fallbackTransport];
			return (await Promise.all(allTransports.map((transport) => transport.flush(timeout)))).every((r) => r);
		}
		return {
			send,
			flush
		};
	};
}
// src/utils/ai/providerSkip.ts
/**
* Registry tracking which AI provider modules should skip instrumentation wrapping.
*
* This prevents duplicate spans when a higher-level integration (like LangChain)
* already instruments AI providers at a higher abstraction level.
*/
const SKIPPED_AI_PROVIDERS = /* @__PURE__ */ new Set();
/**
* Mark AI provider modules to skip instrumentation wrapping.
*
* This prevents duplicate spans when a higher-level integration (like LangChain)
* already instruments AI providers at a higher abstraction level.
*
* @internal
* @param modules - Array of npm module names to skip (e.g., '@anthropic-ai/sdk', 'openai')
*
* @example
* ```typescript
* // In LangChain integration
* _INTERNAL_skipAiProviderWrapping(['@anthropic-ai/sdk', 'openai', '@google/generative-ai']);
* ```
*/
function _INTERNAL_skipAiProviderWrapping(modules) {
	modules.forEach((module) => {
		SKIPPED_AI_PROVIDERS.add(module);
		require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.log(`AI provider "${module}" wrapping will be skipped`);
	});
}
/**
* Check if an AI provider module should skip instrumentation wrapping.
*
* @internal
* @param module - The npm module name (e.g., '@anthropic-ai/sdk', 'openai')
* @returns true if wrapping should be skipped
*
* @example
* ```typescript
* // In AI provider instrumentation
* if (_INTERNAL_shouldSkipAiProviderWrapping('@anthropic-ai/sdk')) {
*   return Reflect.construct(Original, args); // Don't instrument
* }
* ```
*/
function _INTERNAL_shouldSkipAiProviderWrapping(module) {
	return SKIPPED_AI_PROVIDERS.has(module);
}
/**
* Clear all AI provider skip registrations.
*
* This is automatically called at the start of Sentry.init() to ensure a clean state
* between different client initializations.
*
* @internal
*/
function _INTERNAL_clearAiProviderSkips() {
	SKIPPED_AI_PROVIDERS.clear();
	require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.log("Cleared AI provider skip registrations");
}
// src/utils/data-collection/filterCookies.ts
/**
* Filters a `Cookie` / `Set-Cookie` header string according to a `CollectBehavior`.
*
* Each named cookie is filtered independently. A nameless cookie (`"opaque-blob"`, `"=opaque-blob"`)
* is reported as `{ '': '[Filtered]' }`, since its token is the value.
*
* @param headerName - `'set-cookie'` keeps only the cookie pair and ignores the attributes (`Path`, `Max-Age`, ...)
*/
function filterCookies(cookieString, behavior, headerName) {
	if (behavior === false) return {};
	const cookies = require_fetch.cookiePairsToRecord(require_fetch.parseCookieHeader(cookieString, headerName));
	return require_cacheOrigin.filterKeyValueData(cookies, behavior, require_cacheOrigin.SENSITIVE_COOKIE_NAME_SNIPPETS);
}
// src/utils/envToBool.ts
const FALSY_ENV_VALUES = /* @__PURE__ */ new Set([
	"false",
	"f",
	"n",
	"no",
	"off",
	"0"
]);
const TRUTHY_ENV_VALUES = /* @__PURE__ */ new Set([
	"true",
	"t",
	"y",
	"yes",
	"on",
	"1"
]);
/**
* A helper function which casts an ENV variable value to `true` or `false` using the constants defined above.
* In strict mode, it may return `null` if the value doesn't match any of the predefined values.
*
* @param value The value of the env variable
* @param options -- Only has `strict` key for now, which requires a strict match for `true` in TRUTHY_ENV_VALUES
* @returns true/false if the lowercase value matches the predefined values above. If not, null in strict mode,
*          and Boolean(value) in loose mode.
*/
function envToBool(value, options) {
	const normalized = String(value).toLowerCase();
	if (FALSY_ENV_VALUES.has(normalized)) return false;
	if (TRUTHY_ENV_VALUES.has(normalized)) return true;
	return options?.strict ? null : Boolean(value);
}
// src/utils/vercel.ts
/**
* Returns the Vercel environment the code is running in, determined by the `VERCEL_TARGET_ENV` environment variable
* with `VERCEL_ENV` as fallback. Returns `undefined` outside of Vercel.
*
* `VERCEL_TARGET_ENV` also carries the name of custom Vercel environments, whereas `VERCEL_ENV` only ever holds
* `production`, `preview` or `development`. SDKs use this as the default `environment` and the bundler plugins use it
* for the deploys they create, so the two stay in sync and deploys show up next to events.
*/
function getVercelEnv() {
	if (typeof process === "undefined") return;
	return process.env.VERCEL_TARGET_ENV || process.env.VERCEL_ENV || void 0;
}
// src/utils/parameterize.ts
/**
* Tagged template function which returns parameterized representation of the message
* For example: parameterize`This is a log statement with ${x} and ${y} params`, would return:
* "__sentry_template_string__": 'This is a log statement with %s and %s params',
* "__sentry_template_values__": ['first', 'second']
*
* @param strings An array of string values splitted between expressions
* @param values Expressions extracted from template string
*
* @returns A `ParameterizedString` object that can be passed into `captureMessage` or Sentry.logger.X methods.
*/
function parameterize(strings, ...values) {
	const cooked = strings.map((str, i) => str ?? strings.raw[i]);
	const formatted = new String(String.raw({ raw: cooked }, ...values));
	formatted.__sentry_template_string__ = cooked.join("\0").replace(/%/g, "%%").replace(/\0/g, "%s");
	formatted.__sentry_template_values__ = values;
	return formatted;
}
/**
* Tagged template function which returns parameterized representation of the message.
*
* @param strings An array of string values splitted between expressions
* @param values Expressions extracted from template string
* @returns A `ParameterizedString` object that can be passed into `captureMessage` or Sentry.logger.X methods.
*/
const fmt = parameterize;
// src/utils/ipAddress.ts
/**
* @internal
*/
function addAutoIpAddressToSession(session) {
	if ("aggregates" in session) {
		if (session.attrs?.["ip_address"] === void 0) session.attrs = {
			...session.attrs,
			ip_address: "{{auto}}"
		};
	} else if (session.ipAddress === void 0) session.ipAddress = "{{auto}}";
}
// src/utils/sdkMetadata.ts
/**
* Preserve user-provided option keys before SDK wrappers add defaults.
* @internal
*/
function captureOptionsSetByUser(options) {
	if (options._metadata?.optionsSetByUser) return options;
	return {
		...options,
		_metadata: {
			...options._metadata,
			optionsSetByUser: Object.keys(options).filter((key) => key !== "_metadata").sort()
		}
	};
}
/**
* A builder for the SDK metadata in the options for the SDK initialization.
*
* Note: This function is identical to `buildMetadata` in Remix and NextJS and SvelteKit.
* We don't extract it for bundle size reasons.
* @see https://github.com/getsentry/sentry-javascript/pull/7404
* @see https://github.com/getsentry/sentry-javascript/pull/4196
*
* If you make changes to this function consider updating the others as well.
*
* @param options SDK options object that gets mutated
* @param names list of package names
*/
function applySdkMetadata(options, name, names = [name], source = "npm") {
	const sdk = (options._metadata = options._metadata || {}).sdk = options._metadata.sdk || {};
	if (!sdk.name) {
		sdk.name = `sentry.javascript.${name}`;
		sdk.packages = names.map((name) => ({
			name: `${source}:@sentry/${name}`,
			version: require_cacheOrigin.SDK_VERSION
		}));
		sdk.version = require_cacheOrigin.SDK_VERSION;
	}
}
// src/utils/serverTiming.ts
/**
* Returns the value of a `Server-Timing` response header that carries the current trace data.
*
* The browser SDK reads it off the document response to continue the trace of the server request in
* the pageload span. Unlike the meta tags of `getTraceMetaTags`, the header reaches the browser before
* any HTML, so the pageload never has to wait for a tag. The value holds up to two entries,
* `sentry-trace` and `baggage`, and is empty without trace data.
*
* @example
* ```js
* response.setHeader('Server-Timing', getTraceServerTimingHeader());
* ```
*/
function getTraceServerTimingHeader(traceData) {
	return Object.entries(traceData || require_cacheOrigin.getTraceData()).filter(([, value]) => value).map(([key, value]) => `${key};desc="${value}"`).join(", ");
}
const CDN_CACHE_CONTROL_HEADERS = [
	"cdn-cache-control",
	"cloudflare-cdn-cache-control",
	"vercel-cdn-cache-control",
	"surrogate-control"
];
/**
* Whether a cache in front of the app may store a response and serve it to other users. Such a
* response must not carry the trace of one request, in a `Server-Timing` header or otherwise, since
* the cache would hand it to every later visitor.
*
* A CDN that reads a targeted field ignores `Cache-Control`; a cache without targeted support reads
* `Cache-Control`. Any of them storing the response is enough.
*
* @param getHeader Reads a response header by its lowercase name.
*/
function isSharedCacheable(getHeader) {
	for (const name of CDN_CACHE_CONTROL_HEADERS) {
		const value = getHeader(name);
		if (value !== void 0 && sharedCachingVerdict(value.toLowerCase()) === true) return true;
	}
	const verdict = sharedCachingVerdict(getHeader("cache-control")?.toLowerCase() ?? "");
	if (verdict !== void 0) return verdict;
	const expires = getHeader("expires");
	return expires !== void 0 && Date.parse(expires) > require_cacheOrigin.safeDateNow();
}
/** Whether these directives let a shared cache reuse the response, or `undefined` when they say nothing. */
function sharedCachingVerdict(directives) {
	if (/\b(?:no-store|private)\b/.test(directives)) return false;
	if (/\b(?:stale-while-revalidate|stale-if-error)\s*=\s*[1-9]/.test(directives)) return true;
	const sharedMaxAge = directives.match(/\bs-maxage\s*=\s*(\d+)/)?.[1];
	if (sharedMaxAge !== void 0) return Number(sharedMaxAge) > 0;
	if (/\bpublic\b/.test(directives)) return true;
	const maxAge = directives.match(/\bmax-age\s*=\s*(\d+)/)?.[1];
	if (maxAge !== void 0) return Number(maxAge) > 0;
}
// src/utils/array.ts
/**
* Return a new array with duplicate values removed, preserving first-occurrence order.
*
* @param input the array to deduplicate
* @returns a new array containing each distinct value once, in the order it first appeared
*/
function uniq(input) {
	return Array.from(new Set(input));
}
// src/spanKind.ts
/**
* Map of otel span kind numbers to span kind names.
*/
const SPAN_KIND_NUMBER_TO_NAME = {
	[0]: void 0,
	[1]: "server",
	[2]: "client",
	[3]: "producer",
	[4]: "consumer"
};
/**
* Resolve the string name of a span kind value (e.g. `1` → `'SERVER'`), mirroring the reverse
* mapping of OpenTelemetry's `SpanKind` enum. Used for the `otel.kind` span attribute, so SDK
* code doesn't need to import `@opentelemetry/api` just for that reverse lookup.
*/
function spanKindToName(kind) {
	return SPAN_KIND_NUMBER_TO_NAME[kind];
}
// src/integrations/functiontostring.ts
const INTEGRATION_NAME$12 = "FunctionToString";
const SETUP_CLIENTS = /* @__PURE__ */ new WeakMap();
const _functionToStringIntegration = (() => {
	return {
		name: INTEGRATION_NAME$12,
		setupOnce() {
			const originalFunctionToString = Function.prototype.toString;
			const callOriginalFunctionToString = Function.prototype.call.bind(originalFunctionToString);
			const hasOwnProperty = Function.prototype.call.bind(Object.prototype.hasOwnProperty);
			try {
				Function.prototype.toString = function() {
					let unwrappedFunction;
					try {
						if (SETUP_CLIENTS.has(require_cacheOrigin.getClient()) && hasOwnProperty(this, "__sentry_original__")) unwrappedFunction = require_cacheOrigin.getOriginalFunction(this);
					} catch {}
					return callOriginalFunctionToString(unwrappedFunction ?? this);
				};
			} catch {}
		},
		setup(client) {
			SETUP_CLIENTS.set(client, true);
		}
	};
});
/**
* Patch toString calls to return proper name for wrapped functions.
*
* ```js
* Sentry.init({
*   integrations: [
*     functionToStringIntegration(),
*   ],
* });
* ```
*/
const functionToStringIntegration = require_cacheOrigin.defineIntegration(_functionToStringIntegration);
// src/integrations/eventFilters.ts
const DEFAULT_IGNORE_ERRORS = [
	/^Script error\.?$/,
	/^Javascript error: Script error\.? on line 0$/,
	/^ResizeObserver loop completed with undelivered notifications.$/,
	/^Cannot redefine property: googletag$/,
	/^Can't find variable: gmo$/,
	/^undefined is not an object \(evaluating 'a\.[A-Z]'\)$/,
	/can't redefine non-configurable property "solana"/,
	/vv\(\)\.getRestrictions is not a function/,
	/Can't find variable: _AutofillCallbackHandler/,
	/Object Not Found Matching Id:\d+, MethodName:simulateEvent/,
	/Java exception was raised during method invocation$/,
	/Java object is gone$/
];
const INTEGRATION_NAME$11 = "EventFilters";
/**
* An integration that filters out events (errors and transactions) based on:
*
* - (Errors) A curated list of known low-value or irrelevant errors (see {@link DEFAULT_IGNORE_ERRORS})
* - (Errors) A list of error messages or urls/filenames passed in via
*   - Top level Sentry.init options (`ignoreErrors`, `denyUrls`, `allowUrls`)
*   - The same options passed to the integration directly via @param options
* - (Transactions/Spans) A list of root span (transaction) names passed in via
*   - Top level Sentry.init option (`ignoreTransactions`)
*   - The same option passed to the integration directly via @param options
*
* Events filtered by this integration will not be sent to Sentry.
*/
const eventFiltersIntegration = require_cacheOrigin.defineIntegration((options = {}) => {
	let mergedOptions;
	return {
		name: INTEGRATION_NAME$11,
		setup(client) {
			mergedOptions = _mergeOptions(options, client.getOptions());
		},
		processEvent(event, _hint, client) {
			if (!mergedOptions) mergedOptions = _mergeOptions(options, client.getOptions());
			return _shouldDropEvent$1(event, mergedOptions) ? null : event;
		}
	};
});
function _mergeOptions(internalOptions = {}, clientOptions = {}) {
	return {
		allowUrls: [...internalOptions.allowUrls || [], ...clientOptions.allowUrls || []],
		denyUrls: [...internalOptions.denyUrls || [], ...clientOptions.denyUrls || []],
		ignoreErrors: [
			...internalOptions.ignoreErrors || [],
			...clientOptions.ignoreErrors || [],
			...internalOptions.disableErrorDefaults ? [] : DEFAULT_IGNORE_ERRORS
		],
		ignoreTransactions: [...internalOptions.ignoreTransactions || [], ...clientOptions.ignoreTransactions || []]
	};
}
function _shouldDropEvent$1(event, options) {
	if (!event.type) {
		if (_isIgnoredError(event, options.ignoreErrors)) {
			require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.warn(`Event dropped due to being matched by \`ignoreErrors\` option.\nEvent: ${require_cacheOrigin.getEventDescription(event)}`);
			return true;
		}
		if (_isUselessError(event)) {
			require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.warn(`Event dropped due to not having an error message, error type or stacktrace.\nEvent: ${require_cacheOrigin.getEventDescription(event)}`);
			return true;
		}
		if (_isDeniedUrl(event, options.denyUrls)) {
			require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.warn(`Event dropped due to being matched by \`denyUrls\` option.\nEvent: ${require_cacheOrigin.getEventDescription(event)}.\nUrl: ${_getEventFilterUrl(event)}`);
			return true;
		}
		if (!_isAllowedUrl(event, options.allowUrls)) {
			require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.warn(`Event dropped due to not being matched by \`allowUrls\` option.\nEvent: ${require_cacheOrigin.getEventDescription(event)}.\nUrl: ${_getEventFilterUrl(event)}`);
			return true;
		}
	} else if (event.type === "transaction") {
		if (_isIgnoredTransaction(event, options.ignoreTransactions)) {
			require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.warn(`Event dropped due to being matched by \`ignoreTransactions\` option.\nEvent: ${require_cacheOrigin.getEventDescription(event)}`);
			return true;
		}
	}
	return false;
}
function _isIgnoredError(event, ignoreErrors) {
	if (!ignoreErrors?.length) return false;
	return require_cacheOrigin.getPossibleEventMessages(event).some((message) => require_cacheOrigin.stringMatchesSomePattern(message, ignoreErrors));
}
function _isIgnoredTransaction(event, ignoreTransactions) {
	if (!ignoreTransactions?.length) return false;
	const name = event.transaction;
	return name ? require_cacheOrigin.stringMatchesSomePattern(name, ignoreTransactions) : false;
}
function _isDeniedUrl(event, denyUrls) {
	if (!denyUrls?.length) return false;
	const url = _getEventFilterUrl(event);
	return !url ? false : require_cacheOrigin.stringMatchesSomePattern(url, denyUrls);
}
function _isAllowedUrl(event, allowUrls) {
	if (!allowUrls?.length) return true;
	const url = _getEventFilterUrl(event);
	return !url ? true : require_cacheOrigin.stringMatchesSomePattern(url, allowUrls);
}
function _getLastValidUrl(frames = []) {
	for (let i = frames.length - 1; i >= 0; i--) {
		const frame = frames[i];
		if (frame && frame.filename !== "<anonymous>" && frame.filename !== "[native code]") return frame.filename || null;
	}
	return null;
}
function _getEventFilterUrl(event) {
	try {
		const frames = [...event.exception?.values ?? []].reverse().find((value) => value.mechanism?.parent_id === void 0 && value.stacktrace?.frames?.length)?.stacktrace?.frames;
		return frames ? _getLastValidUrl(frames) : null;
	} catch {
		require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.error(`Cannot extract url for event ${require_cacheOrigin.getEventDescription(event)}`);
		return null;
	}
}
function _isUselessError(event) {
	if (!event.exception?.values?.length) return false;
	return !event.message && !event.exception.values.some((value) => value.stacktrace || value.type && value.type !== "Error" || value.value);
}
// src/utils/aggregate-errors.ts
/**
* Creates exceptions inside `event.exception.values` for errors that are nested on properties based on the `key` parameter.
*/
function applyAggregateErrorsToEvent(exceptionFromErrorImplementation, parser, key, limit, event, hint) {
	if (!event.exception?.values || !hint || !require_cacheOrigin.isError(hint.originalException)) return;
	const originalException = event.exception.values.length > 0 ? event.exception.values[event.exception.values.length - 1] : void 0;
	if (originalException) event.exception.values = aggregateExceptionsFromError(exceptionFromErrorImplementation, parser, limit, hint.originalException, key, event.exception.values, originalException, 0);
}
function aggregateExceptionsFromError(exceptionFromErrorImplementation, parser, limit, error, key, prevExceptions, exception, exceptionId) {
	if (prevExceptions.length >= limit + 1) return prevExceptions;
	let newExceptions = [...prevExceptions];
	if (require_cacheOrigin.isError(error[key])) {
		applyExceptionGroupFieldsForParentException(exception, exceptionId, error);
		const newException = exceptionFromErrorImplementation(parser, error[key]);
		const newExceptionId = newExceptions.length;
		applyExceptionGroupFieldsForChildException(newException, key, newExceptionId, exceptionId);
		newExceptions = aggregateExceptionsFromError(exceptionFromErrorImplementation, parser, limit, error[key], key, [newException, ...newExceptions], newException, newExceptionId);
	}
	if (isExceptionGroup(error)) error.errors.forEach((childError, i) => {
		if (newExceptions.length < limit + 1 && require_cacheOrigin.isError(childError)) {
			applyExceptionGroupFieldsForParentException(exception, exceptionId, error);
			const newException = exceptionFromErrorImplementation(parser, childError);
			const newExceptionId = newExceptions.length;
			applyExceptionGroupFieldsForChildException(newException, `errors[${i}]`, newExceptionId, exceptionId);
			newExceptions = aggregateExceptionsFromError(exceptionFromErrorImplementation, parser, limit, childError, key, [newException, ...newExceptions], newException, newExceptionId);
		}
	});
	if (isSuppressedError(error)) ["error", "suppressed"].forEach((property) => {
		const childError = error[property];
		if (newExceptions.length < limit + 1 && require_cacheOrigin.isError(childError)) {
			applyExceptionGroupFieldsForParentException(exception, exceptionId, error);
			const newException = exceptionFromErrorImplementation(parser, childError);
			const newExceptionId = newExceptions.length;
			applyExceptionGroupFieldsForChildException(newException, property, newExceptionId, exceptionId);
			newExceptions = aggregateExceptionsFromError(exceptionFromErrorImplementation, parser, limit, childError, key, [newException, ...newExceptions], newException, newExceptionId);
		}
	});
	return newExceptions;
}
function isExceptionGroup(error) {
	return Array.isArray(error.errors);
}
function isSuppressedError(error) {
	return "error" in error && "suppressed" in error;
}
function applyExceptionGroupFieldsForParentException(exception, exceptionId, error) {
	exception.mechanism = {
		handled: true,
		type: "auto.core.linked_errors",
		...isExceptionGroup(error) && { is_exception_group: true },
		...exception.mechanism,
		exception_id: exceptionId
	};
}
function applyExceptionGroupFieldsForChildException(exception, source, exceptionId, parentId) {
	exception.mechanism = {
		handled: true,
		...exception.mechanism,
		type: "chained",
		source,
		exception_id: exceptionId,
		parent_id: parentId
	};
}
// src/integrations/linkederrors.ts
const DEFAULT_KEY = "cause";
const DEFAULT_LIMIT$1 = 5;
const INTEGRATION_NAME$10 = "LinkedErrors";
const _linkedErrorsIntegration = ((options = {}) => {
	const limit = options.limit || DEFAULT_LIMIT$1;
	const key = options.key || DEFAULT_KEY;
	return {
		name: INTEGRATION_NAME$10,
		preprocessEvent(event, hint, client) {
			const options = client.getOptions();
			applyAggregateErrorsToEvent(require_fetch.exceptionFromError, options.stackParser, key, limit, event, hint);
		}
	};
});
const linkedErrorsIntegration = require_cacheOrigin.defineIntegration(_linkedErrorsIntegration);
// src/metadata.ts
/** Keys are source filename/url, values are metadata objects. */
const filenameMetadataMap = /* @__PURE__ */ new Map();
/** Set of stack strings that have already been parsed. */
const parsedStacks = /* @__PURE__ */ new Set();
/**
* Builds a map of filenames to module metadata from the global _sentryModuleMetadata object.
* This is useful for forwarding metadata from web workers to the main thread.
*
* @param parser - Stack parser to use for extracting filenames from stack traces
* @returns A map of filename to metadata object
*/
function getFilenameToMetadataMap(parser) {
	if (!require_cacheOrigin.GLOBAL_OBJ._sentryModuleMetadata) return {};
	const filenameMap = {};
	for (const stack of Object.keys(require_cacheOrigin.GLOBAL_OBJ._sentryModuleMetadata)) {
		const metadata = require_cacheOrigin.GLOBAL_OBJ._sentryModuleMetadata[stack];
		const frames = parser(stack);
		for (const frame of frames.reverse()) if (frame.filename) {
			filenameMap[frame.filename] = metadata;
			break;
		}
	}
	return filenameMap;
}
function ensureMetadataStacksAreParsed(parser) {
	if (!require_cacheOrigin.GLOBAL_OBJ._sentryModuleMetadata) return;
	for (const stack of Object.keys(require_cacheOrigin.GLOBAL_OBJ._sentryModuleMetadata)) {
		const metadata = require_cacheOrigin.GLOBAL_OBJ._sentryModuleMetadata[stack];
		if (parsedStacks.has(stack)) continue;
		parsedStacks.add(stack);
		const frames = parser(stack);
		for (const frame of frames.reverse()) if (frame.filename) {
			filenameMetadataMap.set(frame.filename, metadata);
			break;
		}
	}
}
/**
* Retrieve metadata for a specific JavaScript file URL.
*
* Metadata is injected by the Sentry bundler plugins using the `moduleMetadata` config option.
*/
function getMetadataForUrl(parser, filename) {
	ensureMetadataStacksAreParsed(parser);
	return filenameMetadataMap.get(filename);
}
/**
* Adds metadata to stack frames.
*
* Metadata is injected by the Sentry bundler plugins using the `moduleMetadata` config option.
*/
function addMetadataToStackFrames(parser, event) {
	event.exception?.values?.forEach((exception) => {
		exception.stacktrace?.frames?.forEach((frame) => {
			if (!frame.filename || frame.module_metadata) return;
			const metadata = getMetadataForUrl(parser, frame.filename);
			if (metadata) frame.module_metadata = metadata;
		});
	});
}
/**
* Strips metadata from stack frames.
*/
function stripMetadataFromStackFrames(event) {
	event.exception?.values?.forEach((exception) => {
		exception.stacktrace?.frames?.forEach((frame) => {
			delete frame.module_metadata;
		});
	});
}
// src/integrations/moduleMetadata.ts
/**
* Adds module metadata to stack frames.
*
* Metadata can be injected by the Sentry bundler plugins using the `moduleMetadata` config option.
*
* When this integration is added, the metadata passed to the bundler plugin is added to the stack frames of all events
* under the `module_metadata` property. This can be used to help in tagging or routing of events from different teams
* our sources
*/
const moduleMetadataIntegration = require_cacheOrigin.defineIntegration(() => {
	return {
		name: "ModuleMetadata",
		setup(client) {
			client.on("beforeEnvelope", (envelope) => {
				require_cacheOrigin.forEachEnvelopeItem(envelope, (item, type) => {
					if (type === "event") {
						const event = Array.isArray(item) ? item[1] : void 0;
						if (event) {
							stripMetadataFromStackFrames(event);
							item[1] = event;
						}
					}
				});
			});
			client.on("applyFrameMetadata", (event) => {
				if (event.type) return;
				const stackParser = client.getOptions().stackParser;
				addMetadataToStackFrames(stackParser, event);
			});
		}
	};
});
// src/utils/localhost.ts
const LOCAL_IPS = ["127.0.0.1", "::1"];
const LOCAL_DOMAINS = ["127.0.0.1", "localhost"];
const HOST_HEADERS = ["host", "x-forwarded-host"];
/**
* Whether a request looks like it was served from the developer's own machine.
*
* Ported from Relay's localhost inbound filter so that spans and events are judged by the same rule.
*/
function isLocalhostRequest(request, ipAddress) {
	if (ipAddress && LOCAL_IPS.includes(ipAddress)) return true;
	const url = request?.url ? require_fetch.parseStringToURLObject(request.url) : void 0;
	if (url && !require_fetch.isURLObjectRelative(url)) {
		if (url.protocol === "file:") return true;
		if (LOCAL_DOMAINS.some((domain) => hostMatchesOrIsSubdomainOf(url.hostname, domain))) return true;
	}
	const headers = request?.headers;
	if (headers) for (const [name, value] of Object.entries(headers)) {
		if (!HOST_HEADERS.includes(name.toLowerCase())) continue;
		const host = value?.split(":")[0];
		if (host && LOCAL_DOMAINS.includes(host)) return true;
	}
	return false;
}
function hostMatchesOrIsSubdomainOf(host, domain) {
	return host === domain || host.endsWith(`.${domain}`);
}
// src/integrations/requestdata.ts
const INTEGRATION_NAME$9 = "RequestData";
const _requestDataIntegration = ((options = {}) => {
	function resolveRequestDataOptions(client) {
		const dataCollection = client.getDataCollectionOptions();
		const include = {
			cookies: options.include?.cookies ?? dataCollection.cookies !== false,
			data: options.include?.data ?? true,
			headers: options.include?.headers ?? dataCollection.httpHeaders.request !== false,
			ip: options.include?.ip ?? dataCollection.userInfo,
			query_string: options.include?.query_string ?? dataCollection.urlQueryParams !== false,
			url: options.include?.url ?? true
		};
		return {
			include,
			dataCollection: {
				...dataCollection,
				cookies: resolveFilteringBehavior(include.cookies, dataCollection.cookies),
				httpHeaders: {
					...dataCollection.httpHeaders,
					request: resolveFilteringBehavior(include.headers, dataCollection.httpHeaders.request)
				},
				urlQueryParams: resolveFilteringBehavior(include.query_string, dataCollection.urlQueryParams)
			}
		};
	}
	return {
		name: INTEGRATION_NAME$9,
		processEvent(event, _hint, client) {
			const { sdkProcessingMetadata = {} } = event;
			const { normalizedRequest, ipAddress } = sdkProcessingMetadata;
			if (!normalizedRequest) return event;
			const { include, dataCollection } = resolveRequestDataOptions(client);
			addNormalizedRequestDataToEvent(event, normalizedRequest, { ipAddress }, include, dataCollection);
			return event;
		},
		processSpan(span) {
			const { user, sdkProcessingMetadata } = require_cacheOrigin.getIsolationScope().getScopeData();
			require_cacheOrigin.safeSetSpanJSONAttributes(span, { [_sentry_conventions_attributes.SENTRY_IS_LOCALHOST]: isLocalhostSpan(sdkProcessingMetadata, user.ip_address) });
		},
		processSegmentSpan(span, client) {
			const { sdkProcessingMetadata = {} } = require_cacheOrigin.getIsolationScope().getScopeData();
			const { normalizedRequest, ipAddress } = sdkProcessingMetadata;
			if (!normalizedRequest) return;
			const { include, dataCollection } = resolveRequestDataOptions(client);
			addNormalizedRequestDataToSpan(span, normalizedRequest, ipAddress, include, dataCollection);
		}
	};
});
const localhostByRequest = /* @__PURE__ */ new WeakMap();
/**
* Whether a span belongs to a request served from the developer's own machine.
*
* The client IP is resolved exactly as {@link addNormalizedRequestDataToEvent} resolves the IP it
* writes to `user.ip_address`, so a span and the event for the same request always agree. Crucially
* a forwarding header wins over `ipAddress`, which is the raw socket address: a reverse proxy on the
* same host connects over loopback, so trusting the socket would mark genuine production traffic as
* localhost and let the backend filter silently drop it.
*/
function isLocalhostSpan(sdkProcessingMetadata, scopeUserIpAddress) {
	const { normalizedRequest, ipAddress } = sdkProcessingMetadata;
	if (!normalizedRequest) return isLocalhostRequest(void 0, ipAddress || scopeUserIpAddress);
	const cached = localhostByRequest.get(normalizedRequest);
	if (cached !== void 0) return cached;
	const headers = normalizedRequest.headers;
	const isLocalhost = isLocalhostRequest(normalizedRequest, headers && require_fetch.getClientIPAddress(headers) || ipAddress || scopeUserIpAddress);
	localhostByRequest.set(normalizedRequest, isLocalhost);
	return isLocalhost;
}
/**
* Add data about a request to an event. Primarily for use in Node-based SDKs, but included in `@sentry/core`
* so it can be used in cross-platform SDKs like `@sentry/nextjs`.
*/
const requestDataIntegration = require_cacheOrigin.defineIntegration(_requestDataIntegration);
/**
* Add already normalized request data to an event.
* This mutates the passed in event.
*/
function addNormalizedRequestDataToEvent(event, req, additionalData, include, dataCollection) {
	const requestData = extractNormalizedRequestData(req, include);
	if (requestData.cookies) requestData.cookies = require_cacheOrigin.filterKeyValueData(requestData.cookies, dataCollection.cookies, require_cacheOrigin.SENSITIVE_COOKIE_NAME_SNIPPETS);
	if (requestData.headers) requestData.headers = require_cacheOrigin.filterKeyValueData(requestData.headers, dataCollection.httpHeaders.request);
	if (requestData.query_string) requestData.query_string = normalizeAndFilterQueryString(requestData.query_string, dataCollection.urlQueryParams);
	if (requestData.url) requestData.url = require_fetch.filterUrlQuery(requestData.url, dataCollection.urlQueryParams);
	event.request = {
		...event.request,
		...requestData
	};
	if (include.ip) {
		const ip = req.headers && require_fetch.getClientIPAddress(req.headers) || additionalData.ipAddress;
		if (ip) event.user = {
			...event.user,
			ip_address: ip
		};
	}
}
function addNormalizedRequestDataToSpan(span, normalizedRequest, ipAddress, include, dataCollection) {
	const requestData = extractNormalizedRequestData(normalizedRequest, include);
	const attributes = {};
	if (requestData.url) attributes[_sentry_conventions_attributes.URL_FULL] = require_fetch.filterUrlQuery(requestData.url, dataCollection.urlQueryParams);
	if (requestData.method) attributes[_sentry_conventions_attributes.HTTP_REQUEST_METHOD] = requestData.method;
	if (requestData.query_string) attributes[_sentry_conventions_attributes.URL_QUERY] = normalizeAndFilterQueryString(requestData.query_string, dataCollection.urlQueryParams);
	require_cacheOrigin.safeSetSpanJSONAttributes(span, attributes);
	if (include.cookies) {
		const cookieHeader = normalizedRequest.headers?.cookie;
		const cookiePairs = normalizedRequest.cookies ? Object.entries(normalizedRequest.cookies) : cookieHeader ? require_fetch.parseCookieHeader(cookieHeader, "cookie") : [];
		if (cookiePairs.length > 0) require_cacheOrigin.safeSetSpanJSONAttributes(span, { "http.request.header.cookie": require_fetch.filterCookiePairs(cookiePairs, dataCollection.cookies) });
	}
	if (requestData.headers) {
		const headerAttributes = require_fetch.httpHeadersToSpanAttributes(requestData.headers, dataCollection, "request");
		require_cacheOrigin.safeSetSpanJSONAttributes(span, headerAttributes);
	}
	if (requestData.data != null) {
		const serialized = typeof requestData.data === "string" ? requestData.data : JSON.stringify(requestData.data);
		if (serialized) require_cacheOrigin.safeSetSpanJSONAttributes(span, { [_sentry_conventions_attributes.HTTP_REQUEST_BODY_DATA]: serialized });
	}
	if (include.ip) {
		const ip = normalizedRequest.headers && require_fetch.getClientIPAddress(normalizedRequest.headers) || ipAddress || void 0;
		if (ip) require_cacheOrigin.safeSetSpanJSONAttributes(span, { [_sentry_conventions_attributes.USER_IP_ADDRESS]: ip });
	}
}
function extractNormalizedRequestData(normalizedRequest, include) {
	const requestData = {};
	const headers = { ...normalizedRequest.headers };
	if (include.headers) {
		requestData.headers = headers;
		if (!include.cookies) delete headers.cookie;
		if (!include.ip) {
			const ipHeaderNamesLower = new Set(require_fetch.ipHeaderNames.map((name) => name.toLowerCase()));
			for (const key of Object.keys(headers)) if (ipHeaderNamesLower.has(key.toLowerCase())) delete headers[key];
		}
	}
	requestData.method = normalizedRequest.method;
	if (include.url) requestData.url = normalizedRequest.url;
	if (include.cookies) requestData.cookies = normalizedRequest.cookies || (headers?.cookie ? require_fetch.cookiePairsToRecord(require_fetch.parseCookieHeader(headers.cookie, "cookie")) : void 0) || {};
	if (include.query_string) requestData.query_string = normalizedRequest.query_string;
	if (include.data) requestData.data = normalizedRequest.data;
	return requestData;
}
function resolveFilteringBehavior(isIncluded, behavior) {
	return isIncluded && behavior === false ? true : behavior;
}
function normalizeAndFilterQueryString(queryString, behavior) {
	const normalized = normalizeQueryString(queryString);
	return normalized ? require_fetch.filterQueryParams(normalized, behavior) : void 0;
}
function normalizeQueryString(queryString) {
	if (typeof queryString === "string") return require_fetch.getUrlQuery(queryString);
	const pairs = Array.isArray(queryString) ? queryString : Object.entries(queryString);
	return new URLSearchParams(pairs).toString() || void 0;
}
// src/instrument/console.ts
/**
* Filter out console messages that match the given strings or regular expressions.
* These will neither be passed to the handler, and they will also not be logged to the user, unless they have debug enabled.
* This is a set to avoid duplicate integration setups to add the same filter multiple times.
*/
const _filter = /* @__PURE__ */ new Set([]);
/**
* Add an instrumentation handler for when a console.xxx method is called.
* Returns a function to remove the handler.
*
* Use at your own risk, this might break without changelog notice, only used internally.
* @hidden
*/
function addConsoleInstrumentationHandler(handler) {
	const type = "console";
	const removeHandler = require_cacheOrigin.addHandler(type, handler);
	require_cacheOrigin.maybeInstrument(type, instrumentConsole);
	return removeHandler;
}
/**
* Add a filter to the console instrumentation to filter out console messages that match the given strings or regular expressions.
* Returns a function to remove the filter.
*/
function addConsoleInstrumentationFilter(filter) {
	for (const f of filter) _filter.add(f);
	return () => {
		for (const f of filter) _filter.delete(f);
	};
}
const instrumentedLevels = /* @__PURE__ */ new Set();
/** Only exported for tests. */
function instrumentConsole() {
	if (!("console" in require_cacheOrigin.GLOBAL_OBJ)) return;
	require_cacheOrigin.CONSOLE_LEVELS.forEach(function(level) {
		if (instrumentedLevels.has(level) || !(level in require_cacheOrigin.GLOBAL_OBJ.console)) return;
		instrumentedLevels.add(level);
		require_cacheOrigin.fill(require_cacheOrigin.GLOBAL_OBJ.console, level, function(originalConsoleMethod) {
			require_cacheOrigin.originalConsoleMethods[level] = originalConsoleMethod;
			return function(...args) {
				const firstArg = args[0];
				const log = require_cacheOrigin.originalConsoleMethods[level];
				const isFiltered = _filter.size && typeof firstArg === "string" && require_cacheOrigin.stringMatchesSomePattern(firstArg, _filter);
				if (!isFiltered) require_cacheOrigin.triggerHandlers("console", {
					args,
					level
				});
				if (!isFiltered || require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.isEnabled()) log?.apply(require_cacheOrigin.GLOBAL_OBJ.console, args);
			};
		});
	});
}
// src/utils/severity.ts
/**
* Converts a string-based level into a `SeverityLevel`, normalizing it along the way.
*
* @param level String representation of desired `SeverityLevel`.
* @returns The `SeverityLevel` corresponding to the given string, or 'log' if the string isn't a valid level.
*/
function severityLevelFromString(level) {
	return level === "warn" ? "warning" : [
		"fatal",
		"error",
		"warning",
		"log",
		"info",
		"debug"
	].includes(level) ? level : "log";
}
// src/integrations/captureconsole.ts
const INTEGRATION_NAME$8 = "CaptureConsole";
const _captureConsoleIntegration = ((options = {}) => {
	const levels = options.levels || require_cacheOrigin.CONSOLE_LEVELS;
	const handled = options.handled ?? true;
	return {
		name: INTEGRATION_NAME$8,
		setup(client) {
			if (!("console" in require_cacheOrigin.GLOBAL_OBJ)) return;
			addConsoleInstrumentationHandler(({ args, level }) => {
				if (require_cacheOrigin.getClient() !== client || !levels.includes(level)) return;
				consoleHandler(args, level, handled);
			});
		}
	};
});
/**
* Send Console API calls as Sentry Events.
*/
const captureConsoleIntegration = require_cacheOrigin.defineIntegration(_captureConsoleIntegration);
function consoleHandler(args, level, handled) {
	const severityLevel = severityLevelFromString(level);
	const syntheticException = /* @__PURE__ */ new Error();
	const captureContext = {
		level: severityLevelFromString(level),
		extra: { arguments: args }
	};
	require_cacheOrigin.withScope((scope) => {
		scope.addEventProcessor((event) => {
			event.logger = "console";
			require_cacheOrigin.addExceptionMechanism(event, {
				handled,
				type: "auto.core.capture_console"
			});
			return event;
		});
		if (level === "assert") {
			if (!args[0]) {
				const message = `Assertion failed: ${require_cacheOrigin.safeJoin(args.slice(1), " ") || "console.assert"}`;
				scope.setExtra("arguments", args.slice(1));
				scope.captureMessage(message, severityLevel, {
					captureContext,
					syntheticException
				});
			}
			return;
		}
		const error = args.find((arg) => arg instanceof Error);
		if (error) {
			require_cacheOrigin.captureException(error, captureContext);
			return;
		}
		const message = require_cacheOrigin.safeJoin(args, " ");
		scope.captureMessage(message, severityLevel, {
			captureContext,
			syntheticException
		});
	});
}
// src/integrations/dedupe.ts
const INTEGRATION_NAME$7 = "Dedupe";
const _dedupeIntegration = (() => {
	let previousEvent;
	return {
		name: INTEGRATION_NAME$7,
		processEvent(currentEvent) {
			if (currentEvent.type) return currentEvent;
			try {
				if (_shouldDropEvent(currentEvent, previousEvent)) {
					require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.warn("Event dropped due to being a duplicate of previously captured event.");
					return null;
				}
			} catch {}
			return previousEvent = currentEvent;
		}
	};
});
/**
* Drops an error or message event if it is equal to the previous error or message event.
* Two events are equal if they have the same message (or the same exception type and value),
* the same stack trace and the same fingerprint.
*
* A repeated `captureException` of the same error object is dropped by the client, also without
* this integration (see `checkOrSetAlreadyCaught`).
*/
const dedupeIntegration = require_cacheOrigin.defineIntegration(_dedupeIntegration);
/** only exported for tests. */
function _shouldDropEvent(currentEvent, previousEvent) {
	if (!previousEvent) return false;
	if (_isSameMessageEvent(currentEvent, previousEvent)) return true;
	if (_isSameExceptionEvent(currentEvent, previousEvent)) return true;
	return false;
}
function _isSameMessageEvent(currentEvent, previousEvent) {
	const currentMessage = currentEvent.message;
	const previousMessage = previousEvent.message;
	if (!currentMessage && !previousMessage) return false;
	if (currentMessage && !previousMessage || !currentMessage && previousMessage) return false;
	if (currentMessage !== previousMessage) return false;
	if (!_isSameFingerprint(currentEvent, previousEvent)) return false;
	if (!_isSameStacktrace(currentEvent, previousEvent)) return false;
	return true;
}
function _isSameExceptionEvent(currentEvent, previousEvent) {
	const previousException = _getExceptionFromEvent(previousEvent);
	const currentException = _getExceptionFromEvent(currentEvent);
	if (!previousException || !currentException) return false;
	if (previousException.type !== currentException.type || previousException.value !== currentException.value) return false;
	if (!_isSameFingerprint(currentEvent, previousEvent)) return false;
	if (!_isSameStacktrace(currentEvent, previousEvent)) return false;
	return true;
}
function _isSameStacktrace(currentEvent, previousEvent) {
	const currentFrames = require_cacheOrigin.getFramesFromEvent(currentEvent);
	const previousFrames = require_cacheOrigin.getFramesFromEvent(previousEvent);
	if (!currentFrames || !previousFrames) return !currentFrames && !previousFrames;
	if (previousFrames.length !== currentFrames.length) return false;
	for (let i = 0; i < previousFrames.length; i++) {
		const frameA = previousFrames[i];
		const frameB = currentFrames[i];
		if (frameA.filename !== frameB.filename || frameA.lineno !== frameB.lineno || frameA.colno !== frameB.colno || frameA.function !== frameB.function) return false;
	}
	return true;
}
function _isSameFingerprint(currentEvent, previousEvent) {
	const currentFingerprint = currentEvent.fingerprint;
	const previousFingerprint = previousEvent.fingerprint;
	if (!currentFingerprint || !previousFingerprint) return !currentFingerprint && !previousFingerprint;
	try {
		return !!(currentFingerprint.join("") === previousFingerprint.join(""));
	} catch {
		return false;
	}
}
function _getExceptionFromEvent(event) {
	return event.exception?.values?.[0];
}
// src/integrations/extraerrordata.ts
const INTEGRATION_NAME$6 = "ExtraErrorData";
/**
* Extract additional data for from original exceptions.
*/
const _extraErrorDataIntegration = ((options = {}) => {
	const { depth = 3, captureErrorCause = true } = options;
	return {
		name: INTEGRATION_NAME$6,
		processEvent(event, hint, client) {
			const { maxValueLength } = client.getOptions();
			return _enhanceEventWithErrorData(event, hint, depth, captureErrorCause, maxValueLength);
		}
	};
});
const extraErrorDataIntegration = require_cacheOrigin.defineIntegration(_extraErrorDataIntegration);
function _enhanceEventWithErrorData(event, hint = {}, depth, captureErrorCause, maxValueLength) {
	if (!hint.originalException || !require_cacheOrigin.isError(hint.originalException)) return event;
	const exceptionName = hint.originalException.name || hint.originalException.constructor.name;
	const errorData = _extractErrorData(hint.originalException, captureErrorCause, maxValueLength);
	if (errorData) {
		const contexts = { ...event.contexts };
		const normalizedErrorData = require_cacheOrigin.normalize(errorData, depth);
		if (require_cacheOrigin.isPlainObject(normalizedErrorData)) {
			require_cacheOrigin.setSkipNormalizationHint(normalizedErrorData);
			contexts[exceptionName] = normalizedErrorData;
		}
		return {
			...event,
			contexts
		};
	}
	return event;
}
/**
* Extract extra information from the Error object
*/
function _extractErrorData(error, captureErrorCause, maxValueLength) {
	try {
		const nativeKeys = [
			"name",
			"message",
			"stack",
			"line",
			"column",
			"fileName",
			"lineNumber",
			"columnNumber",
			"toJSON"
		];
		const extraErrorInfo = {};
		for (const key of Object.keys(error)) {
			if (nativeKeys.indexOf(key) !== -1) continue;
			const value = error[key];
			extraErrorInfo[key] = require_cacheOrigin.isError(value) || typeof value === "string" ? maxValueLength ? require_cacheOrigin.truncate(`${value}`, maxValueLength) : `${value}` : value;
		}
		if (captureErrorCause && error.cause !== void 0) {
			if (require_cacheOrigin.isError(error.cause)) extraErrorInfo.cause = { [error.cause.name || error.cause.constructor.name]: _extractErrorData(error.cause, false, maxValueLength) };
			else extraErrorInfo.cause = error.cause;
		}
		if (typeof error.toJSON === "function") {
			const serializedError = error.toJSON();
			for (const key of Object.keys(serializedError)) {
				const value = serializedError[key];
				extraErrorInfo[key] = require_cacheOrigin.isError(value) ? value.toString() : value;
			}
		}
		return extraErrorInfo;
	} catch (oO) {
		require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.error("Unable to extract extra data from the Error object:", oO);
	}
	return null;
}
// src/utils/timestampSequence.ts
let _sequenceNumber = 0;
let _previousTimestampMs;
/**
* Returns the `sentry.timestamp.sequence` attribute entry for a serialized telemetry item.
*
* The sequence number starts at 0 and increments by 1 for each item captured.
* It resets to 0 when the current item's integer millisecond timestamp differs
* from the previous item's integer millisecond timestamp.
*
* @param timestampInSeconds - The timestamp of the telemetry item in seconds.
*/
function getSequenceAttribute(timestampInSeconds) {
	const nowMs = Math.floor(timestampInSeconds * 1e3);
	if (_previousTimestampMs !== void 0 && nowMs !== _previousTimestampMs) _sequenceNumber = 0;
	const value = _sequenceNumber;
	_sequenceNumber++;
	_previousTimestampMs = nowMs;
	return {
		key: _sentry_conventions_attributes.SENTRY_TIMESTAMP_SEQUENCE,
		value: {
			value,
			type: "integer"
		}
	};
}
// src/utils/weightBasedFlushing.ts
const DEFAULT_FLUSH_INTERVAL = 5e3;
/**
* Sets up weight-based flushing for logs or metrics.
* This helper function encapsulates the common pattern of:
* 1. Tracking accumulated weight of items
* 2. Flushing when weight exceeds threshold (800KB)
* 3. Flushing after timeout period from the first item
*
* Uses closure variables to track weight and timeout state.
*/
function setupWeightBasedFlushing(client, afterCaptureHook, flushHook, estimateSizeFn, flushFn) {
	let weight = 0;
	let flushTimeout;
	let isTimerActive = false;
	client.on(flushHook, () => {
		weight = 0;
		clearTimeout(flushTimeout);
		isTimerActive = false;
	});
	client.on(afterCaptureHook, (item) => {
		weight += estimateSizeFn(item);
		if (weight >= 8e5) flushFn(client);
		else if (!isTimerActive) {
			const flushInterval = client.getOptions()._flushInterval ?? DEFAULT_FLUSH_INTERVAL;
			if (flushInterval > 0) {
				isTimerActive = true;
				flushTimeout = require_cacheOrigin.safeUnref(setTimeout(() => {
					flushFn(client);
				}, flushInterval));
			}
		}
	});
	client.on("flush", () => {
		flushFn(client);
	});
}
/**
* Estimate the size of a metric in bytes.
*
* @param metric - The metric to estimate the size of.
* @returns The estimated size of the metric in bytes.
*/
function estimateMetricSizeInBytes(metric) {
	let weight = 0;
	if (metric.name) weight += metric.name.length * 2;
	weight += 8;
	return weight + estimateAttributesSizeInBytes(metric.attributes);
}
/**
* Estimate the size of a log in bytes.
*
* @param log - The log to estimate the size of.
* @returns The estimated size of the log in bytes.
*/
function estimateLogSizeInBytes(log) {
	let weight = 0;
	if (log.message) weight += log.message.length * 2;
	return weight + estimateAttributesSizeInBytes(log.attributes);
}
/**
* Estimate the size of attributes in bytes.
*
* @param attributes - The attributes object to estimate the size of.
* @returns The estimated size of the attributes in bytes.
*/
function estimateAttributesSizeInBytes(attributes) {
	if (!attributes) return 0;
	let weight = 0;
	Object.values(attributes).forEach((value) => {
		if (Array.isArray(value)) weight += value.length * estimatePrimitiveSizeInBytes(value[0]);
		else if (require_cacheOrigin.isPrimitive(value)) weight += estimatePrimitiveSizeInBytes(value);
		else weight += 100;
	});
	return weight;
}
function estimatePrimitiveSizeInBytes(value) {
	if (typeof value === "string") return value.length * 2;
	else if (typeof value === "number") return 8;
	else if (typeof value === "boolean") return 4;
	return 0;
}
// src/metrics/envelope.ts
/**
* Creates a metric container envelope item for a list of metrics.
*
* @param items - The metrics to include in the envelope.
* @param inferUserData - If true, tells Relay to infer the end-user IP and User-Agent from the incoming request.
*                        Only emitted as `ingest_settings` in browser environments.
* @returns The created metric container envelope item.
*/
function createMetricContainerEnvelopeItem(items, inferUserData) {
	const inferSetting = inferUserData ? "auto" : "never";
	return [{
		type: "trace_metric",
		item_count: items.length,
		content_type: "application/vnd.sentry.items.trace-metric+json"
	}, {
		version: 2,
		...require_cacheOrigin.isBrowser() && { ingest_settings: {
			infer_ip: inferSetting,
			infer_user_agent: inferSetting
		} },
		items
	}];
}
/**
* Creates an envelope for a list of metrics.
*
* Metrics from multiple traces can be included in the same envelope.
*
* @param metrics - The metrics to include in the envelope.
* @param metadata - The metadata to include in the envelope.
* @param tunnel - The tunnel to include in the envelope.
* @param dsn - The DSN to include in the envelope.
* @param inferUserData - If true, tells Relay to infer the end-user IP and User-Agent from the incoming request.
* @returns The created envelope.
*/
function createMetricEnvelope(metrics, metadata, tunnel, dsn, inferUserData) {
	const headers = {};
	if (metadata?.sdk) headers.sdk = {
		name: metadata.sdk.name,
		version: metadata.sdk.version
	};
	if (!!tunnel && !!dsn) headers.dsn = require_cacheOrigin.dsnToString(dsn);
	return require_cacheOrigin.createEnvelope(headers, [createMetricContainerEnvelopeItem(metrics, inferUserData)]);
}
// src/metrics/internal.ts
const MAX_METRIC_BUFFER_SIZE = 1e3;
/**
* Sets a metric attribute if the value exists and the attribute key is not already present.
*
* @param metricAttributes - The metric attributes object to modify.
* @param key - The attribute key to set.
* @param value - The value to set (only sets if truthy and key not present).
* @param setEvenIfPresent - Whether to set the attribute if it is present. Defaults to true.
*/
function setMetricAttribute(metricAttributes, key, value, setEvenIfPresent = true) {
	if (value && (setEvenIfPresent || !(key in metricAttributes))) metricAttributes[key] = value;
}
/**
* Captures a serialized metric event and adds it to the metric buffer for the given client.
*
* @param client - A client. Uses the current client if not provided.
* @param serializedMetric - The serialized metric event to capture.
*
* @experimental This method will experience breaking changes. This is not yet part of
* the stable Sentry SDK API and can be changed or removed without warning.
*/
function _INTERNAL_captureSerializedMetric(client, serializedMetric) {
	const bufferMap = _getBufferMap$1();
	const metricBuffer = _INTERNAL_getMetricBuffer(client);
	if (metricBuffer === void 0) {
		setupWeightBasedFlushing(client, "afterCaptureMetric", "flushMetrics", estimateMetricSizeInBytes, _INTERNAL_flushMetricsBuffer);
		bufferMap.set(client, [serializedMetric]);
	} else if (metricBuffer.length >= MAX_METRIC_BUFFER_SIZE) {
		_INTERNAL_flushMetricsBuffer(client, metricBuffer);
		bufferMap.set(client, [serializedMetric]);
	} else bufferMap.set(client, [...metricBuffer, serializedMetric]);
}
/**
* Enriches metric with all contextual attributes (user, SDK metadata, replay, etc.)
*/
function _enrichMetricAttributes(beforeMetric, client, user) {
	const { release, environment } = client.getOptions();
	const processedMetricAttributes = { ...beforeMetric.attributes };
	setMetricAttribute(processedMetricAttributes, _sentry_conventions_attributes.USER_ID, user.id, false);
	setMetricAttribute(processedMetricAttributes, _sentry_conventions_attributes.USER_EMAIL, user.email, false);
	setMetricAttribute(processedMetricAttributes, _sentry_conventions_attributes.USER_NAME, user.username, false);
	setMetricAttribute(processedMetricAttributes, _sentry_conventions_attributes.SENTRY_RELEASE, release);
	setMetricAttribute(processedMetricAttributes, _sentry_conventions_attributes.SENTRY_ENVIRONMENT, environment);
	const { name, version } = client.getSdkMetadata()?.sdk ?? {};
	setMetricAttribute(processedMetricAttributes, _sentry_conventions_attributes.SENTRY_SDK_NAME, name);
	setMetricAttribute(processedMetricAttributes, _sentry_conventions_attributes.SENTRY_SDK_VERSION, version);
	const replay = client.getIntegrationByName("Replay");
	const replayId = replay?.getReplayId(true);
	setMetricAttribute(processedMetricAttributes, _sentry_conventions_attributes.SENTRY_REPLAY_ID, replayId);
	if (replayId && replay?.getRecordingMode() === "buffer") setMetricAttribute(processedMetricAttributes, "sentry._internal.replay_is_buffering", true);
	return {
		...beforeMetric,
		attributes: processedMetricAttributes
	};
}
/**
* Creates a serialized metric ready to be sent to Sentry.
*/
function _buildSerializedMetric(metric, client, currentScope, scopeAttributes) {
	const [, traceContext] = require_fetch._getTraceInfoFromScope(client, currentScope);
	const span = require_cacheOrigin.getActiveSpan(currentScope);
	const traceId = span ? span.spanContext().traceId : traceContext?.trace_id;
	const spanId = span ? span.spanContext().spanId : void 0;
	const timestamp = require_cacheOrigin.timestampInSeconds();
	const sequenceAttr = getSequenceAttribute(timestamp);
	return {
		timestamp,
		trace_id: traceId ?? "",
		span_id: spanId,
		name: metric.name,
		type: metric.type,
		unit: metric.unit,
		value: metric.value,
		attributes: {
			...require_cacheOrigin.serializeAttributes(scopeAttributes),
			...require_cacheOrigin.serializeAttributes(metric.attributes, "skip-undefined"),
			[sequenceAttr.key]: sequenceAttr.value
		}
	};
}
/**
* Captures a metric event and sends it to Sentry.
*
* @param metric - The metric event to capture.
* @param options - Options for capturing the metric.
*
* @experimental This method will experience breaking changes. This is not yet part of
* the stable Sentry SDK API and can be changed or removed without warning.
*/
function _INTERNAL_captureMetric(beforeMetric, options) {
	const currentScope = options?.scope ?? require_cacheOrigin.getCurrentScope();
	const captureSerializedMetric = options?.captureSerializedMetric ?? _INTERNAL_captureSerializedMetric;
	const client = currentScope?.getClient() ?? require_cacheOrigin.getClient();
	if (!client) {
		require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.warn("No client available to capture metric.");
		return;
	}
	const { beforeSendMetric } = client.getOptions();
	const { user, attributes: scopeAttributes } = require_cacheOrigin.getCombinedScopeData(require_cacheOrigin.getIsolationScope(), currentScope);
	const enrichedMetric = _enrichMetricAttributes(beforeMetric, client, user);
	client.emit("processMetric", enrichedMetric);
	const processedMetric = beforeSendMetric ? require_cacheOrigin.safeCallback(require_cacheOrigin.DEBUG_BUILD ? "The `beforeSendMetric` callback threw an error, dropping the metric:" : "", () => beforeSendMetric(enrichedMetric), () => require_cacheOrigin.CALLBACK_ERROR) : enrichedMetric;
	if (processedMetric === require_cacheOrigin.CALLBACK_ERROR) {
		client.recordDroppedEvent("callback_error", "trace_metric", 1);
		return;
	}
	if (!processedMetric) {
		client.recordDroppedEvent("before_send", "trace_metric", 1);
		require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.log("`beforeSendMetric` returned `null`, will not send metric.");
		return;
	}
	const serializedMetric = _buildSerializedMetric(processedMetric, client, currentScope, scopeAttributes);
	require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.log("[Metric]", serializedMetric);
	captureSerializedMetric(client, serializedMetric);
	client.emit("afterCaptureMetric", processedMetric);
}
/**
* Flushes the metrics buffer to Sentry.
*
* @param client - A client.
* @param maybeMetricBuffer - A metric buffer. Uses the metric buffer for the given client if not provided.
*
* @experimental This method will experience breaking changes. This is not yet part of
* the stable Sentry SDK API and can be changed or removed without warning.
*/
function _INTERNAL_flushMetricsBuffer(client, maybeMetricBuffer) {
	const metricBuffer = maybeMetricBuffer ?? _INTERNAL_getMetricBuffer(client) ?? [];
	if (metricBuffer.length === 0) return;
	const clientOptions = client.getOptions();
	const envelope = createMetricEnvelope(metricBuffer, clientOptions._metadata, clientOptions.tunnel, client.getDsn(), client.getDataCollectionOptions().userInfo);
	_getBufferMap$1().set(client, []);
	client.emit("flushMetrics");
	client.sendEnvelope(envelope);
}
/**
* Returns the metric buffer for a given client.
*
* Exported for testing purposes.
*
* @param client - The client to get the metric buffer for.
* @returns The metric buffer for the given client.
*/
function _INTERNAL_getMetricBuffer(client) {
	return _getBufferMap$1().get(client);
}
function _getBufferMap$1() {
	return require_cacheOrigin.getGlobalSingleton("clientToMetricBufferMap", () => /* @__PURE__ */ new WeakMap());
}
// src/metrics/public-api.ts
/**
* Capture a metric with the given type, name, and value.
*
* @param type - The type of the metric.
* @param name - The name of the metric.
* @param value - The value of the metric.
* @param options - Options for capturing the metric.
*/
function captureMetric(type, name, value, options) {
	_INTERNAL_captureMetric({
		type,
		name,
		value,
		unit: options?.unit,
		attributes: options?.attributes
	}, { scope: options?.scope });
}
/**
* @summary Increment a counter metric.
*
* @param name - The name of the counter metric.
* @param value - The value to increment by (defaults to 1).
* @param options - Options for capturing the metric.
*
* @example
*
* ```
* Sentry.metrics.count('api.requests', 1, {
*   attributes: {
*     endpoint: '/api/users',
*     method: 'GET',
*     status: 200
*   }
* });
* ```
*
* @example With custom value
*
* ```
* Sentry.metrics.count('items.processed', 5, {
*   attributes: {
*     processor: 'batch-processor',
*     queue: 'high-priority'
*   }
* });
* ```
*/
function count(name, value = 1, options) {
	captureMetric("counter", name, value, options);
}
/**
* @summary Set a gauge metric to a specific value.
*
* @param name - The name of the gauge metric.
* @param value - The current value of the gauge.
* @param options - Options for capturing the metric.
*
* @example
*
* ```
* Sentry.metrics.gauge('memory.usage', 1024, {
*   unit: 'megabyte',
*   attributes: {
*     process: 'web-server',
*     region: 'us-east-1'
*   }
* });
* ```
*
* @example Without unit
*
* ```
* Sentry.metrics.gauge('active.connections', 42, {
*   attributes: {
*     server: 'api-1',
*     protocol: 'websocket'
*   }
* });
* ```
*/
function gauge(name, value, options) {
	captureMetric("gauge", name, value, options);
}
/**
* @summary Record a value in a distribution metric.
*
* @param name - The name of the distribution metric.
* @param value - The value to record in the distribution.
* @param options - Options for capturing the metric.
*
* @example
*
* ```
* Sentry.metrics.distribution('task.duration', 500, {
*   unit: 'millisecond',
*   attributes: {
*     task: 'data-processing',
*     priority: 'high'
*   }
* });
* ```
*
* @example Without unit
*
* ```
* Sentry.metrics.distribution('batch.size', 100, {
*   attributes: {
*     processor: 'batch-1',
*     type: 'async'
*   }
* });
* ```
*/
function distribution(name, value, options) {
	captureMetric("distribution", name, value, options);
}
/**
* The public metrics API.
*
* A plain object rather than a module namespace so its methods can be spied on in tests.
*/
const metrics = {
	count,
	gauge,
	distribution
};
// src/integrations/reportSdkConfig.ts
const _experimentalReportSdkConfigIntegration = (() => ({
	name: "ExperimentalReportSdkConfig",
	afterAllSetup(client) {
		const scope = new require_cacheOrigin.Scope();
		scope.setClient(client);
		let reported = false;
		const report = () => {
			if (reported) return;
			reported = true;
			clearTimeout(timer);
			try {
				count("sdk.config", 1, {
					attributes: buildConfigAttributes(client),
					scope
				});
			} catch (error) {
				require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.warn("Failed to report SDK configuration", error);
			}
		};
		const timer = require_cacheOrigin.safeUnref(setTimeout(report, 0));
		client.on("flush", () => {
			report();
			_INTERNAL_flushMetricsBuffer(client);
		});
	}
}));
/**
* Reports the SDK options the user passed to `init()` on the next tick after client setup, or on an earlier flush.
*
* @experimental This integration may change or be removed without notice.
*/
const experimentalReportSdkConfigIntegration = require_cacheOrigin.defineIntegration(_experimentalReportSdkConfigIntegration);
function serialize(value, ancestors = /* @__PURE__ */ new Set()) {
	if (typeof value === "function") return `[Function:${require_fetch.fnv1a32(Function.prototype.toString.call(value))}]`;
	if (typeof value === "bigint" || typeof value === "symbol") return `[${typeof value}:${require_fetch.fnv1a32(String(value))}]`;
	if (value === null || typeof value !== "object") return value;
	if (value instanceof RegExp) return value.toString();
	if (ancestors.has(value)) return "[Circular]";
	if (!Array.isArray(value) && !require_cacheOrigin.isPlainObject(value)) return `[${String(Object.prototype.toString.call(value)).slice(8, -1)}:${require_fetch.fnv1a32(String(value))}]`;
	const nextAncestors = new Set(ancestors).add(value);
	if (Array.isArray(value)) return value.map((item) => serialize(item, nextAncestors) ?? null);
	const result = {};
	for (const key of Object.keys(value).sort()) {
		const item = value[key];
		result[key] = item === void 0 ? "[undefined]" : serialize(item, nextAncestors);
	}
	return result;
}
const EXCLUDED_OPTIONS = /* @__PURE__ */ new Set(["integrations", "serverName"]);
function buildConfigAttributes(client) {
	const { sdk, optionsSetByUser = [] } = client.getSdkMetadata() || {};
	const clientOptions = client.getOptions();
	const { release, environment, dist } = clientOptions;
	const runtime = "runtime" in clientOptions ? clientOptions.runtime : void 0;
	const options = Object.fromEntries(Object.entries(clientOptions).filter(([key]) => optionsSetByUser.includes(key) && !EXCLUDED_OPTIONS.has(key)));
	if (Array.isArray(options.defaultIntegrations)) options.defaultIntegrations = options.defaultIntegrations.map((integration) => ({ name: integration.name }));
	const payload = JSON.stringify({
		version: 2,
		sdk: serialize(sdk),
		runtime: serialize(runtime),
		release,
		environment,
		dist,
		integrations: client.getIntegrationNames().map((name) => ({ name })),
		options: serialize(options)
	});
	return {
		"sentry.sdk_config.hash": require_fetch.fnv1a32(payload),
		"sentry.sdk_config.payload": payload
	};
}
// src/utils/path.ts
/** JSDoc */
function normalizeArray(parts, allowAboveRoot) {
	let up = 0;
	for (let i = parts.length - 1; i >= 0; i--) {
		const last = parts[i];
		if (last === ".") parts.splice(i, 1);
		else if (last === "..") {
			parts.splice(i, 1);
			up++;
		} else if (up) {
			parts.splice(i, 1);
			up--;
		}
	}
	if (allowAboveRoot) for (; up--;) parts.unshift("..");
	return parts;
}
const splitPathRe = /^(\S+:\\|\/?)([\s\S]*?)((?:\.{1,2}|[^/\\]+?|)(\.[^./\\]*|))(?:[/\\]*)$/;
/** JSDoc */
function splitPath(filename) {
	const truncated = filename.length > 1024 ? `<truncated>${filename.slice(-1024)}` : filename;
	const parts = splitPathRe.exec(truncated);
	return parts ? parts.slice(1) : [];
}
/** JSDoc */
function resolve(...args) {
	let resolvedPath = "";
	let resolvedAbsolute = false;
	for (let i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) {
		const path = i >= 0 ? args[i] : "/";
		if (!path) continue;
		resolvedPath = `${path}/${resolvedPath}`;
		resolvedAbsolute = path.charAt(0) === "/";
	}
	resolvedPath = normalizeArray(resolvedPath.split("/").filter((p) => !!p), !resolvedAbsolute).join("/");
	return (resolvedAbsolute ? "/" : "") + resolvedPath || ".";
}
/** JSDoc */
function trim(arr) {
	let start = 0;
	for (; start < arr.length; start++) if (arr[start] !== "") break;
	let end = arr.length - 1;
	for (; end >= 0; end--) if (arr[end] !== "") break;
	if (start > end) return [];
	return arr.slice(start, end - start + 1);
}
/** JSDoc */
function relative(from, to) {
	from = resolve(from).slice(1);
	to = resolve(to).slice(1);
	const fromParts = trim(from.split("/"));
	const toParts = trim(to.split("/"));
	const length = Math.min(fromParts.length, toParts.length);
	let samePartsLength = length;
	for (let i = 0; i < length; i++) if (fromParts[i] !== toParts[i]) {
		samePartsLength = i;
		break;
	}
	let outputParts = [];
	for (let i = samePartsLength; i < fromParts.length; i++) outputParts.push("..");
	outputParts = outputParts.concat(toParts.slice(samePartsLength));
	return outputParts.join("/");
}
/** JSDoc */
function normalizePath(path) {
	const isPathAbsolute = isAbsolute(path);
	const trailingSlash = path.slice(-1) === "/";
	let normalizedPath = normalizeArray(path.split("/").filter((p) => !!p), !isPathAbsolute).join("/");
	if (!normalizedPath && !isPathAbsolute) normalizedPath = ".";
	if (normalizedPath && trailingSlash) normalizedPath += "/";
	return (isPathAbsolute ? "/" : "") + normalizedPath;
}
/** JSDoc */
function isAbsolute(path) {
	return path.charAt(0) === "/";
}
/** JSDoc */
function join(...args) {
	return normalizePath(args.join("/"));
}
/** JSDoc */
function dirname(path) {
	const result = splitPath(path);
	const root = result[0] || "";
	let dir = result[1];
	if (!root && !dir) return ".";
	if (dir) dir = dir.slice(0, dir.length - 1);
	return root + dir;
}
/** JSDoc */
function basename(path, ext) {
	let f = splitPath(path)[2] || "";
	if (ext && f.slice(ext.length * -1) === ext) f = f.slice(0, f.length - ext.length);
	return f;
}
// src/integrations/rewriteframes.ts
const INTEGRATION_NAME$5 = "RewriteFrames";
/**
* Rewrite event frames paths.
*/
const rewriteFramesIntegration = require_cacheOrigin.defineIntegration((options = {}) => {
	const root = options.root;
	const prefix = options.prefix || "app:///";
	const isBrowser = "window" in require_cacheOrigin.GLOBAL_OBJ && !!require_cacheOrigin.GLOBAL_OBJ.window;
	const iteratee = options.iteratee || generateIteratee({
		isBrowser,
		root,
		prefix
	});
	/** Process an exception event. */
	function _processExceptionsEvent(event) {
		try {
			return {
				...event,
				exception: {
					...event.exception,
					values: event.exception.values.map((value) => ({
						...value,
						...value.stacktrace && { stacktrace: _processStacktrace(value.stacktrace) }
					}))
				}
			};
		} catch {
			return event;
		}
	}
	/** Process a stack trace. */
	function _processStacktrace(stacktrace) {
		return {
			...stacktrace,
			frames: stacktrace?.frames?.map((f) => iteratee(f))
		};
	}
	return {
		name: INTEGRATION_NAME$5,
		processEvent(originalEvent) {
			let processedEvent = originalEvent;
			if (originalEvent.exception && Array.isArray(originalEvent.exception.values)) processedEvent = _processExceptionsEvent(processedEvent);
			return processedEvent;
		}
	};
});
/**
* Exported only for tests.
*/
function generateIteratee({ isBrowser, root, prefix }) {
	return (frame) => {
		if (!frame.filename) return frame;
		const isWindowsFrame = /^[a-zA-Z]:\\/.test(frame.filename) || frame.filename.includes("\\") && !frame.filename.includes("/");
		const startsWithSlash = /^\//.test(frame.filename);
		if (isBrowser) {
			if (root) {
				const oldFilename = frame.filename;
				if (oldFilename.indexOf(root) === 0) frame.filename = oldFilename.replace(root, prefix);
			}
		} else if (isWindowsFrame || startsWithSlash) {
			const filename = isWindowsFrame ? frame.filename.replace(/^[a-zA-Z]:/, "").replace(/\\/g, "/") : frame.filename;
			frame.filename = `${prefix}${root ? relative(root, filename) : basename(filename)}`;
		}
		return frame;
	};
}
// src/integrations/supabase.ts
const AUTH_OPERATIONS_TO_INSTRUMENT = [
	"reauthenticate",
	"signInAnonymously",
	"signInWithOAuth",
	"signInWithIdToken",
	"signInWithOtp",
	"signInWithPassword",
	"signInWithSSO",
	"signOut",
	"signUp",
	"verifyOtp"
];
const AUTH_ADMIN_OPERATIONS_TO_INSTRUMENT = [
	"createUser",
	"deleteUser",
	"listUsers",
	"getUserById",
	"updateUserById",
	"inviteUserByEmail"
];
const FILTER_MAPPINGS = {
	eq: "eq",
	neq: "neq",
	gt: "gt",
	gte: "gte",
	lt: "lt",
	lte: "lte",
	like: "like",
	"like(all)": "likeAllOf",
	"like(any)": "likeAnyOf",
	ilike: "ilike",
	"ilike(all)": "ilikeAllOf",
	"ilike(any)": "ilikeAnyOf",
	is: "is",
	in: "in",
	cs: "contains",
	cd: "containedBy",
	sr: "rangeGt",
	nxl: "rangeGte",
	sl: "rangeLt",
	nxr: "rangeLte",
	adj: "rangeAdjacent",
	ov: "overlaps",
	fts: "",
	plfts: "plain",
	phfts: "phrase",
	wfts: "websearch",
	not: "not"
};
const DB_OPERATIONS_TO_INSTRUMENT = [
	"select",
	"insert",
	"upsert",
	"update",
	"delete"
];
function markAsInstrumented(fn) {
	try {
		fn.__SENTRY_INSTRUMENTED__ = true;
	} catch {}
}
function isInstrumented(fn) {
	try {
		return fn.__SENTRY_INSTRUMENTED__;
	} catch {
		return false;
	}
}
/**
* Plain-object bodies are copied into `plainBody`; array inserts (and other non-plain shapes) stay only on `rawBody`.
* Returns a payload suitable for span attributes / breadcrumbs when operation data collection is enabled.
*/
function getMutationBodyPayloadForTelemetry(rawBody, plainBody) {
	if (Object.keys(plainBody).length > 0) return plainBody;
	if (Array.isArray(rawBody) && rawBody.length > 0) return rawBody;
}
/** True when the PostgREST builder carries a mutation body (for `insert(...)`, etc. in span descriptions). */
function hasMutationBodyForDescription(rawBody, plainBody) {
	return getMutationBodyPayloadForTelemetry(rawBody, plainBody) !== void 0;
}
/**
* Reads a header off a PostgREST builder, regardless of whether it holds a plain object or a
* `Headers` instance. Lookup is case-insensitive because `Headers` lower-cases all of its keys.
* @param headers - The request headers
* @param name - The header name to look up
* @returns The header value, or `undefined` if it is not set
*/
function getHeader(headers, name) {
	if (!headers) return;
	if (typeof headers.get === "function") return headers.get(name) ?? void 0;
	const plainHeaders = headers;
	const lowerCaseName = name.toLowerCase();
	const key = Object.keys(plainHeaders).find((headerName) => headerName.toLowerCase() === lowerCaseName);
	return key !== void 0 ? plainHeaders[key] : void 0;
}
/**
* Extracts the database operation type from the HTTP method and headers
* @param method - The HTTP method of the request
* @param headers - The request headers
* @returns The database operation type ('select', 'insert', 'upsert', 'update', or 'delete')
*/
function extractOperation(method, headers = {}) {
	switch (method) {
		case "GET":
		case "QUERY": return "select";
		case "POST": if (getHeader(headers, "Prefer")?.includes("resolution=")) return "upsert";
		else return "insert";
		case "PATCH": return "update";
		case "DELETE": return "delete";
		default: return "<unknown-op>";
	}
}
/**
* Translates Supabase filter parameters into readable method names for tracing
* @param key - The filter key from the URL search parameters
* @param query - The filter value from the URL search parameters
* @returns A string representation of the filter as a method call
*/
function translateFiltersIntoMethods(key, query) {
	if (query === "" || query === "*") return "select(*)";
	if (key === "select") return `select(${query})`;
	if (key === "or" || key.endsWith(".or")) return `${key}${query}`;
	const [filter, ...value] = query.split(".");
	let method;
	if (filter?.startsWith("fts")) method = "textSearch";
	else if (filter?.startsWith("plfts")) method = "textSearch[plain]";
	else if (filter?.startsWith("phfts")) method = "textSearch[phrase]";
	else if (filter?.startsWith("wfts")) method = "textSearch[websearch]";
	else method = filter && FILTER_MAPPINGS[filter] || "filter";
	return `${method}(${key}, ${value.join(".")})`;
}
function instrumentAuthOperation(operation, isAdmin = false) {
	return new Proxy(operation, { apply(target, thisArg, argumentsList) {
		const operationName = `auth${isAdmin ? ".admin" : ""}.${operation.name}`;
		const client = require_cacheOrigin.getClient();
		const name = client && require_cacheOrigin.hasSpanStreamingEnabled(client) ? operationName : `auth ${isAdmin ? "(admin) " : ""}${operation.name}`;
		return require_cacheOrigin.startSpanManual$1({
			name,
			onlyIfParent: true,
			attributes: {
				[_sentry_conventions_attributes.SENTRY_ORIGIN]: "auto.db.supabase",
				[_sentry_conventions_attributes.SENTRY_OP]: _sentry_conventions_op.DB,
				[_sentry_conventions_attributes.DB_SYSTEM_NAME]: "postgresql",
				[_sentry_conventions_attributes.DB_OPERATION_NAME]: operationName
			}
		}, (span) => {
			return Reflect.apply(target, thisArg, argumentsList).then((res) => {
				if (require_cacheOrigin.isObjectLike(res) && "error" in res && res.error) {
					span.setStatus({ code: 2 });
					require_cacheOrigin.captureException(res.error, { mechanism: {
						handled: false,
						type: "auto.db.supabase.auth"
					} });
				} else span.setStatus({ code: 1 });
				span.end();
				return res;
			}).catch((err) => {
				span.setStatus({ code: 2 });
				span.end();
				require_cacheOrigin.captureException(err, { mechanism: {
					handled: false,
					type: "auto.db.supabase.auth"
				} });
				throw err;
			}).then(...argumentsList);
		});
	} });
}
function instrumentSupabaseAuthClient(supabaseClientInstance) {
	const auth = supabaseClientInstance.auth;
	if (!auth || isInstrumented(supabaseClientInstance.auth)) return;
	for (const operation of AUTH_OPERATIONS_TO_INSTRUMENT) {
		const authOperation = auth[operation];
		if (!authOperation) continue;
		if (typeof supabaseClientInstance.auth[operation] === "function") supabaseClientInstance.auth[operation] = instrumentAuthOperation(authOperation);
	}
	for (const operation of AUTH_ADMIN_OPERATIONS_TO_INSTRUMENT) {
		const authOperation = auth.admin[operation];
		if (!authOperation) continue;
		if (typeof supabaseClientInstance.auth.admin[operation] === "function") supabaseClientInstance.auth.admin[operation] = instrumentAuthOperation(authOperation, true);
	}
	markAsInstrumented(supabaseClientInstance.auth);
}
function instrumentSupabaseClientConstructor(SupabaseClient, _options) {
	if (isInstrumented(SupabaseClient.prototype.from)) return;
	SupabaseClient.prototype.from = new Proxy(SupabaseClient.prototype.from, { apply(target, thisArg, argumentsList) {
		const rv = Reflect.apply(target, thisArg, argumentsList);
		const PostgRESTQueryBuilder = rv.constructor;
		instrumentPostgRESTQueryBuilder(PostgRESTQueryBuilder, _options);
		return rv;
	} });
	markAsInstrumented(SupabaseClient.prototype.from);
}
function instrumentPostgRESTFilterBuilder(PostgRESTFilterBuilder, _options) {
	if (isInstrumented(PostgRESTFilterBuilder.prototype.then)) return;
	PostgRESTFilterBuilder.prototype.then = new Proxy(PostgRESTFilterBuilder.prototype.then, { apply(target, thisArg, argumentsList) {
		const operations = DB_OPERATIONS_TO_INSTRUMENT;
		const typedThis = thisArg;
		const operation = extractOperation(typedThis.method, typedThis.headers);
		if (!operations.includes(operation)) return Reflect.apply(target, thisArg, argumentsList);
		if (!typedThis?.url?.pathname || typeof typedThis.url.pathname !== "string") return Reflect.apply(target, thisArg, argumentsList);
		const pathParts = typedThis.url.pathname.split("/");
		const table = pathParts.length > 0 ? pathParts[pathParts.length - 1] : "";
		const queryItems = [];
		for (const [key, value] of typedThis.url.searchParams.entries()) queryItems.push(translateFiltersIntoMethods(key, value));
		const body = Object.create(null);
		if (require_cacheOrigin.isPlainObject(typedThis.body)) for (const [key, value] of Object.entries(typedThis.body)) body[key] = value;
		const client = require_cacheOrigin.getClient();
		const shouldSendData = _options.sendOperationData ?? client?.getDataCollectionOptions().databaseQueryData === true;
		const bodyPayload = getMutationBodyPayloadForTelemetry(typedThis.body, body);
		const mutationPart = operation === "select" ? "" : `${operation}${hasMutationBodyForDescription(typedThis.body, body) ? "(...) " : ""}`;
		const queryPart = shouldSendData ? queryItems.join(" ") : queryItems.length > 0 ? "[redacted]" : "";
		const descriptionMiddle = [mutationPart.trimEnd(), queryPart].filter(Boolean).join(" ");
		const description = descriptionMiddle ? `${descriptionMiddle} from(${table})` : `from(${table})`;
		const name = client && require_cacheOrigin.hasSpanStreamingEnabled(client) ? `${operation}${table ? ` ${table}` : ""}` : description;
		const attributes = {
			"db.table": table,
			"db.schema": typedThis.schema,
			"db.url": typedThis.url.origin,
			"db.sdk": getHeader(typedThis.headers, "X-Client-Info"),
			[_sentry_conventions_attributes.DB_SYSTEM_NAME]: "postgresql",
			[_sentry_conventions_attributes.DB_OPERATION_NAME]: operation,
			[_sentry_conventions_attributes.SENTRY_ORIGIN]: "auto.db.supabase",
			[_sentry_conventions_attributes.SENTRY_OP]: _sentry_conventions_op.DB
		};
		if (queryItems.length && shouldSendData) attributes["db.query"] = queryItems;
		if (bodyPayload !== void 0 && shouldSendData) attributes["db.body"] = bodyPayload;
		return require_cacheOrigin.startSpanManual$1({
			name,
			onlyIfParent: true,
			attributes
		}, (span) => {
			return Reflect.apply(target, thisArg, []).then((res) => {
				if (span) {
					if (res && typeof res === "object" && "status" in res) require_cacheOrigin.setHttpStatus(span, res.status || 500);
					span.end();
				}
				if (res?.error) {
					const err = new Error(res.error.message);
					if (res.error.code) err.code = res.error.code;
					if (res.error.details) err.details = res.error.details;
					const supabaseContext = {};
					if (queryItems.length && shouldSendData) supabaseContext.query = queryItems;
					if (bodyPayload !== void 0 && shouldSendData) supabaseContext.body = bodyPayload;
					require_cacheOrigin.captureException(err, (scope) => {
						scope.addEventProcessor((e) => {
							require_cacheOrigin.addExceptionMechanism(e, {
								handled: false,
								type: "auto.db.supabase.postgres"
							});
							return e;
						});
						scope.setContext("supabase", supabaseContext);
						return scope;
					});
				}
				const breadcrumb = {
					type: "supabase",
					category: `db.${operation}`,
					message: description
				};
				const data = {};
				if (queryItems.length && shouldSendData) data.query = queryItems;
				if (bodyPayload !== void 0 && shouldSendData) data.body = bodyPayload;
				if (Object.keys(data).length) breadcrumb.data = data;
				require_fetch.addBreadcrumb(breadcrumb);
				return res;
			}, (err) => {
				if (span) {
					require_cacheOrigin.setHttpStatus(span, 500);
					span.end();
				}
				throw err;
			}).then(...argumentsList);
		});
	} });
	markAsInstrumented(PostgRESTFilterBuilder.prototype.then);
}
function instrumentPostgRESTQueryBuilder(PostgRESTQueryBuilder, _options) {
	for (const operation of DB_OPERATIONS_TO_INSTRUMENT) {
		if (isInstrumented(PostgRESTQueryBuilder.prototype[operation])) continue;
		PostgRESTQueryBuilder.prototype[operation] = new Proxy(PostgRESTQueryBuilder.prototype[operation], { apply(target, thisArg, argumentsList) {
			const rv = Reflect.apply(target, thisArg, argumentsList);
			const PostgRESTFilterBuilder = rv.constructor;
			require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.log(`Instrumenting ${operation} operation's PostgRESTFilterBuilder`);
			instrumentPostgRESTFilterBuilder(PostgRESTFilterBuilder, _options);
			return rv;
		} });
		markAsInstrumented(PostgRESTQueryBuilder.prototype[operation]);
	}
}
const instrumentSupabaseClient = (supabaseClient, options = {}) => {
	if (!supabaseClient) {
		require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.warn("Supabase integration was not installed because no Supabase client was provided.");
		return;
	}
	instrumentSupabaseClientConstructor(supabaseClient.constructor === Function ? supabaseClient : supabaseClient.constructor, options);
	instrumentSupabaseAuthClient(supabaseClient);
};
const INTEGRATION_NAME$4 = "Supabase";
const _supabaseIntegration = ((supabaseClient, options) => {
	return {
		setupOnce() {
			instrumentSupabaseClient(supabaseClient, options);
		},
		name: INTEGRATION_NAME$4
	};
});
const supabaseIntegration = require_cacheOrigin.defineIntegration((options) => {
	return _supabaseIntegration(options.supabaseClient, { sendOperationData: options.sendOperationData });
});
// src/integrations/zoderrors.ts
const DEFAULT_LIMIT = 10;
const INTEGRATION_NAME$3 = "ZodErrors";
function originalExceptionIsZodError(originalException) {
	return require_cacheOrigin.isError(originalException) && (originalException.name === "ZodError" || originalException.name === "$ZodError") && Array.isArray(originalException.issues);
}
/**
* Formats child objects or arrays to a string
* that is preserved when sent to Sentry.
*
* Without this, we end up with something like this in Sentry:
*
* [
*  [Object],
*  [Object],
*  [Object],
*  [Object]
* ]
*/
function flattenIssue(issue) {
	return {
		...issue,
		path: "path" in issue && Array.isArray(issue.path) ? issue.path.join(".") : void 0,
		keys: "keys" in issue ? JSON.stringify(issue.keys) : void 0,
		unionErrors: "unionErrors" in issue ? JSON.stringify(issue.unionErrors) : void 0,
		..."errors" in issue ? { errors: JSON.stringify(issue.errors) } : {}
	};
}
/**
* Takes ZodError issue path array and returns a flattened version as a string.
* This makes it easier to display paths within a Sentry error message.
*
* Array indexes are normalized to reduce duplicate entries
*
* @param path ZodError issue path
* @returns flattened path
*
* @example
* flattenIssuePath([0, 'foo', 1, 'bar']) // -> '<array>.foo.<array>.bar'
*/
function flattenIssuePath(path) {
	return path.map((p) => {
		if (typeof p === "number") return "<array>";
		else return p;
	}).join(".");
}
/**
* Zod error message is a stringified version of ZodError.issues
* This doesn't display well in the Sentry UI. Replace it with something shorter.
*/
function formatIssueMessage(zodError) {
	const errorKeyMap = /* @__PURE__ */ new Set();
	for (const iss of zodError.issues) {
		const issuePath = flattenIssuePath(iss.path);
		if (issuePath.length > 0) errorKeyMap.add(issuePath);
	}
	const errorKeys = Array.from(errorKeyMap);
	if (errorKeys.length === 0) {
		let rootExpectedType = "variable";
		if (zodError.issues.length > 0) {
			const iss = zodError.issues[0];
			if (iss !== void 0 && "expected" in iss && typeof iss.expected === "string") rootExpectedType = iss.expected;
		}
		return `Failed to validate ${rootExpectedType}`;
	}
	return `Failed to validate keys: ${require_cacheOrigin.truncate(errorKeys.join(", "), 100)}`;
}
/**
* Applies ZodError issues to an event extra and replaces the error message
*/
function applyZodErrorsToEvent(limit, saveZodIssuesAsAttachment = false, event, hint) {
	if (!event.exception?.values || !hint.originalException || !originalExceptionIsZodError(hint.originalException) || hint.originalException.issues.length === 0) return event;
	try {
		const flattenedIssues = (saveZodIssuesAsAttachment ? hint.originalException.issues : hint.originalException.issues.slice(0, limit)).map(flattenIssue);
		if (saveZodIssuesAsAttachment) {
			if (!Array.isArray(hint.attachments)) hint.attachments = [];
			hint.attachments.push({
				filename: "zod_issues.json",
				data: JSON.stringify({ issues: flattenedIssues })
			});
		}
		return {
			...event,
			exception: {
				...event.exception,
				values: [{
					...event.exception.values[0],
					value: formatIssueMessage(hint.originalException)
				}, ...event.exception.values.slice(1)]
			},
			extra: {
				...event.extra,
				"zoderror.issues": flattenedIssues.slice(0, limit)
			}
		};
	} catch (e) {
		return {
			...event,
			extra: {
				...event.extra,
				"zoderrors sentry integration parse error": {
					message: "an exception was thrown while processing ZodError within applyZodErrorsToEvent()",
					error: e instanceof Error ? `${e.name}: ${e.message}\n${e.stack}` : "unknown"
				}
			}
		};
	}
}
const _zodErrorsIntegration = ((options = {}) => {
	const limit = options.limit ?? DEFAULT_LIMIT;
	return {
		name: INTEGRATION_NAME$3,
		processEvent(originalEvent, hint) {
			return applyZodErrorsToEvent(limit, options.saveZodIssuesAsAttachment, originalEvent, hint);
		}
	};
});
/**
* Sentry integration to process Zod errors, making them easier to work with in Sentry.
*/
const zodErrorsIntegration = require_cacheOrigin.defineIntegration(_zodErrorsIntegration);
// src/integrations/third-party-errors-filter.ts
/**
* This integration allows you to filter out, or tag error events that do not come from user code marked with a bundle key via the Sentry bundler plugins.
*/
const thirdPartyErrorFilterIntegration = require_cacheOrigin.defineIntegration((options) => {
	const ignoreSentryInternalFrames = options.ignoreSentryInternalFrames ?? false;
	return {
		name: "ThirdPartyErrorsFilter",
		setup(client) {
			client.on("beforeEnvelope", (envelope) => {
				require_cacheOrigin.forEachEnvelopeItem(envelope, (item, type) => {
					if (type === "event") {
						const event = Array.isArray(item) ? item[1] : void 0;
						if (event) {
							stripMetadataFromStackFrames(event);
							item[1] = event;
						}
					}
				});
			});
			client.on("applyFrameMetadata", (event) => {
				if (event.type) return;
				const stackParser = client.getOptions().stackParser;
				addMetadataToStackFrames(stackParser, event);
			});
		},
		preprocessEvent(event) {
			if (ignoreSentryInternalFrames && (require_cacheOrigin.GLOBAL_OBJ._sentryWrappedDepth ?? 0) > 0) event.sdkProcessingMetadata = {
				...event.sdkProcessingMetadata,
				insideSentryWrapped: true
			};
		},
		processEvent(event) {
			const insideSentryWrapped = ignoreSentryInternalFrames ? event.sdkProcessingMetadata?.insideSentryWrapped === true && event.exception?.values?.length === 1 : false;
			const frameKeys = getBundleKeysForAllFramesWithFilenames(event, ignoreSentryInternalFrames, insideSentryWrapped);
			if (frameKeys) {
				if (frameKeys[options.behaviour === "drop-error-if-contains-third-party-frames" || options.behaviour === "apply-tag-if-contains-third-party-frames" ? "some" : "every"]((keys) => !keys.some((key) => options.filterKeys.includes(key)))) {
					if (options.behaviour === "drop-error-if-contains-third-party-frames" || options.behaviour === "drop-error-if-exclusively-contains-third-party-frames") return null;
					else event.tags = {
						...event.tags,
						third_party_code: true
					};
				}
			}
			return event;
		}
	};
});
/** Checks if a frame is Sentry-internal via runtime depth, function name, or source patterns. */
function isSentryInternalFrame(frame, frameIndex, insideSentryWrapped) {
	if (frameIndex !== 0) return false;
	if (insideSentryWrapped && isLikelyMinifiedSentryWrappedFrame(frame)) return true;
	if (frame.function === "sentryWrapped") return true;
	if (!frame.context_line || !frame.filename) return false;
	if (!frame.filename.includes("sentry") || !frame.filename.includes("helpers") || !frame.context_line.includes(SENTRY_INTERNAL_FN_APPLY)) return false;
	if (frame.pre_context) {
		const len = frame.pre_context.length;
		for (let i = 0; i < len; i++) if (frame.pre_context[i]?.includes(SENTRY_INTERNAL_COMMENT)) return true;
	}
	return false;
}
function getBundleKeysForAllFramesWithFilenames(event, ignoreSentryInternalFrames, insideSentryWrapped) {
	const frames = require_cacheOrigin.getFramesFromEvent(event);
	if (!frames) return;
	return frames.filter((frame, index) => {
		if (!frame.filename) return false;
		if (frame.lineno == null && frame.colno == null && frame.instruction_addr == null) return false;
		return !ignoreSentryInternalFrames || !isSentryInternalFrame(frame, index, !!insideSentryWrapped);
	}).map((frame) => {
		if (!frame.module_metadata) return [];
		return Object.keys(frame.module_metadata).filter((key) => key.startsWith(BUNDLER_PLUGIN_APP_KEY_PREFIX)).map((key) => key.slice(BUNDLER_PLUGIN_APP_KEY_PREFIX.length));
	});
}
function isLikelyMinifiedSentryWrappedFrame(frame) {
	return !frame.context_line && !frame.pre_context && !!frame.function && frame.function.length <= 2;
}
const BUNDLER_PLUGIN_APP_KEY_PREFIX = "_sentryBundlerPluginAppKey:";
const SENTRY_INTERNAL_COMMENT = "Attempt to invoke user-land function";
const SENTRY_INTERNAL_FN_APPLY = "fn.apply(this, wrappedArguments)";
// src/integrations/console.ts
const INTEGRATION_NAME$2 = "Console";
/**
* Captures calls to the `console` API as breadcrumbs in Sentry.
*
* By default the integration instruments `console.debug`, `console.info`, `console.warn`, `console.error`,
* `console.log`, `console.trace`, and `console.assert`. You can use the `levels` option to customize which
* levels are captured.
*
* @example
*
* ```js
* Sentry.init({
*   integrations: [Sentry.consoleIntegration({ levels: ['error', 'warn'] })],
* });
* ```
*/
const consoleIntegration = require_cacheOrigin.defineIntegration((options = {}) => {
	const levels = new Set(options.levels || require_cacheOrigin.CONSOLE_LEVELS);
	return {
		name: INTEGRATION_NAME$2,
		setup(client) {
			const unsubscribe = addConsoleInstrumentationHandler(({ args, level }) => {
				if (require_cacheOrigin.getClient() !== client || !levels.has(level)) return;
				addConsoleBreadcrumb(level, args);
			});
			client.registerCleanup(unsubscribe);
			if (options.filter) {
				const unsubscribe = addConsoleInstrumentationFilter(options.filter);
				client.registerCleanup(unsubscribe);
			}
		}
	};
});
/**
* Capture a console breadcrumb.
*
* Exported just for tests.
*/
function addConsoleBreadcrumb(level, args) {
	const breadcrumb = {
		category: "console",
		data: {
			arguments: args,
			logger: "console"
		},
		level: severityLevelFromString(level),
		message: formatConsoleArgs$1(args)
	};
	if (level === "assert") {
		if (args[0] === false) {
			const assertionArgs = args.slice(1);
			breadcrumb.message = assertionArgs.length > 0 ? `Assertion failed: ${formatConsoleArgs$1(assertionArgs)}` : "Assertion failed";
			breadcrumb.data.arguments = assertionArgs;
		} else return;
	}
	require_fetch.addBreadcrumb(breadcrumb, {
		input: args,
		level
	});
}
function formatConsoleArgs$1(values) {
	return "util" in require_cacheOrigin.GLOBAL_OBJ && typeof require_cacheOrigin.GLOBAL_OBJ.util.format === "function" ? require_cacheOrigin.GLOBAL_OBJ.util.format(...values) : require_cacheOrigin.safeJoin(values, " ");
}
// src/utils/featureFlags.ts
/**
* Max size of the LRU flag buffer stored in Sentry scope and event contexts.
*/
const _INTERNAL_FLAG_BUFFER_SIZE = 100;
/**
* Max number of flag evaluations to record per span.
*/
const _INTERNAL_MAX_FLAGS_PER_SPAN = 10;
const SPAN_FLAG_ATTRIBUTE_PREFIX = "flag.evaluation.";
/**
* Copies feature flags that are in current scope context to the event context
*/
function _INTERNAL_copyFlagsFromScopeToEvent(event) {
	if (event.type) return event;
	const flagContext = require_cacheOrigin.getCurrentScope().getScopeData().contexts.flags;
	const flagBuffer = flagContext ? flagContext.values : [];
	if (!flagBuffer.length) return event;
	if (event.contexts === void 0) event.contexts = {};
	event.contexts.flags = { values: [...flagBuffer] };
	return event;
}
/**
* Inserts a flag into the current scope's context while maintaining ordered LRU properties.
* Not thread-safe. After inserting:
* - The flag buffer is sorted in order of recency, with the newest evaluation at the end.
* - The names in the buffer are always unique.
* - The length of the buffer never exceeds `maxSize`.
*
* @param name     Name of the feature flag to insert.
* @param value    Value of the feature flag.
* @param maxSize  Max number of flags the buffer should store. Default value should always be used in production.
*/
function _INTERNAL_insertFlagToScope(name, value, maxSize = 100) {
	const scopeContexts = require_cacheOrigin.getCurrentScope().getScopeData().contexts;
	if (!scopeContexts.flags) scopeContexts.flags = { values: [] };
	const flags = scopeContexts.flags.values;
	_INTERNAL_insertToFlagBuffer(flags, name, value, maxSize);
}
/**
* Exported for tests only. Currently only accepts boolean values (otherwise no-op).
* Inserts a flag into a FeatureFlag array while maintaining the following properties:
* - Flags are sorted in order of recency, with the newest evaluation at the end.
* - The flag names are always unique.
* - The length of the array never exceeds `maxSize`.
*
* @param flags      The buffer to insert the flag into.
* @param name       Name of the feature flag to insert.
* @param value      Value of the feature flag.
* @param maxSize    Max number of flags the buffer should store. Default value should always be used in production.
*/
function _INTERNAL_insertToFlagBuffer(flags, name, value, maxSize) {
	if (typeof value !== "boolean") return;
	if (flags.length > maxSize) {
		require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.error(`[Feature Flags] insertToFlagBuffer called on a buffer larger than maxSize=${maxSize}`);
		return;
	}
	const index = flags.findIndex((f) => f.flag === name);
	if (index !== -1) flags.splice(index, 1);
	if (flags.length === maxSize) flags.shift();
	flags.push({
		flag: name,
		result: value
	});
}
/**
* Records a feature flag evaluation for the active span. This is a no-op for non-boolean values.
* The flag and its value is stored in span attributes with the `flag.evaluation` prefix. Once the
* unique flags for a span reaches maxFlagsPerSpan, subsequent flags are dropped.
*
* @param name             Name of the feature flag.
* @param value            Value of the feature flag. Non-boolean values are ignored.
* @param maxFlagsPerSpan  Max number of flags a buffer should store. Default value should always be used in production.
*/
function _INTERNAL_addFeatureFlagToActiveSpan(name, value, maxFlagsPerSpan = 10) {
	if (typeof value !== "boolean") return;
	const span = require_cacheOrigin.getActiveSpan();
	if (!span) return;
	const attributes = require_cacheOrigin.spanToStaticSpanJSON(span).data;
	if (`${SPAN_FLAG_ATTRIBUTE_PREFIX}${name}` in attributes) {
		span.setAttribute(`${SPAN_FLAG_ATTRIBUTE_PREFIX}${name}`, value);
		return;
	}
	if (Object.keys(attributes).filter((key) => key.startsWith(SPAN_FLAG_ATTRIBUTE_PREFIX)).length < maxFlagsPerSpan) span.setAttribute(`${SPAN_FLAG_ATTRIBUTE_PREFIX}${name}`, value);
}
// src/integrations/featureFlags/featureFlagsIntegration.ts
/**
* Sentry integration for buffering feature flag evaluations manually with an API, and
* capturing them on error events and spans.
*
* See the [feature flag documentation](https://develop.sentry.dev/sdk/expected-features/#feature-flags) for more information.
*
* @example
* ```
* import * as Sentry from '@sentry/browser';
* import { type FeatureFlagsIntegration } from '@sentry/browser';
*
* // Setup
* Sentry.init(..., integrations: [Sentry.featureFlagsIntegration()])
*
* // Verify
* const flagsIntegration = Sentry.getClient()?.getIntegrationByName<FeatureFlagsIntegration>('FeatureFlags');
* if (flagsIntegration) {
*   flagsIntegration.addFeatureFlag('my-flag', true);
* } else {
*   // check your setup
* }
* Sentry.captureException(Exception('broke')); // 'my-flag' should be captured to this Sentry event.
* ```
*/
const featureFlagsIntegration = require_cacheOrigin.defineIntegration(() => {
	return {
		name: "FeatureFlags",
		processEvent(event, _hint, _client) {
			return _INTERNAL_copyFlagsFromScopeToEvent(event);
		},
		addFeatureFlag(name, value) {
			_INTERNAL_insertFlagToScope(name, value);
			_INTERNAL_addFeatureFlagToActiveSpan(name, value);
		}
	};
});
// src/integrations/featureFlags/growthbook.ts
/**
* Sentry integration for capturing feature flag evaluations from GrowthBook.
*
* Only boolean results are captured at this time.
*
* @example
* ```typescript
* import { GrowthBook } from '@growthbook/growthbook';
* import * as Sentry from '@sentry/browser'; // or '@sentry/node'
*
* Sentry.init({
*   dsn: 'your-dsn',
*   integrations: [
*     Sentry.growthbookIntegration({ growthbookClass: GrowthBook })
*   ]
* });
* ```
*/
const growthbookIntegration = require_cacheOrigin.defineIntegration(({ growthbookClass }) => {
	return {
		name: "GrowthBook",
		setupOnce() {
			const proto = growthbookClass.prototype;
			if (typeof proto.isOn === "function") require_cacheOrigin.fill(proto, "isOn", _wrapAndCaptureBooleanResult);
			if (typeof proto.getFeatureValue === "function") require_cacheOrigin.fill(proto, "getFeatureValue", _wrapAndCaptureBooleanResult);
		},
		processEvent(event, _hint, _client) {
			return _INTERNAL_copyFlagsFromScopeToEvent(event);
		}
	};
});
function _wrapAndCaptureBooleanResult(original) {
	return function(...args) {
		const flagName = args[0];
		const result = original.apply(this, args);
		if (typeof flagName === "string" && typeof result === "boolean") {
			_INTERNAL_insertFlagToScope(flagName, result);
			_INTERNAL_addFeatureFlagToActiveSpan(flagName, result);
		}
		return result;
	};
}
// src/integrations/conversationId.ts
const INTEGRATION_NAME$1 = "ConversationId";
const _conversationIdIntegration = (() => {
	return {
		name: INTEGRATION_NAME$1,
		setup(client) {
			client.on("spanStart", (span) => {
				const scopeData = require_cacheOrigin.getCurrentScope().getScopeData();
				const isolationScopeData = require_cacheOrigin.getIsolationScope().getScopeData();
				const conversationId = scopeData.conversationId || isolationScopeData.conversationId;
				if (conversationId) {
					const { op, data: attributes, description: name } = require_cacheOrigin.spanToStaticSpanJSON(span);
					if (!op?.startsWith("gen_ai.") && !attributes["ai.operationId"] && !name?.startsWith("ai.")) return;
					span.setAttribute(_sentry_conventions_attributes.GEN_AI_CONVERSATION_ID, conversationId);
				}
			});
		}
	};
});
/**
* Automatically applies conversation ID from scope to spans.
*
* This integration reads the conversation ID from the current or isolation scope
* and applies it to spans when they start. This ensures the conversation ID is
* available for all AI-related operations.
*/
const conversationIdIntegration = require_cacheOrigin.defineIntegration(_conversationIdIntegration);
// src/profiling.ts
function isProfilingIntegrationWithProfiler(integration) {
	return !!integration && typeof integration["_profiler"] !== "undefined" && typeof integration["_profiler"]["start"] === "function" && typeof integration["_profiler"]["stop"] === "function";
}
/**
* Starts a manually controlled Sentry profiling session.
*
* Profiling starts only when the profiling integration sampled the current session and `profileLifecycle` is set to `manual`.
* While running, the profiler periodically sends profile chunks to Sentry until `stopProfiler()` is called.
*/
function startProfiler() {
	const client = require_cacheOrigin.getClient();
	if (!client) {
		require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.warn("No Sentry client available, profiling is not started");
		return;
	}
	const integration = client.getIntegrationByName("ProfilingIntegration");
	if (!integration) {
		require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.warn("ProfilingIntegration is not available");
		return;
	}
	if (!isProfilingIntegrationWithProfiler(integration)) {
		require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.warn("Profiler is not available on profiling integration.");
		return;
	}
	integration._profiler.start();
}
/**
* Stops a manually controlled Sentry profiling session.
*
* If a manual profiling session is running, stops the profiler and sends the currently collected profile chunk to Sentry.
* Calls are ignored when using the trace lifecycle or when no profiling session is running.
*/
function stopProfiler() {
	const client = require_cacheOrigin.getClient();
	if (!client) {
		require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.warn("No Sentry client available, profiling is not started");
		return;
	}
	const integration = client.getIntegrationByName("ProfilingIntegration");
	if (!integration) {
		require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.warn("ProfilingIntegration is not available");
		return;
	}
	if (!isProfilingIntegrationWithProfiler(integration)) {
		require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.warn("Profiler is not available on profiling integration.");
		return;
	}
	integration._profiler.stop();
}
/**
* Profiler namespace for controlling the profiler in 'manual' mode.
*
* Requires the `nodeProfilingIntegration` from the `@sentry/profiling-node` package.
*/
const profiler = {
	startProfiler,
	stopProfiler
};
// src/feedback.ts
/**
* Send user feedback to Sentry.
*/
function captureFeedback(params, hint = {}, scope = require_cacheOrigin.getCurrentScope()) {
	const { message, name, email, url, source, associatedEventId, tags } = params;
	const feedbackEvent = {
		contexts: { feedback: {
			contact_email: email,
			name,
			message,
			url,
			source,
			associated_event_id: associatedEventId
		} },
		type: "feedback",
		level: "info",
		tags
	};
	const client = scope?.getClient() || require_cacheOrigin.getClient();
	if (client) client.emit("beforeSendFeedback", feedbackEvent, hint);
	return scope.captureEvent(feedbackEvent, hint);
}
// src/logs/constants.ts
/**
* Maps a log severity level to a log severity number.
*
* @see LogSeverityLevel
*/
const SEVERITY_TEXT_TO_SEVERITY_NUMBER = {
	trace: 1,
	debug: 5,
	info: 9,
	warn: 13,
	error: 17,
	fatal: 21
};
// src/logs/envelope.ts
/**
* Creates a log container envelope item for a list of logs.
*
* @param items - The logs to include in the envelope.
* @param inferUserData - If true, tells Relay to infer the end-user IP and User-Agent from the incoming request.
*                        Only emitted as `ingest_settings` in browser environments.
* @returns The created log container envelope item.
*/
function createLogContainerEnvelopeItem(items, inferUserData) {
	const inferSetting = inferUserData ? "auto" : "never";
	return [{
		type: "log",
		item_count: items.length,
		content_type: "application/vnd.sentry.items.log+json"
	}, {
		version: 2,
		...require_cacheOrigin.isBrowser() && { ingest_settings: {
			infer_ip: inferSetting,
			infer_user_agent: inferSetting
		} },
		items
	}];
}
/**
* Creates an envelope for a list of logs.
*
* Logs from multiple traces can be included in the same envelope.
*
* @param logs - The logs to include in the envelope.
* @param metadata - The metadata to include in the envelope.
* @param tunnel - The tunnel to include in the envelope.
* @param dsn - The DSN to include in the envelope.
* @param inferUserData - If true, tells Relay to infer the end-user IP and User-Agent from the incoming request.
* @returns The created envelope.
*/
function createLogEnvelope(logs, metadata, tunnel, dsn, inferUserData) {
	const headers = {};
	if (metadata?.sdk) headers.sdk = {
		name: metadata.sdk.name,
		version: metadata.sdk.version
	};
	if (!!tunnel && !!dsn) headers.dsn = require_cacheOrigin.dsnToString(dsn);
	return require_cacheOrigin.createEnvelope(headers, [createLogContainerEnvelopeItem(logs, inferUserData)]);
}
// src/logs/internal.ts
const MAX_LOG_BUFFER_SIZE = 100;
/**
* Sets a log attribute if the value exists and the attribute key is not already present.
*
* @param logAttributes - The log attributes object to modify.
* @param key - The attribute key to set.
* @param value - The value to set (only sets if truthy and key not present).
* @param setEvenIfPresent - Whether to set the attribute if it is present. Defaults to true.
*/
function setLogAttribute(logAttributes, key, value, setEvenIfPresent = true) {
	if (value && (!logAttributes[key] || setEvenIfPresent)) logAttributes[key] = value;
}
/**
* Captures a serialized log event and adds it to the log buffer for the given client.
*
* @param client - A client. Uses the current client if not provided.
* @param serializedLog - The serialized log event to capture.
*
* @experimental This method will experience breaking changes. This is not yet part of
* the stable Sentry SDK API and can be changed or removed without warning.
*/
function _INTERNAL_captureSerializedLog(client, serializedLog) {
	const bufferMap = _getBufferMap();
	const logBuffer = _INTERNAL_getLogBuffer(client);
	if (logBuffer === void 0) {
		setupWeightBasedFlushing(client, "afterCaptureLog", "flushLogs", estimateLogSizeInBytes, _INTERNAL_flushLogsBuffer);
		bufferMap.set(client, [serializedLog]);
	} else if (logBuffer.length >= MAX_LOG_BUFFER_SIZE) {
		_INTERNAL_flushLogsBuffer(client, logBuffer);
		bufferMap.set(client, [serializedLog]);
	} else bufferMap.set(client, [...logBuffer, serializedLog]);
}
/**
* Captures a log event and sends it to Sentry.
*
* @param log - The log event to capture.
* @param scope - A scope. Uses the current scope if not provided.
* @param client - A client. Uses the current client if not provided.
* @param captureSerializedLog - A function to capture the serialized log.
*
* @experimental This method will experience breaking changes. This is not yet part of
* the stable Sentry SDK API and can be changed or removed without warning.
*/
function _INTERNAL_captureLog(beforeLog, currentScope = require_cacheOrigin.getCurrentScope(), captureSerializedLog = _INTERNAL_captureSerializedLog) {
	const client = currentScope?.getClient() ?? require_cacheOrigin.getClient();
	if (!client) {
		require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.warn("No client available to capture log.");
		return;
	}
	const { release, environment, beforeSendLog } = client.getOptions();
	const [, traceContext] = require_fetch._getTraceInfoFromScope(client, currentScope);
	const processedLogAttributes = { ...beforeLog.attributes };
	const { user: { id, email, username }, attributes: scopeAttributes } = require_cacheOrigin.getCombinedScopeData(require_cacheOrigin.getIsolationScope(), currentScope);
	setLogAttribute(processedLogAttributes, _sentry_conventions_attributes.USER_ID, id, false);
	setLogAttribute(processedLogAttributes, _sentry_conventions_attributes.USER_EMAIL, email, false);
	setLogAttribute(processedLogAttributes, _sentry_conventions_attributes.USER_NAME, username, false);
	setLogAttribute(processedLogAttributes, _sentry_conventions_attributes.SENTRY_RELEASE, release);
	setLogAttribute(processedLogAttributes, _sentry_conventions_attributes.SENTRY_ENVIRONMENT, environment);
	const { name, version } = client.getSdkMetadata()?.sdk ?? {};
	setLogAttribute(processedLogAttributes, _sentry_conventions_attributes.SENTRY_SDK_NAME, name);
	setLogAttribute(processedLogAttributes, _sentry_conventions_attributes.SENTRY_SDK_VERSION, version);
	const replay = client.getIntegrationByName("Replay");
	const replayId = replay?.getReplayId(true);
	setLogAttribute(processedLogAttributes, _sentry_conventions_attributes.SENTRY_REPLAY_ID, replayId);
	if (replayId && replay?.getRecordingMode() === "buffer") setLogAttribute(processedLogAttributes, "sentry._internal.replay_is_buffering", true);
	const beforeLogMessage = beforeLog.message;
	if (require_cacheOrigin.isParameterizedString(beforeLogMessage)) {
		const { __sentry_template_string__, __sentry_template_values__ = [] } = beforeLogMessage;
		if (__sentry_template_values__?.length) processedLogAttributes[_sentry_conventions_attributes.SENTRY_MESSAGE_TEMPLATE] = __sentry_template_string__;
		__sentry_template_values__.forEach((param, index) => {
			processedLogAttributes[`sentry.message.parameter.${index}`] = param;
		});
	}
	const span = require_cacheOrigin.getActiveSpan(currentScope);
	setLogAttribute(processedLogAttributes, _sentry_conventions_attributes.SENTRY_TRACE_PARENT_SPAN_ID, span?.spanContext().spanId);
	const processedLog = {
		...beforeLog,
		attributes: processedLogAttributes
	};
	client.emit("beforeCaptureLog", processedLog);
	const log = beforeSendLog ? require_cacheOrigin.safeCallback(require_cacheOrigin.DEBUG_BUILD ? "The `beforeSendLog` callback threw an error, dropping the log:" : "", () => require_cacheOrigin.consoleSandbox(() => beforeSendLog(processedLog)), () => require_cacheOrigin.CALLBACK_ERROR) : processedLog;
	if (log === require_cacheOrigin.CALLBACK_ERROR) {
		client.recordDroppedEvent("callback_error", "log_item", 1);
		return;
	}
	if (!log) {
		client.recordDroppedEvent("before_send", "log_item", 1);
		require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.warn("beforeSendLog returned null, log will not be captured.");
		return;
	}
	const { level, message, attributes: logAttributes = {}, severityNumber } = log;
	const timestamp = require_cacheOrigin.timestampInSeconds();
	const sequenceAttr = getSequenceAttribute(timestamp);
	captureSerializedLog(client, {
		timestamp,
		level,
		body: _removeLoneSurrogates(String(message)),
		trace_id: traceContext?.trace_id,
		severity_number: severityNumber ?? SEVERITY_TEXT_TO_SEVERITY_NUMBER[level],
		attributes: sanitizeLogAttributes({
			...require_cacheOrigin.serializeAttributes(scopeAttributes),
			...require_cacheOrigin.serializeAttributes(logAttributes, true),
			[sequenceAttr.key]: sequenceAttr.value
		})
	});
	client.emit("afterCaptureLog", log);
}
/**
* Flushes the logs buffer to Sentry.
*
* @param client - A client.
* @param maybeLogBuffer - A log buffer. Uses the log buffer for the given client if not provided.
*
* @experimental This method will experience breaking changes. This is not yet part of
* the stable Sentry SDK API and can be changed or removed without warning.
*/
function _INTERNAL_flushLogsBuffer(client, maybeLogBuffer) {
	const logBuffer = maybeLogBuffer ?? _INTERNAL_getLogBuffer(client) ?? [];
	if (logBuffer.length === 0) return;
	const clientOptions = client.getOptions();
	const envelope = createLogEnvelope(logBuffer, clientOptions._metadata, clientOptions.tunnel, client.getDsn(), client.getDataCollectionOptions().userInfo);
	_getBufferMap().set(client, []);
	client.emit("flushLogs");
	client.sendEnvelope(envelope);
}
/**
* Returns the log buffer for a given client.
*
* Exported for testing purposes.
*
* @param client - The client to get the log buffer for.
* @returns The log buffer for the given client.
*/
function _INTERNAL_getLogBuffer(client) {
	return _getBufferMap().get(client);
}
function _getBufferMap() {
	return require_cacheOrigin.getGlobalSingleton("clientToLogBufferMap", () => /* @__PURE__ */ new WeakMap());
}
/**
* Sanitizes serialized log attributes by replacing lone surrogates in both
* keys and string values with U+FFFD.
*/
function sanitizeLogAttributes(attributes) {
	const sanitized = {};
	for (const [key, attr] of Object.entries(attributes)) {
		const sanitizedKey = _removeLoneSurrogates(key);
		if (attr.type === "string") sanitized[sanitizedKey] = {
			...attr,
			value: _removeLoneSurrogates(attr.value)
		};
		else sanitized[sanitizedKey] = attr;
	}
	return sanitized;
}
/**
* Replaces unpaired UTF-16 surrogates with U+FFFD (replacement character).
*
* Lone surrogates (U+D800–U+DFFF not part of a valid pair) cause `serde_json`
* on the server to reject the entire log batch when they appear in
* JSON-escaped form (e.g. `\uD800`). Replacing them at the SDK level ensures
* only the offending characters are lost instead of the whole payload.
*
* Uses the native `String.prototype.toWellFormed()` when available
* (Node 20+, Chrome 111+, Safari 15.4+, Firefox 119+, Hermes).
* On older runtimes without native support, returns the string as-is.
*
* Exported for testing
*/
function _removeLoneSurrogates(str) {
	const strObj = Object(str);
	const isWellFormed = strObj["isWellFormed"];
	const toWellFormed = strObj["toWellFormed"];
	if (typeof isWellFormed === "function" && typeof toWellFormed === "function") return isWellFormed.call(str) ? str : toWellFormed.call(str);
	return str;
}
// src/logs/public-api.ts
/**
* Capture a log with the given level.
*
* @param level - The level of the log.
* @param message - The message to log.
* @param attributes - Arbitrary structured data that stores information about the log - e.g., userId: 100.
* @param scope - The scope to capture the log with.
* @param severityNumber - The severity number of the log.
*/
function captureLog(level, message, attributes, scope, severityNumber) {
	_INTERNAL_captureLog({
		level,
		message,
		attributes,
		severityNumber
	}, scope);
}
/**
* @summary Capture a log with the `trace` level.
*
* @param message - The message to log.
* @param attributes - Arbitrary structured data that stores information about the log - e.g., { userId: 100, route: '/dashboard' }.
* @param metadata - additional metadata to capture the log with.
*
* @example
*
* ```
* Sentry.logger.trace('User clicked submit button', {
*   buttonId: 'submit-form',
*   formId: 'user-profile',
*   timestamp: Date.now()
* });
* ```
*
* @example With template strings
*
* ```
* Sentry.logger.trace(Sentry.logger.fmt`User ${user} navigated to ${page}`, {
*   userId: '123',
*   sessionId: 'abc-xyz'
* });
* ```
*/
function trace(message, attributes, { scope } = {}) {
	captureLog("trace", message, attributes, scope);
}
/**
* @summary Capture a log with the `debug` level.
*
* @param message - The message to log.
* @param attributes - Arbitrary structured data that stores information about the log - e.g., { component: 'Header', state: 'loading' }.
* @param metadata - additional metadata to capture the log with.
*
* @example
*
* ```
* Sentry.logger.debug('Component mounted', {
*   component: 'UserProfile',
*   props: { userId: 123 },
*   renderTime: 150
* });
* ```
*
* @example With template strings
*
* ```
* Sentry.logger.debug(Sentry.logger.fmt`API request to ${endpoint} failed`, {
*   statusCode: 404,
*   requestId: 'req-123',
*   duration: 250
* });
* ```
*/
function debug$1(message, attributes, { scope } = {}) {
	captureLog("debug", message, attributes, scope);
}
/**
* @summary Capture a log with the `info` level.
*
* @param message - The message to log.
* @param attributes - Arbitrary structured data that stores information about the log - e.g., { feature: 'checkout', status: 'completed' }.
* @param metadata - additional metadata to capture the log with.
*
* @example
*
* ```
* Sentry.logger.info('User completed checkout', {
*   orderId: 'order-123',
*   amount: 99.99,
*   paymentMethod: 'credit_card'
* });
* ```
*
* @example With template strings
*
* ```
* Sentry.logger.info(Sentry.logger.fmt`User ${user} updated profile picture`, {
*   userId: 'user-123',
*   imageSize: '2.5MB',
*   timestamp: Date.now()
* });
* ```
*/
function info(message, attributes, { scope } = {}) {
	captureLog("info", message, attributes, scope);
}
/**
* @summary Capture a log with the `warn` level.
*
* @param message - The message to log.
* @param attributes - Arbitrary structured data that stores information about the log - e.g., { browser: 'Chrome', version: '91.0' }.
* @param metadata - additional metadata to capture the log with.
*
* @example
*
* ```
* Sentry.logger.warn('Browser compatibility issue detected', {
*   browser: 'Safari',
*   version: '14.0',
*   feature: 'WebRTC',
*   fallback: 'enabled'
* });
* ```
*
* @example With template strings
*
* ```
* Sentry.logger.warn(Sentry.logger.fmt`API endpoint ${endpoint} is deprecated`, {
*   recommendedEndpoint: '/api/v2/users',
*   sunsetDate: '2024-12-31',
*   clientVersion: '1.2.3'
* });
* ```
*/
function warn(message, attributes, { scope } = {}) {
	captureLog("warn", message, attributes, scope);
}
/**
* @summary Capture a log with the `error` level.
*
* @param message - The message to log.
* @param attributes - Arbitrary structured data that stores information about the log - e.g., { error: 'NetworkError', url: '/api/data' }.
* @param metadata - additional metadata to capture the log with.
*
* @example
*
* ```
* Sentry.logger.error('Failed to load user data', {
*   error: 'NetworkError',
*   url: '/api/users/123',
*   statusCode: 500,
*   retryCount: 3
* });
* ```
*
* @example With template strings
*
* ```
* Sentry.logger.error(Sentry.logger.fmt`Payment processing failed for order ${orderId}`, {
*   error: 'InsufficientFunds',
*   amount: 100.00,
*   currency: 'USD',
*   userId: 'user-456'
* });
* ```
*/
function error(message, attributes, { scope } = {}) {
	captureLog("error", message, attributes, scope);
}
/**
* @summary Capture a log with the `fatal` level.
*
* @param message - The message to log.
* @param attributes - Arbitrary structured data that stores information about the log - e.g., { appState: 'corrupted', sessionId: 'abc-123' }.
* @param metadata - additional metadata to capture the log with.
*
* @example
*
* ```
* Sentry.logger.fatal('Application state corrupted', {
*   lastKnownState: 'authenticated',
*   sessionId: 'session-123',
*   timestamp: Date.now(),
*   recoveryAttempted: true
* });
* ```
*
* @example With template strings
*
* ```
* Sentry.logger.fatal(Sentry.logger.fmt`Critical system failure in ${service}`, {
*   service: 'payment-processor',
*   errorCode: 'CRITICAL_FAILURE',
*   affectedUsers: 150,
*   timestamp: Date.now()
* });
* ```
*/
function fatal(message, attributes, { scope } = {}) {
	captureLog("fatal", message, attributes, scope);
}
/**
* The public logger API.
*
* A plain object rather than a module namespace so its methods can be spied on in tests.
*/
const logger = {
	trace,
	debug: debug$1,
	info,
	warn,
	error,
	fatal,
	fmt
};
// src/logs/utils.ts
/**
* Formats the given values into a string.
*
* @param values - The values to format.
* @param normalizeDepth - The depth to normalize the values.
* @param normalizeMaxBreadth - The max breadth to normalize the values.
* @returns The formatted string.
*/
function formatConsoleArgs(values, normalizeDepth, normalizeMaxBreadth) {
	return "util" in require_cacheOrigin.GLOBAL_OBJ && typeof require_cacheOrigin.GLOBAL_OBJ.util.format === "function" ? require_cacheOrigin.GLOBAL_OBJ.util.format(...values) : safeJoinConsoleArgs(values, normalizeDepth, normalizeMaxBreadth);
}
/**
* Joins the given values into a string.
*
* @param values - The values to join.
* @param normalizeDepth - The depth to normalize the values.
* @param normalizeMaxBreadth - The max breadth to normalize the values.
* @returns The joined string.
*/
function safeJoinConsoleArgs(values, normalizeDepth, normalizeMaxBreadth) {
	return values.map((value) => require_cacheOrigin.isPrimitive(value) ? String(value) : JSON.stringify(require_cacheOrigin.normalize(value, normalizeDepth, normalizeMaxBreadth))).join(" ");
}
/**
* Checks if a string contains console substitution patterns like %s, %d, %i, %f, %o, %O, %c.
*
* @param str - The string to check
* @returns true if the string contains console substitution patterns
*/
function hasConsoleSubstitutions(str) {
	return /%[sdifocO]/.test(str);
}
/**
* Creates template attributes for multiple console arguments.
*
* @param args - The console arguments
* @returns An object with template and parameter attributes
*/
function createConsoleTemplateAttributes(firstArg, followingArgs) {
	const attributes = {};
	const template = new Array(followingArgs.length).fill("{}").join(" ");
	attributes[_sentry_conventions_attributes.SENTRY_MESSAGE_TEMPLATE] = `${firstArg} ${template}`;
	followingArgs.forEach((arg, index) => {
		attributes[`sentry.message.parameter.${index}`] = arg;
	});
	return attributes;
}
// src/logs/console-integration.ts
const INTEGRATION_NAME = "ConsoleLogs";
const DEFAULT_ATTRIBUTES = { [_sentry_conventions_attributes.SENTRY_ORIGIN]: "auto.log.console" };
const _consoleLoggingIntegration = ((options = {}) => {
	const levels = options.levels || require_cacheOrigin.CONSOLE_LEVELS;
	return {
		name: INTEGRATION_NAME,
		setup(client) {
			const { normalizeDepth = 3, normalizeMaxBreadth = 1e3 } = client.getOptions();
			const unsubscribe = addConsoleInstrumentationHandler(({ args, level }) => {
				if (require_cacheOrigin.getClient() !== client || !levels.includes(level)) return;
				const firstArg = args[0];
				const followingArgs = args.slice(1);
				if (level === "assert") {
					if (!firstArg) _INTERNAL_captureLog({
						level: "error",
						message: followingArgs.length > 0 ? `Assertion failed: ${formatConsoleArgs(followingArgs, normalizeDepth, normalizeMaxBreadth)}` : "Assertion failed",
						attributes: DEFAULT_ATTRIBUTES
					});
					return;
				}
				const isLevelLog = level === "log";
				const attributes = { ...DEFAULT_ATTRIBUTES };
				if (require_cacheOrigin.isPlainObject(firstArg)) {
					Object.assign(attributes, require_cacheOrigin.normalize(firstArg, normalizeDepth, normalizeMaxBreadth));
					const remainingArgsStartIndex = typeof args[1] === "string" ? 2 : 1;
					args.slice(remainingArgsStartIndex).forEach((arg, index) => {
						attributes[`sentry.message.parameter.${index}`] = require_cacheOrigin.normalize(arg, normalizeDepth, normalizeMaxBreadth);
					});
				} else if (followingArgs.length > 0 && typeof firstArg === "string" && !hasConsoleSubstitutions(firstArg)) {
					const templateAttrs = createConsoleTemplateAttributes(firstArg, followingArgs);
					for (const [key, value] of Object.entries(templateAttrs)) attributes[key] = key.startsWith("sentry.message.parameter.") ? require_cacheOrigin.normalize(value, normalizeDepth, normalizeMaxBreadth) : value;
				}
				_INTERNAL_captureLog({
					level: isLevelLog ? "info" : level,
					message: formatConsoleArgs(args, normalizeDepth, normalizeMaxBreadth),
					severityNumber: isLevelLog ? 10 : void 0,
					attributes
				});
			});
			client.registerCleanup(unsubscribe);
		}
	};
});
/**
* Captures calls to the `console` API as logs in Sentry.
*
* @experimental This feature is experimental and may be changed or removed in future versions.
*
* By default the integration instruments `console.debug`, `console.info`, `console.warn`, `console.error`,
* `console.log`, `console.trace`, and `console.assert`. You can use the `levels` option to customize which
* levels are captured.
*
* @example
*
* ```ts
* import * as Sentry from '@sentry/browser';
*
* Sentry.init({
*   integrations: [Sentry.consoleLoggingIntegration({ levels: ['error', 'warn'] })],
* });
* ```
*/
const consoleLoggingIntegration = require_cacheOrigin.defineIntegration(_consoleLoggingIntegration);
// src/integrations/consola.ts
const DEFAULT_CAPTURED_LEVELS = [
	"trace",
	"debug",
	"info",
	"warn",
	"error",
	"fatal"
];
/**
* Creates a new Sentry reporter for Consola that forwards logs to Sentry.
*
* **Note: This integration supports Consola v3.x only.** The reporter interface and log object structure
* may differ in other versions of Consola.
*
* @param options - Configuration options for the reporter.
* @returns A Consola reporter that can be added to consola instances.
*
* @example
* ```ts
* import * as Sentry from '@sentry/node';
* import { consola } from 'consola';
*
* Sentry.init({
*   dsn: '__DSN__',
* });
*
* const sentryReporter = Sentry.createConsolaReporter({
*   // Optional: filter levels to capture
*   levels: ['error', 'warn', 'info'],
* });
*
* consola.addReporter(sentryReporter);
*
* // Now consola logs will be captured by Sentry
* consola.info('This will be sent to Sentry');
* consola.error('This error will also be sent to Sentry');
* ```
*/
function createConsolaReporter(options = {}) {
	const levels = new Set(options.levels ?? DEFAULT_CAPTURED_LEVELS);
	const providedClient = options.client;
	return { log(logObj) {
		const { type, level, message: consolaMessage, args, tag, date: _date, ...rest } = logObj;
		const client = providedClient || require_cacheOrigin.getClient();
		if (!client) return;
		const logSeverityLevel = getLogSeverityLevel(type, level);
		if (!levels.has(logSeverityLevel)) return;
		const { normalizeDepth = 3, normalizeMaxBreadth = 1e3 } = client.getOptions();
		const attributes = {};
		for (const [key, value] of Object.entries(rest)) attributes[key] = require_cacheOrigin.normalize(value, normalizeDepth, normalizeMaxBreadth);
		attributes[_sentry_conventions_attributes.SENTRY_ORIGIN] = "auto.log.consola";
		if (tag) attributes["consola.tag"] = tag;
		if (type) attributes["consola.type"] = type;
		if (level != null && typeof level === "number") attributes["consola.level"] = level;
		const extractionResult = processExtractedAttributes(defaultExtractAttributes(args, normalizeDepth, normalizeMaxBreadth), normalizeDepth, normalizeMaxBreadth);
		if (extractionResult?.attributes) Object.assign(attributes, extractionResult.attributes);
		_INTERNAL_captureLog({
			level: logSeverityLevel,
			message: extractionResult?.message || consolaMessage || args && formatConsoleArgs(args, normalizeDepth, normalizeMaxBreadth) || "",
			attributes
		});
	} };
}
const CONSOLA_TYPE_TO_LOG_SEVERITY_LEVEL_MAP = {
	silent: "trace",
	fatal: "fatal",
	error: "error",
	warn: "warn",
	log: "info",
	info: "info",
	success: "info",
	fail: "error",
	ready: "info",
	start: "info",
	box: "info",
	debug: "debug",
	trace: "trace",
	verbose: "debug",
	critical: "fatal",
	notice: "info"
};
const CONSOLA_LEVEL_TO_LOG_SEVERITY_LEVEL_MAP = {
	0: "fatal",
	1: "warn",
	2: "info",
	3: "info",
	4: "debug",
	5: "trace"
};
/**
* Determines the log severity level from Consola type and level.
*
* @param type - The Consola log type (e.g., 'error', 'warn', 'info')
* @param level - The Consola numeric log level (0-5) or null for some types like 'verbose'
* @returns The corresponding Sentry log severity level
*/
function getLogSeverityLevel(type, level) {
	if (type === "verbose") return "debug";
	if (type === "silent") return "trace";
	if (type) {
		const mappedLevel = CONSOLA_TYPE_TO_LOG_SEVERITY_LEVEL_MAP[type];
		if (mappedLevel) return mappedLevel;
	}
	if (typeof level === "number") {
		const mappedLevel = CONSOLA_LEVEL_TO_LOG_SEVERITY_LEVEL_MAP[level];
		if (mappedLevel) return mappedLevel;
	}
	return "info";
}
/**
* Extracts structured attributes from console arguments. If the first argument is a plain object, its properties are extracted as attributes.
*/
function defaultExtractAttributes(args, normalizeDepth, normalizeMaxBreadth) {
	if (!args?.length) return { message: "" };
	const message = formatConsoleArgs(args, normalizeDepth, normalizeMaxBreadth);
	const firstArg = args[0];
	if (require_cacheOrigin.isPlainObject(firstArg)) {
		const remainingArgsStartIndex = typeof args[1] === "string" ? 2 : 1;
		return {
			message,
			attributes: firstArg,
			messageParameters: args.slice(remainingArgsStartIndex)
		};
	} else {
		const followingArgs = args.slice(1);
		const shouldAddTemplateAttr = followingArgs.length > 0 && typeof firstArg === "string" && !hasConsoleSubstitutions(firstArg);
		return {
			message,
			messageTemplate: shouldAddTemplateAttr ? firstArg : void 0,
			messageParameters: shouldAddTemplateAttr ? followingArgs : void 0
		};
	}
}
/**
* Processes extracted attributes by normalizing them and preparing message parameter attributes if a template is present.
*/
function processExtractedAttributes(extractionResult, normalizeDepth, normalizeMaxBreadth) {
	const { message, attributes, messageTemplate, messageParameters } = extractionResult;
	const messageParamAttributes = {};
	if (messageTemplate && messageParameters) {
		const templateAttrs = createConsoleTemplateAttributes(messageTemplate, messageParameters);
		for (const [key, value] of Object.entries(templateAttrs)) messageParamAttributes[key] = key.startsWith("sentry.message.parameter.") ? require_cacheOrigin.normalize(value, normalizeDepth, normalizeMaxBreadth) : value;
	} else if (messageParameters && messageParameters.length > 0) messageParameters.forEach((arg, index) => {
		messageParamAttributes[`sentry.message.parameter.${index}`] = require_cacheOrigin.normalize(arg, normalizeDepth, normalizeMaxBreadth);
	});
	return {
		message,
		attributes: {
			...require_cacheOrigin.normalize(attributes, normalizeDepth, normalizeMaxBreadth),
			...messageParamAttributes
		}
	};
}
// src/utils/error.ts
/**
* An error emitted by Sentry SDKs and related utilities.
* @deprecated This class is no longer used and will be removed in a future version. Use `Error` instead.
*/
var SentryError = class extends Error {
	constructor(message, logLevel = "warn") {
		super(message);
		this.message = message;
		this.logLevel = logLevel;
	}
};
// src/utils/exports.ts
/**
* Replaces constructor functions in module exports, handling read-only properties,
* and both default and named exports by wrapping them with the constructor.
*
* @param exports The module exports object to modify
* @param exportName The name of the export to replace (e.g., 'GoogleGenAI', 'Anthropic', 'OpenAI')
* @param wrappedConstructor The wrapped constructor function to replace the original with
* @returns void
*/
function replaceExports(exports, exportName, wrappedConstructor) {
	const original = exports[exportName];
	if (typeof original !== "function") return;
	try {
		exports[exportName] = wrappedConstructor;
	} catch {
		Object.defineProperty(exports, exportName, {
			value: wrappedConstructor,
			writable: true,
			configurable: true,
			enumerable: true
		});
	}
	if (exports.default === original) try {
		exports.default = wrappedConstructor;
	} catch {
		Object.defineProperty(exports, "default", {
			value: wrappedConstructor,
			writable: true,
			configurable: true,
			enumerable: true
		});
	}
}
// src/build-time-plugins/warnOnRemovedBuildOptions.ts
/**
* Warns when a build option that was removed in v11 is still present in a user's build config.
*
* TypeScript already rejects these keys, but meta-framework build configs are frequently plain
* JavaScript (`next.config.js`, `next.config.mjs`), where a removed option would otherwise be a
* silent no-op.
*
* @param options The user's build options, if any.
* @param removedKeys The removed option names to check for.
* @param logWarning Called at most once, with the full warning message. Defaults to `console.warn`,
* which suits every SDK whose build step has no logger of its own. Pass this only to route the
* warning through a framework logger (e.g. Astro's).
*
* @internal Only meant for Sentry-internal SDK usage.
* @hidden
*/
function warnOnRemovedBuildOptions(options, removedKeys, logWarning = (message) => require_cacheOrigin.consoleSandbox(() => {
	console.warn(message);
})) {
	if (!options) return;
	const presentKeys = removedKeys.filter((key) => key in options);
	if (!presentKeys.length) return;
	logWarning(`[Sentry] Removed in v11 and ignored: ${presentKeys.join(", ")}. Set bundler plugin options directly on the Sentry build options.`);
}
// src/build-time-plugins/resolveSourceMapsFeatures.ts
/**
* Reads `sourcemaps.upload` and `sourcemaps.injectDebugIds`. When neither is set,
* `sourcemaps.disable` decides.
*
* @internal Only meant for Sentry-internal SDK usage.
* @hidden
*/
function resolveSourceMapsFeatures(sourcemaps) {
	const { upload, injectDebugIds, disable } = sourcemaps ?? {};
	if (upload === void 0 && injectDebugIds === void 0) return {
		injectDebugIds: disable !== true,
		upload: !disable,
		...disable ? { legacyDisable: disable } : {}
	};
	return {
		injectDebugIds: injectDebugIds !== false,
		upload: injectDebugIds !== false && upload !== false
	};
}
// src/build-time-plugins/stringifyForCodeInjection.ts
const UNSAFE_CHARS = /[<>\u2028\u2029]/g;
const ESCAPED_CHARS = {
	"<": "\\u003c",
	">": "\\u003e",
	"\u2028": "\\u2028",
	"\u2029": "\\u2029"
};
/**
* A drop-in replacement for `JSON.stringify`, for values that go into generated JavaScript code.
*
* `JSON.stringify` output is a valid JavaScript expression, but it does not escape `<` and `>`, so
* a value with `<\/script>` or `<!--` breaks out of a `<script>` element when the code is inlined in
* HTML. It also does not escape U+2028 and U+2029, which end a line in JavaScript before ES2019.
* These characters only occur inside JSON strings, where their `\u` escapes have the same value.
*
* Use this every time `JSON.stringify` output is put into code, for example in a bundler plugin.
*
* @internal Only meant for Sentry-internal SDK usage.
* @hidden
*/
function stringifyForCodeInjection(value, replacer, space) {
	return (typeof replacer === "function" ? JSON.stringify(value, replacer, space) : JSON.stringify(value, replacer, space))?.replace(UNSAFE_CHARS, (char) => ESCAPED_CHARS[char]);
}
exports.BROWSER_NAVIGATION_TIMING_SPAN_NAMES = require_fetch.BROWSER_NAVIGATION_TIMING_SPAN_NAMES;
exports.CACHE_OPERATION_NAMES = require_fetch.CACHE_OPERATION_NAMES;
exports.CONSOLE_LEVELS = require_cacheOrigin.CONSOLE_LEVELS;
exports.Client = require_fetch.Client;
exports.DB_SPAN_NAME_FALLBACK = require_fetch.DB_SPAN_NAME_FALLBACK;
exports.DEFAULT_ENVIRONMENT = require_cacheOrigin.DEFAULT_ENVIRONMENT;
exports.DEFAULT_RETRY_AFTER = require_fetch.DEFAULT_RETRY_AFTER;
exports.DEV_ENVIRONMENT = require_cacheOrigin.DEV_ENVIRONMENT;
exports.FUNCTION_SPAN_NAME_FALLBACK = require_fetch.FUNCTION_SPAN_NAME_FALLBACK;
exports.GEN_AI_AGENT_SPAN_NAME_FALLBACK = require_fetch.GEN_AI_AGENT_SPAN_NAME_FALLBACK;
exports.GEN_AI_CONVERSATION_ID_ATTRIBUTE = require_cacheOrigin.GEN_AI_CONVERSATION_ID_ATTRIBUTE;
exports.GEN_AI_INFERENCE_SPAN_NAME_FALLBACK = require_fetch.GEN_AI_INFERENCE_SPAN_NAME_FALLBACK;
exports.GLOBAL_OBJ = require_cacheOrigin.GLOBAL_OBJ;
exports.GRAPHQL_SPAN_NAME_FALLBACK = require_fetch.GRAPHQL_SPAN_NAME_FALLBACK;
exports.HTTP_SPAN_NAME_FALLBACK = require_fetch.HTTP_SPAN_NAME_FALLBACK;
exports.INTERNAL_getSegmentSpan = require_cacheOrigin.INTERNAL_getSegmentSpan;
exports.INTERNAL_setSegmentNameSourceIfSegment = require_cacheOrigin.INTERNAL_setSegmentNameSourceIfSegment;
exports.LRUMap = require_fetch.LRUMap;
exports.MAX_BAGGAGE_STRING_LENGTH = require_cacheOrigin.MAX_BAGGAGE_STRING_LENGTH;
exports.MAX_BODY_BYTE_LENGTH = require_fetch.MAX_BODY_BYTE_LENGTH;
exports.MCP_NOTIFICATION_SPAN_NAME_FALLBACK = require_fetch.MCP_NOTIFICATION_SPAN_NAME_FALLBACK;
exports.MCP_SERVER_SPAN_NAME_FALLBACK = require_fetch.MCP_SERVER_SPAN_NAME_FALLBACK;
exports.MESSAGING_SPAN_NAME_FALLBACK = require_fetch.MESSAGING_SPAN_NAME_FALLBACK;
exports.MULTIPLEXED_TRANSPORT_EXTRA_KEY = MULTIPLEXED_TRANSPORT_EXTRA_KEY;
exports.NAVIGATION_SPAN_NAME_FALLBACK = require_fetch.NAVIGATION_SPAN_NAME_FALLBACK;
exports.PAGELOAD_SPAN_NAME_FALLBACK = require_fetch.PAGELOAD_SPAN_NAME_FALLBACK;
exports.REQUEST_HANDLER_SPAN_NAME_FALLBACK = require_fetch.REQUEST_HANDLER_SPAN_NAME_FALLBACK;
exports.RESOURCE_SPAN_NAME_FALLBACK = require_fetch.RESOURCE_SPAN_NAME_FALLBACK;
exports.ROUTER_SPAN_NAME_FALLBACK = require_fetch.ROUTER_SPAN_NAME_FALLBACK;
exports.SDK_VERSION = require_cacheOrigin.SDK_VERSION;
exports.SEMANTIC_ATTRIBUTE_CACHE_HIT = require_cacheOrigin.SEMANTIC_ATTRIBUTE_CACHE_HIT;
exports.SEMANTIC_ATTRIBUTE_CACHE_ITEM_SIZE = require_cacheOrigin.SEMANTIC_ATTRIBUTE_CACHE_ITEM_SIZE;
exports.SEMANTIC_ATTRIBUTE_CACHE_KEY = require_cacheOrigin.SEMANTIC_ATTRIBUTE_CACHE_KEY;
exports.SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME = require_cacheOrigin.SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME;
exports.SEMANTIC_ATTRIBUTE_HTTP_REQUEST_METHOD = require_cacheOrigin.SEMANTIC_ATTRIBUTE_HTTP_REQUEST_METHOD;
exports.SEMANTIC_ATTRIBUTE_PROFILE_ID = require_cacheOrigin.SEMANTIC_ATTRIBUTE_PROFILE_ID;
exports.SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME = require_cacheOrigin.SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME;
exports.SEMANTIC_ATTRIBUTE_SENTRY_ENVIRONMENT = require_cacheOrigin.SEMANTIC_ATTRIBUTE_SENTRY_ENVIRONMENT;
exports.SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON = require_cacheOrigin.SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON;
exports.SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT = require_cacheOrigin.SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT;
exports.SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE = require_cacheOrigin.SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE;
exports.SEMANTIC_ATTRIBUTE_SENTRY_OP = require_cacheOrigin.SEMANTIC_ATTRIBUTE_SENTRY_OP;
exports.SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN = require_cacheOrigin.SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN;
exports.SEMANTIC_ATTRIBUTE_SENTRY_PREVIOUS_TRACE_SAMPLE_RATE = require_cacheOrigin.SEMANTIC_ATTRIBUTE_SENTRY_PREVIOUS_TRACE_SAMPLE_RATE;
exports.SEMANTIC_ATTRIBUTE_SENTRY_RELEASE = require_cacheOrigin.SEMANTIC_ATTRIBUTE_SENTRY_RELEASE;
exports.SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE = require_cacheOrigin.SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE;
exports.SEMANTIC_ATTRIBUTE_SENTRY_SDK_INTEGRATIONS = require_cacheOrigin.SEMANTIC_ATTRIBUTE_SENTRY_SDK_INTEGRATIONS;
exports.SEMANTIC_ATTRIBUTE_SENTRY_SDK_NAME = require_cacheOrigin.SEMANTIC_ATTRIBUTE_SENTRY_SDK_NAME;
exports.SEMANTIC_ATTRIBUTE_SENTRY_SDK_VERSION = require_cacheOrigin.SEMANTIC_ATTRIBUTE_SENTRY_SDK_VERSION;
exports.SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_ID = require_cacheOrigin.SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_ID;
exports.SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_NAME = require_cacheOrigin.SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_NAME;
exports.SEMANTIC_ATTRIBUTE_SENTRY_STATUS_MESSAGE = require_cacheOrigin.SEMANTIC_ATTRIBUTE_SENTRY_STATUS_MESSAGE;
exports.SEMANTIC_ATTRIBUTE_URL_FULL = require_cacheOrigin.SEMANTIC_ATTRIBUTE_URL_FULL;
exports.SEMANTIC_ATTRIBUTE_USER_EMAIL = require_cacheOrigin.SEMANTIC_ATTRIBUTE_USER_EMAIL;
exports.SEMANTIC_ATTRIBUTE_USER_ID = require_cacheOrigin.SEMANTIC_ATTRIBUTE_USER_ID;
exports.SEMANTIC_ATTRIBUTE_USER_IP_ADDRESS = require_cacheOrigin.SEMANTIC_ATTRIBUTE_USER_IP_ADDRESS;
exports.SEMANTIC_ATTRIBUTE_USER_USERNAME = require_cacheOrigin.SEMANTIC_ATTRIBUTE_USER_USERNAME;
exports.SEMANTIC_LINK_ATTRIBUTE_LINK_TYPE = require_cacheOrigin.SEMANTIC_LINK_ATTRIBUTE_LINK_TYPE;
exports.SENTRY_API_VERSION = require_fetch.SENTRY_API_VERSION;
exports.SENTRY_BAGGAGE_KEY_PREFIX = require_cacheOrigin.SENTRY_BAGGAGE_KEY_PREFIX;
exports.SENTRY_BAGGAGE_KEY_PREFIX_REGEX = require_cacheOrigin.SENTRY_BAGGAGE_KEY_PREFIX_REGEX;
exports.SENTRY_BUFFER_FULL_ERROR = require_fetch.SENTRY_BUFFER_FULL_ERROR;
exports.SERVERLESS_FUNCTION_SPAN_NAME_FALLBACK = require_fetch.SERVERLESS_FUNCTION_SPAN_NAME_FALLBACK;
exports.SPAN_STATUS_ERROR = require_cacheOrigin.SPAN_STATUS_ERROR;
exports.SPAN_STATUS_OK = require_cacheOrigin.SPAN_STATUS_OK;
exports.SPAN_STATUS_UNSET = require_cacheOrigin.SPAN_STATUS_UNSET;
exports.Scope = require_cacheOrigin.Scope;
exports.SentryError = SentryError;
exports.SentryNonRecordingSpan = require_cacheOrigin.SentryNonRecordingSpan;
exports.SentrySpan = require_cacheOrigin.SentrySpan;
exports.SpanBuffer = require_cacheOrigin.SpanBuffer;
exports.SyncPromise = require_cacheOrigin.SyncPromise;
exports.TRACEPARENT_REGEXP = require_cacheOrigin.TRACEPARENT_REGEXP;
exports.TRACING_DEFAULTS = require_cacheOrigin.TRACING_DEFAULTS;
exports.UI_ACTION_CLICK_SPAN_NAME_FALLBACK = require_fetch.UI_ACTION_CLICK_SPAN_NAME_FALLBACK;
exports.UI_ACTION_SPAN_NAME_FALLBACK = require_fetch.UI_ACTION_SPAN_NAME_FALLBACK;
exports.UI_INTERACTION_CLICK_SPAN_NAME_FALLBACK = require_fetch.UI_INTERACTION_CLICK_SPAN_NAME_FALLBACK;
exports.UI_INTERACTION_DRAG_SPAN_NAME_FALLBACK = require_fetch.UI_INTERACTION_DRAG_SPAN_NAME_FALLBACK;
exports.UI_INTERACTION_HOVER_SPAN_NAME_FALLBACK = require_fetch.UI_INTERACTION_HOVER_SPAN_NAME_FALLBACK;
exports.UI_INTERACTION_PRESS_SPAN_NAME_FALLBACK = require_fetch.UI_INTERACTION_PRESS_SPAN_NAME_FALLBACK;
exports.UI_LONG_TASK_SPAN_NAME_FALLBACK = require_fetch.UI_LONG_TASK_SPAN_NAME_FALLBACK;
exports.UI_MOUNT_SPAN_NAME_FALLBACK = require_fetch.UI_MOUNT_SPAN_NAME_FALLBACK;
exports.UI_RENDER_SPAN_NAME_FALLBACK = require_fetch.UI_RENDER_SPAN_NAME_FALLBACK;
exports.UI_RESOLVE_SPAN_NAME_FALLBACK = require_fetch.UI_RESOLVE_SPAN_NAME_FALLBACK;
exports.UI_SPAN_NAME_FALLBACK = require_fetch.UI_SPAN_NAME_FALLBACK;
exports.UI_TASK_SPAN_NAME_FALLBACK = require_fetch.UI_TASK_SPAN_NAME_FALLBACK;
exports.UI_UNMOUNT_SPAN_NAME_FALLBACK = require_fetch.UI_UNMOUNT_SPAN_NAME_FALLBACK;
exports.UI_UPDATE_SPAN_NAME_FALLBACK = require_fetch.UI_UPDATE_SPAN_NAME_FALLBACK;
exports.UI_WEBVITAL_CLS_SPAN_NAME_FALLBACK = require_fetch.UI_WEBVITAL_CLS_SPAN_NAME_FALLBACK;
exports.UI_WEBVITAL_LCP_SPAN_NAME_FALLBACK = require_fetch.UI_WEBVITAL_LCP_SPAN_NAME_FALLBACK;
exports.UNKNOWN_FUNCTION = require_cacheOrigin.UNKNOWN_FUNCTION;
exports._INTERNAL_CACHE_ORIGIN_META_TAG_NAME = require_cacheOrigin._INTERNAL_CACHE_ORIGIN_META_TAG_NAME;
exports._INTERNAL_FLAG_BUFFER_SIZE = _INTERNAL_FLAG_BUFFER_SIZE;
exports._INTERNAL_MAX_FLAGS_PER_SPAN = _INTERNAL_MAX_FLAGS_PER_SPAN;
exports._INTERNAL_RELEASE_META_TAG_NAME = require_fetch.RELEASE_META_TAG_NAME;
exports._INTERNAL_RENDER_START_META_TAG_NAME = require_cacheOrigin._INTERNAL_RENDER_START_META_TAG_NAME;
exports._INTERNAL_addFeatureFlagToActiveSpan = _INTERNAL_addFeatureFlagToActiveSpan;
exports._INTERNAL_applyBrowserTunnelDefaults = require_fetch.applyBrowserTunnelDefaults;
exports._INTERNAL_captureLog = _INTERNAL_captureLog;
exports._INTERNAL_captureMetric = _INTERNAL_captureMetric;
exports._INTERNAL_captureOptionsSetByUser = captureOptionsSetByUser;
exports._INTERNAL_captureSerializedLog = _INTERNAL_captureSerializedLog;
exports._INTERNAL_captureSerializedMetric = _INTERNAL_captureSerializedMetric;
exports._INTERNAL_clearAiProviderSkips = _INTERNAL_clearAiProviderSkips;
exports._INTERNAL_copyFlagsFromScopeToEvent = _INTERNAL_copyFlagsFromScopeToEvent;
exports._INTERNAL_enhanceErrorWithSentryInfo = require_fetch._enhanceErrorWithSentryInfo;
exports._INTERNAL_filterCookies = filterCookies;
exports._INTERNAL_filterKeyValueData = require_cacheOrigin.filterKeyValueData;
exports._INTERNAL_filterQueryParams = require_fetch.filterQueryParams;
exports._INTERNAL_flushLogsBuffer = _INTERNAL_flushLogsBuffer;
exports._INTERNAL_flushMetricsBuffer = _INTERNAL_flushMetricsBuffer;
exports._INTERNAL_getActiveClient = getActiveClient;
exports._INTERNAL_getTracingHeadersForFetchRequest = require_fetch._INTERNAL_getTracingHeadersForFetchRequest;
exports._INTERNAL_insertFlagToScope = _INTERNAL_insertFlagToScope;
exports._INTERNAL_isClientClosed = require_fetch.isClientClosed;
exports._INTERNAL_normalizeTunnelBasePath = require_fetch.normalizeTunnelBasePath;
exports._INTERNAL_performanceTimeToSeconds = require_cacheOrigin.performanceTimeToSeconds;
exports._INTERNAL_safeDateNow = require_cacheOrigin.safeDateNow;
exports._INTERNAL_safeMathRandom = require_cacheOrigin.safeMathRandom;
exports._INTERNAL_setDeferSegmentSpanCapture = require_cacheOrigin._INTERNAL_setDeferSegmentSpanCapture;
exports._INTERNAL_setSpanForScope = require_cacheOrigin._setSpanForScope;
exports._INTERNAL_shouldSkipAiProviderWrapping = _INTERNAL_shouldSkipAiProviderWrapping;
exports._INTERNAL_skipAiProviderWrapping = _INTERNAL_skipAiProviderWrapping;
exports._INTERNAL_warnIfClientIsActive = warnIfClientIsActive;
exports._INTERNAL_withRandomSafeContext = require_cacheOrigin.withRandomSafeContext;
exports.addAutoIpAddressToSession = addAutoIpAddressToSession;
exports.addBreadcrumb = require_fetch.addBreadcrumb;
exports.addChildSpanToSpan = require_cacheOrigin.addChildSpanToSpan;
exports.addConsoleInstrumentationFilter = addConsoleInstrumentationFilter;
exports.addConsoleInstrumentationHandler = addConsoleInstrumentationHandler;
exports.addContextToFrame = require_cacheOrigin.addContextToFrame;
exports.addEventProcessor = require_cacheOrigin.addEventProcessor;
exports.addExceptionMechanism = require_cacheOrigin.addExceptionMechanism;
exports.addExceptionTypeValue = require_cacheOrigin.addExceptionTypeValue;
exports.addFetchEndInstrumentationHandler = require_fetch.addFetchEndInstrumentationHandler;
exports.addFetchInstrumentationHandler = require_fetch.addFetchInstrumentationHandler;
exports.addGlobalErrorInstrumentationHandler = require_cacheOrigin.addGlobalErrorInstrumentationHandler;
exports.addGlobalUnhandledRejectionInstrumentationHandler = require_cacheOrigin.addGlobalUnhandledRejectionInstrumentationHandler;
exports.addHandler = require_cacheOrigin.addHandler;
exports.addIntegration = require_cacheOrigin.addIntegration;
exports.addItemToEnvelope = require_cacheOrigin.addItemToEnvelope;
exports.addNonEnumerableProperty = require_cacheOrigin.addNonEnumerableProperty;
exports.applyAggregateErrorsToEvent = applyAggregateErrorsToEvent;
exports.applyScopeDataToEvent = require_cacheOrigin.applyScopeDataToEvent;
exports.applySdkMetadata = applySdkMetadata;
exports.baggageHeaderToDynamicSamplingContext = require_cacheOrigin.baggageHeaderToDynamicSamplingContext;
exports.basename = basename;
exports.bindScopeToEmitter = require_cacheOrigin.bindScopeToEmitter;
exports.browserPerformanceTimeOrigin = require_cacheOrigin.browserPerformanceTimeOrigin;
exports.captureBodyFromWinterCGRequest = require_fetch.captureBodyFromWinterCGRequest;
exports.captureCheckIn = captureCheckIn;
exports.captureConsoleIntegration = captureConsoleIntegration;
exports.captureEvent = require_cacheOrigin.captureEvent;
exports.captureException = require_cacheOrigin.captureException;
exports.captureFeedback = captureFeedback;
exports.captureMessage = require_cacheOrigin.captureMessage;
exports.captureSession = require_cacheOrigin.captureSession;
exports.captureSpan = require_cacheOrigin.captureSpan;
exports.checkOrSetAlreadyCaught = require_cacheOrigin.checkOrSetAlreadyCaught;
exports.close = require_cacheOrigin.close;
exports.closeSession = require_cacheOrigin.closeSession;
exports.consoleIntegration = consoleIntegration;
exports.consoleLoggingIntegration = consoleLoggingIntegration;
exports.consoleSandbox = require_cacheOrigin.consoleSandbox;
exports.continueTrace = require_cacheOrigin.continueTrace;
exports.conversationIdIntegration = conversationIdIntegration;
exports.convertSpanLinksForEnvelope = require_cacheOrigin.convertSpanLinksForEnvelope;
exports.convertToPlainObject = require_cacheOrigin.convertToPlainObject;
exports.createAttachmentEnvelopeItem = require_cacheOrigin.createAttachmentEnvelopeItem;
exports.createCheckInEnvelope = require_fetch.createCheckInEnvelope;
exports.createClientReportEnvelope = require_fetch.createClientReportEnvelope;
exports.createConsolaReporter = createConsolaReporter;
exports.createEnvelope = require_cacheOrigin.createEnvelope;
exports.createEventEnvelope = require_fetch.createEventEnvelope;
exports.createEventEnvelopeHeaders = require_cacheOrigin.createEventEnvelopeHeaders;
exports.createFetchIntegration = require_fetch.createFetchIntegration;
exports.createSessionEnvelope = require_fetch.createSessionEnvelope;
exports.createStackParser = require_cacheOrigin.createStackParser;
exports.createTransport = require_fetch.createTransport;
exports.dateTimestampInSeconds = require_cacheOrigin.dateTimestampInSeconds;
exports.debounce = require_cacheOrigin.debounce;
exports.debug = require_cacheOrigin.debug;
exports.dedupeIntegration = dedupeIntegration;
exports.defineIntegration = require_cacheOrigin.defineIntegration;
exports.derefWeakRef = require_cacheOrigin.derefWeakRef;
exports.dirname = dirname;
exports.disabledUntil = require_fetch.disabledUntil;
exports.dropUndefinedKeys = require_cacheOrigin.dropUndefinedKeys;
exports.dsnFromString = require_cacheOrigin.dsnFromString;
exports.dsnToString = require_cacheOrigin.dsnToString;
exports.dynamicSamplingContextToSentryBaggageHeader = require_cacheOrigin.dynamicSamplingContextToSentryBaggageHeader;
exports.endSession = require_cacheOrigin.endSession;
exports.envToBool = envToBool;
exports.envelopeContainsItemType = require_cacheOrigin.envelopeContainsItemType;
exports.envelopeItemTypeToDataCategory = require_cacheOrigin.envelopeItemTypeToDataCategory;
exports.escapeStringForRegex = require_cacheOrigin.escapeStringForRegex;
exports.eventFiltersIntegration = eventFiltersIntegration;
exports.eventFromMessage = require_fetch.eventFromMessage;
exports.eventFromUnknownInput = require_fetch.eventFromUnknownInput;
exports.exceptionFromError = require_fetch.exceptionFromError;
exports.experimentalReportSdkConfigIntegration = experimentalReportSdkConfigIntegration;
exports.extendIntegration = require_cacheOrigin.extendIntegration;
exports.extraErrorDataIntegration = extraErrorDataIntegration;
exports.extractExceptionKeysForMessage = require_cacheOrigin.extractExceptionKeysForMessage;
exports.extractQueryParamsFromUrl = require_fetch.extractQueryParamsFromUrl;
exports.extractTraceparentData = require_cacheOrigin.extractTraceparentData;
exports.featureFlagsIntegration = featureFlagsIntegration;
exports.fill = require_cacheOrigin.fill;
exports.filterCollectedUrl = require_fetch.filterCollectedUrl;
exports.filterCollectedUrlQuery = require_fetch.filterCollectedUrlQuery;
exports.flush = require_cacheOrigin.flush;
exports.fmt = fmt;
exports.forEachEnvelopeItem = require_cacheOrigin.forEachEnvelopeItem;
exports.functionToStringIntegration = functionToStringIntegration;
exports.generateSentryTraceHeader = require_cacheOrigin.generateSentryTraceHeader;
exports.generateSpanId = require_cacheOrigin.generateSpanId;
exports.generateTraceId = require_cacheOrigin.generateTraceId;
exports.generateTraceparentHeader = require_cacheOrigin.generateTraceparentHeader;
exports.getActiveSpan = require_cacheOrigin.getActiveSpan;
exports.getAsyncContextStrategy = require_cacheOrigin.getAsyncContextStrategy;
exports.getBreadcrumbLogLevelFromHttpStatusCode = require_fetch.getBreadcrumbLogLevelFromHttpStatusCode;
exports.getCapturedScopesOnSpan = require_cacheOrigin.getCapturedScopesOnSpan;
exports.getClient = require_cacheOrigin.getClient;
exports.getCombinedScopeData = require_cacheOrigin.getCombinedScopeData;
exports.getContentLengthFromHeaders = require_fetch.getContentLengthFromHeaders;
exports.getCurrentScope = require_cacheOrigin.getCurrentScope;
exports.getDebugImagesForResources = require_cacheOrigin.getDebugImagesForResources;
exports.getDefaultCurrentScope = require_cacheOrigin.getDefaultCurrentScope;
exports.getDefaultIsolationScope = require_cacheOrigin.getDefaultIsolationScope;
exports.getDynamicSamplingContextFromClient = require_cacheOrigin.getDynamicSamplingContextFromClient;
exports.getDynamicSamplingContextFromScope = require_cacheOrigin.getDynamicSamplingContextFromScope;
exports.getDynamicSamplingContextFromSpan = require_cacheOrigin.getDynamicSamplingContextFromSpan;
exports.getEnvelopeEndpointWithUrlEncodedAuth = require_fetch.getEnvelopeEndpointWithUrlEncodedAuth;
exports.getEventDescription = require_cacheOrigin.getEventDescription;
exports.getExternalPropagationContext = require_cacheOrigin.getExternalPropagationContext;
exports.getFilenameToDebugIdMap = require_cacheOrigin.getFilenameToDebugIdMap;
exports.getFilenameToMetadataMap = getFilenameToMetadataMap;
exports.getFramesFromEvent = require_cacheOrigin.getFramesFromEvent;
exports.getFunctionName = require_cacheOrigin.getFunctionName;
exports.getGlobalScope = require_cacheOrigin.getGlobalScope;
exports.getGlobalSingleton = require_cacheOrigin.getGlobalSingleton;
exports.getHostFromHeaders = require_fetch.getHostFromHeaders;
exports.getHttpSpanDetailsFromUrlObject = require_fetch.getHttpSpanDetailsFromUrlObject;
exports.getIntegrationsToSetup = require_cacheOrigin.getIntegrationsToSetup;
exports.getIsolationScope = require_cacheOrigin.getIsolationScope;
exports.getMainCarrier = require_cacheOrigin.getMainCarrier;
exports.getMaxBodyByteLength = require_fetch.getMaxBodyByteLength;
exports.getOriginalFunction = require_cacheOrigin.getOriginalFunction;
exports.getReportDialogEndpoint = require_fetch.getReportDialogEndpoint;
exports.getRootSpan = require_cacheOrigin.getRootSpan;
exports.getSDKSource = require_cacheOrigin.getSDKSource;
exports.getSanitizedUrlString = require_fetch.getSanitizedUrlString;
exports.getSanitizedUrlStringFromUrlObject = require_fetch.getSanitizedUrlStringFromUrlObject;
exports.getSdkMetadataForEnvelopeHeader = require_cacheOrigin.getSdkMetadataForEnvelopeHeader;
exports.getSpanDescendants = require_cacheOrigin.getSpanDescendants;
exports.getSpanStatusFromHttpCode = require_cacheOrigin.getSpanStatusFromHttpCode;
exports.getStatusMessage = require_cacheOrigin.getStatusMessage;
exports.getTraceContextFromScope = require_cacheOrigin.getTraceContextFromScope;
exports.getTraceData = require_cacheOrigin.getTraceData;
exports.getTraceMetaTags = require_fetch.getTraceMetaTags;
exports.getTraceServerTimingHeader = getTraceServerTimingHeader;
exports.getTunnelPath = require_fetch.getTunnelPath;
exports.getUrlDomain = require_fetch.getUrlDomain;
exports.getUrlFragment = require_fetch.getUrlFragment;
exports.getUrlQuery = require_fetch.getUrlQuery;
exports.getVercelEnv = getVercelEnv;
exports.growthbookIntegration = growthbookIntegration;
exports.handleCallbackErrors = require_cacheOrigin.handleCallbackErrors;
exports.handleTunnelRequest = require_fetch.handleTunnelRequest;
exports.hasExternalPropagationContext = require_cacheOrigin.hasExternalPropagationContext;
exports.hasSpanStreamingEnabled = require_cacheOrigin.hasSpanStreamingEnabled;
exports.hasSpansEnabled = require_cacheOrigin.hasSpansEnabled;
exports.headersToDict = require_fetch.headersToDict;
exports.httpHeadersToSpanAttributes = require_fetch.httpHeadersToSpanAttributes;
exports.httpRequestToRequestData = require_fetch.httpRequestToRequestData;
exports.initAndBind = initAndBind;
exports.installedIntegrations = require_cacheOrigin.installedIntegrations;
exports.instrumentFetchRequest = require_fetch.instrumentFetchRequest;
exports.instrumentSupabaseClient = instrumentSupabaseClient;
exports.isAbsolute = isAbsolute;
exports.isAlreadyCaptured = require_cacheOrigin.isAlreadyCaptured;
exports.isBrowser = require_cacheOrigin.isBrowser;
exports.isBrowserBundle = require_cacheOrigin.isBrowserBundle;
exports.isContinuingTrace = require_cacheOrigin.isContinuingTrace;
exports.isDOMError = require_cacheOrigin.isDOMError;
exports.isDOMException = require_cacheOrigin.isDOMException;
exports.isElement = require_cacheOrigin.isElement;
exports.isEnabled = require_cacheOrigin.isEnabled;
exports.isError = require_cacheOrigin.isError;
exports.isErrorEvent = require_cacheOrigin.isErrorEvent;
exports.isEvent = require_cacheOrigin.isEvent;
exports.isInitialized = require_cacheOrigin.isInitialized;
exports.isInstanceOf = require_cacheOrigin.isInstanceOf;
exports.isMatchingPattern = require_cacheOrigin.isMatchingPattern;
exports.isNativeFunction = require_fetch.isNativeFunction;
exports.isObjectLike = require_cacheOrigin.isObjectLike;
exports.isParameterizedString = require_cacheOrigin.isParameterizedString;
exports.isPlainObject = require_cacheOrigin.isPlainObject;
exports.isPrimitive = require_cacheOrigin.isPrimitive;
exports.isRateLimited = require_fetch.isRateLimited;
exports.isRegExp = require_cacheOrigin.isRegExp;
exports.isSentryRequestUrl = require_fetch.isSentryRequestUrl;
exports.isSharedCacheable = isSharedCacheable;
exports.isStatusErrorMessageValid = require_cacheOrigin.isStatusErrorMessageValid;
exports.isString = require_cacheOrigin.isString;
exports.isSyntheticEvent = require_cacheOrigin.isSyntheticEvent;
exports.isThenable = require_cacheOrigin.isThenable;
exports.isTracingSuppressed = require_cacheOrigin.isTracingSuppressed;
exports.isURLObjectRelative = require_fetch.isURLObjectRelative;
exports.isVueViewModel = require_cacheOrigin.isVueViewModel;
exports.join = join;
exports.lastEventId = require_cacheOrigin.lastEventId;
exports.linkedErrorsIntegration = linkedErrorsIntegration;
exports.logSpanEnd = require_cacheOrigin.logSpanEnd;
exports.logSpanStart = require_cacheOrigin.logSpanStart;
exports.logger = logger;
exports.makeDsn = require_cacheOrigin.makeDsn;
exports.makeMultiplexedTransport = makeMultiplexedTransport;
exports.makeOfflineTransport = makeOfflineTransport;
exports.makePromiseBuffer = require_fetch.makePromiseBuffer;
exports.makeSession = require_cacheOrigin.makeSession;
exports.makeWeakRef = require_cacheOrigin.makeWeakRef;
exports.markFunctionWrapped = require_cacheOrigin.markFunctionWrapped;
exports.markSpanAsTracerProviderSpan = require_cacheOrigin.markSpanAsTracerProviderSpan;
exports.matchesTracePropagationTargets = require_fetch.matchesTracePropagationTargets;
exports.maybeInstrument = require_cacheOrigin.maybeInstrument;
exports.mergeBaggageHeaders = require_cacheOrigin.mergeBaggageHeaders;
exports.mergeScopeData = require_cacheOrigin.mergeScopeData;
exports.metrics = metrics;
exports.moduleMetadataIntegration = moduleMetadataIntegration;
exports.normalize = require_cacheOrigin.normalize;
exports.normalizePath = normalizePath;
exports.normalizeToSize = require_cacheOrigin.normalizeToSize;
exports.normalizeUrlToBase = require_cacheOrigin.normalizeUrlToBase;
exports.notifyEventProcessors = require_cacheOrigin.notifyEventProcessors;
exports.objectToBaggageHeader = require_cacheOrigin.objectToBaggageHeader;
exports.objectify = require_cacheOrigin.objectify;
exports.originalConsoleMethods = require_cacheOrigin.originalConsoleMethods;
exports.otelTimeInputToSeconds = require_cacheOrigin.otelTimeInputToSeconds;
exports.parameterize = parameterize;
exports.parseBaggageHeader = require_cacheOrigin.parseBaggageHeader;
exports.parseEnvelope = require_cacheOrigin.parseEnvelope;
exports.parseRetryAfterHeader = require_fetch.parseRetryAfterHeader;
exports.parseSampleRate = require_cacheOrigin.parseSampleRate;
exports.parseSemver = require_cacheOrigin.parseSemver;
exports.parseStackFrames = require_fetch.parseStackFrames;
exports.parseStringToURLObject = require_fetch.parseStringToURLObject;
exports.parseUrl = require_fetch.parseUrl;
exports.prepareEvent = require_cacheOrigin.prepareEvent;
exports.profiler = profiler;
exports.propagationContextFromHeaders = require_cacheOrigin.propagationContextFromHeaders;
exports.registerExternalPropagationContext = require_cacheOrigin.registerExternalPropagationContext;
exports.registerSpanErrorInstrumentation = require_cacheOrigin.registerSpanErrorInstrumentation;
exports.rejectedSyncPromise = require_cacheOrigin.rejectedSyncPromise;
exports.relative = relative;
exports.replaceExports = replaceExports;
exports.requestDataIntegration = requestDataIntegration;
exports.resetInstrumentationHandlers = require_cacheOrigin.resetInstrumentationHandlers;
exports.resolve = resolve;
exports.resolveSourceMapsFeatures = resolveSourceMapsFeatures;
exports.resolvedSyncPromise = require_cacheOrigin.resolvedSyncPromise;
exports.rewriteFramesIntegration = rewriteFramesIntegration;
exports.safeCallback = require_cacheOrigin.safeCallback;
exports.safeJoin = require_cacheOrigin.safeJoin;
exports.safeSetSpanJSONAttributes = require_cacheOrigin.safeSetSpanJSONAttributes;
exports.sampleSpan = require_cacheOrigin.sampleSpan;
exports.sentryTraceFromTraceparent = require_cacheOrigin.sentryTraceFromTraceparent;
exports.serializeEnvelope = require_cacheOrigin.serializeEnvelope;
exports.setAsyncContextStrategy = require_cacheOrigin.setAsyncContextStrategy;
exports.setAttribute = require_cacheOrigin.setAttribute;
exports.setAttributes = require_cacheOrigin.setAttributes;
exports.setCapturedScopesOnSpan = require_cacheOrigin.setCapturedScopesOnSpan;
exports.setContext = require_cacheOrigin.setContext;
exports.setConversationId = require_cacheOrigin.setConversationId;
exports.setCurrentClient = setCurrentClient;
exports.setExtra = require_cacheOrigin.setExtra;
exports.setExtras = require_cacheOrigin.setExtras;
exports.setHttpStatus = require_cacheOrigin.setHttpStatus;
exports.setMeasurement = require_cacheOrigin.setMeasurement;
exports.setNormalizationDepthOverrideHint = require_cacheOrigin.setNormalizationDepthOverrideHint;
exports.setNormalizeStringifier = require_cacheOrigin.setNormalizeStringifier;
exports.setSkipNormalizationHint = require_cacheOrigin.setSkipNormalizationHint;
exports.setTag = require_cacheOrigin.setTag;
exports.setTags = require_cacheOrigin.setTags;
exports.setUser = require_cacheOrigin.setUser;
exports.severityLevelFromString = severityLevelFromString;
exports.shouldContinueTrace = require_cacheOrigin.shouldContinueTrace;
exports.shouldIgnoreSpan = require_cacheOrigin.shouldIgnoreSpan;
exports.shouldPropagateTraceForUrl = require_fetch.shouldPropagateTraceForUrl;
exports.snipLine = require_cacheOrigin.snipLine;
exports.spanIsIgnored = require_cacheOrigin.spanIsIgnored;
exports.spanIsSampled = require_cacheOrigin.spanIsSampled;
exports.spanIsSentrySpan = require_cacheOrigin.spanIsSentrySpan;
exports.spanIsTracerProviderSpan = require_cacheOrigin.spanIsTracerProviderSpan;
exports.spanKindToName = spanKindToName;
exports.spanStreamingIntegration = require_cacheOrigin.spanStreamingIntegration;
exports.spanTimeInputToSeconds = require_cacheOrigin.spanTimeInputToSeconds;
exports.spanToBaggageHeader = require_cacheOrigin.spanToBaggageHeader;
exports.spanToJSON = require_cacheOrigin.spanToJSON;
exports.spanToStaticSpanJSON = require_cacheOrigin.spanToStaticSpanJSON;
exports.spanToTraceContext = require_cacheOrigin.spanToTraceContext;
exports.spanToTraceHeader = require_cacheOrigin.spanToTraceHeader;
exports.stackParserFromStackParserOptions = require_cacheOrigin.stackParserFromStackParserOptions;
exports.startInactiveSpan = require_cacheOrigin.startInactiveSpan$1;
exports.startNewTrace = require_cacheOrigin.startNewTrace;
exports.startSession = require_cacheOrigin.startSession;
exports.startSpan = require_cacheOrigin.startSpan$1;
exports.startSpanManual = require_cacheOrigin.startSpanManual$1;
exports.stringMatchesSomePattern = require_cacheOrigin.stringMatchesSomePattern;
exports.stringify = require_cacheOrigin.stringify;
exports.stringifyForCodeInjection = stringifyForCodeInjection;
exports.stripDataUrlContent = require_fetch.stripDataUrlContent;
exports.stripSentryFramesAndReverse = require_cacheOrigin.stripSentryFramesAndReverse;
exports.stripUrlQueryAndFragment = require_fetch.stripUrlQueryAndFragment;
exports.supabaseIntegration = supabaseIntegration;
exports.supportsDOMException = require_fetch.supportsDOMException;
exports.supportsErrorEvent = require_fetch.supportsErrorEvent;
exports.supportsFetch = require_fetch.supportsFetch;
exports.supportsReferrerPolicy = require_fetch.supportsReferrerPolicy;
exports.suppressTracing = require_cacheOrigin.suppressTracing;
exports.thirdPartyErrorFilterIntegration = thirdPartyErrorFilterIntegration;
exports.timedEventsToMeasurements = require_cacheOrigin.timedEventsToMeasurements;
exports.timestampInSeconds = require_cacheOrigin.timestampInSeconds;
exports.triggerHandlers = require_cacheOrigin.triggerHandlers;
exports.truncate = require_cacheOrigin.truncate;
exports.uniq = uniq;
exports.updateRateLimits = require_fetch.updateRateLimits;
exports.updateSession = require_cacheOrigin.updateSession;
exports.updateSpanName = require_cacheOrigin.updateSpanName;
exports.uuid4 = require_cacheOrigin.uuid4;
exports.waitForTracingChannelBinding = waitForTracingChannelBinding;
exports.warnOnRemovedBuildOptions = warnOnRemovedBuildOptions;
exports.winterCGHeadersToDict = require_fetch.winterCGHeadersToDict;
exports.winterCGRequestToRequestData = require_fetch.winterCGRequestToRequestData;
exports.withActiveSpan = require_cacheOrigin.withActiveSpan;
exports.withIsolationScope = require_cacheOrigin.withIsolationScope;
exports.withMonitor = withMonitor;
exports.withScope = require_cacheOrigin.withScope;
exports.withStaticSpan = require_cacheOrigin.withStaticSpan;
exports.withStreamedSpan = require_cacheOrigin.withStreamedSpan;
exports.zodErrorsIntegration = zodErrorsIntegration;

//# sourceMappingURL=index.js.map