@sentry/opentelemetry 11.12.0 → 11.14.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.
@@ -1,603 +1,651 @@
1
- import { derefWeakRef, makeWeakRef, dynamicSamplingContextToSentryBaggageHeader, consoleSandbox, isTracingSuppressed as isTracingSuppressed$1, getClient, getTraceData, propagationContextFromHeaders, baggageHeaderToDynamicSamplingContext, shouldContinueTrace, getCurrentScope, _INTERNAL_safeMathRandom, generateTraceId, getIsolationScope, markSpanAsTracerProviderSpan, getCapturedScopesOnSpan, spanIsIgnored, withScope, _INTERNAL_setSpanForScope, getActiveSpan as getActiveSpan$1, otelTimeInputToSeconds, spanKindToName, startNewTrace, startInactiveSpan, SentryNonRecordingSpan, addChildSpanToSpan, setCapturedScopesOnSpan, getAsyncContextStrategy, getMainCarrier, setAsyncContextStrategy, isContinuingTrace, getDefaultIsolationScope, getDefaultCurrentScope, getDynamicSamplingContextFromSpan } from '@sentry/core';
2
- import * as api from '@opentelemetry/api';
3
- import { createContextKey, context, trace, TraceFlags, isSpanContextValid, ROOT_CONTEXT } from '@opentelemetry/api';
4
- import { SENTRY_KIND } from '@sentry/conventions/attributes';
5
- import { AsyncLocalStorage } from 'node:async_hooks';
6
-
1
+ import { SentryNonRecordingSpan, _INTERNAL_safeMathRandom, _INTERNAL_setSpanForScope, addChildSpanToSpan, baggageHeaderToDynamicSamplingContext, consoleSandbox, derefWeakRef, dynamicSamplingContextToSentryBaggageHeader, generateTraceId, getActiveSpan as getActiveSpan$1, getAsyncContextStrategy, getCapturedScopesOnSpan, getClient, getCurrentScope, getDefaultCurrentScope, getDefaultIsolationScope, getDynamicSamplingContextFromSpan, getIsolationScope, getMainCarrier, getTraceData, isContinuingTrace, isTracingSuppressed as isTracingSuppressed$1, makeWeakRef, markSpanAsTracerProviderSpan, otelTimeInputToSeconds, propagationContextFromHeaders, setAsyncContextStrategy, setCapturedScopesOnSpan, shouldContinueTrace, spanIsIgnored, spanKindToName, startInactiveSpan, startNewTrace, withScope } from "@sentry/core";
2
+ import * as api from "@opentelemetry/api";
3
+ import { ROOT_CONTEXT, TraceFlags, context, createContextKey, isSpanContextValid, trace } from "@opentelemetry/api";
4
+ import { SENTRY_KIND } from "@sentry/conventions/attributes";
5
+ import { AsyncLocalStorage } from "node:async_hooks";
6
+ // src/constants.ts
7
7
  const SENTRY_TRACE_STATE_DSC = "sentry.dsc";
8
8
  const SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING = "sentry.sampled_not_recording";
9
9
  const SENTRY_SCOPES_CONTEXT_KEY = createContextKey("sentry_scopes");
10
10
  const SENTRY_FORK_ISOLATION_SCOPE_CONTEXT_KEY = createContextKey("sentry_fork_isolation_scope");
11
11
  const SENTRY_FORK_SET_SCOPE_CONTEXT_KEY = createContextKey("sentry_fork_set_scope");
12
12
  const SENTRY_FORK_SET_ISOLATION_SCOPE_CONTEXT_KEY = createContextKey("sentry_fork_set_isolation_scope");
13
-
13
+ // src/utils/contextData.ts
14
14
  const SCOPE_CONTEXT_FIELD = "context";
15
+ /**
16
+ * Try to get the current scopes from the given OTEL context.
17
+ * This requires a Context Manager that was wrapped with getWrappedContextManager.
18
+ */
15
19
  function getScopesFromContext(context) {
16
- return context.getValue(SENTRY_SCOPES_CONTEXT_KEY);
20
+ return context.getValue(SENTRY_SCOPES_CONTEXT_KEY);
17
21
  }
22
+ /**
23
+ * Set the current scopes on an OTEL context.
24
+ * This will return a forked context with the Propagation Context set.
25
+ */
18
26
  function setScopesOnContext(context, scopes) {
19
- return context.setValue(SENTRY_SCOPES_CONTEXT_KEY, scopes);
27
+ return context.setValue(SENTRY_SCOPES_CONTEXT_KEY, scopes);
20
28
  }
29
+ /**
30
+ * Set the context on the scope so we can later look it up.
31
+ * We need this to get the context from the scope in the `trace` functions.
32
+ *
33
+ * We use WeakRef to avoid a circular reference between the scope and the context.
34
+ * The context holds scopes (via SENTRY_SCOPES_CONTEXT_KEY), and if the scope held
35
+ * a strong reference back to the context, neither could be garbage collected even
36
+ * when the context is no longer reachable from application code (e.g., after a
37
+ * request completes but pooled connections retain patched callbacks).
38
+ */
21
39
  function setContextOnScope(scope, context) {
22
- scope.refs[SCOPE_CONTEXT_FIELD] = makeWeakRef(context);
40
+ scope.refs[SCOPE_CONTEXT_FIELD] = makeWeakRef(context);
23
41
  }
42
+ /**
43
+ * Get the context related to a scope.
44
+ * Returns undefined if the context has been garbage collected (when WeakRef is used).
45
+ */
24
46
  function getContextFromScope(scope) {
25
- return derefWeakRef(scope.refs[SCOPE_CONTEXT_FIELD]);
26
- }
27
-
28
- class TraceState {
29
- constructor() {
30
- this._internalState = /* @__PURE__ */ new Map();
31
- }
32
- /** @inheritDoc */
33
- set(key, value) {
34
- const next = this._clone();
35
- if (next._internalState.has(key)) {
36
- next._internalState.delete(key);
37
- }
38
- next._internalState.set(key, value);
39
- return next;
40
- }
41
- /** @inheritDoc */
42
- unset(key) {
43
- const next = this._clone();
44
- next._internalState.delete(key);
45
- return next;
46
- }
47
- /** @inheritDoc */
48
- get(key) {
49
- return this._internalState.get(key);
50
- }
51
- /** @inheritDoc */
52
- serialize() {
53
- return Array.from(this._internalState.keys()).reverse().map((key) => `${key}=${this._internalState.get(key)}`).join(",");
54
- }
55
- _clone() {
56
- const next = new TraceState();
57
- next._internalState = new Map(this._internalState);
58
- return next;
59
- }
47
+ return derefWeakRef(scope.refs[SCOPE_CONTEXT_FIELD]);
60
48
  }
61
-
62
- function makeTraceState({
63
- dsc,
64
- sampled
65
- }) {
66
- const dscString = dsc ? dynamicSamplingContextToSentryBaggageHeader(dsc) : void 0;
67
- const traceStateBase = new TraceState();
68
- const traceStateWithDsc = dscString ? traceStateBase.set(SENTRY_TRACE_STATE_DSC, dscString) : traceStateBase;
69
- return sampled === false ? traceStateWithDsc.set(SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING, "1") : traceStateWithDsc;
49
+ // src/utils/TraceState.ts
50
+ /**
51
+ * Minimal implementation of the W3C `tracestate` field as a `@opentelemetry/api`
52
+ * `TraceState`. New entries are inserted at the front of the list, and updating
53
+ * an existing key moves it to the front.
54
+ *
55
+ * See https://www.w3.org/TR/trace-context/#tracestate-field for the field spec.
56
+ */
57
+ var TraceState = class TraceState {
58
+ constructor() {
59
+ this._internalState = /* @__PURE__ */ new Map();
60
+ }
61
+ /** @inheritDoc */
62
+ set(key, value) {
63
+ const next = this._clone();
64
+ if (next._internalState.has(key)) next._internalState.delete(key);
65
+ next._internalState.set(key, value);
66
+ return next;
67
+ }
68
+ /** @inheritDoc */
69
+ unset(key) {
70
+ const next = this._clone();
71
+ next._internalState.delete(key);
72
+ return next;
73
+ }
74
+ /** @inheritDoc */
75
+ get(key) {
76
+ return this._internalState.get(key);
77
+ }
78
+ /** @inheritDoc */
79
+ serialize() {
80
+ return Array.from(this._internalState.keys()).reverse().map((key) => `${key}=${this._internalState.get(key)}`).join(",");
81
+ }
82
+ _clone() {
83
+ const next = new TraceState();
84
+ next._internalState = new Map(this._internalState);
85
+ return next;
86
+ }
87
+ };
88
+ // src/utils/makeTraceState.ts
89
+ /**
90
+ * Generate a TraceState for the given data.
91
+ */
92
+ function makeTraceState({ dsc, sampled }) {
93
+ const dscString = dsc ? dynamicSamplingContextToSentryBaggageHeader(dsc) : void 0;
94
+ const traceStateBase = new TraceState();
95
+ const traceStateWithDsc = dscString ? traceStateBase.set(SENTRY_TRACE_STATE_DSC, dscString) : traceStateBase;
96
+ return sampled === false ? traceStateWithDsc.set(SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING, "1") : traceStateWithDsc;
70
97
  }
71
-
98
+ // src/propagator.ts
72
99
  const SENTRY_TRACE_HEADER = "sentry-trace";
73
100
  const SENTRY_BAGGAGE_HEADER = "baggage";
74
101
  const W3C_TRACEPARENT_HEADER = "traceparent";
75
- class SentryPropagator {
76
- /** @inheritDoc */
77
- inject(ctx, carrier, setter) {
78
- if (ctx !== context.active()) {
79
- consoleSandbox(() => {
80
- console.warn(
81
- "SentryPropagator: Injecting trace data of a different context than the active one is not supported. Skipping injection."
82
- );
83
- });
84
- return;
85
- }
86
- if (isTracingSuppressed$1()) {
87
- return;
88
- }
89
- const { propagateTraceparent } = getClient()?.getOptions() ?? {};
90
- const { "sentry-trace": sentryTrace, baggage, traceparent } = getTraceData({ propagateTraceparent });
91
- if (sentryTrace) {
92
- setter.set(carrier, SENTRY_TRACE_HEADER, sentryTrace);
93
- }
94
- if (baggage) {
95
- setter.set(carrier, SENTRY_BAGGAGE_HEADER, baggage);
96
- }
97
- if (traceparent) {
98
- setter.set(carrier, W3C_TRACEPARENT_HEADER, traceparent);
99
- }
100
- }
101
- /** @inheritDoc */
102
- extract(ctx, carrier, getter) {
103
- const maybeSentryTraceHeader = getter.get(carrier, SENTRY_TRACE_HEADER);
104
- const baggage = getter.get(carrier, SENTRY_BAGGAGE_HEADER);
105
- const sentryTrace = Array.isArray(maybeSentryTraceHeader) ? maybeSentryTraceHeader[0] : maybeSentryTraceHeader;
106
- return getContextWithRemoteActiveSpanAndScopes(ctx, { sentryTrace, baggage });
107
- }
108
- /** @inheritDoc */
109
- fields() {
110
- return [SENTRY_TRACE_HEADER, SENTRY_BAGGAGE_HEADER, W3C_TRACEPARENT_HEADER];
111
- }
112
- }
102
+ /**
103
+ * A minimal OpenTelemetry `TextMapPropagator` that injects and extracts Sentry trace data.
104
+ *
105
+ * This propagator only supports injecting/extracting from current context, for simplicity sake.
106
+ * It will bail and do nothing if using a different context.
107
+ */
108
+ var SentryPropagator = class {
109
+ /** @inheritDoc */
110
+ inject(ctx, carrier, setter) {
111
+ if (ctx !== context.active()) {
112
+ consoleSandbox(() => {
113
+ console.warn("SentryPropagator: Injecting trace data of a different context than the active one is not supported. Skipping injection.");
114
+ });
115
+ return;
116
+ }
117
+ if (isTracingSuppressed$1()) return;
118
+ const { propagateTraceparent } = getClient()?.getOptions() ?? {};
119
+ const { "sentry-trace": sentryTrace, baggage, traceparent } = getTraceData({ propagateTraceparent });
120
+ if (sentryTrace) setter.set(carrier, SENTRY_TRACE_HEADER, sentryTrace);
121
+ if (baggage) setter.set(carrier, SENTRY_BAGGAGE_HEADER, baggage);
122
+ if (traceparent) setter.set(carrier, W3C_TRACEPARENT_HEADER, traceparent);
123
+ }
124
+ /** @inheritDoc */
125
+ extract(ctx, carrier, getter) {
126
+ const maybeSentryTraceHeader = getter.get(carrier, SENTRY_TRACE_HEADER);
127
+ const baggage = getter.get(carrier, SENTRY_BAGGAGE_HEADER);
128
+ return getContextWithRemoteActiveSpanAndScopes(ctx, {
129
+ sentryTrace: Array.isArray(maybeSentryTraceHeader) ? maybeSentryTraceHeader[0] : maybeSentryTraceHeader,
130
+ baggage
131
+ });
132
+ }
133
+ /** @inheritDoc */
134
+ fields() {
135
+ return [
136
+ SENTRY_TRACE_HEADER,
137
+ SENTRY_BAGGAGE_HEADER,
138
+ W3C_TRACEPARENT_HEADER
139
+ ];
140
+ }
141
+ };
113
142
  function getContextWithRemoteActiveSpan(ctx, { sentryTrace, baggage }) {
114
- const propagationContext = propagationContextFromHeaders(sentryTrace, baggage);
115
- const { traceId, parentSpanId, sampled, dsc } = propagationContext;
116
- const client = getClient();
117
- const incomingDsc = baggageHeaderToDynamicSamplingContext(baggage);
118
- if (!parentSpanId || client && !shouldContinueTrace(client, incomingDsc?.org_id)) {
119
- return ctx;
120
- }
121
- const spanContext = generateRemoteSpanContext({
122
- traceId,
123
- spanId: parentSpanId,
124
- sampled,
125
- dsc
126
- });
127
- return trace.setSpanContext(ctx, spanContext);
143
+ const { traceId, parentSpanId, sampled, dsc } = propagationContextFromHeaders(sentryTrace, baggage);
144
+ const client = getClient();
145
+ const incomingDsc = baggageHeaderToDynamicSamplingContext(baggage);
146
+ if (!parentSpanId || client && !shouldContinueTrace(client, incomingDsc?.org_id)) return ctx;
147
+ const spanContext = generateRemoteSpanContext({
148
+ traceId,
149
+ spanId: parentSpanId,
150
+ sampled,
151
+ dsc
152
+ });
153
+ return trace.setSpanContext(ctx, spanContext);
128
154
  }
155
+ /**
156
+ * Build a context that continues an incoming trace as a remote active span, with scopes ensured.
157
+ * Returns the context so it can be used to implement an OpenTelemetry propagator's `extract`.
158
+ */
129
159
  function getContextWithRemoteActiveSpanAndScopes(ctx, options) {
130
- const ctxWithRemoteSpan = getContextWithRemoteActiveSpan(ctx, options);
131
- const isContinuingTrace = trace.getSpanContext(ctxWithRemoteSpan) !== void 0;
132
- return ensureScopesOnContext(ctxWithRemoteSpan, isContinuingTrace);
160
+ const ctxWithRemoteSpan = getContextWithRemoteActiveSpan(ctx, options);
161
+ return ensureScopesOnContext(ctxWithRemoteSpan, trace.getSpanContext(ctxWithRemoteSpan) !== void 0);
133
162
  }
134
163
  function ensureScopesOnContext(ctx, isContinuingTrace) {
135
- const scopes = getScopesFromContext(ctx);
136
- const scope = scopes ? scopes.scope : getCurrentScope().clone();
137
- if (!scopes && !isContinuingTrace) {
138
- const propagationContext = scope.getPropagationContext();
139
- scope.setPropagationContext({
140
- ...propagationContext,
141
- traceId: generateTraceId(),
142
- sampleRand: _INTERNAL_safeMathRandom()
143
- });
144
- }
145
- const newScopes = {
146
- scope,
147
- isolationScope: scopes ? scopes.isolationScope : getIsolationScope()
148
- };
149
- return setScopesOnContext(ctx, newScopes);
164
+ const scopes = getScopesFromContext(ctx);
165
+ const scope = scopes ? scopes.scope : getCurrentScope().clone();
166
+ if (!scopes && !isContinuingTrace) {
167
+ const propagationContext = scope.getPropagationContext();
168
+ scope.setPropagationContext({
169
+ ...propagationContext,
170
+ traceId: generateTraceId(),
171
+ sampleRand: _INTERNAL_safeMathRandom()
172
+ });
173
+ }
174
+ return setScopesOnContext(ctx, {
175
+ scope,
176
+ isolationScope: scopes ? scopes.isolationScope : getIsolationScope()
177
+ });
150
178
  }
151
- function generateRemoteSpanContext({
152
- spanId,
153
- traceId,
154
- sampled,
155
- dsc
156
- }) {
157
- const traceState = makeTraceState({
158
- dsc,
159
- sampled
160
- });
161
- const spanContext = {
162
- traceId,
163
- spanId,
164
- isRemote: true,
165
- traceFlags: sampled ? TraceFlags.SAMPLED : TraceFlags.NONE,
166
- traceState
167
- };
168
- return spanContext;
179
+ function generateRemoteSpanContext({ spanId, traceId, sampled, dsc }) {
180
+ const traceState = makeTraceState({
181
+ dsc,
182
+ sampled
183
+ });
184
+ return {
185
+ traceId,
186
+ spanId,
187
+ isRemote: true,
188
+ traceFlags: sampled ? TraceFlags.SAMPLED : TraceFlags.NONE,
189
+ traceState
190
+ };
169
191
  }
170
-
192
+ // src/utils/suppressTracing.ts
171
193
  const SUPPRESS_TRACING_KEY = createContextKey("OpenTelemetry SDK Context Key SUPPRESS_TRACING");
194
+ /** Whether tracing is suppressed in the given context. */
172
195
  function isTracingSuppressed(context) {
173
- return context.getValue(SUPPRESS_TRACING_KEY) === true;
196
+ return context.getValue(SUPPRESS_TRACING_KEY) === true;
174
197
  }
175
-
198
+ // src/utils/convertSpanLinkType.ts
199
+ /**
200
+ * Converts OpenTelemetry span links to Sentry span links.
201
+ *
202
+ * Since `@opentelemetry/api` 1.10.0, link attribute values are typed as `unknown`.
203
+ * Sentry's `SpanLink` only accepts strings, numbers, booleans and arrays of these as attribute values,
204
+ * so OTel links do not match its type.
205
+ */
176
206
  function convertSpanLinkType(links) {
177
- return links;
207
+ return links;
178
208
  }
179
-
180
- class SentryTracer {
181
- /** @inheritdoc */
182
- startSpan(name, options = {}, ctx) {
183
- const parentContext = ctx || context.active();
184
- const parentSpanCandidate = options.root ? void 0 : trace.getSpan(parentContext);
185
- const parentSpan = parentSpanCandidate && isSpanContextValid(parentSpanCandidate.spanContext()) ? parentSpanCandidate : void 0;
186
- if (isTracingSuppressed(parentContext)) {
187
- return this._createNonRecordingSpan(parentSpan);
188
- }
189
- const span = this._startSentrySpan(name, options, parentSpan, ctx !== void 0);
190
- markSpanAsTracerProviderSpan(span);
191
- return span;
192
- }
193
- startActiveSpan(name, optionsOrFn, contextOrFn, fn) {
194
- const options = typeof optionsOrFn === "function" ? {} : optionsOrFn;
195
- const explicitCtx = typeof contextOrFn === "function" || contextOrFn === void 0 ? void 0 : contextOrFn;
196
- const ctx = explicitCtx ?? context.active();
197
- const callback = typeof optionsOrFn === "function" ? optionsOrFn : typeof contextOrFn === "function" ? contextOrFn : fn;
198
- const span = this.startSpan(name, options, explicitCtx);
199
- const capturedIsolationScope = getCapturedScopesOnSpan(span).isolationScope;
200
- const withCapturedIsolationScope = (contextToFork) => capturedIsolationScope ? contextToFork.setValue(SENTRY_FORK_SET_ISOLATION_SCOPE_CONTEXT_KEY, capturedIsolationScope) : contextToFork;
201
- if (spanIsIgnored(span) && this._hasParentSpan(options, explicitCtx)) {
202
- return context.with(withCapturedIsolationScope(ctx), () => callback(span));
203
- }
204
- return context.with(withCapturedIsolationScope(trace.setSpan(ctx, span)), () => {
205
- if (trace.getSpan(context.active()) !== span) {
206
- return withScope((scope) => {
207
- _INTERNAL_setSpanForScope(scope, span);
208
- return callback(span);
209
- });
210
- }
211
- _INTERNAL_setSpanForScope(getCurrentScope(), span);
212
- return callback(span);
213
- });
214
- }
215
- /**
216
- * Whether a span started with these arguments gets a parent. Mirrors the parent lookup in `startSpan`
217
- * plus core's fallback to the scope's active span, which is what parents the span on runtimes without an
218
- * OTel context manager.
219
- */
220
- _hasParentSpan(options, explicitCtx) {
221
- if (options.root) {
222
- return false;
223
- }
224
- const parentSpan = explicitCtx ? trace.getSpan(explicitCtx) : getActiveSpan$1();
225
- return !!parentSpan && isSpanContextValid(parentSpan.spanContext());
226
- }
227
- _startSentrySpan(name, options, parentSpan, hasExplicitContext) {
228
- const sentryOptions = {
229
- name,
230
- attributes: options.attributes || {},
231
- links: convertSpanLinkType(options.links),
232
- startTime: options.startTime != null ? otelTimeInputToSeconds(options.startTime) : void 0
233
- };
234
- if (options.kind) {
235
- sentryOptions.attributes[SENTRY_KIND] = spanKindToName(options.kind);
236
- }
237
- if (options.root) {
238
- return startNewTrace(() => startInactiveSpan({ ...sentryOptions, parentSpan: null }));
239
- }
240
- if (parentSpan) {
241
- return startInactiveSpan({ ...sentryOptions, parentSpan });
242
- }
243
- return startInactiveSpan({
244
- ...sentryOptions,
245
- parentSpan: hasExplicitContext ? null : void 0
246
- });
247
- }
248
- _createNonRecordingSpan(parentSpan) {
249
- const traceId = parentSpan?.spanContext().traceId ?? getCurrentScope().getPropagationContext().traceId;
250
- const span = new SentryNonRecordingSpan({ traceId });
251
- if (parentSpan) {
252
- addChildSpanToSpan(parentSpan, span);
253
- }
254
- setCapturedScopesOnSpan(span, getCurrentScope(), getIsolationScope());
255
- return span;
256
- }
257
- }
258
-
259
- class SentryTracerProvider {
260
- constructor() {
261
- this._tracers = /* @__PURE__ */ new Map();
262
- }
263
- /** @inheritdoc */
264
- getTracer(name, version, options) {
265
- const key = JSON.stringify([name, version, options]);
266
- const cachedTracer = this._tracers.get(key);
267
- if (cachedTracer) {
268
- return cachedTracer;
269
- }
270
- const tracer = new SentryTracer();
271
- this._tracers.set(key, tracer);
272
- return tracer;
273
- }
274
- /** Compatibility with SDK tracer providers. */
275
- forceFlush() {
276
- return Promise.resolve();
277
- }
278
- /** Compatibility with SDK tracer providers. */
279
- shutdown() {
280
- return Promise.resolve();
281
- }
282
- }
283
-
209
+ // src/tracer.ts
210
+ var SentryTracer = class {
211
+ /** @inheritdoc */
212
+ startSpan(name, options = {}, ctx) {
213
+ const parentContext = ctx || context.active();
214
+ const parentSpanCandidate = options.root ? void 0 : trace.getSpan(parentContext);
215
+ const parentSpan = parentSpanCandidate && isSpanContextValid(parentSpanCandidate.spanContext()) ? parentSpanCandidate : void 0;
216
+ if (isTracingSuppressed(parentContext)) return this._createNonRecordingSpan(parentSpan);
217
+ const span = this._startSentrySpan(name, options, parentSpan, ctx !== void 0);
218
+ markSpanAsTracerProviderSpan(span);
219
+ return span;
220
+ }
221
+ startActiveSpan(name, optionsOrFn, contextOrFn, fn) {
222
+ const options = typeof optionsOrFn === "function" ? {} : optionsOrFn;
223
+ const explicitCtx = typeof contextOrFn === "function" || contextOrFn === void 0 ? void 0 : contextOrFn;
224
+ const ctx = explicitCtx ?? context.active();
225
+ const callback = typeof optionsOrFn === "function" ? optionsOrFn : typeof contextOrFn === "function" ? contextOrFn : fn;
226
+ const span = this.startSpan(name, options, explicitCtx);
227
+ const capturedIsolationScope = getCapturedScopesOnSpan(span).isolationScope;
228
+ const withCapturedIsolationScope = (contextToFork) => capturedIsolationScope ? contextToFork.setValue(SENTRY_FORK_SET_ISOLATION_SCOPE_CONTEXT_KEY, capturedIsolationScope) : contextToFork;
229
+ if (spanIsIgnored(span) && this._hasParentSpan(options, explicitCtx)) return context.with(withCapturedIsolationScope(ctx), () => callback(span));
230
+ return context.with(withCapturedIsolationScope(trace.setSpan(ctx, span)), () => {
231
+ if (trace.getSpan(context.active()) !== span) return withScope((scope) => {
232
+ _INTERNAL_setSpanForScope(scope, span);
233
+ return callback(span);
234
+ });
235
+ _INTERNAL_setSpanForScope(getCurrentScope(), span);
236
+ return callback(span);
237
+ });
238
+ }
239
+ /**
240
+ * Whether a span started with these arguments gets a parent. Mirrors the parent lookup in `startSpan`
241
+ * plus core's fallback to the scope's active span, which is what parents the span on runtimes without an
242
+ * OTel context manager.
243
+ */
244
+ _hasParentSpan(options, explicitCtx) {
245
+ if (options.root) return false;
246
+ const parentSpan = explicitCtx ? trace.getSpan(explicitCtx) : getActiveSpan$1();
247
+ return !!parentSpan && isSpanContextValid(parentSpan.spanContext());
248
+ }
249
+ _startSentrySpan(name, options, parentSpan, hasExplicitContext) {
250
+ const sentryOptions = {
251
+ name,
252
+ attributes: options.attributes || {},
253
+ links: convertSpanLinkType(options.links),
254
+ startTime: options.startTime != null ? otelTimeInputToSeconds(options.startTime) : void 0
255
+ };
256
+ if (options.kind) sentryOptions.attributes[SENTRY_KIND] = spanKindToName(options.kind);
257
+ if (options.root) return startNewTrace(() => startInactiveSpan({
258
+ ...sentryOptions,
259
+ parentSpan: null
260
+ }));
261
+ if (parentSpan) return startInactiveSpan({
262
+ ...sentryOptions,
263
+ parentSpan
264
+ });
265
+ return startInactiveSpan({
266
+ ...sentryOptions,
267
+ parentSpan: hasExplicitContext ? null : void 0
268
+ });
269
+ }
270
+ _createNonRecordingSpan(parentSpan) {
271
+ const traceId = parentSpan?.spanContext().traceId ?? getCurrentScope().getPropagationContext().traceId;
272
+ const span = new SentryNonRecordingSpan({ traceId });
273
+ if (parentSpan) addChildSpanToSpan(parentSpan, span);
274
+ setCapturedScopesOnSpan(span, getCurrentScope(), getIsolationScope());
275
+ return span;
276
+ }
277
+ };
278
+ // src/tracerProvider.ts
279
+ /**
280
+ * A minimal OpenTelemetry TracerProvider which creates native Sentry spans.
281
+ */
282
+ var SentryTracerProvider = class {
283
+ constructor() {
284
+ this._tracers = /* @__PURE__ */ new Map();
285
+ }
286
+ /** @inheritdoc */
287
+ getTracer(name, version, options) {
288
+ const key = JSON.stringify([
289
+ name,
290
+ version,
291
+ options
292
+ ]);
293
+ const cachedTracer = this._tracers.get(key);
294
+ if (cachedTracer) return cachedTracer;
295
+ const tracer = new SentryTracer();
296
+ this._tracers.set(key, tracer);
297
+ return tracer;
298
+ }
299
+ /** Compatibility with SDK tracer providers. */
300
+ forceFlush() {
301
+ return Promise.resolve();
302
+ }
303
+ /** Compatibility with SDK tracer providers. */
304
+ shutdown() {
305
+ return Promise.resolve();
306
+ }
307
+ };
308
+ // src/trace.ts
309
+ /**
310
+ * Forks the current scope and sets the provided span as active span in the context of the provided callback. Can be
311
+ * passed `null` to start an entirely new span tree.
312
+ *
313
+ * @param span Spans started in the context of the provided callback will be children of this span. If `null` is passed,
314
+ * spans started within the callback will be root spans.
315
+ * @param callback Execution context in which the provided span will be active. Is passed the newly forked scope.
316
+ * @returns the value returned from the provided callback function.
317
+ */
284
318
  function withActiveSpan(span, callback) {
285
- const newContextWithActiveSpan = span ? trace.setSpan(context.active(), span) : trace.deleteSpan(context.active());
286
- return context.with(newContextWithActiveSpan, () => {
287
- const scope = getCurrentScope();
288
- _INTERNAL_setSpanForScope(scope, span ?? void 0);
289
- return callback(scope);
290
- });
319
+ const newContextWithActiveSpan = span ? trace.setSpan(context.active(), span) : trace.deleteSpan(context.active());
320
+ return context.with(newContextWithActiveSpan, () => {
321
+ const scope = getCurrentScope();
322
+ _INTERNAL_setSpanForScope(scope, span ?? void 0);
323
+ return callback(scope);
324
+ });
291
325
  }
292
-
326
+ // src/utils/getActiveSpan.ts
327
+ /**
328
+ * Returns the currently active span, or the active span of the given scope's context.
329
+ *
330
+ * Spans with an invalid span context (e.g. a malformed incoming trace/span id put on the context by
331
+ * a propagator) are ignored, matching the OTel SDK tracer, so consumers start a fresh trace instead
332
+ * of continuing a broken one.
333
+ */
293
334
  function getActiveSpan(scope) {
294
- const span = scope ? getSpanFromScope(scope) : trace.getActiveSpan();
295
- return span && isSpanContextValid(span.spanContext()) ? span : void 0;
335
+ const span = scope ? getSpanFromScope(scope) : trace.getActiveSpan();
336
+ return span && isSpanContextValid(span.spanContext()) ? span : void 0;
296
337
  }
297
338
  function getSpanFromScope(scope) {
298
- const ctx = getContextFromScope(scope);
299
- return ctx ? trace.getSpan(ctx) : void 0;
339
+ const ctx = getContextFromScope(scope);
340
+ return ctx ? trace.getSpan(ctx) : void 0;
300
341
  }
301
-
342
+ // src/utils/buildContextWithSentryScopes.ts
343
+ /**
344
+ * Merge Sentry scopes into an OpenTelemetry {@link Context} and apply trace-context adjustments
345
+ * used by Sentry OpenTelemetry context manager(s).
346
+ *
347
+ * @param context - Context passed into `ContextManager.with`.
348
+ * @param activeContext - Context that was active before entering `with` (e.g. `this.active()`), used
349
+ * to restore the parent span when the incoming span is marked ignored for children.
350
+ * @returns A new context ready for `super.with` / `AsyncLocalStorage.run`.
351
+ */
302
352
  function buildContextWithSentryScopes(context) {
303
- const currentScopes = getScopesFromContext(context);
304
- const currentScope = currentScopes?.scope || getCurrentScope();
305
- const currentIsolationScope = currentScopes?.isolationScope || getIsolationScope();
306
- const shouldForkIsolationScope = context.getValue(SENTRY_FORK_ISOLATION_SCOPE_CONTEXT_KEY) === true;
307
- const scope = context.getValue(SENTRY_FORK_SET_SCOPE_CONTEXT_KEY);
308
- const isolationScope = context.getValue(SENTRY_FORK_SET_ISOLATION_SCOPE_CONTEXT_KEY);
309
- const newCurrentScope = scope || currentScope.clone();
310
- const newIsolationScope = isolationScope || (shouldForkIsolationScope ? currentIsolationScope.clone() : currentIsolationScope);
311
- const scopes = { scope: newCurrentScope, isolationScope: newIsolationScope };
312
- const ctx1 = setScopesOnContext(context, scopes);
313
- 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);
314
- setContextOnScope(newCurrentScope, ctx2);
315
- return ctx2;
316
- }
317
-
318
- const ADD_LISTENER_METHODS = ["addListener", "on", "once", "prependListener", "prependOnceListener"];
319
- class SentryAsyncLocalStorageContextManager {
320
- constructor(asyncLocalStorage) {
321
- this._kOtListeners = /* @__PURE__ */ Symbol("OtListeners");
322
- this._wrapped = false;
323
- this._asyncLocalStorage = asyncLocalStorage;
324
- }
325
- active() {
326
- return this._asyncLocalStorage.getStore() ?? ROOT_CONTEXT;
327
- }
328
- with(context, fn, thisArg, ...args) {
329
- const ctx2 = buildContextWithSentryScopes(context);
330
- const cb = thisArg == null ? fn : fn.bind(thisArg);
331
- return this._asyncLocalStorage.run(ctx2, cb, ...args);
332
- }
333
- enable() {
334
- return this;
335
- }
336
- disable() {
337
- try {
338
- this._asyncLocalStorage.disable();
339
- } catch {
340
- }
341
- return this;
342
- }
343
- bind(context, target) {
344
- if (isEventEmitter(target)) {
345
- return this._bindEventEmitter(context, target);
346
- }
347
- if (typeof target === "function") {
348
- return this._bindFunction(context, target);
349
- }
350
- return target;
351
- }
352
- /**
353
- * Gets underlying AsyncLocalStorage and symbol to allow lookup of scope.
354
- * This is Sentry-specific.
355
- */
356
- getAsyncLocalStorageLookup() {
357
- return {
358
- asyncLocalStorage: this._asyncLocalStorage,
359
- contextSymbol: SENTRY_SCOPES_CONTEXT_KEY
360
- };
361
- }
362
- _bindFunction(context, target) {
363
- const managerWith = this.with.bind(this);
364
- const contextWrapper = function(...args) {
365
- return managerWith(context, () => target.apply(this, args));
366
- };
367
- Object.defineProperty(contextWrapper, "length", {
368
- enumerable: false,
369
- configurable: true,
370
- writable: false,
371
- value: target.length
372
- });
373
- return contextWrapper;
374
- }
375
- _bindEventEmitter(context, ee) {
376
- if (this._getPatchMap(ee) !== void 0) {
377
- return ee;
378
- }
379
- if (this._createPatchMap(ee) === void 0) {
380
- return ee;
381
- }
382
- for (const methodName of ADD_LISTENER_METHODS) {
383
- const original = getMethod(ee, methodName);
384
- if (!original) continue;
385
- trySetMethod(ee, methodName, this._patchAddListener(ee, original, context));
386
- }
387
- for (const methodName of ["removeListener", "off"]) {
388
- const original = getMethod(ee, methodName);
389
- if (!original) continue;
390
- trySetMethod(ee, methodName, this._patchRemoveListener(ee, original));
391
- }
392
- const removeAllListeners = getMethod(ee, "removeAllListeners");
393
- if (removeAllListeners) {
394
- trySetMethod(ee, "removeAllListeners", this._patchRemoveAllListeners(ee, removeAllListeners));
395
- }
396
- return ee;
397
- }
398
- _patchRemoveListener(ee, original) {
399
- const contextManager = this;
400
- return function(event, listener) {
401
- const events = contextManager._getPatchMap(ee)?.[event];
402
- if (events === void 0) {
403
- return original.call(this, event, listener);
404
- }
405
- const patchedListener = events.get(listener);
406
- return original.call(this, event, patchedListener || listener);
407
- };
408
- }
409
- _patchRemoveAllListeners(ee, original) {
410
- const contextManager = this;
411
- return function(event) {
412
- const map = contextManager._getPatchMap(ee);
413
- if (map !== void 0) {
414
- if (arguments.length === 0) {
415
- contextManager._createPatchMap(ee);
416
- } else if (event !== void 0 && map[event] !== void 0) {
417
- delete map[event];
418
- }
419
- }
420
- return original.apply(this, arguments);
421
- };
422
- }
423
- _patchAddListener(ee, original, context) {
424
- const contextManager = this;
425
- return function(event, listener) {
426
- if (contextManager._wrapped) {
427
- return original.call(this, event, listener);
428
- }
429
- const map = contextManager._getPatchMap(ee) ?? contextManager._createPatchMap(ee);
430
- if (map === void 0) {
431
- return original.call(this, event, listener);
432
- }
433
- let listeners = map[event];
434
- if (listeners === void 0) {
435
- listeners = /* @__PURE__ */ new WeakMap();
436
- map[event] = listeners;
437
- }
438
- const patchedListener = contextManager.bind(context, listener);
439
- listeners.set(listener, patchedListener);
440
- contextManager._wrapped = true;
441
- try {
442
- return original.call(this, event, patchedListener);
443
- } finally {
444
- contextManager._wrapped = false;
445
- }
446
- };
447
- }
448
- /**
449
- * Attach a fresh patch map to the emitter. Returns `undefined` if the emitter does not accept the
450
- * property (e.g. it is frozen or sealed), in which case the emitter must not be patched at all —
451
- * without a patch map the remove-listener patches could not resolve their wrapped listeners.
452
- */
453
- _createPatchMap(ee) {
454
- const map = /* @__PURE__ */ Object.create(null);
455
- try {
456
- ee[this._kOtListeners] = map;
457
- } catch {
458
- return void 0;
459
- }
460
- return this._getPatchMap(ee) === map ? map : void 0;
461
- }
462
- _getPatchMap(ee) {
463
- return ee[this._kOtListeners];
464
- }
353
+ const currentScopes = getScopesFromContext(context);
354
+ const currentScope = currentScopes?.scope || getCurrentScope();
355
+ const currentIsolationScope = currentScopes?.isolationScope || getIsolationScope();
356
+ const shouldForkIsolationScope = context.getValue(SENTRY_FORK_ISOLATION_SCOPE_CONTEXT_KEY) === true;
357
+ const scope = context.getValue(SENTRY_FORK_SET_SCOPE_CONTEXT_KEY);
358
+ const isolationScope = context.getValue(SENTRY_FORK_SET_ISOLATION_SCOPE_CONTEXT_KEY);
359
+ const newCurrentScope = scope || currentScope.clone();
360
+ const ctx2 = setScopesOnContext(context, {
361
+ scope: newCurrentScope,
362
+ isolationScope: isolationScope || (shouldForkIsolationScope ? currentIsolationScope.clone() : currentIsolationScope)
363
+ }).deleteValue(SENTRY_FORK_ISOLATION_SCOPE_CONTEXT_KEY).deleteValue(SENTRY_FORK_SET_SCOPE_CONTEXT_KEY).deleteValue(SENTRY_FORK_SET_ISOLATION_SCOPE_CONTEXT_KEY);
364
+ if (!scope || !getContextFromScope(scope)) setContextOnScope(newCurrentScope, ctx2);
365
+ return ctx2;
465
366
  }
367
+ // src/asyncLocalStorageContextManager.ts
368
+ const ADD_LISTENER_METHODS = [
369
+ "addListener",
370
+ "on",
371
+ "once",
372
+ "prependListener",
373
+ "prependOnceListener"
374
+ ];
375
+ /**
376
+ * OpenTelemetry-compatible context manager using Node.js `AsyncLocalStorage`.
377
+ */
378
+ var SentryAsyncLocalStorageContextManager = class {
379
+ constructor(asyncLocalStorage) {
380
+ this._kOtListeners = Symbol("OtListeners");
381
+ this._wrapped = false;
382
+ this._asyncLocalStorage = asyncLocalStorage;
383
+ }
384
+ active() {
385
+ return this._asyncLocalStorage.getStore() ?? ROOT_CONTEXT;
386
+ }
387
+ with(context, fn, thisArg, ...args) {
388
+ const ctx2 = buildContextWithSentryScopes(context);
389
+ const cb = thisArg == null ? fn : fn.bind(thisArg);
390
+ return this._asyncLocalStorage.run(ctx2, cb, ...args);
391
+ }
392
+ enable() {
393
+ return this;
394
+ }
395
+ disable() {
396
+ try {
397
+ this._asyncLocalStorage.disable();
398
+ } catch {}
399
+ return this;
400
+ }
401
+ bind(context, target) {
402
+ if (isEventEmitter(target)) return this._bindEventEmitter(context, target);
403
+ if (typeof target === "function") return this._bindFunction(context, target);
404
+ return target;
405
+ }
406
+ /**
407
+ * Gets underlying AsyncLocalStorage and symbol to allow lookup of scope.
408
+ * This is Sentry-specific.
409
+ */
410
+ getAsyncLocalStorageLookup() {
411
+ return {
412
+ asyncLocalStorage: this._asyncLocalStorage,
413
+ contextSymbol: SENTRY_SCOPES_CONTEXT_KEY
414
+ };
415
+ }
416
+ _bindFunction(context, target) {
417
+ const managerWith = this.with.bind(this);
418
+ const contextWrapper = function(...args) {
419
+ return managerWith(context, () => target.apply(this, args));
420
+ };
421
+ Object.defineProperty(contextWrapper, "length", {
422
+ enumerable: false,
423
+ configurable: true,
424
+ writable: false,
425
+ value: target.length
426
+ });
427
+ return contextWrapper;
428
+ }
429
+ _bindEventEmitter(context, ee) {
430
+ if (this._getPatchMap(ee) !== void 0) return ee;
431
+ if (this._createPatchMap(ee) === void 0) return ee;
432
+ for (const methodName of ADD_LISTENER_METHODS) {
433
+ const original = getMethod(ee, methodName);
434
+ if (!original) continue;
435
+ trySetMethod(ee, methodName, this._patchAddListener(ee, original, context));
436
+ }
437
+ for (const methodName of ["removeListener", "off"]) {
438
+ const original = getMethod(ee, methodName);
439
+ if (!original) continue;
440
+ trySetMethod(ee, methodName, this._patchRemoveListener(ee, original));
441
+ }
442
+ const removeAllListeners = getMethod(ee, "removeAllListeners");
443
+ if (removeAllListeners) trySetMethod(ee, "removeAllListeners", this._patchRemoveAllListeners(ee, removeAllListeners));
444
+ return ee;
445
+ }
446
+ _patchRemoveListener(ee, original) {
447
+ const contextManager = this;
448
+ return function(event, listener) {
449
+ const events = contextManager._getPatchMap(ee)?.[event];
450
+ if (events === void 0) return original.call(this, event, listener);
451
+ const patchedListener = events.get(listener);
452
+ return original.call(this, event, patchedListener || listener);
453
+ };
454
+ }
455
+ _patchRemoveAllListeners(ee, original) {
456
+ const contextManager = this;
457
+ return function(event) {
458
+ const map = contextManager._getPatchMap(ee);
459
+ if (map !== void 0) {
460
+ if (arguments.length === 0) contextManager._createPatchMap(ee);
461
+ else if (event !== void 0 && map[event] !== void 0) delete map[event];
462
+ }
463
+ return original.apply(this, arguments);
464
+ };
465
+ }
466
+ _patchAddListener(ee, original, context) {
467
+ const contextManager = this;
468
+ return function(event, listener) {
469
+ if (contextManager._wrapped) return original.call(this, event, listener);
470
+ const map = contextManager._getPatchMap(ee) ?? contextManager._createPatchMap(ee);
471
+ if (map === void 0) return original.call(this, event, listener);
472
+ let listeners = map[event];
473
+ if (listeners === void 0) {
474
+ listeners = /* @__PURE__ */ new WeakMap();
475
+ map[event] = listeners;
476
+ }
477
+ const patchedListener = contextManager.bind(context, listener);
478
+ listeners.set(listener, patchedListener);
479
+ contextManager._wrapped = true;
480
+ try {
481
+ return original.call(this, event, patchedListener);
482
+ } finally {
483
+ contextManager._wrapped = false;
484
+ }
485
+ };
486
+ }
487
+ /**
488
+ * Attach a fresh patch map to the emitter. Returns `undefined` if the emitter does not accept the
489
+ * property (e.g. it is frozen or sealed), in which case the emitter must not be patched at all —
490
+ * without a patch map the remove-listener patches could not resolve their wrapped listeners.
491
+ */
492
+ _createPatchMap(ee) {
493
+ const map = Object.create(null);
494
+ try {
495
+ ee[this._kOtListeners] = map;
496
+ } catch {
497
+ return;
498
+ }
499
+ return this._getPatchMap(ee) === map ? map : void 0;
500
+ }
501
+ _getPatchMap(ee) {
502
+ return ee[this._kOtListeners];
503
+ }
504
+ };
505
+ /**
506
+ * Duck-typed `EventEmitter` check.
507
+ *
508
+ * We use this instead of `instanceof EventEmitter` so it also works in non-Node.js environments (e.g. vercel-edge)
509
+ * and across realms. Both `on` and `emit` must be callable — checking only for the presence of an `on` property
510
+ * would classify plain objects like `{ on: true }` as emitters and later try to call a non-function.
511
+ */
466
512
  function isEventEmitter(target) {
467
- if (typeof target !== "object" || !target) {
468
- return false;
469
- }
470
- const candidate = target;
471
- return typeof candidate.on === "function" && typeof candidate.emit === "function";
513
+ if (typeof target !== "object" || !target) return false;
514
+ const candidate = target;
515
+ return typeof candidate.on === "function" && typeof candidate.emit === "function";
472
516
  }
517
+ /**
518
+ * Read a method off an emitter, ignoring inherited or own properties that are not callable.
519
+ */
473
520
  function getMethod(ee, methodName) {
474
- const value = ee[methodName];
475
- return typeof value === "function" ? value : void 0;
521
+ const value = ee[methodName];
522
+ return typeof value === "function" ? value : void 0;
476
523
  }
524
+ /**
525
+ * Assign a patched method back onto the emitter. Emitters may be frozen or expose getter-only methods,
526
+ * in which case we leave the original method in place instead of throwing.
527
+ */
477
528
  function trySetMethod(ee, methodName, patched) {
478
- try {
479
- ee[methodName] = patched;
480
- } catch {
481
- }
529
+ try {
530
+ ee[methodName] = patched;
531
+ } catch {}
482
532
  }
483
-
533
+ // src/asyncContextStrategy.ts
534
+ /**
535
+ * Sets the async context strategy to use follow the OTEL context under the hood.
536
+ * We handle forking a hub inside of our custom OTEL Context Manager (./otelContextManager.ts)
537
+ */
484
538
  function setOpenTelemetryContextAsyncContextStrategy() {
485
- const existingAsyncLocalStorage = getAsyncContextStrategy(getMainCarrier()).getTracingChannelBinding?.()?.asyncLocalStorage;
486
- const asyncLocalStorage = existingAsyncLocalStorage ?? new AsyncLocalStorage();
487
- function getScopes() {
488
- const ctx = api.context.active();
489
- const scopes = getScopesFromContext(ctx);
490
- if (scopes) {
491
- return scopes;
492
- }
493
- return {
494
- scope: getDefaultCurrentScope(),
495
- isolationScope: getDefaultIsolationScope()
496
- };
497
- }
498
- function withScope(callback) {
499
- const ctx = api.context.active();
500
- return api.context.with(ctx, () => {
501
- return callback(getCurrentScope());
502
- });
503
- }
504
- function withSetScope(scope, callback) {
505
- const ctx = getContextFromScope(scope) || api.context.active();
506
- return api.context.with(ctx.setValue(SENTRY_FORK_SET_SCOPE_CONTEXT_KEY, scope), () => {
507
- return callback(scope);
508
- });
509
- }
510
- function withIsolationScope(callback) {
511
- const ctx = api.context.active();
512
- return api.context.with(ctx.setValue(SENTRY_FORK_ISOLATION_SCOPE_CONTEXT_KEY, true), () => {
513
- const scope = getCurrentScope();
514
- if (!isContinuingTrace(scope.getPropagationContext())) {
515
- scope.setPropagationContext({
516
- traceId: generateTraceId(),
517
- sampleRand: _INTERNAL_safeMathRandom()
518
- });
519
- }
520
- return callback(getIsolationScope());
521
- });
522
- }
523
- function withSetIsolationScope(isolationScope, callback) {
524
- const ctx = api.context.active();
525
- return api.context.with(ctx.setValue(SENTRY_FORK_SET_ISOLATION_SCOPE_CONTEXT_KEY, isolationScope), () => {
526
- return callback(getIsolationScope());
527
- });
528
- }
529
- function getCurrentScope() {
530
- return getScopes().scope;
531
- }
532
- function getIsolationScope() {
533
- return getScopes().isolationScope;
534
- }
535
- function getTracingChannelBinding() {
536
- return {
537
- asyncLocalStorage
538
- };
539
- }
540
- setAsyncContextStrategy({
541
- withScope,
542
- withSetScope,
543
- withSetIsolationScope,
544
- withIsolationScope,
545
- getCurrentScope,
546
- getIsolationScope,
547
- getActiveSpan,
548
- // The types here don't fully align, because our own `Span` type is narrower
549
- // than the OTEL one - but this is OK for here, as we now we'll only have OTEL spans passed around
550
- withActiveSpan,
551
- getTracingChannelBinding
552
- });
553
- const ctxManager = new SentryAsyncLocalStorageContextManager(asyncLocalStorage);
554
- api.context.setGlobalContextManager(ctxManager);
555
- return ctxManager.getAsyncLocalStorageLookup();
539
+ const asyncLocalStorage = getAsyncContextStrategy(getMainCarrier()).getTracingChannelBinding?.()?.asyncLocalStorage ?? new AsyncLocalStorage();
540
+ function getScopes() {
541
+ const scopes = getScopesFromContext(api.context.active());
542
+ if (scopes) return scopes;
543
+ return {
544
+ scope: getDefaultCurrentScope(),
545
+ isolationScope: getDefaultIsolationScope()
546
+ };
547
+ }
548
+ function withScope(callback) {
549
+ const ctx = api.context.active();
550
+ return api.context.with(ctx, () => {
551
+ return callback(getCurrentScope());
552
+ });
553
+ }
554
+ function withSetScope(scope, callback) {
555
+ const ctx = getContextFromScope(scope) || api.context.active();
556
+ return api.context.with(ctx.setValue(SENTRY_FORK_SET_SCOPE_CONTEXT_KEY, scope), () => {
557
+ return callback(scope);
558
+ });
559
+ }
560
+ function withIsolationScope(callback) {
561
+ const ctx = api.context.active();
562
+ return api.context.with(ctx.setValue(SENTRY_FORK_ISOLATION_SCOPE_CONTEXT_KEY, true), () => {
563
+ const scope = getCurrentScope();
564
+ if (!isContinuingTrace(scope.getPropagationContext())) scope.setPropagationContext({
565
+ traceId: generateTraceId(),
566
+ sampleRand: _INTERNAL_safeMathRandom()
567
+ });
568
+ return callback(getIsolationScope());
569
+ });
570
+ }
571
+ function withSetIsolationScope(isolationScope, callback) {
572
+ const ctx = api.context.active();
573
+ return api.context.with(ctx.setValue(SENTRY_FORK_SET_ISOLATION_SCOPE_CONTEXT_KEY, isolationScope), () => {
574
+ return callback(getIsolationScope());
575
+ });
576
+ }
577
+ function getCurrentScope() {
578
+ return getScopes().scope;
579
+ }
580
+ function getIsolationScope() {
581
+ return getScopes().isolationScope;
582
+ }
583
+ function getTracingChannelBinding() {
584
+ return { asyncLocalStorage };
585
+ }
586
+ setAsyncContextStrategy({
587
+ withScope,
588
+ withSetScope,
589
+ withSetIsolationScope,
590
+ withIsolationScope,
591
+ getCurrentScope,
592
+ getIsolationScope,
593
+ getActiveSpan,
594
+ withActiveSpan,
595
+ getTracingChannelBinding
596
+ });
597
+ const ctxManager = new SentryAsyncLocalStorageContextManager(asyncLocalStorage);
598
+ api.context.setGlobalContextManager(ctxManager);
599
+ return ctxManager.getAsyncLocalStorageLookup();
556
600
  }
557
-
601
+ // src/utils/getSamplingDecision.ts
602
+ /**
603
+ * OpenTelemetry only knows about SAMPLED or NONE decision,
604
+ * but for us it is important to differentiate between unset and unsampled.
605
+ *
606
+ * Both of these are identified as `traceFlags === TracegFlags.NONE`,
607
+ * but we additionally look at a special trace state to differentiate between them.
608
+ */
558
609
  function getSamplingDecision(spanContext) {
559
- const { traceFlags, traceState } = spanContext;
560
- const sampledNotRecording = traceState ? traceState.get(SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING) === "1" : false;
561
- if (traceFlags === TraceFlags.SAMPLED) {
562
- return true;
563
- }
564
- if (sampledNotRecording) {
565
- return false;
566
- }
567
- const dscString = traceState ? traceState.get(SENTRY_TRACE_STATE_DSC) : void 0;
568
- const dsc = dscString ? baggageHeaderToDynamicSamplingContext(dscString) : void 0;
569
- if (dsc?.sampled === "true") {
570
- return true;
571
- }
572
- if (dsc?.sampled === "false") {
573
- return false;
574
- }
575
- return void 0;
610
+ const { traceFlags, traceState } = spanContext;
611
+ const sampledNotRecording = traceState ? traceState.get(SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING) === "1" : false;
612
+ if (traceFlags === TraceFlags.SAMPLED) return true;
613
+ if (sampledNotRecording) return false;
614
+ const dscString = traceState ? traceState.get(SENTRY_TRACE_STATE_DSC) : void 0;
615
+ const dsc = dscString ? baggageHeaderToDynamicSamplingContext(dscString) : void 0;
616
+ if (dsc?.sampled === "true") return true;
617
+ if (dsc?.sampled === "false") return false;
576
618
  }
577
-
619
+ // src/prepareSpanScope.ts
620
+ /**
621
+ * Registers the `prepareSpanScope` hook on the client.
622
+ *
623
+ * A remote parent is an incoming trace on the ambient OTel context, set by the propagator. It
624
+ * cannot be used as a local parent span. The hook continues its trace through the propagation
625
+ * context of a forked scope instead, so the span is created as a root span of the incoming trace,
626
+ * like the OpenTelemetry SDK does for remote parents.
627
+ */
578
628
  function registerPrepareSpanScope(client) {
579
- client.on("prepareSpanScope", (spanScope) => {
580
- const { scope, parentSpan } = spanScope;
581
- if (!parentSpan?.spanContext().isRemote) {
582
- return;
583
- }
584
- const { spanId, traceId, traceState } = parentSpan.spanContext();
585
- const dsc = getDynamicSamplingContextFromSpan(parentSpan);
586
- const sampleRand = typeof dsc.sample_rand === "string" ? Number(dsc.sample_rand) : void 0;
587
- const hasIncomingDsc = !!traceState?.get(SENTRY_TRACE_STATE_DSC);
588
- const forkedScope = scope.clone();
589
- forkedScope.setPropagationContext({
590
- traceId,
591
- parentSpanId: spanId,
592
- sampled: getSamplingDecision(parentSpan.spanContext()),
593
- dsc: hasIncomingDsc ? dsc : void 0,
594
- sampleRand: typeof sampleRand === "number" && !Number.isNaN(sampleRand) ? sampleRand : _INTERNAL_safeMathRandom()
595
- });
596
- _INTERNAL_setSpanForScope(forkedScope, void 0);
597
- spanScope.scope = forkedScope;
598
- spanScope.parentSpan = void 0;
599
- });
629
+ client.on("prepareSpanScope", (spanScope) => {
630
+ const { scope, parentSpan } = spanScope;
631
+ if (!parentSpan?.spanContext().isRemote) return;
632
+ const { spanId, traceId, traceState } = parentSpan.spanContext();
633
+ const dsc = getDynamicSamplingContextFromSpan(parentSpan);
634
+ const sampleRand = typeof dsc.sample_rand === "string" ? Number(dsc.sample_rand) : void 0;
635
+ const hasIncomingDsc = !!traceState?.get(SENTRY_TRACE_STATE_DSC);
636
+ const forkedScope = scope.clone();
637
+ forkedScope.setPropagationContext({
638
+ traceId,
639
+ parentSpanId: spanId,
640
+ sampled: getSamplingDecision(parentSpan.spanContext()),
641
+ dsc: hasIncomingDsc ? dsc : void 0,
642
+ sampleRand: typeof sampleRand === "number" && !Number.isNaN(sampleRand) ? sampleRand : _INTERNAL_safeMathRandom()
643
+ });
644
+ _INTERNAL_setSpanForScope(forkedScope, void 0);
645
+ spanScope.scope = forkedScope;
646
+ spanScope.parentSpan = void 0;
647
+ });
600
648
  }
601
-
602
649
  export { SentryPropagator, SentryTracerProvider, getScopesFromContext, registerPrepareSpanScope, setOpenTelemetryContextAsyncContextStrategy };
603
- //# sourceMappingURL=index.js.map
650
+
651
+ //# sourceMappingURL=index.js.map