UNPKG

@sentry/node

Version:

Sentry Node SDK using OpenTelemetry for performance instrumentation

4,271 lines • 215 kB
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
// \0rolldown/runtime.js
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __copyProps = (to, from, except, desc) => {
	if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
		key = keys[i];
		if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
			get: ((k) => from[k]).bind(null, key),
			enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
		});
	}
	return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
	value: mod,
	enumerable: true
}) : target, mod));
let _sentry_conventions_attributes = require("@sentry/conventions/attributes");
let _sentry_core = require("@sentry/core");
let _sentry_core_server = require("@sentry/core/server");
let _opentelemetry_api = require("@opentelemetry/api");
let _sentry_server_utils = require("@sentry/server-utils");
let node_events = require("node:events");
let _sentry_conventions_op = require("@sentry/conventions/op");
let node_http = require("node:http");
node_http = __toESM(node_http);
let url = require("url");
let fs = require("fs");
fs = __toESM(fs);
let module$1 = require("module");
module$1 = __toESM(module$1);
let util = require("util");
let node_worker_threads = require("node:worker_threads");
let node_child_process = require("node:child_process");
let node_fs = require("node:fs");
let node_os = require("node:os");
node_os = __toESM(node_os);
let node_path = require("node:path");
let node_util = require("node:util");
node_util = __toESM(node_util);
let node_readline = require("node:readline");
let node_module = require("node:module");
let worker_threads = require("worker_threads");
let node_https = require("node:https");
node_https = __toESM(node_https);
let node_stream = require("node:stream");
let node_zlib = require("node:zlib");
let node_net = require("node:net");
node_net = __toESM(node_net);
let node_tls = require("node:tls");
node_tls = __toESM(node_tls);
let _sentry_opentelemetry = require("@sentry/opentelemetry");
let _sentry_server_runtime_injection_register = require("@sentry/server-runtime-injection/register");
let perf_hooks = require("perf_hooks");
// src/debug-build.ts
/**
* This serves as a build time flag that will be true by default, but false in non-debug builds or if users replace `__SENTRY_DEBUG__` in their generated code.
*
* ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking.
*/
const DEBUG_BUILD = typeof __SENTRY_DEBUG__ === "undefined" || __SENTRY_DEBUG__;
// src/integrations/http/httpServerIntegration.ts
const HTTP_SERVER_INSTRUMENTED_KEY = (0, _opentelemetry_api.createContextKey)("sentry_http_server_instrumented");
const INTEGRATION_NAME$16 = "Http.Server";
/**
* Add a callback to the request object that will be called when the request is started.
* The callback will receive the next function to continue processing the request.
*/
function addStartSpanCallback(request, callback) {
	(0, _sentry_core.addNonEnumerableProperty)(request, "_startSpanCallback", new WeakRef(callback));
}
const _httpServerIntegration = ((options = {}) => {
	const _options = {
		sessions: options.sessions ?? true,
		sessionFlushingDelayMS: options.sessionFlushingDelayMS ?? 6e4,
		maxRequestBodySize: options.maxRequestBodySize,
		spans: false,
		ignoreRequestBody: options.ignoreRequestBody,
		/**
		* Hook called by core's `instrumentServer` to wrap the upstream
		* `emit('request')` call.
		*
		* We use it to extract OTel context from request headers and re-enter
		* the OTel context before the framework sees the request, so subsequent
		* spans (eg from `httpServerSpansIntegration`) attach to the right trace.
		*/
		wrapServerEmitRequest(request, response, normalizedRequest, next) {
			const client = (0, _sentry_core.getClient)();
			if (!client) return next();
			if (_opentelemetry_api.context.active().getValue(HTTP_SERVER_INSTRUMENTED_KEY)) return next();
			const ctx = _opentelemetry_api.propagation.extract(_opentelemetry_api.context.active(), normalizedRequest.headers).setValue(HTTP_SERVER_INSTRUMENTED_KEY, true);
			_opentelemetry_api.context.with(ctx, () => {
				client.emit("httpServerRequest", request, response, normalizedRequest);
				const callback = request._startSpanCallback?.deref();
				if (callback) callback(() => {
					next();
					return true;
				});
				else next();
			});
		}
	};
	return {
		name: INTEGRATION_NAME$16,
		setupOnce() {
			const { [_sentry_core_server.HTTP_ON_SERVER_REQUEST]: onHttpServerRequestStart, [_sentry_core_server.HTTP2_ON_SERVER_STREAM]: onHttp2ServerStreamStart } = (0, _sentry_core_server.getHttpServerSubscriptions)(_options);
			(0, _sentry_server_utils.subscribeDiagnosticsChannel)(_sentry_core_server.HTTP_ON_SERVER_REQUEST, onHttpServerRequestStart);
			(0, _sentry_server_utils.subscribeDiagnosticsChannel)(_sentry_core_server.HTTP2_ON_SERVER_STREAM, onHttp2ServerStreamStart);
		},
		afterAllSetup(client) {
			if (DEBUG_BUILD && client.getIntegrationByName("Http")) _sentry_core.debug.warn("It seems that you have manually added `httpServerIntegration` while `httpIntegration` is also present. Make sure to remove `httpServerIntegration` when adding `httpIntegration`.");
		}
	};
});
/**
* This integration handles request isolation, trace continuation and other core Sentry functionality around incoming http requests
* handled via the node `http` module, or via the compat API of the `http2` module.
*
* This version uses OpenTelemetry for context propagation and span management.
*
* @see {@link ../../light/integrations/httpServerIntegration.ts} for the lightweight version without OpenTelemetry
*/
const httpServerIntegration = (0, _sentry_core.defineIntegration)(_httpServerIntegration);
// src/integrations/http/httpServerSpansIntegration.ts
const INTEGRATION_NAME$15 = "Http.ServerSpans";
const _httpServerSpansIntegration = ((options = {}) => {
	const ignoreStaticAssets = options.ignoreStaticAssets ?? true;
	const ignoreIncomingRequests = options.ignoreIncomingRequests;
	const ignoreStatusCodes = options.ignoreStatusCodes ?? _sentry_core_server.DEFAULT_IGNORE_STATUS_CODES;
	const { onSpanCreated, onSpanEnd } = options;
	return {
		name: INTEGRATION_NAME$15,
		setup(client) {
			if (typeof __SENTRY_TRACING__ !== "undefined" && !__SENTRY_TRACING__) return;
			client.on("httpServerRequest", (_request, _response, normalizedRequest) => {
				const request = _request;
				const response = _response;
				const startSpan = (next) => {
					if (shouldIgnoreSpansForIncomingRequest(request, {
						ignoreStaticAssets,
						ignoreIncomingRequests
					})) {
						DEBUG_BUILD && _sentry_core.debug.log(INTEGRATION_NAME$15, "Skipping span creation for incoming request", request.url);
						return next();
					}
					const fullUrl = normalizedRequest.url || request.url || "/";
					const urlObj = (0, _sentry_core.parseStringToURLObject)(fullUrl);
					const headers = request.headers;
					const userAgent = headers["user-agent"];
					const httpVersion = request.httpVersion;
					const hostname = (0, _sentry_core.getHostFromHeaders)(headers)?.replace(/^(.*)(:[0-9]{1,5})/, "$1") || "localhost";
					const scheme = fullUrl.startsWith("https") ? "https" : "http";
					const requestMethod = normalizedRequest.method || request.method?.toUpperCase();
					const method = requestMethod || "GET";
					const httpTargetWithoutQueryFragment = urlObj ? urlObj.pathname : (0, _sentry_core.stripUrlQueryAndFragment)(fullUrl);
					const bestEffortTransactionName = `${method} ${httpTargetWithoutQueryFragment}`;
					const query = (0, _sentry_core.getUrlQuery)(urlObj?.search);
					const fragment = (0, _sentry_core.getUrlFragment)(urlObj?.hash);
					const span = (0, _sentry_core.startInactiveSpan)({
						name: (0, _sentry_core.hasSpanStreamingEnabled)(client) ? requestMethod || _sentry_core.HTTP_SPAN_NAME_FALLBACK : bestEffortTransactionName,
						attributes: {
							[_sentry_conventions_attributes.SENTRY_KIND]: "server",
							[_sentry_conventions_attributes.SENTRY_OP]: _sentry_conventions_op.HTTP_SERVER,
							[_sentry_conventions_attributes.SENTRY_SEGMENT_NAME_SOURCE]: "url",
							[_sentry_conventions_attributes.SENTRY_ORIGIN]: "auto.http.http_server",
							[_sentry_conventions_attributes.SENTRY_HTTP_PREFETCH]: isKnownPrefetchRequest(request) || void 0,
							[_sentry_conventions_attributes.URL_FULL]: (0, _sentry_core.filterCollectedUrl)(fullUrl, client),
							[_sentry_conventions_attributes.URL_PATH]: urlObj?.pathname ?? httpTargetWithoutQueryFragment,
							[_sentry_conventions_attributes.URL_QUERY]: (0, _sentry_core.filterCollectedUrlQuery)(query, client),
							[_sentry_conventions_attributes.URL_FRAGMENT]: (0, _sentry_core.filterCollectedUrlFragment)(fragment, client),
							[_sentry_conventions_attributes.HTTP_REQUEST_METHOD]: normalizedRequest.method,
							[_sentry_conventions_attributes.USER_AGENT_ORIGINAL]: userAgent,
							[_sentry_conventions_attributes.URL_SCHEME]: scheme,
							[_sentry_conventions_attributes.SERVER_ADDRESS]: hostname,
							[_sentry_conventions_attributes.NETWORK_PROTOCOL_NAME]: "http",
							[_sentry_conventions_attributes.NETWORK_PROTOCOL_VERSION]: httpVersion,
							[_sentry_conventions_attributes.NETWORK_TRANSPORT]: httpVersion?.toUpperCase() === "QUIC" ? "udp" : "tcp",
							[_sentry_conventions_attributes.HTTP_REQUEST_BODY_SIZE]: (0, _sentry_core.getContentLengthFromHeaders)(request.headers),
							...(0, _sentry_core.httpHeadersToSpanAttributes)(normalizedRequest.headers || {}, client.getDataCollectionOptions())
						}
					});
					(0, _sentry_core.safeCallback)(DEBUG_BUILD ? "The `onSpanCreated` callback threw an error:" : "", () => onSpanCreated?.(span, request, response), () => void 0);
					return (0, _sentry_core.withActiveSpan)(span, () => {
						(0, _sentry_core.bindScopeToEmitter)(request);
						(0, _sentry_core.bindScopeToEmitter)(response);
						let isEnded = false;
						function endSpan(status) {
							if (isEnded) return;
							isEnded = true;
							const newAttributes = getIncomingRequestAttributesOnResponse(request, response, client.getDataCollectionOptions().userInfo);
							span.setAttributes(newAttributes);
							span.setStatus(status);
							if (onSpanEnd) (0, _sentry_core.safeCallback)(DEBUG_BUILD ? "The `onSpanEnd` callback threw an error:" : "", () => onSpanEnd(span, request, response), () => void 0);
							span.end();
						}
						response.on("close", () => {
							endSpan((0, _sentry_core.getSpanStatusFromHttpCode)(response.statusCode));
						});
						response.on(node_events.errorMonitor, () => {
							const httpStatus = (0, _sentry_core.getSpanStatusFromHttpCode)(response.statusCode);
							endSpan(httpStatus.code === _sentry_core.SPAN_STATUS_ERROR ? httpStatus : { code: _sentry_core.SPAN_STATUS_ERROR });
						});
						return next();
					});
				};
				addStartSpanCallback(request, startSpan);
			});
		},
		processEvent(event) {
			return (0, _sentry_core_server.processHttpServerTransactionEvent)(event, ignoreStatusCodes);
		},
		afterAllSetup(client) {
			if (!DEBUG_BUILD) return;
			if (client.getIntegrationByName("Http")) _sentry_core.debug.warn("It seems that you have manually added `httpServerSpansIntegration` while `httpIntegration` is also present. Make sure to remove `httpIntegration` when adding `httpServerSpansIntegration`.");
			if (!client.getIntegrationByName("Http.Server")) _sentry_core.debug.error("It seems that you have manually added `httpServerSpansIntegration` without adding `httpServerIntegration`. This is a requiement for spans to be created - please add the `httpServerIntegration` integration.");
		}
	};
});
/**
* This integration emits spans for incoming requests handled via the node `http` module.
* It requires the `httpServerIntegration` to be present.
*/
const httpServerSpansIntegration = (0, _sentry_core.defineIntegration)(_httpServerSpansIntegration);
function isKnownPrefetchRequest(req) {
	return req.headers["next-router-prefetch"] === "1";
}
/**
* Check if a request is for a common static asset that should be ignored by default.
*
* Only exported for tests.
*/
function isStaticAssetRequest(urlPath) {
	const path = (0, _sentry_core.stripUrlQueryAndFragment)(urlPath);
	if (path.match(/\.(ico|png|jpg|jpeg|gif|svg|css|js|woff|woff2|ttf|eot|webp|avif)$/)) return true;
	if (path.match(/^\/(robots\.txt|sitemap\.xml|manifest\.json|browserconfig\.xml)$/)) return true;
	return false;
}
function shouldIgnoreSpansForIncomingRequest(request, { ignoreStaticAssets, ignoreIncomingRequests }) {
	if ((0, _sentry_core.isTracingSuppressed)()) return true;
	const urlPath = request.url;
	const method = request.method?.toUpperCase();
	if (method === "OPTIONS" || method === "HEAD" || !urlPath) return true;
	if (ignoreStaticAssets && method === "GET" && isStaticAssetRequest(urlPath)) return true;
	if ((0, _sentry_core.safeCallback)(DEBUG_BUILD ? "The `ignoreIncomingRequests` callback threw an error, not ignoring the request:" : "", () => !!ignoreIncomingRequests?.(urlPath, request), () => false)) return true;
	return false;
}
function getIncomingRequestAttributesOnResponse(request, response, collectClientAddress) {
	const { socket } = request;
	const { statusCode } = response;
	const newAttributes = {
		[_sentry_conventions_attributes.HTTP_RESPONSE_STATUS_CODE]: statusCode,
		[_sentry_conventions_attributes.HTTP_RESPONSE_STATUS_TEXT]: request.httpVersion === "2.0" ? void 0 : response.statusMessage?.toUpperCase()
	};
	const forwardedAddress = (0, _sentry_core_server.getClientIPAddress)(request.headers);
	if (collectClientAddress) newAttributes[_sentry_conventions_attributes.CLIENT_ADDRESS] = forwardedAddress || socket?.remoteAddress;
	if (socket) {
		const { localAddress, localPort, remoteAddress, remotePort } = socket;
		newAttributes[_sentry_conventions_attributes.SERVER_PORT] = localPort;
		newAttributes[_sentry_conventions_attributes.NETWORK_LOCAL_ADDRESS] = localAddress;
		newAttributes[_sentry_conventions_attributes.NETWORK_LOCAL_PORT] = localPort;
		newAttributes[_sentry_conventions_attributes.CLIENT_PORT] = forwardedAddress ? void 0 : remotePort;
		newAttributes[_sentry_conventions_attributes.NETWORK_PEER_ADDRESS] = collectClientAddress ? remoteAddress : void 0;
		newAttributes[_sentry_conventions_attributes.NETWORK_PEER_PORT] = remotePort;
	}
	return newAttributes;
}
// src/nodeVersion.ts
const NODE_VERSION = (0, _sentry_core.parseSemver)(process.versions.node);
NODE_VERSION.major;
NODE_VERSION.minor;
// src/integrations/http/SentryHttpInstrumentation.ts
const FULLY_SUPPORTS_HTTP_DIAGNOSTICS_CHANNEL = NODE_VERSION.major === 22 && NODE_VERSION.minor >= 12 || NODE_VERSION.major === 23 && NODE_VERSION.minor >= 2 || NODE_VERSION.major >= 24;
/**
* This instruments the http modules for outgoing requests.
* It uses the diagnostics channel if available, otherwise it falls back to monkey-patching.
*
* The instrumentation will start spans, create breadcrumbs, and propagate trace headers in outgoing requests (depending on the settings).
*/
function instrumentHttpOutgoingRequests(instrumentationOptions = {}) {
	const { outgoingRequestApplyCustomAttributes: applyCustomAttributesOnSpan, ...options } = instrumentationOptions;
	const patchOptions = {
		applyCustomAttributesOnSpan,
		...options,
		tracePropagation: options.tracePropagation ?? true,
		spans: options.spans ?? true,
		ignoreOutgoingRequests(url, request) {
			return (0, _sentry_core.isTracingSuppressed)() || !!options.ignoreOutgoingRequests?.(url, (0, _sentry_core_server.getRequestOptions)(request));
		},
		outgoingRequestHook(span, request) {
			options.outgoingRequestHook?.(span, request);
			const originalOnce = request.once;
			request.once = new Proxy(originalOnce, { apply(target, thisArg, args) {
				const [event] = args;
				if (event !== "response") return target.apply(thisArg, args);
				const parentContext = _opentelemetry_api.context.active();
				const requestContext = _opentelemetry_api.trace.setSpan(parentContext, span);
				return _opentelemetry_api.context.with(requestContext, () => {
					return target.apply(thisArg, args);
				});
			} });
		},
		outgoingResponseHook(span, response) {
			options.outgoingResponseHook?.(span, response);
		},
		errorMonitor: node_events.errorMonitor,
		http: node_http
	};
	if (FULLY_SUPPORTS_HTTP_DIAGNOSTICS_CHANNEL) instrumentHttpOutgoingRequestsViaChannel(patchOptions);
	else instrumentHttpOutgoingRequestsViaMonkeyPatching(patchOptions);
}
function instrumentHttpOutgoingRequestsViaChannel(options) {
	const { [_sentry_core_server.HTTP_ON_CLIENT_REQUEST]: onHttpClientRequestCreated } = (0, _sentry_core_server.getHttpClientSubscriptions)(options);
	(0, _sentry_server_utils.subscribeDiagnosticsChannel)(_sentry_core_server.HTTP_ON_CLIENT_REQUEST, onHttpClientRequestCreated);
}
/**
* Instrument outgoing HTTP(S) requests by old-school monkey-patching the `http` module.
* This is the fallback for runtimes that do not fully support the `node:http` client diagnostics channel
* (Node < 22.12).
*/
function instrumentHttpOutgoingRequestsViaMonkeyPatching(options) {
	(0, _sentry_core_server.patchHttpModuleClient)(node_http, options);
}
// src/integrations/http/index.ts
const INTEGRATION_NAME$14 = "Http";
/**
* The http integration instruments Node's internal http and https modules.
* It creates breadcrumbs and spans for outgoing HTTP requests which will be attached to the currently active span.
*/
const httpIntegration = (0, _sentry_core.defineIntegration)((options = {}) => {
	const spans = options.spans ?? true;
	const enableServerSpans = spans && !options.disableIncomingRequestSpans;
	const server = httpServerIntegration(options);
	const serverSpans = httpServerSpansIntegration(options);
	const serverRequestOptions = {
		spans: enableServerSpans ? void 0 : false,
		sessions: options.sessions,
		sessionFlushingDelayMS: options.sessionFlushingDelayMS,
		maxRequestBodySize: options.maxRequestBodySize,
		ignoreRequestBody: options.ignoreRequestBody,
		ignoreIncomingRequests: options.ignoreIncomingRequests,
		ignoreStaticAssets: options.ignoreStaticAssets,
		onSpanCreated: options.onSpanCreated,
		onSpanEnd: options.onSpanEnd
	};
	return {
		name: INTEGRATION_NAME$14,
		serverRequestOptions,
		setup(client) {
			const clientOptions = client.getOptions();
			if (enableServerSpans && (0, _sentry_core.hasSpansEnabled)(clientOptions)) serverSpans.setup(client);
		},
		setupOnce() {
			server.setupOnce();
			instrumentHttpOutgoingRequests({
				breadcrumbs: options.breadcrumbs,
				spans,
				tracePropagation: options.tracePropagation ?? true,
				ignoreOutgoingRequests: options.ignoreOutgoingRequests,
				outgoingRequestHook: (span, request) => {
					const url = (0, _sentry_core_server.getRequestUrlFromClientRequest)(request);
					if (url.startsWith("data:")) {
						const sanitizedUrl = (0, _sentry_core.stripDataUrlContent)(url);
						const client = (0, _sentry_core.getClient)();
						if (!client || !(0, _sentry_core.hasSpanStreamingEnabled)(client)) span.updateName(`${request.method || "GET"} ${sanitizedUrl}`);
						span.setAttributes({ [_sentry_conventions_attributes.URL_FULL]: sanitizedUrl });
					}
					options.outgoingRequestHook?.(span, request);
				},
				outgoingResponseHook: options.outgoingResponseHook,
				outgoingRequestApplyCustomAttributes: options.outgoingRequestApplyCustomAttributes
			});
		},
		processEvent(event) {
			return serverSpans.processEvent(event);
		}
	};
});
// src/integrations/awsLambdaWeb.ts
const INTEGRATION_NAME$13 = "AwsLambdaWeb";
let requestHandled = false;
const _awsLambdaWebIntegration = (() => {
	if (!process.env.AWS_LAMBDA_HTTP_ENDPOINT) return { name: INTEGRATION_NAME$13 };
	const memory = Number(process.env.AWS_LAMBDA_FUNCTION_MEMORY_SIZE) * 1024 * 1024;
	const lambdaContext = {
		memory_size: Number.isFinite(memory) && memory > 0 ? memory : void 0,
		initialization_type: process.env.AWS_LAMBDA_INITIALIZATION_TYPE
	};
	const environmentAttributes = {
		[_sentry_conventions_attributes.FAAS_MAX_MEMORY]: lambdaContext.memory_size,
		[_sentry_conventions_attributes.AWS_LAMBDA_INITIALIZATION_TYPE]: lambdaContext.initialization_type
	};
	return {
		name: INTEGRATION_NAME$13,
		setup(client) {
			client.on("httpServerRequest", (_request, _response, request) => {
				const coldStart = !requestHandled;
				requestHandled = true;
				const requestId = request.headers?.["lambda-web-request-id"];
				const endpointName = request.headers?.["lambda-web-endpoint-name"];
				const scope = (0, _sentry_core.getIsolationScope)();
				scope.setContext("aws.lambda", {
					...scope.getScopeData().contexts["aws.lambda"],
					cold_start: coldStart,
					aws_request_id: typeof requestId === "string" ? requestId : void 0,
					endpoint_name: typeof endpointName === "string" ? endpointName : void 0
				});
			});
		},
		processEvent(event) {
			event.contexts = {
				...event.contexts,
				"aws.lambda": {
					...lambdaContext,
					...event.contexts?.["aws.lambda"]
				}
			};
			return event;
		},
		processSegmentSpan(span) {
			const requestContext = (0, _sentry_core.getIsolationScope)().getScopeData().contexts["aws.lambda"];
			const attributes = { ...environmentAttributes };
			if (typeof requestContext?.cold_start === "boolean") attributes[_sentry_conventions_attributes.FAAS_COLDSTART] = requestContext.cold_start;
			if (typeof requestContext?.aws_request_id === "string") attributes[_sentry_conventions_attributes.FAAS_INVOCATION_ID] = requestContext.aws_request_id;
			if (typeof requestContext?.endpoint_name === "string") attributes[_sentry_conventions_attributes.AWS_LAMBDA_WEB_ENDPOINT_NAME] = requestContext.endpoint_name;
			(0, _sentry_core.safeSetSpanJSONAttributes)(span, attributes);
		}
	};
});
/** Enrich AWS Lambda Web Function spans and error contexts with platform metadata. */
const awsLambdaWebIntegration = (0, _sentry_core.defineIntegration)(_awsLambdaWebIntegration);
// src/utils/outgoingFetchRequest.ts
const SENTRY_TRACE_HEADER = "sentry-trace";
const SENTRY_BAGGAGE_HEADER = "baggage";
const W3C_TRACEPARENT_HEADER = "traceparent";
/**
* Add trace propagation headers to an outgoing fetch/undici request.
*
* Checks if the request URL matches trace propagation targets,
* then injects sentry-trace, traceparent, and baggage headers.
*
* When a `span` is passed (the outgoing `http.client` span), its trace data is propagated so downstream
* services are parented to that span. Without a span, the active scope's trace data is used.
*
* Existing trace headers (e.g. set manually by the user via `getTraceData()`) always take precedence and
* are de-duplicated rather than overwritten, so we never emit two `sentry-trace`/`baggage` entries.
*/
function addTracePropagationHeadersToFetchRequest(request, propagationDecisionMap, span) {
	const url = getAbsoluteUrl$1(request.origin, request.path);
	const { tracePropagationTargets, propagateTraceparent } = (0, _sentry_core.getClient)()?.getOptions() || {};
	if (!(0, _sentry_core.shouldPropagateTraceForUrl)(url, tracePropagationTargets, propagationDecisionMap)) return;
	const spanForTraceHeaders = span && (0, _sentry_core.spanIsIgnored)(span) && (0, _sentry_core.getActiveSpan)() ? void 0 : span;
	const addedHeaders = spanForTraceHeaders ? (0, _sentry_core.withActiveSpan)(spanForTraceHeaders, () => (0, _sentry_core.getTraceData)({ propagateTraceparent })) : (0, _sentry_core.getTraceData)({ propagateTraceparent });
	if (!addedHeaders) return;
	const { "sentry-trace": sentryTrace, baggage, traceparent } = addedHeaders;
	const requestHeaders = Array.isArray(request.headers) ? normalizeUndiciHeaderPairs(request.headers) : stringToArrayHeaders(request.headers);
	_deduplicateArrayHeader(requestHeaders, SENTRY_TRACE_HEADER);
	_deduplicateArrayHeader(requestHeaders, SENTRY_BAGGAGE_HEADER);
	if (propagateTraceparent) _deduplicateArrayHeader(requestHeaders, W3C_TRACEPARENT_HEADER);
	if (!(_findExistingHeaderIndex(requestHeaders, SENTRY_TRACE_HEADER) !== -1)) {
		if (sentryTrace) requestHeaders.push(SENTRY_TRACE_HEADER, sentryTrace);
		if (traceparent && _findExistingHeaderIndex(requestHeaders, "traceparent") === -1) requestHeaders.push("traceparent", traceparent);
		const existingBaggageIndex = _findExistingHeaderIndex(requestHeaders, SENTRY_BAGGAGE_HEADER);
		if (baggage && existingBaggageIndex === -1) requestHeaders.push(SENTRY_BAGGAGE_HEADER, baggage);
		else if (baggage) {
			const existingBaggageValue = requestHeaders[existingBaggageIndex + 1];
			const merged = (0, _sentry_core.mergeBaggageHeaders)(existingBaggageValue, baggage);
			if (merged) requestHeaders[existingBaggageIndex + 1] = merged;
		}
	}
	if (Array.isArray(request.headers)) request.headers.splice(0, request.headers.length, ...requestHeaders);
	else request.headers = arrayToStringHeaders(requestHeaders);
}
/**
* Convert undici’s header array into `[name, value, name, value, ...]` where every value is a string.
*
* Undici v6 uses this shape: `[k1, v1, k2, v2, ...]`. Types allow each `v` to be `string | string[]` when
* that header has multiple values. Sentry’s dedupe/merge helpers expect one string per value slot, so
* multi-value arrays are joined with `', '`. Missing value slots become `''`.
*/
function normalizeUndiciHeaderPairs(headers) {
	const out = [];
	for (let i = 0; i < headers.length; i++) {
		const entry = headers[i];
		if (i % 2 === 0) out.push(typeof entry === "string" ? entry : String(entry));
		else out.push(Array.isArray(entry) ? entry.join(", ") : entry ?? "");
	}
	return out;
}
function stringToArrayHeaders(requestHeaders) {
	const headersArray = requestHeaders.split("\r\n");
	const headers = [];
	for (const header of headersArray) try {
		const colonIndex = header.indexOf(":");
		if (colonIndex === -1) continue;
		const key = header.slice(0, colonIndex).trim();
		const value = header.slice(colonIndex + 1).trim();
		if (key) headers.push(key, value);
	} catch {
		_sentry_core.debug.warn(`Failed to convert string request header to array header: ${header}`);
	}
	return headers;
}
function arrayToStringHeaders(headers) {
	const headerPairs = [];
	for (let i = 0; i < headers.length; i += 2) {
		const key = headers[i];
		const value = headers[i + 1];
		if (!key || value == null) continue;
		headerPairs.push(`${key}: ${value}`);
	}
	if (!headerPairs.length) return "";
	return headerPairs.join("\r\n").concat("\r\n");
}
/**
* For a given header name, if there are multiple entries in the [key, value, key, value, ...] array,
* keep the first entry and remove the rest.
* For baggage, values are merged to preserve all entries but to dedupe sentry- values, and always
* keep the first occurrence of them
*/
function _deduplicateArrayHeader(headers, headerName) {
	let firstIndex = -1;
	for (let i = 0; i < headers.length; i += 2) {
		if (headers[i] !== headerName) continue;
		if (firstIndex === -1) {
			firstIndex = i;
			continue;
		}
		const firstHeaderValue = headers[firstIndex + 1];
		if (headerName === SENTRY_BAGGAGE_HEADER && firstHeaderValue) {
			const merged = (0, _sentry_core.mergeBaggageHeaders)(headers[i + 1], firstHeaderValue);
			if (merged) headers[firstIndex + 1] = merged;
		}
		headers.splice(i, 2);
		i -= 2;
	}
}
/**
* Find the index of an existing header in an array of headers.
* Only take even indices, because headers are in format [key_0, value_0, key_1, value_1, ...]
* otherwise we could match a header _value_ with @param name
*/
function _findExistingHeaderIndex(headers, name) {
	return headers.findIndex((header, i) => i % 2 === 0 && header === name);
}
/** Add a breadcrumb for an outgoing fetch/undici request. */
function addFetchRequestBreadcrumb(request, response) {
	const data = getBreadcrumbData(request);
	const statusCode = response.statusCode;
	const level = (0, _sentry_core.getBreadcrumbLogLevelFromHttpStatusCode)(statusCode);
	(0, _sentry_core.addBreadcrumb)({
		category: "http",
		data: {
			status_code: statusCode,
			...data
		},
		type: "http",
		level
	}, {
		event: "response",
		request,
		response
	});
}
function getBreadcrumbData(request) {
	try {
		const url = getAbsoluteUrl$1(request.origin, request.path);
		const parsedUrl = (0, _sentry_core.parseUrl)(url);
		return {
			url: (0, _sentry_core.getSanitizedUrlString)(parsedUrl),
			[_sentry_conventions_attributes.HTTP_REQUEST_METHOD]: request.method || "GET",
			[_sentry_conventions_attributes.URL_QUERY]: (0, _sentry_core.filterCollectedUrlQuery)((0, _sentry_core.getUrlQuery)(parsedUrl.search)),
			[_sentry_conventions_attributes.URL_FRAGMENT]: (0, _sentry_core.filterCollectedUrlFragment)((0, _sentry_core.getUrlFragment)(parsedUrl.hash))
		};
	} catch {
		return {};
	}
}
/** Get the absolute URL from an origin and path. */
function getAbsoluteUrl$1(origin, path = "/") {
	try {
		return new URL(path, origin).toString();
	} catch {
		const url = `${origin}`;
		if (url.endsWith("/") && path.startsWith("/")) return `${url}${path.slice(1)}`;
		if (!url.endsWith("/") && !path.startsWith("/")) return `${url}/${path}`;
		return `${url}${path}`;
	}
}
// src/integrations/node-fetch/undici-instrumentation.ts
const ATTR_HTTP_REQUEST_METHOD_ORIGINAL = "http.request.method_original";
let _isInstrumented = false;
const spanFromReq = /* @__PURE__ */ new WeakMap();
const ignoreRequestMap = /* @__PURE__ */ new WeakMap();
const propagationDecisionMap = new _sentry_core.LRUMap(100);
/**
* Instrument outgoing HTTP requests made through `undici` or the global `fetch` API: emit `http.client`
* spans, record breadcrumbs, and propagate traces into the outgoing request headers.
*
* Span creation is gated by the `spans` option (defaults to `true`). When spans are disabled, breadcrumbs
* are still recorded and trace propagation headers are still injected (gated by `tracePropagation`).
*
* undici reports its request lifecycle via `diagnostics_channel`, so rather than patching any module we
* subscribe to those channels directly. This is idempotent — subsequent calls are no-ops once the
* channels have been subscribed to, and the config of the first call wins.
*
* A combination of https://github.com/elastic/apm-agent-nodejs and
* https://github.com/gadget-inc/opentelemetry-instrumentations/blob/main/packages/opentelemetry-instrumentation-undici/src/index.ts
*/
function instrumentUndici(config = {}) {
	if (_isInstrumented) return;
	_isInstrumented = true;
	subscribeToChannel("undici:request:create", (message) => onRequestCreated(config, message));
	subscribeToChannel("undici:client:sendHeaders", (message) => onRequestHeaders(config, message));
	subscribeToChannel("undici:request:headers", (message) => onResponseHeaders(config, message));
	subscribeToChannel("undici:request:trailers", (message) => onDone(message));
	subscribeToChannel("undici:request:error", (message) => onError(message));
}
function subscribeToChannel(diagnosticChannel, onMessage) {
	(0, _sentry_server_utils.subscribeDiagnosticsChannel)(diagnosticChannel, onMessage);
}
function parseRequestHeaders(request) {
	const result = /* @__PURE__ */ new Map();
	if (Array.isArray(request.headers)) for (let i = 0; i < request.headers.length; i += 2) {
		const key = request.headers[i];
		const value = request.headers[i + 1];
		if (typeof key === "string" && value !== void 0) result.set(key.toLowerCase(), value);
	}
	else if (typeof request.headers === "string") {
		const headers = request.headers.split("\r\n");
		for (const line of headers) {
			if (!line) continue;
			const colonIndex = line.indexOf(":");
			if (colonIndex === -1) continue;
			const key = line.substring(0, colonIndex).toLowerCase();
			const value = line.substring(colonIndex + 1).trim();
			const allValues = result.get(key);
			if (allValues && Array.isArray(allValues)) allValues.push(value);
			else if (allValues) result.set(key, [allValues, value]);
			else result.set(key, value);
		}
	}
	return result;
}
function onRequestCreated(config, { request }) {
	const url$1 = getAbsoluteUrl(request.origin, request.path);
	const isIgnored = (0, _sentry_core.isSentryRequestUrl)(url$1, (0, _sentry_core.getClient)()) || (0, _sentry_core.safeCallback)(DEBUG_BUILD ? "The `ignoreOutgoingRequests` callback threw an error, not ignoring the request:" : "", () => !!config.ignoreOutgoingRequests?.(url$1), () => false);
	const ignoreForBreadcrumbs = (0, _sentry_core.isTracingSuppressed)() || isIgnored;
	ignoreRequestMap.set(request, ignoreForBreadcrumbs);
	if (!config.spans) {
		if (config.tracePropagation !== false && !ignoreForBreadcrumbs) addTracePropagationHeadersToFetchRequest(request, propagationDecisionMap);
		return;
	}
	if (request.method === "CONNECT" || isIgnored) return;
	let requestUrl;
	try {
		requestUrl = new url.URL(request.path, request.origin);
	} catch (err) {
		DEBUG_BUILD && _sentry_core.debug.warn("could not determine url.full:", err);
		return;
	}
	const urlScheme = requestUrl.protocol.replace(":", "");
	const requestMethod = getRequestMethod(request.method);
	const attributes = {
		[_sentry_conventions_attributes.SENTRY_KIND]: "client",
		[_sentry_conventions_attributes.SENTRY_OP]: _sentry_conventions_op.HTTP_CLIENT,
		[_sentry_conventions_attributes.HTTP_REQUEST_METHOD]: requestMethod,
		[ATTR_HTTP_REQUEST_METHOD_ORIGINAL]: request.method,
		[_sentry_conventions_attributes.URL_FULL]: (0, _sentry_core.filterCollectedUrl)(requestUrl.toString()),
		[_sentry_conventions_attributes.URL_DOMAIN]: requestUrl.hostname || void 0,
		[_sentry_conventions_attributes.URL_PATH]: requestUrl.pathname,
		[_sentry_conventions_attributes.URL_QUERY]: (0, _sentry_core.filterCollectedUrlQuery)((0, _sentry_core.getUrlQuery)(requestUrl.search)),
		[_sentry_conventions_attributes.URL_FRAGMENT]: (0, _sentry_core.filterCollectedUrlFragment)((0, _sentry_core.getUrlFragment)(requestUrl.hash)),
		[_sentry_conventions_attributes.URL_SCHEME]: urlScheme,
		[_sentry_conventions_attributes.SENTRY_ORIGIN]: "auto.http.node_fetch"
	};
	if (url$1.startsWith("data:")) {
		const sanitizedUrl = (0, _sentry_core.stripDataUrlContent)(url$1);
		attributes[_sentry_conventions_attributes.URL_FULL] = sanitizedUrl;
		attributes[_sentry_core.SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME] = `${request.method || "GET"} ${sanitizedUrl}`;
	}
	const schemePorts = {
		https: "443",
		http: "80"
	};
	const serverAddress = requestUrl.hostname;
	const serverPort = requestUrl.port || schemePorts[urlScheme];
	attributes[_sentry_conventions_attributes.SERVER_ADDRESS] = serverAddress;
	if (serverPort && !isNaN(Number(serverPort))) attributes[_sentry_conventions_attributes.SERVER_PORT] = Number(serverPort);
	const userAgentValues = parseRequestHeaders(request).get("user-agent");
	if (userAgentValues) {
		const userAgent = Array.isArray(userAgentValues) ? userAgentValues[userAgentValues.length - 1] : userAgentValues;
		attributes[_sentry_conventions_attributes.USER_AGENT_ORIGINAL] = userAgent;
	}
	const isDataUrl = url$1.startsWith("data:");
	const client = (0, _sentry_core.getClient)();
	let spanName;
	if (requestMethod === "_OTHER") spanName = _sentry_core.HTTP_SPAN_NAME_FALLBACK;
	else if (!!client && (0, _sentry_core.hasSpanStreamingEnabled)(client)) spanName = requestUrl.hostname ? `${requestMethod} ${requestUrl.hostname}` : requestMethod;
	else if (isDataUrl) spanName = `${request.method || "GET"} ${(0, _sentry_core.stripDataUrlContent)(url$1)}`;
	else spanName = `${requestMethod} ${(0, _sentry_core.getSanitizedUrlString)((0, _sentry_core.parseUrl)(requestUrl.toString()))}`;
	const span = (0, _sentry_core.startInactiveSpan)({
		name: spanName,
		attributes,
		onlyIfParent: !client || !(0, _sentry_core.hasSpanStreamingEnabled)(client)
	});
	(0, _sentry_core.safeCallback)(DEBUG_BUILD ? "The `requestHook` callback threw an error:" : "", () => config.requestHook?.(span, request), () => void 0);
	addTracePropagationHeadersToFetchRequest(request, propagationDecisionMap, span);
	spanFromReq.set(request, span);
}
function onRequestHeaders(config, { request, socket }) {
	const span = spanFromReq.get(request);
	if (!span) return;
	const { remoteAddress, remotePort } = socket;
	const spanAttributes = {
		[_sentry_conventions_attributes.NETWORK_PEER_ADDRESS]: remoteAddress,
		[_sentry_conventions_attributes.NETWORK_PEER_PORT]: remotePort
	};
	const client = (0, _sentry_core.getClient)();
	if (config.headersToSpanAttributes?.requestHeaders && client) {
		const headersToAttribs = new Set(config.headersToSpanAttributes.requestHeaders.map((n) => n.toLowerCase()));
		const headersMap = parseRequestHeaders(request);
		const allowlisted = {};
		for (const [name, value] of headersMap.entries()) if (headersToAttribs.has(name)) allowlisted[name] = value;
		Object.assign(spanAttributes, (0, _sentry_core.httpHeadersToSpanAttributes)(allowlisted, client.getDataCollectionOptions()));
	}
	span.setAttributes(spanAttributes);
}
function onResponseHeaders(config, { request, response }) {
	if (config.breadcrumbs !== false && !ignoreRequestMap.get(request)) addFetchRequestBreadcrumb(request, response);
	const span = spanFromReq.get(request);
	if (!span) return;
	const spanAttributes = { [_sentry_conventions_attributes.HTTP_RESPONSE_STATUS_CODE]: response.statusCode };
	(0, _sentry_core.safeCallback)(DEBUG_BUILD ? "The `responseHook` callback threw an error:" : "", () => config.responseHook?.(span, {
		request,
		response
	}), () => void 0);
	const client = (0, _sentry_core.getClient)();
	if (config.headersToSpanAttributes?.responseHeaders && client) {
		const headersToAttribs = /* @__PURE__ */ new Set();
		config.headersToSpanAttributes?.responseHeaders.forEach((name) => headersToAttribs.add(name.toLowerCase()));
		const allowlisted = {};
		for (let idx = 0; idx < response.headers.length; idx = idx + 2) {
			const nameBuf = response.headers[idx];
			const valueBuf = response.headers[idx + 1];
			if (nameBuf === void 0 || valueBuf === void 0) continue;
			const name = nameBuf.toString().toLowerCase();
			if (headersToAttribs.has(name)) (allowlisted[name] ?? (allowlisted[name] = [])).push(valueBuf.toString());
		}
		Object.assign(spanAttributes, (0, _sentry_core.httpHeadersToSpanAttributes)(allowlisted, client.getDataCollectionOptions(), "response"));
	}
	span.setAttributes(spanAttributes);
	if (response.statusCode >= 400) span.setStatus((0, _sentry_core.getSpanStatusFromHttpCode)(response.statusCode));
}
function onDone({ request }) {
	const span = spanFromReq.get(request);
	if (!span) return;
	span.end();
	spanFromReq.delete(request);
}
function onError({ request, error }) {
	const span = spanFromReq.get(request);
	if (!span) return;
	if (error.name === "AbortError" || typeof DOMException !== "undefined" && error instanceof DOMException && error.code === DOMException.ABORT_ERR) {
		span.end();
		spanFromReq.delete(request);
		return;
	}
	span.setStatus({
		code: _sentry_core.SPAN_STATUS_ERROR,
		message: error.message
	});
	span.end();
	spanFromReq.delete(request);
}
function getRequestMethod(original) {
	if (original.toUpperCase() in {
		CONNECT: true,
		OPTIONS: true,
		HEAD: true,
		GET: true,
		POST: true,
		PUT: true,
		PATCH: true,
		DELETE: true,
		TRACE: true,
		QUERY: true
	}) return original.toUpperCase();
	return "_OTHER";
}
function getAbsoluteUrl(origin, path = "/") {
	const url = `${origin}`;
	if (url.endsWith("/") && path.startsWith("/")) return `${url}${path.slice(1)}`;
	if (!url.endsWith("/") && !path.startsWith("/")) return `${url}/${path}`;
	return `${url}${path}`;
}
// src/integrations/node-fetch/index.ts
const _nativeNodeFetchIntegration = ((options = {}) => {
	return {
		name: "NodeFetch",
		setupOnce() {
			const clientOptions = (0, _sentry_core.getClient)()?.getOptions();
			instrumentUndici({
				...options,
				spans: _shouldInstrumentSpans(options, clientOptions)
			});
		}
	};
});
/**
* Instrument outgoing fetch requests made through the native node `fetch` API.
* This emits (depending on the integration options) spans and breadcrumbs, as well as injecting trace propagation headers into the request.
*/
const nativeNodeFetchIntegration = (0, _sentry_core.defineIntegration)(_nativeNodeFetchIntegration);
function _shouldInstrumentSpans(options, clientOptions = {}) {
	return options.spans ?? (0, _sentry_core.hasSpansEnabled)(clientOptions);
}
// src/integrations/fs/vendored/constants.ts
const PROMISE_FUNCTIONS = [
	"access",
	"appendFile",
	"chmod",
	"chown",
	"copyFile",
	"cp",
	"lchown",
	"link",
	"lstat",
	"lutimes",
	"mkdir",
	"mkdtemp",
	"open",
	"opendir",
	"readdir",
	"readFile",
	"readlink",
	"realpath",
	"rename",
	"rm",
	"rmdir",
	"stat",
	"symlink",
	"truncate",
	"unlink",
	"utimes",
	"writeFile"
];
const CALLBACK_FUNCTIONS = [
	"access",
	"appendFile",
	"chmod",
	"chown",
	"copyFile",
	"cp",
	"exists",
	"lchown",
	"link",
	"lstat",
	"lutimes",
	"mkdir",
	"mkdtemp",
	"open",
	"opendir",
	"readdir",
	"readFile",
	"readlink",
	"realpath",
	"realpath.native",
	"rename",
	"rm",
	"rmdir",
	"stat",
	"symlink",
	"truncate",
	"unlink",
	"utimes",
	"writeFile"
];
const SYNC_FUNCTIONS = [
	"accessSync",
	"appendFileSync",
	"chmodSync",
	"chownSync",
	"copyFileSync",
	"cpSync",
	"existsSync",
	"lchownSync",
	"linkSync",
	"lstatSync",
	"lutimesSync",
	"mkdirSync",
	"mkdtempSync",
	"opendirSync",
	"openSync",
	"readdirSync",
	"readFileSync",
	"readlinkSync",
	"realpathSync",
	"realpathSync.native",
	"renameSync",
	"rmdirSync",
	"rmSync",
	"statSync",
	"symlinkSync",
	"truncateSync",
	"unlinkSync",
	"utimesSync",
	"writeFileSync"
];
// src/integrations/fs/vendored/utils.ts
function splitTwoLevels(functionName) {
	const memberParts = functionName.split(".");
	if (memberParts.length > 1) {
		if (memberParts.length !== 2) throw Error(`Invalid member function name ${functionName}`);
		return memberParts;
	} else return [functionName];
}
function indexFs(fs, member) {
	if (!member) throw new Error(JSON.stringify({ member }));
	const [functionName1, functionName2] = splitTwoLevels(member);
	if (functionName2) return {
		objectToPatch: fs[functionName1],
		functionNameToPatch: functionName2
	};
	else return {
		objectToPatch: fs,
		functionNameToPatch: functionName1
	};
}
// src/integrations/fs/vendored/instrumentation.ts
const moduleExports = module$1;
const syncBuiltinESMExports = moduleExports.default?.syncBuiltinESMExports ?? moduleExports.syncBuiltinESMExports;
const SPAN_ORIGIN = "auto.file.fs";
const SPAN_OP = _sentry_conventions_op.FILE;
const FS_OPERATIONS_WITH_OLD_PATH_NEW_PATH = ["rename", "renameSync"];
const FS_OPERATIONS_WITH_SRC_DEST = [
	"copyFile",
	"cp",
	"copyFileSync",
	"cpSync"
];
const FS_OPERATIONS_WITH_EXISTING_PATH_NEW_PATH = ["link", "linkSync"];
const FS_OPERATIONS_WITH_PREFIX = ["mkdtemp", "mkdtempSync"];
const FS_OPERATIONS_WITH_TARGET_PATH = ["symlink", "symlinkSync"];
const FS_OPERATIONS_WITH_PATH_ARG = [
	"access",
	"appendFile",
	"chmod",
	"chown",
	"exists",
	"mkdir",
	"lchown",
	"lstat",
	"lutimes",
	"open",
	"opendir",
	"readdir",
	"readFile",
	"readlink",
	"realpath",
	"realpath.native",
	"rm",
	"rmdir",
	"stat",
	"truncate",
	"unlink",
	"utimes",
	"writeFile",
	"accessSync",
	"appendFileSync",
	"chmodSync",
	"chownSync",
	"existsSync",
	"lchownSync",
	"lstatSync",
	"lutimesSync",
	"opendirSync",
	"mkdirSync",
	"openSync",
	"readdirSync",
	"readFileSync",
	"readlinkSync",
	"realpathSync",
	"realpathSync.native",
	"rmdirSync",
	"rmSync",
	"statSync",
	"truncateSync",
	"unlinkSync",
	"utimesSync",
	"writeFileSync"
];
/**
* Builds the span attributes for a given `fs` operation, optionally including the file path arguments.
*/
function getSpanAttributes(functionName, args, config) {
	const attributes = {
		[_sentry_conventions_attributes.SENTRY_OP]: SPAN_OP,
		[_sentry_conventions_attributes.SENTRY_ORIGIN]: SPAN_ORIGIN
	};
	if (!config.recordFilePaths) return attributes;
	if (typeof args[0] === "string" && FS_OPERATIONS_WITH_PATH_ARG.includes(functionName)) attributes["path_argument"] = args[0];
	else if (typeof args[0] === "string" && typeof args[1] === "string") {
		if (FS_OPERATIONS_WITH_TARGET_PATH.includes(functionName)) {
			attributes["target_argument"] = args[0];
			attributes["path_argument"] = args[1];
		} else if (FS_OPERATIONS_WITH_EXISTING_PATH_NEW_PATH.includes(functionName)) {
			attributes["existing_path_argument"] = args[0];
			attributes["new_path_argument"] = args[1];
		} else if (FS_OPERATIONS_WITH_SRC_DEST.includes(functionName)) {
			attributes["src_argument"] = args[0];
			attributes["dest_argument"] = args[1];
		} else if (FS_OPERATIONS_WITH_OLD_PATH_NEW_PATH.includes(functionName)) {
			attributes["old_path_argument"] = args[0];
			attributes["new_path_argument"] = args[1];
		}
	} else if (typeof args[0] === "string" && FS_OPERATIONS_WITH_PREFIX.includes(functionName)) attributes["prefix_argument"] = args[0];
	return attributes;
}
/**
* This is important for 2-level functions like `realpath.native` to retain the 2nd-level
* when patching the 1st-level.
*/
function patchedFunctionWithOriginalProperties(patchedFunction, original) {
	return Object.assign(patchedFunction, original);
}
const _patched = /* @__PURE__ */ new WeakMap();
function _patchMethod(obj, name, wrapper) {
	const original = obj[name];
	if (typeof original !== "function") return;
	let patched = _patched.get(obj);
	if (!patched) {
		patched = /* @__PURE__ */ new Set();
		_patched.set(obj, patched);
	}
	if (patched.has(name)) return;
	patched.add(name);
	obj[name] = wrapper(original);
}
function _patchSyncFunction(functionName, original, config) {
	const patchedFunction = function(...args) {
		const attributes = getSpanAttributes(functionName, args, config);
		return (0, _sentry_core.startSpan)({
			name: `fs.${functionName}`,
			onlyIfParent: true,
			attributes
		}, (span) => {
			try {
				return (0, _sentry_core.suppressTracing)(() => original.apply(this, args));
			} catch (error) {
				recordError(span, error, config);
				throw error;
			}
		});
	};
	return patchedFunctionWithOriginalProperties(patchedFunction, original);
}
function _patchCallbackFunction(functionName, original, config) {
	const patchedFunction = function(...args) {
		const lastIdx = args.length - 1;
		const cb = args[lastIdx];
		if (typeof cb !== "function") return original.apply(this, args);
		const attributes = getSpanAttributes(functionName, args, config);
		const span = (0, _sentry_core.startInactiveSpan)({
			name: `fs.${functionName}`,
			onlyIfParent: true,
			attributes
		});
		const parentSpan = (0, _sentry_core.getActiveSpan)();
		args[lastIdx] = function(...cbArgs) {
			const error = cbArgs[0];
			if (error) recordError(span, error, config);
			span.end();
			if (parentSpan) return (0, _sentry_core.withActiveSpan)(parentSpan, () => cb.apply(this, cbArgs));
			return cb.apply(this, cbArgs);
		};
		try {
			return (0, _sentry_core.suppressTracing)(() => original.apply(this, args));
		} catch (error) {
			recordError(span, error, config);
			span.end();
			throw error;
		}
	};
	return patchedFunctionWithOriginalProperties(patchedFunction, original);
}
function _patchExistsCallbackFunction(original, config) {
	const functionName = "exists";
	const patchedFunction = function(...args) {
		const lastIdx = args.length - 1;
		const cb = args[lastIdx];
		if (typeof cb !== "function") return original.apply(this, args);
		const attributes = getSpanAttributes(functionName, args, config);
		const span = (0, _sentry_core.startInactiveSpan)({
			name: `fs.${functionName}`,
			onlyIfParent: true,
			attributes
		});
		const parentSpan = (0, _sentry_core.getActiveSpan)();
		args[lastIdx] = function(...cbArgs) {
			span.end();
			if (parentSpan) return (0, _sentry_core.withActiveSpan)(parentSpan, () => cb.apply(this, cbArgs));
			return cb.apply(this, cbArgs);
		};
		try {
			return (0, _sentry_core.suppressTracing)(() => original.apply(this, args));
		} catch (error) {
			recordError(span, error, config);
			span.end();
			throw error;
		}
	};
	const functionWithOriginalProperties = patchedFunctionWithOriginalProperties(patchedFunction, original);
	const promisified = function(path) {
		return new Promise((resolve) => functionWithOriginalProperties(path, resolve));
	};
	Object.defineProperty(promisified, "name", { value: functionName });
	Object.defineProperty(functionWithOriginalProperties, util.promisify.custom, { value: promisified });
	return functionWithOriginalProperties;
}
function _patchPromiseFunction(functionName, original, config) {
	const patchedFunction = async function(...args) {
		const attributes = getSpanAttributes(functionName, args, config);
		return (0, _sentry_core.startSpan)({
			name: `fs.${functionName}`,
			onlyIfParent: true,
			attributes
		}, async (span) => {
			try {
				return await (0, _sentry_core.suppressTracing)(() => original.apply(this, args));
			} catch (error) {
				recordError(span, error, config);
				throw error;
			}
		});
	};
	return patchedFunctionWithOriginalProperties(patchedFunction, original);
}
function enableFsInstrumentation(config = {}) {
	for (const fName of SYNC_FUNCTIONS) {
		const { objectToPatch, functionNameToPatch } = indexFs(fs.default, fName);
		_patchMethod(objectToPatch, functionNameToPatch, (original) => _patchSyncFunction(fName, original, config));
	}
	for (const fName of CALLBACK_FUNCTIONS) {
		const { objectToPatch, functionNameToPatch } = indexFs(fs.default, fName);
		if (fName === "exists") _patchMethod(objectToPatch, functionNameToPatch, (original) => _patchExistsCallbackFunction(original, config));
		else _patchMethod(objectToPatch, functionNameToPatch, (original) => _patchCallbackFunction(fName, original, config));
	}
	const fsPromises = fs.default.promises;
	for (const fName of PROMISE_FUNCTIONS) _patchMethod(fsPromises, fName, (original) => _patchPromiseFunction(fName, original, config));
	try {
		syncBuiltinESMExports?.();
	} catch {}
}
/**
* Sets the error status on the span and, if configured, records the error type as a span attribute.
*/
function recordError(span, error, config) {
	span.setStatus({
		code: _sentry_core.SPAN_STATUS_ERROR,
		message: "internal_error"
	});
	if (config.recordErrorMessagesAsSpanAttributes && error instanceof Error) span.setAttribute(_sentry_conventions_attributes.ERROR_TYPE, error.code ?? error.name);
}
// src/integrations/fs/index.ts
const INTEGRATION_NAME$12 = "FileSystem";
/**
* This integration will create spans for `fs` API operations, like reading and writing files.
*
* **WARNING:** This integration may add significant overhead to your application. Especially in scenarios with a lot of
* file I/O, like for example when running a framework dev server, including this integration can massively slow down
* your application.
*
* @param options Configuration for this integration.
*/
const fsIntegration = (0, _sentry_core.defineIntegration)((options = {}) => {
	return {
		name: INTEGRATION_NAME$12,
		setupOnce() {
			setImmediate(() => enableFsInstrumentation(options));
		}
	};
});
// src/integrations/tracing/koa.ts
/**
* Add a Koa error handler to capture errors to Sentry.
*
* @deprecated The error handler is now registered automatically when the Koa app
* starts (via the orchestrion `koa` instrumentation), so calling this is no
* longer necessary. It remains a safe, idempotent operation, and is kept for
* setups where auto-registration is unavailable. This will be removed in a
* future major version.
*
* @param app The Koa app instance
*
* @example
* ```javascript
* const Sentry = require('@sentry/node');
* const Koa = require("koa");
*
* const app = new Koa();
*
* // Add your routes, etc.
*
* app.listen(3000);
* ```
*/
const setupKoaErrorHandler = (app) => {
	(0, _sentry_server_utils.attachKoaErrorHandler)(app);
};
// src/integrations/featureFlagShims/launchDarkly.ts
/**
* This is a shim for the LaunchDarkly integration.
* We need this in order to not throw runtime errors when accidentally importing this on the server through a meta framework like Next.js.
*/
const launchDarklyIntegrationShim = (0, _sentry_core.defineIntegration)((_options) => {
	if (!(0, _sentry_core.isBrowser)()) (0, _sentry_core.consoleSandbox)(() => {
		console.warn("The launchDarklyIntegration() can only be used in the browser.");
	});
	return { name: "LaunchDarkly" };
});
/**
* This is a shim for the LaunchDarkly flag used handler.
*/
function buildLaunchDarklyFlagUsedHandlerShim() {
	if (!(0, _sentry_core.isBrowser)()) (0, _sentry_core.consoleSandbox)(() => {
		console.warn("The buildLaunchDarklyFlagUsedHandler() can only be used in the browser.");
	});
	return {
		name: "sentry-flag-auditor",
		type: "flag-used",
		synchronous: true,
		method: () => null
	};
}
// src/integrations/featureFlagShims/openFeature.ts
/**
* This is a shim for the OpenFeature integration.
* We need this in order to not throw runtime errors when accidentally importing this on the server through a meta framework like Next.js.
*/
const openFeatureIntegrationShim = (0, _sentry_core.defineIntegration)((_options) => {
	if (!(0, _sentry_core.isBrowser)()) (0, _sentry_core.consoleSandbox)(() => {
		console.warn("The openFeatureIntegration() can only be used in the browser.");
	});
	return { name: "OpenFeature" };
});
/**
* This is a shim for the OpenFeature integration hook.
*/
var OpenFeatureIntegrationHookShim = class {
	/**
	*
	*/
	constructor() {
		if (!(0, _sentry_core.isBrowser)()) (0, _sentry_core.consoleSandbox)(() => {
			console.warn("The OpenFeatureIntegrationHook can only be used in the browser.");
		});
	}
	/**
	*
	*/
	after() {}
	/**
	*
	*/
	error() {}
};
// src/integrations/featureFlagShims/statsig.ts
/**
* This is a shim for the Statsig integration.
* We need this in order to not throw runtime errors when accidentally importing this on the server through a meta framework like Next.js.
*/
const statsigIntegrationShim = (0, _sentry_core.defineIntegration)((_options) => {
	if (!(0, _sentry_core.isBrowser)()) (0, _sentry_core.consoleSandbox)(() => {
		console.warn("The statsigIntegration() can only be used in the browser.");
	});
	return { name: "Statsig" };
});
// src/integrations/featureFlagShims/unleash.ts
/**
* This is a shim for the Unleash integration.
* We need this in order to not throw runtime errors when accidentally importing this on the server through a meta framework like Next.js.
*/
const unleashIntegrationShim = (0, _sentry_core.defineIntegration)((_options) => {
	if (!(0, _sentry_core.isBrowser)()) (0, _sentry_core.consoleSandbox)(() => {
		console.warn("The unleashIntegration() can only be used in the browser.");
	});
	return { name: "Unleash" };
});
// src/integrations/featureFlagShims/growthbook.ts
/**
* Re-export the core GrowthBook integration for Node.js usage.
* The core integration is runtime-agnostic and works in both browser and Node environments.
*/
const growthbookIntegrationShim = _sentry_core.growthbookIntegration;
// src/integrations/childProcess.ts
const INTEGRATION_NAME$11 = "ChildProcess";
/**
* Capture breadcrumbs and events for child processes.
* For worker thread events, use `workerThreadsIntegration()` instead.
*/
const childProcessIntegration = (0, _sentry_core.defineIntegration)((options = {}) => {
	return {
		name: INTEGRATION_NAME$11,
		setup() {
			(0, _sentry_server_utils.subscribeDiagnosticsChannel)("child_process", (event) => {
				if ((0, _sentry_core.isObjectLike)(event) && "process" in event) captureChildProcessEvents(event.process, options);
			});
		}
	};
});
function captureChildProcessEvents(child, options) {
	let hasExited = false;
	let data;
	child.on("spawn", () => {
		if (child.spawnfile === "/usr/bin/sw_vers") {
			hasExited = true;
			return;
		}
		data = { spawnfile: child.spawnfile };
		if (options.includeChildProcessArgs) data.spawnargs = child.spawnargs;
	}).on("exit", (code) => {
		if (!hasExited) {
			hasExited = true;
			if (code !== null && code !== 0) (0, _sentry_core.addBreadcrumb)({
				category: "child_process",
				message: `Child process exited with code '${code}'`,
				level: code === 0 ? "info" : "warning",
				data
			});
		}
	}).on("error", (error) => {
		if (!hasExited) {
			hasExited = true;
			(0, _sentry_core.addBreadcrumb)({
				category: "child_process",
				message: `Child process errored with '${error.message}'`,
				level: "error",
				data
			});
		}
	});
}
// src/integrations/console.ts
/**
* Node-specific console integration that captures breadcrumbs and handles
* the AWS Lambda runtime replacing console methods after our patch.
*
* In Lambda, console methods are patched via `Object.defineProperty` so that
* external replacements (by the Lambda runtime) are absorbed as the delegate
* while our wrapper stays in place. Outside Lambda, this delegates entirely
* to the core `consoleIntegration` which uses the simpler `fill`-based patch.
*/
const consoleIntegration = (0, _sentry_core.defineIntegration)((options = {}) => {
	return {
		name: "Console",
		setup(client) {
			if (process.env.LAMBDA_TASK_ROOT) (0, _sentry_core.maybeInstrument)("console", instrumentConsoleLambda);
			(0, _sentry_core.consoleIntegration)({
				...options,
				filter: [...options.filter || [], "[DEP0205] DeprecationWarning"]
			}).setup?.(client);
		}
	};
});
/**
* NOTE: This currently ignores the filter option.
* We can revisit this later.
*/
function instrumentConsoleLambda() {
	const consoleObj = _sentry_core.GLOBAL_OBJ?.console;
	if (!consoleObj) return;
	_sentry_core.CONSOLE_LEVELS.forEach((level) => {
		if (level in consoleObj) patchWithDefineProperty(consoleObj, level);
	});
}
function patchWithDefineProperty(consoleObj, level) {
	const nativeMethod = consoleObj[level];
	_sentry_core.originalConsoleMethods[level] = nativeMethod;
	let delegate = nativeMethod;
	let savedDelegate;
	let isExecuting = false;
	const wrapper = function(...args) {
		if (isExecuting) {
			nativeMethod.apply(consoleObj, args);
			return;
		}
		isExecuting = true;
		try {
			(0, _sentry_core.triggerHandlers)("console", {
				args,
				level
			});
			delegate.apply(consoleObj, args);
		} finally {
			isExecuting = false;
		}
	};
	(0, _sentry_core.markFunctionWrapped)(wrapper, nativeMethod);
	const sandboxBypass = nativeMethod.bind(consoleObj);
	_sentry_core.originalConsoleMethods[level] = sandboxBypass;
	try {
		let current = wrapper;
		Object.defineProperty(consoleObj, level, {
			configurable: true,
			enumerable: true,
			get() {
				return current;
			},
			set(newValue) {
				if (newValue === wrapper) {
					if (savedDelegate !== void 0) {
						delegate = savedDelegate;
						savedDelegate = void 0;
					}
					current = wrapper;
				} else if (newValue === sandboxBypass) {
					savedDelegate = delegate;
					current = sandboxBypass;
				} else if (typeof newValue === "function" && !newValue.__sentry_original__) {
					delegate = newValue;
					current = wrapper;
				} else current = newValue;
			}
		});
	} catch {
		(0, _sentry_core.fill)(consoleObj, level, function(originalConsoleMethod) {
			_sentry_core.originalConsoleMethods[level] = originalConsoleMethod;
			return function(...args) {
				(0, _sentry_core.triggerHandlers)("console", {
					args,
					level
				});
				_sentry_core.originalConsoleMethods[level]?.apply(this, args);
			};
		});
	}
}
// src/integrations/context.ts
const readFileAsync = (0, node_util.promisify)(node_fs.readFile);
const readDirAsync = (0, node_util.promisify)(node_fs.readdir);
const INTEGRATION_NAME$10 = "Context";
const _nodeContextIntegration = ((options = {}) => {
	const _options = {
		app: true,
		os: true,
		device: true,
		culture: true,
		cloudResource: true,
		...options
	};
	const appContext = _options.app ? getAppContext() : void 0;
	const deviceContext = _options.device ? getDeviceContext(_options.device) : void 0;
	const cultureContext = _options.culture ? getCultureContext() : void 0;
	const cloudResourceContext = _options.cloudResource ? getCloudResourceContext() : void 0;
	const osContextPromise = _options.os ? getOsContext() : void 0;
	const cachedSpanAttributes = {
		[_sentry_conventions_attributes.PROCESS_RUNTIME_ENGINE_NAME]: "v8",
		[_sentry_conventions_attributes.PROCESS_RUNTIME_ENGINE_VERSION]: process.versions.v8,
		...contextsToSpanAttributes({
			app: appContext,
			device: deviceContext,
			culture: cultureContext,
			cloud_resource: cloudResourceContext
		})
	};
	if (osContextPromise) osContextPromise.then((osCtx) => Object.assign(cachedSpanAttributes, contextsToSpanAttributes({ os: osCtx }))).catch(() => {});
	const contextsPromise = (async () => {
		const contexts = {};
		if (osContextPromise) contexts.os = await osContextPromise;
		if (appContext) contexts.app = appContext;
		if (deviceContext) contexts.device = deviceContext;
		if (cultureContext) contexts.culture = cultureContext;
		if (cloudResourceContext) contexts.cloud_resource = cloudResourceContext;
		return contexts;
	})();
	async function addContext(event) {
		const updatedContext = _updateContext(await contextsPromise);
		event.contexts = {
			...event.contexts,
			app: {
				...updatedContext.app,
				...event.contexts?.app
			},
			os: {
				...updatedContext.os,
				...event.contexts?.os
			},
			device: {
				...updatedContext.device,
				...event.contexts?.device
			},
			culture: {
				...updatedContext.culture,
				...event.contexts?.culture
			},
			cloud_resource: {
				...updatedContext.cloud_resource,
				...event.contexts?.cloud_resource
			}
		};
		return event;
	}
	return {
		name: INTEGRATION_NAME$10,
		processEvent(event) {
			return addContext(event);
		},
		processSegmentSpan(span) {
			(0, _sentry_core.safeSetSpanJSONAttributes)(span, cachedSpanAttributes);
			(0, _sentry_core.safeSetSpanJSONAttributes)(span, getDynamicSpanAttributes(appContext, deviceContext));
		}
	};
});
/**
* Capture context about the environment and the device that the client is running on, to events.
*/
const nodeContextIntegration = (0, _sentry_core.defineIntegration)(_nodeContextIntegration);
/**
* Updates the context with dynamic values that can change
*/
function _updateContext(contexts) {
	if (contexts.app?.app_memory) contexts.app.app_memory = process.memoryUsage().rss;
	if (contexts.app?.free_memory && typeof process.availableMemory === "function") {
		const freeMemory = process.availableMemory();
		if (freeMemory != null) contexts.app.free_memory = freeMemory;
	}
	if (contexts.device?.free_memory) contexts.device.free_memory = node_os.freemem();
	return contexts;
}
function contextsToSpanAttributes(contexts) {
	const attrs = {};
	const { app, device, os: osCtx, culture, cloud_resource } = contexts;
	if (app) {
		if (app.app_start_time) attrs[_sentry_conventions_attributes.APP_START_TIME] = app.app_start_time;
	}
	if (device) {
		if (device.arch) attrs[_sentry_conventions_attributes.DEVICE_ARCHS] = [device.arch];
		if (device.boot_time) attrs[_sentry_conventions_attributes.DEVICE_BOOT_TIME] = device.boot_time;
		if (device.memory_size != null) attrs[_sentry_conventions_attributes.DEVICE_MEMORY_SIZE] = device.memory_size;
		if (device.processor_count != null) attrs[_sentry_conventions_attributes.DEVICE_PROCESSOR_COUNT] = device.processor_count;
		if (device.cpu_description) attrs[_sentry_conventions_attributes.DEVICE_CPU_DESCRIPTION] = device.cpu_description;
		if (device.processor_frequency != null) attrs[_sentry_conventions_attributes.DEVICE_PROCESSOR_FREQUENCY] = device.processor_frequency;
	}
	if (osCtx) {
		if (osCtx.name) attrs[_sentry_conventions_attributes.OS_NAME] = osCtx.name;
		if (osCtx.version) attrs[_sentry_conventions_attributes.OS_VERSION] = osCtx.version;
		if (osCtx.kernel_version) attrs[_sentry_conventions_attributes.OS_KERNEL_VERSION] = osCtx.kernel_version;
		if (osCtx.build) attrs[_sentry_conventions_attributes.OS_BUILD] = osCtx.build;
	}
	if (culture) {
		if (culture.locale) attrs[_sentry_conventions_attributes.CULTURE_LOCALE] = culture.locale;
		if (culture.timezone) attrs[_sentry_conventions_attributes.CULTURE_TIMEZONE] = culture.timezone;
	}
	if (cloud_resource) {
		for (const [key, value] of Object.entries(cloud_resource)) if (value != null) attrs[key] = value;
	}
	return attrs;
}
function getDynamicSpanAttributes(appContext, deviceContext) {
	const attrs = {};
	if (appContext) {
		attrs["app.memory"] = process.memoryUsage().rss;
		if (typeof process.availableMemory === "function") {
			const freeMemory = process.availableMemory();
			if (freeMemory != null) attrs["app.free_memory"] = freeMemory;
		}
	}
	if (deviceContext?.free_memory != null) attrs[_sentry_conventions_attributes.DEVICE_FREE_MEMORY] = node_os.freemem();
	return attrs;
}
/**
* Returns the operating system context.
*
* Based on the current platform, this uses a different strategy to provide the
* most accurate OS information. Since this might involve spawning subprocesses
* or accessing the file system, this should only be executed lazily and cached.
*
*  - On macOS (Darwin), this will execute the `sw_vers` utility. The context
*    has a `name`, `version`, `build` and `kernel_version` set.
*  - On Linux, this will try to load a distribution release from `/etc` and set
*    the `name`, `version` and `kernel_version` fields.
*  - On all other platforms, only a `name` and `version` will be returned. Note
*    that `version` might actually be the kernel version.
*/
async function getOsContext() {
	const platformId = node_os.platform();
	switch (platformId) {
		case "darwin": return getDarwinInfo();
		case "linux": return getLinuxInfo();
		default: return {
			name: PLATFORM_NAMES[platformId] || platformId,
			version: node_os.release()
		};
	}
}
function getCultureContext() {
	try {
		if (typeof process.versions.icu !== "string") return;
		const january = /* @__PURE__ */ new Date(9e8);
		if (new Intl.DateTimeFormat("es", { month: "long" }).format(january) === "enero") {
			const options = Intl.DateTimeFormat().resolvedOptions();
			return {
				locale: options.locale,
				timezone: options.timeZone
			};
		}
	} catch {}
}
/**
* Get app context information from process
*/
function getAppContext() {
	const app_memory = process.memoryUsage().rss;
	const appContext = {
		app_start_time: (/* @__PURE__ */ new Date(Date.now() - process.uptime() * 1e3)).toISOString(),
		app_memory
	};
	if (typeof process.availableMemory === "function") {
		const freeMemory = process.availableMemory();
		if (freeMemory != null) appContext.free_memory = freeMemory;
	}
	return appContext;
}
/**
* Gets device information from os
*/
function getDeviceContext(deviceOpt) {
	const device = {};
	let uptime;
	try {
		uptime = node_os.uptime();
	} catch {}
	if (typeof uptime === "number") device.boot_time = (/* @__PURE__ */ new Date(Date.now() - uptime * 1e3)).toISOString();
	device.arch = node_os.arch();
	if (deviceOpt === true || deviceOpt.memory) {
		device.memory_size = node_os.totalmem();
		device.free_memory = node_os.freemem();
	}
	if (deviceOpt === true || deviceOpt.cpu) {
		const cpuInfo = node_os.cpus();
		const firstCpu = cpuInfo?.[0];
		if (firstCpu) {
			device.processor_count = cpuInfo.length;
			device.cpu_description = firstCpu.model;
			device.processor_frequency = firstCpu.speed;
		}
	}
	return device;
}
/** Mapping of Node's platform names to actual OS names. */
const PLATFORM_NAMES = {
	aix: "IBM AIX",
	freebsd: "FreeBSD",
	openbsd: "OpenBSD",
	sunos: "SunOS",
	win32: "Windows",
	ohos: "OpenHarmony",
	android: "Android"
};
/** Mapping of linux release files located in /etc to distributions. */
const LINUX_DISTROS = [
	{
		name: "fedora-release",
		distros: ["Fedora"]
	},
	{
		name: "redhat-release",
		distros: ["Red Hat Linux", "Centos"]
	},
	{
		name: "redhat_version",
		distros: ["Red Hat Linux"]
	},
	{
		name: "SuSE-release",
		distros: ["SUSE Linux"]
	},
	{
		name: "lsb-release",
		distros: ["Ubuntu Linux", "Arch Linux"]
	},
	{
		name: "debian_version",
		distros: ["Debian"]
	},
	{
		name: "debian_release",
		distros: ["Debian"]
	},
	{
		name: "arch-release",
		distros: ["Arch Linux"]
	},
	{
		name: "gentoo-release",
		distros: ["Gentoo Linux"]
	},
	{
		name: "novell-release",
		distros: ["SUSE Linux"]
	},
	{
		name: "alpine-release",
		distros: ["Alpine Linux"]
	}
];
/** Functions to extract the OS version from Linux release files. */
const LINUX_VERSIONS = {
	alpine: (content) => content,
	arch: (content) => matchFirst(/distrib_release=(.*)/, content),
	centos: (content) => matchFirst(/release ([^ ]+)/, content),
	debian: (content) => content,
	fedora: (content) => matchFirst(/release (..)/, content),
	mint: (content) => matchFirst(/distrib_release=(.*)/, content),
	red: (content) => matchFirst(/release ([^ ]+)/, content),
	suse: (content) => matchFirst(/VERSION = (.*)\n/, content),
	ubuntu: (content) => matchFirst(/distrib_release=(.*)/, content)
};
/**
* Executes a regular expression with one capture group.
*
* @param regex A regular expression to execute.
* @param text Content to execute the RegEx on.
* @returns The captured string if matched; otherwise undefined.
*/
function matchFirst(regex, text) {
	const match = regex.exec(text);
	return match ? match[1] : void 0;
}
/** Loads the macOS operating system context. */
async function getDarwinInfo() {
	const darwinInfo = {
		kernel_version: node_os.release(),
		name: "Mac OS X",
		version: `10.${Number(node_os.release().split(".")[0]) - 4}`
	};
	try {
		const output = await new Promise((resolve, reject) => {
			(0, node_child_process.execFile)("/usr/bin/sw_vers", (error, stdout) => {
				if (error) {
					reject(error);
					return;
				}
				resolve(stdout);
			});
		});
		darwinInfo.name = matchFirst(/^ProductName:\s+(.*)$/m, output);
		darwinInfo.version = matchFirst(/^ProductVersion:\s+(.*)$/m, output);
		darwinInfo.build = matchFirst(/^BuildVersion:\s+(.*)$/m, output);
	} catch {}
	return darwinInfo;
}
/** Returns a distribution identifier to look up version callbacks. */
function getLinuxDistroId(name) {
	return name.split(" ")[0].toLowerCase();
}
/** Loads the Linux operating system context. */
async function getLinuxInfo() {
	const linuxInfo = {
		kernel_version: node_os.release(),
		name: "Linux"
	};
	try {
		const etcFiles = await readDirAsync("/etc");
		const distroFile = LINUX_DISTROS.find((file) => etcFiles.includes(file.name));
		if (!distroFile) return linuxInfo;
		const distroPath = (0, node_path.join)("/etc", distroFile.name);
		const contents = (await readFileAsync(distroPath, { encoding: "utf-8" })).toLowerCase();
		const { distros } = distroFile;
		linuxInfo.name = distros.find((d) => contents.indexOf(getLinuxDistroId(d)) >= 0) || distros[0];
		const id = getLinuxDistroId(linuxInfo.name);
		linuxInfo.version = LINUX_VERSIONS[id]?.(contents);
	} catch {}
	return linuxInfo;
}
/**
* Grabs some information about hosting provider based on best effort.
*/
function getCloudResourceContext() {
	if (process.env.VERCEL) return {
		[_sentry_conventions_attributes.CLOUD_PROVIDER]: "vercel",
		[_sentry_conventions_attributes.CLOUD_REGION]: process.env.VERCEL_REGION
	};
	else if (process.env.AWS_REGION) {
		const executionEnv = process.env.AWS_EXECUTION_ENV;
		return {
			[_sentry_conventions_attributes.CLOUD_PROVIDER]: "aws",
			[_sentry_conventions_attributes.CLOUD_REGION]: process.env.AWS_REGION,
			[_sentry_conventions_attributes.CLOUD_PLATFORM]: executionEnv?.startsWith("AWS_Lambda") ? "aws_lambda" : executionEnv
		};
	} else if (process.env.GCP_PROJECT) return { [_sentry_conventions_attributes.CLOUD_PROVIDER]: "gcp" };
	else if (process.env.ALIYUN_REGION_ID) return {
		[_sentry_conventions_attributes.CLOUD_PROVIDER]: "alibaba_cloud",
		[_sentry_conventions_attributes.CLOUD_REGION]: process.env.ALIYUN_REGION_ID
	};
	else if (process.env.WEBSITE_SITE_NAME && process.env.REGION_NAME) return {
		[_sentry_conventions_attributes.CLOUD_PROVIDER]: "azure",
		[_sentry_conventions_attributes.CLOUD_REGION]: process.env.REGION_NAME
	};
	else if (process.env.IBM_CLOUD_REGION) return {
		[_sentry_conventions_attributes.CLOUD_PROVIDER]: "ibm_cloud",
		[_sentry_conventions_attributes.CLOUD_REGION]: process.env.IBM_CLOUD_REGION
	};
	else if (process.env.TENCENTCLOUD_REGION) return {
		[_sentry_conventions_attributes.CLOUD_PROVIDER]: "tencent_cloud",
		[_sentry_conventions_attributes.CLOUD_REGION]: process.env.TENCENTCLOUD_REGION,
		[_sentry_conventions_attributes.CLOUD_ACCOUNT_ID]: process.env.TENCENTCLOUD_APPID,
		[_sentry_conventions_attributes.CLOUD_AVAILABILITY_ZONE]: process.env.TENCENTCLOUD_ZONE
	};
	else if (process.env.NETLIFY) return { [_sentry_conventions_attributes.CLOUD_PROVIDER]: "netlify" };
	else if (process.env.FLY_REGION) return {
		[_sentry_conventions_attributes.CLOUD_PROVIDER]: "fly.io",
		[_sentry_conventions_attributes.CLOUD_REGION]: process.env.FLY_REGION
	};
	else if (process.env.DYNO) return { [_sentry_conventions_attributes.CLOUD_PROVIDER]: "heroku" };
	else return;
}
// src/integrations/contextlines.ts
const SOURCE_FILE_EXTENSION = /\.(?:[cm]?[jt]sx?|vue|svelte|astro|mdx)$/;
const LRU_FILE_CONTENTS_CACHE = new _sentry_core.LRUMap(10);
const LRU_FILE_CONTENTS_FS_READ_FAILED = new _sentry_core.LRUMap(20);
const DEFAULT_LINES_OF_CONTEXT = 5;
const INTEGRATION_NAME$9 = "ContextLines";
/**
* Get or init map value
*/
function emplace(map, key, contents) {
	const value = map.get(key);
	if (value === void 0) {
		map.set(key, contents);
		return contents;
	}
	return value;
}
/**
* Determines if context lines should be skipped for a file.
* - node: prefixed modules are part of the runtime and cannot be resolved to a file
* - data: skip json, wasm and inline js https://nodejs.org/api/esm.html#data-imports
* - .min.(mjs|cjs|js) files are and not useful since they dont point to the original source
* - anything that is not a JavaScript or TypeScript source file. Frame filenames come
*   from the parsed `error.stack` string, which application code can overwrite with
*   external input, so we must not read arbitrary files off the filesystem.
*/
function shouldSkipContextLinesForFile(path) {
	if (path.startsWith("node:")) return true;
	if (path.startsWith("data:")) return true;
	const pathname = (0, _sentry_core.stripUrlQueryAndFragment)(path).toLowerCase();
	if (pathname.endsWith(".min.js")) return true;
	if (pathname.endsWith(".min.cjs")) return true;
	if (pathname.endsWith(".min.mjs")) return true;
	return !SOURCE_FILE_EXTENSION.test(pathname);
}
/**
* Determines if we should skip contextlines based off the max lineno and colno values.
*/
function shouldSkipContextLinesForFrame(frame) {
	if (frame.lineno !== void 0 && frame.lineno > 1e4) return true;
	if (frame.colno !== void 0 && frame.colno > 1e3) return true;
	return false;
}
/**
* Checks if we have all the contents that we need in the cache.
*/
function rangeExistsInContentCache(file, range) {
	const contents = LRU_FILE_CONTENTS_CACHE.get(file);
	if (contents === void 0) return false;
	for (let i = range[0]; i <= range[1]; i++) if (contents[i] === void 0) return false;
	return true;
}
/**
* Creates contiguous ranges of lines to read from a file. In the case where context lines overlap,
* the ranges are merged to create a single range.
*/
function makeLineReaderRanges(lines, linecontext) {
	if (!lines.length) return [];
	let i = 0;
	const line = lines[0];
	if (typeof line !== "number") return [];
	let current = makeContextRange(line, linecontext);
	const out = [];
	while (true) {
		if (i === lines.length - 1) {
			out.push(current);
			break;
		}
		const next = lines[i + 1];
		if (typeof next !== "number") break;
		if (next <= current[1]) current[1] = next + linecontext;
		else {
			out.push(current);
			current = makeContextRange(next, linecontext);
		}
		i++;
	}
	return out;
}
/**
* Extracts lines from a file and stores them in a cache.
*/
function getContextLinesFromFile(path, ranges, output) {
	return new Promise((resolve, _reject) => {
		const stream = (0, node_fs.createReadStream)(path);
		const lineReaded = (0, node_readline.createInterface)({ input: stream });
		function destroyStreamAndResolve() {
			stream.destroy();
			resolve();
		}
		let lineNumber = 0;
		let currentRangeIndex = 0;
		const range = ranges[currentRangeIndex];
		if (range === void 0) {
			destroyStreamAndResolve();
			return;
		}
		let rangeStart = range[0];
		let rangeEnd = range[1];
		function onStreamError(e) {
			LRU_FILE_CONTENTS_FS_READ_FAILED.set(path, 1);
			DEBUG_BUILD && _sentry_core.debug.error(`Failed to read file: ${path}. Error: ${e}`);
			lineReaded.close();
			lineReaded.removeAllListeners();
			destroyStreamAndResolve();
		}
		stream.on("error", onStreamError);
		lineReaded.on("error", onStreamError);
		lineReaded.on("close", destroyStreamAndResolve);
		lineReaded.on("line", (line) => {
			lineNumber++;
			if (lineNumber < rangeStart) return;
			output[lineNumber] = (0, _sentry_core.snipLine)(line, 0);
			if (lineNumber >= rangeEnd) {
				if (currentRangeIndex === ranges.length - 1) {
					lineReaded.close();
					lineReaded.removeAllListeners();
					return;
				}
				currentRangeIndex++;
				const range = ranges[currentRangeIndex];
				if (range === void 0) {
					lineReaded.close();
					lineReaded.removeAllListeners();
					return;
				}
				rangeStart = range[0];
				rangeEnd = range[1];
			}
		});
	});
}
/**
* Adds surrounding (context) lines of the line that an exception occurred on to the event.
* This is done by reading the file line by line and extracting the lines. The extracted lines are stored in
* a cache to prevent multiple reads of the same file. Failures to read a file are similarly cached to prevent multiple
* failing reads from happening.
*/
async function addSourceContext(event, contextLines) {
	const filesToLines = {};
	if (contextLines > 0 && event.exception?.values) for (const exception of event.exception.values) {
		if (!exception.stacktrace?.frames?.length) continue;
		for (let i = exception.stacktrace.frames.length - 1; i >= 0; i--) {
			const frame = exception.stacktrace.frames[i];
			const filename = frame?.filename;
			if (!frame || typeof filename !== "string" || typeof frame.lineno !== "number" || shouldSkipContextLinesForFile(filename) || shouldSkipContextLinesForFrame(frame)) continue;
			if (!filesToLines[filename]) filesToLines[filename] = [];
			filesToLines[filename].push(frame.lineno);
		}
	}
	const files = Object.keys(filesToLines);
	if (files.length == 0) return event;
	const readlinePromises = [];
	for (const file of files) {
		if (LRU_FILE_CONTENTS_FS_READ_FAILED.get(file)) continue;
		const filesToLineRanges = filesToLines[file];
		if (!filesToLineRanges) continue;
		filesToLineRanges.sort((a, b) => a - b);
		const ranges = makeLineReaderRanges(filesToLineRanges, contextLines);
		if (ranges.every((r) => rangeExistsInContentCache(file, r))) continue;
		const cache = emplace(LRU_FILE_CONTENTS_CACHE, file, {});
		readlinePromises.push(getContextLinesFromFile(file, ranges, cache));
	}
	await Promise.all(readlinePromises).catch(() => {
		DEBUG_BUILD && _sentry_core.debug.log("Failed to read one or more source files and resolve context lines");
	});
	if (contextLines > 0 && event.exception?.values) {
		for (const exception of event.exception.values) if (exception.stacktrace?.frames && exception.stacktrace.frames.length > 0) addSourceContextToFrames(exception.stacktrace.frames, contextLines, LRU_FILE_CONTENTS_CACHE);
	}
	return event;
}
/** Adds context lines to frames */
function addSourceContextToFrames(frames, contextLines, cache) {
	for (const frame of frames) if (frame.filename && frame.context_line === void 0 && typeof frame.lineno === "number") {
		const contents = cache.get(frame.filename);
		if (contents === void 0) continue;
		addContextToFrame(frame.lineno, frame, contextLines, contents);
	}
}
/**
* Clears the context lines from a frame, used to reset a frame to its original state
* if we fail to resolve all context lines for it.
*/
function clearLineContext(frame) {
	delete frame.pre_context;
	delete frame.context_line;
	delete frame.post_context;
}
/**
* Resolves context lines before and after the given line number and appends them to the frame;
*/
function addContextToFrame(lineno, frame, contextLines, contents) {
	if (frame.lineno === void 0 || contents === void 0) {
		DEBUG_BUILD && _sentry_core.debug.error("Cannot resolve context for frame with no lineno or file contents");
		return;
	}
	frame.pre_context = [];
	for (let i = makeRangeStart(lineno, contextLines); i < lineno; i++) {
		const line = contents[i];
		if (line === void 0) {
			clearLineContext(frame);
			DEBUG_BUILD && _sentry_core.debug.error(`Could not find line ${i} in file ${frame.filename}`);
			return;
		}
		frame.pre_context.push(line);
	}
	if (contents[lineno] === void 0) {
		clearLineContext(frame);
		DEBUG_BUILD && _sentry_core.debug.error(`Could not find line ${lineno} in file ${frame.filename}`);
		return;
	}
	frame.context_line = contents[lineno];
	const end = makeRangeEnd(lineno, contextLines);
	frame.post_context = [];
	for (let i = lineno + 1; i <= end; i++) {
		const line = contents[i];
		if (line === void 0) break;
		frame.post_context.push(line);
	}
}
function makeRangeStart(line, linecontext) {
	return Math.max(1, line - linecontext);
}
function makeRangeEnd(line, linecontext) {
	return line + linecontext;
}
function makeContextRange(line, linecontext) {
	return [makeRangeStart(line, linecontext), makeRangeEnd(line, linecontext)];
}
/** Exported only for tests, as a type-safe variant. */
const _contextLinesIntegration = ((options = {}) => {
	return {
		name: INTEGRATION_NAME$9,
		processEvent(event, _hint, client) {
			return addSourceContext(event, options.frameContextLines ?? client?.getDataCollectionOptions().frameContextLines ?? DEFAULT_LINES_OF_CONTEXT);
		}
	};
});
/**
* Capture the lines before and after the frame's context.
*/
const contextLinesIntegration = (0, _sentry_core.defineIntegration)(_contextLinesIntegration);
// src/utils/debug.ts
let cachedDebuggerEnabled;
/**
* Was the debugger enabled when this function was first called?
*/
async function isDebuggerEnabled() {
	if (cachedDebuggerEnabled === void 0) try {
		cachedDebuggerEnabled = !!(await import("node:inspector")).url();
	} catch {
		cachedDebuggerEnabled = false;
	}
	return cachedDebuggerEnabled;
}
// src/integrations/local-variables/common.ts
/**
* Filters captured frame variables by name according to a `dataCollection.stackFrameVariables` behavior.
*
* `true` keeps all variables (built-in sensitive names are still scrubbed), `false` drops them all, and the
* `{ allow: [...] }` / `{ deny: [...] }` forms filter by variable name.
*/
function filterFrameVariables(vars, behavior) {
	return (0, _sentry_core._INTERNAL_filterKeyValueData)(vars, behavior);
}
/**
* The key used to store the local variables on the error object.
*/
const LOCAL_VARIABLES_KEY = "__SENTRY_ERROR_LOCAL_VARIABLES__";
/** Could this be an anonymous function? */
function isAnonymous(name) {
	return name !== void 0 && (name.length === 0 || name === "?" || name === "<anonymous>");
}
/** Do the function names appear to match? */
function functionNamesMatch(a, b) {
	return a === b || `Object.${a}` === b || a === `Object.${b}` || isAnonymous(a) && isAnonymous(b);
}
// src/integrations/local-variables/local-variables-async.ts
const base64WorkerScript$1 = "LyohIEBzZW50cnkvbm9kZSAxMS4yMC4wICg0NTU5NTA2KSB8IGh0dHBzOi8vZ2l0aHViLmNvbS9nZXRzZW50cnkvc2VudHJ5LWphdmFzY3JpcHQgKi8KaW1wb3J0e1Nlc3Npb24gYXMgZX1mc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IHQucG9zdChgRGVidWdnZXIucmVzdW1lYCl9LGFzeW5jIGU9PntuJiZhd2FpdCB0LnBvc3QoYERlYnVnZ2VyLnJlc3VtZWApfSl9KSxhd2FpdCB0LnBvc3QoYERlYnVnZ2VyLmVuYWJsZWApO2xldCByPXMuY2FwdHVyZUFsbEV4Y2VwdGlvbnMhPT0hMTthd2FpdCB0LnBvc3QoYERlYnVnZ2VyLnNldFBhdXNlT25FeGNlcHRpb25zYCx7c3RhdGU6cj9gYWxsYDpgdW5jYXVnaHRgfSksciYmKHA9byhzLm1heEV4Y2VwdGlvbnNQZXJTZWNvbmR8fDUwLGFzeW5jKCk9PntjKGBSYXRlLWxpbWl0IGxpZnRlZC5gKSxhd2FpdCB0LnBvc3QoYERlYnVnZ2VyLnNldFBhdXNlT25FeGNlcHRpb25zYCx7c3RhdGU6YGFsbGB9KX0sYXN5bmMgZT0+e2MoYFJhdGUtbGltaXQgZXhjZWVkZWQuIERpc2FibGluZyBjYXB0dXJpbmcgb2YgY2F1Z2h0IGV4Y2VwdGlvbnMgZm9yICR7ZX0gc2Vjb25kcy5gKSxhd2FpdCB0LnBvc3QoYERlYnVnZ2VyLnNldFBhdXNlT25FeGNlcHRpb25zYCx7c3RhdGU6YHVuY2F1Z2h0YH0pfSkpfWgoKS5jYXRjaChlPT57YyhgRmFpbGVkIHRvIHN0YXJ0IGRlYnVnZ2VyYCxlKX0pLHNldEludGVydmFsKCgpPT57fSwxZTQpOw==";
function log$1(...args) {
	_sentry_core.debug.log("[LocalVariables]", ...args);
}
/**
* Adds local variables to exception frames
*/
const localVariablesAsyncIntegration = (0, _sentry_core.defineIntegration)(((integrationOptions = {}) => {
	function addLocalVariablesToException(exception, localVariables, behavior) {
		if (behavior === false) return;
		const frames = (exception.stacktrace?.frames || []).filter((frame) => frame.function !== "new Promise");
		for (let i = 0; i < frames.length; i++) {
			const frameIndex = frames.length - i - 1;
			const frameLocalVariables = localVariables[i];
			const frame = frames[frameIndex];
			if (!frame || !frameLocalVariables) break;
			if (frameLocalVariables.vars === void 0 || frame.in_app === false && integrationOptions.includeOutOfAppFrames !== true || !functionNamesMatch(frame.function, frameLocalVariables.function)) continue;
			frame.vars = filterFrameVariables(frameLocalVariables.vars, behavior);
		}
	}
	function addLocalVariablesToEvent(event, hint) {
		if (hint.originalException && typeof hint.originalException === "object" && "__SENTRY_ERROR_LOCAL_VARIABLES__" in hint.originalException && Array.isArray(hint.originalException["__SENTRY_ERROR_LOCAL_VARIABLES__"])) {
			const behavior = (0, _sentry_core.getClient)()?.getDataCollectionOptions().stackFrameVariables ?? true;
			for (const exception of event.exception?.values || []) addLocalVariablesToException(exception, hint.originalException[LOCAL_VARIABLES_KEY], behavior);
			hint.originalException[LOCAL_VARIABLES_KEY] = void 0;
		}
		return event;
	}
	async function startInspector() {
		const inspector = await import("node:inspector");
		if (!inspector.url()) inspector.open(0);
	}
	function startWorker(options) {
		const worker = new node_worker_threads.Worker(new URL(`data:application/javascript;base64,${base64WorkerScript$1}`), {
			workerData: options,
			execArgv: [],
			env: {
				...process.env,
				NODE_OPTIONS: void 0
			}
		});
		process.on("exit", () => {
			worker.terminate();
		});
		worker.once("error", (err) => {
			log$1("Worker error", err);
		});
		worker.once("exit", (code) => {
			log$1("Worker exit", code);
		});
		worker.unref();
	}
	return {
		name: "LocalVariablesAsync",
		async setup(client) {
			if (!client.getOptions().includeLocalVariables) return;
			if (await isDebuggerEnabled()) {
				_sentry_core.debug.warn("Local variables capture has been disabled because the debugger was already enabled");
				return;
			}
			const options = {
				...integrationOptions,
				debug: _sentry_core.debug.isEnabled()
			};
			startInspector().then(() => {
				try {
					startWorker(options);
				} catch (e) {
					_sentry_core.debug.error("Failed to start worker", e);
				}
			}, (e) => {
				_sentry_core.debug.error("Failed to start inspector", e);
			});
		},
		processEvent(event, hint) {
			return addLocalVariablesToEvent(event, hint);
		}
	};
}));
// src/integrations/local-variables/index.ts
const localVariablesIntegration = (options = {}) => {
	return localVariablesAsyncIntegration(options);
};
// src/integrations/modules.ts
let moduleCache;
const INTEGRATION_NAME$8 = "Modules";
/**
* Reads the modules injected at build time into `__SENTRY_SERVER_MODULES__` (e.g. by the Next.js SDK).
*
* Must be read lazily (per call), not captured at module-eval time: webpack replaces the token via
* `DefinePlugin` (available immediately), but Turbopack assigns `globalThis.__SENTRY_SERVER_MODULES__`
* at runtime, *after* this module's imports are hoisted and evaluated. A `const` capture would be
* empty under Turbopack. See getsentry/sentry-javascript#19147.
*/
function getServerModules() {
	if (typeof __SENTRY_SERVER_MODULES__ !== "undefined") return __SENTRY_SERVER_MODULES__;
	return _sentry_core.GLOBAL_OBJ.__SENTRY_SERVER_MODULES__ ?? {};
}
const _modulesIntegration = (() => {
	return {
		name: INTEGRATION_NAME$8,
		processEvent(event) {
			event.modules = {
				...event.modules,
				..._getModules()
			};
			return event;
		},
		getModules: _getModules
	};
});
/**
* Adds the app's packages to the event. Versions injected at build time (e.g. by the Next.js SDK) are used as is.
* Otherwise, it uses exact installed versions where they resolve from the entry file, and declared ranges for the rest.
*/
const modulesIntegration = (0, _sentry_core.defineIntegration)(_modulesIntegration);
function readFile(path) {
	try {
		return (0, node_fs.existsSync)(path) ? (0, node_fs.readFileSync)(path, "utf8") : void 0;
	} catch {
		return;
	}
}
/** Files loaded through the CommonJS loader, which includes CommonJS packages imported from ESM. */
function getLoadedCommonJsFiles() {
	try {
		return Object.keys(node_module.Module._cache || {});
	} catch {
		return [];
	}
}
function collectModules() {
	const serverModules = getServerModules();
	if (Object.keys(serverModules).length) return serverModules;
	return (0, _sentry_server_utils.collectInstalledModules)({
		readFile,
		entryPath: process.argv[1],
		cwd: process.cwd(),
		loadedFiles: getLoadedCommonJsFiles()
	});
}
/** Fetches the list of modules and the versions loaded by the entry file for your node.js app. */
function _getModules() {
	if (!moduleCache) moduleCache = collectModules();
	return moduleCache;
}
// src/utils/errorhandling.ts
const DEFAULT_SHUTDOWN_TIMEOUT = 2e3;
let isShuttingDown = false;
/**
* @hidden
*/
function logAndExitProcess(error) {
	if (isShuttingDown) return;
	isShuttingDown = true;
	(0, _sentry_core.consoleSandbox)(() => {
		console.error(error);
	});
	const client = (0, _sentry_core.getClient)();
	if (client === void 0) {
		DEBUG_BUILD && _sentry_core.debug.warn("No NodeClient was defined, we are exiting the process now.");
		global.process.exit(1);
		return;
	}
	const options = client.getOptions();
	const timeout = options?.shutdownTimeout && options.shutdownTimeout > 0 ? options.shutdownTimeout : DEFAULT_SHUTDOWN_TIMEOUT;
	client.close(timeout).then((result) => {
		if (!result) DEBUG_BUILD && _sentry_core.debug.warn("We reached the timeout for emptying the request buffer, still exiting now!");
		global.process.exit(1);
	}, (error) => {
		DEBUG_BUILD && _sentry_core.debug.error(error);
		global.process.exit(1);
	});
}
// src/integrations/onuncaughtexception.ts
const INTEGRATION_NAME$7 = "OnUncaughtException";
/**
* Add a global exception handler.
*/
const onUncaughtExceptionIntegration = (0, _sentry_core.defineIntegration)((options = {}) => {
	const optionsWithDefaults = {
		exitEvenIfOtherHandlersAreRegistered: false,
		...options
	};
	return {
		name: INTEGRATION_NAME$7,
		setup(client) {
			if (!worker_threads.isMainThread) return;
			global.process.on("uncaughtException", makeErrorHandler(client, optionsWithDefaults));
		}
	};
});
/** Exported only for tests */
function makeErrorHandler(client, options) {
	const timeout = 2e3;
	let caughtFirstError = false;
	let caughtSecondError = false;
	let calledFatalError = false;
	let firstError;
	const clientOptions = client.getOptions();
	return Object.assign((error) => {
		let onFatalError = logAndExitProcess;
		if (options.onFatalError) onFatalError = options.onFatalError;
		else if (clientOptions.onFatalError) onFatalError = clientOptions.onFatalError;
		const processWouldExit = global.process.listeners("uncaughtException").filter((listener) => {
			return listener.name !== "domainUncaughtExceptionClear" && listener._errorHandler !== true;
		}).length === 0;
		const shouldApplyFatalHandlingLogic = options.exitEvenIfOtherHandlersAreRegistered || processWouldExit;
		if (!caughtFirstError) {
			firstError = error;
			caughtFirstError = true;
			if ((0, _sentry_core.getClient)() === client) (0, _sentry_core.captureException)(error, {
				originalException: error,
				captureContext: { level: "fatal" },
				mechanism: {
					handled: false,
					type: "auto.node.onuncaughtexception"
				}
			});
			if (!calledFatalError && shouldApplyFatalHandlingLogic) {
				calledFatalError = true;
				onFatalError(error);
			}
		} else if (shouldApplyFatalHandlingLogic) {
			if (calledFatalError) {
				DEBUG_BUILD && _sentry_core.debug.warn("uncaught exception after calling fatal error shutdown callback - this is bad! forcing shutdown");
				logAndExitProcess(error);
			} else if (!caughtSecondError) {
				caughtSecondError = true;
				setTimeout(() => {
					if (!calledFatalError) {
						calledFatalError = true;
						onFatalError(firstError, error);
					}
				}, timeout);
			}
		}
	}, { _errorHandler: true });
}
// src/integrations/onunhandledrejection.ts
const INTEGRATION_NAME$6 = "OnUnhandledRejection";
const DEFAULT_IGNORES = [{ name: "AI_NoOutputGeneratedError" }, { name: "AbortError" }];
const _onUnhandledRejectionIntegration = ((options = {}) => {
	const opts = {
		mode: options.mode ?? "warn",
		ignore: [...DEFAULT_IGNORES, ...options.ignore ?? []]
	};
	return {
		name: INTEGRATION_NAME$6,
		setup(client) {
			global.process.on("unhandledRejection", makeUnhandledPromiseHandler(client, opts));
		}
	};
});
const onUnhandledRejectionIntegration = (0, _sentry_core.defineIntegration)(_onUnhandledRejectionIntegration);
/** Extract error info safely */
function extractErrorInfo(reason) {
	if (!(0, _sentry_core.isObjectLike)(reason)) return {
		name: "",
		message: String(reason ?? "")
	};
	const errorLike = reason;
	return {
		name: typeof errorLike.name === "string" ? errorLike.name : "",
		message: typeof errorLike.message === "string" ? errorLike.message : String(reason)
	};
}
/** Check if a matcher matches the reason */
function isMatchingReason(matcher, errorInfo) {
	const nameMatches = matcher.name === void 0 || (0, _sentry_core.isMatchingPattern)(errorInfo.name, matcher.name, true);
	const messageMatches = matcher.message === void 0 || (0, _sentry_core.isMatchingPattern)(errorInfo.message, matcher.message);
	return nameMatches && messageMatches;
}
/** Match helper */
function matchesIgnore(list, reason) {
	const errorInfo = extractErrorInfo(reason);
	return list.some((matcher) => isMatchingReason(matcher, errorInfo));
}
/** Core handler */
function makeUnhandledPromiseHandler(client, options) {
	return function sendUnhandledPromise(reason, _promise) {
		if ((0, _sentry_core.getClient)() !== client) return;
		if (matchesIgnore(options.ignore ?? [], reason)) return;
		const level = options.mode === "strict" ? "fatal" : "error";
		const activeSpanForError = (0, _sentry_core.isObjectLike)(reason) ? reason._sentry_active_span : void 0;
		(activeSpanForError ? (fn) => (0, _sentry_core.withActiveSpan)(activeSpanForError, fn) : (fn) => fn())(() => {
			(0, _sentry_core.captureException)(reason, {
				originalException: reason,
				captureContext: {
					extra: { unhandledPromiseRejection: true },
					level
				},
				mechanism: {
					handled: false,
					type: "auto.node.onunhandledrejection"
				}
			});
		});
		handleRejection(reason, options.mode);
	};
}
/**
* Handler for `mode` option
*/
function handleRejection(reason, mode) {
	const rejectionWarning = "This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason:";
	if (mode === "warn") (0, _sentry_core.consoleSandbox)(() => {
		console.warn(rejectionWarning);
		console.error((0, _sentry_core.isObjectLike)(reason) && "stack" in reason ? reason.stack : reason);
	});
	else if (mode === "strict") {
		if (!((0, _sentry_core.isObjectLike)(reason) && "stack" in reason)) (0, _sentry_core.consoleSandbox)(() => {
			console.warn(rejectionWarning);
		});
		logAndExitProcess(reason);
	}
}
// src/integrations/processSession.ts
const INTEGRATION_NAME$5 = "ProcessSession";
/**
* Records a Session for the current process to track release health.
*
* Once the process starts serving requests that are tracked as request sessions, release health is
* reported through session aggregates instead, and the process session is discarded.
* This integration exists so that we capture some form of session health data even when the process is not serving requests.
*/
const processSessionIntegration = (0, _sentry_core.defineIntegration)(() => {
	return {
		name: INTEGRATION_NAME$5,
		setup(client) {
			(0, _sentry_core.startSession)();
			const processIsolationScope = (0, _sentry_core.getIsolationScope)();
			process.on("beforeExit", () => {
				if ((0, _sentry_core.getIsolationScope)().getSession()?.status === "ok") (0, _sentry_core.endSession)();
			});
			const unsubscribe = client.on("startRequestSession", () => {
				unsubscribe();
				const session = processIsolationScope.getSession();
				if (!session) return;
				if (!session.init && session.status === "ok") {
					(0, _sentry_core.closeSession)(session);
					client.captureSession(session);
				}
				processIsolationScope.setSession();
			});
		}
	};
});
// src/integrations/spotlight.ts
const INTEGRATION_NAME$4 = "Spotlight";
const _spotlightIntegration = ((options = {}) => {
	const _options = { sidecarUrl: options.sidecarUrl || "http://localhost:8969/stream" };
	return {
		name: INTEGRATION_NAME$4,
		setup(client) {
			try {
				if (process.env.NODE_ENV && process.env.NODE_ENV !== "development") _sentry_core.debug.warn("[Spotlight] It seems you're not in dev mode. Do you really want to have Spotlight enabled?");
			} catch {}
			connectToSpotlight(client, _options);
		}
	};
});
/**
* Use this integration to send errors and transactions to Spotlight.
*
* Learn more about spotlight at https://spotlightjs.com
*/
const spotlightIntegration = (0, _sentry_core.defineIntegration)(_spotlightIntegration);
function connectToSpotlight(client, options) {
	const spotlightUrl = parseSidecarUrl(options.sidecarUrl);
	if (!spotlightUrl) return;
	let failedRequests = 0;
	client.on("beforeEnvelope", (envelope) => {
		if (failedRequests > 3) {
			_sentry_core.debug.warn("[Spotlight] Disabled Sentry -> Spotlight integration due to too many failed requests");
			return;
		}
		const serializedEnvelope = (0, _sentry_core.serializeEnvelope)(envelope);
		(0, _sentry_core.suppressTracing)(() => {
			const req = node_http.request({
				method: "POST",
				path: spotlightUrl.pathname,
				hostname: spotlightUrl.hostname,
				port: spotlightUrl.port,
				headers: { "Content-Type": "application/x-sentry-envelope" }
			}, (res) => {
				if (res.statusCode && res.statusCode >= 200 && res.statusCode < 400) failedRequests = 0;
				res.on("data", () => {});
				res.on("end", () => {});
				res.setEncoding("utf8");
			});
			req.on("error", () => {
				failedRequests++;
				_sentry_core.debug.warn("[Spotlight] Failed to send envelope to Spotlight Sidecar");
			});
			req.write(serializedEnvelope);
			req.end();
		});
	});
}
function parseSidecarUrl(url) {
	try {
		return new URL(`${url}`);
	} catch {
		_sentry_core.debug.warn(`[Spotlight] Invalid sidecar URL: ${url}`);
		return;
	}
}
// src/integrations/systemError.ts
const INTEGRATION_NAME$3 = "NodeSystemError";
function isSystemError(error) {
	if (!(error instanceof Error)) return false;
	if (!("errno" in error) || typeof error.errno !== "number") return false;
	if (typeof node_util.getSystemErrorMap !== "function") return false;
	return node_util.getSystemErrorMap().has(error.errno);
}
/**
* Captures context for Node.js SystemError errors.
*/
const systemErrorIntegration = (0, _sentry_core.defineIntegration)((options = {}) => {
	return {
		name: INTEGRATION_NAME$3,
		processEvent: (event, hint, client) => {
			if (!isSystemError(hint.originalException)) return event;
			const error = hint.originalException;
			const errorContext = { ...error };
			if (!client.getDataCollectionOptions().userInfo && options.includePaths !== true) {
				delete errorContext.path;
				delete errorContext.dest;
			}
			event.contexts = {
				...event.contexts,
				node_system_error: errorContext
			};
			for (const exception of event.exception?.values || []) if (exception.value) {
				if (error.path && exception.value.includes(error.path)) exception.value = exception.value.replace(`'${error.path}'`, "").trim();
				if (error.dest && exception.value.includes(error.dest)) exception.value = exception.value.replace(`'${error.dest}'`, "").trim();
			}
			return event;
		}
	};
});
// src/integrations/workerThreads.ts
const INTEGRATION_NAME$2 = "WorkerThreads";
/**
* Capture events and errors of worker threads.
* For child process events, use `childProcessIntegration()` instead.
*/
const workerThreadsIntegration = (0, _sentry_core.defineIntegration)(() => {
	return {
		name: INTEGRATION_NAME$2,
		setup() {
			(0, _sentry_server_utils.subscribeDiagnosticsChannel)("worker_threads", (event) => {
				if ((0, _sentry_core.isObjectLike)(event) && "worker" in event) captureWorkerThreadEvents(event.worker);
			});
		}
	};
});
function captureWorkerThreadEvents(worker) {
	let threadId;
	worker.on("online", () => {
		threadId = worker.threadId;
	}).on("error", (error) => {
		(0, _sentry_core.captureException)(error, { mechanism: {
			type: "auto.node.worker_threads",
			handled: false,
			data: threadId !== void 0 ? { threadId: String(threadId) } : void 0
		} });
	});
}
// src/proxy/helpers.ts
/**
* This code was originally forked from https://github.com/TooTallNate/proxy-agents/tree/b133295fd16f6475578b6b15bd9b4e33ecb0d0b7
* With the following LICENSE:
*
* (The MIT License)
*
* Copyright (c) 2013 Nathan Rajlich <nathan@tootallnate.net>*
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* 'Software'), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:*
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.*
*
* THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
// src/proxy/base.ts
/**
* This code was originally forked from https://github.com/TooTallNate/proxy-agents/tree/b133295fd16f6475578b6b15bd9b4e33ecb0d0b7
* With the following LICENSE:
*
* (The MIT License)
*
* Copyright (c) 2013 Nathan Rajlich <nathan@tootallnate.net>*
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* 'Software'), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:*
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.*
*
* THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
const INTERNAL = Symbol("AgentBaseInternalState");
var Agent = class extends node_http.Agent {
	constructor(opts) {
		super(opts);
		this[INTERNAL] = {};
	}
	/**
	* Determine whether this is an `http` or `https` request.
	*/
	isSecureEndpoint(options) {
		if (options) {
			if (typeof options.secureEndpoint === "boolean") return options.secureEndpoint;
			if (typeof options.protocol === "string") return options.protocol === "https:";
		}
		const { stack } = /* @__PURE__ */ new Error();
		if (typeof stack !== "string") return false;
		return stack.split("\n").some((l) => l.indexOf("(https.js:") !== -1 || l.indexOf("node:https:") !== -1);
	}
	createSocket(req, options, cb) {
		const connectOpts = {
			...options,
			secureEndpoint: this.isSecureEndpoint(options)
		};
		Promise.resolve().then(() => this.connect(req, connectOpts)).then((socket) => {
			if (socket instanceof node_http.Agent) return socket.addRequest(req, connectOpts);
			this[INTERNAL].currentSocket = socket;
			super.createSocket(req, options, cb);
		}, cb);
	}
	createConnection() {
		const socket = this[INTERNAL].currentSocket;
		this[INTERNAL].currentSocket = void 0;
		if (!socket) throw new Error("No socket was returned in the `connect()` function");
		return socket;
	}
	get defaultPort() {
		return this[INTERNAL].defaultPort ?? (this.protocol === "https:" ? 443 : 80);
	}
	set defaultPort(v) {
		if (this[INTERNAL]) this[INTERNAL].defaultPort = v;
	}
	get protocol() {
		return this[INTERNAL].protocol ?? (this.isSecureEndpoint() ? "https:" : "http:");
	}
	set protocol(v) {
		if (this[INTERNAL]) this[INTERNAL].protocol = v;
	}
};
// src/proxy/parse-proxy-response.ts
function debugLog$1(...args) {
	_sentry_core.debug.log("[https-proxy-agent:parse-proxy-response]", ...args);
}
function parseProxyResponse(socket) {
	return new Promise((resolve, reject) => {
		let buffersLength = 0;
		const buffers = [];
		function read() {
			const b = socket.read();
			if (b) ondata(b);
			else socket.once("readable", read);
		}
		function cleanup() {
			socket.removeListener("end", onend);
			socket.removeListener("error", onerror);
			socket.removeListener("readable", read);
		}
		function onend() {
			cleanup();
			debugLog$1("onend");
			reject(/* @__PURE__ */ new Error("Proxy connection ended before receiving CONNECT response"));
		}
		function onerror(err) {
			cleanup();
			debugLog$1("onerror %o", err);
			reject(err);
		}
		function ondata(b) {
			buffers.push(b);
			buffersLength += b.length;
			const buffered = Buffer.concat(buffers, buffersLength);
			const endOfHeaders = buffered.indexOf("\r\n\r\n");
			if (endOfHeaders === -1) {
				debugLog$1("have not received end of HTTP headers yet...");
				read();
				return;
			}
			const headerParts = buffered.subarray(0, endOfHeaders).toString("ascii").split("\r\n");
			const firstLine = headerParts.shift();
			if (!firstLine) {
				socket.destroy();
				return reject(/* @__PURE__ */ new Error("No header received from proxy CONNECT response"));
			}
			const firstLineParts = firstLine.split(" ");
			const statusCode = +(firstLineParts[1] || 0);
			const statusText = firstLineParts.slice(2).join(" ");
			const headers = {};
			for (const header of headerParts) {
				if (!header) continue;
				const firstColon = header.indexOf(":");
				if (firstColon === -1) {
					socket.destroy();
					return reject(/* @__PURE__ */ new Error(`Invalid header from proxy CONNECT response: "${header}"`));
				}
				const key = header.slice(0, firstColon).toLowerCase();
				const value = header.slice(firstColon + 1).trimStart();
				const current = headers[key];
				if (typeof current === "string") headers[key] = [current, value];
				else if (Array.isArray(current)) current.push(value);
				else headers[key] = value;
			}
			debugLog$1("got proxy server response: %o %o", firstLine, headers);
			cleanup();
			resolve({
				connect: {
					statusCode,
					statusText,
					headers
				},
				buffered
			});
		}
		socket.on("error", onerror);
		socket.on("end", onend);
		read();
	});
}
// src/proxy/index.ts
function debugLog(...args) {
	_sentry_core.debug.log("[https-proxy-agent]", ...args);
}
/**
* The `HttpsProxyAgent` implements an HTTP Agent subclass that connects to
* the specified "HTTP(s) proxy server" in order to proxy HTTPS requests.
*
* Outgoing HTTP requests are first tunneled through the proxy server using the
* `CONNECT` HTTP request method to establish a connection to the proxy server,
* and then the proxy server connects to the destination target and issues the
* HTTP request from the proxy server.
*
* `https:` requests have their socket connection upgraded to TLS once
* the connection to the proxy server has been established.
*/
var HttpsProxyAgent = class extends Agent {
	constructor(proxy, opts) {
		super(opts);
		this.options = {};
		this.proxy = typeof proxy === "string" ? new URL(proxy) : proxy;
		this.proxyHeaders = opts?.headers ?? {};
		debugLog("Creating new HttpsProxyAgent instance: %o", this.proxy.href);
		const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, "");
		const port = this.proxy.port ? parseInt(this.proxy.port, 10) : this.proxy.protocol === "https:" ? 443 : 80;
		this.connectOpts = {
			ALPNProtocols: ["http/1.1"],
			...opts ? omit(opts, "headers") : null,
			host,
			port
		};
	}
	/**
	* Called when the HTTP client library is creating a
	* new HTTP request.
	*/
	async connect(req, opts) {
		const { proxy } = this;
		if (!opts.host) throw new TypeError("No \"host\" provided");
		let socket;
		if (proxy.protocol === "https:") {
			debugLog("Creating `tls.Socket`: %o", this.connectOpts);
			const servername = this.connectOpts.servername || this.connectOpts.host;
			socket = node_tls.connect({
				...this.connectOpts,
				servername: servername && node_net.isIP(servername) ? void 0 : servername
			});
		} else {
			debugLog("Creating `net.Socket`: %o", this.connectOpts);
			socket = node_net.connect(this.connectOpts);
		}
		const headers = typeof this.proxyHeaders === "function" ? this.proxyHeaders() : { ...this.proxyHeaders };
		const host = node_net.isIPv6(opts.host) ? `[${opts.host}]` : opts.host;
		let payload = `CONNECT ${host}:${opts.port} HTTP/1.1\r\n`;
		if (proxy.username || proxy.password) {
			const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`;
			headers["Proxy-Authorization"] = `Basic ${Buffer.from(auth).toString("base64")}`;
		}
		headers.Host = `${host}:${opts.port}`;
		if (!headers["Proxy-Connection"]) headers["Proxy-Connection"] = this.keepAlive ? "Keep-Alive" : "close";
		for (const name of Object.keys(headers)) payload += `${name}: ${headers[name]}\r\n`;
		const proxyResponsePromise = parseProxyResponse(socket);
		socket.write(`${payload}\r\n`);
		const { connect, buffered } = await proxyResponsePromise;
		req.emit("proxyConnect", connect);
		this.emit("proxyConnect", connect, req);
		if (connect.statusCode === 200) {
			req.once("socket", resume);
			if (opts.secureEndpoint) {
				debugLog("Upgrading socket connection to TLS");
				const servername = opts.servername || opts.host;
				return node_tls.connect({
					...omit(opts, "host", "path", "port"),
					socket,
					servername: node_net.isIP(servername) ? void 0 : servername
				});
			}
			return socket;
		}
		socket.destroy();
		const fakeSocket = new node_net.Socket({ writable: false });
		fakeSocket.readable = true;
		req.once("socket", (s) => {
			debugLog("Replaying proxy buffer for failed request");
			s.push(buffered);
			s.push(null);
		});
		return fakeSocket;
	}
};
HttpsProxyAgent.protocols = ["http", "https"];
function resume(socket) {
	socket.resume();
}
function omit(obj, ...keys) {
	const ret = {};
	let key;
	for (key in obj) if (!keys.includes(key)) ret[key] = obj[key];
	return ret;
}
// src/transports/http.ts
const GZIP_THRESHOLD = 32768;
/**
* Gets a stream from a Uint8Array or string
* Readable.from is ideal but was added in node.js v12.3.0 and v10.17.0
*/
function streamFromBody(body) {
	return new node_stream.Readable({ read() {
		this.push(body);
		this.push(null);
	} });
}
/**
* Creates a Transport that uses native the native 'http' and 'https' modules to send events to Sentry.
*/
function makeNodeTransport(options) {
	let urlSegments;
	try {
		urlSegments = new URL(options.url);
	} catch {
		(0, _sentry_core.consoleSandbox)(() => {
			console.warn("[@sentry/node]: Invalid dsn or tunnel option, will not send any events. The tunnel option must be a full URL when used.");
		});
		return (0, _sentry_core.createTransport)(options, () => Promise.resolve({}));
	}
	const nativeHttpModule = urlSegments.protocol === "https:" ? node_https : node_http;
	const agent = getHttpAgent(urlSegments, {
		proxy: options.proxy,
		keepAlive: options.keepAlive
	});
	const requestExecutor = createRequestExecutor(options, options.httpModule ?? nativeHttpModule, agent);
	return (0, _sentry_core.createTransport)(options, requestExecutor);
}
/**
* Returns the agent for requests to `url`: a proxy agent when a proxy applies, otherwise a plain keep-alive agent.
*
* Proxy prioritization: http => `options.proxy` | `process.env.http_proxy`
* Proxy prioritization: https => `options.proxy` | `process.env.https_proxy` | `process.env.http_proxy`
* Hosts listed in `process.env.no_proxy` are never proxied, and `options.proxy: false` disables proxying entirely.
*/
function getHttpAgent(url, options = {}) {
	const isHttps = url.protocol === "https:";
	const proxy = options.proxy === false ? void 0 : applyNoProxyOption(url, options.proxy || (isHttps ? process.env.https_proxy : void 0) || process.env.http_proxy);
	if (proxy) return new HttpsProxyAgent(proxy);
	return new (isHttps ? node_https : node_http).Agent({
		keepAlive: options.keepAlive ?? true,
		maxSockets: 30,
		timeout: 2e3
	});
}
/**
* Honors the `no_proxy` env variable with the highest priority to allow for hosts exclusion.
*
* @param transportUrl The URL the transport intends to send events to.
* @param proxy The client configured proxy.
* @returns A proxy the transport should use.
*/
function applyNoProxyOption(transportUrlSegments, proxy) {
	const { no_proxy } = process.env;
	if (no_proxy?.split(",").some((exemption) => transportUrlSegments.host.endsWith(exemption) || transportUrlSegments.hostname.endsWith(exemption))) return;
	else return proxy;
}
/**
* Creates a RequestExecutor to be used with `createTransport`.
*/
function createRequestExecutor(options, httpModule, agent) {
	const { hostname, pathname, port, protocol, search } = new URL(options.url);
	return function makeRequest(request) {
		const sendRequest = (canRetry) => new Promise((resolve, reject) => {
			(0, _sentry_core.suppressTracing)(() => {
				let body = streamFromBody(request.body);
				const headers = { ...options.headers };
				if (request.body.length > GZIP_THRESHOLD) {
					headers["content-encoding"] = "gzip";
					body = body.pipe((0, node_zlib.createGzip)());
				}
				const hostnameIsIPv6 = hostname.startsWith("[");
				const req = httpModule.request({
					method: "POST",
					agent,
					headers,
					hostname: hostnameIsIPv6 ? hostname.slice(1, -1) : hostname,
					path: `${pathname}${search}`,
					port,
					protocol,
					ca: options.caCerts
				}, (res) => {
					res.on("data", () => {});
					res.on("end", () => {});
					res.setEncoding("utf8");
					const retryAfterHeader = res.headers["retry-after"] ?? null;
					const rateLimitsHeader = res.headers["x-sentry-rate-limits"] ?? null;
					resolve({
						statusCode: res.statusCode,
						headers: {
							"retry-after": retryAfterHeader,
							"x-sentry-rate-limits": Array.isArray(rateLimitsHeader) ? rateLimitsHeader[0] || null : rateLimitsHeader
						}
					});
				});
				req.on("error", (error) => {
					if (canRetry && req.reusedSocket && error.code === "ECONNRESET") resolve(sendRequest(false));
					else reject(error);
				});
				body.pipe(req);
			});
		});
		return sendRequest(true);
	};
}
// src/sdk/api.ts
/**
* Returns a release dynamically from environment variables.
*/
function getSentryRelease(fallback) {
	if (process.env.SENTRY_RELEASE) return process.env.SENTRY_RELEASE;
	if (_sentry_core.GLOBAL_OBJ.SENTRY_RELEASE?.id) return _sentry_core.GLOBAL_OBJ.SENTRY_RELEASE.id;
	return (0, _sentry_core_server._INTERNAL_getReleaseFromCommitEnv)() || fallback;
}
/** Node.js stack parser */
const defaultStackParser = (0, _sentry_core.createStackParser)((0, _sentry_core_server.nodeStackLineParser)((0, _sentry_server_utils.createGetModuleFromFilename)()));
// src/utils/entry-point.ts
/**
* Parses the process arguments to determine the app path, import paths, and require paths.
*/
function parseProcessPaths(proc) {
	const { execArgv, argv, cwd: getCwd } = proc;
	const cwd = getCwd();
	const appPath = (0, node_path.resolve)(cwd, argv[1] || "");
	const joinedArgs = execArgv.join(" ");
	return {
		appPath,
		importPaths: Array.from(joinedArgs.matchAll(/--import[ =](\S+)/g)).map((e) => (0, node_path.resolve)(cwd, e[1] || "")),
		requirePaths: Array.from(joinedArgs.matchAll(/(?:--require|-r)[ =](\S+)/g)).map((e) => (0, node_path.resolve)(cwd, e[1] || ""))
	};
}
/**
* Gets the current entry point type.
*
* `app` means this function was most likely called via the app entry point.
* `import` means this function was most likely called from an --import cli arg.
* `require` means this function was most likely called from a --require cli arg.
* `unknown` means we couldn't determine for sure.
*/
function getEntryPointType(proc = process) {
	const filenames = defaultStackParser((/* @__PURE__ */ new Error()).stack || "").map((f) => f.filename).filter(Boolean);
	const { appPath, importPaths, requirePaths } = parseProcessPaths(proc);
	const output = [];
	if (appPath && filenames.includes(appPath)) output.push("app");
	if (importPaths.some((p) => filenames.includes(p))) output.push("import");
	if (requirePaths.some((p) => filenames.includes(p))) output.push("require");
	if (output.length === 1) return output[0];
	return "unknown";
}
// src/utils/spotlight.ts
/**
* Parse the spotlight option with proper precedence:
* - `false` or explicit string from options: use as-is
* - `true`: enable spotlight, but prefer a custom URL from the env var if set
* - `undefined`: defer entirely to the env var (bool or URL)
*/
function getSpotlightConfig(optionsSpotlight) {
	if (optionsSpotlight === false) return false;
	if (typeof optionsSpotlight === "string") return optionsSpotlight;
	const envBool = (0, _sentry_core.envToBool)(process.env.SENTRY_SPOTLIGHT, { strict: true });
	const envUrl = envBool === null && process.env.SENTRY_SPOTLIGHT ? process.env.SENTRY_SPOTLIGHT : void 0;
	return optionsSpotlight === true ? envUrl ?? true : envBool ?? envUrl;
}
// src/sdk/client.ts
const DEFAULT_CLIENT_REPORT_FLUSH_INTERVAL_MS = 6e4;
/** A client for using Sentry with Node & OpenTelemetry. */
var NodeClient = class extends _sentry_core_server.ServerRuntimeClient {
	constructor(options) {
		const serverName = options.includeServerName === false ? void 0 : options.serverName || global.process.env.SENTRY_NAME || node_os.hostname();
		const clientOptions = {
			...options,
			platform: "node",
			runtime: options.runtime || {
				name: "node",
				version: global.process.version
			},
			serverName
		};
		(0, _sentry_core.applySdkMetadata)(clientOptions, "node");
		_sentry_core.debug.log(`Initializing Sentry: process: ${process.pid}, thread: ${worker_threads.isMainThread ? "main" : `worker-${worker_threads.threadId}`}.`);
		super(clientOptions);
		this._onExitFlushListener = () => {
			this.emit("flush");
		};
		if (serverName) this.on("beforeCaptureLog", (log) => {
			log.attributes = {
				...log.attributes,
				[_sentry_conventions_attributes.SERVER_ADDRESS]: serverName
			};
		});
		process.on("beforeExit", this._onExitFlushListener);
		(0, _sentry_core._INTERNAL_setDeferSegmentSpanCapture)(this);
		(0, _sentry_opentelemetry.registerPrepareSpanScope)(this);
		if ((typeof __SENTRY_CHANNEL_INJECTION__ === "undefined" || __SENTRY_CHANNEL_INJECTION__) && options.enableRuntimeChannelInjection !== false) (0, _sentry_server_runtime_injection_register.registerDiagnosticsChannelInjection)();
	}
	/** @inheritDoc */
	init() {
		if (this.getOptions().enableOpenTelemetrySetup) this.asyncLocalStorageLookup = (0, _sentry_opentelemetry.setOpenTelemetryContextAsyncContextStrategy)();
		else this.asyncLocalStorageLookup = { asyncLocalStorage: (0, _sentry_server_utils.setAsyncLocalStorageAsyncContextStrategy)() };
		super.init();
	}
	/** Get the OTEL tracer. */
	get tracer() {
		if (this._tracer) return this._tracer;
		const name = "@sentry/node";
		const version = _sentry_core.SDK_VERSION;
		const tracer = _opentelemetry_api.trace.getTracer(name, version);
		this._tracer = tracer;
		return tracer;
	}
	/** @inheritDoc */
	async flush(timeout) {
		await this.traceProvider?.forceFlush();
		if (this.getOptions().sendClientReports) this._flushOutcomes();
		return super.flush(timeout);
	}
	/** @inheritDoc */
	async close(timeout) {
		if (this._clientReportInterval) clearInterval(this._clientReportInterval);
		if (this._clientReportOnExitFlushListener) process.off("beforeExit", this._clientReportOnExitFlushListener);
		if (this._onExitFlushListener) process.off("beforeExit", this._onExitFlushListener);
		const allEventsSent = await super.close(timeout);
		if (this.traceProvider) await this.traceProvider.shutdown();
		return allEventsSent;
	}
	/**
	* Will start tracking client reports for this client.
	*
	* NOTICE: This method will create an interval that is periodically called and attach a `process.on('beforeExit')`
	* hook. To clean up these resources, call `.close()` when you no longer intend to use the client. Not doing so will
	* result in a memory leak.
	*/
	startClientReportTracking() {
		const clientOptions = this.getOptions();
		if (clientOptions.sendClientReports) {
			this._clientReportOnExitFlushListener = () => {
				this._flushOutcomes();
			};
			this._clientReportInterval = setInterval(() => {
				DEBUG_BUILD && _sentry_core.debug.log("Flushing client reports based on interval.");
				this._flushOutcomes();
			}, clientOptions.clientReportFlushInterval ?? DEFAULT_CLIENT_REPORT_FLUSH_INTERVAL_MS).unref();
			process.on("beforeExit", this._clientReportOnExitFlushListener);
		}
	}
	/** @inheritDoc */
	_setupIntegrations() {
		(0, _sentry_core._INTERNAL_clearAiProviderSkips)();
		super._setupIntegrations();
	}
};
// src/otel/logger.ts
/**
* Setup the OTEL logger to use our own debug logger.
*/
function setupOpenTelemetryLogger() {
	_opentelemetry_api.diag.disable();
	_opentelemetry_api.diag.setLogger({
		error: _sentry_core.debug.error,
		warn: _sentry_core.debug.warn,
		info: _sentry_core.debug.log,
		debug: _sentry_core.debug.log,
		verbose: _sentry_core.debug.log
	}, _opentelemetry_api.DiagLogLevel.DEBUG);
}
// src/sdk/initOtel.ts
const OTEL_API_GLOBAL_KEY = Symbol.for("opentelemetry.js.api.1");
/**
* Registers the given tracer provider as the global tracer provider, recreating the OpenTelemetry
* API registry when it pre-exists with a different `@opentelemetry/api` version.
*
* Some host runtimes (e.g. Neon Functions) pre-create the registry with their own API version.
* `registerGlobal` requires an exact version match, so every registration through the SDK's copy
* of `@opentelemetry/api` is rejected and tracing is silently disabled
* (https://github.com/getsentry/sentry-javascript/issues/22338). This case is identified by a
* failed registration with an empty `trace` slot: `registerGlobal` checks the slot before the
* version, so an empty slot means the version gate rejected us and recreating the registry
* clobbers no other tracer provider. If the slot is occupied (another provider registered first,
* e.g. a second `Sentry.init()` call), the registry is left untouched and registration fails.
*
* Slots Sentry does not claim itself (e.g. `diag`, `metrics`) are carried over into the recreated
* registry: reads resolve via a semver-compatibility check rather than the exact-match write gate,
* so they keep working for the copy that registered them. `propagation` and `context` are not
* carried over because Sentry registers its own right after this.
*/
function registerGlobalTracerProvider(provider) {
	if (_opentelemetry_api.trace.setGlobalTracerProvider(provider)) return true;
	const otelGlobal = globalThis;
	const registry = otelGlobal[OTEL_API_GLOBAL_KEY];
	if (registry && !registry.trace) {
		DEBUG_BUILD && _sentry_core.debug.warn("Replaced a pre-existing OpenTelemetry API registry that was created by a different @opentelemetry/api version and would have blocked tracing. If you want to manage OpenTelemetry yourself, set `enableOpenTelemetrySetup: false` in `Sentry.init()`.");
		otelGlobal[OTEL_API_GLOBAL_KEY] = void 0;
		if (!_opentelemetry_api.trace.setGlobalTracerProvider(provider)) return false;
		const recreatedRegistry = otelGlobal[OTEL_API_GLOBAL_KEY];
		if (recreatedRegistry) {
			const { propagation: _propagation, context: _context, ...carriedOverSlots } = registry;
			otelGlobal[OTEL_API_GLOBAL_KEY] = {
				...carriedOverSlots,
				...recreatedRegistry
			};
		}
		return true;
	}
	return false;
}
/**
* Initialize OpenTelemetry for Node.
*/
function initOpenTelemetry(client) {
	if (client.getOptions().debug) setupOpenTelemetryLogger();
	client.traceProvider = setupOtel();
}
/** Just exported for tests. */
function setupOtel() {
	const provider = new _sentry_opentelemetry.SentryTracerProvider();
	if (!registerGlobalTracerProvider(provider)) {
		DEBUG_BUILD && _sentry_core.debug.warn("Could not register SentryTracerProvider because another OpenTelemetry tracer provider is already registered.");
		return;
	}
	_opentelemetry_api.propagation.setGlobalPropagator(new _sentry_opentelemetry.SentryPropagator());
	return provider;
}
// src/sdk/vercel.ts
const HTTP_ON_SERVER_RESPONSE_FINISH = "http.server.response.finish";
const REQUEST_END_TIMEOUT_MS = 2e3;
let keepAliveClient;
/**
* Keeps Vercel Node.js functions alive until the SDK has sent the telemetry of each request.
*
* Vercel can suspend a function as soon as the response is sent, so buffered events, spans, logs and metrics
* (and the timers that flush them) arrive late or never. When a response
* finishes, we register one `waitUntil` that waits for the response to close and the request's root span to
* end (2 seconds at most), and then flushes the client.
*/
function setupVercelKeepAlive(client) {
	const isRegistered = !!keepAliveClient;
	keepAliveClient = client;
	if (isRegistered) return;
	process.on("SIGTERM", async () => {
		await keepAliveClient?.flush(200);
	});
	(0, _sentry_server_utils.subscribeDiagnosticsChannel)(HTTP_ON_SERVER_RESPONSE_FINISH, (message) => {
		const { response } = message;
		const requestContext = _sentry_core.GLOBAL_OBJ[Symbol.for("@vercel/request-context")]?.get?.();
		const client = keepAliveClient;
		if (!client || !response || !requestContext?.waitUntil) return;
		const activeSpan = (0, _sentry_core.getActiveSpan)();
		const rootSpan = activeSpan && (0, _sentry_core.getRootSpan)(activeSpan);
		requestContext.waitUntil(waitForRequestEnd(client, response, rootSpan, REQUEST_END_TIMEOUT_MS).then(() => client.flush(2e3)));
	});
}
function waitForRequestEnd(client, response, rootSpan, timeout) {
	return new Promise((resolve) => {
		let responseClosed = false;
		let rootSpanEnded = !rootSpan?.isRecording();
		const done = () => {
			clearTimeout(timer);
			unsubscribe();
			resolve();
		};
		const doneIfRequestEnded = () => {
			if (responseClosed && rootSpanEnded) done();
		};
		const timer = (0, _sentry_core_server._INTERNAL_safeUnref)(setTimeout(done, timeout));
		const unsubscribe = client.on("spanEnd", (span) => {
			if (span === rootSpan) {
				rootSpanEnded = true;
				doneIfRequestEnded();
			}
		});
		response.once("close", () => {
			responseClosed = true;
			doneIfRequestEnded();
		});
	});
}
// src/sdk/index.ts
/**
* Get the base default integrations shared by all Node SDK default-integration sets.
*/
function getBaseDefaultIntegrations() {
	return [
		(0, _sentry_core.eventFiltersIntegration)(),
		(0, _sentry_core.functionToStringIntegration)(),
		(0, _sentry_core.linkedErrorsIntegration)(),
		(0, _sentry_core.dedupeIntegration)(),
		(0, _sentry_core.requestDataIntegration)(),
		systemErrorIntegration(),
		(0, _sentry_core.conversationIdIntegration)(),
		consoleIntegration(),
		httpIntegration(),
		nativeNodeFetchIntegration(),
		onUncaughtExceptionIntegration(),
		onUnhandledRejectionIntegration(),
		contextLinesIntegration(),
		localVariablesIntegration(),
		awsLambdaWebIntegration(),
		nodeContextIntegration(),
		childProcessIntegration(),
		workerThreadsIntegration(),
		processSessionIntegration(),
		modulesIntegration(),
		...(0, _sentry_server_utils.getErrorIntegrations)()
	];
}
/**
* Get default integrations, excluding performance.
*/
function getDefaultIntegrationsWithoutPerformance() {
	return getBaseDefaultIntegrations();
}
/** Get the default integrations for the Node SDK. */
function getDefaultIntegrations(options) {
	return [...getDefaultIntegrationsWithoutPerformance(), ...(0, _sentry_core.hasSpansEnabled)(options) ? (0, _sentry_server_utils.getTracingIntegrations)() : []];
}
/**
* Initialize Sentry for Node.
*/
function init(options = {}) {
	return _init(options, getDefaultIntegrations);
}
/**
* Initialize Sentry for Node, without any integrations added by default.
*/
function initWithoutDefaultIntegrations(options = {}) {
	return _init(options, () => []);
}
/**
* Internal initialization function.
*/
function _init(userOptions = {}, getDefaultIntegrationsImpl) {
	if (!node_worker_threads.isMainThread && !node_worker_threads.parentPort) return;
	if (getEntryPointType() === "require") (0, _sentry_core.consoleSandbox)(() => {
		console.warn("[Sentry] Initializing the SDK via the Node `--require` flag is no longer supported, because Node re-runs `--require` preloads on its module loader thread. Use `--import` instead: `node --import ./instrument.js app.js`");
	});
	const options = (0, _sentry_core._INTERNAL_captureOptionsSetByUser)(userOptions);
	(0, _sentry_core.applySdkMetadata)(options, "node");
	if ((0, _sentry_core.envToBool)(options.debug ?? process.env.SENTRY_DEBUG)) {
		if (DEBUG_BUILD) _sentry_core.debug.enable();
		else (0, _sentry_core.consoleSandbox)(() => {
			console.warn("[Sentry] Cannot initialize SDK with `debug` option using a non-debug bundle.");
		});
	}
	const optionsWithResolvedTracing = {
		...options,
		tracesSampleRate: getTracesSampleRate(options.tracesSampleRate)
	};
	const defaultIntegrations = options.defaultIntegrations ?? getDefaultIntegrationsImpl(optionsWithResolvedTracing);
	const clientOptions = getClientOptions({
		...options,
		defaultIntegrations
	}, getDefaultIntegrationsImpl);
	(0, _sentry_core.warnIfClientIsActive)();
	(0, _sentry_core.getCurrentScope)().update(clientOptions.initialScope);
	if (clientOptions.spotlight && !clientOptions.integrations.some(({ name }) => name === "Spotlight")) clientOptions.integrations.push(spotlightIntegration({ sidecarUrl: typeof clientOptions.spotlight === "string" ? clientOptions.spotlight : void 0 }));
	const client = new NodeClient(clientOptions);
	(0, _sentry_core.getCurrentScope)().setClient(client);
	client.init();
	_sentry_core.debug.log(`SDK initialized from CommonJS`);
	client.startClientReportTracking();
	updateScopeFromEnvVariables();
	if (process.env.VERCEL) setupVercelKeepAlive(client);
	if (clientOptions.enableOpenTelemetrySetup) initOpenTelemetry(client);
	(0, _sentry_server_utils.detectOrchestrionSetup)();
	return client;
}
function getClientOptions(options, getDefaultIntegrationsImpl) {
	const release = getRelease(options.release);
	const spotlight = getSpotlightConfig(options.spotlight);
	const tracesSampleRate = getTracesSampleRate(options.tracesSampleRate);
	const traceLifecycle = getTraceLifecycle(options.traceLifecycle);
	const mergedOptions = {
		...options,
		dsn: options.dsn ?? process.env.SENTRY_DSN,
		environment: options.environment ?? process.env.SENTRY_ENVIRONMENT,
		sendClientReports: options.sendClientReports ?? true,
		transport: options.transport ?? makeNodeTransport,
		stackParser: (0, _sentry_core.stackParserFromStackParserOptions)(options.stackParser || defaultStackParser),
		release,
		tracesSampleRate,
		spotlight,
		traceLifecycle,
		enableOpenTelemetrySetup: options.enableOpenTelemetrySetup ?? false,
		debug: (0, _sentry_core.envToBool)(options.debug ?? process.env.SENTRY_DEBUG)
	};
	const integrations = options.integrations;
	const defaultIntegrations = options.defaultIntegrations ?? getDefaultIntegrationsImpl(mergedOptions);
	const resolvedIntegrations = (0, _sentry_core.getIntegrationsToSetup)({
		defaultIntegrations,
		integrations
	});
	return {
		...mergedOptions,
		integrations: resolvedIntegrations
	};
}
function getRelease(release) {
	if (release !== void 0) return release;
	const detectedRelease = getSentryRelease();
	if (detectedRelease !== void 0) return detectedRelease;
}
function getTracesSampleRate(tracesSampleRate) {
	if (tracesSampleRate !== void 0) return tracesSampleRate;
	const sampleRateFromEnv = process.env.SENTRY_TRACES_SAMPLE_RATE;
	if (!sampleRateFromEnv) return;
	const parsed = parseFloat(sampleRateFromEnv);
	return isFinite(parsed) ? parsed : void 0;
}
function getTraceLifecycle(traceLifecycle) {
	if (traceLifecycle !== void 0) return traceLifecycle;
	const lifecycleFromEnv = process.env.SENTRY_TRACE_LIFECYCLE;
	if (lifecycleFromEnv === "stream" || lifecycleFromEnv === "static") return lifecycleFromEnv;
	return "stream";
}
/**
* Update scope and propagation context based on environmental variables.
*
* See https://github.com/getsentry/rfcs/blob/main/text/0071-continue-trace-over-process-boundaries.md
* for more details.
*/
function updateScopeFromEnvVariables() {
	if ((0, _sentry_core.envToBool)(process.env.SENTRY_USE_ENVIRONMENT) !== false) {
		const sentryTraceEnv = process.env.SENTRY_TRACE;
		const baggageEnv = process.env.SENTRY_BAGGAGE;
		const propagationContext = (0, _sentry_core.propagationContextFromHeaders)(sentryTraceEnv, baggageEnv);
		(0, _sentry_core.getCurrentScope)().setPropagationContext(propagationContext);
	}
}
// src/integrations/tracing/index.ts
function getAutoPerformanceIntegrations() {
	return (0, _sentry_server_utils.getTracingIntegrations)();
}
// src/integrations/serveTunnel.ts
/**
* Lets your server forward the events of a browser SDK set up with `tunnel: true` to Sentry.
*
* With this integration on the server and `tunnel: true` in the browser `init`, the browser sends its events to your
* own server instead of Sentry, where ad-blockers can't drop them, and your server forwards them to Sentry.
*
* Every `node:http` server answers the tunnel requests before the app sees them. To serve them from your own code
* instead, set `intercept: false` and call `handleTunnelRequestIfMatched`.
*
* By default only envelopes for the server's own DSN are forwarded.
*
* @example
* ```js
* // Server
* Sentry.init({
*   dsn: '__DSN__',
*   integrations: [Sentry.serveTunnelIntegration()],
* });
*
* // Browser
* Sentry.init({
*   dsn: '__DSN__',
*   tunnel: true,
* });
* ```
*/
const serveTunnelIntegration = (0, _sentry_server_utils.makeServeTunnelIntegration)();
// src/utils/serverTimingHeader.ts
const SERVER_TIMING_HEADER = "server-timing";
function isHttpServerResponse(response) {
	return (0, _sentry_core.isObjectLike)(response) && typeof response.writeHead === "function" && typeof response.getHeader === "function" && typeof response.setHeader === "function";
}
/**
* Sends the trace of the request in a `Server-Timing` header of a document response of the Node.js
* server, so the browser SDK continues it in the pageload span before any HTML arrived. Next.js
* flushes the headers with the first chunk of the document, inside the request span, so the value is
* computed then rather than when the request comes in. The hook fires for every request, also when
* incoming request spans are disabled, which the Next.js SDK does because Next.js starts the request
* span.
*/
function addServerTimingTraceHeader(client) {
	client.on("httpServerRequest", (_request, response) => {
		if (!isHttpServerResponse(response)) return;
		const writeHead = response.writeHead.bind(response);
		response.writeHead = (...args) => {
			setServerTimingTraceHeader(response, getHeaderObjectArgument(args));
			return writeHead(...args);
		};
	});
}
function getHeaderObjectArgument(args) {
	const last = args[args.length - 1];
	return args.length > 1 && (0, _sentry_core.isObjectLike)(last) && !Array.isArray(last) ? last : void 0;
}
function findHeaderKey(headers, name) {
	return headers && Object.keys(headers).find((key) => key.toLowerCase() === name);
}
function readHeader(response, headers, name) {
	const key = findHeaderKey(headers, name);
	const value = key ? headers?.[key] : response.getHeader(name);
	return Array.isArray(value) ? value.join(", ") : value?.toString();
}
function isDocument(response, headers) {
	return !!readHeader(response, headers, "content-type")?.toLowerCase().startsWith("text/html");
}
/**
* Adds the trace of the current context to the `Server-Timing` header of a document response that no
* shared cache may store. Next.js sends static and ISR documents with `s-maxage`, and a CDN in front of
* the server that stores them would replay the trace, and the sampling decision, of one visitor to
* everyone who gets the cached copy. An existing `sentry-trace` entry of the app is left alone.
*
* @internal
*/
function setServerTimingTraceHeader(response, headers) {
	try {
		if (response.headersSent || (0, _sentry_core.isSharedCacheable)((name) => readHeader(response, headers, name)) || !isDocument(response, headers)) return;
		const existingValue = readHeader(response, headers, SERVER_TIMING_HEADER);
		if (existingValue?.includes("sentry-trace")) return;
		const traceHeader = (0, _sentry_core.getTraceServerTimingHeader)();
		if (!traceHeader) return;
		const value = existingValue ? `${existingValue}, ${traceHeader}` : traceHeader;
		const key = findHeaderKey(headers, SERVER_TIMING_HEADER);
		if (headers && key) headers[key] = value;
		else response.setHeader("Server-Timing", value);
	} catch (e) {
		DEBUG_BUILD && _sentry_core.debug.warn("Failed to add the trace to the Server-Timing header", e);
	}
}
// src/logs/capture.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.
*/
function captureLog(level, ...args) {
	const [messageOrMessageTemplate, paramsOrAttributes, maybeAttributesOrMetadata, maybeMetadata] = args;
	if (Array.isArray(paramsOrAttributes)) {
		const attributes = { ...maybeAttributesOrMetadata };
		attributes[_sentry_conventions_attributes.SENTRY_MESSAGE_TEMPLATE] = messageOrMessageTemplate;
		paramsOrAttributes.forEach((param, index) => {
			attributes[`sentry.message.parameter.${index}`] = param;
		});
		const message = (0, node_util.format)(messageOrMessageTemplate, ...paramsOrAttributes);
		(0, _sentry_core.captureLogEvent)({
			level,
			message,
			attributes
		}, maybeMetadata?.scope);
	} else (0, _sentry_core.captureLogEvent)({
		level,
		message: messageOrMessageTemplate,
		attributes: paramsOrAttributes
	}, maybeAttributesOrMetadata?.scope ?? maybeMetadata?.scope);
}
// src/logs/exports.ts
/**
* @summary Capture a log with the `trace` level.
*
* You can either pass a message and attributes or a message template, params and attributes.
*
* @example
*
* ```
* Sentry.logger.trace('Starting database connection', {
*   database: 'users',
*   connectionId: 'conn_123'
* });
* ```
*
* @example With template strings
*
* ```
* Sentry.logger.trace('Database connection %s established for %s',
*   ['successful', 'users'],
*   { connectionId: 'conn_123' }
* );
* ```
*/
function trace(...args) {
	captureLog("trace", ...args);
}
/**
* @summary Capture a log with the `debug` level.
*
* You can either pass a message and attributes or a message template, params and attributes.
*
* @example
*
* ```
* Sentry.logger.debug('Cache miss for user profile', {
*   userId: 'user_123',
*   cacheKey: 'profile:user_123'
* });
* ```
*
* @example With template strings
*
* ```
* Sentry.logger.debug('Cache %s for %s: %s',
*   ['miss', 'user profile', 'key not found'],
*   { userId: 'user_123' }
* );
* ```
*/
function debug$1(...args) {
	captureLog("debug", ...args);
}
/**
* @summary Capture a log with the `info` level.
*
* You can either pass a message and attributes or a message template, params and attributes.
*
* @example
*
* ```
* Sentry.logger.info('User profile updated', {
*   userId: 'user_123',
*   updatedFields: ['email', 'preferences']
* });
* ```
*
* @example With template strings
*
* ```
* Sentry.logger.info('User %s updated their %s',
*   ['John Doe', 'profile settings'],
*   { userId: 'user_123' }
* );
* ```
*/
function info(...args) {
	captureLog("info", ...args);
}
/**
* @summary Capture a log with the `warn` level.
*
* You can either pass a message and attributes or a message template, params and attributes.
*
* @example
*
* ```
* Sentry.logger.warn('Rate limit approaching', {
*   endpoint: '/api/users',
*   currentRate: '95/100',
*   resetTime: '2024-03-20T10:00:00Z'
* });
* ```
*
* @example With template strings
*
* ```
* Sentry.logger.warn('Rate limit %s for %s: %s',
*   ['approaching', '/api/users', '95/100 requests'],
*   { resetTime: '2024-03-20T10:00:00Z' }
* );
* ```
*/
function warn(...args) {
	captureLog("warn", ...args);
}
/**
* @summary Capture a log with the `error` level.
*
* You can either pass a message and attributes or a message template, params and attributes.
*
* @example
*
* ```
* Sentry.logger.error('Failed to process payment', {
*   orderId: 'order_123',
*   errorCode: 'PAYMENT_FAILED',
*   amount: 99.99
* });
* ```
*
* @example With template strings
*
* ```
* Sentry.logger.error('Payment processing failed for order %s: %s',
*   ['order_123', 'insufficient funds'],
*   { amount: 99.99 }
* );
* ```
*/
function error(...args) {
	captureLog("error", ...args);
}
/**
* @summary Capture a log with the `fatal` level.
*
* You can either pass a message and attributes or a message template, params and attributes.
*
* @example
*
* ```
* Sentry.logger.fatal('Database connection pool exhausted', {
*   database: 'users',
*   activeConnections: 100,
*   maxConnections: 100
* });
* ```
*
* @example With template strings
*
* ```
* Sentry.logger.fatal('Database %s: %s connections active',
*   ['connection pool exhausted', '100/100'],
*   { database: 'users' }
* );
* ```
*/
function fatal(...args) {
	captureLog("fatal", ...args);
}
/**
* 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: _sentry_core.fmt
};
// src/integrations/nodeRuntimeMetrics.ts
const INTEGRATION_NAME$1 = "NodeRuntimeMetrics";
const DEFAULT_INTERVAL_MS = 3e4;
const MIN_COLLECTION_INTERVAL_MS = 1e3;
const EVENT_LOOP_DELAY_RESOLUTION_MS = 10;
/**
* Normalizes a `collectionIntervalMs` value, enforcing a minimum of 1000ms.
* - Non-finite values (NaN, Infinity): warns and falls back to `defaultInterval`.
* - Values below the minimum: warns and clamps to 1000ms.
* @internal
*/
function _INTERNAL_normalizeCollectionInterval(rawInterval, integrationName, defaultInterval) {
	if (!Number.isFinite(rawInterval)) {
		console.warn(`[Sentry] ${integrationName}: collectionIntervalMs (${rawInterval}) is invalid. Using default of ${defaultInterval}ms.`);
		return defaultInterval;
	}
	if (rawInterval < MIN_COLLECTION_INTERVAL_MS) {
		console.warn(`[Sentry] ${integrationName}: collectionIntervalMs (${rawInterval}) is below the minimum of ${MIN_COLLECTION_INTERVAL_MS}ms. Using minimum of ${MIN_COLLECTION_INTERVAL_MS}ms.`);
		return MIN_COLLECTION_INTERVAL_MS;
	}
	return rawInterval;
}
/**
* Automatically collects Node.js runtime metrics and emits them to Sentry.
*
* @example
* ```ts
* Sentry.init({
*   integrations: [
*     Sentry.nodeRuntimeMetricsIntegration(),
*   ],
* });
* ```
*/
const nodeRuntimeMetricsIntegration = (0, _sentry_core.defineIntegration)((options = {}) => {
	const collectionIntervalMs = _INTERNAL_normalizeCollectionInterval(options.collectionIntervalMs ?? DEFAULT_INTERVAL_MS, INTEGRATION_NAME$1, DEFAULT_INTERVAL_MS);
	const collect = {
		cpuUtilization: true,
		memHeapUsed: true,
		memHeapTotal: true,
		memRss: true,
		eventLoopDelayP50: true,
		eventLoopDelayP99: true,
		eventLoopUtilization: true,
		uptime: true,
		cpuTime: false,
		memExternal: false,
		eventLoopDelayMin: false,
		eventLoopDelayMax: false,
		eventLoopDelayMean: false,
		eventLoopDelayP90: false,
		...options.collect
	};
	const needsEventLoopDelay = collect.eventLoopDelayP99 || collect.eventLoopDelayMin || collect.eventLoopDelayMax || collect.eventLoopDelayMean || collect.eventLoopDelayP50 || collect.eventLoopDelayP90;
	const needsCpu = collect.cpuUtilization || collect.cpuTime;
	let intervalId;
	let prevCpuUsage;
	let prevElu;
	let prevFlushTime = 0;
	let eventLoopDelayHistogram;
	const resolutionNs = EVENT_LOOP_DELAY_RESOLUTION_MS * 1e6;
	const nsToS = (ns) => Math.max(0, (ns - resolutionNs) / 1e9);
	const METRIC_ATTRIBUTES = { attributes: { [_sentry_conventions_attributes.SENTRY_ORIGIN]: "auto.node.runtime_metrics" } };
	const METRIC_ATTRIBUTES_BYTE = {
		unit: "byte",
		attributes: { [_sentry_conventions_attributes.SENTRY_ORIGIN]: "auto.node.runtime_metrics" }
	};
	const METRIC_ATTRIBUTES_SECOND = {
		unit: "second",
		attributes: { [_sentry_conventions_attributes.SENTRY_ORIGIN]: "auto.node.runtime_metrics" }
	};
	function collectMetrics() {
		const now = (0, _sentry_core._INTERNAL_safeDateNow)();
		const elapsed = now - prevFlushTime;
		if (needsCpu && prevCpuUsage !== void 0) {
			const delta = process.cpuUsage(prevCpuUsage);
			if (collect.cpuTime) {
				_sentry_core.metrics.gauge("node.runtime.cpu.user", delta.user / 1e6, METRIC_ATTRIBUTES_SECOND);
				_sentry_core.metrics.gauge("node.runtime.cpu.system", delta.system / 1e6, METRIC_ATTRIBUTES_SECOND);
			}
			if (collect.cpuUtilization && elapsed > 0) _sentry_core.metrics.gauge("node.runtime.cpu.utilization", (delta.user + delta.system) / (elapsed * 1e3), METRIC_ATTRIBUTES);
			prevCpuUsage = process.cpuUsage();
		}
		if (collect.memRss || collect.memHeapUsed || collect.memHeapTotal || collect.memExternal) {
			const mem = process.memoryUsage();
			if (collect.memRss) _sentry_core.metrics.gauge("node.runtime.mem.rss", mem.rss, METRIC_ATTRIBUTES_BYTE);
			if (collect.memHeapUsed) _sentry_core.metrics.gauge("node.runtime.mem.heap_used", mem.heapUsed, METRIC_ATTRIBUTES_BYTE);
			if (collect.memHeapTotal) _sentry_core.metrics.gauge("node.runtime.mem.heap_total", mem.heapTotal, METRIC_ATTRIBUTES_BYTE);
			if (collect.memExternal) {
				_sentry_core.metrics.gauge("node.runtime.mem.external", mem.external, METRIC_ATTRIBUTES_BYTE);
				_sentry_core.metrics.gauge("node.runtime.mem.array_buffers", mem.arrayBuffers, METRIC_ATTRIBUTES_BYTE);
			}
		}
		if (needsEventLoopDelay && eventLoopDelayHistogram) {
			if (collect.eventLoopDelayMin) _sentry_core.metrics.gauge("node.runtime.event_loop.delay.min", nsToS(eventLoopDelayHistogram.min), METRIC_ATTRIBUTES_SECOND);
			if (collect.eventLoopDelayMax) _sentry_core.metrics.gauge("node.runtime.event_loop.delay.max", nsToS(eventLoopDelayHistogram.max), METRIC_ATTRIBUTES_SECOND);
			if (collect.eventLoopDelayMean) _sentry_core.metrics.gauge("node.runtime.event_loop.delay.mean", nsToS(eventLoopDelayHistogram.mean), METRIC_ATTRIBUTES_SECOND);
			if (collect.eventLoopDelayP50) _sentry_core.metrics.gauge("node.runtime.event_loop.delay.p50", nsToS(eventLoopDelayHistogram.percentile(50)), METRIC_ATTRIBUTES_SECOND);
			if (collect.eventLoopDelayP90) _sentry_core.metrics.gauge("node.runtime.event_loop.delay.p90", nsToS(eventLoopDelayHistogram.percentile(90)), METRIC_ATTRIBUTES_SECOND);
			if (collect.eventLoopDelayP99) _sentry_core.metrics.gauge("node.runtime.event_loop.delay.p99", nsToS(eventLoopDelayHistogram.percentile(99)), METRIC_ATTRIBUTES_SECOND);
			eventLoopDelayHistogram.reset();
		}
		if (collect.eventLoopUtilization && prevElu !== void 0) {
			const currentElu = perf_hooks.performance.eventLoopUtilization();
			const delta = perf_hooks.performance.eventLoopUtilization(currentElu, prevElu);
			_sentry_core.metrics.gauge("node.runtime.event_loop.utilization", delta.utilization, METRIC_ATTRIBUTES);
			prevElu = currentElu;
		}
		if (collect.uptime && elapsed > 0) _sentry_core.metrics.count("node.runtime.process.uptime", elapsed / 1e3, METRIC_ATTRIBUTES_SECOND);
		prevFlushTime = now;
	}
	return {
		name: INTEGRATION_NAME$1,
		setup() {
			if (needsEventLoopDelay) {
				eventLoopDelayHistogram?.disable();
				try {
					eventLoopDelayHistogram = (0, perf_hooks.monitorEventLoopDelay)({ resolution: EVENT_LOOP_DELAY_RESOLUTION_MS });
					eventLoopDelayHistogram.enable();
				} catch {
					eventLoopDelayHistogram = void 0;
				}
			}
			if (needsCpu) prevCpuUsage = process.cpuUsage();
			if (collect.eventLoopUtilization) prevElu = perf_hooks.performance.eventLoopUtilization();
			prevFlushTime = (0, _sentry_core._INTERNAL_safeDateNow)();
			if (intervalId) clearInterval(intervalId);
			intervalId = (0, _sentry_core_server._INTERNAL_safeUnref)(setInterval(collectMetrics, collectionIntervalMs));
		}
	};
});
// src/eve.ts
/**
* All-in-one Sentry setup for an [eve](https://eve.dev) agent, wired into a single
* `agent/instrumentation/*.ts` provider file.
*
* @example
* ```ts
* // agent/instrumentation/sentry.ts
* import * as Sentry from '@sentry/node';
* import { defineInstrumentation } from 'eve/instrumentation';
*
* export default defineInstrumentation(Sentry.eveInstrumentation({ dsn: '__DSN__' }));
* ```
*
* It:
* - runs `Sentry.init` with the given options at server startup (`setup`), adding {@link eveIntegration};
* - asks eve for full gen_ai results ({@link eveTracePolicy}); Sentry filters content by `dataCollection.genAI`
*   when it builds spans. On eve >= 1.0.0-rc.10 this also sets the AI SDK's `recordInputs`/`recordOutputs` flags,
*   which apply to every AI SDK telemetry integration in the app;
* - tags each turn's AI spans with a Sentry conversation id via `turn.started` and `step.attempt.started`
*   (eve < 0.84) / `model.started` (eve >= 0.84) events — the instrumentation-provider equivalent of `eveConversationHook`. Provider event handlers
*   receive the session id on the event (`event.sessionId` / `event.scope.sessionId`), unlike hook
*   handlers, which read it from their context.
*/
function eveInstrumentation(options = {}) {
	const { getConversationId, ...initOptions } = options;
	const setConversationIdFromSession = (sessionId) => {
		(0, _sentry_core.setConversationId)(getConversationId ? getConversationId({ session: { id: sessionId } }) : sessionId);
	};
	return {
		setup() {
			init({
				...initOptions,
				integrations: withEveIntegration(initOptions.integrations)
			});
		},
		tracePolicy: _sentry_server_utils.eveTracePolicy,
		events: {
			"turn.started": (event) => setConversationIdFromSession(event.sessionId),
			"step.attempt.started": (event) => setConversationIdFromSession(event.scope.sessionId),
			"model.started": (event) => setConversationIdFromSession(event.scope.sessionId)
		}
	};
}
function withEveIntegration(integrations) {
	const eve = (0, _sentry_server_utils.eveIntegration)();
	if (typeof integrations === "function") return (defaults) => [...integrations(defaults), eve];
	return [...integrations ?? [], eve];
}
// src/integrations/anr/index.ts
const { isPromise } = node_util.types;
const base64WorkerScript = "LyohIEBzZW50cnkvbm9kZSAxMS4yMC4wICg0NTU5NTA2KSB8IGh0dHBzOi8vZ2l0aHViLmNvbS9nZXRzZW50cnkvc2VudHJ5LWphdmFzY3JpcHQgKi8KaW1wb3J0e1Nlc3Npb24gYXMgZX1mcm9tIm5vZGU6aW5zcGVjdG9yIjtpbXBvcnR7cGFyZW50UG9ydCBhcyB0LHdvcmtlckRhdGEgYXMgbn1mcm9tIm5vZGU6d29ya2VyX3RocmVhZHMiO2ltcG9ydHtwb3NpeCBhcyByLHNlcCBhcyBpfWZyb20ibm9kZTpwYXRoIjtpbXBvcnQqYXMgYSBmcm9tIm5vZGU6bmV0IjtpbXBvcnQqYXMgbyBmcm9tIm5vZGU6aHR0cCI7aW1wb3J0KmFzIHMgZnJvbSJub2RlOmh0dHBzIjtpbXBvcnR7UmVhZGFibGUgYXMgY31mcm9tIm5vZGU6c3RyZWFtIjtpbXBvcnR7Y3JlYXRlR3ppcCBhcyBsfWZyb20ibm9kZTp6bGliIjtpbXBvcnQqYXMgdSBmcm9tIm5vZGU6dGxzIjtjb25zdCBkPXR5cGVvZiBfX1NFTlRSWV9ERUJVR19fPmB1YHx8X19TRU5UUllfREVCVUdfXyxmPWdsb2JhbFRoaXMscD1gMTEuMjAuMGA7ZnVuY3Rpb24gbSgpe3JldHVybiBoKGYpLGZ9ZnVuY3Rpb24gaChlKXtsZXQgdD1lLl9fU0VOVFJZX189ZS5fX1NFTlRSWV9ffHx7fTtyZXR1cm4gdC52ZXJzaW9uPXQudmVyc2lvbnx8YDExLjIwLjBgLHRbcF09dFtgMTEuMjAuMGBdfHx7fX1mdW5jdGlvbiBnKGU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l9KX1jYXRjaHt9fX1mdW5jdGlvbiBubigpe2xldCBlPXByb2Nlc3MuaHJ0aW1lLmJpZ2ludCgpO3JldHVybntnZXRUaW1lTXM6KCk9Pk51bWJlcigocHJvY2Vzcy5ocnRpbWUuYmlnaW50KCktZSkvMTAwMDAwMG4pLHJlc2V0OigpPT57ZT1wcm9jZXNzLmhydGltZS5iaWdpbnQoKX19fWZ1bmN0aW9uIHJuKCl7WChgV2F0Y2hkb2cgdGltZW91dGApLCQ/KFgoYFBhdXNpbmcgZGVidWdnZXIgdG8gY2FwdHVyZSBzdGFjayB0cmFjZWApLCQoKSk6KFgoYENhcHR1cmluZyBldmVudCB3aXRob3V0IGEgc3RhY2sgdHJhY2VgKSxRKCkudGhlbihudWxsLCgpPT57WChgU2VuZGluZyBBTlIgZXZlbnQgZmFpbGVkIG9uIHdhdGNoZG9nIHRpbWVvdXQuYCl9KSl9Y29uc3R7cG9sbDphbn09UnQobm4sSy5wb2xsSW50ZXJ2YWwsSy5hbnJUaHJlc2hvbGQscm4pO3Q/Lm9uKGBtZXNzYWdlYCxlPT57ZS5zZXNzaW9uJiYocT1QZShlLnNlc3Npb24pKSxlLmRlYnVnSW1hZ2VzJiYoWT1lLmRlYnVnSW1hZ2VzKSxhbigpfSksdD8ucG9zdE1lc3NhZ2UoYHdvcmtlci1yZWFkeWApOw==";
const DEFAULT_INTERVAL = 50;
const DEFAULT_HANG_THRESHOLD = 5e3;
function log(message, ...args) {
	_sentry_core.debug.log(`[ANR] ${message}`, ...args);
}
function globalWithScopeFetchFn() {
	return _sentry_core.GLOBAL_OBJ;
}
/** Fetches merged scope data */
function getScopeData() {
	const scope = (0, _sentry_core.getCombinedScopeData)((0, _sentry_core.getIsolationScope)(), (0, _sentry_core.getCurrentScope)());
	scope.attachments = [];
	scope.eventProcessors = [];
	return scope;
}
/**
* Gets contexts by calling all event processors. This shouldn't be called until all integrations are setup
*/
async function getContexts(client) {
	let event = { message: "ANR" };
	const eventHint = {};
	for (const processor of client.getEventProcessors()) {
		if (event === null) break;
		if (processor.id === "Dedupe") continue;
		event = await processor(event, eventHint);
	}
	return event?.contexts || {};
}
const INTEGRATION_NAME = "Anr";
const _anrIntegration = ((options = {}) => {
	let worker;
	let client;
	let workerReady;
	const gbl = globalWithScopeFetchFn();
	gbl.__SENTRY_GET_SCOPES__ = getScopeData;
	return {
		name: INTEGRATION_NAME,
		startWorker: () => {
			if (worker) return;
			const initializedClient = client;
			if (initializedClient) workerReady = new Promise((resolve) => {
				worker = _startWorker(initializedClient, options, resolve);
			});
		},
		stopWorker: () => {
			if (worker) {
				workerReady = void 0;
				worker.then((stop) => {
					stop();
					worker = void 0;
				});
			}
		},
		waitUntilWorkerReady: () => workerReady ?? Promise.resolve(),
		async setup(initClient) {
			client = initClient;
			if (options.captureStackTrace && await isDebuggerEnabled()) {
				_sentry_core.debug.warn("ANR captureStackTrace has been disabled because the debugger was already enabled");
				options.captureStackTrace = false;
			}
			setImmediate(() => this.startWorker());
		}
	};
});
/**
* Application Not Responding (ANR) integration for Node.js applications.
*
* @deprecated The ANR integration has been deprecated. Use `eventLoopBlockIntegration` from `@sentry/node-native` instead.
*
* Detects when the Node.js main thread event loop is blocked for more than the configured
* threshold (5 seconds by default) and reports these as Sentry events.
*
* ANR detection uses a worker thread to monitor the event loop in the main app thread.
* The main app thread sends a heartbeat message to the ANR worker thread every 50ms by default.
* If the ANR worker does not receive a heartbeat message for the configured threshold duration,
* it triggers an ANR event.
*
* - Node.js 16.17.0 or higher
* - Only supported in the Node.js runtime (not browsers)
* - Not supported for Node.js clusters
*
* Overhead should be minimal:
* - Main thread: Only polling the ANR worker over IPC every 50ms
* - Worker thread: Consumes around 10-20 MB of RAM
* - When ANR detected: Brief pause in debugger to capture stack trace (negligible compared to the blocking)
*
* @example
* ```javascript
* Sentry.init({
*   dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",
*   integrations: [
*     Sentry.anrIntegration({
*       anrThreshold: 5000,
*       captureStackTrace: true,
*       pollInterval: 50,
*     }),
*   ],
* });
* ```
*/
const anrIntegration = (0, _sentry_core.defineIntegration)(_anrIntegration);
/**
* Starts the ANR worker thread
*
* @returns A function to stop the worker
*/
async function _startWorker(client, integrationOptions, onReady) {
	const dsn = client.getDsn();
	if (!dsn) return () => {};
	const contexts = await getContexts(client);
	delete contexts.app?.app_memory;
	delete contexts.device?.free_memory;
	const initOptions = client.getOptions();
	const sdkMetadata = client.getSdkMetadata() || {};
	if (sdkMetadata.sdk) sdkMetadata.sdk.integrations = initOptions.integrations.map((i) => i.name);
	const options = {
		debug: _sentry_core.debug.isEnabled(),
		dsn,
		tunnel: initOptions.tunnel,
		environment: initOptions.environment || "production",
		release: initOptions.release,
		dist: initOptions.dist,
		sdkMetadata,
		appRootPath: integrationOptions.appRootPath,
		pollInterval: integrationOptions.pollInterval || DEFAULT_INTERVAL,
		anrThreshold: integrationOptions.anrThreshold || DEFAULT_HANG_THRESHOLD,
		captureStackTrace: !!integrationOptions.captureStackTrace,
		maxAnrEvents: integrationOptions.maxAnrEvents || 1,
		staticTags: integrationOptions.staticTags || {},
		contexts
	};
	if (options.captureStackTrace) {
		const inspector = await import("node:inspector");
		if (!inspector.url()) inspector.open(0);
	}
	const worker = new node_worker_threads.Worker(new URL(`data:application/javascript;base64,${base64WorkerScript}`), {
		workerData: options,
		execArgv: [],
		env: {
			...process.env,
			NODE_OPTIONS: void 0
		}
	});
	process.on("exit", () => {
		worker.terminate();
	});
	const timer = setInterval(() => {
		try {
			const currentSession = (0, _sentry_core.getIsolationScope)().getSession();
			const session = currentSession ? {
				...currentSession,
				toJSON: void 0
			} : void 0;
			worker.postMessage({
				session,
				debugImages: (0, _sentry_core.getFilenameToDebugIdMap)(initOptions.stackParser)
			});
		} catch {}
	}, options.pollInterval);
	timer.unref();
	worker.on("message", (msg) => {
		if (msg === "session-ended") {
			log("ANR event sent from ANR worker. Clearing session in this thread.");
			(0, _sentry_core.getIsolationScope)().setSession(void 0);
		} else if (msg === "worker-ready") onReady?.();
	});
	worker.once("error", (err) => {
		clearInterval(timer);
		log("ANR worker error", err);
	});
	worker.once("exit", (code) => {
		clearInterval(timer);
		log("ANR worker exit", code);
	});
	worker.unref();
	return () => {
		worker.terminate();
		clearInterval(timer);
	};
}
/**
* Temporarily disables ANR detection for the duration of a callback function.
*
* This utility function allows you to disable ANR detection during operations that
* are expected to block the event loop, such as intensive computational tasks or
* synchronous I/O operations.
*
* @deprecated The ANR integration has been deprecated. Use `eventLoopBlockIntegration` from `@sentry/node-native` instead.
*/
function disableAnrDetectionForCallback(callback) {
	const integration = (0, _sentry_core.getClient)()?.getIntegrationByName(INTEGRATION_NAME);
	if (!integration) return callback();
	integration.stopWorker();
	const result = callback();
	if (isPromise(result)) return result.finally(() => integration.startWorker());
	integration.startWorker();
	return result;
}
exports.BullMQTelemetry = _sentry_server_utils.BullMQTelemetry;
exports.NODE_VERSION = NODE_VERSION;
exports.NodeClient = NodeClient;
exports.OpenFeatureIntegrationHook = OpenFeatureIntegrationHookShim;
exports.SDK_VERSION = _sentry_core.SDK_VERSION;
exports.SEMANTIC_ATTRIBUTE_SENTRY_OP = _sentry_core.SEMANTIC_ATTRIBUTE_SENTRY_OP;
exports.SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN = _sentry_core.SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN;
exports.SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE = _sentry_core.SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE;
exports.Scope = _sentry_core.Scope;
exports.SentryMastraExporter = _sentry_server_utils.SentryMastraExporter;
exports._INTERNAL_normalizeCollectionInterval = _INTERNAL_normalizeCollectionInterval;
exports.addBreadcrumb = _sentry_core.addBreadcrumb;
exports.addEventProcessor = _sentry_core.addEventProcessor;
exports.addIntegration = _sentry_core.addIntegration;
exports.addServerTimingTraceHeader = addServerTimingTraceHeader;
exports.amqplibIntegration = _sentry_server_utils.amqplibIntegration;
exports.anrIntegration = anrIntegration;
exports.anthropicAIIntegration = _sentry_server_utils.anthropicAIIntegration;
exports.awsIntegration = _sentry_server_utils.awsIntegration;
exports.awsLambdaWebIntegration = awsLambdaWebIntegration;
exports.bindScopeToEmitter = _sentry_core.bindScopeToEmitter;
exports.buildLaunchDarklyFlagUsedHandler = buildLaunchDarklyFlagUsedHandlerShim;
exports.captureCheckIn = _sentry_core.captureCheckIn;
exports.captureConsoleIntegration = _sentry_core.captureConsoleIntegration;
exports.captureEvent = _sentry_core.captureEvent;
exports.captureException = _sentry_core.captureException;
exports.captureFeedback = _sentry_core.captureFeedback;
exports.captureMessage = _sentry_core.captureMessage;
exports.captureSession = _sentry_core.captureSession;
exports.childProcessIntegration = childProcessIntegration;
exports.clickhouseIntegration = _sentry_server_utils.clickhouseIntegration;
exports.close = _sentry_core.close;
exports.consoleIntegration = consoleIntegration;
exports.consoleLoggingIntegration = _sentry_core.consoleLoggingIntegration;
exports.contextLinesIntegration = contextLinesIntegration;
exports.continueTrace = _sentry_core.continueTrace;
exports.createConsolaReporter = _sentry_core.createConsolaReporter;
exports.createFlueInstrumentation = _sentry_server_utils.createFlueInstrumentation;
exports.createGetModuleFromFilename = _sentry_server_utils.createGetModuleFromFilename;
exports.createLangChainCallbackHandler = _sentry_server_utils.createLangChainCallbackHandler;
exports.createSentryWinstonTransport = _sentry_server_utils.createSentryWinstonTransport;
exports.createTransport = _sentry_core.createTransport;
exports.cron = _sentry_server_utils.cron;
exports.cronJobIntegration = _sentry_server_utils.cronJobIntegration;
exports.dataloaderIntegration = _sentry_server_utils.dataloaderIntegration;
exports.dedupeIntegration = _sentry_core.dedupeIntegration;
exports.defaultStackParser = defaultStackParser;
exports.disableAnrDetectionForCallback = disableAnrDetectionForCallback;
exports.endSession = _sentry_core.endSession;
exports.eveConversationHook = _sentry_server_utils.eveConversationHook;
exports.eveInstrumentation = eveInstrumentation;
exports.eveIntegration = _sentry_server_utils.eveIntegration;
exports.eventFiltersIntegration = _sentry_core.eventFiltersIntegration;
exports.experimentalReportSdkConfigIntegration = _sentry_core.experimentalReportSdkConfigIntegration;
exports.expressErrorHandler = _sentry_server_utils.expressErrorHandler;
exports.expressIntegration = _sentry_server_utils.expressIntegration;
exports.extraErrorDataIntegration = _sentry_core.extraErrorDataIntegration;
exports.fastifyIntegration = _sentry_server_utils.fastifyIntegration;
exports.featureFlagsIntegration = _sentry_core.featureFlagsIntegration;
exports.firebaseIntegration = _sentry_server_utils.firebaseIntegration;
exports.flush = _sentry_core.flush;
exports.fsIntegration = fsIntegration;
exports.functionToStringIntegration = _sentry_core.functionToStringIntegration;
exports.genericPoolIntegration = _sentry_server_utils.genericPoolIntegration;
exports.getActiveSpan = _sentry_core.getActiveSpan;
exports.getAutoPerformanceIntegrations = getAutoPerformanceIntegrations;
exports.getClient = _sentry_core.getClient;
exports.getCurrentScope = _sentry_core.getCurrentScope;
exports.getDefaultIntegrations = getDefaultIntegrations;
exports.getDefaultIntegrationsWithoutPerformance = getDefaultIntegrationsWithoutPerformance;
exports.getGlobalScope = _sentry_core.getGlobalScope;
exports.getHttpAgent = getHttpAgent;
exports.getInstrumentedModuleNames = _sentry_server_utils.getInstrumentedModuleNames;
exports.getIsolationScope = _sentry_core.getIsolationScope;
exports.getOtlpTracesEndpoint = _sentry_server_utils.getOtlpTracesEndpoint;
exports.getRootSpan = _sentry_core.getRootSpan;
exports.getSentryRelease = getSentryRelease;
exports.getSpanDescendants = _sentry_core.getSpanDescendants;
exports.getSpanStatusFromHttpCode = _sentry_core.getSpanStatusFromHttpCode;
exports.getTraceData = _sentry_core.getTraceData;
exports.getTraceMetaTags = _sentry_core.getTraceMetaTags;
exports.getTunnelPath = _sentry_core.getTunnelPath;
exports.googleGenAIIntegration = _sentry_server_utils.googleGenAIIntegration;
exports.graphqlIntegration = _sentry_server_utils.graphqlIntegration;
exports.groqIntegration = _sentry_server_utils.groqIntegration;
exports.growthbookIntegration = growthbookIntegrationShim;
exports.handleTunnelRequest = _sentry_core.handleTunnelRequest;
exports.handleTunnelRequestIfMatched = _sentry_core_server.handleTunnelRequestIfMatched;
exports.hapiIntegration = _sentry_server_utils.hapiIntegration;
exports.honoIntegration = _sentry_server_utils.honoIntegration;
exports.honoMiddleware = _sentry_server_utils.honoMiddleware;
exports.httpHeadersToSpanAttributes = _sentry_core.httpHeadersToSpanAttributes;
exports.httpIntegration = httpIntegration;
exports.httpServerIntegration = httpServerIntegration;
exports.httpServerSpansIntegration = httpServerSpansIntegration;
exports.init = init;
exports.initOpenTelemetry = initOpenTelemetry;
exports.initWithoutDefaultIntegrations = initWithoutDefaultIntegrations;
exports.instrumentAnthropicAiClient = _sentry_server_utils.instrumentAnthropicAiClient;
exports.instrumentCreateReactAgent = _sentry_server_utils.instrumentCreateReactAgent;
exports.instrumentGoogleGenAIClient = _sentry_server_utils.instrumentGoogleGenAIClient;
exports.instrumentLangChainEmbeddings = _sentry_server_utils.instrumentLangChainEmbeddings;
exports.instrumentMistralAiClient = _sentry_server_utils.instrumentMistralAiClient;
exports.instrumentOpenAiClient = _sentry_server_utils.instrumentOpenAiClient;
exports.instrumentPostgresJsSql = _sentry_server_utils.instrumentPostgresJsSql;
exports.instrumentStateGraph = _sentry_server_utils.instrumentStateGraph;
exports.instrumentStateGraphCompile = _sentry_server_utils.instrumentStateGraphCompile;
exports.instrumentSupabaseClient = _sentry_core.instrumentSupabaseClient;
exports.instrumentTypeSafeClient = _sentry_server_utils.instrumentTypeSafeClient;
exports.isEnabled = _sentry_core.isEnabled;
exports.isInitialized = _sentry_core.isInitialized;
exports.isTunnelRequest = _sentry_core_server.isTunnelRequest;
exports.kafkaIntegration = _sentry_server_utils.kafkaIntegration;
exports.knexIntegration = _sentry_server_utils.knexIntegration;
exports.koaIntegration = _sentry_server_utils.koaIntegration;
exports.langChainIntegration = _sentry_server_utils.langChainIntegration;
exports.langGraphIntegration = _sentry_server_utils.langGraphIntegration;
exports.lastEventId = _sentry_core.lastEventId;
exports.launchDarklyIntegration = launchDarklyIntegrationShim;
exports.linkedErrorsIntegration = _sentry_core.linkedErrorsIntegration;
exports.localVariablesIntegration = localVariablesIntegration;
exports.logger = logger;
exports.lruMemoizerIntegration = _sentry_server_utils.lruMemoizerIntegration;
exports.makeNodeTransport = makeNodeTransport;
exports.mastraIntegration = _sentry_server_utils.mastraIntegration;
exports.mcpServerIntegration = _sentry_server_utils.mcpServerIntegration;
exports.metrics = _sentry_core.metrics;
exports.mistralAIIntegration = _sentry_server_utils.mistralAIIntegration;
exports.moduleMetadataIntegration = _sentry_core.moduleMetadataIntegration;
exports.modulesIntegration = modulesIntegration;
exports.mongoIntegration = _sentry_server_utils.mongoIntegration;
exports.mongooseIntegration = _sentry_server_utils.mongooseIntegration;
exports.mysql2Integration = _sentry_server_utils.mysql2Integration;
exports.mysqlIntegration = _sentry_server_utils.mysqlIntegration;
exports.nativeNodeFetchIntegration = nativeNodeFetchIntegration;
exports.neonIntegration = _sentry_server_utils.neonIntegration;
exports.nitroIntegration = _sentry_server_utils.nitroIntegration;
exports.nodeContextIntegration = nodeContextIntegration;
exports.nodeCronIntegration = _sentry_server_utils.nodeCronIntegration;
exports.nodeRuntimeMetricsIntegration = nodeRuntimeMetricsIntegration;
exports.nodeScheduleIntegration = _sentry_server_utils.nodeScheduleIntegration;
exports.onUncaughtExceptionIntegration = onUncaughtExceptionIntegration;
exports.onUnhandledRejectionIntegration = onUnhandledRejectionIntegration;
exports.openAIIntegration = _sentry_server_utils.openAIIntegration;
exports.openFeatureIntegration = openFeatureIntegrationShim;
exports.openTelemetryIntegration = _sentry_server_utils.openTelemetryIntegration;
exports.parameterize = _sentry_core.parameterize;
exports.piAiIntegration = _sentry_server_utils.piAiIntegration;
exports.piDurableIntegration = _sentry_server_utils.piDurableIntegration;
exports.pinoIntegration = _sentry_server_utils.pinoIntegration;
exports.postgresIntegration = _sentry_server_utils.postgresIntegration;
exports.postgresJsIntegration = _sentry_server_utils.postgresJsIntegration;
exports.prismaIntegration = _sentry_server_utils.prismaIntegration;
exports.processSessionIntegration = processSessionIntegration;
exports.profiler = _sentry_core.profiler;
exports.redisIntegration = _sentry_server_utils.redisIntegration;
exports.requestDataIntegration = _sentry_core.requestDataIntegration;
exports.rewriteFramesIntegration = _sentry_core.rewriteFramesIntegration;
exports.serveTunnelIntegration = serveTunnelIntegration;
exports.setAttribute = _sentry_core.setAttribute;
exports.setAttributes = _sentry_core.setAttributes;
exports.setContext = _sentry_core.setContext;
exports.setConversationId = _sentry_core.setConversationId;
exports.setCurrentClient = _sentry_core.setCurrentClient;
exports.setExtra = _sentry_core.setExtra;
exports.setExtras = _sentry_core.setExtras;
exports.setHttpStatus = _sentry_core.setHttpStatus;
exports.setMeasurement = _sentry_core.setMeasurement;
exports.setOpenTelemetryContextAsyncContextStrategy = _sentry_opentelemetry.setOpenTelemetryContextAsyncContextStrategy;
exports.setTag = _sentry_core.setTag;
exports.setTags = _sentry_core.setTags;
exports.setUser = _sentry_core.setUser;
exports.setupExpressErrorHandler = _sentry_server_utils.setupExpressErrorHandler;
exports.setupFastifyErrorHandler = _sentry_server_utils.setupFastifyErrorHandler;
exports.setupHapiErrorHandler = _sentry_server_utils.setupHapiErrorHandler;
exports.setupKoaErrorHandler = setupKoaErrorHandler;
exports.spanStreamingIntegration = _sentry_core.spanStreamingIntegration;
exports.spanToBaggageHeader = _sentry_core.spanToBaggageHeader;
exports.spanToJSON = _sentry_core.spanToJSON;
exports.spanToStaticSpanJSON = _sentry_core.spanToStaticSpanJSON;
exports.spanToTraceHeader = _sentry_core.spanToTraceHeader;
exports.spotlightIntegration = spotlightIntegration;
exports.startInactiveSpan = _sentry_core.startInactiveSpan;
exports.startNewTrace = _sentry_core.startNewTrace;
exports.startSession = _sentry_core.startSession;
exports.startSpan = _sentry_core.startSpan;
exports.startSpanManual = _sentry_core.startSpanManual;
exports.statsigIntegration = statsigIntegrationShim;
exports.supabaseIntegration = _sentry_core.supabaseIntegration;
exports.suppressTracing = _sentry_core.suppressTracing;
exports.systemErrorIntegration = systemErrorIntegration;
exports.tediousIntegration = _sentry_server_utils.tediousIntegration;
exports.togetherAIIntegration = _sentry_server_utils.togetherAIIntegration;
exports.trpcMiddleware = _sentry_core_server.trpcMiddleware;
exports.typesafeIntegration = _sentry_server_utils.typesafeIntegration;
exports.unleashIntegration = unleashIntegrationShim;
exports.updateSpanName = _sentry_core.updateSpanName;
exports.vercelAIIntegration = _sentry_server_utils.vercelAIIntegration;
exports.winterCGHeadersToDict = _sentry_core.winterCGHeadersToDict;
exports.withActiveSpan = _sentry_core.withActiveSpan;
exports.withIsolationScope = _sentry_core.withIsolationScope;
exports.withMonitor = _sentry_core.withMonitor;
exports.withScope = _sentry_core.withScope;
exports.withStaticSpan = _sentry_core.withStaticSpan;
exports.withStreamedSpan = _sentry_core.withStreamedSpan;
exports.workerThreadsIntegration = workerThreadsIntegration;
exports.wrapMcpServerWithSentry = _sentry_core_server.wrapMcpServerWithSentry;
exports.zodErrorsIntegration = _sentry_core.zodErrorsIntegration;

//# sourceMappingURL=index.js.map