@sentry/opentelemetry 10.68.0 → 11.0.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (124) hide show
  1. package/README.md +2 -15
  2. package/build/cjs/index.js +844 -95
  3. package/build/cjs/index.js.map +1 -1
  4. package/build/esm/index.js +837 -58
  5. package/build/esm/index.js.map +1 -1
  6. package/build/esm/package.json +1 -1
  7. package/build/types/applyOtelSpanData.d.ts +1 -4
  8. package/build/types/applyOtelSpanData.d.ts.map +1 -1
  9. package/build/types/asyncContextStrategy.d.ts +2 -4
  10. package/build/types/asyncContextStrategy.d.ts.map +1 -1
  11. package/build/types/asyncLocalStorageContextManager.d.ts +16 -4
  12. package/build/types/asyncLocalStorageContextManager.d.ts.map +1 -1
  13. package/build/types/constants.d.ts +0 -10
  14. package/build/types/constants.d.ts.map +1 -1
  15. package/build/types/index.d.ts +8 -4
  16. package/build/types/index.d.ts.map +1 -1
  17. package/build/types/propagator.d.ts +12 -33
  18. package/build/types/propagator.d.ts.map +1 -1
  19. package/build/types/trace.d.ts +1 -27
  20. package/build/types/trace.d.ts.map +1 -1
  21. package/build/types/tracer.d.ts.map +1 -1
  22. package/build/types/tracerProvider.d.ts +0 -9
  23. package/build/types/tracerProvider.d.ts.map +1 -1
  24. package/build/types/types.d.ts +2 -21
  25. package/build/types/types.d.ts.map +1 -1
  26. package/build/types/utils/TraceState.d.ts.map +1 -1
  27. package/build/types/utils/backfillStreamedSpanData.d.ts +1 -3
  28. package/build/types/utils/backfillStreamedSpanData.d.ts.map +1 -1
  29. package/build/types/utils/mapStatus.d.ts +0 -6
  30. package/build/types/utils/mapStatus.d.ts.map +1 -1
  31. package/build/types/utils/parseSpanDescription.d.ts +6 -30
  32. package/build/types/utils/parseSpanDescription.d.ts.map +1 -1
  33. package/build/types/utils/reconcileDscSampled.d.ts +14 -0
  34. package/build/types/utils/reconcileDscSampled.d.ts.map +1 -0
  35. package/build/types/utils/suppressTracing.d.ts +5 -4
  36. package/build/types/utils/suppressTracing.d.ts.map +1 -1
  37. package/package.json +10 -37
  38. package/build/cjs/asyncContextStrategy-volGaYqZ.js +0 -1892
  39. package/build/cjs/asyncContextStrategy-volGaYqZ.js.map +0 -1
  40. package/build/cjs/index.browser.js +0 -53
  41. package/build/cjs/index.browser.js.map +0 -1
  42. package/build/esm/asyncContextStrategy-jD8YWNDU.js +0 -1857
  43. package/build/esm/asyncContextStrategy-jD8YWNDU.js.map +0 -1
  44. package/build/esm/index.browser.js +0 -14
  45. package/build/esm/index.browser.js.map +0 -1
  46. package/build/types/contextManager.d.ts +0 -22
  47. package/build/types/contextManager.d.ts.map +0 -1
  48. package/build/types/custom/client.d.ts +0 -12
  49. package/build/types/custom/client.d.ts.map +0 -1
  50. package/build/types/exports.d.ts +0 -27
  51. package/build/types/exports.d.ts.map +0 -1
  52. package/build/types/index.browser.d.ts +0 -10
  53. package/build/types/index.browser.d.ts.map +0 -1
  54. package/build/types/nodeAsyncContextStrategy.d.ts +0 -4
  55. package/build/types/nodeAsyncContextStrategy.d.ts.map +0 -1
  56. package/build/types/resource.d.ts +0 -26
  57. package/build/types/resource.d.ts.map +0 -1
  58. package/build/types/sampler.d.ts +0 -32
  59. package/build/types/sampler.d.ts.map +0 -1
  60. package/build/types/semanticAttributes.d.ts +0 -4
  61. package/build/types/semanticAttributes.d.ts.map +0 -1
  62. package/build/types/spanExporter.d.ts +0 -50
  63. package/build/types/spanExporter.d.ts.map +0 -1
  64. package/build/types/spanProcessor.d.ts +0 -31
  65. package/build/types/spanProcessor.d.ts.map +0 -1
  66. package/build/types/utils/enhanceDscWithOpenTelemetryRootSpanName.d.ts +0 -7
  67. package/build/types/utils/enhanceDscWithOpenTelemetryRootSpanName.d.ts.map +0 -1
  68. package/build/types/utils/getParentSpanId.d.ts +0 -8
  69. package/build/types/utils/getParentSpanId.d.ts.map +0 -1
  70. package/build/types/utils/getRequestSpanData.d.ts +0 -8
  71. package/build/types/utils/getRequestSpanData.d.ts.map +0 -1
  72. package/build/types/utils/getSpanKind.d.ts +0 -10
  73. package/build/types/utils/getSpanKind.d.ts.map +0 -1
  74. package/build/types/utils/getTraceData.d.ts +0 -12
  75. package/build/types/utils/getTraceData.d.ts.map +0 -1
  76. package/build/types/utils/groupSpansWithParents.d.ts +0 -17
  77. package/build/types/utils/groupSpansWithParents.d.ts.map +0 -1
  78. package/build/types/utils/isSentryRequest.d.ts +0 -8
  79. package/build/types/utils/isSentryRequest.d.ts.map +0 -1
  80. package/build/types/utils/setupCheck.d.ts +0 -9
  81. package/build/types/utils/setupCheck.d.ts.map +0 -1
  82. package/build/types/utils/spanTypes.d.ts +0 -52
  83. package/build/types/utils/spanTypes.d.ts.map +0 -1
  84. package/build/types-ts3.8/applyOtelSpanData.d.ts +0 -18
  85. package/build/types-ts3.8/asyncContextStrategy.d.ts +0 -9
  86. package/build/types-ts3.8/asyncLocalStorageContextManager.d.ts +0 -31
  87. package/build/types-ts3.8/constants.d.ts +0 -24
  88. package/build/types-ts3.8/contextManager.d.ts +0 -22
  89. package/build/types-ts3.8/custom/client.d.ts +0 -12
  90. package/build/types-ts3.8/debug-build.d.ts +0 -7
  91. package/build/types-ts3.8/exports.d.ts +0 -27
  92. package/build/types-ts3.8/index.browser.d.ts +0 -10
  93. package/build/types-ts3.8/index.d.ts +0 -5
  94. package/build/types-ts3.8/nodeAsyncContextStrategy.d.ts +0 -4
  95. package/build/types-ts3.8/propagator.d.ts +0 -43
  96. package/build/types-ts3.8/resource.d.ts +0 -29
  97. package/build/types-ts3.8/sampler.d.ts +0 -32
  98. package/build/types-ts3.8/semanticAttributes.d.ts +0 -4
  99. package/build/types-ts3.8/setupEventContextTrace.d.ts +0 -4
  100. package/build/types-ts3.8/spanExporter.d.ts +0 -50
  101. package/build/types-ts3.8/spanProcessor.d.ts +0 -31
  102. package/build/types-ts3.8/trace.d.ts +0 -75
  103. package/build/types-ts3.8/tracer.d.ts +0 -13
  104. package/build/types-ts3.8/tracerProvider.d.ts +0 -23
  105. package/build/types-ts3.8/types.d.ts +0 -29
  106. package/build/types-ts3.8/utils/TraceState.d.ts +0 -21
  107. package/build/types-ts3.8/utils/backfillStreamedSpanData.d.ts +0 -16
  108. package/build/types-ts3.8/utils/buildContextWithSentryScopes.d.ts +0 -12
  109. package/build/types-ts3.8/utils/contextData.d.ts +0 -30
  110. package/build/types-ts3.8/utils/enhanceDscWithOpenTelemetryRootSpanName.d.ts +0 -7
  111. package/build/types-ts3.8/utils/getActiveSpan.d.ts +0 -6
  112. package/build/types-ts3.8/utils/getParentSpanId.d.ts +0 -8
  113. package/build/types-ts3.8/utils/getRequestSpanData.d.ts +0 -8
  114. package/build/types-ts3.8/utils/getSamplingDecision.d.ts +0 -27
  115. package/build/types-ts3.8/utils/getSpanKind.d.ts +0 -10
  116. package/build/types-ts3.8/utils/getTraceData.d.ts +0 -12
  117. package/build/types-ts3.8/utils/groupSpansWithParents.d.ts +0 -17
  118. package/build/types-ts3.8/utils/isSentryRequest.d.ts +0 -8
  119. package/build/types-ts3.8/utils/makeTraceState.d.ts +0 -10
  120. package/build/types-ts3.8/utils/mapStatus.d.ts +0 -9
  121. package/build/types-ts3.8/utils/parseSpanDescription.d.ts +0 -56
  122. package/build/types-ts3.8/utils/setupCheck.d.ts +0 -9
  123. package/build/types-ts3.8/utils/spanTypes.d.ts +0 -52
  124. package/build/types-ts3.8/utils/suppressTracing.d.ts +0 -5
@@ -1,24 +1,732 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
2
 
3
- const asyncContextStrategy = require('./asyncContextStrategy-volGaYqZ.js');
4
3
  const core = require('@sentry/core');
5
4
  const api = require('@opentelemetry/api');
5
+ const attributes = require('@sentry/conventions/attributes');
6
+ const op = require('@sentry/conventions/op');
6
7
  const node_async_hooks = require('node:async_hooks');
7
- const node_events = require('node:events');
8
+
9
+ const SENTRY_TRACE_STATE_DSC = "sentry.dsc";
10
+ const SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING = "sentry.sampled_not_recording";
11
+ const SENTRY_TRACE_STATE_CHILD_IGNORED = "sentry.ignored";
12
+ const SENTRY_SCOPES_CONTEXT_KEY = api.createContextKey("sentry_scopes");
13
+ const SENTRY_FORK_ISOLATION_SCOPE_CONTEXT_KEY = api.createContextKey("sentry_fork_isolation_scope");
14
+ const SENTRY_FORK_SET_SCOPE_CONTEXT_KEY = api.createContextKey("sentry_fork_set_scope");
15
+ const SENTRY_FORK_SET_ISOLATION_SCOPE_CONTEXT_KEY = api.createContextKey("sentry_fork_set_isolation_scope");
16
+
17
+ const SCOPE_CONTEXT_FIELD = "_scopeContext";
18
+ function getScopesFromContext(context) {
19
+ return context.getValue(SENTRY_SCOPES_CONTEXT_KEY);
20
+ }
21
+ function setScopesOnContext(context, scopes) {
22
+ return context.setValue(SENTRY_SCOPES_CONTEXT_KEY, scopes);
23
+ }
24
+ function setContextOnScope(scope, context) {
25
+ core.addNonEnumerableProperty(scope, SCOPE_CONTEXT_FIELD, core.makeWeakRef(context));
26
+ }
27
+ function getContextFromScope(scope) {
28
+ return core.derefWeakRef(scope[SCOPE_CONTEXT_FIELD]);
29
+ }
30
+
31
+ function getActiveSpan() {
32
+ return api.trace.getActiveSpan();
33
+ }
34
+
35
+ function setupEventContextTrace(client) {
36
+ client.on("preprocessEvent", (event) => {
37
+ const span = getActiveSpan();
38
+ if (!span || event.type === "transaction") {
39
+ return;
40
+ }
41
+ event.contexts = {
42
+ trace: core.spanToTraceContext(span),
43
+ ...event.contexts
44
+ };
45
+ const rootSpan = core.getRootSpan(span);
46
+ event.sdkProcessingMetadata = {
47
+ dynamicSamplingContext: core.getDynamicSamplingContextFromSpan(rootSpan),
48
+ ...event.sdkProcessingMetadata
49
+ };
50
+ return event;
51
+ });
52
+ }
53
+
54
+ class TraceState {
55
+ constructor() {
56
+ this._internalState = /* @__PURE__ */ new Map();
57
+ }
58
+ /** @inheritDoc */
59
+ set(key, value) {
60
+ const next = this._clone();
61
+ if (next._internalState.has(key)) {
62
+ next._internalState.delete(key);
63
+ }
64
+ next._internalState.set(key, value);
65
+ return next;
66
+ }
67
+ /** @inheritDoc */
68
+ unset(key) {
69
+ const next = this._clone();
70
+ next._internalState.delete(key);
71
+ return next;
72
+ }
73
+ /** @inheritDoc */
74
+ get(key) {
75
+ return this._internalState.get(key);
76
+ }
77
+ /** @inheritDoc */
78
+ serialize() {
79
+ return Array.from(this._internalState.keys()).reverse().map((key) => `${key}=${this._internalState.get(key)}`).join(",");
80
+ }
81
+ _clone() {
82
+ const next = new TraceState();
83
+ next._internalState = new Map(this._internalState);
84
+ return next;
85
+ }
86
+ }
87
+
88
+ function makeTraceState({
89
+ dsc,
90
+ sampled
91
+ }) {
92
+ const dscString = dsc ? core.dynamicSamplingContextToSentryBaggageHeader(dsc) : void 0;
93
+ const traceStateBase = new TraceState();
94
+ const traceStateWithDsc = dscString ? traceStateBase.set(SENTRY_TRACE_STATE_DSC, dscString) : traceStateBase;
95
+ return sampled === false ? traceStateWithDsc.set(SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING, "1") : traceStateWithDsc;
96
+ }
97
+
98
+ const SENTRY_TRACE_HEADER = "sentry-trace";
99
+ const SENTRY_BAGGAGE_HEADER = "baggage";
100
+ const W3C_TRACEPARENT_HEADER = "traceparent";
101
+ class SentryPropagator {
102
+ /** @inheritDoc */
103
+ inject(ctx, carrier, setter) {
104
+ if (ctx !== api.context.active()) {
105
+ core.consoleSandbox(() => {
106
+ console.warn(
107
+ "SentryPropagator: Injecting trace data of a different context than the active one is not supported. Skipping injection."
108
+ );
109
+ });
110
+ return;
111
+ }
112
+ if (core.isTracingSuppressed()) {
113
+ return;
114
+ }
115
+ const { propagateTraceparent } = core.getClient()?.getOptions() ?? {};
116
+ const { "sentry-trace": sentryTrace, baggage, traceparent } = core.getTraceData({ propagateTraceparent });
117
+ if (sentryTrace) {
118
+ setter.set(carrier, SENTRY_TRACE_HEADER, sentryTrace);
119
+ }
120
+ if (baggage) {
121
+ setter.set(carrier, SENTRY_BAGGAGE_HEADER, baggage);
122
+ }
123
+ if (traceparent) {
124
+ setter.set(carrier, W3C_TRACEPARENT_HEADER, traceparent);
125
+ }
126
+ }
127
+ /** @inheritDoc */
128
+ extract(ctx, carrier, getter) {
129
+ const maybeSentryTraceHeader = getter.get(carrier, SENTRY_TRACE_HEADER);
130
+ const baggage = getter.get(carrier, SENTRY_BAGGAGE_HEADER);
131
+ const sentryTrace = Array.isArray(maybeSentryTraceHeader) ? maybeSentryTraceHeader[0] : maybeSentryTraceHeader;
132
+ return getContextWithRemoteActiveSpanAndScopes(ctx, { sentryTrace, baggage });
133
+ }
134
+ /** @inheritDoc */
135
+ fields() {
136
+ return [SENTRY_TRACE_HEADER, SENTRY_BAGGAGE_HEADER, W3C_TRACEPARENT_HEADER];
137
+ }
138
+ }
139
+ function getContextWithRemoteActiveSpan(ctx, { sentryTrace, baggage }) {
140
+ const propagationContext = core.propagationContextFromHeaders(sentryTrace, baggage);
141
+ const { traceId, parentSpanId, sampled, dsc } = propagationContext;
142
+ const client = core.getClient();
143
+ const incomingDsc = core.baggageHeaderToDynamicSamplingContext(baggage);
144
+ if (!parentSpanId || client && !core.shouldContinueTrace(client, incomingDsc?.org_id)) {
145
+ return ctx;
146
+ }
147
+ const spanContext = generateRemoteSpanContext({
148
+ traceId,
149
+ spanId: parentSpanId,
150
+ sampled,
151
+ dsc
152
+ });
153
+ return api.trace.setSpanContext(ctx, spanContext);
154
+ }
155
+ function getContextWithRemoteActiveSpanAndScopes(ctx, options) {
156
+ const ctxWithRemoteSpan = getContextWithRemoteActiveSpan(ctx, options);
157
+ const isContinuingTrace = api.trace.getSpanContext(ctxWithRemoteSpan) !== void 0;
158
+ return ensureScopesOnContext(ctxWithRemoteSpan, isContinuingTrace);
159
+ }
160
+ function ensureScopesOnContext(ctx, isContinuingTrace) {
161
+ const scopes = getScopesFromContext(ctx);
162
+ const scope = scopes ? scopes.scope : core.getCurrentScope().clone();
163
+ if (!scopes && !isContinuingTrace) {
164
+ const propagationContext = scope.getPropagationContext();
165
+ scope.setPropagationContext({
166
+ ...propagationContext,
167
+ traceId: core.generateTraceId(),
168
+ sampleRand: core._INTERNAL_safeMathRandom()
169
+ });
170
+ }
171
+ const newScopes = {
172
+ scope,
173
+ isolationScope: scopes ? scopes.isolationScope : core.getIsolationScope()
174
+ };
175
+ return setScopesOnContext(ctx, newScopes);
176
+ }
177
+ function generateRemoteSpanContext({
178
+ spanId,
179
+ traceId,
180
+ sampled,
181
+ dsc
182
+ }) {
183
+ const traceState = makeTraceState({
184
+ dsc,
185
+ sampled
186
+ });
187
+ const spanContext = {
188
+ traceId,
189
+ spanId,
190
+ isRemote: true,
191
+ traceFlags: sampled ? api.TraceFlags.SAMPLED : api.TraceFlags.NONE,
192
+ traceState
193
+ };
194
+ return spanContext;
195
+ }
196
+
197
+ const canonicalGrpcErrorCodesMap = {
198
+ "1": "cancelled",
199
+ "2": "unknown_error",
200
+ "3": "invalid_argument",
201
+ "4": "deadline_exceeded",
202
+ "5": "not_found",
203
+ "6": "already_exists",
204
+ "7": "permission_denied",
205
+ "8": "resource_exhausted",
206
+ "9": "failed_precondition",
207
+ "10": "aborted",
208
+ "11": "out_of_range",
209
+ "12": "unimplemented",
210
+ "13": "internal_error",
211
+ "14": "unavailable",
212
+ "15": "data_loss",
213
+ "16": "unauthenticated"
214
+ };
215
+ function inferStatusFromAttributes(attributes$1) {
216
+ const httpCodeAttribute = attributes$1[attributes.HTTP_RESPONSE_STATUS_CODE] || attributes$1[attributes.HTTP_STATUS_CODE];
217
+ const grpcCodeAttribute = attributes$1[attributes.RPC_GRPC_STATUS_CODE];
218
+ const numberHttpCode = typeof httpCodeAttribute === "number" ? httpCodeAttribute : typeof httpCodeAttribute === "string" ? parseInt(httpCodeAttribute) : void 0;
219
+ if (typeof numberHttpCode === "number") {
220
+ return core.getSpanStatusFromHttpCode(numberHttpCode);
221
+ }
222
+ if (typeof grpcCodeAttribute === "string") {
223
+ return { code: core.SPAN_STATUS_ERROR, message: canonicalGrpcErrorCodesMap[grpcCodeAttribute] || "unknown_error" };
224
+ }
225
+ return void 0;
226
+ }
227
+
228
+ function inferSpanData(attributes$1) {
229
+ const httpMethod = attributes$1[attributes.HTTP_REQUEST_METHOD] || attributes$1[attributes.HTTP_METHOD];
230
+ if (httpMethod) {
231
+ return descriptionForHttpMethod(attributes$1);
232
+ }
233
+ const dbSystem = attributes$1[attributes.DB_SYSTEM_NAME] || attributes$1[attributes.DB_SYSTEM];
234
+ const opIsCache = typeof attributes$1[core.SEMANTIC_ATTRIBUTE_SENTRY_OP] === "string" && attributes$1[core.SEMANTIC_ATTRIBUTE_SENTRY_OP].startsWith("cache.");
235
+ if (dbSystem && !opIsCache) {
236
+ return descriptionForDbSystem(attributes$1);
237
+ }
238
+ const rpcService = attributes$1[attributes.RPC_SERVICE];
239
+ if (rpcService) {
240
+ return {
241
+ op: "rpc"
242
+ };
243
+ }
244
+ const messagingSystem = attributes$1[attributes.MESSAGING_SYSTEM];
245
+ if (messagingSystem) {
246
+ return {
247
+ op: getMessagingOp(attributes$1[attributes.MESSAGING_OPERATION_TYPE])
248
+ };
249
+ }
250
+ const faasTrigger = attributes$1[attributes.FAAS_TRIGGER];
251
+ if (faasTrigger) {
252
+ return {
253
+ op: getFaasOp(faasTrigger)
254
+ };
255
+ }
256
+ return { op: void 0 };
257
+ }
258
+ function getFaasOp(trigger) {
259
+ switch (trigger) {
260
+ case "http":
261
+ return op.WEB_SERVER_HTTP_SERVER_SPAN_OP;
262
+ case "pubsub":
263
+ return op.MESSAGING_QUEUE_PROCESS_SPAN_OP;
264
+ default:
265
+ return op.GENERAL_FUNCTION_SPAN_OP;
266
+ }
267
+ }
268
+ function getMessagingOp(operationType) {
269
+ switch (operationType) {
270
+ case "publish":
271
+ case "send":
272
+ return op.MESSAGING_QUEUE_PUBLISH_SPAN_OP;
273
+ case "receive":
274
+ return op.MESSAGING_QUEUE_RECEIVE_SPAN_OP;
275
+ case "process":
276
+ return op.MESSAGING_QUEUE_PROCESS_SPAN_OP;
277
+ default:
278
+ return op.MESSAGING_QUEUE_SPAN_OP;
279
+ }
280
+ }
281
+ function descriptionForDbSystem(attributes) {
282
+ const userDefinedName = attributes[core.SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME];
283
+ if (typeof userDefinedName === "string") {
284
+ return {
285
+ op: "db"
286
+ };
287
+ }
288
+ if (attributes[core.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] === "custom") {
289
+ return { op: "db" };
290
+ }
291
+ return { op: "db" };
292
+ }
293
+ function descriptionForHttpMethod(attributes$1) {
294
+ const kind = attributes$1[attributes.SENTRY_KIND];
295
+ const op$1 = kind === "client" ? op.WEB_SERVER_HTTP_CLIENT_SPAN_OP : kind === "server" ? op.WEB_SERVER_HTTP_SERVER_SPAN_OP : op.WEB_SERVER_HTTP_SPAN_OP;
296
+ const { urlPath, url, query, fragment } = getSanitizedUrl(attributes$1);
297
+ if (!urlPath) {
298
+ return { op: op$1 };
299
+ }
300
+ const data = {};
301
+ if (url) {
302
+ data[attributes.URL_FULL] = core.filterCollectedUrl(url);
303
+ }
304
+ const urlQuery = core.filterCollectedUrlQuery(core.getUrlQuery(query));
305
+ if (urlQuery) {
306
+ data[attributes.URL_QUERY] = urlQuery;
307
+ }
308
+ const urlFragment = core.getUrlFragment(fragment);
309
+ if (urlFragment) {
310
+ data[attributes.URL_FRAGMENT] = urlFragment;
311
+ }
312
+ return {
313
+ op: op$1,
314
+ data
315
+ };
316
+ }
317
+ function getSanitizedUrl(attributes$1) {
318
+ const kind = attributes$1[attributes.SENTRY_KIND];
319
+ const httpTarget = attributes$1[attributes.HTTP_TARGET];
320
+ const httpUrl = attributes$1[attributes.URL_FULL];
321
+ const httpRoute = attributes$1[attributes.HTTP_ROUTE];
322
+ const parsedUrl = typeof httpUrl === "string" ? core.parseUrl(httpUrl) : void 0;
323
+ const url = parsedUrl ? core.getSanitizedUrlString(parsedUrl) : void 0;
324
+ const query = parsedUrl?.search || void 0;
325
+ const fragment = parsedUrl?.hash || void 0;
326
+ if (typeof httpRoute === "string") {
327
+ return { urlPath: httpRoute, url, query, fragment, hasRoute: true };
328
+ }
329
+ if (kind === "server" && typeof httpTarget === "string") {
330
+ return { urlPath: core.stripUrlQueryAndFragment(httpTarget), url, query, fragment, hasRoute: false };
331
+ }
332
+ if (parsedUrl) {
333
+ return { urlPath: url, url, query, fragment, hasRoute: false };
334
+ }
335
+ if (typeof httpTarget === "string") {
336
+ return { urlPath: core.stripUrlQueryAndFragment(httpTarget), url, query, fragment, hasRoute: false };
337
+ }
338
+ return { urlPath: void 0, url, query, fragment, hasRoute: false };
339
+ }
340
+
341
+ function applyOtelSpanData(span, options = {}) {
342
+ const spanJSON = core.spanToJSON(span);
343
+ const attributes = spanJSON.data;
344
+ const mayInferSource = core.spanShouldInferOtelSource(span);
345
+ const hasCustomSpanName = attributes[core.SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME] !== void 0;
346
+ const canInferSource = mayInferSource && !hasCustomSpanName && !core.spanSourceWasExplicitlySet(span);
347
+ const attributesForInference = canInferSource && attributes[core.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] === "custom" ? { ...attributes, [core.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: void 0 } : attributes;
348
+ const inferred = inferSpanData(attributesForInference);
349
+ if (inferred.op && attributes[core.SEMANTIC_ATTRIBUTE_SENTRY_OP] === void 0) {
350
+ span.setAttribute(core.SEMANTIC_ATTRIBUTE_SENTRY_OP, inferred.op);
351
+ }
352
+ if (inferred.data) {
353
+ Object.entries(inferred.data).forEach(([key, value]) => {
354
+ if (value !== void 0 && attributes[key] === void 0) {
355
+ span.setAttribute(key, value);
356
+ }
357
+ });
358
+ }
359
+ if (options.finalizeStatus) {
360
+ applyOtelCompatibilityAttributes(span, attributes);
361
+ const client = core.getClient();
362
+ applyOtelSpanStatus(span, attributes, spanJSON.status, !!client && core.hasSpanStreamingEnabled(client));
363
+ }
364
+ }
365
+ function applyOtelSpanStatus(span, attributes, status, spanStreamingEnabled) {
366
+ if (status === "ok") {
367
+ span.setStatus(inferStatusFromAttributes(attributes) || { code: core.SPAN_STATUS_OK });
368
+ return;
369
+ }
370
+ if (!spanStreamingEnabled && status !== "ok" && !core.isStatusErrorMessageValid(status)) {
371
+ span.setStatus({ code: core.SPAN_STATUS_ERROR, message: "internal_error" });
372
+ }
373
+ }
374
+ function applyOtelCompatibilityAttributes(span, attributes$1) {
375
+ const legacyHttpStatusCode = attributes$1[attributes.HTTP_STATUS_CODE];
376
+ if (attributes$1[attributes.HTTP_RESPONSE_STATUS_CODE] === void 0 && legacyHttpStatusCode !== void 0) {
377
+ span.setAttribute(attributes.HTTP_RESPONSE_STATUS_CODE, legacyHttpStatusCode);
378
+ attributes$1[attributes.HTTP_RESPONSE_STATUS_CODE] = legacyHttpStatusCode;
379
+ }
380
+ }
381
+
382
+ function backfillStreamedSpanDataFromOtel(spanJSON) {
383
+ const attributes$1 = spanJSON.attributes ?? {};
384
+ const { op, data } = inferSpanData(attributes$1);
385
+ core.safeSetSpanJSONAttributes(spanJSON, {
386
+ [core.SEMANTIC_ATTRIBUTE_SENTRY_OP]: op,
387
+ // If nothing in the chain previously set an origin, we now default it to 'manual'
388
+ // For transactions, this is done in the SpanExporter.
389
+ // TODO (v11): Remove this again once we fully moved away from OTel's TracerProvider.
390
+ // at this point, we use `SentrySpan` everywhere, which defaults its origin to 'manual'.
391
+ [attributes.SENTRY_ORIGIN]: "manual",
392
+ ...data
393
+ });
394
+ }
395
+
396
+ const SUPPRESS_TRACING_KEY = api.createContextKey("OpenTelemetry SDK Context Key SUPPRESS_TRACING");
397
+ function suppressTracing(context) {
398
+ return context.setValue(SUPPRESS_TRACING_KEY, true);
399
+ }
400
+ function isTracingSuppressed(context) {
401
+ return context.getValue(SUPPRESS_TRACING_KEY) === true;
402
+ }
403
+
404
+ function getSamplingDecision(spanContext) {
405
+ const { traceFlags, traceState } = spanContext;
406
+ const sampledNotRecording = traceState ? traceState.get(SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING) === "1" : false;
407
+ if (traceFlags === api.TraceFlags.SAMPLED) {
408
+ return true;
409
+ }
410
+ if (sampledNotRecording) {
411
+ return false;
412
+ }
413
+ const dscString = traceState ? traceState.get(SENTRY_TRACE_STATE_DSC) : void 0;
414
+ const dsc = dscString ? core.baggageHeaderToDynamicSamplingContext(dscString) : void 0;
415
+ if (dsc?.sampled === "true") {
416
+ return true;
417
+ }
418
+ if (dsc?.sampled === "false") {
419
+ return false;
420
+ }
421
+ return void 0;
422
+ }
423
+
424
+ class SentryTracer {
425
+ /** @inheritdoc */
426
+ startSpan(name, options = {}, ctx) {
427
+ const parentContext = ctx || api.context.active();
428
+ const parentSpanCandidate = options.root ? void 0 : api.trace.getSpan(parentContext);
429
+ const parentSpan = parentSpanCandidate && api.isSpanContextValid(parentSpanCandidate.spanContext()) ? parentSpanCandidate : void 0;
430
+ if (isTracingSuppressed(parentContext)) {
431
+ return this._createNonRecordingSpan(parentSpan);
432
+ }
433
+ const span = this._startSentrySpan(name, options, parentSpan, ctx !== void 0);
434
+ core.markSpanAsTracerProviderSpan(span);
435
+ if (options.attributes?.[core.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] === void 0) {
436
+ core.markSpanForOtelSourceInference(span);
437
+ }
438
+ applyOtelSpanData(span);
439
+ return span;
440
+ }
441
+ startActiveSpan(name, optionsOrFn, contextOrFn, fn) {
442
+ const options = typeof optionsOrFn === "function" ? {} : optionsOrFn;
443
+ const ctx = typeof contextOrFn === "function" || contextOrFn === void 0 ? api.context.active() : contextOrFn;
444
+ const callback = typeof optionsOrFn === "function" ? optionsOrFn : typeof contextOrFn === "function" ? contextOrFn : fn;
445
+ const span = this.startSpan(name, options, ctx);
446
+ const capturedIsolationScope = core.getCapturedScopesOnSpan(span).isolationScope;
447
+ const withCapturedIsolationScope = (contextToFork) => capturedIsolationScope ? contextToFork.setValue(SENTRY_FORK_SET_ISOLATION_SCOPE_CONTEXT_KEY, capturedIsolationScope) : contextToFork;
448
+ if (core.spanIsIgnored(span) && api.trace.getSpan(ctx)) {
449
+ return api.context.with(withCapturedIsolationScope(ctx), () => callback(span));
450
+ }
451
+ return api.context.with(withCapturedIsolationScope(api.trace.setSpan(ctx, span)), () => {
452
+ core._INTERNAL_setSpanForScope(core.getCurrentScope(), span);
453
+ return callback(span);
454
+ });
455
+ }
456
+ _startSentrySpan(name, options, parentSpan, hasExplicitContext) {
457
+ const sentryOptions = {
458
+ name,
459
+ attributes: options.attributes || {},
460
+ links: options.links,
461
+ startTime: options.startTime
462
+ };
463
+ if (options.kind) {
464
+ sentryOptions.attributes[attributes.SENTRY_KIND] = core.spanKindToName(options.kind);
465
+ }
466
+ if (options.root) {
467
+ return core.startNewTrace(() => core._INTERNAL_startInactiveSpan({ ...sentryOptions, parentSpan: null }));
468
+ }
469
+ if (parentSpan?.spanContext().isRemote) {
470
+ return this._startRootSpanWithRemoteParent(sentryOptions, parentSpan);
471
+ }
472
+ if (parentSpan) {
473
+ return core._INTERNAL_startInactiveSpan({ ...sentryOptions, parentSpan });
474
+ }
475
+ return core._INTERNAL_startInactiveSpan({
476
+ ...sentryOptions,
477
+ parentSpan: hasExplicitContext ? null : void 0
478
+ });
479
+ }
480
+ _startRootSpanWithRemoteParent(options, parentSpan) {
481
+ const { spanId, traceId, traceState } = parentSpan.spanContext();
482
+ const dsc = core.getDynamicSamplingContextFromSpan(parentSpan);
483
+ const sampleRand = typeof dsc.sample_rand === "string" ? Number(dsc.sample_rand) : void 0;
484
+ const hasIncomingDsc = !!traceState?.get(SENTRY_TRACE_STATE_DSC);
485
+ return core.withScope((scope) => {
486
+ scope.setPropagationContext({
487
+ traceId,
488
+ parentSpanId: spanId,
489
+ sampled: getSamplingDecision(parentSpan.spanContext()),
490
+ dsc: hasIncomingDsc ? dsc : void 0,
491
+ sampleRand: typeof sampleRand === "number" && !Number.isNaN(sampleRand) ? sampleRand : core._INTERNAL_safeMathRandom()
492
+ });
493
+ core._INTERNAL_setSpanForScope(scope, void 0);
494
+ return core._INTERNAL_startInactiveSpan({ ...options, parentSpan: null });
495
+ });
496
+ }
497
+ _createNonRecordingSpan(parentSpan) {
498
+ const traceId = parentSpan?.spanContext().traceId ?? core.getCurrentScope().getPropagationContext().traceId;
499
+ const span = new core.SentryNonRecordingSpan({ traceId });
500
+ if (parentSpan) {
501
+ core.addChildSpanToSpan(parentSpan, span);
502
+ }
503
+ core.setCapturedScopesOnSpan(span, core.getCurrentScope(), core.getIsolationScope());
504
+ return span;
505
+ }
506
+ }
507
+
508
+ class SentryTracerProvider {
509
+ constructor() {
510
+ this._tracers = /* @__PURE__ */ new Map();
511
+ }
512
+ /** @inheritdoc */
513
+ getTracer(name, version, options) {
514
+ const key = JSON.stringify([name, version, options]);
515
+ const cachedTracer = this._tracers.get(key);
516
+ if (cachedTracer) {
517
+ return cachedTracer;
518
+ }
519
+ const tracer = new SentryTracer();
520
+ this._tracers.set(key, tracer);
521
+ return tracer;
522
+ }
523
+ /** Compatibility with SDK tracer providers. */
524
+ forceFlush() {
525
+ return Promise.resolve();
526
+ }
527
+ /** Compatibility with SDK tracer providers. */
528
+ shutdown() {
529
+ return Promise.resolve();
530
+ }
531
+ }
532
+
533
+ function reconcileDscSampled(dsc, sampled) {
534
+ const reconciled = { ...dsc };
535
+ if (sampled === void 0) {
536
+ delete reconciled.sampled;
537
+ } else {
538
+ reconciled.sampled = String(sampled);
539
+ if (sampled === false) {
540
+ delete reconciled.transaction;
541
+ }
542
+ }
543
+ return reconciled;
544
+ }
545
+
546
+ function _startSpan(options, callback, autoEnd) {
547
+ const tracer = getTracer();
548
+ const { name, parentSpan: customParentSpan } = options;
549
+ const wrapper = getActiveSpanWrapper(customParentSpan);
550
+ return wrapper(() => {
551
+ const activeCtx = getContext(options.scope, options.forceTransaction);
552
+ const missingRequiredParent = options.onlyIfParent && !api.trace.getSpan(activeCtx);
553
+ const ctx = missingRequiredParent ? suppressTracing(activeCtx) : activeCtx;
554
+ if (missingRequiredParent) {
555
+ core.getClient()?.recordDroppedEvent("no_parent_span", "span");
556
+ }
557
+ const spanOptions = getSpanOptions(options);
558
+ if (!core.hasSpansEnabled()) {
559
+ const suppressedCtx = isTracingSuppressed(ctx) ? ctx : suppressTracing(ctx);
560
+ return api.context.with(suppressedCtx, () => {
561
+ return tracer.startActiveSpan(name, spanOptions, suppressedCtx, (span) => {
562
+ patchSpanEnd(span);
563
+ return api.context.with(api.trace.setSpan(activeCtx, span), () => {
564
+ return core.handleCallbackErrors(
565
+ () => callback(span),
566
+ () => {
567
+ if (core.spanToJSON(span).status === "ok") {
568
+ span.setStatus({ code: api.SpanStatusCode.ERROR });
569
+ }
570
+ },
571
+ autoEnd ? () => span.end() : void 0
572
+ );
573
+ });
574
+ });
575
+ });
576
+ }
577
+ return tracer.startActiveSpan(name, spanOptions, ctx, (span) => {
578
+ patchSpanEnd(span);
579
+ return core.handleCallbackErrors(
580
+ () => callback(span),
581
+ () => {
582
+ if (core.spanToJSON(span).status === "ok") {
583
+ span.setStatus({ code: api.SpanStatusCode.ERROR });
584
+ }
585
+ },
586
+ autoEnd ? () => span.end() : void 0
587
+ );
588
+ });
589
+ });
590
+ }
591
+ function startSpan(options, callback) {
592
+ return _startSpan(options, callback, true);
593
+ }
594
+ function startSpanManual(options, callback) {
595
+ return _startSpan(options, (span) => callback(span, () => span.end()), false);
596
+ }
597
+ function startInactiveSpan(options) {
598
+ const tracer = getTracer();
599
+ const { name, parentSpan: customParentSpan } = options;
600
+ const wrapper = getActiveSpanWrapper(customParentSpan);
601
+ return wrapper(() => {
602
+ const activeCtx = getContext(options.scope, options.forceTransaction);
603
+ const missingRequiredParent = options.onlyIfParent && !api.trace.getSpan(activeCtx);
604
+ let ctx = missingRequiredParent ? suppressTracing(activeCtx) : activeCtx;
605
+ if (missingRequiredParent) {
606
+ core.getClient()?.recordDroppedEvent("no_parent_span", "span");
607
+ }
608
+ const spanOptions = getSpanOptions(options);
609
+ if (!core.hasSpansEnabled()) {
610
+ ctx = isTracingSuppressed(ctx) ? ctx : suppressTracing(ctx);
611
+ }
612
+ const span = tracer.startSpan(name, spanOptions, ctx);
613
+ patchSpanEnd(span);
614
+ return span;
615
+ });
616
+ }
617
+ function withActiveSpan(span, callback) {
618
+ const newContextWithActiveSpan = span ? api.trace.setSpan(api.context.active(), span) : api.trace.deleteSpan(api.context.active());
619
+ return api.context.with(newContextWithActiveSpan, () => callback(core.getCurrentScope()));
620
+ }
621
+ function getTracer() {
622
+ const client = core.getClient();
623
+ return client?.tracer || api.trace.getTracer("@sentry/opentelemetry", core.SDK_VERSION);
624
+ }
625
+ function getSpanOptions(options) {
626
+ const { startTime, attributes, kind, op, links } = options;
627
+ const fixedStartTime = typeof startTime === "number" ? ensureTimestampInMilliseconds(startTime) : startTime;
628
+ return {
629
+ attributes: op ? {
630
+ [core.SEMANTIC_ATTRIBUTE_SENTRY_OP]: op,
631
+ ...attributes
632
+ } : attributes,
633
+ kind,
634
+ links,
635
+ startTime: fixedStartTime
636
+ };
637
+ }
638
+ function ensureTimestampInMilliseconds(timestamp) {
639
+ const isMs = timestamp < 9999999999;
640
+ return isMs ? timestamp * 1e3 : timestamp;
641
+ }
642
+ function patchSpanEnd(span) {
643
+ const originalEnd = span.end.bind(span);
644
+ span.end = (endTime) => {
645
+ return originalEnd(typeof endTime === "number" ? ensureTimestampInMilliseconds(endTime) : endTime);
646
+ };
647
+ }
648
+ function getContext(scope, forceTransaction) {
649
+ const ctx = getContextForScope(scope);
650
+ const parentSpan = api.trace.getSpan(ctx);
651
+ if (!parentSpan) {
652
+ return ctx;
653
+ }
654
+ if (!forceTransaction) {
655
+ return ctx;
656
+ }
657
+ const ctxWithoutSpan = api.trace.deleteSpan(ctx);
658
+ const { spanId, traceId } = parentSpan.spanContext();
659
+ const sampled = getSamplingDecision(parentSpan.spanContext());
660
+ const rootSpan = core.getRootSpan(parentSpan);
661
+ const rawDsc = core.getDynamicSamplingContextFromSpan(rootSpan);
662
+ const hasIncomingFrozenDsc = !!rootSpan.spanContext().traceState?.get(SENTRY_TRACE_STATE_DSC);
663
+ const dsc = hasIncomingFrozenDsc ? rawDsc : reconcileDscSampled(rawDsc, sampled);
664
+ const traceState = makeTraceState({
665
+ dsc,
666
+ sampled
667
+ });
668
+ const spanOptions = {
669
+ traceId,
670
+ spanId,
671
+ isRemote: true,
672
+ traceFlags: sampled ? api.TraceFlags.SAMPLED : api.TraceFlags.NONE,
673
+ traceState
674
+ };
675
+ const ctxWithSpanContext = api.trace.setSpanContext(ctxWithoutSpan, spanOptions);
676
+ return ctxWithSpanContext;
677
+ }
678
+ function getContextForScope(scope) {
679
+ if (scope) {
680
+ const ctx = getContextFromScope(scope);
681
+ if (ctx) {
682
+ return ctx;
683
+ }
684
+ }
685
+ return api.context.active();
686
+ }
687
+ function getActiveSpanWrapper(parentSpan) {
688
+ return parentSpan !== void 0 ? (callback) => {
689
+ return withActiveSpan(parentSpan, callback);
690
+ } : (callback) => callback();
691
+ }
692
+
693
+ function buildContextWithSentryScopes(context, activeContext) {
694
+ const span = api.trace.getSpan(context);
695
+ let effectiveContext;
696
+ if (span?.spanContext().traceState?.get(SENTRY_TRACE_STATE_CHILD_IGNORED) === "1") {
697
+ const contextWithoutSpan = api.trace.deleteSpan(context);
698
+ const parentSpan = api.trace.getSpan(activeContext);
699
+ effectiveContext = parentSpan ? api.trace.setSpan(contextWithoutSpan, parentSpan) : contextWithoutSpan;
700
+ } else {
701
+ effectiveContext = context;
702
+ }
703
+ const currentScopes = getScopesFromContext(effectiveContext);
704
+ const currentScope = currentScopes?.scope || core.getCurrentScope();
705
+ const currentIsolationScope = currentScopes?.isolationScope || core.getIsolationScope();
706
+ const shouldForkIsolationScope = effectiveContext.getValue(SENTRY_FORK_ISOLATION_SCOPE_CONTEXT_KEY) === true;
707
+ const scope = effectiveContext.getValue(SENTRY_FORK_SET_SCOPE_CONTEXT_KEY);
708
+ const isolationScope = effectiveContext.getValue(SENTRY_FORK_SET_ISOLATION_SCOPE_CONTEXT_KEY);
709
+ const newCurrentScope = scope || currentScope.clone();
710
+ const newIsolationScope = isolationScope || (shouldForkIsolationScope ? currentIsolationScope.clone() : currentIsolationScope);
711
+ const scopes = { scope: newCurrentScope, isolationScope: newIsolationScope };
712
+ const ctx1 = setScopesOnContext(effectiveContext, scopes);
713
+ const ctx2 = ctx1.deleteValue(SENTRY_FORK_ISOLATION_SCOPE_CONTEXT_KEY).deleteValue(SENTRY_FORK_SET_SCOPE_CONTEXT_KEY).deleteValue(SENTRY_FORK_SET_ISOLATION_SCOPE_CONTEXT_KEY);
714
+ setContextOnScope(newCurrentScope, ctx2);
715
+ return ctx2;
716
+ }
8
717
 
9
718
  const ADD_LISTENER_METHODS = ["addListener", "on", "once", "prependListener", "prependOnceListener"];
10
719
  class SentryAsyncLocalStorageContextManager {
11
- constructor() {
720
+ constructor(asyncLocalStorage) {
12
721
  this._kOtListeners = /* @__PURE__ */ Symbol("OtListeners");
13
722
  this._wrapped = false;
14
- asyncContextStrategy.setIsSetup("SentryContextManager");
15
- this._asyncLocalStorage = core.getAsyncContextStrategy(core.getMainCarrier()).getTracingChannelBinding?.()?.asyncLocalStorage ?? new node_async_hooks.AsyncLocalStorage();
723
+ this._asyncLocalStorage = asyncLocalStorage;
16
724
  }
17
725
  active() {
18
726
  return this._asyncLocalStorage.getStore() ?? api.ROOT_CONTEXT;
19
727
  }
20
728
  with(context, fn, thisArg, ...args) {
21
- const ctx2 = asyncContextStrategy.buildContextWithSentryScopes(context, this.active());
729
+ const ctx2 = buildContextWithSentryScopes(context, this.active());
22
730
  const cb = thisArg == null ? fn : fn.bind(thisArg);
23
731
  return this._asyncLocalStorage.run(ctx2, cb, ...args);
24
732
  }
@@ -26,11 +734,14 @@ class SentryAsyncLocalStorageContextManager {
26
734
  return this;
27
735
  }
28
736
  disable() {
29
- this._asyncLocalStorage.disable();
737
+ try {
738
+ this._asyncLocalStorage.disable();
739
+ } catch {
740
+ }
30
741
  return this;
31
742
  }
32
743
  bind(context, target) {
33
- if (target instanceof node_events.EventEmitter) {
744
+ if (isEventEmitter(target)) {
34
745
  return this._bindEventEmitter(context, target);
35
746
  }
36
747
  if (typeof target === "function") {
@@ -45,7 +756,7 @@ class SentryAsyncLocalStorageContextManager {
45
756
  getAsyncLocalStorageLookup() {
46
757
  return {
47
758
  asyncLocalStorage: this._asyncLocalStorage,
48
- contextSymbol: asyncContextStrategy.SENTRY_SCOPES_CONTEXT_KEY
759
+ contextSymbol: SENTRY_SCOPES_CONTEXT_KEY
49
760
  };
50
761
  }
51
762
  _bindFunction(context, target) {
@@ -65,27 +776,22 @@ class SentryAsyncLocalStorageContextManager {
65
776
  if (this._getPatchMap(ee) !== void 0) {
66
777
  return ee;
67
778
  }
68
- this._createPatchMap(ee);
69
- for (const methodName of ADD_LISTENER_METHODS) {
70
- if (ee[methodName] === void 0) continue;
71
- ee[methodName] = this._patchAddListener(
72
- ee,
73
- ee[methodName],
74
- context
75
- );
779
+ if (this._createPatchMap(ee) === void 0) {
780
+ return ee;
76
781
  }
77
- if (typeof ee.removeListener === "function") {
78
- ee.removeListener = this._patchRemoveListener(ee, ee.removeListener);
782
+ for (const methodName of ADD_LISTENER_METHODS) {
783
+ const original = getMethod(ee, methodName);
784
+ if (!original) continue;
785
+ trySetMethod(ee, methodName, this._patchAddListener(ee, original, context));
79
786
  }
80
- if (typeof ee.off === "function") {
81
- ee.off = this._patchRemoveListener(ee, ee.off);
787
+ for (const methodName of ["removeListener", "off"]) {
788
+ const original = getMethod(ee, methodName);
789
+ if (!original) continue;
790
+ trySetMethod(ee, methodName, this._patchRemoveListener(ee, original));
82
791
  }
83
- if (typeof ee.removeAllListeners === "function") {
84
- ee.removeAllListeners = this._patchRemoveAllListeners(
85
- ee,
86
- // oxlint-disable-next-line @typescript-eslint/unbound-method
87
- ee.removeAllListeners
88
- );
792
+ const removeAllListeners = getMethod(ee, "removeAllListeners");
793
+ if (removeAllListeners) {
794
+ trySetMethod(ee, "removeAllListeners", this._patchRemoveAllListeners(ee, removeAllListeners));
89
795
  }
90
796
  return ee;
91
797
  }
@@ -120,9 +826,9 @@ class SentryAsyncLocalStorageContextManager {
120
826
  if (contextManager._wrapped) {
121
827
  return original.call(this, event, listener);
122
828
  }
123
- let map = contextManager._getPatchMap(ee);
829
+ const map = contextManager._getPatchMap(ee) ?? contextManager._createPatchMap(ee);
124
830
  if (map === void 0) {
125
- map = contextManager._createPatchMap(ee);
831
+ return original.call(this, event, listener);
126
832
  }
127
833
  let listeners = map[event];
128
834
  if (listeners === void 0) {
@@ -139,87 +845,130 @@ class SentryAsyncLocalStorageContextManager {
139
845
  }
140
846
  };
141
847
  }
848
+ /**
849
+ * Attach a fresh patch map to the emitter. Returns `undefined` if the emitter does not accept the
850
+ * property (e.g. it is frozen or sealed), in which case the emitter must not be patched at all —
851
+ * without a patch map the remove-listener patches could not resolve their wrapped listeners.
852
+ */
142
853
  _createPatchMap(ee) {
143
854
  const map = /* @__PURE__ */ Object.create(null);
144
- ee[this._kOtListeners] = map;
145
- return map;
855
+ try {
856
+ ee[this._kOtListeners] = map;
857
+ } catch {
858
+ return void 0;
859
+ }
860
+ return this._getPatchMap(ee) === map ? map : void 0;
146
861
  }
147
862
  _getPatchMap(ee) {
148
863
  return ee[this._kOtListeners];
149
864
  }
150
865
  }
151
-
152
- function setNodeOpenTelemetryContextAsyncContextStrategy(options) {
153
- asyncContextStrategy.setOpenTelemetryContextAsyncContextStrategy({
154
- getTracingChannelBinding: !options?.skipOpenTelemetrySetup ? getDefaultAsyncLocalStorageFactory() : getCustomAsyncLocalStorageFactory()
155
- });
866
+ function isEventEmitter(target) {
867
+ if (typeof target !== "object" || !target) {
868
+ return false;
869
+ }
870
+ const candidate = target;
871
+ return typeof candidate.on === "function" && typeof candidate.emit === "function";
872
+ }
873
+ function getMethod(ee, methodName) {
874
+ const value = ee[methodName];
875
+ return typeof value === "function" ? value : void 0;
156
876
  }
157
- function getDefaultAsyncLocalStorageFactory() {
158
- const defaultAsyncLocalStorage = new node_async_hooks.AsyncLocalStorage();
159
- return () => {
877
+ function trySetMethod(ee, methodName, patched) {
878
+ try {
879
+ ee[methodName] = patched;
880
+ } catch {
881
+ }
882
+ }
883
+
884
+ function setOpenTelemetryContextAsyncContextStrategy() {
885
+ const existingAsyncLocalStorage = core.getAsyncContextStrategy(core.getMainCarrier()).getTracingChannelBinding?.()?.asyncLocalStorage;
886
+ const asyncLocalStorage = existingAsyncLocalStorage ?? new node_async_hooks.AsyncLocalStorage();
887
+ function getScopes() {
888
+ const ctx = api.context.active();
889
+ const scopes = getScopesFromContext(ctx);
890
+ if (scopes) {
891
+ return scopes;
892
+ }
160
893
  return {
161
- asyncLocalStorage: defaultAsyncLocalStorage,
894
+ scope: core.getDefaultCurrentScope(),
895
+ isolationScope: core.getDefaultIsolationScope()
896
+ };
897
+ }
898
+ function withScope(callback) {
899
+ const ctx = api.context.active();
900
+ return api.context.with(ctx, () => {
901
+ return callback(getCurrentScope());
902
+ });
903
+ }
904
+ function withSetScope(scope, callback) {
905
+ const ctx = getContextFromScope(scope) || api.context.active();
906
+ return api.context.with(ctx.setValue(SENTRY_FORK_SET_SCOPE_CONTEXT_KEY, scope), () => {
907
+ return callback(scope);
908
+ });
909
+ }
910
+ function withIsolationScope(callback) {
911
+ const ctx = api.context.active();
912
+ return api.context.with(ctx.setValue(SENTRY_FORK_ISOLATION_SCOPE_CONTEXT_KEY, true), () => {
913
+ const scope = getCurrentScope();
914
+ if (!core.isContinuingTrace(scope.getPropagationContext())) {
915
+ scope.setPropagationContext({
916
+ traceId: core.generateTraceId(),
917
+ sampleRand: core._INTERNAL_safeMathRandom()
918
+ });
919
+ }
920
+ return callback(getIsolationScope());
921
+ });
922
+ }
923
+ function withSetIsolationScope(isolationScope, callback) {
924
+ const ctx = api.context.active();
925
+ return api.context.with(ctx.setValue(SENTRY_FORK_SET_ISOLATION_SCOPE_CONTEXT_KEY, isolationScope), () => {
926
+ return callback(getIsolationScope());
927
+ });
928
+ }
929
+ function getCurrentScope() {
930
+ return getScopes().scope;
931
+ }
932
+ function getIsolationScope() {
933
+ return getScopes().isolationScope;
934
+ }
935
+ function getTracingChannelBinding() {
936
+ return {
937
+ asyncLocalStorage,
162
938
  getStoreWithActiveSpan
163
939
  };
164
- };
165
- }
166
- function getCustomAsyncLocalStorageFactory() {
167
- return () => {
168
- try {
169
- const contextManager = api.context._getContextManager();
170
- const asyncLocalStorage = contextManager?.getAsyncLocalStorageLookup().asyncLocalStorage;
171
- return asyncLocalStorage ? {
172
- asyncLocalStorage,
173
- getStoreWithActiveSpan
174
- } : void 0;
175
- } catch {
176
- return void 0;
177
- }
178
- };
940
+ }
941
+ core.setAsyncContextStrategy({
942
+ withScope,
943
+ withSetScope,
944
+ withSetIsolationScope,
945
+ withIsolationScope,
946
+ getCurrentScope,
947
+ getIsolationScope,
948
+ startSpan,
949
+ startSpanManual,
950
+ startInactiveSpan,
951
+ getActiveSpan,
952
+ // The types here don't fully align, because our own `Span` type is narrower
953
+ // than the OTEL one - but this is OK for here, as we now we'll only have OTEL spans passed around
954
+ withActiveSpan,
955
+ getTracingChannelBinding
956
+ });
957
+ const ctxManager = new SentryAsyncLocalStorageContextManager(asyncLocalStorage);
958
+ api.context.setGlobalContextManager(ctxManager);
959
+ return ctxManager.getAsyncLocalStorageLookup();
179
960
  }
180
961
  function getStoreWithActiveSpan(span) {
181
962
  const activeContext = api.context.active();
182
- const isIgnoredChild = core.spanIsIgnored(span) && core.getRootSpan(span) !== span || span.spanContext().traceState?.get(asyncContextStrategy.SENTRY_TRACE_STATE_CHILD_IGNORED) === "1";
963
+ const isIgnoredChild = core.spanIsIgnored(span) && core.getRootSpan(span) !== span || span.spanContext().traceState?.get(SENTRY_TRACE_STATE_CHILD_IGNORED) === "1";
183
964
  return isIgnoredChild ? activeContext : api.trace.setSpan(activeContext, span);
184
965
  }
185
966
 
186
- exports.SEMANTIC_ATTRIBUTE_SENTRY_GRAPHQL_OPERATION = asyncContextStrategy.SEMANTIC_ATTRIBUTE_SENTRY_GRAPHQL_OPERATION;
187
- exports.SentryPropagator = asyncContextStrategy.SentryPropagator;
188
- exports.SentrySampler = asyncContextStrategy.SentrySampler;
189
- exports.SentrySpanProcessor = asyncContextStrategy.SentrySpanProcessor;
190
- exports.SentryTracerProvider = asyncContextStrategy.SentryTracerProvider;
191
- exports.applyOtelSpanData = asyncContextStrategy.applyOtelSpanData;
192
- exports.backfillStreamedSpanDataFromOtel = asyncContextStrategy.backfillStreamedSpanDataFromOtel;
193
- exports.continueTrace = asyncContextStrategy.continueTrace;
194
- exports.enhanceDscWithOpenTelemetryRootSpanName = asyncContextStrategy.enhanceDscWithOpenTelemetryRootSpanName;
195
- exports.getActiveSpan = asyncContextStrategy.getActiveSpan;
196
- exports.getRequestSpanData = asyncContextStrategy.getRequestSpanData;
197
- exports.getScopesFromContext = asyncContextStrategy.getScopesFromContext;
198
- exports.getSentryResource = asyncContextStrategy.getSentryResource;
199
- exports.getSpanKind = asyncContextStrategy.getSpanKind;
200
- exports.getTraceContextForScope = asyncContextStrategy.getTraceContextForScope;
201
- exports.isSentryRequestSpan = asyncContextStrategy.isSentryRequestSpan;
202
- exports.openTelemetrySetupCheck = asyncContextStrategy.openTelemetrySetupCheck;
203
- exports.setIsSetup = asyncContextStrategy.setIsSetup;
204
- exports.setupEventContextTrace = asyncContextStrategy.setupEventContextTrace;
205
- exports.spanHasAttributes = asyncContextStrategy.spanHasAttributes;
206
- exports.spanHasEvents = asyncContextStrategy.spanHasEvents;
207
- exports.spanHasKind = asyncContextStrategy.spanHasKind;
208
- exports.spanHasName = asyncContextStrategy.spanHasName;
209
- exports.spanHasParentId = asyncContextStrategy.spanHasParentId;
210
- exports.spanHasStatus = asyncContextStrategy.spanHasStatus;
211
- exports.startInactiveSpan = asyncContextStrategy.startInactiveSpan;
212
- exports.startSpan = asyncContextStrategy.startSpan;
213
- exports.startSpanManual = asyncContextStrategy.startSpanManual;
214
- exports.suppressTracing = asyncContextStrategy.suppressTracing;
215
- exports.withActiveSpan = asyncContextStrategy.withActiveSpan;
216
- exports.wrapClientClass = asyncContextStrategy.wrapClientClass;
217
- exports.wrapContextManagerClass = asyncContextStrategy.wrapContextManagerClass;
218
- exports.wrapSamplingDecision = asyncContextStrategy.wrapSamplingDecision;
219
- exports.getClient = core.getClient;
220
- exports.getDynamicSamplingContextFromSpan = core.getDynamicSamplingContextFromSpan;
221
- exports.shouldPropagateTraceForUrl = core.shouldPropagateTraceForUrl;
222
- exports.withStreamedSpan = core.withStreamedSpan;
223
- exports.SentryAsyncLocalStorageContextManager = SentryAsyncLocalStorageContextManager;
224
- exports.setOpenTelemetryContextAsyncContextStrategy = setNodeOpenTelemetryContextAsyncContextStrategy;
967
+ exports.SentryPropagator = SentryPropagator;
968
+ exports.SentryTracerProvider = SentryTracerProvider;
969
+ exports.applyOtelSpanData = applyOtelSpanData;
970
+ exports.backfillStreamedSpanDataFromOtel = backfillStreamedSpanDataFromOtel;
971
+ exports.getScopesFromContext = getScopesFromContext;
972
+ exports.setOpenTelemetryContextAsyncContextStrategy = setOpenTelemetryContextAsyncContextStrategy;
973
+ exports.setupEventContextTrace = setupEventContextTrace;
225
974
  //# sourceMappingURL=index.js.map