@sentry/opentelemetry 10.70.0 → 11.0.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. package/README.md +2 -15
  2. package/build/cjs/index.js +614 -101
  3. package/build/cjs/index.js.map +1 -1
  4. package/build/esm/index.js +611 -65
  5. package/build/esm/index.js.map +1 -1
  6. package/build/esm/package.json +1 -1
  7. package/build/types/asyncContextStrategy.d.ts +2 -4
  8. package/build/types/asyncContextStrategy.d.ts.map +1 -1
  9. package/build/types/asyncLocalStorageContextManager.d.ts +16 -4
  10. package/build/types/asyncLocalStorageContextManager.d.ts.map +1 -1
  11. package/build/types/constants.d.ts +0 -15
  12. package/build/types/constants.d.ts.map +1 -1
  13. package/build/types/index.d.ts +5 -4
  14. package/build/types/index.d.ts.map +1 -1
  15. package/build/types/propagator.d.ts +11 -38
  16. package/build/types/propagator.d.ts.map +1 -1
  17. package/build/types/trace.d.ts +4 -31
  18. package/build/types/trace.d.ts.map +1 -1
  19. package/build/types/tracer.d.ts.map +1 -1
  20. package/build/types/tracerProvider.d.ts +0 -9
  21. package/build/types/tracerProvider.d.ts.map +1 -1
  22. package/build/types/types.d.ts +1 -24
  23. package/build/types/types.d.ts.map +1 -1
  24. package/build/types/utils/TraceState.d.ts.map +1 -1
  25. package/build/types/utils/buildContextWithSentryScopes.d.ts +1 -1
  26. package/build/types/utils/buildContextWithSentryScopes.d.ts.map +1 -1
  27. package/build/types/utils/contextData.d.ts.map +1 -1
  28. package/build/types/utils/getActiveSpan.d.ts +2 -1
  29. package/build/types/utils/getActiveSpan.d.ts.map +1 -1
  30. package/build/types/utils/getSamplingDecision.d.ts +0 -17
  31. package/build/types/utils/getSamplingDecision.d.ts.map +1 -1
  32. package/build/types/utils/reconcileDscSampled.d.ts +14 -0
  33. package/build/types/utils/reconcileDscSampled.d.ts.map +1 -0
  34. package/build/types/utils/suppressTracing.d.ts +5 -4
  35. package/build/types/utils/suppressTracing.d.ts.map +1 -1
  36. package/package.json +11 -38
  37. package/build/cjs/asyncContextStrategy-volGaYqZ.js +0 -1892
  38. package/build/cjs/asyncContextStrategy-volGaYqZ.js.map +0 -1
  39. package/build/cjs/index.browser.js +0 -53
  40. package/build/cjs/index.browser.js.map +0 -1
  41. package/build/esm/asyncContextStrategy-jD8YWNDU.js +0 -1857
  42. package/build/esm/asyncContextStrategy-jD8YWNDU.js.map +0 -1
  43. package/build/esm/index.browser.js +0 -14
  44. package/build/esm/index.browser.js.map +0 -1
  45. package/build/types/applyOtelSpanData.d.ts +0 -18
  46. package/build/types/applyOtelSpanData.d.ts.map +0 -1
  47. package/build/types/contextManager.d.ts +0 -22
  48. package/build/types/contextManager.d.ts.map +0 -1
  49. package/build/types/custom/client.d.ts +0 -12
  50. package/build/types/custom/client.d.ts.map +0 -1
  51. package/build/types/exports.d.ts +0 -27
  52. package/build/types/exports.d.ts.map +0 -1
  53. package/build/types/index.browser.d.ts +0 -10
  54. package/build/types/index.browser.d.ts.map +0 -1
  55. package/build/types/nodeAsyncContextStrategy.d.ts +0 -4
  56. package/build/types/nodeAsyncContextStrategy.d.ts.map +0 -1
  57. package/build/types/resource.d.ts +0 -26
  58. package/build/types/resource.d.ts.map +0 -1
  59. package/build/types/sampler.d.ts +0 -32
  60. package/build/types/sampler.d.ts.map +0 -1
  61. package/build/types/semanticAttributes.d.ts +0 -4
  62. package/build/types/semanticAttributes.d.ts.map +0 -1
  63. package/build/types/setupEventContextTrace.d.ts +0 -4
  64. package/build/types/setupEventContextTrace.d.ts.map +0 -1
  65. package/build/types/spanExporter.d.ts +0 -50
  66. package/build/types/spanExporter.d.ts.map +0 -1
  67. package/build/types/spanProcessor.d.ts +0 -31
  68. package/build/types/spanProcessor.d.ts.map +0 -1
  69. package/build/types/utils/backfillStreamedSpanData.d.ts +0 -16
  70. package/build/types/utils/backfillStreamedSpanData.d.ts.map +0 -1
  71. package/build/types/utils/enhanceDscWithOpenTelemetryRootSpanName.d.ts +0 -7
  72. package/build/types/utils/enhanceDscWithOpenTelemetryRootSpanName.d.ts.map +0 -1
  73. package/build/types/utils/getParentSpanId.d.ts +0 -8
  74. package/build/types/utils/getParentSpanId.d.ts.map +0 -1
  75. package/build/types/utils/getRequestSpanData.d.ts +0 -8
  76. package/build/types/utils/getRequestSpanData.d.ts.map +0 -1
  77. package/build/types/utils/getSpanKind.d.ts +0 -10
  78. package/build/types/utils/getSpanKind.d.ts.map +0 -1
  79. package/build/types/utils/getTraceData.d.ts +0 -12
  80. package/build/types/utils/getTraceData.d.ts.map +0 -1
  81. package/build/types/utils/groupSpansWithParents.d.ts +0 -17
  82. package/build/types/utils/groupSpansWithParents.d.ts.map +0 -1
  83. package/build/types/utils/isSentryRequest.d.ts +0 -8
  84. package/build/types/utils/isSentryRequest.d.ts.map +0 -1
  85. package/build/types/utils/mapStatus.d.ts +0 -9
  86. package/build/types/utils/mapStatus.d.ts.map +0 -1
  87. package/build/types/utils/parseSpanDescription.d.ts +0 -56
  88. package/build/types/utils/parseSpanDescription.d.ts.map +0 -1
  89. package/build/types/utils/setupCheck.d.ts +0 -9
  90. package/build/types/utils/setupCheck.d.ts.map +0 -1
  91. package/build/types/utils/spanTypes.d.ts +0 -52
  92. package/build/types/utils/spanTypes.d.ts.map +0 -1
  93. package/build/types-ts3.8/applyOtelSpanData.d.ts +0 -18
  94. package/build/types-ts3.8/asyncContextStrategy.d.ts +0 -9
  95. package/build/types-ts3.8/asyncLocalStorageContextManager.d.ts +0 -31
  96. package/build/types-ts3.8/constants.d.ts +0 -24
  97. package/build/types-ts3.8/contextManager.d.ts +0 -22
  98. package/build/types-ts3.8/custom/client.d.ts +0 -12
  99. package/build/types-ts3.8/debug-build.d.ts +0 -7
  100. package/build/types-ts3.8/exports.d.ts +0 -27
  101. package/build/types-ts3.8/index.browser.d.ts +0 -10
  102. package/build/types-ts3.8/index.d.ts +0 -5
  103. package/build/types-ts3.8/nodeAsyncContextStrategy.d.ts +0 -4
  104. package/build/types-ts3.8/propagator.d.ts +0 -43
  105. package/build/types-ts3.8/resource.d.ts +0 -29
  106. package/build/types-ts3.8/sampler.d.ts +0 -32
  107. package/build/types-ts3.8/semanticAttributes.d.ts +0 -4
  108. package/build/types-ts3.8/setupEventContextTrace.d.ts +0 -4
  109. package/build/types-ts3.8/spanExporter.d.ts +0 -50
  110. package/build/types-ts3.8/spanProcessor.d.ts +0 -31
  111. package/build/types-ts3.8/trace.d.ts +0 -75
  112. package/build/types-ts3.8/tracer.d.ts +0 -13
  113. package/build/types-ts3.8/tracerProvider.d.ts +0 -23
  114. package/build/types-ts3.8/types.d.ts +0 -29
  115. package/build/types-ts3.8/utils/TraceState.d.ts +0 -21
  116. package/build/types-ts3.8/utils/backfillStreamedSpanData.d.ts +0 -16
  117. package/build/types-ts3.8/utils/buildContextWithSentryScopes.d.ts +0 -12
  118. package/build/types-ts3.8/utils/contextData.d.ts +0 -30
  119. package/build/types-ts3.8/utils/enhanceDscWithOpenTelemetryRootSpanName.d.ts +0 -7
  120. package/build/types-ts3.8/utils/getActiveSpan.d.ts +0 -6
  121. package/build/types-ts3.8/utils/getParentSpanId.d.ts +0 -8
  122. package/build/types-ts3.8/utils/getRequestSpanData.d.ts +0 -8
  123. package/build/types-ts3.8/utils/getSamplingDecision.d.ts +0 -27
  124. package/build/types-ts3.8/utils/getSpanKind.d.ts +0 -10
  125. package/build/types-ts3.8/utils/getTraceData.d.ts +0 -12
  126. package/build/types-ts3.8/utils/groupSpansWithParents.d.ts +0 -17
  127. package/build/types-ts3.8/utils/isSentryRequest.d.ts +0 -8
  128. package/build/types-ts3.8/utils/makeTraceState.d.ts +0 -10
  129. package/build/types-ts3.8/utils/mapStatus.d.ts +0 -9
  130. package/build/types-ts3.8/utils/parseSpanDescription.d.ts +0 -56
  131. package/build/types-ts3.8/utils/setupCheck.d.ts +0 -9
  132. package/build/types-ts3.8/utils/spanTypes.d.ts +0 -52
  133. package/build/types-ts3.8/utils/suppressTracing.d.ts +0 -5
@@ -1,25 +1,504 @@
1
- import { s as setIsSetup, H as buildContextWithSentryScopes, I as SENTRY_SCOPES_CONTEXT_KEY, q as setOpenTelemetryContextAsyncContextStrategy, J as SENTRY_TRACE_STATE_CHILD_IGNORED } from './asyncContextStrategy-jD8YWNDU.js';
2
- export { S as SEMANTIC_ATTRIBUTE_SENTRY_GRAPHQL_OPERATION, a as SentryPropagator, b as SentrySampler, c as SentrySpanProcessor, d as SentryTracerProvider, e as applyOtelSpanData, f as backfillStreamedSpanDataFromOtel, g as continueTrace, h as enhanceDscWithOpenTelemetryRootSpanName, i as getActiveSpan, j as getRequestSpanData, k as getScopesFromContext, l as getSentryResource, m as getSpanKind, n as getTraceContextForScope, o as isSentryRequestSpan, p as openTelemetrySetupCheck, r as setupEventContextTrace, t as spanHasAttributes, u as spanHasEvents, v as spanHasKind, w as spanHasName, x as spanHasParentId, y as spanHasStatus, z as startInactiveSpan, A as startSpan, B as startSpanManual, C as suppressTracing, D as withActiveSpan, E as wrapClientClass, F as wrapContextManagerClass, G as wrapSamplingDecision } from './asyncContextStrategy-jD8YWNDU.js';
3
- import { getAsyncContextStrategy, getMainCarrier, spanIsIgnored, getRootSpan } from '@sentry/core';
4
- export { getClient, getDynamicSamplingContextFromSpan, shouldPropagateTraceForUrl, withStreamedSpan } from '@sentry/core';
1
+ import { derefWeakRef, makeWeakRef, dynamicSamplingContextToSentryBaggageHeader, consoleSandbox, isTracingSuppressed as isTracingSuppressed$1, getClient, getTraceData, propagationContextFromHeaders, baggageHeaderToDynamicSamplingContext, shouldContinueTrace, getCurrentScope, _INTERNAL_safeMathRandom, generateTraceId, getIsolationScope, markSpanAsTracerProviderSpan, getCapturedScopesOnSpan, spanIsIgnored, _INTERNAL_setSpanForScope, spanKindToName, startNewTrace, _INTERNAL_startInactiveSpan, getDynamicSamplingContextFromSpan, withScope, SentryNonRecordingSpan, addChildSpanToSpan, setCapturedScopesOnSpan, hasSpansEnabled, SDK_VERSION, getRootSpan, SEMANTIC_ATTRIBUTE_SENTRY_OP, handleCallbackErrors, spanToStaticSpanJSON, getAsyncContextStrategy, getMainCarrier, setAsyncContextStrategy, isContinuingTrace, getDefaultIsolationScope, getDefaultCurrentScope } from '@sentry/core';
5
2
  import * as api from '@opentelemetry/api';
6
- import { ROOT_CONTEXT } from '@opentelemetry/api';
3
+ import { createContextKey, context, trace, TraceFlags, isSpanContextValid, SpanStatusCode, ROOT_CONTEXT } from '@opentelemetry/api';
4
+ import { SENTRY_KIND } from '@sentry/conventions/attributes';
7
5
  import { AsyncLocalStorage } from 'node:async_hooks';
8
- import { EventEmitter } from 'node:events';
6
+
7
+ const SENTRY_TRACE_STATE_DSC = "sentry.dsc";
8
+ const SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING = "sentry.sampled_not_recording";
9
+ const SENTRY_SCOPES_CONTEXT_KEY = createContextKey("sentry_scopes");
10
+ const SENTRY_FORK_ISOLATION_SCOPE_CONTEXT_KEY = createContextKey("sentry_fork_isolation_scope");
11
+ const SENTRY_FORK_SET_SCOPE_CONTEXT_KEY = createContextKey("sentry_fork_set_scope");
12
+ const SENTRY_FORK_SET_ISOLATION_SCOPE_CONTEXT_KEY = createContextKey("sentry_fork_set_isolation_scope");
13
+
14
+ const SCOPE_CONTEXT_FIELD = "context";
15
+ function getScopesFromContext(context) {
16
+ return context.getValue(SENTRY_SCOPES_CONTEXT_KEY);
17
+ }
18
+ function setScopesOnContext(context, scopes) {
19
+ return context.setValue(SENTRY_SCOPES_CONTEXT_KEY, scopes);
20
+ }
21
+ function setContextOnScope(scope, context) {
22
+ scope.refs[SCOPE_CONTEXT_FIELD] = makeWeakRef(context);
23
+ }
24
+ 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
+ }
60
+ }
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;
70
+ }
71
+
72
+ const SENTRY_TRACE_HEADER = "sentry-trace";
73
+ const SENTRY_BAGGAGE_HEADER = "baggage";
74
+ 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
+ }
113
+ 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);
128
+ }
129
+ function getContextWithRemoteActiveSpanAndScopes(ctx, options) {
130
+ const ctxWithRemoteSpan = getContextWithRemoteActiveSpan(ctx, options);
131
+ const isContinuingTrace = trace.getSpanContext(ctxWithRemoteSpan) !== void 0;
132
+ return ensureScopesOnContext(ctxWithRemoteSpan, isContinuingTrace);
133
+ }
134
+ 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);
150
+ }
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;
169
+ }
170
+
171
+ const SUPPRESS_TRACING_KEY = createContextKey("OpenTelemetry SDK Context Key SUPPRESS_TRACING");
172
+ function suppressTracing(context) {
173
+ return context.setValue(SUPPRESS_TRACING_KEY, true);
174
+ }
175
+ function isTracingSuppressed(context) {
176
+ return context.getValue(SUPPRESS_TRACING_KEY) === true;
177
+ }
178
+
179
+ function getSamplingDecision(spanContext) {
180
+ const { traceFlags, traceState } = spanContext;
181
+ const sampledNotRecording = traceState ? traceState.get(SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING) === "1" : false;
182
+ if (traceFlags === TraceFlags.SAMPLED) {
183
+ return true;
184
+ }
185
+ if (sampledNotRecording) {
186
+ return false;
187
+ }
188
+ const dscString = traceState ? traceState.get(SENTRY_TRACE_STATE_DSC) : void 0;
189
+ const dsc = dscString ? baggageHeaderToDynamicSamplingContext(dscString) : void 0;
190
+ if (dsc?.sampled === "true") {
191
+ return true;
192
+ }
193
+ if (dsc?.sampled === "false") {
194
+ return false;
195
+ }
196
+ return void 0;
197
+ }
198
+
199
+ class SentryTracer {
200
+ /** @inheritdoc */
201
+ startSpan(name, options = {}, ctx) {
202
+ const parentContext = ctx || context.active();
203
+ const parentSpanCandidate = options.root ? void 0 : trace.getSpan(parentContext);
204
+ const parentSpan = parentSpanCandidate && isSpanContextValid(parentSpanCandidate.spanContext()) ? parentSpanCandidate : void 0;
205
+ if (isTracingSuppressed(parentContext)) {
206
+ return this._createNonRecordingSpan(parentSpan);
207
+ }
208
+ const span = this._startSentrySpan(name, options, parentSpan, ctx !== void 0);
209
+ markSpanAsTracerProviderSpan(span);
210
+ return span;
211
+ }
212
+ startActiveSpan(name, optionsOrFn, contextOrFn, fn) {
213
+ const options = typeof optionsOrFn === "function" ? {} : optionsOrFn;
214
+ const ctx = typeof contextOrFn === "function" || contextOrFn === void 0 ? context.active() : contextOrFn;
215
+ const callback = typeof optionsOrFn === "function" ? optionsOrFn : typeof contextOrFn === "function" ? contextOrFn : fn;
216
+ const span = this.startSpan(name, options, ctx);
217
+ const capturedIsolationScope = getCapturedScopesOnSpan(span).isolationScope;
218
+ const withCapturedIsolationScope = (contextToFork) => capturedIsolationScope ? contextToFork.setValue(SENTRY_FORK_SET_ISOLATION_SCOPE_CONTEXT_KEY, capturedIsolationScope) : contextToFork;
219
+ if (spanIsIgnored(span) && trace.getSpan(ctx)) {
220
+ return context.with(withCapturedIsolationScope(ctx), () => callback(span));
221
+ }
222
+ return context.with(withCapturedIsolationScope(trace.setSpan(ctx, span)), () => {
223
+ _INTERNAL_setSpanForScope(getCurrentScope(), span);
224
+ return callback(span);
225
+ });
226
+ }
227
+ _startSentrySpan(name, options, parentSpan, hasExplicitContext) {
228
+ const sentryOptions = {
229
+ name,
230
+ attributes: options.attributes || {},
231
+ links: options.links,
232
+ startTime: options.startTime
233
+ };
234
+ if (options.kind) {
235
+ sentryOptions.attributes[SENTRY_KIND] = spanKindToName(options.kind);
236
+ }
237
+ if (options.root) {
238
+ return startNewTrace(() => _INTERNAL_startInactiveSpan({ ...sentryOptions, parentSpan: null }));
239
+ }
240
+ if (parentSpan?.spanContext().isRemote) {
241
+ return this._startRootSpanWithRemoteParent(sentryOptions, parentSpan);
242
+ }
243
+ if (parentSpan) {
244
+ return _INTERNAL_startInactiveSpan({ ...sentryOptions, parentSpan });
245
+ }
246
+ return _INTERNAL_startInactiveSpan({
247
+ ...sentryOptions,
248
+ parentSpan: hasExplicitContext ? null : void 0
249
+ });
250
+ }
251
+ _startRootSpanWithRemoteParent(options, parentSpan) {
252
+ const { spanId, traceId, traceState } = parentSpan.spanContext();
253
+ const dsc = getDynamicSamplingContextFromSpan(parentSpan);
254
+ const sampleRand = typeof dsc.sample_rand === "string" ? Number(dsc.sample_rand) : void 0;
255
+ const hasIncomingDsc = !!traceState?.get(SENTRY_TRACE_STATE_DSC);
256
+ return withScope((scope) => {
257
+ scope.setPropagationContext({
258
+ traceId,
259
+ parentSpanId: spanId,
260
+ sampled: getSamplingDecision(parentSpan.spanContext()),
261
+ dsc: hasIncomingDsc ? dsc : void 0,
262
+ sampleRand: typeof sampleRand === "number" && !Number.isNaN(sampleRand) ? sampleRand : _INTERNAL_safeMathRandom()
263
+ });
264
+ _INTERNAL_setSpanForScope(scope, void 0);
265
+ return _INTERNAL_startInactiveSpan({ ...options, parentSpan: null });
266
+ });
267
+ }
268
+ _createNonRecordingSpan(parentSpan) {
269
+ const traceId = parentSpan?.spanContext().traceId ?? getCurrentScope().getPropagationContext().traceId;
270
+ const span = new SentryNonRecordingSpan({ traceId });
271
+ if (parentSpan) {
272
+ addChildSpanToSpan(parentSpan, span);
273
+ }
274
+ setCapturedScopesOnSpan(span, getCurrentScope(), getIsolationScope());
275
+ return span;
276
+ }
277
+ }
278
+
279
+ class SentryTracerProvider {
280
+ constructor() {
281
+ this._tracers = /* @__PURE__ */ new Map();
282
+ }
283
+ /** @inheritdoc */
284
+ getTracer(name, version, options) {
285
+ const key = JSON.stringify([name, version, options]);
286
+ const cachedTracer = this._tracers.get(key);
287
+ if (cachedTracer) {
288
+ return cachedTracer;
289
+ }
290
+ const tracer = new SentryTracer();
291
+ this._tracers.set(key, tracer);
292
+ return tracer;
293
+ }
294
+ /** Compatibility with SDK tracer providers. */
295
+ forceFlush() {
296
+ return Promise.resolve();
297
+ }
298
+ /** Compatibility with SDK tracer providers. */
299
+ shutdown() {
300
+ return Promise.resolve();
301
+ }
302
+ }
303
+
304
+ function reconcileDscSampled(dsc, sampled) {
305
+ const reconciled = { ...dsc };
306
+ if (sampled === void 0) {
307
+ delete reconciled.sampled;
308
+ } else {
309
+ reconciled.sampled = String(sampled);
310
+ if (sampled === false) {
311
+ delete reconciled.transaction;
312
+ }
313
+ }
314
+ return reconciled;
315
+ }
316
+
317
+ function _startSpan(options, callback, autoEnd) {
318
+ const tracer = getTracer();
319
+ const { name, parentSpan: customParentSpan } = options;
320
+ const wrapper = getActiveSpanWrapper(customParentSpan);
321
+ return wrapper(() => {
322
+ const activeCtx = getContext(options.scope, options.forceTransaction);
323
+ const missingRequiredParent = options.onlyIfParent && !trace.getSpan(activeCtx);
324
+ const ctx = missingRequiredParent ? suppressTracing(activeCtx) : activeCtx;
325
+ if (missingRequiredParent) {
326
+ getClient()?.recordDroppedEvent("no_parent_span", "span");
327
+ }
328
+ const spanOptions = getSpanOptions(options);
329
+ if (!hasSpansEnabled()) {
330
+ const suppressedCtx = isTracingSuppressed(ctx) ? ctx : suppressTracing(ctx);
331
+ return context.with(suppressedCtx, () => {
332
+ return tracer.startActiveSpan(name, spanOptions, suppressedCtx, (span) => {
333
+ patchSpanEnd(span);
334
+ return context.with(trace.setSpan(activeCtx, span), () => {
335
+ return handleCallbackErrors(
336
+ () => callback(span),
337
+ () => {
338
+ if (spanToStaticSpanJSON(span).status === "ok") {
339
+ span.setStatus({ code: SpanStatusCode.ERROR });
340
+ }
341
+ },
342
+ autoEnd ? () => span.end() : void 0
343
+ );
344
+ });
345
+ });
346
+ });
347
+ }
348
+ return tracer.startActiveSpan(name, spanOptions, ctx, (span) => {
349
+ patchSpanEnd(span);
350
+ return handleCallbackErrors(
351
+ () => callback(span),
352
+ () => {
353
+ if (spanToStaticSpanJSON(span).status === "ok") {
354
+ span.setStatus({ code: SpanStatusCode.ERROR });
355
+ }
356
+ },
357
+ autoEnd ? () => span.end() : void 0
358
+ );
359
+ });
360
+ });
361
+ }
362
+ function startSpan(options, callback) {
363
+ return _startSpan(options, callback, true);
364
+ }
365
+ function startSpanManual(options, callback) {
366
+ return _startSpan(options, (span) => callback(span, () => span.end()), false);
367
+ }
368
+ function startInactiveSpan(options) {
369
+ const tracer = getTracer();
370
+ const { name, parentSpan: customParentSpan } = options;
371
+ const wrapper = getActiveSpanWrapper(customParentSpan);
372
+ return wrapper(() => {
373
+ const activeCtx = getContext(options.scope, options.forceTransaction);
374
+ const missingRequiredParent = options.onlyIfParent && !trace.getSpan(activeCtx);
375
+ let ctx = missingRequiredParent ? suppressTracing(activeCtx) : activeCtx;
376
+ if (missingRequiredParent) {
377
+ getClient()?.recordDroppedEvent("no_parent_span", "span");
378
+ }
379
+ const spanOptions = getSpanOptions(options);
380
+ if (!hasSpansEnabled()) {
381
+ ctx = isTracingSuppressed(ctx) ? ctx : suppressTracing(ctx);
382
+ }
383
+ const span = tracer.startSpan(name, spanOptions, ctx);
384
+ patchSpanEnd(span);
385
+ return span;
386
+ });
387
+ }
388
+ function withActiveSpan(span, callback) {
389
+ const newContextWithActiveSpan = span ? trace.setSpan(context.active(), span) : trace.deleteSpan(context.active());
390
+ return context.with(newContextWithActiveSpan, () => callback(getCurrentScope()));
391
+ }
392
+ function getTracer() {
393
+ const client = getClient();
394
+ return client?.tracer || trace.getTracer("@sentry/opentelemetry", SDK_VERSION);
395
+ }
396
+ function getSpanOptions(options) {
397
+ const { startTime, attributes, op, links } = options;
398
+ const fixedStartTime = typeof startTime === "number" ? ensureTimestampInMilliseconds(startTime) : startTime;
399
+ return {
400
+ attributes: op ? {
401
+ [SEMANTIC_ATTRIBUTE_SENTRY_OP]: op,
402
+ ...attributes
403
+ } : attributes,
404
+ links,
405
+ startTime: fixedStartTime
406
+ };
407
+ }
408
+ function ensureTimestampInMilliseconds(timestamp) {
409
+ const isMs = timestamp < 9999999999;
410
+ return isMs ? timestamp * 1e3 : timestamp;
411
+ }
412
+ function patchSpanEnd(span) {
413
+ const originalEnd = span.end.bind(span);
414
+ span.end = (endTime) => {
415
+ return originalEnd(typeof endTime === "number" ? ensureTimestampInMilliseconds(endTime) : endTime);
416
+ };
417
+ }
418
+ function getContext(scope, forceTransaction) {
419
+ const ctx = getContextForScope(scope);
420
+ const parentSpan = trace.getSpan(ctx);
421
+ if (!parentSpan) {
422
+ return ctx;
423
+ }
424
+ if (!forceTransaction) {
425
+ return ctx;
426
+ }
427
+ const ctxWithoutSpan = trace.deleteSpan(ctx);
428
+ const { spanId, traceId } = parentSpan.spanContext();
429
+ const sampled = getSamplingDecision(parentSpan.spanContext());
430
+ const rootSpan = getRootSpan(parentSpan);
431
+ const rawDsc = getDynamicSamplingContextFromSpan(rootSpan);
432
+ const hasIncomingFrozenDsc = !!rootSpan.spanContext().traceState?.get(SENTRY_TRACE_STATE_DSC);
433
+ const dsc = hasIncomingFrozenDsc ? rawDsc : reconcileDscSampled(rawDsc, sampled);
434
+ const traceState = makeTraceState({
435
+ dsc,
436
+ sampled
437
+ });
438
+ const spanOptions = {
439
+ traceId,
440
+ spanId,
441
+ isRemote: true,
442
+ traceFlags: sampled ? TraceFlags.SAMPLED : TraceFlags.NONE,
443
+ traceState
444
+ };
445
+ const ctxWithSpanContext = trace.setSpanContext(ctxWithoutSpan, spanOptions);
446
+ return ctxWithSpanContext;
447
+ }
448
+ function getContextForScope(scope) {
449
+ if (scope) {
450
+ const ctx = getContextFromScope(scope);
451
+ if (ctx) {
452
+ return ctx;
453
+ }
454
+ }
455
+ return context.active();
456
+ }
457
+ function getActiveSpanWrapper(parentSpan) {
458
+ return parentSpan !== void 0 ? (callback) => {
459
+ return withActiveSpan(parentSpan, callback);
460
+ } : (callback) => callback();
461
+ }
462
+
463
+ function getActiveSpan(scope) {
464
+ if (!scope) {
465
+ return trace.getActiveSpan();
466
+ }
467
+ const ctx = getContextFromScope(scope);
468
+ if (ctx) {
469
+ return trace.getSpan(ctx);
470
+ }
471
+ return void 0;
472
+ }
473
+
474
+ function buildContextWithSentryScopes(context) {
475
+ const currentScopes = getScopesFromContext(context);
476
+ const currentScope = currentScopes?.scope || getCurrentScope();
477
+ const currentIsolationScope = currentScopes?.isolationScope || getIsolationScope();
478
+ const shouldForkIsolationScope = context.getValue(SENTRY_FORK_ISOLATION_SCOPE_CONTEXT_KEY) === true;
479
+ const scope = context.getValue(SENTRY_FORK_SET_SCOPE_CONTEXT_KEY);
480
+ const isolationScope = context.getValue(SENTRY_FORK_SET_ISOLATION_SCOPE_CONTEXT_KEY);
481
+ const newCurrentScope = scope || currentScope.clone();
482
+ const newIsolationScope = isolationScope || (shouldForkIsolationScope ? currentIsolationScope.clone() : currentIsolationScope);
483
+ const scopes = { scope: newCurrentScope, isolationScope: newIsolationScope };
484
+ const ctx1 = setScopesOnContext(context, scopes);
485
+ 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);
486
+ setContextOnScope(newCurrentScope, ctx2);
487
+ return ctx2;
488
+ }
9
489
 
10
490
  const ADD_LISTENER_METHODS = ["addListener", "on", "once", "prependListener", "prependOnceListener"];
11
491
  class SentryAsyncLocalStorageContextManager {
12
- constructor() {
492
+ constructor(asyncLocalStorage) {
13
493
  this._kOtListeners = /* @__PURE__ */ Symbol("OtListeners");
14
494
  this._wrapped = false;
15
- setIsSetup("SentryContextManager");
16
- this._asyncLocalStorage = getAsyncContextStrategy(getMainCarrier()).getTracingChannelBinding?.()?.asyncLocalStorage ?? new AsyncLocalStorage();
495
+ this._asyncLocalStorage = asyncLocalStorage;
17
496
  }
18
497
  active() {
19
498
  return this._asyncLocalStorage.getStore() ?? ROOT_CONTEXT;
20
499
  }
21
500
  with(context, fn, thisArg, ...args) {
22
- const ctx2 = buildContextWithSentryScopes(context, this.active());
501
+ const ctx2 = buildContextWithSentryScopes(context);
23
502
  const cb = thisArg == null ? fn : fn.bind(thisArg);
24
503
  return this._asyncLocalStorage.run(ctx2, cb, ...args);
25
504
  }
@@ -27,11 +506,14 @@ class SentryAsyncLocalStorageContextManager {
27
506
  return this;
28
507
  }
29
508
  disable() {
30
- this._asyncLocalStorage.disable();
509
+ try {
510
+ this._asyncLocalStorage.disable();
511
+ } catch {
512
+ }
31
513
  return this;
32
514
  }
33
515
  bind(context, target) {
34
- if (target instanceof EventEmitter) {
516
+ if (isEventEmitter(target)) {
35
517
  return this._bindEventEmitter(context, target);
36
518
  }
37
519
  if (typeof target === "function") {
@@ -66,27 +548,22 @@ class SentryAsyncLocalStorageContextManager {
66
548
  if (this._getPatchMap(ee) !== void 0) {
67
549
  return ee;
68
550
  }
69
- this._createPatchMap(ee);
70
- for (const methodName of ADD_LISTENER_METHODS) {
71
- if (ee[methodName] === void 0) continue;
72
- ee[methodName] = this._patchAddListener(
73
- ee,
74
- ee[methodName],
75
- context
76
- );
551
+ if (this._createPatchMap(ee) === void 0) {
552
+ return ee;
77
553
  }
78
- if (typeof ee.removeListener === "function") {
79
- ee.removeListener = this._patchRemoveListener(ee, ee.removeListener);
554
+ for (const methodName of ADD_LISTENER_METHODS) {
555
+ const original = getMethod(ee, methodName);
556
+ if (!original) continue;
557
+ trySetMethod(ee, methodName, this._patchAddListener(ee, original, context));
80
558
  }
81
- if (typeof ee.off === "function") {
82
- ee.off = this._patchRemoveListener(ee, ee.off);
559
+ for (const methodName of ["removeListener", "off"]) {
560
+ const original = getMethod(ee, methodName);
561
+ if (!original) continue;
562
+ trySetMethod(ee, methodName, this._patchRemoveListener(ee, original));
83
563
  }
84
- if (typeof ee.removeAllListeners === "function") {
85
- ee.removeAllListeners = this._patchRemoveAllListeners(
86
- ee,
87
- // oxlint-disable-next-line @typescript-eslint/unbound-method
88
- ee.removeAllListeners
89
- );
564
+ const removeAllListeners = getMethod(ee, "removeAllListeners");
565
+ if (removeAllListeners) {
566
+ trySetMethod(ee, "removeAllListeners", this._patchRemoveAllListeners(ee, removeAllListeners));
90
567
  }
91
568
  return ee;
92
569
  }
@@ -121,9 +598,9 @@ class SentryAsyncLocalStorageContextManager {
121
598
  if (contextManager._wrapped) {
122
599
  return original.call(this, event, listener);
123
600
  }
124
- let map = contextManager._getPatchMap(ee);
601
+ const map = contextManager._getPatchMap(ee) ?? contextManager._createPatchMap(ee);
125
602
  if (map === void 0) {
126
- map = contextManager._createPatchMap(ee);
603
+ return original.call(this, event, listener);
127
604
  }
128
605
  let listeners = map[event];
129
606
  if (listeners === void 0) {
@@ -140,49 +617,118 @@ class SentryAsyncLocalStorageContextManager {
140
617
  }
141
618
  };
142
619
  }
620
+ /**
621
+ * Attach a fresh patch map to the emitter. Returns `undefined` if the emitter does not accept the
622
+ * property (e.g. it is frozen or sealed), in which case the emitter must not be patched at all —
623
+ * without a patch map the remove-listener patches could not resolve their wrapped listeners.
624
+ */
143
625
  _createPatchMap(ee) {
144
626
  const map = /* @__PURE__ */ Object.create(null);
145
- ee[this._kOtListeners] = map;
146
- return map;
627
+ try {
628
+ ee[this._kOtListeners] = map;
629
+ } catch {
630
+ return void 0;
631
+ }
632
+ return this._getPatchMap(ee) === map ? map : void 0;
147
633
  }
148
634
  _getPatchMap(ee) {
149
635
  return ee[this._kOtListeners];
150
636
  }
151
637
  }
152
-
153
- function setNodeOpenTelemetryContextAsyncContextStrategy(options) {
154
- setOpenTelemetryContextAsyncContextStrategy({
155
- getTracingChannelBinding: !options?.skipOpenTelemetrySetup ? getDefaultAsyncLocalStorageFactory() : getCustomAsyncLocalStorageFactory()
156
- });
638
+ function isEventEmitter(target) {
639
+ if (typeof target !== "object" || !target) {
640
+ return false;
641
+ }
642
+ const candidate = target;
643
+ return typeof candidate.on === "function" && typeof candidate.emit === "function";
157
644
  }
158
- function getDefaultAsyncLocalStorageFactory() {
159
- const defaultAsyncLocalStorage = new AsyncLocalStorage();
160
- return () => {
161
- return {
162
- asyncLocalStorage: defaultAsyncLocalStorage,
163
- getStoreWithActiveSpan
164
- };
165
- };
645
+ function getMethod(ee, methodName) {
646
+ const value = ee[methodName];
647
+ return typeof value === "function" ? value : void 0;
166
648
  }
167
- function getCustomAsyncLocalStorageFactory() {
168
- return () => {
169
- try {
170
- const contextManager = api.context._getContextManager();
171
- const asyncLocalStorage = contextManager?.getAsyncLocalStorageLookup().asyncLocalStorage;
172
- return asyncLocalStorage ? {
173
- asyncLocalStorage,
174
- getStoreWithActiveSpan
175
- } : void 0;
176
- } catch {
177
- return void 0;
178
- }
179
- };
649
+ function trySetMethod(ee, methodName, patched) {
650
+ try {
651
+ ee[methodName] = patched;
652
+ } catch {
653
+ }
180
654
  }
181
- function getStoreWithActiveSpan(span) {
182
- const activeContext = api.context.active();
183
- const isIgnoredChild = spanIsIgnored(span) && getRootSpan(span) !== span || span.spanContext().traceState?.get(SENTRY_TRACE_STATE_CHILD_IGNORED) === "1";
184
- return isIgnoredChild ? activeContext : api.trace.setSpan(activeContext, span);
655
+
656
+ function setOpenTelemetryContextAsyncContextStrategy() {
657
+ const existingAsyncLocalStorage = getAsyncContextStrategy(getMainCarrier()).getTracingChannelBinding?.()?.asyncLocalStorage;
658
+ const asyncLocalStorage = existingAsyncLocalStorage ?? new AsyncLocalStorage();
659
+ function getScopes() {
660
+ const ctx = api.context.active();
661
+ const scopes = getScopesFromContext(ctx);
662
+ if (scopes) {
663
+ return scopes;
664
+ }
665
+ return {
666
+ scope: getDefaultCurrentScope(),
667
+ isolationScope: getDefaultIsolationScope()
668
+ };
669
+ }
670
+ function withScope(callback) {
671
+ const ctx = api.context.active();
672
+ return api.context.with(ctx, () => {
673
+ return callback(getCurrentScope());
674
+ });
675
+ }
676
+ function withSetScope(scope, callback) {
677
+ const ctx = getContextFromScope(scope) || api.context.active();
678
+ return api.context.with(ctx.setValue(SENTRY_FORK_SET_SCOPE_CONTEXT_KEY, scope), () => {
679
+ return callback(scope);
680
+ });
681
+ }
682
+ function withIsolationScope(callback) {
683
+ const ctx = api.context.active();
684
+ return api.context.with(ctx.setValue(SENTRY_FORK_ISOLATION_SCOPE_CONTEXT_KEY, true), () => {
685
+ const scope = getCurrentScope();
686
+ if (!isContinuingTrace(scope.getPropagationContext())) {
687
+ scope.setPropagationContext({
688
+ traceId: generateTraceId(),
689
+ sampleRand: _INTERNAL_safeMathRandom()
690
+ });
691
+ }
692
+ return callback(getIsolationScope());
693
+ });
694
+ }
695
+ function withSetIsolationScope(isolationScope, callback) {
696
+ const ctx = api.context.active();
697
+ return api.context.with(ctx.setValue(SENTRY_FORK_SET_ISOLATION_SCOPE_CONTEXT_KEY, isolationScope), () => {
698
+ return callback(getIsolationScope());
699
+ });
700
+ }
701
+ function getCurrentScope() {
702
+ return getScopes().scope;
703
+ }
704
+ function getIsolationScope() {
705
+ return getScopes().isolationScope;
706
+ }
707
+ function getTracingChannelBinding() {
708
+ return {
709
+ asyncLocalStorage
710
+ };
711
+ }
712
+ setAsyncContextStrategy({
713
+ withScope,
714
+ withSetScope,
715
+ withSetIsolationScope,
716
+ withIsolationScope,
717
+ getCurrentScope,
718
+ getIsolationScope,
719
+ startSpan,
720
+ startSpanManual,
721
+ startInactiveSpan,
722
+ getActiveSpan,
723
+ // The types here don't fully align, because our own `Span` type is narrower
724
+ // than the OTEL one - but this is OK for here, as we now we'll only have OTEL spans passed around
725
+ withActiveSpan,
726
+ getTracingChannelBinding
727
+ });
728
+ const ctxManager = new SentryAsyncLocalStorageContextManager(asyncLocalStorage);
729
+ api.context.setGlobalContextManager(ctxManager);
730
+ return ctxManager.getAsyncLocalStorageLookup();
185
731
  }
186
732
 
187
- export { SentryAsyncLocalStorageContextManager, setIsSetup, setNodeOpenTelemetryContextAsyncContextStrategy as setOpenTelemetryContextAsyncContextStrategy };
733
+ export { SentryPropagator, SentryTracerProvider, getScopesFromContext, setOpenTelemetryContextAsyncContextStrategy };
188
734
  //# sourceMappingURL=index.js.map