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